DrugKnowledge commited on
Commit
37f2681
·
verified ·
1 Parent(s): e68e001

Delete app.py

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