File size: 12,603 Bytes
2d566b8
 
cb7e269
 
2d566b8
10f7e62
 
2d566b8
8ecb405
2d566b8
 
 
 
 
 
3481ba0
2d566b8
 
10f7e62
2d566b8
 
 
 
 
10f7e62
 
2d566b8
 
 
d081b7a
0223d15
10f7e62
 
 
 
 
 
 
cb7e269
2d566b8
 
cb7e269
10f7e62
 
 
 
 
 
 
 
3481ba0
10f7e62
 
 
 
 
 
 
 
 
2d566b8
3481ba0
cb7e269
10f7e62
2d566b8
 
3481ba0
2d566b8
 
 
 
 
 
 
 
 
 
 
3481ba0
10f7e62
2d566b8
 
 
 
 
 
 
 
10f7e62
 
 
2d566b8
 
 
3481ba0
10f7e62
3481ba0
2d566b8
10f7e62
 
 
 
7daad2c
10f7e62
 
 
 
 
7daad2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d566b8
 
 
 
10f7e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d566b8
 
 
 
10f7e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7daad2c
 
 
 
 
 
 
 
 
2d566b8
 
 
 
 
 
7daad2c
2d566b8
10f7e62
 
 
 
 
 
 
 
 
 
 
3481ba0
7daad2c
 
 
 
 
10f7e62
 
 
 
 
 
 
 
 
2d566b8
 
 
 
10f7e62
2d566b8
 
 
 
 
 
 
 
 
 
 
 
 
 
10f7e62
 
 
 
2d566b8
 
 
 
3481ba0
2d566b8
10f7e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7daad2c
10f7e62
 
7daad2c
 
10f7e62
7daad2c
10f7e62
 
 
 
 
 
 
 
 
 
 
 
7daad2c
10f7e62
7daad2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10f7e62
 
3481ba0
10f7e62
 
3481ba0
2d566b8
3481ba0
 
 
 
 
10f7e62
3481ba0
10f7e62
7daad2c
10f7e62
 
 
7daad2c
10f7e62
7daad2c
 
3481ba0
10f7e62
 
 
2d566b8
 
 
10f7e62
 
 
2d566b8
10f7e62
2d566b8
 
 
 
 
10f7e62
 
 
 
 
 
 
 
 
7daad2c
10f7e62
 
 
 
 
 
 
2d566b8
 
10f7e62
 
2d566b8
3481ba0
10f7e62
2d566b8
7daad2c
e31e7af
3a23df4
5810d18
36a0f16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# ================== imports ==================
import gradio as gr
import pandas as pd
import numpy as np
import os, tempfile, re
import gdown

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

# ================== إعدادات ==================
BOOKS_FILE = "book.xlsx"
THESES_FILE = "theses.xlsx"

DRIVE_BOOKS_ID = "1IVu5M_zHWg3wo-cbQm3FWhmDIafUSCVP"
DRIVE_THESES_ID = "1hvZIGFG6h0kQY32bIuEWGRdXTZp84vhk"

TOP_K = 20
TFIDF_TOP_N = 120

# ================== تحميل الملفات ==================
def download_from_drive(file_id, output):
    if not os.path.exists(output):
        url = f"https://drive.google.com/uc?id={file_id}"
        print(f"Downloading {output}...")
        gdown.download(url, output, quiet=False)

download_from_drive(DRIVE_BOOKS_ID, BOOKS_FILE)
download_from_drive(DRIVE_THESES_ID, THESES_FILE)

# ================== تحميل البيانات ==================
def safe_read_excel(path):
    if not os.path.exists(path):
        raise FileNotFoundError(f"الملف غير موجود: {path}")
    return pd.read_excel(path).fillna("")

books_df = safe_read_excel(BOOKS_FILE)
theses_df = safe_read_excel(THESES_FILE)

books_df["المصدر"] = "كتاب"
theses_df["المصدر"] = "رسالة"

# ================== توحيد الأعمدة المهمة ==================
def ensure_column(df, col_name):
    if col_name not in df.columns:
        df[col_name] = ""
    return df

important_cols = ["العنوان", "المؤلف", "سنة النشر", "الموقع على الرف"]

for df in [books_df, theses_df]:
    for col in important_cols:
        ensure_column(df, col)

    df["الموقع على الرف"] = (
        df["الموقع على الرف"]
        .astype(str)
        .str.strip()
        .replace(["nan", "NaN", "None", ""], "-")
    )

library_df = pd.concat([books_df, theses_df], ignore_index=True)

# ================== اكتشاف الأعمدة الدلالية ==================
def detect_semantic_columns(df):
    exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"]
    include = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "كلمات"]

    cols = []
    for c in df.columns:
        s = str(c)
        if any(x in s for x in exclude):
            continue
        if any(x in s for x in include):
            cols.append(c)

    if not cols:
        cols = df.select_dtypes(include="object").columns.tolist()

    return list(dict.fromkeys(cols))

semantic_cols = detect_semantic_columns(library_df)

