"""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(
'
'
'📤 رفع ملف جديد للمعرفة
',
unsafe_allow_html=True,
)
col1, col2 = st.columns([1, 2])
with col1:
category = st.selectbox("التصنيف", CATEGORIES, label_visibility="visible")
with col2:
st.markdown(
''
'💡 اختار تصنيف مناسب عشان البوت يفلتر النتائج بشكل أدق
',
unsafe_allow_html=True,
)
uploaded = st.file_uploader(
"اختر ملفات Word أو PDF (تقدر ترفع أكتر من ملف)",
type=["docx", "pdf"],
accept_multiple_files=True,
)
if uploaded:
st.markdown(
f''
f'📋 جاهز للرفع: {len(uploaded)} ملف
',
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(
''
'📋 الملفات المفهرسة
',
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"""
{icon}
{s['source_file']}
{s['chunks']} مقطع مفهرس
""",
unsafe_allow_html=True,
)
with col2:
st.markdown('', unsafe_allow_html=True)
st.caption(f"{s['chunks']} chunks")
with col3:
st.markdown('', 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('', 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(
''
'🔄 إعادة الفهرسة الكاملة
',
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''
f'⚠️ تحذير: هيعيد فهرسة كل الملفات ({len(files_in_dir)} ملف) '
f'من البداية. ده ممكن ياخد وقت.
',
unsafe_allow_html=True,
)
if files_in_dir:
for f in files_in_dir:
st.markdown(
f''
f'{_file_icon(f.name)} {f.name} '
f'{_human_size(f.stat().st_size)}'
f'
',
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()