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:
Abhinav Gupta
2026-10-02 23:40:12 +05:30
commit 9ed0318b19
124 changed files with 22863 additions and 0 deletions
+35
View File
@@ -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",
]
+45
View File
@@ -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
+355
View File
@@ -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)
+174
View File
@@ -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.",
)
+57
View File
@@ -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()
+335
View File
@@ -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,
)
+208
View File
@@ -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