Spaces:
Running
Running
File size: 4,920 Bytes
5532e3f e53b55a 0d5234c e53b55a 0d5234c e53b55a 0d5234c e53b55a 2f4bc0f e53b55a df6393c 0d5234c df6393c 321dd10 3324696 0281983 0d5234c 2f4bc0f 0d5234c c3957e7 0d5234c c3957e7 0d5234c e53b55a 0d5234c 1023f9b 321dd10 0d5234c e53b55a 2f4bc0f e53b55a df6393c 2ab8b76 302c577 0d5234c 302c577 0d5234c 2ab8b76 302c577 0d5234c 3324696 e53b55a 0281983 302c577 2f4bc0f 3f9a318 0281983 2f4bc0f 0281983 2f4bc0f 0281983 2f4bc0f df6393c 5532e3f e53b55a 0281983 321dd10 e53b55a 0281983 302c577 0d5234c df6393c e53b55a 0281983 0d5234c e53b55a 0d5234c 0281983 2f4bc0f e53b55a 0d5234c 302c577 88f183f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | import gradio as gr
import pandas as pd
import uuid
import shutil
import re
import os
import tempfile
from sentence_transformers import SentenceTransformer, util
# Load Bhagavad Gita dataset
df = pd.read_csv("bhagavad_gita.csv")
# Load sentence transformer and precompute embeddings
model = SentenceTransformer("all-MiniLM-L6-v2")
verse_embeddings = model.encode(df['meaning_in_english'].tolist(), convert_to_tensor=True)
# Temporary directory for audio and downloads
TEMP_DIR = tempfile.mkdtemp()
# Background music file path
bg_music_path = "krishna_bg_music.mp3"
def shorten_explanation(text, max_sentences=2):
sentences = text.split('. ')
shortened = '. '.join(sentences[:max_sentences]).strip()
if not shortened.endswith('.'):
shortened += '.'
return shortened
def create_downloadable_text(question, verse_number, sanskrit, translation, explanation):
assurance = "πΌ Remember, Krishna always walks with you, guiding and protecting."
content = f"""Your Question:
{question}
π Bhagavad Gita Verse {verse_number}:
[translate:{sanskrit}]
Translation:
{translation}
Explanation:
{explanation}
{assurance}
"""
filename = os.path.join(TEMP_DIR, f"gita_response_{uuid.uuid4()}.txt")
with open(filename, 'w', encoding='utf-8') as f:
f.write(content)
return filename
def versewise_bot(question, play_music):
if not question.strip():
return "Please ask a valid question.", None, None, None
query_embedding = model.encode(question, convert_to_tensor=True)
similarity_scores = util.pytorch_cos_sim(query_embedding, verse_embeddings)[0]
idx = similarity_scores.argmax().item()
verse = df.iloc[idx]
sanskrit = verse['verse_in_sanskrit']
translation = verse['translation_in_english']
explanation = shorten_explanation(verse['meaning_in_english'])
verse_number = verse['verse_number']
reply = (
f"π Bhagavad Gita {verse_number}\n\n"
f"π \"[translate:{sanskrit[:60]}...]\"\n\n"
f"\"{translation}\"\n\n"
f"π {explanation}\n\n"
"πΌ Stay strong β Krishna walks with you."
)
# Play background music only if toggled and file exists
music_path = None
if play_music and os.path.exists(bg_music_path):
unique_bgm_path = os.path.join(TEMP_DIR, f"bgm_{uuid.uuid4()}.mp3")
try:
shutil.copy(bg_music_path, unique_bgm_path)
music_path = unique_bgm_path
except Exception as e:
print(f"BGM copy error: {e}")
download_file = create_downloadable_text(question, verse_number, sanskrit, translation, explanation)
# No Krishna voice, so audio output set to None
return reply, None, music_path, download_file
def get_quote_of_the_day():
verse = df.sample(1).iloc[0]
sanskrit = verse['verse_in_sanskrit']
translation = verse['translation_in_english']
verse_number = verse['verse_number']
return f"""<div style="font-size:1.1em;padding:10px 0;">
<b>Quote of the Day (Gita {verse_number}):</b><br>
<i>[translate:{sanskrit[:60]}...]</i><br>
<span style="color:#2d2d2d;">"{translation}"</span></div>"""
custom_css = """
body, .gradio-container, .gradio-interface, html {
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;
background-size: cover !important;
background-repeat: no-repeat !important;
background-position: center center !important;
background-attachment: fixed !important;
}
.gradio-container, .gradio-interface {
background-color: rgba(255,255,255,0.92) !important;
border-radius: 18px;
padding: 25px;
max-width: 760px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
margin: auto;
}
@media only screen and (max-width: 768px) {
.gradio-container {
width: 95% !important;
padding: 15px !important;
}
}
input[type="text"], textarea {
font-size: 16px !important;
}
"""
interface = gr.Interface(
fn=versewise_bot,
inputs=[
gr.Textbox(label="Ask Krishna", placeholder="Why am I struggling in life?", lines=2),
gr.Checkbox(label="Play Background Music", value=True)
],
outputs=[
gr.Textbox(label="π§ββ Krishna's Answer"),
gr.Audio(label="π Krishnaβs Voice", visible=False, type="filepath"),
gr.Audio(label="πΆ Background Music", autoplay=True, type="filepath"),
gr.DownloadButton(label="Download Response with Assurance")
],
title="π VerseWise - Divine Wisdom from the Gita",
description="Ask any question, and receive a verse from the Bhagavad Gita with divine guidance.",
article=get_quote_of_the_day(),
flagging_mode="never",
theme="soft",
css=custom_css
)
if __name__ == "__main__":
print(f"Temp directory for audio and downloads: {TEMP_DIR}")
interface.launch()
|