sreelekhaputta2 commited on
Commit
0281983
ยท
verified ยท
1 Parent(s): 3eee339

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -67
app.py CHANGED
@@ -12,71 +12,65 @@ import tempfile
12
  # Load Bhagavad Gita dataset
13
  df = pd.read_csv("bhagavad_gita.csv")
14
 
15
- # Load Sentence Transformer model and precompute embeddings
16
  model = SentenceTransformer("all-MiniLM-L6-v2")
17
  verse_embeddings = model.encode(df['meaning_in_english'].tolist(), convert_to_tensor=True)
18
 
19
- # Temp audio files directory
20
  TEMP_DIR = tempfile.mkdtemp()
21
 
22
- # Background music path
23
  bg_music_path = "krishna_bg_music.mp3"
24
 
 
 
 
 
 
 
25
 
26
- # -------------------- NEW & FIXED FUNCTIONS -------------------- #
27
-
28
- def clean_text(text):
29
- """Remove non-ASCII characters & extra spaces (fixes TTS crash)."""
30
  text = re.sub(r'[^\x00-\x7F]+', ' ', text)
31
  return ' '.join(text.split())
32
 
33
-
34
- async def generate_tts_async(text, voice="en-IN-PrabhatNeural"):
35
- """Generate TTS audio using Microsoft Edge Neural Voice."""
36
- filename = os.path.join(TEMP_DIR, f"krishna_voice_{uuid.uuid4()}.mp3")
37
-
38
  try:
39
- communicate = edge_tts.Communicate(text, voice)
40
  await communicate.save(filename)
41
- return filename
 
42
  except Exception as e:
43
- print("TTS Error:", e)
44
- return None
45
-
46
 
47
  def generate_tts(text):
48
- """Wrapper to run async TTS inside sync gradio fn."""
49
- text = clean_text(text)
50
-
51
  if not text.strip():
52
  return None
53
-
54
- loop = asyncio.new_event_loop()
55
- asyncio.set_event_loop(loop)
56
- return loop.run_until_complete(generate_tts_async(text))
57
-
58
-
59
- # --------------------------------------------------------------- #
60
-
61
- def shorten_explanation(text, max_sentences=2):
62
- sentences = text.split('. ')
63
- shortened = '. '.join(sentences[:max_sentences]).strip()
64
- if not shortened.endswith('.'):
65
- shortened += '.'
66
- return shortened
67
-
68
 
69
  def get_unique_bgm():
 
70
  if not os.path.exists(bg_music_path):
71
  return None
72
  unique_bgm_path = os.path.join(TEMP_DIR, f"bgm_{uuid.uuid4()}.mp3")
73
- shutil.copy(bg_music_path, unique_bgm_path)
74
- return unique_bgm_path
75
-
 
 
 
76
 
77
  def versewise_bot(question, play_music):
 
78
  if not question.strip():
79
- return "Please ask something meaningful.", None, None
80
 
81
  query_embedding = model.encode(question, convert_to_tensor=True)
82
  similarity_scores = util.pytorch_cos_sim(query_embedding, verse_embeddings)[0]
@@ -88,65 +82,71 @@ def versewise_bot(question, play_music):
88
  explanation = shorten_explanation(verse['meaning_in_english'])
89
  verse_number = verse['verse_number']
90
 
91
- formatted_reply = f"""
92
- ๐Ÿ“ฟ **Bhagavad Gita {verse_number}**
93
 
94
- ๐Ÿ•‰ *"{translation}"*
95
 
96
- โœจ {explanation}
97
 
98
- ๐ŸŒผ Remember: Krishna is walking with you.
99
- """
100
-
101
- # TEXT SENT TO TTS BASED ON YOUR NEW REQUIREMENT (NATURAL VOICE)
102
- voice_text = f"{translation}. {explanation}"
103
 
104
- audio_voice = generate_tts(voice_text)
105
- audio_bgm = get_unique_bgm() if play_music else None
106
 
107
- return formatted_reply, audio_voice, audio_bgm
 
 
108
 
 
109
 
110
  def get_quote_of_the_day():
111
  verse = df.sample(1).iloc[0]
