aelsaeed commited on
Commit
2443249
·
verified ·
1 Parent(s): 36a0f16

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -58
app.py CHANGED
@@ -6,7 +6,6 @@ import os, tempfile, re
6
  from sentence_transformers import SentenceTransformer, util
7
  from sklearn.feature_extraction.text import TfidfVectorizer
8
  from sklearn.metrics.pairwise import cosine_similarity
9
- from fuzzywuzzy import fuzz
10
  import gdown
11
 
12
  # ================== إعدادات ==================
@@ -41,35 +40,8 @@ theses_df = pd.read_excel(THESES_FILE).fillna("")
41
  books_df["المصدر"] = "كتاب"
42
  theses_df["المصدر"] = "رسالة"
43
 
44
- # ================== استخراج الأقسام ==================
45
- current_section = ""
46
- sections = []
47
- for idx, row in theses_df.iterrows():
48
- first_col = str(row[0]).strip()
49
- if "جامعة" in first_col:
50
- current_section = first_col
51
- sections.append(current_section)
52
- theses_df["القسم"] = sections
53
-
54
  library_df = pd.concat([books_df, theses_df], ignore_index=True)
55
 
56
- # ================== الأعمدة الدلالية ==================
57
- def detect_semantic_columns(df):
58
- exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
59
- include = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "نوع درجة الرسالة العلمية ", "كلمات"]
60
- cols = []
61
- for c in df.columns:
62
- s = str(c)
63
- if any(x in s for x in exclude):
64
- continue
65
- if any(x in s for x in include):
66
- cols.append(c)
67
- if not cols:
68
- cols = df.select_dtypes(include="object").columns.tolist()
69
- return cols
70
-
71
- semantic_cols = detect_semantic_columns(library_df)
72
-
73
  # ================== Normalize ==================
74
  def normalize_text(text):
75
  text = str(text).lower()
@@ -78,28 +50,23 @@ def normalize_text(text):
78
  text = text.replace("ى", "ي").replace("ة", "ه")
79
  return re.sub(r"\s+", " ", text).strip()
80
 
 
 
 
81
  def row_to_text(row):
82
  text = " ".join(str(row[c]) for c in semantic_cols if row[c])
83
  text = normalize_text(text)
84
- # Boost للمصطلحات الطبية
85
- if any(x in text for x in ["cardio", "toxic", "toxicity"]):
86
- text += " cardiotoxicity cardiac toxicity cardiotoxic effects"
87
  return text
88
 
89
  # ================== Embeddings ==================
90
  texts = library_df.apply(row_to_text, axis=1).tolist()
91
- embeddings = model.encode(
92
- texts,
93
- convert_to_numpy=True,
94
- normalize_embeddings=True,
95
- show_progress_bar=True
96
- )
97
  library_df["embedding"] = list(embeddings)
98
 
99
  # ================== TF-IDF ==================
100
  def tfidf_prefilter(df, query):
101
  texts = df.apply(row_to_text, axis=1).tolist()
102
- vec = TfidfVectorizer(ngram_range=(1, 3), max_features=30000, stop_words="english")
103
  mat = vec.fit_transform(texts)
104
  q_vec = vec.transform([normalize_text(query)])
105
  scores = cosine_similarity(q_vec, mat)[0]
@@ -117,8 +84,7 @@ CUSTOM_CSS = """
117
  .row-title td{background:#e3f2fd;color:#0d47a1;font-weight:bold;}
118
  .row-author td{background:#fce4ec;color:#880e4f;}
119
  .row-year td{background:#e8f5e9;color:#1b5e20;}
120
- .row-degree td{background:#fff3e0;color:#ef6c00;font-weight:bold;}
121
- .row-section td{background:#f3e5f5;color:#6a1b9a;font-weight:bold;}
122
  .row-shelf td{background:#fff8e1;color:#e65100;font-weight:bold;font-size:16px;}
123
  </style>
124
  """
@@ -134,12 +100,26 @@ def results_to_html(df):
134
  html += f"""
135
  <div class="card">
136
  <table>
137
- <tr class="row-title"><td class="label">العنوان</td><td>{safe(r.get("العنوان"))}</td></tr>
138
- <tr class="row-author"><td class="label">المؤلف</td><td>{safe(r.get("المؤلف"))}</td></tr>
139
- <tr class="row-degree"><td class="label">نوع درجة الرسالة العلمية</td><td>{safe(r.get("نوع درجة الرسالة العلمية "))}</td></tr>
140
- <tr class="row-section"><td class="label">القسم</td><td>{safe(r.get("القسم"))}</td></tr>
141
- <tr class="row-year"><td class="label">سنة النشر</td><td>{safe(r.get("سنة النشر"))}</td></tr>
142
- <tr class="row-shelf"><td class="label">الموقع على الرف</td><td>{safe(r.get("الموقع على الرف"))}</td></tr>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  </table>
144
  </div>
145
  """
