M17idd commited on
Commit
d9bc83c
·
verified ·
1 Parent(s): 77480ff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -91
app.py CHANGED
@@ -12,6 +12,12 @@ from together import Together
12
  import pandas as pd
13
  import streamlit as st
14
 
 
 
 
 
 
 
15
  # ----------------- تنظیمات صفحه -----------------
16
  st.set_page_config(page_title="رزم یار ارتش", page_icon="🪖", layout="wide")
17
 
@@ -181,93 +187,50 @@ st.markdown('<div class="chat-message">👋 سلام! چطور میتونم کم
181
 
182
 
183
 
184
- # ----------------- لود csv و ساخت ایندکس -----------------
185
- class TogetherEmbeddings(Embeddings):
186
- def __init__(self, model_name: str, api_key: str):
187
- self.model_name = model_name
188
- self.client = Together(api_key=api_key)
189
-
190
- def embed_documents(self, texts: List[str]) -> List[List[float]]:
191
- # تقسیم متن‌ها به دسته‌های کوچک‌تر برای جلوگیری از خطای 413
192
- batch_size = 100 # این مقدار را می‌توانید تنظیم کنید
193
- embeddings = []
194
- for i in range(0, len(texts), batch_size):
195
- batch = texts[i:i + batch_size]
196
- response = self.client.embeddings.create(model=self.model_name, input=batch)
197
- embeddings.extend([item.embedding for item in response.data])
198
- return embeddings
199
 
200
- def embed_query(self, text: str) -> List[float]:
201
- return self.embed_documents([text])[0]
 
 
202
 
203
  @st.cache_resource
204
- def get_csv_index(csv_file):
205
- with st.spinner('📄 در حال پردازش فایل CSV...'):
206
- # خواندن داده‌های CSV
207
- df = pd.read_csv(csv_file)
208
-
209
- # تبدیل DataFrame به لیست از متون
210
- texts = df.iloc[:, 0].astype(str).tolist() # ستون اول را می‌گیرد
211
-
212
- # فیلتر کردن متن‌های خالی
213
- texts = [text for text in texts if text.strip()]
214
-
215
- # تقسیم متن‌های طولانی به بخش‌های کوچکتر
216
- text_splitter = RecursiveCharacterTextSplitter(
217
- chunk_size=300,
218
- chunk_overlap=50,
219
- length_function=len,
220
- separators=["\n\n", "\n", " ", ""]
221
- )
222
-
223
- split_texts = []
224
- for text in texts:
225
- split_texts.extend(text_splitter.split_text(text))
226
-
227
- # ایجاد embeddings
228
- embeddings = TogetherEmbeddings(
229
- model_name="togethercomputer/m2-bert-80M-8k-retrieval",
230
- api_key="0291f33aee03412a47fa5d8e562e515182dcc5d9aac5a7fb5eefdd1759005979"
231
- )
232
-
233
- # استفاده از VectorstoreIndexCreator برای ساخت ایندکس
234
- index_creator = VectorstoreIndexCreator(
235
- embedding=embeddings,
236
- text_splitter=text_splitter
237
- )
238
-
239
- # تبدیل متون به اسناد (documents)
240
- from langchain.docstore.document import Document
241
- documents = [Document(page_content=text) for text in split_texts]
242
-
243
- return index_creator.from_documents(documents)
244
 
245
  # مسیر فایل CSV
246
  csv_file_path = 'output (1).csv'
247
 
248
  try:
249
- # ساخت ایندکس
250
- csv_index = get_csv_index(csv_file_path)
251
- st.success("ایندکس فایل CSV با موفقیت ساخته شد!")
252
  except Exception as e:
253
- st.error(f"خطا در ساخت ایندکس: {str(e)}")
254
-
255
-
256
-
257
- #------------------------------------------
258
- llm = ChatOpenAI(
259
- base_url="https://api.together.xyz/v1",
260
- api_key='0291f33aee03412a47fa5d8e562e515182dcc5d9aac5a7fb5eefdd1759005979',
261
- model="togethercomputer/m2-bert-80M-8k-retrieval"
262
- )
263
-
264
- chain = RetrievalQA.from_chain_type(
265
- llm=llm,
266
- chain_type='stuff',
267
- retriever=csv_index.vectorstore.as_retriever(),
268
- input_key='question'
269
- )
270
 
 
271
  if 'messages' not in st.session_state:
272
  st.session_state.messages = []
273
 
@@ -276,33 +239,36 @@ if 'pending_prompt' not in st.session_state:
276
 
277
  for msg in st.session_state.messages:
278
  with st.chat_message(msg['role']):
279
- st.markdown(f"🗨️ {msg['content']}", unsafe_allow_html=True)
280
 
281
- prompt = st.chat_input("چطور می‌تونم کمک کنم؟")
282
 
283
- if prompt:
284
- st.session_state.messages.append({'role': 'user', 'content': prompt})
285
- st.session_state.pending_prompt = prompt
286
  st.rerun()
287
 
288
  if st.session_state.pending_prompt:
289
- with st.chat_message('ai'):
290
  thinking = st.empty()
291
- thinking.markdown("🤖 در حال فکر کردن...")
 
 
 
 
 
292
 
293
- response = chain.run(f'پاسخ را فقط به زبان فارسی جواب بده و به هیچ عنوان از زبان غیر از فارسی در پاسخ استفاده نکن: {st.session_state.pending_prompt}')
294
- answer = response.split("Helpful Answer:")[-1].strip() if "Helpful Answer:" in response else response.strip()
295
- if not answer:
296
- answer = "متأسفم، اطلاعات دقیقی در این مورد ندارم."
297
 
298
  thinking.empty()
299
  full_response = ""
300
  placeholder = st.empty()
301
- for word in answer.split():
302
  full_response += word + " "
303
  placeholder.markdown(full_response + "▌")
304
- time.sleep(0.03)
305
 
306
  placeholder.markdown(full_response)
307
  st.session_state.messages.append({'role': 'ai', 'content': full_response})
308
- st.session_state.pending_prompt = None
 
12
  import pandas as pd
13
  import streamlit as st
14
 
15
+
16
+ import numpy as np
17
+ from sentence_transformers import SentenceTransformer
18
+ import faiss
19
+
20
+
21
  # ----------------- تنظیمات صفحه -----------------
22
  st.set_page_config(page_title="رزم یار ارتش", page_icon="🪖", layout="wide")
23
 
 
187
 
188
 
189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
+ # ⚙️ مدل Embedding ساده و سریع
192
+ @st.cache_resource
193
+ def get_embedding_model():
194
+ return SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
195
 
196
  @st.cache_resource
197
+ def process_csv(csv_file):
198
+ df = pd.read_csv(csv_file)
199
+ texts = df.iloc[:, 0].astype(str).tolist()
200
+ texts = [text for text in texts if text.strip()]
201
+
202
+ text_splitter = RecursiveCharacterTextSplitter(
203
+ chunk_size=300,
204
+ chunk_overlap=50,
205
+ length_function=len,
206
+ separators=["\n\n", "\n", " ", ""]
207
+ )
208
+
209
+ split_texts = []
210
+ for text in texts:
211
+ split_texts.extend(text_splitter.split_text(text))
212
+
213
+ # مدل امبدینگ
214
+ model = get_embedding_model()
215
+ embeddings = model.encode(split_texts, show_progress_bar=True)
216
+
217
+ # ساخت ایندکس FAISS
218
+ dim = embeddings.shape[1]
219
+ index = faiss.IndexFlatL2(dim)
220
+ index.add(np.array(embeddings))
221
+
222
+ return split_texts, embeddings, index
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
 
224
  # مسیر فایل CSV
225
  csv_file_path = 'output (1).csv'
226
 
227
  try:
228
+ texts, vectors, index = process_csv(csv_file_path)
229
+ st.success("✅ ایندکس‌سازی با موفقیت انجام شد.")
 
230
  except Exception as e:
231
+ st.error(f"خطا در پردازش فایل: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
 
233
+ # رابط چت
234
  if 'messages' not in st.session_state:
235
  st.session_state.messages = []
236
 
 
239
 
240
  for msg in st.session_state.messages:
241
  with st.chat_message(msg['role']):
242
+ st.markdown(msg['content'], unsafe_allow_html=True)
243
 
244
+ query = st.chat_input("سؤالت را بپرس...")
245
 
246
+ if query:
247
+ st.session_state.messages.append({'role': 'user', 'content': query})
248
+ st.session_state.pending_prompt = query
249
  st.rerun()
250
 
251
  if st.session_state.pending_prompt:
252
+ with st.chat_message("ai"):
253
  thinking = st.empty()
254
+ thinking.markdown("🤖 در حال جستجو...")
255
+
256
+ # امبد کردن سؤال و جستجو
257
+ model = get_embedding_model()
258
+ query_vector = model.encode([st.session_state.pending_prompt])
259
+ D, I = index.search(np.array(query_vector), k=3) # 3 نتیجه نزدیک
260
 
261
+ results = [texts[i] for i in I[0]]
262
+ response = "🧠 نزدیک‌ترین پاسخ‌ها:\n\n" + "\n\n---\n\n".join(results)
 
 
263
 
264
  thinking.empty()
265
  full_response = ""
266
  placeholder = st.empty()
267
+ for word in response.split():
268
  full_response += word + " "
269
  placeholder.markdown(full_response + "▌")
270
+ time.sleep(0.02)
271
 
272
  placeholder.markdown(full_response)
273
  st.session_state.messages.append({'role': 'ai', 'content': full_response})
274
+ st.session_state.pending_prompt = None