aelsaeed commited on
Commit
7daad2c
·
verified ·
1 Parent(s): 10f7e62

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -47
app.py CHANGED
@@ -5,7 +5,6 @@ import numpy as np
5
  import os, tempfile, re
6
  import gdown
7
 
8
- from sentence_transformers import SentenceTransformer, util
9
  from sklearn.feature_extraction.text import TfidfVectorizer
10
  from sklearn.metrics.pairwise import cosine_similarity
11
 
@@ -18,12 +17,6 @@ DRIVE_THESES_ID = "1hvZIGFG6h0kQY32bIuEWGRdXTZp84vhk"
18
 
19
  TOP_K = 20
20
  TFIDF_TOP_N = 120
21
- TFIDF_FALLBACK_MIN = 30
22
-
23
- # ================== تحميل نموذج Semantic ==================
24
- print("Loading semantic model...")
25
- model = SentenceTransformer("all-MiniLM-L6-v2")
26
- print("Semantic model loaded successfully.")
27
 
28
  # ================== تحميل الملفات ==================
29
  def download_from_drive(file_id, output):
@@ -107,22 +100,34 @@ def row_to_text(row):
107
  print("Preparing searchable text...")
108
  library_df["search_text"] = library_df.apply(row_to_text, axis=1)
109
 
110
- # ================== بناء TF-IDF مرة واحدة ==================
111
  print("Building TF-IDF index...")
112
  tfidf_vectorizer = TfidfVectorizer(ngram_range=(1, 2), max_features=20000)
113
  tfidf_matrix = tfidf_vectorizer.fit_transform(library_df["search_text"].tolist())
114
  print("TF-IDF ready.")
115
 
116
- # ================== Embeddings ==================
117
- print("Generating embeddings...")
118
- embeddings = model.encode(
119
- library_df["search_text"].tolist(),
120
- convert_to_numpy=True,
121
- normalize_embeddings=True,
122
- show_progress_bar=True
123
- )
124
- library_df["embedding"] = list(embeddings)
125
- print("Embeddings ready.")
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
  # ================== CSS ==================
128
  CUSTOM_CSS = """
@@ -175,13 +180,22 @@ body {
175
  border-radius:10px;
176
  font-size:16px;
177
  }
 
 
 
 
 
 
 
 
 
178
  </style>
179
  """
180
 
181
  def safe(v):
182
  return "-" if pd.isna(v) or str(v).strip() == "" else str(v)
183
 
184
- def results_to_html(df, query="", mode="", source_filter=""):
185
  if df.empty:
186
  return CUSTOM_CSS + """
187
  <div class="empty">
@@ -195,7 +209,11 @@ def results_to_html(df, query="", mode="", source_filter=""):
195
  </div>
196
  """
197
 
