ayush2917 commited on
Commit
1cb68f6
·
verified ·
1 Parent(s): 466086f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -38
app.py CHANGED
@@ -5,12 +5,13 @@ from dotenv import load_dotenv
5
  from chatbot import get_krishna_response
6
  from image_api import generate_krishna_image, generate_comic_strip
7
  from countdown import get_countdown
8
- from messages import daily_blessings, birthday_messages, auto_generate_birthday_message
 
9
  import logging
10
  import requests
11
  import random
12
  import backoff
13
- from ayush_messages import ayush_surprises
14
 
15
  # Configure logging
16
  logging.basicConfig(level=logging.INFO)
@@ -21,21 +22,21 @@ try:
21
  from firebase_config import save_chat_message, get_chat_history
22
  firebase_enabled = True
23
  logger.info("Firebase integration enabled")
24
- except ImportError as e:
25
  firebase_enabled = False
26
- logger.warning(f"Firebase disabled: {str(e)}")
27
 
28
  # Load environment variables
29
  load_dotenv()
30
  HUGGINGFACE_API_TOKEN = os.getenv("HUGGINGFACE_API_TOKEN")
31
  if not HUGGINGFACE_API_TOKEN:
32
- logger.error("HUGGINGFACE_API_TOKEN not found in environment variables.")
33
- raise ValueError("HUGGINGFACE_API_TOKEN is required.")
34
 
35
  app = Flask(__name__)
36
  app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
37
 
38
- # Daily messages based on the day of the week (with Bhagavad Gita verses)
39
  DAILY_MESSAGES = {
40
  0: {"message": "On Sundays, shine like the sun for all!", "verse": "Bhagavad Gita 9.29"},
41
  1: {"message": "Monday: Do your duty without attachment.", "verse": "Bhagavad Gita 2.47"},
@@ -46,7 +47,7 @@ DAILY_MESSAGES = {
46
  6: {"message": "Saturday: Find joy in spiritual practice.", "verse": "Bhagavad Gita 6.17"}
47
  }
48
 
49
- # Festival messages for specific dates
50
  FESTIVAL_MESSAGES = {
51
  (1, 26): {"message": "Happy Republic Day! Let Dharma guide our nation.", "verse": "Bhagavad Gita 4.7", "special": True},
52
  (8, 19): {"message": "Happy Krishna Janmashtami! Celebrate the divine birth.", "verse": "Bhagavad Gita 4.9", "special": True},
@@ -54,7 +55,7 @@ FESTIVAL_MESSAGES = {
54
  }
55
 
56
  def parse_huggingface_response(response):
57
- """Parse Hugging Face API response and extract generated text."""
58
  try:
59
  result = response.json()
60
  if isinstance(result, list) and result and "generated_text" in result[0]:
@@ -63,20 +64,19 @@ def parse_huggingface_response(response):
63
  return result["generated_text"].strip()
64
  elif isinstance(result, str):
65
  return result.strip()
66
- logger.error("Unexpected API response format.")
67
  return None
68
  except Exception as e:
69
  logger.error(f"Error parsing API response: {str(e)}")
70
  return None
71
 
72
  def get_daily_message_and_blessing():
73
- """Retrieve the daily message and blessing based on the current date."""
74
  try:
75
  today = datetime.now()
76
  day_of_week = (today.weekday() + 1) % 7
77
  month_day = (today.month, today.day)
78
 
79
- # Check for festival messages
80
  if month_day in FESTIVAL_MESSAGES:
81
  daily_message = FESTIVAL_MESSAGES[month_day]
82
  else:
@@ -102,20 +102,20 @@ def get_daily_message_and_blessing():
102
  "blessing": "Hare Manavi! May Vrindavan’s joy fill your heart!"
103
  }
104
 
105
- @backoff.on_exception(backoff.expo, (requests.exceptions.RequestException, requests.exceptions.HTTPError), max_tries=12, max_time=900)
106
- def make_api_request(url, headers, payload, timeout=180):
107
  """Make API requests with exponential backoff."""
108
  try:
109
  response = requests.post(url, headers=headers, json=payload, timeout=timeout)
110
  if response.status_code == 200:
111
  return response
112
- else:
113
- logger.error(f"API error: {response.status_code} - {response.text}")
114
- raise requests.exceptions.HTTPError(f"API returned status {response.status_code}")
115
  except requests.exceptions.RequestException as e:
116
  logger.error(f"API request failed: {str(e)}")
117
  raise
118
 
 
119
  def generate_birthday_message():
120
  """Generate a birthday message for Manavi."""
121
  try:
@@ -148,12 +148,13 @@ def generate_birthday_message():
148
  result = parse_huggingface_response(response)
149
  if result and result.startswith("Happy Birthday, Manavi!"):
150
  return result
151
- logger.warning("Invalid API response; returning auto-generated message.")
152
  return auto_generate_birthday_message(include_tease=True)
153
  except Exception as e:
154
  logger.error(f"Error in generate_birthday_message: {str(e)}")
155
  return auto_generate_birthday_message(include_tease=True)
156
 
 
157
  def generate_gift_suggestions():
158
  """Generate personalized gift suggestions for Manavi."""
159
  try:
@@ -184,7 +185,7 @@ def generate_gift_suggestions():
184
  if result:
185
  suggestions = result.strip().split('\n')
186
  return [s.strip() for s in suggestions if s.strip()]
187
- logger.warning("Returning fallback gift suggestions.")
188
  return [
189
  "Hare Manavi! A peacock feather paintbrush for vibrant art!",
190
  "Hare Manavi! A lotus journal for serene thoughts!",
@@ -198,6 +199,7 @@ def generate_gift_suggestions():
198
  "Hare Manavi! A flute pendant for spiritual melodies!"
199
  ]
200
 
 
201
  def generate_horoscope():
202
  """Generate a daily horoscope for Manavi."""
203
  try:
@@ -228,7 +230,7 @@ def generate_horoscope():
228
  result = parse_huggingface_response(response)
229
  if result:
230
  return result
231
- logger.warning("Returning fallback horoscope.")
232
  return "Hare Manavi! Today, the Yamuna inspires your art—paint with Vrindavan’s colors and let your spirit dance!"
233
  except Exception as e:
234
  logger.error(f"Error in generate_horoscope: {str(e)}")
@@ -250,7 +252,7 @@ def home():
250
  countdown=countdown_days)
