aelsaeed commited on
Commit
3a23df4
·
verified ·
1 Parent(s): 8ecb405

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -14
app.py CHANGED
@@ -36,6 +36,7 @@ download_from_drive(DRIVE_THESES_ID, THESES_FILE)
36
  # ================== تحميل البيانات ==================
37
  books_df = pd.read_excel(BOOKS_FILE).fillna("")
38
  theses_df = pd.read_excel(THESES_FILE).fillna("")
 
39
  books_df["المصدر"] = "كتاب"
40
  theses_df["المصدر"] = "رسالة"
41
 
@@ -45,7 +46,15 @@ library_df = pd.concat([books_df, theses_df], ignore_index=True)
45
  def detect_semantic_columns(df):
46
  exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
47
  include = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "نوع درجة الرسالة العلمية ", "كلمات"]
48
- cols = [c for c in df.columns if not any(x in c for x in exclude) and any(x in c for x in include)]
 
 
 
 
 
 
 
 
49
  if not cols:
50
  cols = df.select_dtypes(include="object").columns.tolist()
51
  return cols
@@ -63,6 +72,7 @@ def normalize_text(text):
63
  def row_to_text(row):
64
  text = " ".join(str(row[c]) for c in semantic_cols if row[c])
65
  text = normalize_text(text)
 
66
  if any(x in text for x in ["cardio", "toxic", "toxicity"]):
67
  text += " cardiotoxicity cardiac toxicity cardiotoxic effects"
68
  return text
@@ -80,7 +90,11 @@ library_df["embedding"] = list(embeddings)
80
  # ================== TF-IDF ==================
81
  def tfidf_prefilter(df, query):
82
  texts = df.apply(row_to_text, axis=1).tolist()
83
- vec = TfidfVectorizer(ngram_range=(1, 3), max_features=30000, stop_words="english")
 
 
 
 
84
  mat = vec.fit_transform(texts)
85
  q_vec = vec.transform([normalize_text(query)])
86
  scores = cosine_similarity(q_vec, mat)[0]
@@ -98,7 +112,7 @@ CUSTOM_CSS = """
98
  .row-title td{background:#e3f2fd;color:#0d47a1;font-weight:bold;}
99
  .row-author td{background:#fce4ec;color:#880e4f;}
100
  .row-year td{background:#e8f5e9;color:#1b5e20;}
101
- .row-degree td{background:#fff3e0;color:#ef6c00;font-weight:bold;font-size:15px;}
102
  .row-shelf td{background:#fff8e1;color:#e65100;font-weight:bold;font-size:16px;}
103
  </style>
104
  """
@@ -122,14 +136,14 @@ def results_to_html(df):
122
  <td class="label">المؤلف</td>
123
  <td>{safe(r.get("المؤلف"))}</td>
124
  </tr>
125
- <tr class="row-year">
126
- <td class="label">سنة النشر</td>
127
- <td>{safe(r.get("سنة النشر"))}</td>
128
- </tr>
129
  <tr class="row-degree">
130
  <td class="label">نوع درجة الرسالة العلمية</td>
131
  <td>{safe(r.get("نوع درجة الرسالة العلمية "))}</td>
132
  </tr>
 
 
 
 
133
  <tr class="row-shelf">
134
  <td class="label">الموقع على الرف</td>
135
  <td>{safe(r.get("الموقع على الرف"))}</td>
@@ -140,12 +154,18 @@ def results_to_html(df):
140
  return CUSTOM_CSS + html
141
 
142
  # ================== البحث ==================
143
- def local_search_df(query, mode, source_filter_val):
144
  if not query.strip():
145
  return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
146
  df = library_df.copy()
147
- if source_filter_val != "الكل":
148
- df = df[df["المصدر"] == source_filter_val]
 
 
 
 
 
 
149
  if mode == "نصي":
150
  q = normalize_text(query)
151
  mask = df.apply(lambda r: q in row_to_text(r), axis=1)
@@ -164,23 +184,27 @@ def local_search_df(query, mode, source_filter_val):
164
  # ================== حفظ النتائج ==================
165
  def save_to_excel(df):
166
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
167
- df.drop(columns=["embedding", "score", "tfidf_score"], errors="ignore").to_excel(tmp.name, index=False)
 
168
  return tmp.name
169
 
170
  # ================== واجهة Gradio ==================
171
  with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
172
  gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
 
173
  query = gr.Textbox(label="كلمة أو موضوع البحث")
174
  mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="دلالي (Semantic)", label="نوع البحث")
175
- source_filter = gr.Dropdown(["الكل", "كتاب", "رسالة"], value="الكل", label="المصدر")
176
-
 
177
  btn = gr.Button("🔎 بحث")
178
  out_html = gr.HTML()
179
  df_state = gr.State()
180
  file_out = gr.File(label="⬇️ تحميل النتائج")
181
 
182
- btn.click(local_search_df, inputs=[query, mode, source_filter], outputs=[out_html, df_state])
183
  gr.Button("📥 حفظ النتائج").click(save_to_excel, df_state, file_out)
