Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -13,16 +13,14 @@ BOOKS_FILE = "book.xlsx"
|
|
| 13 |
THESES_FILE = "theses.xlsx"
|
| 14 |
|
| 15 |
DRIVE_BOOKS_ID = "1IVu5M_zHWg3wo-cbQm3FWhmDIafUSCVP"
|
| 16 |
-
DRIVE_THESES_ID = "
|
| 17 |
|
| 18 |
TOP_K = 20
|
| 19 |
-
TFIDF_TOP_N =
|
| 20 |
-
TFIDF_FALLBACK_MIN =
|
| 21 |
|
| 22 |
-
# ================== نموذج
|
| 23 |
-
model = SentenceTransformer(
|
| 24 |
-
"pritamdeka/BioBERT-mnli-snli-scinli-scitail-mednli-stsb"
|
| 25 |
-
)
|
| 26 |
|
| 27 |
# ================== تحميل الملفات ==================
|
| 28 |
def download_from_drive(file_id, output):
|
|
@@ -40,28 +38,21 @@ theses_df = pd.read_excel(THESES_FILE).fillna("")
|
|
| 40 |
books_df["المصدر"] = "كتاب"
|
| 41 |
theses_df["المصدر"] = "رسالة"
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
title = str(row.get("العنوان", "")).strip()
|
| 52 |
-
if any(k in title for k in ["جامعة", "كليه", "قسم", "مكتبة"]):
|
| 53 |
-
current_category = title
|
| 54 |
-
rows_to_drop.append(i)
|
| 55 |
-
else:
|
| 56 |
-
library_df.at[i, "الفئة"] = current_category
|
| 57 |
-
|
| 58 |
-
library_df.drop(rows_to_drop, inplace=True)
|
| 59 |
-
library_df.reset_index(drop=True, inplace=True)
|
| 60 |
|
| 61 |
# ================== الأعمدة الدلالية ==================
|
| 62 |
def detect_semantic_columns(df):
|
| 63 |
exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 64 |
-
include = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "
|
| 65 |
|
| 66 |
cols = []
|
| 67 |
for c in df.columns:
|
|
@@ -73,6 +64,7 @@ def detect_semantic_columns(df):
|
|
| 73 |
|
| 74 |
if not cols:
|
| 75 |
cols = df.select_dtypes(include="object").columns.tolist()
|
|
|
|
| 76 |
return cols
|
| 77 |
|
| 78 |
semantic_cols = detect_semantic_columns(library_df)
|
|
@@ -80,22 +72,19 @@ semantic_cols = detect_semantic_columns(library_df)
|
|
| 80 |
# ================== Normalize ==================
|
| 81 |
def normalize_text(text):
|
| 82 |
text = str(text).lower()
|
| 83 |
-
text = re.sub(r"[^
|
| 84 |
text = text.replace("أ", "ا").replace("إ", "ا").replace("آ", "ا")
|
| 85 |
text = text.replace("ى", "ي").replace("ة", "ه")
|
| 86 |
return re.sub(r"\s+", " ", text).strip()
|
| 87 |
|
| 88 |
def row_to_text(row):
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
text += " cardiotoxicity cardiac toxicity cardiotoxic effects"
|
| 93 |
-
return text
|
| 94 |
|
| 95 |
# ================== Embeddings ==================
|
| 96 |
-
texts = library_df.apply(row_to_text, axis=1).tolist()
|
| 97 |
embeddings = model.encode(
|
| 98 |
-
|
| 99 |
convert_to_numpy=True,
|
| 100 |
normalize_embeddings=True,
|
| 101 |
show_progress_bar=True
|
|
@@ -105,16 +94,14 @@ library_df["embedding"] = list(embeddings)
|
|
| 105 |
# ================== TF-IDF ==================
|
| 106 |
def tfidf_prefilter(df, query):
|
| 107 |
texts = df.apply(row_to_text, axis=1).tolist()
|
| 108 |
-
vec = TfidfVectorizer(
|
| 109 |
-
ngram_range=(1, 3),
|
| 110 |
-
max_features=30000,
|
| 111 |
-
stop_words="english"
|
| 112 |
-
)
|
| 113 |
mat = vec.fit_transform(texts)
|
| 114 |
q_vec = vec.transform([normalize_text(query)])
|
|
|
|
| 115 |
scores = cosine_similarity(q_vec, mat)[0]
|
| 116 |
df = df.copy()
|
| 117 |
df["tfidf_score"] = scores
|
|
|
|
| 118 |
return df.sort_values("tfidf_score", ascending=False).head(TFIDF_TOP_N)
|
| 119 |
|
| 120 |
# ================== CSS ==================
|
|
@@ -127,9 +114,6 @@ CUSTOM_CSS = """
|
|
| 127 |
.row-title td{background:#e3f2fd;color:#0d47a1;font-weight:bold;}
|
| 128 |
.row-author td{background:#fce4ec;color:#880e4f;}
|
| 129 |
.row-year td{background:#e8f5e9;color:#1b5e20;}
|
| 130 |
-
.row-degree td{background:#fff3e0;color:#e65100;font-weight:bold;font-size:16px;}
|
| 131 |
-
.row-source td{background:#e0f7fa;color:#006064;font-weight:bold;}
|
| 132 |
-
.row-category td{background:#f3e5f5;color:#4a148c;font-weight:bold;}
|
| 133 |
.row-shelf td{background:#fff8e1;color:#e65100;font-weight:bold;font-size:16px;}
|
| 134 |
</style>
|
| 135 |
"""
|
|
@@ -140,6 +124,7 @@ def safe(v):
|
|
| 140 |
def results_to_html(df):
|
| 141 |
if df.empty:
|
| 142 |
return "<p>❌ لا توجد نتائج</p>"
|
|
|
|
| 143 |
html = ""
|
| 144 |
for _, r in df.iterrows():
|
| 145 |
html += f"""
|
|
@@ -153,22 +138,10 @@ def results_to_html(df):
|
|
| 153 |
<td class="label">المؤلف</td>
|
| 154 |
<td>{safe(r.get("المؤلف"))}</td>
|
| 155 |
</tr>
|
| 156 |
-
<tr class="row-degree">
|
| 157 |
-
<td class="label">نوع درجة الرسالة العلمية</td>
|
| 158 |
-
<td>{safe(r.get("نوع درجة الرسالة العلمية "))}</td>
|
| 159 |
-
</tr>
|
| 160 |
<tr class="row-year">
|
| 161 |
<td class="label">سنة النشر</td>
|
| 162 |
<td>{safe(r.get("سنة النشر"))}</td>
|
| 163 |
</tr>
|
| 164 |
-
<tr class="row-source">
|
| 165 |
-
<td class="label">المصدر</td>
|
| 166 |
-
<td>{safe(r.get("المصدر"))}</td>
|
| 167 |
-
</tr>
|
| 168 |
-
<tr class="row-category">
|
| 169 |
-
<td class="label">الفئة</td>
|
| 170 |
-
<td>{safe(r.get("الفئة"))}</td>
|
| 171 |
-
</tr>
|
| 172 |
<tr class="row-shelf">
|
| 173 |
<td class="label">الموقع على الرف</td>
|
| 174 |
<td>{safe(r.get("الموقع على الرف"))}</td>
|
|
@@ -176,41 +149,40 @@ def results_to_html(df):
|
|
| 176 |
</table>
|
| 177 |
</div>
|
| 178 |
"""
|
| 179 |
-
return CUSTOM_CSS + html
|
| 180 |
|
| 181 |
-
|
| 182 |
-
def filter_by_year(df, year_from, year_to):
|
| 183 |
-
try:
|
| 184 |
-
if year_from:
|
| 185 |
-
yf = int(year_from)
|
| 186 |
-
df = df[df["سنة النشر"].apply(lambda x: str(x).isdigit() and int(x) >= yf)]
|
| 187 |
-
if year_to:
|
| 188 |
-
yt = int(year_to)
|
| 189 |
-
df = df[df["سنة النشر"].apply(lambda x: str(x).isdigit() and int(x) <= yt)]
|
| 190 |
-
except:
|
| 191 |
-
pass
|
| 192 |
-
return df
|
| 193 |
|
| 194 |
# ================== البحث ==================
|
| 195 |
-
def local_search_df(query, mode,
|
| 196 |
if not query.strip():
|
| 197 |
return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
|
|
|
|
| 198 |
df = library_df.copy()
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
if mode == "نصي":
|
| 202 |
-
|
| 203 |
-
|
|
|
|
|
|
|
| 204 |
df = df[mask].head(TOP_K)
|
| 205 |
else:
|
| 206 |
df_pref = tfidf_prefilter(df, query)
|
| 207 |
if len(df_pref) < TFIDF_FALLBACK_MIN:
|
| 208 |
df_pref = df
|
|
|
|
| 209 |
q_emb = model.encode([normalize_text(query)], normalize_embeddings=True)
|
| 210 |
mat = np.vstack(df_pref["embedding"].values)
|
| 211 |
scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
|
|
|
|
| 212 |
df_pref["score"] = scores
|
| 213 |
df = df_pref.sort_values("score", ascending=False).head(TOP_K)
|
|
|
|
| 214 |
return results_to_html(df), df
|
| 215 |
|
| 216 |
# ================== حفظ النتائج ==================
|
|
@@ -225,16 +197,15 @@ with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
|
| 225 |
gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
|
| 226 |
|
| 227 |
query = gr.Textbox(label="كلمة أو موضوع البحث")
|
| 228 |
-
mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="
|
| 229 |
-
|
| 230 |
-
year_to = gr.Textbox(label="إلى سنة", placeholder="مثال: 2025")
|
| 231 |
|
| 232 |
btn = gr.Button("🔎 بحث")
|
| 233 |
out_html = gr.HTML()
|
| 234 |
df_state = gr.State()
|
| 235 |
file_out = gr.File(label="⬇️ تحميل النتائج")
|
| 236 |
|
| 237 |
-
btn.click(local_search_df, [query, mode,
|
| 238 |
gr.Button("📥 حفظ النتائج").click(save_to_excel, df_state, file_out)
|
| 239 |
|
| 240 |
app.launch()
|
|
|
|
| 13 |
THESES_FILE = "theses.xlsx"
|
| 14 |
|
| 15 |
DRIVE_BOOKS_ID = "1IVu5M_zHWg3wo-cbQm3FWhmDIafUSCVP"
|
| 16 |
+
DRIVE_THESES_ID = "1hvZIGFG6h0kQY32bIuEWGRdXTZp84vhk"
|
| 17 |
|
| 18 |
TOP_K = 20
|
| 19 |
+
TFIDF_TOP_N = 100
|
| 20 |
+
TFIDF_FALLBACK_MIN = 30
|
| 21 |
|
| 22 |
+
# ================== نموذج Semantic ==================
|
| 23 |
+
model = SentenceTransformer("all-MiniLM-L6-v2")
|
|
|
|
|
|
|
| 24 |
|
| 25 |
# ================== تحميل الملفات ==================
|
| 26 |
def download_from_drive(file_id, output):
|
|
|
|
| 38 |
books_df["المصدر"] = "كتاب"
|
| 39 |
theses_df["المصدر"] = "رسالة"
|
| 40 |
|
| 41 |
+
for df in [books_df, theses_df]:
|
| 42 |
+
if "الموقع على الرف" in df.columns:
|
| 43 |
+
df["الموقع على الرف"] = (
|
| 44 |
+
df["الموقع على الرف"]
|
| 45 |
+
.astype(str)
|
| 46 |
+
.str.strip()
|
| 47 |
+
.replace(["nan", "NaN", "None", ""], "-")
|
| 48 |
+
)
|
| 49 |
|
| 50 |
+
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
# ================== الأعمدة الدلالية ==================
|
| 53 |
def detect_semantic_columns(df):
|
| 54 |
exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 55 |
+
include = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "كلمات"]
|
| 56 |
|
| 57 |
cols = []
|
| 58 |
for c in df.columns:
|
|
|
|
| 64 |
|
| 65 |
if not cols:
|
| 66 |
cols = df.select_dtypes(include="object").columns.tolist()
|
| 67 |
+
|
| 68 |
return cols
|
| 69 |
|
| 70 |
semantic_cols = detect_semantic_columns(library_df)
|
|
|
|
| 72 |
# ================== Normalize ==================
|
| 73 |
def normalize_text(text):
|
| 74 |
text = str(text).lower()
|
| 75 |
+
text = re.sub(r"[^\w\s]", " ", text)
|
| 76 |
text = text.replace("أ", "ا").replace("إ", "ا").replace("آ", "ا")
|
| 77 |
text = text.replace("ى", "ي").replace("ة", "ه")
|
| 78 |
return re.sub(r"\s+", " ", text).strip()
|
| 79 |
|
| 80 |
def row_to_text(row):
|
| 81 |
+
return normalize_text(
|
| 82 |
+
" ".join(str(row[c]) for c in semantic_cols if row[c])
|
| 83 |
+
)
|
|
|
|
|
|
|
| 84 |
|
| 85 |
# ================== Embeddings ==================
|
|
|
|
| 86 |
embeddings = model.encode(
|
| 87 |
+
library_df.apply(row_to_text, axis=1).tolist(),
|
| 88 |
convert_to_numpy=True,
|
| 89 |
normalize_embeddings=True,
|
| 90 |
show_progress_bar=True
|
|
|
|
| 94 |
# ================== TF-IDF ==================
|
| 95 |
def tfidf_prefilter(df, query):
|
| 96 |
texts = df.apply(row_to_text, axis=1).tolist()
|
| 97 |
+
vec = TfidfVectorizer(ngram_range=(1, 2), max_features=20000)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
mat = vec.fit_transform(texts)
|
| 99 |
q_vec = vec.transform([normalize_text(query)])
|
| 100 |
+
|
| 101 |
scores = cosine_similarity(q_vec, mat)[0]
|
| 102 |
df = df.copy()
|
| 103 |
df["tfidf_score"] = scores
|
| 104 |
+
|
| 105 |
return df.sort_values("tfidf_score", ascending=False).head(TFIDF_TOP_N)
|
| 106 |
|
| 107 |
# ================== CSS ==================
|
|
|
|
| 114 |
.row-title td{background:#e3f2fd;color:#0d47a1;font-weight:bold;}
|
| 115 |
.row-author td{background:#fce4ec;color:#880e4f;}
|
| 116 |
.row-year td{background:#e8f5e9;color:#1b5e20;}
|
|
|
|
|
|
|
|
|
|
| 117 |
.row-shelf td{background:#fff8e1;color:#e65100;font-weight:bold;font-size:16px;}
|
| 118 |
</style>
|
| 119 |
"""
|
|
|
|
| 124 |
def results_to_html(df):
|
| 125 |
if df.empty:
|
| 126 |
return "<p>❌ لا توجد نتائج</p>"
|
| 127 |
+
|
| 128 |
html = ""
|
| 129 |
for _, r in df.iterrows():
|
| 130 |
html += f"""
|
|
|
|
| 138 |
<td class="label">المؤلف</td>
|
| 139 |
<td>{safe(r.get("المؤلف"))}</td>
|
| 140 |
</tr>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
<tr class="row-year">
|
| 142 |
<td class="label">سنة النشر</td>
|
| 143 |
<td>{safe(r.get("سنة النشر"))}</td>
|
| 144 |
</tr>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
<tr class="row-shelf">
|
| 146 |
<td class="label">الموقع على الرف</td>
|
| 147 |
<td>{safe(r.get("الموقع على الرف"))}</td>
|
|
|
|
| 149 |
</table>
|
| 150 |
</div>
|
| 151 |
"""
|
|
|
|
| 152 |
|
| 153 |
+
return CUSTOM_CSS + html
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
# ================== البحث ==================
|
| 156 |
+
def local_search_df(query, mode, source_filter):
|
| 157 |
if not query.strip():
|
| 158 |
return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
|
| 159 |
+
|
| 160 |
df = library_df.copy()
|
| 161 |
+
|
| 162 |
+
if source_filter != "الكل":
|
| 163 |
+
df = df[df["المصدر"] == source_filter]
|
| 164 |
+
|
| 165 |
+
if df.empty:
|
| 166 |
+
return "<p>❌ لا توجد بيانات</p>", pd.DataFrame()
|
| 167 |
|
| 168 |
if mode == "نصي":
|
| 169 |
+
mask = (
|
| 170 |
+
df["العنوان"].str.contains(query, case=False, na=False) |
|
| 171 |
+
df["المؤلف"].str.contains(query, case=False, na=False)
|
| 172 |
+
)
|
| 173 |
df = df[mask].head(TOP_K)
|
| 174 |
else:
|
| 175 |
df_pref = tfidf_prefilter(df, query)
|
| 176 |
if len(df_pref) < TFIDF_FALLBACK_MIN:
|
| 177 |
df_pref = df
|
| 178 |
+
|
| 179 |
q_emb = model.encode([normalize_text(query)], normalize_embeddings=True)
|
| 180 |
mat = np.vstack(df_pref["embedding"].values)
|
| 181 |
scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
|
| 182 |
+
|
| 183 |
df_pref["score"] = scores
|
| 184 |
df = df_pref.sort_values("score", ascending=False).head(TOP_K)
|
| 185 |
+
|
| 186 |
return results_to_html(df), df
|
| 187 |
|
| 188 |
# ================== حفظ النتائج ==================
|
|
|
|
| 197 |
gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
|
| 198 |
|
| 199 |
query = gr.Textbox(label="كلمة أو موضوع البحث")
|
| 200 |
+
mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="نصي", label="نوع البحث")
|
| 201 |
+
source_filter = gr.Radio(["الكل", "كتاب", "رسالة"], value="الكل", label="المصدر")
|
|
|
|
| 202 |
|
| 203 |
btn = gr.Button("🔎 بحث")
|
| 204 |
out_html = gr.HTML()
|
| 205 |
df_state = gr.State()
|
| 206 |
file_out = gr.File(label="⬇️ تحميل النتائج")
|
| 207 |
|
| 208 |
+
btn.click(local_search_df, [query, mode, source_filter], [out_html, df_state])
|
| 209 |
gr.Button("📥 حفظ النتائج").click(save_to_excel, df_state, file_out)
|
| 210 |
|
| 211 |
app.launch()
|