Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,10 +3,11 @@ import gradio as gr
|
|
| 3 |
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 |
# ================== إعدادات ==================
|
| 12 |
BOOKS_FILE = "book.xlsx"
|
|
@@ -16,40 +17,58 @@ DRIVE_BOOKS_ID = "1IVu5M_zHWg3wo-cbQm3FWhmDIafUSCVP"
|
|
| 16 |
DRIVE_THESES_ID = "1hvZIGFG6h0kQY32bIuEWGRdXTZp84vhk"
|
| 17 |
|
| 18 |
TOP_K = 20
|
| 19 |
-
TFIDF_TOP_N =
|
| 20 |
TFIDF_FALLBACK_MIN = 30
|
| 21 |
|
| 22 |
-
# ================== نموذج Semantic ==================
|
|
|
|
| 23 |
model = SentenceTransformer("all-MiniLM-L6-v2")
|
|
|
|
| 24 |
|
| 25 |
# ================== تحميل الملفات ==================
|
| 26 |
def download_from_drive(file_id, output):
|
| 27 |
if not os.path.exists(output):
|
| 28 |
url = f"https://drive.google.com/uc?id={file_id}"
|
| 29 |
-
|
|
|
|
| 30 |
|
| 31 |
download_from_drive(DRIVE_BOOKS_ID, BOOKS_FILE)
|
| 32 |
download_from_drive(DRIVE_THESES_ID, THESES_FILE)
|
| 33 |
|
| 34 |
# ================== تحميل البيانات ==================
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
books_df["المصدر"] = "كتاب"
|
| 39 |
theses_df["المصدر"] = "رسالة"
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
for df in [books_df, theses_df]:
|
| 42 |
-
|
| 43 |
-
df
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
)
|
|
|
|
|
|
|
| 49 |
|
| 50 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
| 51 |
|
| 52 |
-
# ================== الأعمدة الدلالية ==================
|
| 53 |
def detect_semantic_columns(df):
|
| 54 |
exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 55 |
include = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "كلمات"]
|
|
@@ -65,73 +84,132 @@ def detect_semantic_columns(df):
|
|
| 65 |
if not cols:
|
| 66 |
cols = df.select_dtypes(include="object").columns.tolist()
|
| 67 |
|
| 68 |
-
return cols
|
| 69 |
|
| 70 |
semantic_cols = detect_semantic_columns(library_df)
|
| 71 |
|
| 72 |
# ================== Normalize ==================
|
| 73 |
def normalize_text(text):
|
| 74 |
text = str(text).lower()
|
| 75 |
-
text = re.sub(r"[^\w\s]", " ", text)
|
| 76 |
text = text.replace("أ", "ا").replace("إ", "ا").replace("آ", "ا")
|
| 77 |
text = text.replace("ى", "ي").replace("ة", "ه")
|
|
|
|
|
|
|
|
|
|
| 78 |
return re.sub(r"\s+", " ", text).strip()
|
| 79 |
|
| 80 |
def row_to_text(row):
|
| 81 |
return normalize_text(
|
| 82 |
-
" ".join(str(row[c]) for c in semantic_cols if row[c])
|
| 83 |
)
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
# ================== Embeddings ==================
|
|
|
|
| 86 |
embeddings = model.encode(
|
| 87 |
-
library_df.
|
| 88 |
convert_to_numpy=True,
|
| 89 |
normalize_embeddings=True,
|
| 90 |
show_progress_bar=True
|
| 91 |
)
|
| 92 |
library_df["embedding"] = list(embeddings)
|
| 93 |
-
|
| 94 |
-
# ================== TF-IDF ==================
|
| 95 |
-
def tfidf_prefilter(df, query):
|
| 96 |
-
texts = df.apply(row_to_text, axis=1).tolist()
|
| 97 |
-
vec = TfidfVectorizer(ngram_range=(1, 2), max_features=20000)
|
| 98 |
-
mat = vec.fit_transform(texts)
|
| 99 |
-
q_vec = vec.transform([normalize_text(query)])
|
| 100 |
-
|
| 101 |
-
scores = cosine_similarity(q_vec, mat)[0]
|
| 102 |
-
df = df.copy()
|
| 103 |
-
df["tfidf_score"] = scores
|
| 104 |
-
|
| 105 |
-
return df.sort_values("tfidf_score", ascending=False).head(TFIDF_TOP_N)
|
| 106 |
|
| 107 |
# ================== CSS ==================
|
| 108 |
CUSTOM_CSS = """
|
| 109 |
<style>
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
.card
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
.row-title td{background:#e3f2fd;color:#0d47a1;font-weight:bold;}
|
| 115 |
.row-author td{background:#fce4ec;color:#880e4f;}
|
| 116 |
.row-year td{background:#e8f5e9;color:#1b5e20;}
|
| 117 |
.row-shelf td{background:#fff8e1;color:#e65100;font-weight:bold;font-size:16px;}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
</style>
|
| 119 |
"""
|
| 120 |
|
| 121 |
def safe(v):
|
| 122 |
return "-" if pd.isna(v) or str(v).strip() == "" else str(v)
|
| 123 |
|
| 124 |
-
def results_to_html(df):
|
| 125 |
if df.empty:
|
| 126 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
-
html = ""
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
html += f"""
|
| 131 |
<div class="card">
|
| 132 |
<table>
|
| 133 |
<tr class="row-title">
|
| 134 |
-
<td class="label">العنوان</td>
|
| 135 |
<td>{safe(r.get("العنوان"))}</td>
|
| 136 |
</tr>
|
| 137 |
<tr class="row-author">
|
|
@@ -146,16 +224,73 @@ def results_to_html(df):
|
|
| 146 |
<td class="label">الموقع على الرف</td>
|
| 147 |
<td>{safe(r.get("الموقع على الرف"))}</td>
|
| 148 |
</tr>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
</table>
|
| 150 |
</div>
|
| 151 |
"""
|
| 152 |
|
| 153 |
return CUSTOM_CSS + html
|
| 154 |
|
| 155 |
-
# ================== البحث ==================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
def local_search_df(query, mode, source_filter):
|
| 157 |
-
if not query.strip():
|
| 158 |
-
return
|
| 159 |
|
| 160 |
df = library_df.copy()
|
| 161 |
|
|
@@ -163,52 +298,59 @@ def local_search_df(query, mode, source_filter):
|
|
| 163 |
df = df[df["المصدر"] == source_filter]
|
| 164 |
|
| 165 |
if df.empty:
|
| 166 |
-
return
|
| 167 |
-
|
| 168 |
-
if mode == "نصي":
|
| 169 |
-
mask = (
|
| 170 |
-
df["العنوان"].str.contains(query, case=False, na=False) |
|
| 171 |
-
df["المؤلف"].str.contains(query, case=False, na=False)
|
| 172 |
-
)
|
| 173 |
-
df = df[mask].head(TOP_K)
|
| 174 |
-
else:
|
| 175 |
-
df_pref = tfidf_prefilter(df, query)
|
| 176 |
-
if len(df_pref) < TFIDF_FALLBACK_MIN:
|
| 177 |
-
df_pref = df
|
| 178 |
-
|
| 179 |
-
q_emb = model.encode([normalize_text(query)], normalize_embeddings=True)
|
| 180 |
-
mat = np.vstack(df_pref["embedding"].values)
|
| 181 |
-
scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
|
| 182 |
|
| 183 |
-
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
-
|
|
|
|
|
|
|
| 187 |
|
| 188 |
# ================== حفظ النتائج ==================
|
| 189 |
def save_to_excel(df):
|
|
|
|
|
|
|
|
|
|
| 190 |
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
|
| 191 |
-
df.drop(columns=["
|
| 192 |
.to_excel(tmp.name, index=False)
|
| 193 |
return tmp.name
|
| 194 |
|
| 195 |
# ================== واجهة Gradio ==================
|
| 196 |
with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
| 197 |
-
gr.Markdown("
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
-
btn = gr.Button("🔎 بحث")
|
| 204 |
out_html = gr.HTML()
|
| 205 |
-
df_state = gr.State()
|
| 206 |
-
file_out = gr.File(label="⬇️ تحميل النتائج")
|
| 207 |
|
| 208 |
btn.click(local_search_df, [query, mode, source_filter], [out_html, df_state])
|
| 209 |
-
|
| 210 |
|
| 211 |
-
app.launch()
|
| 212 |
|
| 213 |
|
| 214 |
|
|
|
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
import os, tempfile, re
|
| 6 |
+
import gdown
|
| 7 |
+
|
| 8 |
from sentence_transformers import SentenceTransformer, util
|
| 9 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 10 |
from sklearn.metrics.pairwise import cosine_similarity
|
|
|
|
| 11 |
|
| 12 |
# ================== إعدادات ==================
|
| 13 |
BOOKS_FILE = "book.xlsx"
|
|
|
|
| 17 |
DRIVE_THESES_ID = "1hvZIGFG6h0kQY32bIuEWGRdXTZp84vhk"
|
| 18 |
|
| 19 |
TOP_K = 20
|
| 20 |
+
TFIDF_TOP_N = 120
|
| 21 |
TFIDF_FALLBACK_MIN = 30
|
| 22 |
|
| 23 |
+
# ================== تحميل نموذج Semantic ==================
|
| 24 |
+
print("Loading semantic model...")
|
| 25 |
model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 26 |
+
print("Semantic model loaded successfully.")
|
| 27 |
|
| 28 |
# ================== تحميل الملفات ==================
|
| 29 |
def download_from_drive(file_id, output):
|
| 30 |
if not os.path.exists(output):
|
| 31 |
url = f"https://drive.google.com/uc?id={file_id}"
|
| 32 |
+
print(f"Downloading {output}...")
|
| 33 |
+
gdown.download(url, output, quiet=False)
|
| 34 |
|
| 35 |
download_from_drive(DRIVE_BOOKS_ID, BOOKS_FILE)
|
| 36 |
download_from_drive(DRIVE_THESES_ID, THESES_FILE)
|
| 37 |
|
| 38 |
# ================== تحميل البيانات ==================
|
| 39 |
+
def safe_read_excel(path):
|
| 40 |
+
if not os.path.exists(path):
|
| 41 |
+
raise FileNotFoundError(f"الملف غير موجود: {path}")
|
| 42 |
+
return pd.read_excel(path).fillna("")
|
| 43 |
+
|
| 44 |
+
books_df = safe_read_excel(BOOKS_FILE)
|
| 45 |
+
theses_df = safe_read_excel(THESES_FILE)
|
| 46 |
|
| 47 |
books_df["المصدر"] = "كتاب"
|
| 48 |
theses_df["المصدر"] = "رسالة"
|
| 49 |
|
| 50 |
+
# ================== توحيد الأعمدة المهمة ==================
|
| 51 |
+
def ensure_column(df, col_name):
|
| 52 |
+
if col_name not in df.columns:
|
| 53 |
+
df[col_name] = ""
|
| 54 |
+
return df
|
| 55 |
+
|
| 56 |
+
important_cols = ["العنوان", "المؤلف", "سنة النشر", "الموقع على الرف"]
|
| 57 |
+
|
| 58 |
for df in [books_df, theses_df]:
|
| 59 |
+
for col in important_cols:
|
| 60 |
+
ensure_column(df, col)
|
| 61 |
+
|
| 62 |
+
df["الموقع على الرف"] = (
|
| 63 |
+
df["الموقع على الرف"]
|
| 64 |
+
.astype(str)
|
| 65 |
+
.str.strip()
|
| 66 |
+
.replace(["nan", "NaN", "None", ""], "-")
|
| 67 |
+
)
|
| 68 |
|
| 69 |
library_df = pd.concat([books_df, theses_df], ignore_index=True)
|
| 70 |
|
| 71 |
+
# ================== اكتشاف الأعمدة الدلالية ==================
|
| 72 |
def detect_semantic_columns(df):
|
| 73 |
exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
|
| 74 |
include = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "كلمات"]
|
|
|
|
| 84 |
if not cols:
|
| 85 |
cols = df.select_dtypes(include="object").columns.tolist()
|
| 86 |
|
| 87 |
+
return list(dict.fromkeys(cols))
|
| 88 |
|
| 89 |
semantic_cols = detect_semantic_columns(library_df)
|
| 90 |
|
| 91 |
# ================== Normalize ==================
|
| 92 |
def normalize_text(text):
|
| 93 |
text = str(text).lower()
|
|
|
|
| 94 |
text = text.replace("أ", "ا").replace("إ", "ا").replace("آ", "ا")
|
| 95 |
text = text.replace("ى", "ي").replace("ة", "ه")
|
| 96 |
+
text = text.replace("ؤ", "و").replace("ئ", "ي")
|
| 97 |
+
text = re.sub(r"[^\w\s]", " ", text)
|
| 98 |
+
text = re.sub(r"\d+", " ", text)
|
| 99 |
return re.sub(r"\s+", " ", text).strip()
|
| 100 |
|
| 101 |
def row_to_text(row):
|
| 102 |
return normalize_text(
|
| 103 |
+
" ".join(str(row[c]) for c in semantic_cols if c in row and str(row[c]).strip())
|
| 104 |
)
|
| 105 |
|
| 106 |
+
# ================== نص موحد للبحث ==================
|
| 107 |
+
print("Preparing searchable text...")
|
| 108 |
+
library_df["search_text"] = library_df.apply(row_to_text, axis=1)
|
| 109 |
+
|
| 110 |
+
# ================== بناء TF-IDF مرة واحدة ==================
|
| 111 |
+
print("Building TF-IDF index...")
|
| 112 |
+
tfidf_vectorizer = TfidfVectorizer(ngram_range=(1, 2), max_features=20000)
|
| 113 |
+
tfidf_matrix = tfidf_vectorizer.fit_transform(library_df["search_text"].tolist())
|
| 114 |
+
print("TF-IDF ready.")
|
| 115 |
+
|
| 116 |
# ================== Embeddings ==================
|
| 117 |
+
print("Generating embeddings...")
|
| 118 |
embeddings = model.encode(
|
| 119 |
+
library_df["search_text"].tolist(),
|
| 120 |
convert_to_numpy=True,
|
| 121 |
normalize_embeddings=True,
|
| 122 |
show_progress_bar=True
|
| 123 |
)
|
| 124 |
library_df["embedding"] = list(embeddings)
|
| 125 |
+
print("Embeddings ready.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
# ================== CSS ==================
|
| 128 |
CUSTOM_CSS = """
|
| 129 |
<style>
|
| 130 |
+
body {
|
| 131 |
+
direction: rtl;
|
| 132 |
+
}
|
| 133 |
+
.card{
|
| 134 |
+
border:1px solid #ddd;
|
| 135 |
+
border-radius:12px;
|
| 136 |
+
padding:12px;
|
| 137 |
+
margin:14px 0;
|
| 138 |
+
background:#fafafa;
|
| 139 |
+
box-shadow:0 2px 8px rgba(0,0,0,0.05);
|
| 140 |
+
}
|
| 141 |
+
.card table{
|
| 142 |
+
width:100%;
|
| 143 |
+
border-collapse:collapse;
|
| 144 |
+
direction:rtl;
|
| 145 |
+
}
|
| 146 |
+
.card td{
|
| 147 |
+
border:1px solid #ccc;
|
| 148 |
+
padding:10px;
|
| 149 |
+
text-align:center;
|
| 150 |
+
vertical-align:middle;
|
| 151 |
+
font-size:15px;
|
| 152 |
+
}
|
| 153 |
+
.card td.label{
|
| 154 |
+
width:30%;
|
| 155 |
+
font-weight:bold;
|
| 156 |
+
}
|
| 157 |
.row-title td{background:#e3f2fd;color:#0d47a1;font-weight:bold;}
|
| 158 |
.row-author td{background:#fce4ec;color:#880e4f;}
|
| 159 |
.row-year td{background:#e8f5e9;color:#1b5e20;}
|
| 160 |
.row-shelf td{background:#fff8e1;color:#e65100;font-weight:bold;font-size:16px;}
|
| 161 |
+
.meta{
|
| 162 |
+
background:#eef6ff;
|
| 163 |
+
border:1px solid #cfe2ff;
|
| 164 |
+
padding:10px 14px;
|
| 165 |
+
border-radius:10px;
|
| 166 |
+
margin-bottom:16px;
|
| 167 |
+
font-size:16px;
|
| 168 |
+
font-weight:bold;
|
| 169 |
+
}
|
| 170 |
+
.empty{
|
| 171 |
+
background:#fff3cd;
|
| 172 |
+
color:#856404;
|
| 173 |
+
border:1px solid #ffeeba;
|
| 174 |
+
padding:12px;
|
| 175 |
+
border-radius:10px;
|
| 176 |
+
font-size:16px;
|
| 177 |
+
}
|
| 178 |
</style>
|
| 179 |
"""
|
| 180 |
|
| 181 |
def safe(v):
|
| 182 |
return "-" if pd.isna(v) or str(v).strip() == "" else str(v)
|
| 183 |
|
| 184 |
+
def results_to_html(df, query="", mode="", source_filter=""):
|
| 185 |
if df.empty:
|
| 186 |
+
return CUSTOM_CSS + """
|
| 187 |
+
<div class="empty">
|
| 188 |
+
❌ لا توجد نتائج مطابقة.<br><br>
|
| 189 |
+
💡 جرّب:
|
| 190 |
+
<ul>
|
| 191 |
+
<li>استخدام كلمة أقصر</li>
|
| 192 |
+
<li>البحث باسم المؤلف أو جزء من العنوان</li>
|
| 193 |
+
<li>استخدام البحث الدلالي إذا لم تجد نتيجة نصية</li>
|
| 194 |
+
</ul>
|
| 195 |
+
</div>
|
| 196 |
+
"""
|
| 197 |
|
| 198 |
+
html = f"""
|
| 199 |
+
<div class="meta">
|
| 200 |
+
✅ تم العثور على {len(df)} نتيجة
|
| 201 |
+
{' | نوع البحث: ' + mode if mode else ''}
|
| 202 |
+
{' | المصدر: ' + source_filter if source_filter else ''}
|
| 203 |
+
{' | الاستعلام: ' + query if query else ''}
|
| 204 |
+
</div>
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
for i, (_, r) in enumerate(df.iterrows(), start=1):
|
| 208 |
html += f"""
|
| 209 |
<div class="card">
|
| 210 |
<table>
|
| 211 |
<tr class="row-title">
|
| 212 |
+
<td class="label">#{i} العنوان</td>
|
| 213 |
<td>{safe(r.get("العنوان"))}</td>
|
| 214 |
</tr>
|
| 215 |
<tr class="row-author">
|
|
|
|
| 224 |
<td class="label">الموقع على الرف</td>
|
| 225 |
<td>{safe(r.get("الموقع على الرف"))}</td>
|
| 226 |
</tr>
|
| 227 |
+
<tr>
|
| 228 |
+
<td class="label">المصدر</td>
|
| 229 |
+
<td>{safe(r.get("المصدر"))}</td>
|
| 230 |
+
</tr>
|
| 231 |
</table>
|
| 232 |
</div>
|
| 233 |
"""
|
| 234 |
|
| 235 |
return CUSTOM_CSS + html
|
| 236 |
|
| 237 |
+
# ================== البحث النصي ==================
|
| 238 |
+
def text_search(df, query):
|
| 239 |
+
q = normalize_text(query)
|
| 240 |
+
if not q:
|
| 241 |
+
return df.iloc[0:0]
|
| 242 |
+
|
| 243 |
+
mask = df["search_text"].str.contains(q, case=False, na=False)
|
| 244 |
+
result = df[mask].copy()
|
| 245 |
+
|
| 246 |
+
if not result.empty:
|
| 247 |
+
result["text_score"] = result["search_text"].apply(lambda x: x.count(q))
|
| 248 |
+
result = result.sort_values("text_score", ascending=False)
|
| 249 |
+
|
| 250 |
+
return result.head(TOP_K)
|
| 251 |
+
|
| 252 |
+
# ================== البحث الدلالي ==================
|
| 253 |
+
def semantic_search(df, query):
|
| 254 |
+
if df.empty:
|
| 255 |
+
return df
|
| 256 |
+
|
| 257 |
+
q = normalize_text(query)
|
| 258 |
+
if not q:
|
| 259 |
+
return df.iloc[0:0]
|
| 260 |
+
|
| 261 |
+
# فلترة أولية بـ TF-IDF من الـ dataset الكامل
|
| 262 |
+
q_vec = tfidf_vectorizer.transform([q])
|
| 263 |
+
tfidf_scores = cosine_similarity(q_vec, tfidf_matrix)[0]
|
| 264 |
+
|
| 265 |
+
temp_df = library_df.copy()
|
| 266 |
+
temp_df["tfidf_score"] = tfidf_scores
|
| 267 |
+
|
| 268 |
+
# فلترة حسب المصدر لو لزم
|
| 269 |
+
if "المصدر" in df.columns and len(df) != len(library_df):
|
| 270 |
+
temp_df = temp_df[temp_df.index.isin(df.index)]
|
| 271 |
+
|
| 272 |
+
df_pref = temp_df.sort_values("tfidf_score", ascending=False).head(TFIDF_TOP_N)
|
| 273 |
+
|
| 274 |
+
if df_pref.empty:
|
| 275 |
+
return df.iloc[0:0]
|
| 276 |
+
|
| 277 |
+
try:
|
| 278 |
+
q_emb = model.encode([q], normalize_embeddings=True)
|
| 279 |
+
mat = np.vstack(df_pref["embedding"].values)
|
| 280 |
+
scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
|
| 281 |
+
|
| 282 |
+
df_pref = df_pref.copy()
|
| 283 |
+
df_pref["score"] = scores
|
| 284 |
+
result = df_pref.sort_values("score", ascending=False).head(TOP_K)
|
| 285 |
+
return result
|
| 286 |
+
except Exception as e:
|
| 287 |
+
print("Semantic search error:", e)
|
| 288 |
+
return df_pref.head(TOP_K)
|
| 289 |
+
|
| 290 |
+
# ================== البحث العام ==================
|
| 291 |
def local_search_df(query, mode, source_filter):
|
| 292 |
+
if not str(query).strip():
|
| 293 |
+
return CUSTOM_CSS + '<div class="empty">⚠️ من فضلك اكتب كلمة أو موضوعًا للبحث</div>', pd.DataFrame()
|
| 294 |
|
| 295 |
df = library_df.copy()
|
| 296 |
|
|
|
|
| 298 |
df = df[df["المصدر"] == source_filter]
|
| 299 |
|
| 300 |
if df.empty:
|
| 301 |
+
return CUSTOM_CSS + '<div class="empty">❌ لا توجد بيانات متاحة لهذا المصدر</div>', pd.DataFrame()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
+
try:
|
| 304 |
+
if mode == "نصي":
|
| 305 |
+
result_df = text_search(df, query)
|
| 306 |
+
else:
|
| 307 |
+
result_df = semantic_search(df, query)
|
| 308 |
+
|
| 309 |
+
clean_df = result_df.drop(columns=["embedding"], errors="ignore")
|
| 310 |
+
return results_to_html(result_df, query, mode, source_filter), clean_df
|
| 311 |
|
| 312 |
+
except Exception as e:
|
| 313 |
+
print("Search error:", e)
|
| 314 |
+
return CUSTOM_CSS + f'<div class="empty">⚠️ حدث خطأ أثناء البحث: {str(e)}</div>', pd.DataFrame()
|
| 315 |
|
| 316 |
# ================== حفظ النتائج ==================
|
| 317 |
def save_to_excel(df):
|
| 318 |
+
if df is None or len(df) == 0:
|
| 319 |
+
return None
|
| 320 |
+
|
| 321 |
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
|
| 322 |
+
df.drop(columns=["score", "tfidf_score", "text_score"], errors="ignore") \
|
| 323 |
.to_excel(tmp.name, index=False)
|
| 324 |
return tmp.name
|
| 325 |
|
| 326 |
# ================== واجهة Gradio ==================
|
| 327 |
with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
|
| 328 |
+
gr.Markdown("""
|
| 329 |
+
# 🔍 نظام البحث الذكي في مقتنيات المكتبة
|
| 330 |
+
ابحث في **الكتب والرسائل العلمية** باستخدام:
|
| 331 |
+
- **البحث النصي**
|
| 332 |
+
- **البحث الدلالي (Semantic Search)**
|
| 333 |
+
""")
|
| 334 |
+
|
| 335 |
+
with gr.Row():
|
| 336 |
+
query = gr.Textbox(label="كلمة أو موضوع البحث", placeholder="مثال: الذكاء الاصطناعي، الفهرسة، المكتبات الرقمية")
|
| 337 |
+
|
| 338 |
+
with gr.Row():
|
| 339 |
+
mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="نصي", label="نوع البحث")
|
| 340 |
+
source_filter = gr.Radio(["الكل", "كتاب", "رسالة"], value="الكل", label="المصدر")
|
| 341 |
+
|
| 342 |
+
with gr.Row():
|
| 343 |
+
btn = gr.Button("🔎 بحث", variant="primary")
|
| 344 |
+
save_btn = gr.Button("📥 حفظ النتائج")
|
| 345 |
|
|
|
|
| 346 |
out_html = gr.HTML()
|
| 347 |
+
df_state = gr.State(pd.DataFrame())
|
| 348 |
+
file_out = gr.File(label="⬇️ تحميل ملف النتائج")
|
| 349 |
|
| 350 |
btn.click(local_search_df, [query, mode, source_filter], [out_html, df_state])
|
| 351 |
+
save_btn.click(save_to_excel, df_state, file_out)
|
| 352 |
|
| 353 |
+
app.launch(server_name="0.0.0.0")
|
| 354 |
|
| 355 |
|
| 356 |
|