File size: 8,389 Bytes
5774aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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)