M17idd commited on
Commit
f656688
·
verified ·
1 Parent(s): 9e2e699

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -65
app.py CHANGED
@@ -11,13 +11,6 @@ from typing import List
11
  from together import Together
12
  import pandas as pd
13
  import streamlit as st
14
- from sklearn.metrics.pairwise import cosine_similarity
15
-
16
-
17
- import numpy as np
18
- from sentence_transformers import SentenceTransformer
19
- import faiss
20
-
21
 
22
  # ----------------- تنظیمات صفحه -----------------
23
  st.set_page_config(page_title="رزم یار ارتش", page_icon="🪖", layout="wide")
@@ -188,46 +181,93 @@ st.markdown('<div class="chat-message">👋 سلام! چطور میتونم کم
188
 
189
 
190
 
 
 
 
 
 
191
 
192
- # ⚙️ مدل Embedding ساده و سریع
193
- @st.cache_resource
194
- def get_embedding_model():
195
- return SentenceTransformer("HooshvareLab/bert-fa-zwnj-base")
196
-
197
- @st.cache_resource
198
- def process_csv(csv_file):
199
- df = pd.read_csv(csv_file)
200
- texts = df.iloc[:, 0].astype(str).tolist()
201
- texts = [text for text in texts if text.strip()]
202
 
203
- text_splitter = RecursiveCharacterTextSplitter(
204
- chunk_size=200,
205
- chunk_overlap=50,
206
- length_function=len,
207
- separators=["\n\n", "\n", " ", ""]
208
- )
209
 
210
- split_texts = []
211
- for text in texts:
212
- split_texts.extend(text_splitter.split_text(text))
213
-
214
- # مدل امبدینگ
215
- model = get_embedding_model()
216
- embeddings = model.encode(split_texts, show_progress_bar=True)
217
-
218
- dim = embeddings.shape[1]
219
- index = faiss.IndexHNSWFlat(dim, 32)
220
- index.hnsw.efSearch = 50
221
- index.add(np.array(embeddings))
222
 
223
- return split_texts, embeddings, index
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
  # مسیر فایل CSV
226
  csv_file_path = 'output (1).csv'
227
 
228
- texts, vectors, index = process_csv(csv_file_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
 
230
- # رابط چت
231
  if 'messages' not in st.session_state:
232
  st.session_state.messages = []
233
 
@@ -236,46 +276,33 @@ if 'pending_prompt' not in st.session_state:
236
 
237
  for msg in st.session_state.messages:
238
  with st.chat_message(msg['role']):
239
- st.markdown(msg['content'], unsafe_allow_html=True)
240
 
241
- query = st.chat_input("سؤالت را بپرس...")
242
 
243
- if query:
244
- st.session_state.messages.append({'role': 'user', 'content': query})
245
- st.session_state.pending_prompt = query
246
  st.rerun()
247
 
248
  if st.session_state.pending_prompt:
249
- with st.chat_message("ai"):
250
  thinking = st.empty()
251
- thinking.markdown("🤖 در حال جستجو...")
252
 
253
- model = get_embedding_model()
254
- query_vector = model.encode([st.session_state.pending_prompt])
255
-
256
- D, I = index.search(np.array(query_vector), k=10)
257
-
258
- top_indices = I[0]
259
- top_texts = [texts[i] for i in top_indices]
260
- top_vectors = np.array([vectors[i] for i in top_indices])
261
-
262
-
263
- similarities = cosine_similarity(query_vector, top_vectors)[0]
264
-
265
- # پیدا کردن دقیق‌ترین متن
266
- best_match_relative_index = np.argmax(similarities)
267
- best_match_index = top_indices[best_match_relative_index]
268
- best_match_text = texts[best_match_index]
269
- response = "🧠 پاسخ سوال :\n\n" .join(best_match_text)
270
 
271
  thinking.empty()
272
  full_response = ""
273
  placeholder = st.empty()
274
- for word in response.split():
275
  full_response += word + " "
276
  placeholder.markdown(full_response + "▌")
277
- time.sleep(0.02)
278
 
279
  placeholder.markdown(full_response)
280
  st.session_state.messages.append({'role': 'ai', 'content': full_response})
281
- st.session_state.pending_prompt = None
 
11
  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")
 
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=2048,
218
+ chunk_overlap=256,
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="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free"
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
 
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