251
  except Exception as e:
252
  logger.error(f"Error in / route: {str(e)}")
253
- return render_template('error.html', error_message='Failed to load homepage.'), 500
254
 
255
  @app.route('/chat', methods=['GET', 'POST'])
256
  def chat():
@@ -258,14 +260,14 @@ def chat():
258
  try:
259
  if request.method == 'POST':
260
  if 'message' not in request.form:
261
- logger.error("Missing 'message' in POST request.")
262
  return jsonify({'error': 'Missing message parameter'}), 400
263
  user_input = escape(request.form['message'].strip())
264
  if not user_input:
265
- logger.error("Empty message received.")
266
  return jsonify({'error': 'Message cannot be empty'}), 400
267
  if len(user_input) > 500:
268
- logger.error("Message too long.")
269
  return jsonify({'error': 'Message too long (max 500 characters)'}), 400
270
  logger.info(f"Received chat input: {user_input}")
271
  reply = get_krishna_response(user_input)
@@ -273,7 +275,7 @@ def chat():
273
  if firebase_enabled:
274
  try:
275
  save_chat_message(user_input, reply)
276
- logger.info("Saved chat message to Firebase.")
277
  except Exception as e:
278
  logger.error(f"Failed to save chat message: {str(e)}")
279
  return jsonify({'reply': reply})
@@ -286,7 +288,7 @@ def chat():
286
  return render_template('chat.html', chat_history=chat_history)
287
  except Exception as e:
288
  logger.error(f"Error in /chat route: {str(e)}")
289
- return render_template('error.html', error_message='Failed to load chat page.'), 500
290
 
291
  @app.route('/adventure', methods=['GET', 'POST'])
292
  def adventure():
@@ -373,7 +375,7 @@ def adventure():
373
  result = parse_huggingface_response(response)
374
  story_text = result or scene['prompt'].split('Example: ')[1]
375
  else:
376
- logger.error("Failed to generate adventure scene.")
377
  story_text = scene['prompt'].split('Example: ')[1]
378
 
379
  next_scene = scene['next_scenes'].get(choice)
@@ -384,7 +386,7 @@ def adventure():
384
  return render_template('adventure.html')
385
  except Exception as e:
386
  logger.error(f"Error in /adventure route: {str(e)}")
387
- return render_template('error.html', error_message='Failed to load adventure page.'), 500
388
 
389
  @app.route('/message')
390
  def message():
@@ -402,7 +404,7 @@ def message():
402
  is_birthday=is_birthday)
403
  except Exception as e:
404
  logger.error(f"Error in /message route: {str(e)}")
405
- return render_template('error.html', error_message='Failed to load birthday message page.'), 500
406
 
