M17idd commited on
Commit
b8fecc5
·
verified ·
1 Parent(s): c615e88

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -41
app.py CHANGED
@@ -103,91 +103,70 @@ st.markdown("""
103
  def get_pdf_index():
104
  with st.spinner('📄 در حال پردازش فایل PDF...'):
105
  loader = PyPDFLoader('test1.pdf')
106
- documents = loader.load()
107
 
108
  splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=128)
109
- texts = []
110
- for doc in documents:
111
- texts.extend(splitter.split_text(doc.page_content))
112
 
113
 
114
  embedding_function = SentenceTransformer("togethercomputer/m2-bert-80M-8k-retrieval", trust_remote_code=True)
115
 
116
- vectorstore_index_creator = VectorstoreIndexCreator(
117
- vectorstore_cls=FAISS,
118
- embedding_function=embedding_function
119
- )
120
 
121
- index = vectorstore_index_creator.from_documents([Document(page_content=text) for text in texts])
122
-
123
- return index
 
124
 
125
  # ----------------- بارگذاری دیتا -----------------
126
- documents, embeddings, index, model = get_pdf_index()
127
-
128
- retriever = SimpleRetriever(
129
- documents=documents,
130
- embeddings=embeddings,
131
- index=index,
132
- model=model
133
- )
134
 
135
- # ----------------- تعریف LLM -----------------
136
  llm = ChatOpenAI(
137
  base_url="https://api.together.xyz/v1",
138
  api_key='0291f33aee03412a47fa5d8e562e515182dcc5d9aac5a7fb5eefdd1759005979',
139
  model="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free"
140
  )
141
 
142
- # ----------------- ساخت Chain -----------------
143
- qa_chain = RetrievalQA.from_chain_type(
144
  llm=llm,
145
- retriever=retriever,
146
- chain_type="stuff",
147
- chain_type_kwargs={"prompt": custom_prompt}
148
  )
149
 
150
- # ----------------- چت استیت -----------------
151
  if 'messages' not in st.session_state:
152
  st.session_state.messages = []
153
 
154
  if 'pending_prompt' not in st.session_state:
155
  st.session_state.pending_prompt = None
156
 
157
- # ----------------- نمایش پیام‌های قبلی -----------------
158
  for msg in st.session_state.messages:
159
  with st.chat_message(msg['role']):
160
  st.markdown(f"🗨️ {msg['content']}", unsafe_allow_html=True)
161
 
162
- # ----------------- ورودی کاربر -----------------
163
- prompt = st.chat_input("سوالی در مورد فایل بپرس...")
164
 
165
  if prompt:
166
  st.session_state.messages.append({'role': 'user', 'content': prompt})
167
  st.session_state.pending_prompt = prompt
168
  st.rerun()
169
 
170
- # ----------------- پاسخ‌دهی مدل -----------------
171
  if st.session_state.pending_prompt:
172
  with st.chat_message('ai'):
173
  thinking = st.empty()
174
  thinking.markdown("🤖 در حال فکر کردن...")
175
 
176
- try:
177
- # اگر مدل نتواند پاسخ دقیقی پیدا کند
178
- response = qa_chain.run(st.session_state.pending_prompt)
179
- if not response.strip(): # اگر پاسخ خالی یا بی‌فایده بود
180
- response = "متاسفانه اطلاعات دقیقی برای پاسخ به این سوال موجود نیست."
181
- else:
182
- response = response.strip()
183
- except Exception as e:
184
- response = "متاسفانه اطلاعات لازم برای پاسخ به این سوال موجود نیست."
185
 
186
  thinking.empty()
187
-
188
  full_response = ""
189
  placeholder = st.empty()
190
- for word in response.split():
191
  full_response += word + " "
192
  placeholder.markdown(full_response + "▌")
193
  time.sleep(0.03)
@@ -195,3 +174,4 @@ if st.session_state.pending_prompt:
195
  placeholder.markdown(full_response)
196
  st.session_state.messages.append({'role': 'ai', 'content': full_response})
197
  st.session_state.pending_prompt = None
 
 
103
  def get_pdf_index():
104
  with st.spinner('📄 در حال پردازش فایل PDF...'):
105
  loader = PyPDFLoader('test1.pdf')
106
+ # documents = loader.load()
107
 
108
  splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=128)
109
+ # texts = []
110
+ # for doc in documents:
111
+ # texts.extend(splitter.split_text(doc.page_content))
112
 
113
 
114
  embedding_function = SentenceTransformer("togethercomputer/m2-bert-80M-8k-retrieval", trust_remote_code=True)
115
 
116
+ # ctorstore_index_creator.from_documents([Document(page_content=text) for text in texts])
 
 
 
117
 
118
+ return VectorstoreIndexCreator(
119
+ embedding=embedding_function,
120
+ text_splitter=splitter
121
+ ).from_loaders(loader)
122
 
123
  # ----------------- بارگذاری دیتا -----------------
124
+ index = get_pdf_index()
 
 
 
 
 
 
 
125
 
 
126
  llm = ChatOpenAI(
127
  base_url="https://api.together.xyz/v1",
128
  api_key='0291f33aee03412a47fa5d8e562e515182dcc5d9aac5a7fb5eefdd1759005979',
129
  model="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free"
130
  )
131
 
132
+ chain = RetrievalQA.from_chain_type(
 
133
  llm=llm,
134
+ chain_type='stuff',
135
+ retriever=index.vectorstore.as_retriever(),
136
+ input_key='question'
137
  )
138
 
 
139
  if 'messages' not in st.session_state:
140
  st.session_state.messages = []
141
 
142
  if 'pending_prompt' not in st.session_state:
143
  st.session_state.pending_prompt = None
144
 
 
145
  for msg in st.session_state.messages:
146
  with st.chat_message(msg['role']):
147
  st.markdown(f"🗨️ {msg['content']}", unsafe_allow_html=True)
148
 
149
+ prompt = st.chat_input("چطور می‌تونم کمک کنم؟")
 
150
 
151
  if prompt:
152
  st.session_state.messages.append({'role': 'user', 'content': prompt})
153
  st.session_state.pending_prompt = prompt
154
  st.rerun()
155
 
 
156
  if st.session_state.pending_prompt:
157
  with st.chat_message('ai'):
158
  thinking = st.empty()
159
  thinking.markdown("🤖 در حال فکر کردن...")
160
 
161
+ response = chain.run(f'پاسخ را فقط به زبان فارسی جواب بده. سوال: {st.session_state.pending_prompt}')
162
+ answer = response.split("Helpful Answer:")[-1].strip()
163
+ if not answer:
164
+ answer = "متأسفم، اطلاعات دقیقی در این مورد ندارم."
 
 
 
 
 
165
 
166
  thinking.empty()
 
167
  full_response = ""
168
  placeholder = st.empty()
169
+ for word in answer.split():
170
  full_response += word + " "
171
  placeholder.markdown(full_response + "▌")
172
  time.sleep(0.03)
 
174
  placeholder.markdown(full_response)
175
  st.session_state.messages.append({'role': 'ai', 'content': full_response})
176
  st.session_state.pending_prompt = None
177
+