Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,6 +6,7 @@ import os, 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
|
|
|
|
| 9 |
import gdown
|
| 10 |
|
| 11 |
# ================== إعدادات ==================
|
|
@@ -35,33 +36,27 @@ download_from_drive(DRIVE_THESES_ID, THESES_FILE)
|
|
| 35 |
|
| 36 |
# ================== تحميل البيانات ==================
|
| 37 |
books_df = pd.read_excel(BOOKS_FILE).fillna("")
|
| 38 |
-
|
| 39 |
|
| 40 |
-
|
| 41 |
-
sections = []
|
| 42 |
-
current_section = ""
|
| 43 |
-
theses_rows = []
|
| 44 |
-
|
| 45 |
-
for _, row in theses_df_raw.iterrows():
|
| 46 |
-
combined_text = " ".join(str(row[c]) for c in theses_df_raw.columns if row[c])
|
| 47 |
-
combined_text = combined_text.strip()
|
| 48 |
-
# إذا الصف طويل ويحتوي على كلمات القسم
|
| 49 |
-
if "جامعة" in combined_text or "مكتبة" in combined_text:
|
| 50 |
-
current_section = combined_text
|
| 51 |
-
else:
|
| 52 |
-
row["القسم"] = current_section
|
| 53 |
-
theses_rows.append(row)
|
| 54 |
-
|
| 55 |
-
theses_df = pd.DataFrame(theses_rows)
|
| 56 |
theses_df["المصدر"] = "رسالة"
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
| 59 |
|
| 60 |
# ================== الأعمدة الدلالية ==================
|
| 61 |
def detect_semantic_columns(df):
|
| 62 |
exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 63 |
-
include = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "كلمات"]
|
| 64 |
-
|
| 65 |
cols = []
|
| 66 |
for c in df.columns:
|
| 67 |
s = str(c)
|
|
@@ -69,10 +64,8 @@ def detect_semantic_columns(df):
|
|
| 69 |
continue
|
| 70 |
if any(x in s for x in include):
|
| 71 |
cols.append(c)
|
| 72 |
-
|
| 73 |
if not cols:
|
| 74 |
cols = df.select_dtypes(include="object").columns.tolist()
|
| 75 |
-
|
| 76 |
return cols
|
| 77 |
|
| 78 |
semantic_cols = detect_semantic_columns(library_df)
|
|
@@ -88,16 +81,13 @@ def normalize_text(text):
|
|
| 88 |
def row_to_text(row):
|
| 89 |
text = " ".join(str(row[c]) for c in semantic_cols if row[c])
|
| 90 |
text = normalize_text(text)
|
| 91 |
-
|
| 92 |
# Boost للمصطلحات الطبية
|
| 93 |
if any(x in text for x in ["cardio", "toxic", "toxicity"]):
|
| 94 |
text += " cardiotoxicity cardiac toxicity cardiotoxic effects"
|
| 95 |
-
|
| 96 |
return text
|
| 97 |
|
| 98 |
# ================== Embeddings ==================
|
| 99 |
texts = library_df.apply(row_to_text, axis=1).tolist()
|
| 100 |
-
|
| 101 |
embeddings = model.encode(
|
| 102 |
texts,
|
| 103 |
convert_to_numpy=True,
|
|
@@ -109,18 +99,12 @@ library_df["embedding"] = list(embeddings)
|
|
| 109 |
# ================== TF-IDF ==================
|
| 110 |
def tfidf_prefilter(df, query):
|
| 111 |
texts = df.apply(row_to_text, axis=1).tolist()
|
| 112 |
-
vec = TfidfVectorizer(
|
| 113 |
-
ngram_range=(1, 3),
|
| 114 |
-
max_features=30000,
|
| 115 |
-
stop_words="english"
|
| 116 |
-
)
|
| 117 |
mat = vec.fit_transform(texts)
|
| 118 |
q_vec = vec.transform([normalize_text(query)])
|
| 119 |
-
|
| 120 |
scores = cosine_similarity(q_vec, mat)[0]
|
| 121 |
df = df.copy()
|
| 122 |
df["tfidf_score"] = scores
|
| 123 |
-
|
| 124 |
return df.sort_values("tfidf_score", ascending=False).head(TFIDF_TOP_N)
|
| 125 |
|
| 126 |
# ================== CSS ==================
|
|
@@ -133,8 +117,9 @@ CUSTOM_CSS = """
|
|
| 133 |
.row-title td{background:#e3f2fd;color:#0d47a1;font-weight:bold;}
|
| 134 |
.row-author td{background:#fce4ec;color:#880e4f;}
|
| 135 |
.row-year td{background:#e8f5e9;color:#1b5e20;}
|
|
|
|
|
|
|
| 136 |
.row-shelf td{background:#fff8e1;color:#e65100;font-weight:bold;font-size:16px;}
|
| 137 |
-
.row-section td{background:#fff3e0;color:#bf360c;font-weight:bold;}
|
| 138 |
</style>
|
| 139 |
"""
|
| 140 |
|
|
@@ -144,99 +129,71 @@ def safe(v):
|
|
| 144 |
def results_to_html(df):
|
| 145 |
if df.empty:
|
| 146 |
return "<p>❌ لا توجد نتائج</p>"
|
| 147 |
-
|
| 148 |
html = ""
|
| 149 |
for _, r in df.iterrows():
|
| 150 |
html += f"""
|
| 151 |
<div class="card">
|
| 152 |
<table>
|
| 153 |
-
<tr class="row-title">
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
</tr>
|
| 157 |
-
<tr class="row-
|
| 158 |
-
|
| 159 |
-
<td>{safe(r.get("المؤلف"))}</td>
|
| 160 |
-
</tr>
|
| 161 |
-
<tr class="row-year">
|
| 162 |
-
<td class="label">سنة النشر</td>
|
| 163 |
-
<td>{safe(r.get("سنة النشر"))}</td>
|
| 164 |
-
</tr>
|
| 165 |
-
<tr class="row-section">
|
| 166 |
-
<td class="label">القسم</td>
|
| 167 |
-
<td>{safe(r.get("القسم"))}</td>
|
| 168 |
-
</tr>
|
| 169 |
-
<tr class="row-shelf">
|
| 170 |
-
<td class="label">الموقع على الرف</td>
|
| 171 |
-
<td>{safe(r.get("الموقع على الرف"))}</td>
|
| 172 |
-
</tr>
|
| 173 |
</table>
|
| 174 |
</div>
|
| 175 |
"""
|
| 176 |
-
|
| 177 |
return CUSTOM_CSS + html
|
| 178 |
|
| 179 |
# ================== البحث ==================
|
| 180 |
-
def local_search_df(query, mode,
|
| 181 |
-
if not query.strip():
|
| 182 |
-
return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
|
| 183 |
-
|
| 184 |
df = library_df.copy()
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
if source_filter != "الكل":
|
| 188 |
-
df = df[df["المصدر"] == source_filter]
|
| 189 |
-
|
| 190 |
-
# تصفية حسب السنة
|
| 191 |
if year_from:
|
| 192 |
-
df = df[df["سنة النشر"].
|
| 193 |
if year_to:
|
| 194 |
-
df = df[df["سنة النشر"].
|
| 195 |
-
|
|
|
|
|
|
|
| 196 |
if mode == "نصي":
|
| 197 |
-
|
| 198 |
-
mask = df.apply(lambda r: q in row_to_text(r), axis=1)
|
| 199 |
df = df[mask].head(TOP_K)
|
| 200 |
else:
|
| 201 |
df_pref = tfidf_prefilter(df, query)
|
| 202 |
if len(df_pref) < TFIDF_FALLBACK_MIN:
|
| 203 |
df_pref = df
|
| 204 |
-
|
| 205 |
-
q_emb = model.encode([normalize_text(query)], normalize_embeddings=True)
|
| 206 |
mat = np.vstack(df_pref["embedding"].values)
|
| 207 |
scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
|
| 208 |
-
|
| 209 |
df_pref["score"] = scores
|
| 210 |
df = df_pref.sort_values("score", ascending=False).head(TOP_K)
|
| 211 |
-
|
| 212 |
return results_to_html(df), df
|
| 213 |
|
| 214 |
# ================== حفظ النتائج ==================
|
| 215 |
def save_to_excel(df):
|
| 216 |
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
|
| 217 |
-
df.drop(columns=["embedding", "score", "tfidf_score"], errors="ignore")
|
| 218 |
-
.to_excel(tmp.name, index=False)
|
| 219 |
return tmp.name
|
| 220 |
|
| 221 |
# ================== واجهة Gradio ==================
|
| 222 |
with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
| 223 |
gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
|
| 224 |
-
|
| 225 |
query = gr.Textbox(label="كلمة أو موضوع البحث")
|
| 226 |
mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="دلالي (Semantic)", label="نوع البحث")
|
| 227 |
-
|
| 228 |
year_from = gr.Textbox(label="من سنة", placeholder="مثال: 2010")
|
| 229 |
year_to = gr.Textbox(label="إلى سنة", placeholder="مثال: 2025")
|
| 230 |
-
|
| 231 |
btn = gr.Button("🔎 بحث")
|
| 232 |
out_html = gr.HTML()
|
| 233 |
df_state = gr.State()
|
| 234 |
file_out = gr.File(label="⬇️ تحميل النتائج")
|
| 235 |
-
|
| 236 |
-
btn.click(local_search_df, [query, mode, source_filter, year_from, year_to], [out_html, df_state])
|
| 237 |
gr.Button("📥 حفظ النتائج").click(save_to_excel, df_state, file_out)
|
| 238 |
|
| 239 |
app.launch()
|
| 240 |
|
| 241 |
|
| 242 |
|
|
|
|
|
|
| 6 |
from sentence_transformers import SentenceTransformer, util
|
| 7 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 8 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 9 |
+
from fuzzywuzzy import fuzz
|
| 10 |
import gdown
|
| 11 |
|
| 12 |
# ================== إعدادات ==================
|
|
|
|
| 36 |
|
| 37 |
# ================== تحميل البيانات ==================
|
| 38 |
books_df = pd.read_excel(BOOKS_FILE).fillna("")
|
| 39 |
+
theses_df = pd.read_excel(THESES_FILE).fillna("")
|
| 40 |
|
| 41 |
+
books_df["المصدر"] = "كتاب"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
theses_df["المصدر"] = "رسالة"
|
| 43 |
|
| 44 |
+
# ================== استخراج الأقسام ==================
|
| 45 |
+
current_section = ""
|
| 46 |
+
sections = []
|
| 47 |
+
for idx, row in theses_df.iterrows():
|
| 48 |
+
first_col = str(row[0]).strip()
|
| 49 |
+
if "جامعة" in first_col:
|
| 50 |
+
current_section = first_col
|
| 51 |
+
sections.append(current_section)
|
| 52 |
+
theses_df["القسم"] = sections
|
| 53 |
+
|
| 54 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
| 55 |
|
| 56 |
# ================== الأعمدة الدلالية ==================
|
| 57 |
def detect_semantic_columns(df):
|
| 58 |
exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 59 |
+
include = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "نوع درجة الرسالة العلمية ", "كلمات"]
|
|
|
|
| 60 |
cols = []
|
| 61 |
for c in df.columns:
|
| 62 |
s = str(c)
|
|
|
|
| 64 |
continue
|
| 65 |
if any(x in s for x in include):
|
| 66 |
cols.append(c)
|
|
|
|
| 67 |
if not cols:
|
| 68 |
cols = df.select_dtypes(include="object").columns.tolist()
|
|
|
|
| 69 |
return cols
|
| 70 |
|
| 71 |
semantic_cols = detect_semantic_columns(library_df)
|
|
|
|
| 81 |
def row_to_text(row):
|
| 82 |
text = " ".join(str(row[c]) for c in semantic_cols if row[c])
|
| 83 |
text = normalize_text(text)
|
|
|
|
| 84 |
# Boost للمصطلحات الطبية
|
| 85 |
if any(x in text for x in ["cardio", "toxic", "toxicity"]):
|
| 86 |
text += " cardiotoxicity cardiac toxicity cardiotoxic effects"
|
|
|
|
| 87 |
return text
|
| 88 |
|
| 89 |
# ================== Embeddings ==================
|
| 90 |
texts = library_df.apply(row_to_text, axis=1).tolist()
|
|
|
|
| 91 |
embeddings = model.encode(
|
| 92 |
texts,
|
| 93 |
convert_to_numpy=True,
|
|
|
|
| 99 |
# ================== TF-IDF ==================
|
| 100 |
def tfidf_prefilter(df, query):
|
| 101 |
texts = df.apply(row_to_text, axis=1).tolist()
|
| 102 |
+
vec = TfidfVectorizer(ngram_range=(1, 3), max_features=30000, stop_words="english")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
mat = vec.fit_transform(texts)
|
| 104 |
q_vec = vec.transform([normalize_text(query)])
|
|
|
|
| 105 |
scores = cosine_similarity(q_vec, mat)[0]
|
| 106 |
df = df.copy()
|
| 107 |
df["tfidf_score"] = scores
|
|
|
|
| 108 |
return df.sort_values("tfidf_score", ascending=False).head(TFIDF_TOP_N)
|
| 109 |
|
| 110 |
# ================== CSS ==================
|
|
|
|
| 117 |
.row-title td{background:#e3f2fd;color:#0d47a1;font-weight:bold;}
|
| 118 |
.row-author td{background:#fce4ec;color:#880e4f;}
|
| 119 |
.row-year td{background:#e8f5e9;color:#1b5e20;}
|
| 120 |
+
.row-degree td{background:#fff3e0;color:#ef6c00;font-weight:bold;}
|
| 121 |
+
.row-section td{background:#f3e5f5;color:#6a1b9a;font-weight:bold;}
|
| 122 |
.row-shelf td{background:#fff8e1;color:#e65100;font-weight:bold;font-size:16px;}
|
|
|
|
| 123 |
</style>
|
| 124 |
"""
|
| 125 |
|
|
|
|
| 129 |
def results_to_html(df):
|
| 130 |
if df.empty:
|
| 131 |
return "<p>❌ لا توجد نتائج</p>"
|
|
|
|
| 132 |
html = ""
|
| 133 |
for _, r in df.iterrows():
|
| 134 |
html += f"""
|
| 135 |
<div class="card">
|
| 136 |
<table>
|
| 137 |
+
<tr class="row-title"><td class="label">العنوان</td><td>{safe(r.get("العنوان"))}</td></tr>
|
| 138 |
+
<tr class="row-author"><td class="label">المؤلف</td><td>{safe(r.get("المؤلف"))}</td></tr>
|
| 139 |
+
<tr class="row-degree"><td class="label">نوع درجة الرسالة العلمية</td><td>{safe(r.get("نوع درجة الرسالة العلمية "))}</td></tr>
|
| 140 |
+
<tr class="row-section"><td class="label">القسم</td><td>{safe(r.get("القسم"))}</td></tr>
|
| 141 |
+
<tr class="row-year"><td class="label">سنة النشر</td><td>{safe(r.get("سنة النشر"))}</td></tr>
|
| 142 |
+
<tr class="row-shelf"><td class="label">الموقع على الرف</td><td>{safe(r.get("الموقع على الرف"))}</td></tr>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
</table>
|
| 144 |
</div>
|
| 145 |
"""
|
|
|
|
| 146 |
return CUSTOM_CSS + html
|
| 147 |
|
| 148 |
# ================== البحث ==================
|
| 149 |
+
def local_search_df(query, mode, category, year_from, year_to):
|
|
|
|
|
|
|
|
|
|
| 150 |
df = library_df.copy()
|
| 151 |
+
if category != "الكل":
|
| 152 |
+
df = df[df["المصدر"] == category]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
if year_from:
|
| 154 |
+
df = df[df["سنة النشر"].apply(lambda x: str(x).isdigit() and int(x) >= int(year_from))]
|
| 155 |
if year_to:
|
| 156 |
+
df = df[df["سنة النشر"].apply(lambda x: str(x).isdigit() and int(x) <= int(year_to))]
|
| 157 |
+
if not query.strip():
|
| 158 |
+
return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
|
| 159 |
+
q_norm = normalize_text(query)
|
| 160 |
if mode == "نصي":
|
| 161 |
+
mask = df.apply(lambda r: fuzz.partial_ratio(q_norm, row_to_text(r)) > 70, axis=1)
|
|
|
|
| 162 |
df = df[mask].head(TOP_K)
|
| 163 |
else:
|
| 164 |
df_pref = tfidf_prefilter(df, query)
|
| 165 |
if len(df_pref) < TFIDF_FALLBACK_MIN:
|
| 166 |
df_pref = df
|
| 167 |
+
q_emb = model.encode([q_norm], normalize_embeddings=True)
|
|
|
|
| 168 |
mat = np.vstack(df_pref["embedding"].values)
|
| 169 |
scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
|
|
|
|
| 170 |
df_pref["score"] = scores
|
| 171 |
df = df_pref.sort_values("score", ascending=False).head(TOP_K)
|
|
|
|
| 172 |
return results_to_html(df), df
|
| 173 |
|
| 174 |
# ================== حفظ النتائج ==================
|
| 175 |
def save_to_excel(df):
|
| 176 |
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
|
| 177 |
+
df.drop(columns=["embedding", "score", "tfidf_score"], errors="ignore").to_excel(tmp.name, index=False)
|
|
|
|
| 178 |
return tmp.name
|
| 179 |
|
| 180 |
# ================== واجهة Gradio ==================
|
| 181 |
with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
| 182 |
gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
|
|
|
|
| 183 |
query = gr.Textbox(label="كلمة أو موضوع البحث")
|
| 184 |
mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="دلالي (Semantic)", label="نوع البحث")
|
| 185 |
+
category = gr.Radio(["الكل", "كتاب", "رسالة"], value="الكل", label="اختر الفئة")
|
| 186 |
year_from = gr.Textbox(label="من سنة", placeholder="مثال: 2010")
|
| 187 |
year_to = gr.Textbox(label="إلى سنة", placeholder="مثال: 2025")
|
|
|
|
| 188 |
btn = gr.Button("🔎 بحث")
|
| 189 |
out_html = gr.HTML()
|
| 190 |
df_state = gr.State()
|
| 191 |
file_out = gr.File(label="⬇️ تحميل النتائج")
|
| 192 |
+
btn.click(local_search_df, [query, mode, category, year_from, year_to], [out_html, df_state])
|
|
|
|
| 193 |
gr.Button("📥 حفظ النتائج").click(save_to_excel, df_state, file_out)
|
| 194 |
|
| 195 |
app.launch()
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
+
|