DrugKnowledge commited on
Commit
7a1d5fe
·
verified ·
1 Parent(s): 16876ec

Upload app.py

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