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"))
+24 -3
View File
@@ -7,6 +7,7 @@ derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`).
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
from core.cama.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad
from webapi.orchestration.silver.extracted import DesdeTexto
from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio
from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre
@@ -23,6 +24,23 @@ def _biopsia_que_pasa(fila) -> bool:
return fila.bx_fecha_solicitud is not None or fila.bx_fecha_reporte is not None
# Results read from text, with how the catalog says each is printed (`etiquetas_fuente`, `alias`): the
# radiologist's interpretation, the pathology report's text layer, and the note's diagnosis and prognosis.
DE_LA_INTERPRETACION = DesdeTexto(
"cama", ("mastografia.densidad", "mastografia.tamano_lesion_mm"), texto=lambda f: f.mast_interpretacion,
)
DEL_REPORTE_DE_PATOLOGIA = DesdeTexto(
"cama",
("biopsia.tipo_histologico", "biopsia.grado_nottingham", "biopsia.receptor_estrogeno",
"biopsia.receptor_estrogeno_pct", "biopsia.receptor_progesterona", "biopsia.receptor_progesterona_pct",
"biopsia.her2", "biopsia.ki67_pct"),
texto=lambda f: f.bx_pdf_blob,
)
DE_LA_NOTA = DesdeTexto(
"cama", ("nota_medica.estadio_clinico",),
texto=lambda f: "\n".join(t for t in (f.nm_diagnostico_texto, f.nm_pronostico) if t),
)
DESDE_STAGING = (
DeStaging(
Mastografia, "mast_id", "toma", estudio_id="mastografia", fecha="mast_fecha_toma",
@@ -33,14 +51,17 @@ DESDE_STAGING = (
DeStaging(
Mastografia, "mast_id", "reporte", estudio_id="mastografia", fecha="mast_fecha_reporte",
solo_si=lambda f: f.mast_fecha_reporte is not None, padres=(LA_MASTOGRAFIA_DE_SU_FILA,),
resultados={"mast_birads": "mastografia.birads"},
derivadas=DE_LA_INTERPRETACION.derivadas,
resultados={"mast_birads": "mastografia.birads", **DE_LA_INTERPRETACION.resultados},
fuentes=DE_LA_INTERPRETACION.fuentes,
),
DeStaging(
BiopsiaMama, "bx_id", "orden", estudio_id="biopsia", fecha="bx_fecha_solicitud",
solo_si=_biopsia_que_pasa, padres=(LA_MASTOGRAFIA_DE_SU_FILA,), columnas={"orden_numero": "ord_numero_hospital"},
derivadas=DEL_REPORTE_DE_PATOLOGIA.derivadas, fuentes=DEL_REPORTE_DE_PATOLOGIA.fuentes,
hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte",
resultados={"bx_grado_histologico": "biopsia.grado"}),),
resultados={"bx_grado_histologico": "biopsia.grado", **DEL_REPORTE_DE_PATOLOGIA.resultados}),),
),
orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES),
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES),
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, extraidos=DE_LA_NOTA),
)
+119
View File
@@ -0,0 +1,119 @@
"""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
@@ -9,11 +9,13 @@ da sus tablas y su catálogo de especialidades. Es la normalización que hacían
como llegó;
- el CIE-10 de la nota, sin espacios ni punto y en mayúsculas; su identificador del hospital, en `id_hospital`;
- el motivo de consulta y el diagnóstico en texto, solo si el proyecto los pide (`con_textos`, CaCu: T-24b),
sin normalizarlos (I-K61).
sin normalizarlos (I-K61);
- the catalog results a project reads from the note's texts (`extraidos`, CaMa's clinical stage).
"""
from collections.abc import Collection, Mapping
from webapi.orchestration.silver.extracted import DesdeTexto
from webapi.orchestration.silver.values import INTENCION, cie, codigo_de_especialidad, texto_limpio
from webapi.orchestration.silver.procedures import DeStaging
@@ -52,22 +54,26 @@ def orden_de_estudio(staging: type, alias: Mapping[str, str], codigos: Collectio
def nota_medica(
staging: type, alias: Mapping[str, str], codigos: Collection[str], *, con_textos: bool = False
staging: type, alias: Mapping[str, str], codigos: Collection[str], *, con_textos: bool = False,
extraidos: DesdeTexto | None = None,
) -> DeStaging:
textos = {
"motivo": lambda f: texto_limpio(f.nm_motivo_consulta),
"diagnostico_texto": lambda f: texto_limpio(f.nm_diagnostico_texto),
} if con_textos else {}
leidos = extraidos.derivadas if extraidos else {}
return DeStaging(
staging, "nm_id", "encuentro", estudio_id="nota_medica", fecha="nm_fecha",
columnas={"id_hospital": "nm_id_hospital"}, # para ligarla después con sus órdenes (provisional)
derivadas={
"cie_codigo": lambda f: cie(f.nm_cie_codigo), **especialidad("nm_especialidad", alias, codigos), **textos,
**leidos,
},
resultados={
"cie_codigo": "nota_medica.diagnostico",
"especialidad": "nota_medica.especialidad",
**({f: f"nota_medica.{f}" for f in textos}),
**(extraidos.resultados if extraidos else {}),
},
fuentes={"especialidad": "especialidad_fuente"},
fuentes={"especialidad": "especialidad_fuente", **(extraidos.fuentes if extraidos else {})},
)