aelsaeed commited on
Commit
e92d763
·
verified ·
1 Parent(s): e1ee45c

Upload app.py

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