DrugKnowledge commited on
Commit
19a125a
·
verified ·
1 Parent(s): 808c167

Delete app.py

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