Spaces:
Sleeping
Sleeping
Download app/ui/admin.py from QDB95/qdb-knowledge-bot: direct link, hf CLI and curl.
- Browser
- Download file 8.33 kB
-
https://huggingface.co/spaces/QDB95/qdb-knowledge-bot/resolve/main/app/ui/admin.py
- Command line
-
hf download hf://spaces/QDB95/qdb-knowledge-bot/app/ui/admin.py
-
curl -L -o admin.py https://huggingface.co/spaces/QDB95/qdb-knowledge-bot/resolve/main/app/ui/admin.py
8.33 kB
| """Admin panel for managing the knowledge base.""" | |
| import sys | |
| from pathlib import Path | |
| _PROJECT_ROOT = Path(__file__).resolve().parents[2] | |
| if str(_PROJECT_ROOT) not in sys.path: | |
| sys.path.insert(0, str(_PROJECT_ROOT)) | |
| import streamlit as st | |
| from app.core.auth import logout, require_login | |
| from app.core.config import settings | |
| from app.ingestion.pipeline import ingest_directory, ingest_file | |
| from app.rag.retriever import delete_source, list_sources | |
| from app.ui._styles import ( | |
| brand_header, | |
| divider, | |
| empty_state, | |
| inject_styles, | |
| page_header, | |
| stat_card, | |
| user_badge, | |
| ) | |
| st.set_page_config(page_title="QDB Admin", page_icon="⚙️", layout="centered") | |
| inject_styles() | |
| CATEGORIES = [ | |
| "📋 عام", | |
| "👥 موارد بشرية", | |
| "💰 مالية", | |
| "💻 تقني", | |
| "📐 تعليمات تشغيل", | |
| "📜 سياسات", | |
| "📊 تقارير", | |
| ] | |
| def _file_icon(name: str) -> str: | |
| if name.lower().endswith(".pdf"): | |
| return "📕" | |
| if name.lower().endswith(".docx"): | |
| return "📘" | |
| return "📄" | |
| def _human_size(b: int) -> str: | |
| if b < 1024: | |
| return f"{b} B" | |
| if b < 1024**2: | |
| return f"{b/1024:.1f} KB" | |
| return f"{b/1024**2:.1f} MB" | |
| def _render_sidebar(user) -> None: | |
| with st.sidebar: | |
| brand_header() | |
| user_badge(user.name, user.email, user.is_admin) | |
| if st.button("🚪 تسجيل الخروج", use_container_width=True): | |
| logout() | |
| divider() | |
| sources = list_sources() | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| stat_card("ملفات", len(sources), "📚") | |
| with col2: | |
| stat_card("مقاطع", sum(s["chunks"] for s in sources), "🧩") | |
| def _tab_upload() -> None: | |
| st.markdown( | |
| '<div style="font-size:18px; font-weight:600; margin-bottom:1rem;">' | |
| '📤 رفع ملف جديد للمعرفة</div>', | |
| unsafe_allow_html=True, | |
| ) | |
| col1, col2 = st.columns([1, 2]) | |
| with col1: | |
| category = st.selectbox("التصنيف", CATEGORIES, label_visibility="visible") | |
| with col2: | |
| st.markdown( | |
| '<div style="background:#FFF8E7; border:1px solid #E5C97D; padding:8px 12px; ' | |
| 'border-radius:8px; font-size:12px; color:#6B5817; margin-top:28px;">' | |
| '💡 اختار تصنيف مناسب عشان البوت يفلتر النتائج بشكل أدق</div>', | |
| unsafe_allow_html=True, | |
| ) | |
| uploaded = st.file_uploader( | |
| "اختر ملفات Word أو PDF (تقدر ترفع أكتر من ملف)", | |
| type=["docx", "pdf"], | |
| accept_multiple_files=True, | |
| ) | |
| if uploaded: | |
| st.markdown( | |
| f'<div style="margin-top:8px; font-size:13px; color:#6B7280;">' | |
| f'📋 جاهز للرفع: <b style="color:#8B1538;">{len(uploaded)} ملف</b></div>', | |
| unsafe_allow_html=True, | |
| ) | |
| if st.button("🚀 رفع وفهرسة الكل", type="primary", use_container_width=True): | |
| settings.documents_dir.mkdir(parents=True, exist_ok=True) | |
| cat_clean = category.split(" ", 1)[1] if " " in category else category | |
| for file in uploaded: | |
| target = settings.documents_dir / file.name | |
| target.write_bytes(file.getbuffer()) | |
| with st.spinner(f"⏳ جاري فهرسة **{file.name}**..."): | |
| try: | |
| n = ingest_file(target, category=cat_clean) | |
| st.success(f"✅ **{file.name}**: تم فهرسة {n} مقطع") | |
| except Exception as e: | |
| st.error(f"❌ **{file.name}**: {e}") | |
| def _tab_manage() -> None: | |
| st.markdown( | |
| '<div style="font-size:18px; font-weight:600; margin-bottom:1rem;">' | |
| '📋 الملفات المفهرسة</div>', | |
| unsafe_allow_html=True, | |
| ) | |
| sources = list_sources() | |
| if not sources: | |
| empty_state( | |
| "📂", | |
| "لا توجد ملفات مفهرسة", | |
| "ارفع ملفاتك من تبويب 'رفع ملفات' لتبدأ", | |
| ) | |
| return | |
| for s in sources: | |
| col1, col2, col3, col4 = st.columns([6, 1.2, 1, 1]) | |
| with col1: | |
| icon = _file_icon(s["source_file"]) | |
| st.markdown( | |
| f""" | |
| <div class="qdb-source-card"> | |
| <div class="qdb-source-icon">{icon}</div> | |
| <div style="flex:1; min-width:0;"> | |
| <div class="qdb-source-name">{s['source_file']}</div> | |
| <div class="qdb-source-meta">{s['chunks']} مقطع مفهرس</div> | |
| </div> | |
| </div> | |
| """, | |
| unsafe_allow_html=True, | |
| ) | |
| with col2: | |
| st.markdown('<div style="margin-top:14px;"></div>', unsafe_allow_html=True) | |
| st.caption(f"{s['chunks']} chunks") | |
| with col3: | |
| st.markdown('<div style="margin-top:10px;"></div>', unsafe_allow_html=True) | |
| if st.button("🔄", key=f"r_{s['source_file']}", help="إعادة فهرسة"): | |
| path = settings.documents_dir / s["source_file"] | |
| if path.exists(): | |
| with st.spinner(f"إعادة فهرسة {s['source_file']}..."): | |
| ingest_file(path) | |
| st.rerun() | |
| else: | |
| st.error("الملف غير موجود في المجلد") | |
| with col4: | |
| st.markdown('<div style="margin-top:10px;"></div>', unsafe_allow_html=True) | |
| if st.button("🗑️", key=f"d_{s['source_file']}", help="حذف"): | |
| delete_source(s["source_file"]) | |
| path = settings.documents_dir / s["source_file"] | |
| if path.exists(): | |
| path.unlink() | |
| st.rerun() | |
| def _tab_reindex() -> None: | |
| st.markdown( | |
| '<div style="font-size:18px; font-weight:600; margin-bottom:1rem;">' | |
| '🔄 إعادة الفهرسة الكاملة</div>', | |
| unsafe_allow_html=True, | |
| ) | |
| settings.documents_dir.mkdir(parents=True, exist_ok=True) | |
| files_in_dir = [ | |
| p for p in settings.documents_dir.iterdir() if p.suffix.lower() in {".docx", ".pdf"} | |
| ] | |
| st.markdown( | |
| f'<div style="background:#FEF3C7; border-left:3px solid #F59E0B; ' | |
| f'padding:12px 16px; border-radius:8px; margin-bottom:1rem;">' | |
| f'<b>⚠️ تحذير:</b> هيعيد فهرسة كل الملفات (<b>{len(files_in_dir)}</b> ملف) ' | |
| f'من البداية. ده ممكن ياخد وقت.</div>', | |
| unsafe_allow_html=True, | |
| ) | |
| if files_in_dir: | |
| for f in files_in_dir: | |
| st.markdown( | |
| f'<div style="padding:6px 12px; background:#F5F5F7; border-radius:6px; ' | |
| f'margin-bottom:4px; font-size:13px;">' | |
| f'{_file_icon(f.name)} {f.name} ' | |
| f'<span style="color:#6B7280; float:left;">{_human_size(f.stat().st_size)}</span>' | |
| f'</div>', | |
| unsafe_allow_html=True, | |
| ) | |
| if st.button("🚀 ابدأ إعادة الفهرسة", type="primary", use_container_width=True): | |
| with st.spinner("جاري إعادة فهرسة كل الملفات..."): | |
| results = ingest_directory() | |
| for fname, count in results.items(): | |
| if count > 0: | |
| st.success(f"✅ {fname}: {count} مقطع") | |
| else: | |
| st.error(f"❌ {fname}: فشل") | |
| else: | |
| empty_state("📁", "لا توجد ملفات في المجلد", "ارفع ملفات من تبويب 'رفع ملفات' أولاً") | |
| def main() -> None: | |
| user = require_login(require_admin=True) | |
| _render_sidebar(user) | |
| page_header( | |
| "⚙️ لوحة الإدارة", | |
| f"إدارة قاعدة المعرفة — مسجل دخولك كـ {user.email}" | |
| ) | |
| tab1, tab2, tab3 = st.tabs(["📤 رفع ملفات", "📋 إدارة الملفات", "🔄 إعادة الفهرسة"]) | |
| with tab1: | |
| _tab_upload() | |
| with tab2: | |
| _tab_manage() | |
| with tab3: | |
| _tab_reindex() | |
| if __name__ == "__main__": | |
| main() | |