from dotenv import load_dotenv
import streamlit as st
from core.ai_service import stream_response
from core.file_service import extract_text
from core.vector_store import load_from_disk, retrieve_with_scores, is_loaded
from core.pii_guard import redact_pii
load_dotenv()
st.set_page_config(
page_title="Mudrik",
page_icon="๐ต",
layout="wide",
initial_sidebar_state="collapsed",
)
st.markdown("""
""", unsafe_allow_html=True)
# โโ Load vector index once per session โโโโโโโโโโโโโโโโโโโโโโโโ
if "rag_ready" not in st.session_state:
st.session_state.rag_ready = load_from_disk()
# โโ Session state โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
if "messages" not in st.session_state:
st.session_state.messages = []
if "file_text" not in st.session_state:
st.session_state.file_text = ""
if "file_name" not in st.session_state:
st.session_state.file_name = ""
# โโ Logo + title โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
col1, col2, col3 = st.columns([1, 1, 1])
with col2:
st.image("assets/logo.png", use_container_width=True)
st.markdown("""
""", unsafe_allow_html=True)
# โโ Helper functions โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def show_sources(scored_chunks: list[tuple[str, float]], file_text: str, msg_id: str):
parts = []
if scored_chunks:
parts.append(f"{len(scored_chunks)} ู
ูุงุฏ ู
ู ูุธุงู
ุงูุนู
ู")
if file_text:
parts.append("ู
ูู ุงูุนูุฏ")
if not parts:
return
with st.popover(f"ุงูู
ุตุงุฏุฑ โ {' ยท '.join(parts)}"):
if file_text:
st.markdown("**ู
ูู ุงูุนูุฏ ุงูู
ุฑููุน**")
preview = file_text[:2000] + ("โฆ" if len(file_text) > 2000 else "")
st.text_area("", value=preview, height=180, disabled=True, key=f"file_{msg_id}", label_visibility="collapsed")
if scored_chunks:
st.divider()
for i, (chunk, score) in enumerate(scored_chunks, 1):
pct = int(score * 100)
color = "#1A9AA8" if pct >= 70 else "#F39C12" if pct >= 50 else "#999"
st.markdown(
f"**ุงูู
ุงุฏุฉ {i}** "
f'ุชุทุงุจู {pct}%',
unsafe_allow_html=True,
)
st.text_area("", value=chunk, height=130, disabled=True, key=f"chunk_{msg_id}_{i}", label_visibility="collapsed")
if i < len(scored_chunks):
st.divider()
def send(prompt: str):
clean_prompt, pii_count = redact_pii(prompt)
st.session_state.messages.append({"role": "user", "content": clean_prompt})
with st.chat_message("user"):
st.markdown(clean_prompt)
if pii_count:
st.caption(f"ุชู
ุฅุฎูุงุก {pii_count} ุจูุงูุงุช ุญุณุงุณุฉ ุชููุงุฆูุงู")
scored_chunks = retrieve_with_scores(clean_prompt, k=5) if is_loaded() else []
file_text = st.session_state.file_text
context_parts = []
if file_text:
context_parts.append(f"=== ู
ูู ุงููุถูุฉ ===\n{file_text}")
if scored_chunks:
law_text = "\n\n---\n\n".join(chunk for chunk, _ in scored_chunks)
context_parts.append(f"=== ู
ูุงุฏ ูุธุงู
ุงูุนู
ู ุฐุงุช ุงูุตูุฉ ===\n{law_text}")
context = "\n\n".join(context_parts)
with st.chat_message("assistant", avatar="โจ"):
response = st.write_stream(stream_response(prompt, context=context))
show_sources(scored_chunks, file_text, msg_id=f"live_{len(st.session_state.messages)}")
st.session_state.messages.append({
"role": "assistant",
"content": response,
"scored_chunks": scored_chunks,
"file_text": file_text,
})
# โโ Chat โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
for idx, msg in enumerate(st.session_state.messages):
with st.chat_message(msg["role"], avatar="โจ" if msg["role"] == "assistant" else None):
st.markdown(msg["content"])
if msg["role"] == "assistant":
show_sources(msg.get("scored_chunks", []), msg.get("file_text", ""), msg_id=f"hist_{idx}")
prompt = st.chat_input(
"ุงุณุฃููู ุนู ูุถุนู ูู ุงูุนูุฏโฆ",
accept_file=True,
file_type=["txt", "pdf"],
)
if prompt and prompt.files:
uploaded_file = prompt.files[0]
with st.spinner("ุฌุงุฑู ูุฑุงุกุฉ ุงูู
ููโฆ"):
raw_text = extract_text(uploaded_file)
redacted_text, pii_count = redact_pii(raw_text)
st.session_state.file_text = redacted_text
st.session_state.file_name = uploaded_file.name
if not prompt.text:
notice = f"ุชู
ุฅุฑูุงู ุงูู
ูู: {st.session_state.file_name}"
if pii_count:
notice += f"\n\nุชู
ุฅุฎูุงุก {pii_count} ุจูุงูุงุช ุญุณุงุณุฉ (ูููุฉ / IBAN) ุชููุงุฆูุงู"
st.session_state.messages.append({"role": "user", "content": notice})
with st.chat_message("user"):
st.markdown(notice)
if prompt and prompt.text:
send(prompt.text)