@@ -147,28 +127,37 @@ def results_to_html(df):
147
 
148
  # ================== البحث ==================
149
  def local_search_df(query, mode, category, year_from, year_to):
 
 
 
150
  df = library_df.copy()
 
 
151
  if category != "الكل":
152
- df = df[df["المصدر"] == category]
 
 
153
  if year_from:
154
- df = df[df["سنة النشر"].apply(lambda x: str(x).isdigit() and int(x) >= int(year_from))]
 
155
  if year_to:
156
- df = df[df["سنة النشر"].apply(lambda x: str(x).isdigit() and int(x) <= int(year_to))]
157
- if not query.strip():
158
- return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
159
- q_norm = normalize_text(query)
160
  if mode == "نصي":
161
- mask = df.apply(lambda r: fuzz.partial_ratio(q_norm, row_to_text(r)) > 70, axis=1)
 
162
  df = df[mask].head(TOP_K)
163
  else:
164
  df_pref = tfidf_prefilter(df, query)
165
  if len(df_pref) < TFIDF_FALLBACK_MIN:
166
  df_pref = df
167
- q_emb = model.encode([q_norm], normalize_embeddings=True)
168
  mat = np.vstack(df_pref["embedding"].values)
169
  scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
170
  df_pref["score"] = scores
171
  df = df_pref.sort_values("score", ascending=False).head(TOP_K)
 
172
  return results_to_html(df), df
173
 
174
  # ================== حفظ النتائج ==================
@@ -178,17 +167,22 @@ def save_to_excel(df):
178
  return tmp.name
179
 
180
  # ================== واجهة Gradio ==================
 
 
181
  with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
182
  gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
 
183
  query = gr.Textbox(label="كلمة أو موضوع البحث")
184
- mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="دلالي (Semantic)", label="نوع البحث")
185
- category = gr.Radio(["الكل", "كتاب", "رسالة"], value="الكل", label="اختر الفئة")
186
- year_from = gr.Textbox(label="من سنة", placeholder="مثال: 2010")
187
- year_to = gr.Textbox(label="إلى سنة", placeholder="مثال: 2025")
 
188
  btn = gr.Button("🔎 بحث")
189
  out_html = gr.HTML()
190
  df_state = gr.State()
191
  file_out = gr.File(label="⬇️ تحميل النتائج")
 
192
  btn.click(local_search_df, [query, mode, category, year_from, year_to], [out_html, df_state])
193
  gr.Button("📥 حفظ النتائج").click(save_to_excel, df_state, file_out)
194
 
 
6
  from sentence_transformers import SentenceTransformer, util
7
  from sklearn.feature_extraction.text import TfidfVectorizer
8
  from sklearn.metrics.pairwise import cosine_similarity
 
9
  import gdown
10
 
11
  # ================== إعدادات ==================
 
40
  books_df["المصدر"] = "كتاب"
41
  theses_df["المصدر"] = "رسالة"
42
 
 
 
 
 
 
 
 
 
 
 
43
  library_df = pd.concat([books_df, theses_df], ignore_index=True)
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  # ================== Normalize ==================
46
  def normalize_text(text):
47
  text = str(text).lower()
 
50
  text = text.replace("ى", "ي").replace("ة", "ه")
51
  return re.sub(r"\s+", " ", text).strip()
52
 
53
+ # ================== استخراج نصوص الصفوف ==================
54
+ semantic_cols = [c for c in library_df.columns if library_df[c].dtype == object]
55
+
56
  def row_to_text(row):
57
  text = " ".join(str(row[c]) for c in semantic_cols if row[c])
58
  text = normalize_text(text)
 
 
 
59
  return text
60
 
61
  # ================== Embeddings ==================
62
  texts = library_df.apply(row_to_text, axis=1).tolist()
63
+ embeddings = model.encode(texts, convert_to_numpy=True, normalize_embeddings=True, show_progress_bar=True)
 
 
 
 
 
64
  library_df["embedding"] = list(embeddings)
65
 
66
  # ================== TF-IDF ==================
