File size: 8,326 Bytes
1fa7d18
 
02c0be9
 
1fa7d18
 
 
 
02c0be9
 
1fa7d18
02c0be9
 
 
1fa7d18
 
 
 
 
 
 
 
 
02c0be9
 
1fa7d18
 
02c0be9
 
1fa7d18
 
 
 
 
 
 
 
 
02c0be9
 
1fa7d18
 
 
 
 
 
02c0be9
 
1fa7d18
 
 
 
 
 
02c0be9
1fa7d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02c0be9
 
1fa7d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02c0be9
 
 
1fa7d18
02c0be9
1fa7d18
 
02c0be9
1fa7d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02c0be9
1fa7d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02c0be9
 
 
 
 
 
1fa7d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02c0be9
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
"""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()