AlirezaHSZ commited on
Commit
11b7607
·
verified ·
1 Parent(s): 3369bc9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -101
app.py CHANGED
@@ -17,7 +17,7 @@ api_key = os.getenv("GOOGLE_API_KEY")
17
  genai.configure(api_key=api_key)
18
 
19
 
20
- # ✅ Function to read all PDF files (Farsi + English)
21
  def get_pdf_text(pdf_docs):
22
  text = ""
23
  for pdf in pdf_docs:
@@ -29,87 +29,65 @@ def get_pdf_text(pdf_docs):
29
  return text
30
 
31
 
32
- # ✅ Function to split text into chunks
33
  def get_text_chunks(text):
34
  splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
35
- chunks = splitter.split_text(text)
36
- return chunks
37
 
38
 
39
- # ✅ Function to get embeddings for each chunk and save to vector store
40
  def get_vector_store(chunks):
41
- try:
42
- embeddings = GoogleGenerativeAIEmbeddings(model="models/text-embedding-004")
43
- vector_store = FAISS.from_texts(chunks, embedding=embeddings)
44
- vector_store.save_local("faiss_index")
45
- except Exception as e:
46
- raise RuntimeError(f"Error creating vector store: {e}")
47
 
48
 
49
- # ✅ Function to get conversational chain
50
  def get_conversational_chain():
51
  prompt_template = """
52
- You are a helpful assistant. Do NOT reveal your identity (Gemini) or the company (Google).
53
- Answer the question as detailed as possible using ONLY the provided context.
54
- If the answer is not in the context, say: "answer is not available in the context".
55
- Do not make up answers.
56
 
57
- Context:
58
  {context}
59
 
60
- Question:
61
  {question}
62
 
63
- Answer:
64
  """
65
- try:
66
- model = ChatGoogleGenerativeAI(model="gemini-2.5-pro", client=genai, temperature=0.3)
67
- prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
68
- chain = load_qa_chain(llm=model, chain_type="stuff", prompt=prompt)
69
- return chain
70
- except Exception as e:
71
- raise RuntimeError(f"Error creating conversational chain: {e}")
72
 
73
 
74
- # ✅ Function to clear chat history
75
  def clear_chat_history():
76
  st.session_state.messages = [{"role": "assistant", "content": "در خدمتیم"}]
77
 
78
 
79
- # ✅ Function to handle user input
80
  def user_input(user_question):
81
- try:
82
- embeddings = GoogleGenerativeAIEmbeddings(model="models/text-embedding-004")
83
- new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
84
- docs = new_db.similarity_search(user_question, k=4)
85
- chain = get_conversational_chain()
86
- response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
87
- return response
88
- except Exception as e:
89
- raise RuntimeError(f"Error while answering: {e}")
90
-
91
-
92
- # ✅ Main function to run the Streamlit app
93
  def main():
94
- st.set_page_config(
95
- page_title="Chatbot",
96
- layout="wide",
97
- initial_sidebar_state="expanded"
98
- )
99
 
