Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
| 16 |
model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 17 |
-
verse_embeddings = model.encode(df[
|
| 18 |
|
| 19 |
bg_music_path = "krishna_bg_music.mp3"
|
|
|
|
|
|
|
| 20 |
TEMP_DIR = tempfile.mkdtemp()
|
| 21 |
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
def clean_english(text):
|
| 24 |
-
text = re.sub(r
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
await communicate.save(filename)
|
| 33 |
-
return filename
|
| 34 |
except Exception as e:
|
| 35 |
-
print("TTS
|
| 36 |
return None
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
voice = "en-IN-PrabhatNeural" if use_krishna_voice else "en-US-GuyNeural"
|
| 41 |
try:
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
loop.
|
| 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 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
| 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
|
| 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[
|
| 74 |
-
translation = verse[
|
| 75 |
-
explanation = shorten_explanation(verse[
|
| 76 |
-
verse_number = verse[
|
| 77 |
|
| 78 |
-
reply = f"""
|
| 79 |
-
π Bhagavad Gita β {verse_number}
|
| 80 |
|
| 81 |
-
π
|
| 82 |
-
[translate:{sanskrit[:60]}...]
|
| 83 |
|
| 84 |
"{translation}"
|
| 85 |
|
| 86 |
π {explanation}
|
| 87 |
|
| 88 |
-
πΌ
|
| 89 |
-
"""
|
| 90 |
|
| 91 |
-
|
| 92 |
-
audio_path =
|
| 93 |
-
|
| 94 |
|
| 95 |
-
return reply, audio_path,
|
| 96 |
|
| 97 |
-
# Quote of the day
|
| 98 |
def get_quote_of_the_day():
|
| 99 |
verse = df.sample(1).iloc[0]
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
"{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 (
|
| 113 |
],
|
| 114 |
outputs=[
|
| 115 |
-
gr.Textbox(label="π§ Krishna
|
| 116 |
-
gr.Audio(label="π Krishna
|
| 117 |
-
gr.Audio(label="πΆ Background Music", autoplay=True, type="filepath")
|
| 118 |
],
|
| 119 |
-
title="π VerseWise
|
| 120 |
-
description="Ask
|
| 121 |
article=get_quote_of_the_day(),
|
| 122 |
flagging_mode="never",
|
|
|
|
|
|
|
| 123 |
)
|
| 124 |
|
| 125 |
if __name__ == "__main__":
|
| 126 |
-
print(f"
|
| 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()
|