sreelekhaputta2 commited on
Commit
3324696
Β·
verified Β·
1 Parent(s): 4ffebc4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -30
app.py CHANGED
@@ -3,24 +3,24 @@ import pandas as pd
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()
@@ -28,43 +28,30 @@ def shorten_explanation(text, max_sentences=2):
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)
@@ -73,7 +60,8 @@ def get_unique_bgm():
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
 
@@ -98,11 +86,13 @@ def versewise_bot(question, play_music, use_krishna_voice):
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']
@@ -112,9 +102,10 @@ def get_quote_of_the_day():
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;
@@ -134,12 +125,11 @@ 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",
@@ -153,3 +143,4 @@ interface = gr.Interface(
153
  if __name__ == "__main__":
154
  print(f"Temp directory for audio: {TEMP_DIR}")
155
  interface.launch()
 
 
3
  import uuid
4
  import shutil
5
  import re
6
+ from gtts import gTTS
7
  from sentence_transformers import SentenceTransformer, util
8
  import os
9
  import tempfile
 
 
10
 
11
  # Load Bhagavad Gita dataset
12
  df = pd.read_csv("bhagavad_gita.csv")
13
 
14
+ # Load sentence transformer model (semantic search)
15
  model = SentenceTransformer("all-MiniLM-L6-v2")
16
  verse_embeddings = model.encode(df['meaning_in_english'].tolist(), convert_to_tensor=True)
17
 
18
  bg_music_path = "krishna_bg_music.mp3"
19
 
20
+ # Temporary directory for generated audio
21
  TEMP_DIR = tempfile.mkdtemp()
22
 
23
+
24
  def shorten_explanation(text, max_sentences=2):
25
  sentences = text.split('. ')
26
  shortened = '. '.join(sentences[:max_sentences]).strip()
 
28
  shortened += '.'
29
  return shortened
30
 
31
+
32
  def clean_english(text):
33
  text = re.sub(r'[^\x00-\x7F]+', ' ', text)
34
  text = ' '.join(text.split())
35
  return text
36
 
37
+
38
+ def generate_voice(text):
39
+ """Generate offline TTS using gTTS."""
40
  if not text.strip():
41
  return None
 
42
  filename = os.path.join(TEMP_DIR, f"voice_{uuid.uuid4()}.mp3")
 
43
  try:
44
+ tts = gTTS(text=text, lang="en", tld="com")
45
+ tts.save(filename)
 
 
 
 
 
46
  return filename
47
  except Exception as e:
48
+ print(f"Voice generation failed: {e}")
49
  return None
50
 
 
 
 
 
 
 
 
51
 
52
  def get_unique_bgm():
53
  if not os.path.exists(bg_music_path):
54
  return None
 
55
  unique_path = os.path.join(TEMP_DIR, f"bgm_{uuid.uuid4()}.mp3")
56
  try:
57
  shutil.copy(bg_music_path, unique_path)
 
60
  print(f"BGM Error: {e}")
61
  return None
62
 
63
+
64
+ def versewise_bot(question, play_music):
65
  if not question.strip():
66
  return "Please ask a valid question.", None, None
67
 
 
86
  🌼 Stay strong β€” Krishna walks with you."""
87
 
88
  voice_text = clean_english(f"{translation}. {explanation}")
89
+ audio_path = generate_voice(voice_text)
90
+
91
  music = get_unique_bgm() if play_music else None
92
 
93
  return reply, audio_path, music
94
 
95
+
96
  def get_quote_of_the_day():
97
  verse = df.sample(1).iloc[0]
98
  sanskrit = verse['verse_in_sanskrit']
 
102
  <i>[translate:{sanskrit[:60]}...]</i><br>
103
  <span style="color:#2d2d2d;">"{translation}"</span></div>"""
104
 
105
+
106
  custom_css = """
107
  body, .gradio-container, .gradio-interface, html {
108
+ background-image: url('https://static.vecteezy.com/system/resources/previews/022/592/272/large_2x/image-of-divine-...' ) !important;
109
  background-size: cover !important;
110
  background-repeat: no-repeat !important;
111
  background-position: center center !important;
 
125
  fn=versewise_bot,
126
  inputs=[
127
  gr.Textbox(label="Ask Krishna", placeholder="Why am I struggling in life?", lines=2),
128
+ gr.Checkbox(label="Play Background Music", value=True)
 
129
  ],
130
  outputs=[
131
  gr.Textbox(label="πŸ§˜β€β™‚ Krishna's Answer"),
132
+ gr.Audio(label="πŸ”Š Krishna Speaks", type="filepath"),
133
  gr.Audio(label="🎢 Background Music", autoplay=True, type="filepath")
134
  ],
135
  title="πŸ•‰ VerseWise - Divine Wisdom from the Gita",
 
143
  if __name__ == "__main__":
144
  print(f"Temp directory for audio: {TEMP_DIR}")
145
  interface.launch()
146
+