Spaces:
Running
Running
| 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() | |