"""Main chat interface for employees — QDB Knowledge Bot.
Conversation persistence + history (ChatGPT-style):
- Every chat is saved to SQLite (per user) with auto-generated titles
- Sidebar lists past conversations — click to resume
- Each assistant message has 👍/👎 feedback buttons
- Generator receives history → real multi-turn memory
"""
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.rag.generator import answer_question, generate_title
from app.storage import db
from app.ui._styles import citation_block, inject_styles, logo_html
st.set_page_config(
page_title="QDB Knowledge Bot",
page_icon="🏛️",
layout="centered",
initial_sidebar_state="collapsed",
)
inject_styles()
db.init_db()
# ============== Helpers ==============
def _is_arabic(text: str) -> bool:
return any("" <= c <= "ۿ" for c in (text or ""))
def _ensure_conversation(user_email: str) -> str:
"""Get or create the active conversation id."""
if "conversation_id" not in st.session_state or not st.session_state.conversation_id:
st.session_state.conversation_id = db.create_conversation(user_email)
st.session_state.messages = []
return st.session_state.conversation_id
def _load_conversation(conversation_id: str) -> None:
"""Load a past conversation into session state."""
st.session_state.conversation_id = conversation_id
msgs = db.get_messages(conversation_id)
st.session_state.messages = [
{
"id": m.id, "role": m.role, "content": m.content,
"citations": m.citations, "feedback": m.feedback,
}
for m in msgs
]
def _start_new_chat() -> None:
st.session_state.conversation_id = None
st.session_state.messages = []
# ============== UI Blocks ==============
def _render_assistant_message(msg: dict, user_email: str) -> None:
msg_id = msg.get("id")
with st.chat_message("assistant", avatar="🏛️"):
if _is_arabic(msg["content"]):
st.markdown(f'
{msg["content"]}
', unsafe_allow_html=True)
else:
st.markdown(msg["content"])
if msg.get("citations"):
citation_block(msg["citations"])
# Feedback row (only if message has been persisted with id)
if msg_id:
current = msg.get("feedback")
col_up, col_down, col_pad = st.columns([1, 1, 12])
with col_up:
up_label = "👍" if current != 1 else "✅"
if st.button(up_label, key=f"up_{msg_id}", help="إجابة مفيدة"):
db.set_feedback(msg_id, user_email, 1)
msg["feedback"] = 1
st.toast("شكراً على التقييم!", icon="✅")
st.rerun()
with col_down:
down_label = "👎" if current != -1 else "❌"
if st.button(down_label, key=f"down_{msg_id}", help="إجابة غير مفيدة"):
db.set_feedback(msg_id, user_email, -1)
msg["feedback"] = -1
st.toast("سجلنا تقييمك", icon="📝")
st.rerun()
def _render_user_message(content: str) -> None:
with st.chat_message("user", avatar="👤"):
if _is_arabic(content):
st.markdown(f'{content}
', unsafe_allow_html=True)
else:
st.markdown(content)
def _render_top_bar(user) -> None:
initial = (user.name or user.email)[0].upper()
role_label = "🛡️ مشرف" if user.is_admin else "موظف"
st.markdown(
f"""{logo_html(size_px=40, with_bg=False)}
مساعد المعرفة
مؤسسة بنك تنمية المهارات
{initial}{user.name.split()[0] if user.name else user.email.split('@')[0]}{role_label}
""",
unsafe_allow_html=True,
)
def _render_sidebar(user) -> None:
with st.sidebar:
st.markdown(
f"""""",
unsafe_allow_html=True,
)
if st.button("➕ محادثة جديدة", use_container_width=True, type="primary"):
_start_new_chat()
st.rerun()
st.markdown(
'📜 المحادثات السابقة
',
unsafe_allow_html=True,
)
conversations = db.list_conversations(user.email, limit=30)
if not conversations:
st.caption("ما فيش محادثات سابقة لسه")
else:
current_id = st.session_state.get("conversation_id")
for conv in conversations:
col_btn, col_del = st.columns([6, 1])
is_active = conv.id == current_id
label = ("📌 " if is_active else "💬 ") + (conv.title[:30] + ("…" if len(conv.title) > 30 else ""))
with col_btn:
if st.button(label, key=f"conv_{conv.id}", use_container_width=True):
_load_conversation(conv.id)
st.rerun()
with col_del:
if st.button("🗑", key=f"del_{conv.id}", help="حذف"):
db.delete_conversation(conv.id)
if current_id == conv.id:
_start_new_chat()
st.rerun()
# Spacer + footer actions
st.markdown('', unsafe_allow_html=True)
if user.is_admin:
st.caption("🛡️ Admin: استخدم الصفحات في الأعلى")
if st.button("🚪 تسجيل الخروج", use_container_width=True):
logout()
def _render_welcome() -> None:
st.markdown(
f"""{logo_html(size_px=80, with_bg=False)}
كيف يمكنني مساعدتك اليوم؟
أول مؤسسة اعتماد مصرية في مجال التعليم الفني والتدريب المهني
""",
unsafe_allow_html=True,
)
suggestions = [
("📋", "إنشاء التقييم", "ما هي إجراءات إنشاء التقييم بالتفصيل؟"),
("🎓", "المؤهلات المعتمدة", "ما هي المؤهلات المتاحة في QDB؟"),
("👨🏫", "تدريب المدربين (TOT)", "كيف يعمل برنامج تدريب المدربين؟"),
("🏢", "اعتماد المراكز", "ما هي عملية اعتماد مراكز التدريب؟"),
]
cols = st.columns(2)
for i, (icon, title, q) in enumerate(suggestions):
with cols[i % 2]:
if st.button(
f"{icon} **{title}**\n\n{q}",
key=f"sug_{i}",
use_container_width=True,
):
st.session_state.pending_question = q
st.rerun()
# ============== Main ==============
def main() -> None:
user = require_login()
_render_sidebar(user)
_render_top_bar(user)
if "messages" not in st.session_state:
st.session_state.messages = []
if "conversation_id" not in st.session_state:
st.session_state.conversation_id = None
# Welcome OR existing messages
if not st.session_state.messages:
_render_welcome()
else:
for msg in st.session_state.messages:
if msg["role"] == "user":
_render_user_message(msg["content"])
else:
_render_assistant_message(msg, user.email)
# New input
pending = st.session_state.pop("pending_question", None)
prompt = pending or st.chat_input("✍️ اسأل سؤالاً...")
if not prompt:
return
# Persist + show user turn
conv_id = _ensure_conversation(user.email)
user_msg_id = db.add_message(conv_id, "user", prompt)
user_msg = {"id": user_msg_id, "role": "user", "content": prompt}
st.session_state.messages.append(user_msg)
_render_user_message(prompt)
# Build history for the generator (everything except the just-added user turn)
prior_history = [
{"role": m["role"], "content": m["content"]}
for m in st.session_state.messages[:-1]
]
# Generate + persist + show assistant turn
with st.chat_message("assistant", avatar="🏛️"):
with st.spinner("..."):
try:
ans = answer_question(prompt, history=prior_history)
if _is_arabic(ans.text):
st.markdown(f'{ans.text}
', unsafe_allow_html=True)
else:
st.markdown(ans.text)
citation_block(ans.citations)
asst_msg_id = db.add_message(conv_id, "assistant", ans.text, ans.citations)
st.session_state.messages.append({
"id": asst_msg_id,
"role": "assistant",
"content": ans.text,
"citations": ans.citations,
"feedback": None,
})
# Auto-title on first user message
if len([m for m in st.session_state.messages if m["role"] == "user"]) == 1:
try:
title = generate_title(prompt)
db.update_conversation_title(conv_id, title)
except Exception:
pass
# Rerun so the feedback buttons appear under the new message
st.rerun()
except Exception as e:
err = f"⚠️ حدث خطأ: {e}"
st.error(err)
db.add_message(conv_id, "assistant", err)
if __name__ == "__main__":
main()