Krish30 commited on
Commit
20459c3
Β·
verified Β·
1 Parent(s): 51a62d0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +539 -539
app.py CHANGED
@@ -1,539 +1,539 @@
1
- import time
2
- import os
3
- import json
4
- import random
5
- import streamlit as st
6
- from langchain_huggingface import HuggingFaceEmbeddings
7
- from langchain_chroma import Chroma
8
- from langchain.memory import ConversationBufferMemory
9
- from langchain.chains import ConversationalRetrievalChain
10
- from vectorize_documents import embeddings
11
- from deep_translator import GoogleTranslator
12
- from googlesearch import search
13
-
14
- # Set up working directory and API configuration
15
- working_dir = os.path.dirname(os.path.abspath(__file__))
16
- config_data = json.load(open(f"{working_dir}/config.json"))
17
- os.environ["GROQ_API_KEY"] = config_data["GROQ_API_KEY"]
18
-
19
- def setup_vectorstore():
20
- persist_directory = f"{working_dir}/vector_db_dir"
21
- vectorstore = Chroma(
22
- persist_directory=persist_directory,
23
- embedding_function=embeddings
24
- )
25
- return vectorstore
26
-
27
- def chat_chain(vectorstore):
28
- from langchain_groq import ChatGroq
29
-
30
- llm = ChatGroq(
31
- model="llama-3.1-70b-versatile",
32
- temperature=0
33
- )
34
- retriever = vectorstore.as_retriever()
35
- memory = ConversationBufferMemory(
36
- llm=llm,
37
- output_key="answer",
38
- memory_key="chat_history",
39
- return_messages=True
40
- )
41
-
42
- chain = ConversationalRetrievalChain.from_llm(
43
- llm=llm,
44
- retriever=retriever,
45
- chain_type="stuff",
46
- memory=memory,
47
- verbose=True,
48
- return_source_documents=True
49
- )
50
- return chain
51
-
52
- def fetch_daily_quote():
53
- query = "Bhagavad Gita inspirational quotes"
54
- results = list(search(query, num_results=5)) # Convert generator to list
55
- if results:
56
- return random.choice(results)
57
- return "Explore the Bhagavad Gita and Yoga Sutras for timeless wisdom!"
58
-
59
- # Streamlit UI
60
- st.set_page_config(
61
- page_title="Bhagavad Gita & Yoga Sutras Assistant",
62
- page_icon="πŸ•‰οΈ",
63
- layout="wide"
64
- )
65
-
66
- st.markdown(
67
- """
68
- <div style="text-align: center;">
69
- <h1 style="color: #4CAF50;">Wisdom Query Assistant</h1>
70
- <p style="font-size: 18px;">Explore timeless wisdom with the guidance of a knowledgeable assistant.</p>
71
- </div>
72
- """,
73
- unsafe_allow_html=True
74
- )
75
-
76
- # User name functionality
77
- if "user_name" not in st.session_state:
78
- st.session_state.user_name = ""
79
-
80
- if "chat_started" not in st.session_state:
81
- st.session_state.chat_started = False
82
-
83
- if not st.session_state.chat_started:
84
- st.markdown("<h3 style='text-align: center;'>Welcome! Before we begin, please enter your name:</h3>", unsafe_allow_html=True)
85
- user_name = st.text_input("Enter your name:", placeholder="Your Name", key="name_input")
86
- start_button = st.button("Start Chat")
87
-
88
- if start_button and user_name.strip():
89
- st.session_state.user_name = user_name.strip()
90
- st.session_state.chat_started = True
91
- st.success(f"Hello {st.session_state.user_name}! How can I assist you today?")
92
-
93
- # Display the daily quote
94
- quote = fetch_daily_quote()
95
- st.markdown(
96
- f"""
97
- <div style="text-align: center; background-color: #f0f8ff; padding: 10px; border-radius: 5px; margin-bottom: 20px;">
98
- <h4>🌟 Daily Wisdom: <a href="{quote}" target="_blank">{quote}</a></h4>
99
- </div>
100
- """,
101
- unsafe_allow_html=True
102
- )
103
-
104
- if st.session_state.chat_started:
105
- # Set up vectorstore and chat chain
106
- vectorstore = setup_vectorstore()
107
- chain = chat_chain(vectorstore)
108
-
109
- # Select language
110
- selected_language = st.selectbox("Select your preferred language:", options=[
111
- "English", "Hindi", "Bengali", "Telugu", "Marathi", "Tamil", "Urdu", "Gujarati", "Malayalam", "Kannada",
112
- "Punjabi", "Odia", "Maithili", "Sanskrit", "Santali", "Kashmiri", "Nepali", "Dogri", "Manipuri", "Bodo",
113
- "Sindhi", "Assamese", "Konkani", "Awadhi", "Rajasthani", "Haryanvi", "Bihari", "Chhattisgarhi", "Magahi"
114
- ], index=0)
115
-
116
- # Display chat history
117
- st.markdown("### πŸ’¬ Chat History")
118
- if "chat_history" in st.session_state:
119
- for chat in st.session_state.chat_history:
120
- st.markdown(f"**{st.session_state.user_name}:** {chat['question']}")
121
- st.markdown(f"**Assistant:** {chat['answer']}")
122
- st.markdown("---")
123
-
124
- # Input box for new query
125
- st.markdown(f"### Ask a new question, {st.session_state.user_name}:")
126
- with st.form("query_form", clear_on_submit=True):
127
- user_query = st.text_input("Your question:", key="query_input", placeholder="Type your query here...")
128
- submitted = st.form_submit_button("Submit")
129
-
130
- if submitted and user_query.strip():
131
- start_time = time.time()
132
- response = chain({"question": user_query.strip()})
133
- end_time = time.time()
134
-
135
- answer = response.get("answer", "No answer found.")
136
- source_documents = response.get("source_documents", [])
137
- execution_time = round(end_time - start_time, 2)
138
-
139
- # Translate response if needed
140
- if selected_language != "English":
141
- translator = GoogleTranslator(source="en", target=selected_language.lower())
142
- translated_answer = translator.translate(answer)
143
- else:
144
- translated_answer = answer
145
-
146
- # Save chat history
147
- if "chat_history" not in st.session_state:
148
- st.session_state.chat_history = []
149
- st.session_state.chat_history.append({
150
- "question": user_query.strip(),
151
- "answer": translated_answer
152
- })
153
-
154
- # Display source documents if available
155
- if source_documents:
156
- with st.expander("πŸ“œ Source Documents"):
157
- for i, doc in enumerate(source_documents):
158
- st.write(f"**Document {i + 1}:** {doc.page_content}")
159
-
160
- st.write(f"**🌟 Enlightened Response:** {translated_answer}")
161
- st.write(f"_Response time: {execution_time} seconds_")
162
-
163
- # Sharing options
164
- st.markdown(
165
- """
166
- <div style="text-align: center;">
167
- <a href="https://wa.me/?text=Explore%20the%20Bhagavad%20Gita%20%26%20Yoga%20Sutras%20Assistant!%20Check%20it%20out%20here:%20https://your-platform-link" target="_blank">
168
- <img src="https://img.icons8.com/color/48/whatsapp.png" alt="WhatsApp" style="margin-right: 10px;">
169
- </a>
170
- <a href="https://www.linkedin.com/shareArticle?mini=true&url=https://your-platform-link&title=Explore%20Wisdom%20with%20Our%20Assistant" target="_blank">
171
- <img src="https://img.icons8.com/color/48/linkedin.png" alt="LinkedIn">
172
- </a>
173
- </div>
174
- """,
175
- unsafe_allow_html=True
176
- )
177
-
178
-
179
-
180
-
181
-
182
-
183
-
184
-
185
-
186
-
187
-
188
-
189
- # import time
190
- # import os
191
- # import json
192
- # import random
193
- # import streamlit as st
194
- # from langchain_huggingface import HuggingFaceEmbeddings
195
- # from langchain_chroma import Chroma
196
- # from langchain.memory import ConversationBufferMemory
197
- # from langchain.chains import ConversationalRetrievalChain
198
- # from vectorize_documents import embeddings
199
- # from deep_translator import GoogleTranslator # For multilingual support
200
-
201
- # # Set up working directory and API configuration
202
- # working_dir = os.path.dirname(os.path.abspath(__file__))
203
- # config_data = json.load(open(f"{working_dir}/config.json"))
204
- # os.environ["GROQ_API_KEY"] = config_data["GROQ_API_KEY"]
205
-
206
- # def setup_vectorstore():
207
- # persist_directory = f"{working_dir}/vector_db_dir"
208
- # vectorstore = Chroma(
209
- # persist_directory=persist_directory,
210
- # embedding_function=embeddings
211
- # )
212
- # return vectorstore
213
-
214
- # def chat_chain(vectorstore):
215
- # from langchain_groq import ChatGroq # Import the LLM class
216
-
217
- # llm = ChatGroq(
218
- # model="llama-3.1-70b-versatile", # Replace with your LLM of choice
219
- # temperature=0 # Set low temperature to reduce hallucinations
220
- # )
221
- # retriever = vectorstore.as_retriever() # Retrieve relevant chunks
222
- # memory = ConversationBufferMemory(
223
- # llm=llm,
224
- # output_key="answer",
225
- # memory_key="chat_history",
226
- # return_messages=True
227
- # )
228
-
229
- # # Build the conversational retrieval chain
230
- # chain = ConversationalRetrievalChain.from_llm(
231
- # llm=llm,
232
- # retriever=retriever,
233
- # chain_type="stuff", # Define how documents are combined
234
- # memory=memory,
235
- # verbose=True,
236
- # return_source_documents=True
237
- # )
238
- # return chain
239
-
240
- # # Streamlit UI
241
- # st.set_page_config(
242
- # page_title="Bhagavad Gita & Yoga Sutras Assistant",
243
- # page_icon="πŸ•‰οΈ", # Custom meaningful favicon
244
- # layout="wide"
245
- # )
246
-
247
- # # Title and description with enhanced styling
248
- # st.markdown(
249
- # """
250
- # <div style="text-align: center;">
251
- # <h1 style="color: #4CAF50;">Wisdom Query Assistant</h1>
252
- # <p style="font-size: 18px;">Explore timeless wisdom with the guidance of a knowledgeable assistant.</p>
253
- # </div>
254
- # """,
255
- # unsafe_allow_html=True
256
- # )
257
-
258
- # # Daily Wisdom Quote
259
- # daily_quotes = [
260
- # "You have the right to work, but never to the fruit of work. – Bhagavad Gita",
261
- # "Yoga is the journey of the self, through the self, to the self. – Bhagavad Gita",
262
- # "When meditation is mastered, the mind is unwavering like the flame of a lamp in a windless place. – Bhagavad Gita",
263
- # "Do not dwell in the past, do not dream of the future, concentrate the mind on the present moment. – Buddha",
264
- # ]
265
- # st.markdown(
266
- # f"""
267
- # <div style="text-align: center; background-color: #f0f8ff; padding: 10px; border-radius: 5px; margin-bottom: 20px;">
268
- # <h4>🌟 Daily Wisdom: {random.choice(daily_quotes)}</h4>
269
- # </div>
270
- # """,
271
- # unsafe_allow_html=True
272
- # )
273
-
274
- # # Theme Toggle
275
- # theme = st.radio("Choose a Theme:", options=["Light", "Dark"], index=0, horizontal=True)
276
- # if theme == "Dark":
277
- # st.markdown(
278
- # """
279
- # <style>
280
- # body { background-color: #121212; color: white; }
281
- # </style>
282
- # """,
283
- # unsafe_allow_html=True
284
- # )
285
-
286
- # vectorstore = setup_vectorstore()
287
- # chain = chat_chain(vectorstore)
288
-
289
- # # Initialize session state
290
- # if "user_name" not in st.session_state:
291
- # st.session_state.user_name = ""
292
-
293
- # if "chat_started" not in st.session_state:
294
- # st.session_state.chat_started = False
295
-
296
- # # Language options
297
- # languages = [
298
- # "English", "Hindi", "Bengali", "Telugu", "Marathi", "Tamil", "Urdu", "Gujarati", "Malayalam", "Kannada",
299
- # "Punjabi", "Odia", "Maithili", "Sanskrit", "Santali", "Kashmiri", "Nepali", "Dogri", "Manipuri", "Bodo",
300
- # "Sindhi", "Assamese", "Konkani", "Awadhi", "Rajasthani", "Haryanvi", "Bihari", "Chhattisgarhi", "Magahi"
301
- # ]
302
-
303
- # # Input for user name
304
- # if not st.session_state.chat_started:
305
- # st.markdown("<h3 style='text-align: center;'>Welcome! Before we begin, please enter your name:</h3>", unsafe_allow_html=True)
306
- # user_name = st.text_input("Enter your name:", placeholder="Your Name", key="name_input")
307
- # start_button = st.button("Start Chat")
308
-
309
- # if start_button and user_name.strip():
310
- # st.session_state.user_name = user_name.strip()
311
- # st.session_state.chat_started = True
312
- # st.success(f"Hello {st.session_state.user_name}! How can I assist you today?")
313
-
314
- # # Chat functionality
315
- # if st.session_state.chat_started:
316
- # st.markdown(f"<h3 style='text-align: center;'>Hello {st.session_state.user_name}! Ask me anything:</h3>", unsafe_allow_html=True)
317
-
318
- # # Language selection dropdown
319
- # selected_language = st.selectbox("Select your preferred language:", options=languages, index=0)
320
-
321
- # # User input and buttons
322
- # user_query = st.text_input("πŸ’¬ Type your question:", placeholder="Type your query here...", key="query_box")
323
- # submit_button = st.button("Submit")
324
-
325
- # if submit_button and user_query.strip():
326
- # # Generate response
327
- # start_time = time.time()
328
- # response = chain({"question": user_query.strip()})
329
- # end_time = time.time()
330
-
331
- # answer = response.get("answer", "No answer found.")
332
- # source_documents = response.get("source_documents", [])
333
- # execution_time = round(end_time - start_time, 2)
334
-
335
- # # Translate response
336
- # if selected_language != "English":
337
- # translator = GoogleTranslator(source="en", target=selected_language.lower())
338
- # translated_answer = translator.translate(answer)
339
- # else:
340
- # translated_answer = answer
341
-
342
- # # Display answer
343
- # st.markdown("---")
344
- # st.markdown(f"### 🌟 Enlightened Response:")
345
- # st.write(translated_answer)
346
-
347
- # # Display source documents
348
- # if source_documents:
349
- # st.markdown("### πŸ“œ Source Documents:")
350
- # for i, doc in enumerate(source_documents):
351
- # with st.expander(f"Source Document {i + 1}"):
352
- # st.write(doc.page_content)
353
- # else:
354
- # st.markdown("No source documents available.")
355
-
356
- # # Execution time
357
- # st.markdown(f"<p style='font-size: 14px;'>Response Time: <strong>{execution_time}</strong> seconds</p>", unsafe_allow_html=True)
358
-
359
- # # Sharing options with icons
360
- # st.markdown("---")
361
- # st.markdown(
362
- # """
363
- # <div style="text-align: center;">
364
- # <a href="https://wa.me/?text=Explore%20the%20Bhagavad%20Gita%20%26%20Yoga%20Sutras%20Assistant!%20Check%20it%20out%20here:%20https://your-platform-link" target="_blank">
365
- # <img src="https://img.icons8.com/color/48/whatsapp.png" alt="WhatsApp" style="margin-right: 10px;">
366
- # </a>
367
- # <a href="https://www.linkedin.com/shareArticle?mini=true&url=https://your-platform-link&title=Explore%20Wisdom%20with%20Our%20Assistant" target="_blank">
368
- # <img src="https://img.icons8.com/color/48/linkedin.png" alt="LinkedIn">
369
- # </a>
370
- # </div>
371
- # """,
372
- # unsafe_allow_html=True
373
- # )
374
-
375
-
376
-
377
-
378
-
379
-
380
-
381
-
382
-
383
-
384
-
385
-
386
-
387
-
388
-
389
-
390
- # import time
391
- # import os
392
- # import json
393
- # import streamlit as st
394
- # from langchain_huggingface import HuggingFaceEmbeddings
395
- # from langchain_chroma import Chroma
396
- # from langchain.memory import ConversationBufferMemory
397
- # from langchain.chains import ConversationalRetrievalChain
398
- # from vectorize_documents import embeddings # Import embeddings from the vectorization script
399
- # from deep_translator import GoogleTranslator # Import Google Translator for multilingual support
400
-
401
- # # Set up working directory and API configuration
402
- # working_dir = os.path.dirname(os.path.abspath(__file__))
403
- # config_data = json.load(open(f"{working_dir}/config.json"))
404
- # os.environ["GROQ_API_KEY"] = config_data["GROQ_API_KEY"]
405
-
406
- # def setup_vectorstore():
407
- # persist_directory = f"{working_dir}/vector_db_dir"
408
- # vectorstore = Chroma(
409
- # persist_directory=persist_directory,
410
- # embedding_function=embeddings
411
- # )
412
- # return vectorstore
413
-
414
- # def chat_chain(vectorstore):
415
- # from langchain_groq import ChatGroq # Import the LLM class
416
-
417
- # llm = ChatGroq(
418
- # model="llama-3.1-70b-versatile", # Replace with your LLM of choice
419
- # temperature=0 # Set low temperature to reduce hallucinations
420
- # )
421
- # retriever = vectorstore.as_retriever() # Retrieve relevant chunks
422
- # memory = ConversationBufferMemory(
423
- # llm=llm,
424
- # output_key="answer",
425
- # memory_key="chat_history",
426
- # return_messages=True
427
- # )
428
-
429
- # # Build the conversational retrieval chain
430
- # chain = ConversationalRetrievalChain.from_llm(
431
- # llm=llm,
432
- # retriever=retriever,
433
- # chain_type="stuff", # Define how documents are combined
434
- # memory=memory,
435
- # verbose=True,
436
- # return_source_documents=True
437
- # )
438
- # return chain
439
-
440
- # # Streamlit UI
441
- # st.set_page_config(page_title="Bhagavad Gita & Yoga Sutras Assistant", layout="wide")
442
-
443
- # # Title and description with enhanced styling
444
- # st.markdown(
445
- # """
446
- # <div style="text-align: center;">
447
- # <h1 style="color: #4CAF50;">Wisdom Query Assistant</h1>
448
- # <p style="font-size: 18px;">Explore timeless wisdom with the guidance of a knowledgeable assistant.</p>
449
- # </div>
450
- # """,
451
- # unsafe_allow_html=True
452
- # )
453
-
454
- # vectorstore = setup_vectorstore()
455
- # chain = chat_chain(vectorstore)
456
-
457
- # # Initialize session state for user name and chat
458
- # if "user_name" not in st.session_state:
459
- # st.session_state.user_name = ""
460
-
461
- # if "chat_started" not in st.session_state:
462
- # st.session_state.chat_started = False
463
-
464
- # # Language options
465
- # languages = [
466
- # "English", "Hindi", "Bengali", "Telugu", "Marathi", "Tamil", "Urdu", "Gujarati", "Malayalam", "Kannada",
467
- # "Punjabi", "Odia", "Maithili", "Sanskrit", "Santali", "Kashmiri", "Nepali", "Dogri", "Manipuri", "Bodo",
468
- # "Sindhi", "Assamese", "Konkani", "Awadhi", "Rajasthani", "Haryanvi", "Bihari", "Chhattisgarhi", "Magahi"
469
- # ]
470
-
471
- # # Input for user name
472
- # if not st.session_state.chat_started:
473
- # st.markdown("<h3 style='text-align: center;'>Welcome! Before we begin, please enter your name:</h3>", unsafe_allow_html=True)
474
- # user_name = st.text_input("Enter your name:", placeholder="Your Name", key="name_input")
475
- # start_button = st.button("Start Chat")
476
-
477
- # if start_button and user_name.strip():
478
- # st.session_state.user_name = user_name.strip()
479
- # st.session_state.chat_started = True
480
- # st.success(f"Hello {st.session_state.user_name}! How can I assist you today?")
481
-
482
- # # Chat functionality
483
- # if st.session_state.chat_started:
484
- # st.markdown(f"<h3 style='text-align: center;'>Hello {st.session_state.user_name}! Ask me about Wisdom:</h3>", unsafe_allow_html=True)
485
-
486
- # # Language selection dropdown
487
- # selected_language = st.selectbox("Select your preferred language:", options=languages, index=0)
488
-
489
- # # User input and submit button at the bottom
490
- # user_query = st.text_input("πŸ’¬ Your question:", placeholder="Type your query here...", key="query_box")
491
- # submit_button = st.button("Submit")
492
-
493
- # if submit_button and user_query.strip():
494
- # # Generate response
495
- # start_time = time.time()
496
- # response = chain({"question": user_query.strip()})
497
- # end_time = time.time()
498
-
499
- # answer = response.get("answer", "No answer found.")
500
- # source_documents = response.get("source_documents", [])
501
- # execution_time = round(end_time - start_time, 2)
502
-
503
- # # Translate the answer based on selected language
504
- # if selected_language != "English":
505
- # translator = GoogleTranslator(source="en", target=selected_language.lower())
506
- # translated_answer = translator.translate(answer)
507
- # else:
508
- # translated_answer = answer
509
-
510
- # # Display the answer
511
- # st.markdown("---")
512
- # st.markdown(f"### 🌟 Enlightened Response:")
513
- # st.write(translated_answer)
514
-
515
- # # Display source documents
516
- # if source_documents:
517
- # st.markdown("### πŸ“œ Source Documents:")
518
- # for i, doc in enumerate(source_documents):
519
- # with st.expander(f"Source Document {i + 1}"):
520
- # st.write(doc.page_content)
521
- # else:
522
- # st.markdown("No source documents available.")
523
-
524
- # # Display execution time
525
- # st.markdown(f"<p style='font-size: 14px;'>Response Time: <strong>{execution_time}</strong> seconds</p>", unsafe_allow_html=True)
526
-
527
-
528
-
529
-
530
-
531
-
532
-
533
-
534
-
535
-
536
-
537
-
538
-
539
-
 
