Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
import os
|
| 2 |
-
|
| 3 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 4 |
from langchain_google_genai import GoogleGenerativeAIEmbeddings
|
| 5 |
import streamlit as st
|
|
@@ -10,43 +10,57 @@ from langchain.chains.question_answering import load_qa_chain
|
|
| 10 |
from langchain.prompts import PromptTemplate
|
| 11 |
from dotenv import load_dotenv
|
| 12 |
from google.api_core.exceptions import GoogleAPIError, InvalidArgument
|
| 13 |
-
from google.cloud import aiplatform
|
| 14 |
|
| 15 |
# Load environment variables
|
| 16 |
load_dotenv()
|
| 17 |
api_key = os.getenv("GOOGLE_API_KEY")
|
| 18 |
genai.configure(api_key=api_key)
|
| 19 |
|
| 20 |
-
|
|
|
|
| 21 |
def get_pdf_text(pdf_docs):
|
|
|
|
| 22 |
text = ""
|
| 23 |
for pdf in pdf_docs:
|
| 24 |
-
|
| 25 |
-
for page in
|
| 26 |
-
|
|
|
|
|
|
|
| 27 |
return text
|
| 28 |
|
| 29 |
-
|
|
|
|
| 30 |
def get_text_chunks(text):
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
|
|
|
| 36 |
def get_vector_store(chunks):
|
|
|
|
| 37 |
try:
|
| 38 |
embeddings = GoogleGenerativeAIEmbeddings(model="models/text-embedding-004")
|
| 39 |
vector_store = FAISS.from_texts(chunks, embedding=embeddings)
|
| 40 |
-
|
| 41 |
except (GoogleAPIError, InvalidArgument):
|
| 42 |
raise RuntimeError("Error processing embeddings. Please try again in a minute.")
|
| 43 |
|
| 44 |
-
|
|
|
|
| 45 |
def get_conversational_chain():
|
|
|
|
| 46 |
prompt_template = """
|
| 47 |
-
You are a
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
| 50 |
Context:\n {context}\n
|
| 51 |
Question:\n {question}\n
|
| 52 |
Answer:
|
|
@@ -59,24 +73,25 @@ def get_conversational_chain():
|
|
| 59 |
except (GoogleAPIError, InvalidArgument):
|
| 60 |
raise RuntimeError("Error creating conversational chain. Please try again in a minute.")
|
| 61 |
|
| 62 |
-
|
|
|
|
| 63 |
def clear_chat_history():
|
| 64 |
st.session_state.messages = [
|
| 65 |
{"role": "assistant", "content": "در خدمتیم"}]
|
| 66 |
|
| 67 |
-
|
| 68 |
def user_input(user_question):
|
|
|
|
| 69 |
try:
|
| 70 |
-
|
| 71 |
-
new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
|
| 72 |
-
docs = new_db.similarity_search(user_question, k=4)
|
| 73 |
chain = get_conversational_chain()
|
| 74 |
response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
|
| 75 |
-
return response
|
| 76 |
except (GoogleAPIError, InvalidArgument):
|
| 77 |
raise RuntimeError("لطفا پس از چند لحظه دوباره امتحان کنید ")
|
| 78 |
|
| 79 |
-
|
|
|
|
| 80 |
def main():
|
| 81 |
st.set_page_config(
|
| 82 |
page_title="Chatbot",
|
|
@@ -157,13 +172,12 @@ def main():
|
|
| 157 |
try:
|
| 158 |
with st.chat_message("assistant"):
|
| 159 |
response = user_input(prompt)
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
message = {"role": "assistant", "content": full_response}
|
| 164 |
-
st.session_state.messages.append(message)
|
| 165 |
except RuntimeError as e:
|
| 166 |
st.error(str(e))
|
| 167 |
|
|
|
|
| 168 |
if __name__ == "__main__":
|
| 169 |
-
main()
|
|
|
|
| 1 |
import os
|
| 2 |
+
import fitz # PyMuPDF
|
| 3 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 4 |
from langchain_google_genai import GoogleGenerativeAIEmbeddings
|
| 5 |
import streamlit as st
|
|
|
|
| 10 |
from langchain.prompts import PromptTemplate
|
| 11 |
from dotenv import load_dotenv
|
| 12 |
from google.api_core.exceptions import GoogleAPIError, InvalidArgument
|
|
|
|
| 13 |
|
| 14 |
# Load environment variables
|
| 15 |
load_dotenv()
|
| 16 |
api_key = os.getenv("GOOGLE_API_KEY")
|
| 17 |
genai.configure(api_key=api_key)
|
| 18 |
|
| 19 |
+
|
| 20 |
+
# ---------------- PDF Extraction ----------------
|
| 21 |
def get_pdf_text(pdf_docs):
|
| 22 |
+
"""Extract text from uploaded PDFs (supports Farsi + English)."""
|
| 23 |
text = ""
|
| 24 |
for pdf in pdf_docs:
|
| 25 |
+
doc = fitz.open(stream=pdf.read(), filetype="pdf")
|
| 26 |
+
for page in doc:
|
| 27 |
+
page_text = page.get_text("text")
|
| 28 |
+
if page_text:
|
| 29 |
+
text += page_text + "\n"
|
| 30 |
return text
|
| 31 |
|
| 32 |
+
|
| 33 |
+
# ---------------- Text Chunking ----------------
|
| 34 |
def get_text_chunks(text):
|
| 35 |
+
"""Split text into smaller chunks for embedding."""
|
| 36 |
+
splitter = RecursiveCharacterTextSplitter(
|
| 37 |
+
chunk_size=800,
|
| 38 |
+
chunk_overlap=150,
|
| 39 |
+
separators=["\n\n", "\n", " ", ""]
|
| 40 |
+
)
|
| 41 |
+
return splitter.split_text(text)
|
| 42 |
|
| 43 |
+
|
| 44 |
+
# ---------------- FAISS Vector Store ----------------
|
| 45 |
def get_vector_store(chunks):
|
| 46 |
+
"""Create and store FAISS index in session state."""
|
| 47 |
try:
|
| 48 |
embeddings = GoogleGenerativeAIEmbeddings(model="models/text-embedding-004")
|
| 49 |
vector_store = FAISS.from_texts(chunks, embedding=embeddings)
|
| 50 |
+
st.session_state.vector_store = vector_store
|
| 51 |
except (GoogleAPIError, InvalidArgument):
|
| 52 |
raise RuntimeError("Error processing embeddings. Please try again in a minute.")
|
| 53 |
|
| 54 |
+
|
| 55 |
+
# ---------------- Conversational Chain ----------------
|
| 56 |
def get_conversational_chain():
|
| 57 |
+
"""Create QA chain with custom prompt."""
|
| 58 |
prompt_template = """
|
| 59 |
+
You are a helpful assistant.
|
| 60 |
+
Always answer in the same language as the question (Farsi or English).
|
| 61 |
+
If the answer is not in the provided context, reply with:
|
| 62 |
+
"پاسخ در متن موجود نیست" for Farsi OR "answer is not available in the context" for English.
|
| 63 |
+
|
| 64 |
Context:\n {context}\n
|
| 65 |
Question:\n {question}\n
|
| 66 |
Answer:
|
|
|
|
| 73 |
except (GoogleAPIError, InvalidArgument):
|
| 74 |
raise RuntimeError("Error creating conversational chain. Please try again in a minute.")
|
| 75 |
|
| 76 |
+
|
| 77 |
+
# ---------------- Chat Functions ----------------
|
| 78 |
def clear_chat_history():
|
| 79 |
st.session_state.messages = [
|
| 80 |
{"role": "assistant", "content": "در خدمتیم"}]
|
| 81 |
|
| 82 |
+
|
| 83 |
def user_input(user_question):
|
| 84 |
+
"""Handle user query and return response."""
|
| 85 |
try:
|
| 86 |
+
docs = st.session_state.vector_store.similarity_search(user_question, k=4)
|
|
|
|
|
|
|
| 87 |
chain = get_conversational_chain()
|
| 88 |
response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
|
| 89 |
+
return response['output_text']
|
| 90 |
except (GoogleAPIError, InvalidArgument):
|
| 91 |
raise RuntimeError("لطفا پس از چند لحظه دوباره امتحان کنید ")
|
| 92 |
|
| 93 |
+
|
| 94 |
+
# ---------------- Main App ----------------
|
| 95 |
def main():
|
| 96 |
st.set_page_config(
|
| 97 |
page_title="Chatbot",
|
|
|
|
| 172 |
try:
|
| 173 |
with st.chat_message("assistant"):
|
| 174 |
response = user_input(prompt)
|
| 175 |
+
st.write(response)
|
| 176 |
+
message = {"role": "assistant", "content": response}
|
| 177 |
+
st.session_state.messages.append(message)
|
|
|
|
|
|
|
| 178 |
except RuntimeError as e:
|
| 179 |
st.error(str(e))
|
| 180 |
|
| 181 |
+
|
| 182 |
if __name__ == "__main__":
|
| 183 |
+
main()
|