Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -40,12 +40,12 @@ theses_df["المصدر"] = "رسالة"
|
|
| 40 |
|
| 41 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
| 42 |
|
| 43 |
-
# ================== تجهيز ال
|
| 44 |
library_df["سنة النشر"] = pd.to_numeric(library_df.get("سنة النشر"), errors="coerce")
|
| 45 |
|
| 46 |
-
#
|
| 47 |
if "الموقع على الرف" in library_df.columns:
|
| 48 |
-
library_df["الموقع على الرف"] = library_df["الموقع على الرف"].fillna("-").astype(str).
|
| 49 |
else:
|
| 50 |
library_df["الموقع على الرف"] = "-"
|
| 51 |
|
|
@@ -53,23 +53,11 @@ else:
|
|
| 53 |
def emb_path(name):
|
| 54 |
return os.path.join(EMB_DIR, f"{name}.pkl")
|
| 55 |
|
| 56 |
-
# ================== الأعمدة الدلالية ==================
|
| 57 |
def detect_semantic_columns(df):
|
| 58 |
exclude_keywords = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 59 |
-
include_keywords = [
|
| 60 |
-
|
| 61 |
-
"مؤلف", "المؤلف",
|
| 62 |
-
"موضوع", "رءوس",
|
| 63 |
-
"ملخص", "الملخص",
|
| 64 |
-
"وصف", "كلمات"
|
| 65 |
-
]
|
| 66 |
-
semantic_cols = []
|
| 67 |
-
for col in df.columns:
|
| 68 |
-
col_str = str(col).strip()
|
| 69 |
-
if any(k in col_str for k in exclude_keywords):
|
| 70 |
-
continue
|
| 71 |
-
if any(k in col_str for k in include_keywords):
|
| 72 |
-
semantic_cols.append(col)
|
| 73 |
if not semantic_cols:
|
| 74 |
semantic_cols = df.select_dtypes(include="object").columns.tolist()
|
| 75 |
return semantic_cols
|
|
@@ -98,9 +86,17 @@ def build_or_load_embeddings(df, name):
|
|
| 98 |
return " ".join(parts)
|
| 99 |
|
| 100 |
texts = df.apply(row_to_text, axis=1).tolist()
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
with open(path, "wb") as f:
|
| 103 |
pickle.dump(emb, f)
|
|
|
|
| 104 |
return emb
|
| 105 |
|
| 106 |
library_embeddings = build_or_load_embeddings(library_df, "library")
|
|
@@ -127,55 +123,47 @@ CUSTOM_CSS = """
|
|
| 127 |
</style>
|
| 128 |
"""
|
| 129 |
|
| 130 |
-
# ==================
|
| 131 |
def results_to_html(df):
|
| 132 |
if df.empty:
|
| 133 |
return "<p>❌ لا توجد نتائج</p>"
|
| 134 |
-
df = df.drop(columns=["embedding", "score"], errors="ignore")
|
| 135 |
cols = ["العنوان", "المؤلف", "سنة النشر", "الموقع على الرف", "المصدر"]
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
# اللون حسب المصدر
|
| 141 |
-
if row.get("المصدر","")=="كتاب": bgcolor="#cce5ff"
|
| 142 |
-
elif row.get("المصدر","")=="رسالة": bgcolor="#d4edda"
|
| 143 |
-
else: bgcolor="#f9f9f9"
|
| 144 |
-
|
| 145 |
-
html += f"<table class='styled-table' style='margin-bottom:15px;background:{bgcolor};'>"
|
| 146 |
-
html += f"<caption style='caption-side:top;text-align:right;font-weight:bold;margin-bottom:5px;'>📘 النتيجة {i+1}</caption>"
|
| 147 |
-
for col in cols[:-1]:
|
| 148 |
-
val = row[col]
|
| 149 |
-
if val is None or str(val).strip()=="" or str(val).lower()=="nan":
|
| 150 |
-
val = "-"
|
| 151 |
-
html += f"<tr><th>{col}</th><td>{val}</td></tr>"
|
| 152 |
-
html += "</table>"
|
| 153 |
-
html += "</div>"
|
| 154 |
-
return html
|
| 155 |
|
| 156 |
# ================== البحث ==================
|
| 157 |
def local_search_df(query, mode, source_filter, year_range):
|
| 158 |
-
|
|
|
|
| 159 |
return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
|
|
|
|
| 160 |
df_search = library_df.copy()
|
| 161 |
-
|
| 162 |
-
|
|
|
|
|
|
|
| 163 |
start_year, end_year = year_range
|
| 164 |
-
df_search = df_search[(df_search["سنة النشر"]>=start_year)&(df_search["سنة النشر"]<=end_year)]
|
|
|
|
| 165 |
if df_search.empty:
|
| 166 |
return "<p>❌ لا توجد بيانات بعد الفلترة</p>", pd.DataFrame()
|
| 167 |
|
| 168 |
-
if mode=="نصي":
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
|
|
|
| 172 |
df = df_search[mask].head(TOP_K)
|
| 173 |
else:
|
|
|
|
| 174 |
q_emb = model.encode([query], convert_to_numpy=True, normalize_embeddings=True)
|
| 175 |
emb_matrix = np.vstack(df_search["embedding"].values)
|
| 176 |
scores = util.cos_sim(q_emb, emb_matrix)[0].cpu().numpy()
|
| 177 |
-
df_scored = df_search.
|
| 178 |
-
|
|
|
|
| 179 |
df = (filtered if not filtered.empty else df_scored).sort_values("score", ascending=False).head(TOP_K)
|
| 180 |
|
| 181 |
return results_to_html(df), df
|
|
@@ -183,7 +171,7 @@ def local_search_df(query, mode, source_filter, year_range):
|
|
| 183 |
# ================== حفظ النتائج ==================
|
| 184 |
def save_to_excel(df):
|
| 185 |
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
|
| 186 |
-
if df is None or
|
| 187 |
pd.DataFrame().to_excel(tmp.name, index=False)
|
| 188 |
else:
|
| 189 |
df.drop(columns=["embedding","score"], errors="ignore").to_excel(tmp.name, index=False)
|
|
@@ -192,18 +180,22 @@ def save_to_excel(df):
|
|
| 192 |
# ================== واجهة Gradio ==================
|
| 193 |
with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
| 194 |
gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
|
|
|
|
| 195 |
query = gr.Textbox(label="كلمة أو موضوع البحث")
|
| 196 |
-
mode = gr.Radio(["نصي","دلالي (Semantic)"], value="نصي", label="نوع البحث")
|
| 197 |
-
source_filter = gr.Radio(["الكل","كتاب","رسالة"], value="الكل", label="المصدر")
|
|
|
|
| 198 |
year_min = int(library_df["سنة النشر"].min())
|
| 199 |
year_max = int(library_df["سنة النشر"].max())
|
| 200 |
-
|
|
|
|
|
|
|
| 201 |
btn_search = gr.Button("🔎 بحث")
|
| 202 |
output_html = gr.HTML()
|
| 203 |
df_state = gr.State()
|
| 204 |
file_out = gr.File(label="⬇️ تحميل النتائج")
|
| 205 |
|
| 206 |
-
btn_search.click(local_search_df, inputs=[query,mode,source_filter,year_range], outputs=[output_html, df_state])
|
| 207 |
gr.Button("📥 حفظ النتائج").click(save_to_excel, inputs=df_state, outputs=file_out)
|
| 208 |
|
| 209 |
app.launch()
|
|
|
|
| 40 |
|
| 41 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
| 42 |
|
| 43 |
+
# ================== تجهيز سنة النشر ==================
|
| 44 |
library_df["سنة النشر"] = pd.to_numeric(library_df.get("سنة النشر"), errors="coerce")
|
| 45 |
|
| 46 |
+
# ================== تنظيف "الموقع على الرف" ==================
|
| 47 |
if "الموقع على الرف" in library_df.columns:
|
| 48 |
+
library_df["الموقع على الرف"] = library_df["الموقع على الرف"].fillna("-").astype(str).str.strip()
|
| 49 |
else:
|
| 50 |
library_df["الموقع على الرف"] = "-"
|
| 51 |
|
|
|
|
| 53 |
def emb_path(name):
|
| 54 |
return os.path.join(EMB_DIR, f"{name}.pkl")
|
| 55 |
|
| 56 |
+
# ================== تحديد الأعمدة الدلالية ==================
|
| 57 |
def detect_semantic_columns(df):
|
| 58 |
exclude_keywords = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 59 |
+
include_keywords = ["عنوان","العنوان","مؤلف","المؤلف","موضوع","رءوس","ملخص","الملخص","وصف","كلمات"]
|
| 60 |
+
semantic_cols = [col for col in df.columns if any(k in col for k in include_keywords) and not any(k in col for k in exclude_keywords)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
if not semantic_cols:
|
| 62 |
semantic_cols = df.select_dtypes(include="object").columns.tolist()
|
| 63 |
return semantic_cols
|
|
|
|
| 86 |
return " ".join(parts)
|
| 87 |
|
| 88 |
texts = df.apply(row_to_text, axis=1).tolist()
|
| 89 |
+
|
| 90 |
+
emb = model.encode(
|
| 91 |
+
texts,
|
| 92 |
+
convert_to_numpy=True,
|
| 93 |
+
normalize_embeddings=True,
|
| 94 |
+
show_progress_bar=True
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
with open(path, "wb") as f:
|
| 98 |
pickle.dump(emb, f)
|
| 99 |
+
|
| 100 |
return emb
|
| 101 |
|
| 102 |
library_embeddings = build_or_load_embeddings(library_df, "library")
|
|
|
|
| 123 |
</style>
|
| 124 |
"""
|
| 125 |
|
| 126 |
+
# ================== تحويل نتائج إلى HTML ==================
|
| 127 |
def results_to_html(df):
|
| 128 |
if df.empty:
|
| 129 |
return "<p>❌ لا توجد نتائج</p>"
|
|
|
|
| 130 |
cols = ["العنوان", "المؤلف", "سنة النشر", "الموقع على الرف", "المصدر"]
|
| 131 |
+
for c in cols:
|
| 132 |
+
if c not in df.columns:
|
| 133 |
+
df[c] = "-"
|
| 134 |
+
return CUSTOM_CSS + df[cols].to_html(index=False, escape=False, classes="styled-table")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
# ================== البحث ==================
|
| 137 |
def local_search_df(query, mode, source_filter, year_range):
|
| 138 |
+
query = query.strip()
|
| 139 |
+
if not query:
|
| 140 |
return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
|
| 141 |
+
|
| 142 |
df_search = library_df.copy()
|
| 143 |
+
|
| 144 |
+
if source_filter != "الكل":
|
| 145 |
+
df_search = df_search[df_search["المصدر"] == source_filter]
|
| 146 |
+
|
| 147 |
start_year, end_year = year_range
|
| 148 |
+
df_search = df_search[(df_search["سنة النشر"] >= start_year) & (df_search["سنة النشر"] <= end_year)]
|
| 149 |
+
|
| 150 |
if df_search.empty:
|
| 151 |
return "<p>❌ لا توجد بيانات بعد الفلترة</p>", pd.DataFrame()
|
| 152 |
|
| 153 |
+
if mode == "نصي":
|
| 154 |
+
mask = (
|
| 155 |
+
df_search["العنوان"].str.contains(query, case=False, na=False) |
|
| 156 |
+
df_search.get("المؤلف","").str.contains(query, case=False, na=False)
|
| 157 |
+
)
|
| 158 |
df = df_search[mask].head(TOP_K)
|
| 159 |
else:
|
| 160 |
+
# --- البحث الدلالي ---
|
| 161 |
q_emb = model.encode([query], convert_to_numpy=True, normalize_embeddings=True)
|
| 162 |
emb_matrix = np.vstack(df_search["embedding"].values)
|
| 163 |
scores = util.cos_sim(q_emb, emb_matrix)[0].cpu().numpy()
|
| 164 |
+
df_scored = df_search.copy()
|
| 165 |
+
df_scored["score"] = scores
|
| 166 |
+
filtered = df_scored[df_scored["score"] >= SIM_THRESHOLD]
|
| 167 |
df = (filtered if not filtered.empty else df_scored).sort_values("score", ascending=False).head(TOP_K)
|
| 168 |
|
| 169 |
return results_to_html(df), df
|
|
|
|
| 171 |
# ================== حفظ النتائج ==================
|
| 172 |
def save_to_excel(df):
|
| 173 |
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
|
| 174 |
+
if df is None or df.empty:
|
| 175 |
pd.DataFrame().to_excel(tmp.name, index=False)
|
| 176 |
else:
|
| 177 |
df.drop(columns=["embedding","score"], errors="ignore").to_excel(tmp.name, index=False)
|
|
|
|
| 180 |
# ================== واجهة Gradio ==================
|
| 181 |
with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
| 182 |
gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
|
| 183 |
+
|
| 184 |
query = gr.Textbox(label="كلمة أو موضوع البحث")
|
| 185 |
+
mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="نصي", label="نوع البحث")
|
| 186 |
+
source_filter = gr.Radio(["الكل", "كتاب", "رسالة"], value="الكل", label="المصدر")
|
| 187 |
+
|
| 188 |
year_min = int(library_df["سنة النشر"].min())
|
| 189 |
year_max = int(library_df["سنة النشر"].max())
|
| 190 |
+
|
| 191 |
+
year_range = gr.Slider(minimum=year_min, maximum=year_max, value=(year_min, year_max), step=1, label="سنة النشر")
|
| 192 |
+
|
| 193 |
btn_search = gr.Button("🔎 بحث")
|
| 194 |
output_html = gr.HTML()
|
| 195 |
df_state = gr.State()
|
| 196 |
file_out = gr.File(label="⬇️ تحميل النتائج")
|
| 197 |
|
| 198 |
+
btn_search.click(local_search_df, inputs=[query, mode, source_filter, year_range], outputs=[output_html, df_state])
|
| 199 |
gr.Button("📥 حفظ النتائج").click(save_to_excel, inputs=df_state, outputs=file_out)
|
| 200 |
|
| 201 |
app.launch()
|