DrugKnowledge commited on
Commit
fc8573b
·
verified ·
1 Parent(s): e51c42d

Delete app.py

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