sreelekhaputta2 commited on
Commit
2f4bc0f
Β·
verified Β·
1 Parent(s): 9facd36

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -59
app.py CHANGED
@@ -3,125 +3,153 @@ import pandas as pd
3
  import uuid
4
  import shutil
5
  import re
6
- import asyncio
7
- import edge_tts
8
  from sentence_transformers import SentenceTransformer, util
9
  import os
10
  import tempfile
 
 
11
 
12
  # Load Bhagavad Gita dataset
13
  df = pd.read_csv("bhagavad_gita.csv")
14
 
15
- # Load SentenceTransformer model & 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
  bg_music_path = "krishna_bg_music.mp3"
 
 
20
  TEMP_DIR = tempfile.mkdtemp()
21
 
22
- # βœ… Clean unwanted characters
 
 
 
 
 
 
23
  def clean_english(text):
24
- text = re.sub(r"[^\x00-\x7F]+", " ", text)
25
- return " ".join(text.split())
 
 
 
 
 
 
26
 
27
- # βœ… Microsoft TTS async function
28
- async def generate_voice_async(text, voice="en-IN-PrabhatNeural"):
29
  filename = os.path.join(TEMP_DIR, f"voice_{uuid.uuid4()}.mp3")
 
30
  try:
31
- communicate = edge_tts.Communicate(text, voice=voice)
 
 
 
 
 
32
  await communicate.save(filename)
33
- return filename if os.path.exists(filename) else None
34
  except Exception as e:
35
- print("TTS Error:", e)
36
  return None
37
 
38
- # βœ… Wrapper for sync Gradio compatibility
39
- def generate_voice(text, use_krishna_voice):
40
- voice = "en-IN-PrabhatNeural" if use_krishna_voice else "en-US-GuyNeural"
41
  try:
42
- loop = asyncio.new_event_loop()
43
- asyncio.set_event_loop(loop)
44
- result = loop.run_until_complete(generate_voice_async(text, voice))
45
- loop.close()
46
- return result
47
- except:
48
- return None
49
 
50
- # βœ… Select background music
51
  def get_unique_bgm():
52
  if not os.path.exists(bg_music_path):
53
  return None
54
- path = os.path.join(TEMP_DIR, f"bgm_{uuid.uuid4()}.mp3")
55
- shutil.copy(bg_music_path, path)
56
- return path
57
 
58
- def shorten_explanation(text, max_sentences=2):
59
- parts = text.split(". ")
60
- shortened = ". ".join(parts[:max_sentences]).strip()
61
- return shortened + "." if not shortened.endswith(".") else shortened
 
 
 
62
 
63
- # βœ… Main bot logic
64
  def versewise_bot(question, play_music, use_krishna_voice):
65
  if not question.strip():
66
- return "Please ask a meaningful question.", None, None
67
 
68
  query_embedding = model.encode(question, convert_to_tensor=True)
69
  similarity_scores = util.pytorch_cos_sim(query_embedding, verse_embeddings)[0]
70
  idx = similarity_scores.argmax().item()
71
  verse = df.iloc[idx]
72
 
73
- sanskrit = verse["verse_in_sanskrit"]
74
- translation = verse["translation_in_english"]
75
- explanation = shorten_explanation(verse["meaning_in_english"])
76
- verse_number = verse["verse_number"]
77
 
78
- reply = f"""
79
- πŸ“– Bhagavad Gita β€” {verse_number}
80
 
81
- πŸ•‰ Sanskrit:
82
- [translate:{sanskrit[:60]}...]
83
 
84
  "{translation}"
85
 
86
  πŸ•Š {explanation}
87
 
88
- 🌼 Trust the process β€” Krishna walks with you.
89
- """
90
 
91
- tts_text = clean_english(f"{translation}. {explanation}")
92
- audio_path = generate_voice(tts_text, use_krishna_voice)
93
- bgm = get_unique_bgm() if play_music else None
94
 
95
- return reply, audio_path, bgm
96
 
97
- # Quote of the day
98
  def get_quote_of_the_day():
