|
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 |
|
|
|
|
|
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") |
|
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 get_daily_message_and_blessing(): |
|
"""Retrieve the daily message and blessing based on the current date.""" |
|
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 |
|
} |
|
|
|
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: |
|
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_horoscope(): |
|
"""Generate a personalized daily horoscope for Manavi in Krishna's tone.""" |
|
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. " |
|
"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, |
|
payload=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, |
|
payload=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, |
|
payload=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, and horoscope""" |
|
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) |
|
|
|
@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 = request.form['message'] |
|
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: {chat_history}") |
|
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 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() |
|
|
|
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: |
|
|
|
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" |
|
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""" |
|
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/EleutherAI/gpt-neo-1.3B", |
|
headers=headers, |
|
payload=payload |
|
) |
|
if response and response.status_code == 200: |
|
result = response.json() |
|
logger.info(f"API response: {result}") |
|
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: |
|
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 jsonify({'error': 'Internal Server Error: Please try again later.'}), 500 |
|
|
|
@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') |
|
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" |
|
} |
|
|
|
|
|
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, payload=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 |
|
|
|
|
|
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, |
|
payload=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, |
|
payload=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) |