DrugKnowledge commited on
Commit
0502c99
·
verified ·
1 Parent(s): 110d136

Upload app.py

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