Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,9 +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 |
-
|
| 8 |
from sentence_transformers import SentenceTransformer, util
|
| 9 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 10 |
from sklearn.metrics.pairwise import cosine_similarity
|
|
@@ -17,11 +15,7 @@ THESES_FILE = "theses.xlsx"
|
|
| 17 |
DRIVE_BOOKS_ID = "11gSkJ3edtWj3GAEVrfOcCJXXZrI79tTm"
|
| 18 |
DRIVE_THESES_ID = "1hvZIGFG6h0kQY32bIuEWGRdXTZp84vhk"
|
| 19 |
|
| 20 |
-
EMB_DIR = "embeddings"
|
| 21 |
-
os.makedirs(EMB_DIR, exist_ok=True)
|
| 22 |
-
|
| 23 |
TOP_K = 20
|
| 24 |
-
SIM_THRESHOLD = 0.35
|
| 25 |
TFIDF_TOP_N = 100
|
| 26 |
TFIDF_FALLBACK_MIN = 30
|
| 27 |
|
|
@@ -44,6 +38,16 @@ theses_df = pd.read_excel(THESES_FILE).fillna("")
|
|
| 44 |
books_df["المصدر"] = "كتاب"
|
| 45 |
theses_df["المصدر"] = "رسالة"
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
| 48 |
|
| 49 |
library_df["سنة النشر"] = pd.to_numeric(
|
|
@@ -53,20 +57,14 @@ library_df["سنة النشر"] = pd.to_numeric(
|
|
| 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 |
-
|
| 67 |
-
if any(
|
| 68 |
continue
|
| 69 |
-
if any(
|
| 70 |
cols.append(c)
|
| 71 |
|
| 72 |
if not cols:
|
|
@@ -78,114 +76,67 @@ def detect_semantic_columns(df):
|
|
| 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 |
-
|
| 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 |
-
|
|
|
|
| 127 |
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 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 |
-
|
|
|
|
|
|
|
| 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:
|
| 168 |
-
padding:
|
| 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
|
| 175 |
-
|
| 176 |
-
|
| 177 |
}
|
| 178 |
-
.card
|
| 179 |
-
|
| 180 |
-
|
|
|
|
| 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:
|
|
@@ -195,12 +146,15 @@ def results_to_html(df):
|
|
| 195 |
for _, r in df.iterrows():
|
| 196 |
html += f"""
|
| 197 |
<div class="card">
|
| 198 |
-
|
| 199 |
-
<
|
| 200 |
-
<
|
| 201 |
-
<
|
|
|
|
|
|
|
| 202 |
</div>
|
| 203 |
"""
|
|
|
|
| 204 |
return CUSTOM_CSS + html
|
| 205 |
|
| 206 |
# ================== البحث ==================
|
|
@@ -213,44 +167,38 @@ def local_search_df(query, mode, source_filter, year_range):
|
|
| 213 |
if source_filter != "الكل":
|
| 214 |
df = df[df["المصدر"] == source_filter]
|
| 215 |
|
| 216 |
-
|
| 217 |
-
df = df[(df["سنة النشر"] >=
|
| 218 |
|
| 219 |
if df.empty:
|
| 220 |
return "<p>❌ لا توجد بيانات</p>", pd.DataFrame()
|
| 221 |
|
| 222 |
if mode == "نصي":
|
| 223 |
-
q = query.strip()
|
| 224 |
mask = (
|
| 225 |
-
df["العنوان"].str.contains(
|
| 226 |
-
df
|
| 227 |
)
|
| 228 |
-
|
| 229 |
|
| 230 |
else:
|
| 231 |
df_pref = tfidf_prefilter(df, query)
|
| 232 |
if len(df_pref) < TFIDF_FALLBACK_MIN:
|
| 233 |
-
df_pref = df
|
| 234 |
|
| 235 |
-
q_emb = model.encode([query],
|
| 236 |
-
|
| 237 |
-
scores = util.cos_sim(q_emb,
|
| 238 |
|
| 239 |
-
df_pref = df_pref.copy()
|
| 240 |
df_pref["score"] = scores
|
|
|
|
| 241 |
|
| 242 |
-
|
| 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 |
-
|
| 250 |
-
|
| 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 ==================
|
|
@@ -261,32 +209,20 @@ with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
|
| 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=
|
| 269 |
-
maximum=
|
| 270 |
-
value=(
|
| 271 |
step=1,
|
| 272 |
label="سنة النشر"
|
| 273 |
)
|
| 274 |
|
| 275 |
-
|
| 276 |
-
|
| 277 |
df_state = gr.State()
|
| 278 |
file_out = gr.File(label="⬇️ تحميل النتائج")
|
| 279 |
|
| 280 |
-
|
| 281 |
-
|
| 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()
|
|
|
|
| 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
|
|
|
|
| 15 |
DRIVE_BOOKS_ID = "11gSkJ3edtWj3GAEVrfOcCJXXZrI79tTm"
|
| 16 |
DRIVE_THESES_ID = "1hvZIGFG6h0kQY32bIuEWGRdXTZp84vhk"
|
| 17 |
|
|
|
|
|
|
|
|
|
|
| 18 |
TOP_K = 20
|
|
|
|
| 19 |
TFIDF_TOP_N = 100
|
| 20 |
TFIDF_FALLBACK_MIN = 30
|
| 21 |
|
|
|
|
| 38 |
books_df["المصدر"] = "كتاب"
|
| 39 |
theses_df["المصدر"] = "رسالة"
|
| 40 |
|
| 41 |
+
# 🔴 تثبيت رقم الرف كنص
|
| 42 |
+
for df in [books_df, theses_df]:
|
| 43 |
+
if "الموقع على الرف" in df.columns:
|
| 44 |
+
df["الموقع على الرف"] = (
|
| 45 |
+
df["الموقع على الرف"]
|
| 46 |
+
.astype(str)
|
| 47 |
+
.str.strip()
|
| 48 |
+
.replace(["nan", "NaN", "None", ""], "-")
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
| 52 |
|
| 53 |
library_df["سنة النشر"] = pd.to_numeric(
|
|
|
|
| 57 |
# ================== الأعمدة الدلالية ==================
|
| 58 |
def detect_semantic_columns(df):
|
| 59 |
exclude_keywords = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 60 |
+
include_keywords = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "كلمات"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
cols = []
|
| 63 |
for c in df.columns:
|
| 64 |
+
s = str(c)
|
| 65 |
+
if any(x in s for x in exclude_keywords):
|
| 66 |
continue
|
| 67 |
+
if any(x in s for x in include_keywords):
|
| 68 |
cols.append(c)
|
| 69 |
|
| 70 |
if not cols:
|
|
|
|
| 76 |
def normalize_text(text):
|
| 77 |
text = str(text).lower()
|
| 78 |
text = re.sub(r"[^\w\s]", " ", text)
|
|
|
|
| 79 |
text = text.replace("أ", "ا").replace("إ", "ا").replace("آ", "ا")
|
| 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(" ".join(str(row[c]) for c in semantic_cols if row[c]))
|
| 88 |
|
| 89 |
+
embeddings = model.encode(
|
| 90 |
+
library_df.apply(row_to_text, axis=1).tolist(),
|
| 91 |
+
convert_to_numpy=True,
|
| 92 |
+
normalize_embeddings=True,
|
| 93 |
+
show_progress_bar=True
|
| 94 |
)
|
| 95 |
+
library_df["embedding"] = list(embeddings)
|
| 96 |
|
| 97 |
# ================== TF-IDF ==================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
def tfidf_prefilter(df, query):
|
| 99 |
+
texts = df.apply(row_to_text, axis=1).tolist()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
vec = TfidfVectorizer(ngram_range=(1, 2), max_features=20000)
|
| 102 |
+
mat = vec.fit_transform(texts)
|
| 103 |
+
q_vec = vec.transform([normalize_text(query)])
|
| 104 |
|
| 105 |
+
scores = cosine_similarity(q_vec, mat)[0]
|
| 106 |
df = df.copy()
|
| 107 |
df["tfidf_score"] = scores
|
| 108 |
|
| 109 |
return df.sort_values("tfidf_score", ascending=False).head(TFIDF_TOP_N)
|
| 110 |
|
| 111 |
+
# ================== عرض النتائج (Card = Table) ==================
|
| 112 |
CUSTOM_CSS = """
|
| 113 |
<style>
|
| 114 |
.card{
|
| 115 |
border:1px solid #ddd;
|
| 116 |
+
border-radius:8px;
|
| 117 |
+
padding:10px;
|
| 118 |
margin:12px 0;
|
| 119 |
+
background:#fafafa;
|
| 120 |
+
}
|
| 121 |
+
.card table{
|
| 122 |
+
width:100%;
|
| 123 |
+
border-collapse:collapse;
|
| 124 |
direction:rtl;
|
|
|
|
|
|
|
| 125 |
}
|
| 126 |
+
.card td{
|
| 127 |
+
border:1px solid #ccc;
|
| 128 |
+
padding:6px;
|
| 129 |
}
|
| 130 |
+
.card td.label{
|
| 131 |
+
background:#f0f0f0;
|
| 132 |
+
width:30%;
|
| 133 |
+
font-weight:bold;
|
| 134 |
}
|
| 135 |
</style>
|
| 136 |
"""
|
| 137 |
|
| 138 |
def safe(v):
|
| 139 |
+
return "-" if pd.isna(v) or str(v).strip() == "" else str(v)
|
|
|
|
|
|
|
| 140 |
|
| 141 |
def results_to_html(df):
|
| 142 |
if df.empty:
|
|
|
|
| 146 |
for _, r in df.iterrows():
|
| 147 |
html += f"""
|
| 148 |
<div class="card">
|
| 149 |
+
<table>
|
| 150 |
+
<tr><td class="label">العنوان</td><td>{safe(r.get("العنوان"))}</td></tr>
|
| 151 |
+
<tr><td class="label">المؤلف</td><td>{safe(r.get("المؤلف"))}</td></tr>
|
| 152 |
+
<tr><td class="label">سنة النشر</td><td>{safe(r.get("سنة النشر"))}</td></tr>
|
| 153 |
+
<tr><td class="label">الموقع على الرف</td><td>{safe(r.get("الموقع على الرف"))}</td></tr>
|
| 154 |
+
</table>
|
| 155 |
</div>
|
| 156 |
"""
|
| 157 |
+
|
| 158 |
return CUSTOM_CSS + html
|
| 159 |
|
| 160 |
# ================== البحث ==================
|
|
|
|
| 167 |
if source_filter != "الكل":
|
| 168 |
df = df[df["المصدر"] == source_filter]
|
| 169 |
|
| 170 |
+
start, end = year_range
|
| 171 |
+
df = df[(df["سنة النشر"] >= start) & (df["سنة النشر"] <= end)]
|
| 172 |
|
| 173 |
if df.empty:
|
| 174 |
return "<p>❌ لا توجد بيانات</p>", pd.DataFrame()
|
| 175 |
|
| 176 |
if mode == "نصي":
|
|
|
|
| 177 |
mask = (
|
| 178 |
+
df["العنوان"].str.contains(query, case=False, na=False) |
|
| 179 |
+
df["المؤلف"].str.contains(query, case=False, na=False)
|
| 180 |
)
|
| 181 |
+
df = df[mask].head(TOP_K)
|
| 182 |
|
| 183 |
else:
|
| 184 |
df_pref = tfidf_prefilter(df, query)
|
| 185 |
if len(df_pref) < TFIDF_FALLBACK_MIN:
|
| 186 |
+
df_pref = df
|
| 187 |
|
| 188 |
+
q_emb = model.encode([normalize_text(query)], normalize_embeddings=True)
|
| 189 |
+
mat = np.vstack(df_pref["embedding"].values)
|
| 190 |
+
scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
|
| 191 |
|
|
|
|
| 192 |
df_pref["score"] = scores
|
| 193 |
+
df = df_pref.sort_values("score", ascending=False).head(TOP_K)
|
| 194 |
|
| 195 |
+
return results_to_html(df), df
|
|
|
|
|
|
|
| 196 |
|
| 197 |
# ================== حفظ النتائج ==================
|
| 198 |
def save_to_excel(df):
|
| 199 |
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
|
| 200 |
+
df.drop(columns=["embedding", "score", "tfidf_score"], errors="ignore") \
|
| 201 |
+
.to_excel(tmp.name, index=False)
|
|
|
|
|
|
|
|
|
|
| 202 |
return tmp.name
|
| 203 |
|
| 204 |
# ================== واجهة Gradio ==================
|
|
|
|
| 209 |
mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="نصي", label="نوع البحث")
|
| 210 |
source_filter = gr.Radio(["الكل", "كتاب", "رسالة"], value="الكل", label="المصدر")
|
| 211 |
|
|
|
|
|
|
|
|
|
|
| 212 |
year_range = gr.Slider(
|
| 213 |
+
minimum=int(library_df["سنة النشر"].min()),
|
| 214 |
+
maximum=int(library_df["سنة النشر"].max()),
|
| 215 |
+
value=(int(library_df["سنة النشر"].min()), int(library_df["سنة النشر"].max())),
|
| 216 |
step=1,
|
| 217 |
label="سنة النشر"
|
| 218 |
)
|
| 219 |
|
| 220 |
+
btn = gr.Button("🔎 بحث")
|
| 221 |
+
out_html = gr.HTML()
|
| 222 |
df_state = gr.State()
|
| 223 |
file_out = gr.File(label="⬇️ تحميل النتائج")
|
| 224 |
|
| 225 |
+
btn.click(local_search_df, [query, mode, source_filter, year_range], [out_html, df_state])
|
| 226 |
+
gr.Button("📥 حفظ النتائج").click(save_to_excel, df_state, file_out)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
|
| 228 |
app.launch()
|