DrugKnowledge commited on
Commit
394886f
·
verified ·
1 Parent(s): 045f6a9

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -1137
app.py DELETED
@@ -1,1137 +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
- .styled-table {
327
- border-collapse: collapse;
328
- margin: 15px 0;
329
- font-size: 14px;
330
- width: 100%;
331
- text-align: right;
332
- direction: rtl;
333
- }
334
- .styled-table th, .styled-table td {
335
- border: 1px solid #ddd;
336
- padding: 8px;
337
- }
338
- .styled-table tr:nth-child(even) {background-color: #f9f9f9;}
339
- .styled-table tr:nth-child(odd) {background-color: #ffffff;}
340
- .styled-table th {background-color: #4da6ff; color: white;}
341
- a {color: #0066cc; text-decoration: none;}
342
- a:hover {text-decoration: underline;}
343
- .question-card {
344
- border: 1px solid #ddd;
345
- padding: 10px;
346
- margin-bottom: 12px;
347
- border-radius: 8px;
348
- background: #fff;
349
- direction: rtl;
350
- }
351
- .question-meta { font-size: 13px; color: #666; margin-bottom:6px; }
352
- .answer { margin-top:8px; padding:8px; border-radius:6px; background:#f7f7f7; }
353
- .anon { color:#999; font-style:italic; }
354
- </style>"""
355
-
356
- # ================== تتبع الاستخدام ==================
357
- def log_usage(tab, query="", mode="", results_count=0):
358
- file_path = "usage_stats.xlsx"
359
- entry = pd.DataFrame([{
360
- "التاريخ": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
361
- "التب": tab,
362
- "الكلمة المفتاحية": query,
363
- "نوع البحث": mode,
364
- "عدد النتائج": results_count
365
- }])
366
- if os.path.exists(file_path):
367
- try:
368
- old = pd.read_excel(file_path)
369
- entry = pd.concat([old, entry], ignore_index=True)
370
- except Exception:
371
- entry = entry
372
- entry.to_excel(file_path, index=False)
373
- # upload to HF dataset (auto backup)
374
- try:
375
- upload_data_file(file_path)
376
- except Exception as e:
377
- print("⚠️ خطأ أثناء رفع usage_stats:", e)
378
-
379
- # ================== عرض إحصاءات الاستخدام ==================
380
- def show_usage_stats():
381
- file_path = "usage_stats.xlsx"
382
- if not os.path.exists(file_path):
383
- return "<p>📊 لا توجد بيانات بعد</p>"
384
- df = pd.read_excel(file_path)
385
- total = len(df)
386
- by_tab = df["التب"].value_counts()
387
- fig, ax = plt.subplots()
388
- labels = [get_display(arabic_reshaper.reshape(str(t))) for t in by_tab.index]
389
- ax.bar(labels, by_tab.values)
390
- for i, v in enumerate(by_tab.values):
391
- ax.text(i, v + 0.1, str(v), ha='center', va='bottom', fontsize=10)
392
- ax.set_title(get_display(arabic_reshaper.reshape("عدد مرات استخدام كل تب")))
393
- ax.set_xlabel(get_display(arabic_reshaper.reshape("التب")))
394
- ax.set_ylabel(get_display(arabic_reshaper.reshape("عدد العمليات")))
395
- plt.xticks(rotation=30, ha='right')
396
- buf = io.BytesIO()
397
- plt.tight_layout()
398
- plt.savefig(buf, format="png")
399
- plt.close(fig)
400
- buf.seek(0)
401
- img = base64.b64encode(buf.read()).decode("utf-8")
402
- summary = f"<h3>📈 إجمالي الاستخدام: {total} عملية</h3>"
403
- html = summary + "<img src='data:image/png;base64," + img + "'/>"
404
- return CUSTOM_CSS + html + df.to_html(escape=False, index=False, classes="styled-table")
405
-
406
- # ================== تحويل نتائج إلى HTML أنيق ==================
407
- def results_to_html(df):
408
- if df.empty:
409
- return "<p>❌ لا توجد نتائج</p>"
410
- html = CUSTOM_CSS + "<div style='direction:rtl;text-align:right;'>"
411
- for i, row in df.iterrows():
412
- html += "<table class='styled-table' style='margin-bottom:15px;'>"
413
- html += f"<caption style='caption-side:top;text-align:right;font-weight:bold;margin-bottom:5px;'>📘 النتيجة {i+1}</caption>"
414
- for col, val in row.items():
415
- html += f"<tr><th>{col}</th><td>{val}</td></tr>"
416
- html += "</table>"
417
- html += "</div>"
418
- return html
419
-
420
- def df_to_html(df):
421
- if isinstance(df, str):
422
- return df
423
- if df.empty:
424
- return "<p>❌ لا توجد نتائج</p>"
425
- return CUSTOM_CSS + df.to_html(escape=False, index=False, classes="styled-table")
426
-
427
- # ================== حفظ النتائج إلى ملف Excel ==================
428
- def save_to_excel(df):
429
- if df is None or (isinstance(df, pd.DataFrame) and df.empty):
430
- tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
431
- pd.DataFrame().to_excel(tmp.name, index=False)
432
- return tmp.name
433
- tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
434
- if isinstance(df, pd.DataFrame):
435
- df.to_excel(tmp.name, index=False)
436
- else:
437
- pd.DataFrame({"result_html":[str(df)]}).to_excel(tmp.name, index=False)
438
- return tmp.name
439
-
440
- # ================== البحث المحلي ==================
441
- def local_search_df(query, category, mode):
442
- if not query or not str(query).strip():
443
- return "<p>⚠️ اكتب كلمة أو جملة للبحث</p>", pd.DataFrame()
444
-
445
- if mode == "نصي":
446
- if category == "Books":
447
- if "العنوان" in books_df.columns:
448
- df = books_df[books_df["العنوان"].astype(str).str.contains(query, case=False, na=False)]
449
- else:
450
- df = books_df[books_df["Title"].astype(str).str.contains(query, case=False, na=False)]
451
- else:
452
- if "العنوان" in theses_df.columns:
453
- df = theses_df[theses_df["العنوان"].astype(str).str.contains(query, case=False, na=False)]
454
- else:
455
- df = theses_df[theses_df["Title"].astype(str).str.contains(query, case=False, na=False)]
456
- else:
457
- q_emb = model.encode([query], convert_to_numpy=True)
458
- if category == "Books":
459
- scores = util.cos_sim(q_emb, books_embeddings)[0].cpu().numpy()
460
- idx = np.argsort(-scores)
461
- df = books_df.iloc[idx]
462
- else:
463
- scores = util.cos_sim(q_emb, theses_embeddings)[0].cpu().numpy()
464
- idx = np.argsort(-scores)
465
- df = theses_df.iloc[idx]
466
-
467
- if df is None or df.empty:
468
- df = pd.DataFrame([{"نتيجة":"❌ لم يتم العثور على نتائج"}])
469
- else:
470
- if "Title" in df.columns:
471
- df = df.drop(columns=["Title"])
472
-
473
- log_usage("البحث المحلي", query, mode, len(df) if isinstance(df, pd.DataFrame) else 0)
474
- html_results = results_to_html(df)
475
- return html_results, df
476
-
477
- # ================== البحث في PubMed ==================
478
- def search_pubmed_html(query, max_results=5):
479
- if not query or not str(query).strip():
480
- return "<p>⚠️ اكتب كلمة للبحث</p>"
481
- try:
482
- handle = Entrez.esearch(db="pubmed", term=query, retmax=max_results)
483
- record = Entrez.read(handle)
484
- handle.close()
485
- ids = record.get("IdList", [])
486
- if not ids:
487
- return "<p>❌ لا توجد نتائج</p>"
488
-
489
- handle = Entrez.efetch(db="pubmed", id=",".join(ids), rettype="xml", retmode="xml")
490
- records = Entrez.read(handle)
491
- handle.close()
492
-
493
- rows = []
494
- for rec in records.get('PubmedArticle', []):
495
- try:
496
- title = rec['MedlineCitation']['Article']['ArticleTitle']
497
- pmid = rec['MedlineCitation']['PMID']
498
- link = f"https://pubmed.ncbi.nlm.nih.gov/{pmid}/"
499
- rows.append({
500
- "الموقع": "PubMed",
501
- "الوصف": "قاعدة بيانات PubMed",
502
- "العنوان": title,
503
- "الرابط": f"<a href='{link}' target='_blank'>فتح</a>"
504
- })
505
- except Exception:
506
- continue
507
-
508
- if not rows:
509
- return "<p>❌ لم يتم العثور على نتائج صالحة.</p>"
510
-
511
- df = pd.DataFrame(rows)
512
- log_usage("المصادر الخارجية", query, "PubMed", len(df))
513
- return CUSTOM_CSS + df.to_html(escape=False, index=False, classes="styled-table")
514
-
515
- except Exception as e:
516
- return f"<p>❌ حدث خطأ أثناء جلب البيانات من PubMed:<br>{str(e)}</p>"
517
-
518
- # ================== البحث في المواقع الخارجية ==================
519
- EXTERNAL_LINKS = {
520
- "Google Scholar": {"url": "https://scholar.google.com/scholar?q=", "desc": "محرك بحث للأبحاث"},
521
- "PubMed": {"url": "https://pubmed.ncbi.nlm.nih.gov/?term=", "desc": "قاعدة بيانات PubMed"},
522
- "Europe PMC": {"url": "https://europepmc.org/search?query=", "desc": "أبحاث Europe PMC"},
523
- "ClinicalTrials.gov": {"url": "https://clinicaltrials.gov/search?term=", "desc": "تجارب سريرية"},
524
- "OpenFDA": {"url": "https://open.fda.gov/", "desc": "بيانات الأدوية FDA"},
525
- "MedlinePlus": {"url": "https://medlineplus.gov/search/?query=", "desc": "معلومات طبية"},
526
- "DrugBank": {"url": "https://go.drugbank.com/", "desc": "قاعدة بيانات الأدوية"},
527
- "WHO GHO": {"url": "https://www.who.int/data/gho/", "desc": "بيانات الصحة العالمية"},
528
- "ICD-11": {"url": "https://icd.who.int/browse11/l-m/en", "desc": "التصنيف الدولي للأمراض"},
529
- "ClinicalKey": {"url": "https://www.clinicalkey.com/search?q=", "desc": "مصادر طبية شاملة"},
530
- "Scimago": {"url": "https://www.scimagojr.com/journalsearch.php?q=", "desc": "تصنيف الدوريات"},
531
- "EKB": {"url": "https://www.ekb.eg/", "desc": "بنك المعرفة المصري"}
532
- }
533
-
534
- def external_search_html(query, site):
535
- try:
536
- if not query or not str(query).strip():
537
- return "<p>⚠️ من فضلك اكتب كلمة للبحث</p>"
538
-
539
- if not site or site not in EXTERNAL_LINKS:
540
- return f"<p>⚠️ الموقع المحدد غير معروف أو غير موجود في القائمة.</p>"
541
-
542
- if site == "PubMed":
543
- return search_pubmed_html(query)
544
-
545
- base = EXTERNAL_LINKS[site]["url"]
546
- desc = EXTERNAL_LINKS[site]["desc"]
547
- if "?" in base or "=" in base:
548
- link = f"{base}{query}"
549
- else:
550
- link = base
551
- df = pd.DataFrame([
552
- {"اسم الموقع": site, "الوصف": desc, "رابط البحث": f"<a href='{link}' target='_blank'>للوصول إلى نتيجة البحث</a>"}
553
- ])
554
- log_usage("المصادر الخارجية", query, site, 1)
555
- html_table = df.to_html(escape=False, index=False, classes="styled-table")
556
- return CUSTOM_CSS + f"<h3>🔗 نتائج البحث في {site}</h3>" + html_table
557
-
558
- except Exception as e:
559
- return f"<p>❌ حدث خطأ أثناء تنفيذ البحث:<br>{str(e)}</p>"
560
-
561
- # ================== البحث في الدوريات ==================
562
- JOURNALS = {
563
- "Elsevier Journal Finder": {"url": "https://journalfinder.elsevier.com/", "desc": "اقتراح مجلات ا��نشر"},
564
- "Springer Journal Suggester": {"url": "https://journalsuggester.springer.com/", "desc": "اقتراح مجلات النشر"},
565
- "DOAJ": {"url": "https://doaj.org/search/journals?ref=homepage-box&source=", "desc": "مجلات مفتوحة الوصول"},
566
- "Journal Citation Reports": {"url": "https://jcr.clarivate.com/jcr/browse-journals?query=", "desc": "تقييم الدوريات العلمية"},
567
- "Scimago": {"url": "https://www.scimagojr.com/journalsearch.php?q=", "desc": "تصنيف الدوريات"},
568
- "Google Scholar": {"url": "https://scholar.google.com/scholar?q=", "desc": "بحث عام"}
569
- }
570
-
571
- def journal_search_html(query, site):
572
- try:
573
- if not query or not str(query).strip():
574
- return "<p>⚠️ من فضلك اكتب كلمة للبحث</p>"
575
- if not site or site not in JOURNALS:
576
- return f"<p>⚠️ الموقع المحدد غير معروف أو غير موجود في قائمة الدوريات.</p>"
577
- base = JOURNALS[site]["url"]
578
- desc = JOURNALS[site]["desc"]
579
- if "?" in base or "=" in base:
580
- link = f"{base}{query}"
581
- else:
582
- link = base
583
- df = pd.DataFrame([{"اسم الموقع": site, "الوصف": desc, "رابط البحث": f"<a href='{link}' target='_blank'>للوصول إلى نتيجة البحث</a>"}])
584
- log_usage("الدوريات", query, site, 1)
585
- html_table = df.to_html(escape=False, index=False, classes="styled-table")
586
- return CUSTOM_CSS + f"<h3>📄 نتائج البحث في {site}</h3>" + html_table
587
- except Exception as e:
588
- return f"<p>❌ حدث خطأ أثناء تنفيذ البحث:<br>{str(e)}</p>"
589
-
590
- # ================== أدوات الذكاء الاصطناعي ==================
591
- AI_TOOLS = {
592
- "Semantic Scholar": {"url": "https://www.semanticscholar.org/search?q=", "desc": "بحث أكاديمي يعتمد على الذكاء الاصطناعي"},
593
- "Connected Papers": {"url": "https://www.connectedpapers.com/search?q=", "desc": "خرائط علاقات بين الأبحاث"},
594
- "Research Rabbit": {"url": "https://www.researchrabbitapp.com/", "desc": "تتبع شبكات الأبحاث"},
595
- "Elicit": {"url": "https://elicit.org/", "desc": "مساعد بحث علمي يستخدم AI"},
596
- "Explainpaper": {"url": "https://www.explainpaper.com/", "desc": "تبسيط الأبحاث العلمية"},
597
- "Consensus": {"url": "https://consensus.app/search/?q=", "desc": "إجابات سريعة مدعومة بالأدلة"}
598
- }
599
-
600
- def ai_search_html(query, site):
601
- try:
602
- if not query or not str(query).strip():
603
- return "<p>⚠️ من فضلك اكتب كلمة للبحث</p>"
604
- if not site or site not in AI_TOOLS:
605
- return f"<p>⚠️ الأداة المحددة غير معروفة أو غير موجودة في القائمة.</p>"
606
- base = AI_TOOLS[site]["url"]
607
- desc = AI_TOOLS[site]["desc"]
608
- if "?" in base or "=" in base:
609
- link = f"{base}{query}"
610
- else:
611
- link = base
612
- df = pd.DataFrame([{"اسم الأداة": site, "الوصف": desc, "رابط البحث": f"<a href='{link}' target='_blank'>للوصول إلى نتيجة البحث</a>"}])
613
- log_usage("أدوات الذكاء الاصطناعي", query, site, 1)
614
- html_table = df.to_html(escape=False, index=False, classes="styled-table")
615
- return CUSTOM_CSS + f"<h3>🤖 نتائج البحث في {site}</h3>" + html_table
616
- except Exception as e:
617
- return f"<p>❌ حدث خطأ أثناء تنفيذ البحث:<br>{str(e)}</p>"
618
-
619
- # ================== وظائف إدارة الأسئلة (CSV) ==================
620
- def ensure_questions_file():
621
- if not os.path.exists(QUESTIONS_FILE):
622
- df = pd.DataFrame(columns=["id","name","question","answer","status","datetime"])
623
- df.to_csv(QUESTIONS_FILE, index=False, encoding="utf-8-sig")
624
-
625
- def read_questions_df():
626
- ensure_questions_file()
627
- try:
628
- df = pd.read_csv(QUESTIONS_FILE, encoding="utf-8-sig")
629
- except Exception:
630
- df = pd.DataFrame(columns=["id","name","question","answer","status","datetime"])
631
- return df
632
-
633
- def save_question_to_csv(name, question):
634
- ensure_questions_file()
635
- df = read_questions_df()
636
- if df.empty:
637
- next_id = 1
638
- else:
639
- try:
640
- next_id = int(df["id"].max()) + 1
641
- except Exception:
642
- next_id = len(df) + 1
643
- row = {
644
- "id": next_id,
645
- "name": name if name and str(name).strip() else "👤 طالب مجهول",
646
- "question": question,
647
- "answer": "",
648
- "status": "لم يتم الرد",
649
- "datetime": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
650
- }
651
- df = pd.concat([df, pd.DataFrame([row])], ignore_index=True)
652
- df.to_csv(QUESTIONS_FILE, index=False, encoding="utf-8-sig")
653
- # رفع تلقائي للملف بعد الحفظ
654
- try:
655
- upload_data_file(QUESTIONS_FILE)
656
- except Exception as e:
657
- print("⚠️ خطأ أثناء رفع questions.csv:", e)
658
- return next_id
659
-
660
- def save_answer_to_csv(qid, answer_text):
661
- ensure_questions_file()
662
- df = read_questions_df()
663
- if df.empty:
664
- return False, "لا توجد أسئلة."
665
- try:
666
- qid = int(qid)
667
- except Exception:
668
- return False, "معرّف السؤال غير صالح."
669
- if qid not in df["id"].values:
670
- return False, "لم يتم إيجاد السؤال بالمعرّف المحدد."
671
- df.loc[df["id"] == qid, "answer"] = answer_text
672
- df.loc[df["id"] == qid, "status"] = "تم الرد"
673
- df.to_csv(QUESTIONS_FILE, index=False, encoding="utf-8-sig")
674
- # رفع تلقائي بعد الحفظ
675
- try:
676
- upload_data_file(QUESTIONS_FILE)
677
- except Exception as e:
678
- print("⚠️ خطأ أثناء رفع questions.csv بعد الرد:", e)
679
- return True, "تم حفظ الرد بنجاح."
680
-
681
- def questions_to_html(df):
682
- if df is None or df.empty:
683
- return "<p>❌ لا توجد أسئلة حتى الآن.</p>"
684
- html = CUSTOM_CSS + "<div style='direction:rtl;text-align:right;'>"
685
- df_sorted = df.sort_values(by="id", ascending=False).reset_index(drop=True)
686
- for _, row in df_sorted.iterrows():
687
- name = row.get("name","👤 طالب مجهول")
688
- qtext = row.get("question","")
689
- answer = row.get("answer","")
690
- status = row.get("status","لم يتم الرد")
691
- qid = row.get("id","")
692
- dt = row.get("datetime","")
693
- html += f"<div class='question-card'><div class='question-meta'># {qid} — {dt} — <b>{name}</b></div>"
694
- html += f"<div><b>السؤال:</b> {qtext}</div>"
695
- if status == "تم الرد" and str(answer).strip():
696
- html += f"<div class='answer'><b>الرد:</b> {answer} <div class='question-meta'>حالة: {status}</div></div>"
697
- else:
698
- html += f"<div class='answer'><i>لم يتم الرد بعد</i> <div class='question-meta'>حالة: {status}</div></div>"
699
- html += "</div>"
700
- html += "</div>"
701
- return html
702
-
703
- # ================== وظائف إدارة طلبات الاستعارة (أعضاء هيئة التدريس) ==================
704
- def ensure_faculty_file():
705
- if not os.path.exists(FACULTY_BORROW_FILE):
706
- df = pd.DataFrame(columns=["id","name","phone","nid","email","position","birthdate","status","datetime"])
707
- df.to_csv(FACULTY_BORROW_FILE, index=False, encoding="utf-8-sig")
708
-
709
- def read_faculty_df():
710
- ensure_faculty_file()
711
- try:
712
- df = pd.read_csv(FACULTY_BORROW_FILE, encoding="utf-8-sig")
713
- except Exception:
714
- df = pd.DataFrame(columns=["id","name","phone","nid","email","position","birthdate","status","datetime"])
715
- return df
716
-
717
- def save_faculty_request(name, phone, nid, email, position, birthdate):
718
- ensure_faculty_file()
719
- df = read_faculty_df()
720
- if df.empty:
721
- next_id = 1
722
- else:
723
- try:
724
- next_id = int(df["id"].max()) + 1
725
- except Exception:
726
- next_id = len(df) + 1
727
- row = {
728
- "id": next_id,
729
- "name": name,
730
- "phone": phone,
731
- "nid": nid,
732
- "email": email,
733
- "position": position,
734
- "birthdate": birthdate,
735
- "status": "قيد المراجعة",
736
- "datetime": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
737
- }
738
- df = pd.concat([df, pd.DataFrame([row])], ignore_index=True)
739
- df.to_csv(FACULTY_BORROW_FILE, index=False, encoding="utf-8-sig")
740
- # رفع تلقائي بعد الحفظ
741
- try:
742
- upload_data_file(FACULTY_BORROW_FILE)
743
- except Exception as e:
744
- print("⚠️ خطأ أثناء رفع faculty_borrow.csv:", e)
745
- return next_id
746
-
747
- # ================== واجهة Gradio ==================
748
- with gr.Blocks() as demo:
749
- with gr.Tab("📚 عن المكتبة"):
750
- with gr.Tabs():
751
- with gr.Tab("🌟 رؤية المكتبة"):
752
- gr.Markdown("تسعى المكتبة إلى أن تكون مركزًا معرفيًا متميزًا يدعم البحث والتعليم ويُسهم في بناء مجتمع المعرفة.")
753
- with gr.Tab("🎯 رسالة المكتبة"):
754
- gr.Markdown("تقديم خدمات معلوماتية متكاملة تُمكّن الباحثين والطلاب من الوصول إلى مصادر المعرفة بسهولة وكفاءة.")
755
- with gr.Tab("🎯 أهداف المكتبة"):
756
- gr.Markdown("- دعم العملية التعليمية والبحثية.\n- تيسير الوصول إلى المعلومات والمصادر العلمية.\n- تشجيع استخدام التقنيات الحديثة في البحث.\n- تعزيز ثقافة القراءة والتعلم الذاتي.")
757
- with gr.Tab("🧩 الخدمات"):
758
- with gr.Tabs():
759
- with gr.Tab("📘 الإحاطة الجارية"):
760
- gr.Markdown("خدمة تتيح للباحثين متابعة أحدث الإصدارات والموضوعات الجديدة في مجالات اهتمامهم.")
761
- with gr.Tab("🔗 التسجيل في بنك المعرفة"):
762
- gr.Markdown("يرجى ملء البيانات التالية للتسجيل في بنك المعرفة المصري:")
763
-
764
- name = gr.Textbox(label="الاسم بالكامل", placeholder="اكتب اسمك الثلاثي هنا")
765
- nid = gr.Textbox(label="رقم البطاقة", placeholder="14 رقمًا")
766
- birth = gr.Textbox(label="تاريخ الميلاد", placeholder="مثال: 1999-05-12")
767
- email = gr.Textbox(label="الإيميل الجامعي", placeholder="example@university.edu.eg")
768
- phone = gr.Textbox(label="رقم التليفون", placeholder="010XXXXXXXXX")
769
- submit_btn = gr.Button("إرسال الطلب")
770
- output_msg = gr.HTML()
771
-
772
- def save_registration(name, nid, birth, email, phone):
773
- import csv, os
774
- from datetime import datetime
775
- file_path = "bank_requests.csv"
776
- file_exists = os.path.exists(file_path)
777
- with open(file_path, mode="a", newline="", encoding="utf-8") as f:
778
- writer = csv.writer(f)
779
- if not file_exists:
780
- writer.writerow(["الاسم", "رقم البطاقة", "تاريخ الميلاد", "الإيميل الجامعي", "رقم التليفون", "تاريخ التسجيل"])
781
- writer.writerow([name, nid, birth, email, phone, datetime.now().strftime("%Y-%m-%d %H:%M:%S")])
782
- # رفع تلقائي للملف
783
- try:
784
- upload_data_file(file_path)
785
- except Exception as e:
786
- print("⚠️ خطأ أثناء رفع bank_requests.csv:", e)
787
- return "<b style='color:green;'>✅ تم استلام بياناتك بنجاح، يرجى مراجعة بريدك الجامعي خلال 24 ساعة.</b>"
788
-
789
- submit_btn.click(save_registration, inputs=[name, nid, birth, email, phone], outputs=output_msg)
790
-
791
- with gr.Tab("🖨️ التصوير"):
792
- gr.Markdown("توفر المكتبة خدمة تصوير المواد العلمية وفق القواعد المعمول بها داخل المكتبة.")
793
- with gr.Tab("🔍 البحث الإلكتروني"):
794
- gr.Markdown("يمكن للباحثين استخدام أجهزة المكتبة للبحث في قواعد البيانات الإلكترونية والمصادر العلمية.")
795
- with gr.Tab("📖 الاطلاع الداخلي"):
796
- gr.Markdown("تتيح المكتبة للرواد قراءة الكتب والمراجع داخل القاعات المخصصة دون الحاجة إلى استعارتها خارجًا.")
797
- # ------------------ تبويب الاستعارة الخارجية (معدّل) ------------------
798
- with gr.Tab("📚 الاستعارة الخارجية"):
799
- gr.Markdown("""
800
- تقدّم المكتبة خدمة الاستعارة الخارجية للكتب تبعًا لعدد النسخ، حيث أنه غير مسموح بالاستعارة الخارجية للكتب والمراجع ذات النسخة الواحدة أو ذات الطابع الخاص أو الدوريات أو الرسائل العلمية.
801
- """)
802
- with gr.Tabs():
803
- with gr.Tab("📌 الاستعارة للطلاب"):
804
- gr.Markdown("""
805
- 📌 يستخرج الطالب استمارة الاستعارة عن طريق ملء استمارة ضمان يقوم بختمها من شؤون الطلاب،
806
- مع ختمها بختم النسر الخاص بالجهة الحكومية التابع لها الضامن.
807
- """)
808
- gr.Markdown("### 📄 تحميل الاستمارات المطلوبة:")
809
- # روابط ملفات Google Drive
810
- student_form_url = "https://drive.google.com/uc?export=download&id=18BBlUYnKu37TEPqup8CeJGPv5UEOy1tY"
811
- guarantor_form_url = "https://drive.google.com/uc?export=download&id=1th9cJm0xxI16_YfLQ148l94zvkSqJmLD"
812
- gr.HTML(f"""
813
- <div style='display:flex; gap:15px; flex-wrap:wrap; margin-top:10px;'>
814
- <a href='{student_form_url}' target='_blank'>
815
- <button style='background-color:#4CAF50; color:white; padding:10px 18px; border:none; border-radius:8px; font-size:16px; cursor:pointer;'>
816
- 📄 تحميل بيانات الطالب
817
- </button>
818
- </a>
819
- <a href='{guarantor_form_url}' target='_blank'>
820
- <button style='background-color:#2196F3; color:white; padding:10px 18px; border:none; border-radius:8px; font-size:16px; cursor:pointer;'>
821
- 📄 تحميل بيانات الضامن
822
- </button>
823
- </a>
824
- </div>
825
- """)
826
- gr.Markdown("برجاء طباعة الاستمارتين وتوقيعهما قبل التوجه إلى المكتبة")
827
-
828
- with gr.Tab("📌 الاستعارة لأعضاء هيئة التدريس"):
829
- gr.Markdown("أعضاء هيئة التدريس يرجى تعبئة البيانات التالية لطلب الاستعارة:")
830
- fac_name = gr.Textbox(label="الاسم", placeholder="الاسم الكامل")
831
- fac_phone = gr.Textbox(label="رقم التليفون", placeholder="010XXXXXXXX")
832
- fac_nid = gr.Textbox(label="رقم البطاقة", placeholder="14 رقمًا")
833
- fac_email = gr.Textbox(label="الإيميل الجامعي", placeholder="example@university.edu.eg")
834
- fac_position = gr.Textbox(label="التوصيف الوظيفي", placeholder="مثال: أستاذ مساعد – قسم الصيدلة")
835
- fac_birth = gr.Textbox(label="تاريخ الميلاد", placeholder="مثال: 1980-05-12")
836
- fac_submit = gr.Button("إرسال الطلب")
837
- fac_msg = gr.Markdown("")
838
-
839
- def submit_faculty_request(name, phone, nid, email, position, birthdate):
840
- if not name or not str(name).strip():
841
- return "<b style='color:red;'>الاسم مطلوب.</b>"
842
- if not phone or not str(phone).strip():
843
- return "<b style='color:red;'>رقم التليفون مطلوب.</b>"
844
- if not nid or not str(nid).strip():
845
- return "<b style='color:red;'>رقم البطاقة مطلوب.</b>"
846
- if not email or not str(email).strip():
847
- return "<b style='color:red;'>الإيميل الجامعي مطلوب.</b>"
848
- # حفظ البيانات
849
- qid = save_faculty_request(name, phone, nid, email, position, birthdate)
850
- return f"✅ تم إرسال طلب الاستعارة (#{qid}) وسيتم مراجعته."
851
-
852
- fac_submit.click(submit_faculty_request, inputs=[fac_name, fac_phone, fac_nid, fac_email, fac_position, fac_birth], outputs=fac_msg)
853
-
854
- with gr.Tab("🔎 البحث المحلي"):
855
- query_local = gr.Textbox(label="اكتب كلمة البحث")
856
- category = gr.Radio(["Books", "Theses"], label="اختر الفئة")
857
- mode = gr.Radio(["نصي", "دلالي (Semantic)"], label="نوع البحث")
858
- btn_local = gr.Button("بحث")
859
-
860
- df_local_state = gr.State()
861
- output_local_html = gr.HTML()
862
- file_local = gr.File(label="⬇️ تحميل النتائج", visible=False)
863
-
864
- btn_local.click(
865
- local_search_df,
866
- inputs=[query_local, category, mode],
867
- outputs=[output_local_html, df_local_state]
868
- )
869
-
870
- btn_save_local = gr.Button("📥 حفظ النتائج")
871
- btn_save_local.click(
872
- save_to_excel,
873
- inputs=df_local_state,
874
- outputs=file_local
875
- )
876
-
877
- file_local.change(lambda x: gr.update(visible=True), inputs=file_local, outputs=file_local)
878
-
879
- with gr.Tab("🌐 المصادر الخارجية"):
880
- query_ext = gr.Textbox(label="كلمة البحث")
881
- site_ext = gr.Dropdown(list(EXTERNAL_LINKS.keys()), label="اختر الموقع")
882
- btn_ext = gr.Button("بحث")
883
- output_ext = gr.HTML()
884
- btn_ext.click(external_search_html, inputs=[query_ext, site_ext], outputs=output_ext)
885
-
886
- with gr.Tab("📄 الدوريات"):
887
- query_jour = gr.Textbox(label="كلمة البحث")
888
- site_jour = gr.Dropdown(list(JOURNALS.keys()), label="اختر الموقع")
889
- btn_jour = gr.Button("بحث")
890
- output_jour = gr.HTML()
891
- btn_jour.click(journal_search_html, inputs=[query_jour, site_jour], outputs=output_jour)
892
-
893
- with gr.Tab("🤖 أدوات الذكاء الاصطناعي"):
894
- query_ai = gr.Textbox(label="كلمة البحث")
895
- site_ai = gr.Dropdown(list(AI_TOOLS.keys()), label="اختر الأداة")
896
- btn_ai = gr.Button("بحث")
897
- output_ai = gr.HTML()
898
- btn_ai.click(ai_search_html, inputs=[query_ai, site_ai], outputs=output_ai)
899
-
900
- with gr.Tab("📑 برامج إدارة المراجع"):
901
- gr.Markdown("ℹ️ **تنويه:** هذه البرامج تحتاج تنزيل أو تثبيت الإضافات الخاصة بها.")
902
- gr.Markdown("### • **Mendeley** \n🔗 [زيارة الموقع](https://www.mendeley.com/)")
903
- gr.Markdown("### • **Zotero** \n🔗 [زيارة الموقع](https://www.zotero.org/)")
904
- gr.Markdown("### • **EndNote** \n🔗 [زيارة الموقع](https://endnote.com/)")
905
-
906
- with gr.Tab("💬 المساعد الذكي"):
907
- q_faq = gr.Textbox(label="اسأل مساعد المكتبة")
908
- ans_faq = gr.HTML()
909
- btn_faq = gr.Button("إجابة")
910
- btn_faq.click(library_assistant_smart, inputs=q_faq, outputs=ans_faq)
911
-
912
- with gr.Tab("📊 الإحصاءات"):
913
- stats_html = gr.HTML()
914
- btn_stats = gr.Button("عرض الإحصاءات")
915
- btn_stats.click(lambda: show_usage_stats(), outputs=stats_html)
916
-
917
- # -------------------- تبويب "📞 تواصل معنا" المضاف سابقًا --------------------
918
- with gr.Tab("📞 تواصل معنا"):
919
-
920
- gr.Markdown("""
921
- ## 📞 تواصل معنا
922
-
923
- يسعدنا تواصلك مع **مكتبة كلية الصيدلة – جامعة المنصورة** عبر القنوات التالية:
924
-
925
- 📍 **العنوان:** الدور الرابع – المبنى الإداري – كلية الصيدلة – جامعة المنصورة
926
- 📧 **البريد الإلكتروني:** [phrlib1@mans.edu.eg](mailto:phrlib1@mans.edu.eg)
927
- """)
928
-
929
-
930
- 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/"
931
- 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"
932
- email_link = "https://mail.google.com/mail/?view=cm&fs=1&to=phrlib1@mans.edu.eg"
933
-
934
-
935
- gr.Markdown("### 🌐 قنوات التواصل السريعة:")
936
-
937
- gr.HTML(f"""
938
- <div style='display:flex; gap:10px; flex-wrap:wrap;'>
939
- <!-- Facebook -->
940
- <a href='{fb_link}' target='_blank' style='text-decoration:none;'>
941
- <button style='background-color:#1877f2;color:white;padding:10px 18px;
942
- border:none;border-radius:8px;font-size:16px;cursor:pointer;display:flex;
943
- align-items:center;gap:8px;'>
944
- <svg xmlns='http://www.w3.org/2000/svg' width='20' height='20'
945
- fill='white' viewBox='0 0 24 24'>
946
- <path d='M22.675 0h-21.35C.597 0 0 .597 0 1.333v21.334C0 23.403.597 24
947
- 1.325 24h11.495v-9.294H9.691v-3.622h3.129V8.413c0-3.1 1.894-4.788
948
- 4.659-4.788 1.325 0 2.464.099 2.797.143v3.243h-1.921c-1.506 0-1.798.716-
949
- 1.798 1.767v2.317h3.595l-.468 3.622h-3.127V24h6.127C23.403 24 24
950
- 23.403 24 22.667V1.333C24 .597 23.403 0 22.675 0z'/>
951
- </svg>
952
- Facebook
953
- </button>
954
- </a>
955
-
956
- <!-- YouTube -->
957
- <a href='{youtube_link}' target='_blank' style='text-decoration:none;'>
958
- <button style='background-color:#FF0000;color:white;padding:10px 18px;
959
- border:none;border-radius:8px;font-size:16px;cursor:pointer;display:flex;
960
- align-items:center;gap:8px;'>
961
- <svg xmlns='http://www.w3.org/2000/svg' width='20' height='20'
962
- fill='white' viewBox='0 0 24 24'>
963
- <path d='M23.498 6.186a2.993 2.993 0 0 0-2.107-2.12C19.4 3.5 12
964
- 3.5 12 3.5s-7.4 0-9.391.566A2.993 2.993 0 0 0 .502 6.186
965
- 31.04 31.04 0 0 0 0 12a31.04 31.04 0 0 0 .502 5.814
966
- 2.993 2.993 0 0 0 2.107 2.12C4.6 20.5 12 20.5 12
967
- 20.5s7.4 0 9.391-.566a2.993 2.993 0 0 0 2.107-2.12A31.04
968
- 31.04 0 0 0 24 12a31.04 31.04 0 0 0-.502-5.814zM9.75
969
- 15.568V8.432L15.818 12 9.75 15.568z'/>
970
- </svg>
971
- YouTube
972
- </button>
973
- </a>
974
-
975
- <!-- Email -->
976
- <a href='{email_link}' target='_blank' style='text-decoration:none;'>
977
- <button style='background-color:#444;color:white;padding:10px 18px;
978
- border:none;border-radius:8px;font-size:16px;cursor:pointer;display:flex;
979
- align-items:center;gap:8px;'>
980
- <svg xmlns='http://www.w3.org/2000/svg' width='20' height='20'
981
- fill='white' viewBox='0 0 24 24'>
982
- <path d='M12 13.065L.015 6h23.97L12 13.065zm0 2.248L24 8v13H0V8l12
983
- 7.313z'/>
984
- </svg>
985
- Email
986
- </button>
987
- </a>
988
- </div>
989
- """)
990
-
991
-
992
-
993
-
994
-
995
- # -------------------- تبويب "❓ اسأل أخصائي المكتبة" (التبويب الجديد للطلاب) --------------------
996
- with gr.Tab("❓ اسأل أخصائي المكتبة"):
997
- gr.Markdown("### اسأل أخصائي المكتبة\nاكتب سؤالك وسيظهر في نظام المكتبة ليرد عليه الأخصائي لاحقًا.")
998
- student_name = gr.Textbox(label="الاسم (اختياري)", placeholder="يمكن تركه فارغًا")
999
- student_question = gr.Textbox(label="السؤال", lines=4, placeholder="اكتب سؤالك هنا...", interactive=True)
1000
- student_send = gr.Button("إرسال السؤال")
1001
- student_result = gr.Markdown("")
1002
- student_questions_html = gr.HTML()
1003
-
1004
- def load_questions_html():
1005
- df = read_questions_df()
1006
- return questions_to_html(df)
1007
-
1008
- def student_submit_question(name, question):
1009
- if not question or not str(question).strip():
1010
- return "⚠️ اكتب سؤالك قبل الإرسال.", questions_to_html(read_questions_df())
1011
- qid = save_question_to_csv(name, question)
1012
- df = read_questions_df()
1013
- return f"✅ تم إرسال سؤالك (#{qid})، سنقوم بالرد في أقرب وقت ممكن.", questions_to_html(df)
1014
-
1015
- student_send.click(student_submit_question, inputs=[student_name, student_question], outputs=[student_result, student_questions_html])
1016
- btn_load_questions = gr.Button("تحديث عرض الأسئلة")
1017
- btn_load_questions.click(lambda: load_questions_html(), outputs=student_questions_html)
1018
-
1019
- # -------------------- 📂 تبويب إدارة خدمات المكتبة --------------------
1020
- with gr.Tab("📂 إدارة خدمات المكتبة"):
1021
- gr.Markdown("### 🔐 تسجيل الدخول لإدارة خدمات المكتبة")
1022
-
1023
- password = gr.Textbox(label="كلمة المرور", type="password", placeholder="أدخل كلمة المرور هنا")
1024
- login_btn = gr.Button("دخول")
1025
- login_msg = gr.Markdown("")
1026
- admin_area = gr.Group(visible=False)
1027
-
1028
- with admin_area:
1029
- gr.Markdown("### عرض طلبات التسجيل في بنك المعرفة")
1030
-
1031
- refresh_btn = gr.Button("🔄 تحديث البيانات")
1032
- data_table = gr.Dataframe(headers=["الاسم", "رقم البطاقة", "تاريخ الميلاد", "الإيميل الجامعي", "رقم التليفون", "تاريخ التسجيل"], interactive=False)
1033
- download_btn = gr.Button("⬇️ تنزيل الطلبات كملف Excel")
1034
- download_file = gr.File(label="ملف Excel", visible=False)
1035
-
1036
- import pandas as pd, os, tempfile
1037
-
1038
- def check_password(pw):
1039
- # اقرأ كلمة مرور الأدمن من Secret (ADMIN_PASS) — لو مش موجود يستخدم 'pharmacy1' كقيمة افتراضية قصيرة الأمد
1040
- correct_pw = os.getenv("ADMIN_PASS", "pharmacy1")
1041
- if pw == correct_pw:
1042
- return gr.update(visible=True), "✅ تم تسجيل الدخول بنجاح."
1043
- else:
1044
- return gr.update(visible=False), "❌ كلمة المرور غير صحيحة."
1045
-
1046
- login_btn.click(check_password, inputs=password, outputs=[admin_area, login_msg])
1047
-
1048
- def load_requests():
1049
- file_path = "bank_requests.csv"
1050
- if not os.path.exists(file_path):
1051
- return pd.DataFrame(columns=["الاسم", "رقم البطاقة", "تاريخ الميلاد", "الإيميل الجامعي", "رقم التليفون", "تاريخ التسجيل"])
1052
- df = pd.read_csv(file_path)
1053
- return df
1054
-
1055
- def export_excel(df):
1056
- if df is None or df.empty:
1057
- return gr.update(visible=False)
1058
- tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
1059
- df.to_excel(tmp.name, index=False)
1060
- return gr.update(value=tmp.name, visible=True)
1061
-
1062
- refresh_btn.click(load_requests, outputs=data_table)
1063
- download_btn.click(export_excel, inputs=data_table, outputs=download_file)
1064
-
1065
- # -------------------- قسم إدارة الأسئلة داخل منطقة الإدارة --------------------
1066
- with admin_area:
1067
- gr.Markdown("### 🛠️ إدارة الأسئلة")
1068
- admin_refresh_q = gr.Button("🔄 تحديث الأسئلة")
1069
- admin_questions_df = gr.Dataframe(headers=["id","name","question","answer","status","datetime"], interactive=False)
1070
- admin_select_q = gr.Dropdown(choices=[], label="اختر رقم السؤال للرد عليه (ID)", value=None)
1071
- admin_answer_box = gr.Textbox(label="اكتب الرد هنا", lines=3, placeholder="أدخل رد الأخصائي...")
1072
- admin_save_answer_btn = gr.Button("حفظ الرد")
1073
- admin_msg = gr.Markdown("")
1074
- admin_export_btn = gr.Button("⬇️ تنزيل الأسئلة كملف Excel")
1075
- admin_export_file = gr.File(label="ملف الأسئلة", visible=False)
1076
-
1077
- def admin_load_questions():
1078
- df = read_questions_df()
1079
- if df is None or df.empty:
1080
- df_show = pd.DataFrame(columns=["id","name","question","answer","status","datetime"])
1081
- else:
1082
- df_show = df.sort_values(by="id", ascending=False)
1083
- choices = df_show["id"].astype(str).tolist() if not df_show.empty else []
1084
- return df_show, gr.update(choices=choices, value=choices[0] if choices else None)
1085
-
1086
- def admin_save_answer(qid, answer_text):
1087
- success, msg = save_answer_to_csv(qid, answer_text)
1088
- if not success:
1089
- return "❌ " + msg, admin_load_questions()[0]
1090
- df_show, dd_update = admin_load_questions()
1091
- return "✅ تم حفظ الرد.", df_show
1092
-
1093
- def admin_export_questions():
1094
- df = read_questions_df()
1095
- if df is None or df.empty:
1096
- return gr.update(visible=False)
1097
- tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
1098
- df.to_excel(tmp.name, index=False)
1099
- return gr.update(value=tmp.name, visible=True)
1100
-
1101
- admin_refresh_q.click(lambda: admin_load_questions()[0], outputs=admin_questions_df)
1102
- admin_refresh_q.click(lambda: admin_load_questions()[1], outputs=admin_select_q)
1103
- admin_save_answer_btn.click(admin_save_answer, inputs=[admin_select_q, admin_answer_box], outputs=[admin_msg, admin_questions_df])
1104
- admin_export_btn.click(admin_export_questions, outputs=admin_export_file)
1105
-
1106
- # -------------------- قسم إدارة طلبات الاستعارة لأعضاء هيئة التدريس --------------------
1107
- with admin_area:
1108
- gr.Markdown("### 🗂️ إدارة طلبات الاستعارة (أعضاء هيئة التدريس)")
1109
- admin_refresh_fac = gr.Button("🔄 تحديث طلبات الاستعارة")
1110
- admin_fac_df = gr.Dataframe(headers=["id","name","phone","nid","email","position","birthdate","status","datetime"], interactive=False)
1111
- admin_export_fac_btn = gr.Button("⬇️ تنزيل طلبات الاستعارة كملف Excel")
1112
- admin_export_fac_file = gr.File(label="ملف طلبات الاستعارة", visible=False)
1113
-
1114
- def admin_load_faculty():
1115
- df = read_faculty_df()
1116
- if df is None or df.empty:
1117
- df_show = pd.DataFrame(columns=["id","name","phone","nid","email","position","birthdate","status","datetime"])
1118
- else:
1119
- df_show = df.sort_values(by="id", ascending=False)
1120
- return df_show
1121
-
1122
- def admin_export_faculty():
1123
- df = read_faculty_df()
1124
- if df is None or df.empty:
1125
- return gr.update(visible=False)
1126
- tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
1127
- df.to_excel(tmp.name, index=False)
1128
- return gr.update(value=tmp.name, visible=True)
1129
-
1130
- admin_refresh_fac.click(lambda: admin_load_faculty(), outputs=admin_fac_df)
1131
- admin_export_fac_btn.click(admin_export_faculty, outputs=admin_export_fac_file)
1132
-
1133
- gr.Markdown("---\n📌 *المشروع أعدته eman anter*")
1134
-
1135
- # تشغيل التطبيق
1136
- if __name__ == "__main__":
1137
- demo.launch(share=True)