67
  def tfidf_prefilter(df, query):
68
  texts = df.apply(row_to_text, axis=1).tolist()
69
+ vec = TfidfVectorizer(ngram_range=(1,3), max_features=30000, stop_words="english")
70
  mat = vec.fit_transform(texts)
71
  q_vec = vec.transform([normalize_text(query)])
72
  scores = cosine_similarity(q_vec, mat)[0]
 
84
  .row-title td{background:#e3f2fd;color:#0d47a1;font-weight:bold;}
85
  .row-author td{background:#fce4ec;color:#880e4f;}
86
  .row-year td{background:#e8f5e9;color:#1b5e20;}
87
+ .row-degree td{background:#f3e5f5;color:#6a1b9a;font-weight:bold;}
 
88
  .row-shelf td{background:#fff8e1;color:#e65100;font-weight:bold;font-size:16px;}
89
  </style>
90
  """
 
100
  html += f"""
101
  <div class="card">
102
  <table>
103
+ <tr class="row-title">
104
+ <td class="label">العنوان</td>
105
+ <td>{safe(r.get("العنوان"))}</td>
106
+ </tr>
107
+ <tr class="row-author">
108
+ <td class="label">المؤلف</td>
109
+ <td>{safe(r.get("المؤلف"))}</td>
110
+ </tr>
111
+ <tr class="row-degree">
112
+ <td class="label">الفئة / القسم</td>
113
+ <td>{safe(r.get("الفئة"))}</td>
114
+ </tr>
115
+ <tr class="row-year">
116
+ <td class="label">سنة النشر</td>
117
+ <td>{safe(r.get("سنة النشر"))}</td>
118
+ </tr>
119
+ <tr class="row-shelf">
120
+ <td class="label">الموقع على الرف</td>
121
+ <td>{safe(r.get("الموقع على الرف"))}</td>
122
+ </tr>
123
  </table>
124
  </div>
125
  """
 
127
 
128
  # ================== البحث ==================
129
  def local_search_df(query, mode, category, year_from, year_to):
130
+ if not query.strip():
131
+ return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
132
+
133
  df = library_df.copy()
134
+
135
+ # فلترة الفئة
136
  if category != "الكل":
137
+ df = df[df["الفئة"] == category]
138
+
139
+ # فلترة سنة النشر
140
  if year_from:
141
+ df = df[df["سنة النشر"].astype(str).str.isnumeric()]
142
+ df = df[df["سنة النشر"].astype(int) >= int(year_from)]
143
  if year_to:
144
+ df = df[df["سنة النشر"].astype(str).str.isnumeric()]
145
+ df = df[df["سنة النشر"].astype(int) <= int(year_to)]
146
+
 
147
  if mode == "نصي":
148
+ q = normalize_text(query)
149
+ mask = df.apply(lambda r: q in row_to_text(r), axis=1)
150
  df = df[mask].head(TOP_K)
151
  else:
152
  df_pref = tfidf_prefilter(df, query)
153
  if len(df_pref) < TFIDF_FALLBACK_MIN:
154
  df_pref = df
155
+ q_emb = model.encode([normalize_text(query)], normalize_embeddings=True)
156
  mat = np.vstack(df_pref["embedding"].values)
157
  scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
158
  df_pref["score"] = scores
159
  df = df_pref.sort_values("score", ascending=False).head(TOP_K)
160
+
161
  return results_to_html(df), df
162
 
163
  # ================== حفظ النتائج ==================
 
167
  return tmp.name
168
 
169
  # ================== واجهة Gradio ==================
170
+ categories = ["الكل"] + sorted(library_df["الفئة"].dropna().unique().tolist())
171
+
172
  with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
173
  gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
174
+
175
  query = gr.Textbox(label="كلمة أو موضوع البحث")
176
+ mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="دلالي", label="نوع البحث")
177
+ category = gr.Dropdown(categories, value="الكل", label="اختر الفئة")
178
+ year_from = gr.Textbox(label="من سنة (اختياري)")
179
+ year_to = gr.Textbox(label="إلى سنة (اختياري)")
180
+
181
  btn = gr.Button("🔎 بحث")
182
  out_html = gr.HTML()
183
  df_state = gr.State()
184
  file_out = gr.File(label="⬇️ تحميل النتائج")
185
+
186
  btn.click(local_search_df, [query, mode, category, year_from, year_to], [out_html, df_state])
187
  gr.Button("📥 حفظ النتائج").click(save_to_excel, df_state, file_out)
188