sreelekhaputta2 commited on
Commit
dda18cb
ยท
verified ยท
1 Parent(s): 4cd4eab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -49
app.py CHANGED
@@ -1,64 +1,133 @@
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
27
 
28
- response = ""
 
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
41
 
 
 
 
 
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
  ],
 
 
 
 
 
 
60
  )
61
 
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
+ # Install required libraries
2
+ !pip install -q gradio sentence-transformers edge-tts
3
+
4
+ # Import libraries
5
  import gradio as gr
6
+ import pandas as pd
7
+ import uuid
8
+ import asyncio
9
+ import shutil
10
+ import edge_tts
11
+ from sentence_transformers import SentenceTransformer, util
12
 
13
+ # Load Gita dataset
14
+ df = pd.read_csv("bhagavad_gita.csv") # Upload this file in Colab
 
 
15
 
16
+ # Load model
17
+ model = SentenceTransformer("all-MiniLM-L6-v2")
18
+ verse_embeddings = model.encode(df['meaning_in_english'].tolist(), convert_to_tensor=True)
19
 
20
+ # Background music path
21
+ bg_music_path = "krishna_bg_music.mp3" # Upload this mp3 in Colab
 
 
 
 
 
 
 
22
 
23
+ # Function to shorten long explanations
24
+ def shorten_explanation(text, max_sentences=2):
25
+ return '. '.join(text.split('. ')[:max_sentences]).strip() + "."
 
 
26
 
27
+ # Clean any Sanskrit characters from voice output
28
+ import re
29
+ def clean_english(text):
30
+ return re.sub(r'[^\x00-\x7F]+', ' ', text)
31
 
32
+ # Generate Krishna voice (only English)
33
+ async def generate_voice(text):
34
+ voice = "en-IN-PrabhatNeural"
35
+ filename = f"/content/{uuid.uuid4()}.mp3"
36
+ communicate = edge_tts.Communicate(text, voice=voice)
37
+ await communicate.save(filename)
38
+ return filename
39
 
40
+ # Duplicate background music to avoid caching
41
+ def get_unique_bgm():
42
+ unique_path = f"/content/bgm_{uuid.uuid4()}.mp3"
43
+ shutil.copy(bg_music_path, unique_path)
44
+ return unique_path
 
 
 
45
 
46
+ # Core chatbot function
47
+ def versewise_bot(question, play_music):
48
+ query_embedding = model.encode(question, convert_to_tensor=True)
49
+ similarity_scores = util.pytorch_cos_sim(query_embedding, verse_embeddings)[0]
50
+ idx = similarity_scores.argmax().item()
51
+ verse = df.iloc[idx]
52
 
53
+ sanskrit = verse['verse_in_sanskrit']
54
+ translation = verse['translation_in_english']
55
+ explanation = shorten_explanation(verse['meaning_in_english'])
56
+ verse_number = verse['verse_number']
57
 
58
+ # Text reply for UI
59
+ reply = f"""๐Ÿ“– **Bhagavad Gita {verse_number}**
60
+
61
+ ๐Ÿ•‰๏ธ *"{sanskrit[:60]}..."*
62
+
63
+ **"{translation}"**
64
+
65
+ ๐Ÿ•Š๏ธ {explanation}
66
+
67
+ ๐ŸŒผ *Stay strong โ€” Krishna walks with you.*"""
68
+
69
+ # Voice (translation + explanation only)
70
+ voice_text = f"{clean_english(translation)}. {clean_english(explanation)}"
71
+ audio_path = asyncio.run(generate_voice(voice_text))
72
+
73
+ music = get_unique_bgm() if play_music else None
74
+ return reply, audio_path, music
75
+
76
+ # Gita quote of the day
77
+ def get_quote_of_the_day():
78
+ verse = df.sample(1).iloc[0]
79
+ sanskrit = verse['verse_in_sanskrit']
80
+ translation = verse['translation_in_english']
81
+ verse_number = verse['verse_number']
82
+ return f"""<div style="font-size:1.1em;padding:10px 0;"><b>Quote of the Day (Gita {verse_number}):</b><br>
83
+ <i>{sanskrit[:60]}...</i><br>
84
+ <span style="color:#2d2d2d;">"{translation}"</span></div>"""
85
+
86
+ # UI Styling
87
+ custom_css = """
88
+ body, .gradio-container {
89
+ background-image: url('https://wallpapercave.com/wp/wp11564258.jpg');
90
+ background-size: cover;
91
+ background-repeat: no-repeat;
92
+ background-position: center;
93
+ }
94
+ .gradio-container, .gradio-interface {
95
+ background-color: rgba(255,255,255,0.90) !important;
96
+ border-radius: 18px;
97
+ padding: 25px;
98
+ max-width: 760px;
99
+ box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
100
+ }
101
+ @media only screen and (max-width: 768px) {
102
+ .gradio-container {
103
+ width: 95% !important;
104
+ padding: 15px !important;
105
+ }
106
+ }
107
+ input[type="text"], textarea {
108
+ font-size: 16px !important;
109
+ }
110
  """
111
+
112
+ # Build Gradio Interface
113
+ interface = gr.Interface(
114
+ fn=versewise_bot,
115
+ inputs=[
116
+ gr.Textbox(label="Ask Krishna", placeholder="Why am I struggling in life?", lines=2),
117
+ gr.Checkbox(label="Play Background Music", value=True)
118
+ ],
119
+ outputs=[
120
+ gr.Textbox(label="๐Ÿง˜โ€โ™‚๏ธ Krishna's Answer"),
121
+ gr.Audio(label="๐Ÿ”Š Listen to Krishna's Voice"),
122
+ gr.Audio(label="๐ŸŽถ Background Music", autoplay=True)
 
 
 
123
  ],
124
+ title="๐Ÿ•‰๏ธ VerseWise - Divine Wisdom from the Gita",
125
+ description="Ask any question, and receive a Gita verse with Krishnaโ€™s loving wisdom.",
126
+ article=get_quote_of_the_day(),
127
+ allow_flagging="never",
128
+ theme="soft",
129
+ css=custom_css
130
  )
131
 
132
+ # Launch app
133
+ interface.launch()