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