184
 
185
  app.launch()
186
 
 
 
36
  # ================== تحميل البيانات ==================
37
  books_df = pd.read_excel(BOOKS_FILE).fillna("")
38
  theses_df = pd.read_excel(THESES_FILE).fillna("")
39
+
40
  books_df["المصدر"] = "كتاب"
41
  theses_df["المصدر"] = "رسالة"
42
 
 
46
  def detect_semantic_columns(df):
47
  exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
48
  include = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "نوع درجة الرسالة العلمية ", "كلمات"]
49
+
50
+ cols = []
51
+ for c in df.columns:
52
+ s = str(c)
53
+ if any(x in s for x in exclude):
54
+ continue
55
+ if any(x in s for x in include):
56
+ cols.append(c)
57
+
58
  if not cols:
59
  cols = df.select_dtypes(include="object").columns.tolist()
60
  return cols
 
72
  def row_to_text(row):
73
  text = " ".join(str(row[c]) for c in semantic_cols if row[c])
74
  text = normalize_text(text)
75
+ # Boost للمصطلحات الطبية
76
  if any(x in text for x in ["cardio", "toxic", "toxicity"]):
77
  text += " cardiotoxicity cardiac toxicity cardiotoxic effects"
78
  return text
 
90
  # ================== TF-IDF ==================
91
  def tfidf_prefilter(df, query):
92
  texts = df.apply(row_to_text, axis=1).tolist()
93
+ vec = TfidfVectorizer(
94
+ ngram_range=(1, 3),
95
+ max_features=30000,
96
+ stop_words="english"
97
+ )
98
  mat = vec.fit_transform(texts)
99
  q_vec = vec.transform([normalize_text(query)])
100
  scores = cosine_similarity(q_vec, mat)[0]
 
112
  .row-title td{background:#e3f2fd;color:#0d47a1;font-weight:bold;}
113
  .row-author td{background:#fce4ec;color:#880e4f;}
114
  .row-year td{background:#e8f5e9;color:#1b5e20;}
115
+ .row-degree td{background:#fff3e0;color:#e65100;font-weight:bold;font-size:16px;}
116
  .row-shelf td{background:#fff8e1;color:#e65100;font-weight:bold;font-size:16px;}
117
  </style>
118
  """
 
136
  <td class="label">المؤلف</td>
137
  <td>{safe(r.get("المؤلف"))}</td>
138
  </tr>
 
 
 
 
139
  <tr class="row-degree">
140
  <td class="label">نوع درجة الرسالة العلمية</td>
141
  <td>{safe(r.get("نوع درجة الرسالة العلمية "))}</td>
142
  </tr>
143
+ <tr class="row-year">
144
+ <td class="label">سنة النشر</td>
145
+ <td>{safe(r.get("سنة النشر"))}</td>
146
+ </tr>
147
  <tr class="row-shelf">
148
  <td class="label">الموقع على الرف</td>
149
  <td>{safe(r.get("الموقع على الرف"))}</td>
 
154
  return CUSTOM_CSS + html
155
 
156
  # ================== البحث ==================
157
+ def local_search_df(query, mode, year_from, year_to):
158
  if not query.strip():
159
  return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
160
  df = library_df.copy()
161
+ # فلترة حسب السنة
162
+ try:
163
+ yf = int(year_from) if year_from else None
164
+ yt = int(year_to) if year_to else None
165
+ if yf: df = df[df["سنة النشر"].apply(lambda x: str(x).isdigit() and int(x) >= yf)]
166
+ if yt: df = df[df["سنة النشر"].apply(lambda x: str(x).isdigit() and int(x) <= yt)]
167
+ except:
168
+ pass
169
  if mode == "نصي":
170
  q = normalize_text(query)
171
  mask = df.apply(lambda r: q in row_to_text(r), axis=1)
 
184
  # ================== حفظ النتائج ==================
185
  def save_to_excel(df):
186
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
187
+ df.drop(columns=["embedding", "score", "tfidf_score"], errors="ignore") \
188
+ .to_excel(tmp.name, index=False)
189
  return tmp.name
190
 
191
  # ================== واجهة Gradio ==================
192
  with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
193
  gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
194
+
195
  query = gr.Textbox(label="كلمة أو موضوع البحث")
196
  mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="دلالي (Semantic)", label="نوع البحث")
197
+ year_from = gr.Textbox(label="من سنة", placeholder="مثال: 2010")
198
+ year_to = gr.Textbox(label="إلى سنة", placeholder="مثال: 2025")
199
+
200
  btn = gr.Button("🔎 بحث")
201
  out_html = gr.HTML()
202
  df_state = gr.State()
203
  file_out = gr.File(label="⬇️ تحميل النتائج")
204
 
205
+ btn.click(local_search_df, [query, mode, year_from, year_to], [out_html, df_state])
206
  gr.Button("📥 حفظ النتائج").click(save_to_excel, df_state, file_out)
207
 
208
  app.launch()
209
 
210
+