407
  @app.route('/image', methods=['POST'])
408
  def image():
@@ -417,7 +419,7 @@ def image():
417
  return jsonify({'error': 'Failed to generate image'}), 500
418
  except Exception as e:
419
  logger.error(f"Error in /image route: {str(e)}")
420
- return jsonify({'error': 'Internal Server Error.'}), 500
421
 
422
  @app.route('/comic', methods=['GET'])
423
  def comic():
@@ -427,7 +429,7 @@ def comic():
427
  return jsonify({'comic_images': comic_images})
428
  except Exception as e:
429
  logger.error(f"Error in /comic route: {str(e)}")
430
- return jsonify({'error': 'Internal Server Error.'}), 500
431
 
432
  @app.route('/story', methods=['POST'])
433
  def story():
@@ -459,11 +461,11 @@ def story():
459
  result = parse_huggingface_response(response)
460
  if result:
461
  return jsonify({'story': result})
462
- logger.error("Failed to generate story.")
463
  return jsonify({'story': f"Hare Manavi! I hid the gopis’ {theme} in a peacock’s nest—what a Vrindavan adventure!'"})
464
  except Exception as e:
465
  logger.error(f"Error in /story route: {str(e)}")
466
- return jsonify({'error': 'Internal Server Error.'}), 500
467
 
468
  @app.route('/story_audio', methods=['POST'])
469
  def story_audio():
@@ -488,11 +490,11 @@ def story_audio():
488
  with open(audio_path, "wb") as f:
489
  f.write(response.content)
490
  return jsonify({'audio_url': f"/{audio_path}"})
491
- logger.error("Failed to generate story audio.")
492
  return jsonify({'error': 'Failed to generate audio'}), 500
493
  except Exception as e:
494
  logger.error(f"Error in /story_audio route: {str(e)}")
495
- return jsonify({'error': 'Internal Server Error.'}), 500
496
 
497
  @app.route('/riddle', methods=['GET'])
498
  def riddle():
@@ -523,11 +525,11 @@ def riddle():
523
  result = parse_huggingface_response(response)
524
  if result:
525
  return jsonify({'riddle': result})
526
- logger.error("Failed to generate riddle.")
527
  return jsonify({'riddle': "Hare Manavi! I play a tune that makes gopis dance—what am I? (Answer: Flute)"})
528
  except Exception as e:
529
  logger.error(f"Error in /riddle route: {str(e)}")
530
- return jsonify({'error': 'Internal Server Error.'}), 500
531
 
532
  @app.route('/countdown')
533
  def countdown():
@@ -537,7 +539,7 @@ def countdown():
537
  return jsonify({'days': days_left})
538
  except Exception as e:
539
  logger.error(f"Error in /countdown route: {str(e)}")
540
- return jsonify({'error': 'Internal Server Error.'}), 500
541
 
542
  if __name__ == '__main__':
543
  port = int(os.environ.get('PORT', 7860))
 
5
  from chatbot import get_krishna_response
6
  from image_api import generate_krishna_image, generate_comic_strip
7
  from countdown import get_countdown
8
+ from messages import daily_blessings, auto_generate_birthday_message
9
+ from ayush_messages import ayush_surprises
10
  import logging
11
  import requests
12
  import random
13
  import backoff
14
+ from functools import lru_cache
15
 
16
  # Configure logging
17
  logging.basicConfig(level=logging.INFO)
 
22
  from firebase_config import save_chat_message, get_chat_history
23
  firebase_enabled = True
24
  logger.info("Firebase integration enabled")
25
+ except ImportError:
26
  firebase_enabled = False
27
+ logger.info("Firebase disabled: firebase_config.py not found")
28
 
29
  # Load environment variables
30
  load_dotenv()
31
  HUGGINGFACE_API_TOKEN = os.getenv("HUGGINGFACE_API_TOKEN")
32
  if not HUGGINGFACE_API_TOKEN:
33
+ logger.error("HUGGINGFACE_API_TOKEN not found in environment variables")
34
+ raise ValueError("HUGGINGFACE_API_TOKEN is required")
35
 
36
  app = Flask(__name__)
37
  app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
38
 
39
+ # Daily messages with Bhagavad Gita verses
40
  DAILY_MESSAGES = {
41
  0: {"message": "On Sundays, shine like the sun for all!", "verse": "Bhagavad Gita 9.29"},
42
  1: {"message": "Monday: Do your duty without attachment.", "verse": "Bhagavad Gita 2.47"},
 
47
  6: {"message": "Saturday: Find joy in spiritual practice.", "verse": "Bhagavad Gita 6.17"}
48
  }
