Krish30 commited on
Commit
c6e8a54
·
verified ·
1 Parent(s): 9206a6d

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +547 -0
  2. chat_history.db +0 -0
  3. config.json +1 -0
  4. requirements.txt +13 -0
app.py ADDED
@@ -0,0 +1,547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import os
2
+ # import json
3
+ # import streamlit as st
4
+ # from langchain_huggingface import HuggingFaceEmbeddings
5
+ # from langchain_chroma import Chroma
6
+ # from langchain.memory import ConversationBufferMemory
7
+ # from langchain.chains import ConversationalRetrievalChain
8
+ # from vectorize_documents import embeddings
9
+ # import speech_recognition as sr
10
+ # import sounddevice as sd
11
+ # import numpy as np
12
+ # from scipy.io.wavfile import write
13
+ # from deep_translator import GoogleTranslator
14
+
15
+ # # Set up working directory and API configuration
16
+ # working_dir = os.path.dirname(os.path.abspath(__file__))
17
+ # config_data = json.load(open(f"{working_dir}/config.json"))
18
+ # os.environ["GROQ_API_KEY"] = config_data["GROQ_API_KEY"]
19
+
20
+ # # Streamlit session state initialization
21
+ # def initialize_session_state():
22
+ # if "chat_history" not in st.session_state:
23
+ # st.session_state["chat_history"] = []
24
+ # if "vectorstore" not in st.session_state:
25
+ # st.session_state["vectorstore"] = setup_vectorstore()
26
+ # if "chain" not in st.session_state:
27
+ # st.session_state["chain"] = chat_chain(st.session_state["vectorstore"])
28
+
29
+ # # Vectorstore setup
30
+ # def setup_vectorstore():
31
+ # embeddings = HuggingFaceEmbeddings()
32
+ # vectorstore = Chroma(
33
+ # persist_directory=f"{working_dir}/vector_db_dir",
34
+ # embedding_function=embeddings
35
+ # )
36
+ # return vectorstore
37
+
38
+ # # Chat chain setup with logging
39
+ # def chat_chain(vectorstore):
40
+ # from langchain_groq import ChatGroq
41
+ # llm = ChatGroq(
42
+ # model="llama-3.1-70b-versatile",
43
+ # temperature=0
44
+ # )
45
+ # retriever = vectorstore.as_retriever()
46
+ # memory = ConversationBufferMemory(
47
+ # memory_key="chat_history",
48
+ # return_messages=True
49
+ # )
50
+ # chain = ConversationalRetrievalChain.from_llm(
51
+ # llm=llm,
52
+ # retriever=retriever,
53
+ # chain_type="stuff",
54
+ # memory=memory,
55
+ # verbose=True # Enables debugging logs
56
+ # )
57
+ # return chain
58
+
59
+ # # Transcription function with SoundDevice
60
+ # def transcribe_audio(selected_language):
61
+ # try:
62
+ # duration = 5 # seconds
63
+ # samplerate = 44100 # Hz
64
+ # st.write("🎤 Listening... Please ask your question.")
65
+ # recording = sd.rec(int(duration * samplerate), samplerate=samplerate, channels=1, dtype='int16')
66
+ # sd.wait()
67
+ # audio_path = "/tmp/temp_audio.wav"
68
+ # write(audio_path, samplerate, recording)
69
+
70
+ # recognizer = sr.Recognizer()
71
+ # with sr.AudioFile(audio_path) as source:
72
+ # audio = recognizer.record(source)
73
+ # query = recognizer.recognize_google(audio, language=selected_language)
74
+ # st.write(f"**🗣️ You said:** {query}")
75
+ # return query
76
+ # except sr.WaitTimeoutError:
77
+ # st.error("⏳ You didn't speak in time. Please try again.")
78
+ # except sr.UnknownValueError:
79
+ # st.error("❌ Sorry, could not understand the audio. Please try again.")
80
+ # except sr.RequestError as e:
81
+ # st.error(f"⚠️ Error with speech recognition service: {e}")
82
+ # except Exception as e:
83
+ # st.error(f"⚠️ Audio input error: {str(e)}")
84
+ # return None
85
+
86
+ # # Translation functions
87
+ # def translate_to_english(text, source_lang):
88
+ # if source_lang == "en":
89
+ # return text
90
+ # return GoogleTranslator(source=source_lang, target="en").translate(text)
91
+
92
+ # def translate_from_english(text, target_lang):
93
+ # if target_lang == "en":
94
+ # return text
95
+ # return GoogleTranslator(source="en", target=target_lang).translate(text)
96
+
97
+ # # Streamlit UI
98
+ # initialize_session_state()
99
+
100
+ # st.markdown(
101
+ # """
102
+ # <style>
103
+ # .main-title {
104
+ # font-size: 36px;
105
+ # color: #FF8C00;
106
+ # font-weight: bold;
107
+ # }
108
+ # .sub-title {
109
+ # font-size: 24px;
110
+ # color: #FF8C00;
111
+ # }
112
+ # .icon {
113
+ # font-size: 50px;
114
+ # color: #FF8C00;
115
+ # }
116
+ # </style>
117
+ # """,
118
+ # unsafe_allow_html=True
119
+ # )
120
+
121
+ # st.markdown('<div class="icon">📚</div>', unsafe_allow_html=True)
122
+ # st.markdown('<div class="main-title">Bhagavad Gita & Yoga Sutras Query Assistant</div>', unsafe_allow_html=True)
123
+ # st.markdown('<div class="sub-title">Ask questions and explore timeless wisdom</div>', unsafe_allow_html=True)
124
+
125
+ # # Language support
126
+ # indian_languages = {
127
+ # "English": "en",
128
+ # "Assamese": "as",
129
+ # "Bengali": "bn",
130
+ # "Gujarati": "gu",
131
+ # "Hindi": "hi",
132
+ # "Kannada": "kn",
133
+ # "Kashmiri": "ks",
134
+ # "Konkani": "kok",
135
+ # "Malayalam": "ml",
136
+ # "Manipuri": "mni",
137
+ # "Marathi": "mr",
138
+ # "Nepali": "ne",
139
+ # "Odia": "or",
140
+ # "Punjabi": "pa",
141
+ # "Sanskrit": "sa",
142
+ # "Santali": "sat",
143
+ # "Sindhi": "sd",
144
+ # "Tamil": "ta",
145
+ # "Telugu": "te",
146
+ # "Urdu": "ur",
147
+ # "Bodo": "brx",
148
+ # "Dogri": "doi",
149
+ # "Maithili": "mai",
150
+ # "Santhali": "sat",
151
+ # "Tulu": "tcy",
152
+ # "Bhili/Bhilodi": "bhi",
153
+ # "Khasi": "kha",
154
+ # "Garo": "grt",
155
+ # "Mizo": "lus",
156
+ # "Sora": "srb",
157
+ # "Ho": "hoc",
158
+ # "Kurukh": "kru",
159
+ # "Korwa": "kfa",
160
+ # "Gondi": "gon",
161
+ # "Konkani": "kok"
162
+ # }
163
+
164
+ # selected_language = st.selectbox("Select your language:", options=list(indian_languages.keys()))
165
+ # language_code = indian_languages[selected_language]
166
+
167
+ # # User-friendly input selection
168
+ # st.markdown("### How would you like to ask your question?")
169
+ # input_mode = st.radio("Choose input method:", ("Voice", "Typing"))
170
+
171
+ # user_query = None
172
+
173
+ # if input_mode == "Voice":
174
+ # st.write("Click the button below to speak your question:")
175
+ # if st.button("🎤 Use Voice Input"):
176
+ # user_query = transcribe_audio(language_code)
177
+ # if user_query:
178
+ # user_query = translate_to_english(user_query, language_code)
179
+ # else:
180
+ # user_query = st.text_input("Type your question here:")
181
+ # if user_query:
182
+ # user_query = translate_to_english(user_query, language_code)
183
+
184
+ # # Handle user query
185
+ # if user_query:
186
+ # with st.spinner("Getting answer..."):
187
+ # try:
188
+ # response = st.session_state["chain"]({"question": user_query})
189
+
190
+ # # Debug retrieved context and chain response
191
+ # relevant_content = response.get("source_documents", None)
192
+ # st.write("Debug Info: Retrieved Context", relevant_content)
193
+
194
+ # if relevant_content:
195
+ # st.markdown("### ✅ **Answer:**")
196
+ # answer = response.get("answer", "No answer generated.")
197
+ # st.write(answer)
198
+ # except Exception as e:
199
+ # st.error(f"⚠️ An error occurred: {str(e)}")
200
+
201
+
202
+ # import os
203
+ # import json
204
+ # import sqlite3
205
+ # from datetime import datetime
206
+ # import streamlit as st
207
+ # from langchain_huggingface import HuggingFaceEmbeddings
208
+ # from langchain_chroma import Chroma
209
+ # from langchain_groq import ChatGroq
210
+ # from langchain.memory import ConversationBufferMemory
211
+ # from langchain.chains import ConversationalRetrievalChain
212
+
213
+ # from vectorize_documents import embeddings
214
+
215
+ # working_dir = os.path.dirname(os.path.abspath(__file__))
216
+ # config_data = json.load(open(f"{working_dir}/config.json"))
217
+ # GROQ_API_KEY = config_data["GROQ_API_KEY"]
218
+ # os.environ["GROQ_API_KEY"]= GROQ_API_KEY
219
+
220
+ # # Set up the database with check_same_thread=False
221
+ # def setup_db():
222
+ # conn = sqlite3.connect("chat_history.db", check_same_thread=False) # Ensure thread-safe connection
223
+ # cursor = conn.cursor()
224
+ # cursor.execute("""
225
+ # CREATE TABLE IF NOT EXISTS chat_histories (
226
+ # id INTEGER PRIMARY KEY AUTOINCREMENT,
227
+ # username TEXT,
228
+ # timestamp TEXT,
229
+ # day TEXT,
230
+ # user_message TEXT,
231
+ # assistant_response TEXT
232
+ # )
233
+ # """)
234
+ # conn.commit()
235
+ # return conn # Return the connection
236
+
237
+ # # Function to save chat history to SQLite
238
+ # def save_chat_history(conn, username, timestamp, day, user_message, assistant_response):
239
+ # cursor = conn.cursor()
240
+ # cursor.execute("""
241
+ # INSERT INTO chat_histories (username, timestamp, day, user_message, assistant_response)
242
+ # VALUES (?, ?, ?, ?, ?)
243
+ # """, (username, timestamp, day, user_message, assistant_response))
244
+ # conn.commit()
245
+
246
+ # # Function to set up vectorstore for embeddings
247
+ # def setup_vectorstore():
248
+ # embeddings = HuggingFaceEmbeddings()
249
+ # vectorstore = Chroma(persist_directory="vector_db_dir", embedding_function=embeddings)
250
+ # return vectorstore
251
+
252
+ # # Function to set up the chatbot chain
253
+ # def chat_chain(vectorstore):
254
+ # llm = ChatGroq(model="llama-3.1-70b-versatile", temperature=0)
255
+ # retriever = vectorstore.as_retriever()
256
+ # memory = ConversationBufferMemory(
257
+ # llm=llm,
258
+ # output_key="answer",
259
+ # memory_key="chat_history",
260
+ # return_messages=True
261
+ # )
262
+ # chain = ConversationalRetrievalChain.from_llm(
263
+ # llm=llm,
264
+ # retriever=retriever,
265
+ # chain_type="stuff",
266
+ # memory=memory,
267
+ # verbose=True,
268
+ # return_source_documents=True
269
+ # )
270
+ # return chain
271
+
272
+ # # Streamlit UI setup
273
+ # # Streamlit setup
274
+ # st.set_page_config(page_title="Bhagavad Gita Query Assistant", page_icon="📚", layout="centered")
275
+ # st.title("📚 Bhagavad Gita & Yoga Sutras Query Assistant")
276
+ # st.subheader("Ask questions and explore timeless wisdom!")
277
+
278
+ # # Step 1: Initialize the connection and check if the user is already logged in
279
+ # if "conn" not in st.session_state:
280
+ # st.session_state.conn = setup_db()
281
+
282
+ # if "username" not in st.session_state:
283
+ # username = st.text_input("Enter your name to proceed:")
284
+ # if username:
285
+ # with st.spinner("Loading chatbot interface... Please wait."):
286
+ # st.session_state.username = username
287
+ # st.session_state.chat_history = [] # Initialize empty chat history in memory
288
+ # st.session_state.vectorstore = setup_vectorstore()
289
+ # st.session_state.conversational_chain = chat_chain(st.session_state.vectorstore)
290
+ # st.success(f"Welcome, {username}! The chatbot interface is ready.")
291
+ # else:
292
+ # username = st.session_state.username
293
+
294
+ # # Step 2: Initialize components if not already set
295
+ # if "conversational_chain" not in st.session_state:
296
+ # st.session_state.vectorstore = setup_vectorstore()
297
+ # st.session_state.conversational_chain = chat_chain(st.session_state.vectorstore)
298
+
299
+ # # Step 3: Display the chat history in the UI
300
+ # if "username" in st.session_state:
301
+ # st.subheader(f"Hello {username}, start your query below!")
302
+
303
+ # # Display chat history (messages exchanged between user and assistant)
304
+ # if st.session_state.chat_history:
305
+ # for message in st.session_state.chat_history:
306
+ # if message['role'] == 'user':
307
+ # with st.chat_message("user"):
308
+ # st.markdown(message["content"])
309
+ # elif message['role'] == 'assistant':
310
+ # with st.chat_message("assistant"):
311
+ # st.markdown(message["content"])
312
+
313
+ # # Input field for the user to type their message
314
+ # user_input = st.chat_input("Ask AI....")
315
+
316
+ # if user_input:
317
+ # with st.spinner("Processing your query... Please wait."):
318
+ # # Save user input to chat history in memory
319
+ # st.session_state.chat_history.append({"role": "user", "content": user_input})
320
+
321
+ # # Display user's message in chatbot (for UI display)
322
+ # with st.chat_message("user"):
323
+ # st.markdown(user_input)
324
+
325
+ # # Get assistant's response from the chain
326
+ # with st.chat_message("assistant"):
327
+ # response = st.session_state.conversational_chain({"question": user_input})
328
+ # assistant_response = response["answer"]
329
+ # st.markdown(assistant_response)
330
+
331
+ # # Save assistant's response to chat history in memory
332
+ # st.session_state.chat_history.append({"role": "assistant", "content": assistant_response})
333
+
334
+ # # Save the chat history to the database (SQLite)
335
+ # timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
336
+ # day = datetime.now().strftime("%A") # Get the day of the week (e.g., Monday)
337
+ # save_chat_history(st.session_state.conn, username, timestamp, day, user_input, assistant_response)
338
+
339
+
340
+ import os
341
+ import json
342
+ import sqlite3
343
+ from datetime import datetime
344
+ import streamlit as st
345
+ from langchain_huggingface import HuggingFaceEmbeddings
346
+ from langchain_chroma import Chroma
347
+ from langchain_groq import ChatGroq
348
+ from langchain.memory import ConversationBufferMemory
349
+ from langchain.chains import ConversationalRetrievalChain
350
+ from deep_translator import GoogleTranslator
351
+ import speech_recognition as sr
352
+
353
+ # Directory paths and configurations
354
+ working_dir = os.path.dirname(os.path.abspath(__file__))
355
+ config_data = json.load(open(f"{working_dir}/config.json"))
356
+ GROQ_API_KEY = config_data["GROQ_API_KEY"]
357
+ os.environ["GROQ_API_KEY"] = GROQ_API_KEY
358
+
359
+ # Set up the database with check_same_thread=False
360
+ def setup_db():
361
+ conn = sqlite3.connect("chat_history.db", check_same_thread=False) # Ensure thread-safe connection
362
+ cursor = conn.cursor()
363
+ cursor.execute("""
364
+ CREATE TABLE IF NOT EXISTS chat_histories (
365
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
366
+ username TEXT,
367
+ timestamp TEXT,
368
+ day TEXT,
369
+ user_message TEXT,
370
+ assistant_response TEXT
371
+ )
372
+ """)
373
+ conn.commit()
374
+ return conn # Return the connection
375
+
376
+ # Function to save chat history to SQLite
377
+ def save_chat_history(conn, username, timestamp, day, user_message, assistant_response):
378
+ cursor = conn.cursor()
379
+ cursor.execute("""
380
+ INSERT INTO chat_histories (username, timestamp, day, user_message, assistant_response)
381
+ VALUES (?, ?, ?, ?, ?)
382
+ """, (username, timestamp, day, user_message, assistant_response))
383
+ conn.commit()
384
+
385
+ # Function to set up vectorstore for embeddings
386
+ def setup_vectorstore():
387
+ embeddings = HuggingFaceEmbeddings()
388
+ vectorstore = Chroma(persist_directory="vector_db_dir", embedding_function=embeddings)
389
+ return vectorstore
390
+
391
+ # Function to set up the chatbot chain
392
+ def chat_chain(vectorstore):
393
+ llm = ChatGroq(model="llama-3.1-70b-versatile", temperature=0)
394
+ retriever = vectorstore.as_retriever()
395
+ memory = ConversationBufferMemory(
396
+ llm=llm,
397
+ output_key="answer",
398
+ memory_key="chat_history",
399
+ return_messages=True
400
+ )
401
+ chain = ConversationalRetrievalChain.from_llm(
402
+ llm=llm,
403
+ retriever=retriever,
404
+ chain_type="stuff",
405
+ memory=memory,
406
+ verbose=True,
407
+ return_source_documents=True
408
+ )
409
+ return chain
410
+
411
+ # Function to get audio input from the user
412
+ def get_audio_input():
413
+ recognizer = sr.Recognizer()
414
+ with sr.Microphone() as source:
415
+ print("🎤 Listening... Please ask your question.")
416
+ try:
417
+ audio = recognizer.listen(source, timeout=5)
418
+ query = recognizer.recognize_google(audio)
419
+ print(f"You said: {query}")
420
+ return query
421
+ except sr.WaitTimeoutError:
422
+ print("⏳ You didn't speak in time. Please try again.")
423
+ except sr.UnknownValueError:
424
+ print("❌ Sorry, could not understand the audio. Please try again.")
425
+ except sr.RequestError as e:
426
+ print(f"⚠️ Error with speech recognition service: {e}")
427
+ return ""
428
+
429
+ # Streamlit UI setup
430
+ st.set_page_config(page_title="Bhagavad Gita Query Assistant", page_icon="📚", layout="centered")
431
+ st.title("📚 Bhagavad Gita & Yoga Sutras Query Assistant")
432
+ st.subheader("Ask questions and explore timeless wisdom!")
433
+
434
+ # Initialize session state
435
+ if "conn" not in st.session_state:
436
+ st.session_state.conn = setup_db()
437
+
438
+ if "username" not in st.session_state:
439
+ username = st.text_input("Enter your name to proceed:")
440
+ if username:
441
+ with st.spinner("Loading chatbot interface... Please wait."):
442
+ st.session_state.username = username
443
+ st.session_state.chat_history = [] # Initialize empty chat history in memory
444
+ st.session_state.vectorstore = setup_vectorstore()
445
+ st.session_state.conversational_chain = chat_chain(st.session_state.vectorstore)
446
+ st.success(f"Welcome, {username}! The chatbot interface is ready.")
447
+ else:
448
+ username = st.session_state.username
449
+
450
+ # Initialize components if not already set
451
+ if "conversational_chain" not in st.session_state:
452
+ st.session_state.vectorstore = setup_vectorstore()
453
+ st.session_state.conversational_chain = chat_chain(st.session_state.vectorstore)
454
+
455
+ # Language options (30 Indian languages)
456
+ languages = [
457
+ "English", "Hindi", "Bengali", "Telugu", "Marathi", "Tamil", "Urdu", "Gujarati", "Malayalam", "Kannada",
458
+ "Punjabi", "Odia", "Maithili", "Sanskrit", "Santali", "Kashmiri", "Nepali", "Dogri", "Manipuri", "Bodo",
459
+ "Sindhi", "Assamese", "Konkani", "Maithili", "Awadhi", "Rajasthani", "Haryanvi", "Bihari", "Chhattisgarhi", "Magahi"
460
+ ]
461
+
462
+ # Main interface
463
+ if "username" in st.session_state:
464
+ st.subheader(f"Hello {username}, start your query below!")
465
+
466
+ # Language selection for translation
467
+ selected_language = st.selectbox("Select the output language", languages, index=languages.index("English"))
468
+
469
+ # Input options for the user to type or use voice input
470
+ input_option = st.radio("Choose Input Method", ("Type your question", "Ask via Voice"))
471
+
472
+ # Container to hold the chat interface (for scrolling)
473
+ chat_container = st.container()
474
+
475
+ with chat_container:
476
+ if "chat_history" in st.session_state:
477
+ for message in st.session_state.chat_history:
478
+ if message['role'] == 'user':
479
+ with st.chat_message("user"):
480
+ st.markdown(message["content"])
481
+ elif message['role'] == 'assistant':
482
+ with st.chat_message("assistant"):
483
+ st.markdown(message["content"])
484
+
485
+ # Keep the chat interface scrollable
486
+ st.markdown(
487
+ """
488
+ <style>
489
+ .streamlit-expanderHeader {
490
+ display: none;
491
+ }
492
+ .chat-container {
493
+ max-height: 400px;
494
+ overflow-y: scroll;
495
+ }
496
+ </style>
497
+ """,
498
+ unsafe_allow_html=True
499
+ )
500
+
501
+ # User input section at the bottom
502
+ user_query = None # Initialize user_query as None
503
+
504
+ if input_option == "Type your question":
505
+ user_query = st.text_input("Ask AI about Bhagavad Gita or Yoga Sutras:")
506
+ elif input_option == "Ask via Voice":
507
+ if st.button("🎤 Ask via Voice"):
508
+ with st.spinner("Listening for your question..."):
509
+ user_query = get_audio_input()
510
+
511
+ # If user input is provided, process the query
512
+ if user_query:
513
+ with st.spinner("Processing your query... Please wait."):
514
+
515
+ # Save user input to chat history in memory
516
+ st.session_state.chat_history.append({"role": "user", "content": user_query})
517
+
518
+ # Display user's message in chatbot (for UI display)
519
+ with st.chat_message("user"):
520
+ st.markdown(user_query)
521
+
522
+ # Get assistant's response from the chain
523
+ with st.chat_message("assistant"):
524
+ response = st.session_state.conversational_chain({"question": user_query})
525
+ assistant_response = response["answer"]
526
+
527
+ # If no relevant content found, return a default response
528
+ if not response.get("source_documents"):
529
+ assistant_response = "I don't have enough information to answer this question from the Bhagavad Gita or Yoga Sutras."
530
+
531
+ # Display the assistant's answer
532
+ st.markdown(assistant_response)
533
+
534
+ # Save assistant's response to chat history in memory
535
+ st.session_state.chat_history.append({"role": "assistant", "content": assistant_response})
536
+
537
+ # Save the chat history to the database (SQLite)
538
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
539
+ day = datetime.now().strftime("%A") # Get the day of the week (e.g., Monday)
540
+ save_chat_history(st.session_state.conn, username, timestamp, day, user_query, assistant_response)
541
+
542
+ # Translate the assistant's response based on selected language
543
+ translator = GoogleTranslator(source="en", target=selected_language.lower())
544
+ translated_response = translator.translate(assistant_response)
545
+
546
+ # Display translated response
547
+ st.markdown(f"**Translated Answer ({selected_language}):** {translated_response}")
chat_history.db ADDED
Binary file (24.6 kB). View file
 
config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"GROQ_API_KEY": "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"}
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit==1.38.0
2
+ langchain-community==0.2.16
3
+ langchain-text-splitters==0.2.4
4
+ langchain-chroma==0.1.3
5
+ langchain-huggingface==0.0.3
6
+ langchain-groq==0.1.9
7
+ unstructured==0.15.0
8
+ nltk==3.8.1
9
+ docx2txt
10
+ SpeechRecognition
11
+ deep-translator
12
+ sounddevice # Replacement for PyAudio
13
+ scipy # Required for WAV file handling with SoundDevice