feat(pipeline): add thread persistence, live progress bar, node oversight timeline, and failure diagnostics
This commit is contained in:
+591
-244
@@ -16,13 +16,19 @@ from medical_coding.ingestion.agent import ClinicalDocumentIngestionAgent
|
||||
from medical_coding.ingestion.detector import DocumentFormat
|
||||
from medical_coding.orchestration.pipeline import MedicalCodingPipeline
|
||||
from medical_coding.pdf.extractor import PDFExtractor
|
||||
from datetime import datetime
|
||||
|
||||
from medical_coding.schemas.enums import ExecutionStatus
|
||||
from medical_coding.schemas.response import CodingResult
|
||||
from medical_coding.ui.components import (
|
||||
NODE_TITLES,
|
||||
render_abstentions,
|
||||
render_failure_alert,
|
||||
render_header,
|
||||
render_kpi_metrics,
|
||||
render_pdf_page_inspector,
|
||||
render_primary_diagnosis,
|
||||
render_process_oversight_timeline,
|
||||
render_secondary_diagnoses,
|
||||
render_validation_audit_trail,
|
||||
)
|
||||
@@ -139,6 +145,116 @@ tab1, tab2, tab3, tab4, tab5 = st.tabs([
|
||||
])
|
||||
|
||||
|
||||
def render_coding_session_results(
|
||||
coding_result: CodingResult,
|
||||
steps_data: list[dict[str, Any]],
|
||||
thread_id: str,
|
||||
document_id: str,
|
||||
raw_text: str = "",
|
||||
active_filename: str = "clinical_document.txt",
|
||||
active_source_type: str = "text",
|
||||
active_file_bytes: bytes | None = None,
|
||||
min_score: float = 0.40,
|
||||
) -> None:
|
||||
"""Render complete diagnostics: Step Oversight Timeline, Failure/Success, KPIs, Diagnoses, and Exports."""
|
||||
is_error = coding_result.status == ExecutionStatus.ERROR
|
||||
has_failed_meta = bool(coding_result.metadata and coding_result.metadata.get("failed_step"))
|
||||
|
||||
if is_error or has_failed_meta:
|
||||
failed_step = (
|
||||
coding_result.metadata.get("failed_step", "unspecified_node")
|
||||
if coding_result.metadata
|
||||
else "unspecified_node"
|
||||
)
|
||||
err_msg = (
|
||||
(coding_result.metadata.get("error") if coding_result.metadata else None)
|
||||
or "An error occurred during workflow execution."
|
||||
)
|
||||
tb_str = coding_result.metadata.get("traceback") if coding_result.metadata else None
|
||||
render_failure_alert(
|
||||
failed_step=failed_step,
|
||||
error_message=err_msg,
|
||||
error_traceback=tb_str,
|
||||
duration_ms=coding_result.processing_time_ms,
|
||||
)
|
||||
render_process_oversight_timeline(steps_data, coding_result.processing_time_ms)
|
||||
return
|
||||
|
||||
# Render Node-by-Node Process Oversight & Latency Timeline
|
||||
render_process_oversight_timeline(steps_data, coding_result.processing_time_ms)
|
||||
|
||||
# High-Level KPIs
|
||||
st.markdown("### 📊 Coding Decisions & Evidence Audit")
|
||||
render_kpi_metrics(coding_result)
|
||||
|
||||
# Primary Diagnosis
|
||||
render_primary_diagnosis(coding_result.primary_diagnosis)
|
||||
|
||||
# Secondary Diagnoses
|
||||
render_secondary_diagnoses(coding_result.secondary_diagnoses)
|
||||
|
||||
# Explicit Abstentions & Rule-Outs
|
||||
render_abstentions(coding_result.abstentions)
|
||||
|
||||
# Deterministic Rule Audit Trail
|
||||
render_validation_audit_trail(coding_result.primary_diagnosis, coding_result.secondary_diagnoses)
|
||||
|
||||
# Structured JSON Response Payload
|
||||
with st.expander("🔍 View Structured JSON Response Payload", expanded=False):
|
||||
st.json(coding_result.model_dump())
|
||||
|
||||
# Downloads
|
||||
st.markdown("---")
|
||||
d_col1, d_col2 = st.columns(2)
|
||||
with d_col1:
|
||||
json_data = coding_result.model_dump_json(indent=2)
|
||||
st.download_button(
|
||||
label="📥 Download Structured JSON Coding Report",
|
||||
data=json_data,
|
||||
file_name=f"{document_id}_coding_report.json",
|
||||
mime="application/json",
|
||||
use_container_width=True,
|
||||
key=f"dl_json_{thread_id}",
|
||||
)
|
||||
with d_col2:
|
||||
export_rows = []
|
||||
if coding_result.primary_diagnosis:
|
||||
export_rows.append({
|
||||
"Encounter": document_id,
|
||||
"Role": "PRIMARY",
|
||||
"Code": coding_result.primary_diagnosis.code,
|
||||
"ICD10CM": coding_result.primary_diagnosis.icd10cm,
|
||||
"ICD_O": coding_result.primary_diagnosis.icdo,
|
||||
"CPT": coding_result.primary_diagnosis.cpt,
|
||||
"Description": coding_result.primary_diagnosis.description,
|
||||
"Confidence": coding_result.primary_diagnosis.confidence_score,
|
||||
"Billable": coding_result.primary_diagnosis.is_terminal_billable,
|
||||
"Evidence": coding_result.primary_diagnosis.evidence_quote,
|
||||
})
|
||||
for s in coding_result.secondary_diagnoses:
|
||||
export_rows.append({
|
||||
"Encounter": document_id,
|
||||
"Role": "SECONDARY",
|
||||
"Code": s.code,
|
||||
"ICD10CM": s.icd10cm,
|
||||
"ICD_O": s.icdo,
|
||||
"CPT": s.cpt,
|
||||
"Description": s.description,
|
||||
"Confidence": s.confidence_score,
|
||||
"Billable": s.is_terminal_billable,
|
||||
"Evidence": s.evidence_quote,
|
||||
})
|
||||
csv_df = pd.DataFrame(export_rows)
|
||||
st.download_button(
|
||||
label="📥 Download Encounter Summary (CSV)",
|
||||
data=csv_df.to_csv(index=False),
|
||||
file_name=f"{document_id}_summary.csv",
|
||||
mime="text/csv",
|
||||
use_container_width=True,
|
||||
key=f"dl_csv_{thread_id}",
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# TAB 1: Clinical Coding Workspace (Multimodal Ingestion & Text Processing)
|
||||
# =============================================================================
|
||||
@@ -149,6 +265,77 @@ with tab1:
|
||||
"or enter text manually. The intelligent ingestion agent auto-detects the format via magic bytes and routes to the specialized parser."
|
||||
)
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Thread Persistence & History Recovery across Browser Refresh
|
||||
# -------------------------------------------------------------------------
|
||||
url_thread_id = st.query_params.get("thread_id")
|
||||
active_thread_id = st.session_state.get("active_thread_id") or url_thread_id
|
||||
|
||||
active_thread_record = repo.get_pipeline_thread(active_thread_id) if active_thread_id else None
|
||||
recent_threads = repo.list_pipeline_threads(limit=20)
|
||||
|
||||
with st.container():
|
||||
p_col1, p_col2, p_col3 = st.columns([3, 2, 1])
|
||||
with p_col1:
|
||||
if active_thread_record:
|
||||
status_clr = (
|
||||
"#10b981"
|
||||
if active_thread_record["status"] == "SUCCESS"
|
||||
else "#ef4444"
|
||||
if active_thread_record["status"] == "FAILED"
|
||||
else "#38bdf8"
|
||||
)
|
||||
st.markdown(
|
||||
f"""
|
||||
<div style="background: rgba(15, 23, 42, 0.85); border: 1px solid rgba(56, 189, 248, 0.4); border-radius: 8px; padding: 8px 14px; margin-bottom: 8px;">
|
||||
<span style="font-size: 11px; color: #94a3b8;">ACTIVE PERSISTENT THREAD:</span>
|
||||
<strong style="color: {status_clr}; margin-left: 6px;">{active_thread_record['thread_id']}</strong>
|
||||
<span class="pill-badge" style="background: rgba(255,255,255,0.05); color: {status_clr}; border: 1px solid {status_clr}; margin-left: 8px;">
|
||||
{active_thread_record['status']}
|
||||
</span>
|
||||
<span style="font-size: 11px; color: #94a3b8; margin-left: 8px;">({active_thread_record['duration_ms']:.1f}ms)</span>
|
||||
<span style="font-size: 11px; color: #10b981; margin-left: 10px;">● Restored from SQLite</span>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
else:
|
||||
st.markdown(
|
||||
"""
|
||||
<div style="background: rgba(15, 23, 42, 0.5); border: 1px solid #1e293b; border-radius: 8px; padding: 8px 14px; margin-bottom: 8px;">
|
||||
<span style="font-size: 12px; color: #94a3b8;">🚀 State persistence active: execution states and histories are stored in SQLite and survive browser refreshes.</span>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
with p_col2:
|
||||
if recent_threads:
|
||||
thread_map = {
|
||||
f"{t['thread_id']} ({t['status']} • {t['document_id']})": t["thread_id"]
|
||||
for t in recent_threads
|
||||
}
|
||||
options = ["-- Quick Switch Thread --"] + list(thread_map.keys())
|
||||
selected_option = st.selectbox(
|
||||
"Switch Thread:",
|
||||
options=options,
|
||||
label_visibility="collapsed",
|
||||
key="quick_thread_select",
|
||||
)
|
||||
if selected_option != "-- Quick Switch Thread --":
|
||||
chosen_tid = thread_map[selected_option]
|
||||
if chosen_tid != active_thread_id:
|
||||
st.query_params["thread_id"] = chosen_tid
|
||||
st.session_state["active_thread_id"] = chosen_tid
|
||||
st.rerun()
|
||||
with p_col3:
|
||||
if active_thread_id:
|
||||
if st.button("✨ Reset Session", use_container_width=True, key="reset_active_thread_btn"):
|
||||
if "thread_id" in st.query_params:
|
||||
del st.query_params["thread_id"]
|
||||
if "active_thread_id" in st.session_state:
|
||||
del st.session_state["active_thread_id"]
|
||||
st.rerun()
|
||||
|
||||
input_mode = st.radio(
|
||||
"Choose Input Modality:",
|
||||
[
|
||||
@@ -159,10 +346,15 @@ with tab1:
|
||||
horizontal=True,
|
||||
)
|
||||
|
||||
document_id = st.text_input("Encounter Identifier (Document ID):", value=f"ENC-{uuid4().hex[:8].upper()}")
|
||||
clinical_text = ""
|
||||
default_doc_id = (
|
||||
active_thread_record.get("document_id")
|
||||
if active_thread_record
|
||||
else f"ENC-{uuid4().hex[:8].upper()}"
|
||||
)
|
||||
document_id = st.text_input("Encounter Identifier (Document ID):", value=default_doc_id)
|
||||
clinical_text = active_thread_record.get("raw_text", "") if active_thread_record else ""
|
||||
active_file_bytes: bytes | None = None
|
||||
active_filename = "clinical_document.txt"
|
||||
active_filename = active_thread_record.get("input_source", "clinical_document.txt") if active_thread_record else "clinical_document.txt"
|
||||
active_source_type = "text"
|
||||
extracted_pages_data: list[Any] = []
|
||||
ingest_result = None
|
||||
@@ -452,121 +644,151 @@ with tab1:
|
||||
if not clinical_text and not active_file_bytes:
|
||||
st.error("❌ Please provide clinical text or upload a document/screenshot before running coding.")
|
||||
else:
|
||||
with st.status("🏥 Executing Offline ICD-10-CM Coding Pipeline...", expanded=True) as status_box:
|
||||
st.write(f"1️⃣ Multimodal Ingestion & Normalization ({active_source_type.upper()})...")
|
||||
st.write("2️⃣ Extracting clinical diagnosis assertions with required verbatim evidence...")
|
||||
st.write("3️⃣ Evaluating clinical context (negation, temporality, certainty, acuity)...")
|
||||
st.write("4️⃣ Executing hybrid BM25 + FAISS candidate retrieval over local ICD catalog...")
|
||||
st.write("5️⃣ Ranking candidate pool and bounding model selections...")
|
||||
st.write("6️⃣ Enforcing deterministic HIPAA billable leaf invariants & Excludes1 checks...")
|
||||
new_thread_id = f"thread-{uuid4().hex[:10]}"
|
||||
st.query_params["thread_id"] = new_thread_id
|
||||
st.session_state["active_thread_id"] = new_thread_id
|
||||
|
||||
# Execute pipeline asynchronously
|
||||
try:
|
||||
coding_result: CodingResult = asyncio.run(
|
||||
pipeline.run_document(
|
||||
document_id=document_id,
|
||||
text=clinical_text,
|
||||
file_bytes=active_file_bytes,
|
||||
metadata={
|
||||
"filename": active_filename,
|
||||
"min_score": min_score,
|
||||
"source_type": active_source_type,
|
||||
},
|
||||
)
|
||||
st.markdown("#### ⚡ Real-Time Pipeline Progress")
|
||||
progress_bar = st.progress(0.0)
|
||||
status_placeholder = st.empty()
|
||||
with st.expander("📋 Live Node Execution Log Stream", expanded=True):
|
||||
log_placeholder = st.empty()
|
||||
|
||||
live_logs = [f"[{datetime.now().strftime('%H:%M:%S')}] Initialized execution thread {new_thread_id}"]
|
||||
log_placeholder.code("\n".join(live_logs), language="text")
|
||||
|
||||
def on_progress(step_idx: int, total_steps: int, node_name: str, log_msg: str, duration_ms: float) -> None:
|
||||
pct = min(1.0, max(0.0, step_idx / total_steps))
|
||||
progress_bar.progress(pct)
|
||||
title = NODE_TITLES.get(node_name, node_name)
|
||||
status_placeholder.markdown(
|
||||
f"""
|
||||
<div class="progress-container">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<span class="active-agent-badge">
|
||||
⚙️ Step {step_idx}/{total_steps}: {title}
|
||||
</span>
|
||||
<span style="font-family: 'JetBrains Mono', monospace; font-size: 13px; color: #38bdf8;">
|
||||
{duration_ms:.1f} ms
|
||||
</span>
|
||||
</div>
|
||||
<div style="margin-top: 8px; font-size: 13px; color: #e2e8f0;">
|
||||
{log_msg}
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
live_logs.append(
|
||||
f"[{datetime.now().strftime('%H:%M:%S')}] Step {step_idx} ({title}): {log_msg} ({duration_ms:.1f}ms)"
|
||||
)
|
||||
log_placeholder.code("\n".join(live_logs), language="text")
|
||||
|
||||
try:
|
||||
coding_result: CodingResult = asyncio.run(
|
||||
pipeline.run_document(
|
||||
document_id=document_id,
|
||||
text=clinical_text,
|
||||
file_bytes=active_file_bytes,
|
||||
metadata={
|
||||
"filename": active_filename,
|
||||
"min_score": min_score,
|
||||
"source_type": active_source_type,
|
||||
},
|
||||
thread_id=new_thread_id,
|
||||
progress_callback=on_progress,
|
||||
persist_thread=True,
|
||||
)
|
||||
status_box.update(label="✅ Medical Coding Completed Successfully!", state="complete", expanded=False)
|
||||
except Exception as exc:
|
||||
status_box.update(label=f"❌ Pipeline Execution Error: {exc}", state="error")
|
||||
st.exception(exc)
|
||||
coding_result = None
|
||||
)
|
||||
progress_bar.progress(1.0)
|
||||
except Exception as exc:
|
||||
coding_result = CodingResult(
|
||||
document_id=document_id,
|
||||
status=ExecutionStatus.ERROR,
|
||||
primary_diagnosis=None,
|
||||
secondary_diagnoses=[],
|
||||
abstentions=[],
|
||||
processing_time_ms=0.0,
|
||||
models_used={},
|
||||
metadata={"error": str(exc), "failed_step": "pipeline_execution_error", "thread_id": new_thread_id},
|
||||
)
|
||||
|
||||
if coding_result:
|
||||
# Save automatically to SQLite Database
|
||||
# Persist document record into encounter archive
|
||||
if coding_result and coding_result.status != ExecutionStatus.ERROR:
|
||||
file_size = len(active_file_bytes) if active_file_bytes else len(clinical_text.encode("utf-8"))
|
||||
page_count = len(extracted_pages_data) if extracted_pages_data else 1
|
||||
|
||||
saved_record = repo.save_coding_result(
|
||||
repo.save_coding_result(
|
||||
result=coding_result,
|
||||
raw_text=clinical_text,
|
||||
filename=active_filename,
|
||||
source_type=active_source_type,
|
||||
page_count=page_count,
|
||||
file_size_bytes=file_size,
|
||||
metadata={"min_score": min_score, "modality": active_source_type},
|
||||
metadata={"min_score": min_score, "modality": active_source_type, "thread_id": new_thread_id},
|
||||
)
|
||||
|
||||
st.success(
|
||||
f"💾 Encounter successfully archived in SQLite Database! (Document ID: **{document_id}**, Row #{saved_record['id']})"
|
||||
fresh_thread = repo.get_pipeline_thread(new_thread_id)
|
||||
steps_data = fresh_thread.get("steps", []) if fresh_thread else []
|
||||
|
||||
render_coding_session_results(
|
||||
coding_result=coding_result,
|
||||
steps_data=steps_data,
|
||||
thread_id=new_thread_id,
|
||||
document_id=document_id,
|
||||
raw_text=clinical_text,
|
||||
active_filename=active_filename,
|
||||
active_source_type=active_source_type,
|
||||
active_file_bytes=active_file_bytes,
|
||||
min_score=min_score,
|
||||
)
|
||||
|
||||
elif active_thread_record:
|
||||
# Browser refresh or historical thread restoration
|
||||
st.markdown("---")
|
||||
st.markdown(f"#### 📜 Restored Pipeline Execution Session (`{active_thread_id}`)")
|
||||
|
||||
steps_data = active_thread_record.get("steps", [])
|
||||
thread_status = active_thread_record.get("status")
|
||||
|
||||
if thread_status == "SUCCESS" and active_thread_record.get("result"):
|
||||
try:
|
||||
res_obj = CodingResult(**active_thread_record["result"])
|
||||
except Exception:
|
||||
res_obj = None
|
||||
|
||||
if res_obj:
|
||||
render_coding_session_results(
|
||||
coding_result=res_obj,
|
||||
steps_data=steps_data,
|
||||
thread_id=active_thread_id,
|
||||
document_id=active_thread_record.get("document_id", document_id),
|
||||
raw_text=active_thread_record.get("raw_text", ""),
|
||||
active_filename=active_thread_record.get("input_source", "clinical_document.txt"),
|
||||
active_source_type="text",
|
||||
min_score=min_score,
|
||||
)
|
||||
else:
|
||||
st.warning("Could not reconstruct result payload for this thread.")
|
||||
render_process_oversight_timeline(steps_data, active_thread_record.get("duration_ms", 0.0))
|
||||
|
||||
# Format Results with Rich Aesthetics
|
||||
st.markdown("### 📊 Coding Decisions & Evidence Audit")
|
||||
render_kpi_metrics(coding_result)
|
||||
elif thread_status == "FAILED":
|
||||
render_failure_alert(
|
||||
failed_step=active_thread_record.get("failed_step"),
|
||||
error_message=active_thread_record.get("error_message"),
|
||||
error_traceback=active_thread_record.get("error_traceback"),
|
||||
duration_ms=active_thread_record.get("duration_ms", 0.0),
|
||||
)
|
||||
render_process_oversight_timeline(steps_data, active_thread_record.get("duration_ms", 0.0))
|
||||
|
||||
# Primary Diagnosis
|
||||
render_primary_diagnosis(coding_result.primary_diagnosis)
|
||||
elif thread_status == "RUNNING":
|
||||
pct = active_thread_record.get("progress_pct", 0.0) / 100.0
|
||||
st.info(
|
||||
f"⏳ Pipeline Thread was recorded as RUNNING at step: **{active_thread_record.get('current_step_name')}** ({active_thread_record.get('progress_pct')}%)"
|
||||
)
|
||||
st.progress(pct)
|
||||
render_process_oversight_timeline(steps_data, active_thread_record.get("duration_ms", 0.0))
|
||||
|
||||
# Secondary Diagnoses
|
||||
render_secondary_diagnoses(coding_result.secondary_diagnoses)
|
||||
|
||||
# Abstentions & Exclusions
|
||||
render_abstentions(coding_result.abstentions)
|
||||
|
||||
# Deterministic Rule Audit Trail
|
||||
render_validation_audit_trail(coding_result.primary_diagnosis, coding_result.secondary_diagnoses)
|
||||
|
||||
# Interactive JSON Viewer Expander
|
||||
with st.expander("🔍 View Structured JSON Response Payload", expanded=False):
|
||||
st.json(coding_result.model_dump())
|
||||
|
||||
# Download Buttons
|
||||
st.markdown("---")
|
||||
d_col1, d_col2 = st.columns(2)
|
||||
with d_col1:
|
||||
json_data = coding_result.model_dump_json(indent=2)
|
||||
st.download_button(
|
||||
label="📥 Download Structured JSON Coding Report",
|
||||
data=json_data,
|
||||
file_name=f"{document_id}_coding_result.json",
|
||||
mime="application/json",
|
||||
use_container_width=True,
|
||||
)
|
||||
with d_col2:
|
||||
export_rows = []
|
||||
if coding_result.primary_diagnosis:
|
||||
export_rows.append({
|
||||
"Encounter": document_id,
|
||||
"Role": "PRIMARY",
|
||||
"Code": coding_result.primary_diagnosis.code,
|
||||
"ICD10CM": coding_result.primary_diagnosis.icd10cm,
|
||||
"ICD_O": coding_result.primary_diagnosis.icdo,
|
||||
"CPT": coding_result.primary_diagnosis.cpt,
|
||||
"Description": coding_result.primary_diagnosis.description,
|
||||
"Confidence": coding_result.primary_diagnosis.confidence_score,
|
||||
"Billable": coding_result.primary_diagnosis.is_terminal_billable,
|
||||
"Evidence": coding_result.primary_diagnosis.evidence_quote,
|
||||
})
|
||||
for s in coding_result.secondary_diagnoses:
|
||||
export_rows.append({
|
||||
"Encounter": document_id,
|
||||
"Role": "SECONDARY",
|
||||
"Code": s.code,
|
||||
"ICD10CM": s.icd10cm,
|
||||
"ICD_O": s.icdo,
|
||||
"CPT": s.cpt,
|
||||
"Description": s.description,
|
||||
"Confidence": s.confidence_score,
|
||||
"Billable": s.is_terminal_billable,
|
||||
"Evidence": s.evidence_quote,
|
||||
})
|
||||
csv_df = pd.DataFrame(export_rows)
|
||||
st.download_button(
|
||||
label="📥 Download Encounter Summary (CSV)",
|
||||
data=csv_df.to_csv(index=False),
|
||||
file_name=f"{document_id}_summary.csv",
|
||||
mime="text/csv",
|
||||
use_container_width=True,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
@@ -659,8 +881,6 @@ with tab2:
|
||||
|
||||
# Display Batch Results Table
|
||||
b_df = pd.DataFrame(batch_results)
|
||||
st.dataframe(b_df, use_container_width=True)
|
||||
|
||||
st.download_button(
|
||||
label="📥 Download Batch Results (CSV)",
|
||||
data=b_df.to_csv(index=False),
|
||||
@@ -673,170 +893,297 @@ with tab2:
|
||||
# TAB 3: Database & Encounters Vault
|
||||
# =============================================================================
|
||||
with tab3:
|
||||
st.markdown("#### SQLite Encounters Vault & Clinical Archive")
|
||||
st.caption("Direct connection to local SQLite database (`./data/medical_coding.db`). Search, inspect, and audit historical encounters and validated diagnoses.")
|
||||
|
||||
# High-level DB metrics
|
||||
stats = repo.get_analytics_summary()
|
||||
m1, m2, m3, m4 = st.columns(4)
|
||||
m1.metric("Total Encounters Saved", stats["total_documents"])
|
||||
m2.metric("Total Diagnoses Stored", stats["total_diagnoses"])
|
||||
m3.metric("HIPAA Billable Ratio", f"{stats['billable_ratio_percent']}%")
|
||||
m4.metric("Avg Latency", f"{stats['average_processing_time_ms']} ms")
|
||||
|
||||
st.markdown("---")
|
||||
|
||||
# Search & Filters
|
||||
f1, f2, f3 = st.columns([2, 1, 1])
|
||||
with f1:
|
||||
search_query = st.text_input("🔍 Search Encounters (ID, Filename, Clinical Notes):", placeholder="e.g. heart failure, ENC-HF-...")
|
||||
with f2:
|
||||
status_filter = st.selectbox("Status Filter:", ["ALL", "SUCCESS", "PARTIAL_SUCCESS", "ABSTAINED", "ERROR"])
|
||||
with f3:
|
||||
code_filter = st.text_input("Filter by ICD-10 Code:", placeholder="e.g. I50, E11")
|
||||
|
||||
# Fetch matching documents
|
||||
stored_docs = repo.list_documents(
|
||||
search=search_query if search_query else None,
|
||||
status=status_filter,
|
||||
code_filter=code_filter if code_filter else None,
|
||||
limit=200,
|
||||
st.markdown("#### Database Vault & Historical Execution Audit")
|
||||
st.caption(
|
||||
"Direct connection to local SQLite database (`./data/medical_coding.db`) using WAL mode. "
|
||||
"Standardized SQLAlchemy model abstraction allows 1-click drop-in replacement with PostgreSQL."
|
||||
)
|
||||
|
||||
if not stored_docs:
|
||||
st.info("No encounter records found matching current query or filters.")
|
||||
else:
|
||||
st.write(f"Showing **{len(stored_docs)}** encounter record(s):")
|
||||
vault_tab1, vault_tab2 = st.tabs([
|
||||
"🗄️ Clinical Encounters Archive",
|
||||
"🧵 Pipeline Execution Threads & Node Logs",
|
||||
])
|
||||
|
||||
# Table summary
|
||||
summary_rows = []
|
||||
for d in stored_docs:
|
||||
src = (d["source_type"] or "").upper()
|
||||
if "PDF" in src:
|
||||
modality_icon = "📄 PDF"
|
||||
elif "IMAGE" in src:
|
||||
modality_icon = "🖼️ IMAGE"
|
||||
elif "MANUAL" in src:
|
||||
modality_icon = "✍️ MANUAL"
|
||||
elif "TXT" in src or "TEXT" in src:
|
||||
modality_icon = "📝 TXT"
|
||||
else:
|
||||
modality_icon = src or "TEXT"
|
||||
with vault_tab1:
|
||||
# High-level DB metrics
|
||||
stats = repo.get_analytics_summary()
|
||||
m1, m2, m3, m4 = st.columns(4)
|
||||
m1.metric("Total Encounters Saved", stats["total_documents"])
|
||||
m2.metric("Total Diagnoses Stored", stats["total_diagnoses"])
|
||||
m3.metric("HIPAA Billable Ratio", f"{stats['billable_ratio_percent']}%")
|
||||
m4.metric("Avg Latency", f"{stats['average_processing_time_ms']} ms")
|
||||
|
||||
summary_rows.append({
|
||||
"Document ID": d["document_id"],
|
||||
"Filename": d["filename"],
|
||||
"Modality": modality_icon,
|
||||
"Status": d["status"],
|
||||
"Primary Code": d["primary_code"] or "None",
|
||||
"Primary Description": d["primary_description"] or "None",
|
||||
"Secondaries": d["secondary_count"],
|
||||
"Abstentions": d["abstention_count"],
|
||||
"Latency (ms)": f"{d['processing_time_ms']:.1f}",
|
||||
"Date": d["created_at"][:19] if d["created_at"] else "N/A",
|
||||
})
|
||||
st.dataframe(pd.DataFrame(summary_rows), use_container_width=True)
|
||||
|
||||
# Detailed Encounter Inspector Drawer
|
||||
st.markdown("---")
|
||||
st.markdown("##### 🔎 Inspect Full Encounter Record")
|
||||
doc_ids = [d["document_id"] for d in stored_docs]
|
||||
selected_doc_id = st.selectbox("Select Encounter ID to Inspect:", doc_ids)
|
||||
|
||||
if selected_doc_id:
|
||||
full_doc = repo.get_document_by_id(selected_doc_id)
|
||||
if full_doc:
|
||||
col_info1, col_info2 = st.columns([3, 1])
|
||||
with col_info1:
|
||||
src_val = (full_doc["source_type"] or "").upper()
|
||||
st.markdown(
|
||||
f"**Encounter:** `{full_doc['document_id']}` | **Modality:** `{src_val}` | **File:** `{full_doc['filename']}` | **Pages:** `{full_doc['page_count']}` | **Words:** `{full_doc['word_count']}`"
|
||||
)
|
||||
with col_info2:
|
||||
if st.button("🗑️ Delete Encounter", key=f"del_{selected_doc_id}"):
|
||||
repo.delete_document(selected_doc_id)
|
||||
st.success(f"Encounter {selected_doc_id} deleted!")
|
||||
st.rerun()
|
||||
# Search & Filters
|
||||
f1, f2, f3 = st.columns([2, 1, 1])
|
||||
with f1:
|
||||
search_query = st.text_input("🔍 Search Encounters (ID, Filename, Clinical Notes):", placeholder="e.g. heart failure, ENC-HF-...")
|
||||
with f2:
|
||||
status_filter = st.selectbox("Status Filter:", ["ALL", "SUCCESS", "PARTIAL_SUCCESS", "ABSTAINED", "ERROR"])
|
||||
with f3:
|
||||
code_filter = st.text_input("Filter by ICD-10 Code:", placeholder="e.g. I50, E11")
|
||||
|
||||
# Tabbed detail view for the encounter
|
||||
d_tab1, d_tab2, d_tab3, d_tab4 = st.tabs([
|
||||
"🩺 Diagnoses & Evidences",
|
||||
"🚫 Abstentions",
|
||||
"📝 Raw Clinical Text",
|
||||
"🛡️ Invariant Checks",
|
||||
])
|
||||
# Fetch matching documents
|
||||
stored_docs = repo.list_documents(
|
||||
search=search_query if search_query else None,
|
||||
status=status_filter,
|
||||
code_filter=code_filter if code_filter else None,
|
||||
limit=200,
|
||||
)
|
||||
|
||||
with d_tab1:
|
||||
if full_doc["primary_code"]:
|
||||
if not stored_docs:
|
||||
st.info("No encounter records found matching current query or filters.")
|
||||
else:
|
||||
st.write(f"Showing **{len(stored_docs)}** encounter record(s):")
|
||||
|
||||
# Table summary
|
||||
summary_rows = []
|
||||
for d in stored_docs:
|
||||
src = (d["source_type"] or "").upper()
|
||||
if "PDF" in src:
|
||||
modality_icon = "📄 PDF"
|
||||
elif "IMAGE" in src:
|
||||
modality_icon = "🖼️ IMAGE"
|
||||
elif "MANUAL" in src:
|
||||
modality_icon = "✍️ MANUAL"
|
||||
elif "TXT" in src or "TEXT" in src:
|
||||
modality_icon = "📝 TXT"
|
||||
else:
|
||||
modality_icon = src or "TEXT"
|
||||
|
||||
summary_rows.append({
|
||||
"Document ID": d["document_id"],
|
||||
"Filename": d["filename"],
|
||||
"Modality": modality_icon,
|
||||
"Status": d["status"],
|
||||
"Primary Code": d["primary_code"] or "None",
|
||||
"Primary Description": d["primary_description"] or "None",
|
||||
"Secondaries": d["secondary_count"],
|
||||
"Abstentions": d["abstention_count"],
|
||||
"Latency (ms)": f"{d['processing_time_ms']:.1f}",
|
||||
"Date": d["created_at"][:19] if d["created_at"] else "N/A",
|
||||
})
|
||||
st.dataframe(pd.DataFrame(summary_rows), use_container_width=True)
|
||||
|
||||
# Detailed Encounter Inspector Drawer
|
||||
st.markdown("---")
|
||||
st.markdown("##### 🔎 Inspect Full Encounter Record")
|
||||
doc_ids = [d["document_id"] for d in stored_docs]
|
||||
selected_doc_id = st.selectbox("Select Encounter ID to Inspect:", doc_ids)
|
||||
|
||||
if selected_doc_id:
|
||||
full_doc = repo.get_document_by_id(selected_doc_id)
|
||||
if full_doc:
|
||||
col_info1, col_info2 = st.columns([3, 1])
|
||||
with col_info1:
|
||||
src_val = (full_doc["source_type"] or "").upper()
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="primary-card">
|
||||
<div class="primary-code">{full_doc['primary_code']}</div>
|
||||
<div class="primary-desc">{full_doc['primary_description']}</div>
|
||||
<span class="pill-badge badge-success">✓ Primary Diagnosis</span>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
f"**Encounter:** `{full_doc['document_id']}` | **Modality:** `{src_val}` | **File:** `{full_doc['filename']}` | **Pages:** `{full_doc['page_count']}` | **Words:** `{full_doc['word_count']}`"
|
||||
)
|
||||
for diag in full_doc["diagnoses"]:
|
||||
if diag["role"] != "PRIMARY":
|
||||
with col_info2:
|
||||
if st.button("🗑️ Delete Encounter", key=f"del_{selected_doc_id}"):
|
||||
repo.delete_document(selected_doc_id)
|
||||
st.success(f"Encounter {selected_doc_id} deleted!")
|
||||
st.rerun()
|
||||
|
||||
# Tabbed detail view for the encounter
|
||||
d_tab1, d_tab2, d_tab3, d_tab4 = st.tabs([
|
||||
"🩺 Diagnoses & Evidences",
|
||||
"🚫 Abstentions",
|
||||
"📝 Raw Clinical Text",
|
||||
"🛡️ Invariant Checks",
|
||||
])
|
||||
|
||||
with d_tab1:
|
||||
if full_doc["primary_code"]:
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="secondary-card">
|
||||
<div style="font-weight: 600; color: #38bdf8;">{diag['code']} - {diag['description']}</div>
|
||||
<div style="font-size: 12px; color: #94a3b8; margin: 4px 0;">Role: {diag['role']} | Acuity: {diag['acuity']} | Certainty: {diag['certainty']}</div>
|
||||
<div class="evidence-box">
|
||||
<em>"{diag['evidence_quote']}"</em>
|
||||
<div class="primary-card">
|
||||
<div class="primary-code">{full_doc['primary_code']}</div>
|
||||
<div class="primary-desc">{full_doc['primary_description']}</div>
|
||||
<span class="pill-badge badge-success">✓ Primary Diagnosis</span>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
for diag in full_doc["diagnoses"]:
|
||||
if diag["role"] != "PRIMARY":
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="secondary-card">
|
||||
<div style="font-weight: 600; color: #38bdf8;">{diag['code']} - {diag['description']}</div>
|
||||
<div style="font-size: 12px; color: #94a3b8; margin: 4px 0;">Role: {diag['role']} | Acuity: {diag['acuity']} | Certainty: {diag['certainty']}</div>
|
||||
<div class="evidence-box">
|
||||
<em>"{diag['evidence_quote']}"</em>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
with d_tab2:
|
||||
if not full_doc["abstentions"]:
|
||||
st.write("No abstentions recorded for this encounter.")
|
||||
for a in full_doc["abstentions"]:
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="abstention-card">
|
||||
<strong>{a['raw_term'] or 'Condition'}</strong>: {a['detail']}
|
||||
<div style="font-size: 11px; color: #94a3b8;">Reason: <code>{a['reason']}</code></div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
with d_tab2:
|
||||
if not full_doc["abstentions"]:
|
||||
st.write("No abstentions recorded for this encounter.")
|
||||
for a in full_doc["abstentions"]:
|
||||
with d_tab3:
|
||||
st.text_area("Stored Clinical Text:", value=full_doc["raw_text"], height=250, disabled=True)
|
||||
|
||||
with d_tab4:
|
||||
if not full_doc["validation_checks"]:
|
||||
st.write("No explicit individual check records stored; general invariants verified.")
|
||||
for v in full_doc["validation_checks"]:
|
||||
check_icon = "✔" if v["passed"] else "✖"
|
||||
st.write(f"{check_icon} **{v['rule_name']}**: {v['details']}")
|
||||
|
||||
# Vault Export Options
|
||||
st.markdown("---")
|
||||
e_col1, e_col2 = st.columns(2)
|
||||
with e_col1:
|
||||
full_df = repo.get_documents_df()
|
||||
st.download_button(
|
||||
label="📥 Export Full Vault to CSV",
|
||||
data=full_df.to_csv(index=False),
|
||||
file_name="encounters_vault_export.csv",
|
||||
mime="text/csv",
|
||||
use_container_width=True,
|
||||
)
|
||||
with e_col2:
|
||||
st.download_button(
|
||||
label="📥 Export Full Vault to JSON",
|
||||
data=json.dumps(stored_docs, indent=2),
|
||||
file_name="encounters_vault_export.json",
|
||||
mime="application/json",
|
||||
use_container_width=True,
|
||||
)
|
||||
|
||||
with vault_tab2:
|
||||
st.markdown("#### 🧵 Pipeline Execution Threads & Node Logs Vault")
|
||||
st.caption(
|
||||
"Complete log records, latency breakdowns, and node oversight for every pipeline run. "
|
||||
"Stored persistently in SQLite; ready for PostgreSQL migration without code changes."
|
||||
)
|
||||
|
||||
all_threads_list = repo.list_pipeline_threads(limit=100)
|
||||
total_th = len(all_threads_list)
|
||||
succ_th = sum(1 for t in all_threads_list if t.get("status") == "SUCCESS")
|
||||
fail_th = sum(1 for t in all_threads_list if t.get("status") == "FAILED")
|
||||
avg_th_lat = round(
|
||||
sum(t.get("duration_ms", 0.0) for t in all_threads_list) / max(1, total_th), 1
|
||||
)
|
||||
|
||||
th_m1, th_m2, th_m3, th_m4 = st.columns(4)
|
||||
th_m1.metric("Total Executions", total_th)
|
||||
th_m2.metric("Successful Threads", succ_th)
|
||||
th_m3.metric("Failed Threads", fail_th)
|
||||
th_m4.metric("Avg Thread Latency", f"{avg_th_lat} ms")
|
||||
|
||||
st.markdown("---")
|
||||
|
||||
th_f1, th_f2 = st.columns([3, 1])
|
||||
with th_f1:
|
||||
th_search = st.text_input(
|
||||
"🔍 Search Threads (ID, Document ID, Source):",
|
||||
placeholder="e.g. thread-..., ENC-...",
|
||||
key="th_search_input",
|
||||
)
|
||||
with th_f2:
|
||||
th_status_filter = st.selectbox(
|
||||
"Filter Status:",
|
||||
["ALL", "SUCCESS", "FAILED", "RUNNING"],
|
||||
key="th_status_filter_sel",
|
||||
)
|
||||
|
||||
filtered_threads = all_threads_list
|
||||
if th_status_filter and th_status_filter != "ALL":
|
||||
filtered_threads = [t for t in filtered_threads if t.get("status") == th_status_filter]
|
||||
if th_search:
|
||||
term = th_search.strip().lower()
|
||||
filtered_threads = [
|
||||
t for t in filtered_threads
|
||||
if term in t.get("thread_id", "").lower()
|
||||
or term in t.get("document_id", "").lower()
|
||||
or term in t.get("input_source", "").lower()
|
||||
]
|
||||
|
||||
if not filtered_threads:
|
||||
st.info("No execution thread history found matching criteria.")
|
||||
else:
|
||||
st.write(f"Showing **{len(filtered_threads)}** pipeline thread(s):")
|
||||
th_summary_rows = []
|
||||
for t in filtered_threads:
|
||||
th_summary_rows.append({
|
||||
"Thread ID": t["thread_id"],
|
||||
"Document ID": t["document_id"],
|
||||
"Source": t["input_source"],
|
||||
"Status": t["status"],
|
||||
"Current / Failed Step": t["failed_step"] or t["current_step_name"],
|
||||
"Steps Completed": len(t.get("steps", [])),
|
||||
"Latency (ms)": f"{t['duration_ms']:.1f}",
|
||||
"Start Time": t["start_time"][:19] if t["start_time"] else "N/A",
|
||||
})
|
||||
st.dataframe(pd.DataFrame(th_summary_rows), use_container_width=True)
|
||||
|
||||
st.markdown("---")
|
||||
st.markdown("##### 🔎 Inspect Execution Thread Timeline & Audit")
|
||||
th_ids = [t["thread_id"] for t in filtered_threads]
|
||||
selected_th_id = st.selectbox("Select Thread ID to Inspect:", th_ids, key="sel_th_inspect")
|
||||
|
||||
if selected_th_id:
|
||||
sel_thread = repo.get_pipeline_thread(selected_th_id)
|
||||
if sel_thread:
|
||||
c_act1, c_act2, c_act3 = st.columns([2, 1, 1])
|
||||
with c_act1:
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="abstention-card">
|
||||
<strong>{a['raw_term'] or 'Condition'}</strong>: {a['detail']}
|
||||
<div style="font-size: 11px; color: #94a3b8;">Reason: <code>{a['reason']}</code></div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
f"**Thread:** `{sel_thread['thread_id']}` | **Status:** `{sel_thread['status']}` | **Duration:** `{sel_thread['duration_ms']:.1f}ms`"
|
||||
)
|
||||
with c_act2:
|
||||
if st.button("🚀 Load into Workspace (Tab 1)", key=f"load_ws_{selected_th_id}", use_container_width=True):
|
||||
st.query_params["thread_id"] = selected_th_id
|
||||
st.session_state["active_thread_id"] = selected_th_id
|
||||
st.success(f"Thread {selected_th_id} loaded! Switch to Tab 1.")
|
||||
st.rerun()
|
||||
with c_act3:
|
||||
if st.button("🗑️ Delete Thread", key=f"del_th_{selected_th_id}", use_container_width=True):
|
||||
repo.delete_pipeline_thread(selected_th_id)
|
||||
st.success(f"Thread {selected_th_id} deleted!")
|
||||
st.rerun()
|
||||
|
||||
# Render timeline for selected thread
|
||||
render_process_oversight_timeline(
|
||||
sel_thread.get("steps", []), sel_thread.get("duration_ms", 0.0)
|
||||
)
|
||||
|
||||
if sel_thread.get("status") == "FAILED":
|
||||
render_failure_alert(
|
||||
failed_step=sel_thread.get("failed_step"),
|
||||
error_message=sel_thread.get("error_message"),
|
||||
error_traceback=sel_thread.get("error_traceback"),
|
||||
duration_ms=sel_thread.get("duration_ms", 0.0),
|
||||
)
|
||||
|
||||
with d_tab3:
|
||||
st.text_area("Stored Clinical Text:", value=full_doc["raw_text"], height=250, disabled=True)
|
||||
with st.expander("📄 Clinical Document Input Text", expanded=False):
|
||||
st.text_area(
|
||||
"Input Document Text:",
|
||||
value=sel_thread.get("raw_text", ""),
|
||||
height=200,
|
||||
disabled=True,
|
||||
key=f"txt_th_{selected_th_id}",
|
||||
)
|
||||
|
||||
with d_tab4:
|
||||
if not full_doc["validation_checks"]:
|
||||
st.write("No explicit individual check records stored; general invariants verified.")
|
||||
for v in full_doc["validation_checks"]:
|
||||
check_icon = "✔" if v["passed"] else "✖"
|
||||
st.write(f"{check_icon} **{v['rule_name']}**: {v['details']}")
|
||||
|
||||
# Vault Export Options
|
||||
st.markdown("---")
|
||||
e_col1, e_col2 = st.columns(2)
|
||||
with e_col1:
|
||||
full_df = repo.get_documents_df()
|
||||
st.download_button(
|
||||
label="📥 Export Full Vault to CSV",
|
||||
data=full_df.to_csv(index=False),
|
||||
file_name="encounters_vault_export.csv",
|
||||
mime="text/csv",
|
||||
use_container_width=True,
|
||||
)
|
||||
with e_col2:
|
||||
st.download_button(
|
||||
label="📥 Export Full Vault to JSON",
|
||||
data=json.dumps(stored_docs, indent=2),
|
||||
file_name="encounters_vault_export.json",
|
||||
mime="application/json",
|
||||
use_container_width=True,
|
||||
)
|
||||
if sel_thread.get("result"):
|
||||
with st.expander("🔍 Structured Output Result JSON", expanded=False):
|
||||
st.json(sel_thread.get("result"))
|
||||
|
||||
|
||||
# =============================================================================
|
||||
|
||||
Reference in New Issue
Block a user