AlirezaHSZ commited on
Commit
339553b
·
verified ·
1 Parent(s): a881790

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -43
app.py CHANGED
@@ -8,16 +8,14 @@ from langchain.vectorstores import FAISS
8
  from langchain_google_genai import ChatGoogleGenerativeAI
9
  from langchain.chains.question_answering import load_qa_chain
10
  from langchain.prompts import PromptTemplate
11
- from langdetect import detect
12
  from dotenv import load_dotenv
13
  from google.api_core.exceptions import GoogleAPIError, InvalidArgument
 
14
 
15
  # Load environment variables
16
  load_dotenv()
17
- genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
18
- # Mock configuration for PersianLLaMA (replace with actual configuration)
19
- persian_api_key = os.getenv("PERSIAN_LLAMA_API_KEY")
20
- # persianllama.configure(api_key=persian_api_key)
21
 
22
  # Function to read all PDF files and return text
23
  def get_pdf_text(pdf_docs):
@@ -30,28 +28,25 @@ def get_pdf_text(pdf_docs):
30
 
31
  # Function to split text into chunks
32
  def get_text_chunks(text):
33
- splitter = RecursiveCharacterTextSplitter(
34
- chunk_size=10000, chunk_overlap=1000)
35
  chunks = splitter.split_text(text)
36
  return chunks # list of strings
37
 
38
- # Function to get embeddings for each chunk and save to vector store (language-specific)
39
- def get_vector_store(chunks, language):
40
- try:
41
- if language == 'fa':
42
- embeddings = PersianLLaMAEmbeddings(
43
- model="persianllama-embedding") # Mock PersianLLaMA embeddings
44
- else:
45
- embeddings = GoogleGenerativeAIEmbeddings(
46
- model="models/embedding-001") # Gemini embeddings
47
 
 
 
 
 
48
  vector_store = FAISS.from_texts(chunks, embedding=embeddings)
49
  vector_store.save_local("faiss_index")
50
  except (GoogleAPIError, InvalidArgument):
51
  raise RuntimeError("Error processing embeddings. Please try again in a minute.")
52
 
53
- # Function to get conversational chain (language-specific)
54
- def get_conversational_chain(language):
55
  prompt_template = """
56
  Answer the question as detailed as possible from the provided context.
57
  If the answer is not in the provided context, just say, "answer is not available in the context".
@@ -61,15 +56,8 @@ def get_conversational_chain(language):
61
  Answer:
62
  """
63
  try:
64
- if language == 'fa':
65
- model = PersianLLaMAChat(model="persianllama-chat") # Mock PersianLLaMA chat
66
- else:
67
- model = ChatGoogleGenerativeAI(model="gemini-pro",
68
- client=genai,
69
- temperature=0.3)
70
-
71
- prompt = PromptTemplate(template=prompt_template,
72
- input_variables=["context", "question"])
73
  chain = load_qa_chain(llm=model, chain_type="stuff", prompt=prompt)
74
  return chain
75
  except (GoogleAPIError, InvalidArgument):
@@ -80,21 +68,16 @@ def clear_chat_history():
80
  st.session_state.messages = [
81
  {"role": "assistant", "content": "Upload some PDFs and ask me a question"}]
82
 
83
- # Function to handle user input (language-specific)
84
- def user_input(user_question, language):
85
  try:
86
- if language == 'fa':
87
- embeddings = PersianLLaMAEmbeddings(
88
- model="persianllama-embedding") # Mock PersianLLaMA embeddings
89
- else:
90
- embeddings = GoogleGenerativeAIEmbeddings(
91
- model="models/embedding-001") # Gemini embeddings
92
-
93
  new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
94
  docs = new_db.similarity_search(user_question, k=4)
95
- chain = get_conversational_chain(language)
96
- response = chain(
97
- {"input_documents": docs, "question": user_question}, return_only_outputs=True)
 
98
  return response
99
  except (GoogleAPIError, InvalidArgument):
100
  raise RuntimeError("Error processing request. Please try again in a minute.")
@@ -153,13 +136,56 @@ def main():
153
  # Sidebar for uploading PDF files
154
  with st.sidebar:
155
  st.title("Menu")
156
- pdf_docs = st.file_uploader(
157
- "Upload your PDF files", accept_multiple_files=True)
158
  if st.button("Submit & Process", key="submit_button"):
159
  if pdf_docs:
160
  try:
161
  with st.spinner("Processing..."):
162
  raw_text = get_pdf_text(pdf_docs)
163
- language = detect(raw_text)
164
  text_chunks = get_text_chunks(raw_text)
