Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 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 |
import gdown
|
| 8 |
|
|
@@ -20,8 +20,7 @@ TOP_K = 20
|
|
| 20 |
SIM_THRESHOLD = 0.35
|
| 21 |
|
| 22 |
# ================== تحميل نموذج Semantic ==================
|
| 23 |
-
|
| 24 |
-
model = SentenceTransformer(MODEL_NAME)
|
| 25 |
|
| 26 |
# ================== تحميل من Google Drive ==================
|
| 27 |
def download_from_drive(file_id, output):
|
|
@@ -39,7 +38,6 @@ theses_df = pd.read_excel(THESES_FILE).fillna("")
|
|
| 39 |
books_df["المصدر"] = "كتاب"
|
| 40 |
theses_df["المصدر"] = "رسالة"
|
| 41 |
|
| 42 |
-
# ================== دمج البيانات ==================
|
| 43 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
| 44 |
|
| 45 |
# ================== تجهيز سنة النشر ==================
|
|
@@ -51,19 +49,31 @@ library_df["سنة النشر"] = pd.to_numeric(
|
|
| 51 |
def emb_path(name):
|
| 52 |
return os.path.join(EMB_DIR, f"{name}.pkl")
|
| 53 |
|
| 54 |
-
# ================== تحديد الأعمدة الدلالية
|
| 55 |
def detect_semantic_columns(df):
|
| 56 |
exclude_keywords = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 57 |
-
include_keywords = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
semantic_cols = []
|
| 60 |
for col in df.columns:
|
| 61 |
-
col_str = str(col)
|
|
|
|
| 62 |
if any(k in col_str for k in exclude_keywords):
|
| 63 |
continue
|
|
|
|
| 64 |
if any(k in col_str for k in include_keywords):
|
| 65 |
semantic_cols.append(col)
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
return semantic_cols
|
| 68 |
|
| 69 |
# ================== بناء أو تحميل embeddings ==================
|
|
@@ -86,7 +96,8 @@ def build_or_load_embeddings(df, name):
|
|
| 86 |
for col in semantic_cols:
|
| 87 |
val = str(row[col]).strip()
|
| 88 |
if val:
|
| 89 |
-
|
|
|
|
| 90 |
return " ".join(parts)
|
| 91 |
|
| 92 |
texts = df.apply(row_to_text, axis=1).tolist()
|
|
@@ -94,8 +105,8 @@ def build_or_load_embeddings(df, name):
|
|
| 94 |
emb = model.encode(
|
| 95 |
texts,
|
| 96 |
convert_to_numpy=True,
|
| 97 |
-
|
| 98 |
-
|
| 99 |
)
|
| 100 |
|
| 101 |
with open(path, "wb") as f:
|
|
@@ -111,11 +122,9 @@ CUSTOM_CSS = """
|
|
| 111 |
<style>
|
| 112 |
.styled-table{
|
| 113 |
border-collapse:collapse;
|
| 114 |
-
margin:15px 0;
|
| 115 |
-
font-size:14px;
|
| 116 |
width:100%;
|
| 117 |
-
text-align:right;
|
| 118 |
direction:rtl;
|
|
|
|
| 119 |
}
|
| 120 |
.styled-table th,.styled-table td{
|
| 121 |
border:1px solid #ddd;
|
|
@@ -132,65 +141,57 @@ CUSTOM_CSS = """
|
|
| 132 |
# ================== عرض النتائج ==================
|
| 133 |
def results_to_html(df):
|
| 134 |
if df.empty:
|
| 135 |
-
return "<p>❌ ل
|
| 136 |
|
| 137 |
cols = ["المؤلف", "العنوان", "سنة النشر", "الموقع على الرف", "المصدر"]
|
| 138 |
for c in cols:
|
| 139 |
if c not in df.columns:
|
| 140 |
df[c] = "-"
|
| 141 |
|
| 142 |
-
|
| 143 |
index=False,
|
| 144 |
escape=False,
|
| 145 |
classes="styled-table",
|
| 146 |
border=0
|
| 147 |
)
|
| 148 |
|
| 149 |
-
return CUSTOM_CSS + html
|
| 150 |
-
|
| 151 |
# ================== البحث ==================
|
| 152 |
def local_search_df(query, mode, source_filter, year_range):
|
| 153 |
if not query.strip():
|
| 154 |
-
return "<p>⚠️ اكتب كلمة
|
| 155 |
|
| 156 |
df_search = library_df.copy()
|
| 157 |
|
| 158 |
-
# فلترة المصدر
|
| 159 |
if source_filter != "الكل":
|
| 160 |
df_search = df_search[df_search["المصدر"] == source_filter]
|
| 161 |
|
| 162 |
-
# فلترة سنة النشر
|
| 163 |
start_year, end_year = year_range
|
| 164 |
df_search = df_search[
|
| 165 |
(df_search["سنة النشر"] >= start_year) &
|
| 166 |
(df_search["سنة النشر"] <= end_year)
|
| 167 |
]
|
| 168 |
|
| 169 |
-
|
|
|
|
|
|
|
| 170 |
if mode == "نصي":
|
| 171 |
q = query.strip()
|
| 172 |
mask = (
|
| 173 |
df_search["العنوان"].str.contains(q, case=False, na=False) |
|
| 174 |
-
df_search.get("المؤلف",
|
| 175 |
)
|
| 176 |
df = df_search[mask].head(TOP_K)
|
| 177 |
|
| 178 |
-
# البحث الدلالي
|
| 179 |
else:
|
| 180 |
-
q_emb = model.encode(
|
| 181 |
-
[query],
|
| 182 |
-
convert_to_numpy=True,
|
| 183 |
-
normalize_embeddings=True
|
| 184 |
-
)
|
| 185 |
emb_matrix = np.vstack(df_search["embedding"].values)
|
| 186 |
scores = util.cos_sim(q_emb, emb_matrix)[0].cpu().numpy()
|
| 187 |
df_search["score"] = scores
|
| 188 |
|
| 189 |
filtered = df_search[df_search["score"] >= SIM_THRESHOLD]
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
df = filtered.sort_values("score", ascending=False).head(TOP_K)
|
| 194 |
|
| 195 |
return results_to_html(df), df
|
| 196 |
|
|
@@ -209,19 +210,9 @@ with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
|
| 209 |
|
| 210 |
gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
|
| 211 |
|
| 212 |
-
query = gr.Textbox(label="
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
["نصي", "دلالي (Semantic)"],
|
| 216 |
-
value="نصي",
|
| 217 |
-
label="نوع البحث"
|
| 218 |
-
)
|
| 219 |
-
|
| 220 |
-
source_filter = gr.Radio(
|
| 221 |
-
["الكل", "كتاب", "رسالة"],
|
| 222 |
-
value="الكل",
|
| 223 |
-
label="المصدر"
|
| 224 |
-
)
|
| 225 |
|
| 226 |
year_min = int(library_df["سنة النشر"].min())
|
| 227 |
year_max = int(library_df["سنة النشر"].max())
|
|
@@ -231,13 +222,12 @@ with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
|
| 231 |
maximum=year_max,
|
| 232 |
value=(year_min, year_max),
|
| 233 |
step=1,
|
| 234 |
-
label="
|
| 235 |
)
|
| 236 |
|
| 237 |
btn_search = gr.Button("🔎 بحث")
|
| 238 |
-
|
| 239 |
-
df_state = gr.State()
|
| 240 |
output_html = gr.HTML()
|
|
|
|
| 241 |
file_out = gr.File(label="⬇️ تحميل النتائج")
|
| 242 |
|
| 243 |
btn_search.click(
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
+
import os, pickle, tempfile, shutil
|
| 6 |
from sentence_transformers import SentenceTransformer, util
|
| 7 |
import gdown
|
| 8 |
|
|
|
|
| 20 |
SIM_THRESHOLD = 0.35
|
| 21 |
|
| 22 |
# ================== تحميل نموذج Semantic ==================
|
| 23 |
+
model = SentenceTransformer("all-MiniLM-L6-v2")
|
|
|
|
| 24 |
|
| 25 |
# ================== تحميل من Google Drive ==================
|
| 26 |
def download_from_drive(file_id, output):
|
|
|
|
| 38 |
books_df["المصدر"] = "كتاب"
|
| 39 |
theses_df["المصدر"] = "رسالة"
|
| 40 |
|
|
|
|
| 41 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
| 42 |
|
| 43 |
# ================== تجهيز سنة النشر ==================
|
|
|
|
| 49 |
def emb_path(name):
|
| 50 |
return os.path.join(EMB_DIR, f"{name}.pkl")
|
| 51 |
|
| 52 |
+
# ================== تحديد الأعمدة الدلالية (نهائي) ==================
|
| 53 |
def detect_semantic_columns(df):
|
| 54 |
exclude_keywords = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 55 |
+
include_keywords = [
|
| 56 |
+
"عنوان", "العنوان",
|
| 57 |
+
"مؤلف", "المؤلف",
|
| 58 |
+
"موضوع", "رءوس",
|
| 59 |
+
"ملخص", "الملخص",
|
| 60 |
+
"وصف", "كلمات"
|
| 61 |
+
]
|
| 62 |
|
| 63 |
semantic_cols = []
|
| 64 |
for col in df.columns:
|
| 65 |
+
col_str = str(col).strip()
|
| 66 |
+
|
| 67 |
if any(k in col_str for k in exclude_keywords):
|
| 68 |
continue
|
| 69 |
+
|
| 70 |
if any(k in col_str for k in include_keywords):
|
| 71 |
semantic_cols.append(col)
|
| 72 |
|
| 73 |
+
# Fallback أمان
|
| 74 |
+
if not semantic_cols:
|
| 75 |
+
semantic_cols = df.select_dtypes(include="object").columns.tolist()
|
| 76 |
+
|
| 77 |
return semantic_cols
|
| 78 |
|
| 79 |
# ================== بناء أو تحميل embeddings ==================
|
|
|
|
| 96 |
for col in semantic_cols:
|
| 97 |
val = str(row[col]).strip()
|
| 98 |
if val:
|
| 99 |
+
weight = 3 if ("ملخص" in col or "رءوس" in col) else 1
|
| 100 |
+
parts.append((f"{col}: {val} ") * weight)
|
| 101 |
return " ".join(parts)
|
| 102 |
|
| 103 |
texts = df.apply(row_to_text, axis=1).tolist()
|
|
|
|
| 105 |
emb = model.encode(
|
| 106 |
texts,
|
| 107 |
convert_to_numpy=True,
|
| 108 |
+
normalize_embeddings=True,
|
| 109 |
+
show_progress_bar=True
|
| 110 |
)
|
| 111 |
|
| 112 |
with open(path, "wb") as f:
|
|
|
|
| 122 |
<style>
|
| 123 |
.styled-table{
|
| 124 |
border-collapse:collapse;
|
|
|
|
|
|
|
| 125 |
width:100%;
|
|
|
|
| 126 |
direction:rtl;
|
| 127 |
+
font-size:14px;
|
| 128 |
}
|
| 129 |
.styled-table th,.styled-table td{
|
| 130 |
border:1px solid #ddd;
|
|
|
|
| 141 |
# ================== عرض النتائج ==================
|
| 142 |
def results_to_html(df):
|
| 143 |
if df.empty:
|
| 144 |
+
return "<p>❌ لا توجد نتائج</p>"
|
| 145 |
|
| 146 |
cols = ["المؤلف", "العنوان", "سنة النشر", "الموقع على الرف", "المصدر"]
|
| 147 |
for c in cols:
|
| 148 |
if c not in df.columns:
|
| 149 |
df[c] = "-"
|
| 150 |
|
| 151 |
+
return CUSTOM_CSS + df[cols].to_html(
|
| 152 |
index=False,
|
| 153 |
escape=False,
|
| 154 |
classes="styled-table",
|
| 155 |
border=0
|
| 156 |
)
|
| 157 |
|
|
|
|
|
|
|
| 158 |
# ================== البحث ==================
|
| 159 |
def local_search_df(query, mode, source_filter, year_range):
|
| 160 |
if not query.strip():
|
| 161 |
+
return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
|
| 162 |
|
| 163 |
df_search = library_df.copy()
|
| 164 |
|
|
|
|
| 165 |
if source_filter != "الكل":
|
| 166 |
df_search = df_search[df_search["المصدر"] == source_filter]
|
| 167 |
|
|
|
|
| 168 |
start_year, end_year = year_range
|
| 169 |
df_search = df_search[
|
| 170 |
(df_search["سنة النشر"] >= start_year) &
|
| 171 |
(df_search["سنة النشر"] <= end_year)
|
| 172 |
]
|
| 173 |
|
| 174 |
+
if df_search.empty:
|
| 175 |
+
return "<p>❌ لا توجد بيانات بعد الفلترة</p>", pd.DataFrame()
|
| 176 |
+
|
| 177 |
if mode == "نصي":
|
| 178 |
q = query.strip()
|
| 179 |
mask = (
|
| 180 |
df_search["العنوان"].str.contains(q, case=False, na=False) |
|
| 181 |
+
df_search.get("المؤلف","").str.contains(q, case=False, na=False)
|
| 182 |
)
|
| 183 |
df = df_search[mask].head(TOP_K)
|
| 184 |
|
|
|
|
| 185 |
else:
|
| 186 |
+
q_emb = model.encode([query], convert_to_numpy=True, normalize_embeddings=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
emb_matrix = np.vstack(df_search["embedding"].values)
|
| 188 |
scores = util.cos_sim(q_emb, emb_matrix)[0].cpu().numpy()
|
| 189 |
df_search["score"] = scores
|
| 190 |
|
| 191 |
filtered = df_search[df_search["score"] >= SIM_THRESHOLD]
|
| 192 |
+
df = (
|
| 193 |
+
filtered if not filtered.empty else df_search
|
| 194 |
+
).sort_values("score", ascending=False).head(TOP_K)
|
|
|
|
| 195 |
|
| 196 |
return results_to_html(df), df
|
| 197 |
|
|
|
|
| 210 |
|
| 211 |
gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
|
| 212 |
|
| 213 |
+
query = gr.Textbox(label="كلمة أو موضوع البحث")
|
| 214 |
+
mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="نصي", label="نوع البحث")
|
| 215 |
+
source_filter = gr.Radio(["الكل", "كتاب", "رسالة"], value="الكل", label="المصدر")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
year_min = int(library_df["سنة النشر"].min())
|
| 218 |
year_max = int(library_df["سنة النشر"].max())
|
|
|
|
| 222 |
maximum=year_max,
|
| 223 |
value=(year_min, year_max),
|
| 224 |
step=1,
|
| 225 |
+
label="سنة النشر"
|
| 226 |
)
|
| 227 |
|
| 228 |
btn_search = gr.Button("🔎 بحث")
|
|
|
|
|
|
|
| 229 |
output_html = gr.HTML()
|
| 230 |
+
df_state = gr.State()
|
| 231 |
file_out = gr.File(label="⬇️ تحميل النتائج")
|
| 232 |
|
| 233 |
btn_search.click(
|