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