49
 
50
+ # Festival messages
51
  FESTIVAL_MESSAGES = {
52
  (1, 26): {"message": "Happy Republic Day! Let Dharma guide our nation.", "verse": "Bhagavad Gita 4.7", "special": True},
53
  (8, 19): {"message": "Happy Krishna Janmashtami! Celebrate the divine birth.", "verse": "Bhagavad Gita 4.9", "special": True},
 
55
  }
56
 
57
  def parse_huggingface_response(response):
58
+ """Parse Hugging Face API response."""
59
  try:
60
  result = response.json()
61
  if isinstance(result, list) and result and "generated_text" in result[0]:
 
64
  return result["generated_text"].strip()
65
  elif isinstance(result, str):
66
  return result.strip()
67
+ logger.error("Unexpected API response format")
68
  return None
69
  except Exception as e:
70
  logger.error(f"Error parsing API response: {str(e)}")
71
  return None
72
 
73
  def get_daily_message_and_blessing():
74
+ """Retrieve daily message and blessing."""
75
  try:
76
  today = datetime.now()
77
  day_of_week = (today.weekday() + 1) % 7
78
  month_day = (today.month, today.day)
79
 
 
80
  if month_day in FESTIVAL_MESSAGES:
81
  daily_message = FESTIVAL_MESSAGES[month_day]
82
  else:
 
102
  "blessing": "Hare Manavi! May Vrindavan’s joy fill your heart!"
103
  }
104
 
105
+ @backoff.on_exception(backoff.expo, (requests.exceptions.RequestException, requests.exceptions.HTTPError), max_tries=2, max_time=60)
106
+ def make_api_request(url, headers, payload, timeout=30):
107
  """Make API requests with exponential backoff."""
108
  try:
109
  response = requests.post(url, headers=headers, json=payload, timeout=timeout)
110
  if response.status_code == 200:
111
  return response
112
+ logger.error(f"API error: {response.status_code} - {response.text}")
113
+ raise requests.exceptions.HTTPError(f"API returned status {response.status_code}")
 
114
  except requests.exceptions.RequestException as e:
115
  logger.error(f"API request failed: {str(e)}")
116
  raise
117
 
118
+ @lru_cache(maxsize=10)
119
  def generate_birthday_message():
120
  """Generate a birthday message for Manavi."""
121
  try:
 
148
  result = parse_huggingface_response(response)
149
  if result and result.startswith("Happy Birthday, Manavi!"):
150
  return result
151
+ logger.warning("Invalid API response; using fallback")
152
  return auto_generate_birthday_message(include_tease=True)
153
  except Exception as e:
154
  logger.error(f"Error in generate_birthday_message: {str(e)}")
155
  return auto_generate_birthday_message(include_tease=True)
156
 
157
+ @lru_cache(maxsize=10)
158
  def generate_gift_suggestions():
159
  """Generate personalized gift suggestions for Manavi."""
160
  try:
 
185
  if result:
186
  suggestions = result.strip().split('\n')
187
  return [s.strip() for s in suggestions if s.strip()]
188
+ logger.warning("Using fallback gift suggestions")
189
  return [
190
  "Hare Manavi! A peacock feather paintbrush for vibrant art!",
191
  "Hare Manavi! A lotus journal for serene thoughts!",
 
199
  "Hare Manavi! A flute pendant for spiritual melodies!"
200
  ]
201
 
202
+ @lru_cache(maxsize=10)
203
  def generate_horoscope():
204
  """Generate a daily horoscope for Manavi."""
205
  try:
 
230
  result = parse_huggingface_response(response)
231
  if result:
232
  return result
233
+ logger.warning("Using fallback horoscope")
234
  return "Hare Manavi! Today, the Yamuna inspires your art—paint with Vrindavan’s colors and let your spirit dance!"
235
  except Exception as e:
236
  logger.error(f"Error in generate_horoscope: {str(e)}")
 
252
  countdown=countdown_days)
253
  except Exception as e:
254
  logger.error(f"Error in / route: {str(e)}")
255
+ return render_template('error.html', error_message='Failed to load homepage. Please try again.'), 500
256
 
257
  @app.route('/chat', methods=['GET', 'POST'])
258
  def chat():
 
260
  try:
261
  if request.method == 'POST':
262
  if 'message' not in request.form:
263
+ logger.error("Missing 'message' in POST request")
264
  return jsonify({'error': 'Missing message parameter'}), 400
265
  user_input = escape(request.form['message'].strip())
266
  if not user_input:
