DrugKnowledge commited on
Commit
8466f84
·
verified ·
1 Parent(s): 681102d

Upload app.py

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