Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -32,13 +32,19 @@ download_from_drive(DRIVE_BOOKS_ID, BOOKS_FILE)
|
|
| 32 |
download_from_drive(DRIVE_THESES_ID, THESES_FILE)
|
| 33 |
|
| 34 |
# ================== تحميل البيانات ==================
|
| 35 |
-
books_df = pd.read_excel(BOOKS_FILE)
|
| 36 |
-
theses_df = pd.read_excel(THESES_FILE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
books_df["المصدر"] = "كتاب"
|
| 39 |
theses_df["المصدر"] = "رسالة"
|
| 40 |
|
| 41 |
-
# تثبيت رقم الرف كنص
|
| 42 |
for df in [books_df, theses_df]:
|
| 43 |
if "الموقع على الرف" in df.columns:
|
| 44 |
df["الموقع على الرف"] = (
|
|
@@ -50,29 +56,33 @@ for df in [books_df, theses_df]:
|
|
| 50 |
|
| 51 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
| 55 |
)
|
| 56 |
|
| 57 |
# ================== الأعمدة الدلالية ==================
|
| 58 |
def detect_semantic_columns(df):
|
| 59 |
-
|
| 60 |
-
|
| 61 |
|
| 62 |
cols = []
|
| 63 |
for c in df.columns:
|
| 64 |
s = str(c)
|
| 65 |
-
if any(x in s for x in
|
| 66 |
continue
|
| 67 |
-
if any(x in s for x in
|
| 68 |
cols.append(c)
|
| 69 |
|
| 70 |
if not cols:
|
| 71 |
cols = df.select_dtypes(include="object").columns.tolist()
|
| 72 |
-
|
| 73 |
return cols
|
| 74 |
|
| 75 |
-
|
|
|
|
|
|
|
| 76 |
def normalize_text(text):
|
| 77 |
text = str(text).lower()
|
| 78 |
text = re.sub(r"[^\w\s]", " ", text)
|
|
@@ -80,14 +90,10 @@ def normalize_text(text):
|
|
| 80 |
text = text.replace("ى", "ي").replace("ة", "ه")
|
| 81 |
return re.sub(r"\s+", " ", text).strip()
|
| 82 |
|
| 83 |
-
# ================== Embeddings ==================
|
| 84 |
-
semantic_cols = detect_semantic_columns(library_df)
|
| 85 |
-
|
| 86 |
def row_to_text(row):
|
| 87 |
-
return normalize_text(
|
| 88 |
-
" ".join(str(row[c]) for c in semantic_cols if row[c])
|
| 89 |
-
)
|
| 90 |
|
|
|
|
| 91 |
embeddings = model.encode(
|
| 92 |
library_df.apply(row_to_text, axis=1).tolist(),
|
| 93 |
convert_to_numpy=True,
|
|
@@ -99,6 +105,9 @@ library_df["embedding"] = list(embeddings)
|
|
| 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, 2), max_features=20000)
|
| 103 |
mat = vec.fit_transform(texts)
|
| 104 |
q_vec = vec.transform([normalize_text(query)])
|
|
@@ -106,65 +115,18 @@ def tfidf_prefilter(df, query):
|
|
| 106 |
scores = cosine_similarity(q_vec, mat)[0]
|
| 107 |
df = df.copy()
|
| 108 |
df["tfidf_score"] = scores
|
| 109 |
-
|
| 110 |
return df.sort_values("tfidf_score", ascending=False).head(TFIDF_TOP_N)
|
| 111 |
|
| 112 |
# ================== CSS ==================
|
| 113 |
CUSTOM_CSS = """
|
| 114 |
<style>
|
| 115 |
-
.card{
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
}
|
| 122 |
-
|
| 123 |
-
.card table{
|
| 124 |
-
width:100%;
|
| 125 |
-
border-collapse:collapse;
|
| 126 |
-
direction:rtl;
|
| 127 |
-
}
|
| 128 |
-
|
| 129 |
-
.card td{
|
| 130 |
-
border:1px solid #ccc;
|
| 131 |
-
padding:8px;
|
| 132 |
-
text-align:center;
|
| 133 |
-
vertical-align:middle;
|
| 134 |
-
font-size:15px;
|
| 135 |
-
}
|
| 136 |
-
|
| 137 |
-
.card td.label{
|
| 138 |
-
width:30%;
|
| 139 |
-
font-weight:bold;
|
| 140 |
-
}
|
| 141 |
-
|
| 142 |
-
/* العنوان */
|
| 143 |
-
.row-title td{
|
| 144 |
-
background:#e3f2fd;
|
| 145 |
-
color:#0d47a1;
|
| 146 |
-
font-weight:bold;
|
| 147 |
-
}
|
| 148 |
-
|
| 149 |
-
/* المؤلف */
|
| 150 |
-
.row-author td{
|
| 151 |
-
background:#fce4ec;
|
| 152 |
-
color:#880e4f;
|
| 153 |
-
}
|
| 154 |
-
|
| 155 |
-
/* سنة النشر */
|
| 156 |
-
.row-year td{
|
| 157 |
-
background:#e8f5e9;
|
| 158 |
-
color:#1b5e20;
|
| 159 |
-
}
|
| 160 |
-
|
| 161 |
-
/* الموقع على الرف */
|
| 162 |
-
.row-shelf td{
|
| 163 |
-
background:#fff8e1;
|
| 164 |
-
color:#e65100;
|
| 165 |
-
font-weight:bold;
|
| 166 |
-
font-size:16px;
|
| 167 |
-
}
|
| 168 |
</style>
|
| 169 |
"""
|
| 170 |
|
|
@@ -180,26 +142,13 @@ def results_to_html(df):
|
|
| 180 |
html += f"""
|
| 181 |
<div class="card">
|
| 182 |
<table>
|
| 183 |
-
<tr class="row-title">
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
</tr>
|
| 187 |
-
<tr class="row-author">
|
| 188 |
-
<td class="label">المؤلف</td>
|
| 189 |
-
<td>{safe(r.get("المؤلف"))}</td>
|
| 190 |
-
</tr>
|
| 191 |
-
<tr class="row-year">
|
| 192 |
-
<td class="label">سنة النشر</td>
|
| 193 |
-
<td>{safe(r.get("سنة النشر"))}</td>
|
| 194 |
-
</tr>
|
| 195 |
-
<tr class="row-shelf">
|
| 196 |
-
<td class="label">الموقع على الرف</td>
|
| 197 |
-
<td>{safe(r.get("الموقع على الرف"))}</td>
|
| 198 |
-
</tr>
|
| 199 |
</table>
|
| 200 |
</div>
|
| 201 |
"""
|
| 202 |
-
|
| 203 |
return CUSTOM_CSS + html
|
| 204 |
|
| 205 |
# ================== البحث ==================
|
|
@@ -224,12 +173,17 @@ def local_search_df(query, mode, source_filter, year_range):
|
|
| 224 |
df["المؤلف"].str.contains(query, case=False, na=False)
|
| 225 |
)
|
| 226 |
df = df[mask].head(TOP_K)
|
|
|
|
| 227 |
else:
|
| 228 |
df_pref = tfidf_prefilter(df, query)
|
| 229 |
-
if
|
| 230 |
-
df_pref = df
|
| 231 |
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
mat = np.vstack(df_pref["embedding"].values)
|
| 234 |
scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
|
| 235 |
|
|
@@ -246,6 +200,9 @@ def save_to_excel(df):
|
|
| 246 |
return tmp.name
|
| 247 |
|
| 248 |
# ================== واجهة Gradio ==================
|
|
|
|
|
|
|
|
|
|
| 249 |
with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
| 250 |
gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
|
| 251 |
|
|
@@ -254,9 +211,9 @@ with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
|
| 254 |
source_filter = gr.Radio(["الكل", "كتاب", "رسالة"], value="الكل", label="المصدر")
|
| 255 |
|
| 256 |
year_range = gr.Slider(
|
| 257 |
-
minimum=
|
| 258 |
-
maximum=
|
| 259 |
-
value=(
|
| 260 |
step=1,
|
| 261 |
label="سنة النشر"
|
| 262 |
)
|
|
|
|
| 32 |
download_from_drive(DRIVE_THESES_ID, THESES_FILE)
|
| 33 |
|
| 34 |
# ================== تحميل البيانات ==================
|
| 35 |
+
books_df = pd.read_excel(BOOKS_FILE)
|
| 36 |
+
theses_df = pd.read_excel(THESES_FILE)
|
| 37 |
+
|
| 38 |
+
books_df.columns = books_df.columns.str.strip()
|
| 39 |
+
theses_df.columns = theses_df.columns.str.strip()
|
| 40 |
+
|
| 41 |
+
books_df = books_df.fillna("")
|
| 42 |
+
theses_df = theses_df.fillna("")
|
| 43 |
|
| 44 |
books_df["المصدر"] = "كتاب"
|
| 45 |
theses_df["المصدر"] = "رسالة"
|
| 46 |
|
| 47 |
+
# 🔒 تثبيت رقم الرف كنص
|
| 48 |
for df in [books_df, theses_df]:
|
| 49 |
if "الموقع على الرف" in df.columns:
|
| 50 |
df["الموقع على الرف"] = (
|
|
|
|
| 56 |
|
| 57 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
| 58 |
|
| 59 |
+
# ================== سنة النشر (إصلاح كامل) ==================
|
| 60 |
+
library_df["سنة النشر"] = (
|
| 61 |
+
pd.to_numeric(library_df.get("سنة النشر"), errors="coerce")
|
| 62 |
+
.fillna(0)
|
| 63 |
+
.astype(int)
|
| 64 |
)
|
| 65 |
|
| 66 |
# ================== الأعمدة الدلالية ==================
|
| 67 |
def detect_semantic_columns(df):
|
| 68 |
+
exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 69 |
+
include = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "كلمات"]
|
| 70 |
|
| 71 |
cols = []
|
| 72 |
for c in df.columns:
|
| 73 |
s = str(c)
|
| 74 |
+
if any(x in s for x in exclude):
|
| 75 |
continue
|
| 76 |
+
if any(x in s for x in include):
|
| 77 |
cols.append(c)
|
| 78 |
|
| 79 |
if not cols:
|
| 80 |
cols = df.select_dtypes(include="object").columns.tolist()
|
|
|
|
| 81 |
return cols
|
| 82 |
|
| 83 |
+
semantic_cols = detect_semantic_columns(library_df)
|
| 84 |
+
|
| 85 |
+
# ================== Normalize ==================
|
| 86 |
def normalize_text(text):
|
| 87 |
text = str(text).lower()
|
| 88 |
text = re.sub(r"[^\w\s]", " ", text)
|
|
|
|
| 90 |
text = text.replace("ى", "ي").replace("ة", "ه")
|
| 91 |
return re.sub(r"\s+", " ", text).strip()
|
| 92 |
|
|
|
|
|
|
|
|
|
|
| 93 |
def row_to_text(row):
|
| 94 |
+
return normalize_text(" ".join(str(row[c]) for c in semantic_cols if str(row[c]).strip()))
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
# ================== Embeddings ==================
|
| 97 |
embeddings = model.encode(
|
| 98 |
library_df.apply(row_to_text, axis=1).tolist(),
|
| 99 |
convert_to_numpy=True,
|
|
|
|
| 105 |
# ================== TF-IDF ==================
|
| 106 |
def tfidf_prefilter(df, query):
|
| 107 |
texts = df.apply(row_to_text, axis=1).tolist()
|
| 108 |
+
if not texts:
|
| 109 |
+
return df
|
| 110 |
+
|
| 111 |
vec = TfidfVectorizer(ngram_range=(1, 2), max_features=20000)
|
| 112 |
mat = vec.fit_transform(texts)
|
| 113 |
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 ==================
|
| 121 |
CUSTOM_CSS = """
|
| 122 |
<style>
|
| 123 |
+
.card{border:1px solid #ddd;border-radius:8px;padding:10px;margin:12px 0;background:#fafafa;}
|
| 124 |
+
.card table{width:100%;border-collapse:collapse;direction:rtl;}
|
| 125 |
+
.card td{border:1px solid #ccc;padding:8px;text-align:center;font-size:15px;}
|
| 126 |
+
.row-title td{background:#e3f2fd;color:#0d47a1;font-weight:bold;}
|
| 127 |
+
.row-author td{background:#fce4ec;color:#880e4f;}
|
| 128 |
+
.row-year td{background:#e8f5e9;color:#1b5e20;}
|
| 129 |
+
.row-shelf td{background:#fff8e1;color:#e65100;font-weight:bold;font-size:16px;}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
</style>
|
| 131 |
"""
|
| 132 |
|
|
|
|
| 142 |
html += f"""
|
| 143 |
<div class="card">
|
| 144 |
<table>
|
| 145 |
+
<tr class="row-title"><td>العنوان</td><td>{safe(r.get("العنوان"))}</td></tr>
|
| 146 |
+
<tr class="row-author"><td>المؤلف</td><td>{safe(r.get("المؤلف"))}</td></tr>
|
| 147 |
+
<tr class="row-year"><td>سنة النشر</td><td>{safe(r.get("سنة النشر"))}</td></tr>
|
| 148 |
+
<tr class="row-shelf"><td>الموقع على الرف</td><td>{safe(r.get("الموقع على الرف"))}</td></tr>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
</table>
|
| 150 |
</div>
|
| 151 |
"""
|
|
|
|
| 152 |
return CUSTOM_CSS + html
|
| 153 |
|
| 154 |
# ================== البحث ==================
|
|
|
|
| 173 |
df["المؤلف"].str.contains(query, case=False, na=False)
|
| 174 |
)
|
| 175 |
df = df[mask].head(TOP_K)
|
| 176 |
+
|
| 177 |
else:
|
| 178 |
df_pref = tfidf_prefilter(df, query)
|
| 179 |
+
if df_pref.empty:
|
| 180 |
+
df_pref = df.copy()
|
| 181 |
|
| 182 |
+
df_pref = df_pref[df_pref["embedding"].notna()]
|
| 183 |
+
if df_pref.empty:
|
| 184 |
+
return "<p>❌ لا توجد نتائج دلالية</p>", pd.DataFrame()
|
| 185 |
+
|
| 186 |
+
q_emb = model.encode([normalize_text(query)], convert_to_numpy=True, normalize_embeddings=True)
|
| 187 |
mat = np.vstack(df_pref["embedding"].values)
|
| 188 |
scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
|
| 189 |
|
|
|
|
| 200 |
return tmp.name
|
| 201 |
|
| 202 |
# ================== واجهة Gradio ==================
|
| 203 |
+
year_min = int(library_df["سنة النشر"].replace(0, np.nan).min())
|
| 204 |
+
year_max = int(library_df["سنة النشر"].max())
|
| 205 |
+
|
| 206 |
with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
| 207 |
gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
|
| 208 |
|
|
|
|
| 211 |
source_filter = gr.Radio(["الكل", "كتاب", "رسالة"], value="الكل", label="المصدر")
|
| 212 |
|
| 213 |
year_range = gr.Slider(
|
| 214 |
+
minimum=year_min,
|
| 215 |
+
maximum=year_max,
|
| 216 |
+
value=(year_min, year_max),
|
| 217 |
step=1,
|
| 218 |
label="سنة النشر"
|
| 219 |
)
|