112
- return f"""
113
- <b>Quote of the Day (Gita {verse['verse_number']}):</b><br>
114
- <i>{verse['translation_in_english']}</i>
115
- """
116
-
 
 
117
 
118
- # Custom Styling
119
  custom_css = """
120
  body, .gradio-container, .gradio-interface, html {
121
  background-image: url('https://static.vecteezy.com/system/resources/previews/022/592/272/large_2x/image-of-divine-beautiful-closed-eyes-blue-colored-krishna-generative-ai-free-photo.jpeg') !important;
122
- background-size: cover;
 
 
 
123
  }
124
- .gradio-container {
125
- background-color: rgba(255,255,255,0.90) !important;
126
  border-radius: 18px;
127
  padding: 25px;
 
 
 
128
  }
129
  """
130
 
131
- # Gradio UI
132
  interface = gr.Interface(
133
  fn=versewise_bot,
134
  inputs=[
135
- gr.Textbox(label="Ask Krishna", placeholder="Why am I struggling?", lines=2),
136
  gr.Checkbox(label="Play Background Music", value=True)
137
  ],
138
  outputs=[
139
- gr.Textbox(label="๐Ÿง˜ Krishna's Answer"),
140
  gr.Audio(label="๐Ÿ”Š Krishnaโ€™s Voice", type="filepath"),
141
- gr.Audio(label="๐ŸŽถ Music", autoplay=True, type="filepath")
142
  ],
143
- title="๐Ÿ•‰ VerseWise - Divine Guidance from Bhagavad Gita",
144
- description="Ask any question and receive a verse from the Bhagavad Gita.",
145
  article=get_quote_of_the_day(),
146
  flagging_mode="never",
 
147
  css=custom_css
148
  )
149
 
150
  if __name__ == "__main__":
151
- print(f"Temp folder created: {TEMP_DIR}")
152
  interface.launch()
 
12
  # Load Bhagavad Gita dataset
13
  df = pd.read_csv("bhagavad_gita.csv")
14
 
15
+ # Load sentence transformer and precompute embeddings
16
  model = SentenceTransformer("all-MiniLM-L6-v2")
17
  verse_embeddings = model.encode(df['meaning_in_english'].tolist(), convert_to_tensor=True)
18
 
19
+ # Temp folder for audio files
20
  TEMP_DIR = tempfile.mkdtemp()
21
 
22
+ # Background music file path
23
  bg_music_path = "krishna_bg_music.mp3"
24
 
25
+ def shorten_explanation(text, max_sentences=2):
26
+ sentences = text.split('. ')
27
+ shortened = '. '.join(sentences[:max_sentences]).strip()
28
+ if not shortened.endswith('.'):
29
+ shortened += '.'
30
+ return shortened
31
 
32
+ def clean_english(text):
 
 
 
33
  text = re.sub(r'[^\x00-\x7F]+', ' ', text)
34
  return ' '.join(text.split())
35
 
36
+ async def tts_generate_async(text, voice="en-IN-PrabhatNeural"):
37
+ """Generate audio asynchronously using edge-tts with Krishna male voice."""
38
+ filename = os.path.join(TEMP_DIR, f"voice_{uuid.uuid4()}.mp3")
 
 
39
  try:
40
+ communicate = edge_tts.Communicate(text, voice=voice)
41
  await communicate.save(filename)
42
+ if os.path.exists(filename) and os.path.getsize(filename) > 1000:
43
+ return filename
44
  except Exception as e:
45
+ print(f"TTS Error: {e}")
46
+ return None
 
47
 
48
  def generate_tts(text):
49
+ """Synchronous wrapper for async TTS generation."""
 
 
50
  if not text.strip():
51
  return None
52
+ try:
53
+ return asyncio.run(tts_generate_async(clean_english(text)))
54
+ except Exception as e:
55
+ print(f"TTS Generation failed: {e}")
56
+ return None
 
 
 
 
 
 
 
 
 
 
57
 
58
  def get_unique_bgm():
59
+ """Return unique copy of background music (optional)."""
60
  if not os.path.exists(bg_music_path):
61
  return None
