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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from datetime import datetime
|
| 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 |
+
def setup_vectorstore():
|
| 21 |
+
persist_directory = f"{working_dir}/vector_db_dir"
|
| 22 |
+
vectorstore = Chroma(
|
| 23 |
+
persist_directory=persist_directory,
|
| 24 |
+
embedding_function=embeddings
|
| 25 |
+
)
|
| 26 |
+
return vectorstore
|
| 27 |
+
|
| 28 |
+
def chat_chain(vectorstore):
|
| 29 |
+
from langchain_groq import ChatGroq
|
| 30 |
+
|
| 31 |
+
llm = ChatGroq(
|
| 32 |
+
model="llama-3.1-70b-versatile",
|
| 33 |
+
temperature=0
|
| 34 |
+
)
|
| 35 |
+
retriever = vectorstore.as_retriever()
|
| 36 |
+
memory = ConversationBufferMemory(
|
| 37 |
+
llm=llm,
|
| 38 |
+
output_key="answer",
|
| 39 |
+
memory_key="chat_history",
|
| 40 |
+
return_messages=True
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
chain = ConversationalRetrievalChain.from_llm(
|
| 44 |
+
llm=llm,
|
| 45 |
+
retriever=retriever,
|
| 46 |
+
chain_type="stuff",
|
| 47 |
+
memory=memory,
|
| 48 |
+
verbose=True,
|
| 49 |
+
return_source_documents=True
|
| 50 |
+
)
|
| 51 |
+
return chain
|
| 52 |
+
|
| 53 |
+
def fetch_daily_quote():
|
| 54 |
+
"""Fetch a daily Bhagavad Gita quote with its URL."""
|
| 55 |
+
query = "Bhagavad Gita inspirational quotes"
|
| 56 |
+
results = list(search(query, num_results=5)) # Convert generator to list
|
| 57 |
+
if results:
|
| 58 |
+
chosen_result = random.choice(results)
|
| 59 |
+
return chosen_result
|
| 60 |
+
return "Explore the Bhagavad Gita and Yoga Sutras for timeless wisdom!"
|
| 61 |
+
|
| 62 |
+
def get_daily_quote():
|
| 63 |
+
"""Get or refresh the daily quote based on the date."""
|
| 64 |
+
current_date = datetime.now().date()
|
| 65 |
+
if "daily_quote_date" not in st.session_state or st.session_state.daily_quote_date != current_date:
|
| 66 |
+
# Fetch new quote and save the current date
|
| 67 |
+
st.session_state.daily_quote_date = current_date
|
| 68 |
+
st.session_state.daily_quote = fetch_daily_quote()
|
| 69 |
+
|
| 70 |
+
return st.session_state.daily_quote
|
| 71 |
+
|
| 72 |
+
# Streamlit UI
|
| 73 |
+
st.set_page_config(
|
| 74 |
+
page_title="Bhagavad Gita & Yoga Sutras Assistant",
|
| 75 |
+
page_icon="ποΈ",
|
| 76 |
+
layout="wide"
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
st.markdown(
|
| 80 |
+
"""
|
| 81 |
+
<div style="text-align: center;">
|
| 82 |
+
<h1 style="color: #4CAF50;">Wisdom Query Assistant</h1>
|
| 83 |
+
<p style="font-size: 18px;">Explore timeless wisdom with the guidance of a knowledgeable assistant.</p>
|
| 84 |
+
</div>
|
| 85 |
+
""",
|
| 86 |
+
unsafe_allow_html=True
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
# User name functionality
|
| 90 |
+
if "user_name" not in st.session_state:
|
| 91 |
+
st.session_state.user_name = ""
|
| 92 |
+
|
| 93 |
+
if "chat_started" not in st.session_state:
|
| 94 |
+
st.session_state.chat_started = False
|
| 95 |
+
|
| 96 |
+
if not st.session_state.chat_started:
|
| 97 |
+
st.markdown("<h3 style='text-align: center;'>Welcome! Before we begin, please enter your name:</h3>", unsafe_allow_html=True)
|
| 98 |
+
user_name = st.text_input("Enter your name:", placeholder="Your Name", key="name_input")
|
| 99 |
+
start_button = st.button("Start Chat")
|
| 100 |
+
|
| 101 |
+
if start_button and user_name.strip():
|
| 102 |
+
st.session_state.user_name = user_name.strip()
|
| 103 |
+
st.session_state.chat_started = True
|
| 104 |
+
st.success(f"Hello {st.session_state.user_name}! How can I assist you today?")
|
| 105 |
+
|
| 106 |
+
# Display the daily quote
|
| 107 |
+
daily_quote = get_daily_quote()
|
| 108 |
+
st.markdown(
|
| 109 |
+
f"""
|
| 110 |
+
<div style="text-align: center; background-color: #f0f8ff; padding: 10px; border-radius: 5px; margin-bottom: 20px;">
|
| 111 |
+
<h4>π Daily Wisdom: <a href="{daily_quote}" target="_blank">{daily_quote}</a></h4>
|
| 112 |
+
</div>
|
| 113 |
+
""",
|
| 114 |
+
unsafe_allow_html=True
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
if st.session_state.chat_started:
|
| 118 |
+
# Set up vectorstore and chat chain
|
| 119 |
+
vectorstore = setup_vectorstore()
|
| 120 |
+
chain = chat_chain(vectorstore)
|
| 121 |
+
|
| 122 |
+
# Select language
|
| 123 |
+
selected_language = st.selectbox("Select your preferred language:", options=[
|
| 124 |
+
"English", "Hindi", "Bengali", "Telugu", "Marathi", "Tamil", "Urdu", "Gujarati", "Malayalam", "Kannada",
|
| 125 |
+
"Punjabi", "Odia", "Maithili", "Sanskrit", "Santali", "Kashmiri", "Nepali", "Dogri", "Manipuri", "Bodo",
|
| 126 |
+
"Sindhi", "Assamese", "Konkani", "Awadhi", "Rajasthani", "Haryanvi", "Bihari", "Chhattisgarhi", "Magahi"
|
| 127 |
+
], index=0)
|
| 128 |
+
|
| 129 |
+
# Display chat history
|
| 130 |
+
st.markdown("### π¬ Chat History")
|
| 131 |
+
if "chat_history" in st.session_state:
|
| 132 |
+
for chat in st.session_state.chat_history:
|
| 133 |
+
st.markdown(f"**{st.session_state.user_name}:** {chat['question']}")
|
| 134 |
+
st.markdown(f"**Assistant:** {chat['answer']}")
|
| 135 |
+
st.markdown("---")
|
| 136 |
+
|
| 137 |
+
# Input box for new query
|
| 138 |
+
st.markdown(f"### Ask a new question, {st.session_state.user_name}:")
|
| 139 |
+
with st.form("query_form", clear_on_submit=True):
|
| 140 |
+
user_query = st.text_input("Your question:", key="query_input", placeholder="Type your query here...")
|
| 141 |
+
submitted = st.form_submit_button("Submit")
|
| 142 |
+
|
| 143 |
+
if submitted and user_query.strip():
|
| 144 |
+
start_time = time.time()
|
| 145 |
+
response = chain({"question": user_query.strip()})
|
| 146 |
+
end_time = time.time()
|
| 147 |
+
|
| 148 |
+
answer = response.get("answer", "No answer found.")
|
| 149 |
+
source_documents = response.get("source_documents", [])
|
| 150 |
+
execution_time = round(end_time - start_time, 2)
|
| 151 |
+
|
| 152 |
+
# Translate response if needed
|
| 153 |
+
if selected_language != "English":
|
| 154 |
+
translator = GoogleTranslator(source="en", target=selected_language.lower())
|
| 155 |
+
translated_answer = translator.translate(answer)
|
| 156 |
+
else:
|
| 157 |
+
translated_answer = answer
|
| 158 |
+
|
| 159 |
+
# Save chat history
|
| 160 |
+
if "chat_history" not in st.session_state:
|
| 161 |
+
st.session_state.chat_history = []
|
| 162 |
+
st.session_state.chat_history.append({
|
| 163 |
+
"question": user_query.strip(),
|
| 164 |
+
"answer": translated_answer
|
| 165 |
+
})
|
| 166 |
+
|
| 167 |
+
# Display source documents if available
|
| 168 |
+
if source_documents:
|
| 169 |
+
with st.expander("π Source Documents"):
|
| 170 |
+
for i, doc in enumerate(source_documents):
|
| 171 |
+
st.write(f"**Document {i + 1}:** {doc.page_content}")
|
| 172 |
+
|
| 173 |
+
st.write(f"**π§ββοΈ Assistant:** {translated_answer}")
|
| 174 |
+
st.write(f"_Response time: {execution_time} seconds_")
|
| 175 |
+
|
| 176 |
+
# Sharing options
|
| 177 |
+
st.markdown(
|
| 178 |
+
"""
|
| 179 |
+
<div style="text-align: center;">
|
| 180 |
+
<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">
|
| 181 |
+
<img src="https://img.icons8.com/color/48/whatsapp.png" alt="WhatsApp" style="margin-right: 10px;">
|
| 182 |
+
</a>
|
| 183 |
+
<a href="https://www.linkedin.com/shareArticle?mini=true&url=https://your-platform-link&title=Explore%20Wisdom%20with%20Our%20Assistant" target="_blank">
|
| 184 |
+
<img src="https://img.icons8.com/color/48/linkedin.png" alt="LinkedIn">
|
| 185 |
+
</a>
|
| 186 |
+
</div>
|
| 187 |
+
""",
|
| 188 |
+
unsafe_allow_html=True
|
| 189 |
+
)
|