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