62
  unique_bgm_path = os.path.join(TEMP_DIR, f"bgm_{uuid.uuid4()}.mp3")
63
+ try:
64
+ shutil.copy(bg_music_path, unique_bgm_path)
65
+ return unique_bgm_path
66
+ except Exception as e:
67
+ print(f"BGM Error: {e}")
68
+ return None
69
 
70
  def versewise_bot(question, play_music):
71
+ """Main chatbot logic: find the most similar verse and return the answer."""
72
  if not question.strip():
73
+ return "Please ask a valid question.", None, None
74
 
75
  query_embedding = model.encode(question, convert_to_tensor=True)
76
  similarity_scores = util.pytorch_cos_sim(query_embedding, verse_embeddings)[0]
 
82
  explanation = shorten_explanation(verse['meaning_in_english'])
83
  verse_number = verse['verse_number']
84
 
85
+ reply = f"""๐Ÿ“– Bhagavad Gita {verse_number}
 
86
 
87
+ ๐Ÿ•‰ "[translate:{sanskrit[:60]}...]"
88
 
89
+ "{translation}"
90
 
91
+ ๐Ÿ•Š {explanation}
 
 
 
 
92
 
93
+ ๐ŸŒผ Stay strong โ€” Krishna walks with you."""
 
94
 
95
+ voice_text = f"{translation}. {explanation}"
96
+ audio_path = generate_tts(voice_text)
97
+ music_path = get_unique_bgm() if play_music else None
98
 
99
+ return reply, audio_path, music_path
100
 
101
  def get_quote_of_the_day():
102
  verse = df.sample(1).iloc[0]
103
+ sanskrit = verse['verse_in_sanskrit']
104
+ translation = verse['translation_in_english']
105
+ verse_number = verse['verse_number']
106
+ return f"""<div style="font-size:1.1em;padding:10px 0;">
107
+ <b>Quote of the Day (Gita {verse_number}):</b><br>
108
+ <i>[translate:{sanskrit[:60]}...]</i><br>
109
+ <span style="color:#2d2d2d;">"{translation}"</span></div>"""
110
 
111
+ # Custom UI theme styling
112
  custom_css = """
113
  body, .gradio-container, .gradio-interface, html {
114
  background-image: url('https://static.vecteezy.com/system/resources/previews/022/592/272/large_2x/image-of-divine-beautiful-closed-eyes-blue-colored-krishna-generative-ai-free-photo.jpeg') !important;
115
+ background-size: cover !important;
116
+ background-repeat: no-repeat !important;
117
+ background-position: center center !important;
118
+ background-attachment: fixed !important;
119
  }
120
+ .gradio-container, .gradio-interface {
121
+ background-color: rgba(255,255,255,0.92) !important;
122
  border-radius: 18px;
123
  padding: 25px;
124
+ max-width: 760px;
125
+ box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
126
+ margin: auto;
127
  }
128
  """
129
 
130
+ # Gradio interface without voice toggle; Krishna's male voice fixed
131
  interface = gr.Interface(
132
  fn=versewise_bot,
133
  inputs=[
134
+ gr.Textbox(label="Ask Krishna", placeholder="Why am I struggling in life?", lines=2),
135
  gr.Checkbox(label="Play Background Music", value=True)
136
  ],
137
  outputs=[
138
+ gr.Textbox(label="๐Ÿง˜โ€โ™‚ Krishna's Answer"),
139
  gr.Audio(label="๐Ÿ”Š Krishnaโ€™s Voice", type="filepath"),
140
+ gr.Audio(label="๐ŸŽถ Background Music", autoplay=True, type="filepath")
141
  ],
142
+ title="๐Ÿ•‰ VerseWise - Divine Wisdom from the Gita",
143
+ description="Ask any question, and receive a verse from the Bhagavad Gita with divine guidance.",
144
  article=get_quote_of_the_day(),
145
  flagging_mode="never",
146
+ theme="soft",
147
  css=custom_css
148
  )
149
 
150
  if __name__ == "__main__":
151
+ print(f"Temp directory for audio files: {TEMP_DIR}")
152
  interface.launch()