aelsaeed commited on
Commit
cb7e269
·
verified ·
1 Parent(s): 159c208

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +212 -165
app.py CHANGED
@@ -1,165 +1,212 @@
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
- BOOKS_FILE = "book.xlsx"
11
- THESES_FILE = "theses.xlsx"
12
-
13
- DRIVE_BOOKS_ID = "1FElHiASfiVLeuHWYaqd2Q5foxWRlJT-O"
14
- DRIVE_THESES_ID = "1K2Mtze6ZdvfKUsFMCOWlRBjDq-ZnJNrv"
15
-
16
- EMB_DIR = "embeddings"
17
- os.makedirs(EMB_DIR, exist_ok=True)
18
-
19
- MODEL_NAME = "paraphrase-multilingual-MiniLM-L12-v2"
20
- model = SentenceTransformer(MODEL_NAME)
21
-
22
- # ================== تحميل من Drive ==================
23
- def download_from_drive(file_id, output):
24
- if not os.path.exists(output):
25
- url = f"https://drive.google.com/uc?id={file_id}"
26
- try:
27
- gdown.download(url, output, quiet=True)
28
- except Exception:
29
- pass
30
-
31
- download_from_drive(DRIVE_BOOKS_ID, BOOKS_FILE)
32
- download_from_drive(DRIVE_THESES_ID, THESES_FILE)
33
-
34
- # ================== تحميل ودمج الملفات ==================
35
- def load_and_merge():
36
- if not os.path.exists(BOOKS_FILE) or not os.path.exists(THESES_FILE):
37
- raise FileNotFoundError("❌ تأكدي من وجود book.xlsx و theses.xlsx")
38
-
39
- books = pd.read_excel(BOOKS_FILE).fillna("")
40
- theses = pd.read_excel(THESES_FILE).fillna("")
41
-
42
- # توحيد عمود العنوان
43
- def normalize_title(df):
44
- if "Title" not in df.columns:
45
- if "العنوان" in df.columns:
46
- df["Title"] = df["العنوان"].astype(str)
47
- else:
48
- df["Title"] = df.iloc[:, 0].astype(str)
49
- return df
50
-
51
- books = normalize_title(books)
52
- theses = normalize_title(theses)
53
-
54
- # إضافة نوع المصدر
55
- books["المصدر"] = "كتاب"
56
- theses["المصدر"] = "رسالة"
57
-
58
- # دمج
59
- merged = pd.concat([books, theses], ignore_index=True)
60
- return merged
61
-
62
- library_df = load_and_merge()
63
-
64
- # ================== Embeddings ==================
65
- def emb_path(name):
66
- return os.path.join(EMB_DIR, f"{name}.pkl")
67
-
68
- def build_or_load_embeddings(df, name):
69
- path = emb_path(name)
70
- if os.path.exists(path):
71
- with open(path, "rb") as f:
72
- emb = pickle.load(f)
73
- if len(emb) == len(df):
74
- return emb
75
-
76
- texts = df["Title"].astype(str).tolist()
77
- emb = model.encode(texts, convert_to_numpy=True, show_progress_bar=True)
78
- with open(path, "wb") as f:
79
- pickle.dump(emb, f)
80
- return emb
81
-
82
- library_embeddings = build_or_load_embeddings(library_df, "library")
83
-
84
- # ================== عرض النتائج HTML ==================
85
- def results_to_html(df):
86
- return df.to_html(index=False, escape=False)
87
-
88
- # ================== البحث ==================
89
- def local_search_df(query, mode, source_filter):
90
- if not query or not query.strip():
91
- return "<p>⚠️ اكتب كلمة أو جملة للبحث</p>", pd.DataFrame()
92
-
93
- df_search = library_df.copy()
94
-
95
- # فلترة حسب المصدر
96
- if source_filter != "الكل":
97
- df_search = df_search[df_search["المصدر"] == source_filter]
98
-
99
- # ---- بحث نصي ----
100
- if mode == "نصي":
101
- col = "العنوان" if "العنوان" in df_search.columns else "Title"
102
- df = df_search[df_search[col].astype(str).str.contains(query, case=False, na=False)]
103
-
104
- # ---- بحث دلالي ----
105
- else:
106
- q_emb = model.encode([query], convert_to_numpy=True)
107
- scores = util.cos_sim(q_emb, library_embeddings)[0].cpu().numpy()
108
- df_search = df_search.copy()
109
- df_search["score"] = scores
110
- df = df_search.sort_values("score", ascending=False)
111
-
112
- if df.empty:
113
- df = pd.DataFrame([{"نتيجة": "❌ لم يتم العثور على نتائج"}])
114
-
115
- if "Title" in df.columns:
116
- df = df.drop(columns=["Title"])
117
-
118
- return results_to_html(df), df
119
-
120
- # ================== حفظ النتائج Excel ==================
121
- def save_to_excel(df):
122
- tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
123
- if df is None or df.empty:
124
- pd.DataFrame().to_excel(tmp.name, index=False)
125
- else:
126
- df.to_excel(tmp.name, index=False)
127
- return tmp.name
128
-
129
- # ================== الواجهة ==================
130
- with gr.Blocks(title="البحث الدلالي بالمكتبة") as app:
131
- gr.Markdown("## 🔍 البحث بالمكتبة (ملف موحد)")
132
-
133
- query = gr.Textbox(label="اكتب كلمة أو موضوع البحث")
134
-
135
- mode = gr.Radio(
136
- ["نصي", "دلالي (Semantic)"],
137
- value="نصي",
138
- label="نوع البحث"
139
- )
140
-
141
- source_filter = gr.Radio(
142
- ["الكل", "كتاب", "رسالة"],
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, source_filter],
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()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ BOOKS_FILE = "book.xlsx"
11
+ THESES_FILE = "theses.xlsx"
12
+
13
+ DRIVE_BOOKS_ID = "1FElHiASfiVLeuHWYaqd2Q5foxWRlJT-O"
14
+ DRIVE_THESES_ID = "1K2Mtze6ZdvfKUsFMCOWlRBjDq-ZnJNrv"
15
+
16
+ EMB_DIR = "embeddings"
17
+ os.makedirs(EMB_DIR, exist_ok=True)
18
+
19
+ MODEL_NAME = "paraphrase-multilingual-MiniLM-L12-v2"
20
+ model = SentenceTransformer(MODEL_NAME)
21
+
22
+ # ================== تحميل من Drive ==================
23
+ def download_from_drive(file_id, output):
24
+ if not os.path.exists(output):
25
+ url = f"https://drive.google.com/uc?id={file_id}"
26
+ try:
27
+ gdown.download(url, output, quiet=True)
28
+ except Exception:
29
+ pass
30
+
31
+ download_from_drive(DRIVE_BOOKS_ID, BOOKS_FILE)
32
+ download_from_drive(DRIVE_THESES_ID, THESES_FILE)
33
+
34
+ # ================== تحميل ودمج الملفات ==================
35
+ def load_and_merge():
36
+ if not os.path.exists(BOOKS_FILE) or not os.path.exists(THESES_FILE):
37
+ raise FileNotFoundError("❌ تأكدي من وجود book.xlsx و theses.xlsx")
38
+
39
+ books = pd.read_excel(BOOKS_FILE).fillna("")
40
+ theses = pd.read_excel(THESES_FILE).fillna("")
41
+
42
+ # توحيد عمود العنوان
43
+ def normalize_title(df):
44
+ if "Title" not in df.columns:
45
+ if "العنوان" in df.columns:
46
+ df["Title"] = df["العنوان"].astype(str)
47
+ else:
48
+ df["Title"] = df.iloc[:, 0].astype(str)
49
+ return df
50
+
51
+ books = normalize_title(books)
52
+ theses = normalize_title(theses)
53
+
54
+ # إضافة نوع المصدر
55
+ books["المصدر"] = "كتاب"
56
+ theses["المصدر"] = "رسالة"
57
+
58
+ # دمج
59
+ merged = pd.concat([books, theses], ignore_index=True)
60
+ return merged
61
+
62
+ library_df = load_and_merge()
63
+
64
+ # ================== Embeddings ==================
65
+ def emb_path(name):
66
+ return os.path.join(EMB_DIR, f"{name}.pkl")
67
+
68
+ def build_or_load_embeddings(df, name):
69
+ path = emb_path(name)
70
+ if os.path.exists(path):
71
+ with open(path, "rb") as f:
72
+ emb = pickle.load(f)
73
+ if len(emb) == len(df):
74
+ return emb
75
+
76
+ texts = df["Title"].astype(str).tolist()
77
+ emb = model.encode(texts, convert_to_numpy=True, show_progress_bar=True)
78
+ with open(path, "wb") as f:
79
+ pickle.dump(emb, f)
80
+ return emb
81
+
82
+ library_embeddings = build_or_load_embeddings(library_df, "library")
83
+
84
+ # ================== عرض النتائج HTML ==================
85
+ def results_to_html(df):
86
+ if df.empty:
87
+ return "<p>❌ لم يتم العثور على نتائج</p>"
88
+
89
+ # اختيار الأعمدة المطلوبة
90
+ cols = []
91
+ if "المؤلف" in df.columns:
92
+ cols.append("المؤلف")
93
+ elif "Author" in df.columns:
94
+ df["المؤلف"] = df["Author"]
95
+ cols.append("المؤلف")
96
+ else:
97
+ df["المؤلف"] = "-"
98
+ cols.append("المؤلف")
99
+
100
+ if "العنوان" in df.columns:
101
+ cols.append("العنوان")
102
+ else:
103
+ df["العنوان"] = df.get("Title", "-")
104
+ cols.append("العنوان")
105
+
106
+ if "سنة النشر" in df.columns:
107
+ cols.append("سنة النشر")
108
+ else:
109
+ df["سنة النشر"] = "-"
110
+ cols.append("سنة النشر")
111
+
112
+ if "الموقع على الرف" in df.columns:
113
+ cols.append("الموقع على الرف")
114
+ else:
115
+ df["الموقع على الرف"] = "-"
116
+ cols.append("الموقع على الرف")
117
+
118
+ if "المصدر" in df.columns:
119
+ cols.append("المصدر")
120
+ else:
121
+ df["المصدر"] = "-"
122
+ cols.append("المصدر")
123
+
124
+ df_display = df[cols]
125
+
126
+ # تحويل إلى HTML مع تنسيق بسيط
127
+ return df_display.to_html(index=False, escape=False, classes="table table-striped")
128
+
129
+
130
+ # ================== البحث ==================
131
+ def local_search_df(query, mode, source_filter):
132
+ if not query or not query.strip():
133
+ return "<p>⚠️ اكتب كلمة أو جملة للبحث</p>", pd.DataFrame()
134
+
135
+ df_search = library_df.copy()
136
+
137
+ # فلترة حسب المصدر
138
+ if source_filter != "الكل":
139
+ df_search = df_search[df_search["المصدر"] == source_filter]
140
+
141
+ # ---- بحث نصي ----
142
+ if mode == "نصي":
143
+ col = "العنوان" if "العنوان" in df_search.columns else "Title"
144
+ df = df_search[df_search[col].astype(str).str.contains(query, case=False, na=False)]
145
+
146
+ # ---- بحث دلالي ----
147
+ else:
148
+ q_emb = model.encode([query], convert_to_numpy=True)
149
+ scores = util.cos_sim(q_emb, library_embeddings)[0].cpu().numpy()
150
+ df_search = df_search.copy()
151
+ df_search["score"] = scores
152
+ df = df_search.sort_values("score", ascending=False)
153
+
154
+ if df.empty:
155
+ df = pd.DataFrame([{"نتيجة": "❌ لم يتم العثور على نتائج"}])
156
+
157
+ if "Title" in df.columns:
158
+ df = df.drop(columns=["Title"])
159
+
160
+ return results_to_html(df), df
161
+
162
+ # ================== حفظ النتائج Excel ==================
163
+ def save_to_excel(df):
164
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
165
+ if df is None or df.empty:
166
+ pd.DataFrame().to_excel(tmp.name, index=False)
167
+ else:
168
+ df.to_excel(tmp.name, index=False)
169
+ return tmp.name
170
+
171
+ # ================== الواجهة ==================
172
+ with gr.Blocks(title="البحث الدلالي بالمكتبة") as app:
173
+ gr.Markdown("## 🔍 البحث بالمكتبة (ملف موحد)")
174
+
175
+ # صورة المكتبة
176
+ gr.Image("https://drive.google.com/uc?id=1y1cbJbdXSrhkEM7bMDrAUKr0dTiHPe-y",
177
+ elem_id="library-image", type="auto")
178
+
179
+ query = gr.Textbox(label="اكتب كلمة أو موضوع البحث")
180
+
181
+ mode = gr.Radio(
182
+ ["نصي", "دلالي (Semantic)"],
183
+ value="نصي",
184
+ label="نوع البحث"
185
+ )
186
+
187
+ source_filter = gr.Radio(
188
+ ["الكل", "كتاب", "رسالة"],
189
+ value="الكل",
190
+ label="فلترة حسب المصدر"
191
+ )
192
+
193
+ btn_search = gr.Button("🔎 بحث")
194
+
195
+ df_state = gr.State()
196
+ output_html = gr.HTML()
197
+ file_out = gr.File(label="⬇️ تحميل النتائج")
198
+
199
+ btn_search.click(
200
+ local_search_df,
201
+ inputs=[query, mode, source_filter],
202
+ outputs=[output_html, df_state]
203
+ )
204
+
205
+ gr.Button("📥 حفظ النتائج").click(
206
+ save_to_excel,
207
+ inputs=df_state,
208
+ outputs=file_out
209
+ )
210
+
211
+
212
+ app.launch()