File size: 12,042 Bytes
6cca5b1 | 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 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | """
DocMind — Reusable Streamlit UI Components
Provides render functions for chat messages, source cards,
grounding bars, confidence badges, and pipeline progress.
"""
import streamlit as st
from typing import Dict, List, Optional
from pipeline.chunker import ChunkMetadata
from pipeline.grounding import ConfidenceLevel, GroundingResult, SentenceScore
from pipeline.retriever import RetrievalStats
# ── Chat Messages ───────────────────────────────────────────────────
def render_chat_message(
role: str,
content: str,
grounding_result: Optional[GroundingResult] = None,
sources: Optional[List[ChunkMetadata]] = None,
doc_index_map: Optional[Dict[str, int]] = None,
) -> None:
"""
Render a single chat message with optional grounding info and sources.
Args:
role: "user" or "bot"
content: The message text
grounding_result: Optional grounding gate result for bot messages
sources: Optional list of source chunks for bot messages
doc_index_map: Optional mapping of doc_id → color index
"""
if role == "user":
avatar = "👤"
bubble_class = "user"
else:
avatar = "🧠"
bubble_class = "bot"
st.markdown(f"""
<div class="chat-msg {role}">
<div class="chat-avatar {role}">{avatar}</div>
<div class="chat-bubble {bubble_class}">{content}</div>
</div>
""", unsafe_allow_html=True)
# For bot messages, show grounding info and sources
if role == "bot" and grounding_result and not grounding_result.is_refused:
render_grounding_bar(grounding_result)
render_confidence_badge(grounding_result.confidence)
# Show per-sentence scores in an expander
if grounding_result.sentence_scores:
with st.expander("📊 Per-sentence grounding scores"):
for ss in grounding_result.sentence_scores:
_render_sentence_score(ss)
if role == "bot" and sources:
with st.expander(f"📎 Source chunks ({len(sources)})"):
for chunk in sources:
doc_idx = 0
if doc_index_map and chunk.doc_id in doc_index_map:
doc_idx = doc_index_map[chunk.doc_id]
render_source_card(chunk, doc_idx)
# ── Source Cards ────────────────────────────────────────────────────
def render_source_card(chunk: ChunkMetadata, doc_color_index: int = 0) -> None:
"""Render a collapsible source chunk preview with document color tag."""
tag_class = f"doc-tag-{doc_color_index % 3}"
preview_text = chunk.text[:300] + ("..." if len(chunk.text) > 300 else "")
st.markdown(f"""
<div class="source-card">
<div class="source-card-header">
<span class="source-tag {tag_class}">{chunk.doc_name}</span>
<span>📄 Page {chunk.page_num}</span>
<span style="color: #64748B;">|</span>
<span style="color: #64748B;">{chunk.chunk_id}</span>
</div>
<div>{preview_text}</div>
</div>
""", unsafe_allow_html=True)
# ── Grounding Bar ──────────────────────────────────────────────────
def render_grounding_bar(grounding_result: GroundingResult) -> None:
"""Render an animated grounding score progress bar."""
score = grounding_result.overall_score
pct = max(0, min(100, int(score * 100)))
if grounding_result.confidence == ConfidenceLevel.HIGH:
fill_class = "high"
elif grounding_result.confidence == ConfidenceLevel.MODERATE:
fill_class = "moderate"
else:
fill_class = "low"
st.markdown(f"""
<div class="grounding-bar-container">
<div class="grounding-bar-label">
<span>Grounding Score</span>
<span>{score:.1%}</span>
</div>
<div class="grounding-bar-track">
<div class="grounding-bar-fill {fill_class}" style="width: {pct}%;"></div>
</div>
</div>
""", unsafe_allow_html=True)
# ── Confidence Badge ───────────────────────────────────────────────
def render_confidence_badge(level: ConfidenceLevel) -> None:
"""Render a confidence level badge."""
badges = {
ConfidenceLevel.HIGH: ("✅ High Confidence", "badge-high"),
ConfidenceLevel.MODERATE: ("⚠️ Moderate Confidence", "badge-moderate"),
ConfidenceLevel.LOW: ("❌ Insufficient Grounding", "badge-low"),
}
text, css_class = badges.get(level, ("❓ Unknown", "badge-low"))
st.markdown(f"""
<div class="badge {css_class}">{text}</div>
""", unsafe_allow_html=True)
def _render_sentence_score(ss: SentenceScore) -> None:
"""Render a single sentence's grounding score."""
if ss.confidence == ConfidenceLevel.HIGH:
color = "#34D399"
icon = "✅"
elif ss.confidence == ConfidenceLevel.MODERATE:
color = "#FBBF24"
icon = "⚠️"
else:
color = "#F87171"
icon = "❌"
st.markdown(f"""
<div style="padding: 0.3rem 0; border-bottom: 1px solid rgba(148,163,184,0.08);">
<span>{icon}</span>
<span style="color: {color}; font-weight: 600; font-size: 0.8rem;">
{ss.entailment_score:.1%}
</span>
<span style="color: #94A3B8; font-size: 0.78rem; margin-left: 0.3rem;">
[{ss.chunk_id}]
</span>
<br>
<span style="color: #CBD5E1; font-size: 0.82rem;">{ss.sentence}</span>
</div>
""", unsafe_allow_html=True)
# ── Retrieval Stats ────────────────────────────────────────────────
def render_retrieval_stats(stats: RetrievalStats) -> None:
"""Render retrieval debug information."""
st.markdown(f"""
<div class="debug-panel">
<strong>Retrieval Stats</strong><br>
BM25: {stats.bm25_hits} hits |
Dense: {stats.dense_hits} hits |
After RRF: {stats.rrf_results} |
Latency: {stats.latency_ms:.0f}ms
</div>
""", unsafe_allow_html=True)
# ── Document Status ────────────────────────────────────────────────
def render_document_status(
doc_name: str,
chunk_count: int,
page_count: int,
doc_color_index: int = 0,
) -> None:
"""Render a sidebar document status card."""
tag_class = f"doc-tag-{doc_color_index % 3}"
st.markdown(f"""
<div class="doc-status">
<div class="doc-status-name">
<span class="source-tag {tag_class}"> </span>
📄 {doc_name}
</div>
<div class="doc-status-meta">
{chunk_count} chunks • {page_count} pages
</div>
</div>
""", unsafe_allow_html=True)
# ── Pipeline Progress ──────────────────────────────────────────────
def render_pipeline_progress(stages: List[dict]) -> None:
"""
Render a multi-stage pipeline progress indicator.
Each stage is a dict: {"name": str, "status": "done"|"active"|"pending"}
"""
icons = {"done": "✅", "active": "⏳", "pending": "⏸️"}
html_parts = []
for stage in stages:
icon = icons.get(stage["status"], "⏸️")
css_class = stage["status"]
html_parts.append(
f'<div class="pipeline-step {css_class}">{icon} {stage["name"]}</div>'
)
st.markdown("\n".join(html_parts), unsafe_allow_html=True)
# ── Empty State / Hero ─────────────────────────────────────────────
def render_empty_state() -> None:
"""Render the advanced empty state (Hero Section) when no documents are uploaded."""
st.html("""
<div class="hero-container">
<h2 style="font-size: 2.2rem; font-weight: 700; color: #E2E8F0; margin-bottom: 0.5rem;">Welcome to DocMind</h2>
<p style="color: #94A3B8; font-size: 1.1rem; max-width: 600px; margin: 0 auto;">
Upload your documents in the sidebar to securely chat, summarize, and compare content using Grounded RAG.
</p>
<div class="feature-grid">
<div class="feature-card">
<div class="feature-icon">⚡</div>
<div class="feature-title">Hybrid Retrieval</div>
<div class="feature-desc">
Combines dense vector search (BGE-M3) with sparse keyword search (BM25) to ensure maximum context recall across your documents.
</div>
</div>
<div class="feature-card">
<div class="feature-icon">🛡️</div>
<div class="feature-title">NLI Grounding</div>
<div class="feature-desc">
Every generated sentence is rigorously verified against the source context using Natural Language Inference models to eliminate hallucinations.
</div>
</div>
<div class="feature-card">
<div class="feature-icon">🧠</div>
<div class="feature-title">Llama 3 Powered</div>
<div class="feature-desc">
Utilizes Groq's lightning-fast inference for deep reasoning, automated summarization, and side-by-side document comparison.
</div>
</div>
</div>
</div>
""")
# ── Comparison Table ───────────────────────────────────────────────
def render_comparison_table(comparison_text: str) -> None:
"""Render a document comparison result."""
st.markdown(comparison_text, unsafe_allow_html=True)
# ── Dashboard Metrics ──────────────────────────────────────────────
def render_dashboard_metrics(doc_count: int, chunk_count: int, memory_mb: float = 0.0) -> None:
"""Render a row of top-level metric cards for the dashboard."""
st.markdown(f"""
<div class="metric-row">
<div class="metric-card">
<div class="metric-title">Documents</div>
<div class="metric-value">{doc_count}</div>
<div class="metric-subtitle">Currently Indexed</div>
</div>
<div class="metric-card">
<div class="metric-title">Knowledge Chunks</div>
<div class="metric-value">{chunk_count}</div>
<div class="metric-subtitle">Vector DB + BM25</div>
</div>
<div class="metric-card">
<div class="metric-title">System Status</div>
<div class="metric-value">Ready</div>
<div class="metric-subtitle" style="color: #34D399;">Hybrid Retrieval Online</div>
</div>
</div>
""", unsafe_allow_html=True)
# ── Key Point Card ─────────────────────────────────────────────────
def render_keypoint_card(text: str, page_ref: str = "") -> None:
"""Render a styled HTML card for a key point."""
page_html = f" <span style='color:#64748B; font-size:0.8rem;'>{page_ref}</span>" if page_ref else ""
st.markdown(f"""
<div class="keypoint-card">
<div class="keypoint-icon">🎯</div>
<div>
{text}{page_html}
</div>
</div>
""", unsafe_allow_html=True)
|