Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
import gradio as gr
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
-
import os, pickle, tempfile
|
| 6 |
from sentence_transformers import SentenceTransformer, util
|
| 7 |
import gdown
|
| 8 |
|
|
@@ -41,30 +41,45 @@ theses_df["المصدر"] = "رسالة"
|
|
| 41 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
| 42 |
|
| 43 |
# ================== تجهيز سنة النشر ==================
|
| 44 |
-
library_df["سنة النشر"] = pd.to_numeric(
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
if "الموقع على الرف" in library_df.columns:
|
| 48 |
-
library_df["الموقع على الرف"] = library_df["الموقع على الرف"].fillna("-").astype(str).str.strip()
|
| 49 |
-
else:
|
| 50 |
-
library_df["الموقع على الرف"] = "-"
|
| 51 |
|
| 52 |
# ================== مسار embeddings ==================
|
| 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 |
if not semantic_cols:
|
| 62 |
semantic_cols = df.select_dtypes(include="object").columns.tolist()
|
|
|
|
| 63 |
return semantic_cols
|
| 64 |
|
| 65 |
# ================== بناء أو تحميل embeddings ==================
|
| 66 |
def build_or_load_embeddings(df, name):
|
| 67 |
path = emb_path(name)
|
|
|
|
| 68 |
if os.path.exists(path):
|
| 69 |
try:
|
| 70 |
with open(path, "rb") as f:
|
|
@@ -123,48 +138,60 @@ CUSTOM_CSS = """
|
|
| 123 |
</style>
|
| 124 |
"""
|
| 125 |
|
| 126 |
-
# ==================
|
| 127 |
def results_to_html(df):
|
| 128 |
if df.empty:
|
| 129 |
return "<p>❌ لا توجد نتائج</p>"
|
| 130 |
-
|
|
|
|
| 131 |
for c in cols:
|
| 132 |
if c not in df.columns:
|
| 133 |
df[c] = "-"
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
# ================== البحث ==================
|
| 137 |
def local_search_df(query, mode, source_filter, year_range):
|
| 138 |
-
|
| 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[
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
if df_search.empty:
|
| 151 |
return "<p>❌ لا توجد بيانات بعد الفلترة</p>", pd.DataFrame()
|
| 152 |
|
| 153 |
if mode == "نصي":
|
|
|
|
| 154 |
mask = (
|
| 155 |
-
df_search["العنوان"].str.contains(
|
| 156 |
-
df_search.get("المؤلف","").str.contains(
|
| 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 |
-
|
| 165 |
-
|
| 166 |
-
filtered =
|
| 167 |
-
df = (
|
|
|
|
|
|
|
| 168 |
|
| 169 |
return results_to_html(df), df
|
| 170 |
|
|
@@ -174,11 +201,13 @@ def save_to_excel(df):
|
|
| 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")
|
|
|
|
| 178 |
return tmp.name
|
| 179 |
|
| 180 |
# ================== واجهة Gradio ==================
|
| 181 |
with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
|
|
|
| 182 |
gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
|
| 183 |
|
| 184 |
query = gr.Textbox(label="كلمة أو موضوع البحث")
|
|
@@ -188,14 +217,29 @@ with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
|
| 188 |
year_min = int(library_df["سنة النشر"].min())
|
| 189 |
year_max = int(library_df["سنة النشر"].max())
|
| 190 |
|
| 191 |
-
year_range = gr.Slider(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
app.launch()
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
+
import os, pickle, tempfile, shutil
|
| 6 |
from sentence_transformers import SentenceTransformer, util
|
| 7 |
import gdown
|
| 8 |
|
|
|
|
| 41 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
| 42 |
|
| 43 |
# ================== تجهيز سنة النشر ==================
|
| 44 |
+
library_df["سنة النشر"] = pd.to_numeric(
|
| 45 |
+
library_df.get("سنة النشر"), errors="coerce"
|
| 46 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
# ================== مسار embeddings ==================
|
| 49 |
def emb_path(name):
|
| 50 |
return os.path.join(EMB_DIR, f"{name}.pkl")
|
| 51 |
|
| 52 |
+
# ================== تحديد الأعمدة الدلالية (نهائي) ==================
|
| 53 |
def detect_semantic_columns(df):
|
| 54 |
exclude_keywords = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 55 |
+
include_keywords = [
|
| 56 |
+
"عنوان", "العنوان",
|
| 57 |
+
"مؤلف", "المؤلف",
|
| 58 |
+
"موضوع", "رءوس",
|
| 59 |
+
"ملخص", "الملخص",
|
| 60 |
+
"وصف", "كلمات"
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
semantic_cols = []
|
| 64 |
+
for col in df.columns:
|
| 65 |
+
col_str = str(col).strip()
|
| 66 |
+
|
| 67 |
+
if any(k in col_str for k in exclude_keywords):
|
| 68 |
+
continue
|
| 69 |
+
|
| 70 |
+
if any(k in col_str for k in include_keywords):
|
| 71 |
+
semantic_cols.append(col)
|
| 72 |
+
|
| 73 |
+
# Fallback أمان
|
| 74 |
if not semantic_cols:
|
| 75 |
semantic_cols = df.select_dtypes(include="object").columns.tolist()
|
| 76 |
+
|
| 77 |
return semantic_cols
|
| 78 |
|
| 79 |
# ================== بناء أو تحميل embeddings ==================
|
| 80 |
def build_or_load_embeddings(df, name):
|
| 81 |
path = emb_path(name)
|
| 82 |
+
|
| 83 |
if os.path.exists(path):
|
| 84 |
try:
|
| 85 |
with open(path, "rb") as f:
|
|
|
|
| 138 |
</style>
|
| 139 |
"""
|
| 140 |
|
| 141 |
+
# ================== عرض النتائج ==================
|
| 142 |
def results_to_html(df):
|
| 143 |
if df.empty:
|
| 144 |
return "<p>❌ لا توجد نتائج</p>"
|
| 145 |
+
|
| 146 |
+
cols = ["المؤلف", "العنوان", "سنة النشر", "الموقع على الرف", "المصدر"]
|
| 147 |
for c in cols:
|
| 148 |
if c not in df.columns:
|
| 149 |
df[c] = "-"
|
| 150 |
+
|
| 151 |
+
return CUSTOM_CSS + df[cols].to_html(
|
| 152 |
+
index=False,
|
| 153 |
+
escape=False,
|
| 154 |
+
classes="styled-table",
|
| 155 |
+
border=0
|
| 156 |
+
)
|
| 157 |
|
| 158 |
# ================== البحث ==================
|
| 159 |
def local_search_df(query, mode, source_filter, year_range):
|
| 160 |
+
if not query.strip():
|
|
|
|
| 161 |
return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
|
| 162 |
+
|
| 163 |
df_search = library_df.copy()
|
| 164 |
|
| 165 |
if source_filter != "الكل":
|
| 166 |
df_search = df_search[df_search["المصدر"] == source_filter]
|
| 167 |
|
| 168 |
start_year, end_year = year_range
|
| 169 |
+
df_search = df_search[
|
| 170 |
+
(df_search["سنة النشر"] >= start_year) &
|
| 171 |
+
(df_search["سنة النشر"] <= end_year)
|
| 172 |
+
]
|
| 173 |
|
| 174 |
if df_search.empty:
|
| 175 |
return "<p>❌ لا توجد بيانات بعد الفلترة</p>", pd.DataFrame()
|
| 176 |
|
| 177 |
if mode == "نصي":
|
| 178 |
+
q = query.strip()
|
| 179 |
mask = (
|
| 180 |
+
df_search["العنوان"].str.contains(q, case=False, na=False) |
|
| 181 |
+
df_search.get("المؤلف","").str.contains(q, case=False, na=False)
|
| 182 |
)
|
| 183 |
df = df_search[mask].head(TOP_K)
|
| 184 |
+
|
| 185 |
else:
|
|
|
|
| 186 |
q_emb = model.encode([query], convert_to_numpy=True, normalize_embeddings=True)
|
| 187 |
emb_matrix = np.vstack(df_search["embedding"].values)
|
| 188 |
scores = util.cos_sim(q_emb, emb_matrix)[0].cpu().numpy()
|
| 189 |
+
df_search["score"] = scores
|
| 190 |
+
|
| 191 |
+
filtered = df_search[df_search["score"] >= SIM_THRESHOLD]
|
| 192 |
+
df = (
|
| 193 |
+
filtered if not filtered.empty else df_search
|
| 194 |
+
).sort_values("score", ascending=False).head(TOP_K)
|
| 195 |
|
| 196 |
return results_to_html(df), df
|
| 197 |
|
|
|
|
| 201 |
if df is None or df.empty:
|
| 202 |
pd.DataFrame().to_excel(tmp.name, index=False)
|
| 203 |
else:
|
| 204 |
+
df.drop(columns=["embedding", "score"], errors="ignore") \
|
| 205 |
+
.to_excel(tmp.name, index=False)
|
| 206 |
return tmp.name
|
| 207 |
|
| 208 |
# ================== واجهة Gradio ==================
|
| 209 |
with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
| 210 |
+
|
| 211 |
gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
|
| 212 |
|
| 213 |
query = gr.Textbox(label="كلمة أو موضوع البحث")
|
|
|
|
| 217 |
year_min = int(library_df["سنة النشر"].min())
|
| 218 |
year_max = int(library_df["سنة النشر"].max())
|
| 219 |
|
| 220 |
+
year_range = gr.Slider(
|
| 221 |
+
minimum=year_min,
|
| 222 |
+
maximum=year_max,
|
| 223 |
+
value=(year_min, year_max),
|
| 224 |
+
step=1,
|
| 225 |
+
label="سنة النشر"
|
| 226 |
+
)
|
| 227 |
|
| 228 |
btn_search = gr.Button("🔎 بحث")
|
| 229 |
output_html = gr.HTML()
|
| 230 |
df_state = gr.State()
|
| 231 |
file_out = gr.File(label="⬇️ تحميل النتائج")
|
| 232 |
|
| 233 |
+
btn_search.click(
|
| 234 |
+
local_search_df,
|
| 235 |
+
inputs=[query, mode, source_filter, year_range],
|
| 236 |
+
outputs=[output_html, df_state]
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
gr.Button("📥 حفظ النتائج").click(
|
| 240 |
+
save_to_excel,
|
| 241 |
+
inputs=df_state,
|
| 242 |
+
outputs=file_out
|
| 243 |
+
)
|
| 244 |
|
| 245 |
app.launch()
|