99
  verse = df.sample(1).iloc[0]
100
- return f"""
101
- <b>Quote of the Day β€” Gita {verse['verse_number']}</b><br>
102
- <i>[translate:{verse['verse_in_sanskrit'][:60]}...]</i><br>
103
- "{verse['translation_in_english']}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  """
105
 
106
- # βœ… Gradio UI
107
  interface = gr.Interface(
108
  fn=versewise_bot,
109
  inputs=[
110
  gr.Textbox(label="Ask Krishna", placeholder="Why am I struggling in life?", lines=2),
111
  gr.Checkbox(label="Play Background Music", value=True),
112
- gr.Checkbox(label="Use Krishna's Voice (PrabhatNeural)", value=True),
113
  ],
114
  outputs=[
115
- gr.Textbox(label="🧘 Krishna’s Answer"),
116
- gr.Audio(label="πŸ”Š Krishna Speaks", type="filepath"),
117
- gr.Audio(label="🎢 Background Music", autoplay=True, type="filepath"),
118
  ],
119
- title="πŸ•‰ VerseWise β€” Direct Wisdom from the Gita",
120
- description="Ask a question, receive Krishna’s answer via Bhagavad Gita.",
121
  article=get_quote_of_the_day(),
122
  flagging_mode="never",
 
 
123
  )
124
 
125
  if __name__ == "__main__":
126
- print(f"TTS temp directory: {TEMP_DIR}")
127
  interface.launch()
 
3
  import uuid
4
  import shutil
5
  import re
 
 
6
  from sentence_transformers import SentenceTransformer, util
7
  import os
8
  import tempfile
9
+ import asyncio
10
+ import edge_tts
11
 
12
  # Load Bhagavad Gita dataset
13
  df = pd.read_csv("bhagavad_gita.csv")
14
 
15
+ # Load sentence transformer model and precompute embeddings (once)
16
  model = SentenceTransformer("all-MiniLM-L6-v2")
17
+ verse_embeddings = model.encode(df['meaning_in_english'].tolist(), convert_to_tensor=True)
18
 
19
  bg_music_path = "krishna_bg_music.mp3"
20
+
21
+ # Create temp directory for audio files
22
  TEMP_DIR = tempfile.mkdtemp()
23
 
24
+ def shorten_explanation(text, max_sentences=2):
25
+ sentences = text.split('. ')
26
+ shortened = '. '.join(sentences[:max_sentences]).strip()
27
+ if not shortened.endswith('.'):
28
+ shortened += '.'
29
+ return shortened
30
+
31
  def clean_english(text):
32
+ text = re.sub(r'[^\x00-\x7F]+', ' ', text)
33
+ text = ' '.join(text.split())
34
+ return text
35
+
36
+ async def generate_voice_edge_tts_async(text, use_krishna_voice):
37
+ """Generate speech using Edge TTS with en-IN-PrabhatNeural."""
38
+ if not text.strip():
39
+ return None
40
 
 
 
41
  filename = os.path.join(TEMP_DIR, f"voice_{uuid.uuid4()}.mp3")
42
+
43
  try:
44
+ communicate = edge_tts.Communicate(
45
+ text=text,
46
+ voice="en-IN-PrabhatNeural",
47
+ rate="-2%",
48
+ volume="+0%"
49
+ )
50
  await communicate.save(filename)
51
+ return filename
52
  except Exception as e:
53
+ print(f"Edge TTS ERROR: {e}")
54
  return None
55
 
56
+ def generate_voice_edge_tts(text, use_krishna_voice):
57
+ """Wrapper to run the async Edge TTS speech synthesis synchronously."""
 
58
  try:
59
+ return asyncio.run(generate_voice_edge_tts_async(text, use_krishna_voice))
60
+ except RuntimeError:
61
+ loop = asyncio.get_event_loop()
62
+ return loop.run_until_complete(generate_voice_edge_tts_async(text, use_krishna_voice))
 
 
 
63
 
 
64
  def get_unique_bgm():
65
  if not os.path.exists(bg_music_path):
