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
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ================== imports ==================
|
| 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 |
+
|
| 9 |
+
# ================== إعدادات ==================
|
| 10 |
+
LIB_FILE = "library.xlsx" # ملف المكتبة
|
| 11 |
+
DRIVE_FILE_ID = "PUT_DRIVE_FILE_ID_HERE" # ID الملف على Google Drive
|
| 12 |
+
|
| 13 |
+
EMB_DIR = "embeddings"
|
| 14 |
+
os.makedirs(EMB_DIR, exist_ok=True)
|
| 15 |
+
|
| 16 |
+
MODEL_NAME = "paraphrase-multilingual-MiniLM-L12-v2"
|
| 17 |
+
model = SentenceTransformer(MODEL_NAME)
|
| 18 |
+
|
| 19 |
+
# ================== تحميل من Drive ==================
|
| 20 |
+
def download_from_drive(file_id, output):
|
| 21 |
+
if not os.path.exists(output):
|
| 22 |
+
url = f"https://drive.google.com/uc?id={file_id}"
|
| 23 |
+
try:
|
| 24 |
+
gdown.download(url, output, quiet=True)
|
| 25 |
+
except Exception:
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
download_from_drive(DRIVE_FILE_ID, LIB_FILE)
|
| 29 |
+
|
| 30 |
+
# ================== تحميل البيانات ==================
|
| 31 |
+
def load_library():
|
| 32 |
+
if not os.path.exists(LIB_FILE):
|
| 33 |
+
raise FileNotFoundError("❌ ملف library.xlsx غير موجود")
|
| 34 |
+
|
| 35 |
+
df = pd.read_excel(LIB_FILE).fillna("غير متوافر")
|
| 36 |
+
|
| 37 |
+
# توحيد عمود العنوان
|
| 38 |
+
if "Title" not in df.columns:
|
| 39 |
+
if "العنوان" in df.columns:
|
| 40 |
+
df["Title"] = df["العنوان"].astype(str)
|
| 41 |
+
else:
|
| 42 |
+
df["Title"] = df.iloc[:, 0].astype(str)
|
| 43 |
+
|
| 44 |
+
# تأكد من وجود عمود المؤلف، سنة النشر، الموقع على الرف
|
| 45 |
+
for col in ["المؤلف", "سنة النشر", "الموقع على الرف"]:
|
| 46 |
+
if col not in df.columns:
|
| 47 |
+
df[col] = "غير متوافر"
|
| 48 |
+
|
| 49 |
+
# إذا لم يوجد عمود المصدر (كتاب/رسالة) أضيفيه
|
| 50 |
+
if "المصدر" not in df.columns:
|
| 51 |
+
df["المصدر"] = "كتاب"
|
| 52 |
+
|
| 53 |
+
return df
|
| 54 |
+
|
| 55 |
+
library_df = load_library()
|
| 56 |
+
|
| 57 |
+
# ================== Embeddings ==================
|
| 58 |
+
def emb_path(name):
|
| 59 |
+
return os.path.join(EMB_DIR, f"{name}.pkl")
|
| 60 |
+
|
| 61 |
+
def build_or_load_embeddings(df, name):
|
| 62 |
+
path = emb_path(name)
|
| 63 |
+
if os.path.exists(path):
|
| 64 |
+
with open(path, "rb") as f:
|
| 65 |
+
emb = pickle.load(f)
|
| 66 |
+
if len(emb) == len(df):
|
| 67 |
+
return emb
|
| 68 |
+
|
| 69 |
+
texts = df["Title"].astype(str).tolist()
|
| 70 |
+
emb = model.encode(texts, convert_to_numpy=True, show_progress_bar=True)
|
| 71 |
+
with open(path, "wb") as f:
|
| 72 |
+
pickle.dump(emb, f)
|
| 73 |
+
return emb
|
| 74 |
+
|
| 75 |
+
library_embeddings = build_or_load_embeddings(library_df, "library")
|
| 76 |
+
|
| 77 |
+
# ================== عرض النتائج HTML كـ Cards ==================
|
| 78 |
+
def results_to_html_cards(df):
|
| 79 |
+
if df.empty:
|
| 80 |
+
return "<p>❌ لم يتم العثور على نتائج</p>"
|
| 81 |
+
|
| 82 |
+
html = '<div style="display:flex; flex-wrap:wrap; gap:15px;">'
|
| 83 |
+
for _, row in df.iterrows():
|
| 84 |
+
card = f"""
|
| 85 |
+
<div style="
|
| 86 |
+
border:1px solid #ccc;
|
| 87 |
+
border-radius:10px;
|
| 88 |
+
padding:15px;
|
| 89 |
+
width:250px;
|
| 90 |
+
box-shadow: 2px 2px 8px rgba(0,0,0,0.1);
|
| 91 |
+
background: #f9f9f9;">
|
| 92 |
+
<div style="font-size:40px; text-align:center;">📖</div>
|
| 93 |
+
<h3 style="margin-top:5px; font-size:16px;">{row['Title']}</h3>
|
| 94 |
+
<p><b>المؤلف:</b> {row['المؤلف']}</p>
|
| 95 |
+
<p><b>سنة النشر:</b> {row['سنة النشر']}</p>
|
| 96 |
+
<p><b>الموقع على الرف:</b> {row['الموقع على الرف']}</p>
|
| 97 |
+
<p><b>المصدر:</b> {row['المصدر']}</p>
|
| 98 |
+
</div>
|
| 99 |
+
"""
|
| 100 |
+
html += card
|
| 101 |
+
html += "</div>"
|
| 102 |
+
return html
|
| 103 |
+
|
| 104 |
+
# ================== البحث ==================
|
| 105 |
+
def local_search_df(query, mode):
|
| 106 |
+
if not query or not query.strip():
|
| 107 |
+
return "<p>⚠️ اكتب كلمة أو جملة للبحث</p>", pd.DataFrame()
|
| 108 |
+
|
| 109 |
+
# ---- بحث نصي ----
|
| 110 |
+
if mode == "نصي":
|
| 111 |
+
col = "العنوان" if "العنوان" in library_df.columns else "Title"
|
| 112 |
+
df = library_df[library_df[col].astype(str).str.contains(query, case=False, na=False)]
|
| 113 |
+
|
| 114 |
+
# ---- بحث دلالي ----
|
| 115 |
+
else:
|
| 116 |
+
q_emb = model.encode([query], convert_to_numpy=True)
|
| 117 |
+
scores = util.cos_sim(q_emb, library_embeddings)[0].cpu().numpy()
|
| 118 |
+
df = library_df.copy()
|
| 119 |
+
df["score"] = scores
|
| 120 |
+
df = df.sort_values("score", ascending=False)
|
| 121 |
+
|
| 122 |
+
if df.empty:
|
| 123 |
+
df = pd.DataFrame([{"Title":"❌ لم يتم العثور على نتائج"}])
|
| 124 |
+
|
| 125 |
+
return results_to_html_cards(df), df
|
| 126 |
+
|
| 127 |
+
# ================== حفظ النتائج Excel ==================
|
| 128 |
+
def save_to_excel(df):
|
| 129 |
+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
|
| 130 |
+
if df is None or df.empty:
|
| 131 |
+
pd.DataFrame().to_excel(tmp.name, index=False)
|
| 132 |
+
else:
|
| 133 |
+
df.to_excel(tmp.name, index=False)
|
| 134 |
+
return tmp.name
|
| 135 |
+
|
| 136 |
+
# ================== الواجهة ==================
|
| 137 |
+
with gr.Blocks(title="AI Library Explorer") as app:
|
| 138 |
+
gr.Markdown("## 📚 البحث في مقتنيات المكتبة")
|
| 139 |
+
query = gr.Textbox(label="اكتب كلمة أو موضوع البحث")
|
| 140 |
+
|
| 141 |
+
mode = gr.Radio(
|
| 142 |
+
["نصي", "دلالي (Semantic)"],
|
| 143 |
+
value="نصي",
|
| 144 |
+
label="نوع البحث"
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
btn_search = gr.Button("🔎 بحث")
|
| 148 |
+
|
| 149 |
+
df_state = gr.State()
|
| 150 |
+
output_html = gr.HTML()
|
| 151 |
+
file_out = gr.File(label="⬇️ تحميل النتائج")
|
| 152 |
+
|
| 153 |
+
btn_search.click(
|
| 154 |
+
local_search_df,
|
| 155 |
+
inputs=[query, mode],
|
| 156 |
+
outputs=[output_html, df_state]
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
gr.Button("📥 حفظ النتائج").click(
|
| 160 |
+
save_to_excel,
|
| 161 |
+
inputs=df_state,
|
| 162 |
+
outputs=file_out
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
app.launch()
|