267
+ logger.error("Empty message received")
268
  return jsonify({'error': 'Message cannot be empty'}), 400
269
  if len(user_input) > 500:
270
+ logger.error("Message too long")
271
  return jsonify({'error': 'Message too long (max 500 characters)'}), 400
272
  logger.info(f"Received chat input: {user_input}")
273
  reply = get_krishna_response(user_input)
 
275
  if firebase_enabled:
276
  try:
277
  save_chat_message(user_input, reply)
278
+ logger.info("Saved chat message to Firebase")
279
  except Exception as e:
280
  logger.error(f"Failed to save chat message: {str(e)}")
281
  return jsonify({'reply': reply})
 
288
  return render_template('chat.html', chat_history=chat_history)
289
  except Exception as e:
290
  logger.error(f"Error in /chat route: {str(e)}")
291
+ return render_template('error.html', error_message='Failed to load chat page. Please try again.'), 500
292
 
293
  @app.route('/adventure', methods=['GET', 'POST'])
294
  def adventure():
 
375
  result = parse_huggingface_response(response)
376
  story_text = result or scene['prompt'].split('Example: ')[1]
377
  else:
378
+ logger.error("Failed to generate adventure scene")
379
  story_text = scene['prompt'].split('Example: ')[1]
380
 
381
  next_scene = scene['next_scenes'].get(choice)
 
386
  return render_template('adventure.html')
387
  except Exception as e:
388
  logger.error(f"Error in /adventure route: {str(e)}")
389
+ return render_template('error.html', error_message='Failed to load adventure page. Please try again.'), 500
390
 
391
  @app.route('/message')
392
  def message():
 
404
  is_birthday=is_birthday)
405
  except Exception as e:
406
  logger.error(f"Error in /message route: {str(e)}")
407
+ return render_template('error.html', error_message='Failed to load birthday message page. Please try again.'), 500
408
 
409
  @app.route('/image', methods=['POST'])
410
  def image():
 
419
  return jsonify({'error': 'Failed to generate image'}), 500
420
  except Exception as e:
421
  logger.error(f"Error in /image route: {str(e)}")
422
+ return jsonify({'error': 'Internal Server Error. Please try again.'}), 500
423
 
424
  @app.route('/comic', methods=['GET'])
425
  def comic():
 
429
  return jsonify({'comic_images': comic_images})
430
  except Exception as e:
431
  logger.error(f"Error in /comic route: {str(e)}")
432
+ return jsonify({'error': 'Internal Server Error. Please try again.'}), 500
433
 
434
  @app.route('/story', methods=['POST'])
435
  def story():
 
461
  result = parse_huggingface_response(response)
462
  if result:
463
  return jsonify({'story': result})
464
+ logger.error("Failed to generate story")
465
  return jsonify({'story': f"Hare Manavi! I hid the gopis’ {theme} in a peacock’s nest—what a Vrindavan adventure!'"})
466
  except Exception as e:
467
  logger.error(f"Error in /story route: {str(e)}")
468
+ return jsonify({'error': 'Internal Server Error. Please try again.'}), 500
469
 
470
  @app.route('/story_audio', methods=['POST'])
471
  def story_audio():
 
490
  with open(audio_path, "wb") as f:
491
  f.write(response.content)
492
  return jsonify({'audio_url': f"/{audio_path}"})
493
+ logger.error("Failed to generate story audio")
494
  return jsonify({'error': 'Failed to generate audio'}), 500
495
  except Exception as e:
496
  logger.error(f"Error in /story_audio route: {str(e)}")
497
+ return jsonify({'error': 'Internal Server Error. Please try again.'}), 500
498
 
499
  @app.route('/riddle', methods=['GET'])
500
  def riddle():
 
525
  result = parse_huggingface_response(response)
526
  if result:
527
  return jsonify({'riddle': result})
528
+ logger.error("Failed to generate riddle")
529
  return jsonify({'riddle': "Hare Manavi! I play a tune that makes gopis dance—what am I? (Answer: Flute)"})
530
  except Exception as e:
531
  logger.error(f"Error in /riddle route: {str(e)}")
532
+ return jsonify({'error': 'Internal Server Error. Please try again.'}), 500
533
 
534
  @app.route('/countdown')
535
  def countdown():
 
539
  return jsonify({'days': days_left})
540
  except Exception as e:
541
  logger.error(f"Error in /countdown route: {str(e)}")
542
+ return jsonify({'error': 'Internal Server Error. Please try again.'}), 500
543
 
544
  if __name__ == '__main__':
545
  port = int(os.environ.get('PORT', 7860))