Update app.py
Browse files
app.py
CHANGED
@@ -9,6 +9,7 @@ from messages import daily_blessings
|
|
9 |
import logging
|
10 |
import requests
|
11 |
import random
|
|
|
12 |
|
13 |
# Configure logging
|
14 |
logging.basicConfig(level=logging.INFO)
|
@@ -55,7 +56,6 @@ def get_daily_message_and_blessing():
|
|
55 |
# weekday() returns 0 for Monday, 6 for Sunday, so we shift it: (weekday() + 1) % 7
|
56 |
day_of_week = (today.weekday() + 1) % 7 # Maps Monday (0) to 1, Tuesday (1) to 2, ..., Sunday (6) to 0
|
57 |
month_day = (today.month, today.day)
|
58 |
-
day_of_month = today.day
|
59 |
|
60 |
# Check for festival messages first
|
61 |
if month_day in FESTIVAL_MESSAGES:
|
@@ -67,8 +67,8 @@ def get_daily_message_and_blessing():
|
|
67 |
"verse": "Bhagavad Gita 6.30"})
|
68 |
daily_message['special'] = False
|
69 |
|
70 |
-
#
|
71 |
-
daily_blessing_index = (
|
72 |
daily_blessing = daily_blessings[daily_blessing_index]
|
73 |
|
74 |
return {
|
@@ -78,6 +78,27 @@ def get_daily_message_and_blessing():
|
|
78 |
"blessing": daily_blessing
|
79 |
}
|
80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
def generate_daily_quote():
|
82 |
"""Generate a daily inspirational quote in Krishna's tone using an AI model."""
|
83 |
headers = {
|
@@ -98,34 +119,33 @@ def generate_daily_quote():
|
|
98 |
"top_k": 50
|
99 |
}
|
100 |
}
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
except Exception as e:
|
117 |
-
logger.error(f"Error generating daily quote: {str(e)}")
|
118 |
-
return "Hare Manavi! Let your heart bloom like the lotus in the Yamuna, for love is the sweetest melody of Vrindavan!"
|
119 |
|
120 |
def generate_horoscope():
|
121 |
"""Generate a personalized daily horoscope for Manavi in Krishna's tone."""
|
|
|
122 |
headers = {
|
123 |
"Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}",
|
124 |
"Content-Type": "application/json"
|
125 |
}
|
126 |
prompt = (
|
127 |
-
"You are Little Krishna, a wise and playful cowherd from Vrindavan, speaking to Manavi on
|
128 |
"Generate a short, personalized daily horoscope (1-2 sentences) for Manavi, reflecting her interests in art, nature, and spirituality, in a wise yet playful tone, using Vrindavan imagery. "
|
|
|
129 |
"Example: 'Hare Manavi! Today, the Yamuna’s gentle waves inspire your art—paint with the colors of Vrindavan’s flowers and let your spirit dance like the peacocks!'"
|
130 |
)
|
131 |
payload = {
|
@@ -137,24 +157,21 @@ def generate_horoscope():
|
|
137 |
"top_k": 50
|
138 |
}
|
139 |
}
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
except Exception as e:
|
156 |
-
logger.error(f"Error generating horoscope: {str(e)}")
|
157 |
-
return "Hare Manavi! Today, the Yamuna’s gentle waves inspire your art—paint with the colors of Vrindavan’s flowers and let your spirit dance like the peacocks!"
|
158 |
|
159 |
def generate_birthday_message():
|
160 |
"""Generate a unique birthday message for Manavi using an AI model."""
|
@@ -177,24 +194,21 @@ def generate_birthday_message():
|
|
177 |
"top_k": 50
|
178 |
}
|
179 |
}
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
except Exception as e:
|
196 |
-
logger.error(f"Error generating birthday message: {str(e)}")
|
197 |
-
return "Hare Manavi! On your special day, I’ve brought the sweetest butter from Vrindavan and a flute melody to make your heart dance—happy birthday, my dear gopi!"
|
198 |
|
199 |
def generate_gift_suggestions():
|
200 |
"""Generate personalized gift suggestions for Manavi in Krishna's tone."""
|
@@ -218,32 +232,25 @@ def generate_gift_suggestions():
|
|
218 |
"top_k": 50
|
219 |
}
|
220 |
}
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
except Exception as e:
|
241 |
-
logger.error(f"Error generating gift suggestions: {str(e)}")
|
242 |
-
return [
|
243 |
-
"Hare Manavi! A peacock feather paintbrush to create art as vibrant as Vrindavan’s flowers!",
|
244 |
-
"Hare Manavi! A lotus-shaped journal to capture your thoughts by the Yamuna’s serene banks!",
|
245 |
-
"Hare Manavi! A flute pendant to carry Vrindavan’s spiritual melody close to your heart!"
|
246 |
-
]
|
247 |
|
248 |
@app.route('/')
|
249 |
def home():
|
@@ -282,6 +289,10 @@ def message():
|
|
282 |
# Generate a birthday image for Manavi
|
283 |
image_prompt = "Little Krishna celebrating Manavi’s birthday in Vrindavan, with peacocks, butter pots, and a festive atmosphere, cartoon style"
|
284 |
birthday_image_url = generate_krishna_image(image_prompt)
|
|
|
|
|
|
|
|
|
285 |
if not birthday_image_url:
|
286 |
birthday_image_url = "/static/assets/krishna.png" # Fallback image
|
287 |
return render_template('message.html', birthday_message=birthday_message, birthday_image_url=birthday_image_url, gift_suggestions=gift_suggestions)
|
@@ -365,26 +376,23 @@ def adventure():
|
|
365 |
"top_k": 50
|
366 |
}
|
367 |
}
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
story_text = result.strip()
|
382 |
-
else:
|
383 |
-
story_text = scene['prompt'].split('Example: ')[1]
|
384 |
else:
|
385 |
story_text = scene['prompt'].split('Example: ')[1]
|
386 |
-
|
387 |
-
logger.error(
|
388 |
story_text = scene['prompt'].split('Example: ')[1]
|
389 |
|
390 |
next_scene = scene['next_scenes'].get(choice, None)
|
@@ -458,12 +466,8 @@ def story():
|
|
458 |
"inputs": prompt,
|
459 |
"parameters": model["parameters"]
|
460 |
}
|
461 |
-
response =
|
462 |
-
|
463 |
-
headers=headers,
|
464 |
-
json=payload
|
465 |
-
)
|
466 |
-
if response.status_code == 200:
|
467 |
result = response.json()
|
468 |
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
|
469 |
return jsonify({'story': result[0]["generated_text"].strip()})
|
@@ -471,7 +475,7 @@ def story():
|
|
471 |
return jsonify({'story': result["generated_text"].strip()})
|
472 |
elif isinstance(result, str):
|
473 |
return jsonify({'story': result.strip()})
|
474 |
-
print(f"Error with {model['name']}: {response.text}")
|
475 |
continue
|
476 |
except Exception as e:
|
477 |
print(f"Error connecting to {model['name']}: {str(e)}")
|
@@ -491,22 +495,19 @@ def story_audio():
|
|
491 |
payload = {
|
492 |
"inputs": story_text
|
493 |
}
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
except Exception as e:
|
508 |
-
logger.error(f"Error generating story audio: {str(e)}")
|
509 |
-
return jsonify({'error': 'Failed to generate audio'}), 500
|
510 |
|
511 |
@app.route('/riddle', methods=['GET'])
|
512 |
def riddle():
|
@@ -530,24 +531,21 @@ def riddle():
|
|
530 |
"top_k": 50
|
531 |
}
|
532 |
}
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
|
538 |
-
|
539 |
-
|
540 |
-
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
|
548 |
-
except Exception as e:
|
549 |
-
logger.error(f"Error generating riddle: {str(e)}")
|
550 |
-
return jsonify({'riddle': "Hare Manavi! I play a tune that makes the gopis dance, but I’m not a drum—what am I? (Answer: Flute)"})
|
551 |
|
552 |
@app.route('/countdown')
|
553 |
def countdown():
|
|
|
9 |
import logging
|
10 |
import requests
|
11 |
import random
|
12 |
+
import time
|
13 |
|
14 |
# Configure logging
|
15 |
logging.basicConfig(level=logging.INFO)
|
|
|
56 |
# weekday() returns 0 for Monday, 6 for Sunday, so we shift it: (weekday() + 1) % 7
|
57 |
day_of_week = (today.weekday() + 1) % 7 # Maps Monday (0) to 1, Tuesday (1) to 2, ..., Sunday (6) to 0
|
58 |
month_day = (today.month, today.day)
|
|
|
59 |
|
60 |
# Check for festival messages first
|
61 |
if month_day in FESTIVAL_MESSAGES:
|
|
|
67 |
"verse": "Bhagavad Gita 6.30"})
|
68 |
daily_message['special'] = False
|
69 |
|
70 |
+
# Precompute daily blessing index
|
71 |
+
daily_blessing_index = (today.day - 1) % len(daily_blessings)
|
72 |
daily_blessing = daily_blessings[daily_blessing_index]
|
73 |
|
74 |
return {
|
|
|
78 |
"blessing": daily_blessing
|
79 |
}
|
80 |
|
81 |
+
def make_api_request(url, headers, payload, retries=3, delay=5):
|
82 |
+
"""Helper function to make API requests with retry logic."""
|
83 |
+
for attempt in range(retries):
|
84 |
+
try:
|
85 |
+
response = requests.post(url, headers=headers, json=payload)
|
86 |
+
if response.status_code == 200:
|
87 |
+
return response
|
88 |
+
elif response.status_code == 429: # Rate limit
|
89 |
+
logger.warning(f"Rate limit hit on attempt {attempt + 1}. Retrying after {delay} seconds...")
|
90 |
+
time.sleep(delay)
|
91 |
+
continue
|
92 |
+
else:
|
93 |
+
logger.error(f"API error: {response.text}")
|
94 |
+
return None
|
95 |
+
except Exception as e:
|
96 |
+
logger.error(f"API request failed: {str(e)}")
|
97 |
+
if attempt < retries - 1:
|
98 |
+
time.sleep(delay)
|
99 |
+
continue
|
100 |
+
return None
|
101 |
+
|
102 |
def generate_daily_quote():
|
103 |
"""Generate a daily inspirational quote in Krishna's tone using an AI model."""
|
104 |
headers = {
|
|
|
119 |
"top_k": 50
|
120 |
}
|
121 |
}
|
122 |
+
response = make_api_request(
|
123 |
+
"https://api-inference.huggingface.co/models/EleutherAI/gpt-neo-1.3B",
|
124 |
+
headers=headers,
|
125 |
+
json=payload
|
126 |
+
)
|
127 |
+
if response:
|
128 |
+
result = response.json()
|
129 |
+
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
|
130 |
+
return result[0]["generated_text"].strip()
|
131 |
+
elif isinstance(result, dict) and "generated_text" in result:
|
132 |
+
return result["generated_text"].strip()
|
133 |
+
elif isinstance(result, str):
|
134 |
+
return result.strip()
|
135 |
+
logger.error("Failed to generate daily quote after retries.")
|
136 |
+
return "Hare Manavi! Let your heart bloom like the lotus in the Yamuna, for love is the sweetest melody of Vrindavan!"
|
|
|
|
|
|
|
137 |
|
138 |
def generate_horoscope():
|
139 |
"""Generate a personalized daily horoscope for Manavi in Krishna's tone."""
|
140 |
+
today = datetime.now().strftime("%B %d, %Y") # Dynamically get the current date
|
141 |
headers = {
|
142 |
"Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}",
|
143 |
"Content-Type": "application/json"
|
144 |
}
|
145 |
prompt = (
|
146 |
+
f"You are Little Krishna, a wise and playful cowherd from Vrindavan, speaking to Manavi on {today}. "
|
147 |
"Generate a short, personalized daily horoscope (1-2 sentences) for Manavi, reflecting her interests in art, nature, and spirituality, in a wise yet playful tone, using Vrindavan imagery. "
|
148 |
+
"Do not include any self-referential text about being Little Krishna or Manavi's identity. "
|
149 |
"Example: 'Hare Manavi! Today, the Yamuna’s gentle waves inspire your art—paint with the colors of Vrindavan’s flowers and let your spirit dance like the peacocks!'"
|
150 |
)
|
151 |
payload = {
|
|
|
157 |
"top_k": 50
|
158 |
}
|
159 |
}
|
160 |
+
response = make_api_request(
|
161 |
+
"https://api-inference.huggingface.co/models/bigscience/bloom-560m",
|
162 |
+
headers=headers,
|
163 |
+
json=payload
|
164 |
+
)
|
165 |
+
if response:
|
166 |
+
result = response.json()
|
167 |
+
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
|
168 |
+
return result[0]["generated_text"].strip()
|
169 |
+
elif isinstance(result, dict) and "generated_text" in result:
|
170 |
+
return result["generated_text"].strip()
|
171 |
+
elif isinstance(result, str):
|
172 |
+
return result.strip()
|
173 |
+
logger.error("Failed to generate horoscope after retries.")
|
174 |
+
return "Hare Manavi! Today, the Yamuna’s gentle waves inspire your art—paint with the colors of Vrindavan’s flowers and let your spirit dance like the peacocks!"
|
|
|
|
|
|
|
175 |
|
176 |
def generate_birthday_message():
|
177 |
"""Generate a unique birthday message for Manavi using an AI model."""
|
|
|
194 |
"top_k": 50
|
195 |
}
|
196 |
}
|
197 |
+
response = make_api_request(
|
198 |
+
"https://api-inference.huggingface.co/models/bigscience/bloom-560m",
|
199 |
+
headers=headers,
|
200 |
+
json=payload
|
201 |
+
)
|
202 |
+
if response:
|
203 |
+
result = response.json()
|
204 |
+
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
|
205 |
+
return result[0]["generated_text"].strip()
|
206 |
+
elif isinstance(result, dict) and "generated_text" in result:
|
207 |
+
return result["generated_text"].strip()
|
208 |
+
elif isinstance(result, str):
|
209 |
+
return result.strip()
|
210 |
+
logger.error("Failed to generate birthday message after retries.")
|
211 |
+
return "Hare Manavi! On your special day, I’ve brought the sweetest butter from Vrindavan and a flute melody to make your heart dance—happy birthday, my dear gopi!"
|
|
|
|
|
|
|
212 |
|
213 |
def generate_gift_suggestions():
|
214 |
"""Generate personalized gift suggestions for Manavi in Krishna's tone."""
|
|
|
232 |
"top_k": 50
|
233 |
}
|
234 |
}
|
235 |
+
response = make_api_request(
|
236 |
+
"https://api-inference.huggingface.co/models/google/gemma-2b",
|
237 |
+
headers=headers,
|
238 |
+
json=payload
|
239 |
+
)
|
240 |
+
if response:
|
241 |
+
result = response.json()
|
242 |
+
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
|
243 |
+
return result[0]["generated_text"].strip().split('\n')
|
244 |
+
elif isinstance(result, dict) and "generated_text" in result:
|
245 |
+
return result["generated_text"].strip().split('\n')
|
246 |
+
elif isinstance(result, str):
|
247 |
+
return result.strip().split('\n')
|
248 |
+
logger.error("Failed to generate gift suggestions after retries.")
|
249 |
+
return [
|
250 |
+
"Hare Manavi! A peacock feather paintbrush to create art as vibrant as Vrindavan’s flowers!",
|
251 |
+
"Hare Manavi! A lotus-shaped journal to capture your thoughts by the Yamuna’s serene banks!",
|
252 |
+
"Hare Manavi! A flute pendant to carry Vrindavan’s spiritual melody close to your heart!"
|
253 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
254 |
|
255 |
@app.route('/')
|
256 |
def home():
|
|
|
289 |
# Generate a birthday image for Manavi
|
290 |
image_prompt = "Little Krishna celebrating Manavi’s birthday in Vrindavan, with peacocks, butter pots, and a festive atmosphere, cartoon style"
|
291 |
birthday_image_url = generate_krishna_image(image_prompt)
|
292 |
+
if not birthday_image_url:
|
293 |
+
# Retry with a simpler prompt
|
294 |
+
image_prompt = "Little Krishna with a peacock feather, playing a flute in Vrindavan, cartoon style"
|
295 |
+
birthday_image_url = generate_krishna_image(image_prompt)
|
296 |
if not birthday_image_url:
|
297 |
birthday_image_url = "/static/assets/krishna.png" # Fallback image
|
298 |
return render_template('message.html', birthday_message=birthday_message, birthday_image_url=birthday_image_url, gift_suggestions=gift_suggestions)
|
|
|
376 |
"top_k": 50
|
377 |
}
|
378 |
}
|
379 |
+
response = make_api_request(
|
380 |
+
"https://api-inference.huggingface.co/models/EleutherAI/gpt-neo-1.3B",
|
381 |
+
headers=headers,
|
382 |
+
json=payload
|
383 |
+
)
|
384 |
+
if response:
|
385 |
+
result = response.json()
|
386 |
+
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
|
387 |
+
story_text = result[0]["generated_text"].strip()
|
388 |
+
elif isinstance(result, dict) and "generated_text" in result:
|
389 |
+
story_text = result["generated_text"].strip()
|
390 |
+
elif isinstance(result, str):
|
391 |
+
story_text = result.strip()
|
|
|
|
|
|
|
392 |
else:
|
393 |
story_text = scene['prompt'].split('Example: ')[1]
|
394 |
+
else:
|
395 |
+
logger.error("Failed to generate adventure scene after retries.")
|
396 |
story_text = scene['prompt'].split('Example: ')[1]
|
397 |
|
398 |
next_scene = scene['next_scenes'].get(choice, None)
|
|
|
466 |
"inputs": prompt,
|
467 |
"parameters": model["parameters"]
|
468 |
}
|
469 |
+
response = make_api_request(model["endpoint"], headers=headers, json=payload)
|
470 |
+
if response and response.status_code == 200:
|
|
|
|
|
|
|
|
|
471 |
result = response.json()
|
472 |
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
|
473 |
return jsonify({'story': result[0]["generated_text"].strip()})
|
|
|
475 |
return jsonify({'story': result["generated_text"].strip()})
|
476 |
elif isinstance(result, str):
|
477 |
return jsonify({'story': result.strip()})
|
478 |
+
print(f"Error with {model['name']}: {response.text if response else 'No response'}")
|
479 |
continue
|
480 |
except Exception as e:
|
481 |
print(f"Error connecting to {model['name']}: {str(e)}")
|
|
|
495 |
payload = {
|
496 |
"inputs": story_text
|
497 |
}
|
498 |
+
response = make_api_request(
|
499 |
+
"https://api-inference.huggingface.co/models/facebook/tts-transformer-en-ljspeech",
|
500 |
+
headers=headers,
|
501 |
+
json=payload
|
502 |
+
)
|
503 |
+
if response and response.status_code == 200:
|
504 |
+
# Save the audio file temporarily
|
505 |
+
audio_path = "static/audio/story_audio.mp3"
|
506 |
+
with open(audio_path, "wb") as f:
|
507 |
+
f.write(response.content)
|
508 |
+
return jsonify({'audio_url': f"/{audio_path}"})
|
509 |
+
logger.error("Failed to generate story audio after retries.")
|
510 |
+
return jsonify({'error': 'Failed to generate audio'}), 500
|
|
|
|
|
|
|
511 |
|
512 |
@app.route('/riddle', methods=['GET'])
|
513 |
def riddle():
|
|
|
531 |
"top_k": 50
|
532 |
}
|
533 |
}
|
534 |
+
response = make_api_request(
|
535 |
+
"https://api-inference.huggingface.co/models/mistralai/Mixtral-8x7B-Instruct-v0.1",
|
536 |
+
headers=headers,
|
537 |
+
json=payload
|
538 |
+
)
|
539 |
+
if response and response.status_code == 200:
|
540 |
+
result = response.json()
|
541 |
+
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
|
542 |
+
return jsonify({'riddle': result[0]["generated_text"].strip()})
|
543 |
+
elif isinstance(result, dict) and "generated_text" in result:
|
544 |
+
return jsonify({'riddle': result["generated_text"].strip()})
|
545 |
+
elif isinstance(result, str):
|
546 |
+
return jsonify({'riddle': result.strip()})
|
547 |
+
logger.error("Failed to generate riddle after retries.")
|
548 |
+
return jsonify({'riddle': "Hare Manavi! I play a tune that makes the gopis dance, but I’m not a drum—what am I? (Answer: Flute)"})
|
|
|
|
|
|
|
549 |
|
550 |
@app.route('/countdown')
|
551 |
def countdown():
|