Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -35,9 +35,24 @@ download_from_drive(DRIVE_THESES_ID, THESES_FILE)
|
|
| 35 |
|
| 36 |
# ================== تحميل البيانات ==================
|
| 37 |
books_df = pd.read_excel(BOOKS_FILE).fillna("")
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
|
| 41 |
theses_df["المصدر"] = "رسالة"
|
| 42 |
|
| 43 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
|
@@ -45,7 +60,7 @@ library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
|
| 45 |
# ================== الأعمدة الدلالية ==================
|
| 46 |
def detect_semantic_columns(df):
|
| 47 |
exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 48 |
-
include = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "
|
| 49 |
|
| 50 |
cols = []
|
| 51 |
for c in df.columns:
|
|
@@ -57,6 +72,7 @@ def detect_semantic_columns(df):
|
|
| 57 |
|
| 58 |
if not cols:
|
| 59 |
cols = df.select_dtypes(include="object").columns.tolist()
|
|
|
|
| 60 |
return cols
|
| 61 |
|
| 62 |
semantic_cols = detect_semantic_columns(library_df)
|
|
@@ -72,13 +88,16 @@ def normalize_text(text):
|
|
| 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
|
| 79 |
|
| 80 |
# ================== Embeddings ==================
|
| 81 |
texts = library_df.apply(row_to_text, axis=1).tolist()
|
|
|
|
| 82 |
embeddings = model.encode(
|
| 83 |
texts,
|
| 84 |
convert_to_numpy=True,
|
|
@@ -97,9 +116,11 @@ def tfidf_prefilter(df, query):
|
|
| 97 |
)
|
| 98 |
mat = vec.fit_transform(texts)
|
| 99 |
q_vec = vec.transform([normalize_text(query)])
|
|
|
|
| 100 |
scores = cosine_similarity(q_vec, mat)[0]
|
| 101 |
df = df.copy()
|
| 102 |
df["tfidf_score"] = scores
|
|
|
|
| 103 |
return df.sort_values("tfidf_score", ascending=False).head(TFIDF_TOP_N)
|
| 104 |
|
| 105 |
# ================== CSS ==================
|
|
@@ -112,8 +133,8 @@ CUSTOM_CSS = """
|
|
| 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 |
"""
|
| 119 |
|
|
@@ -123,6 +144,7 @@ def safe(v):
|
|
| 123 |
def results_to_html(df):
|
| 124 |
if df.empty:
|
| 125 |
return "<p>❌ لا توجد نتائج</p>"
|
|
|
|
| 126 |
html = ""
|
| 127 |
for _, r in df.iterrows():
|
| 128 |
html += f"""
|
|
@@ -136,14 +158,14 @@ def results_to_html(df):
|
|
| 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>
|
|
@@ -151,21 +173,26 @@ def results_to_html(df):
|
|
| 151 |
</table>
|
| 152 |
</div>
|
| 153 |
"""
|
|
|
|
| 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 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
| 169 |
if mode == "نصي":
|
| 170 |
q = normalize_text(query)
|
| 171 |
mask = df.apply(lambda r: q in row_to_text(r), axis=1)
|
|
@@ -174,11 +201,14 @@ def local_search_df(query, mode, year_from, year_to):
|
|
| 174 |
df_pref = tfidf_prefilter(df, query)
|
| 175 |
if len(df_pref) < TFIDF_FALLBACK_MIN:
|
| 176 |
df_pref = df
|
|
|
|
| 177 |
q_emb = model.encode([normalize_text(query)], normalize_embeddings=True)
|
| 178 |
mat = np.vstack(df_pref["embedding"].values)
|
| 179 |
scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
|
|
|
|
| 180 |
df_pref["score"] = scores
|
| 181 |
df = df_pref.sort_values("score", ascending=False).head(TOP_K)
|
|
|
|
| 182 |
return results_to_html(df), df
|
| 183 |
|
| 184 |
# ================== حفظ النتائج ==================
|
|
@@ -194,6 +224,7 @@ with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
|
| 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 |
|
|
@@ -202,9 +233,10 @@ with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
|
| 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 |
|
|
|
|
|
|
| 35 |
|
| 36 |
# ================== تحميل البيانات ==================
|
| 37 |
books_df = pd.read_excel(BOOKS_FILE).fillna("")
|
| 38 |
+
theses_df_raw = pd.read_excel(THESES_FILE).fillna("")
|
| 39 |
+
|
| 40 |
+
# ================== معالجة الرسائل لإضافة العمود "القسم" ==================
|
| 41 |
+
sections = []
|
| 42 |
+
current_section = ""
|
| 43 |
+
theses_rows = []
|
| 44 |
+
|
| 45 |
+
for _, row in theses_df_raw.iterrows():
|
| 46 |
+
combined_text = " ".join(str(row[c]) for c in theses_df_raw.columns if row[c])
|
| 47 |
+
combined_text = combined_text.strip()
|
| 48 |
+
# إذا الصف طويل ويحتوي على كلمات القسم
|
| 49 |
+
if "جامعة" in combined_text or "مكتبة" in combined_text:
|
| 50 |
+
current_section = combined_text
|
| 51 |
+
else:
|
| 52 |
+
row["القسم"] = current_section
|
| 53 |
+
theses_rows.append(row)
|
| 54 |
|
| 55 |
+
theses_df = pd.DataFrame(theses_rows)
|
| 56 |
theses_df["المصدر"] = "رسالة"
|
| 57 |
|
| 58 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
|
|
|
| 60 |
# ================== الأعمدة الدلالية ==================
|
| 61 |
def detect_semantic_columns(df):
|
| 62 |
exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 63 |
+
include = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "كلمات"]
|
| 64 |
|
| 65 |
cols = []
|
| 66 |
for c in df.columns:
|
|
|
|
| 72 |
|
| 73 |
if not cols:
|
| 74 |
cols = df.select_dtypes(include="object").columns.tolist()
|
| 75 |
+
|
| 76 |
return cols
|
| 77 |
|
| 78 |
semantic_cols = detect_semantic_columns(library_df)
|
|
|
|
| 88 |
def row_to_text(row):
|
| 89 |
text = " ".join(str(row[c]) for c in semantic_cols if row[c])
|
| 90 |
text = normalize_text(text)
|
| 91 |
+
|
| 92 |
# Boost للمصطلحات الطبية
|
| 93 |
if any(x in text for x in ["cardio", "toxic", "toxicity"]):
|
| 94 |
text += " cardiotoxicity cardiac toxicity cardiotoxic effects"
|
| 95 |
+
|
| 96 |
return text
|
| 97 |
|
| 98 |
# ================== Embeddings ==================
|
| 99 |
texts = library_df.apply(row_to_text, axis=1).tolist()
|
| 100 |
+
|
| 101 |
embeddings = model.encode(
|
| 102 |
texts,
|
| 103 |
convert_to_numpy=True,
|
|
|
|
| 116 |
)
|
| 117 |
mat = vec.fit_transform(texts)
|
| 118 |
q_vec = vec.transform([normalize_text(query)])
|
| 119 |
+
|
| 120 |
scores = cosine_similarity(q_vec, mat)[0]
|
| 121 |
df = df.copy()
|
| 122 |
df["tfidf_score"] = scores
|
| 123 |
+
|
| 124 |
return df.sort_values("tfidf_score", ascending=False).head(TFIDF_TOP_N)
|
| 125 |
|
| 126 |
# ================== CSS ==================
|
|
|
|
| 133 |
.row-title td{background:#e3f2fd;color:#0d47a1;font-weight:bold;}
|
| 134 |
.row-author td{background:#fce4ec;color:#880e4f;}
|
| 135 |
.row-year td{background:#e8f5e9;color:#1b5e20;}
|
|
|
|
| 136 |
.row-shelf td{background:#fff8e1;color:#e65100;font-weight:bold;font-size:16px;}
|
| 137 |
+
.row-section td{background:#fff3e0;color:#bf360c;font-weight:bold;}
|
| 138 |
</style>
|
| 139 |
"""
|
| 140 |
|
|
|
|
| 144 |
def results_to_html(df):
|
| 145 |
if df.empty:
|
| 146 |
return "<p>❌ لا توجد نتائج</p>"
|
| 147 |
+
|
| 148 |
html = ""
|
| 149 |
for _, r in df.iterrows():
|
| 150 |
html += f"""
|
|
|
|
| 158 |
<td class="label">المؤلف</td>
|
| 159 |
<td>{safe(r.get("المؤلف"))}</td>
|
| 160 |
</tr>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
<tr class="row-year">
|
| 162 |
<td class="label">سنة النشر</td>
|
| 163 |
<td>{safe(r.get("سنة النشر"))}</td>
|
| 164 |
</tr>
|
| 165 |
+
<tr class="row-section">
|
| 166 |
+
<td class="label">القسم</td>
|
| 167 |
+
<td>{safe(r.get("القسم"))}</td>
|
| 168 |
+
</tr>
|
| 169 |
<tr class="row-shelf">
|
| 170 |
<td class="label">الموقع على الرف</td>
|
| 171 |
<td>{safe(r.get("الموقع على الرف"))}</td>
|
|
|
|
| 173 |
</table>
|
| 174 |
</div>
|
| 175 |
"""
|
| 176 |
+
|
| 177 |
return CUSTOM_CSS + html
|
| 178 |
|
| 179 |
# ================== البحث ==================
|
| 180 |
+
def local_search_df(query, mode, source_filter, year_from, year_to):
|
| 181 |
if not query.strip():
|
| 182 |
return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
|
| 183 |
+
|
| 184 |
df = library_df.copy()
|
| 185 |
+
|
| 186 |
+
# تصفية حسب المصدر
|
| 187 |
+
if source_filter != "الكل":
|
| 188 |
+
df = df[df["المصدر"] == source_filter]
|
| 189 |
+
|
| 190 |
+
# تصفية حسب السنة
|
| 191 |
+
if year_from:
|
| 192 |
+
df = df[df["سنة النشر"].astype(str).str[:4].astype(int) >= int(year_from)]
|
| 193 |
+
if year_to:
|
| 194 |
+
df = df[df["سنة النشر"].astype(str).str[:4].astype(int) <= int(year_to)]
|
| 195 |
+
|
| 196 |
if mode == "نصي":
|
| 197 |
q = normalize_text(query)
|
| 198 |
mask = df.apply(lambda r: q in row_to_text(r), axis=1)
|
|
|
|
| 201 |
df_pref = tfidf_prefilter(df, query)
|
| 202 |
if len(df_pref) < TFIDF_FALLBACK_MIN:
|
| 203 |
df_pref = df
|
| 204 |
+
|
| 205 |
q_emb = model.encode([normalize_text(query)], normalize_embeddings=True)
|
| 206 |
mat = np.vstack(df_pref["embedding"].values)
|
| 207 |
scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
|
| 208 |
+
|
| 209 |
df_pref["score"] = scores
|
| 210 |
df = df_pref.sort_values("score", ascending=False).head(TOP_K)
|
| 211 |
+
|
| 212 |
return results_to_html(df), df
|
| 213 |
|
| 214 |
# ================== حفظ النتائج ==================
|
|
|
|
| 224 |
|
| 225 |
query = gr.Textbox(label="كلمة أو موضوع البحث")
|
| 226 |
mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="دلالي (Semantic)", label="نوع البحث")
|
| 227 |
+
source_filter = gr.Radio(["الكل", "كتاب", "رسالة"], value="الكل", label="اختر الفئة")
|
| 228 |
year_from = gr.Textbox(label="من سنة", placeholder="مثال: 2010")
|
| 229 |
year_to = gr.Textbox(label="إلى سنة", placeholder="مثال: 2025")
|
| 230 |
|
|
|
|
| 233 |
df_state = gr.State()
|
| 234 |
file_out = gr.File(label="⬇️ تحميل النتائج")
|
| 235 |
|
| 236 |
+
btn.click(local_search_df, [query, mode, source_filter, year_from, year_to], [out_html, df_state])
|
| 237 |
gr.Button("📥 حفظ النتائج").click(save_to_excel, df_state, file_out)
|
| 238 |
|
| 239 |
app.launch()
|
| 240 |
|
| 241 |
|
| 242 |
+
|