DrugKnowledge commited on
Commit
f5e2e1b
·
verified ·
1 Parent(s): 37f2681

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +1053 -0
app.py ADDED
@@ -0,0 +1,1053 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ # ================== الاستيراد ==================
3
+ import gradio as gr
4
+ import pandas as pd
5
+ import numpy as np
6
+ import tempfile
7
+ import os, pickle
8
+ from datetime import datetime
9
+ import io, base64
10
+ import arabic_reshaper
11
+ from bidi.algorithm import get_display
12
+ import matplotlib.pyplot as plt
13
+ from sentence_transformers import SentenceTransformer, util
14
+ from Bio import Entrez
15
+ import gdown
16
+
17
+ # ------------------ Data store & Google Drive sync (background sync) ------------------
18
+ DATA_FOLDER = "data_store"
19
+ DRIVE_FOLDER_ID = "1znvCrr63iSN2MWveAZvcXuGT3o5TfZc2" # Library_Backups folder ID on your Drive
20
+
21
+ def ensure_data_folder():
22
+ os.makedirs(DATA_FOLDER, exist_ok=True)
23
+ return DATA_FOLDER
24
+
25
+ def get_data_path(filename):
26
+ ensure_data_folder()
27
+ return os.path.join(DATA_FOLDER, filename)
28
+
29
+ # Attempt to import PyDrive2 and set up authentication functions.
30
+ try:
31
+ from pydrive2.auth import GoogleAuth
32
+ from pydrive2.drive import GoogleDrive
33
+ _GD_AVAILABLE = True
34
+ except Exception:
35
+ _GD_AVAILABLE = False
36
+
37
+ def ensure_drive_auth():
38
+ """
39
+ Authenticate to Google Drive using a Service Account JSON file (client_secrets.json)
40
+ placed inside data_store/. Works automatically on Spaces without manual login.
41
+ """
42
+ if not _GD_AVAILABLE:
43
+ print("❌ PyDrive2 not available.")
44
+ return None
45
+ try:
46
+ from pydrive2.auth import GoogleAuth
47
+ from pydrive2.drive import GoogleDrive
48
+
49
+ service_account_path = os.path.join(DATA_FOLDER, "client_secrets.json")
50
+
51
+ if not os.path.exists(service_account_path):
52
+ print("⚠️ لم يتم العثور على ملف client_secrets.json في data_store/")
53
+ return None
54
+
55
+ gauth = GoogleAuth()
56
+ gauth.LoadServiceConfigFile(service_account_path) # ✅ التغيير هنا
57
+ gauth.ServiceAuth()
58
+ drive = GoogleDrive(gauth)
59
+ print("✅ تم الاتصال بـ Google Drive باستخدام Service Account بنجاح.")
60
+ return drive
61
+
62
+ except Exception as e:
63
+ print("❌ فشل الاتصال بـ Google Drive:", e)
64
+ return None
65
+ return None
66
+
67
+
68
+ def upload_to_drive(local_path, remote_name=None):
69
+ """
70
+ Uploads a local file to Google Drive inside the folder defined by DRIVE_FOLDER_ID.
71
+ """
72
+ try:
73
+ drive = ensure_drive_auth()
74
+ if drive is None:
75
+ print("⚠️ لم يتم الاتصال بـ Google Drive، لم يتم رفع الملف:", local_path)
76
+ return False
77
+ if remote_name is None:
78
+ remote_name = os.path.basename(local_path)
79
+
80
+ q = f"'{DRIVE_FOLDER_ID}' in parents and title = '{remote_name}' and trashed=false"
81
+ file_list = drive.ListFile({'q': q}).GetList()
82
+ if file_list:
83
+ f = file_list[0]
84
+ f.SetContentFile(local_path)
85
+ f.Upload()
86
+ print(f"🔁 تم تحديث الملف الموجود في Google Drive: {remote_name}")
87
+ else:
88
+ file_metadata = {'title': remote_name, 'parents': [{'id': DRIVE_FOLDER_ID}]}
89
+ f = drive.CreateFile(file_metadata)
90
+ f.SetContentFile(local_path)
91
+ f.Upload()
92
+ print(f"✅ تم رفع ملف جديد إلى Google Drive: {remote_name}")
93
+ return True
94
+ except Exception as e:
95
+ print("❌ خطأ أثناء رفع الملف إلى Google Drive:", e)
96
+ return False
97
+ import shutil, time, threading
98
+
99
+ def _background_sync(interval_seconds=30):
100
+ """
101
+ Background thread to watch for new or modified CSV/XLSX files and upload them to Google Drive automatically.
102
+ """
103
+ def _worker():
104
+ seen = {}
105
+ while True:
106
+ try:
107
+ # scan for csv and xlsx files in project root
108
+ for fname in os.listdir():
109
+ if fname.lower().endswith(('.csv', '.xlsx')) and fname not in (os.path.basename(__file__),):
110
+ try:
111
+ src_path = os.path.join(os.getcwd(), fname)
112
+ dst_path = get_data_path(fname)
113
+
114
+ # check modification time
115
+ mtime = os.path.getmtime(src_path)
116
+ if fname not in seen or seen[fname] < mtime:
117
+ # copy file to data_store
118
+ shutil.copy2(src_path, dst_path)
119
+ seen[fname] = mtime
120
+
121
+ # try uploading to Drive
122
+ success = upload_to_drive(dst_path, os.path.basename(dst_path))
123
+ if success:
124
+ print(f"📤 تمت مزامنة الملف مع Google Drive: {fname} ({datetime.now().strftime('%Y-%m-%d %H:%M:%S')})")
125
+ else:
126
+ print(f"⚠️ فشل رفع الملف: {fname}")
127
+ except Exception as e:
128
+ print("❌ خطأ أثناء المزامنة:", e)
129
+ pass
130
+ except Exception:
131
+ pass
132
+ time.sleep(interval_seconds)
133
+
134
+ t = threading.Thread(target=_worker, daemon=True)
135
+ t.start()
136
+
137
+ # تشغيل المزامنة التلقائية كل 20 ثانية
138
+ try:
139
+ _background_sync(interval_seconds=20)
140
+ except Exception as e:
141
+ print("⚠️ لم يتم تشغيل المزامنة التلقائية:", e)
142
+
143
+
144
+ # ------------------ end background sync ------------------
145
+
146
+
147
+ # ================== دوال مساعدة ==================
148
+ def download_from_drive(file_id, output):
149
+ url = f"https://drive.google.com/uc?id={file_id}"
150
+ try:
151
+ gdown.download(url, output, quiet=True)
152
+ except Exception:
153
+ # إذا فشل التحميل من Drive نتابع لوجود ملفات محلية بالفعل
154
+ pass
155
+
156
+ # ================== إعدادات ومسارات ==================
157
+ Entrez.email = "emananter0123@gmail.com"
158
+ EMB_DIR = "embeddings_cache"
159
+ os.makedirs(EMB_DIR, exist_ok=True)
160
+
161
+ def embeddings_path(name):
162
+ return os.path.join(EMB_DIR, f"{name}_embeddings.pkl")
163
+
164
+ BOOKS_FILE, THESES_FILE, FAQ_FILE = "book.xlsx", "theses.xlsx", "faq.xlsx"
165
+ QUESTIONS_FILE = "questions.csv" # ملف حفظ الأسئلة
166
+ FACULTY_BORROW_FILE = "faculty_borrow.csv" # طلبات أعضاء هيئة التدريس للاستعارة
167
+
168
+ # محاولة تنزيل الملفات من Google Drive (إن أردتِ يمكنك حذف السطور التالية إذا الملفات محلية)
169
+ download_from_drive("1FElHiASfiVLeuHWYaqd2Q5foxWRlJT-O", BOOKS_FILE) # book.xlsx
170
+ download_from_drive("1K2Mtze6ZdvfKUsFMCOWlRBjDq-ZnJNrv", THESES_FILE) # theses.xlsx
171
+ download_from_drive("1ONjXtfv709BOxiIR0Qzmz6lQngnWEEso", FAQ_FILE) # faq.xlsx
172
+
173
+ # ================== تحميل البيانات المحلية ==================
174
+ def load_local_data():
175
+ if not os.path.exists(BOOKS_FILE) or not os.path.exists(THESES_FILE):
176
+ raise FileNotFoundError("تأكدي من رفع الملفات book.xlsx و theses.xlsx في مجلد المشروع.")
177
+ books = pd.read_excel(BOOKS_FILE).fillna("غير متوافر")
178
+ theses = pd.read_excel(THESES_FILE).fillna("غير متوافر")
179
+ # توحيد اسم عمود العنوان بين ملفات مختلفة
180
+ if "Title" not in books.columns and "العنوان" in books.columns:
181
+ books["Title"] = books["العنوان"].astype(str)
182
+ elif "Title" not in books.columns:
183
+ books["Title"] = books.iloc[:,0].astype(str)
184
+
185
+ if "Title" not in theses.columns and "العنوان" in theses.columns:
186
+ theses["Title"] = theses["العنوان"].astype(str)
187
+ elif "Title" not in theses.columns:
188
+ theses["Title"] = theses.iloc[:,0].astype(str)
189
+
190
+ return books, theses
191
+
192
+ books_df, theses_df = load_local_data()
193
+
194
+ # ================== نموذج Semantic ==================
195
+ MODEL_NAME = "all-MiniLM-L6-v2"
196
+ model = SentenceTransformer(MODEL_NAME)
197
+
198
+ def build_or_load_embeddings(df, name):
199
+ path = embeddings_path(name)
200
+ if os.path.exists(path):
201
+ try:
202
+ with open(path,"rb") as f:
203
+ emb = pickle.load(f)
204
+ if len(emb) == len(df):
205
+ return emb
206
+ except Exception:
207
+ pass
208
+ texts = df["Title"].astype(str).tolist()
209
+ emb = model.encode(texts, convert_to_numpy=True, show_progress_bar=True)
210
+ with open(path,"wb") as f:
211
+ pickle.dump(emb,f)
212
+ return emb
213
+
214
+ books_embeddings = build_or_load_embeddings(books_df,"books")
215
+ theses_embeddings = build_or_load_embeddings(theses_df,"theses")
216
+
217
+ # ================== FAQ & مساعد ذكي ==================
218
+ if os.path.exists(FAQ_FILE):
219
+ faq_df = pd.read_excel(FAQ_FILE).fillna("")
220
+ else:
221
+ faq_df = pd.DataFrame({
222
+ "السؤال":["مواعيد المكتبة","خدمات المكتبة","كيفية الاستعارة","التسجيل في بنك المعرفة","التصوير","أقسام المكتبة","التواصل"],
223
+ "الإجابة":[
224
+ "🕘 المكتبة تعمل من السبت إلى الخميس من 9 صباحًا حتى 2 ظهرًا",
225
+ "📌 خدمات المكتبة: الإحاطة الجارية، التسجيل على بنك المعرفة، التصوير، البحث الإلكتروني، الاستعارة الخارجية",
226
+ "✅ يتم استعارة الكتب لمدة أسبوعين (أو حسب القاعدة المحلية)",
227
+ "🔗 التسجيل في بنك المعرفة عبر موقع بنك المعرفة المصري",
228
+ "🖨️ التصوير متاح وفق القواعد",
229
+ "📚 المكتبة بها: قاعة المراجع، قاعة الكتب الدراسية، قاعة الدوريات، قاعة الرسائل الجامعية",
230
+ "☎️ للتواصل: <a href='https://www.facebook.com/share/1AuUSQUn4n/' target='_blank'>صفحة الفيسبوك</a>"
231
+ ]
232
+ })
233
+
234
+ faq_questions = faq_df["السؤال"].astype(str).tolist()
235
+ faq_answers = faq_df["الإجابة"].astype(str).tolist()
236
+
237
+ FAQ_EMB_PATH = embeddings_path("faq")
238
+ def build_or_load_faq_embeddings(questions):
239
+ if os.path.exists(FAQ_EMB_PATH):
240
+ try:
241
+ with open(FAQ_EMB_PATH,"rb") as f:
242
+ emb = pickle.load(f)
243
+ if len(emb) == len(questions):
244
+ return emb
245
+ except Exception:
246
+ pass
247
+ emb = model.encode(questions, convert_to_numpy=True, show_progress_bar=False)
248
+ with open(FAQ_EMB_PATH,"wb") as f:
249
+ pickle.dump(emb,f)
250
+ return emb
251
+
252
+ faq_embeddings = build_or_load_faq_embeddings(faq_questions)
253
+
254
+ def library_assistant_smart(question):
255
+ if not str(question).strip():
256
+ return "⚠️ من فضلك اكتب سؤالك"
257
+ q_emb = model.encode([str(question)], convert_to_numpy=True)
258
+ sims = util.cos_sim(q_emb, faq_embeddings)[0].cpu().numpy()
259
+ idx_best = int(np.argmax(sims))
260
+ best_score = sims[idx_best]
261
+ log_usage("المساعد الذكي", question, "FAQ", 1)
262
+ if best_score < 0.75:
263
+ return "❗ لم أجد إجابة مناسبة، حاول صياغة سؤالك بشكل مختلف."
264
+ return f"<b>الإجابة الأقرب:</b><br>{faq_answers[idx_best]}<br><i>درجة التشابه: {best_score:.2f}</i>"
265
+
266
+ # ================== CSS ==================
267
+ CUSTOM_CSS = """<style>
268
+ .styled-table {
269
+ border-collapse: collapse;
270
+ margin: 15px 0;
271
+ font-size: 14px;
272
+ width: 100%;
273
+ text-align: right;
274
+ direction: rtl;
275
+ }
276
+ .styled-table th, .styled-table td {
277
+ border: 1px solid #ddd;
278
+ padding: 8px;
279
+ }
280
+ .styled-table tr:nth-child(even) {background-color: #f9f9f9;}
281
+ .styled-table tr:nth-child(odd) {background-color: #ffffff;}
282
+ .styled-table th {background-color: #4da6ff; color: white;}
283
+ a {color: #0066cc; text-decoration: none;}
284
+ a:hover {text-decoration: underline;}
285
+ .question-card {
286
+ border: 1px solid #ddd;
287
+ padding: 10px;
288
+ margin-bottom: 12px;
289
+ border-radius: 8px;
290
+ background: #fff;
291
+ direction: rtl;
292
+ }
293
+ .question-meta { font-size: 13px; color: #666; margin-bottom:6px; }
294
+ .answer { margin-top:8px; padding:8px; border-radius:6px; background:#f7f7f7; }
295
+ .anon { color:#999; font-style:italic; }
296
+ </style>"""
297
+
298
+ # ================== تتبع الاستخدام ==================
299
+ def log_usage(tab, query="", mode="", results_count=0):
300
+ file_path = "usage_stats.xlsx"
301
+ entry = pd.DataFrame([{
302
+ "التاريخ": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
303
+ "التب": tab,
304
+ "الكلمة المفتاحية": query,
305
+ "نوع البحث": mode,
306
+ "عدد النتائج": results_count
307
+ }])
308
+ if os.path.exists(file_path):
309
+ try:
310
+ old = pd.read_excel(file_path)
311
+ entry = pd.concat([old, entry], ignore_index=True)
312
+ except Exception:
313
+ entry = entry
314
+ entry.to_excel(file_path, index=False)
315
+
316
+ # ================== عرض إحصاءات الاستخدام ==================
317
+ def show_usage_stats():
318
+ file_path = "usage_stats.xlsx"
319
+ if not os.path.exists(file_path):
320
+ return "<p>📊 لا توجد بيانات بعد</p>"
321
+ df = pd.read_excel(file_path)
322
+ total = len(df)
323
+ by_tab = df["التب"].value_counts()
324
+ fig, ax = plt.subplots()
325
+ labels = [get_display(arabic_reshaper.reshape(str(t))) for t in by_tab.index]
326
+ ax.bar(labels, by_tab.values)
327
+ for i, v in enumerate(by_tab.values):
328
+ ax.text(i, v + 0.1, str(v), ha='center', va='bottom', fontsize=10)
329
+ ax.set_title(get_display(arabic_reshaper.reshape("عدد مرات استخدام كل تب")))
330
+ ax.set_xlabel(get_display(arabic_reshaper.reshape("التب")))
331
+ ax.set_ylabel(get_display(arabic_reshaper.reshape("عدد العمليات")))
332
+ plt.xticks(rotation=30, ha='right')
333
+ buf = io.BytesIO()
334
+ plt.tight_layout()
335
+ plt.savefig(buf, format="png")
336
+ plt.close(fig)
337
+ buf.seek(0)
338
+ img = base64.b64encode(buf.read()).decode("utf-8")
339
+ summary = f"<h3>📈 إجمالي الاستخدام: {total} عملية</h3>"
340
+ html = summary + "<img src='data:image/png;base64," + img + "'/>"
341
+ return CUSTOM_CSS + html + df.to_html(escape=False, index=False, classes="styled-table")
342
+
343
+ # ================== تحويل نتائج إلى HTML أنيق ==================
344
+ def results_to_html(df):
345
+ if df.empty:
346
+ return "<p>❌ لا توجد نتائج</p>"
347
+ html = CUSTOM_CSS + "<div style='direction:rtl;text-align:right;'>"
348
+ for i, row in df.iterrows():
349
+ html += "<table class='styled-table' style='margin-bottom:15px;'>"
350
+ html += f"<caption style='caption-side:top;text-align:right;font-weight:bold;margin-bottom:5px;'>📘 النتيجة {i+1}</caption>"
351
+ for col, val in row.items():
352
+ html += f"<tr><th>{col}</th><td>{val}</td></tr>"
353
+ html += "</table>"
354
+ html += "</div>"
355
+ return html
356
+
357
+ def df_to_html(df):
358
+ if isinstance(df, str):
359
+ return df
360
+ if df.empty:
361
+ return "<p>��� لا توجد نتائج</p>"
362
+ return CUSTOM_CSS + df.to_html(escape=False, index=False, classes="styled-table")
363
+
364
+ # ================== حفظ النتائج إلى ملف Excel ==================
365
+ def save_to_excel(df):
366
+ if df is None or (isinstance(df, pd.DataFrame) and df.empty):
367
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
368
+ pd.DataFrame().to_excel(tmp.name, index=False)
369
+ return tmp.name
370
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
371
+ if isinstance(df, pd.DataFrame):
372
+ df.to_excel(tmp.name, index=False)
373
+ else:
374
+ pd.DataFrame({"result_html":[str(df)]}).to_excel(tmp.name, index=False)
375
+ return tmp.name
376
+
377
+ # ================== البحث المحلي ==================
378
+ def local_search_df(query, category, mode):
379
+ if not query or not str(query).strip():
380
+ return "<p>⚠️ اكتب كلمة أو جملة للبحث</p>", pd.DataFrame()
381
+
382
+ if mode == "نصي":
383
+ if category == "Books":
384
+ if "العنوان" in books_df.columns:
385
+ df = books_df[books_df["العنوان"].astype(str).str.contains(query, case=False, na=False)]
386
+ else:
387
+ df = books_df[books_df["Title"].astype(str).str.contains(query, case=False, na=False)]
388
+ else:
389
+ if "العنوان" in theses_df.columns:
390
+ df = theses_df[theses_df["العنوان"].astype(str).str.contains(query, case=False, na=False)]
391
+ else:
392
+ df = theses_df[theses_df["Title"].astype(str).str.contains(query, case=False, na=False)]
393
+ else:
394
+ q_emb = model.encode([query], convert_to_numpy=True)
395
+ if category == "Books":
396
+ scores = util.cos_sim(q_emb, books_embeddings)[0].cpu().numpy()
397
+ idx = np.argsort(-scores)
398
+ df = books_df.iloc[idx]
399
+ else:
400
+ scores = util.cos_sim(q_emb, theses_embeddings)[0].cpu().numpy()
401
+ idx = np.argsort(-scores)
402
+ df = theses_df.iloc[idx]
403
+
404
+ if df is None or df.empty:
405
+ df = pd.DataFrame([{"نتيجة":"❌ لم يتم العثور على نتائج"}])
406
+ else:
407
+ if "Title" in df.columns:
408
+ df = df.drop(columns=["Title"])
409
+
410
+ log_usage("البحث المحلي", query, mode, len(df) if isinstance(df, pd.DataFrame) else 0)
411
+ html_results = results_to_html(df)
412
+ return html_results, df
413
+
414
+ # ================== البحث في PubMed ==================
415
+ def search_pubmed_html(query, max_results=5):
416
+ if not query or not str(query).strip():
417
+ return "<p>⚠️ اكتب كلمة للبحث</p>"
418
+ try:
419
+ handle = Entrez.esearch(db="pubmed", term=query, retmax=max_results)
420
+ record = Entrez.read(handle)
421
+ handle.close()
422
+ ids = record.get("IdList", [])
423
+ if not ids:
424
+ return "<p>❌ لا توجد نتائج</p>"
425
+
426
+ handle = Entrez.efetch(db="pubmed", id=",".join(ids), rettype="xml", retmode="xml")
427
+ records = Entrez.read(handle)
428
+ handle.close()
429
+
430
+ rows = []
431
+ for rec in records.get('PubmedArticle', []):
432
+ try:
433
+ title = rec['MedlineCitation']['Article']['ArticleTitle']
434
+ pmid = rec['MedlineCitation']['PMID']
435
+ link = f"https://pubmed.ncbi.nlm.nih.gov/{pmid}/"
436
+ rows.append({
437
+ "الموقع": "PubMed",
438
+ "الوصف": "قاعدة بيانات PubMed",
439
+ "العنوان": title,
440
+ "الرابط": f"<a href='{link}' target='_blank'>فتح</a>"
441
+ })
442
+ except Exception:
443
+ continue
444
+
445
+ if not rows:
446
+ return "<p>❌ لم يتم العثور على نتائج صالحة.</p>"
447
+
448
+ df = pd.DataFrame(rows)
449
+ log_usage("المصادر الخارجية", query, "PubMed", len(df))
450
+ return CUSTOM_CSS + df.to_html(escape=False, index=False, classes="styled-table")
451
+
452
+ except Exception as e:
453
+ return f"<p>❌ حدث خطأ أثناء جلب البيانات من PubMed:<br>{str(e)}</p>"
454
+
455
+ # ================== البحث في المواقع الخارجية ==================
456
+ EXTERNAL_LINKS = {
457
+ "Google Scholar": {"url": "https://scholar.google.com/scholar?q=", "desc": "محرك بحث للأبحاث"},
458
+ "PubMed": {"url": "https://pubmed.ncbi.nlm.nih.gov/?term=", "desc": "قاعدة بيانات PubMed"},
459
+ "Europe PMC": {"url": "https://europepmc.org/search?query=", "desc": "أبحاث Europe PMC"},
460
+ "ClinicalTrials.gov": {"url": "https://clinicaltrials.gov/search?term=", "desc": "تجارب سريرية"},
461
+ "OpenFDA": {"url": "https://open.fda.gov/", "desc": "بيانات الأدوية FDA"},
462
+ "MedlinePlus": {"url": "https://medlineplus.gov/search/?query=", "desc": "معلومات طبية"},
463
+ "DrugBank": {"url": "https://go.drugbank.com/", "desc": "قاعدة بيانات الأدوية"},
464
+ "WHO GHO": {"url": "https://www.who.int/data/gho/", "desc": "بيانات ا��صحة العالمية"},
465
+ "ICD-11": {"url": "https://icd.who.int/browse11/l-m/en", "desc": "التصنيف الدولي للأمراض"},
466
+ "ClinicalKey": {"url": "https://www.clinicalkey.com/search?q=", "desc": "مصادر طبية شاملة"},
467
+ "Scimago": {"url": "https://www.scimagojr.com/journalsearch.php?q=", "desc": "تصنيف الدوريات"},
468
+ "EKB": {"url": "https://www.ekb.eg/", "desc": "بنك المعرفة المصري"}
469
+ }
470
+
471
+ def external_search_html(query, site):
472
+ try:
473
+ if not query or not str(query).strip():
474
+ return "<p>⚠️ من فضلك اكتب كلمة للبحث</p>"
475
+
476
+ if not site or site not in EXTERNAL_LINKS:
477
+ return f"<p>⚠️ الموقع المحدد غير معروف أو غير موجود في القائمة.</p>"
478
+
479
+ if site == "PubMed":
480
+ return search_pubmed_html(query)
481
+
482
+ base = EXTERNAL_LINKS[site]["url"]
483
+ desc = EXTERNAL_LINKS[site]["desc"]
484
+ if "?" in base or "=" in base:
485
+ link = f"{base}{query}"
486
+ else:
487
+ link = base
488
+ df = pd.DataFrame([
489
+ {"اسم الموقع": site, "الوصف": desc, "رابط البحث": f"<a href='{link}' target='_blank'>للوصول إلى نتيجة البحث</a>"}
490
+ ])
491
+ log_usage("المصادر الخارجية", query, site, 1)
492
+ html_table = df.to_html(escape=False, index=False, classes="styled-table")
493
+ return CUSTOM_CSS + f"<h3>🔗 نتائج البحث في {site}</h3>" + html_table
494
+
495
+ except Exception as e:
496
+ return f"<p>❌ حدث خطأ أثناء تنفيذ البحث:<br>{str(e)}</p>"
497
+
498
+ # ================== البحث في الدوريات ==================
499
+ JOURNALS = {
500
+ "Elsevier Journal Finder": {"url": "https://journalfinder.elsevier.com/", "desc": "اقتراح مجلات النشر"},
501
+ "Springer Journal Suggester": {"url": "https://journalsuggester.springer.com/", "desc": "اقتراح مجلات النشر"},
502
+ "DOAJ": {"url": "https://doaj.org/search/journals?ref=homepage-box&source=", "desc": "مجلات مفتوحة الوصول"},
503
+ "Journal Citation Reports": {"url": "https://jcr.clarivate.com/jcr/browse-journals?query=", "desc": "تقييم الدوريات العلمية"},
504
+ "Scimago": {"url": "https://www.scimagojr.com/journalsearch.php?q=", "desc": "تصنيف الدوريات"},
505
+ "Google Scholar": {"url": "https://scholar.google.com/scholar?q=", "desc": "بحث عام"}
506
+ }
507
+
508
+ def journal_search_html(query, site):
509
+ try:
510
+ if not query or not str(query).strip():
511
+ return "<p>⚠️ من فضلك اكتب كلمة للبحث</p>"
512
+ if not site or site not in JOURNALS:
513
+ return f"<p>⚠️ الموقع المحدد غير معروف أو غير موجود في قائمة الدوريات.</p>"
514
+ base = JOURNALS[site]["url"]
515
+ desc = JOURNALS[site]["desc"]
516
+ if "?" in base or "=" in base:
517
+ link = f"{base}{query}"
518
+ else:
519
+ link = base
520
+ df = pd.DataFrame([{"اسم الموقع": site, "الوصف": desc, "رابط البحث": f"<a href='{link}' target='_blank'>للوصول إلى نتيجة البحث</a>"}])
521
+ log_usage("الدوريات", query, site, 1)
522
+ html_table = df.to_html(escape=False, index=False, classes="styled-table")
523
+ return CUSTOM_CSS + f"<h3>📄 نتائج البحث في {site}</h3>" + html_table
524
+ except Exception as e:
525
+ return f"<p>❌ حدث خطأ أثناء تنفيذ البحث:<br>{str(e)}</p>"
526
+
527
+ # ================== أدوات الذكاء الاصطناعي ==================
528
+ AI_TOOLS = {
529
+ "Semantic Scholar": {"url": "https://www.semanticscholar.org/search?q=", "desc": "بحث أكاديمي يعتمد على الذكاء الاصطناعي"},
530
+ "Connected Papers": {"url": "https://www.connectedpapers.com/search?q=", "desc": "خرائط علاقات بين الأبحاث"},
531
+ "Research Rabbit": {"url": "https://www.researchrabbitapp.com/", "desc": "تتبع شبكات الأبحاث"},
532
+ "Elicit": {"url": "https://elicit.org/", "desc": "مساعد بحث علمي يستخدم AI"},
533
+ "Explainpaper": {"url": "https://www.explainpaper.com/", "desc": "تبسيط الأبحاث العلمية"},
534
+ "Consensus": {"url": "https://consensus.app/search/?q=", "desc": "إجابات سريعة مدعومة بالأدلة"}
535
+ }
536
+
537
+ def ai_search_html(query, site):
538
+ try:
539
+ if not query or not str(query).strip():
540
+ return "<p>⚠️ من فضلك اكتب كلمة للبحث</p>"
541
+ if not site or site not in AI_TOOLS:
542
+ return f"<p>⚠️ الأداة المحددة غير معروفة أو غير موجودة في القائمة.</p>"
543
+ base = AI_TOOLS[site]["url"]
544
+ desc = AI_TOOLS[site]["desc"]
545
+ if "?" in base or "=" in base:
546
+ link = f"{base}{query}"
547
+ else:
548
+ link = base
549
+ df = pd.DataFrame([{"اسم الأداة": site, "الوصف": desc, "رابط ال��حث": f"<a href='{link}' target='_blank'>للوصول إلى نتيجة البحث</a>"}])
550
+ log_usage("أدوات الذكاء الاصطناعي", query, site, 1)
551
+ html_table = df.to_html(escape=False, index=False, classes="styled-table")
552
+ return CUSTOM_CSS + f"<h3>🤖 نتائج البحث في {site}</h3>" + html_table
553
+ except Exception as e:
554
+ return f"<p>❌ حدث خطأ أثناء تنفيذ البحث:<br>{str(e)}</p>"
555
+
556
+ # ================== وظائف إدارة الأسئلة (CSV) ==================
557
+ def ensure_questions_file():
558
+ if not os.path.exists(QUESTIONS_FILE):
559
+ df = pd.DataFrame(columns=["id","name","question","answer","status","datetime"])
560
+ df.to_csv(QUESTIONS_FILE, index=False, encoding="utf-8-sig")
561
+
562
+ def read_questions_df():
563
+ ensure_questions_file()
564
+ try:
565
+ df = pd.read_csv(QUESTIONS_FILE, encoding="utf-8-sig")
566
+ except Exception:
567
+ df = pd.DataFrame(columns=["id","name","question","answer","status","datetime"])
568
+ return df
569
+
570
+ def save_question_to_csv(name, question):
571
+ ensure_questions_file()
572
+ df = read_questions_df()
573
+ if df.empty:
574
+ next_id = 1
575
+ else:
576
+ try:
577
+ next_id = int(df["id"].max()) + 1
578
+ except Exception:
579
+ next_id = len(df) + 1
580
+ row = {
581
+ "id": next_id,
582
+ "name": name if name and str(name).strip() else "👤 طالب مجهول",
583
+ "question": question,
584
+ "answer": "",
585
+ "status": "لم يتم الرد",
586
+ "datetime": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
587
+ }
588
+ df = pd.concat([df, pd.DataFrame([row])], ignore_index=True)
589
+ df.to_csv(QUESTIONS_FILE, index=False, encoding="utf-8-sig")
590
+ return next_id
591
+
592
+ def save_answer_to_csv(qid, answer_text):
593
+ ensure_questions_file()
594
+ df = read_questions_df()
595
+ if df.empty:
596
+ return False, "لا توجد أسئلة."
597
+ try:
598
+ qid = int(qid)
599
+ except Exception:
600
+ return False, "معرّف السؤال غير صالح."
601
+ if qid not in df["id"].values:
602
+ return False, "لم يتم إيجاد السؤال بالمعرّف المحدد."
603
+ df.loc[df["id"] == qid, "answer"] = answer_text
604
+ df.loc[df["id"] == qid, "status"] = "تم الرد"
605
+ df.to_csv(QUESTIONS_FILE, index=False, encoding="utf-8-sig")
606
+ return True, "تم حفظ الرد بنجاح."
607
+
608
+ def questions_to_html(df):
609
+ if df is None or df.empty:
610
+ return "<p>❌ لا توجد أسئلة حتى الآن.</p>"
611
+ html = CUSTOM_CSS + "<div style='direction:rtl;text-align:right;'>"
612
+ df_sorted = df.sort_values(by="id", ascending=False).reset_index(drop=True)
613
+ for _, row in df_sorted.iterrows():
614
+ name = row.get("name","👤 طالب مجهول")
615
+ qtext = row.get("question","")
616
+ answer = row.get("answer","")
617
+ status = row.get("status","لم يتم الرد")
618
+ qid = row.get("id","")
619
+ dt = row.get("datetime","")
620
+ html += f"<div class='question-card'><div class='question-meta'># {qid} — {dt} — <b>{name}</b></div>"
621
+ html += f"<div><b>السؤال:</b> {qtext}</div>"
622
+ if status == "تم الرد" and str(answer).strip():
623
+ html += f"<div class='answer'><b>الرد:</b> {answer} <div class='question-meta'>حالة: {status}</div></div>"
624
+ else:
625
+ html += f"<div class='answer'><i>لم يتم الرد بعد</i> <div class='question-meta'>حالة: {status}</div></div>"
626
+ html += "</div>"
627
+ html += "</div>"
628
+ return html
629
+
630
+ # ================== وظائف إدارة طلبات الاستعارة (أعضاء هيئة التدريس) ==================
631
+ def ensure_faculty_file():
632
+ if not os.path.exists(FACULTY_BORROW_FILE):
633
+ df = pd.DataFrame(columns=["id","name","phone","nid","email","position","birthdate","status","datetime"])
634
+ df.to_csv(FACULTY_BORROW_FILE, index=False, encoding="utf-8-sig")
635
+
636
+ def read_faculty_df():
637
+ ensure_faculty_file()
638
+ try:
639
+ df = pd.read_csv(FACULTY_BORROW_FILE, encoding="utf-8-sig")
640
+ except Exception:
641
+ df = pd.DataFrame(columns=["id","name","phone","nid","email","position","birthdate","status","datetime"])
642
+ return df
643
+
644
+ def save_faculty_request(name, phone, nid, email, position, birthdate):
645
+ ensure_faculty_file()
646
+ df = read_faculty_df()
647
+ if df.empty:
648
+ next_id = 1
649
+ else:
650
+ try:
651
+ next_id = int(df["id"].max()) + 1
652
+ except Exception:
653
+ next_id = len(df) + 1
654
+ row = {
655
+ "id": next_id,
656
+ "name": name,
657
+ "phone": phone,
658
+ "nid": nid,
659
+ "email": email,
660
+ "position": position,
661
+ "birthdate": birthdate,
662
+ "status": "قيد المراجعة",
663
+ "datetime": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
664
+ }
665
+ df = pd.concat([df, pd.DataFrame([row])], ignore_index=True)
666
+ df.to_csv(FACULTY_BORROW_FILE, index=False, encoding="utf-8-sig")
667
+ return next_id
668
+
669
+ # ================== واجهة Gradio ==================
670
+ with gr.Blocks() as demo:
671
+ with gr.Tab("📚 عن المكتبة"):
672
+ with gr.Tabs():
673
+ with gr.Tab("🌟 رؤية المكتبة"):
674
+ gr.Markdown("تسعى المكتبة إلى أن تكون مركزًا معرفيًا متميزًا يدعم البحث والتعليم ويُسهم في بناء مجتمع المعرفة.")
675
+ with gr.Tab("🎯 رسالة المكتبة"):
676
+ gr.Markdown("تقديم خدمات معلوماتية متكاملة تُمكّن الباحثين والطلاب من الوصول إلى مصادر المعرفة بسهولة وكفاءة.")
677
+ with gr.Tab("🎯 أهداف المكتبة"):
678
+ gr.Markdown("- دعم العملية التعليمية والبحثية.\n- تيسير الوصول إلى المعلومات والمصادر العلمية.\n- تشجيع استخدام التقنيات الحديثة في البحث.\n- تعزيز ثقافة القراءة والتعلم الذاتي.")
679
+ with gr.Tab("🧩 الخدمات"):
680
+ with gr.Tabs():
681
+ with gr.Tab("📘 الإحاطة الجارية"):
682
+ gr.Markdown("خدمة تتيح للباحثين متابعة أحدث الإصدارات والموضوعات الجديدة في مجالات اهتمامهم.")
683
+ with gr.Tab("🔗 التسجيل في بنك المعرفة"):
684
+ gr.Markdown("يرجى ملء البيانات التالية للتسجيل في بنك المعرفة المصري:")
685
+
686
+ name = gr.Textbox(label="الاسم بالكامل", placeholder="اكتب اسمك الثلاثي هنا")
687
+ nid = gr.Textbox(label="رقم البطاقة", placeholder="14 رقمًا")
688
+ birth = gr.Textbox(label="تاريخ الميلاد", placeholder="مثال: 1999-05-12")
689
+ email = gr.Textbox(label="الإيميل الجامعي", placeholder="example@university.edu.eg")
690
+ phone = gr.Textbox(label="رقم التليفون", placeholder="010XXXXXXXXX")
691
+ submit_btn = gr.Button("إرسال الطلب")
692
+ output_msg = gr.HTML()
693
+
694
+ def save_registration(name, nid, birth, email, phone):
695
+ import csv, os
696
+ from datetime import datetime
697
+ file_path = "bank_requests.csv"
698
+ file_exists = os.path.exists(file_path)
699
+ with open(file_path, mode="a", newline="", encoding="utf-8") as f:
700
+ writer = csv.writer(f)
701
+ if not file_exists:
702
+ writer.writerow(["الاسم", "رقم البطاقة", "تاريخ الميلاد", "الإيميل الجامعي", "رقم التليفون", "تاريخ التسجيل"])
703
+ writer.writerow([name, nid, birth, email, phone, datetime.now().strftime("%Y-%m-%d %H:%M:%S")])
704
+ return "<b style='color:green;'>✅ تم استلام بياناتك بنجاح، يرجى مراجعة بريدك الجامعي خلال 24 ساعة.</b>"
705
+
706
+ submit_btn.click(save_registration, inputs=[name, nid, birth, email, phone], outputs=output_msg)
707
+
708
+ with gr.Tab("🖨️ التصوير"):
709
+ gr.Markdown("توفر المكتبة خدمة تصوير المواد العلمية وفق القواعد المعمول بها داخل المكتبة.")
710
+ with gr.Tab("🔍 البحث الإلكتروني"):
711
+ gr.Markdown("يمكن للباحثين استخدام أجهزة المكتبة للبحث في قواعد البيانات الإلكترونية والمصادر العلمية.")
712
+ with gr.Tab("📖 الاطلاع الداخلي"):
713
+ gr.Markdown("تتيح المكتبة للرواد قراءة الكتب والمراجع داخل القاعات المخصصة دون الحاجة إلى استعارتها خارجًا.")
714
+ # ------------------ تبويب الاستعارة الخارجية (معدّل) ------------------
715
+ with gr.Tab("📚 الاستعارة الخارجية"):
716
+ gr.Markdown("""
717
+ تقدّم المكتبة خدمة الاستعارة الخارجية للكتب تبعًا لعدد النسخ، حيث أنه غير مسموح بالاستعارة الخارجية للكتب والمراجع ذات النسخة الواحدة أو ذات الطابع الخاص أو الدوريات أو الرسائل العلمية.
718
+ """)
719
+ with gr.Tabs():
720
+ with gr.Tab("📌 الاستعارة للطلاب"):
721
+ gr.Markdown("""
722
+ 📌 يستخرج الطالب استمارة الاستعارة عن طريق ملء استمارة ضمان يقوم بختمها من شؤون الطلاب،
723
+ مع ختمها بختم النسر الخاص بالجهة الحكومية التابع لها الضامن.
724
+ """)
725
+ gr.Markdown("### 📄 تحميل الاستمارات المطلوبة:")
726
+ # روابط ملفات Google Drive
727
+ student_form_url = "https://drive.google.com/uc?export=download&id=18BBlUYnKu37TEPqup8CeJGPv5UEOy1tY"
728
+ guarantor_form_url = "https://drive.google.com/uc?export=download&id=1th9cJm0xxI16_YfLQ148l94zvkSqJmLD"
729
+ gr.HTML(f"""
730
+ <div style='display:flex; gap:15px; flex-wrap:wrap; margin-top:10px;'>
731
+ <a href='{student_form_url}' target='_blank'>
732
+ <button style='background-color:#4CAF50; color:white; padding:10px 18px; border:none; border-radius:8px; font-size:16px; cursor:pointer;'>
733
+ 📄 تحميل بيانات الطالب
734
+ </button>
735
+ </a>
736
+ <a href='{guarantor_form_url}' target='_blank'>
737
+ <button style='background-color:#2196F3; color:white; padding:10px 18px; border:none; border-radius:8px; font-size:16px; cursor:pointer;'>
738
+ 📄 تحميل بيانات الضامن
739
+ </button>
740
+ </a>
741
+ </div>
742
+ """)
743
+ gr.Markdown("برجاء طباعة الاستمارتين وتوقيعهما قبل التوجه إلى المكتبة")
744
+
745
+ with gr.Tab("📌 الاستعارة لأعضاء هيئة التدريس"):
746
+ gr.Markdown("أعضاء هيئة التدريس يرجى تعبئة البيانات التالية لطلب الاستعارة:")
747
+ fac_name = gr.Textbox(label="الاسم", placeholder="الاسم الكامل")
748
+ fac_phone = gr.Textbox(label="رقم التليفون", placeholder="010XXXXXXXX")
749
+ fac_nid = gr.Textbox(label="رقم البطاقة", placeholder="14 رقمًا")
750
+ fac_email = gr.Textbox(label="الإيميل الجامعي", placeholder="example@university.edu.eg")
751
+ fac_position = gr.Textbox(label="التوصيف الوظيفي", placeholder="مثال: أستاذ مساعد – قسم الصيدلة")
752
+ fac_birth = gr.Textbox(label="تاريخ الميلاد", placeholder="مثال: 1980-05-12")
753
+ fac_submit = gr.Button("إرسال الطلب")
754
+ fac_msg = gr.Markdown("")
755
+
756
+ def submit_faculty_request(name, phone, nid, email, position, birthdate):
757
+ if not name or not str(name).strip():
758
+ return "<b style='color:red;'>الاسم مطلوب.</b>"
759
+ if not phone or not str(phone).strip():
760
+ return "<b style='color:red;'>رقم التليفون مطلوب.</b>"
761
+ if not nid or not str(nid).strip():
762
+ return "<b style='color:red;'>رقم البطاقة مطلوب.</b>"
763
+ if not email or not str(email).strip():
764
+ return "<b style='color:red;'>الإيميل الجامعي مطلوب.</b>"
765
+ # حفظ البيانات
766
+ qid = save_faculty_request(name, phone, nid, email, position, birthdate)
767
+ return f"✅ تم إرسال طلب الاستعارة (#{qid}) وسيتم مراجعته."
768
+
769
+ fac_submit.click(submit_faculty_request, inputs=[fac_name, fac_phone, fac_nid, fac_email, fac_position, fac_birth], outputs=fac_msg)
770
+
771
+ with gr.Tab("🔎 البحث المحلي"):
772
+ query_local = gr.Textbox(label="اكتب كلمة البحث")
773
+ category = gr.Radio(["Books", "Theses"], label="اختر الفئة")
774
+ mode = gr.Radio(["نصي", "دلالي (Semantic)"], label="نوع البحث")
775
+ btn_local = gr.Button("بحث")
776
+
777
+ df_local_state = gr.State()
778
+ output_local_html = gr.HTML()
779
+ file_local = gr.File(label="⬇️ تحميل النتائج", visible=False)
780
+
781
+ btn_local.click(
782
+ local_search_df,
783
+ inputs=[query_local, category, mode],
784
+ outputs=[output_local_html, df_local_state]
785
+ )
786
+
787
+ btn_save_local = gr.Button("📥 حفظ النتائج")
788
+ btn_save_local.click(
789
+ save_to_excel,
790
+ inputs=df_local_state,
791
+ outputs=file_local
792
+ )
793
+
794
+ file_local.change(lambda x: gr.update(visible=True), inputs=file_local, outputs=file_local)
795
+
796
+ with gr.Tab("🌐 المصادر الخارجية"):
797
+ query_ext = gr.Textbox(label="كلمة البحث")
798
+ site_ext = gr.Dropdown(list(EXTERNAL_LINKS.keys()), label="اختر الموقع")
799
+ btn_ext = gr.Button("بحث")
800
+ output_ext = gr.HTML()
801
+ btn_ext.click(external_search_html, inputs=[query_ext, site_ext], outputs=output_ext)
802
+
803
+ with gr.Tab("📄 الدوريات"):
804
+ query_jour = gr.Textbox(label="كلمة البحث")
805
+ site_jour = gr.Dropdown(list(JOURNALS.keys()), label="اختر الموقع")
806
+ btn_jour = gr.Button("بحث")
807
+ output_jour = gr.HTML()
808
+ btn_jour.click(journal_search_html, inputs=[query_jour, site_jour], outputs=output_jour)
809
+
810
+ with gr.Tab("🤖 أدوات الذكاء الاصطناعي"):
811
+ query_ai = gr.Textbox(label="كلمة البحث")
812
+ site_ai = gr.Dropdown(list(AI_TOOLS.keys()), label="اختر الأداة")
813
+ btn_ai = gr.Button("بحث")
814
+ output_ai = gr.HTML()
815
+ btn_ai.click(ai_search_html, inputs=[query_ai, site_ai], outputs=output_ai)
816
+
817
+ with gr.Tab("📑 برامج إدارة المراجع"):
818
+ gr.Markdown("ℹ️ **تنويه:** هذه البرامج تحتاج تنزيل أو تثبيت الإضافات الخاصة بها.")
819
+ gr.Markdown("### • **Mendeley** \n🔗 [زيارة الموقع](https://www.mendeley.com/)")
820
+ gr.Markdown("### • **Zotero** \n🔗 [زيارة الموقع](https://www.zotero.org/)")
821
+ gr.Markdown("### • **EndNote** \n🔗 [زيارة الموقع](https://endnote.com/)")
822
+
823
+ with gr.Tab("💬 المساعد الذكي"):
824
+ q_faq = gr.Textbox(label="اسأل مساعد المكتبة")
825
+ ans_faq = gr.HTML()
826
+ btn_faq = gr.Button("إجابة")
827
+ btn_faq.click(library_assistant_smart, inputs=q_faq, outputs=ans_faq)
828
+
829
+ with gr.Tab("📊 الإحصاءات"):
830
+ stats_html = gr.HTML()
831
+ btn_stats = gr.Button("عرض الإحصاءات")
832
+ btn_stats.click(lambda: show_usage_stats(), outputs=stats_html)
833
+
834
+ # -------------------- تبويب "📞 تواصل معنا" المضاف سابقًا --------------------
835
+ with gr.Tab("📞 تواصل معنا"):
836
+
837
+ gr.Markdown("""
838
+ ## 📞 تواصل معنا
839
+
840
+ يسعدنا تواصلك مع **مكتبة كلية الصيدلة – جامعة المنصورة** عبر القنوات التالية:
841
+
842
+ 📍 **العنوان:** الدور الرابع – المبنى الإداري – كلية الصيدلة – جامعة المنصورة
843
+ 📧 **البريد الإلكتروني:** [phrlib1@mans.edu.eg](mailto:phrlib1@mans.edu.eg)
844
+ """)
845
+
846
+
847
+ fb_link = "https://www.facebook.com/people/%D9%85%D9%83%D8%AA%D8%A8%D8%A9-%D9%83%D9%84%D9%8A%D8%A9-%D8%A7%D9%84%D8%B5%D9%8A%D8%AF%D9%84%D8%A9-%D8%AC%D8%A7%D9%85%D8%B9%D8%A9-%D8%A7%D9%84%D9%85%D9%86%D8%B5%D9%88%D8%B1%D8%A9/61554318849433/"
848
+ youtube_link = "https://www.youtube.com/@%D9%85%D9%83%D8%AA%D8%A8%D8%A9%D9%83%D9%84%D9%8A%D8%A9%D8%A7%D9%84%D8%B5%D9%8A%D8%AF%D9%84%D8%A9%D8%AC%D8%A7%D9%85%D8%B9%D8%A9%D8%A7%D9%84%D9%85%D9%86%D8%B5%D9%88%D8%B1%D8%A9"
849
+ email_link = "https://mail.google.com/mail/?view=cm&fs=1&to=phrlib1@mans.edu.eg"
850
+
851
+
852
+ gr.Markdown("### 🌐 قنوات التواصل السريعة:")
853
+
854
+ gr.HTML(f"""
855
+ <div style='display:flex; gap:10px; flex-wrap:wrap;'>
856
+ <!-- Facebook -->
857
+ <a href='{fb_link}' target='_blank' style='text-decoration:none;'>
858
+ <button style='background-color:#1877f2;color:white;padding:10px 18px;
859
+ border:none;border-radius:8px;font-size:16px;cursor:pointer;display:flex;
860
+ align-items:center;gap:8px;'>
861
+ <svg xmlns='http://www.w3.org/2000/svg' width='20' height='20'
862
+ fill='white' viewBox='0 0 24 24'>
863
+ <path d='M22.675 0h-21.35C.597 0 0 .597 0 1.333v21.334C0 23.403.597 24
864
+ 1.325 24h11.495v-9.294H9.691v-3.622h3.129V8.413c0-3.1 1.894-4.788
865
+ 4.659-4.788 1.325 0 2.464.099 2.797.143v3.243h-1.921c-1.506 0-1.798.716-
866
+ 1.798 1.767v2.317h3.595l-.468 3.622h-3.127V24h6.127C23.403 24 24
867
+ 23.403 24 22.667V1.333C24 .597 23.403 0 22.675 0z'/>
868
+ </svg>
869
+ Facebook
870
+ </button>
871
+ </a>
872
+
873
+ <!-- YouTube -->
874
+ <a href='{youtube_link}' target='_blank' style='text-decoration:none;'>
875
+ <button style='background-color:#FF0000;color:white;padding:10px 18px;
876
+ border:none;border-radius:8px;font-size:16px;cursor:pointer;display:flex;
877
+ align-items:center;gap:8px;'>
878
+ <svg xmlns='http://www.w3.org/2000/svg' width='20' height='20'
879
+ fill='white' viewBox='0 0 24 24'>
880
+ <path d='M23.498 6.186a2.993 2.993 0 0 0-2.107-2.12C19.4 3.5 12
881
+ 3.5 12 3.5s-7.4 0-9.391.566A2.993 2.993 0 0 0 .502 6.186
882
+ 31.04 31.04 0 0 0 0 12a31.04 31.04 0 0 0 .502 5.814
883
+ 2.993 2.993 0 0 0 2.107 2.12C4.6 20.5 12 20.5 12
884
+ 20.5s7.4 0 9.391-.566a2.993 2.993 0 0 0 2.107-2.12A31.04
885
+ 31.04 0 0 0 24 12a31.04 31.04 0 0 0-.502-5.814zM9.75
886
+ 15.568V8.432L15.818 12 9.75 15.568z'/>
887
+ </svg>
888
+ YouTube
889
+ </button>
890
+ </a>
891
+
892
+ <!-- Email -->
893
+ <a href='{email_link}' target='_blank' style='text-decoration:none;'>
894
+ <button style='background-color:#444;color:white;padding:10px 18px;
895
+ border:none;border-radius:8px;font-size:16px;cursor:pointer;display:flex;
896
+ align-items:center;gap:8px;'>
897
+ <svg xmlns='http://www.w3.org/2000/svg' width='20' height='20'
898
+ fill='white' viewBox='0 0 24 24'>
899
+ <path d='M12 13.065L.015 6h23.97L12 13.065zm0 2.248L24 8v13H0V8l12
900
+ 7.313z'/>
901
+ </svg>
902
+ Email
903
+ </button>
904
+ </a>
905
+ </div>
906
+ """)
907
+
908
+
909
+
910
+
911
+
912
+ # -------------------- تبويب "❓ اسأل أخصائي المكتبة" (التبويب الجديد للطلاب) --------------------
913
+ with gr.Tab("❓ اسأل أخصائي المكتبة"):
914
+ gr.Markdown("### اسأل أخصائي المكتبة\nاكتب سؤالك وسيظهر في نظام المكتبة ليرد عليه الأخصائي لاحقًا.")
915
+ student_name = gr.Textbox(label="الاسم (اختياري)", placeholder="يمكن تركه فارغًا")
916
+ student_question = gr.Textbox(label="السؤال", lines=4, placeholder="اكتب سؤالك هنا...", interactive=True)
917
+ student_send = gr.Button("إرسال السؤال")
918
+ student_result = gr.Markdown("")
919
+ student_questions_html = gr.HTML()
920
+
921
+ def load_questions_html():
922
+ df = read_questions_df()
923
+ return questions_to_html(df)
924
+
925
+ def student_submit_question(name, question):
926
+ if not question or not str(question).strip():
927
+ return "⚠️ اكتب سؤالك قبل الإرسال.", questions_to_html(read_questions_df())
928
+ qid = save_question_to_csv(name, question)
929
+ df = read_questions_df()
930
+ return f"✅ تم إرسال سؤالك (#{qid})، سنقوم بالرد في أقرب وقت ممكن.", questions_to_html(df)
931
+
932
+ student_send.click(student_submit_question, inputs=[student_name, student_question], outputs=[student_result, student_questions_html])
933
+ btn_load_questions = gr.Button("تحديث عرض الأسئلة")
934
+ btn_load_questions.click(lambda: load_questions_html(), outputs=student_questions_html)
935
+
936
+ # -------------------- 📂 تبويب إدارة خدمات المكتبة --------------------
937
+ with gr.Tab("📂 إدارة خدمات المكتبة"):
938
+ gr.Markdown("### 🔐 تسجيل الدخول لإدارة خدمات المكتبة")
939
+
940
+ password = gr.Textbox(label="كلمة المرور", type="password", placeholder="أدخل كلمة المرور هنا")
941
+ login_btn = gr.Button("دخول")
942
+ login_msg = gr.Markdown("")
943
+ admin_area = gr.Group(visible=False)
944
+
945
+ with admin_area:
946
+ gr.Markdown("### عرض طلبات التسجيل في بنك المعرفة")
947
+
948
+ refresh_btn = gr.Button("🔄 تحديث البيانات")
949
+ data_table = gr.Dataframe(headers=["الاسم", "رقم البطاقة", "تاريخ الميلاد", "الإيميل الجامعي", "رقم التليفون", "تاريخ التسجيل"], interactive=False)
950
+ download_btn = gr.Button("⬇️ تنزيل الطلبات كملف Excel")
951
+ download_file = gr.File(label="ملف Excel", visible=False)
952
+
953
+ import pandas as pd, os, tempfile
954
+
955
+ def check_password(pw):
956
+ correct_pw = "admin123" # ← يمكنك تغييرها إلى أي كلمة مرور تريدينها
957
+ if pw == correct_pw:
958
+ return gr.update(visible=True), "✅ تم تسجيل الدخول بنجاح."
959
+ else:
960
+ return gr.update(visible=False), "❌ كلمة المرور غير صحيحة."
961
+
962
+ login_btn.click(check_password, inputs=password, outputs=[admin_area, login_msg])
963
+
964
+ def load_requests():
965
+ file_path = "bank_requests.csv"
966
+ if not os.path.exists(file_path):
967
+ return pd.DataFrame(columns=["الاسم", "رقم البطاقة", "تاريخ الميلاد", "الإيميل الجامعي", "رقم التليفون", "تاريخ التسجيل"])
968
+ df = pd.read_csv(file_path)
969
+ return df
970
+
971
+ def export_excel(df):
972
+ if df is None or df.empty:
973
+ return gr.update(visible=False)
974
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
975
+ df.to_excel(tmp.name, index=False)
976
+ return gr.update(value=tmp.name, visible=True)
977
+
978
+ refresh_btn.click(load_requests, outputs=data_table)
979
+ download_btn.click(export_excel, inputs=data_table, outputs=download_file)
980
+
981
+ # -------------------- قسم إدارة الأسئلة داخل منطقة الإدارة --------------------
982
+ with admin_area:
983
+ gr.Markdown("### 🛠️ إدارة الأسئلة")
984
+ admin_refresh_q = gr.Button("🔄 تحديث الأسئلة")
985
+ admin_questions_df = gr.Dataframe(headers=["id","name","question","answer","status","datetime"], interactive=False)
986
+ admin_select_q = gr.Dropdown(choices=[], label="اختر رقم السؤال للرد عليه (ID)", value=None)
987
+ admin_answer_box = gr.Textbox(label="اكتب الرد هنا", lines=3, placeholder="أدخل رد الأخصائي...")
988
+ admin_save_answer_btn = gr.Button("حفظ الرد")
989
+ admin_msg = gr.Markdown("")
990
+ admin_export_btn = gr.Button("⬇️ تنزيل الأسئلة كملف Excel")
991
+ admin_export_file = gr.File(label="ملف الأسئلة", visible=False)
992
+
993
+ def admin_load_questions():
994
+ df = read_questions_df()
995
+ if df is None or df.empty:
996
+ df_show = pd.DataFrame(columns=["id","name","question","answer","status","datetime"])
997
+ else:
998
+ df_show = df.sort_values(by="id", ascending=False)
999
+ choices = df_show["id"].astype(str).tolist() if not df_show.empty else []
1000
+ return df_show, gr.update(choices=choices, value=choices[0] if choices else None)
1001
+
1002
+ def admin_save_answer(qid, answer_text):
1003
+ success, msg = save_answer_to_csv(qid, answer_text)
1004
+ if not success:
1005
+ return "❌ " + msg, admin_load_questions()[0]
1006
+ df_show, dd_update = admin_load_questions()
1007
+ return "✅ تم حفظ الرد.", df_show
1008
+
1009
+ def admin_export_questions():
1010
+ df = read_questions_df()
1011
+ if df is None or df.empty:
1012
+ return gr.update(visible=False)
1013
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
1014
+ df.to_excel(tmp.name, index=False)
1015
+ return gr.update(value=tmp.name, visible=True)
1016
+
1017
+ admin_refresh_q.click(lambda: admin_load_questions()[0], outputs=admin_questions_df)
1018
+ admin_refresh_q.click(lambda: admin_load_questions()[1], outputs=admin_select_q)
1019
+ admin_save_answer_btn.click(admin_save_answer, inputs=[admin_select_q, admin_answer_box], outputs=[admin_msg, admin_questions_df])
1020
+ admin_export_btn.click(admin_export_questions, outputs=admin_export_file)
1021
+
1022
+ # -------------------- قسم إدارة طلبات الاستعارة لأعضاء هيئة التدريس --------------------
1023
+ with admin_area:
1024
+ gr.Markdown("### 🗂️ إدارة طلبات الاستعارة (أعضاء هيئة التدريس)")
1025
+ admin_refresh_fac = gr.Button("🔄 تحديث طلبات الاستعارة")
1026
+ admin_fac_df = gr.Dataframe(headers=["id","name","phone","nid","email","position","birthdate","status","datetime"], interactive=False)
1027
+ admin_export_fac_btn = gr.Button("⬇️ تنزيل طلبات الاستعارة كملف Excel")
1028
+ admin_export_fac_file = gr.File(label="ملف طلبات الاستعارة", visible=False)
1029
+
1030
+ def admin_load_faculty():
1031
+ df = read_faculty_df()
1032
+ if df is None or df.empty:
1033
+ df_show = pd.DataFrame(columns=["id","name","phone","nid","email","position","birthdate","status","datetime"])
1034
+ else:
1035
+ df_show = df.sort_values(by="id", ascending=False)
1036
+ return df_show
1037
+
1038
+ def admin_export_faculty():
1039
+ df = read_faculty_df()
1040
+ if df is None or df.empty:
1041
+ return gr.update(visible=False)
1042
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
1043
+ df.to_excel(tmp.name, index=False)
1044
+ return gr.update(value=tmp.name, visible=True)
1045
+
1046
+ admin_refresh_fac.click(lambda: admin_load_faculty(), outputs=admin_fac_df)
1047
+ admin_export_fac_btn.click(admin_export_faculty, outputs=admin_export_fac_file)
1048
+
1049
+ gr.Markdown("---\n📌 *المشروع أعدته eman anter*")
1050
+
1051
+ # تشغيل التطبيق
1052
+ if __name__ == "__main__":
1053
+ demo.launch(share=True)