File size: 27,202 Bytes
5d58e11 d3c471e d144e07 5d58e11 6c135a6 d144e07 35e69a7 ceb56a9 8d77a93 d144e07 5d58e11 d144e07 5d58e11 d144e07 71d9217 d144e07 5d58e11 35e69a7 5d58e11 d144e07 71d9217 6c135a6 5ef7f89 d3c471e 6c135a6 d3c471e 5d58e11 6c135a6 d3c471e 6c135a6 35e69a7 d3c471e d144e07 6c135a6 02d2087 d3c471e 5ef7f89 881b719 d3c471e 6c135a6 d3c471e 6c135a6 8d77a93 6c135a6 5d58e11 8d77a93 02d2087 8d77a93 02d2087 a140eb6 8d77a93 a140eb6 8d77a93 a140eb6 8d77a93 a140eb6 8d77a93 a140eb6 35e69a7 8d77a93 35e69a7 a140eb6 8d77a93 a140eb6 d3c471e a140eb6 6c135a6 02d2087 a140eb6 d3c471e 6c135a6 02d2087 a140eb6 6c135a6 02d2087 584a614 6c135a6 a140eb6 35e69a7 a140eb6 35e69a7 8d77a93 35e69a7 a140eb6 8d77a93 a140eb6 8d77a93 a140eb6 6c135a6 02d2087 6c135a6 02d2087 6c135a6 d144e07 02d2087 ceb56a9 02d2087 ceb56a9 02d2087 ceb56a9 8d77a93 ceb56a9 8d77a93 ceb56a9 02d2087 a140eb6 8d77a93 45fb63b 8d77a93 a140eb6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 |
import os
from datetime import datetime
from flask import Flask, render_template, request, jsonify
from dotenv import load_dotenv
from chatbot import get_krishna_response
from image_api import generate_krishna_image, generate_comic_strip
from countdown import get_countdown
from messages import daily_blessings
import logging
import requests
import random
import time
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize Firebase if available
try:
from firebase_config import save_chat_message, get_chat_history
firebase_enabled = True
logger.info("Firebase integration enabled")
except ImportError as e:
firebase_enabled = False
logger.warning(f"Firebase disabled: {str(e)}")
# Load environment variables
load_dotenv()
HUGGINGFACE_API_TOKEN = os.getenv("HUGGINGFACE_API_TOKEN")
app = Flask(__name__)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
# Daily messages based on the day of the week (with Bhagavad Gita verses)
# Index 0 = Sunday, 1 = Monday, ..., 6 = Saturday
DAILY_MESSAGES = {
0: {"message": "On Sundays, remember: Be like the sun - shine equally on all.", "verse": "Bhagavad Gita 9.29"},
1: {"message": "Monday's wisdom: Perform your duty without attachment to results.", "verse": "Bhagavad Gita 2.47"},
2: {"message": "Tuesday's teaching: The soul is eternal, beyond birth and death.", "verse": "Bhagavad Gita 2.20"},
3: {"message": "Wednesday's lesson: Wherever there is Krishna, there is victory.", "verse": "Bhagavad Gita 18.78"},
4: {"message": "Thursday's insight: Surrender completely to the divine will.", "verse": "Bhagavad Gita 18.66"},
5: {"message": "Friday's guidance: Cultivate divine qualities like compassion.", "verse": "Bhagavad Gita 16.1-3"},
6: {"message": "Saturday's reminder: Find joy in spiritual practice.", "verse": "Bhagavad Gita 6.17"}
}
# Festival messages for specific dates
FESTIVAL_MESSAGES = {
(1, 26): {"message": "Happy Republic Day! Let Dharma guide our nation.", "verse": "Bhagavad Gita 4.7", "special": True},
(8, 19): {"message": "Happy Krishna Janmashtami! Celebrate the divine birth.", "verse": "Bhagavad Gita 4.9", "special": True},
(4, 19): {"message": "Happy Birthday, Manavi! I’ve brought Vrindavan’s magic to celebrate with you!", "verse": "Bhagavad Gita 2.22", "special": True}
}
def get_daily_message_and_blessing():
"""Retrieve the daily message and blessing based on the current date."""
today = datetime.now()
# Adjust weekday() to match DAILY_MESSAGES mapping (0 = Sunday, 1 = Monday, ..., 6 = Saturday)
# weekday() returns 0 for Monday, 6 for Sunday, so we shift it: (weekday() + 1) % 7
day_of_week = (today.weekday() + 1) % 7 # Maps Monday (0) to 1, Tuesday (1) to 2, ..., Sunday (6) to 0
month_day = (today.month, today.day)
# Check for festival messages first
if month_day in FESTIVAL_MESSAGES:
daily_message = FESTIVAL_MESSAGES[month_day]
else:
# Default to day-of-the-week message
daily_message = DAILY_MESSAGES.get(day_of_week,
{"message": "Seek the divine in all you do today.",
"verse": "Bhagavad Gita 6.30"})
daily_message['special'] = False
# Precompute daily blessing index
daily_blessing_index = (today.day - 1) % len(daily_blessings)
daily_blessing = daily_blessings[daily_blessing_index]
return {
"message": daily_message["message"],
"verse": daily_message["verse"],
"is_special": daily_message.get("special", False),
"blessing": daily_blessing
}
def make_api_request(url, headers, payload, retries=3, delay=5):
"""Helper function to make API requests with retry logic."""
for attempt in range(retries):
try:
response = requests.post(url, headers=headers, json=payload)
if response.status_code == 200:
return response
elif response.status_code == 429: # Rate limit
logger.warning(f"Rate limit hit on attempt {attempt + 1}. Retrying after {delay} seconds...")
time.sleep(delay)
continue
else:
logger.error(f"API error: {response.text}")
return None
except Exception as e:
logger.error(f"API request failed: {str(e)}")
if attempt < retries - 1:
time.sleep(delay)
continue
return None
def generate_daily_quote():
"""Generate a daily inspirational quote in Krishna's tone using an AI model."""
headers = {
"Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}",
"Content-Type": "application/json"
}
prompt = (
"You are Little Krishna, a wise and playful cowherd from Vrindavan, speaking to Manavi. "
"Generate a short, inspirational quote (1 sentence) in a wise yet playful tone, using Vrindavan imagery. "
"Example: 'Hare Manavi! Let your heart bloom like the lotus in the Yamuna, for love is the sweetest melody of Vrindavan!'"
)
payload = {
"inputs": prompt,
"parameters": {
"max_length": 50,
"temperature": 0.9,
"top_p": 0.9,
"top_k": 50
}
}
response = make_api_request(
"https://api-inference.huggingface.co/models/EleutherAI/gpt-neo-1.3B",
headers=headers,
json=payload
)
if response:
result = response.json()
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
return result[0]["generated_text"].strip()
elif isinstance(result, dict) and "generated_text" in result:
return result["generated_text"].strip()
elif isinstance(result, str):
return result.strip()
logger.error("Failed to generate daily quote after retries.")
return "Hare Manavi! Let your heart bloom like the lotus in the Yamuna, for love is the sweetest melody of Vrindavan!"
def generate_horoscope():
"""Generate a personalized daily horoscope for Manavi in Krishna's tone."""
today = datetime.now().strftime("%B %d, %Y") # Dynamically get the current date
headers = {
"Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}",
"Content-Type": "application/json"
}
prompt = (
f"You are Little Krishna, a wise and playful cowherd from Vrindavan, speaking to Manavi on {today}. "
"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. "
"Do not include any self-referential text about being Little Krishna or Manavi's identity. "
"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!'"
)
payload = {
"inputs": prompt,
"parameters": {
"max_length": 60,
"temperature": 0.9,
"top_p": 0.9,
"top_k": 50
}
}
response = make_api_request(
"https://api-inference.huggingface.co/models/bigscience/bloom-560m",
headers=headers,
json=payload
)
if response:
result = response.json()
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
return result[0]["generated_text"].strip()
elif isinstance(result, dict) and "generated_text" in result:
return result["generated_text"].strip()
elif isinstance(result, str):
return result.strip()
logger.error("Failed to generate horoscope after retries.")
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!"
def generate_birthday_message():
"""Generate a unique birthday message for Manavi using an AI model."""
headers = {
"Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}",
"Content-Type": "application/json"
}
prompt = (
"You are Little Krishna, a playful and loving cowherd from Vrindavan, speaking to Manavi on her birthday, April 19, 2025. "
"Ayush has created this chatbot as a surprise for her, and you are his wingman. "
"Write a short, heartfelt birthday message (1-2 sentences) for Manavi, filled with Vrindavan imagery and a playful tone. "
"Example: '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!'"
)
payload = {
"inputs": prompt,
"parameters": {
"max_length": 60,
"temperature": 0.9,
"top_p": 0.9,
"top_k": 50
}
}
response = make_api_request(
"https://api-inference.huggingface.co/models/bigscience/bloom-560m",
headers=headers,
json=payload
)
if response:
result = response.json()
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
return result[0]["generated_text"].strip()
elif isinstance(result, dict) and "generated_text" in result:
return result["generated_text"].strip()
elif isinstance(result, str):
return result.strip()
logger.error("Failed to generate birthday message after retries.")
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!"
def generate_gift_suggestions():
"""Generate personalized gift suggestions for Manavi in Krishna's tone."""
headers = {
"Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}",
"Content-Type": "application/json"
}
prompt = (
"You are Little Krishna, a playful cowherd from Vrindavan, speaking to Manavi on her birthday, April 19, 2025. "
"Ayush has created this chatbot as a surprise for her. "
"Suggest three personalized gifts for Manavi that reflect her interests in art, nature, and spirituality, in a playful Krishna tone. "
"Keep each suggestion short (1 sentence) and use Vrindavan imagery. "
"Example: 'Hare Manavi! A peacock feather paintbrush to create art as vibrant as Vrindavan’s flowers!'"
)
payload = {
"inputs": prompt,
"parameters": {
"max_length": 100,
"temperature": 0.9,
"top_p": 0.9,
"top_k": 50
}
}
response = make_api_request(
"https://api-inference.huggingface.co/models/google/gemma-2b",
headers=headers,
json=payload
)
if response:
result = response.json()
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
return result[0]["generated_text"].strip().split('\n')
elif isinstance(result, dict) and "generated_text" in result:
return result["generated_text"].strip().split('\n')
elif isinstance(result, str):
return result.strip().split('\n')
logger.error("Failed to generate gift suggestions after retries.")
return [
"Hare Manavi! A peacock feather paintbrush to create art as vibrant as Vrindavan’s flowers!",
"Hare Manavi! A lotus-shaped journal to capture your thoughts by the Yamuna’s serene banks!",
"Hare Manavi! A flute pendant to carry Vrindavan’s spiritual melody close to your heart!"
]
@app.route('/')
def home():
"""Render the home page with daily message, blessing, quote, and horoscope"""
daily_data = get_daily_message_and_blessing()
countdown_days = get_countdown()
daily_quote = generate_daily_quote()
daily_horoscope = generate_horoscope()
return render_template('home.html',
daily_message=daily_data['message'],
verse_reference=daily_data['verse'],
is_special=daily_data['is_special'],
daily_blessing=daily_data['blessing'],
daily_quote=daily_quote,
daily_horoscope=daily_horoscope,
countdown=countdown_days)
@app.route('/chat', methods=['GET', 'POST'])
def chat():
"""Handle chat interactions with Little Krishna"""
try:
if request.method == 'POST':
user_input = request.form['message']
reply = get_krishna_response(user_input)
if firebase_enabled:
try:
save_chat_message(user_input, reply)
except Exception as e:
logger.error(f"Failed to save chat message to Firebase: {str(e)}")
return jsonify({'reply': reply})
chat_history = get_chat_history() if firebase_enabled else []
return render_template('chat.html', chat_history=chat_history)
except Exception as e:
logger.error(f"Error in /chat route: {str(e)}")
return jsonify({'error': 'Internal Server Error: Please try again later.'}), 500
@app.route('/message')
def message():
"""Render the birthday message page with an AI-generated message, image, and gift suggestions"""
birthday_message = generate_birthday_message()
gift_suggestions = generate_gift_suggestions()
# Generate a birthday image for Manavi
image_prompt = "Little Krishna celebrating Manavi’s birthday in Vrindavan, with peacocks, butter pots, and a festive atmosphere, cartoon style"
birthday_image_url = generate_krishna_image(image_prompt)
if not birthday_image_url:
# Retry with a simpler prompt
image_prompt = "Little Krishna with a peacock feather, playing a flute in Vrindavan, cartoon style"
birthday_image_url = generate_krishna_image(image_prompt)
if not birthday_image_url:
birthday_image_url = "/static/assets/krishna.png" # Fallback image
return render_template('message.html', birthday_message=birthday_message, birthday_image_url=birthday_image_url, gift_suggestions=gift_suggestions)
@app.route('/adventure', methods=['GET', 'POST'])
def adventure():
"""Handle the interactive Vrindavan adventure game"""
if request.method == 'POST':
choice = request.form.get('choice', '')
current_scene = request.form.get('current_scene', 'start')
scenes = {
'start': {
'prompt': (
"You are Little Krishna, a playful cowherd from Vrindavan, guiding Manavi on an interactive adventure in Vrindavan. "
"Start the adventure with a short scene (2-3 sentences) introducing Manavi to Vrindavan, and offer her two choices to continue the story. "
"Example: 'Hare Manavi! We’re standing by the Yamuna’s sparkling waters in Vrindavan—shall we chase the peacocks dancing nearby or sneak some butter from the gopis’ pots? (Choices: Chase peacocks, Sneak butter)'"
),
'next_scenes': {'Chase peacocks': 'peacocks', 'Sneak butter': 'butter'}
},
'peacocks': {
'prompt': (
"You are Little Krishna, a playful cowherd from Vrindavan, guiding Manavi on an interactive adventure in Vrindavan. "
"Manavi chose to chase peacocks. Describe a short scene (2-3 sentences) where Manavi chases peacocks with you, and offer her two new choices to continue the story. "
"Example: 'Hare Manavi! We chased the peacocks through Vrindavan’s fields, their feathers shimmering like rainbows—now, shall we climb the kadamba tree to see them better or play a tune on my flute to call them back? (Choices: Climb tree, Play flute)'"
),
'next_scenes': {'Climb tree': 'tree', 'Play flute': 'flute'}
},
'butter': {
'prompt': (
"You are Little Krishna, a playful cowherd from Vrindavan, guiding Manavi on an interactive adventure in Vrindavan. "
"Manavi chose to sneak butter. Describe a short scene (2-3 sentences) where Manavi sneaks butter with you, and offer her two new choices to continue the story. "
"Example: 'Hare Manavi! We sneaked some butter from the gopis’ pots, giggling as they chased us—shall we hide by the Yamuna to enjoy our treat or share it with the calves? (Choices: Hide by Yamuna, Share with calves)'"
),
'next_scenes': {'Hide by Yamuna': 'yamuna', 'Share with calves': 'calves'}
},
'tree': {
'prompt': (
"You are Little Krishna, a playful cowherd from Vrindavan, guiding Manavi on an interactive adventure in Vrindavan. "
"Manavi chose to climb the kadamba tree. Describe a short scene (2-3 sentences) where Manavi climbs the tree with you, and end the story with a playful conclusion. "
"Example: 'Hare Manavi! We climbed the kadamba tree, watching the peacocks dance below, and I played a flute tune to make them twirl even faster—what a magical Vrindavan day!'"
),
'next_scenes': {}
},
'flute': {
'prompt': (
"You are Little Krishna, a playful cowherd from Vrindavan, guiding Manavi on an interactive adventure in Vrindavan. "
"Manavi chose to play the flute. Describe a short scene (2-3 sentences) where Manavi listens to your flute, and end the story with a playful conclusion. "
"Example: 'Hare Manavi! I played a sweet flute tune, and the peacocks gathered around us, dancing to the melody—what a joyful Vrindavan memory we’ve made!'"
),
'next_scenes': {}
},
'yamuna': {
'prompt': (
"You are Little Krishna, a playful cowherd from Vrindavan, guiding Manavi on an interactive adventure in Vrindavan. "
"Manavi chose to hide by the Yamuna. Describe a short scene (2-3 sentences) where Manavi hides by the Yamuna with you, and end the story with a playful conclusion. "
"Example: 'Hare Manavi! We hid by the Yamuna, sharing the butter as the river sparkled, and the gopis laughed when they found us—what a mischievous Vrindavan adventure!'"
),
'next_scenes': {}
},
'calves': {
'prompt': (
"You are Little Krishna, a playful cowherd from Vrindavan, guiding Manavi on an interactive adventure in Vrindavan. "
"Manavi chose to share the butter with the calves. Describe a short scene (2-3 sentences) where Manavi shares the butter with the calves, and end the story with a playful conclusion. "
"Example: 'Hare Manavi! We shared the butter with the calves, who mooed happily, and the gopis smiled at our kindness—what a sweet Vrindavan moment!'"
),
'next_scenes': {}
}
}
scene = scenes.get(current_scene, scenes['start'])
headers = {
"Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}",
"Content-Type": "application/json"
}
payload = {
"inputs": scene['prompt'],
"parameters": {
"max_length": 80,
"temperature": 0.9,
"top_p": 0.9,
"top_k": 50
}
}
response = make_api_request(
"https://api-inference.huggingface.co/models/EleutherAI/gpt-neo-1.3B",
headers=headers,
json=payload
)
if response:
result = response.json()
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
story_text = result[0]["generated_text"].strip()
elif isinstance(result, dict) and "generated_text" in result:
story_text = result["generated_text"].strip()
elif isinstance(result, str):
story_text = result.strip()
else:
story_text = scene['prompt'].split('Example: ')[1]
else:
logger.error("Failed to generate adventure scene after retries.")
story_text = scene['prompt'].split('Example: ')[1]
next_scene = scene['next_scenes'].get(choice, None)
if next_scene:
return jsonify({'scene': story_text, 'current_scene': next_scene, 'choices': list(scene['next_scenes'].keys())})
else:
return jsonify({'scene': story_text, 'current_scene': None, 'choices': []})
return render_template('adventure.html')
@app.route('/image', methods=['POST'])
def image():
"""Generate a Krishna-themed image based on a prompt"""
prompt = request.json['prompt']
image_url = generate_krishna_image(prompt)
if image_url:
return jsonify({'image_url': image_url})
return jsonify({'error': 'Failed to generate image'}), 500
@app.route('/comic', methods=['GET'])
def comic():
"""Generate a Krishna-themed comic strip"""
comic_images = generate_comic_strip()
return jsonify({'comic_images': comic_images})
@app.route('/story', methods=['POST'])
def story():
"""Generate a text-based Krishna story based on a user-provided theme"""
theme = request.json.get('theme', 'Vrindavan') # Default theme if none provided
story_models = [
{
"name": "microsoft/DialoGPT-large",
"endpoint": "https://api-inference.huggingface.co/models/microsoft/DialoGPT-large",
"parameters": {
"max_length": 80,
"temperature": 0.9,
"top_p": 0.9,
"top_k": 50
}
},
{
"name": "EleutherAI/gpt-neo-1.3B",
"endpoint": "https://api-inference.huggingface.co/models/EleutherAI/gpt-neo-1.3B",
"parameters": {
"max_length": 80,
"temperature": 0.9,
"top_p": 0.9,
"top_k": 50
}
}
]
prompt = (
f"You are Little Krishna, a playful cowherd from Vrindavan, telling a short story (2-3 sentences) to Manavi. "
f"The story should be fun, Krishna-like, and include the theme '{theme}'. "
f"Example: 'Hare Manavi! One day, I hid the gopis’ butter in a peacock’s nest, and they danced with me to get it back—what a Vrindavan adventure!'"
)
headers = {
"Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}",
"Content-Type": "application/json"
}
# Shuffle models to try them in random order
models_to_try = story_models.copy()
random.shuffle(models_to_try)
for model in models_to_try:
try:
payload = {
"inputs": prompt,
"parameters": model["parameters"]
}
response = make_api_request(model["endpoint"], headers=headers, json=payload)
if response and response.status_code == 200:
result = response.json()
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
return jsonify({'story': result[0]["generated_text"].strip()})
elif isinstance(result, dict) and "generated_text" in result:
return jsonify({'story': result["generated_text"].strip()})
elif isinstance(result, str):
return jsonify({'story': result.strip()})
print(f"Error with {model['name']}: {response.text if response else 'No response'}")
continue
except Exception as e:
print(f"Error connecting to {model['name']}: {str(e)}")
continue
# Fallback if all models fail
return jsonify({'story': f"Hare Manavi! One day, I hid the gopis’ {theme} in a peacock’s nest, and they danced with me to get it back—what a Vrindavan adventure!"})
@app.route('/story_audio', methods=['POST'])
def story_audio():
"""Generate audio narration for a story using text-to-speech."""
story_text = request.json.get('story_text', '')
headers = {
"Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}",
"Content-Type": "application/json"
}
payload = {
"inputs": story_text
}
response = make_api_request(
"https://api-inference.huggingface.co/models/facebook/tts-transformer-en-ljspeech",
headers=headers,
json=payload
)
if response and response.status_code == 200:
audio_path = "static/audio/story_audio.mp3"
with open(audio_path, "wb") as f:
f.write(response.content)
return jsonify({'audio_url': f"/{audio_path}"})
logger.error("Failed to generate story audio after retries.")
return jsonify({'error': 'Failed to generate audio'}), 500
@app.route('/riddle', methods=['GET'])
def riddle():
"""Generate a Krishna-themed riddle using an AI model."""
headers = {
"Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}",
"Content-Type": "application/json"
}
prompt = (
"You are Little Krishna, a playful cowherd from Vrindavan, speaking to Manavi. "
"Generate a short, Krishna-themed riddle (1-2 sentences) with a playful tone, using Vrindavan imagery. "
"Include the answer in parentheses at the end. "
"Example: 'Hare Manavi! I play a tune that makes the gopis dance, but I’m not a drum—what am I? (Answer: Flute)'"
)
payload = {
"inputs": prompt,
"parameters": {
"max_length": 60,
"temperature": 0.9,
"top_p": 0.9,
"top_k": 50
}
}
response = make_api_request(
"https://api-inference.huggingface.co/models/mistralai/Mixtral-8x7B-Instruct-v0.1",
headers=headers,
json=payload
)
if response and response.status_code == 200:
result = response.json()
if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
return jsonify({'riddle': result[0]["generated_text"].strip()})
elif isinstance(result, dict) and "generated_text" in result:
return jsonify({'riddle': result["generated_text"].strip()})
elif isinstance(result, str):
return jsonify({'riddle': result.strip()})
logger.error("Failed to generate riddle after retries.")
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)"})
@app.route('/countdown')
def countdown():
"""Return the number of days until Manavi's birthday"""
days_left = get_countdown()
return jsonify({'days': days_left})
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port, debug=False) |