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