From 97480ab832dbc1a8970c715c2f4b8bcdbff0a5a7 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Fri, 13 Nov 2026 11:55:17 -0600 Subject: [PATCH] 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. --- tests/staging/cama.py | 44 ++++- tests/test_extracted_results.py | 178 ++++++++++++++++++ webapi/orchestration/reference/catalogs.py | 60 ++++++ webapi/orchestration/silver/cama.py | 27 ++- webapi/orchestration/silver/extracted.py | 119 ++++++++++++ .../orchestration/silver/orders_and_notes.py | 12 +- 6 files changed, 433 insertions(+), 7 deletions(-) create mode 100644 tests/test_extracted_results.py create mode 100644 webapi/orchestration/silver/extracted.py diff --git a/tests/staging/cama.py b/tests/staging/cama.py index 1b56465..42b3d27 100644 --- a/tests/staging/cama.py +++ b/tests/staging/cama.py @@ -20,12 +20,18 @@ reporte y grado, y una solicitada que todavía no lo tiene. Seis notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico (`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`). +Texts the silver load reads results from (`TEXTOS`, `INFORME_DE_PATOLOGIA`, `DIAGNOSTICO_DE_NOTA`): +H-003's B4A carries density C and a 14 mm lesion, its biopsy a PDF with an invasive ductal carcinoma, grade 2, +ER+ 90 %, PR- 0 %, HER2 3+ and Ki-67 25 %, and its oncology note stage IIA. H-101's first mammography says +density "tipo E", which the catalog doesn't know: it stays as source text, out of catalog. + H-001 y H-003 también están en el fixture de CaCu, con otro `pac_id`: lo único común entre los dos sistemas es `pac_id_hospital`. Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio. """ +import io from datetime import date, timedelta from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente @@ -69,6 +75,39 @@ NOTAS = ( ("H-104", None, "C50", ONCOLOGIA), # sin fecha: no cuenta ) +# Index in MASTOGRAFIAS -> the radiologist's interpretation. +TEXTOS = { + 0: "Densidad mamaria: tipo E\nSin hallazgos.", + 4: "Densidad mamaria: heterogéneamente densas (C).\nNódulo irregular en CSE.\nTamaño de la lesión: 14 mm.", +} +# Index in BIOPSIAS -> the lines of its pathology report, as a PDF with a text layer. +INFORME_DE_PATOLOGIA = { + 1: ( + "DIAGNÓSTICO: Carcinoma ductal infiltrante", + "Grado histológico: 2 (moderadamente diferenciado)", + "Receptores de estrógeno: Positivo (90%)", + "Receptores de progesterona: Negativo (0%)", + "HER2: 3+", + "Ki-67: 25%", + ), +} +# Patient -> the diagnosis text of their note. +DIAGNOSTICO_DE_NOTA = {"H-003": "Carcinoma de mama izquierda, estadio clínico IIA (T2N0M0)"} + + +def pdf_de(lineas) -> bytes: + """A one-page PDF with these lines as its text layer.""" + from reportlab.lib.pagesizes import letter + from reportlab.pdfgen import canvas + + buffer = io.BytesIO() + hoja = canvas.Canvas(buffer, pagesize=letter) + for i, linea in enumerate(lineas): + hoja.drawString(72, 720 - 18 * i, linea) + hoja.save() + return buffer.getvalue() + + # Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital). # La segunda no es de tamizaje; la tercera está pedida y todavía no tiene mastografía. ORDENES = ( @@ -141,11 +180,12 @@ def insertar(sesion: Session) -> None: mast_calidad_imagen=calidad, mast_birads=birads, mast_fecha_reporte=None if sin_reporte else toma + timedelta(days=7), + mast_interpretacion=TEXTOS.get(indice), ) ) sesion.add_all(mastografias) sesion.flush() - for indice, solicitud, reporte, grado in BIOPSIAS: + for numero, (indice, solicitud, reporte, grado) in enumerate(BIOPSIAS): mastografia = mastografias[indice] sesion.add( BiopsiaMama( @@ -155,6 +195,7 @@ def insertar(sesion: Session) -> None: bx_fecha_solicitud=solicitud, bx_fecha_reporte=reporte, bx_grado_histologico=grado, + bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[numero]) if numero in INFORME_DE_PATOLOGIA else None, ) ) sesion.add_all( @@ -165,6 +206,7 @@ def insertar(sesion: Session) -> None: nm_fecha=fecha, nm_cie_codigo=cie, nm_especialidad=especialidad, + nm_diagnostico_texto=DIAGNOSTICO_DE_NOTA.get(hospital) if especialidad == ONCOLOGIA else None, ) for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1) ) diff --git a/tests/test_extracted_results.py b/tests/test_extracted_results.py new file mode 100644 index 0000000..8dd938e --- /dev/null +++ b/tests/test_extracted_results.py @@ -0,0 +1,178 @@ +"""What this module covers: catalog results read from a staging row's text (`silver.extracted`). The catalog's +`etiquetas_fuente` and `alias` checked when it's read; a report's text, a PDF's text layer and a note turned into +codes, numbers and their sources; a spelling the catalog doesn't know kept as text and turned into a code by a +catalog change alone; and CaMa's load putting them in silver and dbt's timeline. + +Fixtures: `catalogo_en`, a copy of CaMa's catalog in `tmp_path` that the catalog functions read instead of Core's; +`cargada`, the CaMa fixture database (`staging/cama.py`: H-003's texts and pathology PDF, H-101's unknown density) +loaded, with dbt's views when `DBT_MANIFEST` is set. +""" + +import os +from types import SimpleNamespace + +import pytest +from sqlalchemy import text +from staging.cama import INFORME_DE_PATOLOGIA, pdf_de +from webapi.orchestration.reference import catalogs +from webapi.orchestration.reference.catalogs import CatalogoInvalido, catalogo_desde_toml, ruta_de_catalogo +from webapi.orchestration.silver import cama +from webapi.orchestration.silver.extracted import DesdeTexto +from webapi.orchestration.tables import tablas_de + +DENSIDAD = """ +[mastografia] +etiqueta = "Mastografía" + +[mastografia.resultados.densidad] +etiqueta = "Densidad" +tipo_valor = "codigo" +etiquetas_fuente = ["Densidad mamaria"] +valores = [ + { valor = "C", etiqueta = "Heterogéneamente densa", alias = ["Tipo C"] }, + { valor = "D", etiqueta = "Extremadamente densa", alias = ["Tipo D"] }, +] +""" + + +@pytest.fixture +def catalogo_en(tmp_path, monkeypatch): + """Writes a catalog for `cama` in `tmp_path` and points the catalog functions at it. Returns a writer.""" + ruta = tmp_path / "cama.toml" + monkeypatch.setattr(catalogs, "ruta_de_catalogo", lambda proyecto: ruta) + + def escribir(contenido: str): + ruta.write_text(contenido, encoding="utf-8") + return ruta + + return escribir + + +@pytest.fixture +def proyecto(): + return "cama" + + +@pytest.fixture +def cargada(base): + pasos = ("catalogs", "load", "event_models") if os.environ.get("DBT_MANIFEST") else ("catalogs", "load") + base.run(*pasos) + return base + + +def observaciones(base, resultado_prefijo: str) -> dict[str, tuple]: + """`resultado_id` -> (valor_id, valor_numerico, valor_fuente) of the observations whose result starts so.""" + with base.motor.connect() as con: + filas = con.execute(text( + "SELECT resultado_id, valor_id, valor_numerico, valor_fuente FROM observacion_clinica " + "WHERE resultado_id LIKE :p AND (valor_id IS NOT NULL OR valor_numerico IS NOT NULL OR valor_fuente IS NOT NULL)" + ), {"p": resultado_prefijo + "%"}).all() + return {f.resultado_id: (f.valor_id, f.valor_numerico, f.valor_fuente) for f in filas} + + +# --- the catalog --- + +def test_the_catalog_lists_cama_s_extractable_results_as_provisional(): + """Pins down: every CaMa result with captions is extractable and marked provisional, and the catalog still + loads with them. Fails if `resultados_extraibles` drops a result or the new keys break `catalogo_desde_toml`.""" + extraibles = catalogs.resultados_extraibles("cama") + assert set(extraibles) >= {"mastografia.densidad", "biopsia.her2", "nota_medica.estadio_clinico"} + assert all(e.provisional for e in extraibles.values()) + catalogo = catalogo_desde_toml(ruta_de_catalogo("cama"), tablas=tablas_de("cama")) + assert {r.resultado_id for r in catalogo.resultados} >= set(extraibles) + + +@pytest.mark.parametrize("cambio, error", [ + (('alias = ["Tipo D"]', 'alias = ["Tipo C"]'), "se escribe igual"), + (('etiquetas_fuente = ["Densidad mamaria"]', 'etiquetas_fuente = []'), "lista de textos"), + (('etiquetas_fuente = ["Densidad mamaria"]\n', ''), "solo sirven con etiquetas_fuente"), +]) +def test_an_ambiguous_or_incomplete_mapping_is_rejected(catalogo_en, cambio, error): + """Pins down: one spelling on two values, empty captions, or aliases without captions stop the catalog from + loading. Fails if a check is dropped and an alias could turn into either of two codes.""" + ruta = catalogo_en(DENSIDAD.replace(*cambio)) + with pytest.raises(CatalogoInvalido, match=error): + catalogo_desde_toml(ruta, tablas=tablas_de("cama")) + + +# --- reading text --- + +def test_a_report_s_text_gives_codes_with_their_spelling_and_numbers(): + """Pins down: a caption followed by a known spelling gives its code and that spelling as source; a number + after its caption gives the number. Fails if the catalog's aliases stop reaching Extraction's field specs.""" + leido = cama.DE_LA_INTERPRETACION.leer(SimpleNamespace( + mast_interpretacion="Densidad mamaria: heterogéneamente densas (C).\nTamaño de la lesión: 14 mm.")) + assert leido == {"mastografia.densidad": ("C", "heterogéneamente densas"), "mastografia.tamano_lesion_mm": (14.0, None)} + + +def test_an_unknown_spelling_is_kept_as_its_source_without_a_code(): + """Pins down: what follows a caption that matches no alias is kept as source text, with no code. Fails if it's + dropped (it couldn't be found and mapped later) or forced into a code.""" + leido = cama.DE_LA_INTERPRETACION.leer(SimpleNamespace(mast_interpretacion="Densidad mamaria: tipo E")) + assert leido["mastografia.densidad"] == (None, "tipo E") + + +def test_a_stage_is_found_in_a_note_without_a_caption(): + """Pins down: a result marked `buscar_en_texto` is found as a mention in narrative text. Fails if the flag + stops reaching `scan_free_text`.""" + leido = cama.DE_LA_NOTA.leer(SimpleNamespace( + nm_diagnostico_texto="Carcinoma de mama izquierda, estadio clínico IIA (T2N0M0)", nm_pronostico=None)) + assert leido["nota_medica.estadio_clinico"] == ("EIIA", "estadio clínico IIA") + + +def test_a_pathology_pdf_s_text_layer_gives_its_results(): + """Pins down: a PDF's text layer is read without OCR and every result on it comes out. Fails if bytes stop + going through the PDF reader, or a receptor's percentage stops sharing its captions with the receptor.""" + leido = cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[1]))) + assert {r: v for r, (v, _) in leido.items()} == { + "biopsia.tipo_histologico": "DUCTAL_INFILTRANTE", "biopsia.grado_nottingham": "G2", + "biopsia.receptor_estrogeno": "POSITIVO", "biopsia.receptor_estrogeno_pct": 90.0, + "biopsia.receptor_progesterona": "NEGATIVO", "biopsia.receptor_progesterona_pct": 0.0, + "biopsia.her2": "H3", "biopsia.ki67_pct": 25.0, + } + + +def test_no_text_gives_no_values(): + """Pins down: a row without text (or a PDF that can't be read) gives every result empty. Fails if an empty + text or broken bytes raise during a load.""" + assert set(cama.DE_LA_NOTA.leer(SimpleNamespace(nm_diagnostico_texto=None, nm_pronostico=None)).values()) == {(None, None)} + assert set(cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=b"not a pdf")).values()) == {(None, None)} + + +def test_adding_an_alias_maps_the_same_text_on_the_next_read(catalogo_en): + """Pins down: an unknown spelling becomes a code by adding it to the catalog, with nothing else changed. Fails + if the mapping is cached across catalog reads or lives anywhere but the catalog.""" + fila = SimpleNamespace(mast_interpretacion="Densidad mamaria: tipo E") + catalogo_en(DENSIDAD) + antes = DesdeTexto("cama", ("mastografia.densidad",), texto=lambda f: f.mast_interpretacion).leer(fila) + catalogo_en(DENSIDAD.replace('alias = ["Tipo D"]', 'alias = ["Tipo D", "Tipo E"]')) + despues = DesdeTexto("cama", ("mastografia.densidad",), texto=lambda f: f.mast_interpretacion).leer(fila) + assert antes["mastografia.densidad"] == (None, "tipo E") + assert despues["mastografia.densidad"] == ("D", "tipo E") + + +# --- the load --- + +def test_the_load_puts_the_extracted_results_in_silver(cargada): + """Pins down: CaMa's load writes the results read from the interpretation, the pathology PDF and the note, and + an unknown spelling as an out-of-catalog source. Fails if `cama.DESDE_STAGING` stops wiring a `DesdeTexto`.""" + with cargada.motor.connect() as con: + densidades = sorted(con.execute(text( + "SELECT coalesce(valor_id, '?') || ':' || valor_fuente FROM observacion_clinica " + "WHERE resultado_id = 'mastografia.densidad' AND valor_fuente IS NOT NULL")).scalars()) + assert densidades == ["?:tipo E", "C:heterogéneamente densas"] + assert observaciones(cargada, "biopsia.her2") == {"biopsia.her2": ("H3", None, "3+")} + assert observaciones(cargada, "biopsia.ki67_pct") == {"biopsia.ki67_pct": (None, 25.0, None)} + assert observaciones(cargada, "nota_medica.estadio_clinico") == { + "nota_medica.estadio_clinico": ("EIIA", None, "estadio clínico IIA")} + + +def test_the_timeline_carries_the_extracted_results(cargada): + """Pins down: the timeline declares the new results, so H-003's stage, receptors and density are rows of it. + Fails if a source line is missing from `cama_linea_de_tiempo.yml`.""" + if not os.environ.get("DBT_MANIFEST"): + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + filas = cargada.ctx.repos.silver.timeline.read() + valores = {(f["tipo"], f["valor_codigo"] or f["valor_numerico"]) for f in filas} + assert {("estadio_clinico", "EIIA"), ("her2", "H3"), ("receptor_estrogeno_pct", 90.0), + ("densidad_mamaria", "C"), ("densidad_mamaria", "tipo E")} <= valores diff --git a/webapi/orchestration/reference/catalogs.py b/webapi/orchestration/reference/catalogs.py index afb0798..3a59dc3 100644 --- a/webapi/orchestration/reference/catalogs.py +++ b/webapi/orchestration/reference/catalogs.py @@ -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")) diff --git a/webapi/orchestration/silver/cama.py b/webapi/orchestration/silver/cama.py index e81acba..4716e56 100644 --- a/webapi/orchestration/silver/cama.py +++ b/webapi/orchestration/silver/cama.py @@ -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), ) diff --git a/webapi/orchestration/silver/extracted.py b/webapi/orchestration/silver/extracted.py new file mode 100644 index 0000000..dee3604 --- /dev/null +++ b/webapi/orchestration/silver/extracted.py @@ -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 diff --git a/webapi/orchestration/silver/orders_and_notes.py b/webapi/orchestration/silver/orders_and_notes.py index f7ecde6..3c20ba5 100644 --- a/webapi/orchestration/silver/orders_and_notes.py +++ b/webapi/orchestration/silver/orders_and_notes.py @@ -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 {})}, )