Spaces:
Sleeping
Sleeping
Download ui/components.py from ksk76/structural-encoder-uplan: direct link, hf CLI and curl.
- Browser
- Download file 8.39 kB
-
https://huggingface.co/spaces/ksk76/structural-encoder-uplan/resolve/main/ui/components.py
- Command line
-
hf download hf://spaces/ksk76/structural-encoder-uplan/ui/components.py
-
curl -L -o components.py https://huggingface.co/spaces/ksk76/structural-encoder-uplan/resolve/main/ui/components.py
8.39 kB
| """ | |
| Uplan UI β Reusable Streamlit Components | |
| Renders: compression stats, findings dashboard, verdict card, narrative report. | |
| """ | |
| from __future__ import annotations | |
| import streamlit as st | |
| # ββ Compression Stats (strongest demo moment) βββββββββββββββββββββββ | |
| def render_compression_stats(metadata: dict) -> None: | |
| """Hero metric: the 60k β 1,200 token reduction.""" | |
| raw = metadata.get("estimated_raw_tokens", 0) | |
| graph = metadata.get("token_count", 1) | |
| pages = metadata.get("page_count", 0) | |
| duration = metadata.get("duration_ms", 0) | |
| reduction = (1 - graph / max(raw, 1)) * 100 | |
| ratio = raw / max(graph, 1) | |
| st.markdown("### π¬ Structural Encoding β Token Compression") | |
| cols = st.columns(4) | |
| cols[0].metric("π Pages Processed", f"{pages}") | |
| cols[1].metric("π Raw Tokens (est.)", f"{raw:,}") | |
| cols[2].metric("𧬠Graph Tokens", f"{graph:,}") | |
| cols[3].metric("π Reduction", f"{reduction:.1f}%") | |
| # Progress bar visualizing the compression | |
| st.progress(min(reduction / 100, 1.0)) | |
| st.caption( | |
| f"**{ratio:.0f}:1 compression** β {pages} pages of raw documents condensed " | |
| f"into a {graph:,}-token semantic graph in {duration / 1000:.1f}s. " | |
| f"Fits any 4k+ context window." | |
| ) | |
| # ββ Rule Findings βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def render_rule_findings(findings: list[dict]) -> None: | |
| """Display deterministic rule engine results with severity badges.""" | |
| st.markdown("### βοΈ Deterministic Rule Engine") | |
| if not findings: | |
| st.success("β No rule violations detected.") | |
| return | |
| critical = [f for f in findings if f["severity"] == "critical"] | |
| warnings = [f for f in findings if f["severity"] == "warning"] | |
| info = [f for f in findings if f["severity"] == "info"] | |
| if critical: | |
| st.error(f"π΄ {len(critical)} critical finding(s)") | |
| if warnings: | |
| st.warning(f"π‘ {len(warnings)} warning(s)") | |
| if info: | |
| st.info(f"π΅ {len(info)} informational finding(s)") | |
| for f in findings: | |
| icon = {"critical": "π΄", "warning": "π‘", "info": "π΅"}.get(f["severity"], "βͺ") | |
| with st.expander(f"{icon} [{f['rule_id']}] {f['message']}", expanded=f["severity"] == "critical"): | |
| col1, col2 = st.columns(2) | |
| col1.markdown(f"**Expected:** `{f.get('expected', 'N/A')}`") | |
| col2.markdown(f"**Actual:** `{f.get('actual', 'N/A')}`") | |
| st.caption(f"Field: `{f['field_path']}`") | |
| # ββ Agent Findings ββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def render_agent_findings(findings: list[dict]) -> None: | |
| """Display specialist agent reasoning results.""" | |
| st.markdown("### π΅οΈ Specialist Agent Analysis") | |
| if not findings: | |
| st.info("No agent findings available.") | |
| return | |
| for af in findings: | |
| verdict_color = { | |
| "pass": "π’", | |
| "flag": "π‘", | |
| "critical": "π΄", | |
| }.get(af.get("agent_verdict", ""), "βͺ") | |
| agent_label = af["agent_id"].replace("_", " ").title() | |
| confidence = af.get("confidence", 0) | |
| with st.expander( | |
| f"{verdict_color} {agent_label} β {af['agent_verdict'].upper()} " | |
| f"(confidence: {confidence:.0%})", | |
| expanded=af.get("agent_verdict") == "critical", | |
| ): | |
| st.markdown(f"**Summary:** {af.get('summary', 'N/A')}") | |
| anomalies = af.get("anomalies", []) | |
| if anomalies: | |
| for anomaly in anomalies: | |
| sev_icon = {"critical": "π΄", "warning": "π‘", "info": "π΅"}.get( | |
| anomaly["severity"], "βͺ" | |
| ) | |
| st.markdown( | |
| f"- {sev_icon} **`{anomaly['field_path']}`**: {anomaly['explanation']}" | |
| ) | |
| if anomaly.get("rule_id"): | |
| st.caption(f" Linked rule: `{anomaly['rule_id']}`") | |
| else: | |
| st.success("No anomalies detected by this agent.") | |
| # ββ Verdict Card ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def render_verdict(verdict: dict, risk_score: float) -> None: | |
| """Hero card: final verdict with risk gauge.""" | |
| st.markdown("---") | |
| st.markdown("## π Final Assessment") | |
| verdict_text = verdict.get("verdict", "UNKNOWN") | |
| verdict_styles = { | |
| "PASS": ("success", "β "), | |
| "CONDITIONAL": ("warning", "β οΈ"), | |
| "FAIL": ("error", "β"), | |
| } | |
| style, icon = verdict_styles.get(verdict_text, ("info", "β")) | |
| # Verdict + Risk score side by side | |
| col1, col2 = st.columns([2, 1]) | |
| with col1: | |
| getattr(st, style)(f"{icon} Verdict: **{verdict_text}**") | |
| with col2: | |
| risk_color = "π΄" if risk_score > 0.7 else "π‘" if risk_score > 0.3 else "π’" | |
| st.metric(f"{risk_color} Risk Score", f"{risk_score:.2f}") | |
| # Risk progress bar | |
| st.progress(min(risk_score, 1.0)) | |
| # Issues summary | |
| critical = verdict.get("critical_issues", []) | |
| warnings = verdict.get("warning_issues", []) | |
| if critical: | |
| st.markdown("#### π΄ Critical Issues") | |
| for issue in critical: | |
| st.markdown(f"- {issue}") | |
| if warnings: | |
| st.markdown("#### π‘ Warnings") | |
| for issue in warnings: | |
| st.markdown(f"- {issue}") | |
| # ββ Narrative Report ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def render_narrative(verdict: dict) -> None: | |
| """Full rejection narrative and rebuttal guidance.""" | |
| rejection = verdict.get("rejection_narrative", "") | |
| rebuttals = verdict.get("rebuttal_guidance", []) | |
| citations = verdict.get("citations", []) | |
| if rejection: | |
| st.markdown("### π Officer's Assessment") | |
| st.markdown( | |
| f'<div style="background: #1a1a2e; border-left: 4px solid #e94560; ' | |
| f'padding: 16px; border-radius: 4px; font-family: serif; ' | |
| f'line-height: 1.8;">{rejection}</div>', | |
| unsafe_allow_html=True, | |
| ) | |
| if rebuttals: | |
| st.markdown("### π‘οΈ Rebuttal Guidance") | |
| st.caption("How the applicant can address each issue:") | |
| for i, r in enumerate(rebuttals, 1): | |
| st.markdown(f"**{i}.** {r}") | |
| if citations: | |
| st.markdown("### π Evidence Citations") | |
| st.caption("Graph node paths supporting the verdict:") | |
| for c in citations: | |
| st.code(c, language=None) | |
| # ββ Semantic Graph Summary ββββββββββββββββββββββββββββββββββββββββββ | |
| def render_graph_summary(graph: dict) -> None: | |
| """Quick overview of what the semantic graph contains.""" | |
| st.markdown("### 𧬠Semantic Graph Structure") | |
| identity = graph.get("identity", {}) | |
| financial = graph.get("financial", {}) | |
| temporal = graph.get("temporal", {}) | |
| sponsor = graph.get("sponsor") | |
| enrollment = graph.get("enrollment") | |
| edges = graph.get("edges", []) | |
| cols = st.columns(5) | |
| cols[0].metric("π€ Identity", f"{len(identity.get('name_variants', []))} names") | |
| cols[1].metric("π° Financial", f"{financial.get('transaction_count', 0)} txns") | |
| cols[2].metric("π Temporal", f"{len(temporal.get('doc_date_ranges', []))} ranges") | |
| cols[3].metric("π€ Sponsor", "Present" if sponsor else "None") | |
| cols[4].metric("π Enrollment", "Present" if enrollment else "None") | |
| # Edge coherence | |
| coherent = sum(1 for e in edges if e.get("coherent")) | |
| incoherent = len(edges) - coherent | |
| if incoherent > 0: | |
| st.warning(f"β οΈ {incoherent}/{len(edges)} cross-document edges are **incoherent**") | |
| elif edges: | |
| st.success(f"β All {len(edges)} cross-document relationships are coherent") | |
| # Raw graph JSON in expander | |
| with st.expander("π View Raw Graph JSON"): | |
| st.json(graph) | |