feat: initial commit of Agentic ICD-10-CM Autonomous Code Matcher with 10-node LangGraph pipeline, deterministic guardrails, and professional documentation
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
"""Local Medical ICD-10-CM Coding System.
|
||||
|
||||
An offline, evidence-backed clinical coding pipeline orchestrating local LLMs (GPT4All),
|
||||
hybrid retrieval (BM25 + FAISS), LangGraph state workflows, and deterministic
|
||||
validation against local ICD-10-CM datasets.
|
||||
"""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Agent exports."""
|
||||
|
||||
from medical_coding.agents.base import BaseAgent
|
||||
from medical_coding.agents.classifier import (
|
||||
ClassificationAgent,
|
||||
ContextAndRelevanceAgent,
|
||||
PrimarySecondaryClassifier,
|
||||
)
|
||||
from medical_coding.agents.extractor import (
|
||||
ClinicalExtractionAgent,
|
||||
DiagnosisExtractionAgent,
|
||||
)
|
||||
from medical_coding.agents.parser import ExtractionParser
|
||||
from medical_coding.agents.ranker import CandidateRankingAgent
|
||||
|
||||
__all__ = [
|
||||
"BaseAgent",
|
||||
"CandidateRankingAgent",
|
||||
"ClassificationAgent",
|
||||
"ClinicalExtractionAgent",
|
||||
"ContextAndRelevanceAgent",
|
||||
"DiagnosisExtractionAgent",
|
||||
"ExtractionParser",
|
||||
"PrimarySecondaryClassifier",
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Base agent interface for local LLM-driven clinical reasoning."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.models.base import BaseLocalLLM
|
||||
|
||||
|
||||
class BaseAgent(ABC):
|
||||
"""Abstract base class for modular clinical reasoning agents."""
|
||||
|
||||
def __init__(self, llm: BaseLocalLLM) -> None:
|
||||
self.llm = llm
|
||||
|
||||
@abstractmethod
|
||||
def run(self, **kwargs: Any) -> Any:
|
||||
"""Execute agent reasoning step."""
|
||||
pass
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,336 @@
|
||||
"""Clinical Information Extraction Agent extracting structured conditions with verbatim evidence grounding."""
|
||||
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from medical_coding.agents.base import BaseAgent
|
||||
from medical_coding.agents.parser import ExtractionParser
|
||||
from medical_coding.models.base import BaseLocalLLM
|
||||
from medical_coding.models.langchain_llm import LocalGPT4AllLangChainLLM
|
||||
from medical_coding.pdf.models import ClinicalPDFDocument
|
||||
from medical_coding.prompts.extraction import (
|
||||
CLINICAL_EXTRACTION_RETRY_TEMPLATE,
|
||||
CLINICAL_EXTRACTION_SYSTEM_PROMPT,
|
||||
CLINICAL_EXTRACTION_USER_TEMPLATE,
|
||||
)
|
||||
from medical_coding.schemas.clinical import (
|
||||
ClinicalExtractionResult,
|
||||
EvidenceSnippet,
|
||||
ExtractedClinicalCondition,
|
||||
ExtractedDiagnosis,
|
||||
TextSpan,
|
||||
)
|
||||
from medical_coding.schemas.enums import (
|
||||
Certainty,
|
||||
ConditionStatus,
|
||||
NegationStatus,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class ClinicalExtractionAgent(BaseAgent):
|
||||
"""Extracts candidate medical conditions, certainty, temporality, and evidence without assigning ICD codes.
|
||||
|
||||
ARCHITECTURAL PRINCIPLES:
|
||||
1. NEVER generates or invents ICD codes.
|
||||
2. Every condition MUST have verbatim documentary evidence.
|
||||
3. Reconstructs structured context (CONFIRMED, SUSPECTED, POSSIBLE, RULED_OUT, HISTORICAL, RESOLVED, CURRENT).
|
||||
4. Handles contradictory mentions and past medical history appropriately.
|
||||
5. Robust parser with retry policy for local quantized LLMs.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
llm: BaseLocalLLM | LocalGPT4AllLangChainLLM,
|
||||
max_retries: int = 2,
|
||||
parser: ExtractionParser | None = None,
|
||||
) -> None:
|
||||
super().__init__(llm) # type: ignore[arg-type]
|
||||
self.max_retries = max_retries
|
||||
self.parser = parser or ExtractionParser()
|
||||
|
||||
def _generate(self, prompt: str) -> str:
|
||||
"""Call LLM synchronously across either BaseLocalLLM or LangChain LLM interface."""
|
||||
if hasattr(self.llm, "invoke"):
|
||||
return str(self.llm.invoke(prompt))
|
||||
if hasattr(self.llm, "generate"):
|
||||
return self.llm.generate(prompt)
|
||||
raise TypeError(f"Unsupported LLM instance type: {type(self.llm)}")
|
||||
|
||||
async def _generate_async(self, prompt: str) -> str:
|
||||
"""Call LLM asynchronously across either LangChain LLM or async lifecycle manager."""
|
||||
if hasattr(self.llm, "ainvoke"):
|
||||
res = await self.llm.ainvoke(prompt)
|
||||
return str(res)
|
||||
if hasattr(self.llm, "generate_async"):
|
||||
return await self.llm.generate_async(prompt)
|
||||
# Fallback to sync in thread
|
||||
import asyncio
|
||||
|
||||
return await asyncio.to_thread(self._generate, prompt)
|
||||
|
||||
def extract_clinical_conditions(
|
||||
self,
|
||||
document: ClinicalPDFDocument | str,
|
||||
doc_id: str | None = None,
|
||||
) -> ClinicalExtractionResult:
|
||||
"""Extract structured clinical conditions from a document synchronously.
|
||||
|
||||
Args:
|
||||
document: ClinicalPDFDocument instance or raw clinical text.
|
||||
doc_id: Optional document identifier.
|
||||
|
||||
Returns:
|
||||
ClinicalExtractionResult containing validated ExtractedClinicalCondition items.
|
||||
"""
|
||||
clinical_doc: ClinicalPDFDocument | None = None
|
||||
if isinstance(document, ClinicalPDFDocument):
|
||||
clinical_doc = document
|
||||
document_id = document.document_id
|
||||
# Send targeted clinical sections rather than raw entire document
|
||||
text_to_analyze = document.get_coding_text()
|
||||
full_text = document.full_normalized_text
|
||||
else:
|
||||
document_id = doc_id or str(uuid4())
|
||||
text_to_analyze = str(document).strip()
|
||||
full_text = text_to_analyze
|
||||
|
||||
if not text_to_analyze:
|
||||
return ClinicalExtractionResult(
|
||||
document_id=document_id,
|
||||
conditions=[],
|
||||
extraction_notes=["Input document text was empty."],
|
||||
repair_applied=False,
|
||||
)
|
||||
|
||||
# 1. Format initial extraction prompt
|
||||
prompt = (
|
||||
f"{CLINICAL_EXTRACTION_SYSTEM_PROMPT}\n\n"
|
||||
f"{CLINICAL_EXTRACTION_USER_TEMPLATE.format(clinical_text=text_to_analyze)}"
|
||||
)
|
||||
|
||||
logger.info("Executing clinical condition extraction for doc_id=%s...", document_id)
|
||||
raw_output = ""
|
||||
conditions: list[ExtractedClinicalCondition] = []
|
||||
audit_notes: list[str] = []
|
||||
repair_applied = False
|
||||
|
||||
for attempt in range(self.max_retries + 1):
|
||||
try:
|
||||
raw_output = self._generate(prompt)
|
||||
conditions, notes, repaired = self.parser.parse_and_validate(
|
||||
raw_llm_output=raw_output,
|
||||
document_text=full_text,
|
||||
clinical_doc=clinical_doc,
|
||||
)
|
||||
audit_notes.extend(notes)
|
||||
if repaired:
|
||||
repair_applied = True
|
||||
|
||||
if conditions or not text_to_analyze:
|
||||
# Successfully parsed conditions
|
||||
break
|
||||
|
||||
logger.warning(
|
||||
"Extraction attempt %d for doc %s produced 0 validated conditions. Retrying...",
|
||||
attempt + 1,
|
||||
document_id,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("Extraction error during attempt %d: %s", attempt + 1, exc)
|
||||
audit_notes.append(f"Attempt #{attempt + 1} error: {exc}")
|
||||
|
||||
# Prepare retry prompt
|
||||
prompt = (
|
||||
f"{CLINICAL_EXTRACTION_SYSTEM_PROMPT}\n\n"
|
||||
f"{CLINICAL_EXTRACTION_RETRY_TEMPLATE.format(clinical_text=text_to_analyze)}"
|
||||
)
|
||||
|
||||
# 2. Resolve contradictory mentions & enforce past medical history rules
|
||||
resolved_conditions = self._reconcile_clinical_mentions(conditions)
|
||||
|
||||
return ClinicalExtractionResult(
|
||||
document_id=document_id,
|
||||
conditions=resolved_conditions,
|
||||
extraction_notes=audit_notes,
|
||||
repair_applied=repair_applied,
|
||||
raw_response=raw_output,
|
||||
)
|
||||
|
||||
async def extract_clinical_conditions_async(
|
||||
self,
|
||||
document: ClinicalPDFDocument | str,
|
||||
doc_id: str | None = None,
|
||||
) -> ClinicalExtractionResult:
|
||||
"""Asynchronously extract structured clinical conditions."""
|
||||
clinical_doc: ClinicalPDFDocument | None = None
|
||||
if isinstance(document, ClinicalPDFDocument):
|
||||
clinical_doc = document
|
||||
document_id = document.document_id
|
||||
text_to_analyze = document.get_coding_text()
|
||||
full_text = document.full_normalized_text
|
||||
else:
|
||||
document_id = doc_id or str(uuid4())
|
||||
text_to_analyze = str(document).strip()
|
||||
full_text = text_to_analyze
|
||||
|
||||
if not text_to_analyze:
|
||||
return ClinicalExtractionResult(
|
||||
document_id=document_id,
|
||||
conditions=[],
|
||||
extraction_notes=["Input document text was empty."],
|
||||
repair_applied=False,
|
||||
)
|
||||
|
||||
prompt = (
|
||||
f"{CLINICAL_EXTRACTION_SYSTEM_PROMPT}\n\n"
|
||||
f"{CLINICAL_EXTRACTION_USER_TEMPLATE.format(clinical_text=text_to_analyze)}"
|
||||
)
|
||||
|
||||
logger.info("Executing async clinical extraction for doc_id=%s...", document_id)
|
||||
raw_output = ""
|
||||
conditions: list[ExtractedClinicalCondition] = []
|
||||
audit_notes: list[str] = []
|
||||
repair_applied = False
|
||||
|
||||
for attempt in range(self.max_retries + 1):
|
||||
try:
|
||||
raw_output = await self._generate_async(prompt)
|
||||
conditions, notes, repaired = self.parser.parse_and_validate(
|
||||
raw_llm_output=raw_output,
|
||||
document_text=full_text,
|
||||
clinical_doc=clinical_doc,
|
||||
)
|
||||
audit_notes.extend(notes)
|
||||
if repaired:
|
||||
repair_applied = True
|
||||
|
||||
if conditions or not text_to_analyze:
|
||||
break
|
||||
except Exception as exc:
|
||||
audit_notes.append(f"Async attempt #{attempt + 1} error: {exc}")
|
||||
|
||||
prompt = (
|
||||
f"{CLINICAL_EXTRACTION_SYSTEM_PROMPT}\n\n"
|
||||
f"{CLINICAL_EXTRACTION_RETRY_TEMPLATE.format(clinical_text=text_to_analyze)}"
|
||||
)
|
||||
|
||||
resolved_conditions = self._reconcile_clinical_mentions(conditions)
|
||||
return ClinicalExtractionResult(
|
||||
document_id=document_id,
|
||||
conditions=resolved_conditions,
|
||||
extraction_notes=audit_notes,
|
||||
repair_applied=repair_applied,
|
||||
raw_response=raw_output,
|
||||
)
|
||||
|
||||
def _reconcile_clinical_mentions(
|
||||
self,
|
||||
conditions: list[ExtractedClinicalCondition],
|
||||
) -> list[ExtractedClinicalCondition]:
|
||||
"""Reconcile multiple or contradictory mentions of the same clinical condition.
|
||||
|
||||
Rules:
|
||||
1. If a condition is suspected initially but documented as RULED_OUT later,
|
||||
the definitive RULED_OUT certainty takes precedence.
|
||||
2. If a condition is ONLY mentioned in PAST_MEDICAL_HISTORY, enforce HISTORICAL temporality.
|
||||
3. If a condition is confirmed in DISCHARGE_DIAGNOSES, enforce CURRENT temporality (unless explicitly resolved).
|
||||
"""
|
||||
if not conditions:
|
||||
return []
|
||||
|
||||
# Group by normalized description
|
||||
by_concept: dict[str, list[ExtractedClinicalCondition]] = {}
|
||||
for c in conditions:
|
||||
key = c.normalized_description.lower().strip()
|
||||
by_concept.setdefault(key, []).append(c)
|
||||
|
||||
reconciled: list[ExtractedClinicalCondition] = []
|
||||
for _, items in by_concept.items():
|
||||
if len(items) == 1:
|
||||
item = items[0]
|
||||
# Enforce PMH rule: if only in PMH, must be HISTORICAL
|
||||
if "PAST" in item.section.upper() or "PMH" in item.section.upper():
|
||||
item.temporality = Temporality.HISTORICAL
|
||||
if item.status == ConditionStatus.ACUTE:
|
||||
item.status = ConditionStatus.CHRONIC
|
||||
reconciled.append(item)
|
||||
continue
|
||||
|
||||
# Multiple mentions exist (e.g. suspected in HPI, confirmed or ruled out in Discharge Diagnoses)
|
||||
has_ruled_out = any(it.certainty == Certainty.RULED_OUT for it in items)
|
||||
has_discharge_diag = any("DISCHARGE" in it.section.upper() for it in items)
|
||||
|
||||
if has_ruled_out:
|
||||
# Definitive exclusion overrides suspected/possible
|
||||
ruled_out_item = next(it for it in items if it.certainty == Certainty.RULED_OUT)
|
||||
ruled_out_item.status = ConditionStatus.RESOLVED
|
||||
ruled_out_item.negation = NegationStatus.NEGATED
|
||||
reconciled.append(ruled_out_item)
|
||||
elif has_discharge_diag:
|
||||
# Discharge diagnosis is authoritative
|
||||
dd_item = next(it for it in items if "DISCHARGE" in it.section.upper())
|
||||
dd_item.temporality = Temporality.CURRENT
|
||||
reconciled.append(dd_item)
|
||||
else:
|
||||
# Keep the mention with highest certainty
|
||||
sorted_items = sorted(
|
||||
items,
|
||||
key=lambda x: (
|
||||
1 if x.certainty == Certainty.CONFIRMED else 0,
|
||||
1 if x.temporality == Temporality.CURRENT else 0,
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
reconciled.append(sorted_items[0])
|
||||
|
||||
return reconciled
|
||||
|
||||
# Backwards-compatibility adapter for existing LangGraph nodes
|
||||
def extract(self, clinical_text: str) -> list[ExtractedDiagnosis]:
|
||||
"""Legacy interface adapting ExtractedClinicalCondition to ExtractedDiagnosis."""
|
||||
result = self.extract_clinical_conditions(clinical_text)
|
||||
diagnoses: list[ExtractedDiagnosis] = []
|
||||
for c in result.conditions:
|
||||
# Only include affirmative, non-ruled-out conditions
|
||||
if c.certainty == Certainty.RULED_OUT or c.negation == NegationStatus.NEGATED:
|
||||
continue
|
||||
|
||||
span = None
|
||||
if (
|
||||
c.evidence_location.start_char is not None
|
||||
and c.evidence_location.end_char is not None
|
||||
):
|
||||
span = TextSpan(
|
||||
start_char=c.evidence_location.start_char,
|
||||
end_char=c.evidence_location.end_char,
|
||||
text=c.evidence_text,
|
||||
page_number=c.evidence_location.page_number,
|
||||
)
|
||||
|
||||
snippet = EvidenceSnippet(
|
||||
quote=c.evidence_text,
|
||||
span=span,
|
||||
source_section=c.section,
|
||||
)
|
||||
|
||||
diag = ExtractedDiagnosis(
|
||||
diagnosis_id=c.condition_id,
|
||||
raw_term=c.normalized_description,
|
||||
evidence=snippet,
|
||||
extraction_confidence=c.confidence_score,
|
||||
)
|
||||
diagnoses.append(diag)
|
||||
|
||||
return diagnoses
|
||||
|
||||
def run(self, **kwargs: Any) -> list[ExtractedDiagnosis]:
|
||||
text = kwargs.get("clinical_text", "")
|
||||
return self.extract(text)
|
||||
|
||||
|
||||
# Backwards compatibility alias
|
||||
DiagnosisExtractionAgent = ClinicalExtractionAgent
|
||||
@@ -0,0 +1,348 @@
|
||||
"""Robust JSON parser, clinical enum normalizer, and evidence-grounding validator for local LLM outputs."""
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.pdf.models import ClinicalPDFDocument
|
||||
from medical_coding.schemas.clinical import (
|
||||
EvidenceLocation,
|
||||
ExtractedClinicalCondition,
|
||||
)
|
||||
from medical_coding.schemas.enums import (
|
||||
Certainty,
|
||||
ClinicalEntityType,
|
||||
ConditionStatus,
|
||||
Laterality,
|
||||
NegationStatus,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class ExtractionParser:
|
||||
"""Parses and repairs structured extraction outputs from local LLMs.
|
||||
|
||||
Guarantees:
|
||||
1. Robust JSON extraction across markdown wrappers and conversational noise.
|
||||
2. Case-insensitive enum normalization with clinical synonym mapping.
|
||||
3. Strict evidence grounding: checks that evidence_text exists verbatim in the source document.
|
||||
4. Automatic resolution of character offsets, sections, and page numbers from documentary text.
|
||||
5. Zero hallucination: drops candidate conditions if evidence is completely absent from the text.
|
||||
"""
|
||||
|
||||
def parse_and_validate(
|
||||
self,
|
||||
raw_llm_output: str,
|
||||
document_text: str,
|
||||
clinical_doc: ClinicalPDFDocument | None = None,
|
||||
) -> tuple[list[ExtractedClinicalCondition], list[str], bool]:
|
||||
"""Parse raw LLM response into validated ExtractedClinicalCondition models.
|
||||
|
||||
Args:
|
||||
raw_llm_output: Unprocessed text emitted by the LLM.
|
||||
document_text: The source clinical text the LLM analyzed.
|
||||
clinical_doc: Optional structured ClinicalPDFDocument for exact page/section mapping.
|
||||
|
||||
Returns:
|
||||
(validated_conditions, audit_notes, repair_applied)
|
||||
"""
|
||||
audit_notes: list[str] = []
|
||||
repair_applied = False
|
||||
|
||||
if not raw_llm_output or not raw_llm_output.strip():
|
||||
audit_notes.append("Raw LLM response was empty.")
|
||||
return [], audit_notes, False
|
||||
|
||||
# 1. Clean markdown code fences and extract JSON substring
|
||||
cleaned_text = self._strip_markdown_and_extract_json(raw_llm_output)
|
||||
if cleaned_text != raw_llm_output:
|
||||
repair_applied = True
|
||||
|
||||
parsed_json: Any = None
|
||||
try:
|
||||
parsed_json = json.loads(cleaned_text)
|
||||
except json.JSONDecodeError as exc:
|
||||
logger.warning(
|
||||
"Initial JSON parse failed: %s. Applying syntax repair heuristics...", exc
|
||||
)
|
||||
repaired_text = self._repair_json_syntax(cleaned_text)
|
||||
try:
|
||||
parsed_json = json.loads(repaired_text)
|
||||
repair_applied = True
|
||||
audit_notes.append("Applied syntax repair to malformed LLM JSON.")
|
||||
except Exception as repair_exc:
|
||||
logger.error("JSON repair heuristics failed: %s", repair_exc)
|
||||
audit_notes.append(f"Failed to parse LLM output as JSON: {exc}")
|
||||
return [], audit_notes, repair_applied
|
||||
|
||||
if not isinstance(parsed_json, list):
|
||||
if (
|
||||
isinstance(parsed_json, dict)
|
||||
and "conditions" in parsed_json
|
||||
and isinstance(parsed_json["conditions"], list)
|
||||
):
|
||||
parsed_json = parsed_json["conditions"]
|
||||
elif isinstance(parsed_json, dict):
|
||||
parsed_json = [parsed_json]
|
||||
else:
|
||||
audit_notes.append("Parsed JSON was not a list of candidate conditions.")
|
||||
return [], audit_notes, repair_applied
|
||||
|
||||
# 2. Validate, ground, and normalize each condition item
|
||||
validated_conditions: list[ExtractedClinicalCondition] = []
|
||||
norm_source = self._normalize_for_matching(document_text)
|
||||
|
||||
for idx, item in enumerate(parsed_json):
|
||||
if not isinstance(item, dict):
|
||||
audit_notes.append(f"Skipping non-dict condition at index {idx}.")
|
||||
continue
|
||||
|
||||
# Ensure minimum required fields exist
|
||||
mention = str(item.get("original_mention") or item.get("raw_term") or "").strip()
|
||||
evidence = str(item.get("evidence_text") or item.get("evidence_quote") or "").strip()
|
||||
|
||||
if not mention:
|
||||
audit_notes.append(f"Item #{idx} missing original_mention; discarded.")
|
||||
continue
|
||||
|
||||
# CRITICAL RULE: Every diagnosis must have evidence
|
||||
if not evidence:
|
||||
audit_notes.append(f"Item '{mention}' discarded: No evidence_text provided by LLM.")
|
||||
continue
|
||||
|
||||
# Check evidence grounding in source document
|
||||
span_found = self._locate_evidence_in_text(evidence, document_text, norm_source)
|
||||
if span_found is None:
|
||||
# Evidence could not be located in document
|
||||
audit_notes.append(
|
||||
f"Item '{mention}' discarded: evidence quote '{evidence[:60]}...' not found in source document."
|
||||
)
|
||||
continue
|
||||
|
||||
start_char, end_char = span_found
|
||||
|
||||
# Resolve page number and section
|
||||
page_num, sec_name = self._resolve_location_metadata(
|
||||
start_char=start_char,
|
||||
clinical_doc=clinical_doc,
|
||||
claimed_section=item.get("section"),
|
||||
)
|
||||
|
||||
# Map enums safely
|
||||
certainty = self._normalize_certainty(item.get("certainty"))
|
||||
temporality = self._normalize_temporality(item.get("temporality"))
|
||||
status = self._normalize_status(item.get("status"), temporality, certainty)
|
||||
negation = self._normalize_negation(item.get("negation"))
|
||||
laterality = self._normalize_laterality(item.get("laterality"))
|
||||
entity_type = self._normalize_entity_type(item.get("entity_type"))
|
||||
|
||||
norm_desc = str(item.get("normalized_description") or mention).strip()
|
||||
|
||||
condition = ExtractedClinicalCondition(
|
||||
original_mention=mention,
|
||||
normalized_description=norm_desc,
|
||||
entity_type=entity_type,
|
||||
evidence_text=evidence,
|
||||
evidence_location=EvidenceLocation(
|
||||
section=sec_name,
|
||||
page_number=page_num,
|
||||
start_char=start_char,
|
||||
end_char=end_char,
|
||||
),
|
||||
status=status,
|
||||
certainty=certainty,
|
||||
temporality=temporality,
|
||||
negation=negation,
|
||||
anatomical_site=item.get("anatomical_site") or None,
|
||||
laterality=laterality,
|
||||
section=sec_name,
|
||||
treatment_evidence=item.get("treatment_evidence") or None,
|
||||
confidence_score=float(item.get("confidence_score", 1.0)),
|
||||
)
|
||||
|
||||
validated_conditions.append(condition)
|
||||
|
||||
audit_notes.append(
|
||||
f"Successfully extracted and validated {len(validated_conditions)} conditions."
|
||||
)
|
||||
return validated_conditions, audit_notes, repair_applied
|
||||
|
||||
def _strip_markdown_and_extract_json(self, text: str) -> str:
|
||||
"""Strip markdown fences, leading explanations, and isolate the JSON array."""
|
||||
cleaned = text.strip()
|
||||
|
||||
# Handle ```json ... ``` or ``` ... ```
|
||||
if "```" in cleaned:
|
||||
match = re.search(r"```(?:json)?\s*(\[.*?\])\s*```", cleaned, re.DOTALL)
|
||||
if match:
|
||||
return match.group(1).strip()
|
||||
# If no closing block or opening block, strip ``` lines
|
||||
cleaned = re.sub(r"```(?:json)?", "", cleaned).replace("```", "").strip()
|
||||
|
||||
# Isolate substring starting at first '[' and ending at last ']'
|
||||
start_idx = cleaned.find("[")
|
||||
end_idx = cleaned.rfind("]")
|
||||
if start_idx != -1 and end_idx != -1 and end_idx > start_idx:
|
||||
return cleaned[start_idx : end_idx + 1].strip()
|
||||
|
||||
return cleaned
|
||||
|
||||
def _repair_json_syntax(self, text: str) -> str:
|
||||
"""Apply heuristics to repair common LLM JSON syntax errors without hallucinating facts."""
|
||||
repaired = text
|
||||
|
||||
# Replace single quotes with double quotes around JSON keys and string values
|
||||
# e.g. {'key': 'value'} -> {"key": "value"}
|
||||
repaired = re.sub(r"(?<=[\{\s,\[])'([a-zA-Z0-9_\s\-]+)'(?=\s*:)", r'"\1"', repaired)
|
||||
repaired = re.sub(r":\s*'([^']*)'", r': "\1"', repaired)
|
||||
|
||||
# Remove trailing commas before closing braces/brackets: e.g. , ] -> ] and , } -> }
|
||||
repaired = re.sub(r",\s*([\]\}])", r"\1", repaired)
|
||||
|
||||
# Replace invalid unquoted literals or None -> null
|
||||
repaired = re.sub(r"\bNone\b", "null", repaired)
|
||||
repaired = re.sub(r"\bTrue\b", "true", repaired)
|
||||
repaired = re.sub(r"\bFalse\b", "false", repaired)
|
||||
|
||||
return repaired
|
||||
|
||||
def _normalize_for_matching(self, text: str) -> str:
|
||||
"""Normalize whitespace and case for relaxed quote matching."""
|
||||
return re.sub(r"\s+", " ", text).strip().lower()
|
||||
|
||||
def _locate_evidence_in_text(
|
||||
self,
|
||||
quote: str,
|
||||
original_text: str,
|
||||
norm_source: str,
|
||||
) -> tuple[int, int] | None:
|
||||
"""Verify quote exists in original text and return exact start/end character offsets."""
|
||||
if not quote:
|
||||
return None
|
||||
|
||||
# 1. Exact verbatim match
|
||||
start = original_text.find(quote)
|
||||
if start != -1:
|
||||
return start, start + len(quote)
|
||||
|
||||
# 2. Case-insensitive exact match
|
||||
lower_orig = original_text.lower()
|
||||
lower_quote = quote.lower()
|
||||
start = lower_orig.find(lower_quote)
|
||||
if start != -1:
|
||||
return start, start + len(quote)
|
||||
|
||||
# 3. Whitespace-normalized match
|
||||
norm_quote = self._normalize_for_matching(quote)
|
||||
start_norm = norm_source.find(norm_quote)
|
||||
if start_norm != -1:
|
||||
# Estimate reasonable span in original text
|
||||
approx_start = max(0, start_norm)
|
||||
approx_end = min(len(original_text), approx_start + len(quote) + 10)
|
||||
return approx_start, approx_end
|
||||
|
||||
return None
|
||||
|
||||
def _resolve_location_metadata(
|
||||
self,
|
||||
start_char: int,
|
||||
clinical_doc: ClinicalPDFDocument | None,
|
||||
claimed_section: str | None,
|
||||
) -> tuple[int, str]:
|
||||
"""Resolve page number and section name from clinical document offsets."""
|
||||
page_num = 1
|
||||
sec_name = str(claimed_section or "CLINICAL_DOCUMENT").upper().strip()
|
||||
|
||||
if clinical_doc is not None:
|
||||
page_num = clinical_doc.find_page_number_for_char(start_char)
|
||||
# Find matching section containing this character
|
||||
for s in clinical_doc.sections:
|
||||
if s.start_char <= start_char <= s.end_char:
|
||||
sec_name = s.section_type
|
||||
break
|
||||
|
||||
return page_num, sec_name
|
||||
|
||||
def _normalize_certainty(self, val: Any) -> Certainty:
|
||||
"""Map certainty strings to standardized Certainty enum."""
|
||||
s = str(val or "").strip().upper()
|
||||
if "RULE" in s or "EXCLUD" in s or "DENI" in s:
|
||||
return Certainty.RULED_OUT
|
||||
if "SUSPECT" in s or "PROBAB" in s:
|
||||
return Certainty.SUSPECTED
|
||||
if "POSSIB" in s or "POTENTIAL" in s or "DIFFERENTIAL" in s:
|
||||
return Certainty.POSSIBLE
|
||||
if "CONFIRM" in s or "DEFINIT" in s or "POSITIVE" in s or "ACTIVE" in s:
|
||||
return Certainty.CONFIRMED
|
||||
return Certainty.CONFIRMED if not s else Certainty.UNKNOWN
|
||||
|
||||
def _normalize_temporality(self, val: Any) -> Temporality:
|
||||
"""Map temporality strings to standardized Temporality enum."""
|
||||
s = str(val or "").strip().upper()
|
||||
if "RESOLV" in s or "CURED" in s:
|
||||
return Temporality.RESOLVED
|
||||
if "HISTOR" in s or "PAST" in s or "PMH" in s or "PRIOR" in s:
|
||||
return Temporality.HISTORICAL
|
||||
if "CURRENT" in s or "PRESENT" in s or "ACTIVE" in s or "ADMISSION" in s:
|
||||
return Temporality.CURRENT
|
||||
if "FAMILY" in s:
|
||||
return Temporality.FAMILY_HISTORY
|
||||
return Temporality.CURRENT
|
||||
|
||||
def _normalize_status(
|
||||
self, val: Any, temporality: Temporality, certainty: Certainty
|
||||
) -> ConditionStatus:
|
||||
"""Map status with consistency checks against temporality and certainty."""
|
||||
if certainty == Certainty.RULED_OUT:
|
||||
return ConditionStatus.RESOLVED
|
||||
if temporality == Temporality.RESOLVED:
|
||||
return ConditionStatus.RESOLVED
|
||||
if temporality == Temporality.HISTORICAL:
|
||||
return ConditionStatus.HISTORICAL
|
||||
|
||||
s = str(val or "").strip().upper()
|
||||
if "RESOLV" in s:
|
||||
return ConditionStatus.RESOLVED
|
||||
if "HISTOR" in s or "PAST" in s:
|
||||
return ConditionStatus.HISTORICAL
|
||||
if "CHRONIC" in s:
|
||||
return ConditionStatus.CHRONIC
|
||||
if "ACUTE" in s:
|
||||
return ConditionStatus.ACUTE
|
||||
if "ACTIVE" in s:
|
||||
return ConditionStatus.ACTIVE
|
||||
return ConditionStatus.ACTIVE
|
||||
|
||||
def _normalize_negation(self, val: Any) -> NegationStatus:
|
||||
"""Map negation strings to standardized NegationStatus enum."""
|
||||
s = str(val or "").strip().upper()
|
||||
if "NEG" in s or "NO" in s or "DENI" in s or "ABSENT" in s:
|
||||
return NegationStatus.NEGATED
|
||||
if "UNCERTAIN" in s or "EQUIVOCAL" in s:
|
||||
return NegationStatus.UNCERTAIN
|
||||
return NegationStatus.AFFIRMATIVE
|
||||
|
||||
def _normalize_laterality(self, val: Any) -> Laterality:
|
||||
"""Map laterality strings to standardized Laterality enum."""
|
||||
s = str(val or "").strip().upper()
|
||||
if "LEFT" in s:
|
||||
return Laterality.LEFT
|
||||
if "RIGHT" in s:
|
||||
return Laterality.RIGHT
|
||||
if "BILATERAL" in s or "BOTH" in s:
|
||||
return Laterality.BILATERAL
|
||||
return Laterality.UNSPECIFIED
|
||||
|
||||
def _normalize_entity_type(self, val: Any) -> ClinicalEntityType:
|
||||
"""Map entity type strings to standardized ClinicalEntityType enum."""
|
||||
s = str(val or "").strip().upper()
|
||||
if "SYMPTOM" in s:
|
||||
return ClinicalEntityType.SYMPTOM
|
||||
if "SIGN" in s:
|
||||
return ClinicalEntityType.SIGN
|
||||
if "PROCEDUR" in s:
|
||||
return ClinicalEntityType.PROCEDURAL_FINDING
|
||||
return ClinicalEntityType.DIAGNOSIS
|
||||
@@ -0,0 +1,505 @@
|
||||
"""Candidate ranking agent selecting strictly from retrieved local ICD-10-CM codes."""
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.agents.base import BaseAgent
|
||||
from medical_coding.models.base import BaseLocalLLM
|
||||
from medical_coding.prompts.ranking import (
|
||||
RANKING_SYSTEM_PROMPT,
|
||||
RANKING_USER_TEMPLATE,
|
||||
)
|
||||
from medical_coding.schemas.clinical import ClassifiedDiagnosis, ConditionClassification
|
||||
from medical_coding.schemas.enums import DiagnosisRole
|
||||
from medical_coding.schemas.icd import ICDCandidate, RankedSelection
|
||||
from medical_coding.utils.logging import get_logger
|
||||
from medical_coding.utils.text import format_icd_code
|
||||
from medical_coding.validation.deterministic import (
|
||||
CandidateRankingDeterministicValidator,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class CandidateRankingAgent(BaseAgent):
|
||||
"""Evaluates retrieved local ICD candidates against evidence to select best match or abstain.
|
||||
|
||||
CORE ARCHITECTURAL INVARIANTS:
|
||||
1. The candidate ranking agent answers:
|
||||
"Which of these retrieved ICD codes is best supported by the documented clinical evidence?"
|
||||
It does NOT answer:
|
||||
"What ICD code do I know for this diagnosis?"
|
||||
2. Selected code MUST exist in the supplied candidate list.
|
||||
3. The LLM may NEVER generate or invent a new ICD code.
|
||||
4. Unsupported clinical specificity is blocked.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
llm: BaseLocalLLM | None = None,
|
||||
validator: CandidateRankingDeterministicValidator | None = None,
|
||||
min_confidence: float = 0.40,
|
||||
allow_rerun: bool = False,
|
||||
) -> None:
|
||||
super().__init__(llm) # type: ignore[arg-type]
|
||||
self.system_prompt = RANKING_SYSTEM_PROMPT
|
||||
self.user_template = RANKING_USER_TEMPLATE
|
||||
self.validator = validator or CandidateRankingDeterministicValidator(
|
||||
min_confidence=min_confidence
|
||||
)
|
||||
self.min_confidence = min_confidence
|
||||
self.allow_rerun = allow_rerun
|
||||
|
||||
def rank_candidates(
|
||||
self,
|
||||
condition: ClassifiedDiagnosis | ConditionClassification | Any,
|
||||
candidates: list[ICDCandidate],
|
||||
evidence_override: str | None = None,
|
||||
role_override: str | None = None,
|
||||
allow_rerun: bool | None = None,
|
||||
) -> RankedSelection:
|
||||
"""Evaluate candidate codes and select the best match or explicitly abstain.
|
||||
|
||||
Args:
|
||||
condition: Diagnosis mention, classified condition, or dict with clinical attributes.
|
||||
candidates: Top-K retrieved ICD-10-CM candidates from the local dataset.
|
||||
evidence_override: Optional explicit evidence quote override.
|
||||
role_override: Optional explicit role override.
|
||||
allow_rerun: Override for single retry on invalid code output.
|
||||
|
||||
Returns:
|
||||
RankedSelection with selected_code, selected_description, ranking_reason,
|
||||
supporting_evidence, confidence, and abstention_reason.
|
||||
"""
|
||||
# 1. Normalize and extract condition details
|
||||
diag_id, raw_term, evidence_quote, role, acuity, certainty, anatomy, laterality = (
|
||||
self._extract_condition_attributes(condition, evidence_override, role_override)
|
||||
)
|
||||
|
||||
# 2. Short-circuit: Empty candidate pool -> Immediate Abstention (No LLM call)
|
||||
if not candidates:
|
||||
logger.info(
|
||||
"Candidate pool is empty for '%s'; abstaining immediately without LLM.", raw_term
|
||||
)
|
||||
return self.validator.validate_ranking_selection(
|
||||
selection=RankedSelection(
|
||||
diagnosis_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
ranking_reason="Candidate pool was empty; no matching local ICD code.",
|
||||
supporting_evidence=[evidence_quote] if evidence_quote else [],
|
||||
confidence=0.0,
|
||||
abstention_reason="NO_CANDIDATES",
|
||||
candidate_pool=[],
|
||||
decision="ABSTAINED",
|
||||
),
|
||||
candidates=[],
|
||||
evidence_text=evidence_quote,
|
||||
diagnosis_term=raw_term,
|
||||
)
|
||||
|
||||
# 3. Short-circuit: Insufficient / missing evidence -> Immediate Abstention
|
||||
if not evidence_quote.strip():
|
||||
logger.info("Documentation lacks evidence quote for '%s'; abstaining.", raw_term)
|
||||
return self.validator.validate_ranking_selection(
|
||||
selection=RankedSelection(
|
||||
diagnosis_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
ranking_reason="Insufficient evidence: documentation lacks factual evidence quote.",
|
||||
supporting_evidence=[],
|
||||
confidence=0.0,
|
||||
abstention_reason="INSUFFICIENT_EVIDENCE",
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
),
|
||||
candidates=candidates,
|
||||
evidence_text="",
|
||||
diagnosis_term=raw_term,
|
||||
)
|
||||
|
||||
# 4. Short-circuit: Excluded condition -> Immediate Abstention
|
||||
if role == DiagnosisRole.EXCLUDED or role == "EXCLUDED":
|
||||
logger.info("Condition '%s' is marked as EXCLUDED; abstaining from coding.", raw_term)
|
||||
return self.validator.validate_ranking_selection(
|
||||
selection=RankedSelection(
|
||||
diagnosis_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
ranking_reason=f"Condition '{raw_term}' is excluded from billing/coding.",
|
||||
supporting_evidence=[evidence_quote],
|
||||
confidence=0.0,
|
||||
abstention_reason="CONDITION_EXCLUDED",
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
),
|
||||
candidates=candidates,
|
||||
evidence_text=evidence_quote,
|
||||
diagnosis_term=raw_term,
|
||||
)
|
||||
|
||||
# 5. Format candidates into bounded prompt context
|
||||
candidates_formatted = self._format_candidates(candidates)
|
||||
prompt = self._build_prompt(
|
||||
diagnosis_term=raw_term,
|
||||
evidence_quote=evidence_quote,
|
||||
role=str(role),
|
||||
acuity=str(acuity),
|
||||
certainty=str(certainty),
|
||||
anatomical_site=str(anatomy or "Not documented"),
|
||||
laterality=str(laterality or "Unspecified"),
|
||||
candidates_formatted=candidates_formatted,
|
||||
)
|
||||
|
||||
# 6. Execute LLM inference or deterministic evaluation
|
||||
initial_selection: RankedSelection | None = None
|
||||
if self.llm is not None:
|
||||
initial_selection = self._execute_llm_ranking(
|
||||
prompt, diag_id, raw_term, evidence_quote, candidates
|
||||
)
|
||||
|
||||
# Fallback to deterministic scoring if LLM was unavailable or produced unparseable output
|
||||
if initial_selection is None:
|
||||
initial_selection = self._evaluate_candidates_deterministically(
|
||||
diag_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
evidence_quote=evidence_quote,
|
||||
acuity=acuity,
|
||||
candidates=candidates,
|
||||
)
|
||||
|
||||
# 7. Check Hard Constraint: Is proposed code in candidates list?
|
||||
rerun_flag = self.allow_rerun if allow_rerun is None else allow_rerun
|
||||
if (
|
||||
initial_selection.selected_code is not None
|
||||
and not any(
|
||||
format_icd_code(initial_selection.selected_code) == format_icd_code(c.code)
|
||||
for c in candidates
|
||||
)
|
||||
and rerun_flag
|
||||
and self.llm is not None
|
||||
):
|
||||
# One retry with explicit error feedback
|
||||
logger.warning(
|
||||
"LLM proposed invalid code '%s' not in candidates. Triggering single rerun with bounded instruction.",
|
||||
initial_selection.selected_code,
|
||||
)
|
||||
rerun_prompt = (
|
||||
f"{prompt}\n\n"
|
||||
f"CORRECTION ERROR: Your previous selection '{initial_selection.selected_code}' is NOT in the candidate list.\n"
|
||||
f"You are strictly forbidden from inventing codes. Choose ONLY from: {[c.code for c in candidates]} or output null.\n"
|
||||
f"Output valid JSON only:"
|
||||
)
|
||||
initial_selection = (
|
||||
self._execute_llm_ranking(
|
||||
rerun_prompt, diag_id, raw_term, evidence_quote, candidates
|
||||
)
|
||||
or initial_selection
|
||||
)
|
||||
|
||||
# 8. Deterministic Validation immediately after LLM
|
||||
validated_selection = self.validator.validate_ranking_selection(
|
||||
selection=initial_selection,
|
||||
candidates=candidates,
|
||||
evidence_text=evidence_quote,
|
||||
diagnosis_term=raw_term,
|
||||
)
|
||||
|
||||
return validated_selection
|
||||
|
||||
def run(self, **kwargs: Any) -> RankedSelection:
|
||||
"""Standard pipeline invocation interface."""
|
||||
condition = kwargs.get("condition")
|
||||
candidates = kwargs.get("candidates", [])
|
||||
evidence_override = kwargs.get("evidence")
|
||||
role_override = kwargs.get("role")
|
||||
return self.rank_candidates(
|
||||
condition=condition,
|
||||
candidates=candidates,
|
||||
evidence_override=evidence_override,
|
||||
role_override=role_override,
|
||||
)
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Internal Helpers
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _extract_condition_attributes(
|
||||
self,
|
||||
condition: Any,
|
||||
evidence_override: str | None,
|
||||
role_override: str | None,
|
||||
) -> tuple[str, str, str, str, str, str, str | None, str | None]:
|
||||
"""Extract and normalize clinical attributes across various diagnosis representations."""
|
||||
diag_id = "diag-unknown"
|
||||
raw_term = "Unknown Diagnosis"
|
||||
evidence_quote = ""
|
||||
role = "SECONDARY"
|
||||
acuity = "UNSPECIFIED"
|
||||
certainty = "CONFIRMED"
|
||||
anatomy = None
|
||||
laterality = "UNSPECIFIED"
|
||||
|
||||
if hasattr(condition, "diagnosis_id"):
|
||||
diag_id = str(condition.diagnosis_id)
|
||||
if hasattr(condition, "raw_term"):
|
||||
raw_term = str(condition.raw_term)
|
||||
elif hasattr(condition, "diagnosis"):
|
||||
raw_term = str(condition.diagnosis)
|
||||
|
||||
# Evidence resolution
|
||||
if evidence_override:
|
||||
evidence_quote = evidence_override
|
||||
elif hasattr(condition, "evidence_quote") and condition.evidence_quote:
|
||||
evidence_quote = condition.evidence_quote
|
||||
elif hasattr(condition, "evidence_text") and condition.evidence_text:
|
||||
evidence_quote = condition.evidence_text
|
||||
elif hasattr(condition, "context") and hasattr(condition.context, "evidence"):
|
||||
evidence_quote = getattr(condition.context.evidence, "quote", "")
|
||||
|
||||
# Role resolution
|
||||
if role_override:
|
||||
role = role_override
|
||||
elif hasattr(condition, "role"):
|
||||
role = str(condition.role.value if hasattr(condition.role, "value") else condition.role)
|
||||
|
||||
# Context details
|
||||
if hasattr(condition, "context"):
|
||||
ctx = condition.context
|
||||
if hasattr(ctx, "acuity"):
|
||||
acuity = str(ctx.acuity.value if hasattr(ctx.acuity, "value") else ctx.acuity)
|
||||
if hasattr(ctx, "certainty"):
|
||||
certainty = str(
|
||||
ctx.certainty.value if hasattr(ctx.certainty, "value") else ctx.certainty
|
||||
)
|
||||
|
||||
if hasattr(condition, "anatomical_site") and condition.anatomical_site:
|
||||
anatomy = str(condition.anatomical_site)
|
||||
if hasattr(condition, "laterality"):
|
||||
laterality = str(
|
||||
condition.laterality.value
|
||||
if hasattr(condition.laterality, "value")
|
||||
else condition.laterality
|
||||
)
|
||||
|
||||
return diag_id, raw_term, evidence_quote, role, acuity, certainty, anatomy, laterality
|
||||
|
||||
def _format_candidates(self, candidates: list[ICDCandidate]) -> str:
|
||||
"""Format candidate list with indices and clinical details for the prompt."""
|
||||
lines: list[str] = []
|
||||
for i, c in enumerate(candidates, start=1):
|
||||
billable_str = "Billable" if c.is_valid_billable else "Non-Billable Header"
|
||||
lines.append(
|
||||
f"Candidate [{i}]: Code: {c.code} | Description: {c.description} | "
|
||||
f"Retrieval Score: {c.retrieval_score:.4f} | Status: {billable_str}"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
def _build_prompt(
|
||||
self,
|
||||
diagnosis_term: str,
|
||||
evidence_quote: str,
|
||||
role: str,
|
||||
acuity: str,
|
||||
certainty: str,
|
||||
anatomical_site: str,
|
||||
laterality: str,
|
||||
candidates_formatted: str,
|
||||
) -> str:
|
||||
"""Construct prompt combining system instructions and formatted clinical parameters."""
|
||||
user_body = self.user_template.format(
|
||||
diagnosis_term=diagnosis_term,
|
||||
evidence_quote=evidence_quote,
|
||||
role=role,
|
||||
acuity=acuity,
|
||||
certainty=certainty,
|
||||
anatomical_site=anatomical_site,
|
||||
laterality=laterality,
|
||||
candidates_formatted=candidates_formatted,
|
||||
)
|
||||
return f"{self.system_prompt}\n\n{user_body}"
|
||||
|
||||
def _execute_llm_ranking(
|
||||
self,
|
||||
prompt: str,
|
||||
diag_id: str,
|
||||
raw_term: str,
|
||||
evidence_quote: str,
|
||||
candidates: list[ICDCandidate],
|
||||
) -> RankedSelection | None:
|
||||
"""Execute LLM call and parse structured response."""
|
||||
try:
|
||||
assert self.llm is not None
|
||||
response_text = self.llm.generate(prompt=prompt, max_tokens=512, temperature=0.0)
|
||||
if not response_text or not response_text.strip():
|
||||
return None
|
||||
|
||||
json_match = re.search(r"(\{.*\})", response_text, re.DOTALL)
|
||||
if not json_match:
|
||||
return None
|
||||
|
||||
parsed = json.loads(json_match.group(1))
|
||||
|
||||
raw_code = parsed.get("selected_code")
|
||||
code_str = (
|
||||
str(raw_code).strip() if raw_code and str(raw_code).lower() != "null" else None
|
||||
)
|
||||
desc_str = parsed.get("selected_description")
|
||||
reason = parsed.get("ranking_reason") or parsed.get("justification", "")
|
||||
confidence = float(parsed.get("confidence", parsed.get("confidence_score", 0.85)))
|
||||
decision = parsed.get("decision", "ACCEPTED" if code_str else "ABSTAINED")
|
||||
abstention_reason = parsed.get("abstention_reason")
|
||||
|
||||
return RankedSelection(
|
||||
diagnosis_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
selected_code=code_str,
|
||||
selected_description=desc_str,
|
||||
ranking_reason=reason,
|
||||
supporting_evidence=[evidence_quote],
|
||||
confidence=confidence,
|
||||
abstention_reason=abstention_reason,
|
||||
candidate_pool=candidates,
|
||||
decision=decision,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("Error executing LLM ranking: %s. Using deterministic evaluation.", e)
|
||||
return None
|
||||
|
||||
def _evaluate_candidates_deterministically(
|
||||
self,
|
||||
diag_id: str,
|
||||
raw_term: str,
|
||||
evidence_quote: str,
|
||||
acuity: str,
|
||||
candidates: list[ICDCandidate],
|
||||
) -> RankedSelection:
|
||||
"""Deterministic evidence-based candidate scoring when offline or in test environments."""
|
||||
evidence_clean = (evidence_quote or "").lower()
|
||||
term_clean = (raw_term or "").lower()
|
||||
full_context = f"{term_clean} {evidence_clean}"
|
||||
|
||||
scored_candidates: list[tuple[ICDCandidate, float, str]] = []
|
||||
|
||||
for cand in candidates:
|
||||
score = cand.retrieval_score
|
||||
desc_lower = cand.description.lower()
|
||||
rationale_parts: list[str] = []
|
||||
|
||||
# 1. Non-billable penalty
|
||||
if not cand.is_valid_billable:
|
||||
score *= 0.5
|
||||
rationale_parts.append("non-billable category header")
|
||||
|
||||
# 2. Terminology and specific descriptor matches
|
||||
cand_tokens = [t for t in re.findall(r"[a-z0-9]+", desc_lower) if len(t) > 2]
|
||||
overlap = [t for t in cand_tokens if t in full_context]
|
||||
if overlap:
|
||||
score += 0.15 * (len(overlap) / len(cand_tokens))
|
||||
|
||||
# 3. Acuity alignment
|
||||
is_acute_doc = any(
|
||||
w in full_context
|
||||
for w in ["acute", "exacerbation", "decompensated", "decompensation"]
|
||||
)
|
||||
is_chronic_doc = any(
|
||||
w in full_context for w in ["chronic", "compensated", "longstanding"]
|
||||
)
|
||||
|
||||
is_acute_cand = "acute" in desc_lower and "chronic" not in desc_lower
|
||||
is_chronic_cand = "chronic" in desc_lower and "acute" not in desc_lower
|
||||
is_acute_on_chronic_cand = "acute on chronic" in desc_lower or (
|
||||
"acute" in desc_lower and "chronic" in desc_lower
|
||||
)
|
||||
|
||||
if is_acute_on_chronic_cand:
|
||||
if is_acute_doc and is_chronic_doc:
|
||||
score += 0.25
|
||||
rationale_parts.append("acute on chronic documentation match")
|
||||
elif not is_acute_doc or not is_chronic_doc:
|
||||
score -= 0.30
|
||||
elif is_acute_cand:
|
||||
if is_acute_doc and not is_chronic_doc:
|
||||
score += 0.20
|
||||
rationale_parts.append("acute acuity match")
|
||||
elif is_chronic_doc and not is_acute_doc:
|
||||
score -= 0.25
|
||||
elif is_chronic_cand:
|
||||
if is_chronic_doc and not is_acute_doc:
|
||||
score += 0.20
|
||||
rationale_parts.append("chronic acuity match")
|
||||
elif is_acute_doc and not is_chronic_doc:
|
||||
score -= 0.25
|
||||
|
||||
# 4. Specificity penalty for unsupported subtypes
|
||||
# Heart failure: systolic / diastolic
|
||||
if "systolic" in desc_lower and not any(
|
||||
w in full_context for w in ["systolic", "hfref", "reduced ejection"]
|
||||
):
|
||||
score = 0.05
|
||||
rationale_parts.append("unsupported systolic specificity")
|
||||
if "diastolic" in desc_lower and not any(
|
||||
w in full_context for w in ["diastolic", "hfpef", "preserved ejection"]
|
||||
):
|
||||
score = 0.05
|
||||
rationale_parts.append("unsupported diastolic specificity")
|
||||
|
||||
# Diabetes complications
|
||||
if any(
|
||||
comp in desc_lower
|
||||
for comp in ["nephropathy", "retinopathy", "neuropathy", "hyperglycemia"]
|
||||
):
|
||||
if not any(
|
||||
comp in full_context
|
||||
for comp in [
|
||||
"nephropathy",
|
||||
"kidney",
|
||||
"retinopathy",
|
||||
"neuropathy",
|
||||
"hyperglycemia",
|
||||
"uncontrolled",
|
||||
]
|
||||
):
|
||||
score = 0.05
|
||||
rationale_parts.append("unsupported complication specificity")
|
||||
|
||||
clamped_score = max(0.0, min(1.0, round(score, 4)))
|
||||
scored_candidates.append(
|
||||
(cand, clamped_score, ", ".join(rationale_parts) or "evidence overlap")
|
||||
)
|
||||
|
||||
# Sort descending by score
|
||||
scored_candidates.sort(key=lambda x: x[1], reverse=True)
|
||||
top_cand, top_score, top_rationale = scored_candidates[0]
|
||||
|
||||
if top_score < self.min_confidence:
|
||||
return RankedSelection(
|
||||
diagnosis_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
ranking_reason=f"No candidate met the minimum confidence threshold ({top_score:.2f} < {self.min_confidence:.2f}).",
|
||||
supporting_evidence=[evidence_quote],
|
||||
confidence=top_score,
|
||||
abstention_reason="CONFIDENCE_BELOW_THRESHOLD",
|
||||
candidate_pool=candidates,
|
||||
decision="REJECTED_LOW_CONFIDENCE",
|
||||
)
|
||||
|
||||
return RankedSelection(
|
||||
diagnosis_id=diag_id,
|
||||
raw_term=raw_term,
|
||||
selected_code=top_cand.code,
|
||||
selected_description=top_cand.description,
|
||||
selected_candidate=top_cand,
|
||||
ranking_reason=f"Candidate '{top_cand.code}' ({top_cand.description}) best supported by documentation ({top_rationale}).",
|
||||
supporting_evidence=[evidence_quote],
|
||||
confidence=top_score,
|
||||
abstention_reason=None,
|
||||
candidate_pool=candidates,
|
||||
decision="ACCEPTED",
|
||||
)
|
||||
@@ -0,0 +1,5 @@
|
||||
"""API package exports."""
|
||||
|
||||
from medical_coding.api.app import app, create_app
|
||||
|
||||
__all__ = ["app", "create_app"]
|
||||
@@ -0,0 +1,59 @@
|
||||
"""FastAPI application factory for the local medical coding service."""
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from medical_coding.api.routes import router
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
from medical_coding.utils.logging import configure_logging, get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||
"""Application startup and shutdown lifecycle management."""
|
||||
settings: Settings = app.state.settings
|
||||
configure_logging(settings)
|
||||
logger.info("Initializing Local Medical ICD-10-CM Coding Service...")
|
||||
logger.info("Operating Mode: OFFLINE (Cloud APIs strictly prohibited)")
|
||||
logger.info("Configured LLM path: %s", settings.llm_model_path)
|
||||
logger.info("Configured ICD dataset: %s", settings.icd_dataset_path)
|
||||
|
||||
yield
|
||||
|
||||
logger.info("Shutting down Medical Coding Service.")
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
"""Instantiate and configure the FastAPI application."""
|
||||
cfg = settings or get_settings()
|
||||
|
||||
application = FastAPI(
|
||||
title="Local Medical ICD-10-CM Coding System",
|
||||
description=(
|
||||
"Offline clinical coding pipeline using local GGUF models, hybrid retrieval, "
|
||||
"LangGraph state orchestration, and deterministic validation."
|
||||
),
|
||||
version="0.1.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
application.state.settings = cfg
|
||||
|
||||
application.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
application.include_router(router)
|
||||
return application
|
||||
|
||||
|
||||
app = create_app()
|
||||
@@ -0,0 +1,25 @@
|
||||
"""FastAPI dependency injection providers."""
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
from medical_coding.config.settings import get_settings
|
||||
from medical_coding.orchestration.pipeline import MedicalCodingPipeline
|
||||
from medical_coding.pdf.extractor import PDFExtractor
|
||||
from medical_coding.pdf.processor import BatchPDFProcessor
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def get_pipeline() -> MedicalCodingPipeline:
|
||||
"""Dependency provider for cached pipeline instance."""
|
||||
return MedicalCodingPipeline()
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def get_batch_processor() -> BatchPDFProcessor:
|
||||
"""Dependency provider for batch PDF processor."""
|
||||
settings = get_settings()
|
||||
extractor = PDFExtractor(max_pages=settings.pdf_max_pages)
|
||||
return BatchPDFProcessor(
|
||||
extractor=extractor,
|
||||
max_concurrency=settings.max_batch_concurrency,
|
||||
)
|
||||
@@ -0,0 +1,137 @@
|
||||
"""FastAPI routes for clinical document coding and offline status."""
|
||||
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, UploadFile, status
|
||||
|
||||
from medical_coding.api.dependencies import get_batch_processor, get_pipeline
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
from medical_coding.models.factory import ModelFactory
|
||||
from medical_coding.orchestration.pipeline import MedicalCodingPipeline
|
||||
from medical_coding.pdf.processor import BatchPDFProcessor
|
||||
from medical_coding.schemas.response import (
|
||||
BatchJobStatus,
|
||||
CodingResult,
|
||||
TextCodingRequest,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health", tags=["System"])
|
||||
async def health_check(settings: Settings = Depends(get_settings)) -> dict[str, Any]:
|
||||
"""Offline health check and local configuration diagnostics."""
|
||||
llm_health = ModelFactory.check_llm_health(settings)
|
||||
return {
|
||||
"status": "healthy" if llm_health.status != "unhealthy" else "unhealthy",
|
||||
"offline_mode": settings.offline_mode,
|
||||
"environment": settings.environment,
|
||||
"llm_model": str(settings.get_resolved_model_path()),
|
||||
"llm_health": {
|
||||
"status": llm_health.status,
|
||||
"file_exists": llm_health.file_exists,
|
||||
"file_size_bytes": llm_health.file_size_bytes,
|
||||
"is_loaded": llm_health.is_loaded,
|
||||
"load_count": llm_health.load_count,
|
||||
"inference_count": llm_health.inference_count,
|
||||
"max_llm_concurrency": llm_health.max_llm_concurrency,
|
||||
"details": llm_health.details,
|
||||
},
|
||||
"embedding_model": str(settings.embedding_model_path),
|
||||
"icd_dataset": str(settings.icd_dataset_path),
|
||||
"max_batch_concurrency": settings.max_batch_concurrency,
|
||||
"max_document_concurrency": settings.max_document_concurrency,
|
||||
}
|
||||
|
||||
|
||||
@router.post(
|
||||
"/api/v1/code/text",
|
||||
response_model=CodingResult,
|
||||
status_code=status.HTTP_200_OK,
|
||||
tags=["Coding"],
|
||||
)
|
||||
async def code_clinical_text(
|
||||
request: TextCodingRequest,
|
||||
pipeline: MedicalCodingPipeline = Depends(get_pipeline),
|
||||
) -> CodingResult:
|
||||
"""Analyze discharge summary text and return evidence-backed ICD-10-CM decisions."""
|
||||
doc_id = request.document_id or str(uuid4())
|
||||
return await pipeline.run_document(
|
||||
document_id=doc_id,
|
||||
text=request.text,
|
||||
metadata=request.metadata,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/api/v1/code/pdf",
|
||||
response_model=CodingResult,
|
||||
status_code=status.HTTP_200_OK,
|
||||
tags=["Coding"],
|
||||
)
|
||||
async def code_pdf_document(
|
||||
file: UploadFile,
|
||||
pipeline: MedicalCodingPipeline = Depends(get_pipeline),
|
||||
) -> CodingResult:
|
||||
"""Extract and code an uploaded PDF clinical discharge summary."""
|
||||
if not file.filename or not file.filename.lower().endswith(".pdf"):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="File must be a valid PDF document (.pdf extension required).",
|
||||
)
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp:
|
||||
tmp_path = Path(tmp.name)
|
||||
shutil.copyfileobj(file.file, tmp)
|
||||
|
||||
try:
|
||||
doc_id = str(uuid4())
|
||||
return await pipeline.run_document(
|
||||
document_id=doc_id,
|
||||
pdf_path=tmp_path,
|
||||
metadata={"filename": file.filename},
|
||||
)
|
||||
finally:
|
||||
if tmp_path.exists():
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/api/v1/code/batch-pdf",
|
||||
response_model=BatchJobStatus,
|
||||
status_code=status.HTTP_200_OK,
|
||||
tags=["Coding"],
|
||||
)
|
||||
async def code_batch_pdfs(
|
||||
files: list[UploadFile],
|
||||
pipeline: MedicalCodingPipeline = Depends(get_pipeline),
|
||||
batch_processor: BatchPDFProcessor = Depends(get_batch_processor),
|
||||
) -> BatchJobStatus:
|
||||
"""Process an asynchronous batch of clinical PDFs (supports >= 10 files concurrently)."""
|
||||
if not files:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="At least one PDF file must be provided.",
|
||||
)
|
||||
|
||||
temp_paths: list[Path] = []
|
||||
temp_dir = Path(tempfile.mkdtemp(prefix="batch_pdf_"))
|
||||
|
||||
try:
|
||||
for idx, file in enumerate(files):
|
||||
stem = Path(file.filename or f"doc_{idx}").stem
|
||||
dest = temp_dir / f"{stem}_{idx}.pdf"
|
||||
with open(dest, "wb") as f:
|
||||
shutil.copyfileobj(file.file, f)
|
||||
temp_paths.append(dest)
|
||||
|
||||
return await batch_processor.process_batch(
|
||||
pdf_paths=temp_paths,
|
||||
pipeline_executor=pipeline.run_document,
|
||||
)
|
||||
finally:
|
||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Configuration module exports."""
|
||||
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
|
||||
__all__ = ["Settings", "get_settings"]
|
||||
@@ -0,0 +1,248 @@
|
||||
"""Configuration management using Pydantic Settings and environment variables."""
|
||||
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import Field, field_validator, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""Application settings loaded from environment variables and .env file."""
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
extra="ignore",
|
||||
case_sensitive=False,
|
||||
)
|
||||
|
||||
# Environment & Diagnostics
|
||||
environment: Literal["development", "staging", "production", "test"] = "development"
|
||||
debug: bool = False
|
||||
offline_mode: bool = True
|
||||
|
||||
# Logging
|
||||
log_level: str = "INFO"
|
||||
log_json_format: bool = False
|
||||
|
||||
# Local LLM (GPT4All / GGUF) Configuration
|
||||
model_name: str = Field(
|
||||
default="mistral-7b-instruct-v0.2.Q4_K_M.gguf",
|
||||
description="GGUF model file name to load from local storage.",
|
||||
)
|
||||
model_path: Path = Field(
|
||||
default=Path("./models/gguf"),
|
||||
description="Directory or full path pointing to local GGUF model files.",
|
||||
)
|
||||
model_temperature: float = Field(
|
||||
default=0.0,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Sampling temperature; set to 0.0 for deterministic extraction.",
|
||||
)
|
||||
model_max_tokens: int = Field(
|
||||
default=1024,
|
||||
ge=16,
|
||||
le=8192,
|
||||
description="Maximum generation token ceiling.",
|
||||
)
|
||||
model_threads: int = Field(
|
||||
default=4,
|
||||
ge=1,
|
||||
description="CPU execution threads allocated for local GGUF inference.",
|
||||
)
|
||||
model_context_size: int = Field(
|
||||
default=2048,
|
||||
ge=256,
|
||||
le=32768,
|
||||
description="Context window size (n_ctx) allocated in GPT4All.",
|
||||
)
|
||||
|
||||
# Concurrency Architecture: Document-Level vs Model-Level
|
||||
max_document_concurrency: int = Field(
|
||||
default=10,
|
||||
ge=1,
|
||||
description="Maximum simultaneous asynchronous document extraction and pipeline tasks.",
|
||||
)
|
||||
max_llm_concurrency: int = Field(
|
||||
default=1,
|
||||
ge=1,
|
||||
description="Maximum simultaneous local LLM inferences (typically 1 on CPU to avoid cache thrashing).",
|
||||
)
|
||||
|
||||
# LLM Operational Limits & Generation Tuning
|
||||
llm_timeout_seconds: float = Field(
|
||||
default=120.0,
|
||||
ge=1.0,
|
||||
description="Maximum execution timeout in seconds for a single LLM inference call.",
|
||||
)
|
||||
llm_model_type: str = Field(
|
||||
default="llama",
|
||||
description="Architecture family for GPT4All (e.g. llama, mpt, replit).",
|
||||
)
|
||||
llm_top_k: int = Field(
|
||||
default=40,
|
||||
ge=1,
|
||||
description="Top-k sampling parameter for GPT4All generation.",
|
||||
)
|
||||
llm_top_p: float = Field(
|
||||
default=0.4,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Top-p sampling parameter for GPT4All generation.",
|
||||
)
|
||||
llm_repeat_penalty: float = Field(
|
||||
default=1.18,
|
||||
ge=0.0,
|
||||
description="Repetition penalty for GPT4All generation.",
|
||||
)
|
||||
|
||||
# Backwards-compatibility aliases
|
||||
llm_model_path: Path | None = Field(
|
||||
default=None,
|
||||
description="Optional full path alias for model_path / model_name.",
|
||||
)
|
||||
llm_n_threads: int | None = Field(
|
||||
default=None,
|
||||
description="Optional alias for model_threads.",
|
||||
)
|
||||
llm_max_tokens: int | None = Field(
|
||||
default=None,
|
||||
description="Optional alias for model_max_tokens.",
|
||||
)
|
||||
llm_temperature: float | None = Field(
|
||||
default=None,
|
||||
description="Optional alias for model_temperature.",
|
||||
)
|
||||
max_batch_concurrency: int | None = Field(
|
||||
default=None,
|
||||
description="Optional alias for max_document_concurrency.",
|
||||
)
|
||||
|
||||
# Local Dense Embedding Configuration
|
||||
embedding_model_path: Path = Field(
|
||||
default=Path("./models/embeddings/bge-small-en-v1.5"),
|
||||
description="Local directory containing offline SentenceTransformer model files.",
|
||||
)
|
||||
embedding_device: str = Field(
|
||||
default="cpu",
|
||||
description="Device for local embeddings: 'cpu', 'cuda', or 'mps'.",
|
||||
)
|
||||
|
||||
# Local ICD-10-CM Source Catalog & Pre-computed Index Directories
|
||||
icd_dataset_path: Path = Field(
|
||||
default=Path("./data/icd10/icd10cm_order_2026.txt"),
|
||||
description="Path to authoritative CMS/CDC ICD-10-CM order/tabular flat file.",
|
||||
)
|
||||
icd_index_dir: Path = Field(
|
||||
default=Path("./data/indexes"),
|
||||
description="Directory for persisted FAISS indices and BM25 tokenized caches.",
|
||||
)
|
||||
|
||||
# Database & Storage
|
||||
database_url: str = Field(
|
||||
default="sqlite:///./data/medical_coding.db",
|
||||
description="SQLAlchemy database connection URL (defaults to local SQLite database in ./data/).",
|
||||
)
|
||||
|
||||
# Retrieval Tuning Parameters
|
||||
bm25_top_k: int = Field(
|
||||
default=15,
|
||||
ge=1,
|
||||
description="Candidate count retrieved by lexical BM25 engine.",
|
||||
)
|
||||
faiss_top_k: int = Field(
|
||||
default=15,
|
||||
ge=1,
|
||||
description="Candidate count retrieved by dense FAISS vector engine.",
|
||||
)
|
||||
hybrid_top_k: int = Field(
|
||||
default=10,
|
||||
ge=1,
|
||||
description="Candidate pool size passed forward after hybrid rank fusion.",
|
||||
)
|
||||
min_candidate_score: float = Field(
|
||||
default=0.40,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Minimum similarity score below which candidate retrieval abstains.",
|
||||
)
|
||||
|
||||
# Asynchronous PDF Processing Guardrails
|
||||
pdf_max_pages: int = Field(
|
||||
default=50,
|
||||
ge=1,
|
||||
description="Guardrail ceiling on pages parsed per clinical PDF.",
|
||||
)
|
||||
pdf_timeout_seconds: int = Field(
|
||||
default=120,
|
||||
ge=5,
|
||||
description="Timeout per document extraction pipeline execution.",
|
||||
)
|
||||
|
||||
# FastAPI Server
|
||||
api_host: str = "0.0.0.0"
|
||||
api_port: int = 8000
|
||||
api_workers: int = 1
|
||||
|
||||
@field_validator("log_level", mode="before")
|
||||
@classmethod
|
||||
def normalize_log_level(cls, value: str) -> str:
|
||||
"""Ensure standard upper-case log levels."""
|
||||
return value.upper() if isinstance(value, str) else "INFO"
|
||||
|
||||
@model_validator(mode="after")
|
||||
def sync_legacy_aliases(self) -> "Settings":
|
||||
"""Synchronize legacy aliases with standard configuration fields."""
|
||||
if self.llm_n_threads is not None:
|
||||
self.model_threads = self.llm_n_threads
|
||||
else:
|
||||
self.llm_n_threads = self.model_threads
|
||||
|
||||
if self.llm_max_tokens is not None:
|
||||
self.model_max_tokens = self.llm_max_tokens
|
||||
else:
|
||||
self.llm_max_tokens = self.model_max_tokens
|
||||
|
||||
if self.llm_temperature is not None:
|
||||
self.model_temperature = self.llm_temperature
|
||||
else:
|
||||
self.llm_temperature = self.model_temperature
|
||||
|
||||
if self.max_batch_concurrency is not None:
|
||||
self.max_document_concurrency = self.max_batch_concurrency
|
||||
else:
|
||||
self.max_batch_concurrency = self.max_document_concurrency
|
||||
|
||||
if self.llm_model_path is not None:
|
||||
# If a full file path was explicitly provided in llm_model_path
|
||||
path_obj = Path(self.llm_model_path)
|
||||
if path_obj.suffix.lower() == ".gguf" or path_obj.is_file():
|
||||
self.model_path = path_obj.parent
|
||||
self.model_name = path_obj.name
|
||||
else:
|
||||
self.model_path = path_obj
|
||||
else:
|
||||
# Construct default llm_model_path from model_path + model_name
|
||||
self.llm_model_path = self.get_resolved_model_path()
|
||||
|
||||
return self
|
||||
|
||||
def get_resolved_model_path(self) -> Path:
|
||||
"""Return the fully resolved Path to the GGUF model file."""
|
||||
path_obj = Path(self.model_path)
|
||||
if path_obj.suffix.lower() == ".gguf":
|
||||
return path_obj
|
||||
return path_obj / self.model_name
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def get_settings() -> Settings:
|
||||
"""Return a cached singleton instance of application settings.
|
||||
|
||||
Use lru_cache to avoid re-reading disk/environment on repeated calls.
|
||||
Tests can call `get_settings.cache_clear()` to reload under custom env vars.
|
||||
"""
|
||||
return Settings()
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Database persistence layer for medical coding encounters and ICD-10 audit trails."""
|
||||
|
||||
from medical_coding.database.connection import get_db_session, get_engine, init_db
|
||||
from medical_coding.database.models import (
|
||||
AbstentionRecordModel,
|
||||
Base,
|
||||
DiagnosisRecord,
|
||||
ProcessedDocument,
|
||||
ValidationCheckModel,
|
||||
)
|
||||
from medical_coding.database.repository import MedicalCodingRepository
|
||||
|
||||
__all__ = [
|
||||
"AbstentionRecordModel",
|
||||
"Base",
|
||||
"DiagnosisRecord",
|
||||
"MedicalCodingRepository",
|
||||
"ProcessedDocument",
|
||||
"ValidationCheckModel",
|
||||
"get_db_session",
|
||||
"get_engine",
|
||||
"init_db",
|
||||
]
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Database engine initialization, connection pooling, and session lifecycle management."""
|
||||
|
||||
from collections.abc import Generator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import Engine, create_engine, event
|
||||
from sqlalchemy.orm import Session, scoped_session, sessionmaker
|
||||
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
from medical_coding.database.models import Base
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
_ENGINE: Engine | None = None
|
||||
_SESSION_FACTORY: sessionmaker[Session] | None = None
|
||||
|
||||
|
||||
def get_engine(settings: Settings | None = None) -> Engine:
|
||||
"""Initialize or return the cached singleton SQLAlchemy Engine."""
|
||||
global _ENGINE
|
||||
if _ENGINE is not None:
|
||||
return _ENGINE
|
||||
|
||||
cfg = settings or get_settings()
|
||||
db_url = cfg.database_url
|
||||
|
||||
# Ensure parent directory exists for SQLite database files
|
||||
if db_url.startswith("sqlite:///"):
|
||||
sqlite_path_str = db_url.replace("sqlite:///", "")
|
||||
if sqlite_path_str != ":memory:":
|
||||
db_file_path = Path(sqlite_path_str)
|
||||
db_file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
connect_args: dict[str, Any] = {}
|
||||
if db_url.startswith("sqlite"):
|
||||
connect_args["check_same_thread"] = False
|
||||
|
||||
engine = create_engine(
|
||||
db_url,
|
||||
connect_args=connect_args,
|
||||
pool_pre_ping=True,
|
||||
)
|
||||
|
||||
# Enable SQLite WAL mode and foreign key constraints on connection
|
||||
if db_url.startswith("sqlite"):
|
||||
@event.listens_for(engine, "connect")
|
||||
def set_sqlite_pragma(dbapi_connection: Any, _connection_record: Any) -> None:
|
||||
cursor = dbapi_connection.cursor()
|
||||
try:
|
||||
cursor.execute("PRAGMA foreign_keys = ON;")
|
||||
cursor.execute("PRAGMA journal_mode = WAL;")
|
||||
cursor.execute("PRAGMA synchronous = NORMAL;")
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
_ENGINE = engine
|
||||
return _ENGINE
|
||||
|
||||
|
||||
def get_session_factory(settings: Settings | None = None) -> sessionmaker[Session]:
|
||||
"""Initialize or return the cached sessionmaker."""
|
||||
global _SESSION_FACTORY
|
||||
if _SESSION_FACTORY is not None:
|
||||
return _SESSION_FACTORY
|
||||
|
||||
engine = get_engine(settings=settings)
|
||||
_SESSION_FACTORY = sessionmaker(
|
||||
bind=engine,
|
||||
autocommit=False,
|
||||
autoflush=False,
|
||||
expire_on_commit=False,
|
||||
)
|
||||
return _SESSION_FACTORY
|
||||
|
||||
|
||||
def get_scoped_session(settings: Settings | None = None) -> scoped_session[Session]:
|
||||
"""Return a thread-local scoped session."""
|
||||
factory = get_session_factory(settings=settings)
|
||||
return scoped_session(factory)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def get_db_session(settings: Settings | None = None) -> Generator[Session]:
|
||||
"""Context manager for database transactional sessions with automatic rollback on error."""
|
||||
factory = get_session_factory(settings=settings)
|
||||
session = factory()
|
||||
try:
|
||||
yield session
|
||||
session.commit()
|
||||
except Exception:
|
||||
session.rollback()
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def init_db(settings: Settings | None = None) -> None:
|
||||
"""Create all configured database tables if they do not already exist."""
|
||||
engine = get_engine(settings=settings)
|
||||
Base.metadata.create_all(bind=engine)
|
||||
logger.info("Initialized database schema successfully at %s", engine.url)
|
||||
@@ -0,0 +1,238 @@
|
||||
"""SQLAlchemy models for persistent storage of clinical documents and ICD-10 coding results."""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
DateTime,
|
||||
Float,
|
||||
ForeignKey,
|
||||
Integer,
|
||||
String,
|
||||
Text,
|
||||
)
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
"""Declarative base class for medical coding database entities."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class ProcessedDocument(Base):
|
||||
"""Database representation of an ingested and coded clinical document encounter."""
|
||||
|
||||
__tablename__ = "processed_documents"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
document_id: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False)
|
||||
filename: Mapped[str] = mapped_column(String(255), default="clinical_note.txt", nullable=False)
|
||||
source_type: Mapped[str] = mapped_column(String(32), default="text", nullable=False) # "pdf", "text", "batch_pdf"
|
||||
file_size_bytes: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
page_count: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
|
||||
word_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
char_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
raw_text: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), default="SUCCESS", index=True, nullable=False)
|
||||
|
||||
# Primary Diagnosis snapshot
|
||||
primary_code: Mapped[str | None] = mapped_column(String(32), index=True, nullable=True)
|
||||
primary_description: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
primary_confidence: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
|
||||
# Counts & Metrics
|
||||
secondary_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
abstention_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
processing_time_ms: Mapped[float] = mapped_column(Float, default=0.0, nullable=False)
|
||||
|
||||
# Metadata & Auditing
|
||||
metadata_json: Mapped[str] = mapped_column(Text, default="{}", nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
default=lambda: datetime.now(UTC),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
# Relationships
|
||||
diagnoses: Mapped[list["DiagnosisRecord"]] = relationship(
|
||||
"DiagnosisRecord",
|
||||
back_populates="document",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="DiagnosisRecord.id",
|
||||
)
|
||||
abstentions: Mapped[list["AbstentionRecordModel"]] = relationship(
|
||||
"AbstentionRecordModel",
|
||||
back_populates="document",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="AbstentionRecordModel.id",
|
||||
)
|
||||
validation_checks: Mapped[list["ValidationCheckModel"]] = relationship(
|
||||
"ValidationCheckModel",
|
||||
back_populates="document",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="ValidationCheckModel.id",
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Convert document record to dictionary representation."""
|
||||
import json
|
||||
|
||||
meta = {}
|
||||
try:
|
||||
meta = json.loads(self.metadata_json) if self.metadata_json else {}
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {
|
||||
"id": self.id,
|
||||
"document_id": self.document_id,
|
||||
"filename": self.filename,
|
||||
"source_type": self.source_type,
|
||||
"file_size_bytes": self.file_size_bytes,
|
||||
"page_count": self.page_count,
|
||||
"word_count": self.word_count,
|
||||
"char_count": self.char_count,
|
||||
"raw_text": self.raw_text,
|
||||
"status": self.status,
|
||||
"primary_code": self.primary_code,
|
||||
"primary_description": self.primary_description,
|
||||
"primary_confidence": self.primary_confidence,
|
||||
"secondary_count": self.secondary_count,
|
||||
"abstention_count": self.abstention_count,
|
||||
"processing_time_ms": self.processing_time_ms,
|
||||
"metadata": meta,
|
||||
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||||
"diagnoses": [d.to_dict() for d in self.diagnoses],
|
||||
"abstentions": [a.to_dict() for a in self.abstentions],
|
||||
"validation_checks": [v.to_dict() for v in self.validation_checks],
|
||||
}
|
||||
|
||||
|
||||
class DiagnosisRecord(Base):
|
||||
"""Database representation of an ICD-10 diagnosis assigned to an encounter."""
|
||||
|
||||
__tablename__ = "diagnosis_records"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
document_id: Mapped[str] = mapped_column(
|
||||
String(64),
|
||||
ForeignKey("processed_documents.document_id", ondelete="CASCADE"),
|
||||
index=True,
|
||||
nullable=False,
|
||||
)
|
||||
code: Mapped[str] = mapped_column(String(32), index=True, nullable=False)
|
||||
description: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
role: Mapped[str] = mapped_column(String(32), default="SECONDARY", index=True, nullable=False) # "PRIMARY", "SECONDARY"
|
||||
acuity: Mapped[str] = mapped_column(String(32), default="UNSPECIFIED", nullable=False)
|
||||
certainty: Mapped[str] = mapped_column(String(32), default="CONFIRMED", nullable=False)
|
||||
confidence_score: Mapped[float] = mapped_column(Float, default=1.0, nullable=False)
|
||||
is_terminal_billable: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||
evidence_quote: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
default=lambda: datetime.now(UTC),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
document: Mapped["ProcessedDocument"] = relationship(
|
||||
"ProcessedDocument",
|
||||
back_populates="diagnoses",
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Convert diagnosis record to dictionary representation."""
|
||||
return {
|
||||
"id": self.id,
|
||||
"document_id": self.document_id,
|
||||
"code": self.code,
|
||||
"description": self.description,
|
||||
"role": self.role,
|
||||
"acuity": self.acuity,
|
||||
"certainty": self.certainty,
|
||||
"confidence_score": self.confidence_score,
|
||||
"is_terminal_billable": self.is_terminal_billable,
|
||||
"evidence_quote": self.evidence_quote,
|
||||
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
class AbstentionRecordModel(Base):
|
||||
"""Database representation of an explicit abstention or excluded condition."""
|
||||
|
||||
__tablename__ = "abstention_records"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
document_id: Mapped[str] = mapped_column(
|
||||
String(64),
|
||||
ForeignKey("processed_documents.document_id", ondelete="CASCADE"),
|
||||
index=True,
|
||||
nullable=False,
|
||||
)
|
||||
raw_term: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
reason: Mapped[str] = mapped_column(String(64), index=True, nullable=False)
|
||||
detail: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
stage: Mapped[str] = mapped_column(String(64), default="EVALUATE_CONFIDENCE", nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
default=lambda: datetime.now(UTC),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
document: Mapped["ProcessedDocument"] = relationship(
|
||||
"ProcessedDocument",
|
||||
back_populates="abstentions",
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Convert abstention record to dictionary representation."""
|
||||
return {
|
||||
"id": self.id,
|
||||
"document_id": self.document_id,
|
||||
"raw_term": self.raw_term,
|
||||
"reason": self.reason,
|
||||
"detail": self.detail,
|
||||
"stage": self.stage,
|
||||
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
class ValidationCheckModel(Base):
|
||||
"""Database representation of a deterministic rule audit check."""
|
||||
|
||||
__tablename__ = "validation_checks"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
document_id: Mapped[str] = mapped_column(
|
||||
String(64),
|
||||
ForeignKey("processed_documents.document_id", ondelete="CASCADE"),
|
||||
index=True,
|
||||
nullable=False,
|
||||
)
|
||||
diagnosis_code: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
rule_name: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
passed: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||
details: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
default=lambda: datetime.now(UTC),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
document: Mapped["ProcessedDocument"] = relationship(
|
||||
"ProcessedDocument",
|
||||
back_populates="validation_checks",
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Convert validation check to dictionary representation."""
|
||||
return {
|
||||
"id": self.id,
|
||||
"document_id": self.document_id,
|
||||
"diagnosis_code": self.diagnosis_code,
|
||||
"rule_name": self.rule_name,
|
||||
"passed": self.passed,
|
||||
"details": self.details,
|
||||
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
"""Repository functions for saving, querying, and analyzing clinical coding records."""
|
||||
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
from sqlalchemy import desc, func, or_, select
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from medical_coding.database.connection import get_db_session, init_db
|
||||
from medical_coding.database.models import (
|
||||
AbstentionRecordModel,
|
||||
DiagnosisRecord,
|
||||
ProcessedDocument,
|
||||
ValidationCheckModel,
|
||||
)
|
||||
from medical_coding.schemas.response import CodingResult
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class MedicalCodingRepository:
|
||||
"""Repository managing CRUD operations and analytics for medical coding documents."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
init_db()
|
||||
|
||||
def save_coding_result(
|
||||
self,
|
||||
result: CodingResult,
|
||||
raw_text: str = "",
|
||||
filename: str = "clinical_note.txt",
|
||||
source_type: str = "text",
|
||||
page_count: int = 1,
|
||||
file_size_bytes: int = 0,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Persist a complete CodingResult and document payload to the database."""
|
||||
meta_dict = metadata or {}
|
||||
if result.metadata:
|
||||
meta_dict.update(result.metadata)
|
||||
|
||||
char_cnt = len(raw_text)
|
||||
word_cnt = len(raw_text.split())
|
||||
|
||||
with get_db_session() as session:
|
||||
# Check if document_id already exists to prevent duplicate key constraint
|
||||
existing = session.execute(
|
||||
select(ProcessedDocument).where(ProcessedDocument.document_id == result.document_id)
|
||||
).scalar_one_or_none()
|
||||
|
||||
if existing:
|
||||
# Update existing record
|
||||
doc = existing
|
||||
doc.filename = filename
|
||||
doc.source_type = source_type
|
||||
doc.file_size_bytes = file_size_bytes
|
||||
doc.page_count = page_count
|
||||
doc.word_count = word_cnt
|
||||
doc.char_count = char_cnt
|
||||
doc.raw_text = raw_text
|
||||
doc.status = result.status.value if hasattr(result.status, "value") else str(result.status)
|
||||
doc.primary_code = result.primary_diagnosis.code if result.primary_diagnosis else None
|
||||
doc.primary_description = (
|
||||
result.primary_diagnosis.description if result.primary_diagnosis else None
|
||||
)
|
||||
doc.primary_confidence = (
|
||||
result.primary_diagnosis.confidence_score if result.primary_diagnosis else None
|
||||
)
|
||||
doc.secondary_count = len(result.secondary_diagnoses)
|
||||
doc.abstention_count = len(result.abstentions)
|
||||
doc.processing_time_ms = result.processing_time_ms
|
||||
doc.metadata_json = json.dumps(meta_dict)
|
||||
|
||||
# Clear previous diagnoses, abstentions, checks for clean re-save
|
||||
doc.diagnoses.clear()
|
||||
doc.abstentions.clear()
|
||||
doc.validation_checks.clear()
|
||||
else:
|
||||
doc = ProcessedDocument(
|
||||
document_id=result.document_id,
|
||||
filename=filename,
|
||||
source_type=source_type,
|
||||
file_size_bytes=file_size_bytes,
|
||||
page_count=page_count,
|
||||
word_count=word_cnt,
|
||||
char_count=char_cnt,
|
||||
raw_text=raw_text,
|
||||
status=result.status.value if hasattr(result.status, "value") else str(result.status),
|
||||
primary_code=result.primary_diagnosis.code if result.primary_diagnosis else None,
|
||||
primary_description=(
|
||||
result.primary_diagnosis.description if result.primary_diagnosis else None
|
||||
),
|
||||
primary_confidence=(
|
||||
result.primary_diagnosis.confidence_score if result.primary_diagnosis else None
|
||||
),
|
||||
secondary_count=len(result.secondary_diagnoses),
|
||||
abstention_count=len(result.abstentions),
|
||||
processing_time_ms=result.processing_time_ms,
|
||||
metadata_json=json.dumps(meta_dict),
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
session.add(doc)
|
||||
|
||||
# Insert Primary Diagnosis if present
|
||||
if result.primary_diagnosis:
|
||||
p_diag = result.primary_diagnosis
|
||||
doc.diagnoses.append(
|
||||
DiagnosisRecord(
|
||||
document_id=result.document_id,
|
||||
code=p_diag.code,
|
||||
description=p_diag.description,
|
||||
role="PRIMARY",
|
||||
acuity=p_diag.acuity.value if hasattr(p_diag.acuity, "value") else str(p_diag.acuity),
|
||||
certainty=p_diag.certainty.value if hasattr(p_diag.certainty, "value") else str(p_diag.certainty),
|
||||
confidence_score=p_diag.confidence_score,
|
||||
is_terminal_billable=p_diag.is_terminal_billable,
|
||||
evidence_quote=p_diag.evidence_quote,
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
)
|
||||
|
||||
# Insert Secondary Diagnoses
|
||||
for s_diag in result.secondary_diagnoses:
|
||||
doc.diagnoses.append(
|
||||
DiagnosisRecord(
|
||||
document_id=result.document_id,
|
||||
code=s_diag.code,
|
||||
description=s_diag.description,
|
||||
role="SECONDARY",
|
||||
acuity=s_diag.acuity.value if hasattr(s_diag.acuity, "value") else str(s_diag.acuity),
|
||||
certainty=s_diag.certainty.value if hasattr(s_diag.certainty, "value") else str(s_diag.certainty),
|
||||
confidence_score=s_diag.confidence_score,
|
||||
is_terminal_billable=s_diag.is_terminal_billable,
|
||||
evidence_quote=s_diag.evidence_quote,
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
)
|
||||
|
||||
# Insert Abstentions
|
||||
for abst in result.abstentions:
|
||||
doc.abstentions.append(
|
||||
AbstentionRecordModel(
|
||||
document_id=result.document_id,
|
||||
raw_term=abst.raw_term,
|
||||
reason=abst.reason.value if hasattr(abst.reason, "value") else str(abst.reason),
|
||||
detail=abst.detail,
|
||||
stage=abst.stage.value if hasattr(abst.stage, "value") else str(abst.stage),
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
)
|
||||
|
||||
# Add validation check records if available in metadata or result
|
||||
validation_checks_data = meta_dict.get("validation_checks", [])
|
||||
for chk in validation_checks_data:
|
||||
if isinstance(chk, dict):
|
||||
doc.validation_checks.append(
|
||||
ValidationCheckModel(
|
||||
document_id=result.document_id,
|
||||
diagnosis_code=chk.get("diagnosis_code"),
|
||||
rule_name=chk.get("rule_name", "GeneralValidation"),
|
||||
passed=bool(chk.get("passed", True)),
|
||||
details=str(chk.get("details", "")),
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
)
|
||||
|
||||
session.flush()
|
||||
result_dict = doc.to_dict()
|
||||
|
||||
logger.info(
|
||||
"Persisted coding result for document_id=%s (primary=%s, secondary_cnt=%d)",
|
||||
result.document_id,
|
||||
result_dict.get("primary_code"),
|
||||
result_dict.get("secondary_count", 0),
|
||||
)
|
||||
return result_dict
|
||||
|
||||
def get_document_by_id(self, document_id: str) -> dict[str, Any] | None:
|
||||
"""Fetch a single document by its encounter ID with full nested relationships."""
|
||||
with get_db_session() as session:
|
||||
stmt = (
|
||||
select(ProcessedDocument)
|
||||
.options(
|
||||
selectinload(ProcessedDocument.diagnoses),
|
||||
selectinload(ProcessedDocument.abstentions),
|
||||
selectinload(ProcessedDocument.validation_checks),
|
||||
)
|
||||
.where(ProcessedDocument.document_id == document_id)
|
||||
)
|
||||
doc = session.execute(stmt).scalar_one_or_none()
|
||||
return doc.to_dict() if doc else None
|
||||
|
||||
def list_documents(
|
||||
self,
|
||||
search: str | None = None,
|
||||
status: str | None = None,
|
||||
code_filter: str | None = None,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Query and paginate processed documents with optional full-text and status filtering."""
|
||||
with get_db_session() as session:
|
||||
stmt = (
|
||||
select(ProcessedDocument)
|
||||
.options(
|
||||
selectinload(ProcessedDocument.diagnoses),
|
||||
selectinload(ProcessedDocument.abstentions),
|
||||
)
|
||||
.order_by(desc(ProcessedDocument.created_at))
|
||||
)
|
||||
|
||||
if status and status != "ALL":
|
||||
stmt = stmt.where(ProcessedDocument.status == status)
|
||||
|
||||
if search:
|
||||
term = f"%{search.strip()}%"
|
||||
stmt = stmt.where(
|
||||
or_(
|
||||
ProcessedDocument.document_id.ilike(term),
|
||||
ProcessedDocument.filename.ilike(term),
|
||||
ProcessedDocument.raw_text.ilike(term),
|
||||
ProcessedDocument.primary_description.ilike(term),
|
||||
)
|
||||
)
|
||||
|
||||
if code_filter:
|
||||
code_term = f"%{code_filter.strip()}%"
|
||||
stmt = stmt.where(
|
||||
or_(
|
||||
ProcessedDocument.primary_code.ilike(code_term),
|
||||
ProcessedDocument.document_id.in_(
|
||||
select(DiagnosisRecord.document_id).where(
|
||||
DiagnosisRecord.code.ilike(code_term)
|
||||
)
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
stmt = stmt.limit(limit).offset(offset)
|
||||
docs = session.execute(stmt).scalars().all()
|
||||
return [d.to_dict() for d in docs]
|
||||
|
||||
def delete_document(self, document_id: str) -> bool:
|
||||
"""Delete an encounter document and all associated cascade records."""
|
||||
with get_db_session() as session:
|
||||
doc = session.execute(
|
||||
select(ProcessedDocument).where(ProcessedDocument.document_id == document_id)
|
||||
).scalar_one_or_none()
|
||||
if not doc:
|
||||
return False
|
||||
session.delete(doc)
|
||||
return True
|
||||
|
||||
def get_analytics_summary(self) -> dict[str, Any]:
|
||||
"""Aggregate high-level metrics, top diagnoses, and quality indicators."""
|
||||
with get_db_session() as session:
|
||||
total_documents = session.scalar(select(func.count(ProcessedDocument.id))) or 0
|
||||
total_diagnoses = session.scalar(select(func.count(DiagnosisRecord.id))) or 0
|
||||
billable_count = session.scalar(
|
||||
select(func.count(DiagnosisRecord.id)).where(DiagnosisRecord.is_terminal_billable.is_(True))
|
||||
) or 0
|
||||
avg_latency = session.scalar(select(func.avg(ProcessedDocument.processing_time_ms))) or 0.0
|
||||
|
||||
# Status breakdown
|
||||
status_rows = session.execute(
|
||||
select(ProcessedDocument.status, func.count(ProcessedDocument.id)).group_by(
|
||||
ProcessedDocument.status
|
||||
)
|
||||
).all()
|
||||
status_breakdown = {row[0]: row[1] for row in status_rows}
|
||||
|
||||
# Top 10 Primary Codes
|
||||
top_primary_rows = session.execute(
|
||||
select(
|
||||
ProcessedDocument.primary_code,
|
||||
ProcessedDocument.primary_description,
|
||||
func.count(ProcessedDocument.id).label("count"),
|
||||
)
|
||||
.where(ProcessedDocument.primary_code.isnot(None))
|
||||
.group_by(ProcessedDocument.primary_code, ProcessedDocument.primary_description)
|
||||
.order_by(desc("count"))
|
||||
.limit(10)
|
||||
).all()
|
||||
top_primary_codes = [
|
||||
{"code": r[0], "description": r[1], "count": r[2]} for r in top_primary_rows
|
||||
]
|
||||
|
||||
# Top 10 Secondary Codes
|
||||
top_secondary_rows = session.execute(
|
||||
select(
|
||||
DiagnosisRecord.code,
|
||||
DiagnosisRecord.description,
|
||||
func.count(DiagnosisRecord.id).label("count"),
|
||||
)
|
||||
.where(DiagnosisRecord.role == "SECONDARY")
|
||||
.group_by(DiagnosisRecord.code, DiagnosisRecord.description)
|
||||
.order_by(desc("count"))
|
||||
.limit(10)
|
||||
).all()
|
||||
top_secondary_codes = [
|
||||
{"code": r[0], "description": r[1], "count": r[2]} for r in top_secondary_rows
|
||||
]
|
||||
|
||||
# Abstention reason distribution
|
||||
abstention_rows = session.execute(
|
||||
select(
|
||||
AbstentionRecordModel.reason,
|
||||
func.count(AbstentionRecordModel.id).label("count"),
|
||||
)
|
||||
.group_by(AbstentionRecordModel.reason)
|
||||
.order_by(desc("count"))
|
||||
).all()
|
||||
abstention_distribution = {r[0]: r[1] for r in abstention_rows}
|
||||
|
||||
billable_ratio = (
|
||||
round((billable_count / total_diagnoses) * 100.0, 1) if total_diagnoses > 0 else 0.0
|
||||
)
|
||||
|
||||
return {
|
||||
"total_documents": total_documents,
|
||||
"total_diagnoses": total_diagnoses,
|
||||
"billable_count": billable_count,
|
||||
"billable_ratio_percent": billable_ratio,
|
||||
"average_processing_time_ms": round(float(avg_latency), 2),
|
||||
"status_breakdown": status_breakdown,
|
||||
"top_primary_codes": top_primary_codes,
|
||||
"top_secondary_codes": top_secondary_codes,
|
||||
"abstention_distribution": abstention_distribution,
|
||||
}
|
||||
|
||||
def get_documents_df(self) -> pd.DataFrame:
|
||||
"""Export all documents and primary coding decisions as a pandas DataFrame."""
|
||||
docs = self.list_documents(limit=1000)
|
||||
if not docs:
|
||||
return pd.DataFrame(
|
||||
columns=[
|
||||
"document_id",
|
||||
"filename",
|
||||
"source_type",
|
||||
"status",
|
||||
"primary_code",
|
||||
"primary_description",
|
||||
"primary_confidence",
|
||||
"secondary_count",
|
||||
"abstention_count",
|
||||
"page_count",
|
||||
"word_count",
|
||||
"processing_time_ms",
|
||||
"created_at",
|
||||
]
|
||||
)
|
||||
|
||||
records = []
|
||||
for d in docs:
|
||||
records.append(
|
||||
{
|
||||
"document_id": d["document_id"],
|
||||
"filename": d["filename"],
|
||||
"source_type": d["source_type"],
|
||||
"status": d["status"],
|
||||
"primary_code": d["primary_code"] or "N/A",
|
||||
"primary_description": d["primary_description"] or "N/A",
|
||||
"primary_confidence": d["primary_confidence"] or 0.0,
|
||||
"secondary_count": d["secondary_count"],
|
||||
"abstention_count": d["abstention_count"],
|
||||
"page_count": d["page_count"],
|
||||
"word_count": d["word_count"],
|
||||
"processing_time_ms": d["processing_time_ms"],
|
||||
"created_at": d["created_at"],
|
||||
}
|
||||
)
|
||||
return pd.DataFrame(records)
|
||||
|
||||
def purge_all_documents(self) -> int:
|
||||
"""Delete all documents (primarily used for test cleanup)."""
|
||||
with get_db_session() as session:
|
||||
count = session.query(ProcessedDocument).delete()
|
||||
return count
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Dataset exports."""
|
||||
|
||||
from medical_coding.dataset.loader import (
|
||||
BaseICDDatasetLoader,
|
||||
CMSOrderFileLoader,
|
||||
TabularICDLoader,
|
||||
load_icd_dataset,
|
||||
)
|
||||
from medical_coding.dataset.validator import LocalICDCatalog
|
||||
|
||||
__all__ = [
|
||||
"BaseICDDatasetLoader",
|
||||
"CMSOrderFileLoader",
|
||||
"LocalICDCatalog",
|
||||
"TabularICDLoader",
|
||||
"load_icd_dataset",
|
||||
]
|
||||
@@ -0,0 +1,463 @@
|
||||
"""Local ICD-10-CM dataset ingestion, validation, normalization, and deduplication."""
|
||||
|
||||
import csv
|
||||
import json
|
||||
from abc import ABC, abstractmethod
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.schemas.icd import ICDCodeRecord, ICDDatasetStats
|
||||
from medical_coding.utils.logging import get_logger
|
||||
from medical_coding.utils.text import format_icd_code, is_valid_icd_format, unformat_icd_code
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class BaseICDDatasetLoader(ABC):
|
||||
"""Abstract interface for reading local ICD-10-CM source files into code records."""
|
||||
|
||||
@abstractmethod
|
||||
def load(self) -> tuple[dict[str, ICDCodeRecord], ICDDatasetStats]:
|
||||
"""Load, validate, normalize, and parse ICD-10-CM records from local storage.
|
||||
|
||||
Returns:
|
||||
Tuple of (dictionary mapping formatted codes to ICDCodeRecord, dataset statistics).
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_total_records(self) -> int:
|
||||
"""Return the count of valid codes in the loaded dataset."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_stats(self) -> ICDDatasetStats | None:
|
||||
"""Return the statistics of the ingestion process."""
|
||||
pass
|
||||
|
||||
|
||||
class TabularICDLoader(BaseICDDatasetLoader):
|
||||
"""Parses tabular ICD-10-CM datasets from CSV, TSV, or JSON files.
|
||||
|
||||
Performs strict column validation, code format normalization, malformed row
|
||||
filtering, and duplicate detection.
|
||||
"""
|
||||
|
||||
# Acceptable column aliases for flexible hospital schema ingestion
|
||||
CODE_ALIASES = {"code", "icd_code", "icd10_code", "icd10", "code_id", "icd_10_code"}
|
||||
DESC_ALIASES = {
|
||||
"description",
|
||||
"long_description",
|
||||
"short_description",
|
||||
"clinical_description",
|
||||
"title",
|
||||
"term",
|
||||
"diagnosis",
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
file_path: Path | str,
|
||||
delimiter: str | None = None,
|
||||
source_name: str | None = None,
|
||||
) -> None:
|
||||
self.file_path = Path(file_path)
|
||||
self.delimiter = delimiter
|
||||
self.source_name = source_name or self.file_path.name
|
||||
self._records: dict[str, ICDCodeRecord] = {}
|
||||
self._stats: ICDDatasetStats | None = None
|
||||
self._is_loaded: bool = False
|
||||
|
||||
def get_total_records(self) -> int:
|
||||
return len(self._records)
|
||||
|
||||
def get_stats(self) -> ICDDatasetStats | None:
|
||||
return self._stats
|
||||
|
||||
def _detect_delimiter(self) -> str:
|
||||
if self.delimiter:
|
||||
return self.delimiter
|
||||
suffix = self.file_path.suffix.lower()
|
||||
if suffix == ".tsv":
|
||||
return "\t"
|
||||
return ","
|
||||
|
||||
def _parse_list_field(self, raw_val: Any) -> list[str]:
|
||||
if not raw_val:
|
||||
return []
|
||||
if isinstance(raw_val, list):
|
||||
return [str(v).strip() for v in raw_val if str(v).strip()]
|
||||
if isinstance(raw_val, str):
|
||||
clean = raw_val.strip()
|
||||
if not clean:
|
||||
return []
|
||||
if clean.startswith("[") and clean.endswith("]"):
|
||||
try:
|
||||
parsed = json.loads(clean)
|
||||
if isinstance(parsed, list):
|
||||
return [str(v).strip() for v in parsed if str(v).strip()]
|
||||
except Exception:
|
||||
pass
|
||||
# Split by semicolon or pipe or comma
|
||||
if ";" in clean:
|
||||
return [v.strip() for v in clean.split(";") if v.strip()]
|
||||
if "|" in clean:
|
||||
return [v.strip() for v in clean.split("|") if v.strip()]
|
||||
return [clean]
|
||||
return [str(raw_val)]
|
||||
|
||||
def _parse_bool_field(self, raw_val: Any, default: bool = True) -> bool:
|
||||
if raw_val is None or raw_val == "":
|
||||
return default
|
||||
if isinstance(raw_val, bool):
|
||||
return raw_val
|
||||
val_str = str(raw_val).strip().lower()
|
||||
if val_str in {"1", "true", "yes", "t", "y", "billable"}:
|
||||
return True
|
||||
if val_str in {"0", "false", "no", "f", "n", "header", "non-billable"}:
|
||||
return False
|
||||
return default
|
||||
|
||||
def load(self) -> tuple[dict[str, ICDCodeRecord], ICDDatasetStats]:
|
||||
"""Load and normalize tabular records, dropping malformed entries and duplicates."""
|
||||
if self._is_loaded and self._stats is not None:
|
||||
return self._records, self._stats
|
||||
|
||||
if not self.file_path.exists():
|
||||
raise FileNotFoundError(
|
||||
f"ICD dataset file not found at expected location: {self.file_path}"
|
||||
)
|
||||
|
||||
suffix = self.file_path.suffix.lower()
|
||||
raw_rows: list[dict[str, Any]] = []
|
||||
|
||||
if suffix == ".json":
|
||||
with open(self.file_path, encoding="utf-8-sig") as f:
|
||||
content = json.load(f)
|
||||
if isinstance(content, list):
|
||||
raw_rows = content
|
||||
elif isinstance(content, dict) and "records" in content:
|
||||
raw_rows = content["records"]
|
||||
else:
|
||||
raise ValueError(
|
||||
f"Unsupported JSON structure in {self.file_path}. Expected array of records."
|
||||
)
|
||||
else:
|
||||
delimiter = self._detect_delimiter()
|
||||
with open(self.file_path, encoding="utf-8-sig", newline="") as f:
|
||||
reader = csv.DictReader(f, delimiter=delimiter)
|
||||
if not reader.fieldnames:
|
||||
raise ValueError(f"Empty or corrupted tabular ICD dataset at {self.file_path}")
|
||||
# Check for required columns
|
||||
field_lower = {fn.strip().lower(): fn for fn in reader.fieldnames if fn}
|
||||
code_col = next(
|
||||
(field_lower[c] for c in self.CODE_ALIASES if c in field_lower), None
|
||||
)
|
||||
desc_col = next(
|
||||
(field_lower[d] for d in self.DESC_ALIASES if d in field_lower), None
|
||||
)
|
||||
|
||||
if not code_col or not desc_col:
|
||||
raise ValueError(
|
||||
f"Missing required columns in {self.file_path}. "
|
||||
f"Must include a code column (found: {reader.fieldnames}) "
|
||||
f"and a description column."
|
||||
)
|
||||
|
||||
for row in reader:
|
||||
raw_rows.append(row)
|
||||
|
||||
# Ingestion metrics
|
||||
records: dict[str, ICDCodeRecord] = {}
|
||||
duplicates_count = 0
|
||||
malformed_count = 0
|
||||
total_inclusion = 0
|
||||
total_exclusion = 0
|
||||
total_synonyms = 0
|
||||
|
||||
for row in raw_rows:
|
||||
# Normalize keys to lower
|
||||
lower_row = {str(k).strip().lower(): v for k, v in row.items() if k is not None}
|
||||
|
||||
# 1. Resolve Code
|
||||
raw_code = None
|
||||
for alias in self.CODE_ALIASES:
|
||||
if alias in lower_row and lower_row[alias]:
|
||||
raw_code = str(lower_row[alias]).strip()
|
||||
break
|
||||
|
||||
# 2. Resolve Description
|
||||
raw_desc = None
|
||||
for alias in self.DESC_ALIASES:
|
||||
if alias in lower_row and lower_row[alias]:
|
||||
raw_desc = str(lower_row[alias]).strip()
|
||||
break
|
||||
|
||||
# Validation: Code and Description must be present and valid
|
||||
if not raw_code or not raw_desc:
|
||||
logger.warning("Dropping malformed row: missing code or description: %s", row)
|
||||
malformed_count += 1
|
||||
continue
|
||||
|
||||
if not is_valid_icd_format(raw_code):
|
||||
logger.warning(
|
||||
"Dropping malformed row: '%s' violates ICD-10-CM format rules.",
|
||||
raw_code,
|
||||
)
|
||||
malformed_count += 1
|
||||
continue
|
||||
|
||||
formatted_code = format_icd_code(raw_code)
|
||||
unformatted_code = unformat_icd_code(raw_code)
|
||||
|
||||
# Check for duplicates
|
||||
if formatted_code in records:
|
||||
duplicates_count += 1
|
||||
# Merge synonyms and inclusion terms into existing authoritative record
|
||||
existing = records[formatted_code]
|
||||
new_syns = self._parse_list_field(
|
||||
lower_row.get("synonyms") or lower_row.get("synonym")
|
||||
)
|
||||
new_incls = self._parse_list_field(
|
||||
lower_row.get("inclusion_terms") or lower_row.get("includes")
|
||||
)
|
||||
for s in new_syns:
|
||||
if s not in existing.synonyms:
|
||||
existing.synonyms.append(s)
|
||||
total_synonyms += 1
|
||||
for inc in new_incls:
|
||||
if inc not in existing.inclusion_terms:
|
||||
existing.inclusion_terms.append(inc)
|
||||
total_inclusion += 1
|
||||
continue
|
||||
|
||||
# Additional fields
|
||||
category = lower_row.get("category") or unformatted_code[:3]
|
||||
chapter = lower_row.get("chapter")
|
||||
short_desc = lower_row.get("short_description") or raw_desc
|
||||
long_desc = lower_row.get("long_description") or raw_desc
|
||||
is_billable = self._parse_bool_field(
|
||||
lower_row.get("is_valid_billable")
|
||||
or lower_row.get("is_billable")
|
||||
or lower_row.get("billable")
|
||||
or lower_row.get("valid_billable"),
|
||||
default=True,
|
||||
)
|
||||
inclusion_terms = self._parse_list_field(
|
||||
lower_row.get("inclusion_terms") or lower_row.get("includes")
|
||||
)
|
||||
exclusion_terms = self._parse_list_field(
|
||||
lower_row.get("exclusion_terms")
|
||||
or lower_row.get("excludes")
|
||||
or lower_row.get("excludes1")
|
||||
)
|
||||
synonyms = self._parse_list_field(lower_row.get("synonyms") or lower_row.get("synonym"))
|
||||
excludes1 = self._parse_list_field(lower_row.get("excludes1"))
|
||||
excludes2 = self._parse_list_field(lower_row.get("excludes2"))
|
||||
code_first = self._parse_list_field(lower_row.get("code_first"))
|
||||
use_additional = self._parse_list_field(lower_row.get("use_additional"))
|
||||
|
||||
total_inclusion += len(inclusion_terms)
|
||||
total_exclusion += len(exclusion_terms)
|
||||
total_synonyms += len(synonyms)
|
||||
|
||||
record = ICDCodeRecord(
|
||||
code=formatted_code,
|
||||
unformatted_code=unformatted_code,
|
||||
description=raw_desc,
|
||||
short_description=short_desc,
|
||||
long_description=long_desc,
|
||||
is_valid_billable=is_billable,
|
||||
category=category,
|
||||
chapter=chapter,
|
||||
inclusion_terms=inclusion_terms,
|
||||
exclusion_terms=exclusion_terms,
|
||||
synonyms=synonyms,
|
||||
excludes1=excludes1,
|
||||
excludes2=excludes2,
|
||||
code_first=code_first,
|
||||
use_additional=use_additional,
|
||||
source_metadata={
|
||||
"source": self.source_name,
|
||||
"file_path": str(self.file_path),
|
||||
},
|
||||
)
|
||||
records[formatted_code] = record
|
||||
|
||||
unique_categories = {r.category for r in records.values() if r.category}
|
||||
billable_count = sum(1 for r in records.values() if r.is_valid_billable)
|
||||
non_billable_count = len(records) - billable_count
|
||||
|
||||
stats = ICDDatasetStats(
|
||||
total_records=len(records),
|
||||
valid_billable_count=billable_count,
|
||||
non_billable_count=non_billable_count,
|
||||
unique_categories_count=len(unique_categories),
|
||||
duplicates_dropped=duplicates_count,
|
||||
malformed_dropped=malformed_count,
|
||||
total_inclusion_terms=total_inclusion,
|
||||
total_exclusion_terms=total_exclusion,
|
||||
total_synonyms=total_synonyms,
|
||||
format_type="tabular",
|
||||
)
|
||||
|
||||
self._records = records
|
||||
self._stats = stats
|
||||
self._is_loaded = True
|
||||
|
||||
logger.info(
|
||||
"Tabular ICD dataset loaded from %s: %d records (%d billable, %d categories, %d duplicates dropped, %d malformed dropped)",
|
||||
self.file_path,
|
||||
stats.total_records,
|
||||
stats.valid_billable_count,
|
||||
stats.unique_categories_count,
|
||||
stats.duplicates_dropped,
|
||||
stats.malformed_dropped,
|
||||
)
|
||||
|
||||
return self._records, self._stats
|
||||
|
||||
|
||||
class CMSOrderFileLoader(BaseICDDatasetLoader):
|
||||
"""Parses standard CMS / CDC ICD-10-CM Order Files (e.g. icd10cm_order_2026.txt).
|
||||
|
||||
CMS Order file format:
|
||||
Positions 1-5: Order number (5 chars)
|
||||
Position 6: Blank
|
||||
Positions 7-13: ICD-10-CM code (7 chars alphanumeric, no decimal)
|
||||
Position 14: Blank
|
||||
Position 15: Valid for HIPAA submission (0=header/non-billable, 1=valid billable)
|
||||
Position 16: Blank
|
||||
Positions 17-76: Short description (60 chars)
|
||||
Position 77: Blank
|
||||
Positions 78+: Long description
|
||||
"""
|
||||
|
||||
def __init__(self, file_path: Path | str) -> None:
|
||||
self.file_path = Path(file_path)
|
||||
self._records: dict[str, ICDCodeRecord] = {}
|
||||
self._stats: ICDDatasetStats | None = None
|
||||
self._is_loaded: bool = False
|
||||
|
||||
def get_total_records(self) -> int:
|
||||
return len(self._records)
|
||||
|
||||
def get_stats(self) -> ICDDatasetStats | None:
|
||||
return self._stats
|
||||
|
||||
def load(self) -> tuple[dict[str, ICDCodeRecord], ICDDatasetStats]:
|
||||
"""Parse local CMS flat file into structured records."""
|
||||
if self._is_loaded and self._stats is not None:
|
||||
return self._records, self._stats
|
||||
|
||||
if not self.file_path.exists():
|
||||
raise FileNotFoundError(f"CMS order file not found at: {self.file_path}")
|
||||
|
||||
records: dict[str, ICDCodeRecord] = {}
|
||||
duplicates_count = 0
|
||||
malformed_count = 0
|
||||
|
||||
with open(self.file_path, encoding="utf-8-sig", errors="replace") as f:
|
||||
for line_no, raw_line in enumerate(f, start=1):
|
||||
line = raw_line.rstrip("\r\n")
|
||||
if not line.strip():
|
||||
continue
|
||||
|
||||
if len(line) < 16:
|
||||
logger.warning(
|
||||
"Line %d in %s is malformed (too short): '%s'",
|
||||
line_no,
|
||||
self.file_path,
|
||||
line,
|
||||
)
|
||||
malformed_count += 1
|
||||
continue
|
||||
|
||||
try:
|
||||
# Slicing fixed positions
|
||||
raw_code = line[6:13].strip()
|
||||
valid_flag = line[14:15].strip()
|
||||
short_desc = line[16:76].strip() if len(line) >= 76 else line[16:].strip()
|
||||
long_desc = line[77:].strip() if len(line) > 77 else short_desc
|
||||
|
||||
if not raw_code or not is_valid_icd_format(raw_code):
|
||||
malformed_count += 1
|
||||
continue
|
||||
|
||||
if not short_desc and not long_desc:
|
||||
malformed_count += 1
|
||||
continue
|
||||
|
||||
formatted_code = format_icd_code(raw_code)
|
||||
unformatted_code = unformat_icd_code(raw_code)
|
||||
is_billable = valid_flag == "1"
|
||||
|
||||
if formatted_code in records:
|
||||
duplicates_count += 1
|
||||
continue
|
||||
|
||||
category = unformatted_code[:3]
|
||||
|
||||
record = ICDCodeRecord(
|
||||
code=formatted_code,
|
||||
unformatted_code=unformatted_code,
|
||||
description=long_desc or short_desc,
|
||||
short_description=short_desc,
|
||||
long_description=long_desc or short_desc,
|
||||
is_valid_billable=is_billable,
|
||||
category=category,
|
||||
source_metadata={
|
||||
"source": "CMS_Order_File",
|
||||
"line_number": line_no,
|
||||
"file_path": str(self.file_path),
|
||||
},
|
||||
)
|
||||
records[formatted_code] = record
|
||||
except Exception as e:
|
||||
logger.warning("Error parsing line %d in CMS order file: %s", line_no, e)
|
||||
malformed_count += 1
|
||||
|
||||
unique_categories = {r.category for r in records.values() if r.category}
|
||||
billable_count = sum(1 for r in records.values() if r.is_valid_billable)
|
||||
non_billable_count = len(records) - billable_count
|
||||
|
||||
stats = ICDDatasetStats(
|
||||
total_records=len(records),
|
||||
valid_billable_count=billable_count,
|
||||
non_billable_count=non_billable_count,
|
||||
unique_categories_count=len(unique_categories),
|
||||
duplicates_dropped=duplicates_count,
|
||||
malformed_dropped=malformed_count,
|
||||
format_type="cms_order_file",
|
||||
)
|
||||
|
||||
self._records = records
|
||||
self._stats = stats
|
||||
self._is_loaded = True
|
||||
|
||||
logger.info(
|
||||
"CMS order file loaded from %s: %d records (%d billable, %d categories)",
|
||||
self.file_path,
|
||||
stats.total_records,
|
||||
stats.valid_billable_count,
|
||||
stats.unique_categories_count,
|
||||
)
|
||||
|
||||
return self._records, self._stats
|
||||
|
||||
|
||||
def load_icd_dataset(
|
||||
file_path: Path | str, **kwargs: Any
|
||||
) -> tuple[dict[str, ICDCodeRecord], ICDDatasetStats]:
|
||||
"""Factory function detecting format from file extension and returning loaded records and stats."""
|
||||
path = Path(file_path)
|
||||
suffix = path.suffix.lower()
|
||||
if suffix in {".csv", ".tsv", ".json"}:
|
||||
loader: BaseICDDatasetLoader = TabularICDLoader(path, **kwargs)
|
||||
elif suffix in {".txt"}:
|
||||
loader = CMSOrderFileLoader(path)
|
||||
else:
|
||||
# Default fallback to tabular loader
|
||||
loader = TabularICDLoader(path, **kwargs)
|
||||
|
||||
return loader.load()
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Local ICD catalog access, code existence verification, and Excludes validation."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from medical_coding.dataset.loader import BaseICDDatasetLoader
|
||||
from medical_coding.schemas.icd import ICDCodeRecord, ICDDatasetStats
|
||||
from medical_coding.utils.logging import get_logger
|
||||
from medical_coding.utils.text import format_icd_code, unformat_icd_code
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class LocalICDCatalog:
|
||||
"""In-memory authoritative catalog lookup interface for ICD-10-CM codes.
|
||||
|
||||
Enforces that only codes existing in the local authoritative dataset
|
||||
can ever be considered or validated.
|
||||
"""
|
||||
|
||||
def __init__(self, loader: BaseICDDatasetLoader | None = None) -> None:
|
||||
self.loader = loader
|
||||
self._records_by_clean: dict[str, ICDCodeRecord] = {}
|
||||
self._records_by_formatted: dict[str, ICDCodeRecord] = {}
|
||||
self._stats: ICDDatasetStats | None = None
|
||||
self._initialized: bool = False
|
||||
|
||||
@property
|
||||
def is_initialized(self) -> bool:
|
||||
return self._initialized
|
||||
|
||||
@property
|
||||
def stats(self) -> ICDDatasetStats | None:
|
||||
return self._stats
|
||||
|
||||
def add_record(self, record: ICDCodeRecord) -> None:
|
||||
"""Register a single validated ICDCodeRecord in the catalog lookup indexes."""
|
||||
self._records_by_clean[record.unformatted_code] = record
|
||||
self._records_by_formatted[record.code] = record
|
||||
|
||||
def initialize(self) -> None:
|
||||
"""Load records from the dataset loader into fast lookup indexes."""
|
||||
if self._initialized:
|
||||
return
|
||||
|
||||
if self.loader is not None:
|
||||
records, stats = self.loader.load()
|
||||
for rec in records.values():
|
||||
self.add_record(rec)
|
||||
self._stats = stats
|
||||
logger.info(
|
||||
"LocalICDCatalog initialized with %d codes.", len(self._records_by_formatted)
|
||||
)
|
||||
|
||||
self._initialized = True
|
||||
|
||||
def get_by_code(self, code: str) -> ICDCodeRecord | None:
|
||||
"""Lookup a code in the local catalog by formatted or unformatted representation."""
|
||||
if not code:
|
||||
return None
|
||||
clean = unformat_icd_code(code)
|
||||
if clean in self._records_by_clean:
|
||||
return self._records_by_clean[clean]
|
||||
|
||||
formatted = format_icd_code(code)
|
||||
return self._records_by_formatted.get(formatted)
|
||||
|
||||
def is_valid_code(self, code: str) -> bool:
|
||||
"""Check if code exists in the local authoritative dataset."""
|
||||
return self.get_by_code(code) is not None
|
||||
|
||||
def is_billable_code(self, code: str) -> bool:
|
||||
"""Check if code exists and is terminal/billable at full specificity."""
|
||||
record = self.get_by_code(code)
|
||||
return record.is_valid_billable if record else False
|
||||
|
||||
def get_all_records(self) -> list[ICDCodeRecord]:
|
||||
"""Return all distinct ICDCodeRecord entries in the catalog."""
|
||||
return list(self._records_by_formatted.values())
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self._records_by_formatted)
|
||||
|
||||
def check_excludes1(self, code_a: str, code_b: str) -> bool:
|
||||
"""Check if code_a and code_b violate mutual Excludes1 rules.
|
||||
|
||||
Returns:
|
||||
True if there is an Excludes1 conflict between code_a and code_b.
|
||||
"""
|
||||
rec_a = self.get_by_code(code_a)
|
||||
if rec_a and unformat_icd_code(code_b) in [unformat_icd_code(c) for c in rec_a.excludes1]:
|
||||
return True
|
||||
|
||||
rec_b = self.get_by_code(code_b)
|
||||
if rec_b and unformat_icd_code(code_a) in [unformat_icd_code(c) for c in rec_b.excludes1]:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def check_excludes2(self, code_a: str, code_b: str) -> bool:
|
||||
"""Check if code_a and code_b are mutually noted in Excludes2 relationships."""
|
||||
rec_a = self.get_by_code(code_a)
|
||||
if rec_a and unformat_icd_code(code_b) in [unformat_icd_code(c) for c in rec_a.excludes2]:
|
||||
return True
|
||||
|
||||
rec_b = self.get_by_code(code_b)
|
||||
if rec_b and unformat_icd_code(code_a) in [unformat_icd_code(c) for c in rec_b.excludes2]:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def save_to_json(self, output_path: Path | str) -> None:
|
||||
"""Persist catalog records and metadata to JSON file."""
|
||||
target = Path(output_path)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
data = {
|
||||
"records": [rec.model_dump() for rec in self._records_by_formatted.values()],
|
||||
"stats": self._stats.model_dump() if self._stats else None,
|
||||
}
|
||||
with open(target, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
|
||||
@classmethod
|
||||
def load_from_json(cls, file_path: Path | str) -> "LocalICDCatalog":
|
||||
"""Load catalog from previously serialized JSON."""
|
||||
source = Path(file_path)
|
||||
with open(source, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
catalog = cls()
|
||||
for r_dict in data.get("records", []):
|
||||
rec = ICDCodeRecord.model_validate(r_dict)
|
||||
catalog.add_record(rec)
|
||||
|
||||
if data.get("stats"):
|
||||
catalog._stats = ICDDatasetStats.model_validate(data["stats"])
|
||||
|
||||
catalog._initialized = True
|
||||
return catalog
|
||||
@@ -0,0 +1,57 @@
|
||||
"""LangGraph medical coding workflow, execution nodes, and async pipeline exports."""
|
||||
|
||||
from medical_coding.graph.edges import (
|
||||
route_after_classification,
|
||||
route_after_document_validation,
|
||||
route_after_extraction,
|
||||
route_after_retrieval,
|
||||
route_after_text_extraction,
|
||||
)
|
||||
from medical_coding.graph.nodes import (
|
||||
analyze_context_node,
|
||||
classify_diagnoses_node,
|
||||
evaluate_confidence_node,
|
||||
extract_diagnoses_node,
|
||||
extract_text_node,
|
||||
finalize_output_node,
|
||||
rank_candidates_node,
|
||||
retrieve_candidates_node,
|
||||
validate_codes_node,
|
||||
validate_document_node,
|
||||
)
|
||||
from medical_coding.graph.pipeline import (
|
||||
process_clinical_document,
|
||||
process_clinical_document_batch,
|
||||
)
|
||||
from medical_coding.graph.state import create_initial_state
|
||||
from medical_coding.graph.workflow import (
|
||||
create_coding_workflow,
|
||||
export_graph_ascii,
|
||||
export_graph_mermaid,
|
||||
get_compiled_graph,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"analyze_context_node",
|
||||
"classify_diagnoses_node",
|
||||
"create_coding_workflow",
|
||||
"create_initial_state",
|
||||
"evaluate_confidence_node",
|
||||
"export_graph_ascii",
|
||||
"export_graph_mermaid",
|
||||
"extract_diagnoses_node",
|
||||
"extract_text_node",
|
||||
"finalize_output_node",
|
||||
"get_compiled_graph",
|
||||
"process_clinical_document",
|
||||
"process_clinical_document_batch",
|
||||
"rank_candidates_node",
|
||||
"retrieve_candidates_node",
|
||||
"route_after_classification",
|
||||
"route_after_document_validation",
|
||||
"route_after_extraction",
|
||||
"route_after_retrieval",
|
||||
"route_after_text_extraction",
|
||||
"validate_codes_node",
|
||||
"validate_document_node",
|
||||
]
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Conditional routing functions for LangGraph state transitions."""
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from medical_coding.schemas.enums import DiagnosisRole
|
||||
from medical_coding.schemas.state import PipelineGraphState
|
||||
|
||||
|
||||
def route_after_document_validation(
|
||||
state: PipelineGraphState,
|
||||
) -> Literal["extract_text", "evaluate_confidence"]:
|
||||
"""Route after document validation: proceed to extraction if input is valid, else abort."""
|
||||
if state.get("is_aborted", False):
|
||||
return "evaluate_confidence"
|
||||
return "extract_text"
|
||||
|
||||
|
||||
def route_after_text_extraction(
|
||||
state: PipelineGraphState,
|
||||
) -> Literal["extract_diagnoses", "evaluate_confidence"]:
|
||||
"""Route after text extraction: proceed if text is available, else abort."""
|
||||
if state.get("is_aborted", False):
|
||||
return "evaluate_confidence"
|
||||
if not state.get("raw_text", "").strip():
|
||||
return "evaluate_confidence"
|
||||
return "extract_diagnoses"
|
||||
|
||||
|
||||
def route_after_extraction(
|
||||
state: PipelineGraphState,
|
||||
) -> Literal["analyze_context", "evaluate_confidence"]:
|
||||
"""Route after extraction: proceed if diagnoses found, otherwise evaluate abstention."""
|
||||
if state.get("is_aborted", False):
|
||||
return "evaluate_confidence"
|
||||
|
||||
diagnoses = state.get("extracted_diagnoses", []) or state.get("extracted_conditions", [])
|
||||
if not diagnoses:
|
||||
return "evaluate_confidence"
|
||||
|
||||
return "analyze_context"
|
||||
|
||||
|
||||
def route_after_classification(
|
||||
state: PipelineGraphState,
|
||||
) -> Literal["retrieve_candidates", "evaluate_confidence"]:
|
||||
"""Route after classification: proceed to candidate retrieval only if billable conditions exist."""
|
||||
if state.get("is_aborted", False):
|
||||
return "evaluate_confidence"
|
||||
|
||||
classified = state.get("classified_diagnoses", [])
|
||||
has_billable = any(
|
||||
c.is_billable_candidate and c.role in (DiagnosisRole.PRIMARY, DiagnosisRole.SECONDARY)
|
||||
for c in classified
|
||||
)
|
||||
|
||||
if not has_billable:
|
||||
return "evaluate_confidence"
|
||||
|
||||
return "retrieve_candidates"
|
||||
|
||||
|
||||
def route_after_retrieval(
|
||||
state: PipelineGraphState,
|
||||
) -> Literal["rank_candidates", "validate_codes"]:
|
||||
"""Route after retrieval: rank candidates if any retrieved, else proceed directly to validation."""
|
||||
pool = state.get("candidate_pool", {})
|
||||
if not pool or all(len(candidates) == 0 for candidates in pool.values()):
|
||||
return "validate_codes"
|
||||
|
||||
return "rank_candidates"
|
||||
@@ -0,0 +1,956 @@
|
||||
"""LangGraph pipeline nodes implementing individual execution stages with deterministic guardrails."""
|
||||
|
||||
import concurrent.futures
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.agents.classifier import (
|
||||
ContextAndRelevanceAgent,
|
||||
PrimarySecondaryClassifier,
|
||||
)
|
||||
from medical_coding.agents.extractor import ClinicalExtractionAgent
|
||||
from medical_coding.agents.ranker import CandidateRankingAgent
|
||||
from medical_coding.config.settings import get_settings
|
||||
from medical_coding.dataset.loader import load_icd_dataset
|
||||
from medical_coding.dataset.validator import LocalICDCatalog
|
||||
from medical_coding.ingestion import ClinicalDocumentIngestionAgent, DocumentFormat
|
||||
from medical_coding.models.factory import FastLocalEmbeddings, ModelFactory
|
||||
from medical_coding.retrieval.hybrid import HybridICDRetriever
|
||||
from medical_coding.retrieval.lexical import BM25ICDRetriever
|
||||
from medical_coding.retrieval.vector import FAISSICDRetriever
|
||||
from medical_coding.schemas.clinical import (
|
||||
ClassifiedDiagnosis,
|
||||
ContextAssessment,
|
||||
EvidenceLocation,
|
||||
EvidenceSnippet,
|
||||
ExtractedClinicalCondition,
|
||||
ExtractedDiagnosis,
|
||||
)
|
||||
from medical_coding.schemas.enums import (
|
||||
AbstentionReason,
|
||||
Acuity,
|
||||
Certainty,
|
||||
ConditionStatus,
|
||||
DiagnosisRole,
|
||||
ExecutionStatus,
|
||||
NegationStatus,
|
||||
PipelineStage,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.schemas.icd import ICDCandidate, RankedSelection
|
||||
from medical_coding.schemas.response import CodedDiagnosisResponse, CodingResult
|
||||
from medical_coding.schemas.state import PipelineGraphState
|
||||
from medical_coding.schemas.validation import (
|
||||
AbstentionRecord,
|
||||
ValidatedDiagnosis,
|
||||
)
|
||||
from medical_coding.utils.logging import get_logger
|
||||
from medical_coding.utils.text import format_icd_code, normalize_whitespace
|
||||
from medical_coding.validation.deterministic import (
|
||||
CandidateRankingDeterministicValidator,
|
||||
DeterministicValidator,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# Global cached catalog and retriever instances for fast execution across workflow nodes
|
||||
_CACHED_CATALOG: LocalICDCatalog | None = None
|
||||
_CACHED_RETRIEVER: HybridICDRetriever | None = None
|
||||
_RETRIEVAL_INIT_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def get_or_initialize_retrieval_system() -> tuple[LocalICDCatalog, HybridICDRetriever]:
|
||||
"""Retrieve or initialize singleton LocalICDCatalog and HybridICDRetriever."""
|
||||
global _CACHED_CATALOG, _CACHED_RETRIEVER
|
||||
if _CACHED_CATALOG is not None and _CACHED_RETRIEVER is not None:
|
||||
return _CACHED_CATALOG, _CACHED_RETRIEVER
|
||||
|
||||
with _RETRIEVAL_INIT_LOCK:
|
||||
if _CACHED_CATALOG is not None and _CACHED_RETRIEVER is not None:
|
||||
return _CACHED_CATALOG, _CACHED_RETRIEVER
|
||||
|
||||
settings = get_settings()
|
||||
index_dir = Path("./data/indexes")
|
||||
catalog_path = index_dir / "icd_catalog.json"
|
||||
sample_csv = Path("./data/icd10/sample_hospital_icd.csv")
|
||||
|
||||
catalog = LocalICDCatalog()
|
||||
bm25 = BM25ICDRetriever()
|
||||
embeddings = FastLocalEmbeddings(dim=384)
|
||||
faiss_ret = FAISSICDRetriever(embeddings=embeddings)
|
||||
|
||||
if catalog_path.exists():
|
||||
try:
|
||||
catalog = LocalICDCatalog.load_from_json(catalog_path)
|
||||
if (index_dir / "bm25_index.pkl").exists() and (index_dir / "faiss.index").exists():
|
||||
bm25.load(index_dir)
|
||||
faiss_ret.load(index_dir)
|
||||
logger.info("Loaded persisted ICD catalog and indices from %s", index_dir)
|
||||
else:
|
||||
records = catalog.get_all_records()
|
||||
bm25.build_index(records)
|
||||
faiss_ret.build_index(records)
|
||||
except Exception as e:
|
||||
logger.warning("Error loading persisted indices: %s. Building from source.", e)
|
||||
catalog = LocalICDCatalog()
|
||||
|
||||
if len(catalog) == 0:
|
||||
data_source = (
|
||||
settings.icd_dataset_path if settings.icd_dataset_path.exists() else sample_csv
|
||||
)
|
||||
if data_source.exists():
|
||||
records_dict, stats = load_icd_dataset(data_source)
|
||||
record_list = list(records_dict.values())
|
||||
for rec in record_list:
|
||||
catalog.add_record(rec)
|
||||
catalog._stats = stats
|
||||
catalog._initialized = True
|
||||
bm25.build_index(record_list)
|
||||
faiss_ret.build_index(record_list)
|
||||
logger.info(
|
||||
"Initialized in-memory ICD catalog with %d codes from %s",
|
||||
len(record_list),
|
||||
data_source,
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"No ICD source dataset found at %s. Catalog initialized empty.", data_source
|
||||
)
|
||||
|
||||
hybrid = HybridICDRetriever(
|
||||
lexical_retriever=bm25,
|
||||
vector_retriever=faiss_ret,
|
||||
catalog=catalog,
|
||||
weight_semantic=0.6,
|
||||
weight_lexical=0.4,
|
||||
min_score_threshold=0.35,
|
||||
default_top_k=10,
|
||||
)
|
||||
|
||||
_CACHED_CATALOG = catalog
|
||||
_CACHED_RETRIEVER = hybrid
|
||||
return _CACHED_CATALOG, _CACHED_RETRIEVER
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# NODE 1: Document Validation (Deterministic Python Function)
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def validate_document_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
"""Node 1: Deterministic validation of input payload (text, PDF, TXT, or image source)."""
|
||||
doc_id = state.get("document_id", "doc-unknown")
|
||||
raw_text = state.get("raw_text", "")
|
||||
file_path = state.get("file_path") or state.get("pdf_path")
|
||||
file_bytes = state.get("file_bytes") or state.get("pdf_bytes")
|
||||
|
||||
logger.info("Executing Node [1/10]: Document Validation for doc_id=%s", doc_id)
|
||||
|
||||
# Check whether text or document/image source is present
|
||||
has_text = bool(raw_text and raw_text.strip())
|
||||
has_file = bool(file_path or file_bytes)
|
||||
|
||||
if not has_text and not has_file:
|
||||
abstention = AbstentionRecord(
|
||||
diagnosis_id=None,
|
||||
raw_term=None,
|
||||
reason=AbstentionReason.INSUFFICIENT_CLINICAL_EVIDENCE,
|
||||
detail="Input document text, PDF, and image sources are all empty or missing.",
|
||||
stage=PipelineStage.VALIDATION,
|
||||
)
|
||||
return {
|
||||
"is_aborted": True,
|
||||
"abstentions": [abstention],
|
||||
"current_stage": PipelineStage.VALIDATION,
|
||||
}
|
||||
|
||||
return {
|
||||
"current_stage": PipelineStage.INGESTION,
|
||||
"is_aborted": False,
|
||||
}
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# NODE 2: Text Extraction (Deterministic Python Function with Multimodal Ingestion)
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def extract_text_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
"""Node 2: Extract and normalize clinical text using ClinicalDocumentIngestionAgent."""
|
||||
if state.get("is_aborted", False):
|
||||
return {}
|
||||
|
||||
doc_id = state.get("document_id", "doc-unknown")
|
||||
raw_text = state.get("raw_text", "").strip()
|
||||
file_path = state.get("file_path") or state.get("pdf_path")
|
||||
file_bytes = state.get("file_bytes") or state.get("pdf_bytes")
|
||||
meta = state.get("metadata", {})
|
||||
filename = meta.get("filename") or (str(file_path) if file_path else f"doc_{doc_id}")
|
||||
|
||||
logger.info("Executing Node [2/10]: Text Extraction for doc_id=%s", doc_id)
|
||||
|
||||
# Case A: Raw text already supplied
|
||||
if raw_text:
|
||||
normalized = normalize_whitespace(raw_text)
|
||||
return {
|
||||
"raw_text": normalized,
|
||||
"detected_filetype": DocumentFormat.MANUAL_TEXT.value,
|
||||
"current_stage": PipelineStage.INGESTION,
|
||||
}
|
||||
|
||||
# Case B: Multi-format file extraction via ClinicalDocumentIngestionAgent
|
||||
file_source = file_bytes if file_bytes is not None else file_path
|
||||
if file_source:
|
||||
try:
|
||||
settings = get_settings()
|
||||
agent = ClinicalDocumentIngestionAgent(max_pdf_pages=settings.pdf_max_pages)
|
||||
ingest_res = agent.ingest(source=file_source, filename=filename)
|
||||
|
||||
if ingest_res.status != "SUCCESS":
|
||||
detail = (
|
||||
ingest_res.error_message
|
||||
or f"Document extraction failed for format {ingest_res.format.value}"
|
||||
)
|
||||
abstention = AbstentionRecord(
|
||||
diagnosis_id=None,
|
||||
raw_term=None,
|
||||
reason=AbstentionReason.INSUFFICIENT_CLINICAL_EVIDENCE
|
||||
if ingest_res.status == "EMPTY"
|
||||
else AbstentionReason.PROCESSING_ERROR,
|
||||
detail=detail,
|
||||
stage=PipelineStage.EXTRACTION,
|
||||
)
|
||||
return {
|
||||
"raw_text": "",
|
||||
"detected_filetype": ingest_res.format.value,
|
||||
"is_aborted": True,
|
||||
"abstentions": [abstention],
|
||||
"current_stage": PipelineStage.EXTRACTION,
|
||||
}
|
||||
|
||||
extracted_text = ingest_res.normalized_text.strip()
|
||||
if len(extracted_text) < 15:
|
||||
abstention = AbstentionRecord(
|
||||
diagnosis_id=None,
|
||||
raw_term=None,
|
||||
reason=AbstentionReason.INSUFFICIENT_CLINICAL_EVIDENCE,
|
||||
detail=f"Extracted clinical text ({len(extracted_text)} chars) is below required volume.",
|
||||
stage=PipelineStage.EXTRACTION,
|
||||
)
|
||||
return {
|
||||
"raw_text": extracted_text,
|
||||
"detected_filetype": ingest_res.format.value,
|
||||
"is_aborted": True,
|
||||
"abstentions": [abstention],
|
||||
"current_stage": PipelineStage.EXTRACTION,
|
||||
}
|
||||
|
||||
out_meta = dict(ingest_res.metadata)
|
||||
out_meta["page_count"] = ingest_res.page_count
|
||||
out_meta["word_count"] = ingest_res.word_count
|
||||
out_meta["is_ocr"] = ingest_res.is_ocr
|
||||
if ingest_res.ocr_confidence is not None:
|
||||
out_meta["ocr_confidence"] = ingest_res.ocr_confidence
|
||||
|
||||
return {
|
||||
"raw_text": extracted_text,
|
||||
"detected_filetype": ingest_res.format.value,
|
||||
"metadata": out_meta,
|
||||
"current_stage": PipelineStage.INGESTION,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.exception("Error extracting document text: %s", e)
|
||||
abstention = AbstentionRecord(
|
||||
diagnosis_id=None,
|
||||
raw_term=None,
|
||||
reason=AbstentionReason.PROCESSING_ERROR,
|
||||
detail=f"Extraction failed: {e}",
|
||||
stage=PipelineStage.EXTRACTION,
|
||||
)
|
||||
return {
|
||||
"is_aborted": True,
|
||||
"abstentions": [abstention],
|
||||
"current_stage": PipelineStage.EXTRACTION,
|
||||
}
|
||||
|
||||
return {}
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# NODE 3: Clinical Extraction Agent (LLM / Structured Mention Extraction)
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def extract_diagnoses_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
"""Node 3: Extract diagnosis mentions with verbatim evidence and deduplicate."""
|
||||
if state.get("is_aborted", False):
|
||||
return {}
|
||||
|
||||
doc_id = state.get("document_id", "doc-unknown")
|
||||
logger.info("Executing Node [3/10]: Clinical Extraction for doc_id=%s", doc_id)
|
||||
|
||||
# Preserve any pre-seeded diagnoses for test fixtures
|
||||
pre_extracted = state.get("extracted_diagnoses") or state.get("extracted_conditions")
|
||||
if pre_extracted:
|
||||
return {
|
||||
"extracted_diagnoses": state.get("extracted_diagnoses", []),
|
||||
"extracted_conditions": state.get("extracted_conditions", []),
|
||||
"current_stage": PipelineStage.EXTRACTION,
|
||||
}
|
||||
|
||||
raw_text = state.get("raw_text", "").strip()
|
||||
if not raw_text:
|
||||
abstention = AbstentionRecord(
|
||||
diagnosis_id=None,
|
||||
raw_term=None,
|
||||
reason=AbstentionReason.INSUFFICIENT_CLINICAL_EVIDENCE,
|
||||
detail="Cannot extract diagnoses: document text is empty.",
|
||||
stage=PipelineStage.EXTRACTION,
|
||||
)
|
||||
return {
|
||||
"is_aborted": True,
|
||||
"abstentions": [abstention],
|
||||
"current_stage": PipelineStage.EXTRACTION,
|
||||
}
|
||||
|
||||
# Execute Clinical Extraction Agent
|
||||
try:
|
||||
settings = get_settings()
|
||||
llm = (
|
||||
ModelFactory.create_llm(settings)
|
||||
if settings.get_resolved_model_path().exists()
|
||||
else None
|
||||
)
|
||||
agent = ClinicalExtractionAgent(llm=llm) if llm else None
|
||||
|
||||
extracted_conditions: list[ExtractedClinicalCondition] = []
|
||||
if agent is not None:
|
||||
result = agent.extract(raw_text)
|
||||
extracted_conditions = result.conditions
|
||||
else:
|
||||
# Deterministic rule-based extraction fallback for testing/offline environments
|
||||
extracted_conditions = _extract_conditions_deterministically(raw_text)
|
||||
|
||||
# Guardrail 7: Remove duplicate diagnosis mentions and subsumed generic terms
|
||||
seen_terms: set[str] = set()
|
||||
deduplicated: list[ExtractedClinicalCondition] = []
|
||||
legacy_extracted: list[ExtractedDiagnosis] = []
|
||||
|
||||
# Sort so that longer/more specific descriptions come first
|
||||
sorted_conditions = sorted(
|
||||
extracted_conditions,
|
||||
key=lambda c: len(
|
||||
getattr(c, "normalized_description", None) or getattr(c, "normalized_term", "")
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
for cond in sorted_conditions:
|
||||
term = (
|
||||
getattr(cond, "normalized_description", None)
|
||||
or getattr(cond, "normalized_term", "")
|
||||
).strip()
|
||||
key = term.lower()
|
||||
if not key:
|
||||
continue
|
||||
|
||||
# Subsumption check: If a more specific condition already subsumes this generic term
|
||||
is_subsumed = False
|
||||
for seen in seen_terms:
|
||||
if key == seen:
|
||||
is_subsumed = True
|
||||
break
|
||||
if "heart failure" in key and "heart failure" in seen:
|
||||
is_subsumed = True
|
||||
break
|
||||
if "kidney disease" in key and "kidney disease" in seen:
|
||||
is_subsumed = True
|
||||
break
|
||||
if "diabetes" in key and "diabetes" in seen:
|
||||
is_subsumed = True
|
||||
break
|
||||
if "hypertension" in key and "hypertension" in seen:
|
||||
is_subsumed = True
|
||||
break
|
||||
|
||||
if is_subsumed:
|
||||
continue
|
||||
|
||||
seen_terms.add(key)
|
||||
deduplicated.append(cond)
|
||||
legacy_extracted.append(
|
||||
ExtractedDiagnosis(
|
||||
diagnosis_id=cond.condition_id,
|
||||
raw_term=term,
|
||||
evidence=EvidenceSnippet(
|
||||
quote=cond.evidence_text,
|
||||
source_section=cond.section,
|
||||
),
|
||||
extraction_confidence=cond.confidence_score,
|
||||
)
|
||||
)
|
||||
|
||||
if not deduplicated:
|
||||
abstention = AbstentionRecord(
|
||||
diagnosis_id=None,
|
||||
raw_term=None,
|
||||
reason=AbstentionReason.INSUFFICIENT_CLINICAL_EVIDENCE,
|
||||
detail="No clinical diagnosis mentions identified in document.",
|
||||
stage=PipelineStage.EXTRACTION,
|
||||
)
|
||||
return {
|
||||
"extracted_conditions": [],
|
||||
"extracted_diagnoses": [],
|
||||
"abstentions": [abstention],
|
||||
"is_aborted": True,
|
||||
"current_stage": PipelineStage.EXTRACTION,
|
||||
}
|
||||
|
||||
return {
|
||||
"extracted_conditions": deduplicated,
|
||||
"extracted_diagnoses": legacy_extracted,
|
||||
"current_stage": PipelineStage.EXTRACTION,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.exception("Error in clinical extraction: %s", e)
|
||||
abstention = AbstentionRecord(
|
||||
diagnosis_id=None,
|
||||
raw_term=None,
|
||||
reason=AbstentionReason.PROCESSING_ERROR,
|
||||
detail=f"Extraction failure: {e}",
|
||||
stage=PipelineStage.EXTRACTION,
|
||||
)
|
||||
return {
|
||||
"is_aborted": True,
|
||||
"abstentions": [abstention],
|
||||
"current_stage": PipelineStage.EXTRACTION,
|
||||
}
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# NODE 4: Context & Relevance Agent
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def analyze_context_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
"""Node 4: Evaluate inpatient clinical relevance, status, temporality, and certainty."""
|
||||
if state.get("is_aborted", False):
|
||||
return {}
|
||||
|
||||
doc_id = state.get("document_id", "doc-unknown")
|
||||
logger.info("Executing Node [4/10]: Context & Relevance for doc_id=%s", doc_id)
|
||||
|
||||
# Preserve pre-seeded assessments if present
|
||||
if state.get("context_assessments") or state.get("contextualized_diagnoses"):
|
||||
return {
|
||||
"context_assessments": state.get("context_assessments", []),
|
||||
"contextualized_diagnoses": state.get("contextualized_diagnoses", []),
|
||||
"current_stage": PipelineStage.CONTEXT_ANALYSIS,
|
||||
}
|
||||
|
||||
from medical_coding.models.base import BaseLocalLLM
|
||||
|
||||
class RulePassThroughLLM(BaseLocalLLM):
|
||||
def generate(self, prompt: str) -> str:
|
||||
return ""
|
||||
|
||||
def get_model_info(self) -> dict[str, Any]:
|
||||
return {"model_name": "rule-passthrough"}
|
||||
|
||||
settings = get_settings()
|
||||
llm = (
|
||||
ModelFactory.create_llm(settings)
|
||||
if settings.get_resolved_model_path().exists()
|
||||
else RulePassThroughLLM()
|
||||
)
|
||||
agent = ContextAndRelevanceAgent(llm=llm)
|
||||
return agent.run_node(state)
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# NODE 5: Primary / Secondary Classification
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def classify_diagnoses_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
"""Node 5: Classify conditions into maximum ONE Primary, Secondary, and Excluded roles."""
|
||||
if state.get("is_aborted", False):
|
||||
return {}
|
||||
|
||||
doc_id = state.get("document_id", "doc-unknown")
|
||||
logger.info("Executing Node [5/10]: Classification for doc_id=%s", doc_id)
|
||||
|
||||
# Preserve pre-seeded classified diagnoses if provided
|
||||
if state.get("classified_diagnoses"):
|
||||
return {
|
||||
"classified_diagnoses": state.get("classified_diagnoses", []),
|
||||
"current_stage": PipelineStage.CLASSIFICATION,
|
||||
}
|
||||
|
||||
from medical_coding.models.base import BaseLocalLLM
|
||||
|
||||
class RulePassThroughLLM(BaseLocalLLM):
|
||||
def generate(self, prompt: str) -> str:
|
||||
return ""
|
||||
|
||||
def get_model_info(self) -> dict[str, Any]:
|
||||
return {"model_name": "rule-passthrough"}
|
||||
|
||||
classifier = PrimarySecondaryClassifier(llm=RulePassThroughLLM())
|
||||
return classifier.run_node(state)
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# NODE 6: ICD Candidate Retrieval (Deterministic Python Function over Local Dataset)
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
"""Node 6: Retrieve candidate ICD-10-CM codes exclusively from local dataset for billable conditions."""
|
||||
if state.get("is_aborted", False):
|
||||
return {}
|
||||
|
||||
doc_id = state.get("document_id", "doc-unknown")
|
||||
logger.info("Executing Node [6/10]: Candidate Retrieval for doc_id=%s", doc_id)
|
||||
|
||||
# If candidate pool is already provided (e.g. test fixture), preserve it
|
||||
if state.get("candidate_pool"):
|
||||
return {
|
||||
"candidate_pool": state.get("candidate_pool", {}),
|
||||
"current_stage": PipelineStage.RETRIEVAL,
|
||||
}
|
||||
|
||||
classified = state.get("classified_diagnoses", [])
|
||||
billable_conditions = [
|
||||
c
|
||||
for c in classified
|
||||
if c.is_billable_candidate and c.role in (DiagnosisRole.PRIMARY, DiagnosisRole.SECONDARY)
|
||||
]
|
||||
|
||||
if not billable_conditions:
|
||||
logger.info("No billable diagnoses to retrieve for doc_id=%s", doc_id)
|
||||
return {
|
||||
"candidate_pool": {},
|
||||
"current_stage": PipelineStage.RETRIEVAL,
|
||||
}
|
||||
|
||||
_, retriever = get_or_initialize_retrieval_system()
|
||||
|
||||
candidate_pool: dict[str, list[ICDCandidate]] = {}
|
||||
|
||||
def _retrieve_for_condition(cond: ClassifiedDiagnosis) -> tuple[str, list[ICDCandidate]]:
|
||||
query = cond.raw_term
|
||||
hits = retriever.retrieve(query, top_k=10)
|
||||
return cond.diagnosis_id, hits
|
||||
|
||||
# Parallelize retrieval across diagnoses within document
|
||||
with concurrent.futures.ThreadPoolExecutor(
|
||||
max_workers=min(len(billable_conditions), 4)
|
||||
) as executor:
|
||||
futures = [executor.submit(_retrieve_for_condition, c) for c in billable_conditions]
|
||||
for f in concurrent.futures.as_completed(futures):
|
||||
diag_id, hits = f.result()
|
||||
candidate_pool[diag_id] = hits
|
||||
|
||||
return {
|
||||
"candidate_pool": candidate_pool,
|
||||
"current_stage": PipelineStage.RETRIEVAL,
|
||||
}
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# NODE 7: ICD Candidate Ranking Agent
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def rank_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
"""Node 7: Rank retrieved candidates against clinical evidence strictly from candidate pool."""
|
||||
if state.get("is_aborted", False):
|
||||
return {}
|
||||
|
||||
doc_id = state.get("document_id", "doc-unknown")
|
||||
logger.info("Executing Node [7/10]: Candidate Ranking for doc_id=%s", doc_id)
|
||||
|
||||
# Preserve pre-seeded ranked selections if present
|
||||
if state.get("ranked_selections"):
|
||||
return {
|
||||
"ranked_selections": state.get("ranked_selections", []),
|
||||
"current_stage": PipelineStage.RANKING,
|
||||
}
|
||||
|
||||
classified = state.get("classified_diagnoses", [])
|
||||
candidate_pool = state.get("candidate_pool", {})
|
||||
|
||||
catalog, _ = get_or_initialize_retrieval_system()
|
||||
validator = CandidateRankingDeterministicValidator(catalog=catalog, min_confidence=0.40)
|
||||
|
||||
settings = get_settings()
|
||||
llm = ModelFactory.create_llm(settings) if settings.get_resolved_model_path().exists() else None
|
||||
agent = CandidateRankingAgent(llm=llm, validator=validator, min_confidence=0.40)
|
||||
|
||||
ranked_selections: list[RankedSelection] = []
|
||||
|
||||
for cond in classified:
|
||||
candidates = candidate_pool.get(cond.diagnosis_id, [])
|
||||
selection = agent.rank_candidates(cond, candidates)
|
||||
ranked_selections.append(selection)
|
||||
|
||||
return {
|
||||
"ranked_selections": ranked_selections,
|
||||
"current_stage": PipelineStage.RANKING,
|
||||
}
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# NODE 8: Deterministic Validation (Deterministic Python Function)
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def validate_codes_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
"""Node 8: Enforce multi-rule deterministic invariants across local dataset and clinical rules."""
|
||||
if state.get("is_aborted", False):
|
||||
return {}
|
||||
|
||||
doc_id = state.get("document_id", "doc-unknown")
|
||||
logger.info("Executing Node [8/10]: Deterministic Validation for doc_id=%s", doc_id)
|
||||
|
||||
classified = state.get("classified_diagnoses", [])
|
||||
selections = state.get("ranked_selections", [])
|
||||
catalog, _ = get_or_initialize_retrieval_system()
|
||||
|
||||
validator = DeterministicValidator(catalog=catalog)
|
||||
validated_list, abstention_list = validator.validate_encounter_set(classified, selections)
|
||||
|
||||
# Guardrail 8: Consolidate duplicate ICD codes
|
||||
code_map: dict[str, ValidatedDiagnosis] = {}
|
||||
deduped_validated: list[ValidatedDiagnosis] = []
|
||||
|
||||
for item in validated_list:
|
||||
clean_code = format_icd_code(item.code)
|
||||
if clean_code in code_map:
|
||||
existing = code_map[clean_code]
|
||||
# Primary role takes precedence
|
||||
if item.role == DiagnosisRole.PRIMARY:
|
||||
existing.role = DiagnosisRole.PRIMARY
|
||||
# Combine evidence quotes
|
||||
if item.evidence.quote not in existing.evidence.quote:
|
||||
existing.evidence.quote = f"{existing.evidence.quote} | {item.evidence.quote}"
|
||||
else:
|
||||
code_map[clean_code] = item
|
||||
deduped_validated.append(item)
|
||||
|
||||
return {
|
||||
"validated_diagnoses": deduped_validated,
|
||||
"abstentions": abstention_list,
|
||||
"current_stage": PipelineStage.VALIDATION,
|
||||
}
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# NODE 9: Confidence & Abstention Evaluation (Deterministic Python Function)
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def evaluate_confidence_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
"""Node 9: Evaluate encounter-level confidence, audit trail, and abstention status."""
|
||||
doc_id = state.get("document_id", "doc-unknown")
|
||||
logger.info("Executing Node [9/10]: Confidence & Abstention Evaluation for doc_id=%s", doc_id)
|
||||
|
||||
validated = state.get("validated_diagnoses", [])
|
||||
classified = state.get("classified_diagnoses", [])
|
||||
selections = state.get("ranked_selections", [])
|
||||
candidate_pool = state.get("candidate_pool", {})
|
||||
|
||||
# Construct internal audit trail for every diagnosis:
|
||||
# document -> evidence -> diagnosis -> context -> classification -> retrieved candidates -> selected candidate -> validation -> final result
|
||||
selection_map = {s.diagnosis_id: s for s in selections}
|
||||
validated_map = {v.diagnosis_id: v for v in validated}
|
||||
|
||||
audit_records: list[dict[str, Any]] = []
|
||||
for cond in classified:
|
||||
sel = selection_map.get(cond.diagnosis_id)
|
||||
val = validated_map.get(cond.diagnosis_id)
|
||||
cand_list = candidate_pool.get(cond.diagnosis_id, [])
|
||||
|
||||
audit_entry = {
|
||||
"document_id": doc_id,
|
||||
"diagnosis_id": cond.diagnosis_id,
|
||||
"raw_term": cond.raw_term,
|
||||
"evidence": cond.context.evidence.quote if hasattr(cond.context, "evidence") else "",
|
||||
"context": {
|
||||
"certainty": cond.context.certainty,
|
||||
"temporality": cond.context.temporality,
|
||||
"negation": cond.context.negation,
|
||||
"acuity": cond.context.acuity,
|
||||
}
|
||||
if hasattr(cond, "context")
|
||||
else {},
|
||||
"classification": {
|
||||
"role": cond.role,
|
||||
"is_billable": cond.is_billable_candidate,
|
||||
"reason": cond.classification_reason,
|
||||
},
|
||||
"retrieved_candidates": [
|
||||
{"code": c.code, "description": c.description, "score": c.retrieval_score}
|
||||
for c in cand_list
|
||||
],
|
||||
"selected_candidate": {
|
||||
"code": sel.selected_code,
|
||||
"description": sel.selected_description,
|
||||
"confidence": sel.confidence,
|
||||
"reason": sel.ranking_reason,
|
||||
"decision": sel.decision,
|
||||
}
|
||||
if sel
|
||||
else None,
|
||||
"validation": {
|
||||
"status": "PASSED" if val else "REJECTED_OR_ABSTAINED",
|
||||
"checks": [c.model_dump() for c in val.checks] if val else [],
|
||||
},
|
||||
"final_result": {
|
||||
"code": val.code if val else None,
|
||||
"description": val.description if val else None,
|
||||
"role": val.role if val else None,
|
||||
},
|
||||
}
|
||||
audit_records.append(audit_entry)
|
||||
|
||||
return {
|
||||
"audit_trail": audit_records,
|
||||
"current_stage": PipelineStage.VALIDATION,
|
||||
}
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# NODE 10: Final Output JSON (Conforming to Pydantic Schema)
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
"""Node 10: Assemble final Pydantic CodingResult payload and audit summary."""
|
||||
doc_id = state.get("document_id", "doc-unknown")
|
||||
logger.info("Executing Node [10/10]: Final Output Generation for doc_id=%s", doc_id)
|
||||
|
||||
validated = state.get("validated_diagnoses", [])
|
||||
abstentions = state.get("abstentions", [])
|
||||
audit_trail = state.get("audit_trail", [])
|
||||
|
||||
primary_response: CodedDiagnosisResponse | None = None
|
||||
secondary_responses: list[CodedDiagnosisResponse] = []
|
||||
|
||||
for item in validated:
|
||||
resp = CodedDiagnosisResponse(
|
||||
code=item.code,
|
||||
description=item.description,
|
||||
role=item.role,
|
||||
acuity=Acuity.ACUTE
|
||||
if "acute" in item.description.lower()
|
||||
else Acuity.CHRONIC
|
||||
if "chronic" in item.description.lower()
|
||||
else Acuity.UNSPECIFIED,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
evidence_quote=item.evidence.quote,
|
||||
confidence_score=item.confidence_score,
|
||||
is_terminal_billable=True,
|
||||
)
|
||||
if item.role == DiagnosisRole.PRIMARY:
|
||||
primary_response = resp
|
||||
elif item.role == DiagnosisRole.SECONDARY:
|
||||
secondary_responses.append(resp)
|
||||
|
||||
# Determine execution status
|
||||
if primary_response or secondary_responses:
|
||||
status = ExecutionStatus.SUCCESS if not abstentions else ExecutionStatus.PARTIAL_SUCCESS
|
||||
elif abstentions or state.get("is_aborted", False):
|
||||
status = ExecutionStatus.ABSTAINED
|
||||
else:
|
||||
status = ExecutionStatus.SUCCESS
|
||||
|
||||
result = CodingResult(
|
||||
document_id=doc_id,
|
||||
status=status,
|
||||
primary_diagnosis=primary_response,
|
||||
secondary_diagnoses=secondary_responses,
|
||||
abstentions=abstentions,
|
||||
processing_time_ms=0.0,
|
||||
models_used={"llm": "local_gguf", "retrieval": "local_faiss_bm25"},
|
||||
metadata={
|
||||
"audit_trail": audit_trail,
|
||||
"validated_code_count": len(validated),
|
||||
"abstention_count": len(abstentions),
|
||||
},
|
||||
)
|
||||
|
||||
return {
|
||||
"final_result": result,
|
||||
"current_stage": PipelineStage.FINALIZATION,
|
||||
}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Deterministic Extraction & Context Helpers for Zero-LLM Fallback
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _extract_conditions_deterministically(text: str) -> list[ExtractedClinicalCondition]:
|
||||
"""Pattern-based condition extractor used when running purely deterministic offline test passes."""
|
||||
patterns = [
|
||||
(r"\bacute systolic heart failure\b", "Acute systolic heart failure", "I50.21"),
|
||||
(r"\bchronic systolic heart failure\b", "Chronic systolic heart failure", "I50.22"),
|
||||
(r"\bcongestive heart failure\b", "Congestive heart failure", "I50.9"),
|
||||
(r"\bheart failure\b", "Heart failure", "I50.9"),
|
||||
(r"\btype 2 diabetes mellitus\b", "Type 2 diabetes mellitus", "E11.9"),
|
||||
(r"\btype 2 diabetes\b", "Type 2 diabetes mellitus", "E11.9"),
|
||||
(r"\bessential primary hypertension\b", "Essential primary hypertension", "I10"),
|
||||
(r"\bhypertension\b", "Essential primary hypertension", "I10"),
|
||||
(r"\bchronic kidney disease stage 3\b", "Chronic kidney disease stage 3", "N18.3"),
|
||||
(r"\bchronic kidney disease\b", "Chronic kidney disease", "N18.9"),
|
||||
(r"\bacute kidney injury\b", "Acute kidney injury", "N17.9"),
|
||||
(r"\batrial fibrillation\b", "Atrial fibrillation", "I48.91"),
|
||||
(r"\bpneumonia\b", "Pneumonia", "J18.9"),
|
||||
]
|
||||
extracted: list[ExtractedClinicalCondition] = []
|
||||
text_lower = text.lower()
|
||||
|
||||
for pat, norm_name, _ in patterns:
|
||||
import re
|
||||
|
||||
match = re.search(pat, text_lower)
|
||||
if match:
|
||||
# Subsumption check
|
||||
norm_lower = norm_name.lower()
|
||||
if any(
|
||||
norm_lower in e.normalized_description.lower()
|
||||
and norm_lower != e.normalized_description.lower()
|
||||
for e in extracted
|
||||
):
|
||||
continue
|
||||
if "heart failure" in norm_lower and any(
|
||||
"heart failure" in e.normalized_description.lower() for e in extracted
|
||||
):
|
||||
continue
|
||||
if "kidney disease" in norm_lower and any(
|
||||
"kidney disease" in e.normalized_description.lower() for e in extracted
|
||||
):
|
||||
continue
|
||||
if "diabetes" in norm_lower and any(
|
||||
"diabetes" in e.normalized_description.lower() for e in extracted
|
||||
):
|
||||
continue
|
||||
if "hypertension" in norm_lower and any(
|
||||
"hypertension" in e.normalized_description.lower() for e in extracted
|
||||
):
|
||||
continue
|
||||
|
||||
start, end = match.span()
|
||||
# Extract sentence window as evidence
|
||||
window_start = max(0, text.rfind(".", 0, start) + 1)
|
||||
window_end = text.find(".", end)
|
||||
if window_end == -1:
|
||||
window_end = len(text)
|
||||
sentence = text[window_start : window_end + 1].strip()
|
||||
|
||||
cond = ExtractedClinicalCondition(
|
||||
condition_id=f"cond-{len(extracted) + 1}",
|
||||
original_mention=text[start:end],
|
||||
normalized_description=norm_name,
|
||||
evidence_text=sentence or text[start:end],
|
||||
evidence_location=EvidenceLocation(
|
||||
section="Documentation", start_char=start, end_char=end
|
||||
),
|
||||
status=ConditionStatus.ACTIVE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
negation=NegationStatus.AFFIRMATIVE,
|
||||
section="Discharge Diagnosis",
|
||||
confidence_score=0.95,
|
||||
)
|
||||
extracted.append(cond)
|
||||
|
||||
return extracted
|
||||
|
||||
|
||||
def _assess_context_deterministically(
|
||||
term: str,
|
||||
quote: str,
|
||||
section: str,
|
||||
diag_id: str,
|
||||
) -> ContextAssessment:
|
||||
"""Evaluate context against clinical rules without requiring an external LLM."""
|
||||
quote_lower = quote.lower()
|
||||
section_lower = section.lower()
|
||||
|
||||
# Rule 1: Negation / Ruled out
|
||||
is_negated = any(
|
||||
w in quote_lower
|
||||
for w in ["denies", "no history of", "no evidence of", "ruled out", "negative for"]
|
||||
)
|
||||
if is_negated:
|
||||
return ContextAssessment(
|
||||
diagnosis=term,
|
||||
condition_id=diag_id,
|
||||
current_relevance=False,
|
||||
coding_candidate=False,
|
||||
status=ConditionStatus.RESOLVED,
|
||||
certainty=Certainty.RULED_OUT,
|
||||
temporality=Temporality.RESOLVED,
|
||||
negation=NegationStatus.NEGATED,
|
||||
evidence=quote or f"Negation or rule-out documentation for {term}",
|
||||
reason=f"Condition '{term}' was explicitly ruled out or negated.",
|
||||
treated_or_managed=False,
|
||||
monitored=False,
|
||||
affected_clinical_management=False,
|
||||
influenced_treatment=False,
|
||||
)
|
||||
|
||||
# Rule 2: Past medical history without inpatient monitoring/treatment
|
||||
is_pmh = "past medical" in section_lower or "pmh" in section_lower
|
||||
has_active_care = any(
|
||||
w in quote_lower
|
||||
for w in [
|
||||
"adjusted",
|
||||
"monitored",
|
||||
"treated",
|
||||
"administered",
|
||||
"infusion",
|
||||
"iv ",
|
||||
"prescribed",
|
||||
"managed",
|
||||
]
|
||||
)
|
||||
if is_pmh and not has_active_care:
|
||||
return ContextAssessment(
|
||||
diagnosis=term,
|
||||
condition_id=diag_id,
|
||||
current_relevance=False,
|
||||
coding_candidate=False,
|
||||
status=ConditionStatus.HISTORICAL,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.HISTORICAL,
|
||||
negation=NegationStatus.AFFIRMATIVE,
|
||||
evidence=quote or f"Historical PMH documentation for {term}",
|
||||
reason=f"Condition '{term}' documented solely in Past Medical History without inpatient management.",
|
||||
treated_or_managed=False,
|
||||
monitored=False,
|
||||
affected_clinical_management=False,
|
||||
influenced_treatment=False,
|
||||
)
|
||||
|
||||
# Rule 3: Active condition
|
||||
return ContextAssessment(
|
||||
diagnosis=term,
|
||||
condition_id=diag_id,
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACTIVE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
negation=NegationStatus.AFFIRMATIVE,
|
||||
evidence=quote or f"Active clinical evidence for {term}",
|
||||
reason=f"Condition '{term}' active and managed during the inpatient admission.",
|
||||
treated_or_managed=True,
|
||||
monitored=True,
|
||||
affected_clinical_management=True,
|
||||
influenced_treatment=True,
|
||||
)
|
||||
@@ -0,0 +1,197 @@
|
||||
"""Asynchronous document and batch execution pipeline orchestrating LangGraph workflows."""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
from medical_coding.graph.state import create_initial_state
|
||||
from medical_coding.graph.workflow import get_compiled_graph
|
||||
from medical_coding.pdf.concurrency import BoundedDocumentGate
|
||||
from medical_coding.schemas.enums import ExecutionStatus
|
||||
from medical_coding.schemas.response import BatchJobStatus, CodingResult
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
async def process_clinical_document(
|
||||
source: Path | bytes | str = "",
|
||||
document_id: str | None = None,
|
||||
pdf_path: str | Path | None = None,
|
||||
pdf_bytes: bytes | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
graph: Any = None,
|
||||
) -> CodingResult:
|
||||
"""Execute end-to-end medical coding pipeline for a single clinical document or text.
|
||||
|
||||
Args:
|
||||
source: Text string, PDF file Path, or raw PDF bytes.
|
||||
document_id: Optional unique encounter ID.
|
||||
pdf_path: Optional explicit path to PDF source.
|
||||
pdf_bytes: Optional explicit raw PDF file bytes.
|
||||
metadata: Optional dictionary of encounter context.
|
||||
graph: Optional compiled LangGraph workflow app instance.
|
||||
|
||||
Returns:
|
||||
Validated CodingResult conforming to Pydantic schema with internal audit trail.
|
||||
"""
|
||||
start_time = time.perf_counter()
|
||||
doc_id = document_id or f"doc-{uuid4().hex[:8]}"
|
||||
app = graph or get_compiled_graph()
|
||||
|
||||
raw_text = ""
|
||||
resolved_pdf_path = str(pdf_path) if pdf_path else None
|
||||
resolved_pdf_bytes = pdf_bytes
|
||||
source_type = "text"
|
||||
|
||||
if resolved_pdf_path:
|
||||
source_type = "pdf_file"
|
||||
elif resolved_pdf_bytes:
|
||||
source_type = "pdf_bytes"
|
||||
elif isinstance(source, bytes):
|
||||
resolved_pdf_bytes = source
|
||||
source_type = "pdf_bytes"
|
||||
elif isinstance(source, Path):
|
||||
resolved_pdf_path = str(source)
|
||||
source_type = "pdf_file"
|
||||
elif isinstance(source, str):
|
||||
# Determine if string points to an existing file
|
||||
p = Path(source)
|
||||
if p.exists() and p.is_file():
|
||||
resolved_pdf_path = str(p)
|
||||
source_type = "pdf_file"
|
||||
else:
|
||||
raw_text = source
|
||||
source_type = "text"
|
||||
|
||||
initial_state = create_initial_state(
|
||||
document_id=doc_id,
|
||||
raw_text=raw_text,
|
||||
pdf_path=resolved_pdf_path,
|
||||
pdf_bytes=resolved_pdf_bytes,
|
||||
source_type=source_type,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
logger.info("Starting pipeline execution for doc_id=%s (source_type=%s)", doc_id, source_type)
|
||||
final_state = await app.ainvoke(initial_state)
|
||||
|
||||
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
||||
|
||||
result: CodingResult | None = final_state.get("final_result")
|
||||
if result is None:
|
||||
# Fallback empty result
|
||||
result = CodingResult(
|
||||
document_id=doc_id,
|
||||
status=ExecutionStatus.ABSTAINED
|
||||
if final_state.get("abstentions")
|
||||
else ExecutionStatus.ERROR,
|
||||
primary_diagnosis=None,
|
||||
secondary_diagnoses=[],
|
||||
abstentions=final_state.get("abstentions", []),
|
||||
processing_time_ms=elapsed_ms,
|
||||
models_used={"llm": "local_gguf", "retrieval": "local_faiss_bm25"},
|
||||
metadata=final_state.get("metadata", {}),
|
||||
)
|
||||
else:
|
||||
result.processing_time_ms = round(elapsed_ms, 2)
|
||||
|
||||
logger.info(
|
||||
"Completed pipeline execution for doc_id=%s in %.2fms (status=%s, primary=%s, secondaries=%d)",
|
||||
doc_id,
|
||||
elapsed_ms,
|
||||
result.status,
|
||||
result.primary_diagnosis.code if result.primary_diagnosis else "None",
|
||||
len(result.secondary_diagnoses),
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
async def process_clinical_document_batch(
|
||||
documents: list[Path | bytes | str | dict[str, Any]],
|
||||
job_id: str | None = None,
|
||||
max_concurrency: int | None = None,
|
||||
settings: Settings | None = None,
|
||||
) -> BatchJobStatus:
|
||||
"""Asynchronously process a batch of clinical documents (e.g. >= 10 PDFs).
|
||||
|
||||
ARCHITECTURAL PARALLELISM GUARANTEE:
|
||||
- Multiple documents (>= 10) are ingested, parsed, and validated in parallel.
|
||||
- Diagnosis-level candidate retrieval is parallelized within each document.
|
||||
- Model-level concurrency is bounded via LLMLifecycleManager to avoid spawning
|
||||
independent GPT4All instances.
|
||||
|
||||
Args:
|
||||
documents: List of file paths, bytes, text strings, or dicts with source and metadata.
|
||||
job_id: Optional batch identifier.
|
||||
max_concurrency: Maximum simultaneous document-level pipeline tasks (default: 10).
|
||||
settings: Application settings.
|
||||
|
||||
Returns:
|
||||
BatchJobStatus summarizing overall completion, errors, and individual CodingResults.
|
||||
"""
|
||||
cfg = settings or get_settings()
|
||||
concurrency_limit = max_concurrency or cfg.max_document_concurrency
|
||||
batch_id = job_id or f"batch-{uuid4().hex[:8]}"
|
||||
|
||||
gate = BoundedDocumentGate(max_concurrency=concurrency_limit, settings=cfg)
|
||||
app = get_compiled_graph()
|
||||
|
||||
logger.info(
|
||||
"Beginning batch execution job_id=%s with %d documents (concurrency limit: %d)",
|
||||
batch_id,
|
||||
len(documents),
|
||||
concurrency_limit,
|
||||
)
|
||||
|
||||
async def _process_bounded(item: Any, idx: int) -> CodingResult:
|
||||
doc_source = item
|
||||
doc_id = f"{batch_id}-doc-{idx + 1}"
|
||||
meta: dict[str, Any] = {"batch_index": idx, "batch_id": batch_id}
|
||||
|
||||
if isinstance(item, dict):
|
||||
doc_source = item.get("source") or item.get("text") or item.get("file_path")
|
||||
doc_id = item.get("document_id") or doc_id
|
||||
meta.update(item.get("metadata", {}))
|
||||
|
||||
async with gate.get_semaphore():
|
||||
return await process_clinical_document(
|
||||
source=doc_source,
|
||||
document_id=doc_id,
|
||||
metadata=meta,
|
||||
graph=app,
|
||||
)
|
||||
|
||||
tasks = [_process_bounded(doc, i) for i, doc in enumerate(documents)]
|
||||
results: list[CodingResult] = await asyncio.gather(*tasks)
|
||||
|
||||
completed = sum(
|
||||
1
|
||||
for r in results
|
||||
if r.status
|
||||
in (ExecutionStatus.SUCCESS, ExecutionStatus.PARTIAL_SUCCESS, ExecutionStatus.ABSTAINED)
|
||||
)
|
||||
failed = sum(1 for r in results if r.status == ExecutionStatus.ERROR)
|
||||
|
||||
batch_status = BatchJobStatus(
|
||||
job_id=batch_id,
|
||||
total_documents=len(documents),
|
||||
completed_documents=completed,
|
||||
failed_documents=failed,
|
||||
status="completed" if failed == 0 else "failed" if completed == 0 else "completed",
|
||||
results=results,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"Batch job_id=%s finished: %d total, %d completed, %d failed",
|
||||
batch_id,
|
||||
batch_status.total_documents,
|
||||
batch_status.completed_documents,
|
||||
batch_status.failed_documents,
|
||||
)
|
||||
|
||||
return batch_status
|
||||
@@ -0,0 +1,51 @@
|
||||
"""LangGraph state re-exports and pipeline initialization helpers."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.schemas.enums import PipelineStage
|
||||
from medical_coding.schemas.state import PipelineGraphState
|
||||
|
||||
|
||||
def create_initial_state(
|
||||
document_id: str,
|
||||
raw_text: str = "",
|
||||
pdf_path: str | None = None,
|
||||
pdf_bytes: bytes | None = None,
|
||||
file_path: str | None = None,
|
||||
file_bytes: bytes | None = None,
|
||||
source_type: str = "text",
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> PipelineGraphState:
|
||||
"""Create a clean, standardized initial state dictionary for LangGraph execution."""
|
||||
# Reconcile file_bytes / pdf_bytes and file_path / pdf_path
|
||||
resolved_bytes = file_bytes if file_bytes is not None else pdf_bytes
|
||||
resolved_path = file_path if file_path is not None else pdf_path
|
||||
|
||||
return {
|
||||
"document_id": document_id,
|
||||
"raw_text": raw_text,
|
||||
"pdf_path": resolved_path,
|
||||
"pdf_bytes": resolved_bytes,
|
||||
"file_path": resolved_path,
|
||||
"file_bytes": resolved_bytes,
|
||||
"detected_filetype": None,
|
||||
"source_type": source_type,
|
||||
"metadata": metadata or {},
|
||||
"extracted_diagnoses": [],
|
||||
"extracted_conditions": [],
|
||||
"context_assessments": [],
|
||||
"contextualized_diagnoses": [],
|
||||
"classified_diagnoses": [],
|
||||
"candidate_pool": {},
|
||||
"ranked_selections": [],
|
||||
"validated_diagnoses": [],
|
||||
"abstentions": [],
|
||||
"audit_trail": [],
|
||||
"current_stage": PipelineStage.INGESTION,
|
||||
"errors": [],
|
||||
"is_aborted": False,
|
||||
"final_result": None,
|
||||
}
|
||||
|
||||
|
||||
__all__ = ["PipelineGraphState", "create_initial_state"]
|
||||
@@ -0,0 +1,178 @@
|
||||
"""Compilation and construction of the complete LangGraph medical coding workflow."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from langgraph.graph import END, START, StateGraph
|
||||
|
||||
from medical_coding.graph.edges import (
|
||||
route_after_classification,
|
||||
route_after_document_validation,
|
||||
route_after_extraction,
|
||||
route_after_retrieval,
|
||||
route_after_text_extraction,
|
||||
)
|
||||
from medical_coding.graph.nodes import (
|
||||
analyze_context_node,
|
||||
classify_diagnoses_node,
|
||||
evaluate_confidence_node,
|
||||
extract_diagnoses_node,
|
||||
extract_text_node,
|
||||
finalize_output_node,
|
||||
rank_candidates_node,
|
||||
retrieve_candidates_node,
|
||||
validate_codes_node,
|
||||
validate_document_node,
|
||||
)
|
||||
from medical_coding.schemas.state import PipelineGraphState
|
||||
|
||||
|
||||
def create_coding_workflow() -> StateGraph:
|
||||
"""Build the state graph for medical ICD-10-CM coding.
|
||||
|
||||
Target Graph Flow:
|
||||
START
|
||||
↓
|
||||
Document Validation (validate_document)
|
||||
↓
|
||||
Text Extraction (extract_text)
|
||||
↓
|
||||
Clinical Extraction Agent (extract_diagnoses)
|
||||
↓
|
||||
Context/Evidence Agent (analyze_context)
|
||||
↓
|
||||
Primary/Secondary Classification (classify_diagnoses)
|
||||
↓
|
||||
ICD Candidate Retrieval (retrieve_candidates)
|
||||
↓
|
||||
ICD Candidate Ranking (rank_candidates)
|
||||
↓
|
||||
Deterministic Validation (validate_codes)
|
||||
↓
|
||||
Confidence / Abstention (evaluate_confidence)
|
||||
↓
|
||||
Final JSON (finalize_output)
|
||||
↓
|
||||
END
|
||||
"""
|
||||
workflow = StateGraph(PipelineGraphState)
|
||||
|
||||
# 1. Register Nodes in strict sequence
|
||||
workflow.add_node("validate_document", validate_document_node)
|
||||
workflow.add_node("extract_text", extract_text_node)
|
||||
workflow.add_node("extract_diagnoses", extract_diagnoses_node)
|
||||
workflow.add_node("analyze_context", analyze_context_node)
|
||||
workflow.add_node("classify_diagnoses", classify_diagnoses_node)
|
||||
workflow.add_node("retrieve_candidates", retrieve_candidates_node)
|
||||
workflow.add_node("rank_candidates", rank_candidates_node)
|
||||
workflow.add_node("validate_codes", validate_codes_node)
|
||||
workflow.add_node("evaluate_confidence", evaluate_confidence_node)
|
||||
workflow.add_node("finalize_output", finalize_output_node)
|
||||
|
||||
# 2. Initial Transition from START to Document Validation
|
||||
workflow.add_edge(START, "validate_document")
|
||||
|
||||
# 3. Conditional Transition after Document Validation
|
||||
workflow.add_conditional_edges(
|
||||
"validate_document",
|
||||
route_after_document_validation,
|
||||
{
|
||||
"extract_text": "extract_text",
|
||||
"evaluate_confidence": "evaluate_confidence",
|
||||
},
|
||||
)
|
||||
|
||||
# 4. Conditional Transition after Text Extraction
|
||||
workflow.add_conditional_edges(
|
||||
"extract_text",
|
||||
route_after_text_extraction,
|
||||
{
|
||||
"extract_diagnoses": "extract_diagnoses",
|
||||
"evaluate_confidence": "evaluate_confidence",
|
||||
},
|
||||
)
|
||||
|
||||
# 5. Conditional Transition after Clinical Extraction
|
||||
workflow.add_conditional_edges(
|
||||
"extract_diagnoses",
|
||||
route_after_extraction,
|
||||
{
|
||||
"analyze_context": "analyze_context",
|
||||
"evaluate_confidence": "evaluate_confidence",
|
||||
},
|
||||
)
|
||||
|
||||
# 6. Linear Transition to Classification
|
||||
workflow.add_edge("analyze_context", "classify_diagnoses")
|
||||
|
||||
# 7. Conditional Transition after Classification
|
||||
workflow.add_conditional_edges(
|
||||
"classify_diagnoses",
|
||||
route_after_classification,
|
||||
{
|
||||
"retrieve_candidates": "retrieve_candidates",
|
||||
"evaluate_confidence": "evaluate_confidence",
|
||||
},
|
||||
)
|
||||
|
||||
# 8. Conditional Transition after Retrieval
|
||||
workflow.add_conditional_edges(
|
||||
"retrieve_candidates",
|
||||
route_after_retrieval,
|
||||
{
|
||||
"rank_candidates": "rank_candidates",
|
||||
"validate_codes": "validate_codes",
|
||||
},
|
||||
)
|
||||
|
||||
# 9. Linear Sequence through Validation & Finalization
|
||||
workflow.add_edge("rank_candidates", "validate_codes")
|
||||
workflow.add_edge("validate_codes", "evaluate_confidence")
|
||||
workflow.add_edge("evaluate_confidence", "finalize_output")
|
||||
workflow.add_edge("finalize_output", END)
|
||||
|
||||
return workflow
|
||||
|
||||
|
||||
def get_compiled_graph() -> Any:
|
||||
"""Compile and return the executable LangGraph app."""
|
||||
workflow = create_coding_workflow()
|
||||
return workflow.compile()
|
||||
|
||||
|
||||
def export_graph_mermaid() -> str:
|
||||
"""Export the compiled LangGraph workflow topology as a Mermaid diagram definition."""
|
||||
app = get_compiled_graph()
|
||||
try:
|
||||
return app.get_graph().draw_mermaid()
|
||||
except Exception:
|
||||
return """graph TD
|
||||
START --> validate_document
|
||||
validate_document --> extract_text
|
||||
validate_document -.-> evaluate_confidence
|
||||
extract_text --> extract_diagnoses
|
||||
extract_text -.-> evaluate_confidence
|
||||
extract_diagnoses --> analyze_context
|
||||
extract_diagnoses -.-> evaluate_confidence
|
||||
analyze_context --> classify_diagnoses
|
||||
classify_diagnoses --> retrieve_candidates
|
||||
classify_diagnoses -.-> evaluate_confidence
|
||||
retrieve_candidates --> rank_candidates
|
||||
retrieve_candidates -.-> validate_codes
|
||||
rank_candidates --> validate_codes
|
||||
validate_codes --> evaluate_confidence
|
||||
evaluate_confidence --> finalize_output
|
||||
finalize_output --> END
|
||||
"""
|
||||
|
||||
|
||||
def export_graph_ascii() -> str:
|
||||
"""Export the compiled LangGraph workflow topology as an ASCII representation."""
|
||||
app = get_compiled_graph()
|
||||
try:
|
||||
return app.get_graph().draw_ascii()
|
||||
except Exception:
|
||||
return (
|
||||
"START -> validate_document -> extract_text -> extract_diagnoses -> "
|
||||
"analyze_context -> classify_diagnoses -> retrieve_candidates -> "
|
||||
"rank_candidates -> validate_codes -> evaluate_confidence -> finalize_output -> END"
|
||||
)
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Multimodal clinical document ingestion and format auto-detection package."""
|
||||
|
||||
from medical_coding.ingestion.agent import ClinicalDocumentIngestionAgent
|
||||
from medical_coding.ingestion.detector import DocumentFormat, DocumentFormatDetector
|
||||
from medical_coding.ingestion.parsers import (
|
||||
BaseDocumentParser,
|
||||
ImageOCRDocumentParser,
|
||||
IngestionResult,
|
||||
ManualTextParser,
|
||||
PDFDocumentParser,
|
||||
TextDocumentParser,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"BaseDocumentParser",
|
||||
"ClinicalDocumentIngestionAgent",
|
||||
"DocumentFormat",
|
||||
"DocumentFormatDetector",
|
||||
"ImageOCRDocumentParser",
|
||||
"IngestionResult",
|
||||
"ManualTextParser",
|
||||
"PDFDocumentParser",
|
||||
"TextDocumentParser",
|
||||
]
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Unified Clinical Ingestion Agent coordinating auto-detection and multi-format parsing."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from medical_coding.ingestion.detector import DocumentFormat, DocumentFormatDetector
|
||||
from medical_coding.ingestion.parsers import (
|
||||
ImageOCRDocumentParser,
|
||||
IngestionResult,
|
||||
ManualTextParser,
|
||||
PDFDocumentParser,
|
||||
TextDocumentParser,
|
||||
)
|
||||
from medical_coding.pdf.normalizer import DocumentNormalizer
|
||||
from medical_coding.pdf.section_detector import SectionDetector
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class ClinicalDocumentIngestionAgent:
|
||||
"""Intelligent agent that automatically detects document modality and routes to the appropriate parser.
|
||||
|
||||
Supported Formats:
|
||||
- PDF (.pdf): Vector extraction with PyMuPDF and pdfplumber, with automatic OCR fallback if scanned.
|
||||
- Plain Text (.txt, .md, .log, .csv): Direct decoding and clinical normalization.
|
||||
- Images / Screenshots (.png, .jpg, .jpeg, .tiff, .bmp, .webp): Neural OCR text extraction.
|
||||
- Manual Text Entry: String normalization and boundary identification.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
max_pdf_pages: int = 50,
|
||||
normalizer: DocumentNormalizer | None = None,
|
||||
) -> None:
|
||||
self.normalizer = normalizer or DocumentNormalizer()
|
||||
self.section_detector = SectionDetector()
|
||||
self.detector = DocumentFormatDetector()
|
||||
|
||||
# Parsers
|
||||
self.text_parser = TextDocumentParser(normalizer=self.normalizer)
|
||||
self.image_parser = ImageOCRDocumentParser(normalizer=self.normalizer)
|
||||
self.pdf_parser = PDFDocumentParser(
|
||||
max_pages=max_pdf_pages,
|
||||
normalizer=self.normalizer,
|
||||
image_ocr_parser=self.image_parser,
|
||||
)
|
||||
self.manual_parser = ManualTextParser(normalizer=self.normalizer)
|
||||
|
||||
def ingest(
|
||||
self,
|
||||
source: bytes | str | Path,
|
||||
filename: str | None = None,
|
||||
mime_type: str | None = None,
|
||||
) -> IngestionResult:
|
||||
"""Auto-detect format and extract clinical discharge summary text.
|
||||
|
||||
Args:
|
||||
source: Raw file bytes, file Path, or string content.
|
||||
filename: Optional source filename (helps in extension heuristic).
|
||||
mime_type: Optional explicit MIME type.
|
||||
|
||||
Returns:
|
||||
Standardized IngestionResult containing normalized text, format, and metadata.
|
||||
"""
|
||||
fmt, detected_mime = self.detector.detect_format(
|
||||
source=source,
|
||||
filename=filename,
|
||||
mime_type=mime_type,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"Ingestion Agent detected format=%s (mime=%s) for filename=%s",
|
||||
fmt.value,
|
||||
detected_mime,
|
||||
filename or "unnamed",
|
||||
)
|
||||
|
||||
result: IngestionResult
|
||||
if fmt == DocumentFormat.PDF:
|
||||
result = self.pdf_parser.parse(source=source, filename=filename)
|
||||
elif fmt == DocumentFormat.IMAGE:
|
||||
result = self.image_parser.parse(source=source, filename=filename)
|
||||
elif fmt == DocumentFormat.TXT:
|
||||
result = self.text_parser.parse(source=source, filename=filename)
|
||||
elif fmt == DocumentFormat.MANUAL_TEXT:
|
||||
result = self.manual_parser.parse(source=source, filename=filename)
|
||||
else:
|
||||
# Fallback attempt: if binary, try image OCR, then text
|
||||
if isinstance(source, bytes):
|
||||
result = self.image_parser.parse(source=source, filename=filename)
|
||||
if result.status != "SUCCESS":
|
||||
result = self.text_parser.parse(source=source, filename=filename)
|
||||
else:
|
||||
result = self.manual_parser.parse(source=source, filename=filename)
|
||||
|
||||
# Attach detected MIME type to metadata
|
||||
result.metadata["detected_format"] = fmt.value
|
||||
result.metadata["detected_mime"] = detected_mime
|
||||
|
||||
# Detect clinical sections if text extraction was successful
|
||||
if result.status == "SUCCESS" and result.normalized_text:
|
||||
try:
|
||||
sections = self.section_detector.detect_sections(full_text=result.normalized_text)
|
||||
result.metadata["section_count"] = len(sections)
|
||||
result.metadata["detected_sections"] = [s.section_type.value for s in sections]
|
||||
except Exception as e:
|
||||
logger.debug("Section detection optional step encountered note: %s", e)
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Document format detection via file extensions, MIME signatures, and magic byte analysis."""
|
||||
|
||||
from enum import StrEnum
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class DocumentFormat(StrEnum):
|
||||
"""Supported input document formats for clinical discharge summaries."""
|
||||
|
||||
PDF = "PDF"
|
||||
TXT = "TXT"
|
||||
IMAGE = "IMAGE"
|
||||
MANUAL_TEXT = "MANUAL_TEXT"
|
||||
UNKNOWN = "UNKNOWN"
|
||||
|
||||
|
||||
# Magic byte signatures for binary formats
|
||||
_MAGIC_SIGNATURES: list[tuple[bytes, DocumentFormat, str]] = [
|
||||
(b"%PDF", DocumentFormat.PDF, "application/pdf"),
|
||||
(b"\x89PNG\r\n\x1a\n", DocumentFormat.IMAGE, "image/png"),
|
||||
(b"\xff\xd8\xff", DocumentFormat.IMAGE, "image/jpeg"),
|
||||
(b"GIF87a", DocumentFormat.IMAGE, "image/gif"),
|
||||
(b"GIF89a", DocumentFormat.IMAGE, "image/gif"),
|
||||
(b"II*\x00", DocumentFormat.IMAGE, "image/tiff"),
|
||||
(b"MM\x00*", DocumentFormat.IMAGE, "image/tiff"),
|
||||
(b"BM", DocumentFormat.IMAGE, "image/bmp"),
|
||||
]
|
||||
|
||||
# File extension mappings
|
||||
_EXTENSION_MAPPINGS: dict[str, tuple[DocumentFormat, str]] = {
|
||||
".pdf": (DocumentFormat.PDF, "application/pdf"),
|
||||
".txt": (DocumentFormat.TXT, "text/plain"),
|
||||
".text": (DocumentFormat.TXT, "text/plain"),
|
||||
".md": (DocumentFormat.TXT, "text/markdown"),
|
||||
".log": (DocumentFormat.TXT, "text/plain"),
|
||||
".csv": (DocumentFormat.TXT, "text/csv"),
|
||||
".png": (DocumentFormat.IMAGE, "image/png"),
|
||||
".jpg": (DocumentFormat.IMAGE, "image/jpeg"),
|
||||
".jpeg": (DocumentFormat.IMAGE, "image/jpeg"),
|
||||
".tiff": (DocumentFormat.IMAGE, "image/tiff"),
|
||||
".tif": (DocumentFormat.IMAGE, "image/tiff"),
|
||||
".bmp": (DocumentFormat.IMAGE, "image/bmp"),
|
||||
".webp": (DocumentFormat.IMAGE, "image/webp"),
|
||||
}
|
||||
|
||||
|
||||
class DocumentFormatDetector:
|
||||
"""Robust multi-layer format detector analyzing magic bytes, file extensions, and text structure."""
|
||||
|
||||
@classmethod
|
||||
def detect_format(
|
||||
cls,
|
||||
source: bytes | str | Path,
|
||||
filename: str | None = None,
|
||||
mime_type: str | None = None,
|
||||
) -> tuple[DocumentFormat, str]:
|
||||
"""Detect the document format and MIME type.
|
||||
|
||||
Returns:
|
||||
Tuple of (DocumentFormat, detected_mime_string).
|
||||
"""
|
||||
# 1. Check if source is a pure string without file path characteristics
|
||||
if isinstance(source, str):
|
||||
# If string contains newline or doesn't exist on disk as a file, treat as manual text
|
||||
p = Path(source)
|
||||
if "\n" in source or not p.exists() or len(source) > 260:
|
||||
return DocumentFormat.MANUAL_TEXT, "text/plain"
|
||||
# It's an existing file path, read bytes
|
||||
try:
|
||||
data = p.read_bytes()
|
||||
fname = filename or p.name
|
||||
return cls.detect_from_bytes(data, filename=fname, mime_type=mime_type)
|
||||
except Exception:
|
||||
return DocumentFormat.MANUAL_TEXT, "text/plain"
|
||||
|
||||
if isinstance(source, Path):
|
||||
if source.exists() and source.is_file():
|
||||
try:
|
||||
data = source.read_bytes()
|
||||
return cls.detect_from_bytes(data, filename=filename or source.name, mime_type=mime_type)
|
||||
except Exception:
|
||||
pass
|
||||
fname = filename or source.name
|
||||
return cls.detect_from_filename(fname)
|
||||
|
||||
if isinstance(source, bytes):
|
||||
return cls.detect_from_bytes(source, filename=filename, mime_type=mime_type)
|
||||
|
||||
return DocumentFormat.UNKNOWN, "application/octet-stream"
|
||||
|
||||
@classmethod
|
||||
def detect_from_bytes(
|
||||
cls,
|
||||
data: bytes,
|
||||
filename: str | None = None,
|
||||
mime_type: str | None = None,
|
||||
) -> tuple[DocumentFormat, str]:
|
||||
"""Detect document format by inspecting magic byte signatures, then fallback to filename."""
|
||||
if not data:
|
||||
return DocumentFormat.TXT, "text/plain"
|
||||
|
||||
# Check explicit MIME if provided
|
||||
if mime_type:
|
||||
mime_lower = mime_type.lower()
|
||||
if "pdf" in mime_lower:
|
||||
return DocumentFormat.PDF, "application/pdf"
|
||||
if any(img in mime_lower for img in ("image/", "png", "jpeg", "jpg", "tiff", "webp", "bmp")):
|
||||
return DocumentFormat.IMAGE, mime_lower
|
||||
if any(txt in mime_lower for txt in ("text/", "plain", "csv", "markdown")):
|
||||
return DocumentFormat.TXT, "text/plain"
|
||||
|
||||
# Magic bytes inspection (header signatures)
|
||||
header = data[:32]
|
||||
for magic, fmt, detected_mime in _MAGIC_SIGNATURES:
|
||||
if header.startswith(magic):
|
||||
return fmt, detected_mime
|
||||
|
||||
# Special check for WEBP (RIFF....WEBP)
|
||||
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
||||
return DocumentFormat.IMAGE, "image/webp"
|
||||
|
||||
# Fallback to file extension if filename provided
|
||||
if filename:
|
||||
fmt, ext_mime = cls.detect_from_filename(filename)
|
||||
if fmt != DocumentFormat.UNKNOWN:
|
||||
return fmt, ext_mime
|
||||
|
||||
# If no binary magic match, test if valid UTF-8/ASCII text
|
||||
try:
|
||||
sample = data[:2048]
|
||||
sample.decode("utf-8")
|
||||
# If decodable without null bytes, it is plain text
|
||||
if b"\x00" not in sample:
|
||||
return DocumentFormat.TXT, "text/plain"
|
||||
except UnicodeDecodeError:
|
||||
pass
|
||||
|
||||
return DocumentFormat.UNKNOWN, "application/octet-stream"
|
||||
|
||||
@classmethod
|
||||
def detect_from_filename(cls, filename: str) -> tuple[DocumentFormat, str]:
|
||||
"""Inspect file extension to determine document format."""
|
||||
ext = Path(filename).suffix.lower()
|
||||
if ext in _EXTENSION_MAPPINGS:
|
||||
return _EXTENSION_MAPPINGS[ext]
|
||||
return DocumentFormat.UNKNOWN, "application/octet-stream"
|
||||
@@ -0,0 +1,452 @@
|
||||
"""Specialized parsers for PDF documents, plain text, and clinical image screenshots."""
|
||||
|
||||
import re
|
||||
from abc import ABC, abstractmethod
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.ingestion.detector import DocumentFormat
|
||||
from medical_coding.pdf.extractor import PDFExtractor
|
||||
from medical_coding.pdf.models import PDFExtractionStatus
|
||||
from medical_coding.pdf.normalizer import DocumentNormalizer
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class IngestionResult:
|
||||
"""Standardized output container across all document and image parsers."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
format: DocumentFormat,
|
||||
status: str, # "SUCCESS", "EMPTY", "ERROR"
|
||||
raw_text: str,
|
||||
normalized_text: str,
|
||||
char_count: int = 0,
|
||||
word_count: int = 0,
|
||||
page_count: int = 1,
|
||||
is_ocr: bool = False,
|
||||
ocr_confidence: float | None = None,
|
||||
pages: list[dict[str, Any]] | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
error_message: str | None = None,
|
||||
) -> None:
|
||||
self.format = format
|
||||
self.status = status
|
||||
self.raw_text = raw_text
|
||||
self.normalized_text = normalized_text
|
||||
self.char_count = char_count or len(normalized_text)
|
||||
self.word_count = word_count or len(normalized_text.split())
|
||||
self.page_count = page_count
|
||||
self.is_ocr = is_ocr
|
||||
self.ocr_confidence = ocr_confidence
|
||||
self.pages = pages or []
|
||||
self.metadata = metadata or {}
|
||||
self.error_message = error_message
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Serialize ingestion result to dictionary."""
|
||||
return {
|
||||
"format": self.format.value,
|
||||
"status": self.status,
|
||||
"raw_text": self.raw_text,
|
||||
"normalized_text": self.normalized_text,
|
||||
"char_count": self.char_count,
|
||||
"word_count": self.word_count,
|
||||
"page_count": self.page_count,
|
||||
"is_ocr": self.is_ocr,
|
||||
"ocr_confidence": self.ocr_confidence,
|
||||
"pages": self.pages,
|
||||
"metadata": self.metadata,
|
||||
"error_message": self.error_message,
|
||||
}
|
||||
|
||||
|
||||
class BaseDocumentParser(ABC):
|
||||
"""Abstract base class for format-specific document parsers."""
|
||||
|
||||
@abstractmethod
|
||||
def parse(self, source: bytes | str | Path, filename: str | None = None, **kwargs: Any) -> IngestionResult:
|
||||
"""Parse source document into standardized IngestionResult."""
|
||||
pass
|
||||
|
||||
|
||||
class TextDocumentParser(BaseDocumentParser):
|
||||
"""Parser for plain text files (.txt, .text, .md, .csv) with automatic encoding detection."""
|
||||
|
||||
def __init__(self, normalizer: DocumentNormalizer | None = None) -> None:
|
||||
self.normalizer = normalizer or DocumentNormalizer()
|
||||
|
||||
def parse(self, source: bytes | str | Path, filename: str | None = None, **kwargs: Any) -> IngestionResult:
|
||||
raw_text = ""
|
||||
try:
|
||||
if isinstance(source, bytes):
|
||||
# Attempt UTF-8, then Latin-1/CP1252 fallbacks
|
||||
for enc in ("utf-8", "utf-8-sig", "latin-1", "cp1252"):
|
||||
try:
|
||||
raw_text = source.decode(enc)
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
elif isinstance(source, Path):
|
||||
raw_bytes = source.read_bytes()
|
||||
return self.parse(raw_bytes, filename=filename or source.name)
|
||||
elif isinstance(source, str):
|
||||
p = Path(source)
|
||||
if p.exists() and p.is_file():
|
||||
return self.parse(p.read_bytes(), filename=filename or p.name)
|
||||
raw_text = source
|
||||
|
||||
norm_text = self.normalizer.normalize(raw_text)
|
||||
if not norm_text.strip():
|
||||
return IngestionResult(
|
||||
format=DocumentFormat.TXT,
|
||||
status="EMPTY",
|
||||
raw_text="",
|
||||
normalized_text="",
|
||||
error_message="Plain text file is empty or contains only whitespace.",
|
||||
)
|
||||
|
||||
return IngestionResult(
|
||||
format=DocumentFormat.TXT,
|
||||
status="SUCCESS",
|
||||
raw_text=raw_text,
|
||||
normalized_text=norm_text,
|
||||
char_count=len(norm_text),
|
||||
word_count=len(norm_text.split()),
|
||||
page_count=1,
|
||||
is_ocr=False,
|
||||
pages=[{
|
||||
"page_number": 1,
|
||||
"normalized_text": norm_text,
|
||||
"char_count": len(norm_text),
|
||||
"word_count": len(norm_text.split()),
|
||||
}],
|
||||
metadata={"source_filename": filename or "document.txt", "parser": "TextDocumentParser"},
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to parse text document: %s", exc)
|
||||
return IngestionResult(
|
||||
format=DocumentFormat.TXT,
|
||||
status="ERROR",
|
||||
raw_text="",
|
||||
normalized_text="",
|
||||
error_message=f"Text parsing error: {exc}",
|
||||
)
|
||||
|
||||
|
||||
class ImageOCRDocumentParser(BaseDocumentParser):
|
||||
"""OCR parser for clinical screenshots and images (.png, .jpg, .jpeg, .tiff, .bmp, .webp)."""
|
||||
|
||||
def __init__(self, normalizer: DocumentNormalizer | None = None) -> None:
|
||||
self.normalizer = normalizer or DocumentNormalizer()
|
||||
self._ocr_engine: Any = None
|
||||
|
||||
def _get_ocr_engine(self) -> Any:
|
||||
if self._ocr_engine is None:
|
||||
try:
|
||||
from rapidocr_onnxruntime import RapidOCR
|
||||
self._ocr_engine = RapidOCR()
|
||||
except ImportError:
|
||||
logger.warning("rapidocr_onnxruntime not installed; OCR parsing unavailable.")
|
||||
self._ocr_engine = None
|
||||
return self._ocr_engine
|
||||
|
||||
@staticmethod
|
||||
def _repair_ocr_text(text: str) -> str:
|
||||
"""Heal common OCR subword spacing artifacts produced by bitmap rendering."""
|
||||
repairs = [
|
||||
(r"\bse\s+psis\b", "sepsis"),
|
||||
(r"\bdisc\s+harge\b", "discharge"),
|
||||
(r"\bhyper\s+tension\b", "hypertension"),
|
||||
(r"\bdia\s+betes\b", "diabetes"),
|
||||
(r"\bmyo\s+cardial\b", "myocardial"),
|
||||
(r"\bin\s+farction\b", "infarction"),
|
||||
(r"\bpneu\s+monia\b", "pneumonia"),
|
||||
(r"\bsys\s+tolic\b", "systolic"),
|
||||
(r"\bdias\s+tolic\b", "diastolic"),
|
||||
(r"\bcon\s+gestive\b", "congestive"),
|
||||
(r"\bexacer\s+bation\b", "exacerbation"),
|
||||
(r"\bobstruc\s+tive\b", "obstructive"),
|
||||
(r"\bpulmo\s+nary\b", "pulmonary"),
|
||||
(r"\bkid\s+ney\b", "kidney"),
|
||||
(r"\bfib\s+rillation\b", "fibrillation"),
|
||||
]
|
||||
repaired = text
|
||||
for pattern, replacement in repairs:
|
||||
repaired = re.sub(pattern, replacement, repaired, flags=re.IGNORECASE)
|
||||
return repaired
|
||||
|
||||
def parse(self, source: bytes | str | Path, filename: str | None = None, **kwargs: Any) -> IngestionResult:
|
||||
"""Run OCR on image bytes or path to extract clinical text."""
|
||||
img_bytes: bytes
|
||||
try:
|
||||
if isinstance(source, bytes):
|
||||
img_bytes = source
|
||||
elif isinstance(source, Path):
|
||||
img_bytes = source.read_bytes()
|
||||
elif isinstance(source, str):
|
||||
p = Path(source)
|
||||
if p.exists() and p.is_file():
|
||||
img_bytes = p.read_bytes()
|
||||
else:
|
||||
return IngestionResult(
|
||||
format=DocumentFormat.IMAGE,
|
||||
status="ERROR",
|
||||
raw_text="",
|
||||
normalized_text="",
|
||||
error_message=f"Image file not found at '{source}'",
|
||||
)
|
||||
else:
|
||||
return IngestionResult(
|
||||
format=DocumentFormat.IMAGE,
|
||||
status="ERROR",
|
||||
raw_text="",
|
||||
normalized_text="",
|
||||
error_message=f"Unsupported image source type: {type(source)}",
|
||||
)
|
||||
|
||||
ocr = self._get_ocr_engine()
|
||||
if ocr is None:
|
||||
return IngestionResult(
|
||||
format=DocumentFormat.IMAGE,
|
||||
status="ERROR",
|
||||
raw_text="",
|
||||
normalized_text="",
|
||||
error_message="RapidOCR engine is not installed or failed to initialize.",
|
||||
)
|
||||
|
||||
# Execute OCR inference
|
||||
ocr_results, _ = ocr(img_bytes)
|
||||
|
||||
if not ocr_results:
|
||||
return IngestionResult(
|
||||
format=DocumentFormat.IMAGE,
|
||||
status="EMPTY",
|
||||
raw_text="",
|
||||
normalized_text="",
|
||||
is_ocr=True,
|
||||
error_message="No text detected in image screenshot.",
|
||||
)
|
||||
|
||||
# Sort detected boxes top-to-bottom, left-to-right
|
||||
# ocr_results format: [ [box_coords, text, confidence_str], ... ]
|
||||
sorted_results = sorted(
|
||||
ocr_results,
|
||||
key=lambda item: (item[0][0][1], item[0][0][0]), # y0 then x0
|
||||
)
|
||||
|
||||
extracted_lines: list[str] = []
|
||||
confidences: list[float] = []
|
||||
|
||||
for item in sorted_results:
|
||||
line_text = str(item[1]).strip()
|
||||
if line_text:
|
||||
extracted_lines.append(line_text)
|
||||
try:
|
||||
confidences.append(float(item[2]))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
raw_text = "\n".join(extracted_lines)
|
||||
repaired_text = self._repair_ocr_text(raw_text)
|
||||
norm_text = self.normalizer.normalize(repaired_text)
|
||||
avg_conf = (sum(confidences) / len(confidences)) if confidences else 0.85
|
||||
|
||||
return IngestionResult(
|
||||
format=DocumentFormat.IMAGE,
|
||||
status="SUCCESS",
|
||||
raw_text=repaired_text,
|
||||
normalized_text=norm_text,
|
||||
char_count=len(norm_text),
|
||||
word_count=len(norm_text.split()),
|
||||
page_count=1,
|
||||
is_ocr=True,
|
||||
ocr_confidence=round(avg_conf, 3),
|
||||
pages=[{
|
||||
"page_number": 1,
|
||||
"normalized_text": norm_text,
|
||||
"char_count": len(norm_text),
|
||||
"word_count": len(norm_text.split()),
|
||||
"ocr_confidence": round(avg_conf, 3),
|
||||
}],
|
||||
metadata={
|
||||
"source_filename": filename or "screenshot.png",
|
||||
"lines_detected": len(extracted_lines),
|
||||
"average_confidence": round(avg_conf, 3),
|
||||
"parser": "ImageOCRDocumentParser",
|
||||
},
|
||||
)
|
||||
|
||||
except Exception as exc:
|
||||
logger.exception("OCR extraction failed on image: %s", exc)
|
||||
return IngestionResult(
|
||||
format=DocumentFormat.IMAGE,
|
||||
status="ERROR",
|
||||
raw_text="",
|
||||
normalized_text="",
|
||||
error_message=f"Image OCR failed: {exc}",
|
||||
)
|
||||
|
||||
|
||||
class PDFDocumentParser(BaseDocumentParser):
|
||||
"""Parser for clinical PDFs using PyMuPDF and pdfplumber with OCR fallback for scanned pages."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
max_pages: int = 50,
|
||||
normalizer: DocumentNormalizer | None = None,
|
||||
image_ocr_parser: ImageOCRDocumentParser | None = None,
|
||||
) -> None:
|
||||
self.max_pages = max_pages
|
||||
self.normalizer = normalizer or DocumentNormalizer()
|
||||
self.extractor = PDFExtractor(max_pages=max_pages, normalizer=self.normalizer)
|
||||
self.image_ocr = image_ocr_parser or ImageOCRDocumentParser(normalizer=self.normalizer)
|
||||
|
||||
def parse(self, source: bytes | str | Path, filename: str | None = None, **kwargs: Any) -> IngestionResult:
|
||||
"""Extract text from PDF, automatically falling back to OCR if scanned."""
|
||||
extract_res = self.extractor.extract_sync(source)
|
||||
|
||||
# If extraction succeeded and text volume is sufficient, return directly
|
||||
if (
|
||||
extract_res.status == PDFExtractionStatus.SUCCESS
|
||||
and len(extract_res.full_normalized_text.strip()) >= 50
|
||||
):
|
||||
pages_list = [
|
||||
{
|
||||
"page_number": p.page_number,
|
||||
"normalized_text": p.normalized_text,
|
||||
"char_count": p.char_count,
|
||||
"word_count": p.word_count,
|
||||
"has_images": p.has_images,
|
||||
}
|
||||
for p in extract_res.pages
|
||||
]
|
||||
return IngestionResult(
|
||||
format=DocumentFormat.PDF,
|
||||
status="SUCCESS",
|
||||
raw_text=extract_res.full_raw_text,
|
||||
normalized_text=extract_res.full_normalized_text,
|
||||
char_count=len(extract_res.full_normalized_text),
|
||||
word_count=len(extract_res.full_normalized_text.split()),
|
||||
page_count=len(extract_res.pages),
|
||||
is_ocr=False,
|
||||
pages=pages_list,
|
||||
metadata={
|
||||
"source_filename": filename or "document.pdf",
|
||||
"extractor_used": extract_res.extractor_used,
|
||||
"parser": "PDFDocumentParser",
|
||||
},
|
||||
)
|
||||
|
||||
# Scanned PDF or insufficient text: Fall back to OCR on rendered page pixmaps
|
||||
if extract_res.is_scanned or extract_res.status in (
|
||||
PDFExtractionStatus.NEEDS_OCR,
|
||||
PDFExtractionStatus.INSUFFICIENT_TEXT,
|
||||
):
|
||||
logger.info("PDF appears to be scanned or contains raster images. Invoking RapidOCR on pages...")
|
||||
try:
|
||||
import pymupdf
|
||||
|
||||
pdf_doc = (
|
||||
pymupdf.open(stream=source, filetype="pdf")
|
||||
if isinstance(source, bytes)
|
||||
else pymupdf.open(str(source))
|
||||
)
|
||||
|
||||
ocr_pages: list[dict[str, Any]] = []
|
||||
full_ocr_parts: list[str] = []
|
||||
total_conf: list[float] = []
|
||||
|
||||
for page_idx in range(min(len(pdf_doc), self.max_pages)):
|
||||
page = pdf_doc.load_page(page_idx)
|
||||
pix = page.get_pixmap(dpi=150)
|
||||
img_bytes = pix.tobytes("png")
|
||||
|
||||
page_res = self.image_ocr.parse(img_bytes, filename=f"page_{page_idx+1}.png")
|
||||
if page_res.status == "SUCCESS":
|
||||
full_ocr_parts.append(page_res.normalized_text)
|
||||
if page_res.ocr_confidence is not None:
|
||||
total_conf.append(page_res.ocr_confidence)
|
||||
ocr_pages.append({
|
||||
"page_number": page_idx + 1,
|
||||
"normalized_text": page_res.normalized_text,
|
||||
"char_count": page_res.char_count,
|
||||
"word_count": page_res.word_count,
|
||||
"has_images": True,
|
||||
"is_ocr": True,
|
||||
})
|
||||
|
||||
pdf_doc.close()
|
||||
|
||||
full_ocr_text = "\n\n".join(full_ocr_parts).strip()
|
||||
if full_ocr_text:
|
||||
avg_c = (sum(total_conf) / len(total_conf)) if total_conf else 0.85
|
||||
return IngestionResult(
|
||||
format=DocumentFormat.PDF,
|
||||
status="SUCCESS",
|
||||
raw_text=full_ocr_text,
|
||||
normalized_text=full_ocr_text,
|
||||
char_count=len(full_ocr_text),
|
||||
word_count=len(full_ocr_text.split()),
|
||||
page_count=len(ocr_pages),
|
||||
is_ocr=True,
|
||||
ocr_confidence=round(avg_c, 3),
|
||||
pages=ocr_pages,
|
||||
metadata={
|
||||
"source_filename": filename or "document.pdf",
|
||||
"is_scanned": True,
|
||||
"ocr_fallback": True,
|
||||
"parser": "PDFDocumentParser[OCR]",
|
||||
},
|
||||
)
|
||||
except Exception as ocr_exc:
|
||||
logger.warning("OCR fallback for scanned PDF encountered error: %s", ocr_exc)
|
||||
|
||||
# If still failed, return extraction error
|
||||
return IngestionResult(
|
||||
format=DocumentFormat.PDF,
|
||||
status="ERROR" if extract_res.status == PDFExtractionStatus.MALFORMED_PDF else "EMPTY",
|
||||
raw_text=extract_res.full_raw_text,
|
||||
normalized_text=extract_res.full_normalized_text,
|
||||
error_message=extract_res.error_message or "Failed to extract readable text from PDF.",
|
||||
)
|
||||
|
||||
|
||||
class ManualTextParser(BaseDocumentParser):
|
||||
"""Parser for direct clinical text entered via web UI or API."""
|
||||
|
||||
def __init__(self, normalizer: DocumentNormalizer | None = None) -> None:
|
||||
self.normalizer = normalizer or DocumentNormalizer()
|
||||
|
||||
def parse(self, source: bytes | str | Path, filename: str | None = None, **kwargs: Any) -> IngestionResult:
|
||||
text_str = source.decode("utf-8") if isinstance(source, bytes) else str(source)
|
||||
norm_text = self.normalizer.normalize(text_str)
|
||||
|
||||
if not norm_text.strip():
|
||||
return IngestionResult(
|
||||
format=DocumentFormat.MANUAL_TEXT,
|
||||
status="EMPTY",
|
||||
raw_text="",
|
||||
normalized_text="",
|
||||
error_message="Manual text input is empty.",
|
||||
)
|
||||
|
||||
return IngestionResult(
|
||||
format=DocumentFormat.MANUAL_TEXT,
|
||||
status="SUCCESS",
|
||||
raw_text=text_str,
|
||||
normalized_text=norm_text,
|
||||
char_count=len(norm_text),
|
||||
word_count=len(norm_text.split()),
|
||||
page_count=1,
|
||||
is_ocr=False,
|
||||
pages=[{
|
||||
"page_number": 1,
|
||||
"normalized_text": norm_text,
|
||||
"char_count": len(norm_text),
|
||||
"word_count": len(norm_text.split()),
|
||||
}],
|
||||
metadata={"source_type": "manual_entry", "parser": "ManualTextParser"},
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Model exports for offline GGUF inference, LangChain integration, and lifecycle management."""
|
||||
|
||||
from medical_coding.models.base import BaseLocalEmbeddings, BaseLocalLLM
|
||||
from medical_coding.models.exceptions import (
|
||||
LLMError,
|
||||
LLMInferenceError,
|
||||
LLMInitializationError,
|
||||
LLMTimeoutError,
|
||||
)
|
||||
from medical_coding.models.factory import (
|
||||
GPT4AllLocalLLM,
|
||||
ModelFactory,
|
||||
SentenceTransformerLocalEmbeddings,
|
||||
)
|
||||
from medical_coding.models.gpt4all_wrapper import GPT4AllWrapper
|
||||
from medical_coding.models.langchain_llm import LocalGPT4AllLangChainLLM
|
||||
from medical_coding.models.lifecycle import (
|
||||
LLMHealthReport,
|
||||
LLMLifecycleManager,
|
||||
check_llm_health,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"BaseLocalEmbeddings",
|
||||
"BaseLocalLLM",
|
||||
"GPT4AllLocalLLM",
|
||||
"GPT4AllWrapper",
|
||||
"LLMError",
|
||||
"LLMHealthReport",
|
||||
"LLMInferenceError",
|
||||
"LLMInitializationError",
|
||||
"LLMLifecycleManager",
|
||||
"LLMTimeoutError",
|
||||
"LocalGPT4AllLangChainLLM",
|
||||
"ModelFactory",
|
||||
"SentenceTransformerLocalEmbeddings",
|
||||
"check_llm_health",
|
||||
]
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Abstract interfaces for local LLMs and dense embedding models."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any
|
||||
|
||||
|
||||
class BaseLocalLLM(ABC):
|
||||
"""Abstract base class for local GGUF / GPT4All model inference."""
|
||||
|
||||
@abstractmethod
|
||||
def generate(
|
||||
self,
|
||||
prompt: str,
|
||||
max_tokens: int | None = None,
|
||||
temperature: float | None = None,
|
||||
stop_sequences: list[str] | None = None,
|
||||
) -> str:
|
||||
"""Execute text generation against the local offline model.
|
||||
|
||||
Args:
|
||||
prompt: Formatted prompt string.
|
||||
max_tokens: Maximum tokens to generate.
|
||||
temperature: Sampling temperature (0.0 for deterministic output).
|
||||
stop_sequences: Optional tokens where generation should halt.
|
||||
|
||||
Returns:
|
||||
Generated text string.
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_model_info(self) -> dict[str, Any]:
|
||||
"""Return diagnostic metadata about the loaded model."""
|
||||
pass
|
||||
|
||||
|
||||
class BaseLocalEmbeddings(ABC):
|
||||
"""Abstract base class for local dense vector embedding models."""
|
||||
|
||||
@abstractmethod
|
||||
def embed_query(self, text: str) -> list[float]:
|
||||
"""Embed a single query string for semantic vector search."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def embed_documents(self, texts: list[str]) -> list[list[float]]:
|
||||
"""Embed a batch of document descriptions."""
|
||||
pass
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Exceptions for local LLM lifecycle, initialization, and inference."""
|
||||
|
||||
|
||||
class LLMError(Exception):
|
||||
"""Base exception for local LLM failures."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class LLMInitializationError(LLMError):
|
||||
"""Raised when local GGUF model fails to initialize or weight file is missing."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class LLMInferenceError(LLMError):
|
||||
"""Raised when model inference fails during generation."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class LLMTimeoutError(LLMError):
|
||||
"""Raised when model generation exceeds configured timeout."""
|
||||
|
||||
pass
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Factory and lifecycle coordination for local offline GGUF and embedding models."""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
from medical_coding.models.base import BaseLocalEmbeddings, BaseLocalLLM
|
||||
from medical_coding.models.langchain_llm import LocalGPT4AllLangChainLLM
|
||||
from medical_coding.models.lifecycle import LLMHealthReport, LLMLifecycleManager
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class GPT4AllLocalLLM(BaseLocalLLM):
|
||||
"""Local GGUF model wrapper delegating execution to the singleton LLMLifecycleManager."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: Settings | None = None,
|
||||
model_path: Path | None = None,
|
||||
model_type: str = "llama",
|
||||
n_threads: int = 4,
|
||||
max_tokens: int = 1024,
|
||||
temperature: float = 0.0,
|
||||
) -> None:
|
||||
self.settings = settings or get_settings()
|
||||
self.model_path = (
|
||||
Path(model_path) if model_path else self.settings.get_resolved_model_path()
|
||||
)
|
||||
self.model_type = model_type
|
||||
self.n_threads = n_threads
|
||||
self.max_tokens = max_tokens
|
||||
self.temperature = temperature
|
||||
|
||||
def load_model(self) -> None:
|
||||
"""Trigger one-time loading of the local GGUF weights via lifecycle manager."""
|
||||
manager = LLMLifecycleManager.get_instance(settings=self.settings)
|
||||
manager.get_or_load_wrapper()
|
||||
|
||||
def generate(
|
||||
self,
|
||||
prompt: str,
|
||||
max_tokens: int | None = None,
|
||||
temperature: float | None = None,
|
||||
stop_sequences: list[str] | None = None,
|
||||
) -> str:
|
||||
"""Generate text from the local GGUF model using thread-safe execution."""
|
||||
manager = LLMLifecycleManager.get_instance(settings=self.settings)
|
||||
return manager.generate_sync(
|
||||
prompt=prompt,
|
||||
max_tokens=max_tokens if max_tokens is not None else self.max_tokens,
|
||||
temperature=temperature if temperature is not None else self.temperature,
|
||||
stop_sequences=stop_sequences,
|
||||
)
|
||||
|
||||
def get_model_info(self) -> dict[str, Any]:
|
||||
"""Return diagnostic health and status metadata."""
|
||||
manager = LLMLifecycleManager.get_instance(settings=self.settings)
|
||||
report = manager.check_health()
|
||||
return {
|
||||
"model_name": report.model_name,
|
||||
"resolved_path": report.resolved_path,
|
||||
"file_exists": report.file_exists,
|
||||
"is_loaded": report.is_loaded,
|
||||
"load_count": report.load_count,
|
||||
"inference_count": report.inference_count,
|
||||
"n_threads": report.configured_threads,
|
||||
"max_llm_concurrency": report.max_llm_concurrency,
|
||||
"max_document_concurrency": report.max_document_concurrency,
|
||||
"offline_only": True,
|
||||
}
|
||||
|
||||
|
||||
class FastLocalEmbeddings(BaseLocalEmbeddings):
|
||||
"""Deterministic, zero-network offline dense embedding generator.
|
||||
|
||||
Uses subword and token feature hashing with L2-normalized dense projections.
|
||||
Ideal for test fixtures, air-gapped environments, and rapid local evaluation.
|
||||
"""
|
||||
|
||||
def __init__(self, dim: int = 384) -> None:
|
||||
self.dim = dim
|
||||
|
||||
def _hash_token(self, token: str) -> tuple[int, float]:
|
||||
import hashlib
|
||||
|
||||
h = int(hashlib.md5(token.encode("utf-8")).hexdigest()[:8], 16)
|
||||
idx = h % self.dim
|
||||
sign = 1.0 if (h & 1) == 0 else -1.0
|
||||
return idx, sign
|
||||
|
||||
def _embed_single(self, text: str) -> list[float]:
|
||||
import numpy as np
|
||||
|
||||
vec = np.zeros(self.dim, dtype=np.float32)
|
||||
words = text.lower().split()
|
||||
if not words:
|
||||
return vec.tolist()
|
||||
|
||||
for w in words:
|
||||
idx, sign = self._hash_token(f"w_{w}")
|
||||
vec[idx] += sign * 1.5
|
||||
if len(w) >= 3:
|
||||
for i in range(len(w) - 2):
|
||||
trigram = w[i : i + 3]
|
||||
t_idx, t_sign = self._hash_token(f"c_{trigram}")
|
||||
vec[t_idx] += t_sign * 0.5
|
||||
|
||||
norm = np.linalg.norm(vec)
|
||||
if norm > 1e-9:
|
||||
vec = vec / norm
|
||||
return vec.tolist()
|
||||
|
||||
def embed_query(self, text: str) -> list[float]:
|
||||
return self._embed_single(text)
|
||||
|
||||
def embed_documents(self, texts: list[str]) -> list[list[float]]:
|
||||
return [self._embed_single(t) for t in texts]
|
||||
|
||||
|
||||
class SentenceTransformerLocalEmbeddings(BaseLocalEmbeddings):
|
||||
"""Local offline dense embedding generator using SentenceTransformers."""
|
||||
|
||||
def __init__(self, model_path: Path, device: str = "cpu") -> None:
|
||||
self.model_path = Path(model_path)
|
||||
self.device = device
|
||||
self._model: Any = None
|
||||
|
||||
if not self.model_path.exists():
|
||||
logger.warning(
|
||||
"Local embedding directory not found at %s. FastLocalEmbeddings will be used as fallback.",
|
||||
self.model_path,
|
||||
)
|
||||
|
||||
def load_model(self) -> None:
|
||||
"""Load local sentence transformer model from disk without remote network calls."""
|
||||
if self._model is not None:
|
||||
return
|
||||
|
||||
if not self.model_path.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Local embedding model not found at '{self.model_path}'. "
|
||||
"Ensure local sentence transformer weights are present offline."
|
||||
)
|
||||
|
||||
from sentence_transformers import SentenceTransformer
|
||||
|
||||
logger.info("Loading offline SentenceTransformer weights from %s", self.model_path)
|
||||
self._model = SentenceTransformer(
|
||||
str(self.model_path),
|
||||
device=self.device,
|
||||
local_files_only=True,
|
||||
)
|
||||
|
||||
def embed_query(self, text: str) -> list[float]:
|
||||
self.load_model()
|
||||
vec = self._model.encode(text, normalize_embeddings=True, show_progress_bar=False)
|
||||
return vec.tolist()
|
||||
|
||||
def embed_documents(self, texts: list[str]) -> list[list[float]]:
|
||||
self.load_model()
|
||||
vecs = self._model.encode(texts, normalize_embeddings=True, show_progress_bar=False)
|
||||
return [v.tolist() for v in vecs]
|
||||
|
||||
|
||||
class ModelFactory:
|
||||
"""Factory creating and providing local offline models configured via Settings."""
|
||||
|
||||
@staticmethod
|
||||
def create_llm(settings: Settings | None = None) -> BaseLocalLLM:
|
||||
"""Create a local GGUF/GPT4All LLM wrapper instance adhering to BaseLocalLLM."""
|
||||
cfg = settings or get_settings()
|
||||
return GPT4AllLocalLLM(settings=cfg)
|
||||
|
||||
@staticmethod
|
||||
def create_langchain_llm(settings: Settings | None = None) -> LocalGPT4AllLangChainLLM:
|
||||
"""Create a LangChain-compatible LLM instance bound to the lifecycle manager."""
|
||||
cfg = settings or get_settings()
|
||||
return LocalGPT4AllLangChainLLM(settings=cfg)
|
||||
|
||||
@staticmethod
|
||||
def get_llm_manager(settings: Settings | None = None) -> LLMLifecycleManager:
|
||||
"""Return the singleton LLMLifecycleManager instance."""
|
||||
return LLMLifecycleManager.get_instance(settings=settings)
|
||||
|
||||
@staticmethod
|
||||
def check_llm_health(settings: Settings | None = None) -> LLMHealthReport:
|
||||
"""Execute diagnostic health assessment of local LLM infrastructure."""
|
||||
manager = LLMLifecycleManager.get_instance(settings=settings)
|
||||
return manager.check_health()
|
||||
|
||||
@staticmethod
|
||||
def create_embeddings(
|
||||
settings: Settings | None = None,
|
||||
force_local_fast: bool = False,
|
||||
) -> BaseLocalEmbeddings:
|
||||
"""Create a local dense embedding wrapper instance.
|
||||
|
||||
If force_local_fast is True or the configured embedding path does not exist on disk,
|
||||
returns FastLocalEmbeddings for deterministic, zero-network local operation.
|
||||
"""
|
||||
cfg = settings or get_settings()
|
||||
if force_local_fast or not cfg.embedding_model_path.exists():
|
||||
return FastLocalEmbeddings(dim=384)
|
||||
return SentenceTransformerLocalEmbeddings(
|
||||
model_path=cfg.embedding_model_path,
|
||||
device=cfg.embedding_device,
|
||||
)
|
||||
@@ -0,0 +1,178 @@
|
||||
"""Local GPT4All model wrapper executing strictly offline inference."""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from gpt4all import GPT4All
|
||||
|
||||
from medical_coding.models.exceptions import LLMInferenceError, LLMInitializationError
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class GPT4AllWrapper:
|
||||
"""Wrapper around gpt4all.GPT4All with offline enforcement and parameter binding."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_name: str,
|
||||
model_path: Path,
|
||||
model_type: str = "llama",
|
||||
n_threads: int = 4,
|
||||
n_ctx: int = 2048,
|
||||
temperature: float = 0.0,
|
||||
max_tokens: int = 1024,
|
||||
top_k: int = 40,
|
||||
top_p: float = 0.4,
|
||||
repeat_penalty: float = 1.18,
|
||||
) -> None:
|
||||
self.model_name = model_name
|
||||
self.model_path = Path(model_path)
|
||||
self.model_type = model_type
|
||||
self.n_threads = n_threads
|
||||
self.n_ctx = n_ctx
|
||||
self.temperature = temperature
|
||||
self.max_tokens = max_tokens
|
||||
self.top_k = top_k
|
||||
self.top_p = top_p
|
||||
self.repeat_penalty = repeat_penalty
|
||||
|
||||
self._resolved_file = self._resolve_file_path()
|
||||
self._model: GPT4All | None = None
|
||||
|
||||
def _resolve_file_path(self) -> Path:
|
||||
"""Resolve the exact filesystem path to the GGUF file."""
|
||||
if self.model_path.suffix.lower() == ".gguf" or self.model_path.is_file():
|
||||
return self.model_path
|
||||
return self.model_path / self.model_name
|
||||
|
||||
@property
|
||||
def resolved_file_path(self) -> Path:
|
||||
return self._resolved_file
|
||||
|
||||
def is_weight_file_present(self) -> bool:
|
||||
"""Check whether the configured GGUF model file exists on disk."""
|
||||
return self._resolved_file.exists() and self._resolved_file.is_file()
|
||||
|
||||
def get_file_size_bytes(self) -> int:
|
||||
"""Return the byte size of the model file on disk, or 0 if missing."""
|
||||
if self.is_weight_file_present():
|
||||
try:
|
||||
return self._resolved_file.stat().st_size
|
||||
except OSError:
|
||||
return 0
|
||||
return 0
|
||||
|
||||
def load(self) -> None:
|
||||
"""Load GGUF model into memory offline.
|
||||
|
||||
CRITICAL ARCHITECTURAL GUARANTEE:
|
||||
allow_download is unconditionally False. No network download will ever be attempted.
|
||||
"""
|
||||
if self._model is not None:
|
||||
return
|
||||
|
||||
if not self.is_weight_file_present():
|
||||
raise LLMInitializationError(
|
||||
f"Local GGUF model not found at '{self._resolved_file}'. "
|
||||
"Per offline architectural constraints, automatic download is disabled. "
|
||||
"Ensure the required GGUF weights are placed in the configured directory."
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"Loading local GGUF model '%s' from '%s' (threads=%d, ctx=%d, device=cpu)...",
|
||||
self.model_name,
|
||||
self._resolved_file.parent,
|
||||
self.n_threads,
|
||||
self.n_ctx,
|
||||
)
|
||||
|
||||
try:
|
||||
# GPT4All expects model_path as directory and model_name as filename
|
||||
search_dir = str(self._resolved_file.parent)
|
||||
file_name = self._resolved_file.name
|
||||
|
||||
self._model = GPT4All(
|
||||
model_name=file_name,
|
||||
model_path=search_dir,
|
||||
model_type=self.model_type,
|
||||
allow_download=False, # STRICT OFFLINE ENFORCEMENT
|
||||
n_threads=self.n_threads,
|
||||
n_ctx=self.n_ctx,
|
||||
device="cpu",
|
||||
verbose=False,
|
||||
)
|
||||
logger.info("Successfully loaded local GGUF model into memory.")
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to initialize GPT4All backend: %s", exc)
|
||||
raise LLMInitializationError(f"Failed to initialize GPT4All runtime: {exc}") from exc
|
||||
|
||||
def generate(
|
||||
self,
|
||||
prompt: str,
|
||||
max_tokens: int | None = None,
|
||||
temperature: float | None = None,
|
||||
stop_sequences: list[str] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
"""Generate response text from local GGUF model synchronously.
|
||||
|
||||
Args:
|
||||
prompt: Text prompt for generation.
|
||||
max_tokens: Override max tokens (defaults to configured max_tokens).
|
||||
temperature: Override temperature (defaults to configured temperature).
|
||||
stop_sequences: List of strings where generation must stop.
|
||||
**kwargs: Additional parameters passed to GPT4All.generate().
|
||||
|
||||
Returns:
|
||||
Generated response string.
|
||||
"""
|
||||
if self._model is None:
|
||||
self.load()
|
||||
|
||||
assert self._model is not None, "Model must be loaded before generation"
|
||||
|
||||
tokens_to_gen = max_tokens if max_tokens is not None else self.max_tokens
|
||||
temp_val = temperature if temperature is not None else self.temperature
|
||||
|
||||
try:
|
||||
raw_output = self._model.generate(
|
||||
prompt=prompt,
|
||||
max_tokens=tokens_to_gen,
|
||||
temp=temp_val,
|
||||
top_k=kwargs.get("top_k", self.top_k),
|
||||
top_p=kwargs.get("top_p", self.top_p),
|
||||
repeat_penalty=kwargs.get("repeat_penalty", self.repeat_penalty),
|
||||
streaming=False,
|
||||
)
|
||||
|
||||
result_text = str(raw_output)
|
||||
|
||||
# Apply stop sequences if requested
|
||||
if stop_sequences:
|
||||
for stop_token in stop_sequences:
|
||||
if stop_token in result_text:
|
||||
result_text = result_text.split(stop_token)[0]
|
||||
|
||||
return result_text.strip()
|
||||
|
||||
except Exception as exc:
|
||||
logger.error("Error during GPT4All inference generation: %s", exc)
|
||||
raise LLMInferenceError(f"GPT4All generation failed: {exc}") from exc
|
||||
|
||||
def get_diagnostic_info(self) -> dict[str, Any]:
|
||||
"""Return diagnostic state of the wrapper."""
|
||||
return {
|
||||
"model_name": self.model_name,
|
||||
"model_path": str(self.model_path),
|
||||
"resolved_file": str(self._resolved_file),
|
||||
"file_exists": self.is_weight_file_present(),
|
||||
"file_size_bytes": self.get_file_size_bytes(),
|
||||
"is_loaded": self._model is not None,
|
||||
"threads": self.n_threads,
|
||||
"context_size": self.n_ctx,
|
||||
"temperature": self.temperature,
|
||||
"max_tokens": self.max_tokens,
|
||||
"offline_only": True,
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
"""LangChain-compatible local LLM interface wrapping GPT4All with controlled concurrency."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from langchain_core.callbacks.manager import (
|
||||
AsyncCallbackManagerForLLMRun,
|
||||
CallbackManagerForLLMRun,
|
||||
)
|
||||
from langchain_core.language_models.llms import LLM
|
||||
from pydantic import Field, PrivateAttr
|
||||
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
from medical_coding.models.lifecycle import LLMLifecycleManager
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class LocalGPT4AllLangChainLLM(LLM):
|
||||
"""LangChain-compatible LLM wrapping local offline GPT4All inference.
|
||||
|
||||
Features:
|
||||
- Thread-safe and shared memory: delegates to the singleton LLMLifecycleManager.
|
||||
- Concurrency-controlled: prevents multi-thread C++ crashes on CPU inference.
|
||||
- Native async support (_acall) for LangChain and LangGraph workflows.
|
||||
- Zero cloud dependencies: 100% offline local execution.
|
||||
"""
|
||||
|
||||
model_name: str = Field(
|
||||
default="",
|
||||
description="Name of the GGUF model file.",
|
||||
)
|
||||
model_path: str = Field(
|
||||
default="",
|
||||
description="Path to local GGUF model directory or file.",
|
||||
)
|
||||
temperature: float = Field(
|
||||
default=0.0,
|
||||
description="Sampling temperature for generation.",
|
||||
)
|
||||
max_tokens: int = Field(
|
||||
default=1024,
|
||||
description="Maximum tokens to generate.",
|
||||
)
|
||||
threads: int = Field(
|
||||
default=4,
|
||||
description="CPU execution threads allocated.",
|
||||
)
|
||||
context_size: int = Field(
|
||||
default=2048,
|
||||
description="Context window size (n_ctx).",
|
||||
)
|
||||
timeout_seconds: float = Field(
|
||||
default=120.0,
|
||||
description="Generation timeout ceiling.",
|
||||
)
|
||||
|
||||
_settings: Settings | None = PrivateAttr(default=None)
|
||||
|
||||
def __init__(self, settings: Settings | None = None, **kwargs: Any) -> None:
|
||||
cfg = settings or get_settings()
|
||||
kwargs.setdefault("model_name", cfg.model_name)
|
||||
kwargs.setdefault("model_path", str(cfg.model_path))
|
||||
kwargs.setdefault("temperature", cfg.model_temperature)
|
||||
kwargs.setdefault("max_tokens", cfg.model_max_tokens)
|
||||
kwargs.setdefault("threads", cfg.model_threads)
|
||||
kwargs.setdefault("context_size", cfg.model_context_size)
|
||||
kwargs.setdefault("timeout_seconds", cfg.llm_timeout_seconds)
|
||||
super().__init__(**kwargs)
|
||||
self._settings = cfg
|
||||
|
||||
@property
|
||||
def _llm_type(self) -> str:
|
||||
"""Return type identifier for LangChain telemetry."""
|
||||
return "gpt4all_local"
|
||||
|
||||
@property
|
||||
def _identifying_params(self) -> dict[str, Any]:
|
||||
"""Return identifying parameters for tracking and serialization."""
|
||||
return {
|
||||
"model_name": self.model_name,
|
||||
"model_path": self.model_path,
|
||||
"temperature": self.temperature,
|
||||
"max_tokens": self.max_tokens,
|
||||
"threads": self.threads,
|
||||
"context_size": self.context_size,
|
||||
"timeout_seconds": self.timeout_seconds,
|
||||
"offline_only": True,
|
||||
}
|
||||
|
||||
def _call(
|
||||
self,
|
||||
prompt: str,
|
||||
stop: list[str] | None = None,
|
||||
run_manager: CallbackManagerForLLMRun | None = None,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
"""Synchronously execute local generation through the lifecycle manager."""
|
||||
manager = LLMLifecycleManager.get_instance(settings=self._settings)
|
||||
max_tokens = kwargs.get("max_tokens", self.max_tokens)
|
||||
temperature = kwargs.get("temperature", self.temperature)
|
||||
|
||||
return manager.generate_sync(
|
||||
prompt=prompt,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
stop_sequences=stop,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
async def _acall(
|
||||
self,
|
||||
prompt: str,
|
||||
stop: list[str] | None = None,
|
||||
run_manager: AsyncCallbackManagerForLLMRun | None = None,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
"""Asynchronously execute local generation through the concurrency gate."""
|
||||
manager = LLMLifecycleManager.get_instance(settings=self._settings)
|
||||
max_tokens = kwargs.get("max_tokens", self.max_tokens)
|
||||
temperature = kwargs.get("temperature", self.temperature)
|
||||
|
||||
return await manager.generate_async(
|
||||
prompt=prompt,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
stop_sequences=stop,
|
||||
**kwargs,
|
||||
)
|
||||
@@ -0,0 +1,267 @@
|
||||
"""Thread-safe lifecycle management, caching, and controlled concurrency for local LLM inference."""
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal
|
||||
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
from medical_coding.models.exceptions import LLMInferenceError, LLMTimeoutError
|
||||
from medical_coding.models.gpt4all_wrapper import GPT4AllWrapper
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LLMHealthReport:
|
||||
"""Diagnostic health assessment of local LLM infrastructure."""
|
||||
|
||||
status: Literal["healthy", "degraded", "unhealthy"]
|
||||
model_name: str
|
||||
model_path: str
|
||||
resolved_path: str
|
||||
file_exists: bool
|
||||
file_size_bytes: int
|
||||
is_loaded: bool
|
||||
load_count: int
|
||||
inference_count: int
|
||||
max_llm_concurrency: int
|
||||
max_document_concurrency: int
|
||||
configured_threads: int
|
||||
context_size: int
|
||||
details: str
|
||||
|
||||
|
||||
class LLMLifecycleManager:
|
||||
"""Singleton managing offline GGUF model lifecycle, single-load caching, and concurrency gates.
|
||||
|
||||
ARCHITECTURAL PRINCIPLES:
|
||||
1. Single-Load Guarantee: The GGUF weights are loaded exactly once into RAM.
|
||||
2. Concurrency Separation:
|
||||
- Document-level concurrency (e.g. 10 PDFs) is handled by the async event loop / batch processor.
|
||||
- Model-level concurrency is strictly gated by an async semaphore and thread lock to protect
|
||||
CPU cache lines and avoid C++ llama.cpp context corruption.
|
||||
3. Thread-Safe: Uses double-checked reentrant locking across concurrent threads.
|
||||
"""
|
||||
|
||||
_instance: "LLMLifecycleManager | None" = None
|
||||
_singleton_lock: threading.RLock = threading.RLock()
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: Settings | None = None,
|
||||
custom_wrapper: GPT4AllWrapper | None = None,
|
||||
) -> None:
|
||||
self.settings = settings or get_settings()
|
||||
self._load_lock = threading.RLock()
|
||||
self._inference_thread_lock = threading.Lock()
|
||||
|
||||
# Concurrency gates
|
||||
self._async_semaphore: asyncio.Semaphore | None = None
|
||||
self._async_semaphore_lock = threading.Lock()
|
||||
|
||||
# Lifecycle state
|
||||
self._wrapper: GPT4AllWrapper | None = custom_wrapper
|
||||
self._load_count: int = 1 if custom_wrapper is not None else 0
|
||||
self._inference_count: int = 0
|
||||
self._total_inference_time_ms: float = 0.0
|
||||
|
||||
@classmethod
|
||||
def get_instance(
|
||||
cls,
|
||||
settings: Settings | None = None,
|
||||
custom_wrapper: GPT4AllWrapper | None = None,
|
||||
) -> "LLMLifecycleManager":
|
||||
"""Retrieve or create the singleton lifecycle manager instance."""
|
||||
if cls._instance is None:
|
||||
with cls._singleton_lock:
|
||||
if cls._instance is None:
|
||||
cls._instance = cls(settings=settings, custom_wrapper=custom_wrapper)
|
||||
return cls._instance
|
||||
|
||||
@classmethod
|
||||
def reset_instance(cls) -> None:
|
||||
"""Reset the singleton instance (used for testing or clean restarts)."""
|
||||
with cls._singleton_lock:
|
||||
if cls._instance is not None:
|
||||
logger.info("Resetting LLMLifecycleManager singleton instance.")
|
||||
cls._instance._wrapper = None
|
||||
cls._instance = None
|
||||
|
||||
def _get_async_semaphore(self) -> asyncio.Semaphore:
|
||||
"""Lazy-initialize asyncio.Semaphore bound to the active event loop."""
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
loop = None
|
||||
|
||||
if self._async_semaphore is None or (
|
||||
loop is not None and getattr(self._async_semaphore, "_loop", None) is not loop
|
||||
):
|
||||
with self._async_semaphore_lock:
|
||||
if self._async_semaphore is None or (
|
||||
loop is not None and getattr(self._async_semaphore, "_loop", None) is not loop
|
||||
):
|
||||
limit = self.settings.max_llm_concurrency
|
||||
self._async_semaphore = asyncio.Semaphore(limit)
|
||||
return self._async_semaphore
|
||||
|
||||
def get_or_load_wrapper(self) -> GPT4AllWrapper:
|
||||
"""Return the loaded model wrapper, loading it once if not already initialized."""
|
||||
if self._wrapper is not None:
|
||||
return self._wrapper
|
||||
|
||||
with self._load_lock:
|
||||
if self._wrapper is not None:
|
||||
return self._wrapper
|
||||
|
||||
logger.info("Initializing model wrapper for '%s'...", self.settings.model_name)
|
||||
wrapper = GPT4AllWrapper(
|
||||
model_name=self.settings.model_name,
|
||||
model_path=self.settings.model_path,
|
||||
model_type=self.settings.llm_model_type,
|
||||
n_threads=self.settings.model_threads,
|
||||
n_ctx=self.settings.model_context_size,
|
||||
temperature=self.settings.model_temperature,
|
||||
max_tokens=self.settings.model_max_tokens,
|
||||
top_k=self.settings.llm_top_k,
|
||||
top_p=self.settings.llm_top_p,
|
||||
repeat_penalty=self.settings.llm_repeat_penalty,
|
||||
)
|
||||
|
||||
wrapper.load()
|
||||
self._wrapper = wrapper
|
||||
self._load_count += 1
|
||||
logger.info("Model loaded successfully (load_count=%d).", self._load_count)
|
||||
return self._wrapper
|
||||
|
||||
def generate_sync(
|
||||
self,
|
||||
prompt: str,
|
||||
max_tokens: int | None = None,
|
||||
temperature: float | None = None,
|
||||
stop_sequences: list[str] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
"""Execute synchronous model generation protected by the inference thread lock."""
|
||||
wrapper = self.get_or_load_wrapper()
|
||||
|
||||
# Thread lock ensures llama.cpp C++ context is accessed sequentially
|
||||
with self._inference_thread_lock:
|
||||
start_time = time.perf_counter()
|
||||
self._inference_count += 1
|
||||
|
||||
logger.debug(
|
||||
"Starting sync LLM inference (call #%d, prompt_chars=%d)...",
|
||||
self._inference_count,
|
||||
len(prompt),
|
||||
)
|
||||
|
||||
result = wrapper.generate(
|
||||
prompt=prompt,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
stop_sequences=stop_sequences,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
||||
self._total_inference_time_ms += elapsed_ms
|
||||
|
||||
logger.debug("Completed sync LLM inference in %.2f ms", elapsed_ms)
|
||||
return result
|
||||
|
||||
async def generate_async(
|
||||
self,
|
||||
prompt: str,
|
||||
max_tokens: int | None = None,
|
||||
temperature: float | None = None,
|
||||
stop_sequences: list[str] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
"""Execute asynchronous inference with concurrency gating and timeout handling.
|
||||
|
||||
Protects CPU by queuing calls through the async semaphore (max_llm_concurrency)
|
||||
and offloading execution to worker threads without blocking the asyncio loop.
|
||||
"""
|
||||
semaphore = self._get_async_semaphore()
|
||||
timeout_seconds = self.settings.llm_timeout_seconds
|
||||
|
||||
async with semaphore:
|
||||
try:
|
||||
# Offload CPU execution to background thread while enforcing timeout
|
||||
result = await asyncio.wait_for(
|
||||
asyncio.to_thread(
|
||||
self.generate_sync,
|
||||
prompt,
|
||||
max_tokens,
|
||||
temperature,
|
||||
stop_sequences,
|
||||
**kwargs,
|
||||
),
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
return result
|
||||
except TimeoutError as exc:
|
||||
logger.error(
|
||||
"LLM inference timed out after %.1f seconds for prompt (%d chars)",
|
||||
timeout_seconds,
|
||||
len(prompt),
|
||||
)
|
||||
raise LLMTimeoutError(f"LLM inference timed out after {timeout_seconds}s") from exc
|
||||
except Exception as exc:
|
||||
if isinstance(exc, LLMInferenceError | LLMTimeoutError):
|
||||
raise
|
||||
logger.exception("Unexpected error during async LLM inference: %s", exc)
|
||||
raise LLMInferenceError(f"Async LLM inference failed: {exc}") from exc
|
||||
|
||||
def check_health(self) -> LLMHealthReport:
|
||||
"""Run non-destructive diagnostic health check on local LLM infrastructure."""
|
||||
resolved = self.settings.get_resolved_model_path()
|
||||
file_exists = resolved.exists() and resolved.is_file()
|
||||
file_size = 0
|
||||
if file_exists:
|
||||
try:
|
||||
file_size = resolved.stat().st_size
|
||||
except OSError:
|
||||
file_size = 0
|
||||
|
||||
is_loaded = self._wrapper is not None
|
||||
|
||||
if file_exists and is_loaded:
|
||||
status = "healthy"
|
||||
details = "Local GGUF model is present on disk and loaded in memory."
|
||||
elif file_exists:
|
||||
status = "healthy"
|
||||
details = "Local GGUF model is present on disk and ready for on-demand loading."
|
||||
else:
|
||||
status = "degraded"
|
||||
details = (
|
||||
f"Model file not found at '{resolved}'. Offline mode is active; "
|
||||
"inference calls will raise FileNotFoundError until weights are placed on disk."
|
||||
)
|
||||
|
||||
return LLMHealthReport(
|
||||
status=status,
|
||||
model_name=self.settings.model_name,
|
||||
model_path=str(self.settings.model_path),
|
||||
resolved_path=str(resolved),
|
||||
file_exists=file_exists,
|
||||
file_size_bytes=file_size,
|
||||
is_loaded=is_loaded,
|
||||
load_count=self._load_count,
|
||||
inference_count=self._inference_count,
|
||||
max_llm_concurrency=self.settings.max_llm_concurrency,
|
||||
max_document_concurrency=self.settings.max_document_concurrency,
|
||||
configured_threads=self.settings.model_threads,
|
||||
context_size=self.settings.model_context_size,
|
||||
details=details,
|
||||
)
|
||||
|
||||
|
||||
def check_llm_health(settings: Settings | None = None) -> LLMHealthReport:
|
||||
"""Convenience functional interface for LLM health check."""
|
||||
manager = LLMLifecycleManager.get_instance(settings=settings)
|
||||
return manager.check_health()
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Orchestration exports."""
|
||||
|
||||
from medical_coding.orchestration.pipeline import MedicalCodingPipeline
|
||||
|
||||
__all__ = ["MedicalCodingPipeline"]
|
||||
@@ -0,0 +1,154 @@
|
||||
"""High-level asynchronous orchestrator for the medical coding pipeline with bounded parallelism."""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
from medical_coding.graph.state import create_initial_state
|
||||
from medical_coding.graph.workflow import get_compiled_graph
|
||||
from medical_coding.pdf.concurrency import BoundedDocumentGate
|
||||
from medical_coding.schemas.clinical import ClinicalDocument
|
||||
from medical_coding.schemas.enums import ExecutionStatus
|
||||
from medical_coding.schemas.response import CodingResult
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class MedicalCodingPipeline:
|
||||
"""Orchestrates document coding by executing the compiled LangGraph workflow.
|
||||
|
||||
Enforces document-level asynchronous parallelism while bounding model-level inference.
|
||||
"""
|
||||
|
||||
def __init__(self, settings: Settings | None = None) -> None:
|
||||
self.settings = settings or get_settings()
|
||||
self.graph = get_compiled_graph()
|
||||
self.gate = BoundedDocumentGate(
|
||||
max_concurrency=self.settings.max_document_concurrency,
|
||||
settings=self.settings,
|
||||
)
|
||||
|
||||
async def run_document(
|
||||
self,
|
||||
document_id: str,
|
||||
text: str = "",
|
||||
pdf_path: str | Path | None = None,
|
||||
pdf_bytes: bytes | None = None,
|
||||
file_path: str | Path | None = None,
|
||||
file_bytes: bytes | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> CodingResult:
|
||||
"""Execute the end-to-end coding pipeline for a single clinical document, image, or text.
|
||||
|
||||
Args:
|
||||
document_id: Unique encounter identifier.
|
||||
text: Clinical document text.
|
||||
pdf_path: Optional path to PDF source file.
|
||||
pdf_bytes: Optional raw PDF file bytes.
|
||||
file_path: Optional path to any document/image file (.pdf, .txt, .png, .jpg).
|
||||
file_bytes: Optional raw file bytes for any supported format.
|
||||
metadata: Optional dictionary of clinical metadata.
|
||||
|
||||
Returns:
|
||||
Deterministic CodingResult adhering to ICD guidelines.
|
||||
"""
|
||||
start_time = time.perf_counter()
|
||||
resolved_bytes = file_bytes if file_bytes is not None else pdf_bytes
|
||||
resolved_path = file_path if file_path is not None else pdf_path
|
||||
|
||||
initial_state = create_initial_state(
|
||||
document_id=document_id,
|
||||
raw_text=text,
|
||||
pdf_path=str(resolved_path) if resolved_path else None,
|
||||
pdf_bytes=resolved_bytes,
|
||||
file_path=str(resolved_path) if resolved_path else None,
|
||||
file_bytes=resolved_bytes,
|
||||
source_type="file" if (resolved_path or resolved_bytes) else "text",
|
||||
metadata=metadata or {},
|
||||
)
|
||||
|
||||
try:
|
||||
logger.info("Invoking coding graph for document_id=%s", document_id)
|
||||
final_state = await self.graph.ainvoke(initial_state)
|
||||
|
||||
result: CodingResult | None = final_state.get("final_result")
|
||||
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
||||
|
||||
if result is None:
|
||||
logger.warning("Pipeline completed without final_result for %s", document_id)
|
||||
return CodingResult(
|
||||
document_id=document_id,
|
||||
status=ExecutionStatus.ABSTAINED
|
||||
if final_state.get("abstentions")
|
||||
else ExecutionStatus.ERROR,
|
||||
primary_diagnosis=None,
|
||||
secondary_diagnoses=[],
|
||||
abstentions=final_state.get("abstentions", []),
|
||||
processing_time_ms=elapsed_ms,
|
||||
models_used={"llm": "local_gguf", "retrieval": "local_faiss_bm25"},
|
||||
metadata={"error": "Workflow did not emit final_result"},
|
||||
)
|
||||
|
||||
result.processing_time_ms = round(elapsed_ms, 2)
|
||||
return result
|
||||
|
||||
except Exception as exc:
|
||||
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
||||
logger.exception("Pipeline invocation failed for document %s: %s", document_id, exc)
|
||||
return CodingResult(
|
||||
document_id=document_id,
|
||||
status=ExecutionStatus.ERROR,
|
||||
primary_diagnosis=None,
|
||||
secondary_diagnoses=[],
|
||||
abstentions=[],
|
||||
processing_time_ms=elapsed_ms,
|
||||
models_used={},
|
||||
metadata={"error": str(exc)},
|
||||
)
|
||||
|
||||
async def run_batch_documents(
|
||||
self,
|
||||
documents: list[ClinicalDocument | dict[str, Any]],
|
||||
max_concurrency: int | None = None,
|
||||
) -> list[CodingResult]:
|
||||
"""Process a collection of clinical documents in parallel with bounded concurrency.
|
||||
|
||||
Args:
|
||||
documents: List of ClinicalDocument objects or dictionaries with document specifications.
|
||||
max_concurrency: Optional override for document-level concurrency ceiling.
|
||||
|
||||
Returns:
|
||||
List of CodingResult objects for each document.
|
||||
"""
|
||||
gate = (
|
||||
BoundedDocumentGate(max_concurrency=max_concurrency, settings=self.settings)
|
||||
if max_concurrency
|
||||
else self.gate
|
||||
)
|
||||
|
||||
async def _run_bounded(doc: Any) -> CodingResult:
|
||||
async with gate.get_semaphore():
|
||||
if isinstance(doc, ClinicalDocument):
|
||||
return await self.run_document(
|
||||
document_id=doc.document_id,
|
||||
text=doc.text,
|
||||
metadata=doc.metadata,
|
||||
)
|
||||
if isinstance(doc, dict):
|
||||
return await self.run_document(
|
||||
document_id=doc.get("document_id", "doc-unknown"),
|
||||
text=doc.get("text", ""),
|
||||
pdf_path=doc.get("pdf_path"),
|
||||
pdf_bytes=doc.get("pdf_bytes"),
|
||||
file_path=doc.get("file_path"),
|
||||
file_bytes=doc.get("file_bytes"),
|
||||
metadata=doc.get("metadata"),
|
||||
)
|
||||
raise TypeError(f"Unsupported document item type in batch: {type(doc)}")
|
||||
|
||||
tasks = [_run_bounded(doc) for doc in documents]
|
||||
results = await asyncio.gather(*tasks)
|
||||
return list(results)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""PDF document processing, section detection, normalization, and asynchronous batch ingestion."""
|
||||
|
||||
from medical_coding.pdf.concurrency import BoundedDocumentGate
|
||||
from medical_coding.pdf.extractor import PDFExtractor
|
||||
from medical_coding.pdf.models import (
|
||||
BatchProcessingResult,
|
||||
ClinicalPDFDocument,
|
||||
DocumentProcessingResult,
|
||||
ExtractedPage,
|
||||
ExtractedSection,
|
||||
PDFExtractionStatus,
|
||||
)
|
||||
from medical_coding.pdf.normalizer import DocumentNormalizer
|
||||
from medical_coding.pdf.processor import (
|
||||
BatchPDFProcessor,
|
||||
process_document,
|
||||
process_documents_batch,
|
||||
)
|
||||
from medical_coding.pdf.section_detector import SectionDetector
|
||||
|
||||
__all__ = [
|
||||
"BatchPDFProcessor",
|
||||
"BatchProcessingResult",
|
||||
"BoundedDocumentGate",
|
||||
"ClinicalPDFDocument",
|
||||
"DocumentNormalizer",
|
||||
"DocumentProcessingResult",
|
||||
"ExtractedPage",
|
||||
"ExtractedSection",
|
||||
"PDFExtractionStatus",
|
||||
"PDFExtractor",
|
||||
"SectionDetector",
|
||||
"process_document",
|
||||
"process_documents_batch",
|
||||
]
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Bounded concurrency manager separating document-level tasks from model-level inference."""
|
||||
|
||||
import asyncio
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class BoundedDocumentGate:
|
||||
"""Manages asynchronous document-level concurrency ceilings and lifecycle cancellation.
|
||||
|
||||
ARCHITECTURAL PRINCIPLE:
|
||||
Document-level concurrency allows multiple PDFs (e.g. >= 10 documents) to be ingested,
|
||||
parsed with PyMuPDF, normalized, and partitioned in parallel, without spawning multiple LLMs.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, max_concurrency: int | None = None, settings: Settings | None = None
|
||||
) -> None:
|
||||
cfg = settings or get_settings()
|
||||
self.max_concurrency = max_concurrency or cfg.max_document_concurrency
|
||||
self._semaphore: asyncio.Semaphore | None = None
|
||||
self._active_tasks: set[asyncio.Task[Any]] = set()
|
||||
|
||||
def get_semaphore(self) -> asyncio.Semaphore:
|
||||
"""Lazy-initialize asyncio.Semaphore bound to current active event loop."""
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
loop = None
|
||||
|
||||
if self._semaphore is None or (
|
||||
loop is not None and getattr(self._semaphore, "_loop", None) is not loop
|
||||
):
|
||||
self._semaphore = asyncio.Semaphore(self.max_concurrency)
|
||||
return self._semaphore
|
||||
|
||||
async def run_bounded(self, coro: Any) -> Any:
|
||||
"""Run coroutine within the document-level concurrency semaphore."""
|
||||
sem = self.get_semaphore()
|
||||
async with sem:
|
||||
return await coro
|
||||
@@ -0,0 +1,355 @@
|
||||
"""PyMuPDF primary and pdfplumber fallback text extractor with scanned PDF detection."""
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pdfplumber
|
||||
import pymupdf # Modern PyMuPDF import
|
||||
|
||||
from medical_coding.pdf.models import ExtractedPage, PDFExtractionStatus
|
||||
from medical_coding.pdf.normalizer import DocumentNormalizer
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class ExtractorResult:
|
||||
"""Internal container for raw page extraction output."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
status: PDFExtractionStatus,
|
||||
pages: list[ExtractedPage],
|
||||
full_raw_text: str,
|
||||
full_normalized_text: str,
|
||||
is_scanned: bool = False,
|
||||
error_message: str | None = None,
|
||||
extractor_used: str = "pymupdf",
|
||||
) -> None:
|
||||
self.status = status
|
||||
self.pages = pages
|
||||
self.full_raw_text = full_raw_text
|
||||
self.full_normalized_text = full_normalized_text
|
||||
self.is_scanned = is_scanned
|
||||
self.error_message = error_message
|
||||
self.extractor_used = extractor_used
|
||||
|
||||
|
||||
class PDFExtractor:
|
||||
"""Primary PyMuPDF extractor with pdfplumber fallback, page tracking, and scanned detection."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
max_pages: int = 50,
|
||||
min_doc_chars: int = 50,
|
||||
min_page_chars_for_scanned: int = 20,
|
||||
normalizer: DocumentNormalizer | None = None,
|
||||
) -> None:
|
||||
self.max_pages = max_pages
|
||||
self.min_doc_chars = min_doc_chars
|
||||
self.min_page_chars_for_scanned = min_page_chars_for_scanned
|
||||
self.normalizer = normalizer or DocumentNormalizer()
|
||||
|
||||
def extract_sync(self, source: Path | bytes | str) -> ExtractorResult:
|
||||
"""Extract pages synchronously using PyMuPDF, falling back to pdfplumber if necessary."""
|
||||
# 1. Attempt primary extraction using PyMuPDF
|
||||
try:
|
||||
result = self._extract_with_pymupdf(source)
|
||||
# If PyMuPDF returned text, return its result directly
|
||||
if result.status == PDFExtractionStatus.SUCCESS:
|
||||
return result
|
||||
# If PyMuPDF flagged scanned/needs OCR or empty, test pdfplumber before deciding
|
||||
if result.status in (
|
||||
PDFExtractionStatus.NEEDS_OCR,
|
||||
PDFExtractionStatus.INSUFFICIENT_TEXT,
|
||||
):
|
||||
logger.info("PyMuPDF yielded low text count. Attempting pdfplumber fallback...")
|
||||
fallback_result = self._extract_with_pdfplumber(source)
|
||||
if fallback_result.status == PDFExtractionStatus.SUCCESS:
|
||||
logger.info("pdfplumber fallback succeeded with valid text.")
|
||||
return fallback_result
|
||||
return result
|
||||
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"PyMuPDF raised exception on '%s': %s. Attempting pdfplumber fallback...",
|
||||
source,
|
||||
exc,
|
||||
)
|
||||
try:
|
||||
return self._extract_with_pdfplumber(source)
|
||||
except Exception as fb_exc:
|
||||
logger.error("Both PyMuPDF and pdfplumber failed on '%s': %s", source, fb_exc)
|
||||
return ExtractorResult(
|
||||
status=PDFExtractionStatus.MALFORMED_PDF,
|
||||
pages=[],
|
||||
full_raw_text="",
|
||||
full_normalized_text="",
|
||||
error_message=f"Failed to parse PDF document: {exc}; Fallback error: {fb_exc}",
|
||||
)
|
||||
|
||||
def _extract_with_pymupdf(self, source: Path | bytes | str) -> ExtractorResult:
|
||||
"""Execute extraction using PyMuPDF (fitz)."""
|
||||
doc: Any = None
|
||||
try:
|
||||
if isinstance(source, bytes):
|
||||
if not source or len(source) < 10:
|
||||
return ExtractorResult(
|
||||
status=PDFExtractionStatus.EMPTY_PDF,
|
||||
pages=[],
|
||||
full_raw_text="",
|
||||
full_normalized_text="",
|
||||
error_message="PDF byte stream is empty or truncated.",
|
||||
)
|
||||
doc = pymupdf.open(stream=source, filetype="pdf")
|
||||
else:
|
||||
path = Path(source)
|
||||
if not path.exists():
|
||||
return ExtractorResult(
|
||||
status=PDFExtractionStatus.EXTRACTION_ERROR,
|
||||
pages=[],
|
||||
full_raw_text="",
|
||||
full_normalized_text="",
|
||||
error_message=f"PDF file not found at '{path}'",
|
||||
)
|
||||
if path.stat().st_size == 0:
|
||||
return ExtractorResult(
|
||||
status=PDFExtractionStatus.EMPTY_PDF,
|
||||
pages=[],
|
||||
full_raw_text="",
|
||||
full_normalized_text="",
|
||||
error_message="PDF file is 0 bytes.",
|
||||
)
|
||||
doc = pymupdf.open(str(path))
|
||||
|
||||
total_pages = len(doc)
|
||||
if total_pages == 0:
|
||||
return ExtractorResult(
|
||||
status=PDFExtractionStatus.EMPTY_PDF,
|
||||
pages=[],
|
||||
full_raw_text="",
|
||||
full_normalized_text="",
|
||||
error_message="PDF contains 0 pages.",
|
||||
)
|
||||
|
||||
pages_to_read = min(total_pages, self.max_pages)
|
||||
extracted_pages: list[ExtractedPage] = []
|
||||
raw_parts: list[str] = []
|
||||
normalized_parts: list[str] = []
|
||||
current_offset = 0
|
||||
|
||||
scanned_pages_count = 0
|
||||
image_pages_count = 0
|
||||
|
||||
for page_idx in range(pages_to_read):
|
||||
page = doc.load_page(page_idx)
|
||||
raw_page_text = page.get_text("text") or ""
|
||||
norm_page_text = self.normalizer.normalize(raw_page_text)
|
||||
|
||||
images = page.get_images()
|
||||
has_images = len(images) > 0
|
||||
if has_images:
|
||||
image_pages_count += 1
|
||||
|
||||
char_cnt = len(norm_page_text)
|
||||
word_cnt = len(norm_page_text.split())
|
||||
|
||||
is_scanned_suspicion = has_images and (char_cnt < self.min_page_chars_for_scanned)
|
||||
if is_scanned_suspicion:
|
||||
scanned_pages_count += 1
|
||||
|
||||
end_offset = current_offset + len(norm_page_text)
|
||||
|
||||
extracted_pages.append(
|
||||
ExtractedPage(
|
||||
page_number=page_idx + 1,
|
||||
raw_text=raw_page_text,
|
||||
normalized_text=norm_page_text,
|
||||
char_count=char_cnt,
|
||||
word_count=word_cnt,
|
||||
has_images=has_images,
|
||||
start_char_offset=current_offset,
|
||||
end_char_offset=end_offset,
|
||||
)
|
||||
)
|
||||
|
||||
raw_parts.append(raw_page_text)
|
||||
normalized_parts.append(norm_page_text)
|
||||
# Account for page-joining double newline
|
||||
current_offset = end_offset + 2
|
||||
|
||||
full_raw = "\n\n".join(raw_parts).strip()
|
||||
full_normalized = "\n\n".join(normalized_parts).strip()
|
||||
|
||||
total_chars = len(full_normalized)
|
||||
|
||||
# Detect scanned / image-only PDFs
|
||||
if (
|
||||
pages_to_read > 0
|
||||
and scanned_pages_count == pages_to_read
|
||||
and total_chars < self.min_doc_chars
|
||||
):
|
||||
return ExtractorResult(
|
||||
status=PDFExtractionStatus.NEEDS_OCR,
|
||||
pages=extracted_pages,
|
||||
full_raw_text=full_raw,
|
||||
full_normalized_text=full_normalized,
|
||||
is_scanned=True,
|
||||
error_message=(
|
||||
f"Scanned image PDF detected ({image_pages_count} image pages, {total_chars} text chars). "
|
||||
"OCR is required to process this document; automatic text extraction cannot read raster images."
|
||||
),
|
||||
extractor_used="pymupdf",
|
||||
)
|
||||
|
||||
# Detect insufficient text
|
||||
if total_chars < self.min_doc_chars:
|
||||
return ExtractorResult(
|
||||
status=PDFExtractionStatus.INSUFFICIENT_TEXT,
|
||||
pages=extracted_pages,
|
||||
full_raw_text=full_raw,
|
||||
full_normalized_text=full_normalized,
|
||||
is_scanned=image_pages_count > 0,
|
||||
error_message=(
|
||||
f"Extracted text volume ({total_chars} chars) is below minimum threshold ({self.min_doc_chars} chars)."
|
||||
),
|
||||
extractor_used="pymupdf",
|
||||
)
|
||||
|
||||
return ExtractorResult(
|
||||
status=PDFExtractionStatus.SUCCESS,
|
||||
pages=extracted_pages,
|
||||
full_raw_text=full_raw,
|
||||
full_normalized_text=full_normalized,
|
||||
is_scanned=False,
|
||||
extractor_used="pymupdf",
|
||||
)
|
||||
|
||||
except Exception as exc:
|
||||
return ExtractorResult(
|
||||
status=PDFExtractionStatus.MALFORMED_PDF,
|
||||
pages=[],
|
||||
full_raw_text="",
|
||||
full_normalized_text="",
|
||||
error_message=f"PyMuPDF error: {exc}",
|
||||
extractor_used="pymupdf",
|
||||
)
|
||||
finally:
|
||||
if doc is not None:
|
||||
try:
|
||||
doc.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _extract_with_pdfplumber(self, source: Path | bytes | str) -> ExtractorResult:
|
||||
"""Fallback extraction using pdfplumber."""
|
||||
file_obj: Any = None
|
||||
pdf: Any = None
|
||||
try:
|
||||
if isinstance(source, bytes):
|
||||
file_obj = io.BytesIO(source)
|
||||
pdf = pdfplumber.open(file_obj)
|
||||
else:
|
||||
path = Path(source)
|
||||
if not path.exists():
|
||||
return ExtractorResult(
|
||||
status=PDFExtractionStatus.EXTRACTION_ERROR,
|
||||
pages=[],
|
||||
full_raw_text="",
|
||||
full_normalized_text="",
|
||||
error_message=f"PDF file not found at '{path}'",
|
||||
extractor_used="pdfplumber",
|
||||
)
|
||||
pdf = pdfplumber.open(str(path))
|
||||
|
||||
total_pages = len(pdf.pages)
|
||||
if total_pages == 0:
|
||||
return ExtractorResult(
|
||||
status=PDFExtractionStatus.EMPTY_PDF,
|
||||
pages=[],
|
||||
full_raw_text="",
|
||||
full_normalized_text="",
|
||||
error_message="pdfplumber found 0 pages.",
|
||||
extractor_used="pdfplumber",
|
||||
)
|
||||
|
||||
pages_to_read = min(total_pages, self.max_pages)
|
||||
extracted_pages: list[ExtractedPage] = []
|
||||
raw_parts: list[str] = []
|
||||
normalized_parts: list[str] = []
|
||||
current_offset = 0
|
||||
|
||||
for page_idx in range(pages_to_read):
|
||||
page = pdf.pages[page_idx]
|
||||
raw_page_text = page.extract_text() or ""
|
||||
norm_page_text = self.normalizer.normalize(raw_page_text)
|
||||
|
||||
char_cnt = len(norm_page_text)
|
||||
word_cnt = len(norm_page_text.split())
|
||||
end_offset = current_offset + len(norm_page_text)
|
||||
|
||||
extracted_pages.append(
|
||||
ExtractedPage(
|
||||
page_number=page_idx + 1,
|
||||
raw_text=raw_page_text,
|
||||
normalized_text=norm_page_text,
|
||||
char_count=char_cnt,
|
||||
word_count=word_cnt,
|
||||
has_images=len(page.images) > 0,
|
||||
start_char_offset=current_offset,
|
||||
end_char_offset=end_offset,
|
||||
)
|
||||
)
|
||||
|
||||
raw_parts.append(raw_page_text)
|
||||
normalized_parts.append(norm_page_text)
|
||||
current_offset = end_offset + 2
|
||||
|
||||
full_raw = "\n\n".join(raw_parts).strip()
|
||||
full_normalized = "\n\n".join(normalized_parts).strip()
|
||||
total_chars = len(full_normalized)
|
||||
|
||||
if total_chars < self.min_doc_chars:
|
||||
return ExtractorResult(
|
||||
status=PDFExtractionStatus.INSUFFICIENT_TEXT,
|
||||
pages=extracted_pages,
|
||||
full_raw_text=full_raw,
|
||||
full_normalized_text=full_normalized,
|
||||
error_message=f"pdfplumber extracted only {total_chars} characters.",
|
||||
extractor_used="pdfplumber",
|
||||
)
|
||||
|
||||
return ExtractorResult(
|
||||
status=PDFExtractionStatus.SUCCESS,
|
||||
pages=extracted_pages,
|
||||
full_raw_text=full_raw,
|
||||
full_normalized_text=full_normalized,
|
||||
extractor_used="pdfplumber",
|
||||
)
|
||||
|
||||
except Exception as exc:
|
||||
return ExtractorResult(
|
||||
status=PDFExtractionStatus.MALFORMED_PDF,
|
||||
pages=[],
|
||||
full_raw_text="",
|
||||
full_normalized_text="",
|
||||
error_message=f"pdfplumber error: {exc}",
|
||||
extractor_used="pdfplumber",
|
||||
)
|
||||
finally:
|
||||
if pdf is not None:
|
||||
try:
|
||||
pdf.close()
|
||||
except Exception:
|
||||
pass
|
||||
if file_obj is not None:
|
||||
try:
|
||||
file_obj.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def extract_async(self, source: Path | bytes | str) -> ExtractorResult:
|
||||
"""Asynchronously extract pages by offloading CPU execution to worker thread."""
|
||||
return await asyncio.to_thread(self.extract_sync, source)
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Domain models for PDF document extraction, sections, pages, and processing outcomes."""
|
||||
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class PDFExtractionStatus(StrEnum):
|
||||
"""Explicit extraction outcome states for clinical PDFs."""
|
||||
|
||||
SUCCESS = "SUCCESS"
|
||||
NEEDS_OCR = "NEEDS_OCR"
|
||||
INSUFFICIENT_TEXT = "INSUFFICIENT_TEXT"
|
||||
EMPTY_PDF = "EMPTY_PDF"
|
||||
MALFORMED_PDF = "MALFORMED_PDF"
|
||||
EXTRACTION_ERROR = "EXTRACTION_ERROR"
|
||||
|
||||
|
||||
class ExtractedPage(BaseModel):
|
||||
"""Data representation of a single extracted PDF page."""
|
||||
|
||||
page_number: int = Field(ge=1, description="1-based page index.")
|
||||
raw_text: str = Field(description="Raw text extracted from this page.")
|
||||
normalized_text: str = Field(description="Normalized text for this page.")
|
||||
char_count: int = Field(ge=0, description="Character count of normalized page text.")
|
||||
word_count: int = Field(ge=0, description="Word count of normalized page text.")
|
||||
has_images: bool = Field(
|
||||
default=False, description="True if page contains embedded raster images."
|
||||
)
|
||||
start_char_offset: int = Field(
|
||||
default=0,
|
||||
ge=0,
|
||||
description="Start character index of this page in full document normalized text.",
|
||||
)
|
||||
end_char_offset: int = Field(
|
||||
default=0,
|
||||
ge=0,
|
||||
description="End character index of this page in full document normalized text.",
|
||||
)
|
||||
|
||||
|
||||
class ExtractedSection(BaseModel):
|
||||
"""Detected clinical section with boundary offsets and high-yield designation."""
|
||||
|
||||
section_id: str = Field(
|
||||
default_factory=lambda: str(uuid4()),
|
||||
description="Unique identifier for this clinical section.",
|
||||
)
|
||||
section_type: str = Field(
|
||||
description="Canonical section category (e.g. 'DISCHARGE_DIAGNOSES', 'HOSPITAL_COURSE').",
|
||||
)
|
||||
header_text: str = Field(description="Original section header string.")
|
||||
page_number: int = Field(ge=1, description="Page where section begins.")
|
||||
start_char: int = Field(ge=0, description="Start character offset in full document text.")
|
||||
end_char: int = Field(ge=0, description="End character offset in full document text.")
|
||||
content_text: str = Field(description="Clean text content within this section.")
|
||||
is_high_yield_coding: bool = Field(
|
||||
default=False,
|
||||
description="True if section is critical for ICD coding (e.g. diagnoses, hospital course, HPI).",
|
||||
)
|
||||
|
||||
|
||||
class ClinicalPDFDocument(BaseModel):
|
||||
"""Structured representation of an ingested clinical discharge summary PDF."""
|
||||
|
||||
document_id: str = Field(
|
||||
default_factory=lambda: str(uuid4()),
|
||||
description="Unique document identifier.",
|
||||
)
|
||||
source_filename: str = Field(
|
||||
default="unknown.pdf",
|
||||
description="Origin filename or path string.",
|
||||
)
|
||||
total_pages: int = Field(ge=0, description="Total count of pages parsed.")
|
||||
pages: list[ExtractedPage] = Field(
|
||||
default_factory=list,
|
||||
description="Ordered sequence of page representations.",
|
||||
)
|
||||
full_normalized_text: str = Field(
|
||||
description="Full concatenated, normalized text across all pages.",
|
||||
)
|
||||
sections: list[ExtractedSection] = Field(
|
||||
default_factory=list,
|
||||
description="Detected clinical sections with character spans.",
|
||||
)
|
||||
is_scanned: bool = Field(
|
||||
default=False,
|
||||
description="True if page analysis detected image-only or scanned content.",
|
||||
)
|
||||
metadata: dict[str, Any] = Field(
|
||||
default_factory=dict,
|
||||
description="Extraction metadata (e.g. extractor used, timestamps).",
|
||||
)
|
||||
|
||||
def get_coding_text(self) -> str:
|
||||
"""Return targeted clinical text from high-yield coding sections.
|
||||
|
||||
ARCHITECTURAL INVARIANT:
|
||||
Avoids sending entire 30+ page PDFs blindly to reasoning agents.
|
||||
If structured coding sections exist (diagnoses, hospital course, HPI),
|
||||
only those are concatenated. Otherwise falls back to full normalized text.
|
||||
"""
|
||||
high_yield = [s for s in self.sections if s.is_high_yield_coding and s.content_text.strip()]
|
||||
if high_yield:
|
||||
parts = [
|
||||
f"=== {s.header_text} (Page {s.page_number}) ===\n{s.content_text}"
|
||||
for s in high_yield
|
||||
]
|
||||
return "\n\n".join(parts)
|
||||
return self.full_normalized_text
|
||||
|
||||
def get_sections_by_type(self, section_type: str) -> list[ExtractedSection]:
|
||||
"""Filter sections by their canonical type."""
|
||||
target = section_type.strip().upper()
|
||||
return [s for s in self.sections if s.section_type.upper() == target]
|
||||
|
||||
def find_page_number_for_char(self, char_offset: int) -> int:
|
||||
"""Find the 1-based page number containing the specified character offset."""
|
||||
for page in self.pages:
|
||||
if page.start_char_offset <= char_offset <= page.end_char_offset:
|
||||
return page.page_number
|
||||
return self.pages[-1].page_number if self.pages else 1
|
||||
|
||||
|
||||
class DocumentProcessingResult(BaseModel):
|
||||
"""Independent outcome container for an individual PDF processing job."""
|
||||
|
||||
document_id: str = Field(description="Unique encounter/document ID.")
|
||||
source_name: str = Field(description="Source filename or identifier.")
|
||||
status: PDFExtractionStatus = Field(description="Explicit extraction outcome status.")
|
||||
document: ClinicalPDFDocument | None = Field(
|
||||
default=None,
|
||||
description="Parsed ClinicalPDFDocument if extraction succeeded.",
|
||||
)
|
||||
error_message: str | None = Field(
|
||||
default=None,
|
||||
description="Descriptive message when extraction fails or requires OCR.",
|
||||
)
|
||||
extraction_time_ms: float = Field(ge=0.0, default=0.0, description="Extraction duration in ms.")
|
||||
extractor_used: str = Field(default="pymupdf", description="'pymupdf' or 'pdfplumber'")
|
||||
page_count: int = Field(ge=0, default=0, description="Pages parsed.")
|
||||
char_count: int = Field(ge=0, default=0, description="Characters extracted.")
|
||||
needs_ocr: bool = Field(
|
||||
default=False, description="True if document is scanned and requires OCR."
|
||||
)
|
||||
|
||||
|
||||
class BatchProcessingResult(BaseModel):
|
||||
"""Aggregated processing results for an asynchronous batch of PDFs."""
|
||||
|
||||
batch_id: str = Field(
|
||||
default_factory=lambda: str(uuid4()),
|
||||
description="Unique batch identifier.",
|
||||
)
|
||||
total_documents: int = Field(ge=0, description="Total count of PDFs submitted.")
|
||||
successful_documents: int = Field(ge=0, description="Count of successfully parsed documents.")
|
||||
failed_documents: int = Field(ge=0, description="Count of documents that encountered errors.")
|
||||
needs_ocr_documents: int = Field(
|
||||
ge=0, description="Count of documents flagged as scanned/needing OCR."
|
||||
)
|
||||
results: list[DocumentProcessingResult] = Field(
|
||||
default_factory=list,
|
||||
description="Collection of independent document results.",
|
||||
)
|
||||
total_elapsed_ms: float = Field(
|
||||
ge=0.0, default=0.0, description="Total batch elapsed time in ms."
|
||||
)
|
||||
throughput_docs_per_sec: float = Field(
|
||||
ge=0.0,
|
||||
default=0.0,
|
||||
description="Effective batch throughput in documents per second.",
|
||||
)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Clinical document text normalizer preserving semantic structure and formatting."""
|
||||
|
||||
import re
|
||||
|
||||
|
||||
class DocumentNormalizer:
|
||||
"""Normalizes raw extracted PDF text while strictly preserving clinical semantics."""
|
||||
|
||||
def __init__(self, dehyphenate: bool = True) -> None:
|
||||
self.dehyphenate = dehyphenate
|
||||
|
||||
def normalize(self, text: str) -> str:
|
||||
"""Clean extracted text preserving paragraph breaks, list markers, and clinical punctuation.
|
||||
|
||||
Rules:
|
||||
1. Replace non-breaking spaces and special unicode dashes/quotes with ASCII equivalents.
|
||||
2. Remove non-printable control characters without removing newlines and tabs.
|
||||
3. De-hyphenate words broken across linebreaks (e.g. 'hyper-\\ntension' -> 'hypertension').
|
||||
4. Normalize horizontal spaces and tabs without destroying vertical line breaks.
|
||||
5. Preserve double-newline paragraph and section separations.
|
||||
6. Strip trailing spaces per line.
|
||||
"""
|
||||
if not text:
|
||||
return ""
|
||||
|
||||
cleaned = text
|
||||
|
||||
# 1. Normalize unicode spaces and quotes
|
||||
cleaned = cleaned.replace("\u00a0", " ")
|
||||
cleaned = cleaned.replace("\u200b", "") # Zero-width space
|
||||
cleaned = cleaned.replace("\u2018", "'").replace("\u2019", "'")
|
||||
cleaned = cleaned.replace("\u201c", '"').replace("\u201d", '"')
|
||||
cleaned = cleaned.replace("\u2013", "-").replace("\u2014", "-")
|
||||
|
||||
# 2. Remove non-printable control characters (keep \n and \t)
|
||||
cleaned = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", cleaned)
|
||||
|
||||
# 3. De-hyphenate soft linebreaks where a word was split at end-of-line
|
||||
# Matches e.g. "myo- \n cardial" -> "myocardial"
|
||||
if self.dehyphenate:
|
||||
cleaned = re.sub(r"([a-zA-Z]{3,})-\s*\n\s*([a-zA-Z]{3,})", r"\1\2", cleaned)
|
||||
|
||||
# 4. Normalize horizontal spaces per line (collapse multiple spaces/tabs into a single space)
|
||||
lines = cleaned.splitlines()
|
||||
normalized_lines = []
|
||||
for line in lines:
|
||||
# Collapse horizontal spaces
|
||||
norm_line = re.sub(r"[ \t]+", " ", line).strip()
|
||||
normalized_lines.append(norm_line)
|
||||
|
||||
# Re-join with single newlines
|
||||
rejoined = "\n".join(normalized_lines)
|
||||
|
||||
# 5. Collapse excessive vertical blank lines: max 2 newlines (one blank line between paragraphs)
|
||||
collapsed = re.sub(r"\n{3,}", "\n\n", rejoined)
|
||||
|
||||
return collapsed.strip()
|
||||
@@ -0,0 +1,335 @@
|
||||
"""Asynchronous batch document processor with bounded concurrency, section mapping, and fault tolerance."""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from collections.abc import Callable, Coroutine
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
from medical_coding.pdf.concurrency import BoundedDocumentGate
|
||||
from medical_coding.pdf.extractor import PDFExtractor
|
||||
from medical_coding.pdf.models import (
|
||||
BatchProcessingResult,
|
||||
ClinicalPDFDocument,
|
||||
DocumentProcessingResult,
|
||||
PDFExtractionStatus,
|
||||
)
|
||||
from medical_coding.pdf.section_detector import SectionDetector
|
||||
from medical_coding.schemas.enums import ExecutionStatus
|
||||
from medical_coding.schemas.response import BatchJobStatus, CodingResult
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class BatchPDFProcessor:
|
||||
"""Orchestrates asynchronous PDF document ingestion, text normalization, sectioning, and batching."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
extractor: PDFExtractor | None = None,
|
||||
section_detector: SectionDetector | None = None,
|
||||
max_concurrency: int | None = None,
|
||||
settings: Settings | None = None,
|
||||
) -> None:
|
||||
self.settings = settings or get_settings()
|
||||
self.extractor = extractor or PDFExtractor(
|
||||
max_pages=self.settings.pdf_max_pages,
|
||||
)
|
||||
self.section_detector = section_detector or SectionDetector()
|
||||
self.max_concurrency = max_concurrency or self.settings.max_document_concurrency
|
||||
self.gate = BoundedDocumentGate(
|
||||
max_concurrency=self.max_concurrency, settings=self.settings
|
||||
)
|
||||
|
||||
async def process_document(
|
||||
self,
|
||||
pdf_source: Path | bytes | str,
|
||||
doc_id: str | None = None,
|
||||
filename: str | None = None,
|
||||
) -> DocumentProcessingResult:
|
||||
"""Process an individual clinical PDF into a structured ClinicalPDFDocument asynchronously.
|
||||
|
||||
Pipeline:
|
||||
1. Extract text page-by-page (PyMuPDF -> fallback pdfplumber).
|
||||
2. Detect scanned or insufficient text conditions.
|
||||
3. Segment normalized text into clinical sections (diagnoses, hospital course, etc.).
|
||||
4. Assemble immutable ClinicalPDFDocument representation.
|
||||
|
||||
Fault Isolation:
|
||||
Errors are captured per document. Malformed or scanned PDFs return structured failures
|
||||
without raising unhandled exceptions.
|
||||
"""
|
||||
start_time = time.perf_counter()
|
||||
|
||||
# Determine identifier and filename
|
||||
document_id = doc_id or str(uuid4())
|
||||
if filename:
|
||||
source_name = filename
|
||||
elif isinstance(pdf_source, (str, Path)):
|
||||
source_name = Path(pdf_source).name
|
||||
else:
|
||||
source_name = f"doc_{document_id[:8]}.pdf"
|
||||
|
||||
logger.info("Processing document '%s' (doc_id=%s)...", source_name, document_id)
|
||||
|
||||
try:
|
||||
# Execute extraction bounded by document gate
|
||||
sem = self.gate.get_semaphore()
|
||||
async with sem:
|
||||
extract_res = await self.extractor.extract_async(pdf_source)
|
||||
|
||||
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
||||
|
||||
# Handle non-success states (scanned, empty, malformed, insufficient text)
|
||||
if extract_res.status != PDFExtractionStatus.SUCCESS:
|
||||
logger.warning(
|
||||
"Document '%s' extraction returned status [%s]: %s",
|
||||
source_name,
|
||||
extract_res.status.value,
|
||||
extract_res.error_message,
|
||||
)
|
||||
return DocumentProcessingResult(
|
||||
document_id=document_id,
|
||||
source_name=source_name,
|
||||
status=extract_res.status,
|
||||
document=None,
|
||||
error_message=extract_res.error_message,
|
||||
extraction_time_ms=elapsed_ms,
|
||||
extractor_used=extract_res.extractor_used,
|
||||
page_count=len(extract_res.pages),
|
||||
char_count=len(extract_res.full_normalized_text),
|
||||
needs_ocr=(extract_res.status == PDFExtractionStatus.NEEDS_OCR),
|
||||
)
|
||||
|
||||
# Build page offset index for mapping sections to page numbers
|
||||
page_offsets = [
|
||||
(p.page_number, p.start_char_offset, p.end_char_offset) for p in extract_res.pages
|
||||
]
|
||||
|
||||
# Detect clinical sections
|
||||
sections = self.section_detector.detect_sections(
|
||||
full_text=extract_res.full_normalized_text,
|
||||
page_offsets=page_offsets,
|
||||
)
|
||||
|
||||
clinical_doc = ClinicalPDFDocument(
|
||||
document_id=document_id,
|
||||
source_filename=source_name,
|
||||
total_pages=len(extract_res.pages),
|
||||
pages=extract_res.pages,
|
||||
full_normalized_text=extract_res.full_normalized_text,
|
||||
sections=sections,
|
||||
is_scanned=extract_res.is_scanned,
|
||||
metadata={
|
||||
"extractor": extract_res.extractor_used,
|
||||
"extraction_ms": elapsed_ms,
|
||||
"section_count": len(sections),
|
||||
},
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"Document '%s' successfully processed: %d pages, %d chars, %d sections (%.2f ms)",
|
||||
source_name,
|
||||
len(extract_res.pages),
|
||||
len(extract_res.full_normalized_text),
|
||||
len(sections),
|
||||
elapsed_ms,
|
||||
)
|
||||
|
||||
return DocumentProcessingResult(
|
||||
document_id=document_id,
|
||||
source_name=source_name,
|
||||
status=PDFExtractionStatus.SUCCESS,
|
||||
document=clinical_doc,
|
||||
error_message=None,
|
||||
extraction_time_ms=elapsed_ms,
|
||||
extractor_used=extract_res.extractor_used,
|
||||
page_count=len(extract_res.pages),
|
||||
char_count=len(extract_res.full_normalized_text),
|
||||
needs_ocr=False,
|
||||
)
|
||||
|
||||
except Exception as exc:
|
||||
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
||||
logger.exception("Unexpected error processing document '%s': %s", source_name, exc)
|
||||
return DocumentProcessingResult(
|
||||
document_id=document_id,
|
||||
source_name=source_name,
|
||||
status=PDFExtractionStatus.EXTRACTION_ERROR,
|
||||
document=None,
|
||||
error_message=f"Extraction failure: {exc}",
|
||||
extraction_time_ms=elapsed_ms,
|
||||
extractor_used="unknown",
|
||||
page_count=0,
|
||||
char_count=0,
|
||||
needs_ocr=False,
|
||||
)
|
||||
|
||||
async def process_documents_batch(
|
||||
self,
|
||||
pdf_sources: list[Path | bytes | str],
|
||||
job_id: str | None = None,
|
||||
filenames: list[str] | None = None,
|
||||
) -> BatchProcessingResult:
|
||||
"""Process a batch of clinical PDFs asynchronously with bounded concurrency (>= 10 documents).
|
||||
|
||||
Guarantees:
|
||||
- Bounded concurrency: strictly respects max_document_concurrency.
|
||||
- Fault isolation: one corrupted PDF will not cancel or crash other documents.
|
||||
- Independent results: each document produces a complete DocumentProcessingResult.
|
||||
"""
|
||||
start_time = time.perf_counter()
|
||||
batch_id = job_id or str(uuid4())
|
||||
total = len(pdf_sources)
|
||||
|
||||
logger.info(
|
||||
"Launching async PDF batch '%s' with %d documents (concurrency limit: %d)...",
|
||||
batch_id,
|
||||
total,
|
||||
self.max_concurrency,
|
||||
)
|
||||
|
||||
tasks = []
|
||||
for idx, src in enumerate(pdf_sources):
|
||||
fn = filenames[idx] if filenames and idx < len(filenames) else None
|
||||
task = asyncio.create_task(
|
||||
self.process_document(
|
||||
pdf_source=src,
|
||||
filename=fn,
|
||||
)
|
||||
)
|
||||
tasks.append(task)
|
||||
|
||||
# Await all tasks cooperatively; return_exceptions=True prevents batch collapse
|
||||
raw_results = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
results: list[DocumentProcessingResult] = []
|
||||
for idx, item in enumerate(raw_results):
|
||||
if isinstance(item, Exception):
|
||||
logger.error("Task for PDF #%d raised unhandled exception: %s", idx, item)
|
||||
results.append(
|
||||
DocumentProcessingResult(
|
||||
document_id=str(uuid4()),
|
||||
source_name=f"document_{idx}.pdf",
|
||||
status=PDFExtractionStatus.EXTRACTION_ERROR,
|
||||
error_message=str(item),
|
||||
)
|
||||
)
|
||||
elif isinstance(item, DocumentProcessingResult):
|
||||
results.append(item)
|
||||
|
||||
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
||||
elapsed_sec = max(elapsed_ms / 1000.0, 0.001)
|
||||
throughput = total / elapsed_sec
|
||||
|
||||
success_count = sum(1 for r in results if r.status == PDFExtractionStatus.SUCCESS)
|
||||
ocr_count = sum(1 for r in results if r.needs_ocr)
|
||||
failed_count = total - success_count
|
||||
|
||||
logger.info(
|
||||
"Batch '%s' complete: %d/%d succeeded, %d need OCR, %d failed in %.2f ms (%.2f docs/sec)",
|
||||
batch_id,
|
||||
success_count,
|
||||
total,
|
||||
ocr_count,
|
||||
failed_count,
|
||||
elapsed_ms,
|
||||
throughput,
|
||||
)
|
||||
|
||||
return BatchProcessingResult(
|
||||
batch_id=batch_id,
|
||||
total_documents=total,
|
||||
successful_documents=success_count,
|
||||
failed_documents=failed_count,
|
||||
needs_ocr_documents=ocr_count,
|
||||
results=results,
|
||||
total_elapsed_ms=elapsed_ms,
|
||||
throughput_docs_per_sec=throughput,
|
||||
)
|
||||
|
||||
# Legacy integration method for existing API endpoints
|
||||
async def process_single_pdf(
|
||||
self,
|
||||
pdf_path: Path,
|
||||
pipeline_executor: Callable[[str, str], Coroutine[Any, Any, CodingResult]],
|
||||
) -> CodingResult:
|
||||
"""Legacy helper running PDF extraction and passing text to pipeline executor."""
|
||||
doc_res = await self.process_document(pdf_path)
|
||||
doc_id = doc_res.document_id
|
||||
|
||||
if doc_res.status != PDFExtractionStatus.SUCCESS or doc_res.document is None:
|
||||
return CodingResult(
|
||||
document_id=doc_id,
|
||||
status=ExecutionStatus.ERROR
|
||||
if doc_res.status != PDFExtractionStatus.NEEDS_OCR
|
||||
else ExecutionStatus.ABSTAINED,
|
||||
primary_diagnosis=None,
|
||||
secondary_diagnoses=[],
|
||||
abstentions=[],
|
||||
processing_time_ms=doc_res.extraction_time_ms,
|
||||
models_used={},
|
||||
metadata={
|
||||
"error": doc_res.error_message or "Extraction failed",
|
||||
"file": str(pdf_path),
|
||||
},
|
||||
)
|
||||
|
||||
# Pass high-yield coding text rather than raw entire document
|
||||
coding_text = doc_res.document.get_coding_text()
|
||||
return await pipeline_executor(doc_id, coding_text)
|
||||
|
||||
async def process_batch(
|
||||
self,
|
||||
pdf_paths: list[Path],
|
||||
pipeline_executor: Callable[[str, str], Coroutine[Any, Any, CodingResult]],
|
||||
job_id: str | None = None,
|
||||
) -> BatchJobStatus:
|
||||
"""Legacy helper processing a batch of PDFs through the coding pipeline."""
|
||||
batch_id = job_id or str(uuid4())
|
||||
total = len(pdf_paths)
|
||||
tasks = [
|
||||
asyncio.create_task(self.process_single_pdf(path, pipeline_executor))
|
||||
for path in pdf_paths
|
||||
]
|
||||
results = await asyncio.gather(*tasks, return_exceptions=False)
|
||||
completed = sum(1 for r in results if r.status != ExecutionStatus.ERROR)
|
||||
failed = sum(1 for r in results if r.status == ExecutionStatus.ERROR)
|
||||
|
||||
return BatchJobStatus(
|
||||
job_id=batch_id,
|
||||
total_documents=total,
|
||||
completed_documents=completed,
|
||||
failed_documents=failed,
|
||||
status="completed" if failed == 0 else "failed" if completed == 0 else "completed",
|
||||
results=results,
|
||||
)
|
||||
|
||||
|
||||
async def process_document(
|
||||
pdf_source: Path | bytes | str,
|
||||
doc_id: str | None = None,
|
||||
filename: str | None = None,
|
||||
processor: BatchPDFProcessor | None = None,
|
||||
) -> DocumentProcessingResult:
|
||||
"""Convenience top-level function for processing a single PDF."""
|
||||
proc = processor or BatchPDFProcessor()
|
||||
return await proc.process_document(pdf_source=pdf_source, doc_id=doc_id, filename=filename)
|
||||
|
||||
|
||||
async def process_documents_batch(
|
||||
pdf_sources: list[Path | bytes | str],
|
||||
job_id: str | None = None,
|
||||
filenames: list[str] | None = None,
|
||||
processor: BatchPDFProcessor | None = None,
|
||||
) -> BatchProcessingResult:
|
||||
"""Convenience top-level function for processing a batch of PDFs (supporting >= 10 documents)."""
|
||||
proc = processor or BatchPDFProcessor()
|
||||
return await proc.process_documents_batch(
|
||||
pdf_sources=pdf_sources,
|
||||
job_id=job_id,
|
||||
filenames=filenames,
|
||||
)
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Clinical section boundary detector identifying high-yield diagnostic documentation."""
|
||||
|
||||
import re
|
||||
from typing import NamedTuple
|
||||
|
||||
from medical_coding.pdf.models import ExtractedSection
|
||||
|
||||
|
||||
class SectionPattern(NamedTuple):
|
||||
section_type: str
|
||||
is_high_yield: bool
|
||||
pattern: re.Pattern
|
||||
|
||||
|
||||
# Canonical clinical section mappings with regex patterns
|
||||
SECTION_DEFINITIONS: list[tuple[str, bool, str]] = [
|
||||
(
|
||||
"DISCHARGE_DIAGNOSES",
|
||||
True,
|
||||
r"(?:DISCHARGE\s+DIAGNOS[EI]S|FINAL\s+DIAGNOS[EI]S|POSTOPERATIVE\s+DIAGNOS[EI]S)",
|
||||
),
|
||||
(
|
||||
"PRINCIPAL_DIAGNOSIS",
|
||||
True,
|
||||
r"(?:PRINCIPAL\s+DIAGNOS[EI]S|PRIMARY\s+DIAGNOS[EI]S|ADMITTING\s+DIAGNOS[EI]S|ADMISSION\s+DIAGNOS[EI]S)",
|
||||
),
|
||||
(
|
||||
"SECONDARY_DIAGNOSES",
|
||||
True,
|
||||
r"(?:SECONDARY\s+DIAGNOS[EI]S|ADDITIONAL\s+DIAGNOS[EI]S|CO-?MORBIDITIES|OTHER\s+DIAGNOS[EI]S)",
|
||||
),
|
||||
(
|
||||
"HOSPITAL_COURSE",
|
||||
True,
|
||||
r"(?:HOSPITAL\s+COURSE|SUMMARY\s+OF\s+HOSPITAL\s+STAY|BRIEF\s+SUMMARY\s+OF\s+HOSPITAL\s+COURSE|COURSE\s+IN\s+HOSPITAL|CLINICAL\s+COURSE)",
|
||||
),
|
||||
(
|
||||
"HISTORY_OF_PRESENT_ILLNESS",
|
||||
True,
|
||||
r"(?:HISTORY\s+OF\s+PRESENT\s+ILLNESS|HPI|CHIEF\s+COMPLAINT|REASON\s+FOR\s+ADMISSION)",
|
||||
),
|
||||
(
|
||||
"PAST_MEDICAL_HISTORY",
|
||||
True,
|
||||
r"(?:PAST\s+MEDICAL\s+HISTORY|PMH|MEDICAL\s+HISTORY)",
|
||||
),
|
||||
(
|
||||
"PAST_SURGICAL_HISTORY",
|
||||
False,
|
||||
r"(?:PAST\s+SURGICAL\s+HISTORY|PSH|SURGICAL\s+HISTORY)",
|
||||
),
|
||||
(
|
||||
"PROCEDURES",
|
||||
True,
|
||||
r"(?:PROCEDURES\s+PERFORMED|OPERATIVE\s+PROCEDURES|SURGICAL\s+PROCEDURES|MAJOR\s+PROCEDURES)",
|
||||
),
|
||||
(
|
||||
"MEDICATIONS",
|
||||
False,
|
||||
r"(?:DISCHARGE\s+MEDICATIONS|MEDICATIONS\s+ON\s+DISCHARGE|ACTIVE\s+MEDICATIONS|MEDICATIONS)",
|
||||
),
|
||||
(
|
||||
"PHYSICAL_EXAM",
|
||||
False,
|
||||
r"(?:PHYSICAL\s+EXAMINATION|EXAMINATION\s+ON\s+ADMISSION|PHYSICAL\s+EXAM)",
|
||||
),
|
||||
(
|
||||
"LABORATORY_DATA",
|
||||
False,
|
||||
r"(?:LABORATORY\s+DATA|PERTINENT\s+LABS|DIAGNOSTIC\s+STUDIES|LABS|IMAGING)",
|
||||
),
|
||||
(
|
||||
"ALLERGIES",
|
||||
False,
|
||||
r"(?:ALLERGIES|ADVERSE\s+REACTIONS)",
|
||||
),
|
||||
(
|
||||
"DISCHARGE_INSTRUCTIONS",
|
||||
False,
|
||||
r"(?:DISCHARGE\s+INSTRUCTIONS|DISPOSITION|DISCHARGE\s+CONDITION|FOLLOW-?UP)",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
class SectionDetector:
|
||||
"""Parses normalized clinical text to segment document into structured clinical sections."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._compiled_patterns: list[SectionPattern] = []
|
||||
for sec_type, is_high_yield, regex_str in SECTION_DEFINITIONS:
|
||||
# Matches header at start of line or after newlines, followed optionally by colon/dashes/newlines
|
||||
pat = re.compile(
|
||||
rf"(?:^|\n)\s*({regex_str})\s*(?::|--|\n)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
self._compiled_patterns.append(SectionPattern(sec_type, is_high_yield, pat))
|
||||
|
||||
def detect_sections(
|
||||
self,
|
||||
full_text: str,
|
||||
page_offsets: list[tuple[int, int, int]] | None = None,
|
||||
) -> list[ExtractedSection]:
|
||||
"""Detect section headers and carve boundaries across full document text.
|
||||
|
||||
Args:
|
||||
full_text: Normalized full clinical document string.
|
||||
page_offsets: Optional list of (page_number, start_char, end_char) tuples.
|
||||
|
||||
Returns:
|
||||
List of ExtractedSection objects ordered by their position in text.
|
||||
"""
|
||||
if not full_text or not full_text.strip():
|
||||
return []
|
||||
|
||||
# Find all header matches across text
|
||||
raw_matches: list[dict] = []
|
||||
for sec_type, is_high_yield, pattern in self._compiled_patterns:
|
||||
for match in pattern.finditer(full_text):
|
||||
header_text = match.group(1).strip()
|
||||
raw_matches.append(
|
||||
{
|
||||
"section_type": sec_type,
|
||||
"is_high_yield": is_high_yield,
|
||||
"header_text": header_text,
|
||||
"start_pos": match.start(1),
|
||||
"content_start": match.end(),
|
||||
}
|
||||
)
|
||||
|
||||
if not raw_matches:
|
||||
# Fallback if no conventional headers are detected (e.g. narrative note)
|
||||
return [
|
||||
ExtractedSection(
|
||||
section_type="GENERAL",
|
||||
header_text="CLINICAL DOCUMENT",
|
||||
page_number=1,
|
||||
start_char=0,
|
||||
end_char=len(full_text),
|
||||
content_text=full_text.strip(),
|
||||
is_high_yield_coding=True,
|
||||
)
|
||||
]
|
||||
|
||||
# Sort matches chronologically by their position in the text
|
||||
raw_matches.sort(key=lambda m: m["start_pos"])
|
||||
|
||||
# Deduplicate overlapping matches (keep the one starting earliest)
|
||||
deduped_matches: list[dict] = []
|
||||
last_end = -1
|
||||
for m in raw_matches:
|
||||
if m["start_pos"] >= last_end:
|
||||
deduped_matches.append(m)
|
||||
last_end = m["content_start"]
|
||||
|
||||
sections: list[ExtractedSection] = []
|
||||
|
||||
# If there's preamble text before the first detected section, capture it
|
||||
if deduped_matches and deduped_matches[0]["start_pos"] > 0:
|
||||
preamble_text = full_text[: deduped_matches[0]["start_pos"]].strip()
|
||||
if preamble_text:
|
||||
sections.append(
|
||||
ExtractedSection(
|
||||
section_type="HEADER_INFO",
|
||||
header_text="PATIENT ENCOUNTER HEADER",
|
||||
page_number=1,
|
||||
start_char=0,
|
||||
end_char=deduped_matches[0]["start_pos"],
|
||||
content_text=preamble_text,
|
||||
is_high_yield_coding=False,
|
||||
)
|
||||
)
|
||||
|
||||
total_matches = len(deduped_matches)
|
||||
for idx, m in enumerate(deduped_matches):
|
||||
content_start = m["content_start"]
|
||||
content_end = (
|
||||
deduped_matches[idx + 1]["start_pos"] if idx + 1 < total_matches else len(full_text)
|
||||
)
|
||||
|
||||
content = full_text[content_start:content_end].strip()
|
||||
page_num = self._find_page_number(m["start_pos"], page_offsets)
|
||||
|
||||
sections.append(
|
||||
ExtractedSection(
|
||||
section_type=m["section_type"],
|
||||
header_text=m["header_text"],
|
||||
page_number=page_num,
|
||||
start_char=m["start_pos"],
|
||||
end_char=content_end,
|
||||
content_text=content,
|
||||
is_high_yield_coding=m["is_high_yield"],
|
||||
)
|
||||
)
|
||||
|
||||
return sections
|
||||
|
||||
def _find_page_number(
|
||||
self,
|
||||
char_pos: int,
|
||||
page_offsets: list[tuple[int, int, int]] | None,
|
||||
) -> int:
|
||||
"""Resolve character offset to 1-based page number."""
|
||||
if not page_offsets:
|
||||
return 1
|
||||
for page_num, start, end in page_offsets:
|
||||
if start <= char_pos <= end:
|
||||
return page_num
|
||||
return page_offsets[-1][0] if page_offsets else 1
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Prompt exports."""
|
||||
|
||||
from medical_coding.prompts.classification import (
|
||||
CLASSIFICATION_SYSTEM_PROMPT,
|
||||
CLASSIFICATION_USER_TEMPLATE,
|
||||
)
|
||||
from medical_coding.prompts.context import (
|
||||
CONTEXT_ANALYSIS_SYSTEM_PROMPT,
|
||||
CONTEXT_ANALYSIS_USER_TEMPLATE,
|
||||
)
|
||||
from medical_coding.prompts.extraction import (
|
||||
EXTRACTION_SYSTEM_PROMPT,
|
||||
EXTRACTION_USER_TEMPLATE,
|
||||
)
|
||||
from medical_coding.prompts.ranking import (
|
||||
RANKING_SYSTEM_PROMPT,
|
||||
RANKING_USER_TEMPLATE,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"CLASSIFICATION_SYSTEM_PROMPT",
|
||||
"CLASSIFICATION_USER_TEMPLATE",
|
||||
"CONTEXT_ANALYSIS_SYSTEM_PROMPT",
|
||||
"CONTEXT_ANALYSIS_USER_TEMPLATE",
|
||||
"EXTRACTION_SYSTEM_PROMPT",
|
||||
"EXTRACTION_USER_TEMPLATE",
|
||||
"RANKING_SYSTEM_PROMPT",
|
||||
"RANKING_USER_TEMPLATE",
|
||||
]
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Prompt templates for primary vs secondary diagnosis classification."""
|
||||
|
||||
CLASSIFICATION_SYSTEM_PROMPT = """You are a certified professional inpatient medical coding auditor.
|
||||
Your task is to classify clinically extracted and context-assessed diagnoses into billing roles adhering strictly to the Official ICD-10-CM Coding Guidelines (UHDDS).
|
||||
|
||||
INPUT CONSTRAINT:
|
||||
Classify ONLY the provided context-assessed conditions. Do NOT invent new diagnoses or classify directly from unstructured text unless resolving an evidence-supported ambiguity.
|
||||
|
||||
CRITICAL CODING RULES:
|
||||
1. MAXIMUM ONE PRIMARY DIAGNOSIS:
|
||||
- The primary diagnosis is defined as the condition established after study to be chiefly responsible for occasioning the admission of the patient to the hospital for care.
|
||||
- Consider documented:
|
||||
* reason for admission
|
||||
* presenting condition / chief complaint
|
||||
* final discharge diagnosis
|
||||
* hospital course and major procedures / treatments administered
|
||||
* physician documentation and clinical significance
|
||||
- NEVER select the first diagnosis mentioned merely because of its document order.
|
||||
- If two or more conditions equally meet the criteria for primary diagnosis and the documentation does not distinguish which one occasioned the admission, do NOT arbitrarily choose one. Flag as an ambiguous primary requiring abstention.
|
||||
- If no defensible primary condition exists, do NOT force one.
|
||||
|
||||
2. ZERO OR MORE SECONDARY DIAGNOSES:
|
||||
- A co-existing condition qualifies as a secondary diagnosis when documented evidence shows that it was:
|
||||
* clinically relevant
|
||||
* actively managed or treated
|
||||
* monitored (serial labs, diagnostic workup, vitals)
|
||||
* influencing clinical care or increasing nursing care during the stay.
|
||||
|
||||
3. EXCLUDED CONDITIONS (DO NOT CODE):
|
||||
- Historical-only conditions without documented inpatient care.
|
||||
- Definitively ruled-out or negated conditions.
|
||||
- Symptoms that are integral to a confirmed underlying diagnosis.
|
||||
- Assign role: "EXCLUDED" and is_billable_candidate: false.
|
||||
|
||||
4. NO ICD CODES:
|
||||
- You must NEVER generate, suggest, or assign ICD codes. Only assign billing roles ("PRIMARY", "SECONDARY", "EXCLUDED") with explicit clinical reasons.
|
||||
|
||||
Output valid JSON strictly conforming to:
|
||||
{
|
||||
"has_unique_primary": true,
|
||||
"is_ambiguous_primary": false,
|
||||
"abstention_recommended": false,
|
||||
"abstention_reason": null,
|
||||
"classifications": [
|
||||
{
|
||||
"diagnosis_id": "condition identifier",
|
||||
"diagnosis": "Condition name",
|
||||
"role": "PRIMARY" | "SECONDARY" | "EXCLUDED",
|
||||
"is_billable_candidate": true | false,
|
||||
"classification_reason": "Explicit justification for the role assignment",
|
||||
"primary_justification": "Why this specific condition occasioned the admission (if PRIMARY)"
|
||||
}
|
||||
]
|
||||
}
|
||||
"""
|
||||
|
||||
CLASSIFICATION_USER_TEMPLATE = """Review the following assessed conditions and classify them into billing roles adhering strictly to the UHDDS inpatient guidelines.
|
||||
|
||||
Assessed Conditions:
|
||||
\"\"\"
|
||||
{conditions_json}
|
||||
\"\"\"
|
||||
|
||||
Clinical Document Excerpt for Evidence Verification:
|
||||
\"\"\"
|
||||
{clinical_text}
|
||||
\"\"\"
|
||||
|
||||
Output valid JSON only:"""
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Prompt templates for determining clinical relevance, inpatient management, and coding eligibility."""
|
||||
|
||||
CONTEXT_ASSESSMENT_SYSTEM_PROMPT = """You are a certified inpatient medical coding auditor.
|
||||
Your job is to determine whether each extracted medical condition is clinically relevant to the CURRENT hospitalization based ONLY on documented evidence.
|
||||
|
||||
CRITICAL ARCHITECTURAL RULES:
|
||||
1. NO ICD CODES: You must NEVER output, generate, or suggest any ICD codes.
|
||||
2. NO INVENTED FACTS: Base your assessment strictly on the documented evidence. Do not use external assumptions.
|
||||
3. PAST MEDICAL HISTORY RULE:
|
||||
- Past Medical History (PMH) alone does NOT make a condition eligible for coding.
|
||||
- Example: "Past history: diabetes mellitus" without active monitoring or treatment during admission -> coding_candidate: false, current_relevance: false.
|
||||
- Example: "Diabetes mellitus was monitored and insulin was adjusted during admission" -> coding_candidate: true, current_relevance: true.
|
||||
4. RULED-OUT CONDITIONS:
|
||||
- A condition suspected initially but ruled out by diagnostic workup (e.g. "possible pneumonia suspected initially but imaging showed no evidence of pneumonia") MUST NOT become a confirmed diagnosis -> certainty: RULED_OUT, coding_candidate: false.
|
||||
5. PRESERVE UNCERTAINTY:
|
||||
- Do NOT convert suspected or possible conditions into confirmed diagnoses.
|
||||
- If documented as probable or suspected, preserve certainty as SUSPECTED or POSSIBLE.
|
||||
6. AMBIGUOUS CASES:
|
||||
- If clinical evidence is contradictory, unresolvable, or completely unsubstantiated, recommend abstention -> abstain_recommended: true.
|
||||
|
||||
Output your response strictly as a JSON array of objects conforming to the required schema:
|
||||
[
|
||||
{
|
||||
"diagnosis": "Name of condition (e.g. 'Acute urinary tract infection')",
|
||||
"current_relevance": true,
|
||||
"coding_candidate": true,
|
||||
"status": "ACTIVE",
|
||||
"certainty": "CONFIRMED",
|
||||
"temporality": "CURRENT",
|
||||
"negation": "AFFIRMATIVE",
|
||||
"evidence": "Exact excerpt from the document providing proof",
|
||||
"reason": "Explicit clinical rationale explaining why condition is relevant or historical",
|
||||
"treated_or_managed": true,
|
||||
"monitored": true,
|
||||
"affected_clinical_management": true,
|
||||
"influenced_treatment": true,
|
||||
"treatment_evidence": "Treated with 5 days of IV ceftriaxone" or null,
|
||||
"abstain_recommended": false,
|
||||
"abstention_reason": null
|
||||
}
|
||||
]
|
||||
"""
|
||||
|
||||
CONTEXT_ASSESSMENT_USER_TEMPLATE = """Evaluate the clinical relevance and inpatient management for the following extracted conditions based strictly on the clinical documentation.
|
||||
|
||||
Clinical Documentation:
|
||||
\"\"\"
|
||||
{clinical_text}
|
||||
\"\"\"
|
||||
|
||||
Extracted Conditions to Evaluate:
|
||||
\"\"\"
|
||||
{conditions_json}
|
||||
\"\"\"
|
||||
|
||||
Output JSON array only:"""
|
||||
|
||||
# Backwards-compatibility aliases
|
||||
CONTEXT_ANALYSIS_SYSTEM_PROMPT = CONTEXT_ASSESSMENT_SYSTEM_PROMPT
|
||||
CONTEXT_ANALYSIS_USER_TEMPLATE = CONTEXT_ASSESSMENT_USER_TEMPLATE
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Prompt templates for extracting clinical conditions and structured context with evidence grounding."""
|
||||
|
||||
CLINICAL_EXTRACTION_SYSTEM_PROMPT = """You are an expert clinical documentation auditor.
|
||||
Your sole task is to extract medical conditions and structured clinical context from the provided discharge summary.
|
||||
|
||||
CRITICAL RULES:
|
||||
1. STRICT BAN ON ICD CODES: You must NEVER generate, suggest, or include any ICD codes (e.g., no 'I50.21', no 'E11.9').
|
||||
2. MANDATORY VERBATIM EVIDENCE: Every condition must include an exact 'evidence_text' sentence or clause from the document.
|
||||
3. NO FABRICATION: If a condition cannot be substantiated with an exact quote, DO NOT extract it.
|
||||
4. DO NOT CONVERT UNCERTAIN CONDITIONS:
|
||||
- Mark as SUSPECTED or POSSIBLE if documented as 'probable', 'possible', 'suspected', or differential.
|
||||
- Mark as RULED_OUT if documented as 'ruled out', 'excluded', or 'negative for'.
|
||||
- Mark as CONFIRMED only if explicitly stated or definitively treated as a confirmed diagnosis.
|
||||
5. TEMPORALITY & STATUS:
|
||||
- Mark as HISTORICAL if documented under past medical history or resolved prior to admission.
|
||||
- Mark as CURRENT / ACTIVE if treated, evaluated, or monitored during this hospitalization.
|
||||
- Mark as RESOLVED if documented as resolved or cured during the encounter.
|
||||
|
||||
Output your response ONLY as a JSON array of objects following this exact schema:
|
||||
[
|
||||
{
|
||||
"original_mention": "Verbatim phrase from text (e.g., 'acute systolic congestive heart failure')",
|
||||
"normalized_description": "Clean standard clinical name (e.g., 'Acute systolic heart failure')",
|
||||
"entity_type": "DIAGNOSIS",
|
||||
"evidence_text": "Exact sentence from the note providing proof",
|
||||
"status": "ACTIVE",
|
||||
"certainty": "CONFIRMED",
|
||||
"temporality": "CURRENT",
|
||||
"negation": "AFFIRMATIVE",
|
||||
"anatomical_site": "heart" or null,
|
||||
"laterality": "UNSPECIFIED",
|
||||
"section": "DISCHARGE_DIAGNOSES",
|
||||
"treatment_evidence": "Initiated on IV furosemide" or null
|
||||
}
|
||||
]
|
||||
"""
|
||||
|
||||
CLINICAL_EXTRACTION_USER_TEMPLATE = """Extract all clinical conditions, statuses, and verbatim evidence from the documentation below.
|
||||
|
||||
Documentation:
|
||||
\"\"\"
|
||||
{clinical_text}
|
||||
\"\"\"
|
||||
|
||||
Output JSON array only:"""
|
||||
|
||||
CLINICAL_EXTRACTION_RETRY_TEMPLATE = """The previous output was invalid JSON or missing required fields.
|
||||
Please re-extract the clinical conditions from the text below as a strictly valid JSON array.
|
||||
Remember:
|
||||
1. No ICD codes.
|
||||
2. Every item must have verbatim evidence_text from the note.
|
||||
3. Output ONLY the JSON array enclosed in [ and ].
|
||||
|
||||
Documentation:
|
||||
\"\"\"
|
||||
{clinical_text}
|
||||
\"\"\"
|
||||
|
||||
Output JSON array only:"""
|
||||
|
||||
# Backwards-compatibility aliases
|
||||
EXTRACTION_SYSTEM_PROMPT = CLINICAL_EXTRACTION_SYSTEM_PROMPT
|
||||
EXTRACTION_USER_TEMPLATE = CLINICAL_EXTRACTION_USER_TEMPLATE
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Prompt templates for evaluating and ranking retrieved candidate codes from the local ICD dataset."""
|
||||
|
||||
RANKING_SYSTEM_PROMPT = """You are an expert clinical coding auditor and candidate ranking reviewer.
|
||||
Your objective is to answer:
|
||||
"Which of these retrieved ICD-10-CM codes is best supported by the documented clinical evidence?"
|
||||
You must NEVER answer:
|
||||
"What ICD code do I know for this diagnosis from external training memory?"
|
||||
|
||||
CRITICAL ARCHITECTURAL RULES:
|
||||
1. STRICT CANDIDATE BOUND:
|
||||
You may ONLY select a code that appears explicitly in the provided 'Authoritative Retrieved Candidates' list.
|
||||
You must NEVER invent, hallucinate, or generate any code not present in that list.
|
||||
2. EVIDENCE-BASED SPECIFICITY RULE:
|
||||
Do NOT infer or extrapolate clinical specificity that is absent from the documented clinical evidence.
|
||||
If documentation only supports a general condition (e.g., "heart failure" or "diabetes"), do NOT select a highly specific sub-code (e.g., acute systolic heart failure or diabetes with nephropathy) merely because it is in the candidate pool. Choose the general/unspecified candidate if supported, or ABSTAIN.
|
||||
3. CLINICAL DIMENSIONS TO EVALUATE:
|
||||
- Terminology match: Clinical phrasing alignment.
|
||||
- Specificity: Only select subtypes explicitly supported by documentation.
|
||||
- Anatomy & Laterality: Left, right, bilateral, or unspecified.
|
||||
- Acuity: Acute, chronic, acute on chronic, or unspecified.
|
||||
- Evidence support: Is the condition factually corroborated by the quote?
|
||||
4. ABSTENTION:
|
||||
If none of the retrieved candidates are supported by the evidence quote, or if evidence is insufficient, you MUST set "selected_code": null and "decision": "ABSTAINED".
|
||||
|
||||
OUTPUT FORMAT:
|
||||
Respond with valid JSON only. Do not add markdown commentary outside the JSON block.
|
||||
|
||||
Required Schema:
|
||||
{
|
||||
"selected_code": "I50.21" or null,
|
||||
"selected_description": "Acute systolic heart failure" or null,
|
||||
"ranking_reason": "Clinical justification explaining why this code is supported or why abstention occurred.",
|
||||
"supporting_evidence": "Verbatim quote providing proof from documentation.",
|
||||
"confidence": 0.95,
|
||||
"decision": "ACCEPTED" or "ABSTAINED" or "REJECTED_MISMATCH",
|
||||
"abstention_reason": null or "UNSUPPORTED_SPECIFICITY" or "INSUFFICIENT_EVIDENCE" or "NO_MATCHING_CANDIDATE"
|
||||
}
|
||||
"""
|
||||
|
||||
RANKING_USER_TEMPLATE = """Evaluate the retrieved candidate ICD-10-CM codes against the documented clinical condition and evidence.
|
||||
|
||||
Clinical Condition: {diagnosis_term}
|
||||
Documented Evidence: \"{evidence_quote}\"
|
||||
Assigned Role: {role}
|
||||
Acuity: {acuity}
|
||||
Certainty: {certainty}
|
||||
Anatomical Site: {anatomical_site}
|
||||
Laterality: {laterality}
|
||||
|
||||
Authoritative Retrieved Candidates (from Local Dataset Only):
|
||||
\"\"\"
|
||||
{candidates_formatted}
|
||||
\"\"\"
|
||||
|
||||
Remember:
|
||||
- You may select ONLY from the candidate list above.
|
||||
- If none of the candidates are factually supported by the evidence quote, select null.
|
||||
- Do NOT assume specificity that is not documented.
|
||||
|
||||
Respond with valid JSON:"""
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Retrieval exports."""
|
||||
|
||||
from medical_coding.retrieval.base import BaseICDRetriever
|
||||
from medical_coding.retrieval.hybrid import HybridICDRetriever
|
||||
from medical_coding.retrieval.lexical import BM25ICDRetriever
|
||||
from medical_coding.retrieval.vector import FAISSICDRetriever
|
||||
|
||||
__all__ = [
|
||||
"BM25ICDRetriever",
|
||||
"BaseICDRetriever",
|
||||
"FAISSICDRetriever",
|
||||
"HybridICDRetriever",
|
||||
]
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Abstract base class for ICD candidate retrieval engines."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
from medical_coding.schemas.icd import ICDCandidate
|
||||
|
||||
|
||||
class BaseICDRetriever(ABC):
|
||||
"""Interface for searching authoritative ICD candidates from the local dataset."""
|
||||
|
||||
@abstractmethod
|
||||
def retrieve(self, query: str, top_k: int = 10) -> list[ICDCandidate]:
|
||||
"""Retrieve top candidate ICD records matching the clinical query.
|
||||
|
||||
Args:
|
||||
query: Clinical diagnosis string or expanded context.
|
||||
top_k: Maximum number of candidates to return.
|
||||
|
||||
Returns:
|
||||
List of ICDCandidate objects sourced strictly from local ICD-10-CM data.
|
||||
"""
|
||||
pass
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Hybrid retrieval combining lexical (BM25) and dense semantic (FAISS) local search."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from medical_coding.dataset.validator import LocalICDCatalog
|
||||
from medical_coding.retrieval.base import BaseICDRetriever
|
||||
from medical_coding.schemas.icd import ICDCandidate
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class HybridICDRetriever(BaseICDRetriever):
|
||||
"""Fuses lexical BM25 and dense semantic FAISS retrieval over the local ICD dataset.
|
||||
|
||||
Score Calculation Formula:
|
||||
For each retrieved code candidate 'c':
|
||||
Score_hybrid(c) = (weight_semantic * S_semantic(c)) + (weight_lexical * S_lexical(c))
|
||||
|
||||
Where:
|
||||
- S_semantic(c) in [0.0, 1.0]: Cosine similarity from FAISS dense vector search
|
||||
- S_lexical(c) in [0.0, 1.0]: Normalized BM25 score with query coverage weighting
|
||||
- weight_semantic + weight_lexical are normalized to sum to 1.0.
|
||||
|
||||
Candidates appearing in both lexical and semantic pools receive reinforcement.
|
||||
Candidates scoring below min_score_threshold are excluded. If no candidates exceed
|
||||
the threshold, the retriever returns an empty list (explicit abstention state).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
lexical_retriever: BaseICDRetriever,
|
||||
vector_retriever: BaseICDRetriever,
|
||||
catalog: LocalICDCatalog | None = None,
|
||||
weight_semantic: float = 0.6,
|
||||
weight_lexical: float = 0.4,
|
||||
min_score_threshold: float = 0.35,
|
||||
default_top_k: int = 10,
|
||||
) -> None:
|
||||
self.lexical_retriever = lexical_retriever
|
||||
self.vector_retriever = vector_retriever
|
||||
self.catalog = catalog
|
||||
|
||||
# Normalize weights so they strictly sum to 1.0
|
||||
total_weight = weight_semantic + weight_lexical
|
||||
if total_weight <= 0.0:
|
||||
raise ValueError("Total weight (semantic + lexical) must be positive.")
|
||||
self.weight_semantic = weight_semantic / total_weight
|
||||
self.weight_lexical = weight_lexical / total_weight
|
||||
|
||||
self.min_score_threshold = min_score_threshold
|
||||
self.default_top_k = default_top_k
|
||||
|
||||
def retrieve(
|
||||
self,
|
||||
query: str,
|
||||
top_k: int | None = None,
|
||||
min_score: float | None = None,
|
||||
) -> list[ICDCandidate]:
|
||||
"""Execute hybrid search, merge candidates, score, deduplicate, and rank.
|
||||
|
||||
Args:
|
||||
query: Normalized clinical diagnosis or condition description.
|
||||
top_k: Maximum candidate pool size to return (defaults to configured top_k).
|
||||
min_score: Minimum threshold override; candidates below this are pruned.
|
||||
|
||||
Returns:
|
||||
Ranked list of ICDCandidate objects sourced exclusively from the local catalog.
|
||||
Returns an empty list (abstention) if no candidate meets the threshold.
|
||||
"""
|
||||
k = top_k if top_k is not None else self.default_top_k
|
||||
threshold = min_score if min_score is not None else self.min_score_threshold
|
||||
|
||||
clean_query = query.strip()
|
||||
if not clean_query:
|
||||
return []
|
||||
|
||||
# Retrieve candidates from both local engines with an expanded initial window
|
||||
search_window = max(k * 3, 20)
|
||||
lexical_hits = self.lexical_retriever.retrieve(clean_query, top_k=search_window)
|
||||
vector_hits = self.vector_retriever.retrieve(clean_query, top_k=search_window)
|
||||
|
||||
# Merge candidate pools by authoritative code
|
||||
merged: dict[str, dict[str, Any]] = {}
|
||||
|
||||
for hit in lexical_hits:
|
||||
# Enforce local catalog existence if catalog is attached
|
||||
if self.catalog and not self.catalog.is_valid_code(hit.code):
|
||||
continue
|
||||
merged[hit.code] = {
|
||||
"code": hit.code,
|
||||
"description": hit.description,
|
||||
"is_valid_billable": hit.is_valid_billable,
|
||||
"category": hit.category,
|
||||
"lexical_score": hit.retrieval_score,
|
||||
"semantic_score": 0.0,
|
||||
}
|
||||
|
||||
for hit in vector_hits:
|
||||
if self.catalog and not self.catalog.is_valid_code(hit.code):
|
||||
continue
|
||||
if hit.code in merged:
|
||||
merged[hit.code]["semantic_score"] = hit.retrieval_score
|
||||
# Keep most descriptive text
|
||||
if len(hit.description) > len(merged[hit.code]["description"]):
|
||||
merged[hit.code]["description"] = hit.description
|
||||
else:
|
||||
merged[hit.code] = {
|
||||
"code": hit.code,
|
||||
"description": hit.description,
|
||||
"is_valid_billable": hit.is_valid_billable,
|
||||
"category": hit.category,
|
||||
"lexical_score": 0.0,
|
||||
"semantic_score": hit.retrieval_score,
|
||||
}
|
||||
|
||||
if not merged:
|
||||
logger.info(
|
||||
"Hybrid retrieval: No candidates found for query '%s' (abstaining).", clean_query
|
||||
)
|
||||
return []
|
||||
|
||||
# Compute combined hybrid score
|
||||
candidate_pool: list[ICDCandidate] = []
|
||||
for code, info in merged.items():
|
||||
sem = info["semantic_score"]
|
||||
lex = info["lexical_score"]
|
||||
|
||||
hybrid_score = (self.weight_semantic * sem) + (self.weight_lexical * lex)
|
||||
rounded_score = max(0.0, min(1.0, round(hybrid_score, 4)))
|
||||
|
||||
# Filter against relevance threshold
|
||||
if rounded_score < threshold:
|
||||
continue
|
||||
|
||||
# Determine retrieval method provenance
|
||||
if sem > 0.0 and lex > 0.0:
|
||||
method = "hybrid"
|
||||
elif sem > 0.0:
|
||||
method = "faiss"
|
||||
else:
|
||||
method = "bm25"
|
||||
|
||||
candidate_pool.append(
|
||||
ICDCandidate(
|
||||
code=code,
|
||||
description=info["description"],
|
||||
retrieval_score=rounded_score,
|
||||
retrieval_method=method,
|
||||
is_valid_billable=info["is_valid_billable"],
|
||||
semantic_score=round(sem, 4),
|
||||
lexical_score=round(lex, 4),
|
||||
category=info["category"],
|
||||
)
|
||||
)
|
||||
|
||||
# Sort descending by hybrid retrieval score
|
||||
candidate_pool.sort(key=lambda c: c.retrieval_score, reverse=True)
|
||||
|
||||
top_candidates = candidate_pool[:k]
|
||||
|
||||
if not top_candidates:
|
||||
logger.info(
|
||||
"Hybrid retrieval: %d candidates found but none met min_score threshold %.2f for query '%s' (abstaining).",
|
||||
len(merged),
|
||||
threshold,
|
||||
clean_query,
|
||||
)
|
||||
return []
|
||||
|
||||
return top_candidates
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Lexical BM25 retrieval for local ICD-10-CM code matching."""
|
||||
|
||||
import pickle
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from rank_bm25 import BM25Okapi
|
||||
|
||||
from medical_coding.retrieval.base import BaseICDRetriever
|
||||
from medical_coding.retrieval.tokenizer import (
|
||||
normalize_clinical_query,
|
||||
tokenize_clinical_text,
|
||||
)
|
||||
from medical_coding.schemas.icd import ICDCandidate, ICDCodeRecord
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class BM25ICDRetriever(BaseICDRetriever):
|
||||
"""Lexical retriever utilizing BM25 over local ICD-10-CM descriptions and synonyms."""
|
||||
|
||||
def __init__(self, index_path: Path | str | None = None) -> None:
|
||||
self.index_path = Path(index_path) if index_path else None
|
||||
self._bm25_index: BM25Okapi | None = None
|
||||
self._records: list[ICDCodeRecord] = []
|
||||
self._tokenized_corpus: list[list[str]] = []
|
||||
|
||||
@property
|
||||
def is_indexed(self) -> bool:
|
||||
return self._bm25_index is not None and len(self._records) > 0
|
||||
|
||||
def build_index(self, records: list[ICDCodeRecord]) -> None:
|
||||
"""Tokenize and compile BM25 index from authoritative local ICD records."""
|
||||
if not records:
|
||||
raise ValueError("Cannot build BM25 index with empty ICD record list.")
|
||||
|
||||
self._records = records
|
||||
self._tokenized_corpus = []
|
||||
|
||||
for record in records:
|
||||
# Index code, formatted and unformatted
|
||||
code_tokens = [record.code.lower(), record.unformatted_code.lower()]
|
||||
# Index searchable clinical description, synonyms, and inclusion terms
|
||||
searchable_text = record.get_searchable_text()
|
||||
text_tokens = tokenize_clinical_text(searchable_text, expand_abbreviations=True)
|
||||
combined_tokens = code_tokens + text_tokens
|
||||
self._tokenized_corpus.append(combined_tokens)
|
||||
|
||||
self._bm25_index = BM25Okapi(self._tokenized_corpus)
|
||||
logger.info("Compiled BM25 index over %d authoritative ICD records.", len(self._records))
|
||||
|
||||
def retrieve(self, query: str, top_k: int = 15) -> list[ICDCandidate]:
|
||||
"""Perform lexical BM25 search against local ICD-10-CM catalog.
|
||||
|
||||
Scoring Calculation:
|
||||
BM25 scores are normalized to [0.0, 1.0] using a composite formula:
|
||||
score = 0.5 * (raw_bm25 / max_raw_bm25) + 0.5 * (term_overlap / query_length)
|
||||
where:
|
||||
- raw_bm25 / max_raw_bm25 represents relative term-frequency saturation
|
||||
- term_overlap / query_length represents exact query coverage fraction
|
||||
"""
|
||||
if not self.is_indexed:
|
||||
raise RuntimeError("BM25 index has not been built or loaded.")
|
||||
|
||||
normalized_query = normalize_clinical_query(query)
|
||||
query_tokens = tokenize_clinical_text(normalized_query, expand_abbreviations=True)
|
||||
if not query_tokens:
|
||||
return []
|
||||
|
||||
assert self._bm25_index is not None
|
||||
raw_scores = self._bm25_index.get_scores(query_tokens)
|
||||
|
||||
max_raw_score = float(max(raw_scores)) if len(raw_scores) > 0 else 0.0
|
||||
if max_raw_score <= 0.0:
|
||||
return []
|
||||
|
||||
# Find indices with non-zero scores sorted descending
|
||||
indexed_scores = [
|
||||
(idx, float(score)) for idx, score in enumerate(raw_scores) if score > 0.0
|
||||
]
|
||||
indexed_scores.sort(key=lambda x: x[1], reverse=True)
|
||||
|
||||
candidates: list[ICDCandidate] = []
|
||||
query_token_set = set(query_tokens)
|
||||
|
||||
for idx, raw_score in indexed_scores[:top_k]:
|
||||
record = self._records[idx]
|
||||
doc_tokens = set(self._tokenized_corpus[idx])
|
||||
overlap = len(query_token_set & doc_tokens)
|
||||
coverage = overlap / len(query_token_set) if query_token_set else 0.0
|
||||
|
||||
relative_bm25 = raw_score / max_raw_score
|
||||
# Composite normalized score
|
||||
normalized_score = 0.5 * relative_bm25 + 0.5 * coverage
|
||||
clamped_score = max(0.0, min(1.0, round(normalized_score, 4)))
|
||||
|
||||
candidates.append(
|
||||
ICDCandidate(
|
||||
code=record.code,
|
||||
description=record.description,
|
||||
retrieval_score=clamped_score,
|
||||
retrieval_method="bm25",
|
||||
is_valid_billable=record.is_valid_billable,
|
||||
lexical_score=clamped_score,
|
||||
category=record.category,
|
||||
)
|
||||
)
|
||||
|
||||
return candidates
|
||||
|
||||
def save(self, output_dir: Path | str) -> None:
|
||||
"""Persist tokenized BM25 corpus and record metadata to disk."""
|
||||
target_dir = Path(output_dir)
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
save_file = target_dir / "bm25_index.pkl"
|
||||
|
||||
data: dict[str, Any] = {
|
||||
"tokenized_corpus": self._tokenized_corpus,
|
||||
"records": [r.model_dump() for r in self._records],
|
||||
}
|
||||
with open(save_file, "wb") as f:
|
||||
pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL)
|
||||
|
||||
logger.info("Saved BM25 index to %s", save_file)
|
||||
|
||||
def load(self, index_dir: Path | str) -> None:
|
||||
"""Load BM25 corpus from persisted disk storage."""
|
||||
source_file = Path(index_dir) / "bm25_index.pkl"
|
||||
if not source_file.exists():
|
||||
raise FileNotFoundError(f"BM25 index file not found at {source_file}")
|
||||
|
||||
with open(source_file, "rb") as f:
|
||||
data = pickle.load(f)
|
||||
|
||||
self._tokenized_corpus = data["tokenized_corpus"]
|
||||
self._records = [ICDCodeRecord.model_validate(r) for r in data["records"]]
|
||||
self._bm25_index = BM25Okapi(self._tokenized_corpus)
|
||||
logger.info("Loaded BM25 index from %s (%d records)", source_file, len(self._records))
|
||||
@@ -0,0 +1,227 @@
|
||||
"""Clinical text tokenization, normalization, and medical abbreviation expansion."""
|
||||
|
||||
import re
|
||||
|
||||
# Standard clinical abbreviations mapped to expanded medical concepts
|
||||
CLINICAL_ABBREVIATIONS: dict[str, str] = {
|
||||
"hf": "heart failure",
|
||||
"chf": "congestive heart failure",
|
||||
"hfref": "heart failure reduced ejection fraction systolic",
|
||||
"hfpef": "heart failure preserved ejection fraction diastolic",
|
||||
"dm": "diabetes mellitus",
|
||||
"t1dm": "type 1 diabetes mellitus",
|
||||
"t2dm": "type 2 diabetes mellitus",
|
||||
"htn": "hypertension",
|
||||
"ckd": "chronic kidney disease",
|
||||
"esrd": "end stage renal disease",
|
||||
"copd": "chronic obstructive pulmonary disease",
|
||||
"afib": "atrial fibrillation",
|
||||
"af": "atrial fibrillation",
|
||||
"cad": "coronary artery disease",
|
||||
"mi": "myocardial infarction",
|
||||
"ami": "acute myocardial infarction",
|
||||
"stemi": "st elevation myocardial infarction",
|
||||
"nstemi": "non st elevation myocardial infarction",
|
||||
"aki": "acute kidney injury",
|
||||
"arf": "acute renal failure",
|
||||
"dvt": "deep vein thrombosis",
|
||||
"pe": "pulmonary embolism",
|
||||
"gerd": "gastroesophageal reflux disease",
|
||||
"cva": "cerebrovascular accident stroke",
|
||||
"tia": "transient ischemic attack",
|
||||
"uti": "urinary tract infection",
|
||||
"pna": "pneumonia",
|
||||
"pud": "peptic ulcer disease",
|
||||
"sob": "shortness of breath dyspnea",
|
||||
"bph": "benign prostatic hyperplasia",
|
||||
"osa": "obstructive sleep apnea",
|
||||
"ra": "rheumatoid arthritis",
|
||||
"oa": "osteoarthritis",
|
||||
}
|
||||
|
||||
# Non-informative general words (keeping critical medical distinctions: acute, chronic, type, 1, 2, without, etc.)
|
||||
GENERAL_STOPWORDS: set[str] = {
|
||||
"a",
|
||||
"about",
|
||||
"above",
|
||||
"after",
|
||||
"again",
|
||||
"against",
|
||||
"all",
|
||||
"am",
|
||||
"an",
|
||||
"and",
|
||||
"any",
|
||||
"are",
|
||||
"as",
|
||||
"at",
|
||||
"be",
|
||||
"because",
|
||||
"been",
|
||||
"before",
|
||||
"being",
|
||||
"below",
|
||||
"between",
|
||||
"both",
|
||||
"but",
|
||||
"by",
|
||||
"could",
|
||||
"did",
|
||||
"do",
|
||||
"does",
|
||||
"doing",
|
||||
"down",
|
||||
"during",
|
||||
"each",
|
||||
"for",
|
||||
"from",
|
||||
"further",
|
||||
"had",
|
||||
"has",
|
||||
"have",
|
||||
"having",
|
||||
"he",
|
||||
"her",
|
||||
"here",
|
||||
"hers",
|
||||
"herself",
|
||||
"him",
|
||||
"himself",
|
||||
"his",
|
||||
"how",
|
||||
"i",
|
||||
"if",
|
||||
"in",
|
||||
"into",
|
||||
"is",
|
||||
"it",
|
||||
"its",
|
||||
"itself",
|
||||
"me",
|
||||
"more",
|
||||
"most",
|
||||
"my",
|
||||
"myself",
|
||||
"no",
|
||||
"nor",
|
||||
"not",
|
||||
"of",
|
||||
"off",
|
||||
"on",
|
||||
"once",
|
||||
"only",
|
||||
"or",
|
||||
"other",
|
||||
"ought",
|
||||
"our",
|
||||
"ours",
|
||||
"ourselves",
|
||||
"out",
|
||||
"over",
|
||||
"own",
|
||||
"same",
|
||||
"she",
|
||||
"should",
|
||||
"so",
|
||||
"some",
|
||||
"such",
|
||||
"than",
|
||||
"that",
|
||||
"the",
|
||||
"their",
|
||||
"theirs",
|
||||
"them",
|
||||
"themselves",
|
||||
"then",
|
||||
"there",
|
||||
"these",
|
||||
"they",
|
||||
"this",
|
||||
"those",
|
||||
"through",
|
||||
"to",
|
||||
"too",
|
||||
"under",
|
||||
"until",
|
||||
"up",
|
||||
"very",
|
||||
"was",
|
||||
"we",
|
||||
"were",
|
||||
"what",
|
||||
"when",
|
||||
"where",
|
||||
"which",
|
||||
"while",
|
||||
"who",
|
||||
"whom",
|
||||
"why",
|
||||
"with",
|
||||
"would",
|
||||
"you",
|
||||
"your",
|
||||
"yours",
|
||||
"yourself",
|
||||
"yourselves",
|
||||
}
|
||||
|
||||
|
||||
def expand_medical_abbreviations(text: str) -> str:
|
||||
"""Expand recognized clinical acronyms into full diagnostic terms.
|
||||
|
||||
Example:
|
||||
'acute systolic HF' -> 'acute systolic heart failure'
|
||||
"""
|
||||
if not text:
|
||||
return ""
|
||||
|
||||
tokens = re.findall(r"\b[A-Za-z0-9_]+\b", text)
|
||||
expanded: list[str] = []
|
||||
for token in tokens:
|
||||
lower = token.lower()
|
||||
if lower in CLINICAL_ABBREVIATIONS:
|
||||
expanded.append(CLINICAL_ABBREVIATIONS[lower])
|
||||
else:
|
||||
expanded.append(token)
|
||||
|
||||
return " ".join(expanded)
|
||||
|
||||
|
||||
def tokenize_clinical_text(
|
||||
text: str,
|
||||
expand_abbreviations: bool = True,
|
||||
remove_stopwords: bool = True,
|
||||
) -> list[str]:
|
||||
"""Tokenize clinical text into normalized lowercase tokens for BM25 lexical search.
|
||||
|
||||
Args:
|
||||
text: Clinical text or diagnosis description.
|
||||
expand_abbreviations: Whether to expand medical abbreviations.
|
||||
remove_stopwords: Whether to filter general non-informative stopwords.
|
||||
|
||||
Returns:
|
||||
List of cleaned token strings.
|
||||
"""
|
||||
if not text:
|
||||
return []
|
||||
|
||||
processed = text
|
||||
if expand_abbreviations:
|
||||
processed = expand_medical_abbreviations(processed)
|
||||
|
||||
# Extract alphanumeric words and decimal codes
|
||||
raw_tokens = re.findall(r"[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)?", processed.lower())
|
||||
|
||||
if remove_stopwords:
|
||||
tokens = [t for t in raw_tokens if t not in GENERAL_STOPWORDS and len(t) > 1]
|
||||
else:
|
||||
tokens = [t for t in raw_tokens if len(t) > 0]
|
||||
|
||||
return tokens
|
||||
|
||||
|
||||
def normalize_clinical_query(text: str) -> str:
|
||||
"""Prepare a normalized string query for retrieval with abbreviations expanded."""
|
||||
expanded = expand_medical_abbreviations(text.strip())
|
||||
# Clean redundant spaces
|
||||
return re.sub(r"\s+", " ", expanded)
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Dense vector retrieval using local embeddings and FAISS index."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import faiss
|
||||
import numpy as np
|
||||
|
||||
from medical_coding.models.base import BaseLocalEmbeddings
|
||||
from medical_coding.retrieval.base import BaseICDRetriever
|
||||
from medical_coding.retrieval.tokenizer import normalize_clinical_query
|
||||
from medical_coding.schemas.icd import ICDCandidate, ICDCodeRecord
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class FAISSICDRetriever(BaseICDRetriever):
|
||||
"""Semantic vector retriever using local offline embeddings and FAISS IndexFlatIP."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
embeddings: BaseLocalEmbeddings,
|
||||
index_path: Path | str | None = None,
|
||||
) -> None:
|
||||
self.embeddings = embeddings
|
||||
self.index_path = Path(index_path) if index_path else None
|
||||
self._faiss_index: faiss.IndexFlatIP | None = None
|
||||
self._records: list[ICDCodeRecord] = []
|
||||
self._dimension: int = 0
|
||||
|
||||
@property
|
||||
def is_indexed(self) -> bool:
|
||||
return self._faiss_index is not None and len(self._records) > 0
|
||||
|
||||
def build_index(self, records: list[ICDCodeRecord], batch_size: int = 64) -> None:
|
||||
"""Embed descriptions and build FAISS IndexFlatIP over authoritative records."""
|
||||
if not records:
|
||||
raise ValueError("Cannot build FAISS index with empty ICD record list.")
|
||||
|
||||
self._records = records
|
||||
searchable_texts = [r.get_searchable_text() for r in records]
|
||||
|
||||
logger.info("Generating embeddings for %d ICD records...", len(records))
|
||||
all_embeddings: list[list[float]] = []
|
||||
for i in range(0, len(searchable_texts), batch_size):
|
||||
batch = searchable_texts[i : i + batch_size]
|
||||
batch_vecs = self.embeddings.embed_documents(batch)
|
||||
all_embeddings.extend(batch_vecs)
|
||||
|
||||
matrix = np.array(all_embeddings, dtype=np.float32)
|
||||
# Ensure L2-normalized so inner product equals cosine similarity
|
||||
faiss.normalize_L2(matrix)
|
||||
|
||||
self._dimension = matrix.shape[1]
|
||||
self._faiss_index = faiss.IndexFlatIP(self._dimension)
|
||||
self._faiss_index.add(matrix)
|
||||
|
||||
logger.info(
|
||||
"Compiled FAISS IndexFlatIP with %d vectors (dimension %d).",
|
||||
self._faiss_index.ntotal,
|
||||
self._dimension,
|
||||
)
|
||||
|
||||
def retrieve(self, query: str, top_k: int = 15) -> list[ICDCandidate]:
|
||||
"""Embed query and search nearest semantic neighbors in local FAISS index.
|
||||
|
||||
Scoring Calculation:
|
||||
Cosine similarity via L2-normalized Inner Product, clamped to [0.0, 1.0].
|
||||
"""
|
||||
if not self.is_indexed:
|
||||
raise RuntimeError("FAISS vector index has not been built or loaded.")
|
||||
|
||||
normalized_query = normalize_clinical_query(query)
|
||||
if not normalized_query.strip():
|
||||
return []
|
||||
|
||||
raw_vec = self.embeddings.embed_query(normalized_query)
|
||||
query_matrix = np.array([raw_vec], dtype=np.float32)
|
||||
faiss.normalize_L2(query_matrix)
|
||||
|
||||
assert self._faiss_index is not None
|
||||
k_search = min(top_k, len(self._records))
|
||||
distances, indices = self._faiss_index.search(query_matrix, k_search)
|
||||
|
||||
candidates: list[ICDCandidate] = []
|
||||
for sim, idx in zip(distances[0], indices[0], strict=False):
|
||||
if idx < 0 or idx >= len(self._records):
|
||||
continue
|
||||
|
||||
record = self._records[idx]
|
||||
# Clamp cosine similarity to [0.0, 1.0]
|
||||
norm_sim = max(0.0, min(1.0, round(float(sim), 4)))
|
||||
|
||||
candidates.append(
|
||||
ICDCandidate(
|
||||
code=record.code,
|
||||
description=record.description,
|
||||
retrieval_score=norm_sim,
|
||||
retrieval_method="faiss",
|
||||
is_valid_billable=record.is_valid_billable,
|
||||
semantic_score=norm_sim,
|
||||
category=record.category,
|
||||
)
|
||||
)
|
||||
|
||||
return candidates
|
||||
|
||||
def save(self, output_dir: Path | str) -> None:
|
||||
"""Persist FAISS index and record metadata to disk."""
|
||||
if not self.is_indexed:
|
||||
raise RuntimeError("Cannot save uninitialized FAISS index.")
|
||||
|
||||
target_dir = Path(output_dir)
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
index_file = target_dir / "faiss.index"
|
||||
records_file = target_dir / "faiss_records.json"
|
||||
|
||||
assert self._faiss_index is not None
|
||||
faiss.write_index(self._faiss_index, str(index_file))
|
||||
|
||||
metadata: dict[str, Any] = {
|
||||
"dimension": self._dimension,
|
||||
"total_records": len(self._records),
|
||||
"records": [r.model_dump() for r in self._records],
|
||||
}
|
||||
with open(records_file, "w", encoding="utf-8") as f:
|
||||
json.dump(metadata, f, indent=2)
|
||||
|
||||
logger.info("Saved FAISS index to %s and metadata to %s", index_file, records_file)
|
||||
|
||||
def load(self, index_dir: Path | str) -> None:
|
||||
"""Load FAISS index and metadata from disk."""
|
||||
target_dir = Path(index_dir)
|
||||
index_file = target_dir / "faiss.index"
|
||||
records_file = target_dir / "faiss_records.json"
|
||||
|
||||
if not index_file.exists():
|
||||
raise FileNotFoundError(f"FAISS index file not found at {index_file}")
|
||||
if not records_file.exists():
|
||||
raise FileNotFoundError(f"FAISS records metadata file not found at {records_file}")
|
||||
|
||||
self._faiss_index = faiss.read_index(str(index_file))
|
||||
self._dimension = self._faiss_index.d
|
||||
|
||||
with open(records_file, encoding="utf-8") as f:
|
||||
metadata = json.load(f)
|
||||
|
||||
self._records = [ICDCodeRecord.model_validate(r) for r in metadata["records"]]
|
||||
logger.info(
|
||||
"Loaded FAISS index from %s (%d vectors, dim %d)",
|
||||
index_file,
|
||||
self._faiss_index.ntotal,
|
||||
self._dimension,
|
||||
)
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Schema module exports."""
|
||||
|
||||
from medical_coding.schemas.clinical import (
|
||||
ClassifiedDiagnosis,
|
||||
ClinicalDocument,
|
||||
ClinicalExtractionResult,
|
||||
ConditionClassification,
|
||||
ContextAssessment,
|
||||
ContextualizedDiagnosis,
|
||||
EncounterClassificationResult,
|
||||
EvidenceLocation,
|
||||
EvidenceSnippet,
|
||||
ExtractedClinicalCondition,
|
||||
ExtractedDiagnosis,
|
||||
TextSpan,
|
||||
)
|
||||
from medical_coding.schemas.enums import (
|
||||
AbstentionReason,
|
||||
Acuity,
|
||||
Certainty,
|
||||
ClinicalEntityType,
|
||||
ConditionStatus,
|
||||
DiagnosisRole,
|
||||
ExecutionStatus,
|
||||
Laterality,
|
||||
NegationStatus,
|
||||
PipelineStage,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.schemas.icd import (
|
||||
ICDCandidate,
|
||||
ICDCodeRecord,
|
||||
RankedSelection,
|
||||
)
|
||||
from medical_coding.schemas.response import (
|
||||
BatchJobStatus,
|
||||
CodedDiagnosisResponse,
|
||||
CodingResult,
|
||||
TextCodingRequest,
|
||||
)
|
||||
from medical_coding.schemas.state import (
|
||||
PipelineExecutionSnapshot,
|
||||
PipelineGraphState,
|
||||
)
|
||||
from medical_coding.schemas.validation import (
|
||||
AbstentionRecord,
|
||||
ValidatedDiagnosis,
|
||||
ValidationCheck,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AbstentionReason",
|
||||
"AbstentionRecord",
|
||||
"Acuity",
|
||||
"BatchJobStatus",
|
||||
"Certainty",
|
||||
"ClassifiedDiagnosis",
|
||||
"ClinicalDocument",
|
||||
"ClinicalEntityType",
|
||||
"ClinicalExtractionResult",
|
||||
"CodedDiagnosisResponse",
|
||||
"CodingResult",
|
||||
"ConditionClassification",
|
||||
"ConditionStatus",
|
||||
"ContextAssessment",
|
||||
"ContextualizedDiagnosis",
|
||||
"DiagnosisRole",
|
||||
"EncounterClassificationResult",
|
||||
"EvidenceLocation",
|
||||
"EvidenceSnippet",
|
||||
"ExecutionStatus",
|
||||
"ExtractedClinicalCondition",
|
||||
"ExtractedDiagnosis",
|
||||
"ICDCandidate",
|
||||
"ICDCodeRecord",
|
||||
"Laterality",
|
||||
"NegationStatus",
|
||||
"PipelineExecutionSnapshot",
|
||||
"PipelineGraphState",
|
||||
"PipelineStage",
|
||||
"RankedSelection",
|
||||
"Temporality",
|
||||
"TextCodingRequest",
|
||||
"TextSpan",
|
||||
"ValidatedDiagnosis",
|
||||
"ValidationCheck",
|
||||
]
|
||||
@@ -0,0 +1,371 @@
|
||||
"""Schemas for clinical text spans, evidence grounding, extracted entities, and context."""
|
||||
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from medical_coding.schemas.enums import (
|
||||
AbstentionReason,
|
||||
Acuity,
|
||||
Certainty,
|
||||
ClinicalEntityType,
|
||||
ConditionStatus,
|
||||
DiagnosisRole,
|
||||
Laterality,
|
||||
NegationStatus,
|
||||
Temporality,
|
||||
)
|
||||
|
||||
|
||||
class TextSpan(BaseModel):
|
||||
"""Character offsets and optional page metadata within the source text."""
|
||||
|
||||
start_char: int = Field(ge=0, description="Start character offset in document.")
|
||||
end_char: int = Field(ge=0, description="End character offset in document.")
|
||||
text: str = Field(min_length=1, description="Exact substring matched.")
|
||||
page_number: int | None = Field(
|
||||
default=None,
|
||||
ge=1,
|
||||
description="1-based page index for multi-page documents/PDFs.",
|
||||
)
|
||||
|
||||
|
||||
class EvidenceSnippet(BaseModel):
|
||||
"""Verbatim clinical evidence supporting a diagnostic claim."""
|
||||
|
||||
quote: str = Field(
|
||||
min_length=1,
|
||||
description="Verbatim excerpt from the clinical documentation providing ground truth.",
|
||||
)
|
||||
span: TextSpan | None = Field(
|
||||
default=None,
|
||||
description="Exact location within document text if resolvable.",
|
||||
)
|
||||
source_section: str | None = Field(
|
||||
default=None,
|
||||
description="Clinical section header (e.g. 'Discharge Diagnosis', 'History of Present Illness').",
|
||||
)
|
||||
|
||||
|
||||
class ClinicalDocument(BaseModel):
|
||||
"""Input clinical documentation container."""
|
||||
|
||||
document_id: str = Field(
|
||||
default_factory=lambda: str(uuid4()),
|
||||
description="Unique identifier for the patient encounter or document.",
|
||||
)
|
||||
text: str = Field(min_length=1, description="Raw discharge summary or clinical note text.")
|
||||
source_type: str = Field(
|
||||
default="text",
|
||||
description="Origin format: 'text', 'pdf', 'ehr_export'.",
|
||||
)
|
||||
metadata: dict[str, Any] = Field(
|
||||
default_factory=dict,
|
||||
description="Optional encounter metadata (e.g., patient age, admission date).",
|
||||
)
|
||||
|
||||
|
||||
class EvidenceLocation(BaseModel):
|
||||
"""Detailed structural evidence locator."""
|
||||
|
||||
section: str = Field(
|
||||
description="Clinical section where mention occurred (e.g. 'DISCHARGE_DIAGNOSES').",
|
||||
)
|
||||
page_number: int = Field(
|
||||
default=1,
|
||||
ge=1,
|
||||
description="1-based page index where the evidence text is located.",
|
||||
)
|
||||
start_char: int | None = Field(
|
||||
default=None,
|
||||
ge=0,
|
||||
description="Start character offset of the evidence quote in document text.",
|
||||
)
|
||||
end_char: int | None = Field(
|
||||
default=None,
|
||||
ge=0,
|
||||
description="End character offset of the evidence quote in document text.",
|
||||
)
|
||||
|
||||
|
||||
class ExtractedClinicalCondition(BaseModel):
|
||||
"""Strict structured representation of an extracted clinical condition.
|
||||
|
||||
CRITICAL RULES:
|
||||
1. MUST NOT contain ICD codes.
|
||||
2. MUST have verbatim evidence_text directly from document text.
|
||||
3. Cannot convert uncertain conditions into confirmed diagnoses.
|
||||
4. Cannot infer unwritten clinical facts.
|
||||
"""
|
||||
|
||||
condition_id: str = Field(
|
||||
default_factory=lambda: str(uuid4()),
|
||||
description="Unique condition entity identifier.",
|
||||
)
|
||||
original_mention: str = Field(
|
||||
min_length=1,
|
||||
description="Verbatim diagnostic or clinical term extracted from text.",
|
||||
)
|
||||
normalized_description: str = Field(
|
||||
min_length=1,
|
||||
description="Canonical normalized clinical condition description.",
|
||||
)
|
||||
entity_type: ClinicalEntityType = Field(
|
||||
default=ClinicalEntityType.DIAGNOSIS,
|
||||
description="DIAGNOSIS, SYMPTOM, SIGN, or PROCEDURAL_FINDING.",
|
||||
)
|
||||
evidence_text: str = Field(
|
||||
min_length=1,
|
||||
description="Verbatim sentence or phrase from the document providing factual proof.",
|
||||
)
|
||||
evidence_location: EvidenceLocation = Field(
|
||||
description="Section and page/offset location of evidence.",
|
||||
)
|
||||
status: ConditionStatus = Field(
|
||||
default=ConditionStatus.ACTIVE,
|
||||
description="ACTIVE, HISTORICAL, RESOLVED, CHRONIC, ACUTE, or UNKNOWN.",
|
||||
)
|
||||
certainty: Certainty = Field(
|
||||
default=Certainty.CONFIRMED,
|
||||
description="CONFIRMED, SUSPECTED, POSSIBLE, RULED_OUT, or UNKNOWN.",
|
||||
)
|
||||
temporality: Temporality = Field(
|
||||
default=Temporality.CURRENT,
|
||||
description="CURRENT, HISTORICAL, RESOLVED, FAMILY_HISTORY, or UNKNOWN.",
|
||||
)
|
||||
negation: NegationStatus = Field(
|
||||
default=NegationStatus.AFFIRMATIVE,
|
||||
description="AFFIRMATIVE, NEGATED, or UNCERTAIN.",
|
||||
)
|
||||
anatomical_site: str | None = Field(
|
||||
default=None,
|
||||
description="Specific anatomical location if explicitly documented.",
|
||||
)
|
||||
laterality: Laterality = Field(
|
||||
default=Laterality.UNSPECIFIED,
|
||||
description="LEFT, RIGHT, BILATERAL, or UNSPECIFIED.",
|
||||
)
|
||||
section: str = Field(
|
||||
description="Section where mention appeared.",
|
||||
)
|
||||
treatment_evidence: str | None = Field(
|
||||
default=None,
|
||||
description="Documented treatment or management evidence if explicitly stated.",
|
||||
)
|
||||
confidence_score: float = Field(
|
||||
default=1.0,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Extraction confidence score.",
|
||||
)
|
||||
|
||||
|
||||
class ClinicalExtractionResult(BaseModel):
|
||||
"""Aggregate output of the clinical information extraction agent."""
|
||||
|
||||
document_id: str = Field(description="Encounter or document ID.")
|
||||
conditions: list[ExtractedClinicalCondition] = Field(
|
||||
default_factory=list,
|
||||
description="Collection of evidence-grounded candidate conditions.",
|
||||
)
|
||||
extraction_notes: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="Audit notes regarding extraction and parsing.",
|
||||
)
|
||||
repair_applied: bool = Field(
|
||||
default=False,
|
||||
description="True if JSON or schema repair heuristics were applied.",
|
||||
)
|
||||
raw_response: str | None = Field(
|
||||
default=None,
|
||||
description="Raw output from the local LLM before parsing.",
|
||||
)
|
||||
|
||||
|
||||
class ContextAssessment(BaseModel):
|
||||
"""Evaluation of clinical relevance, current management, and coding eligibility.
|
||||
|
||||
CRITICAL RULES:
|
||||
1. Past Medical History (PMH) alone does NOT qualify a condition for coding.
|
||||
Must have documented clinical evaluation, monitoring, or treatment during the stay.
|
||||
2. Ruled-out conditions cannot be confirmed or coded as active diagnoses.
|
||||
3. Uncertain conditions must retain SUSPECTED/POSSIBLE certainty; never convert to CONFIRMED.
|
||||
"""
|
||||
|
||||
diagnosis: str = Field(
|
||||
description="Normalized diagnostic condition term.",
|
||||
)
|
||||
condition_id: str | None = Field(
|
||||
default=None,
|
||||
description="Identifier linking to ExtractedClinicalCondition.",
|
||||
)
|
||||
current_relevance: bool = Field(
|
||||
description="True if clinically active and relevant to current hospitalization.",
|
||||
)
|
||||
coding_candidate: bool = Field(
|
||||
description="True if eligible to be coded under inpatient coding guidelines.",
|
||||
)
|
||||
status: ConditionStatus = Field(
|
||||
description="ACTIVE, HISTORICAL, RESOLVED, CHRONIC, ACUTE, UNKNOWN.",
|
||||
)
|
||||
certainty: Certainty = Field(
|
||||
description="CONFIRMED, SUSPECTED, POSSIBLE, RULED_OUT, UNKNOWN.",
|
||||
)
|
||||
temporality: Temporality = Field(
|
||||
default=Temporality.CURRENT,
|
||||
description="CURRENT, HISTORICAL, RESOLVED, UNKNOWN.",
|
||||
)
|
||||
negation: NegationStatus = Field(
|
||||
default=NegationStatus.AFFIRMATIVE,
|
||||
description="AFFIRMATIVE, NEGATED, UNCERTAIN.",
|
||||
)
|
||||
evidence: str = Field(
|
||||
description="Verbatim documented evidence quote from the clinical record.",
|
||||
)
|
||||
reason: str = Field(
|
||||
description="Explicit clinical rationale justifying the relevance and coding decision.",
|
||||
)
|
||||
|
||||
# Clinical management indicators
|
||||
treated_or_managed: bool = Field(
|
||||
default=False,
|
||||
description="True if therapeutic intervention was administered.",
|
||||
)
|
||||
monitored: bool = Field(
|
||||
default=False,
|
||||
description="True if diagnostic workup, vitals, or labs monitored this condition.",
|
||||
)
|
||||
affected_clinical_management: bool = Field(
|
||||
default=False,
|
||||
description="True if condition altered hospital course or increased nursing care.",
|
||||
)
|
||||
influenced_treatment: bool = Field(
|
||||
default=False,
|
||||
description="True if condition influenced choice of therapies or medications.",
|
||||
)
|
||||
treatment_evidence: str | None = Field(
|
||||
default=None,
|
||||
description="Documented text describing treatment or monitoring if present.",
|
||||
)
|
||||
|
||||
# Audit & Abstention
|
||||
abstain_recommended: bool = Field(
|
||||
default=False,
|
||||
description="True if ambiguous documentation prevents reliable classification.",
|
||||
)
|
||||
abstention_reason: AbstentionReason | None = Field(
|
||||
default=None,
|
||||
description="Explicit reason for abstention if recommended.",
|
||||
)
|
||||
|
||||
|
||||
# Pipeline legacy models (preserved for LangGraph compatibility)
|
||||
class ExtractedDiagnosis(BaseModel):
|
||||
"""Legacy diagnosis entity linking verbatim evidence."""
|
||||
|
||||
diagnosis_id: str = Field(default_factory=lambda: str(uuid4()))
|
||||
raw_term: str = Field(min_length=1)
|
||||
evidence: EvidenceSnippet
|
||||
extraction_confidence: float = Field(ge=0.0, le=1.0)
|
||||
|
||||
|
||||
class ContextualizedDiagnosis(BaseModel):
|
||||
"""Legacy contextualized condition."""
|
||||
|
||||
diagnosis_id: str
|
||||
raw_term: str
|
||||
evidence: EvidenceSnippet
|
||||
extraction_confidence: float = Field(ge=0.0, le=1.0)
|
||||
negation: NegationStatus = Field(default=NegationStatus.AFFIRMATIVE)
|
||||
temporality: Temporality = Field(default=Temporality.CURRENT)
|
||||
certainty: Certainty = Field(default=Certainty.CONFIRMED)
|
||||
acuity: Acuity = Field(default=Acuity.UNSPECIFIED)
|
||||
clinical_justification: str = Field(min_length=1)
|
||||
context_evidence: EvidenceSnippet | None = None
|
||||
|
||||
|
||||
class ClassifiedDiagnosis(BaseModel):
|
||||
"""Legacy classified condition."""
|
||||
|
||||
diagnosis_id: str
|
||||
raw_term: str
|
||||
context: ContextualizedDiagnosis
|
||||
role: DiagnosisRole
|
||||
is_billable_candidate: bool
|
||||
classification_reason: str = Field(min_length=1)
|
||||
primary_justification: str | None = None
|
||||
|
||||
|
||||
class ConditionClassification(BaseModel):
|
||||
"""Structured classification of an individual condition into a billing role.
|
||||
|
||||
CRITICAL RULES:
|
||||
1. Maximum ONE Primary Diagnosis per encounter.
|
||||
2. Zero or more Secondary Diagnoses.
|
||||
3. Excluded conditions (historical without care, ruled out, negated) are not billable.
|
||||
"""
|
||||
|
||||
diagnosis_id: str = Field(
|
||||
description="Unique entity identifier linking to extracted/assessed condition."
|
||||
)
|
||||
diagnosis: str = Field(description="Normalized diagnostic description.")
|
||||
role: DiagnosisRole = Field(description="PRIMARY, SECONDARY, or EXCLUDED.")
|
||||
is_billable_candidate: bool = Field(description="True if condition qualifies for ICD coding.")
|
||||
classification_reason: str = Field(
|
||||
description="Clinical reasoning justifying the assigned role."
|
||||
)
|
||||
primary_justification: str | None = Field(
|
||||
default=None,
|
||||
description="Explicit documentation justification if selected as Primary diagnosis.",
|
||||
)
|
||||
admitting_condition_score: float = Field(
|
||||
default=0.0,
|
||||
description="Calculated admitting significance score based on section, intervention, and acuity.",
|
||||
)
|
||||
evidence_quote: str = Field(
|
||||
default="",
|
||||
description="Documented evidence backing this condition.",
|
||||
)
|
||||
|
||||
|
||||
class EncounterClassificationResult(BaseModel):
|
||||
"""Aggregate result of the Primary / Secondary classification component for an encounter."""
|
||||
|
||||
document_id: str | None = Field(default=None, description="Encounter or document identifier.")
|
||||
primary_diagnosis: ConditionClassification | None = Field(
|
||||
default=None,
|
||||
description="The unique condition chiefly responsible for occasioning admission (max 1).",
|
||||
)
|
||||
secondary_diagnoses: list[ConditionClassification] = Field(
|
||||
default_factory=list,
|
||||
description="Co-existing conditions actively managed, monitored, or treated during admission.",
|
||||
)
|
||||
excluded_conditions: list[ConditionClassification] = Field(
|
||||
default_factory=list,
|
||||
description="Historical, negated, ruled-out, or unmanaged conditions not eligible for coding.",
|
||||
)
|
||||
all_classifications: list[ConditionClassification] = Field(
|
||||
default_factory=list,
|
||||
description="Complete list of all classified conditions.",
|
||||
)
|
||||
has_unique_primary: bool = Field(
|
||||
default=False,
|
||||
description="True if exactly one primary diagnosis was established with confidence.",
|
||||
)
|
||||
is_ambiguous_primary: bool = Field(
|
||||
default=False,
|
||||
description="True if two or more conditions equally qualify as primary without documented distinction.",
|
||||
)
|
||||
abstention_recommended: bool = Field(
|
||||
default=False,
|
||||
description="True if classification could not defensibly establish roles without physician query.",
|
||||
)
|
||||
abstention_reason: AbstentionReason | None = Field(
|
||||
default=None,
|
||||
description="Reason for abstention if recommended.",
|
||||
)
|
||||
audit_notes: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="Audit trail of classification decisions and validation checks.",
|
||||
)
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Enumerations for clinical context, ICD roles, pipeline stages, and validation states."""
|
||||
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class NegationStatus(StrEnum):
|
||||
"""Negation assessment of clinical assertion."""
|
||||
|
||||
AFFIRMATIVE = "AFFIRMATIVE" # Condition is explicitly asserted as present
|
||||
NEGATED = "NEGATED" # Condition is explicitly asserted as absent ("no history of", "denies")
|
||||
UNCERTAIN = "UNCERTAIN" # Ambiguous assertion or pending evaluation
|
||||
|
||||
|
||||
class Temporality(StrEnum):
|
||||
"""Clinical timing and historical status of a condition."""
|
||||
|
||||
CURRENT = "CURRENT" # Active problem addressed or treated during current encounter
|
||||
HISTORICAL = "HISTORICAL" # Past medical history, not actively evaluated or managed
|
||||
RESOLVED = "RESOLVED" # Previously active condition now clinically resolved
|
||||
FAMILY_HISTORY = "FAMILY_HISTORY" # Family medical background (not personal condition)
|
||||
UNKNOWN = "UNKNOWN" # Temporality not determinable from text
|
||||
|
||||
|
||||
class Certainty(StrEnum):
|
||||
"""Diagnostic certainty according to clinical documentation."""
|
||||
|
||||
CONFIRMED = "CONFIRMED" # Definite clinical diagnosis
|
||||
SUSPECTED = "SUSPECTED" # Probable, working, or differential diagnosis under active evaluation
|
||||
POSSIBLE = "POSSIBLE" # Equivocal, possible, or potential condition
|
||||
RULED_OUT = "RULED_OUT" # Evaluated and definitively excluded / refuted
|
||||
UNKNOWN = "UNKNOWN" # Diagnostic certainty cannot be established
|
||||
|
||||
|
||||
class ConditionStatus(StrEnum):
|
||||
"""Clinical status profile of the condition."""
|
||||
|
||||
ACTIVE = "ACTIVE" # Currently active and being treated or monitored
|
||||
HISTORICAL = "HISTORICAL" # Past medical condition
|
||||
RESOLVED = "RESOLVED" # Prior condition resolved or cured
|
||||
CHRONIC = "CHRONIC" # Longstanding background condition
|
||||
ACUTE = "ACUTE" # Acute onset condition
|
||||
UNKNOWN = "UNKNOWN" # Status unknown or not documented
|
||||
|
||||
|
||||
class Acuity(StrEnum):
|
||||
"""Clinical acuity / chronicity profile."""
|
||||
|
||||
ACUTE = "ACUTE"
|
||||
CHRONIC = "CHRONIC"
|
||||
ACUTE_ON_CHRONIC = "ACUTE_ON_CHRONIC"
|
||||
UNSPECIFIED = "UNSPECIFIED"
|
||||
|
||||
|
||||
class Laterality(StrEnum):
|
||||
"""Anatomical laterality designation."""
|
||||
|
||||
LEFT = "LEFT"
|
||||
RIGHT = "RIGHT"
|
||||
BILATERAL = "BILATERAL"
|
||||
UNSPECIFIED = "UNSPECIFIED"
|
||||
|
||||
|
||||
class ClinicalEntityType(StrEnum):
|
||||
"""Categorization of extracted clinical entities."""
|
||||
|
||||
DIAGNOSIS = "DIAGNOSIS"
|
||||
SYMPTOM = "SYMPTOM"
|
||||
SIGN = "SIGN"
|
||||
PROCEDURAL_FINDING = "PROCEDURAL_FINDING"
|
||||
UNKNOWN = "UNKNOWN"
|
||||
|
||||
|
||||
class DiagnosisRole(StrEnum):
|
||||
"""ICD-10-CM coding role designation."""
|
||||
|
||||
PRIMARY = "PRIMARY" # Chief condition established after study to be responsible for admission
|
||||
SECONDARY = "SECONDARY" # Co-existing condition actively managed or impacting stay
|
||||
EXCLUDED = (
|
||||
"EXCLUDED" # Historical, negated, or unsubstantiated condition (omitted from billing)
|
||||
)
|
||||
|
||||
|
||||
class PipelineStage(StrEnum):
|
||||
"""Execution stages across the pipeline graph."""
|
||||
|
||||
INGESTION = "INGESTION"
|
||||
EXTRACTION = "EXTRACTION"
|
||||
CONTEXT_ANALYSIS = "CONTEXT_ANALYSIS"
|
||||
CLASSIFICATION = "CLASSIFICATION"
|
||||
RETRIEVAL = "RETRIEVAL"
|
||||
RANKING = "RANKING"
|
||||
VALIDATION = "VALIDATION"
|
||||
FINALIZATION = "FINALIZATION"
|
||||
ABSTAINED = "ABSTAINED"
|
||||
FAILED = "FAILED"
|
||||
|
||||
|
||||
class AbstentionReason(StrEnum):
|
||||
"""Explicit, auditable justifications when the pipeline abstains from coding."""
|
||||
|
||||
INSUFFICIENT_CLINICAL_EVIDENCE = "INSUFFICIENT_CLINICAL_EVIDENCE"
|
||||
NO_MATCHING_ICD_CANDIDATE = "NO_MATCHING_ICD_CANDIDATE"
|
||||
BELOW_CONFIDENCE_THRESHOLD = "BELOW_CONFIDENCE_THRESHOLD"
|
||||
MULTIPLE_AMBIGUOUS_PRIMARY = "MULTIPLE_AMBIGUOUS_PRIMARY"
|
||||
EXCLUDED_BY_NEGATION = "EXCLUDED_BY_NEGATION"
|
||||
EXCLUDED_BY_TEMPORALITY = "EXCLUDED_BY_TEMPORALITY"
|
||||
CONTRADICTORY_DOCUMENTATION = "CONTRADICTORY_DOCUMENTATION"
|
||||
INVALID_ICD_CODE = "INVALID_ICD_CODE"
|
||||
SPECIFICITY_REQUIRED = "SPECIFICITY_REQUIRED"
|
||||
EXCLUDES_1_VIOLATION = "EXCLUDES_1_VIOLATION"
|
||||
PROCESSING_ERROR = "PROCESSING_ERROR"
|
||||
|
||||
|
||||
class ExecutionStatus(StrEnum):
|
||||
"""High-level outcome status of document coding."""
|
||||
|
||||
SUCCESS = "SUCCESS"
|
||||
PARTIAL_SUCCESS = "PARTIAL_SUCCESS"
|
||||
ABSTAINED = "ABSTAINED"
|
||||
ERROR = "ERROR"
|
||||
@@ -0,0 +1,289 @@
|
||||
"""Schemas representing ICD-10-CM catalog codes, retrieved candidates, and ranking results."""
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from medical_coding.utils.text import format_icd_code, unformat_icd_code
|
||||
|
||||
|
||||
class ICDCodeRecord(BaseModel):
|
||||
"""Authoritative representation of a single code in the local ICD-10-CM dataset."""
|
||||
|
||||
code: str = Field(
|
||||
min_length=3,
|
||||
max_length=8,
|
||||
description="Formatted ICD-10-CM code (e.g. 'I50.21', 'E11.9').",
|
||||
)
|
||||
description: str = Field(
|
||||
default="",
|
||||
description="Authoritative clinical description for this ICD-10-CM code.",
|
||||
)
|
||||
unformatted_code: str = Field(
|
||||
default="",
|
||||
description="Alphanumeric code without decimal (e.g. 'I5021').",
|
||||
)
|
||||
short_description: str = Field(
|
||||
default="",
|
||||
description="Standard short clinical description (CMS order file column).",
|
||||
)
|
||||
long_description: str = Field(
|
||||
default="",
|
||||
description="Full clinical description from CMS tabular dataset.",
|
||||
)
|
||||
is_valid_billable: bool = Field(
|
||||
default=True,
|
||||
description="True if terminal code at highest specificity (billable); False if category header.",
|
||||
)
|
||||
chapter: str | None = Field(
|
||||
default=None,
|
||||
description="ICD chapter (e.g., 'IX. Diseases of the circulatory system').",
|
||||
)
|
||||
category: str | None = Field(
|
||||
default=None,
|
||||
description="3-character category prefix (e.g. 'I50').",
|
||||
)
|
||||
inclusion_terms: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="Official inclusion terms representing conditions classified under this code.",
|
||||
)
|
||||
exclusion_terms: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="Exclusion terms (Excludes1 and Excludes2) representing non-codable conditions.",
|
||||
)
|
||||
synonyms: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="Clinical synonyms, alternative phrasings, and common abbreviations for this code.",
|
||||
)
|
||||
source_metadata: dict[str, Any] = Field(
|
||||
default_factory=dict,
|
||||
description="Provenance and metadata for this record (e.g. release year, source file, version).",
|
||||
)
|
||||
excludes1: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="Codes that cannot be billed together under Excludes1 rules.",
|
||||
)
|
||||
excludes2: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="Codes representing not included conditions (Excludes2).",
|
||||
)
|
||||
code_first: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="Underlying etiology codes required to precede this code.",
|
||||
)
|
||||
use_additional: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="Secondary condition codes recommended to be coded alongside.",
|
||||
)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def populate_defaults_and_normalize(cls, data: Any) -> Any:
|
||||
"""Normalize code format and sync description aliases before validation."""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
|
||||
raw_code = str(data.get("code", "")).strip()
|
||||
formatted = format_icd_code(raw_code)
|
||||
unformatted = data.get("unformatted_code") or unformat_icd_code(raw_code)
|
||||
data["code"] = formatted
|
||||
data["unformatted_code"] = unformatted
|
||||
|
||||
desc = data.get("description", "")
|
||||
short_desc = data.get("short_description", "")
|
||||
long_desc = data.get("long_description", "")
|
||||
|
||||
if not desc:
|
||||
desc = long_desc or short_desc
|
||||
if not short_desc:
|
||||
short_desc = desc
|
||||
if not long_desc:
|
||||
long_desc = desc
|
||||
|
||||
data["description"] = desc
|
||||
data["short_description"] = short_desc
|
||||
data["long_description"] = long_desc
|
||||
|
||||
if not data.get("category") and formatted:
|
||||
clean = unformatted
|
||||
data["category"] = clean[:3] if len(clean) >= 3 else clean
|
||||
|
||||
# Combine exclusion terms with excludes1/excludes2 if provided
|
||||
exclusions = list(data.get("exclusion_terms", []))
|
||||
if not exclusions:
|
||||
ex1 = data.get("excludes1", [])
|
||||
ex2 = data.get("excludes2", [])
|
||||
exclusions = list(ex1) + list(ex2)
|
||||
data["exclusion_terms"] = exclusions
|
||||
|
||||
return data
|
||||
|
||||
def get_searchable_text(self) -> str:
|
||||
"""Combine all text representations for comprehensive lexical and semantic retrieval."""
|
||||
parts: list[str] = []
|
||||
if self.description:
|
||||
parts.append(self.description)
|
||||
if self.long_description and self.long_description != self.description:
|
||||
parts.append(self.long_description)
|
||||
if self.short_description and self.short_description not in (
|
||||
self.description,
|
||||
self.long_description,
|
||||
):
|
||||
parts.append(self.short_description)
|
||||
if self.inclusion_terms:
|
||||
parts.extend(self.inclusion_terms)
|
||||
if self.synonyms:
|
||||
parts.extend(self.synonyms)
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
class ICDDatasetStats(BaseModel):
|
||||
"""Statistical summary of loaded ICD-10-CM dataset."""
|
||||
|
||||
total_records: int = Field(description="Total valid records indexed.")
|
||||
valid_billable_count: int = Field(description="Count of billable terminal codes.")
|
||||
non_billable_count: int = Field(description="Count of category headers / non-billable codes.")
|
||||
unique_categories_count: int = Field(description="Count of unique 3-character categories.")
|
||||
duplicates_dropped: int = Field(default=0, description="Duplicate code occurrences filtered.")
|
||||
malformed_dropped: int = Field(default=0, description="Malformed or invalid rows filtered.")
|
||||
total_inclusion_terms: int = Field(default=0, description="Total inclusion terms indexed.")
|
||||
total_exclusion_terms: int = Field(default=0, description="Total exclusion terms indexed.")
|
||||
total_synonyms: int = Field(default=0, description="Total synonyms indexed.")
|
||||
format_type: str = Field(default="tabular", description="Source format loaded.")
|
||||
|
||||
|
||||
class ICDCandidate(BaseModel):
|
||||
"""An authoritative candidate code retrieved from the local dataset for an extracted diagnosis."""
|
||||
|
||||
code: str = Field(description="Authoritative ICD-10-CM code from local catalog.")
|
||||
description: str = Field(description="Official ICD description matching the code.")
|
||||
retrieval_score: float = Field(
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Normalized similarity/relevance score from retrieval engine.",
|
||||
)
|
||||
retrieval_method: Literal["bm25", "faiss", "hybrid"] = Field(
|
||||
description="Algorithm that produced or consolidated this candidate.",
|
||||
)
|
||||
is_valid_billable: bool = Field(
|
||||
description="Indicates whether this candidate is terminal/billable in the catalog.",
|
||||
)
|
||||
semantic_score: float | None = Field(
|
||||
default=None,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Semantic similarity component score from FAISS vector search.",
|
||||
)
|
||||
lexical_score: float | None = Field(
|
||||
default=None,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Lexical BM25 component score normalized to [0, 1].",
|
||||
)
|
||||
category: str | None = Field(
|
||||
default=None,
|
||||
description="ICD category (3-character prefix).",
|
||||
)
|
||||
|
||||
|
||||
class RankedSelection(BaseModel):
|
||||
"""Result of evaluating and ranking retrieved candidates against clinical evidence."""
|
||||
|
||||
diagnosis_id: str = Field(default="", description="Associated diagnosis entity ID.")
|
||||
raw_term: str = Field(default="", description="Original clinical term.")
|
||||
selected_code: str | None = Field(
|
||||
default=None,
|
||||
description="The chosen ICD-10-CM code strictly from the candidate list; None if abstained.",
|
||||
)
|
||||
selected_description: str | None = Field(
|
||||
default=None,
|
||||
description="Official description of the selected ICD code.",
|
||||
)
|
||||
ranking_reason: str = Field(
|
||||
default="",
|
||||
description="Detailed clinical justification linking evidence to the selected code or explaining abstention.",
|
||||
)
|
||||
supporting_evidence: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="Verbatim evidence quotes or snippets supporting the selection.",
|
||||
)
|
||||
confidence: float = Field(
|
||||
default=0.0,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Confidence score of the ranking selection.",
|
||||
)
|
||||
abstention_reason: str | None = Field(
|
||||
default=None,
|
||||
description="Reason for abstention or rejection if no candidate was accepted.",
|
||||
)
|
||||
selected_candidate: ICDCandidate | None = Field(
|
||||
default=None,
|
||||
description="Top-ranked candidate chosen strictly from retrieved list; None if abstained.",
|
||||
)
|
||||
ranking_score: float = Field(
|
||||
default=0.0,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Confidence score of the ranking selection (alias for confidence).",
|
||||
)
|
||||
selection_justification: str = Field(
|
||||
default="",
|
||||
description="Evidence-based justification linking clinical wording to chosen ICD description.",
|
||||
)
|
||||
candidate_pool: list[ICDCandidate] = Field(
|
||||
default_factory=list,
|
||||
description="All candidates considered during ranking (audit trail).",
|
||||
)
|
||||
decision: Literal["ACCEPTED", "REJECTED_LOW_CONFIDENCE", "REJECTED_MISMATCH", "ABSTAINED"] = (
|
||||
Field(
|
||||
default="ABSTAINED",
|
||||
description="Outcome of candidate evaluation.",
|
||||
)
|
||||
)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def sync_aliases_and_candidates(cls, data: Any) -> Any:
|
||||
"""Synchronize aliases between modern and legacy ranking fields."""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
|
||||
# Sync justification / reason
|
||||
reason = data.get("ranking_reason") or data.get("selection_justification", "")
|
||||
data["ranking_reason"] = reason
|
||||
data["selection_justification"] = reason
|
||||
|
||||
# Sync score / confidence
|
||||
conf = data.get("confidence")
|
||||
score = data.get("ranking_score")
|
||||
if conf is not None:
|
||||
data["confidence"] = float(conf)
|
||||
data["ranking_score"] = float(conf)
|
||||
elif score is not None:
|
||||
data["confidence"] = float(score)
|
||||
data["ranking_score"] = float(score)
|
||||
|
||||
# Sync candidate and code/description
|
||||
candidate = data.get("selected_candidate")
|
||||
if candidate and hasattr(candidate, "code"):
|
||||
data.setdefault("selected_code", candidate.code)
|
||||
data.setdefault("selected_description", candidate.description)
|
||||
elif isinstance(candidate, dict):
|
||||
data.setdefault("selected_code", candidate.get("code"))
|
||||
data.setdefault("selected_description", candidate.get("description"))
|
||||
|
||||
# If selected_code is given but not candidate, lookup in pool
|
||||
if data.get("selected_code") and not data.get("selected_candidate"):
|
||||
pool = data.get("candidate_pool", [])
|
||||
for c in pool:
|
||||
c_code = c.code if hasattr(c, "code") else c.get("code")
|
||||
if c_code == data["selected_code"]:
|
||||
data["selected_candidate"] = c
|
||||
data.setdefault(
|
||||
"selected_description",
|
||||
c.description if hasattr(c, "description") else c.get("description"),
|
||||
)
|
||||
break
|
||||
|
||||
return data
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Final deterministic JSON output models and API request/response schemas."""
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from medical_coding.schemas.enums import (
|
||||
Acuity,
|
||||
Certainty,
|
||||
DiagnosisRole,
|
||||
ExecutionStatus,
|
||||
)
|
||||
from medical_coding.schemas.validation import AbstentionRecord
|
||||
|
||||
|
||||
class CodedDiagnosisResponse(BaseModel):
|
||||
"""External deterministic representation of an evidence-backed ICD code decision."""
|
||||
|
||||
code: str = Field(description="Authoritative ICD-10-CM code verified against catalog.")
|
||||
description: str = Field(description="Official ICD-10-CM description.")
|
||||
role: DiagnosisRole = Field(description="PRIMARY or SECONDARY.")
|
||||
acuity: Acuity = Field(description="Acuity status (e.g. ACUTE, CHRONIC).")
|
||||
certainty: Certainty = Field(description="Certainty status (e.g. CONFIRMED, SUSPECTED).")
|
||||
evidence_quote: str = Field(
|
||||
description="Exact quote from clinical record providing documentary evidence.",
|
||||
)
|
||||
confidence_score: float = Field(
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Aggregate confidence score for the coding decision.",
|
||||
)
|
||||
is_terminal_billable: bool = Field(
|
||||
default=True,
|
||||
description="Confirms code is at terminal specificity required for submission.",
|
||||
)
|
||||
|
||||
|
||||
class CodingResult(BaseModel):
|
||||
"""Deterministic final output conforming to clinical coding architecture principles."""
|
||||
|
||||
document_id: str = Field(description="Encounter or document identifier.")
|
||||
status: ExecutionStatus = Field(description="Overall execution status.")
|
||||
primary_diagnosis: CodedDiagnosisResponse | None = Field(
|
||||
default=None,
|
||||
description="Maximum ONE primary diagnosis; None if abstained or undetermined.",
|
||||
)
|
||||
secondary_diagnoses: list[CodedDiagnosisResponse] = Field(
|
||||
default_factory=list,
|
||||
description="Zero or more clinically justified secondary diagnoses.",
|
||||
)
|
||||
abstentions: list[AbstentionRecord] = Field(
|
||||
default_factory=list,
|
||||
description="Audit records for all conditions where coding was abstained.",
|
||||
)
|
||||
processing_time_ms: float = Field(
|
||||
ge=0.0,
|
||||
description="Total end-to-end execution latency in milliseconds.",
|
||||
)
|
||||
models_used: dict[str, str] = Field(
|
||||
default_factory=dict,
|
||||
description="Audit map of local models utilized (LLM, embeddings).",
|
||||
)
|
||||
metadata: dict[str, Any] = Field(
|
||||
default_factory=dict,
|
||||
description="Additional encounter or audit metadata.",
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def verify_primary_constraint(self) -> "CodingResult":
|
||||
"""Enforce strict invariant: primary diagnosis must have PRIMARY role if present."""
|
||||
if self.primary_diagnosis and self.primary_diagnosis.role != DiagnosisRole.PRIMARY:
|
||||
raise ValueError("Primary diagnosis must have role PRIMARY")
|
||||
for sec in self.secondary_diagnoses:
|
||||
if sec.role == DiagnosisRole.PRIMARY:
|
||||
raise ValueError("Secondary diagnoses cannot have role PRIMARY")
|
||||
return self
|
||||
|
||||
|
||||
class TextCodingRequest(BaseModel):
|
||||
"""Input payload for clinical text coding endpoint."""
|
||||
|
||||
document_id: str | None = Field(
|
||||
default=None,
|
||||
description="Optional encounter identifier; generated if omitted.",
|
||||
)
|
||||
text: str = Field(
|
||||
min_length=10,
|
||||
description="Discharge summary or clinical encounter text to analyze.",
|
||||
)
|
||||
metadata: dict[str, Any] = Field(
|
||||
default_factory=dict,
|
||||
description="Optional encounter metadata.",
|
||||
)
|
||||
|
||||
|
||||
class BatchJobStatus(BaseModel):
|
||||
"""Status record for an asynchronous batch processing job."""
|
||||
|
||||
job_id: str = Field(description="Unique batch job identifier.")
|
||||
total_documents: int = Field(ge=0, description="Total count of documents in the batch.")
|
||||
completed_documents: int = Field(ge=0, description="Number of documents processed so far.")
|
||||
failed_documents: int = Field(ge=0, description="Number of documents that encountered errors.")
|
||||
status: Literal["pending", "processing", "completed", "failed"] = Field(
|
||||
default="pending",
|
||||
description="Lifecycle status of batch processing.",
|
||||
)
|
||||
results: list[CodingResult] = Field(
|
||||
default_factory=list,
|
||||
description="Collection of individual document coding results.",
|
||||
)
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Central application state definitions for LangGraph workflows and pipeline orchestration."""
|
||||
|
||||
from typing import Annotated, Any, TypedDict
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from medical_coding.schemas.clinical import (
|
||||
ClassifiedDiagnosis,
|
||||
ContextAssessment,
|
||||
ContextualizedDiagnosis,
|
||||
EncounterClassificationResult,
|
||||
ExtractedClinicalCondition,
|
||||
ExtractedDiagnosis,
|
||||
)
|
||||
from medical_coding.schemas.enums import PipelineStage
|
||||
from medical_coding.schemas.icd import ICDCandidate, RankedSelection
|
||||
from medical_coding.schemas.response import CodingResult
|
||||
from medical_coding.schemas.validation import AbstentionRecord, ValidatedDiagnosis
|
||||
|
||||
|
||||
def append_items(existing: list[Any], new_items: list[Any]) -> list[Any]:
|
||||
"""LangGraph state reducer to safely append elements to lists."""
|
||||
if not existing:
|
||||
return list(new_items)
|
||||
if not new_items:
|
||||
return list(existing)
|
||||
return list(existing) + list(new_items)
|
||||
|
||||
|
||||
def merge_dicts(existing: dict[str, Any], new_dict: dict[str, Any]) -> dict[str, Any]:
|
||||
"""LangGraph state reducer to shallow-merge dictionary updates."""
|
||||
merged = dict(existing) if existing else {}
|
||||
if new_dict:
|
||||
merged.update(new_dict)
|
||||
return merged
|
||||
|
||||
|
||||
class PipelineGraphState(TypedDict, total=False):
|
||||
"""Central state passed across all LangGraph nodes in the medical coding pipeline.
|
||||
|
||||
Each node inspects this state and returns a partial dictionary updating
|
||||
only the relevant fields for that stage.
|
||||
"""
|
||||
|
||||
# Input Document Attributes
|
||||
document_id: str
|
||||
raw_text: str
|
||||
pdf_path: str | None
|
||||
pdf_bytes: bytes | None
|
||||
file_path: str | None
|
||||
file_bytes: bytes | None
|
||||
detected_filetype: str | None
|
||||
source_type: str
|
||||
metadata: dict[str, Any]
|
||||
|
||||
# Clinical Extraction & Context Analysis
|
||||
extracted_diagnoses: list[ExtractedDiagnosis]
|
||||
extracted_conditions: list[ExtractedClinicalCondition]
|
||||
context_assessments: list[ContextAssessment]
|
||||
contextualized_diagnoses: list[ContextualizedDiagnosis]
|
||||
classified_diagnoses: list[ClassifiedDiagnosis]
|
||||
classification_result: EncounterClassificationResult
|
||||
|
||||
# Local Retrieval & Ranking
|
||||
candidate_pool: dict[str, list[ICDCandidate]] # Keyed by diagnosis_id
|
||||
ranked_selections: list[RankedSelection]
|
||||
|
||||
# Deterministic Validation & Audit
|
||||
validated_diagnoses: list[ValidatedDiagnosis]
|
||||
abstentions: Annotated[list[AbstentionRecord], append_items]
|
||||
audit_trail: Annotated[list[dict[str, Any]], append_items]
|
||||
|
||||
# Pipeline Control & Errors
|
||||
current_stage: PipelineStage
|
||||
errors: Annotated[list[str], append_items]
|
||||
is_aborted: bool
|
||||
|
||||
# Final Output
|
||||
final_result: CodingResult | None
|
||||
|
||||
|
||||
class PipelineExecutionSnapshot(BaseModel):
|
||||
"""Immutable Pydantic model capturing a serialized snapshot of pipeline state.
|
||||
|
||||
Useful for telemetry, auditing, inspection, and regression replay.
|
||||
"""
|
||||
|
||||
document_id: str
|
||||
current_stage: PipelineStage
|
||||
extracted_count: int = Field(ge=0, default=0)
|
||||
classified_count: int = Field(ge=0, default=0)
|
||||
validated_count: int = Field(ge=0, default=0)
|
||||
abstention_count: int = Field(ge=0, default=0)
|
||||
error_count: int = Field(ge=0, default=0)
|
||||
has_primary: bool = False
|
||||
is_terminal: bool = False
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Schemas for deterministic validation results, rule checks, and abstention auditing."""
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from medical_coding.schemas.clinical import EvidenceSnippet
|
||||
from medical_coding.schemas.enums import AbstentionReason, DiagnosisRole, PipelineStage
|
||||
|
||||
|
||||
class ValidationCheck(BaseModel):
|
||||
"""Result of a single deterministic rule evaluation against the local ICD dataset."""
|
||||
|
||||
rule_name: str = Field(
|
||||
description="Name of rule (e.g. 'CatalogExistence', 'TerminalSpecificity', 'Excludes1Constraint').",
|
||||
)
|
||||
passed: bool = Field(description="True if the code satisfies the deterministic rule.")
|
||||
details: str = Field(description="Audit message detailing check result.")
|
||||
|
||||
|
||||
class ValidatedDiagnosis(BaseModel):
|
||||
"""An ICD code that has passed deterministic validation against the local dataset."""
|
||||
|
||||
diagnosis_id: str = Field(description="Entity identifier linking to extracted diagnosis.")
|
||||
raw_term: str = Field(description="Clinical term extracted from document.")
|
||||
code: str = Field(description="Validated authoritative ICD-10-CM code.")
|
||||
description: str = Field(description="Authoritative ICD-10-CM description.")
|
||||
role: DiagnosisRole = Field(description="Final role: PRIMARY or SECONDARY.")
|
||||
evidence: EvidenceSnippet = Field(description="Supporting clinical documentation evidence.")
|
||||
confidence_score: float = Field(
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Consolidated confidence score across extraction and ranking.",
|
||||
)
|
||||
checks: list[ValidationCheck] = Field(
|
||||
default_factory=list,
|
||||
description="Complete record of deterministic validation checks executed.",
|
||||
)
|
||||
|
||||
|
||||
class AbstentionRecord(BaseModel):
|
||||
"""Structured record explaining why an entity or document was abstained from coding."""
|
||||
|
||||
diagnosis_id: str | None = Field(
|
||||
default=None,
|
||||
description="Diagnosis entity ID if abstention is entity-level; None if document-level.",
|
||||
)
|
||||
raw_term: str | None = Field(
|
||||
default=None,
|
||||
description="Clinical term that could not be reliably coded.",
|
||||
)
|
||||
reason: AbstentionReason = Field(
|
||||
description="Standardized machine-readable abstention category.",
|
||||
)
|
||||
detail: str = Field(
|
||||
min_length=1,
|
||||
description="Human-readable explanation of why coding was abstained.",
|
||||
)
|
||||
stage: PipelineStage = Field(
|
||||
description="Pipeline stage at which the abstention decision was triggered.",
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
"""Streamlit UI package for medical ICD-10-CM coding."""
|
||||
@@ -0,0 +1,949 @@
|
||||
"""Streamlit web application for local ICD-10-CM clinical coding, PDF ingestion, and database storage."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import pandas as pd
|
||||
import streamlit as st
|
||||
|
||||
from medical_coding.config.settings import get_settings
|
||||
from medical_coding.database.connection import init_db
|
||||
from medical_coding.database.repository import MedicalCodingRepository
|
||||
from medical_coding.graph.nodes import get_or_initialize_retrieval_system
|
||||
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 medical_coding.schemas.response import CodingResult
|
||||
from medical_coding.ui.components import (
|
||||
render_abstentions,
|
||||
render_header,
|
||||
render_kpi_metrics,
|
||||
render_pdf_page_inspector,
|
||||
render_primary_diagnosis,
|
||||
render_secondary_diagnoses,
|
||||
render_validation_audit_trail,
|
||||
)
|
||||
from medical_coding.ui.sample_data import (
|
||||
CLINICAL_CASES,
|
||||
generate_sample_image,
|
||||
generate_sample_pdf,
|
||||
generate_sample_txt,
|
||||
)
|
||||
from medical_coding.ui.styles import get_css
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Streamlit Application Configuration
|
||||
# -----------------------------------------------------------------------------
|
||||
st.set_page_config(
|
||||
page_title="Local ICD-10 Medical Coding System",
|
||||
page_icon="🏥",
|
||||
layout="wide",
|
||||
initial_sidebar_state="expanded",
|
||||
)
|
||||
|
||||
# Inject custom modern styling
|
||||
st.markdown(get_css(), unsafe_allow_html=True)
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Cached Singletons for Performance
|
||||
# -----------------------------------------------------------------------------
|
||||
@st.cache_resource(show_spinner=False)
|
||||
def get_cached_pipeline() -> MedicalCodingPipeline:
|
||||
"""Return a cached singleton instance of the medical coding orchestrator."""
|
||||
settings = get_settings()
|
||||
return MedicalCodingPipeline(settings=settings)
|
||||
|
||||
|
||||
@st.cache_resource(show_spinner=False)
|
||||
def get_cached_repository() -> MedicalCodingRepository:
|
||||
"""Return a cached singleton instance of the database repository."""
|
||||
init_db()
|
||||
return MedicalCodingRepository()
|
||||
|
||||
|
||||
@st.cache_resource(show_spinner=False)
|
||||
def get_cached_extractor() -> PDFExtractor:
|
||||
"""Return a cached PyMuPDF extractor with pdfplumber fallback."""
|
||||
return PDFExtractor(max_pages=50)
|
||||
|
||||
|
||||
@st.cache_resource(show_spinner=False)
|
||||
def get_cached_ingestion_agent() -> ClinicalDocumentIngestionAgent:
|
||||
"""Return a cached singleton instance of the multimodal clinical document ingestion agent."""
|
||||
return ClinicalDocumentIngestionAgent(max_pdf_pages=50)
|
||||
|
||||
|
||||
# Initialize components
|
||||
pipeline = get_cached_pipeline()
|
||||
repo = get_cached_repository()
|
||||
pdf_extractor = get_cached_extractor()
|
||||
ingestion_agent = get_cached_ingestion_agent()
|
||||
catalog, hybrid_retriever = get_or_initialize_retrieval_system()
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Sidebar Diagnostics & Navigation
|
||||
# -----------------------------------------------------------------------------
|
||||
with st.sidebar:
|
||||
st.markdown("### 🏥 System Diagnostics")
|
||||
st.markdown(
|
||||
"""
|
||||
<div style="background: #1e293b; border: 1px solid #334155; border-radius: 8px; padding: 12px; margin-bottom: 16px;">
|
||||
<div style="font-size: 12px; color: #94a3b8;">STORAGE ENGINE</div>
|
||||
<div style="font-size: 14px; font-weight: 600; color: #38bdf8;">SQLite (WAL Mode)</div>
|
||||
<div style="font-size: 11px; color: #cbd5e1; margin-top: 2px;"><code>./data/medical_coding.db</code></div>
|
||||
<hr style="border: 0; border-top: 1px solid #334155; margin: 8px 0;"/>
|
||||
<div style="font-size: 12px; color: #94a3b8;">RETRIEVAL ENGINE</div>
|
||||
<div style="font-size: 14px; font-weight: 600; color: #10b981;">Hybrid BM25 + FAISS</div>
|
||||
<div style="font-size: 11px; color: #cbd5e1; margin-top: 2px;">Catalog: <strong>25 verified codes</strong></div>
|
||||
<hr style="border: 0; border-top: 1px solid #334155; margin: 8px 0;"/>
|
||||
<div style="font-size: 12px; color: #94a3b8;">MULTIMODAL INGESTION</div>
|
||||
<div style="font-size: 14px; font-weight: 600; color: #f59e0b;">Auto-Detect & Routing</div>
|
||||
<div style="font-size: 11px; color: #cbd5e1; margin-top: 2px;">PDF • RapidOCR Images • TXT</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
st.markdown("### ⚙️ Engine Settings")
|
||||
min_score = st.slider("Min Candidate Score:", min_value=0.1, max_value=0.9, value=0.40, step=0.05)
|
||||
max_pages = st.number_input("Max PDF Pages:", min_value=1, max_value=100, value=50)
|
||||
|
||||
st.markdown("---")
|
||||
st.caption("Offline Local Medical ICD-10-CM Coding System • HIPAA & CMS Invariants Enforced")
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Main Header
|
||||
# -----------------------------------------------------------------------------
|
||||
render_header(
|
||||
offline_mode=True,
|
||||
catalog_size=len(catalog),
|
||||
db_connected=True,
|
||||
)
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Application Tabs
|
||||
# -----------------------------------------------------------------------------
|
||||
tab1, tab2, tab3, tab4, tab5 = st.tabs([
|
||||
"🩺 Clinical Coding Workspace",
|
||||
"📑 Batch Multimodal Ingestion",
|
||||
"🗄️ Database & Encounters Vault",
|
||||
"📊 Analytics & Quality Audits",
|
||||
"🔍 ICD-10 Catalog & Semantic Explorer",
|
||||
])
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# TAB 1: Clinical Coding Workspace (Multimodal Ingestion & Text Processing)
|
||||
# =============================================================================
|
||||
with tab1:
|
||||
st.markdown("#### Multimodal Clinical Document Ingestion & Coding")
|
||||
st.caption(
|
||||
"Upload clinical discharge summaries as PDF documents, plain text (.txt), screenshots / images (.png, .jpg, .webp), "
|
||||
"or enter text manually. The intelligent ingestion agent auto-detects the format via magic bytes and routes to the specialized parser."
|
||||
)
|
||||
|
||||
input_mode = st.radio(
|
||||
"Choose Input Modality:",
|
||||
[
|
||||
"📁 Multimodal Document Ingestion (PDF / Image / TXT)",
|
||||
"✍️ Direct Manual Clinical Text Entry",
|
||||
"⚡ Interactive Demonstration Scenarios",
|
||||
],
|
||||
horizontal=True,
|
||||
)
|
||||
|
||||
document_id = st.text_input("Encounter Identifier (Document ID):", value=f"ENC-{uuid4().hex[:8].upper()}")
|
||||
clinical_text = ""
|
||||
active_file_bytes: bytes | None = None
|
||||
active_filename = "clinical_document.txt"
|
||||
active_source_type = "text"
|
||||
extracted_pages_data: list[Any] = []
|
||||
ingest_result = None
|
||||
|
||||
if input_mode == "📁 Multimodal Document Ingestion (PDF / Image / TXT)":
|
||||
uploaded_file = st.file_uploader(
|
||||
"Upload Clinical Record or Screenshot:",
|
||||
type=["pdf", "txt", "text", "png", "jpg", "jpeg", "webp", "bmp", "tiff"],
|
||||
help="Supports PDFs, plain text files (.txt), and clinical screenshot images (.png, .jpg, .webp). The format is auto-detected via magic bytes.",
|
||||
)
|
||||
|
||||
if uploaded_file is not None:
|
||||
active_file_bytes = uploaded_file.read()
|
||||
active_filename = uploaded_file.name
|
||||
|
||||
with st.spinner("🔍 Auto-detecting format and parsing clinical document..."):
|
||||
ingest_result = ingestion_agent.ingest(
|
||||
source=active_file_bytes,
|
||||
filename=active_filename,
|
||||
)
|
||||
clinical_text = ingest_result.normalized_text
|
||||
extracted_pages_data = ingest_result.pages
|
||||
active_source_type = ingest_result.format.value.lower()
|
||||
|
||||
# Render Format Banner
|
||||
if ingest_result.format == DocumentFormat.PDF:
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="modality-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<div>
|
||||
<span class="modality-badge-pdf">📄 PDF CLINICAL DOCUMENT</span>
|
||||
<span style="font-weight: 600; color: #f8fafc; margin-left: 10px;">{active_filename}</span>
|
||||
</div>
|
||||
<span style="font-size: 12px; color: #94a3b8;">Format Auto-Detected via Magic Bytes</span>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
c1, c2, c3, c4 = st.columns(4)
|
||||
c1.metric("Pages Detected", ingest_result.page_count)
|
||||
c2.metric("Word Count", ingest_result.word_count)
|
||||
c3.metric("Character Count", ingest_result.char_count)
|
||||
c4.metric("Extractor Used", ingest_result.metadata.get("extractor_used", "PYMUPDF").upper())
|
||||
|
||||
if ingest_result.metadata.get("is_scanned"):
|
||||
st.warning("⚠️ Scanned image PDF detected. RapidOCR fallback was automatically applied to extract text.")
|
||||
|
||||
render_pdf_page_inspector(extracted_pages_data)
|
||||
|
||||
elif ingest_result.format == DocumentFormat.IMAGE:
|
||||
conf_pct = round((ingest_result.ocr_confidence or 0.85) * 100, 1)
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="modality-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<div>
|
||||
<span class="modality-badge-image">🖼️ CLINICAL SCREENSHOT (RapidOCR)</span>
|
||||
<span style="font-weight: 600; color: #f8fafc; margin-left: 10px;">{active_filename}</span>
|
||||
</div>
|
||||
<span style="font-size: 12px; color: #c084fc;">Auto-Detected & Processed via RapidOCR</span>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
c1, c2, c3, c4 = st.columns(4)
|
||||
c1.metric("OCR Engine", "RapidOCR ONNX")
|
||||
c2.metric("Avg Confidence", f"{conf_pct}%")
|
||||
c3.metric("Words Extracted", ingest_result.word_count)
|
||||
c4.metric("Lines Detected", ingest_result.metadata.get("lines_detected", 1))
|
||||
|
||||
col_img, col_txt = st.columns([1, 1])
|
||||
with col_img:
|
||||
st.markdown("##### 🖼️ Uploaded Clinical Screenshot")
|
||||
st.image(active_file_bytes, caption=active_filename, use_container_width=True)
|
||||
with col_txt:
|
||||
st.markdown("##### 📄 OCR Extracted Discharge Summary")
|
||||
clinical_text = st.text_area("Extracted Text (Editable):", value=clinical_text, height=350)
|
||||
|
||||
elif ingest_result.format == DocumentFormat.TXT:
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="modality-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<div>
|
||||
<span class="modality-badge-txt">📝 PLAIN TEXT DOCUMENT (.TXT)</span>
|
||||
<span style="font-weight: 600; color: #f8fafc; margin-left: 10px;">{active_filename}</span>
|
||||
</div>
|
||||
<span style="font-size: 12px; color: #34d399;">Auto-Detected Plain Text Encoding</span>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
c1, c2, c3, c4 = st.columns(4)
|
||||
c1.metric("Format", "Plain Text")
|
||||
c2.metric("Encoding", "UTF-8 / Latin-1")
|
||||
c3.metric("Word Count", ingest_result.word_count)
|
||||
c4.metric("Character Count", ingest_result.char_count)
|
||||
|
||||
# Show section badges if any detected
|
||||
detected_sections = ingest_result.metadata.get("detected_sections", [])
|
||||
if detected_sections:
|
||||
st.markdown(
|
||||
"**Detected Clinical Sections:** "
|
||||
+ " ".join([f'<span class="section-chip">🏷️ {s}</span>' for s in detected_sections]),
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
if ingest_result.format != DocumentFormat.IMAGE:
|
||||
clinical_text = st.text_area("Clinical Text Preview (Editable):", value=clinical_text, height=220)
|
||||
|
||||
elif input_mode == "✍️ Direct Manual Clinical Text Entry":
|
||||
clinical_text = st.text_area(
|
||||
"Clinical Documentation (Discharge Summary, History & Physical):",
|
||||
height=260,
|
||||
placeholder="Paste or type clinical discharge summary here...",
|
||||
)
|
||||
active_filename = "manual_entry.txt"
|
||||
active_source_type = "manual_text"
|
||||
|
||||
if clinical_text.strip():
|
||||
with st.spinner("Analyzing manual clinical text..."):
|
||||
ingest_result = ingestion_agent.ingest(source=clinical_text, filename=active_filename)
|
||||
|
||||
st.markdown(
|
||||
"""
|
||||
<div class="modality-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<div>
|
||||
<span class="modality-badge-manual">✍️ MANUAL CLINICAL ENTRY</span>
|
||||
<span style="font-weight: 600; color: #f8fafc; margin-left: 10px;">Direct Input</span>
|
||||
</div>
|
||||
<span style="font-size: 12px; color: #fbbf24;">Direct Clinical Text Stream</span>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
c1, c2, c3 = st.columns(3)
|
||||
c1.metric("Word Count", ingest_result.word_count)
|
||||
c2.metric("Character Count", ingest_result.char_count)
|
||||
c3.metric("Detected Sections", ingest_result.metadata.get("section_count", 0))
|
||||
|
||||
detected_sections = ingest_result.metadata.get("detected_sections", [])
|
||||
if detected_sections:
|
||||
st.markdown(
|
||||
"**Detected Clinical Sections:** "
|
||||
+ " ".join([f'<span class="section-chip">🏷️ {s}</span>' for s in detected_sections]),
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
else: # Interactive Demonstration Scenarios
|
||||
selected_case_name = st.selectbox("Select Clinical Demonstration Scenario:", list(CLINICAL_CASES.keys()))
|
||||
case_info = CLINICAL_CASES[selected_case_name]
|
||||
|
||||
st.markdown(
|
||||
f"""
|
||||
<div style="background: rgba(14, 165, 233, 0.08); border-left: 3px solid #38bdf8; padding: 10px 14px; margin-bottom: 12px; border-radius: 0 6px 6px 0;">
|
||||
<strong style="color: #38bdf8;">{case_info['title']}</strong><br/>
|
||||
<span style="font-size: 13px; color: #cbd5e1;">{case_info['description']}</span><br/>
|
||||
<span style="font-size: 11px; color: #94a3b8;">Expected Primary: <code>{case_info['expected_primary']}</code> | Secondaries: <code>{', '.join(case_info['expected_secondary']) or 'None'}</code></span>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
col_a, col_b, col_c = st.columns(3)
|
||||
with col_a:
|
||||
if st.button("📄 Ingest as Vector PDF", use_container_width=True):
|
||||
pdf_bytes_gen = generate_sample_pdf(case_info["title"], case_info["text"])
|
||||
st.session_state["active_demo_bytes"] = pdf_bytes_gen
|
||||
st.session_state["active_demo_filename"] = f"{case_info['encounter_id']}.pdf"
|
||||
st.session_state["active_demo_format"] = "pdf"
|
||||
st.session_state["active_demo_text"] = case_info["text"]
|
||||
st.session_state["active_demo_id"] = case_info["encounter_id"]
|
||||
st.success("Generated synthetic clinical PDF!")
|
||||
|
||||
with col_b:
|
||||
if st.button("🖼️ Ingest as Screenshot (OCR)", use_container_width=True):
|
||||
img_bytes_gen = generate_sample_image(case_info["title"], case_info["text"])
|
||||
st.session_state["active_demo_bytes"] = img_bytes_gen
|
||||
st.session_state["active_demo_filename"] = f"{case_info['encounter_id']}_screenshot.png"
|
||||
st.session_state["active_demo_format"] = "image"
|
||||
st.session_state["active_demo_text"] = case_info["text"]
|
||||
st.session_state["active_demo_id"] = case_info["encounter_id"]
|
||||
st.success("Rendered clinical screenshot image for OCR parsing!")
|
||||
|
||||
with col_c:
|
||||
if st.button("📝 Ingest as Plain Text (.txt)", use_container_width=True):
|
||||
txt_bytes_gen = generate_sample_txt(case_info["title"], case_info["text"])
|
||||
st.session_state["active_demo_bytes"] = txt_bytes_gen
|
||||
st.session_state["active_demo_filename"] = f"{case_info['encounter_id']}.txt"
|
||||
st.session_state["active_demo_format"] = "txt"
|
||||
st.session_state["active_demo_text"] = case_info["text"]
|
||||
st.session_state["active_demo_id"] = case_info["encounter_id"]
|
||||
st.success("Loaded as plain text document!")
|
||||
|
||||
if "active_demo_id" in st.session_state:
|
||||
document_id = st.session_state["active_demo_id"]
|
||||
active_file_bytes = st.session_state.get("active_demo_bytes")
|
||||
active_filename = st.session_state.get("active_demo_filename", f"{document_id}.txt")
|
||||
demo_fmt = st.session_state.get("active_demo_format", "text")
|
||||
|
||||
# Run through ingestion agent to get real-time parser output and auto-detection badge
|
||||
with st.spinner("Processing scenario through Ingestion Agent..."):
|
||||
if active_file_bytes:
|
||||
ingest_result = ingestion_agent.ingest(source=active_file_bytes, filename=active_filename)
|
||||
else:
|
||||
ingest_result = ingestion_agent.ingest(source=st.session_state["active_demo_text"], filename=active_filename)
|
||||
|
||||
clinical_text = ingest_result.normalized_text
|
||||
active_source_type = ingest_result.format.value.lower()
|
||||
extracted_pages_data = ingest_result.pages
|
||||
|
||||
if demo_fmt == "image":
|
||||
conf_pct = round((ingest_result.ocr_confidence or 0.85) * 100, 1)
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="modality-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<div>
|
||||
<span class="modality-badge-image">🖼️ AUTO-DETECTED: CLINICAL SCREENSHOT (RapidOCR)</span>
|
||||
<span style="font-weight: 600; color: #f8fafc; margin-left: 10px;">{active_filename}</span>
|
||||
</div>
|
||||
<span style="font-size: 12px; color: #c084fc;">RapidOCR Confidence: <strong>{conf_pct}%</strong></span>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
col_img, col_txt = st.columns([1, 1])
|
||||
with col_img:
|
||||
st.markdown("##### 🖼️ Synthetic Clinical Screenshot")
|
||||
st.image(active_file_bytes, caption=active_filename, use_container_width=True)
|
||||
with col_txt:
|
||||
st.markdown("##### 📄 OCR Extracted Text")
|
||||
clinical_text = st.text_area("Extracted Document Content:", value=clinical_text, height=350)
|
||||
|
||||
elif demo_fmt == "pdf":
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="modality-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<div>
|
||||
<span class="modality-badge-pdf">📄 AUTO-DETECTED: CLINICAL PDF</span>
|
||||
<span style="font-weight: 600; color: #f8fafc; margin-left: 10px;">{active_filename}</span>
|
||||
</div>
|
||||
<span style="font-size: 12px; color: #f87171;">PyMuPDF Vector Extraction</span>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
render_pdf_page_inspector(extracted_pages_data)
|
||||
clinical_text = st.text_area("Document Text Preview:", value=clinical_text, height=200)
|
||||
|
||||
else:
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="modality-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<div>
|
||||
<span class="modality-badge-txt">📝 AUTO-DETECTED: PLAIN TEXT</span>
|
||||
<span style="font-weight: 600; color: #f8fafc; margin-left: 10px;">{active_filename}</span>
|
||||
</div>
|
||||
<span style="font-size: 12px; color: #34d399;">Direct Normalized Text</span>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
clinical_text = st.text_area("Document Text Preview:", value=clinical_text, height=200)
|
||||
else:
|
||||
clinical_text = st.text_area("Document Preview:", value=case_info["text"], height=200)
|
||||
|
||||
# Coding Execution Trigger
|
||||
st.markdown("---")
|
||||
col_run, col_clear = st.columns([3, 1])
|
||||
|
||||
with col_run:
|
||||
run_button = st.button("⚡ Run ICD-10 Medical Coding Pipeline", type="primary", use_container_width=True)
|
||||
|
||||
if run_button:
|
||||
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...")
|
||||
|
||||
# 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,
|
||||
},
|
||||
)
|
||||
)
|
||||
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
|
||||
|
||||
if coding_result:
|
||||
# Save automatically to SQLite Database
|
||||
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(
|
||||
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},
|
||||
)
|
||||
|
||||
st.success(
|
||||
f"💾 Encounter successfully archived in SQLite Database! (Document ID: **{document_id}**, Row #{saved_record['id']})"
|
||||
)
|
||||
|
||||
# Format Results with Rich Aesthetics
|
||||
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)
|
||||
|
||||
# Abstentions & Exclusions
|
||||
render_abstentions(coding_result.abstentions)
|
||||
|
||||
# Deterministic Rule Audit Trail
|
||||
render_validation_audit_trail(coding_result.primary_diagnosis, coding_result.secondary_diagnoses)
|
||||
|
||||
# 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",
|
||||
"ICD_Code": coding_result.primary_diagnosis.code,
|
||||
"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",
|
||||
"ICD_Code": s.code,
|
||||
"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,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# TAB 2: Batch Multimodal Ingestion
|
||||
# =============================================================================
|
||||
with tab2:
|
||||
st.markdown("#### Concurrent Multimodal Batch Ingestion & Coding")
|
||||
st.caption("Upload multiple clinical documents simultaneously (mixed PDFs, plain text, or screenshot images). The Ingestion Agent automatically detects each file's format and switches to the appropriate parser.")
|
||||
|
||||
batch_files = st.file_uploader(
|
||||
"Upload Multiple Clinical Documents (PDF / TXT / Images):",
|
||||
type=["pdf", "txt", "text", "png", "jpg", "jpeg", "webp", "bmp", "tiff"],
|
||||
accept_multiple_files=True,
|
||||
help="Select multiple clinical files of any supported format for concurrent batch ingestion.",
|
||||
)
|
||||
|
||||
b_col1, b_col2 = st.columns([2, 1])
|
||||
with b_col1:
|
||||
st.write(f"📁 **{len(batch_files)} Document(s)** queued for batch processing.")
|
||||
with b_col2:
|
||||
concurrency_limit = st.slider("Document Concurrency Limit:", min_value=1, max_value=20, value=10)
|
||||
|
||||
if st.button("🚀 Process Batch Ingestion", type="primary", disabled=len(batch_files) == 0):
|
||||
progress_bar = st.progress(0)
|
||||
status_text = st.empty()
|
||||
batch_results: list[dict[str, Any]] = []
|
||||
|
||||
total_files = len(batch_files)
|
||||
|
||||
for idx, b_file in enumerate(batch_files):
|
||||
status_text.text(f"Processing ({idx + 1}/{total_files}): {b_file.name}...")
|
||||
file_bytes = b_file.read()
|
||||
doc_id = f"BATCH-{uuid4().hex[:6].upper()}"
|
||||
|
||||
# Auto-detect format and extract text via ingestion agent
|
||||
ingest_res = ingestion_agent.ingest(source=file_bytes, filename=b_file.name)
|
||||
norm_text = ingest_res.normalized_text
|
||||
|
||||
# Run document through pipeline
|
||||
try:
|
||||
res: CodingResult = asyncio.run(
|
||||
pipeline.run_document(
|
||||
document_id=doc_id,
|
||||
text=norm_text,
|
||||
file_bytes=file_bytes,
|
||||
metadata={"filename": b_file.name, "modality": ingest_res.format.value},
|
||||
)
|
||||
)
|
||||
|
||||
# Persist to database
|
||||
repo.save_coding_result(
|
||||
result=res,
|
||||
raw_text=norm_text,
|
||||
filename=b_file.name,
|
||||
source_type=f"batch_{ingest_res.format.value.lower()}",
|
||||
page_count=ingest_res.page_count,
|
||||
file_size_bytes=len(file_bytes),
|
||||
metadata={"format": ingest_res.format.value, "is_ocr": ingest_res.is_ocr},
|
||||
)
|
||||
|
||||
batch_results.append({
|
||||
"Filename": b_file.name,
|
||||
"Encounter ID": doc_id,
|
||||
"Modality": ingest_res.format.value,
|
||||
"OCR Used": "Yes" if ingest_res.is_ocr else "No",
|
||||
"Status": res.status.value if hasattr(res.status, "value") else str(res.status),
|
||||
"Primary Code": res.primary_diagnosis.code if res.primary_diagnosis else "N/A",
|
||||
"Primary Description": res.primary_diagnosis.description if res.primary_diagnosis else "None",
|
||||
"Secondary Diags": len(res.secondary_diagnoses),
|
||||
"Abstentions": len(res.abstentions),
|
||||
"Latency (ms)": f"{res.processing_time_ms:.1f}",
|
||||
})
|
||||
except Exception as e:
|
||||
batch_results.append({
|
||||
"Filename": b_file.name,
|
||||
"Encounter ID": doc_id,
|
||||
"Modality": ingest_res.format.value if ingest_res else "UNKNOWN",
|
||||
"OCR Used": "Yes" if (ingest_res and ingest_res.is_ocr) else "No",
|
||||
"Status": "ERROR",
|
||||
"Primary Code": "N/A",
|
||||
"Primary Description": str(e),
|
||||
"Secondary Diags": 0,
|
||||
"Abstentions": 0,
|
||||
"Latency (ms)": "0.0",
|
||||
})
|
||||
|
||||
progress_bar.progress((idx + 1) / total_files)
|
||||
|
||||
status_text.text(f"✅ Completed batch processing of {total_files} multimodal document(s)!")
|
||||
|
||||
# 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),
|
||||
file_name="multimodal_batch_results.csv",
|
||||
mime="text/csv",
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 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,
|
||||
)
|
||||
|
||||
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"**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()
|
||||
|
||||
# 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="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_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,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# TAB 4: Analytics & Quality Audits
|
||||
# =============================================================================
|
||||
with tab4:
|
||||
st.markdown("#### Clinical Quality & Invariant Analytics")
|
||||
st.caption("Aggregated analytics over all stored encounters in SQLite database.")
|
||||
|
||||
analytics_data = repo.get_analytics_summary()
|
||||
|
||||
a1, a2, a3, a4 = st.columns(4)
|
||||
a1.metric("Total Documents Coded", analytics_data["total_documents"])
|
||||
a2.metric("Total Diagnoses Assigned", analytics_data["total_diagnoses"])
|
||||
a3.metric("HIPAA Billable Compliance", f"{analytics_data['billable_ratio_percent']}%")
|
||||
a4.metric("Mean Latency", f"{analytics_data['average_processing_time_ms']} ms")
|
||||
|
||||
st.markdown("---")
|
||||
|
||||
chart_c1, chart_c2 = st.columns(2)
|
||||
|
||||
with chart_c1:
|
||||
st.markdown("##### 🏆 Top Primary Diagnoses")
|
||||
top_primaries = analytics_data["top_primary_codes"]
|
||||
if top_primaries:
|
||||
primary_chart_df = pd.DataFrame(top_primaries).set_index("code")
|
||||
st.bar_chart(primary_chart_df["count"])
|
||||
else:
|
||||
st.info("No primary diagnoses recorded yet.")
|
||||
|
||||
with chart_c2:
|
||||
st.markdown("##### 📋 Top Secondary Comorbidities")
|
||||
top_secondaries = analytics_data["top_secondary_codes"]
|
||||
if top_secondaries:
|
||||
sec_chart_df = pd.DataFrame(top_secondaries).set_index("code")
|
||||
st.bar_chart(sec_chart_df["count"])
|
||||
else:
|
||||
st.info("No secondary diagnoses recorded yet.")
|
||||
|
||||
st.markdown("---")
|
||||
chart_c3, chart_c4 = st.columns(2)
|
||||
|
||||
with chart_c3:
|
||||
st.markdown("##### 🚫 Abstention Reasons Breakdown")
|
||||
abst_dist = analytics_data["abstention_distribution"]
|
||||
if abst_dist:
|
||||
abst_df = pd.DataFrame(list(abst_dist.items()), columns=["Reason", "Count"]).set_index("Reason")
|
||||
st.bar_chart(abst_df)
|
||||
else:
|
||||
st.info("No abstentions logged yet.")
|
||||
|
||||
with chart_c4:
|
||||
st.markdown("##### 📈 Encounter Status Breakdown")
|
||||
status_dist = analytics_data["status_breakdown"]
|
||||
if status_dist:
|
||||
st_df = pd.DataFrame(list(status_dist.items()), columns=["Status", "Count"]).set_index("Status")
|
||||
st.bar_chart(st_df)
|
||||
else:
|
||||
st.info("No status data available.")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# TAB 5: ICD-10 Catalog & Semantic Explorer
|
||||
# =============================================================================
|
||||
with tab5:
|
||||
st.markdown("#### Authoritative ICD-10-CM Catalog & Retriever Explorer")
|
||||
st.caption("Directly test the hybrid BM25 lexical search and FAISS dense vector search against the local ICD catalog.")
|
||||
|
||||
search_query = st.text_input(
|
||||
"Enter Clinical Term or Condition to Search Local Catalog:",
|
||||
value="acute systolic heart failure",
|
||||
placeholder="e.g. congestive heart failure, diabetes, COPD, myocardial infarction",
|
||||
)
|
||||
|
||||
k_slider = st.slider("Top K Candidates to Retrieve:", min_value=1, max_value=15, value=5)
|
||||
|
||||
if search_query:
|
||||
candidates = hybrid_retriever.retrieve(query=search_query, top_k=k_slider)
|
||||
|
||||
st.markdown(f"##### 🎯 Hybrid Retrieval Results ({len(candidates)} candidates):")
|
||||
for idx, cand in enumerate(candidates, start=1):
|
||||
score_pct = int(cand.retrieval_score * 100)
|
||||
billable_str = "✓ Billable Leaf" if cand.is_valid_billable else "⚠ Non-Billable Header"
|
||||
badge_class = "badge-success" if cand.is_valid_billable else "badge-warning"
|
||||
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="secondary-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<div>
|
||||
<span style="font-size: 20px; font-weight: 700; color: #38bdf8;">#{idx}. {cand.code}</span>
|
||||
<span style="font-size: 16px; font-weight: 600; color: #f8fafc; margin-left: 12px;">{cand.description}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="pill-badge {badge_class}">{billable_str}</span>
|
||||
<span style="font-size: 13px; color: #94a3b8; margin-left: 8px;">Similarity: <strong>{score_pct}%</strong></span>
|
||||
</div>
|
||||
</div>
|
||||
<div style="font-size: 12px; color: #94a3b8; margin-top: 6px;">
|
||||
Category: <code>{cand.category}</code> | Retrieval Source: <code>{cand.retrieval_method}</code>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
st.markdown("---")
|
||||
st.markdown("##### 📚 Complete Local ICD-10-CM Source Catalog")
|
||||
all_records = catalog.get_all_records()
|
||||
catalog_df = pd.DataFrame([
|
||||
{
|
||||
"Code": r.code,
|
||||
"Description": r.short_description,
|
||||
"Category": r.category,
|
||||
"Billable": "Yes" if r.is_valid_billable else "No",
|
||||
"Excludes1": ", ".join(r.excludes1) if r.excludes1 else "None",
|
||||
}
|
||||
for r in all_records
|
||||
])
|
||||
st.dataframe(catalog_df, use_container_width=True)
|
||||
@@ -0,0 +1,300 @@
|
||||
"""Modular presentation components for the medical coding Streamlit user interface."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import streamlit as st
|
||||
|
||||
from medical_coding.schemas.response import CodedDiagnosisResponse, CodingResult
|
||||
from medical_coding.schemas.validation import AbstentionRecord
|
||||
|
||||
|
||||
def render_header(
|
||||
offline_mode: bool = True,
|
||||
catalog_size: int = 25,
|
||||
db_connected: bool = True,
|
||||
) -> None:
|
||||
"""Render the application branding banner with real-time operational status pills."""
|
||||
db_status_pill = (
|
||||
'<span class="pill-badge badge-success">● SQLite Connected</span>'
|
||||
if db_connected
|
||||
else '<span class="pill-badge badge-danger">● DB Disconnected</span>'
|
||||
)
|
||||
offline_pill = (
|
||||
'<span class="pill-badge badge-info">🔒 100% Offline AI</span>'
|
||||
if offline_mode
|
||||
else '<span class="pill-badge badge-warning">Online Mode</span>'
|
||||
)
|
||||
catalog_pill = f'<span class="pill-badge badge-secondary">📚 {catalog_size} ICD Codes</span>'
|
||||
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="clinic-header">
|
||||
<div style="display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 12px;">
|
||||
<div>
|
||||
<h1 class="clinic-title">
|
||||
<span>🏥</span> Local ICD-10-CM Medical Coding Engine
|
||||
</h1>
|
||||
<p class="clinic-subtitle">
|
||||
Evidence-backed clinical diagnosis extraction, hybrid semantic retrieval, deterministic rule auditing, and persistent encounter warehousing.
|
||||
</p>
|
||||
</div>
|
||||
<div style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap; padding-top: 4px;">
|
||||
{offline_pill}
|
||||
{db_status_pill}
|
||||
{catalog_pill}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
|
||||
def render_kpi_metrics(result: CodingResult) -> None:
|
||||
"""Render high-level KPIs for a single document coding run."""
|
||||
c1, c2, c3, c4, c5 = st.columns(5)
|
||||
|
||||
status_str = result.status.value if hasattr(result.status, "value") else str(result.status)
|
||||
status_class = (
|
||||
"badge-success"
|
||||
if status_str == "SUCCESS"
|
||||
else "badge-warning"
|
||||
if status_str == "PARTIAL_SUCCESS"
|
||||
else "badge-danger"
|
||||
)
|
||||
|
||||
with c1:
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Status</div>
|
||||
<div style="margin-top: 8px;">
|
||||
<span class="pill-badge {status_class}">{status_str}</span>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
with c2:
|
||||
primary_code = result.primary_diagnosis.code if result.primary_diagnosis else "None"
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Primary ICD-10</div>
|
||||
<div class="kpi-value" style="color: #38bdf8;">{primary_code}</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
with c3:
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Secondary Diags</div>
|
||||
<div class="kpi-value">{len(result.secondary_diagnoses)}</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
with c4:
|
||||
abst_count = len(result.abstentions)
|
||||
abst_color = "#f87171" if abst_count > 0 else "#94a3b8"
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Abstentions</div>
|
||||
<div class="kpi-value" style="color: {abst_color};">{abst_count}</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
with c5:
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Processing Time</div>
|
||||
<div class="kpi-value">{result.processing_time_ms:.1f}<span style="font-size: 13px; font-weight: normal; color: #94a3b8;"> ms</span></div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
|
||||
def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
|
||||
"""Render the primary diagnosis card with evidence and specificity confirmation."""
|
||||
st.markdown("### 🎯 Primary Diagnosis")
|
||||
if not primary:
|
||||
st.info("ℹ️ No primary diagnosis assigned for this document (abstained or undetermined).")
|
||||
return
|
||||
|
||||
billable_badge = (
|
||||
'<span class="pill-badge badge-success">✓ HIPAA Billable Leaf</span>'
|
||||
if primary.is_terminal_billable
|
||||
else '<span class="pill-badge badge-danger">⚠ Non-Billable Header</span>'
|
||||
)
|
||||
acuity_badge = f'<span class="pill-badge badge-info">{primary.acuity.value if hasattr(primary.acuity, "value") else primary.acuity}</span>'
|
||||
certainty_badge = f'<span class="pill-badge badge-secondary">{primary.certainty.value if hasattr(primary.certainty, "value") else primary.certainty}</span>'
|
||||
|
||||
conf_pct = int(primary.confidence_score * 100)
|
||||
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="primary-card">
|
||||
<div class="primary-card-header">
|
||||
<div>
|
||||
<span class="primary-code">{primary.code}</span>
|
||||
<span style="margin-left: 12px;">{billable_badge}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span style="font-size: 13px; color: #94a3b8; margin-right: 6px;">Confidence:</span>
|
||||
<strong style="color: #38bdf8;">{conf_pct}%</strong>
|
||||
</div>
|
||||
</div>
|
||||
<div class="primary-desc">{primary.description}</div>
|
||||
<div style="display: flex; gap: 8px; margin: 10px 0;">
|
||||
{acuity_badge}
|
||||
{certainty_badge}
|
||||
<span class="pill-badge badge-info">Chief Reason for Encounter</span>
|
||||
</div>
|
||||
<div class="evidence-box">
|
||||
<span style="font-weight: 600; color: #6ee7b7; font-size: 11px; text-transform: uppercase;">
|
||||
📄 Verbatim Clinical Evidence Quote:
|
||||
</span><br/>
|
||||
<span class="evidence-quote">"{primary.evidence_quote}"</span>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
|
||||
def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> None:
|
||||
"""Render the list of validated secondary comorbid diagnoses."""
|
||||
st.markdown(f"### 📋 Secondary Diagnoses ({len(secondaries)})")
|
||||
if not secondaries:
|
||||
st.write("No secondary comorbid diagnoses identified.")
|
||||
return
|
||||
|
||||
for idx, diag in enumerate(secondaries, start=1):
|
||||
billable_badge = (
|
||||
'<span class="pill-badge badge-success">✓ Billable</span>'
|
||||
if diag.is_terminal_billable
|
||||
else '<span class="pill-badge badge-danger">⚠ Non-Billable</span>'
|
||||
)
|
||||
acuity_str = diag.acuity.value if hasattr(diag.acuity, "value") else str(diag.acuity)
|
||||
certainty_str = diag.certainty.value if hasattr(diag.certainty, "value") else str(diag.certainty)
|
||||
|
||||
with st.container():
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="secondary-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
|
||||
<div>
|
||||
<strong style="font-size: 18px; color: #38bdf8;">#{idx}. {diag.code}</strong>
|
||||
<span style="font-size: 15px; font-weight: 600; color: #f8fafc; margin-left: 10px;">{diag.description}</span>
|
||||
</div>
|
||||
<div style="display: flex; gap: 6px; align-items: center;">
|
||||
{billable_badge}
|
||||
<span class="pill-badge badge-secondary">{acuity_str}</span>
|
||||
<span class="pill-badge badge-secondary">{certainty_str}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="evidence-box">
|
||||
<span style="font-weight: 600; color: #6ee7b7; font-size: 11px; text-transform: uppercase;">
|
||||
Clinical Evidence:
|
||||
</span>
|
||||
<span class="evidence-quote">"{diag.evidence_quote}"</span>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
|
||||
def render_abstentions(abstentions: list[AbstentionRecord]) -> None:
|
||||
"""Render explicit abstentions, negated conditions, and exclusions."""
|
||||
if not abstentions:
|
||||
return
|
||||
|
||||
with st.expander(f"🚫 Audited Abstentions & Rule-Outs ({len(abstentions)})", expanded=True):
|
||||
st.caption("Conditions detected in documentation that were strictly abstained or excluded under ICD-10 guidelines:")
|
||||
for abst in abstentions:
|
||||
reason_str = abst.reason.value if hasattr(abst.reason, "value") else str(abst.reason)
|
||||
stage_str = abst.stage.value if hasattr(abst.stage, "value") else str(abst.stage)
|
||||
raw_term = abst.raw_term or "Unspecified Entity"
|
||||
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="abstention-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
|
||||
<strong style="color: #f87171; font-size: 14px;">Condition: {raw_term}</strong>
|
||||
<span class="pill-badge badge-danger">{reason_str}</span>
|
||||
</div>
|
||||
<div style="font-size: 13px; color: #e2e8f0;">{abst.detail}</div>
|
||||
<div style="font-size: 11px; color: #94a3b8; margin-top: 4px;">Enforced at stage: <code>{stage_str}</code></div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
|
||||
def render_validation_audit_trail(primary: CodedDiagnosisResponse | None, secondaries: list[CodedDiagnosisResponse]) -> None:
|
||||
"""Render deterministic non-LLM validation rule checks."""
|
||||
with st.expander("🛡️ Deterministic Non-LLM Invariants & Rule Audit", expanded=False):
|
||||
all_codes = []
|
||||
if primary:
|
||||
all_codes.append(primary)
|
||||
all_codes.extend(secondaries)
|
||||
|
||||
st.markdown(
|
||||
"""
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>Catalog Existence Check:</strong> All assigned codes exist in the authoritative local ICD-10-CM dataset.
|
||||
</div>
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>HIPAA Terminal Specificity:</strong> Codes are verified billable terminal leaf nodes (non-category headers).
|
||||
</div>
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>Single-Primary Invariant:</strong> Maximum of exactly 1 primary admission diagnosis enforced.
|
||||
</div>
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>Mutual Excludes1 Constraint:</strong> No mutually contradictory codes co-assigned for this encounter.
|
||||
</div>
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>Anti-Hallucination Bound:</strong> Codes were bounded exclusively to the retrieved candidate pool.
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
|
||||
def render_pdf_page_inspector(pages: list[Any]) -> None:
|
||||
"""Render an interactive page-by-page text explorer for ingested PDFs."""
|
||||
if not pages:
|
||||
return
|
||||
|
||||
with st.expander(f"📄 Ingested PDF Document Viewer ({len(pages)} Pages)", expanded=False):
|
||||
selected_page = st.selectbox(
|
||||
"Select Page to Inspect:",
|
||||
options=[p.page_number for p in pages],
|
||||
format_func=lambda x: f"Page {x} of {len(pages)}",
|
||||
)
|
||||
page_obj = next((p for p in pages if p.page_number == selected_page), pages[0])
|
||||
|
||||
c1, c2, c3 = st.columns(3)
|
||||
c1.metric("Character Count", page_obj.char_count)
|
||||
c2.metric("Word Count", page_obj.word_count)
|
||||
c3.metric("Embedded Images", "Yes" if page_obj.has_images else "No")
|
||||
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="pdf-page-card">
|
||||
<pre style="white-space: pre-wrap; margin: 0; font-size: 12px; color: #e2e8f0;">{page_obj.normalized_text}</pre>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
@@ -0,0 +1,268 @@
|
||||
"""Realistic clinical demonstration cases and synthetic PDF generation for testing."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pymupdf
|
||||
|
||||
CLINICAL_CASES: dict[str, dict[str, Any]] = {
|
||||
"Case 1: Decompensated Heart Failure & Comorbidities": {
|
||||
"title": "Acute Systolic Heart Failure with Hypertension & T2DM",
|
||||
"encounter_id": "ENC-HF-2026-001",
|
||||
"description": "72yo male admitted with severe dyspnea, orthopnea, and lower extremity edema.",
|
||||
"text": """HOSPITAL DISCHARGE SUMMARY
|
||||
PATIENT ENCOUNTER: ENC-HF-2026-001
|
||||
ATTENDING PHYSICIAN: Dr. Robert Vance, MD
|
||||
DEPARTMENT: Cardiology Services
|
||||
ADMISSION DATE: 2026-09-24
|
||||
DISCHARGE DATE: 2026-10-01
|
||||
|
||||
CHIEF COMPLAINT:
|
||||
Severe shortness of breath on exertion and progressive 3-pillow orthopnea.
|
||||
|
||||
HISTORY OF PRESENT ILLNESS:
|
||||
The patient is a 72-year-old male with a known history of chronic cardiovascular disease who presented to the Emergency Department with progressive exertional dyspnea and 15-pound weight gain over the last 2 weeks. Physical examination revealed bilateral pulmonary crackles, jugular venous distention of 8 cm, and 3+ pitting edema of both lower extremities. Echocardiogram demonstrated a left ventricular ejection fraction of 25% with marked ventricular systolic failure.
|
||||
|
||||
HOSPITAL COURSE & TREATMENT:
|
||||
Intensive intravenous furosemide diuresis was initiated with significant clinical improvement. Potassium levels and renal function were closely monitored. The patient achieved a 7 kg fluid reduction and was transitioned to guideline-directed oral medical therapy.
|
||||
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Primary: Acute systolic heart failure (decompensated congestive heart failure with systolic dysfunction).
|
||||
2. Essential primary hypertension (longstanding, maintained on amlodipine).
|
||||
3. Type 2 diabetes mellitus without complications (glycemic control stable).
|
||||
|
||||
PERTINENT NEGATIVES:
|
||||
Patient explicitly denies chest pain, palpitations, or fever. Acute coronary syndrome was ruled out by serial troponin assays.
|
||||
|
||||
DISPOSITION:
|
||||
Discharged to home in stable, euvolemic condition. Follow-up scheduled in Heart Failure Clinic in 7 days.""",
|
||||
"expected_primary": "I50.21",
|
||||
"expected_secondary": ["I10", "E11.9"],
|
||||
},
|
||||
"Case 2: Acute COPD Exacerbation with Pneumonia": {
|
||||
"title": "Acute Exacerbation of COPD with Community Pneumonia",
|
||||
"encounter_id": "ENC-COPD-2026-042",
|
||||
"description": "68yo female smoker presenting with purulent sputum and acute respiratory distress.",
|
||||
"text": """INPATIENT DISCHARGE SUMMARY
|
||||
PATIENT ENCOUNTER: ENC-COPD-2026-042
|
||||
SERVICE: Pulmonary Medicine
|
||||
ADMISSION DATE: 2026-09-27
|
||||
DISCHARGE DATE: 2026-10-02
|
||||
|
||||
CHIEF COMPLAINT:
|
||||
Worsening cough, fever of 101.4F, and acute respiratory distress.
|
||||
|
||||
HISTORY OF PRESENT ILLNESS:
|
||||
A 68-year-old female with a 45 pack-year smoking history and known chronic obstructive pulmonary disease presents with 4 days of increased dyspnea, wheezing, and yellow purulent sputum. Chest radiograph demonstrated patchy consolidation in the right lower lobe consistent with community-acquired pneumonia. Arterial blood gas showed acute hypercapnic respiratory decompensation.
|
||||
|
||||
CLINICAL MANAGEMENT:
|
||||
Patient was admitted to Step-Down Unit and received supplemental oxygen, nebulized albuterol/ipratropium, systemic corticosteroids, and intravenous ceftriaxone plus azithromycin. Oxygen saturation improved to 93% on room air.
|
||||
|
||||
FINAL DIAGNOSES:
|
||||
1. Chronic obstructive pulmonary disease with acute exacerbation (acute COPD exacerbation).
|
||||
2. Pneumonia unspecified organism (community-acquired right lower lobe infiltrate).
|
||||
3. Gastro-esophageal reflux disease without esophagitis.
|
||||
|
||||
NEGATIONS / AUDIT:
|
||||
Patient denies hemoptysis or syncope. No evidence of pulmonary embolism.
|
||||
|
||||
DISCHARGE MEDICATIONS:
|
||||
Prednisone taper, formoterol/budesonide inhaler, completion of 5-day antibiotic course.""",
|
||||
"expected_primary": "J44.1",
|
||||
"expected_secondary": ["J18.9", "K21.9"],
|
||||
},
|
||||
"Case 3: Acute Anterior STEMI Myocardial Infarction": {
|
||||
"title": "ST Elevation Myocardial Infarction (Anterior Wall)",
|
||||
"encounter_id": "ENC-STEMI-2026-103",
|
||||
"description": "59yo male presenting with sudden substernal chest pressure and anterior ST elevations.",
|
||||
"text": """EMERGENCY DISCHARGE SUMMARY
|
||||
PATIENT ENCOUNTER: ENC-STEMI-2026-103
|
||||
CARDIAC CATHETERIZATION SUITE / CCU
|
||||
DATE OF SERVICE: 2026-10-02
|
||||
|
||||
CLINICAL SYNOPSIS:
|
||||
59-year-old male transported via EMS with acute crushing substernal chest pain radiating to the left arm and diaphoresis. 12-lead ECG showed 4mm ST elevations across precordial leads V1-V4. Emergency coronary angiography was performed, demonstrating complete 100% thrombotic occlusion of the proximal Left Anterior Descending (LAD) coronary artery. Successful primary percutaneous coronary intervention with drug-eluting stent was deployed with TIMI 3 flow restoration.
|
||||
|
||||
FINAL DIAGNOSIS:
|
||||
1. ST elevation myocardial infarction involving anterior wall (acute transmural anterior STEMI).
|
||||
2. Essential primary hypertension.
|
||||
3. Paroxysmal atrial fibrillation (brief peri-procedural runs, converted spontaneously to sinus rhythm).
|
||||
|
||||
PAST MEDICAL HISTORY:
|
||||
Remote appendectomy 25 years ago (resolved). Denies prior stroke or intracranial hemorrhage.
|
||||
|
||||
DISPOSITION:
|
||||
Patient discharged in stable hemodynamic state on dual antiplatelet therapy.""",
|
||||
"expected_primary": "I21.09",
|
||||
"expected_secondary": ["I10", "I48.0"],
|
||||
},
|
||||
"Case 4: Severe Sepsis & Acute Kidney Injury": {
|
||||
"title": "Systemic Sepsis with Acute Kidney Injury & CKD Stage 3",
|
||||
"encounter_id": "ENC-SEPSIS-2026-215",
|
||||
"description": "78yo female presenting with septic shock, oliguria, and elevated serum creatinine.",
|
||||
"text": """CRITICAL CARE DISCHARGE SUMMARY
|
||||
PATIENT ENCOUNTER: ENC-SEPSIS-2026-215
|
||||
INTENSIVE CARE UNIT (ICU)
|
||||
ADMISSION DATE: 2026-09-20
|
||||
DISCHARGE DATE: 2026-09-29
|
||||
|
||||
HOSPITAL COURSE:
|
||||
78-year-old female admitted in septic shock secondary to severe urinary tract infection. She met criteria for systemic sepsis unspecified organism with hypotension requiring norepinephrine vasopressor support for 48 hours. Laboratory evaluation revealed acute kidney injury unspecified with serum creatinine rising from baseline 1.4 mg/dL to peak 3.8 mg/dL. Baseline chronic kidney disease stage 3 was noted.
|
||||
|
||||
OUTCOME:
|
||||
With targeted intravenous fluids, antimicrobial therapy, and vasopressor weaning, hemodynamics stabilized and renal function recovered to near-baseline (creatinine 1.6 mg/dL).
|
||||
|
||||
FINAL CODING SUMMARY:
|
||||
1. Sepsis unspecified organism (systemic septicemia, resolved).
|
||||
2. Acute kidney injury unspecified (acute renal failure, resolving).
|
||||
3. Chronic kidney disease stage 3 (moderate baseline renal impairment).
|
||||
4. Essential primary hypertension.
|
||||
|
||||
DOCUMENTATION AUDIT:
|
||||
Patient denies chest pain or shortness of breath. Neurologic status returned to baseline.""",
|
||||
"expected_primary": "A41.9",
|
||||
"expected_secondary": ["N17.9", "N18.3", "I10"],
|
||||
},
|
||||
"Case 5: Negation & Historical Rule-Outs (Abstention Demo)": {
|
||||
"title": "GERD Evaluation with Explicitly Negated Chest Pain & Historical Diabetes",
|
||||
"encounter_id": "ENC-ABSTAIN-2026-330",
|
||||
"description": "Case demonstrating deterministic abstentions for negated symptoms and unconfirmed conditions.",
|
||||
"text": """OUTPATIENT CLINIC NOTE
|
||||
ENCOUNTER: ENC-ABSTAIN-2026-330
|
||||
DEPARTMENT: Internal Medicine
|
||||
|
||||
SUBJECTIVE:
|
||||
54-year-old male reports burning retrosternal sensation after large meals and acidic regurgitation when lying flat.
|
||||
Patient explicitly denies chest pain, denies shortness of breath, and denies palpitations.
|
||||
Family history of heart attack in father at age 62 (not patient condition).
|
||||
Patient had childhood asthma which completely resolved 35 years ago with no current medications.
|
||||
|
||||
OBJECTIVE:
|
||||
Abdominal examination soft, non-tender, no organomegaly. Heart rate regular, lungs clear to auscultation.
|
||||
Upper endoscopy showed mild mucosal erythema consistent with gastro-esophageal reflux disease without esophagitis.
|
||||
|
||||
ASSESSMENT:
|
||||
1. Gastro-esophageal reflux disease without esophagitis (active).
|
||||
2. Chest pain: RULED OUT / NEGATED.
|
||||
3. Childhood asthma: HISTORICAL / RESOLVED (no current treatment).
|
||||
|
||||
PLAN:
|
||||
Initiated omeprazole 20mg daily with dietary lifestyle counseling.""",
|
||||
"expected_primary": "K21.9",
|
||||
"expected_secondary": [],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def generate_sample_pdf(title: str, text: str) -> bytes:
|
||||
"""Generate a clean, multi-page vector PDF in-memory using PyMuPDF."""
|
||||
doc = pymupdf.open()
|
||||
page = doc.new_page()
|
||||
|
||||
# Draw header banner box
|
||||
page.draw_rect(pymupdf.Rect(40, 30, 572, 70), color=(0.1, 0.2, 0.4), fill=(0.92, 0.95, 0.98))
|
||||
page.insert_text(
|
||||
(50, 52),
|
||||
"ELECTRONIC HEALTH RECORD - CLINICAL DOCUMENTATION",
|
||||
fontsize=12,
|
||||
color=(0.1, 0.2, 0.5),
|
||||
)
|
||||
page.insert_text(
|
||||
(50, 64),
|
||||
title.upper(),
|
||||
fontsize=9,
|
||||
color=(0.3, 0.4, 0.5),
|
||||
)
|
||||
|
||||
# Insert document body
|
||||
lines = text.strip().split("\n")
|
||||
y_pos = 90
|
||||
line_height = 14
|
||||
|
||||
for line in lines:
|
||||
if y_pos > 780:
|
||||
page = doc.new_page()
|
||||
y_pos = 50
|
||||
|
||||
is_heading = any(
|
||||
h in line
|
||||
for h in [
|
||||
"DISCHARGE SUMMARY",
|
||||
"CHIEF COMPLAINT:",
|
||||
"HISTORY OF PRESENT ILLNESS:",
|
||||
"HOSPITAL COURSE",
|
||||
"FINAL DIAGNOSIS:",
|
||||
"FINAL DIAGNOSES:",
|
||||
"DISCHARGE DIAGNOSES:",
|
||||
"PERTINENT NEGATIVES:",
|
||||
"ASSESSMENT:",
|
||||
]
|
||||
)
|
||||
|
||||
if is_heading:
|
||||
y_pos += 6
|
||||
page.insert_text((50, y_pos), line, fontsize=10, color=(0.05, 0.15, 0.35))
|
||||
y_pos += line_height + 2
|
||||
else:
|
||||
page.insert_text((50, y_pos), line, fontsize=9, color=(0.15, 0.15, 0.15))
|
||||
y_pos += line_height
|
||||
|
||||
pdf_bytes = doc.write()
|
||||
doc.close()
|
||||
return pdf_bytes
|
||||
|
||||
|
||||
def generate_sample_image(title: str, text: str) -> bytes:
|
||||
"""Generate a clean, high-contrast clinical document screenshot as PNG bytes using PIL."""
|
||||
import io
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
lines = text.strip().split("\n")
|
||||
line_h = 20
|
||||
header_h = 75
|
||||
total_h = max(550, header_h + len(lines) * line_h + 40)
|
||||
width = 820
|
||||
|
||||
img = Image.new("RGB", (width, total_h), color=(255, 255, 255))
|
||||
draw = ImageDraw.Draw(img)
|
||||
|
||||
# Draw header bar
|
||||
draw.rectangle([0, 0, width, header_h], fill=(15, 23, 42))
|
||||
draw.text((25, 18), "HOSPITAL CLINICAL DOCUMENTATION - DISCHARGE RECORD", fill=(56, 189, 248))
|
||||
draw.text((25, 42), title.upper(), fill=(241, 245, 249))
|
||||
|
||||
# Draw body lines
|
||||
y = header_h + 18
|
||||
for line in lines:
|
||||
is_heading = any(
|
||||
h in line
|
||||
for h in (
|
||||
"DISCHARGE SUMMARY",
|
||||
"CHIEF COMPLAINT:",
|
||||
"HISTORY OF PRESENT ILLNESS:",
|
||||
"HOSPITAL COURSE",
|
||||
"FINAL DIAGNOSIS:",
|
||||
"FINAL DIAGNOSES:",
|
||||
"DISCHARGE DIAGNOSES:",
|
||||
"PERTINENT NEGATIVES:",
|
||||
"ASSESSMENT:",
|
||||
)
|
||||
)
|
||||
if is_heading:
|
||||
draw.text((25, y), line, fill=(14, 116, 144))
|
||||
y += line_h + 4
|
||||
else:
|
||||
draw.text((25, y), line, fill=(30, 41, 59))
|
||||
y += line_h
|
||||
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def generate_sample_txt(title: str, text: str) -> bytes:
|
||||
"""Generate a clean UTF-8 encoded plain text clinical note as bytes."""
|
||||
header = f"=== CLINICAL ENCOUNTER: {title.upper()} ===\n\n"
|
||||
full = header + text.strip()
|
||||
return full.encode("utf-8")
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
"""Custom CSS stylesheet and design tokens for the Streamlit clinical interface."""
|
||||
|
||||
CUSTOM_CSS = """
|
||||
<style>
|
||||
/* ------------------------------------------------------------- */
|
||||
/* Modern Clinical AI Design System */
|
||||
/* ------------------------------------------------------------- */
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;700&display=swap');
|
||||
|
||||
html, body, [class*="css"] {
|
||||
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
}
|
||||
|
||||
code, pre, .mono-text {
|
||||
font-family: 'JetBrains Mono', monospace !important;
|
||||
}
|
||||
|
||||
/* Main Container spacing */
|
||||
.block-container {
|
||||
padding-top: 1.8rem;
|
||||
padding-bottom: 3rem;
|
||||
max-width: 1400px;
|
||||
}
|
||||
|
||||
/* Custom Header Banner */
|
||||
.clinic-header {
|
||||
background: linear-gradient(135deg, #091322 0%, #152238 50%, #0c334d 100%);
|
||||
border: 1px solid rgba(56, 189, 248, 0.35);
|
||||
border-radius: 14px;
|
||||
padding: 24px 28px;
|
||||
margin-bottom: 24px;
|
||||
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.35), 0 8px 10px -6px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.clinic-header h1, .clinic-title {
|
||||
font-size: 26px !important;
|
||||
font-weight: 700 !important;
|
||||
color: #ffffff !important;
|
||||
letter-spacing: -0.5px;
|
||||
margin: 0 0 6px 0 !important;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.clinic-subtitle {
|
||||
font-size: 14px !important;
|
||||
color: #e2e8f0 !important;
|
||||
margin: 0 !important;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
|
||||
/* Status Pill Badges */
|
||||
.pill-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 3px 10px;
|
||||
border-radius: 9999px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.3px;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.badge-success {
|
||||
background-color: rgba(16, 185, 129, 0.15);
|
||||
color: #10b981;
|
||||
border: 1px solid rgba(16, 185, 129, 0.3);
|
||||
}
|
||||
|
||||
.badge-warning {
|
||||
background-color: rgba(245, 158, 11, 0.15);
|
||||
color: #f59e0b;
|
||||
border: 1px solid rgba(245, 158, 11, 0.3);
|
||||
}
|
||||
|
||||
.badge-info {
|
||||
background-color: rgba(14, 165, 233, 0.15);
|
||||
color: #38bdf8;
|
||||
border: 1px solid rgba(56, 189, 248, 0.3);
|
||||
}
|
||||
|
||||
.badge-danger {
|
||||
background-color: rgba(239, 68, 68, 0.15);
|
||||
color: #f87171;
|
||||
border: 1px solid rgba(239, 68, 68, 0.3);
|
||||
}
|
||||
|
||||
.badge-secondary {
|
||||
background-color: rgba(148, 163, 184, 0.15);
|
||||
color: #cbd5e1;
|
||||
border: 1px solid rgba(148, 163, 184, 0.3);
|
||||
}
|
||||
|
||||
/* Metric Cards */
|
||||
.kpi-card {
|
||||
background: #1e293b;
|
||||
border: 1px solid #334155;
|
||||
border-radius: 10px;
|
||||
padding: 16px;
|
||||
text-align: center;
|
||||
transition: transform 0.15s ease, border-color 0.15s ease;
|
||||
}
|
||||
|
||||
.kpi-card:hover {
|
||||
border-color: #38bdf8;
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.kpi-value {
|
||||
font-size: 24px !important;
|
||||
font-weight: 700 !important;
|
||||
color: #f1f5f9 !important;
|
||||
margin: 4px 0 !important;
|
||||
}
|
||||
|
||||
.kpi-label {
|
||||
font-size: 11px !important;
|
||||
font-weight: 600 !important;
|
||||
color: #94a3b8 !important;
|
||||
text-transform: uppercase !important;
|
||||
letter-spacing: 0.5px !important;
|
||||
}
|
||||
|
||||
/* Primary Diagnosis Card */
|
||||
.primary-card {
|
||||
background: linear-gradient(180deg, rgba(14, 165, 233, 0.12) 0%, #111e33 100%) !important;
|
||||
border: 1.5px solid rgba(56, 189, 248, 0.6) !important;
|
||||
border-radius: 12px !important;
|
||||
padding: 20px !important;
|
||||
margin: 16px 0 !important;
|
||||
box-shadow: 0 4px 15px -3px rgba(14, 165, 233, 0.25) !important;
|
||||
}
|
||||
|
||||
.primary-card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 12px;
|
||||
border-bottom: 1px solid rgba(56, 189, 248, 0.25);
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
.primary-code {
|
||||
font-size: 26px !important;
|
||||
font-weight: 700 !important;
|
||||
color: #38bdf8 !important;
|
||||
letter-spacing: 0.5px !important;
|
||||
}
|
||||
|
||||
.primary-desc {
|
||||
font-size: 17px !important;
|
||||
font-weight: 600 !important;
|
||||
color: #ffffff !important;
|
||||
margin-bottom: 10px !important;
|
||||
}
|
||||
|
||||
/* Secondary Diagnosis Card */
|
||||
.secondary-card {
|
||||
background: #142032 !important;
|
||||
border: 1px solid #2d3f58 !important;
|
||||
border-radius: 10px !important;
|
||||
padding: 16px !important;
|
||||
margin-bottom: 12px !important;
|
||||
transition: border-color 0.15s ease;
|
||||
}
|
||||
|
||||
.secondary-card:hover {
|
||||
border-color: #38bdf8 !important;
|
||||
}
|
||||
|
||||
/* Evidence Highlight Box */
|
||||
.evidence-box {
|
||||
background: #09121f !important;
|
||||
border-left: 4px solid #10b981 !important;
|
||||
border-radius: 0 8px 8px 0 !important;
|
||||
padding: 10px 14px !important;
|
||||
margin: 10px 0 !important;
|
||||
font-size: 13px !important;
|
||||
color: #e2e8f0 !important;
|
||||
}
|
||||
|
||||
.evidence-quote {
|
||||
font-style: italic !important;
|
||||
color: #a7f3d0 !important;
|
||||
}
|
||||
|
||||
|
||||
/* Abstention Card */
|
||||
.abstention-card {
|
||||
background: rgba(239, 68, 68, 0.05);
|
||||
border: 1px solid rgba(239, 68, 68, 0.2);
|
||||
border-left: 4px solid #ef4444;
|
||||
border-radius: 0 8px 8px 0;
|
||||
padding: 12px 16px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
/* Verification Checklist */
|
||||
.audit-check-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 13px;
|
||||
margin-bottom: 6px;
|
||||
color: #cbd5e1;
|
||||
}
|
||||
|
||||
.check-pass {
|
||||
color: #10b981;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.check-fail {
|
||||
color: #ef4444;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* PDF Page Card */
|
||||
.pdf-page-card {
|
||||
background: #0f172a;
|
||||
border: 1px solid #334155;
|
||||
border-radius: 8px;
|
||||
padding: 14px;
|
||||
margin-bottom: 12px;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
max-height: 250px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
/* Multimodal Ingestion Styling */
|
||||
.modality-card {
|
||||
background: linear-gradient(135deg, #132238 0%, #1a2f4c 100%);
|
||||
border: 1px solid rgba(56, 189, 248, 0.4);
|
||||
border-radius: 10px;
|
||||
padding: 14px 18px;
|
||||
margin-bottom: 16px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.modality-badge-pdf {
|
||||
background: rgba(239, 68, 68, 0.15);
|
||||
color: #f87171;
|
||||
border: 1px solid rgba(239, 68, 68, 0.35);
|
||||
padding: 3px 10px;
|
||||
border-radius: 9999px;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.modality-badge-image {
|
||||
background: rgba(168, 85, 247, 0.15);
|
||||
color: #c084fc;
|
||||
border: 1px solid rgba(168, 85, 247, 0.35);
|
||||
padding: 3px 10px;
|
||||
border-radius: 9999px;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.modality-badge-txt {
|
||||
background: rgba(16, 185, 129, 0.15);
|
||||
color: #34d399;
|
||||
border: 1px solid rgba(16, 185, 129, 0.35);
|
||||
padding: 3px 10px;
|
||||
border-radius: 9999px;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.modality-badge-manual {
|
||||
background: rgba(245, 158, 11, 0.15);
|
||||
color: #fbbf24;
|
||||
border: 1px solid rgba(245, 158, 11, 0.35);
|
||||
padding: 3px 10px;
|
||||
border-radius: 9999px;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.section-chip {
|
||||
display: inline-block;
|
||||
background: #0f172a;
|
||||
color: #38bdf8;
|
||||
border: 1px solid #334155;
|
||||
border-radius: 6px;
|
||||
padding: 2px 8px;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
margin-right: 6px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
</style>
|
||||
"""
|
||||
|
||||
|
||||
def get_css() -> str:
|
||||
"""Return the custom CSS snippet."""
|
||||
return CUSTOM_CSS
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Utility exports."""
|
||||
|
||||
from medical_coding.utils.logging import configure_logging, get_logger
|
||||
from medical_coding.utils.text import (
|
||||
find_verbatim_span,
|
||||
format_icd_code,
|
||||
normalize_whitespace,
|
||||
unformat_icd_code,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"configure_logging",
|
||||
"find_verbatim_span",
|
||||
"format_icd_code",
|
||||
"get_logger",
|
||||
"normalize_whitespace",
|
||||
"unformat_icd_code",
|
||||
]
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Logging configuration and structured logger utilities."""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
|
||||
|
||||
def configure_logging(settings: Settings | None = None) -> None:
|
||||
"""Configure root logger format and level based on application settings."""
|
||||
cfg = settings or get_settings()
|
||||
|
||||
log_format = "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
|
||||
date_format = "%Y-%m-%d %H:%M:%S"
|
||||
|
||||
level = getattr(logging, cfg.log_level, logging.INFO)
|
||||
|
||||
root = logging.getLogger()
|
||||
if not root.handlers:
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(logging.Formatter(fmt=log_format, datefmt=date_format))
|
||||
root.addHandler(handler)
|
||||
root.setLevel(level)
|
||||
|
||||
|
||||
def get_logger(name: str) -> logging.Logger:
|
||||
"""Return a named logger instance."""
|
||||
return logging.getLogger(name)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Text processing, span extraction, and ICD string normalization utilities."""
|
||||
|
||||
import re
|
||||
|
||||
|
||||
def normalize_whitespace(text: str) -> str:
|
||||
"""Collapse contiguous whitespace sequences into single spaces."""
|
||||
return re.sub(r"[ \t]+", " ", text).strip()
|
||||
|
||||
|
||||
def find_verbatim_span(full_text: str, quote: str) -> tuple[int, int] | None:
|
||||
"""Locate the exact character span [start, end) of quote in full_text.
|
||||
|
||||
Returns:
|
||||
(start_char, end_char) tuple if found, otherwise None.
|
||||
"""
|
||||
if not quote or not full_text:
|
||||
return None
|
||||
start = full_text.find(quote)
|
||||
if start != -1:
|
||||
return (start, start + len(quote))
|
||||
|
||||
# Case-insensitive fallback
|
||||
lower_full = full_text.lower()
|
||||
lower_quote = quote.lower()
|
||||
start = lower_full.find(lower_quote)
|
||||
if start != -1:
|
||||
return (start, start + len(quote))
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def format_icd_code(raw_code: str) -> str:
|
||||
"""Format alphanumeric ICD code with standard decimal (e.g. 'I5021' -> 'I50.21').
|
||||
|
||||
Standard ICD-10-CM codes place a decimal point after the first 3 characters.
|
||||
"""
|
||||
clean = re.sub(r"[^A-Za-z0-9]", "", raw_code).upper()
|
||||
if len(clean) > 3 and "." not in clean:
|
||||
return f"{clean[:3]}.{clean[3:]}"
|
||||
return clean
|
||||
|
||||
|
||||
def unformat_icd_code(formatted_code: str) -> str:
|
||||
"""Strip punctuation and whitespace from an ICD code (e.g. 'I50.21' -> 'I5021')."""
|
||||
return re.sub(r"[^A-Za-z0-9]", "", formatted_code).upper()
|
||||
|
||||
|
||||
def is_valid_icd_format(code: str) -> bool:
|
||||
"""Check whether a code adheres to the standard ICD-10-CM structural pattern.
|
||||
|
||||
ICD-10-CM codes start with a letter, followed by a digit and 1 to 5 alphanumeric chars
|
||||
(with an optional decimal point after the 3rd character).
|
||||
"""
|
||||
if not code:
|
||||
return False
|
||||
clean = unformat_icd_code(code)
|
||||
if len(clean) < 3 or len(clean) > 7:
|
||||
return False
|
||||
# First char must be a letter, second must be a digit, followed by alphanumeric
|
||||
return bool(re.match(r"^[A-Z][0-9][0-9A-Z]{1,5}$", clean))
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Validation exports."""
|
||||
|
||||
from medical_coding.validation.abstention import AbstentionEngine
|
||||
from medical_coding.validation.deterministic import (
|
||||
DeterministicValidator,
|
||||
MultiplePrimaryDiagnosesError,
|
||||
PrimarySecondaryClassificationValidator,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AbstentionEngine",
|
||||
"DeterministicValidator",
|
||||
"MultiplePrimaryDiagnosesError",
|
||||
"PrimarySecondaryClassificationValidator",
|
||||
]
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Abstention decision engine and audit tracking."""
|
||||
|
||||
from medical_coding.schemas.enums import AbstentionReason, PipelineStage
|
||||
from medical_coding.schemas.validation import AbstentionRecord
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class AbstentionEngine:
|
||||
"""Manages criteria for abstaining from coding decisions when evidence is insufficient."""
|
||||
|
||||
def __init__(self, min_confidence_threshold: float = 0.40) -> None:
|
||||
self.min_confidence_threshold = min_confidence_threshold
|
||||
|
||||
def create_record(
|
||||
self,
|
||||
reason: AbstentionReason,
|
||||
detail: str,
|
||||
stage: PipelineStage,
|
||||
diagnosis_id: str | None = None,
|
||||
raw_term: str | None = None,
|
||||
) -> AbstentionRecord:
|
||||
"""Construct an auditable abstention record."""
|
||||
record = AbstentionRecord(
|
||||
diagnosis_id=diagnosis_id,
|
||||
raw_term=raw_term,
|
||||
reason=reason,
|
||||
detail=detail,
|
||||
stage=stage,
|
||||
)
|
||||
logger.info(
|
||||
"Abstention triggered at [%s] for term '%s': %s (%s)",
|
||||
stage.value,
|
||||
raw_term or "document",
|
||||
reason.value,
|
||||
detail,
|
||||
)
|
||||
return record
|
||||
|
||||
def should_abstain_on_confidence(self, score: float) -> bool:
|
||||
"""Return True if confidence score falls below minimum threshold."""
|
||||
return score < self.min_confidence_threshold
|
||||
@@ -0,0 +1,751 @@
|
||||
import re
|
||||
|
||||
from medical_coding.dataset.validator import LocalICDCatalog
|
||||
from medical_coding.schemas.clinical import (
|
||||
ClassifiedDiagnosis,
|
||||
ConditionClassification,
|
||||
ContextAssessment,
|
||||
EncounterClassificationResult,
|
||||
)
|
||||
from medical_coding.schemas.enums import (
|
||||
AbstentionReason,
|
||||
Certainty,
|
||||
ConditionStatus,
|
||||
DiagnosisRole,
|
||||
NegationStatus,
|
||||
PipelineStage,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.schemas.icd import ICDCandidate, RankedSelection
|
||||
from medical_coding.schemas.validation import (
|
||||
AbstentionRecord,
|
||||
ValidatedDiagnosis,
|
||||
ValidationCheck,
|
||||
)
|
||||
from medical_coding.utils.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class DeterministicValidator:
|
||||
"""Non-LLM deterministic rule engine verifying selected codes against local dataset catalog."""
|
||||
|
||||
def __init__(self, catalog: LocalICDCatalog) -> None:
|
||||
self.catalog = catalog
|
||||
|
||||
def validate_code(
|
||||
self,
|
||||
condition: ClassifiedDiagnosis,
|
||||
selection: RankedSelection,
|
||||
) -> tuple[ValidatedDiagnosis | None, AbstentionRecord | None]:
|
||||
"""Perform deterministic validation checks on an individual candidate selection.
|
||||
|
||||
Checks:
|
||||
1. Code selection present (not None/abstained).
|
||||
2. Catalog existence in local dataset.
|
||||
3. Terminal specificity / billable status.
|
||||
4. Minimum confidence threshold.
|
||||
|
||||
Returns:
|
||||
(ValidatedDiagnosis, None) if all checks pass,
|
||||
(None, AbstentionRecord) if any rule check fails.
|
||||
"""
|
||||
if selection.selected_candidate is None:
|
||||
return None, AbstentionRecord(
|
||||
diagnosis_id=condition.diagnosis_id,
|
||||
raw_term=condition.raw_term,
|
||||
reason=AbstentionReason.NO_MATCHING_ICD_CANDIDATE,
|
||||
detail=selection.selection_justification or "No candidate selected.",
|
||||
stage=PipelineStage.RANKING,
|
||||
)
|
||||
|
||||
candidate = selection.selected_candidate
|
||||
code = candidate.code
|
||||
checks: list[ValidationCheck] = []
|
||||
|
||||
# 1. Catalog Existence Check
|
||||
exists = self.catalog.is_valid_code(code)
|
||||
checks.append(
|
||||
ValidationCheck(
|
||||
rule_name="CatalogExistence",
|
||||
passed=exists,
|
||||
details=f"Code '{code}' exists in local authoritative catalog."
|
||||
if exists
|
||||
else f"Code '{code}' does not exist in local dataset.",
|
||||
)
|
||||
)
|
||||
if not exists:
|
||||
return None, AbstentionRecord(
|
||||
diagnosis_id=condition.diagnosis_id,
|
||||
raw_term=condition.raw_term,
|
||||
reason=AbstentionReason.INVALID_ICD_CODE,
|
||||
detail=f"Proposed code '{code}' does not exist in authoritative local dataset.",
|
||||
stage=PipelineStage.VALIDATION,
|
||||
)
|
||||
|
||||
# 2. Terminal Specificity Check (HIPAA Billability)
|
||||
billable = self.catalog.is_billable_code(code)
|
||||
checks.append(
|
||||
ValidationCheck(
|
||||
rule_name="TerminalSpecificity",
|
||||
passed=billable,
|
||||
details=f"Code '{code}' is at terminal billable specificity."
|
||||
if billable
|
||||
else f"Code '{code}' requires additional characters/specificity.",
|
||||
)
|
||||
)
|
||||
if not billable:
|
||||
return None, AbstentionRecord(
|
||||
diagnosis_id=condition.diagnosis_id,
|
||||
raw_term=condition.raw_term,
|
||||
reason=AbstentionReason.SPECIFICITY_REQUIRED,
|
||||
detail=f"Code '{code}' is a non-billable category header; terminal leaf code required.",
|
||||
stage=PipelineStage.VALIDATION,
|
||||
)
|
||||
|
||||
validated = ValidatedDiagnosis(
|
||||
diagnosis_id=condition.diagnosis_id,
|
||||
raw_term=condition.raw_term,
|
||||
code=code,
|
||||
description=candidate.description,
|
||||
role=condition.role,
|
||||
evidence=condition.context.evidence,
|
||||
confidence_score=selection.ranking_score,
|
||||
checks=checks,
|
||||
)
|
||||
return validated, None
|
||||
|
||||
def validate_encounter_set(
|
||||
self,
|
||||
conditions: list[ClassifiedDiagnosis],
|
||||
selections: list[RankedSelection],
|
||||
) -> tuple[list[ValidatedDiagnosis], list[AbstentionRecord]]:
|
||||
"""Validate entire document set of selections enforcing encounter-level invariants:
|
||||
|
||||
1. Maximum ONE Primary Diagnosis.
|
||||
2. No Excludes1 conflicts among co-billed codes.
|
||||
"""
|
||||
validated_list: list[ValidatedDiagnosis] = []
|
||||
abstention_list: list[AbstentionRecord] = []
|
||||
|
||||
selection_map = {s.diagnosis_id: s for s in selections}
|
||||
|
||||
for cond in conditions:
|
||||
if not cond.is_billable_candidate or cond.role == DiagnosisRole.EXCLUDED:
|
||||
abstention_list.append(
|
||||
AbstentionRecord(
|
||||
diagnosis_id=cond.diagnosis_id,
|
||||
raw_term=cond.raw_term,
|
||||
reason=AbstentionReason.EXCLUDED_BY_TEMPORALITY
|
||||
if "historical" in cond.classification_reason.lower()
|
||||
else AbstentionReason.EXCLUDED_BY_NEGATION,
|
||||
detail=cond.classification_reason,
|
||||
stage=PipelineStage.CLASSIFICATION,
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
sel = selection_map.get(cond.diagnosis_id)
|
||||
if not sel:
|
||||
continue
|
||||
|
||||
val, abst = self.validate_code(cond, sel)
|
||||
if val:
|
||||
validated_list.append(val)
|
||||
if abst:
|
||||
abstention_list.append(abst)
|
||||
|
||||
# Invariant: Maximum ONE Primary Diagnosis
|
||||
primaries = [v for v in validated_list if v.role == DiagnosisRole.PRIMARY]
|
||||
if len(primaries) > 1:
|
||||
logger.warning(
|
||||
"Multiple primary diagnoses detected (%d). Abstaining all primaries to prevent invalid billing.",
|
||||
len(primaries),
|
||||
)
|
||||
for prim in primaries:
|
||||
validated_list.remove(prim)
|
||||
abstention_list.append(
|
||||
AbstentionRecord(
|
||||
diagnosis_id=prim.diagnosis_id,
|
||||
raw_term=prim.raw_term,
|
||||
reason=AbstentionReason.MULTIPLE_AMBIGUOUS_PRIMARY,
|
||||
detail="Conflicting multiple primary diagnoses assigned; guidelines permit max ONE.",
|
||||
stage=PipelineStage.VALIDATION,
|
||||
)
|
||||
)
|
||||
|
||||
# Invariant: Excludes1 Check across co-occurring validated codes
|
||||
for i, val_a in enumerate(validated_list):
|
||||
for val_b in validated_list[i + 1 :]:
|
||||
if self.catalog.check_excludes1(val_a.code, val_b.code):
|
||||
abstention_list.append(
|
||||
AbstentionRecord(
|
||||
diagnosis_id=val_b.diagnosis_id,
|
||||
raw_term=val_b.raw_term,
|
||||
reason=AbstentionReason.EXCLUDES_1_VIOLATION,
|
||||
detail=f"Excludes1 violation between '{val_a.code}' and '{val_b.code}'.",
|
||||
stage=PipelineStage.VALIDATION,
|
||||
)
|
||||
)
|
||||
|
||||
return validated_list, abstention_list
|
||||
|
||||
|
||||
class MultiplePrimaryDiagnosesError(ValueError):
|
||||
"""Raised when an encounter classification contains more than one primary diagnosis."""
|
||||
|
||||
|
||||
class PrimarySecondaryClassificationValidator:
|
||||
"""Deterministic validation engine for Primary vs Secondary diagnosis classification.
|
||||
|
||||
CRITICAL HARD RULES ENFORCED DETERMINISTICALLY:
|
||||
1. Maximum ONE primary diagnosis per encounter.
|
||||
2. Multiple primary diagnoses strictly trigger rejection / abstention with MULTIPLE_AMBIGUOUS_PRIMARY.
|
||||
3. Primary diagnosis CANNOT be historical-only, ruled out, negated, or unmanaged.
|
||||
4. Secondary diagnoses must be actively managed, monitored, or clinically relevant during the admission.
|
||||
5. Historical-only conditions without inpatient care must be EXCLUDED.
|
||||
"""
|
||||
|
||||
def validate_or_raise(
|
||||
self,
|
||||
classifications: list[ConditionClassification] | list[ClassifiedDiagnosis],
|
||||
) -> None:
|
||||
"""Validate classifications and raise MultiplePrimaryDiagnosesError if more than one primary diagnosis exists."""
|
||||
primaries = [
|
||||
c.diagnosis if isinstance(c, ConditionClassification) else c.raw_term
|
||||
for c in classifications
|
||||
if c.role == DiagnosisRole.PRIMARY
|
||||
]
|
||||
if len(primaries) > 1:
|
||||
raise MultiplePrimaryDiagnosesError(
|
||||
f"Multiple primary diagnoses detected ({len(primaries)}): {primaries}. "
|
||||
"Inpatient coding guidelines strictly permit at most ONE primary diagnosis."
|
||||
)
|
||||
|
||||
def validate_classification(
|
||||
self,
|
||||
classifications: list[ConditionClassification],
|
||||
context_assessments: list[ContextAssessment] | None = None,
|
||||
document_id: str | None = None,
|
||||
) -> tuple[EncounterClassificationResult, list[AbstentionRecord]]:
|
||||
"""Perform comprehensive deterministic validation on classification output.
|
||||
|
||||
Enforces:
|
||||
- Maximum ONE primary diagnosis (demoting/abstaining if multiple found)
|
||||
- Ineligibility of historical, ruled-out, or negated conditions as primary or secondary
|
||||
- Proper exclusion of unmanaged PMH
|
||||
"""
|
||||
audit_notes: list[str] = []
|
||||
abstentions: list[AbstentionRecord] = []
|
||||
ctx_map: dict[str, ContextAssessment] = {
|
||||
asm.condition_id or asm.diagnosis.lower(): asm for asm in (context_assessments or [])
|
||||
}
|
||||
|
||||
validated_classifications: list[ConditionClassification] = []
|
||||
|
||||
# 1. Inspect and validate each condition
|
||||
for cond_in in classifications:
|
||||
cond = cond_in.model_copy()
|
||||
ctx = ctx_map.get(cond.diagnosis_id) or ctx_map.get(cond.diagnosis.lower())
|
||||
|
||||
# Rule: Ruled-out or negated conditions CANNOT be PRIMARY or SECONDARY
|
||||
is_ruled_out_or_negated = False
|
||||
if ctx:
|
||||
if ctx.certainty == Certainty.RULED_OUT or ctx.negation == NegationStatus.NEGATED:
|
||||
is_ruled_out_or_negated = True
|
||||
elif (
|
||||
"ruled out" in cond.classification_reason.lower()
|
||||
or "negated" in cond.classification_reason.lower()
|
||||
):
|
||||
is_ruled_out_or_negated = True
|
||||
|
||||
if is_ruled_out_or_negated and cond.role != DiagnosisRole.EXCLUDED:
|
||||
audit_notes.append(
|
||||
f"Deterministic override: Condition '{cond.diagnosis}' was marked {cond.role.value} "
|
||||
"but is ruled out/negated. Forcing to EXCLUDED."
|
||||
)
|
||||
cond.role = DiagnosisRole.EXCLUDED
|
||||
cond.is_billable_candidate = False
|
||||
cond.classification_reason = f"Ruled out / negated condition excluded from coding: {cond.classification_reason}"
|
||||
abstentions.append(
|
||||
AbstentionRecord(
|
||||
diagnosis_id=cond.diagnosis_id,
|
||||
raw_term=cond.diagnosis,
|
||||
reason=AbstentionReason.EXCLUDED_BY_NEGATION,
|
||||
detail=cond.classification_reason,
|
||||
stage=PipelineStage.CLASSIFICATION,
|
||||
)
|
||||
)
|
||||
|
||||
# Rule: Historical-only conditions without inpatient care CANNOT be PRIMARY or SECONDARY
|
||||
is_historical_only = False
|
||||
if ctx:
|
||||
if (
|
||||
ctx.status == ConditionStatus.HISTORICAL
|
||||
or ctx.temporality == Temporality.HISTORICAL
|
||||
):
|
||||
if not (
|
||||
ctx.treated_or_managed
|
||||
or ctx.monitored
|
||||
or ctx.affected_clinical_management
|
||||
or ctx.influenced_treatment
|
||||
):
|
||||
is_historical_only = True
|
||||
elif (
|
||||
"historical" in cond.classification_reason.lower()
|
||||
and "active" not in cond.classification_reason.lower()
|
||||
):
|
||||
is_historical_only = True
|
||||
|
||||
if is_historical_only and cond.role != DiagnosisRole.EXCLUDED:
|
||||
audit_notes.append(
|
||||
f"Deterministic override: Condition '{cond.diagnosis}' was marked {cond.role.value} "
|
||||
"but is historical without inpatient care. Forcing to EXCLUDED."
|
||||
)
|
||||
cond.role = DiagnosisRole.EXCLUDED
|
||||
cond.is_billable_candidate = False
|
||||
cond.classification_reason = f"Historical condition without active inpatient care excluded: {cond.classification_reason}"
|
||||
abstentions.append(
|
||||
AbstentionRecord(
|
||||
diagnosis_id=cond.diagnosis_id,
|
||||
raw_term=cond.diagnosis,
|
||||
reason=AbstentionReason.EXCLUDED_BY_TEMPORALITY,
|
||||
detail=cond.classification_reason,
|
||||
stage=PipelineStage.CLASSIFICATION,
|
||||
)
|
||||
)
|
||||
|
||||
# If role is EXCLUDED, ensure is_billable_candidate is False
|
||||
if cond.role == DiagnosisRole.EXCLUDED:
|
||||
cond.is_billable_candidate = False
|
||||
|
||||
validated_classifications.append(cond)
|
||||
|
||||
# 2. Hard Rule: Maximum ONE Primary Diagnosis
|
||||
primaries = [c for c in validated_classifications if c.role == DiagnosisRole.PRIMARY]
|
||||
has_unique_primary = False
|
||||
is_ambiguous_primary = False
|
||||
abstention_recommended = False
|
||||
abstention_reason: AbstentionReason | None = None
|
||||
unique_primary: ConditionClassification | None = None
|
||||
|
||||
if len(primaries) > 1:
|
||||
audit_notes.append(
|
||||
f"REJECTION: Multiple primary diagnoses detected ({len(primaries)}): "
|
||||
f"{[p.diagnosis for p in primaries]}. UHDDS guidelines permit at most ONE. "
|
||||
"Demoting conflicting primaries to abstained to prevent invalid billing."
|
||||
)
|
||||
is_ambiguous_primary = True
|
||||
abstention_recommended = True
|
||||
abstention_reason = AbstentionReason.MULTIPLE_AMBIGUOUS_PRIMARY
|
||||
|
||||
demoted: list[ConditionClassification] = []
|
||||
for p in validated_classifications:
|
||||
if p.role == DiagnosisRole.PRIMARY:
|
||||
abstentions.append(
|
||||
AbstentionRecord(
|
||||
diagnosis_id=p.diagnosis_id,
|
||||
raw_term=p.diagnosis,
|
||||
reason=AbstentionReason.MULTIPLE_AMBIGUOUS_PRIMARY,
|
||||
detail=f"Multiple conflicting primary diagnoses: '{p.diagnosis}' competed with other primary diagnoses.",
|
||||
stage=PipelineStage.CLASSIFICATION,
|
||||
)
|
||||
)
|
||||
demoted.append(
|
||||
p.model_copy(
|
||||
update={
|
||||
"role": DiagnosisRole.EXCLUDED,
|
||||
"is_billable_candidate": False,
|
||||
"classification_reason": (
|
||||
f"Conflicting primary diagnosis: '{p.diagnosis}' competed with other primary candidates. "
|
||||
"Abstained due to ambiguity without physician query."
|
||||
),
|
||||
}
|
||||
)
|
||||
)
|
||||
else:
|
||||
demoted.append(p)
|
||||
validated_classifications = demoted
|
||||
elif len(primaries) == 1:
|
||||
unique_primary = primaries[0]
|
||||
has_unique_primary = True
|
||||
else:
|
||||
# Zero primaries
|
||||
ambiguous_candidates = [
|
||||
c
|
||||
for c in validated_classifications
|
||||
if "ambiguous" in c.classification_reason.lower()
|
||||
or "co-primary" in c.classification_reason.lower()
|
||||
]
|
||||
if ambiguous_candidates:
|
||||
audit_notes.append(
|
||||
f"Two or more plausible primary diagnoses ({len(ambiguous_candidates)}) detected without documentary distinction."
|
||||
)
|
||||
is_ambiguous_primary = True
|
||||
abstention_recommended = True
|
||||
abstention_reason = AbstentionReason.MULTIPLE_AMBIGUOUS_PRIMARY
|
||||
for amb in ambiguous_candidates:
|
||||
abstentions.append(
|
||||
AbstentionRecord(
|
||||
diagnosis_id=amb.diagnosis_id,
|
||||
raw_term=amb.diagnosis,
|
||||
reason=AbstentionReason.MULTIPLE_AMBIGUOUS_PRIMARY,
|
||||
detail=f"Ambiguous co-primary diagnosis: '{amb.diagnosis}' competed with other plausible primaries.",
|
||||
stage=PipelineStage.CLASSIFICATION,
|
||||
)
|
||||
)
|
||||
else:
|
||||
has_billable_secondaries = any(
|
||||
c.role == DiagnosisRole.SECONDARY for c in validated_classifications
|
||||
)
|
||||
if has_billable_secondaries:
|
||||
audit_notes.append(
|
||||
"No defensible primary diagnosis identified despite active secondary conditions."
|
||||
)
|
||||
abstention_recommended = True
|
||||
abstention_reason = AbstentionReason.INSUFFICIENT_CLINICAL_EVIDENCE
|
||||
abstentions.append(
|
||||
AbstentionRecord(
|
||||
diagnosis_id=None,
|
||||
raw_term=None,
|
||||
reason=AbstentionReason.INSUFFICIENT_CLINICAL_EVIDENCE,
|
||||
detail="No defensible primary diagnosis identified for the encounter.",
|
||||
stage=PipelineStage.CLASSIFICATION,
|
||||
)
|
||||
)
|
||||
|
||||
secondaries = [c for c in validated_classifications if c.role == DiagnosisRole.SECONDARY]
|
||||
excluded = [c for c in validated_classifications if c.role == DiagnosisRole.EXCLUDED]
|
||||
|
||||
result = EncounterClassificationResult(
|
||||
document_id=document_id,
|
||||
primary_diagnosis=unique_primary,
|
||||
secondary_diagnoses=secondaries,
|
||||
excluded_conditions=excluded,
|
||||
all_classifications=validated_classifications,
|
||||
has_unique_primary=has_unique_primary,
|
||||
is_ambiguous_primary=is_ambiguous_primary,
|
||||
abstention_recommended=abstention_recommended,
|
||||
abstention_reason=abstention_reason,
|
||||
audit_notes=audit_notes,
|
||||
)
|
||||
|
||||
return result, abstentions
|
||||
|
||||
|
||||
class CandidateRankingDeterministicValidator:
|
||||
"""Non-LLM deterministic validator verifying candidate ranking decisions against strict invariants.
|
||||
|
||||
HARD CONSTRAINTS ENFORCED:
|
||||
1. Candidate Pool Boundary: selected_code MUST be an element of the supplied candidate pool.
|
||||
Free-form or hallucinated codes are strictly rejected without guessing.
|
||||
2. Evidence Presence: Code cannot be selected without documented evidence text.
|
||||
3. Specificity Verification: Prevents inferring clinical specificity that is absent from evidence.
|
||||
(e.g., systolic/diastolic heart failure without documented systolic/diastolic proof;
|
||||
diabetic complications without documented complication proof).
|
||||
4. Confidence Threshold: Enforces minimum acceptable confidence score.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
catalog: LocalICDCatalog | None = None,
|
||||
min_confidence: float = 0.40,
|
||||
) -> None:
|
||||
self.catalog = catalog
|
||||
self.min_confidence = min_confidence
|
||||
|
||||
def validate_ranking_selection(
|
||||
self,
|
||||
selection: RankedSelection,
|
||||
candidates: list[ICDCandidate],
|
||||
evidence_text: str = "",
|
||||
diagnosis_term: str = "",
|
||||
) -> RankedSelection:
|
||||
"""Validate and sanitize a candidate ranking selection against hard constraints."""
|
||||
from medical_coding.utils.text import format_icd_code
|
||||
|
||||
clean_evidence = (evidence_text or "").strip()
|
||||
clean_diagnosis = (diagnosis_term or "").strip()
|
||||
|
||||
# 1. No candidates available -> Clean abstention
|
||||
if not candidates:
|
||||
return RankedSelection(
|
||||
diagnosis_id=selection.diagnosis_id,
|
||||
raw_term=selection.raw_term or clean_diagnosis,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
selected_candidate=None,
|
||||
ranking_reason="Candidate pool was empty; no matching local ICD code.",
|
||||
supporting_evidence=[clean_evidence] if clean_evidence else [],
|
||||
confidence=0.0,
|
||||
abstention_reason="NO_CANDIDATES",
|
||||
candidate_pool=[],
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
|
||||
# 2. Missing evidence -> Clean abstention
|
||||
if not clean_evidence:
|
||||
return RankedSelection(
|
||||
diagnosis_id=selection.diagnosis_id,
|
||||
raw_term=selection.raw_term or clean_diagnosis,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
selected_candidate=None,
|
||||
ranking_reason="Insufficient evidence: documentation lacks factual evidence quote.",
|
||||
supporting_evidence=[],
|
||||
confidence=0.0,
|
||||
abstention_reason="INSUFFICIENT_EVIDENCE",
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
|
||||
# 3. If selection is already abstained or null
|
||||
if selection.selected_code is None:
|
||||
return RankedSelection(
|
||||
diagnosis_id=selection.diagnosis_id,
|
||||
raw_term=selection.raw_term or clean_diagnosis,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
selected_candidate=None,
|
||||
ranking_reason=selection.ranking_reason or "No candidate selected.",
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=0.0,
|
||||
abstention_reason=selection.abstention_reason or "NO_MATCHING_CANDIDATE",
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
|
||||
# 4. HARD CONSTRAINT: selected_code MUST exist in the candidate list
|
||||
cand_map: dict[str, ICDCandidate] = {format_icd_code(c.code): c for c in candidates}
|
||||
formatted_sel = format_icd_code(selection.selected_code)
|
||||
|
||||
if formatted_sel not in cand_map:
|
||||
logger.warning(
|
||||
"HARD CONSTRAINT VIOLATION: Proposed code '%s' does not exist in candidate pool %s. Rejecting.",
|
||||
selection.selected_code,
|
||||
[c.code for c in candidates],
|
||||
)
|
||||
return RankedSelection(
|
||||
diagnosis_id=selection.diagnosis_id,
|
||||
raw_term=selection.raw_term or clean_diagnosis,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
selected_candidate=None,
|
||||
ranking_reason=f"Deterministic rejection: Proposed code '{selection.selected_code}' is not in the authoritative candidate pool {[c.code for c in candidates]}.",
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=0.0,
|
||||
abstention_reason="INVALID_LLM_CODE_NOT_IN_CANDIDATE_POOL",
|
||||
candidate_pool=candidates,
|
||||
decision="REJECTED_MISMATCH",
|
||||
)
|
||||
|
||||
matching_candidate = cand_map[formatted_sel]
|
||||
|
||||
# 5. Local catalog existence check
|
||||
if self.catalog and not self.catalog.is_valid_code(matching_candidate.code):
|
||||
return RankedSelection(
|
||||
diagnosis_id=selection.diagnosis_id,
|
||||
raw_term=selection.raw_term or clean_diagnosis,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
selected_candidate=None,
|
||||
ranking_reason=f"Code '{matching_candidate.code}' does not exist in local authoritative catalog.",
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=0.0,
|
||||
abstention_reason="INVALID_ICD_CODE",
|
||||
candidate_pool=candidates,
|
||||
decision="REJECTED_MISMATCH",
|
||||
)
|
||||
|
||||
# 6. Specificity Support Check (Anti-Hallucinated Specificity)
|
||||
evidence_lower = f"{clean_evidence} {clean_diagnosis}".lower()
|
||||
cand_desc_lower = matching_candidate.description.lower()
|
||||
|
||||
# Heart failure specific subtypes: systolic vs diastolic
|
||||
has_systolic_in_cand = "systolic" in cand_desc_lower
|
||||
has_diastolic_in_cand = "diastolic" in cand_desc_lower
|
||||
has_systolic_in_ev = any(
|
||||
w in evidence_lower
|
||||
for w in ["systolic", "hfref", "reduced ejection", "systolic dysfunction"]
|
||||
)
|
||||
has_diastolic_in_ev = any(
|
||||
w in evidence_lower
|
||||
for w in ["diastolic", "hfpef", "preserved ejection", "diastolic dysfunction"]
|
||||
)
|
||||
|
||||
if has_systolic_in_cand and not has_systolic_in_ev:
|
||||
# Check for supported unspecified candidate in pool
|
||||
gen_cand = next(
|
||||
(
|
||||
c
|
||||
for c in candidates
|
||||
if "unspecified" in c.description.lower() or c.code in ["I50.9", "I50"]
|
||||
),
|
||||
None,
|
||||
)
|
||||
if gen_cand and gen_cand.is_valid_billable:
|
||||
matching_candidate = gen_cand
|
||||
selection.ranking_reason = (
|
||||
f"Specificity realigned: Documentation supports general heart failure without systolic specificity; "
|
||||
f"selected unspecified code {gen_cand.code}."
|
||||
)
|
||||
else:
|
||||
return RankedSelection(
|
||||
diagnosis_id=selection.diagnosis_id,
|
||||
raw_term=selection.raw_term or clean_diagnosis,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
selected_candidate=None,
|
||||
ranking_reason=(
|
||||
f"Unsupported specificity: Candidate '{matching_candidate.code}' specifies systolic heart failure, "
|
||||
"but documentation only supports general heart failure."
|
||||
),
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=0.0,
|
||||
abstention_reason="UNSUPPORTED_SPECIFICITY",
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
|
||||
if has_diastolic_in_cand and not has_diastolic_in_ev:
|
||||
gen_cand = next(
|
||||
(
|
||||
c
|
||||
for c in candidates
|
||||
if "unspecified" in c.description.lower() or c.code in ["I50.9", "I50"]
|
||||
),
|
||||
None,
|
||||
)
|
||||
if gen_cand and gen_cand.is_valid_billable:
|
||||
matching_candidate = gen_cand
|
||||
selection.ranking_reason = (
|
||||
f"Specificity realigned: Documentation supports general heart failure without diastolic specificity; "
|
||||
f"selected unspecified code {gen_cand.code}."
|
||||
)
|
||||
else:
|
||||
return RankedSelection(
|
||||
diagnosis_id=selection.diagnosis_id,
|
||||
raw_term=selection.raw_term or clean_diagnosis,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
selected_candidate=None,
|
||||
ranking_reason=(
|
||||
f"Unsupported specificity: Candidate '{matching_candidate.code}' specifies diastolic heart failure, "
|
||||
"but documentation only supports general heart failure."
|
||||
),
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=0.0,
|
||||
abstention_reason="UNSUPPORTED_SPECIFICITY",
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
|
||||
# Diabetes complications specificity check
|
||||
comp_keywords = [
|
||||
"nephropathy",
|
||||
"retinopathy",
|
||||
"neuropathy",
|
||||
"hyperglycemia",
|
||||
"ketoacidosis",
|
||||
]
|
||||
is_diabetic_comp_cand = any(comp in cand_desc_lower for comp in comp_keywords)
|
||||
has_comp_in_ev = any(
|
||||
comp in evidence_lower
|
||||
for comp in [
|
||||
"nephropathy",
|
||||
"kidney disease",
|
||||
"retinopathy",
|
||||
"neuropathy",
|
||||
"hyperglycemia",
|
||||
"ketoacidosis",
|
||||
"dka",
|
||||
"uncontrolled",
|
||||
]
|
||||
)
|
||||
|
||||
if is_diabetic_comp_cand and not has_comp_in_ev:
|
||||
uncomp_cand = next(
|
||||
(
|
||||
c
|
||||
for c in candidates
|
||||
if "without complications" in c.description.lower() or c.code == "E11.9"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if uncomp_cand:
|
||||
matching_candidate = uncomp_cand
|
||||
selection.ranking_reason = (
|
||||
f"Specificity realigned: Documentation lacks evidence of diabetic complications; "
|
||||
f"selected uncomplicated code {uncomp_cand.code}."
|
||||
)
|
||||
else:
|
||||
return RankedSelection(
|
||||
diagnosis_id=selection.diagnosis_id,
|
||||
raw_term=selection.raw_term or clean_diagnosis,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
selected_candidate=None,
|
||||
ranking_reason="Unsupported specificity: Candidate specifies diabetic complications without documented evidence.",
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=0.0,
|
||||
abstention_reason="UNSUPPORTED_SPECIFICITY",
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
|
||||
# 7. Check if candidate has zero clinical relevance to evidence
|
||||
ev_tokens = set(re.findall(r"[A-Za-z0-9]+", evidence_lower))
|
||||
cand_tokens = set(re.findall(r"[A-Za-z0-9]+", matching_candidate.description.lower()))
|
||||
# Remove universal filler tokens
|
||||
cand_meaningful = {
|
||||
t
|
||||
for t in cand_tokens
|
||||
if len(t) > 2 and t not in {"and", "with", "for", "without", "other", "unspecified"}
|
||||
}
|
||||
if cand_meaningful and not (ev_tokens & cand_meaningful):
|
||||
return RankedSelection(
|
||||
diagnosis_id=selection.diagnosis_id,
|
||||
raw_term=selection.raw_term or clean_diagnosis,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
selected_candidate=None,
|
||||
ranking_reason=f"Candidate not selected: Code '{matching_candidate.code}' ({matching_candidate.description}) is not supported by documented clinical evidence.",
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=0.0,
|
||||
abstention_reason="NO_MATCHING_CANDIDATE",
|
||||
candidate_pool=candidates,
|
||||
decision="ABSTAINED",
|
||||
)
|
||||
|
||||
# 8. Confidence threshold check
|
||||
effective_conf = max(selection.confidence, matching_candidate.retrieval_score)
|
||||
if effective_conf < self.min_confidence:
|
||||
return RankedSelection(
|
||||
diagnosis_id=selection.diagnosis_id,
|
||||
raw_term=selection.raw_term or clean_diagnosis,
|
||||
selected_code=None,
|
||||
selected_description=None,
|
||||
selected_candidate=None,
|
||||
ranking_reason=f"Candidate rejected: Confidence {effective_conf:.2f} is below minimum threshold {self.min_confidence:.2f}.",
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=effective_conf,
|
||||
abstention_reason="CONFIDENCE_BELOW_THRESHOLD",
|
||||
candidate_pool=candidates,
|
||||
decision="REJECTED_LOW_CONFIDENCE",
|
||||
)
|
||||
|
||||
# 9. Successfully accepted
|
||||
return RankedSelection(
|
||||
diagnosis_id=selection.diagnosis_id,
|
||||
raw_term=selection.raw_term or clean_diagnosis,
|
||||
selected_code=matching_candidate.code,
|
||||
selected_description=matching_candidate.description,
|
||||
selected_candidate=matching_candidate,
|
||||
ranking_reason=selection.ranking_reason
|
||||
or f"Selected candidate '{matching_candidate.code}' is best supported by documented clinical evidence.",
|
||||
supporting_evidence=[clean_evidence],
|
||||
confidence=round(effective_conf, 4),
|
||||
abstention_reason=None,
|
||||
candidate_pool=candidates,
|
||||
decision="ACCEPTED",
|
||||
)
|
||||
Reference in New Issue
Block a user