sreelekhaputta2 commited on
Commit
c3957e7
Β·
verified Β·
1 Parent(s): 934f0cb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -68
app.py CHANGED
@@ -1,3 +1,5 @@
 
 
1
  import gradio as gr
2
  import pandas as pd
3
  import uuid
@@ -6,72 +8,39 @@ 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 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]
77
  idx = similarity_scores.argmax().item()
@@ -84,7 +53,7 @@ def versewise_bot(question, play_music):
84
 
85
  reply = f"""πŸ“– Bhagavad Gita {verse_number}
86
 
87
- πŸ•‰ "[translate:{sanskrit[:60]}...]"
88
 
89
  "{translation}"
90
 
@@ -92,23 +61,21 @@ def versewise_bot(question, play_music):
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;
@@ -125,9 +92,17 @@ body, .gradio-container, .gradio-interface, html {
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=[
@@ -136,17 +111,15 @@ interface = gr.Interface(
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()
 
1
+ # app.py
2
+
3
  import gradio as gr
4
  import pandas as pd
5
  import uuid
 
8
  import asyncio
9
  import edge_tts
10
  from sentence_transformers import SentenceTransformer, util
 
 
11
 
12
+ # Load Gita dataset
13
  df = pd.read_csv("bhagavad_gita.csv")
14
 
15
+ # Load model
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
  def shorten_explanation(text, max_sentences=2):
22
+ return '. '.join(text.split('. ')[:max_sentences]).strip() + "."
 
 
 
 
23
 
24
  def clean_english(text):
25
+ return re.sub(r'[^\x00-\x7F]+', ' ', text)
26
+
27
+ # Async wrapper for TTS
28
+ async def generate_voice_async(text):
29
+ voice = "en-IN-PrabhatNeural"
30
+ filename = f"voice_{uuid.uuid4()}.mp3"
31
+ communicate = edge_tts.Communicate(text, voice=voice)
32
+ await communicate.save(filename)
33
+ return filename
34
+
35
+ def generate_voice(text):
36
+ return asyncio.run(generate_voice_async(text))
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  def get_unique_bgm():
39
+ unique_path = f"bgm_{uuid.uuid4()}.mp3"
40
+ shutil.copy(bg_music_path, unique_path)
41
+ return unique_path
 
 
 
 
 
 
 
42
 
43
  def versewise_bot(question, play_music):
 
 
 
 
44
  query_embedding = model.encode(question, convert_to_tensor=True)
45
  similarity_scores = util.pytorch_cos_sim(query_embedding, verse_embeddings)[0]
46
  idx = similarity_scores.argmax().item()
 
53
 
54
  reply = f"""πŸ“– Bhagavad Gita {verse_number}
55
 
56
+ πŸ•‰ "{sanskrit[:60]}..."
57
 
58
  "{translation}"
59
 
 
61
 
62
  🌼 Stay strong β€” Krishna walks with you."""
63
 
64
+ voice_text = f"{clean_english(translation)}. {clean_english(explanation)}"
65
+ audio_path = generate_voice(voice_text)
66
+ music = get_unique_bgm() if play_music else None
67
 
68
+ return reply, audio_path, music
69
 
70
  def get_quote_of_the_day():
71
  verse = df.sample(1).iloc[0]
72
  sanskrit = verse['verse_in_sanskrit']
73
  translation = verse['translation_in_english']
74
  verse_number = verse['verse_number']
75
+ return f"""<div style="font-size:1.1em;padding:10px 0;"><b>Quote of the Day (Gita {verse_number}):</b><br>
76
+ <i>{sanskrit[:60]}...</i><br>
 
77
  <span style="color:#2d2d2d;">"{translation}"</span></div>"""
78
 
 
79
  custom_css = """
80
  body, .gradio-container, .gradio-interface, html {
81
  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;
 
92
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
93
  margin: auto;
94
  }
95
+ @media only screen and (max-width: 768px) {
96
+ .gradio-container {
97
+ width: 95% !important;
98
+ padding: 15px !important;
99
+ }
100
+ }
101
+ input[type="text"], textarea {
102
+ font-size: 16px !important;
103
+ }
104
  """
105
 
 
106
  interface = gr.Interface(
107
  fn=versewise_bot,
108
  inputs=[
 
111
  ],
112
  outputs=[
113
  gr.Textbox(label="πŸ§˜β€β™‚ Krishna's Answer"),
114
+ gr.Audio(label="πŸ”Š Listen to Krishna's Voice"),
115
+ gr.Audio(label="🎢 Background Music", autoplay=True)
116
  ],
117
  title="πŸ•‰ VerseWise - Divine Wisdom from the Gita",
118
+ description="Ask any question, and receive a Gita verse with Krishna’s loving wisdom.",
119
  article=get_quote_of_the_day(),
120
+ allow_flagging="never",
121
  theme="soft",
122
  css=custom_css
123
  )
124
 
125
+ interface.launch()