66
  return None
 
 
 
67
 
68
+ unique_path = os.path.join(TEMP_DIR, f"bgm_{uuid.uuid4()}.mp3")
69
+ try:
70
+ shutil.copy(bg_music_path, unique_path)
71
+ return unique_path
72
+ except Exception as e:
73
+ print(f"BGM Error: {e}")
74
+ return None
75
 
 
76
  def versewise_bot(question, play_music, use_krishna_voice):
77
  if not question.strip():
78
+ return "Please ask a valid question.", None, None
79
 
80
  query_embedding = model.encode(question, convert_to_tensor=True)
81
  similarity_scores = util.pytorch_cos_sim(query_embedding, verse_embeddings)[0]
82
  idx = similarity_scores.argmax().item()
83
  verse = df.iloc[idx]
84
 
85
+ sanskrit = verse['verse_in_sanskrit']
86
+ translation = verse['translation_in_english']
87
+ explanation = shorten_explanation(verse['meaning_in_english'])
88
+ verse_number = verse['verse_number']
89
 
90
+ reply = f"""πŸ“– Bhagavad Gita {verse_number}
 
91
 
92
+ πŸ•‰ "[translate:{sanskrit[:60]}...]"
 
93
 
94
  "{translation}"
95
 
96
  πŸ•Š {explanation}
97
 
98
+ 🌼 Stay strong β€” Krishna walks with you."""
 
99
 
100
+ voice_text = clean_english(f"{translation}. {explanation}")
101
+ audio_path = generate_voice_edge_tts(voice_text, use_krishna_voice)
102
+ music = get_unique_bgm() if play_music else None
103
 
104
+ return reply, audio_path, music
105
 
 
106
  def get_quote_of_the_day():
107
  verse = df.sample(1).iloc[0]
108
+ sanskrit = verse['verse_in_sanskrit']
109
+ translation = verse['translation_in_english']
110
+ verse_number = verse['verse_number']
111
+ return f"""<div style="font-size:1.1em;padding:10px 0;"><b>Quote of the Day (Gita {verse_number}):</b><br>
112
+ <i>[translate:{sanskrit[:60]}...]</i><br>
113
+ <span style="color:#2d2d2d;">"{translation}"</span></div>"""
114
+
115
+ custom_css = """
116
+ body, .gradio-container, .gradio-interface, html {
117
+ 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;
118
+ background-size: cover !important;
119
+ background-repeat: no-repeat !important;
120
+ background-position: center center !important;
121
+ background-attachment: fixed !important;
122
+ }
123
+ .gradio-container, .gradio-interface {
124
+ background-color: rgba(255,255,255,0.92) !important;
125
+ border-radius: 18px;
126
+ padding: 25px;
127
+ max-width: 760px;
128
+ box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
129
+ margin: auto;
130
+ }
131
  """
132
 
 
133
  interface = gr.Interface(
134
  fn=versewise_bot,
135
  inputs=[
136
  gr.Textbox(label="Ask Krishna", placeholder="Why am I struggling in life?", lines=2),
137
  gr.Checkbox(label="Play Background Music", value=True),
138
+ gr.Checkbox(label="Use Krishna's Voice (Male Voice)", value=True)
139
  ],
140
  outputs=[
141
+ gr.Textbox(label="πŸ§˜β€β™‚ Krishna's Answer"),
142
+ gr.Audio(label="πŸ”Š Listen to Krishna's Voice", type="filepath"),
143
+ gr.Audio(label="🎢 Background Music", autoplay=True, type="filepath")
144
  ],
145
+ title="πŸ•‰ VerseWise - Divine Wisdom from the Gita",
146
+ description="Ask any question, and receive a Gita verse with Krishna's loving wisdom.",
147
  article=get_quote_of_the_day(),
148
  flagging_mode="never",
149
+ theme="soft",
150
+ css=custom_css
151
  )
152
 
153
  if __name__ == "__main__":
154
+ print(f"Temp directory for audio: {TEMP_DIR}")
155
  interface.launch()