BirthdayM / app.py
ayush2917's picture
Update app.py
35e69a7 verified
raw
history blame
7.52 kB
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
# 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)
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():
today = datetime.now()
day_of_week = today.weekday()
month_day = (today.month, today.day)
day_of_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
# Get the daily blessing based on the day of the month
daily_blessing_index = (day_of_month - 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 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
}
}
try:
response = requests.post(
"https://api-inference.huggingface.co/models/bigscience/bloom-560m",
headers=headers,
json=payload
)
if response.status_code == 200:
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()
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!"
except Exception as e:
logger.error(f"Error generating birthday message: {str(e)}")
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!"
@app.route('/')
def home():
"""Render the home page with daily message and blessing"""
daily_data = get_daily_message_and_blessing()
countdown_days = get_countdown()
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'],
countdown=countdown_days)
@app.route('/chat', methods=['GET', 'POST'])
def chat():
if request.method == 'POST':
user_input = request.form['message']
reply = get_krishna_response(user_input)
if firebase_enabled:
save_chat_message(user_input, reply)
return jsonify({'reply': reply})
chat_history = get_chat_history() if firebase_enabled else []
return render_template('chat.html', chat_history=chat_history)
@app.route('/message')
def message():
birthday_message = generate_birthday_message()
# 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:
birthday_image_url = "/static/assets/krishna.png" # Fallback image
return render_template('message.html', birthday_message=birthday_message, birthday_image_url=birthday_image_url)
@app.route('/image', methods=['POST'])
def image():
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():
comic_images = generate_comic_strip()
return jsonify({'comic_images': comic_images})
@app.route('/countdown')
def countdown():
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)