aelsaeed commited on
Commit
3344229
·
verified ·
1 Parent(s): f555fc1

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -0
app.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ================== app.py ==================
2
+ import os
3
+ import pandas as pd
4
+ import numpy as np
5
+ import gradio as gr
6
+ from sentence_transformers import SentenceTransformer, util
7
+ import gdown
8
+
9
+ # --------- إعدادات ----------
10
+ EMB_DIR = "embeddings_cache"
11
+ os.makedirs(EMB_DIR, exist_ok=True)
12
+
13
+ BOOKS_FILE = "book.xlsx"
14
+ THESES_FILE = "theses.xlsx"
15
+
16
+ # روابط Google Drive للملفات
17
+ DRIVE_LINKS = {
18
+ "books": "https://drive.google.com/uc?export=download&id=1FElHiASfiVLeuHWYaqd2Q5foxWRlJT-O",
19
+ "theses": "https://drive.google.com/uc?export=download&id=1K2Mtze6ZdvfKUsFMCOWlRBjDq-ZnJNrv"
20
+ }
21
+
22
+ # --------- تحميل الملفات من Drive لو مش موجودة ----------
23
+ def download_from_drive(link, output):
24
+ if not os.path.exists(output):
25
+ gdown.download(link, output, quiet=False)
26
+
27
+ download_from_drive(DRIVE_LINKS["books"], BOOKS_FILE)
28
+ download_from_drive(DRIVE_LINKS["theses"], THESES_FILE)
29
+
30
+ # --------- قراءة البيانات ----------
31
+ def load_data(file):
32
+ df = pd.read_excel(file).fillna("غير متوافر")
33
+ if "Title" not in df.columns and "العنوان" in df.columns:
34
+ df["Title"] = df["العنوان"].astype(str)
35
+ elif "Title" not in df.columns:
36
+ df["Title"] = df.iloc[:,0].astype(str)
37
+ return df
38
+
39
+ books_df = load_data(BOOKS_FILE)
40
+ theses_df = load_data(THESES_FILE)
41
+
42
+ # --------- نموذج Semantic ----------
43
+ MODEL_NAME = "all-MiniLM-L6-v2"
44
+ model = SentenceTransformer(MODEL_NAME)
45
+
46
+ # --------- إنشاء Embeddings مرة واحدة ----------
47
+ books_embeddings = model.encode(books_df["Title"].tolist(), convert_to_numpy=True)
48
+ theses_embeddings = model.encode(theses_df["Title"].tolist(), convert_to_numpy=True)
49
+
50
+ # --------- البحث ----------
51
+ def search(query, category, mode):
52
+ if not query.strip():
53
+ return "⚠️ اكتب كلمة أو جملة للبحث"
54
+
55
+ if mode == "نصي":
56
+ df = books_df if category=="Books" else theses_df
57
+ results = df[df["Title"].str.contains(query, case=False, na=False)]
58
+ else:
59
+ q_emb = model.encode([query], convert_to_numpy=True)
60
+ df = books_df if category=="Books" else theses_df
61
+ emb = books_embeddings if category=="Books" else theses_embeddings
62
+ scores = util.cos_sim(q_emb, emb)[0].cpu().numpy()
63
+ idx = np.argsort(-scores)
64
+ results = df.iloc[idx]
65
+
66
+ if results.empty:
67
+ return "❌ لم يتم العثور على نتائج"
68
+
69
+ html = "<table border=1 style='border-collapse:collapse;width:100%;'>"
70
+ html += "<tr>" + "".join([f"<th>{col}</th>" for col in results.columns]) + "</tr>"
71
+ for _, row in results.iterrows():
72
+ html += "<tr>" + "".join([f"<td>{val}</td>" for val in row.values]) + "</tr>"
73
+ html += "</table>"
74
+ return html
75
+
76
+ # --------- واجهة Gradio ----------
77
+ iface = gr.Interface(
78
+ fn=search,
79
+ inputs=[
80
+ gr.Textbox(label="اكتب كلمة البحث"),
81
+ gr.Dropdown(["Books","Theses"], label="الفئة"),
82
+ gr.Radio(["نصي","دلالي"], label="نوع البحث")
83
+ ],
84
+ outputs="html",
85
+ title="البحث في المكتبة الرقمية"
86
+ )
87
+
88
+ iface.launch()