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"""