Files
WebApi/webapi/orchestration/silver/extracted.py
T
rockdrigo 9775a22c57 CaMa's silver load reads results from the reports' text, mapped by the catalog
How: `silver.extracted.DesdeTexto` turns the catalog's `etiquetas_fuente` and each value's `alias` into
Extraction's field specs and into derived columns of a `DeStaging`. CaMa reads density and lesion size from the
mammography interpretation, histology, grade, receptors, HER2 and Ki-67 from the pathology PDF's text layer (no
OCR at load time), and the clinical stage from the note's texts. `resultados_extraibles` reads and checks the new
keys: captions are a non-empty list, aliases need captions, and no spelling names two values.

Implications: a code comes with the spelling it matched as `valor_fuente`; an unknown spelling is kept as
`valor_fuente` with no code, counted as out of catalog, and becomes a code on the next load once its alias is in
the catalog. Nothing is renamed in the stored data and no table or column changes. The synthetic CaMa staging
gains a mammography text, a pathology PDF and a note with a stage.
2026-11-13 15:14:46 -06:00

120 lines
5.6 KiB
Python

"""Results of the catalog read from a staging row's text: a report's interpretation, a note, a PDF's text layer.
The catalog says how each result is printed (`etiquetas_fuente`, each value's `alias`;
`reference.catalogs.resultados_extraibles`); `DesdeTexto` turns that into Extraction's field specs and into the
derived columns, results and sources of a `DeStaging`. A coded value comes out as its `valor_id` when one of its
spellings matches, and always with what was read as `valor_fuente`: a spelling the catalog doesn't know yet stays
stored as text, counted as out of catalog by the silver check, and becomes a code on the next load after its alias
is added. Nothing extracted is written anywhere but silver's two tables.
"""
from collections.abc import Callable
from dataclasses import dataclass, field
from functools import lru_cache
from extraction import BBox, ExtractionError, FieldKind, FieldSpec, Line, read_document
from extraction.nlp.extractors import RecordExtractor, SegmentLine
from webapi.orchestration.reference.catalogs import ResultadoExtraible, resultados_extraibles
# A value read after a caption, kept as its source when the catalog doesn't know it: enough to recognize it.
LARGO_DE_FUENTE = 120
TIPOS = {"codigo": FieldKind.CHOICE, "numero": FieldKind.DECIMAL, "fecha": FieldKind.DATE, "texto": FieldKind.TEXT}
SUFIJO_DE_TEXTO = "#texto" # the plain-text twin of a coded field: what follows its caption, matched or not
def especificaciones(resultado: ResultadoExtraible) -> tuple[FieldSpec, ...]:
"""Extraction's fields for one result: the result itself and, if coded, the text after its caption."""
choices = {forma: valor for valor, formas in resultado.alias.items() for forma in formas}
campo = FieldSpec(
resultado.resultado_id, TIPOS[resultado.tipo_valor], labels=resultado.etiquetas_fuente,
choices=choices, scan_free_text=resultado.buscar_en_texto,
)
if resultado.tipo_valor != "codigo":
return (campo,)
return campo, FieldSpec(resultado.resultado_id + SUFIJO_DE_TEXTO, FieldKind.TEXT, labels=resultado.etiquetas_fuente)
def lineas_de_texto(texto: str, nombre: str = "texto") -> list[SegmentLine]:
"""A plain text as the lines of one page, as a reader would give them."""
renglones = [r for r in texto.splitlines() if r.strip()]
alto = 1 / max(len(renglones), 1)
return [SegmentLine(nombre, 1, Line(r, BBox(0, i * alto, 1, (i + 1) * alto))) for i, r in enumerate(renglones)]
def lineas_de_pdf(contenido: bytes) -> list[SegmentLine]:
"""The text layer of a PDF, without OCR: a load doesn't run OCR, and a scan without text gives no lines."""
try:
documento = read_document("documento.pdf", contenido, ocr_mode="never")
except ExtractionError:
return []
return [SegmentLine(documento.name, p.number, linea) for p in documento.pages for linea in p.lines]
@dataclass(frozen=True)
class DesdeTexto:
"""Catalog results read from what `texto` gives for a row: a text, a PDF's bytes, or nothing.
`derivadas`, `resultados` and `fuentes` go into the `DeStaging` (or its `Hija`) as they are. The row is read
once for all its results.
"""
proyecto: str
resultado_ids: tuple[str, ...]
texto: Callable[[object], str | bytes | None]
_extraer: Callable = field(init=False, repr=False, compare=False)
def __post_init__(self):
extraibles = resultados_extraibles(self.proyecto)
faltan = [r for r in self.resultado_ids if r not in extraibles]
if faltan:
raise ValueError(f"Sin etiquetas_fuente en el catálogo de {self.proyecto}: {', '.join(faltan)}.")
tipos = {r: extraibles[r].tipo_valor for r in self.resultado_ids}
extractor = RecordExtractor([e for r in self.resultado_ids for e in especificaciones(extraibles[r])])
@lru_cache(maxsize=256)
def extraer(contenido: str | bytes) -> dict[str, tuple]:
lineas = lineas_de_pdf(contenido) if isinstance(contenido, bytes) else lineas_de_texto(contenido)
leidos = extractor.extract(lineas)
return {r: _valor_y_fuente(leidos.get(r), leidos.get(r + SUFIJO_DE_TEXTO), tipos[r]) for r in tipos}
object.__setattr__(self, "_extraer", extraer)
def leer(self, fila) -> dict[str, tuple]:
"""`resultado_id` -> (value, source) read from the row; (None, None) when it isn't there."""
contenido = self.texto(fila)
if not contenido or (isinstance(contenido, str) and not contenido.strip()):
return dict.fromkeys(self.resultado_ids, (None, None))
return self._extraer(contenido)
@property
def derivadas(self) -> dict[str, Callable]:
columnas = {}
for r in self.resultado_ids:
columnas[_columna(r)] = lambda f, r=r: self.leer(f)[r][0]
columnas[_columna(r) + "_fuente"] = lambda f, r=r: self.leer(f)[r][1]
return columnas
@property
def resultados(self) -> dict[str, str]:
return {_columna(r): r for r in self.resultado_ids}
@property
def fuentes(self) -> dict[str, str]:
return {_columna(r): _columna(r) + "_fuente" for r in self.resultado_ids}
def _columna(resultado_id: str) -> str:
return "extraido:" + resultado_id
def _valor_y_fuente(leido, texto, tipo_valor: str) -> tuple:
"""A coded value with the spelling it matched, or, unmatched, with what followed its caption; others as read."""
if tipo_valor != "codigo":
return (None, None) if leido is None else (leido.value, None)
if leido is not None:
return leido.value, leido.raw
if texto is not None and str(texto.value).strip():
return None, str(texto.value).strip()[:LARGO_DE_FUENTE]
return None, None