DrugKnowledge commited on
Commit
176832c
·
verified ·
1 Parent(s): 0c56bfc

Delete app.py

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