198
- html = f"""
 
 
 
 
199
  <div class="meta">
200
  ✅ تم العثور على {len(df)} نتيجة
201
  {' | نوع البحث: ' + mode if mode else ''}
@@ -249,43 +267,43 @@ def text_search(df, query):
249
 
250
  return result.head(TOP_K)
251
 
252
- # ================== البحث الدلالي ==================
253
  def semantic_search(df, query):
254
- if df.empty:
255
- return df
256
-
257
  q = normalize_text(query)
258
- if not q:
259
- return df.iloc[0:0]
260
 
261
- # فلترة أولية بـ TF-IDF من الـ dataset الكامل
262
  q_vec = tfidf_vectorizer.transform([q])
263
  tfidf_scores = cosine_similarity(q_vec, tfidf_matrix)[0]
264
 
265
  temp_df = library_df.copy()
266
  temp_df["tfidf_score"] = tfidf_scores
267
 
268
- # فلترة حسب المصدر لو لزم
269
  if "المصدر" in df.columns and len(df) != len(library_df):
270
  temp_df = temp_df[temp_df.index.isin(df.index)]
271
 
272
  df_pref = temp_df.sort_values("tfidf_score", ascending=False).head(TFIDF_TOP_N)
273
 
274
  if df_pref.empty:
275
- return df.iloc[0:0]
276
 
277
- try:
278
- q_emb = model.encode([q], normalize_embeddings=True)
279
- mat = np.vstack(df_pref["embedding"].values)
280
- scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
281
-
282
- df_pref = df_pref.copy()
283
- df_pref["score"] = scores
284
- result = df_pref.sort_values("score", ascending=False).head(TOP_K)
285
- return result
286
- except Exception as e:
287
- print("Semantic search error:", e)
288
- return df_pref.head(TOP_K)
 
 
 
 
289
 
290
  # ================== البحث العام ==================
291
  def local_search_df(query, mode, source_filter):
@@ -301,13 +319,14 @@ def local_search_df(query, mode, source_filter):
301
  return CUSTOM_CSS + '<div class="empty">❌ لا توجد بيانات متاحة لهذا المصدر</div>', pd.DataFrame()
302
 
303
  try:
 
304
  if mode == "نصي":
305
  result_df = text_search(df, query)
306
  else:
307
- result_df = semantic_search(df, query)
308
 
309
- clean_df = result_df.drop(columns=["embedding"], errors="ignore")
310
- return results_to_html(result_df, query, mode, source_filter), clean_df
311
 
312
  except Exception as e:
313
  print("Search error:", e)
@@ -334,7 +353,7 @@ with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
334
 
335
  with gr.Row():
336
  query = gr.Textbox(label="كلمة أو موضوع البحث", placeholder="مثال: الذكاء الاصطناعي، الفهرسة، المكتبات الرقمية")
337
-
338
  with gr.Row():
339
  mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="نصي", label="نوع البحث")
340
  source_filter = gr.Radio(["الكل", "كتاب", "رسالة"], value="الكل", label="المصدر")
@@ -350,8 +369,7 @@ with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
350
  btn.click(local_search_df, [query, mode, source_filter], [out_html, df_state])
351
  save_btn.click(save_to_excel, df_state, file_out)
352
 
353
- app.launch(server_name="0.0.0.0")
354
-
355
 
356
 
357
 
 
5
  import os, tempfile, re
6
  import gdown
7
 
 
8
  from sklearn.feature_extraction.text import TfidfVectorizer
9
  from sklearn.metrics.pairwise import cosine_similarity
10
 
 
17
 
18
  TOP_K = 20
19
  TFIDF_TOP_N = 120
 
 
 
 
 
 
20
 
21
  # ================== تحميل الملفات ==================
22
  def download_from_drive(file_id, output):
 
100
  print("Preparing searchable text...")
101
  library_df["search_text"] = library_df.apply(row_to_text, axis=1)
102
 
103
+ # ================== بناء TF-IDF مرة واحدة فقط ==================
104
  print("Building TF-IDF index...")
105
  tfidf_vectorizer = TfidfVectorizer(ngram_range=(1, 2), max_features=20000)
106
  tfidf_matrix = tfidf_vectorizer.fit_transform(library_df["search_text"].tolist())
107
  print("TF-IDF ready.")
108
 
109
+ # ================== تحميل الـ Semantic Model عند الحاجة فقط ==================
110
+ semantic_model = None
111
+ embeddings_cache = None
112
+
113
+ def load_semantic_resources():
114
+ global semantic_model, embeddings_cache
115
+
116
+ if semantic_model is None:
117
+ print("Loading semantic model lazily...")
118
+ from sentence_transformers import SentenceTransformer
119
+ semantic_model = SentenceTransformer("sentence-transformers/paraphrase-MiniLM-L3-v2")
120
+ print("Semantic model loaded.")
121
+
122
+ if embeddings_cache is None:
123
+ print("Generating embeddings lazily...")
124
+ embeddings_cache = semantic_model.encode(
125
+ library_df["search_text"].tolist(),
126
+ convert_to_numpy=True,
127
+ normalize_embeddings=True,
128
+ show_progress_bar=True
129
+ )
130
+ print("Embeddings ready.")
131
 
132
  # ================== CSS ==================
133
  CUSTOM_CSS = """
 
180
  border-radius:10px;
181
  font-size:16px;
182
  }
183
+ .note{
184
+ background:#f0f9ff;
185
+ color:#0c4a6e;
186
+ border:1px solid #bae6fd;
187
+ padding:12px;
188
+ border-radius:10px;
189
+ font-size:15px;
190
+ margin-bottom:12px;
191
+ }
192
  </style>
