268 lines
11 KiB
Python
268 lines
11 KiB
Python
"""Extraction of results from the PDF reports stored with each study
|
|
(VAR-01..09, VARM-01..05).
|
|
|
|
Each `OcrJob` says which table, which stored PDF and which result columns
|
|
an extraction fills; `OCR_JOBS` lists them all. Adding a job is adding an
|
|
`OcrExtractor` (usually a `ReportOcrExtractor` with its `fields`) and an
|
|
entry in `OCR_JOBS`.
|
|
|
|
Extraction method (VAR-04, VARM-05): the PDF's text layer is read with
|
|
pdfplumber; pages without one are recognized with Tesseract 5's LSTM engine
|
|
(Smith, R. "An Overview of the Tesseract OCR Engine", ICDAR 2007). Values
|
|
are then located by caption matching tolerant to OCR errors, and by
|
|
lexicon matching over the narrative with NegEx-style negation handling
|
|
(Chapman, W. et al. "A Simple Algorithm for Identifying Negated Findings and
|
|
Diseases in Discharge Summaries", J Biomed Inform 34(5), 2001). Every
|
|
value carries a 0..1 confidence: caption match quality x parse quality x
|
|
Tesseract's word confidence.
|
|
"""
|
|
import json
|
|
from abc import ABC, abstractmethod
|
|
from dataclasses import dataclass, field
|
|
from datetime import datetime, timezone
|
|
from typing import Any, ClassVar
|
|
|
|
from sqlalchemy import func, or_
|
|
from sqlmodel import select
|
|
|
|
from core.cacu.enums import GRADO_CIN_ALIAS, GradoCIN, ResultadoVPH
|
|
from core.cama.enums import GradoHistologicoMama
|
|
from core.ocr import OcrEstatus
|
|
from extraction import FieldKind, FieldSpec, read_document
|
|
from extraction.nlp import RecordExtractor, SegmentLine
|
|
from extraction.nlp.vocabulary import CLINICAL_TERMS, labels_for
|
|
from extraction.ocr import TesseractOcr
|
|
from models.io.storage import resolve_repository
|
|
from persistance.repository import Repository
|
|
|
|
# Below this confidence a value is stored but flagged for manual review.
|
|
REVIEW_THRESHOLD = 0.8
|
|
|
|
|
|
@dataclass
|
|
class OcrExtractionResult:
|
|
"""VAR-03/VARM-04a: the values plus their confidence and provenance."""
|
|
|
|
values: dict[str, Any]
|
|
confianza: float
|
|
estatus: OcrEstatus
|
|
requiere_revision: bool
|
|
metodo_principal: str
|
|
metodo_alternativo: str | None = None
|
|
quality_validation: str | None = None
|
|
|
|
|
|
@dataclass
|
|
class OcrColumnSpec:
|
|
"""The columns of one extraction on its table: the stored PDF, the
|
|
five traceability columns, and extractor result key -> result column."""
|
|
|
|
blob_field: str
|
|
confianza_field: str
|
|
estatus_field: str
|
|
requiere_revision_field: str
|
|
metodo_principal_field: str
|
|
metodo_alternativo_field: str
|
|
result_field_map: dict[str, str] = field(default_factory=dict)
|
|
|
|
|
|
class OcrExtractor(ABC):
|
|
@abstractmethod
|
|
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
|
|
"""Reads `pdf_blob`. A document that can be read but where nothing
|
|
is found returns estatus FALLIDO with requiere_revision; an
|
|
unreadable one may raise, and the driver records FALLIDO."""
|
|
|
|
|
|
class ReportOcrExtractor(OcrExtractor):
|
|
"""Reads a report and looks for `fields` (result key -> FieldSpec)."""
|
|
|
|
fields: ClassVar[dict[str, FieldSpec]]
|
|
|
|
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
|
|
document = read_document("reporte.pdf", pdf_blob)
|
|
lines = [SegmentLine(document.name, page.number, line) for page in document.pages for line in page.lines]
|
|
found = RecordExtractor(list(self.fields.values())).extract(lines)
|
|
by_key = {key: found[spec.name] for key, spec in self.fields.items() if spec.name in found}
|
|
|
|
sources = {page.source for page in document.pages}
|
|
principal = "pdf-texto" if "text" in sources else TesseractOcr().name
|
|
alternativo = TesseractOcr().name if sources == {"text", "ocr"} else None
|
|
evidence = {key: value.to_dict() for key, value in by_key.items()}
|
|
missing = [key for key in self.fields if key not in by_key]
|
|
if missing:
|
|
evidence["faltantes"] = missing
|
|
|
|
if not by_key:
|
|
return OcrExtractionResult({}, 0.0, OcrEstatus.FALLIDO, True, principal, alternativo, json.dumps(evidence, ensure_ascii=False))
|
|
confianza = round(min(value.confidence for value in by_key.values()) * len(by_key) / len(self.fields), 3)
|
|
return OcrExtractionResult(
|
|
values={key: value.value for key, value in by_key.items()},
|
|
confianza=confianza,
|
|
estatus=OcrEstatus.REALIZADO,
|
|
requiere_revision=bool(missing) or confianza < REVIEW_THRESHOLD,
|
|
metodo_principal=principal,
|
|
metodo_alternativo=alternativo,
|
|
quality_validation=json.dumps(evidence, ensure_ascii=False, default=str),
|
|
)
|
|
|
|
|
|
def choice_field(column: str, values: dict[str, Any], **options) -> FieldSpec:
|
|
return FieldSpec(column, FieldKind.CHOICE, labels=labels_for(column), choices={**values, **CLINICAL_TERMS.get(column, {})}, **options)
|
|
|
|
|
|
class VphOcrExtractor(ReportOcrExtractor):
|
|
"""VAR-01: VPH result and genotypes 16/18 from `cit_vph_pdf_blob`."""
|
|
|
|
fields = {
|
|
"resultado": choice_field("cit_vph_resultado", {m.value: m.value for m in ResultadoVPH}, scan_free_text=True),
|
|
"genotipo_16": choice_field("cit_vph_genotipo_16", {}),
|
|
"genotipo_18": choice_field("cit_vph_genotipo_18", {}),
|
|
}
|
|
|
|
|
|
class CinGradoOcrExtractor(ReportOcrExtractor):
|
|
"""VAR-02: CIN grade from the cervical biopsy report `bx_pdf_blob`."""
|
|
|
|
fields = {"grado": choice_field("bx_cin_grado", {**{m.value: m.value for m in GradoCIN}, **GRADO_CIN_ALIAS}, scan_free_text=True)}
|
|
|
|
|
|
class GradoHistologicoOcrExtractor(ReportOcrExtractor):
|
|
"""VARM-03: histological grade from the breast biopsy report `bx_pdf_blob`."""
|
|
|
|
fields = {
|
|
"grado": choice_field(
|
|
"bx_grado_histologico",
|
|
{m.value.replace("_", " "): m.value for m in GradoHistologicoMama},
|
|
scan_free_text=True,
|
|
)
|
|
}
|
|
|
|
|
|
def _ocr_columns(prefix: str, blob_field: str, results: dict[str, str]) -> OcrColumnSpec:
|
|
return OcrColumnSpec(
|
|
blob_field=blob_field,
|
|
confianza_field=f"{prefix}_ocr_confianza",
|
|
estatus_field=f"{prefix}_ocr_estatus",
|
|
requiere_revision_field=f"{prefix}_ocr_requiere_revision",
|
|
metodo_principal_field=f"{prefix}_ocr_metodo_principal",
|
|
metodo_alternativo_field=f"{prefix}_ocr_metodo_alternativo",
|
|
result_field_map=results,
|
|
)
|
|
|
|
|
|
CIT_VPH_COLUMNS = _ocr_columns(
|
|
"cit_vph",
|
|
"cit_vph_pdf_blob",
|
|
{"resultado": "cit_vph_resultado", "genotipo_16": "cit_vph_genotipo_16", "genotipo_18": "cit_vph_genotipo_18"},
|
|
)
|
|
BX_CIN_COLUMNS = _ocr_columns("bx", "bx_pdf_blob", {"grado": "bx_cin_grado"})
|
|
BX_GRADO_HISTOLOGICO_COLUMNS = _ocr_columns("bx", "bx_pdf_blob", {"grado": "bx_grado_histologico"})
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class OcrJob:
|
|
domain: str
|
|
entity: str # repository name in persistance.<domain>, without `_repository`
|
|
label: str
|
|
columns: OcrColumnSpec
|
|
extractor: type[OcrExtractor]
|
|
|
|
@property
|
|
def repository(self) -> Repository:
|
|
"""Resolved on use, so it follows whatever database URL is active."""
|
|
return resolve_repository(self.domain, self.entity)
|
|
|
|
|
|
OCR_JOBS: dict[tuple[str, str], OcrJob] = {
|
|
(job.domain, job.entity): job
|
|
for job in (
|
|
OcrJob("cacu", "citologia_cervical", "CaCu · Resultado de VPH (citología cervical)", CIT_VPH_COLUMNS, VphOcrExtractor),
|
|
OcrJob("cacu", "biopsia_cervical", "CaCu · Grado CIN (biopsia cervical)", BX_CIN_COLUMNS, CinGradoOcrExtractor),
|
|
OcrJob("cama", "biopsia_mama", "CaMa · Grado histológico (biopsia de mama)", BX_GRADO_HISTOLOGICO_COLUMNS, GradoHistologicoOcrExtractor),
|
|
)
|
|
}
|
|
|
|
|
|
@dataclass
|
|
class OcrRunSummary:
|
|
processed: int = 0
|
|
skipped_already_done: int = 0
|
|
failed: int = 0
|
|
needs_review: int = 0
|
|
|
|
|
|
def run_pending_extractions(
|
|
repository: Repository,
|
|
spec: OcrColumnSpec,
|
|
extractor: OcrExtractor,
|
|
*,
|
|
domain: str,
|
|
entity: str,
|
|
governance_repository: Repository | None = None,
|
|
source_description: str | None = None,
|
|
limit: int = 500,
|
|
) -> OcrRunSummary:
|
|
"""VAR-09: rows whose status is already REALIZADO are skipped, so the
|
|
persisted result is what prevents duplicate runs. A failing row is
|
|
stored as FALLIDO and the batch continues. With `governance_repository`,
|
|
every processed row is logged as an `ExtractionRun` (VAR-07/08)."""
|
|
from core.governance.enums import EstatusExtraccion
|
|
from core.governance.models import ExtractionRun
|
|
|
|
summary = OcrRunSummary()
|
|
model = repository.model
|
|
primary_key = list(model.__table__.primary_key.columns)
|
|
estatus = getattr(model, spec.estatus_field)
|
|
with_report = getattr(model, spec.blob_field).is_not(None)
|
|
done = estatus == OcrEstatus.REALIZADO.value
|
|
with repository.open_session() as session:
|
|
summary.skipped_already_done = session.exec(select(func.count()).select_from(model).where(with_report, done)).one()
|
|
pending = select(model).where(with_report, or_(estatus.is_(None), ~done)).order_by(*primary_key).limit(limit)
|
|
for tracked in session.exec(pending).all():
|
|
pk_value = getattr(tracked, primary_key[0].name)
|
|
started_at = datetime.now(timezone.utc)
|
|
try:
|
|
result = extractor.extract(getattr(tracked, spec.blob_field))
|
|
except NotImplementedError:
|
|
raise
|
|
except Exception as exc: # noqa: BLE001 -- one unreadable report must not stop the batch
|
|
result = OcrExtractionResult({}, 0.0, OcrEstatus.FALLIDO, True, type(extractor).__name__, None, f"error: {exc}")
|
|
|
|
for result_key, column in spec.result_field_map.items():
|
|
if result_key in result.values:
|
|
setattr(tracked, column, result.values[result_key])
|
|
setattr(tracked, spec.confianza_field, result.confianza)
|
|
setattr(tracked, spec.estatus_field, OcrEstatus(result.estatus).value)
|
|
setattr(tracked, spec.requiere_revision_field, result.requiere_revision)
|
|
setattr(tracked, spec.metodo_principal_field, result.metodo_principal)
|
|
setattr(tracked, spec.metodo_alternativo_field, result.metodo_alternativo)
|
|
session.add(tracked)
|
|
if result.estatus == OcrEstatus.FALLIDO:
|
|
summary.failed += 1
|
|
else:
|
|
summary.processed += 1
|
|
if result.requiere_revision:
|
|
summary.needs_review += 1
|
|
|
|
if governance_repository is not None:
|
|
governance_repository.create(
|
|
ExtractionRun(
|
|
domain=domain,
|
|
entity=entity,
|
|
entity_pk=str(pk_value),
|
|
column_extracted=",".join(spec.result_field_map.values()),
|
|
source_description=source_description,
|
|
source_started_at=started_at,
|
|
source_ended_at=datetime.now(timezone.utc),
|
|
transform_description=f"{type(extractor).__name__}: {result.metodo_principal}"
|
|
+ (f" + {result.metodo_alternativo}" if result.metodo_alternativo else ""),
|
|
quality_validation=result.quality_validation,
|
|
estatus=(
|
|
EstatusExtraccion.COMPLETADA if result.estatus == OcrEstatus.REALIZADO else EstatusExtraccion.FALLIDA
|
|
).value,
|
|
)
|
|
)
|
|
session.commit()
|
|
return summary
|