100
- # Dark theme styling
101
  st.markdown(
102
  """
103
  <style>
104
- body {
105
- background-color: #000000;
106
- color: #ffffff;
107
- }
108
- .main {
109
- background-color: #333333;
110
- padding: 20px;
111
- border-radius: 10px;
112
- }
113
  </style>
114
  """,
115
  unsafe_allow_html=True
@@ -120,25 +98,22 @@ def main():
120
 
121
  if not st.session_state.uploaded:
122
  # Upload Page
123
- st.title("Your personal assistant ...")
124
- pdf_docs = st.file_uploader("فایل پی دی اف مورد نظر را آپلود کنید ", accept_multiple_files=True)
125
  if st.button("تایید"):
126
  if pdf_docs:
127
- try:
128
- st.info("در حال پردازش ...")
129
- raw_text = get_pdf_text(pdf_docs)
130
- text_chunks = get_text_chunks(raw_text)
131
- get_vector_store(text_chunks)
132
- st.session_state.uploaded = True
133
- st.success("پردازش موفق شد ✅")
134
- except RuntimeError as e:
135
- st.error(str(e))
136
  else:
137
- st.error("لطفا حداقل یک فایل را آپلود کنید")
138
  else:
139
  # Chat Page
140
- st.title("Assistant ready ...")
141
- st.write("میتونین سوالتونو بپرسین 👇")
142
 
143
  if st.button("بازگشت به صفحه آپلود"):
144
  st.session_state.uploaded = False
@@ -153,44 +128,28 @@ def main():
153
  # Show history
154
  for message in st.session_state.messages:
155
  with st.chat_message(message["role"]):
156
- st.markdown(
157
- f"""
158
- <div style="direction: rtl; text-align: right; font-size: 16px;">
159
- {message["content"]}
160
- </div>
161
- """,
162
- unsafe_allow_html=True
163
- )
164
 
165
  if prompt := st.chat_input():
166
  st.session_state.messages.append({"role": "user", "content": prompt})
167
  with st.chat_message("user"):
168
- st.markdown(
169
- f"""
170
- <div style="direction: rtl; text-align: right; font-size: 16px;">
171
- {prompt}
172
- </div>
173
- """,
174
- unsafe_allow_html=True
175
- )
176
 
177
  if st.session_state.messages[-1]["role"] != "assistant":
178
- try:
179
- with st.chat_message("assistant"):
180
- response = user_input(prompt)
181
- if response:
182
- full_response = response['output_text']
183
- st.markdown(
184
- f"""
185
- <div style="direction: rtl; text-align: right; font-size: 16px;">
186
- {full_response}
187
- </div>
188
- """,
189
- unsafe_allow_html=True
190
- )
191
- st.session_state.messages.append({"role": "assistant", "content": full_response})
192
- except RuntimeError as e:
193
- st.error(str(e))
194
 
195
 
196
  if __name__ == "__main__":
 
17
  genai.configure(api_key=api_key)
18
 
19
 
20
+ # ✅ Read all PDFs (supports Farsi + English)
21
  def get_pdf_text(pdf_docs):
22
  text = ""
23
  for pdf in pdf_docs:
 
29
  return text
30
 
31
 
32
+ # ✅ Split text into chunks
33
  def get_text_chunks(text):
34
  splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
35
+ return splitter.split_text(text)
 
36
 
37
 
38
+ # ✅ Get embeddings + save vector store
39
  def get_vector_store(chunks):
40
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/text-embedding-004")
41
+ vector_store = FAISS.from_texts(chunks, embedding=embeddings)
42
+ vector_store.save_local("faiss_index")
 
 
 
43
 
44
 
45
+ # ✅ Conversational chain
46
  def get_conversational_chain():
47
  prompt_template = """
48
+ شما یک دستیار هوشمند هستید. لطفاً فقط بر اساس متن موجود در زمینه پاسخ دهید.
49
+ اگر پاسخ دقیق در متن نبود، بگویید: "اطلاعات کافی در متن موجود نیست".
50
+ از اضافه‌گویی یا ساختن جواب خودداری کنید.
 
51
 
52
+ --- زمینه:
53
  {context}
54
 
55
+ --- سوال:
56
  {question}
57
 
58
+ --- پاسخ:
59
  """
60
+ model = ChatGoogleGenerativeAI(model="gemini-2.5-pro", client=genai, temperature=0.3)
61
+ prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
62
+ chain = load_qa_chain(llm=model, chain_type="map_reduce", prompt=prompt)
63
+ return chain
 
 
 
64
 
65
 
66
+ # ✅ Clear history
67
  def clear_chat_history():
68
  st.session_state.messages = [{"role": "assistant", "content": "در خدمتیم"}]
69
 
70
 
71
+ # ✅ Handle user input
72
  def user_input(user_question):
73
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/text-embedding-004")
74
+ new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
75
+ docs = new_db.similarity_search(user_question, k=8) # ⬅️ بیشتر شده
76
+ chain = get_conversational_chain()
77
+ response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
78
+ return response
79
+
80
+
81
+ # Main Streamlit app
 
 
 
82
  def main():
83
+ st.set_page_config(page_title="Chatbot", layout="wide", initial_sidebar_state="expanded")
 
 
 
 
84
 
 
85
  st.markdown(
86
  """
87
  <style>
88
+ body { background-color: #000000; color: #ffffff; }
89
+ .main { background-color: #333333; padding: 20px; border-radius: 10px; }
90
+ .rtl { direction: rtl; text-align: right; }
 
 
 
 
 
 
91
  </style>
92
  """,
93
  unsafe_allow_html=True
 
98
 
99
  if not st.session_state.uploaded:
100
  # Upload Page
101
+ st.title("دستیار شخصی شما ...")
102
+ pdf_docs = st.file_uploader("فایل(های) PDF را آپلود کنید", accept_multiple_files=True)
103
  if st.button("تایید"):
104
  if pdf_docs:
105
+ st.info("در حال پردازش ...")
106
+ raw_text = get_pdf_text(pdf_docs)
107
+ text_chunks = get_text_chunks(raw_text)
108
+ get_vector_store(text_chunks)
109
+ st.session_state.uploaded = True
110
+ st.success("پردازش موفق شد ✅")
 
 
 
111
  else:
112
+ st.error("لطفاً حداقل یک فایل انتخاب کنید")
113
  else:
114
  # Chat Page
115
+ st.title("دستیار آماده است ...")
116
+ st.write("سؤالتان را بپرسید 👇")
117
 
118
  if st.button("بازگشت به صفحه آپلود"):
119
  st.session_state.uploaded = False
 
128
  # Show history
129
  for message in st.session_state.messages:
130
  with st.chat_message(message["role"]):
131
+ # تشخیص ساده فارسی برای نمایش راست به چپ
132
+ if any("\u0600" <= ch <= "\u06FF" for ch in message["content"]):
133
+ st.markdown(f"<div class='rtl'>{message['content']}</div>", unsafe_allow_html=True)
134
+ else:
135
+ st.write(message["content"])
 
 
 
136
 
137
  if prompt := st.chat_input():
138
  st.session_state.messages.append({"role": "user", "content": prompt})
139
  with st.chat_message("user"):
140
+ st.markdown(f"<div class='rtl'>{prompt}</div>", unsafe_allow_html=True) if any(
141
+ "\u0600" <= ch <= "\u06FF" for ch in prompt) else st.write(prompt)
 
 
 
 
 
 
142
 
143
  if st.session_state.messages[-1]["role"] != "assistant":
144
+ with st.chat_message("assistant"):
145
+ response = user_input(prompt)
146
+ if response:
147
+ full_response = response['output_text']
148
+ if any("\u0600" <= ch <= "\u06FF" for ch in full_response):
149
+ st.markdown(f"<div class='rtl'>{full_response}</div>", unsafe_allow_html=True)
150
+ else:
151
+ st.write(full_response)
152
+ st.session_state.messages.append({"role": "assistant", "content": full_response})
 
 
 
 
 
 
 
153
 
154
 
155
  if __name__ == "__main__":