# ================== Normalize ==================
def normalize_text(text):
    text = str(text).lower()
    text = text.replace("أ", "ا").replace("إ", "ا").replace("آ", "ا")
    text = text.replace("ى", "ي").replace("ة", "ه")
    text = text.replace("ؤ", "و").replace("ئ", "ي")
    text = re.sub(r"[^\w\s]", " ", text)
    text = re.sub(r"\d+", " ", text)
    return re.sub(r"\s+", " ", text).strip()

def row_to_text(row):
    return normalize_text(
        " ".join(str(row[c]) for c in semantic_cols if c in row and str(row[c]).strip())
    )

# ================== نص موحد للبحث ==================
print("Preparing searchable text...")
library_df["search_text"] = library_df.apply(row_to_text, axis=1)

# ================== بناء TF-IDF مرة واحدة فقط ==================
print("Building TF-IDF index...")
tfidf_vectorizer = TfidfVectorizer(ngram_range=(1, 2), max_features=20000)
tfidf_matrix = tfidf_vectorizer.fit_transform(library_df["search_text"].tolist())
print("TF-IDF ready.")

# ================== تحميل الـ Semantic Model عند الحاجة فقط ==================
semantic_model = None
embeddings_cache = None

def load_semantic_resources():
    global semantic_model, embeddings_cache

    if semantic_model is None:
        print("Loading semantic model lazily...")
        from sentence_transformers import SentenceTransformer
        semantic_model = SentenceTransformer("sentence-transformers/paraphrase-MiniLM-L3-v2")
        print("Semantic model loaded.")

    if embeddings_cache is None:
        print("Generating embeddings lazily...")
        embeddings_cache = semantic_model.encode(
            library_df["search_text"].tolist(),
            convert_to_numpy=True,
            normalize_embeddings=True,
            show_progress_bar=True
        )
        print("Embeddings ready.")

# ================== CSS ==================
CUSTOM_CSS = """
<style>
body {
    direction: rtl;
}
.card{
    border:1px solid #ddd;
    border-radius:12px;
    padding:12px;
    margin:14px 0;
    background:#fafafa;
    box-shadow:0 2px 8px rgba(0,0,0,0.05);
}
.card table{
    width:100%;
    border-collapse:collapse;
    direction:rtl;
}
.card td{
    border:1px solid #ccc;
    padding:10px;
    text-align:center;
    vertical-align:middle;
    font-size:15px;
}
.card td.label{
    width:30%;
    font-weight:bold;
}
.row-title td{background:#e3f2fd;color:#0d47a1;font-weight:bold;}
.row-author td{background:#fce4ec;color:#880e4f;}
.row-year td{background:#e8f5e9;color:#1b5e20;}
.row-shelf td{background:#fff8e1;color:#e65100;font-weight:bold;font-size:16px;}
.meta{
    background:#eef6ff;
    border:1px solid #cfe2ff;
    padding:10px 14px;
    border-radius:10px;
    margin-bottom:16px;
    font-size:16px;
    font-weight:bold;
}
.empty{
    background:#fff3cd;
    color:#856404;
    border:1px solid #ffeeba;
    padding:12px;
    border-radius:10px;
    font-size:16px;
}
.note{
    background:#f0f9ff;
    color:#0c4a6e;
    border:1px solid #bae6fd;
    padding:12px;
    border-radius:10px;
    font-size:15px;
    margin-bottom:12px;
}
</style>
"""

def safe(v):
    return "-" if pd.isna(v) or str(v).strip() == "" else str(v)

def results_to_html(df, query="", mode="", source_filter="", extra_note=""):
    if df.empty:
        return CUSTOM_CSS + """
        <div class="empty">
            ❌ لا توجد نتائج مطابقة.<br><br>
            💡 جرّب:
            <ul>
                <li>استخدام كلمة أقصر</li>
                <li>البحث باسم المؤلف أو جزء من العنوان</li>
                <li>استخدام البحث الدلالي إذا لم تجد نتيجة نصية</li>
            </ul>
        </div>
        """

    html = ""
    if extra_note:
        html += f'<div class="note">{extra_note}</div>'

    html += f"""
    <div class="meta">
        ✅ تم العثور على {len(df)} نتيجة
        {' | نوع البحث: ' + mode if mode else ''}
        {' | المصدر: ' + source_filter if source_filter else ''}
        {' | الاستعلام: ' + query if query else ''}
    </div>
    """

    for i, (_, r) in enumerate(df.iterrows(), start=1):
        html += f"""
        <div class="card">
        <table>
            <tr class="row-title">
                <td class="label">#{i} العنوان</td>
                <td>{safe(r.get("العنوان"))}</td>
            </tr>
            <tr class="row-author">
                <td class="label">المؤلف</td>
                <td>{safe(r.get("المؤلف"))}</td>
            </tr>
            <tr class="row-year">
                <td class="label">سنة النشر</td>
                <td>{safe(r.get("سنة النشر"))}</td>
            </tr>
            <tr class="row-shelf">
                <td class="label">الموقع على الرف</td>
                <td>{safe(r.get("الموقع على الرف"))}</td>
            </tr>
            <tr>
                <td class="label">المصدر</td>
                <td>{safe(r.get("المصدر"))}</td>
            </tr>
        </table>
        </div>
        """

    return CUSTOM_CSS + html