165
- get_vector_store(text_chunks, language
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  from langchain_google_genai import ChatGoogleGenerativeAI
9
  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 langdetect import detect
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
  # Function to read all PDF files and return text
21
  def get_pdf_text(pdf_docs):
 
28
 
29
  # Function to split text into chunks
30
  def get_text_chunks(text):
31
+ splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
 
32
  chunks = splitter.split_text(text)
33
  return chunks # list of strings
34
 
35
+ # Function to detect the language of the text
36
+ def detect_language(text):
37
+ return detect(text)
 
 
 
 
 
 
38
 
39
+ # Function to get embeddings for each chunk and save to vector store
40
+ def get_vector_store(chunks, model_name):
41
+ try:
42
+ embeddings = GoogleGenerativeAIEmbeddings(model=model_name) # type: ignore
43
  vector_store = FAISS.from_texts(chunks, embedding=embeddings)
44
  vector_store.save_local("faiss_index")
45
  except (GoogleAPIError, InvalidArgument):
46
  raise RuntimeError("Error processing embeddings. Please try again in a minute.")
47
 
48
+ # Function to get conversational chain
49
+ def get_conversational_chain(model_name):
50
  prompt_template = """
51
  Answer the question as detailed as possible from the provided context.
52
  If the answer is not in the provided context, just say, "answer is not available in the context".
 
56
  Answer:
57
  """
58
  try:
59
+ model = ChatGoogleGenerativeAI(model=model_name, client=genai, temperature=0.3)
60
+ prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
 
 
 
 
 
 
 
61
  chain = load_qa_chain(llm=model, chain_type="stuff", prompt=prompt)
62
  return chain
63
  except (GoogleAPIError, InvalidArgument):
 
68
  st.session_state.messages = [
69
  {"role": "assistant", "content": "Upload some PDFs and ask me a question"}]
70
 
71
+ # Function to handle user input
72
+ def user_input(user_question):
73
  try:
74
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001") # type: ignore
 
 
 
 
 
 
75
  new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
76
  docs = new_db.similarity_search(user_question, k=4)
77
+ language = detect_language(' '.join([doc.page_content for doc in docs]))
78
+ model_name = "farsi-model" if language == "fa" else "gemini-pro"
79
+ chain = get_conversational_chain(model_name)
80
+ response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
81
  return response
82
  except (GoogleAPIError, InvalidArgument):
83
  raise RuntimeError("Error processing request. Please try again in a minute.")
 
136
  # Sidebar for uploading PDF files
137
  with st.sidebar:
138
  st.title("Menu")
139
+ pdf_docs = st.file_uploader("Upload your PDF files", accept_multiple_files=True)
 
140
  if st.button("Submit & Process", key="submit_button"):
141
  if pdf_docs:
142
  try:
143
  with st.spinner("Processing..."):
144
  raw_text = get_pdf_text(pdf_docs)
 
145
  text_chunks = get_text_chunks(raw_text)
146
+ language = detect_language(raw_text)
147
+ model_name = "farsi-model" if language == "fa" else "gemini-pro"
148
+ get_vector_store(text_chunks, model_name)
149
+ st.success("Processing completed!")
150
+ except RuntimeError as e:
151
+ st.error(str(e))
152
+ else:
153
+ st.error("Please upload at least one PDF file.")
154
+
155
+ # Main content area for displaying chat messages
156
+ st.title("Gemini PDF Chatbot")
157
+ st.write("Welcome to the Gemini PDF Chatbot! Upload your PDFs and ask questions.")
158
+ st.sidebar.button('Clear Chat History', on_click=clear_chat_history)
159
+
160
+ # Initialize chat history
161
+ if "messages" not in st.session_state:
162
+ st.session_state.messages = [
163
+ {"role": "assistant", "content": "Upload some PDFs and ask me a question"}]
164
+
165
+ # Display chat messages
166
+ for message in st.session_state.messages:
167
+ with st.chat_message(message["role"]):
168
+ st.write(message["content"])
169
+
170
+ # Chat input
171
+ if prompt := st.chat_input():
172
+ st.session_state.messages.append({"role": "user", "content": prompt})
173
+ with st.chat_message("user"):
174
+ st.write(prompt)
175
+
176
+ # Generate bot response
177
+ if st.session_state.messages[-1]["role"] != "assistant":
178
+ try:
179
+ with st.chat_message("assistant"):
180
+ with st.spinner("Thinking..."):
181
+ response = user_input(prompt)
182
+ if response:
183
+ full_response = ''.join(response['output_text'])
184
+ st.write(full_response)
185
+ message = {"role": "assistant", "content": full_response}
186
+ st.session_state.messages.append(message)
187
+ except RuntimeError as e:
188
+ st.error(str(e))
189
+
190
+ if __name__ == "__main__":
191
+ main()