Spaces:
Runtime error
Runtime error
File size: 8,756 Bytes
197a96c | 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 | 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("""
<style>
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+Arabic:wght@400;500;600;700&display=swap');
html, body, [class*="css"] { font-family: 'IBM Plex Sans Arabic', sans-serif; }
#MainMenu, footer, header { visibility: hidden; }
[data-testid="stSidebar"] { display: none; }
.block-container { padding-top: 2rem; padding-bottom: 7rem; max-width: 760px; }
[data-testid="stAppViewContainer"], body, html { background: #FAFEFE; direction: rtl; }
/* โโ Scrollbar styling only โ don't touch overflow/flex โโ */
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: #D0F0F3; border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: #B2E8EC; }
/* โโ Header โโ */
.top-header { text-align: center; padding: 0 0 1.4rem; }
.top-header h1 { font-size: 2.4rem; font-weight: 700; color: #1A9AA8; margin: 0 0 0.2rem; }
.top-header p { font-size: 1rem; color: #8FC9CE; margin: 0; }
[data-testid="stHeaderActionElements"] { display: none !important; }
/* โโ File tag โโ */
.file-tag {
background: #E6F9FA;
border: 1px solid #B2E8EC;
border-radius: 8px;
padding: 0.3rem 0.8rem;
font-size: 0.8rem;
color: #1A9AA8;
display: inline-block;
}
/* โโ Chat messages โโ */
[data-testid="stChatMessage"] { gap: 0.7rem; }
[data-testid="stChatMessage"]:has([data-testid="stChatMessageAvatarUser"]) {
background: #E6F9FA;
border-radius: 1.1rem;
padding: 0.75rem 1.15rem;
max-width: 75%;
margin-left: auto;
margin-right: 0;
text-align: right;
}
[data-testid="stChatMessage"]:has([data-testid="stChatMessageAvatarAssistant"]) {
background: transparent;
padding: 0.3rem 0 0.6rem;
}
[data-testid="stChatMessageAvatarUser"], [data-testid="stChatMessageAvatarAssistant"] {
background: #1A9AA8 !important;
color: #fff !important;
}
/* โโ Chat input โโ */
[data-testid="stChatInput"] textarea {
border: 1.5px solid #D8F1F3 !important;
border-radius: 1.4rem !important;
background: #FFFFFF !important;
font-size: 0.95rem !important;
padding: 0.85rem 1.2rem !important;
}
[data-testid="stChatInput"] textarea:focus {
border-color: #4ECDD4 !important;
box-shadow: 0 0 0 3px rgba(78,205,212,0.15) !important;
}
[data-testid="stChatInputFileUploadButton"],
[data-testid="stChatInputSubmitButton"] {
color: #1A9AA8 !important;
}
/* โโ Sources expander scrollable โโ */
[data-testid="stExpanderDetails"] {
max-height: 420px;
overflow-y: auto;
overflow-x: hidden;
}
[data-testid="stExpanderDetails"]::-webkit-scrollbar { width: 6px; }
[data-testid="stExpanderDetails"]::-webkit-scrollbar-track { background: transparent; }
[data-testid="stExpanderDetails"]::-webkit-scrollbar-thumb {
background: #B2E8EC;
border-radius: 4px;
}
</style>
""", 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("""
<div class="top-header">
<h1>ู
ุฏุฑู</h1>
<p>ู
ุณุงุนุฏู ุงูุฐูู ูููู
ูุธุงู
ุงูุนู
ู ุงูุณุนูุฏู</p>
</div>
""", 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'<span style="font-size:0.75rem;color:{color};">ุชุทุงุจู {pct}%</span>',
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)
|