"""Generate crisp SVG and high-resolution PNG workflow flowchart diagrams.""" from pathlib import Path import pymupdf OUTPUT_DIR = Path("docs/assets") OUTPUT_DIR.mkdir(parents=True, exist_ok=True) SVG_PATH = OUTPUT_DIR / "workflow_flowchart.svg" PNG_PATH = OUTPUT_DIR / "workflow_flowchart.png" svg_content = """ AGENTIC ICD-10-CM AUTONOMOUS CODING PIPELINE Deterministic-First LangGraph Workflow • Offline GGUF Inference • Hybrid BM25+FAISS Retrieval • Strict UHDDS Compliance 100% AIR-GAPPED ZERO HALLUCINATION UHDDS & HIPAA VERIFIED PHASE 1: INGESTION & DOC CHECK INPUT Clinical Documentation • Inpatient Discharge Summaries • Formats: Plain Text (.txt) or PDF (.pdf) • Batch Concurrency: ≥ 10 documents BoundedDocumentGate (asyncio.Semaphore) NODE 1 validate_document • Verifies payload integrity & existence • Non-zero byte & non-empty string checks • Rejects unreadable or corrupted files Fail → Short-circuits to Abstention NODE 2 extract_text • PyMuPDF thread-pool offloading • Scanned image detection & OCR alerts SectionDetector Segmentation: • Discharge / Principal Diagnoses • History of Present Illness (HPI) • Hospital Course & Assessment • Whitespace normalization & offsets Parsed Document State • Clean text spans & character offsets • Section boundaries mapped • Thread-safe state ready for LLM agent PHASE 2: CLINICAL NLP & UHDDS NODE 3 extract_diagnoses • Local LLM: Offline GGUF inference • Mandatory verbatim text quote • Exact start & end character offsets ✘ STRICT BAN: NO ICD CODES HERE LLM is strictly forbidden from guessing codes • Subsumption removes broad duplicate terms NODE 4 analyze_context Clinical Context Dimensions: • Negation: Affirmative vs Negated ("denies") • Temporality: Current vs Historical PMH • Certainty: Confirmed vs Suspected vs Ruled Out • Acuity: Acute, Chronic, Acute-on-Chronic Verifies documented inpatient management NODE 5 classify_diagnoses UHDDS Role Disambiguation: • PRIMARY: Exactly ONE chief reason for admission • SECONDARY: Active co-existing comorbidities • EXCLUDED: Inactive PMH or Ruled-Out INVARIANT: Single Primary Diagnosis Multiple primary ties → demote or flag for query PHASE 3: RETRIEVAL & RANKING CATALOG Local ICD-10 Dataset • Official CMS / CDC Order Files • Terminal billable leaf codes (HIPAA) • Authoritative Excludes1 & Inclusions Zero cloud API • 100% Local Dataset NODE 6 retrieve_candidates BM25 Lexical Keyword matching Clinical synonyms FAISS Dense BGE-Small vectors Cosine similarity Hybrid Fusion Formula: Score = 0.6*Dense + 0.4*BM25 • Reciprocal Rank Fusion (RRF) • Top-K candidate pool extraction (K=5..10) Catalog Boundary: Out-of-catalog codes purged NODE 7 rank_candidates • Evaluates candidate pool vs clinical quotes • Aligns clinical specificity (e.g. STEMI) • Computes confidence score & justification ✔ CONSTRAINED POOL INVARIANT Ranker strictly confined to retrieved candidates • Rejects out-of-pool choices • Low confidence (<0.65) → flags for abstention PHASE 4: GUARDRAILS & STORAGE NODE 8 validate_codes 100% NON-LLM Deterministic Verification Engine: • Catalog Check: Code exists in local ICD dataset • Leaf Specificity: Must be terminal billable code • Excludes1 Rules: Detects mutually exclusive pairs • Duplicate Consolidation: Merges duplicate codes • Anti-Hallucination Specificity: Demotes over-specific AUDIT TRAIL GENERATION Every check logs rule code, evidence quote, timestamp NODE 9 evaluate_confidence • Composite Confidence Scoring (Extraction + Retrieval + Ranking) Explicit Abstention Engine: • INSUFFICIENT_CLINICAL_EVIDENCE • MULTIPLE_AMBIGUOUS_PRIMARY • SPECIFICITY_REQUIRED / UNSPECIFIED • EXCLUDES1_CONFLICT_DETECTED Responsible AI: Refuses to guess under ambiguity NODE 10 finalize_output Delivery & Persistence Targets: Pydantic CodingResult Schema Validated JSON payload • Internal prompts omitted SQLite Encounters Vault (WAL Mode) Indexed by encounter, ICD code, billable status Streamlit UI & FastAPI REST Service • Interactive clinical cards & analytics • Endpoints: /code/text, /code/pdf, /batch-pdf ✔ PIPELINE COMPLETE Author: Abhinav Gupta • Email: abhinavgupta15.ag@gmail.com • GitHub: https://github.com/AbhinavEliac/Agentic_ICD_Code_Matcher Engineered with Python 3.13 • LangGraph • GPT4All • FAISS • PyMuPDF • Streamlit """ with open(SVG_PATH, "w", encoding="utf-8") as f: f.write(svg_content.strip()) print(f"SVG generated successfully: {SVG_PATH}") doc = pymupdf.open(stream=svg_content.encode("utf-8"), filetype="svg") pix = doc[0].get_pixmap(dpi=150) pix.save(PNG_PATH) print(f"High-resolution PNG generated successfully: {PNG_PATH} ({pix.width}x{pix.height})")