490 lines
23 KiB
Python
490 lines
23 KiB
Python
import hashlib
|
|
import json
|
|
import logging
|
|
import re
|
|
import threading
|
|
import unicodedata
|
|
from collections import OrderedDict
|
|
from importlib.metadata import PackageNotFoundError
|
|
from importlib.metadata import version as package_version
|
|
from typing import Any, ClassVar, Iterator
|
|
|
|
import pandas as pd
|
|
|
|
from extraction import DocumentExtractor, ExtractedRecord, ExtractionError, make_segmenter, read_document, reader_for
|
|
from extraction.readers import PdfReader, combine_pages, supported_extensions
|
|
from extraction.nlp.ranking import examples_for, same_value
|
|
from extraction.segmentation import SEGMENTERS
|
|
from webapi.imports.connectors.base import decode_file
|
|
from webapi.imports.connectors.document_columns import DocumentBatch, DocumentColumns, document_bytes # noqa: F401
|
|
from webapi.imports.connectors.errors import ConnectorError
|
|
from webapi.imports.connectors.registry import register_connector
|
|
from webapi.imports.connectors.sql import SqlConnector
|
|
from webapi.imports.connectors.tabular import DataFrameConnector
|
|
from webapi.imports.schemas.field_specs import field_specs_for, foreign_subjects_for, key_field_for, subject_for
|
|
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
|
|
|
DOCUMENT_COLUMN = "documento"
|
|
IMAGE_COLUMN = "imagen"
|
|
CONFIDENCE_COLUMN = "confianza_extraccion"
|
|
SOURCES_COLUMN = "origen"
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class _ResultCache:
|
|
"""OCR over a stack of scans is slow, and the stateless API runs the
|
|
same extraction for preview, validation and commit. Results are kept
|
|
per worker for the last few distinct requests."""
|
|
|
|
def __init__(self, size: int = 8):
|
|
self._items: OrderedDict[str, Any] = OrderedDict()
|
|
self._size = size
|
|
self._lock = threading.Lock()
|
|
|
|
def get_or_compute(self, key: str, compute) -> Any:
|
|
with self._lock:
|
|
if key in self._items:
|
|
self._items.move_to_end(key)
|
|
return self._items[key]
|
|
value = compute()
|
|
with self._lock:
|
|
self._items[key] = value
|
|
while len(self._items) > self._size:
|
|
self._items.popitem(last=False)
|
|
return value
|
|
|
|
|
|
_CACHE = _ResultCache()
|
|
|
|
|
|
def _files_from_sql(sql: dict[str, Any]) -> DocumentBatch:
|
|
"""The documents of a SQL table or query (connected the same way
|
|
`SqlConnector` is), read as `DocumentColumns` describes: `column` or
|
|
`columns` hold them, and `key_column`/`name_by`, `group_column`/
|
|
`group_by` and `fields` name, group and carry values for them."""
|
|
if not sql.get("table") and not sql.get("query"):
|
|
raise ConnectorError("falta table o query")
|
|
spec = DocumentColumns.parse(sql)
|
|
connector = SqlConnector.connect(sql)
|
|
connector = (
|
|
connector.select_query(sql["query"]) if sql.get("query") else connector.select_table(sql["table"], schema=sql.get("schema"))
|
|
)
|
|
return spec.assemble(connector.read_rows({column: column for column in spec.source_columns()}))
|
|
|
|
|
|
@register_connector
|
|
class DocumentConnector(DataFrameConnector):
|
|
"""Clinical documents that are not tables: one report per patient,
|
|
several pages per patient, many patients per file, scans, free text —
|
|
uploaded directly, or read one row at a time from a SQL source whose
|
|
`payload` carries `sql` (a connection plus `table`/`query`, `column`
|
|
and `key_column`) instead of `files`; either way, every row's content
|
|
reaches the same extraction, PDF, image or plain text alike.
|
|
|
|
Every file is read page by page (text layer or OCR; plain text as its
|
|
own lines), split into per-patient records, and the target entity's
|
|
fields are extracted from labels and narrative text. Records of the
|
|
same patient found in other pages or files — or rows — are merged.
|
|
Each row also carries the record's pages as a PDF (`documento`),
|
|
mappable to the entity's file column, when the source produced one.
|
|
|
|
A SQL source's `sql.fields` (`{target_field: sql_column}`) carries other
|
|
columns of the same row straight through as that row's values for those
|
|
fields, overriding whatever the document's own text parses to — a
|
|
source's own patient or study id is a structured join key, not a guess,
|
|
so it wins even over a page that prints nothing recognizable, or
|
|
prints something else entirely. Corrections made while reviewing
|
|
travel in `overrides` (`{"<row>": {"field": value}}`) and win over
|
|
both.
|
|
"""
|
|
|
|
kind = "document"
|
|
label = "Documentos clínicos"
|
|
description = "Reportes, formatos y notas en PDF, imagen o texto; los campos se extraen del contenido"
|
|
category = "document"
|
|
icon = "document_scanner"
|
|
extensions: ClassVar[tuple[str, ...]] = tuple(supported_extensions())
|
|
|
|
def __init__(
|
|
self,
|
|
files: list[tuple[str, bytes]],
|
|
*,
|
|
target: str,
|
|
segmentation: str = "auto",
|
|
pages_per_record: int = 1,
|
|
ocr_mode: str = "auto",
|
|
key_pattern: str | None = None,
|
|
overrides: dict[str, dict[str, Any]] | None = None,
|
|
source_fields: dict[str, dict[str, Any]] | None = None,
|
|
record_keys: dict[str, str] | None = None,
|
|
include_pattern: str | None = None,
|
|
exclude_pattern: str | None = None,
|
|
):
|
|
if not files:
|
|
raise ConnectorError("no se recibieron documentos")
|
|
entity = ENTITY_REGISTRY.get(target)
|
|
if entity is None:
|
|
raise ConnectorError(f"destino desconocido: {target!r}")
|
|
if segmentation not in SEGMENTERS:
|
|
raise ConnectorError(f"segmentación desconocida {segmentation!r} (disponibles: {', '.join(SEGMENTERS)})")
|
|
if ocr_mode not in ("auto", "always", "never"):
|
|
raise ConnectorError(f"ocr_mode desconocido {ocr_mode!r}")
|
|
self.files = files
|
|
self.target = target
|
|
self.domain = target.split(".", 1)[0]
|
|
self.subject = subject_for(entity)
|
|
self.foreign = foreign_subjects_for(entity)
|
|
# The entity's column for the extraction version that filled it, when it has one.
|
|
self.nlp_field = next((name for name in entity.schema.model_fields if name.endswith("_nlp_version")), None)
|
|
self.ranker = _ranker(self.domain)
|
|
self.specs = field_specs_for(entity, key_pattern=key_pattern)
|
|
self.key_field = key_field_for(entity)
|
|
self.segmentation = segmentation
|
|
self.pages_per_record = max(1, int(pages_per_record))
|
|
self.ocr_mode = ocr_mode
|
|
self.key_pattern = key_pattern
|
|
self.overrides = {str(k): v for k, v in (overrides or {}).items()}
|
|
self.source_fields = {str(k): v for k, v in (source_fields or {}).items()}
|
|
self.record_keys = {str(k): str(v) for k, v in (record_keys or {}).items()}
|
|
self.include_pattern = _compile_filter(include_pattern, "include_pattern")
|
|
self.exclude_pattern = _compile_filter(exclude_pattern, "exclude_pattern")
|
|
self.skipped: list[dict[str, str]] = []
|
|
# A source's own ids (`ado_id`) are never read off a page, but a source may carry them.
|
|
known = set(entity.schema.model_fields)
|
|
unknown = sorted({name for values in self.source_fields.values() for name in values} - known)
|
|
if unknown:
|
|
raise ConnectorError(f"fields desconocidos para {target}: {', '.join(unknown)}")
|
|
self._df: pd.DataFrame | None = None
|
|
|
|
@classmethod
|
|
def from_payload(cls, payload: dict[str, Any]) -> "DocumentConnector":
|
|
if payload.get("sql"):
|
|
documents = _files_from_sql(payload["sql"])
|
|
else:
|
|
documents = DocumentBatch(
|
|
files=[(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)]
|
|
)
|
|
return cls(
|
|
documents.files,
|
|
target=payload["target"],
|
|
segmentation=payload.get("segmentation", "auto"),
|
|
pages_per_record=payload.get("pages_per_record", 1),
|
|
ocr_mode=payload.get("ocr_mode", "auto"),
|
|
key_pattern=payload.get("key_pattern") or None,
|
|
overrides=payload.get("overrides"),
|
|
source_fields=documents.source_fields,
|
|
record_keys=documents.record_keys,
|
|
include_pattern=payload.get("include_pattern") or None,
|
|
exclude_pattern=payload.get("exclude_pattern") or None,
|
|
)
|
|
|
|
@classmethod
|
|
def describe(cls) -> dict[str, Any]:
|
|
segmentations = [{"id": name, "label": segmenter.label} for name, segmenter in SEGMENTERS.items()]
|
|
return {**super().describe(), "segmentations": segmentations}
|
|
|
|
# -- extraction -----------------------------------------------------------
|
|
|
|
@property
|
|
def records(self) -> list[ExtractedRecord]:
|
|
records, self.skipped = _CACHE.get_or_compute(self._cache_key(), self._extract)
|
|
return records
|
|
|
|
def _extract(self) -> tuple[list[ExtractedRecord], list[dict[str, str]]]:
|
|
documents, skipped = [], []
|
|
for name, raw in self.files:
|
|
try:
|
|
document = read_document(name, raw, ocr_mode=self.ocr_mode)
|
|
except ExtractionError as exc:
|
|
skipped.append({"document": name, "reason": f"ilegible: {exc}"})
|
|
continue
|
|
reason = self._filtered_out(document)
|
|
if reason:
|
|
skipped.append({"document": name, "reason": reason})
|
|
continue
|
|
documents.append(document)
|
|
if not documents:
|
|
detail = "; ".join(f"{s['document']}: {s['reason']}" for s in skipped[:5])
|
|
raise ConnectorError(f"ningún documento se pudo usar ({detail})")
|
|
segmenter = make_segmenter(
|
|
self.segmentation,
|
|
key=next((s for s in self.specs if s.name == self.key_field), None),
|
|
pages_per_record=self.pages_per_record,
|
|
)
|
|
records = DocumentExtractor(
|
|
self.specs, key_field=self.key_field, segmenter=segmenter, subject=self.subject, foreign=self.foreign, ranker=self.ranker
|
|
).extract(documents, source_fields=self.source_fields, record_keys=self.record_keys)
|
|
return records, skipped
|
|
|
|
@property
|
|
def nlp_version(self) -> str:
|
|
"""The extraction code's version and the ranker's (`extraccion:<n>`), when one was used."""
|
|
try:
|
|
code = package_version("extraction")
|
|
except PackageNotFoundError:
|
|
code = "dev"
|
|
return f"extraction {code}" + (f" + {self.ranker.version}" if self.ranker is not None and self.ranker.version else "")
|
|
|
|
def _filtered_out(self, document) -> str | None:
|
|
"""Why a document is left out by `include_pattern`/`exclude_pattern`,
|
|
matched case- and accent-insensitively against all of its text,
|
|
so a source mixing several kinds of report feeds each target only
|
|
its own."""
|
|
text = "\n".join(page.text for page in document.pages)
|
|
plain = _unaccented(text)
|
|
if self.include_pattern and not (self.include_pattern.search(text) or self.include_pattern.search(plain)):
|
|
return "no coincide con include_pattern"
|
|
if self.exclude_pattern and (self.exclude_pattern.search(text) or self.exclude_pattern.search(plain)):
|
|
return "coincide con exclude_pattern"
|
|
return None
|
|
|
|
def _cache_key(self) -> str:
|
|
digest = hashlib.sha256()
|
|
for name, raw in self.files:
|
|
digest.update(name.encode())
|
|
digest.update(hashlib.sha256(raw).digest())
|
|
config = [
|
|
self.target,
|
|
self.nlp_version,
|
|
self.segmentation,
|
|
self.pages_per_record,
|
|
self.ocr_mode,
|
|
self.key_pattern,
|
|
self.source_fields,
|
|
self.record_keys,
|
|
self.include_pattern.pattern if self.include_pattern else None,
|
|
self.exclude_pattern.pattern if self.exclude_pattern else None,
|
|
]
|
|
digest.update(json.dumps(config, sort_keys=True, default=str).encode())
|
|
return digest.hexdigest()
|
|
|
|
# -- rows -----------------------------------------------------------------
|
|
|
|
def _dataframe(self) -> pd.DataFrame:
|
|
if self._df is None:
|
|
columns = (
|
|
[spec.name for spec in self.specs]
|
|
+ self._carried_columns()
|
|
+ ([self.nlp_field] if self.nlp_field else [])
|
|
+ self.caption_columns()
|
|
+ [DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN]
|
|
)
|
|
rows = [self._row(index, record) for index, record in enumerate(self.records)]
|
|
self._df = pd.DataFrame(rows, columns=columns, dtype=object)
|
|
return self._df
|
|
|
|
def _carried_columns(self) -> list[str]:
|
|
"""Fields the source carries that no document spec reads, such as its own ids, in the order first seen."""
|
|
specs = {spec.name for spec in self.specs}
|
|
carried: list[str] = []
|
|
for values in self.source_fields.values():
|
|
carried.extend(name for name in values if name not in specs and name not in carried)
|
|
return carried
|
|
|
|
def caption_columns(self) -> list[str]:
|
|
"""Every caption the documents print that no field of the target
|
|
claims, in the order first seen: columns of their own, mappable
|
|
and usable in derived fields like any column of a table."""
|
|
reserved = {spec.name for spec in self.specs} | set(self._carried_columns()) | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN}
|
|
columns: list[str] = []
|
|
for record in self.records:
|
|
for found in record.discovered:
|
|
name = _caption_column(found.caption, reserved)
|
|
if name not in columns:
|
|
columns.append(name)
|
|
return columns
|
|
|
|
def record_rows(self) -> Iterator[tuple[dict[str, Any], list[str]]]:
|
|
"""Each record's row (overrides applied, its captions as columns,
|
|
its pages as `documento`) with the names of the documents it was
|
|
read from."""
|
|
for index, record in enumerate(self.records):
|
|
yield self._row(index, record), [source.document for source in record.sources]
|
|
|
|
def _row(self, index: int, record: ExtractedRecord) -> dict[str, Any]:
|
|
row: dict[str, Any] = record.row()
|
|
reserved = {spec.name for spec in self.specs} | set(self._carried_columns()) | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN}
|
|
for found in record.discovered:
|
|
row.setdefault(_caption_column(found.caption, reserved), found.value)
|
|
row.update(self.overrides.get(str(index), {}))
|
|
if self.nlp_field and record.values:
|
|
row[self.nlp_field] = self.nlp_version
|
|
row[DOCUMENT_COLUMN] = self._record_pdf(record)
|
|
row[IMAGE_COLUMN] = self._record_image(record)
|
|
row[CONFIDENCE_COLUMN] = round(record.confidence, 3)
|
|
row[SOURCES_COLUMN] = "; ".join(f"{s.document} p. {', '.join(map(str, s.page_numbers))}" for s in record.sources)
|
|
return row
|
|
|
|
def _record_pdf(self, record: ExtractedRecord) -> bytes | None:
|
|
"""The record's pages from every PDF it was found in, as one PDF."""
|
|
by_name = dict(self.files)
|
|
parts = [
|
|
(by_name[source.document], source.page_numbers)
|
|
for source in record.sources
|
|
if source.document in by_name and PdfReader.accepts(source.document, by_name[source.document][:8])
|
|
]
|
|
return combine_pages(parts) if parts else None
|
|
|
|
def _record_image(self, record: ExtractedRecord) -> bytes | None:
|
|
"""A PNG of the first picture embedded on the record's pages (a mammogram,
|
|
a lesion photo), mappable onto an image column such as `mast_dicom_blob`.
|
|
A `figure` wins over a `scan`, which is the whole page."""
|
|
by_name = dict(self.files)
|
|
candidates = [(document, image) for document, image in record.images if document in by_name]
|
|
if not candidates:
|
|
return None
|
|
figures = [c for c in candidates if c[1].kind == "figure"]
|
|
document, image = figures[0] if figures else candidates[0]
|
|
raw = by_name[document]
|
|
try:
|
|
return reader_for(document, raw).render_region(raw, image.page_number, image.bbox)
|
|
except ExtractionError:
|
|
return None
|
|
|
|
# -- review ---------------------------------------------------------------
|
|
|
|
def report(self) -> list[dict[str, Any]]:
|
|
"""Per record: every extracted value with its confidence, method and
|
|
the line it was read from, conflicts between sources, and the
|
|
images found on its pages."""
|
|
report = []
|
|
for index, record in enumerate(self.records):
|
|
overrides = self.overrides.get(str(index), {})
|
|
fields = {name: value.to_dict() for name, value in record.values.items()}
|
|
for name, value in overrides.items():
|
|
fields[name] = {**fields.get(name, {}), "value": value, "method": "manual", "confidence": 1.0}
|
|
report.append(
|
|
{
|
|
"index": index,
|
|
"key": record.key,
|
|
"confidence": round(record.confidence, 3),
|
|
"on_topic": record.on_topic,
|
|
"fields": fields,
|
|
"alternatives": {
|
|
name: _alternatives(proposed, record.values.get(name))
|
|
for name, proposed in record.candidates.items()
|
|
if _alternatives(proposed, record.values.get(name))
|
|
},
|
|
"missing": [s.name for s in self.specs if s.required and s.name not in fields],
|
|
"conflicts": [
|
|
{"field": c.field, "kept": c.kept.to_dict(), "discarded": c.discarded.to_dict()}
|
|
for c in record.conflicts
|
|
],
|
|
"sources": [{"document": s.document, "page_numbers": s.page_numbers} for s in record.sources],
|
|
"images": [
|
|
{"document": name, "page_number": image.page_number, "bbox": image.bbox.as_list(), "kind": image.kind}
|
|
for name, image in record.images
|
|
],
|
|
}
|
|
)
|
|
return report
|
|
|
|
def metadata(self) -> dict[str, Any]:
|
|
return {
|
|
"records": len(self.records),
|
|
"key_field": self.key_field,
|
|
"documents": [name for name, _ in self.files],
|
|
"skipped": self.skipped,
|
|
"nlp_version": self.nlp_version,
|
|
}
|
|
|
|
# -- learning -------------------------------------------------------------
|
|
|
|
def reviewed(self) -> list[tuple[ExtractedRecord, dict[str, Any]]]:
|
|
"""The records a person corrected while reviewing, each with what is
|
|
known to be right about it: the corrected fields, and every other
|
|
field as it was extracted, since whoever corrected the record read
|
|
it. Fields a correction emptied are known to be empty."""
|
|
reviewed = []
|
|
for index, record in enumerate(self.records):
|
|
corrections = self.overrides.get(str(index))
|
|
if not corrections:
|
|
continue
|
|
truth: dict[str, Any] = {name: value.value for name, value in record.values.items()}
|
|
truth.update({name: (None if value in ("", None) else value) for name, value in corrections.items()})
|
|
known = {spec.name for spec in self.specs}
|
|
reviewed.append((record, {name: value for name, value in truth.items() if name in known}))
|
|
return reviewed
|
|
|
|
def learning_examples(self) -> tuple[list, dict[str, int], int]:
|
|
"""Examples for the ranker from the reviewed records
|
|
(`extraction.nlp.ranking.examples_for`), per field how many right
|
|
values no candidate had proposed, and how many records they came from."""
|
|
examples: list = []
|
|
unreachable: dict[str, int] = {}
|
|
reviewed = self.reviewed()
|
|
for record, truth in reviewed:
|
|
examples.extend(examples_for(self.specs, record.candidates, truth))
|
|
for name, value in truth.items():
|
|
if value is not None and not any(same_value(c.value, value) for c in record.candidates.get(name, ())):
|
|
unreachable[name] = unreachable.get(name, 0) + 1
|
|
return examples, unreachable, len(reviewed)
|
|
|
|
|
|
def _ranker(domain: str):
|
|
"""The domain's extraction ranker in the model registry, or `None` (rank by
|
|
confidence) when there is none or the registry can't be read."""
|
|
try:
|
|
from models.io.extraction_ranker import current
|
|
|
|
return current(domain)
|
|
except Exception as exc: # noqa: BLE001 - extraction must work without the registry
|
|
logger.warning("sin ranker de extracción para %s: %s", domain, exc)
|
|
return None
|
|
|
|
|
|
def _alternatives(proposed: list, chosen) -> list[dict[str, Any]]:
|
|
"""The other values the extractors proposed for a field, best first, for a reviewer to pick from."""
|
|
seen, found = set(), []
|
|
for candidate in sorted(proposed, key=lambda c: -c.confidence):
|
|
if chosen is not None and same_value(candidate.value, chosen.value):
|
|
continue
|
|
key = json.dumps(candidate.to_dict()["value"], default=str)
|
|
if key in seen:
|
|
continue
|
|
seen.add(key)
|
|
found.append({**candidate.to_dict(), "confidence": round(candidate.confidence, 3)})
|
|
return found[:5]
|
|
|
|
|
|
def _caption_column(caption: str, reserved: set[str]) -> str:
|
|
"""A discovered caption as a column name, kept apart from the target's
|
|
own fields and the connector's bookkeeping columns."""
|
|
name = " ".join(caption.split())
|
|
return f"texto: {name}" if name in reserved else name
|
|
|
|
|
|
def _compile_filter(pattern: str | None, name: str) -> re.Pattern | None:
|
|
if not pattern:
|
|
return None
|
|
try:
|
|
return re.compile(pattern, re.I)
|
|
except re.error as exc:
|
|
raise ConnectorError(f"{name} no es una expresión regular válida: {exc}") from exc
|
|
|
|
|
|
def _unaccented(text: str) -> str:
|
|
return "".join(ch for ch in unicodedata.normalize("NFKD", text) if not unicodedata.combining(ch))
|
|
|
|
|
|
DOCUMENT_OPTIONS = ("segmentation", "pages_per_record", "ocr_mode", "key_pattern", "overrides", "include_pattern", "exclude_pattern")
|
|
|
|
|
|
def document_options(raw: dict[str, Any]) -> dict[str, Any]:
|
|
"""The extraction settings `DocumentConnector` takes, out of a request."""
|
|
return {name: raw[name] for name in DOCUMENT_OPTIONS if raw.get(name) not in (None, "")}
|
|
|
|
|
|
def connector_for_batch(batch: DocumentBatch, target: str, options: dict[str, Any]) -> "DocumentConnector":
|
|
"""A `DocumentConnector` over documents read from a source's columns,
|
|
their row values restricted to the target's fields."""
|
|
entity = ENTITY_REGISTRY.get(target)
|
|
if entity is None:
|
|
raise ConnectorError(f"destino desconocido: {target!r}")
|
|
known = set(entity.schema.model_fields)
|
|
source_fields = {name: {k: v for k, v in values.items() if k in known} for name, values in batch.source_fields.items()}
|
|
return DocumentConnector(
|
|
batch.files, target=target, source_fields=source_fields, record_keys=batch.record_keys, **document_options(options)
|
|
)
|