193
  """
194
 
195
  def safe(v):
196
  return "-" if pd.isna(v) or str(v).strip() == "" else str(v)
197
 
198
+ def results_to_html(df, query="", mode="", source_filter="", extra_note=""):
199
  if df.empty:
200
  return CUSTOM_CSS + """
201
  <div class="empty">
 
209
  </div>
210
  """
211
 
212
+ html = ""
213
+ if extra_note:
214
+ html += f'<div class="note">{extra_note}</div>'
215
+
216
+ html += f"""
217
  <div class="meta">
218
  ✅ تم العثور على {len(df)} نتيجة
219
  {' | نوع البحث: ' + mode if mode else ''}
 
267
 
268
  return result.head(TOP_K)
269
 
270
+ # ================== البحث الدلالي الخفيف ==================
271
  def semantic_search(df, query):
 
 
 
272
  q = normalize_text(query)
273
+ if not q or df.empty:
274
+ return df.iloc[0:0], "⚠️ لم يتم إدخال استعلام صالح."
275
 
276
+ # 1) فلترة أولية سريعة بـ TF-IDF
277
  q_vec = tfidf_vectorizer.transform([q])
278
  tfidf_scores = cosine_similarity(q_vec, tfidf_matrix)[0]
279
 
280
  temp_df = library_df.copy()
281
  temp_df["tfidf_score"] = tfidf_scores
282
 
 
283
  if "المصدر" in df.columns and len(df) != len(library_df):
284
  temp_df = temp_df[temp_df.index.isin(df.index)]
285
 
286
  df_pref = temp_df.sort_values("tfidf_score", ascending=False).head(TFIDF_TOP_N)
287
 
288
  if df_pref.empty:
289
+ return df.iloc[0:0], "❌ لا توجد نتائج دلالية."
290
 
291
+ # 2) تحم��ل الموارد الثقيلة فقط عند أول مرة
292
+ load_semantic_resources()
293
+
294
+ # 3) حساب التشابه الدلالي فقط على أفضل المرشحين
295
+ from sentence_transformers import util
296
+
297
+ pref_embeddings = embeddings_cache[df_pref.index]
298
+ q_emb = semantic_model.encode([q], normalize_embeddings=True)
299
+ scores = util.cos_sim(q_emb, pref_embeddings)[0].cpu().numpy()
300
+
301
+ df_pref = df_pref.copy()
302
+ df_pref["score"] = scores
303
+ result = df_pref.sort_values("score", ascending=False).head(TOP_K)
304
+
305
+ note = "🧠 تم استخدام البحث الدلالي. أول تشغيل له قد يستغرق وقتًا أطول قليلاً، وبعدها يصبح أسرع."
306
+ return result, note
307
 
308
  # ================== البحث العام ==================
309
  def local_search_df(query, mode, source_filter):
 
319
  return CUSTOM_CSS + '<div class="empty">❌ لا توجد بيانات متاحة لهذا المصدر</div>', pd.DataFrame()
320
 
321
  try:
322
+ note = ""
323
  if mode == "نصي":
324
  result_df = text_search(df, query)
325
  else:
326
+ result_df, note = semantic_search(df, query)
327
 
328
+ clean_df = result_df.drop(columns=[], errors="ignore")
329
+ return results_to_html(result_df, query, mode, source_filter, note), clean_df
330
 
331
  except Exception as e:
332
  print("Search error:", e)
 
353
 
354
  with gr.Row():
355
  query = gr.Textbox(label="كلمة أو موضوع البحث", placeholder="مثال: الذكاء الاصطناعي، الفهرسة، المكتبات الرقمية")
356
+
357
  with gr.Row():
358
  mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="نصي", label="نوع البحث")
359
  source_filter = gr.Radio(["الكل", "كتاب", "رسالة"], value="الكل", label="المصدر")
 
369
  btn.click(local_search_df, [query, mode, source_filter], [out_html, df_state])
370
  save_btn.click(save_to_excel, df_state, file_out)
371
 
372
+ app.launch(server_name="0.0.0.0", server_port=7860)
 
373
 
374
 
375