Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| dc9a3422e0 | |||
| 97480ab832 |
+43
-1
@@ -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)
|
||||
)
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""What this module covers: CaMa's tumour stratifiers, from the results read from reports to a measure's strata.
|
||||
dbt's `cama_estratificadores` (stage group, early or advanced stage, surrogate molecular subtype, T by size) as
|
||||
timeline facts; `CAMA_BIRADS_CANCER_INVASOR` broken down by them with the `linea_de_tiempo_al_corte` stratum; and the
|
||||
labels a timeline stratum's values carry into FHIR.
|
||||
|
||||
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database
|
||||
(`staging/cama.py`) through the cycle up to `event_models`. Only H-003 has an invasive cancer: biopsy reported on
|
||||
2025-07-28 from her BI-RADS 4A mammogram (14 mm), HER2 3+, and a note of 2025-08-04 with stage IIA.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import replace
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from conftest import base_de
|
||||
from sqlalchemy import text
|
||||
from webapi.compositions import answer_composition, composition_definitions
|
||||
from webapi.fhir.measures import _label
|
||||
from webapi.metrics import Question
|
||||
|
||||
URL = "cama/CAMA_BIRADS_CANCER_INVASOR"
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manifest():
|
||||
path = os.environ.get("DBT_MANIFEST")
|
||||
if not path:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
return Path(path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def base(tmp_path, sin_supresion, manifest):
|
||||
base = base_de("cama", tmp_path)
|
||||
base.run(*UNTIL_MODELS, parameters=sin_supresion, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def answered(base, manifest, period: str, event_cutoff: date | None = None):
|
||||
d = base.dominio
|
||||
definition = composition_definitions(manifest)[URL]
|
||||
return answer_composition("cama", definition, Question(URL, period, event_cutoff=event_cutoff),
|
||||
parameters=d.def_parametro_repository, periods=d.dim_periodo_repository,
|
||||
history=d.history_repository, queries=d.dbt_query_repository, allow_undecided=True)
|
||||
|
||||
|
||||
def stratifiers(base) -> set[str]:
|
||||
with base.motor.connect() as con:
|
||||
return set(con.execute(text("select tipo from cama_estratificadores")).scalars())
|
||||
|
||||
|
||||
def test_the_stratifiers_come_from_h003_s_reports(base):
|
||||
"""Pins down: the view derives the stage's group and early stage from the note, the subtype from the pathology
|
||||
report and T1 from the 14 mm lesion, and nothing for patients without those results. Fails if a rule in
|
||||
`vars.cama.estratos` or a timeline `tipo` it reads changes."""
|
||||
assert stratifiers(base) == {"estadio_ii", "etapa_temprana", "subtipo_her2", "tamano_t1"}
|
||||
|
||||
|
||||
def test_the_measure_breaks_down_the_invasive_cancers_by_tumour(base, manifest):
|
||||
"""Pins down: H-003 counts in S2, the period of her biopsy report, under the BI-RADS of the mammogram that led to
|
||||
it, and in each stratum by what her reports said. S1 has no invasive cancer. Fails if the event model, the
|
||||
category or a stratum's values drift."""
|
||||
assert answered(base, manifest, "2025-S1").categories == {}
|
||||
result = answered(base, manifest, "2025-S2")
|
||||
assert result.categories == {"B4A": 1}
|
||||
assert result.strata == {"grupo_edad": {"50-59": {"B4A": 1}}, "estadio": {"II": {"B4A": 1}},
|
||||
"etapa": {"TEMPRANA": {"B4A": 1}}, "clasificacion": {"HER2": {"B4A": 1}},
|
||||
"tamano": {"T1": {"B4A": 1}}}
|
||||
|
||||
|
||||
def test_a_stratum_by_the_cut_off_sees_only_what_was_dated_by_then(base, manifest):
|
||||
"""Pins down: `linea_de_tiempo_al_corte` reads the timeline up to the event cut-off: on 2025-08-01 the subtype
|
||||
(report of 07-28) is known and the stage (note of 08-04) isn't yet. Fails if the stratum reads before the period's
|
||||
start (H-003 would have nothing) or ignores the cut-off (she'd have her stage)."""
|
||||
strata = answered(base, manifest, "2025-S2", event_cutoff=date(2025, 8, 1)).strata
|
||||
assert strata["clasificacion"] == {"HER2": {"B4A": 1}}
|
||||
assert strata["estadio"] == {"SIN_DATO": {"B4A": 1}}
|
||||
|
||||
|
||||
SUBTIPOS = [
|
||||
({"her2": "H3"}, "subtipo_her2"),
|
||||
({"her2": "H1", "receptor_estrogeno": "NEGATIVO", "receptor_progesterona": "NEGATIVO"}, "subtipo_triple_negativo"),
|
||||
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 10.0}, "subtipo_luminal_a"),
|
||||
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 30.0}, "subtipo_luminal_b"),
|
||||
({"her2": "H0", "receptor_progesterona_pct": 10.0, "ki67_pct": 10.0}, "subtipo_luminal_b"),
|
||||
({"her2": "H0", "ki67_pct": None}, None),
|
||||
({"her2": "H2"}, None),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cambios, subtipo", SUBTIPOS)
|
||||
def test_the_surrogate_subtype_follows_its_rules(base, cambios, subtipo):
|
||||
"""Pins down the surrogate subtype from one pathology report: HER2 3+ is HER2-positive; HER2 0 or 1+ with both
|
||||
receptors negative, triple negative; with a positive receptor, luminal A only with Ki-67 under 20 % and
|
||||
progesterone of at least 20 %, else luminal B; without Ki-67, or with an equivocal HER2, none. The fixture's
|
||||
report starts as ER+ 90 %, PR- 0 %, HER2 3+, Ki-67 25 %, with PR made positive here unless a case says otherwise.
|
||||
Fails if a branch of the rule or a threshold in `vars.cama.estratos` changes."""
|
||||
valores = {"receptor_progesterona": "POSITIVO", **cambios}
|
||||
with base.motor.begin() as con:
|
||||
for nombre, valor in valores.items():
|
||||
columna = "valor_numerico" if nombre.endswith("_pct") else "valor_id"
|
||||
con.execute(text(f"update observacion_clinica set {columna} = :v where resultado_id = :r"),
|
||||
{"v": valor, "r": f"biopsia.{nombre}"})
|
||||
assert {t for t in stratifiers(base) if t.startswith("subtipo_")} == ({subtipo} if subtipo else set())
|
||||
|
||||
|
||||
def test_a_timeline_stratum_s_values_carry_their_labels():
|
||||
"""Pins down: FHIR labels a timeline stratum's value from its entry in `valores`, and its `resto` from
|
||||
`resto_etiqueta`. Fails if `_label` reads labels only from a map."""
|
||||
spec = {"valores": [{"valor": "II", "etiqueta": "Estadio II", "si": []}], "resto": "SIN_DATO",
|
||||
"resto_etiqueta": "Sin dato"}
|
||||
assert (_label(spec, "II"), _label(spec, "SIN_DATO"), _label(spec, "IV")) == ("Estadio II", "Sin dato", None)
|
||||
@@ -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
|
||||
@@ -45,7 +45,7 @@ def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client):
|
||||
with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape."""
|
||||
domain, client = domain_client
|
||||
measures = valid(client.get(f"/{domain}/fhir/Measure").get_json())
|
||||
assert measures["total"] == 7
|
||||
assert measures["total"] == {"cacu": 7, "cama": 8}[domain]
|
||||
for item in measures["entry"]:
|
||||
response = client.get(f"/{domain}/fhir/Measure/{item['resource']['id']}/$evaluate-measure?periodo=2025-S1")
|
||||
assert response.status_code in (200, 409), response.get_json()
|
||||
|
||||
@@ -84,11 +84,11 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
|
||||
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
|
||||
resumen = base.run("definitions")["definitions"]
|
||||
|
||||
# CaCu: three strata and its seven measures; CaMa: its seven measures, without strata; TEA: the age group and its
|
||||
# ten measures.
|
||||
assert resumen["definitions"] == {"cacu": 10, "cama": 7, "tea": 11}[base.proyecto]
|
||||
# CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers and its eight measures;
|
||||
# TEA: the age group and its ten measures.
|
||||
assert resumen["definitions"] == {"cacu": 10, "cama": 13, "tea": 11}[base.proyecto]
|
||||
# Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado.
|
||||
assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 7, "tea": 10}[base.proyecto]
|
||||
assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 8, "tea": 10}[base.proyecto]
|
||||
assert base.run("definitions")["definitions"]["borradas"] == 0
|
||||
|
||||
|
||||
|
||||
@@ -120,9 +120,15 @@ def _proportion_cells(definition, counts: Counts, excluded: int | None = None) -
|
||||
|
||||
|
||||
def _label(spec: dict, value: str) -> str | None:
|
||||
"""A stratum value's label, when the stratum's `valores` maps values to labels."""
|
||||
"""A stratum value's label: from `valores` as a map of values to labels, or as a list of entries with `etiqueta`
|
||||
(a timeline stratum's), or `resto_etiqueta` for its `resto`."""
|
||||
labels_of = spec.get("valores")
|
||||
return labels_of.get(value) if isinstance(labels_of, dict) else None
|
||||
if isinstance(labels_of, dict):
|
||||
return labels_of.get(value)
|
||||
if isinstance(labels_of, list):
|
||||
found = [v.get("etiqueta") for v in labels_of if isinstance(v, dict) and v.get("valor") == value]
|
||||
return found[0] if found else (spec.get("resto_etiqueta") if value == spec.get("resto") else None)
|
||||
return None
|
||||
|
||||
|
||||
def _stratum_value(stratifier: str, value: str, display: str | None = None) -> dict:
|
||||
|
||||
+12
-3
@@ -46,6 +46,7 @@ TOTAL = "total"
|
||||
NO_DATA = "sin_dato"
|
||||
AGE_AT_PERIOD_START = "edad_al_inicio_del_periodo"
|
||||
TIMELINE_AT_PERIOD_START = "linea_de_tiempo_al_inicio_del_periodo"
|
||||
TIMELINE_BY_CUTOFF = "linea_de_tiempo_al_corte"
|
||||
OF_THE_CHOSEN = "del_elegido"
|
||||
COLUMN = "columna"
|
||||
STATUS_AT_PERIOD_END = "estado_al_fin_del_periodo"
|
||||
@@ -129,6 +130,9 @@ class Stratum:
|
||||
`fecha` and `conocida_en`) held before the period's start. `valores` are tried in order and the first whose
|
||||
condition holds is the value, else `resto`; a condition (`si`) is a list of alternatives, each a map from a
|
||||
timeline `tipo` to whether there was one;
|
||||
- `linea_de_tiempo_al_corte`: the same, with what the timeline held by the question's event cut-off (all of it
|
||||
without one) instead of before the period's start: a patient's characteristic learned after the fact that
|
||||
put her in the period, such as the stage of a cancer whose biopsy the period counts;
|
||||
- `del_elegido`: in a composition, the `valor` column of the fact that gave the unit its category;
|
||||
- `columna`: a column of the event model (`columna`), one value per unit; `sin_dato` when null.
|
||||
"""
|
||||
@@ -143,7 +147,7 @@ class Stratum:
|
||||
|
||||
@classmethod
|
||||
def of(cls, name: str, spec: dict) -> "Stratum":
|
||||
if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, OF_THE_CHOSEN, COLUMN):
|
||||
if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, TIMELINE_BY_CUTOFF, OF_THE_CHOSEN, COLUMN):
|
||||
raise NotImplementedError(f"strata of kind {spec['tipo']!r} aren't answered")
|
||||
return cls(name, spec["tipo"], spec)
|
||||
|
||||
@@ -411,7 +415,8 @@ class MeasureQueries:
|
||||
return joined
|
||||
|
||||
def _timeline(self, stratum: Stratum):
|
||||
"""Per patient, one 0/1 column per timeline `tipo` the stratum asks about: had one before the period's start.
|
||||
"""Per patient, one 0/1 column per timeline `tipo` the stratum asks about: had one before the period's start
|
||||
(or, for `linea_de_tiempo_al_corte`, by the event cut-off).
|
||||
|
||||
Known by the knowledge cut-off, if the question has one. Joined, not correlated, so the value can be grouped
|
||||
by on every engine.
|
||||
@@ -422,7 +427,11 @@ class MeasureQueries:
|
||||
line = table(stratum.spec["linea"], column("pac_id"), column("tipo"), column("fecha"),
|
||||
column("conocida_en", FechaHoraUTC))
|
||||
period = self.periods.alias(f"periodo_{stratum.name}")
|
||||
conditions = [line.c.tipo.in_(kinds), line.c.fecha < period.c.inicio]
|
||||
conditions = [line.c.tipo.in_(kinds)]
|
||||
if stratum.kind == TIMELINE_AT_PERIOD_START:
|
||||
conditions.append(line.c.fecha < period.c.inicio)
|
||||
elif self.q.event_cutoff is not None:
|
||||
conditions.append(line.c.fecha <= self.q.event_cutoff.isoformat())
|
||||
if self.q.knowledge_cutoff is not None:
|
||||
conditions.append(line.c.conocida_en <= self.q.knowledge_cutoff)
|
||||
had = (select(line.c.pac_id, *(func.max(case((line.c.tipo == k, 1), else_=0)).label(k) for k in kinds))
|
||||
|
||||
@@ -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"))
|
||||
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
|
||||
@@ -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 {})},
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user