|
import os |
|
from datetime import datetime |
|
from flask import Flask, render_template, request, jsonify, escape |
|
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, birthday_messages, auto_generate_birthday_message |
|
import logging |
|
import requests |
|
import random |
|
import backoff |
|
|
|
|
|
logging.basicConfig(level=logging.INFO) |
|
logger = logging.getLogger(__name__) |
|
|
|
|
|
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_dotenv() |
|
HUGGINGFACE_API_TOKEN = os.getenv("HUGGINGFACE_API_TOKEN") |
|
if not HUGGINGFACE_API_TOKEN: |
|
logger.error("HUGGINGFACE_API_TOKEN not found in environment variables.") |
|
raise ValueError("HUGGINGFACE_API_TOKEN is required.") |
|
|
|
app = Flask(__name__) |
|
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True |
|
|
|
|
|
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 = { |
|
(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 parse_huggingface_response(response): |
|
"""Parse Hugging Face API response and extract generated text.""" |
|
try: |
|
result = response.json() |
|
if isinstance(result, list) and result 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("Unexpected API response format.") |
|
return None |
|
except Exception as e: |
|
logger.error(f"Error parsing API response: {str(e)}") |
|
return None |
|
|
|
def get_daily_message_and_blessing(): |
|
"""Retrieve the daily message and blessing based on the current date.""" |
|
try: |
|
today = datetime.now() |
|
day_of_week = (today.weekday() + 1) % 7 |
|
month_day = (today.month, today.day) |
|
|
|
|
|
if month_day in FESTIVAL_MESSAGES: |
|
daily_message = FESTIVAL_MESSAGES[month_day] |
|
else: |
|
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 |
|
|
|
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 |
|
} |
|
except Exception as e: |
|
logger.error(f"Error in get_daily_message_and_blessing: {str(e)}") |
|
return { |
|
"message": "Seek the divine in all you do today.", |
|
"verse": "Bhagavad Gita 6.30", |
|
"is_special": False, |
|
"blessing": "Hare Manavi! May Vrindavan’s joy fill your heart today!" |
|
} |
|
|
|
@backoff.on_exception(backoff.expo, (requests.exceptions.RequestException, requests.exceptions.HTTPError), max_tries=12, max_time=900) |
|
def make_api_request(url, headers, payload, timeout=180): |
|
"""Helper function to make API requests with exponential backoff.""" |
|
try: |
|
response = requests.post(url, headers=headers, json=payload, timeout=timeout) |
|
if response.status_code == 200: |
|
return response |
|
else: |
|
logger.error(f"API error: {response.status_code} - {response.text}") |
|
raise requests.exceptions.HTTPError(f"API returned status {response.status_code}") |
|
except requests.exceptions.RequestException as e: |
|
logger.error(f"API request failed: {str(e)}") |
|
raise |
|
|
|
def generate_birthday_message(): |
|
"""Generate a unique, festive birthday message for Manavi.""" |
|
try: |
|
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) starting with 'Happy Birthday, Manavi!', filled with Vrindavan imagery and a festive tone. " |
|
"Example: 'Happy Birthday, Manavi! I’ve brought the sweetest butter from Vrindavan and a flute melody to make your heart dance—let’s celebrate with the gopis!'" |
|
) |
|
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, |
|
payload=payload |
|
) |
|
result = parse_huggingface_response(response) |
|
if result and result.startswith("Happy Birthday, Manavi!"): |
|
return result |
|
logger.warning("Invalid API response; returning auto-generated birthday message.") |
|
return auto_generate_birthday_message(include_tease=True) |
|
except Exception as e: |
|
logger.error(f"Error in generate_birthday_message: {str(e)}") |
|
return auto_generate_birthday_message(include_tease=True) |
|
|
|
def generate_gift_suggestions(): |
|
"""Generate personalized gift suggestions for Manavi in Krishna's tone.""" |
|
try: |
|
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. " |
|
"Return the suggestions as a numbered list (1., 2., 3.). " |
|
"Example: '1. Hare Manavi! A peacock feather paintbrush to create art as vibrant as Vrindavan’s flowers!\n" |
|
"2. A lotus-shaped journal to capture your thoughts by the Yamuna’s serene banks!\n" |
|
"3. A flute pendant to carry Vrindavan’s spiritual melody close to your heart!'" |
|
) |
|
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/mistralai/Mixtral-8x7B-Instruct-v0.1", |
|
headers=headers, |
|
payload=payload |
|
) |
|
result = parse_huggingface_response(response) |
|
if result: |
|
suggestions = result.strip().split('\n') |
|
return [s.strip() for s in suggestions if s.strip()] |
|
logger.warning("Returning fallback gift suggestions due to API failure.") |
|
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!" |
|
] |
|
except Exception as e: |
|
logger.error(f"Error in generate_gift_suggestions: {str(e)}") |
|
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!" |
|
] |
|
|
|
def generate_horoscope(): |
|
"""Generate a personalized daily horoscope for Manavi in Krishna's tone.""" |
|
try: |
|
today = datetime.now().strftime("%B %d, %Y") |
|
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. " |
|
"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/mistralai/Mixtral-8x7B-Instruct-v0.1", |
|
headers=headers, |
|
payload=payload |
|
) |
|
result = parse_huggingface_response(response) |
|
if result: |
|
return result |
|
logger.warning("Returning fallback horoscope due to API failure.") |
|
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!" |
|
except Exception as e: |
|
logger.error(f"Error in generate_horoscope: {str(e)}") |
|
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!" |
|
|
|
@app.route('/') |
|
def home(): |
|
"""Render the home page with daily message, blessing, and horoscope.""" |
|
try: |
|
daily_data = get_daily_message_and_blessing() |
|
countdown_days = get_countdown() |
|
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_horoscope=daily_horoscope, |
|
countdown=countdown_days) |
|
except Exception as e: |
|
logger.error(f"Error in / route: {str(e)}") |
|
return render_template('error.html', error_message='Failed to load homepage. Please try again later.'), 500 |
|
|
|
@app.route('/chat', methods=['GET', 'POST']) |
|
def chat(): |
|
"""Handle chat interactions with Little Krishna.""" |
|
try: |
|
if request.method == 'POST': |
|
if 'message' not in request.form: |
|
logger.error("Missing 'message' in POST request form data.") |
|
return jsonify({'error': 'Missing message parameter'}), 400 |
|
user_input = escape(request.form['message'].strip()) |
|
if not user_input: |
|
logger.error("Empty message received.") |
|
return jsonify({'error': 'Message cannot be empty'}), 400 |
|
if len(user_input) > 500: |
|
logger.error("Message too long.") |
|
return jsonify({'error': 'Message too long (max 500 characters)'}), 400 |
|
logger.info(f"Received chat input: {user_input}") |
|
reply = get_krishna_response(user_input) |
|
logger.info(f"Generated reply: {reply}") |
|
if firebase_enabled: |
|
try: |
|
save_chat_message(user_input, reply) |
|
logger.info("Successfully saved chat message to Firebase.") |
|
except Exception as e: |
|
logger.error(f"Failed to save chat message to Firebase: {str(e)}") |
|
return jsonify({'reply': reply}) |
|
try: |
|
chat_history = get_chat_history() if firebase_enabled else [] |
|
logger.info(f"Retrieved chat history: {len(chat_history)} messages") |
|
except Exception as e: |
|
logger.error(f"Failed to retrieve chat history from Firebase: {str(e)}") |
|
chat_history = [] |
|
return render_template('chat.html', chat_history=chat_history) |
|
except Exception as e: |
|
logger.error(f"Error in /chat route: {str(e)}") |
|
return render_template('error.html', error_message='Failed to load chat page. Please try again later.'), 500 |
|
|
|
@app.route('/adventure', methods=['GET', 'POST']) |
|
def adventure(): |
|
"""Handle the interactive Vrindavan adventure game.""" |
|
try: |
|
if request.method == 'POST': |
|
choice = request.form.get('choice', '') |
|
current_scene = request.form.get('current_scene', 'start') |
|
logger.info(f"Adventure POST request: current_scene={current_scene}, choice={choice}") |
|
|
|
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/mistralai/Mixtral-8x7B-Instruct-v0.1", |
|
headers=headers, |
|
payload=payload |
|
) |
|
if response and response.status_code == 200: |
|
result = parse_huggingface_response(response) |
|
logger.info(f"API response: {result}") |
|
if result: |
|
story_text = result |
|
else: |
|
logger.error("Unexpected API response format.") |
|
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') |
|
except Exception as e: |
|
logger.error(f"Error in /adventure route: {str(e)}") |
|
return render_template('error.html', error_message='Failed to load adventure page. Please try again later.'), 500 |
|
|
|
@app.route('/message') |
|
def message(): |
|
"""Render the birthday message page with an AI-generated message and gift suggestions.""" |
|
try: |
|
birthday_message = generate_birthday_message() |
|
gift_suggestions = generate_gift_suggestions() |
|
birthday_image_url = "/static/assets/krishna.png" |
|
today = datetime.now() |
|
is_birthday = today.month == 4 and today.day == 19 |
|
return render_template('message.html', |
|
birthday_message=birthday_message, |
|
birthday_image_url=birthday_image_url, |
|
gift_suggestions=gift_suggestions, |
|
is_birthday=is_birthday) |
|
except Exception as e: |
|
logger.error(f"Error in /message route: {str(e)}") |
|
return render_template('error.html', error_message='Failed to load birthday message page. Please try again later.'), 500 |
|
|
|
@app.route('/image', methods=['POST']) |
|
def image(): |
|
"""Generate a Krishna-themed image based on a prompt.""" |
|
try: |
|
prompt = request.json.get('prompt', '') |
|
if not prompt: |
|
return jsonify({'error': 'Missing prompt parameter'}), 400 |
|
image_url = generate_krishna_image(prompt) |
|
if image_url: |
|
return jsonify({'image_url': image_url}) |
|
return jsonify({'error': 'Failed to generate image'}), 500 |
|
except Exception as e: |
|
logger.error(f"Error in /image route: {str(e)}") |
|
return jsonify({'error': 'Internal Server Error: Please try again later.'}), 500 |
|
|
|
@app.route('/comic', methods=['GET']) |
|
def comic(): |
|
"""Generate a Krishna-themed comic strip.""" |
|
try: |
|
comic_images = generate_comic_strip() |
|
return jsonify({'comic_images': comic_images}) |
|
except Exception as e: |
|
logger.error(f"Error in /comic route: {str(e)}") |
|
return jsonify({'error': 'Internal Server Error: Please try again later.'}), 500 |
|
|
|
@app.route('/story', methods=['POST']) |
|
def story(): |
|
"""Generate a text-based Krishna story based on a user-provided theme.""" |
|
try: |
|
theme = request.json.get('theme', 'Vrindavan') |
|
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" |
|
} |
|
payload = { |
|
"inputs": 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/mistralai/Mixtral-8x7B-Instruct-v0.1", |
|
headers=headers, |
|
payload=payload |
|
) |
|
result = parse_huggingface_response(response) |
|
if result: |
|
return jsonify({'story': result}) |
|
logger.error("Failed to generate story after retries.") |
|
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!"}) |
|
except Exception as e: |
|
logger.error(f"Error in /story route: {str(e)}") |
|
return jsonify({'error': 'Internal Server Error: Please try again later.'}), 500 |
|
|
|
@app.route('/story_audio', methods=['POST']) |
|
def story_audio(): |
|
"""Generate audio narration for a story using text-to-speech.""" |
|
try: |
|
story_text = request.json.get('story_text', '') |
|
if not story_text: |
|
return jsonify({'error': 'Missing story_text parameter'}), 400 |
|
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, |
|
payload=payload |
|
) |
|
if response and response.status_code == 200: |
|
audio_path = "static/audio/story_audio.mp3" |
|
os.makedirs(os.path.dirname(audio_path), exist_ok=True) |
|
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 |
|
except Exception as e: |
|
logger.error(f"Error in /story_audio route: {str(e)}") |
|
return jsonify({'error': 'Internal Server Error: Please try again later.'}), 500 |
|
|
|
@app.route('/riddle', methods=['GET']) |
|
def riddle(): |
|
"""Generate a Krishna-themed riddle using an AI model.""" |
|
try: |
|
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, |
|
payload=payload |
|
) |
|
result = parse_huggingface_response(response) |
|
if result: |
|
return jsonify({'riddle': result}) |
|
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)"}) |
|
except Exception as e: |
|
logger.error(f"Error in /riddle route: {str(e)}") |
|
return jsonify({'error': 'Internal Server Error: Please try again later.'}), 500 |
|
|
|
@app.route('/countdown') |
|
def countdown(): |
|
"""Return the number of days until Manavi's birthday.""" |
|
try: |
|
days_left = get_countdown() |
|
return jsonify({'days': days_left}) |
|
except Exception as e: |
|
logger.error(f"Error in /countdown route: {str(e)}") |
|
return jsonify({'error': 'Internal Server Error: Please try again later.'}), 500 |
|
|
|
if __name__ == '__main__': |
|
port = int(os.environ.get('PORT', 7860)) |
|
app.run(host='0.0.0.0', port=port, debug=False) |