DrugKnowledge commited on
Commit
bfe9a47
·
verified ·
1 Parent(s): 396aa0a

Upload app.py

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