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.
This commit is contained in:
rockdrigo
2026-11-13 11:55:17 -06:00
parent 0f9433949f
commit 97480ab832
6 changed files with 433 additions and 7 deletions
@@ -15,6 +15,7 @@ from pathlib import Path
from typing import NamedTuple
import core
from extraction.nlp.text import fold
from core.indicadores.catalogos import TIPOS_DE_VALOR
from sqlmodel import SQLModel
@@ -54,6 +55,7 @@ def catalogo_desde_toml(ruta: Path, *, tablas: TablasKit) -> Catalogo:
for nombre, resultado in estudio.get("resultados", {}).items():
resultado_id = f"{estudio_id}.{nombre}"
tipo_valor = _tipo_de_valor(resultado, resultado_id)
_claves_de_extraccion(resultado, resultado_id)
resultados.append(
tablas.CatResultado(
resultado_id=resultado_id,
@@ -93,6 +95,64 @@ def codigos_hospital(proyecto: str) -> dict[str, str]:
return codigos
class ResultadoExtraible(NamedTuple):
"""A result read from a document's text: the captions it's printed under and, if coded, each value's spellings."""
resultado_id: str
tipo_valor: str
etiquetas_fuente: tuple[str, ...]
alias: dict[str, tuple[str, ...]] # valor -> its spellings, the label included
buscar_en_texto: bool # also as a mention anywhere in the text, without a caption
provisional: bool
def resultados_extraibles(proyecto: str) -> dict[str, ResultadoExtraible]:
"""`resultado_id` -> how it's found in a document, for every result of the catalog with `etiquetas_fuente`.
The mapping lives in the catalog so that a new caption or spelling from the laboratory is one line there:
the next load reads it, and nothing already stored is renamed.
"""
extraibles = {}
for estudio_id, estudio in _leer(ruta_de_catalogo(proyecto)).items():
for nombre, resultado in estudio.get("resultados", {}).items():
resultado_id = f"{estudio_id}.{nombre}"
_claves_de_extraccion(resultado, resultado_id)
if "etiquetas_fuente" not in resultado:
continue
extraibles[resultado_id] = ResultadoExtraible(
resultado_id=resultado_id,
tipo_valor=resultado["tipo_valor"],
etiquetas_fuente=tuple(resultado["etiquetas_fuente"]),
alias={v["valor"]: (v["etiqueta"], *v.get("alias", ())) for v in resultado.get("valores", ())},
buscar_en_texto=bool(resultado.get("buscar_en_texto", False)),
provisional=bool(resultado.get("provisional", False)),
)
return extraibles
def _claves_de_extraccion(resultado: dict, resultado_id: str) -> None:
"""The extraction keys of a result: captions as a non-empty list of texts, and no spelling on two values."""
etiquetas = resultado.get("etiquetas_fuente")
if etiquetas is not None and (not isinstance(etiquetas, list) or not etiquetas
or not all(isinstance(e, str) and e.strip() for e in etiquetas)):
raise CatalogoInvalido(f"{resultado_id}: etiquetas_fuente es una lista de textos, no vacía.")
if etiquetas is None and ("buscar_en_texto" in resultado or any("alias" in v for v in resultado.get("valores", ()))):
raise CatalogoInvalido(f"{resultado_id}: alias y buscar_en_texto solo sirven con etiquetas_fuente.")
if etiquetas is not None and resultado.get("tipo_valor") not in ("codigo", "numero", "fecha", "texto"):
raise CatalogoInvalido(f"{resultado_id}: un resultado de tipo {resultado.get('tipo_valor')} no se extrae de texto.")
if resultado.get("buscar_en_texto") and resultado.get("tipo_valor") != "codigo":
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo se busca como mención en el texto.")
de: dict[str, str] = {}
for valor in resultado.get("valores", ()):
for forma in (valor.get("etiqueta", ""), *valor.get("alias", ())):
clave = " ".join(fold(forma).split())
if de.get(clave, valor["valor"]) != valor["valor"]:
raise CatalogoInvalido(
f"{resultado_id}: {forma!r} se escribe igual para {de[clave]!r} y {valor['valor']!r}."
)
de[clave] = valor["valor"]
def _leer(ruta: Path) -> dict:
return tomllib.loads(Path(ruta).read_text(encoding="utf-8"))