File size: 8,231 Bytes
b2ad034 b14fc84 b2ad034 661eb14 b2ad034 b14fc84 b2ad034 661eb14 b14fc84 b2ad034 b14fc84 b2ad034 b14fc84 b2ad034 b14fc84 b2ad034 b14fc84 b2ad034 b14fc84 b2ad034 b14fc84 b2ad034 b14fc84 b2ad034 | 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 | import io
import json
import pandas as pd
import streamlit as st
from core import audit
_ACTION_LABELS = {
"criteria_extracted": "📋 Criteria Extracted",
"bidder_processed": "📥 Bidder Document Indexed",
"criterion_evaluated": "⚖️ Criterion Evaluated",
"human_review_action": "👤 Human Review Action",
"precomputed_fallback_used":"⚠️ Fallback Used",
"vision_ocr_invoked": "👁️ Vision OCR Invoked",
"smoke_test": "🧪 Smoke Test",
}
_ACTION_CATEGORIES = {
"criteria_extracted": "system",
"bidder_processed": "system",
"criterion_evaluated": "system",
"human_review_action": "human",
"precomputed_fallback_used": "warning",
"vision_ocr_invoked": "system",
}
_VERDICT_ICONS = {
"eligible": "✅ Eligible",
"not_eligible": "❌ Not Eligible",
"needs_review": "⚠️ Needs Review",
}
def _make_summary(row: dict) -> str:
action = row.get("action", "")
bidder = row.get("bidder_id") or ""
crit = row.get("criterion_id") or ""
try:
p = json.loads(row.get("payload_json") or "{}")
except Exception:
p = {}
if action == "criteria_extracted":
return f"Extracted {p.get('count', '?')} criteria from {p.get('source', 'tender PDF')}"
if action == "bidder_processed":
return f"{bidder} — {p.get('doc_name', '?')} indexed ({p.get('chunk_count', '?')} chunks)"
if action == "criterion_evaluated":
verdict = _VERDICT_ICONS.get(p.get("verdict", ""), p.get("verdict", "?"))
conf = p.get("combined_confidence", "?")
conf_str = f"{float(conf):.0%}" if conf != "?" else "?"
extracted = p.get("extracted_value", "")
esc = p.get("escalation_reason", "")
base = f"{bidder} / {crit} → {verdict} (confidence: {conf_str})"
if extracted:
base += f" | Extracted: {extracted}"
if esc:
base += f" | ⚠️ {esc}"
return base
if action == "human_review_action":
taken = p.get("action_taken", "?").capitalize()
orig = p.get("original_extracted_value", "")
edited = p.get("edited_value", "")
base = f"Officer {taken}: {bidder} / {crit}"
if orig:
base += f" | Original value: {orig}"
if edited:
base += f" → Edited to: {edited}"
return base
if action == "precomputed_fallback_used":
return f"API unavailable — pre-computed data used | {p.get('reason', '')}"
if action == "vision_ocr_invoked":
tc = p.get("tesseract_conf", "?")
tc_str = f"{float(tc):.0%}" if tc != "?" else "?"
return f"{bidder} page {p.get('page', '?')} — Tesseract confidence {tc_str}, escalated to Vision LLM"
return action
def _category_color(category: str) -> str:
return {"system": "🔵", "human": "🟢", "warning": "🟡"}.get(category, "⚪")
def render() -> None:
st.header("Audit Log")
st.caption(
"Every system action and human decision is recorded here. "
"This log is the compliance trail — it can be exported and submitted as part of the evaluation record."
)
# ── Filters ──────────────────────────────────────────────────────────────
col1, col2, col3 = st.columns(3)
with col1:
bidder_filter = st.selectbox(
"Filter by bidder",
options=["All", "bidder_a", "bidder_b", "bidder_c"],
)
with col2:
action_filter = st.selectbox(
"Filter by action",
options=["All"] + list(_ACTION_LABELS.keys()),
format_func=lambda x: "All" if x == "All" else _ACTION_LABELS.get(x, x),
)
with col3:
if st.button("🗑 Clear Log", type="secondary", use_container_width=True):
st.session_state["confirm_clear_audit"] = True
if st.session_state.get("confirm_clear_audit"):
st.warning("This will permanently delete all audit entries. Are you sure?")
c1, c2 = st.columns(2)
if c1.button("Yes, clear everything", type="primary", use_container_width=True):
audit.clear()
st.session_state.pop("confirm_clear_audit", None)
st.success("Audit log cleared.")
st.rerun()
if c2.button("Cancel", use_container_width=True):
st.session_state.pop("confirm_clear_audit", None)
st.rerun()
filters: dict = {}
if bidder_filter != "All":
filters["bidder_id"] = bidder_filter
if action_filter != "All":
filters["action"] = action_filter
rows = audit.query(filters if filters else None)
if not rows:
st.info("No audit entries yet. Run an evaluation to generate entries.")
return
# ── Summary counts ────────────────────────────────────────────────────────
total = len(rows)
human_actions = sum(1 for r in rows if r["action"] == "human_review_action")
fallbacks = sum(1 for r in rows if r["action"] == "precomputed_fallback_used")
vision_ocr = sum(1 for r in rows if r["action"] == "vision_ocr_invoked")
m1, m2, m3, m4 = st.columns(4)
m1.metric("Total entries", total)
m2.metric("Human actions", human_actions)
m3.metric("Fallback events", fallbacks)
m4.metric("Vision OCR calls", vision_ocr)
st.divider()
# ── Human-readable table ──────────────────────────────────────────────────
df = pd.DataFrame(rows)
df["Action"] = df["action"].map(lambda x: _ACTION_LABELS.get(x, x))
df["Category"] = df["action"].map(
lambda x: _category_color(_ACTION_CATEGORIES.get(x, "system"))
)
df["Summary"] = df.apply(_make_summary, axis=1)
df["Timestamp"] = df["ts"].str[:19].str.replace("T", " ")
df["Actor"] = df["actor"]
df["Bidder"] = df["bidder_id"].fillna("—")
df["Criterion"] = df["criterion_id"].fillna("—")
display = df[["Category", "Timestamp", "Action", "Bidder", "Criterion", "Summary", "Actor"]].copy()
st.dataframe(
display,
use_container_width=True,
hide_index=True,
column_config={
"Category": st.column_config.TextColumn("", width="small"),
"Timestamp": st.column_config.TextColumn("Timestamp", width="medium"),
"Action": st.column_config.TextColumn("Action", width="medium"),
"Bidder": st.column_config.TextColumn("Bidder", width="small"),
"Criterion": st.column_config.TextColumn("Criterion", width="small"),
"Summary": st.column_config.TextColumn("Summary", width="large"),
"Actor": st.column_config.TextColumn("Actor", width="small"),
},
)
# ── Raw detail expander ───────────────────────────────────────────────────
with st.expander("Raw payload data (for compliance / full detail)", expanded=False):
raw_df = df[["Timestamp", "action", "actor", "bidder_id", "criterion_id", "payload_json"]].copy()
raw_df.columns = ["Timestamp", "action", "actor", "bidder_id", "criterion_id", "payload_json"]
st.dataframe(raw_df, use_container_width=True, hide_index=True)
# ── Export ────────────────────────────────────────────────────────────────
export_df = df[["Timestamp", "Action", "Actor", "Bidder", "Criterion", "Summary"]].copy()
export_df["raw_payload"] = df["payload_json"]
csv_buf = io.StringIO()
export_df.to_csv(csv_buf, index=False)
st.download_button(
label="Export CSV",
data=csv_buf.getvalue().encode("utf-8"),
file_name="tenderiq_audit_log.csv",
mime="text/csv",
)
|