Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,8 +2,7 @@
|
|
| 2 |
import gradio as gr
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
-
import os, pickle, tempfile
|
| 6 |
-
import re
|
| 7 |
from sentence_transformers import SentenceTransformer, util
|
| 8 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 9 |
from sklearn.metrics.pairwise import cosine_similarity
|
|
@@ -49,134 +48,68 @@ library_df["سنة النشر"] = pd.to_numeric(
|
|
| 49 |
library_df.get("سنة النشر"), errors="coerce"
|
| 50 |
)
|
| 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 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
semantic_cols = []
|
| 68 |
-
for col in df.columns:
|
| 69 |
-
col_str = str(col).strip()
|
| 70 |
-
if any(k in col_str for k in exclude_keywords):
|
| 71 |
continue
|
| 72 |
-
if any(
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
if not semantic_cols:
|
| 76 |
-
semantic_cols = df.select_dtypes(include="object").columns.tolist()
|
| 77 |
|
| 78 |
-
return
|
| 79 |
|
| 80 |
# ================== Normalize عربي / إنجليزي ==================
|
| 81 |
-
def normalize_text(
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
text = re.sub(r"\s+", " ", text).strip()
|
| 89 |
-
return text
|
| 90 |
|
| 91 |
# ================== Embeddings ==================
|
| 92 |
def build_or_load_embeddings(df, name):
|
| 93 |
-
path =
|
| 94 |
-
|
| 95 |
if os.path.exists(path):
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
parts.append((f"{col}: {val} ") * weight)
|
| 113 |
-
return " ".join(parts)
|
| 114 |
-
|
| 115 |
-
texts = df.apply(row_to_text, axis=1).tolist()
|
| 116 |
-
|
| 117 |
-
emb = model.encode(
|
| 118 |
-
texts,
|
| 119 |
-
convert_to_numpy=True,
|
| 120 |
-
normalize_embeddings=True,
|
| 121 |
-
show_progress_bar=True
|
| 122 |
-
)
|
| 123 |
-
|
| 124 |
with open(path, "wb") as f:
|
| 125 |
pickle.dump(emb, f)
|
| 126 |
-
|
| 127 |
return emb
|
| 128 |
|
| 129 |
-
|
| 130 |
-
library_df["embedding"] = list(library_embeddings)
|
| 131 |
-
|
| 132 |
-
# ================== TF-IDF ==================
|
| 133 |
-
def build_tfidf_texts(df):
|
| 134 |
-
semantic_cols = detect_semantic_columns(df)
|
| 135 |
-
texts = []
|
| 136 |
-
|
| 137 |
-
for _, row in df.iterrows():
|
| 138 |
-
parts = []
|
| 139 |
-
for col in semantic_cols:
|
| 140 |
-
val = str(row[col]).strip()
|
| 141 |
-
if val:
|
| 142 |
-
parts.append(val)
|
| 143 |
-
texts.append(normalize_text(" ".join(parts)))
|
| 144 |
-
|
| 145 |
-
return texts
|
| 146 |
-
|
| 147 |
-
def tfidf_prefilter(df, query, top_n=TFIDF_TOP_N):
|
| 148 |
-
if df.empty:
|
| 149 |
-
return df
|
| 150 |
-
|
| 151 |
-
texts = build_tfidf_texts(df)
|
| 152 |
-
|
| 153 |
-
vectorizer = TfidfVectorizer(
|
| 154 |
-
ngram_range=(1, 2),
|
| 155 |
-
max_features=20000
|
| 156 |
-
)
|
| 157 |
-
|
| 158 |
-
tfidf_matrix = vectorizer.fit_transform(texts)
|
| 159 |
-
query_vec = vectorizer.transform([normalize_text(query)])
|
| 160 |
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
|
| 165 |
-
|
|
|
|
| 166 |
|
| 167 |
-
# ==================
|
| 168 |
CUSTOM_CSS = """
|
| 169 |
<style>
|
| 170 |
-
.card{
|
| 171 |
-
|
| 172 |
-
border-radius:8px;
|
| 173 |
-
padding:12px;
|
| 174 |
-
margin:10px 0;
|
| 175 |
-
direction:rtl;
|
| 176 |
-
background:#fafafa;
|
| 177 |
-
}
|
| 178 |
-
.card h3{margin:0 0 5px 0;}
|
| 179 |
-
.card p{margin:3px 0;}
|
| 180 |
</style>
|
| 181 |
"""
|
| 182 |
|
|
@@ -185,16 +118,15 @@ def results_to_html(df):
|
|
| 185 |
return "<p>❌ لا توجد نتائج</p>"
|
| 186 |
|
| 187 |
html = ""
|
| 188 |
-
for _,
|
| 189 |
html += f"""
|
| 190 |
<div class="card">
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
</div>
|
| 196 |
"""
|
| 197 |
-
|
| 198 |
return CUSTOM_CSS + html
|
| 199 |
|
| 200 |
# ================== البحث ==================
|
|
@@ -202,88 +134,70 @@ def local_search_df(query, mode, source_filter, year_range):
|
|
| 202 |
if not query.strip():
|
| 203 |
return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
|
| 204 |
|
| 205 |
-
|
| 206 |
|
| 207 |
if source_filter != "الكل":
|
| 208 |
-
|
| 209 |
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
(df_search["سنة النشر"] >= start_year) &
|
| 213 |
-
(df_search["سنة النشر"] <= end_year)
|
| 214 |
-
]
|
| 215 |
|
| 216 |
-
if
|
| 217 |
return "<p>❌ لا توجد بيانات</p>", pd.DataFrame()
|
| 218 |
|
| 219 |
if mode == "نصي":
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
df_search["العنوان"].str.contains(q, case=False, na=False) |
|
| 223 |
-
df_search.get("المؤلف","").str.contains(q, case=False, na=False)
|
| 224 |
-
)
|
| 225 |
-
df = df_search[mask].head(TOP_K)
|
| 226 |
|
| 227 |
else:
|
| 228 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
|
| 230 |
if len(df_pref) < TFIDF_FALLBACK_MIN:
|
| 231 |
-
df_pref =
|
| 232 |
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
|
|
|
| 236 |
|
| 237 |
-
df_pref
|
| 238 |
-
df = df_pref.sort_values("score", ascending=False).head(TOP_K)
|
| 239 |
|
| 240 |
-
return results_to_html(
|
| 241 |
|
| 242 |
# ================== حفظ النتائج ==================
|
| 243 |
def save_to_excel(df):
|
| 244 |
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
|
| 245 |
-
if df is None
|
| 246 |
-
|
| 247 |
-
else:
|
| 248 |
-
df.drop(columns=["embedding", "score", "tfidf_score"], errors="ignore") \
|
| 249 |
.to_excel(tmp.name, index=False)
|
| 250 |
return tmp.name
|
| 251 |
|
| 252 |
-
# ================== واجهة
|
| 253 |
with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
| 254 |
-
|
| 255 |
gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
|
| 256 |
|
| 257 |
-
|
| 258 |
-
mode = gr.Radio(["نصي",
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
year_min = int(library_df["سنة النشر"].min())
|
| 262 |
-
year_max = int(library_df["سنة النشر"].max())
|
| 263 |
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
value=(
|
| 268 |
-
step=1,
|
| 269 |
-
label="سنة النشر"
|
| 270 |
)
|
| 271 |
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
inputs=[query, mode, source_filter, year_range],
|
| 280 |
-
outputs=[output_html, df_state]
|
| 281 |
-
)
|
| 282 |
-
|
| 283 |
-
gr.Button("📥 حفظ النتائج").click(
|
| 284 |
-
save_to_excel,
|
| 285 |
-
inputs=df_state,
|
| 286 |
-
outputs=file_out
|
| 287 |
-
)
|
| 288 |
|
| 289 |
app.launch()
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
+
import os, pickle, tempfile, re
|
|
|
|
| 6 |
from sentence_transformers import SentenceTransformer, util
|
| 7 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 8 |
from sklearn.metrics.pairwise import cosine_similarity
|
|
|
|
| 48 |
library_df.get("سنة النشر"), errors="coerce"
|
| 49 |
)
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
# ================== الأعمدة الدلالية ==================
|
| 52 |
def detect_semantic_columns(df):
|
| 53 |
+
exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 54 |
+
include = ["عنوان", "العنوان", "مؤلف", "المؤلف",
|
| 55 |
+
"موضوع", "رءوس", "ملخص", "الملخص", "وصف", "كلمات"]
|
| 56 |
+
|
| 57 |
+
cols = []
|
| 58 |
+
for c in df.columns:
|
| 59 |
+
c = str(c)
|
| 60 |
+
if any(x in c for x in exclude):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
continue
|
| 62 |
+
if any(x in c for x in include):
|
| 63 |
+
cols.append(c)
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
+
return cols or df.select_dtypes(include="object").columns.tolist()
|
| 66 |
|
| 67 |
# ================== Normalize عربي / إنجليزي ==================
|
| 68 |
+
def normalize_text(t):
|
| 69 |
+
t = str(t).lower()
|
| 70 |
+
t = re.sub(r"[^\w\s]", " ", t)
|
| 71 |
+
t = t.replace("أ","ا").replace("إ","ا").replace("آ","ا")
|
| 72 |
+
t = t.replace("ى","ي").replace("ة","ه")
|
| 73 |
+
return re.sub(r"\s+", " ", t).strip()
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
# ================== Embeddings ==================
|
| 76 |
def build_or_load_embeddings(df, name):
|
| 77 |
+
path = os.path.join(EMB_DIR, f"{name}.pkl")
|
|
|
|
| 78 |
if os.path.exists(path):
|
| 79 |
+
with open(path, "rb") as f:
|
| 80 |
+
emb = pickle.load(f)
|
| 81 |
+
if len(emb) == len(df):
|
| 82 |
+
return emb
|
| 83 |
+
|
| 84 |
+
cols = detect_semantic_columns(df)
|
| 85 |
+
|
| 86 |
+
texts = df.apply(
|
| 87 |
+
lambda r: " ".join(
|
| 88 |
+
(str(r[c]) + " ") * (3 if "ملخص" in c else 1)
|
| 89 |
+
for c in cols if str(r[c]).strip()
|
| 90 |
+
),
|
| 91 |
+
axis=1
|
| 92 |
+
).tolist()
|
| 93 |
+
|
| 94 |
+
emb = model.encode(texts, normalize_embeddings=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
with open(path, "wb") as f:
|
| 96 |
pickle.dump(emb, f)
|
|
|
|
| 97 |
return emb
|
| 98 |
|
| 99 |
+
library_df["embedding"] = list(build_or_load_embeddings(library_df, "library"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
# ================== TF-IDF (مرة واحدة) ==================
|
| 102 |
+
semantic_cols = detect_semantic_columns(library_df)
|
| 103 |
+
tfidf_texts = library_df[semantic_cols].astype(str).agg(" ".join, axis=1).map(normalize_text)
|
| 104 |
|
| 105 |
+
tfidf_vectorizer = TfidfVectorizer(ngram_range=(1,2), max_features=20000)
|
| 106 |
+
tfidf_matrix = tfidf_vectorizer.fit_transform(tfidf_texts)
|
| 107 |
|
| 108 |
+
# ================== HTML Cards ==================
|
| 109 |
CUSTOM_CSS = """
|
| 110 |
<style>
|
| 111 |
+
.card{border:1px solid #ddd;border-radius:8px;padding:12px;margin:10px 0;
|
| 112 |
+
direction:rtl;background:#fafafa}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
</style>
|
| 114 |
"""
|
| 115 |
|
|
|
|
| 118 |
return "<p>❌ لا توجد نتائج</p>"
|
| 119 |
|
| 120 |
html = ""
|
| 121 |
+
for _, r in df.iterrows():
|
| 122 |
html += f"""
|
| 123 |
<div class="card">
|
| 124 |
+
<b>{r.get("العنوان","-")}</b><br>
|
| 125 |
+
المؤلف: {r.get("المؤلف","-")}<br>
|
| 126 |
+
سنة النشر: {r.get("سنة النشر","-")}<br>
|
| 127 |
+
الموقع على الرف: {r.get("الموقع على الرف","-")}
|
| 128 |
</div>
|
| 129 |
"""
|
|
|
|
| 130 |
return CUSTOM_CSS + html
|
| 131 |
|
| 132 |
# ================== البحث ==================
|
|
|
|
| 134 |
if not query.strip():
|
| 135 |
return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
|
| 136 |
|
| 137 |
+
df = library_df.copy()
|
| 138 |
|
| 139 |
if source_filter != "الكل":
|
| 140 |
+
df = df[df["المصدر"] == source_filter]
|
| 141 |
|
| 142 |
+
y1, y2 = year_range
|
| 143 |
+
df = df[(df["سنة النشر"] >= y1) & (df["سنة النشر"] <= y2)]
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
+
if df.empty:
|
| 146 |
return "<p>❌ لا توجد بيانات</p>", pd.DataFrame()
|
| 147 |
|
| 148 |
if mode == "نصي":
|
| 149 |
+
mask = df["العنوان"].str.contains(query, case=False, na=False)
|
| 150 |
+
res = df[mask].head(TOP_K)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
else:
|
| 153 |
+
q_vec = tfidf_vectorizer.transform([normalize_text(query)])
|
| 154 |
+
scores = cosine_similarity(q_vec, tfidf_matrix[df.index])[0]
|
| 155 |
+
|
| 156 |
+
df_pref = df.copy()
|
| 157 |
+
df_pref["tfidf"] = scores
|
| 158 |
+
df_pref = df_pref.sort_values("tfidf", ascending=False).head(TFIDF_TOP_N)
|
| 159 |
|
| 160 |
if len(df_pref) < TFIDF_FALLBACK_MIN:
|
| 161 |
+
df_pref = df.copy()
|
| 162 |
|
| 163 |
+
emb_q = model.encode([query], normalize_embeddings=True)
|
| 164 |
+
emb_m = np.vstack(df_pref["embedding"].values)
|
| 165 |
+
df_pref = df_pref.copy()
|
| 166 |
+
df_pref["score"] = util.cos_sim(emb_q, emb_m)[0].cpu().numpy()
|
| 167 |
|
| 168 |
+
res = df_pref.sort_values("score", ascending=False).head(TOP_K)
|
|
|
|
| 169 |
|
| 170 |
+
return results_to_html(res), res.copy()
|
| 171 |
|
| 172 |
# ================== حفظ النتائج ==================
|
| 173 |
def save_to_excel(df):
|
| 174 |
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
|
| 175 |
+
if df is not None and not df.empty:
|
| 176 |
+
df.drop(columns=["embedding","score","tfidf"], errors="ignore") \
|
|
|
|
|
|
|
| 177 |
.to_excel(tmp.name, index=False)
|
| 178 |
return tmp.name
|
| 179 |
|
| 180 |
+
# ================== الواجهة ==================
|
| 181 |
with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
|
|
|
| 182 |
gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
|
| 183 |
|
| 184 |
+
q = gr.Textbox(label="كلمة البحث")
|
| 185 |
+
mode = gr.Radio(["نصي","دلالي (Semantic)"], value="نصي")
|
| 186 |
+
src = gr.Radio(["الكل","كتاب","رسالة"], value="الكل")
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
+
yr = gr.Slider(
|
| 189 |
+
int(library_df["سنة النشر"].min()),
|
| 190 |
+
int(library_df["سنة النشر"].max()),
|
| 191 |
+
value=(int(library_df["سنة النشر"].min()), int(library_df["سنة النشر"].max())),
|
| 192 |
+
step=1, label="سنة النشر"
|
|
|
|
| 193 |
)
|
| 194 |
|
| 195 |
+
btn = gr.Button("بحث")
|
| 196 |
+
out = gr.HTML()
|
| 197 |
+
state = gr.State()
|
| 198 |
+
file = gr.File()
|
| 199 |
|
| 200 |
+
btn.click(local_search_df, [q,mode,src,yr], [out,state])
|
| 201 |
+
gr.Button("تحميل النتائج").click(save_to_excel, state, file)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
app.launch()
|