1
+ import time
2
+ import os
3
+ import json
4
+ import random
5
+ import streamlit as st
6
+ from langchain_huggingface import HuggingFaceEmbeddings
7
+ from langchain_chroma import Chroma
8
+ from langchain.memory import ConversationBufferMemory
9
+ from langchain.chains import ConversationalRetrievalChain
10
+ from vectorize_documents import embeddings
11
+ from deep_translator import GoogleTranslator
12
+ from googlesearch import search
13
+
14
+ # Set up working directory and API configuration
15
+ working_dir = os.path.dirname(os.path.abspath(__file__))
16
+ config_data = json.load(open(f"{working_dir}/config.json"))
17
+ os.environ["GROQ_API_KEY"] = config_data["GROQ_API_KEY"]
18
+
19
+ def setup_vectorstore():
20
+ persist_directory = f"{working_dir}/vector_db_dir"
21
+ vectorstore = Chroma(
22
+ persist_directory=persist_directory,
23
+ embedding_function=embeddings
24
+ )
25
+ return vectorstore
26
+
27
+ def chat_chain(vectorstore):
28
+ from langchain_groq import ChatGroq
29
+
30
+ llm = ChatGroq(
31
+ model="llama-3.1-70b-versatile",
32
+ temperature=0
33
+ )
34
+ retriever = vectorstore.as_retriever()
35
+ memory = ConversationBufferMemory(
36
+ llm=llm,
37
+ output_key="answer",
38
+ memory_key="chat_history",
39
+ return_messages=True
40
+ )
41
+
42
+ chain = ConversationalRetrievalChain.from_llm(
43
+ llm=llm,
44
+ retriever=retriever,
45
+ chain_type="stuff",
46
+ memory=memory,
47
+ verbose=True,
48
+ return_source_documents=True
49
+ )
50
+ return chain
51
+
52
+ def fetch_daily_quote():
53
+ query = "Bhagavad Gita inspirational quotes"
54
+ results = list(search(query, num_results=5)) # Convert generator to list
55
+ if results:
56
+ return random.choice(results)
57
+ return "Explore the Bhagavad Gita and Yoga Sutras for timeless wisdom!"
58
+
59
+ # Streamlit UI
60
+ st.set_page_config(
61
+ page_title="Bhagavad Gita & Yoga Sutras Assistant",
62
+ page_icon="πŸ•‰οΈ",
63
+ layout="wide"
64
+ )
65
+
66
+ st.markdown(
67
+ """
68
+ <div style="text-align: center;">
69
+ <h1 style="color: #4CAF50;">Wisdom Query Assistant</h1>
70
+ <p style="font-size: 18px;">Explore timeless wisdom with the guidance of a knowledgeable assistant.</p>
71
+ </div>
72
+ """,
73
+ unsafe_allow_html=True
74
+ )
75
+
76
+ # User name functionality
77
+ if "user_name" not in st.session_state:
78
+ st.session_state.user_name = ""
79
+
80
+ if "chat_started" not in st.session_state:
81
+ st.session_state.chat_started = False
82
+
83
+ if not st.session_state.chat_started:
84
+ st.markdown("<h3 style='text-align: center;'>Welcome! Before we begin, please enter your name:</h3>", unsafe_allow_html=True)
85
+ user_name = st.text_input("Enter your name:", placeholder="Your Name", key="name_input")
86
+ start_button = st.button("Start Chat")
87
+
88
+ if start_button and user_name.strip():
89
+ st.session_state.user_name = user_name.strip()
90
+ st.session_state.chat_started = True
91
+ st.success(f"Hello {st.session_state.user_name}! How can I assist you today?")
92
+
93
+ # Display the daily quote
94
+ quote = fetch_daily_quote()
95
+ st.markdown(
96
+ f"""
97
+ <div style="text-align: center; background-color: #f0f8ff; padding: 10px; border-radius: 5px; margin-bottom: 20px;">
98
+ <h4>🌟 Daily Wisdom: <a href="{quote}" target="_blank">{quote}</a></h4>
99
+ </div>
100
+ """,
101
+ unsafe_allow_html=True
102
+ )
103
+
104
+ if st.session_state.chat_started:
105
+ # Set up vectorstore and chat chain
106
+ vectorstore = setup_vectorstore()
107
+ chain = chat_chain(vectorstore)
108
+
109
+ # Select language
110
+ selected_language = st.selectbox("Select your preferred language:", options=[
111
+ "English", "Hindi", "Bengali", "Telugu", "Marathi", "Tamil", "Urdu", "Gujarati", "Malayalam", "Kannada",
112
+ "Punjabi", "Odia", "Maithili", "Sanskrit", "Santali", "Kashmiri", "Nepali", "Dogri", "Manipuri", "Bodo",
113
+ "Sindhi", "Assamese", "Konkani", "Awadhi", "Rajasthani", "Haryanvi", "Bihari", "Chhattisgarhi", "Magahi"
114
+ ], index=0)
115
+
116
+ # Display chat history
117
+ st.markdown("### πŸ’¬ Chat History")
118
+ if "chat_history" in st.session_state:
119
+ for chat in st.session_state.chat_history:
120
+ st.markdown(f"**{st.session_state.user_name}:** {chat['question']}")
121
+ st.markdown(f"**Assistant:** {chat['answer']}")
122
+ st.markdown("---")
123
+
124
+ # Input box for new query
125
+ st.markdown(f"### Ask a new question, {st.session_state.user_name}:")
126
+ with st.form("query_form", clear_on_submit=True):
127
+ user_query = st.text_input("Your question:", key="query_input", placeholder="Type your query here...")
128
+ submitted = st.form_submit_button("Submit")
129
+
130
+ if submitted and user_query.strip():
131
+ start_time = time.time()
132
+ response = chain({"question": user_query.strip()})
133
+ end_time = time.time()
134
+
135
+ answer = response.get("answer", "No answer found.")
136
+ source_documents = response.get("source_documents", [])
137
+ execution_time = round(end_time - start_time, 2)
138
+
139
+ # Translate response if needed
140
+ if selected_language != "English":
141
+ translator = GoogleTranslator(source="en", target=selected_language.lower())
142
+ translated_answer = translator.translate(answer)
143
+ else:
144
+ translated_answer = answer
145
+
146
+ # Save chat history
147
+ if "chat_history" not in st.session_state:
148
+ st.session_state.chat_history = []
149
+ st.session_state.chat_history.append({
150
+ "question": user_query.strip(),
151
+ "answer": translated_answer
152
+ })
153
+
154
+ # Display source documents if available
155
+ if source_documents:
156
+ with st.expander("πŸ“œ Source Documents"):
157
+ for i, doc in enumerate(source_documents):
158
+ st.write(f"**Document {i + 1}:** {doc.page_content}")
159
+
160
+ st.write(f"**🌟 Enlightened Response:** {translated_answer}")
161
+ st.write(f"_Response time: {execution_time} seconds_")
162
+
163
+ # Sharing options
164
+ st.markdown(
165
+ """
166
+ <div style="text-align: center;">
167
+ <a href="https://wa.me/?text=Explore%20the%20Bhagavad%20Gita%20%26%20Yoga%20Sutras%20Assistant!%20Check%20it%20out%20here:%20https://krish30-wisdom-query-assistant.hf.space" target="_blank">
168
+ <img src="https://img.icons8.com/color/48/whatsapp.png" alt="WhatsApp" style="margin-right: 10px;">
169
+ </a>
170
+ <a href="https://www.linkedin.com/shareArticle?mini=true&url=https://krish30-wisdom-query-assistant.hf.space&title=Explore%20Wisdom%20with%20Our%20Assistant" target="_blank">
171
+ <img src="https://img.icons8.com/color/48/linkedin.png" alt="LinkedIn">
172
+ </a>
173
+ </div>
174
+ """,
175
+ unsafe_allow_html=True
176
+ )
177
+
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+ # import time
190
+ # import os
191
+ # import json
192
+ # import random
193
+ # import streamlit as st
194
+ # from langchain_huggingface import HuggingFaceEmbeddings
195
+ # from langchain_chroma import Chroma
196
+ # from langchain.memory import ConversationBufferMemory
197
+ # from langchain.chains import ConversationalRetrievalChain
198
+ # from vectorize_documents import embeddings
199
+ # from deep_translator import GoogleTranslator # For multilingual support
200
+
201
+ # # Set up working directory and API configuration
202
+ # working_dir = os.path.dirname(os.path.abspath(__file__))
203
+ # config_data = json.load(open(f"{working_dir}/config.json"))
204
+ # os.environ["GROQ_API_KEY"] = config_data["GROQ_API_KEY"]
205
+
206
+ # def setup_vectorstore():
207
+ # persist_directory = f"{working_dir}/vector_db_dir"
208
+ # vectorstore = Chroma(
209
+ # persist_directory=persist_directory,
210
+ # embedding_function=embeddings
211
+ # )
212
+ # return vectorstore
213
+
214
+ # def chat_chain(vectorstore):
215
+ # from langchain_groq import ChatGroq # Import the LLM class
216
+
217
+ # llm = ChatGroq(
218
+ # model="llama-3.1-70b-versatile", # Replace with your LLM of choice
219
+ # temperature=0 # Set low temperature to reduce hallucinations
220
+ # )
221
+ # retriever = vectorstore.as_retriever() # Retrieve relevant chunks
222
+ # memory = ConversationBufferMemory(
223
+ # llm=llm,
224
+ # output_key="answer",
225
+ # memory_key="chat_history",
226
+ # return_messages=True
227
+ # )
228
+
229
+ # # Build the conversational retrieval chain
230
+ # chain = ConversationalRetrievalChain.from_llm(
231
+ # llm=llm,
232
+ # retriever=retriever,
233
+ # chain_type="stuff", # Define how documents are combined
234
+ # memory=memory,
235
+ # verbose=True,
236
+ # return_source_documents=True
237
+ # )
238
+ # return chain
239
+
240
+ # # Streamlit UI
241
+ # st.set_page_config(
242
+ # page_title="Bhagavad Gita & Yoga Sutras Assistant",
243
+ # page_icon="πŸ•‰οΈ", # Custom meaningful favicon
244
+ # layout="wide"
245
+ # )
246
+
247
+ # # Title and description with enhanced styling
248
+ # st.markdown(
249
+ # """
250
+ # <div style="text-align: center;">
251
+ # <h1 style="color: #4CAF50;">Wisdom Query Assistant</h1>
252
+ # <p style="font-size: 18px;">Explore timeless wisdom with the guidance of a knowledgeable assistant.</p>
253
+ # </div>
254
+ # """,
255
+ # unsafe_allow_html=True
256
+ # )
257
+
258
+ # # Daily Wisdom Quote
259
+ # daily_quotes = [
260
+ # "You have the right to work, but never to the fruit of work. – Bhagavad Gita",
261
+ # "Yoga is the journey of the self, through the self, to the self. – Bhagavad Gita",
262
+ # "When meditation is mastered, the mind is unwavering like the flame of a lamp in a windless place. – Bhagavad Gita",
263
+ # "Do not dwell in the past, do not dream of the future, concentrate the mind on the present moment. – Buddha",
264
+ # ]
265
+ # st.markdown(
266
+ # f"""
267
+ # <div style="text-align: center; background-color: #f0f8ff; padding: 10px; border-radius: 5px; margin-bottom: 20px;">
268
+ # <h4>🌟 Daily Wisdom: {random.choice(daily_quotes)}</h4>
269
+ # </div>
270
+ # """,
271
+ # unsafe_allow_html=True
272
+ # )
273
+
274
+ # # Theme Toggle
275
+ # theme = st.radio("Choose a Theme:", options=["Light", "Dark"], index=0, horizontal=True)
276
+ # if theme == "Dark":
277
+ # st.markdown(
278
+ # """
279
+ # <style>
280
+ # body { background-color: #121212; color: white; }
281
+ # </style>
282
+ # """,
283
+ # unsafe_allow_html=True
284
+ # )
285
+
286
+ # vectorstore = setup_vectorstore()
287
+ # chain = chat_chain(vectorstore)
288
+
289
+ # # Initialize session state
290
+ # if "user_name" not in st.session_state:
291
+ # st.session_state.user_name = ""
292
+
293
+ # if "chat_started" not in st.session_state:
294
+ # st.session_state.chat_started = False
295
+
296
+ # # Language options
297
+ # languages = [
298
+ # "English", "Hindi", "Bengali", "Telugu", "Marathi", "Tamil", "Urdu", "Gujarati", "Malayalam", "Kannada",
299
+ # "Punjabi", "Odia", "Maithili", "Sanskrit", "Santali", "Kashmiri", "Nepali", "Dogri", "Manipuri", "Bodo",
300
+ # "Sindhi", "Assamese", "Konkani", "Awadhi", "Rajasthani", "Haryanvi", "Bihari", "Chhattisgarhi", "Magahi"
301
+ # ]
302
+
303
+ # # Input for user name
304
+ # if not st.session_state.chat_started:
305
+ # st.markdown("<h3 style='text-align: center;'>Welcome! Before we begin, please enter your name:</h3>", unsafe_allow_html=True)
306
+ # user_name = st.text_input("Enter your name:", placeholder="Your Name", key="name_input")
307
+ # start_button = st.button("Start Chat")
308
+
309
+ # if start_button and user_name.strip():
310
+ # st.session_state.user_name = user_name.strip()
311
+ # st.session_state.chat_started = True
312
+ # st.success(f"Hello {st.session_state.user_name}! How can I assist you today?")
313
+
314
+ # # Chat functionality
315
+ # if st.session_state.chat_started:
316
+ # st.markdown(f"<h3 style='text-align: center;'>Hello {st.session_state.user_name}! Ask me anything:</h3>", unsafe_allow_html=True)
317
+
318
+ # # Language selection dropdown
319
+ # selected_language = st.selectbox("Select your preferred language:", options=languages, index=0)
320
+
321
+ # # User input and buttons
322
+ # user_query = st.text_input("πŸ’¬ Type your question:", placeholder="Type your query here...", key="query_box")
323
+ # submit_button = st.button("Submit")
324
+
325
+ # if submit_button and user_query.strip():
326
+ # # Generate response
327
+ # start_time = time.time()
328
+ # response = chain({"question": user_query.strip()})
329
+ # end_time = time.time()
330
+
331
+ # answer = response.get("answer", "No answer found.")
332
+ # source_documents = response.get("source_documents", [])
333
+ # execution_time = round(end_time - start_time, 2)
334
+
335
+ # # Translate response
336
+ # if selected_language != "English":
337
+ # translator = GoogleTranslator(source="en", target=selected_language.lower())
338
+ # translated_answer = translator.translate(answer)
339
+ # else:
340
+ # translated_answer = answer
341
+
342
+ # # Display answer
343
+ # st.markdown("---")
344
+ # st.markdown(f"### 🌟 Enlightened Response:")
345
+ # st.write(translated_answer)
346
+
347
+ # # Display source documents
348
+ # if source_documents:
349
+ # st.markdown("### πŸ“œ Source Documents:")
350
+ # for i, doc in enumerate(source_documents):
351
+ # with st.expander(f"Source Document {i + 1}"):
352
+ # st.write(doc.page_content)
353
+ # else:
354
+ # st.markdown("No source documents available.")
355
+
356
+ # # Execution time
357
+ # st.markdown(f"<p style='font-size: 14px;'>Response Time: <strong>{execution_time}</strong> seconds</p>", unsafe_allow_html=True)
358
+
359
+ # # Sharing options with icons
360
+ # st.markdown("---")
361
+ # st.markdown(
362
+ # """
363
+ # <div style="text-align: center;">
364
+ # <a href="https://wa.me/?text=Explore%20the%20Bhagavad%20Gita%20%26%20Yoga%20Sutras%20Assistant!%20Check%20it%20out%20here:%20https://your-platform-link" target="_blank">
365
+ # <img src="https://img.icons8.com/color/48/whatsapp.png" alt="WhatsApp" style="margin-right: 10px;">
366
+ # </a>
367
+ # <a href="https://www.linkedin.com/shareArticle?mini=true&url=https://your-platform-link&title=Explore%20Wisdom%20with%20Our%20Assistant" target="_blank">
368
+ # <img src="https://img.icons8.com/color/48/linkedin.png" alt="LinkedIn">
369
+ # </a>
370
+ # </div>
371
+ # """,
372
+ # unsafe_allow_html=True
373
+ # )
374
+
375
+
376
+
377
+
378
+
379
+
380
+
381
+
382
+
383
+
384
+
385
+
386
+
387
+
388
+
389
+
390
+ # import time
391
+ # import os
392
+ # import json
393
+ # import streamlit as st
394
+ # from langchain_huggingface import HuggingFaceEmbeddings
395
+ # from langchain_chroma import Chroma
396
+ # from langchain.memory import ConversationBufferMemory
397
+ # from langchain.chains import ConversationalRetrievalChain
398
+ # from vectorize_documents import embeddings # Import embeddings from the vectorization script
399
+ # from deep_translator import GoogleTranslator # Import Google Translator for multilingual support
400
+
401
+ # # Set up working directory and API configuration
402
+ # working_dir = os.path.dirname(os.path.abspath(__file__))
403
+ # config_data = json.load(open(f"{working_dir}/config.json"))
404
+ # os.environ["GROQ_API_KEY"] = config_data["GROQ_API_KEY"]
405
+
406
+ # def setup_vectorstore():
407
+ # persist_directory = f"{working_dir}/vector_db_dir"
408
+ # vectorstore = Chroma(
409
+ # persist_directory=persist_directory,
410
+ # embedding_function=embeddings
411
+ # )
412
+ # return vectorstore
413
+
414
+ # def chat_chain(vectorstore):
415
+ # from langchain_groq import ChatGroq # Import the LLM class
416
+
417
+ # llm = ChatGroq(
418
+ # model="llama-3.1-70b-versatile", # Replace with your LLM of choice
419
+ # temperature=0 # Set low temperature to reduce hallucinations
420
+ # )
421
+ # retriever = vectorstore.as_retriever() # Retrieve relevant chunks
422
+ # memory = ConversationBufferMemory(
423
+ # llm=llm,
424
+ # output_key="answer",
425
+ # memory_key="chat_history",
426
+ # return_messages=True
427
+ # )
428
+
429
+ # # Build the conversational retrieval chain
430
+ # chain = ConversationalRetrievalChain.from_llm(
431
+ # llm=llm,
432
+ # retriever=retriever,
433
+ # chain_type="stuff", # Define how documents are combined
434
+ # memory=memory,
435
+ # verbose=True,
436
+ # return_source_documents=True
437
+ # )
438
+ # return chain
439
+
440
+ # # Streamlit UI
441
+ # st.set_page_config(page_title="Bhagavad Gita & Yoga Sutras Assistant", layout="wide")
442
+
443
+ # # Title and description with enhanced styling
444
+ # st.markdown(
445
+ # """
446
+ # <div style="text-align: center;">
447
+ # <h1 style="color: #4CAF50;">Wisdom Query Assistant</h1>
448
+ # <p style="font-size: 18px;">Explore timeless wisdom with the guidance of a knowledgeable assistant.</p>
449
+ # </div>
450
+ # """,
451
+ # unsafe_allow_html=True
452
+ # )
453
+
454
+ # vectorstore = setup_vectorstore()
455
+ # chain = chat_chain(vectorstore)
456
+
457
+ # # Initialize session state for user name and chat
458
+ # if "user_name" not in st.session_state:
459
+ # st.session_state.user_name = ""
460
+
461
+ # if "chat_started" not in st.session_state:
462
+ # st.session_state.chat_started = False
463
+
464
+ # # Language options
465
+ # languages = [
466
+ # "English", "Hindi", "Bengali", "Telugu", "Marathi", "Tamil", "Urdu", "Gujarati", "Malayalam", "Kannada",
467
+ # "Punjabi", "Odia", "Maithili", "Sanskrit", "Santali", "Kashmiri", "Nepali", "Dogri", "Manipuri", "Bodo",
468
+ # "Sindhi", "Assamese", "Konkani", "Awadhi", "Rajasthani", "Haryanvi", "Bihari", "Chhattisgarhi", "Magahi"
469
+ # ]
470
+
471
+ # # Input for user name
472
+ # if not st.session_state.chat_started:
473
+ # st.markdown("<h3 style='text-align: center;'>Welcome! Before we begin, please enter your name:</h3>", unsafe_allow_html=True)
474
+ # user_name = st.text_input("Enter your name:", placeholder="Your Name", key="name_input")
475
+ # start_button = st.button("Start Chat")
476
+
477
+ # if start_button and user_name.strip():
478
+ # st.session_state.user_name = user_name.strip()
479
+ # st.session_state.chat_started = True
480
+ # st.success(f"Hello {st.session_state.user_name}! How can I assist you today?")
481
+
482
+ # # Chat functionality
483
+ # if st.session_state.chat_started:
484
+ # st.markdown(f"<h3 style='text-align: center;'>Hello {st.session_state.user_name}! Ask me about Wisdom:</h3>", unsafe_allow_html=True)
485
+
486
+ # # Language selection dropdown
487
+ # selected_language = st.selectbox("Select your preferred language:", options=languages, index=0)
488
+
489
+ # # User input and submit button at the bottom
490
+ # user_query = st.text_input("πŸ’¬ Your question:", placeholder="Type your query here...", key="query_box")
491
+ # submit_button = st.button("Submit")
492
+
493
+ # if submit_button and user_query.strip():
494
+ # # Generate response
495
+ # start_time = time.time()
496
+ # response = chain({"question": user_query.strip()})
497
+ # end_time = time.time()
498
+
499
+ # answer = response.get("answer", "No answer found.")
500
+ # source_documents = response.get("source_documents", [])
501
+ # execution_time = round(end_time - start_time, 2)
502
+
503
+ # # Translate the answer based on selected language
504
+ # if selected_language != "English":
505
+ # translator = GoogleTranslator(source="en", target=selected_language.lower())
506
+ # translated_answer = translator.translate(answer)
507
+ # else:
508
+ # translated_answer = answer
509
+
510
+ # # Display the answer
511
+ # st.markdown("---")
512
+ # st.markdown(f"### 🌟 Enlightened Response:")
513
+ # st.write(translated_answer)
514
+
515
+ # # Display source documents
516
+ # if source_documents:
517
+ # st.markdown("### πŸ“œ Source Documents:")
518
+ # for i, doc in enumerate(source_documents):
519
+ # with st.expander(f"Source Document {i + 1}"):
520
+ # st.write(doc.page_content)
521
+ # else:
522
+ # st.markdown("No source documents available.")
523
+
524
+ # # Display execution time
525
+ # st.markdown(f"<p style='font-size: 14px;'>Response Time: <strong>{execution_time}</strong> seconds</p>", unsafe_allow_html=True)
526
+
527
+
528
+
529
+
530
+
531
+
532
+
533
+
534
+
535
+
536
+
537
+
538
+
539
+