# ================== البحث النصي ==================
def text_search(df, query):
    q = normalize_text(query)
    if not q:
        return df.iloc[0:0]

    mask = df["search_text"].str.contains(q, case=False, na=False)
    result = df[mask].copy()

    if not result.empty:
        result["text_score"] = result["search_text"].apply(lambda x: x.count(q))
        result = result.sort_values("text_score", ascending=False)

    return result.head(TOP_K)

# ================== البحث الدلالي الخفيف ==================
def semantic_search(df, query):
    q = normalize_text(query)
    if not q or df.empty:
        return df.iloc[0:0], "⚠️ لم يتم إدخال استعلام صالح."

    # 1) فلترة أولية سريعة بـ TF-IDF
    q_vec = tfidf_vectorizer.transform([q])
    tfidf_scores = cosine_similarity(q_vec, tfidf_matrix)[0]

    temp_df = library_df.copy()
    temp_df["tfidf_score"] = tfidf_scores

    if "المصدر" in df.columns and len(df) != len(library_df):
        temp_df = temp_df[temp_df.index.isin(df.index)]

    df_pref = temp_df.sort_values("tfidf_score", ascending=False).head(TFIDF_TOP_N)

    if df_pref.empty:
        return df.iloc[0:0], "❌ لا توجد نتائج دلالية."

    # 2) تحميل الموارد الثقيلة فقط عند أول مرة
    load_semantic_resources()

    # 3) حساب التشابه الدلالي فقط على أفضل المرشحين
    from sentence_transformers import util

    pref_embeddings = embeddings_cache[df_pref.index]
    q_emb = semantic_model.encode([q], normalize_embeddings=True)
    scores = util.cos_sim(q_emb, pref_embeddings)[0].cpu().numpy()

    df_pref = df_pref.copy()
    df_pref["score"] = scores
    result = df_pref.sort_values("score", ascending=False).head(TOP_K)

    note = "🧠 تم استخدام البحث الدلالي. أول تشغيل له قد يستغرق وقتًا أطول قليلاً، وبعدها يصبح أسرع."
    return result, note

# ================== البحث العام ==================
def local_search_df(query, mode, source_filter):
    if not str(query).strip():
        return CUSTOM_CSS + '<div class="empty">⚠️ من فضلك اكتب كلمة أو موضوعًا للبحث</div>', pd.DataFrame()

    df = library_df.copy()

    if source_filter != "الكل":
        df = df[df["المصدر"] == source_filter]

    if df.empty:
        return CUSTOM_CSS + '<div class="empty">❌ لا توجد بيانات متاحة لهذا المصدر</div>', pd.DataFrame()

    try:
        note = ""
        if mode == "نصي":
            result_df = text_search(df, query)
        else:
            result_df, note = semantic_search(df, query)

        clean_df = result_df.drop(columns=[], errors="ignore")
        return results_to_html(result_df, query, mode, source_filter, note), clean_df

    except Exception as e:
        print("Search error:", e)
        return CUSTOM_CSS + f'<div class="empty">⚠️ حدث خطأ أثناء البحث: {str(e)}</div>', pd.DataFrame()

# ================== حفظ النتائج ==================
def save_to_excel(df):
    if df is None or len(df) == 0:
        return None

    tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
    df.drop(columns=["score", "tfidf_score", "text_score"], errors="ignore") \
      .to_excel(tmp.name, index=False)
    return tmp.name

# ================== واجهة Gradio ==================
with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
    gr.Markdown("""
    # 🔍 نظام البحث الذكي في مقتنيات المكتبة
    ابحث في **الكتب والرسائل العلمية** باستخدام:
    - **البحث النصي**
    - **البحث الدلالي (Semantic Search)**
    """)

    with gr.Row():
        query = gr.Textbox(label="كلمة أو موضوع البحث", placeholder="مثال: الذكاء الاصطناعي، الفهرسة، المكتبات الرقمية")

    with gr.Row():
        mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="نصي", label="نوع البحث")
        source_filter = gr.Radio(["الكل", "كتاب", "رسالة"], value="الكل", label="المصدر")

    with gr.Row():
        btn = gr.Button("🔎 بحث", variant="primary")
        save_btn = gr.Button("📥 حفظ النتائج")

    out_html = gr.HTML()
    df_state = gr.State(pd.DataFrame())
    file_out = gr.File(label="⬇️ تحميل ملف النتائج")

    btn.click(local_search_df, [query, mode, source_filter], [out_html, df_state])
    save_btn.click(save_to_excel, df_state, file_out)

app.launch(server_name="0.0.0.0", server_port=7860)