Compare commits
34 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9737b5a67f | |||
| 854a2e9c55 | |||
| b8045e7481 | |||
| 6dce665d93 | |||
| 461d651805 | |||
| 790879513b | |||
| 73cbf0cfb8 | |||
| 64d3d721e3 | |||
| cea74e1566 | |||
| 113b792a7b | |||
| f183e495fb | |||
| 9775a22c57 | |||
| 7d5c79f520 | |||
| e224b8b2aa | |||
| 205bc214fa | |||
| 4fc822d5c7 | |||
| 73b1db1121 | |||
| ea228da7b4 | |||
| e19121bc42 | |||
| 8f84253205 | |||
| ce67de17bc | |||
| e41a2b7127 | |||
| 0f9433949f | |||
| a0407e41d6 | |||
| 59fe94ad97 | |||
| edd12df144 | |||
| 96a29cfb19 | |||
| 7d0213eda7 | |||
| 1710cd5ca2 | |||
| 3c28a43cb1 | |||
| 21e6533dab | |||
| b9adedbf6f | |||
| 0cbe390b25 | |||
| 0f00a975fa |
+23
-1
@@ -1,6 +1,22 @@
|
||||
# Build context is the repo root (see docker-compose.yml) so the sibling
|
||||
# packages Core/, Persistance/, Extraction/ and models/
|
||||
# can be copied.
|
||||
# can be copied, and Transformation/ compiled.
|
||||
|
||||
# dbt's manifest: the measures' definitions and the compiled SQL of their event
|
||||
# models. The API serves the measures from it and the indicator cycle creates
|
||||
# the views. The manifest built here is SQLite's, the image's default engine;
|
||||
# the same environments compile it again at start-up against MySQL/MariaDB,
|
||||
# PostgreSQL or SQL Server when *_DATABASE_URL points there (docker-entrypoint.sh),
|
||||
# because those adapters open a connection to compile. dbt-mysql needs an
|
||||
# older dbt-core, so it gets an environment of its own.
|
||||
FROM python:3.12-slim AS manifest
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.7.9 /uv /uvx /bin/
|
||||
WORKDIR /app/Transformation
|
||||
COPY Transformation/ ./
|
||||
RUN uv sync --group sqlite --group sqlserver --group postgres \
|
||||
&& UV_PROJECT_ENVIRONMENT=.venv-mysql uv sync --only-group mysql \
|
||||
&& uv run --no-sync dbt compile --profiles-dir . --profile cacu --target sqlite --no-introspect
|
||||
|
||||
FROM python:3.12-slim
|
||||
|
||||
# Tesseract (with Spanish data) for scanned documents; pytesseract only wraps the binary.
|
||||
@@ -34,6 +50,12 @@ ENV MLFLOW_DISABLE_TELEMETRY=true DO_NOT_TRACK=true
|
||||
ENV WEBAPI_REPORT_DIR=/data/reportes
|
||||
ENV INDICADORES_DIR=/data/indicadores
|
||||
ENV MLFLOW_DISABLE_AGENT_HINT=1
|
||||
# Without it the measure routes (/<domain>/indicadores, /<domain>/fhir) aren't
|
||||
# registered. The entrypoint replaces it with one compiled against the
|
||||
# deployment's engine when that engine isn't SQLite (webapi.dbt_manifest).
|
||||
COPY --from=manifest /app/Transformation /app/Transformation
|
||||
ENV DBT_MANIFEST=/app/Transformation/target/manifest.json
|
||||
ENV TRANSFORMATION_DIR=/app/Transformation
|
||||
|
||||
RUN chmod +x /app/WebApi/docker-entrypoint.sh
|
||||
|
||||
|
||||
@@ -18,13 +18,15 @@ webapi/
|
||||
│ ├── data.py /data: lectura paginada de cada tabla importable
|
||||
│ ├── cacu.py, cama.py, tea.py /<dominio>/indicadores
|
||||
│ ├── reportes.py /reportes: bitácora de importaciones y estado del recálculo
|
||||
│ └── governance.py /governance: versiones de modelos y cola de OCR
|
||||
│ └── governance.py /governance: versiones de modelos, notebooks y cola de OCR
|
||||
├── imports/
|
||||
│ ├── connectors/ una clase por tipo de fuente (@register_connector)
|
||||
│ ├── schemas/ un esquema pydantic por tabla destino; registry.py los enlista
|
||||
│ ├── mapping/ sugerencia de mapeo de columnas
|
||||
│ ├── services/ validación, combinación de fuentes, enlace de llaves y escritura
|
||||
│ ├── services/ validación, combinación de fuentes, enlace de llaves, escritura
|
||||
│ │ y aprendizaje de las correcciones de documentos (review_learning.py)
|
||||
│ └── audit.py bitácora agregada (sin datos de pacientes)
|
||||
├── nlp.py python -m webapi.nlp evaluate|train: extracción contra una clave de respuestas
|
||||
├── indicadores.py rutas de indicadores (del equipo de indicadores)
|
||||
├── recomputation.py cola y servicio que recalcula indicadores tras cada carga
|
||||
└── seguimiento.py lista de seguimiento por paciente (solo con DEV_REVISION)
|
||||
@@ -45,7 +47,7 @@ y una entrada en `imports/schemas/registry.py`.
|
||||
| `/data/<dominio>.<Tabla>` | Filas de una tabla importable, paginadas (`limit`, `offset`) |
|
||||
| `/<dominio>/indicadores` | Catálogo de indicadores y, por indicador, `/periodos`, `/datos`, `/metadatos` y `/figuras/<figura>` |
|
||||
| `/reportes` | `GET /reportes/importaciones` (resumen y últimos intentos), `/importaciones/descarga`, `GET /reportes/indicadores`, `POST /reportes/indicadores/<dominio>/recalcular` |
|
||||
| `/governance` | Versiones de modelos en MLflow (registro, revisión, promoción, retiro) y cola de revisión de OCR |
|
||||
| `/governance` | Versiones de modelos en MLflow (registro, revisión, promoción, retiro, descarga de sus archivos), notebooks corridos sobre una cohorte exportada (`/governance/experiments`, `/governance/cohort-files`) y cola de revisión de OCR |
|
||||
| `/health` | Verificación de vida |
|
||||
|
||||
Los errores de la solicitud se responden con `{"error": "..."}` y código 400
|
||||
@@ -69,6 +71,15 @@ Los errores de la solicitud se responden con `{"error": "..."}` y código 400
|
||||
| `INDICADORES_INTERVALO_S` | `20` | Cada cuánto revisa la cola |
|
||||
| `INDICADORES_AL_INICIAR` | `1` | Recalcular los tres dominios al arrancar |
|
||||
| `PORT`, `WEBAPI_WORKERS`, `WEBAPI_TIMEOUT` | `5000`, `2`, `600` | gunicorn en el contenedor |
|
||||
| `NOTEBOOK_JOBS_DIR` | sin carpeta | Carpeta compartida con el servicio `notebooks`; con ella los notebooks corren aislados en ese contenedor |
|
||||
| `NOTEBOOK_EXECUTOR` | `contenedor` con `NOTEBOOK_JOBS_DIR`, si no `local` | Dónde corren los notebooks; `local` es en el propio proceso, sin aislar (desarrollo) |
|
||||
| `NOTEBOOK_RUNNER_UID` | ninguno | Usuario del contenedor `notebooks`, dueño de cada carpeta de trabajo |
|
||||
| `NOTEBOOK_JOB_TIMEOUT`, `NOTEBOOK_CELL_TIMEOUT` | `21600`, `1800` | Segundos que espera un notebook completo y una celda |
|
||||
| `NOTEBOOK_MAX_IMPORT_MB` | `500` | Tope de archivos que se importan de lo que entrenó un notebook |
|
||||
| `WEBAPI_NOTEBOOK_WORKERS` | `1` | Notebooks a la vez por proceso de la API |
|
||||
| `EXTRACTION_RANKER` | `auto` | Ranker de extracción de documentos: `auto` (el de producción, si no el último), `produccion` (solo el de producción) o `ninguno` |
|
||||
| `EXTRACTION_LEARNING` | `1` | `0` deja de aprender de las correcciones hechas al revisar documentos |
|
||||
| `NOTEBOOK_RENDERER` | `quarto` si está instalado, si no `jupyter` | Con qué se corre y se arma la página |
|
||||
|
||||
## Ejecución
|
||||
|
||||
@@ -83,6 +94,15 @@ uv run python main.py # http://localhost:5050
|
||||
uv run python -m webapi.recomputation # recálculo de indicadores, en otra terminal
|
||||
```
|
||||
|
||||
Medir la extracción de documentos contra una clave de respuestas (por documento y
|
||||
destino, el valor correcto de cada campo revisado; `null` si debe quedar vacío)
|
||||
y entrenar con ella el ranker del dominio (`Extraction/README.md`):
|
||||
|
||||
```bash
|
||||
uv run python -m webapi.nlp evaluate --documents carpeta/ --key clave.json [--with-values] [--no-ranker]
|
||||
uv run python -m webapi.nlp train --documents carpeta/ --key clave.json
|
||||
```
|
||||
|
||||
Con Docker, desde la raíz del repositorio: `docker compose up --build`. La
|
||||
imagen se construye con `WebApi/Dockerfile` (contexto: la raíz, para copiar
|
||||
los paquetes hermanos); `docker-entrypoint.sh` aplica las migraciones y
|
||||
|
||||
+25
-2
@@ -1,6 +1,12 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# The notebook runner shares the image but runs with no network, a read-only
|
||||
# system and only the jobs folder (models.io.notebook_jobs): it never touches /data.
|
||||
if [ "$1" = "notebooks" ]; then
|
||||
exec /app/WebApi/.venv/bin/python -m models notebooks serve
|
||||
fi
|
||||
|
||||
mkdir -p /data
|
||||
|
||||
# SQLite won't create a missing parent directory for its database file.
|
||||
@@ -10,14 +16,31 @@ for url in "$CACU_DATABASE_URL" "$CAMA_DATABASE_URL" "$TEA_DATABASE_URL" "$GOVER
|
||||
esac
|
||||
done
|
||||
|
||||
cd /app/WebApi
|
||||
|
||||
# dbt's manifest for the deployment's engine: the image's is SQLite's; on
|
||||
# another engine it's compiled now, against the configured databases, into
|
||||
# /data (webapi.dbt_manifest prints the path to use, or nothing to keep the
|
||||
# image's).
|
||||
if compiled="$(uv run --no-sync python -m webapi.dbt_manifest)"; then
|
||||
[ -n "$compiled" ] && export DBT_MANIFEST="$compiled"
|
||||
else
|
||||
echo "dbt manifest: compilation failed; the measure routes will stay unregistered" >&2
|
||||
fi
|
||||
|
||||
# The live indicator worker (webapi.recomputation) shares the image; the
|
||||
# API container runs the migrations, so the worker starts after it.
|
||||
if [ "$1" = "indicadores" ]; then
|
||||
cd /app/WebApi
|
||||
exec uv run --no-sync python -m webapi.recomputation
|
||||
fi
|
||||
|
||||
cd /app/WebApi
|
||||
# One-shot training of the CaCu model on the loaded data (compose profile
|
||||
# `entrenar`): the trained version goes into production and the worker's next
|
||||
# cycle estimates with it.
|
||||
if [ "$1" = "entrenar" ]; then
|
||||
exec uv run --no-sync python -m models run cacu cin2_logistic --export --train --promote
|
||||
fi
|
||||
|
||||
# --no-sync: the environment was synced at build time; syncing at startup
|
||||
# would try to reach the package index (and pull dev deps).
|
||||
for domain in cacu cama tea governance; do
|
||||
|
||||
+3
-1
@@ -6,7 +6,7 @@ requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"flask>=3.0",
|
||||
"persistance",
|
||||
"models[export]",
|
||||
"models[notebooks]",
|
||||
"extraction",
|
||||
"apache-hamilton>=1.90",
|
||||
"pandas>=2.0",
|
||||
@@ -20,6 +20,7 @@ dependencies = [
|
||||
"gunicorn>=23.0",
|
||||
"sqlglot>=25.0",
|
||||
"rapidfuzz>=3.9",
|
||||
"watchdog>=6.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
@@ -43,6 +44,7 @@ packages = ["webapi"]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"fhir-resources>=8",
|
||||
"pytest>=8.0.0",
|
||||
"reportlab>=4.0",
|
||||
]
|
||||
|
||||
+5
-1
@@ -31,6 +31,10 @@ os.environ.setdefault("WEBAPI_SQL_ALLOWED_DIALECTS", "sqlite,mysql,mariadb,postg
|
||||
_STATE_DIR = tempfile.mkdtemp(prefix="webapi-tests-")
|
||||
os.environ.setdefault("WEBAPI_REPORT_DIR", os.path.join(_STATE_DIR, "reportes"))
|
||||
os.environ.setdefault("INDICADORES_DIR", os.path.join(_STATE_DIR, "indicadores"))
|
||||
# Extraction ranks by confidence and learns nothing unless a test sets up a
|
||||
# model registry of its own (test_review_learning.py).
|
||||
os.environ.setdefault("EXTRACTION_RANKER", "ninguno")
|
||||
os.environ.setdefault("EXTRACTION_LEARNING", "0")
|
||||
|
||||
ANIO = 2025
|
||||
|
||||
@@ -67,7 +71,7 @@ def base_de(proyecto: str, carpeta, datos=None) -> Base:
|
||||
return Base(proyecto, ctx, import_module(f"persistance.{proyecto}"), motor)
|
||||
|
||||
|
||||
@pytest.fixture(params=["cacu", "cama"])
|
||||
@pytest.fixture(params=["cacu", "cama", "tea"])
|
||||
def proyecto(request):
|
||||
return request.param
|
||||
|
||||
|
||||
+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,139 @@
|
||||
"""TEA's synthetic staging, written by hand. Never real data.
|
||||
|
||||
Seven children screened in 2025, each one exercising a rule of the screening's chain (M-CHAT, psychology note
|
||||
with the ADOS-2, neuropediatrics note, good-quality EEG). Ages are at the first M-CHAT, in completed months:
|
||||
|
||||
- 1, H-T01, 19 months (16 to 23): the whole chain. M-CHAT 10 Jan, ADOS-2 5 Feb, F84.0 note 12 Mar, a bad EEG
|
||||
2 Apr, a good EEG 20 May with a slow posterior rhythm, then a second good EEG 1 Sep that changes nothing. Leaves
|
||||
after May. Its EEG has an order.
|
||||
- 2, H-T02, 26 months (24 to 29): M-CHAT 20 Jan, ADOS-2 1 Mar, a note with F84 without subcode 10 Apr (not a
|
||||
confirmation), no EEG: stays at neuropediatrics.
|
||||
- 3, H-T03, 35 months (30 to 36): M-CHAT 14 Feb (a second one 10 Jun doesn't count), ADOS-2 28 Feb, nothing else:
|
||||
stays at psychology.
|
||||
- 4, H-T04, 39 months: out of the cohort, never counted.
|
||||
- 5, H-T05, 21 months: M-CHAT 15 Jun, a F84.0 note 1 Jul and a good EEG 20 Jul without the ADOS-2: steps go in
|
||||
order, so it stays at M-CHAT and in process.
|
||||
- 6, H-T06, 26 months: M-CHAT 5 Apr, ADOS-2 20 Apr, a good EEG 1 Jun before its F84.0 note of 2 Jun: the EEG
|
||||
step is dated by the note, so it reaches EEG on 2 Jun and leaves after June.
|
||||
- 7, H-T07, without birth date: in the cohort with age group `sin_dato`. M-CHAT 1 May, nothing else.
|
||||
|
||||
Every EEG's quality criteria are written as its analysis would; a bad EEG has one criterion out of its threshold.
|
||||
|
||||
Test support: writes in the session it's given, never in the domain's database.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core.tea.models import (
|
||||
Ados2,
|
||||
Eeg,
|
||||
EegMetrica,
|
||||
EegMetricaElectrodo,
|
||||
EvaluacionNeuropediatrica,
|
||||
Mchat,
|
||||
OrdenesEstudio,
|
||||
Pacientes,
|
||||
)
|
||||
from sqlmodel import Session
|
||||
|
||||
# (pac_id, pac_id_hospital, birth date)
|
||||
PACIENTES = (
|
||||
(1, "H-T01", date(2023, 6, 1)),
|
||||
(2, "H-T02", date(2022, 11, 15)),
|
||||
(3, "H-T03", date(2022, 3, 1)),
|
||||
(4, "H-T04", date(2021, 12, 1)),
|
||||
(5, "H-T05", date(2023, 9, 1)),
|
||||
(6, "H-T06", date(2023, 1, 10)),
|
||||
(7, "H-T07", None),
|
||||
)
|
||||
|
||||
# (pac_id, date, score)
|
||||
MCHATS = (
|
||||
(1, date(2025, 1, 10), 12),
|
||||
(2, date(2025, 1, 20), 9),
|
||||
(3, date(2025, 2, 14), 15),
|
||||
(3, date(2025, 6, 10), 4),
|
||||
(4, date(2025, 3, 3), 11),
|
||||
(5, date(2025, 6, 15), 8),
|
||||
(6, date(2025, 4, 5), 14),
|
||||
(7, date(2025, 5, 1), 7),
|
||||
)
|
||||
|
||||
# (pac_id, date, module, CSS, classification)
|
||||
ADOS2 = (
|
||||
(1, date(2025, 2, 5), "MODULO_1", 7, "AUTISMO"),
|
||||
(2, date(2025, 3, 1), "Toddler", 4, "espectro autista"),
|
||||
(3, date(2025, 2, 28), "MODULO_2", 2, "NO_TEA"),
|
||||
(6, date(2025, 4, 20), "MODULO_1", 8, "AUTISMO"),
|
||||
)
|
||||
|
||||
# (pac_id, date, ICD-10 as the hospital writes it)
|
||||
NOTAS = (
|
||||
(1, date(2025, 3, 12), "F84.0"),
|
||||
(2, date(2025, 4, 10), "F84"),
|
||||
(5, date(2025, 7, 1), "f84.0"),
|
||||
(6, date(2025, 6, 2), "F84.0"),
|
||||
)
|
||||
|
||||
GOOD = {"amplitud": 0, "alta_frecuencia": 1, "correlacion": 0, "sin_senal": 0, "linea": 3.5}
|
||||
BAD = {**GOOD, "sin_senal": 5}
|
||||
|
||||
# (eeg id, pac_id, date, laboratory id, criteria, with sleep)
|
||||
EEGS = (
|
||||
("eeg-1a", 1, date(2025, 4, 2), "LAB-1A", BAD, 0),
|
||||
("eeg-1b", 1, date(2025, 5, 20), "LAB-1B", GOOD, 1),
|
||||
("eeg-1c", 1, date(2025, 9, 1), "LAB-1C", GOOD, 1),
|
||||
("eeg-5", 5, date(2025, 7, 20), "LAB-5", GOOD, 0),
|
||||
("eeg-6", 6, date(2025, 6, 1), "LAB-6", GOOD, 1),
|
||||
)
|
||||
|
||||
# (metric id, eeg id, code, value): a null value can't be evaluated.
|
||||
METRICAS = (
|
||||
("met-1b-rp", "eeg-1b", "RITMO_POSTERIOR", 3.2),
|
||||
("met-1b-n2", "eeg-1b", "HUSOS_SUENO_N2", 4.0),
|
||||
("met-1b-pp", "eeg-1b", "PICOS_PAROXISTICOS", 0.4),
|
||||
("met-1a-rp", "eeg-1a", "RITMO_POSTERIOR", 2.0),
|
||||
("met-6-rp", "eeg-6", "RITMO_POSTERIOR", 6.5),
|
||||
("met-6-n2", "eeg-6", "HUSOS_SUENO_N2", None),
|
||||
("met-6-gr", "eeg-6", "GRADIENTE_ANTEROPOSTERIOR", 2.6),
|
||||
)
|
||||
|
||||
# (electrode value id, metric id, electrode, z-score)
|
||||
ELECTRODOS = (
|
||||
("mel-1", "met-1b-rp", "O1", -2.8),
|
||||
("mel-2", "met-1b-rp", "O2", -2.4),
|
||||
("mel-3", "met-1b-rp", "Pz", -1.1),
|
||||
)
|
||||
|
||||
# The EEG of child 1 that completes the chain hangs from an order.
|
||||
ORDENES = (("ord-1b", 1, "ORD-T01-EEG", "ELECTROENCEFALOGRAMA", date(2025, 5, 2)),)
|
||||
ORDEN_DE = {"eeg-1b": "ord-1b"}
|
||||
|
||||
# What the load gives (`test_orquestacion_plata`).
|
||||
PROCEDIMIENTOS = len(ORDENES) + len(MCHATS) + len(ADOS2) + len(NOTAS) + len(EEGS) + len(ELECTRODOS)
|
||||
|
||||
|
||||
def insertar(sesion: Session) -> None:
|
||||
"""Writes the children, their orders and their studies."""
|
||||
sesion.add_all(Pacientes(pac_id=p, pac_id_hospital=h, pac_fecha_nacimiento=n) for p, h, n in PACIENTES)
|
||||
sesion.add_all(OrdenesEstudio(ord_id=i, ord_pac_id=p, ord_id_hospital=h, ord_tipo_estudio=t, ord_fecha=f)
|
||||
for i, p, h, t, f in ORDENES)
|
||||
sesion.add_all(Mchat(mch_id=f"mch-{k}", mch_pac_id=p, mch_fecha=f, mch_puntaje=s)
|
||||
for k, (p, f, s) in enumerate(MCHATS, 1))
|
||||
for k, (p, f, modulo, css, clasificacion) in enumerate(ADOS2, 1):
|
||||
items = {f"ado_sa_b{n}": n % 3 for n in range(1, 6)} | {"ado_rrb_d1": 2, "ado_rrb_d2": 1}
|
||||
sesion.add(Ados2(ado_id=f"ado-{k}", ado_pac_id=p, ado_fecha=f, ado_modulo=modulo, ado_css=css,
|
||||
ado_clasificacion=clasificacion, ado_algoritmo="Pocas o ninguna palabra", **items))
|
||||
sesion.add_all(EvaluacionNeuropediatrica(neu_id=f"neu-{k}", neu_pac_id=p, neu_fecha=f, neu_cie_codigo=c)
|
||||
for k, (p, f, c) in enumerate(NOTAS, 1))
|
||||
for i, p, f, lab, criterios, sueno in EEGS:
|
||||
sesion.add(Eeg(
|
||||
eeg_id=i, eeg_pac_id=p, eeg_fecha_estudio=f, eeg_id_registro_laboratorio=lab, eeg_ord_id=ORDEN_DE.get(i),
|
||||
eeg_con_sueno=sueno, eeg_canales=19, eeg_duracion_min=25.0,
|
||||
eeg_canales_amplitud=criterios["amplitud"], eeg_canales_alta_frecuencia=criterios["alta_frecuencia"],
|
||||
eeg_canales_correlacion=criterios["correlacion"], eeg_canales_sin_senal=criterios["sin_senal"],
|
||||
eeg_ruido_linea_db=criterios["linea"],
|
||||
))
|
||||
sesion.add_all(EegMetrica(met_id=i, met_eeg_id=e, met_codigo=c, met_valor=v) for i, e, c, v in METRICAS)
|
||||
sesion.add_all(EegMetricaElectrodo(mel_id=i, mel_met_id=m, mel_electrodo=e, mel_valor=v)
|
||||
for i, m, e, v in ELECTRODOS)
|
||||
@@ -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,117 @@
|
||||
"""`commit_discovered_fields`: writes captions no known field claims
|
||||
straight into `procedimiento`/`observacion`, tagged apart from every
|
||||
staging-derived row with `FUENTE_CATALOGO_ABIERTO`. Fails if a known
|
||||
patient's discovered fields stop landing there, or if an unmatched one
|
||||
stops growing the catalog instead of being silently dropped.
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from sqlmodel import select
|
||||
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
from extraction import ExtractedRecord
|
||||
from extraction.nlp import DiscoveredField, Evidence
|
||||
from webapi.imports.services.catalog_commit_service import FUENTE_CATALOGO_ABIERTO, commit_discovered_fields
|
||||
|
||||
EVIDENCE = Evidence("fila.pdf", 1, "")
|
||||
|
||||
|
||||
def _record(key: str, pairs: list[tuple[str, str]]) -> ExtractedRecord:
|
||||
return ExtractedRecord(
|
||||
values={}, sources=[], key=key, discovered=[DiscoveredField(c, v, EVIDENCE) for c, v in pairs]
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cacu_catalog(tmp_path, monkeypatch):
|
||||
"""`add_resultado`/`sync` write real rows and a real file:
|
||||
kept off the checked-in `cacu.toml` and off any other domain's data."""
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
(tmp_path / "cacu.toml").write_text(
|
||||
'[citologia]\netiqueta = "Citología cervical"\n\n'
|
||||
'[citologia.resultados.calidad_muestra]\netiqueta = "Calidad de la muestra"\ntipo_valor = "texto"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
return tmp_path / "cacu.toml"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def known_patient(wire_domain):
|
||||
wire_domain("cacu")
|
||||
from core.cacu.paciente.model import Paciente
|
||||
from persistance.cacu import paciente_repository
|
||||
|
||||
paciente_repository.create(Paciente(pac_id_hospital="DOC-FB-1", pac_fecha_nacimiento=date(1990, 1, 1)))
|
||||
return "DOC-FB-1"
|
||||
|
||||
|
||||
def test_a_matched_field_is_written_on_the_existing_resultado(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||
assert observacion.resultado_id == "citologia.calidad_muestra"
|
||||
assert observacion.valor_texto == "Insatisfactoria"
|
||||
[procedimiento] = sesion.exec(select(carga_repository.procedimiento)).all()
|
||||
assert procedimiento.fuente_tabla == FUENTE_CATALOGO_ABIERTO
|
||||
assert procedimiento.fuente_id == known_patient
|
||||
|
||||
|
||||
def test_an_unmatched_field_is_counted_and_the_catalog_left_untouched(cacu_catalog, known_patient):
|
||||
"""A caption the catalog doesn't know is counted, not written, and the
|
||||
catalog file isn't edited: it's versioned with the code. Fails if the
|
||||
import path mints catalog entries again."""
|
||||
before = cacu_catalog.read_text(encoding="utf-8")
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Tipo de fijador", "Formol")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert (result.records_written, result.fields_minted, result.fields_unmatched) == (0, 0, 1)
|
||||
assert cacu_catalog.read_text(encoding="utf-8") == before
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
assert sesion.exec(select(carga_repository.observacion)).all() == []
|
||||
|
||||
|
||||
def test_a_patient_outside_persona_is_skipped_not_dropped_silently(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields(
|
||||
[_record("NOT-A-PATIENT", [("Calidad de muestra", "x")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert (result.records_written, result.records_without_patient) == (0, 1)
|
||||
|
||||
|
||||
def test_a_record_without_discovered_fields_is_ignored(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields([_record(known_patient, [])], proyecto="cacu", estudio_id="citologia")
|
||||
assert result.records_written == 0
|
||||
|
||||
|
||||
def test_a_repeated_caption_is_folded_not_written_twice(cacu_catalog, known_patient):
|
||||
"""A static label printed on several pages of the same document (a date,
|
||||
a signature line) discovers as one `DiscoveredField` per occurrence,
|
||||
on purpose (`discover_captions`'s docstring). Fails if this stops
|
||||
folding repeats before writing: `observacion` has one row per
|
||||
`(procedimiento, resultado_id)`, so a second occurrence of the same
|
||||
resultado_id raises `IntegrityError` and the whole record's fields —
|
||||
including the ones that weren't duplicated — are lost."""
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria"), ("Calidad de muestra", "Satisfactoria")])],
|
||||
proyecto="cacu",
|
||||
estudio_id="citologia",
|
||||
)
|
||||
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||
assert observacion.resultado_id == "citologia.calidad_muestra"
|
||||
assert observacion.valor_texto == "Insatisfactoria"
|
||||
@@ -0,0 +1,90 @@
|
||||
"""`catalog_matching.match_or_mint`: fails if it stops reusing an existing
|
||||
catalog field for an OCR caption that's clearly the same thing worded
|
||||
differently, or if an unmatched caption stops being added to the catalog
|
||||
and silently drops its value instead.
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
from webapi.orchestration.reference.catalogs import Catalogo
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
from extraction.nlp import DiscoveredField, Evidence
|
||||
from webapi.imports.schemas.catalog_matching import match_or_mint
|
||||
|
||||
EVIDENCE = Evidence("fila.pdf", 1, "")
|
||||
|
||||
|
||||
def _field(caption: str, value: str) -> DiscoveredField:
|
||||
return DiscoveredField(caption, value, EVIDENCE)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo() -> Catalogo:
|
||||
tablas = tablas_de("cacu")
|
||||
return Catalogo(
|
||||
estudios=[tablas.CatEstudio(estudio_id="citologia", etiqueta="Citología cervical")],
|
||||
resultados=[
|
||||
tablas.CatResultado(
|
||||
resultado_id="citologia.calidad_muestra", estudio_id="citologia",
|
||||
etiqueta="Calidad de la muestra", tipo_valor="codigo",
|
||||
),
|
||||
tablas.CatResultado(
|
||||
resultado_id="citologia.celulas_glandulares", estudio_id="citologia",
|
||||
etiqueta="Células glandulares", tipo_valor="texto",
|
||||
),
|
||||
],
|
||||
valores=[
|
||||
tablas.CatValor(
|
||||
resultado_id="citologia.calidad_muestra", valor_id="SATISFACTORIO",
|
||||
etiqueta="Satisfactoria", orden=1, estado="vigente",
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo_toml(tmp_path, monkeypatch):
|
||||
"""`add_resultado` writes to disk; keep it off the real `cacu.toml`."""
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
(tmp_path / "cacu.toml").write_text("", encoding="utf-8")
|
||||
return tmp_path / "cacu.toml"
|
||||
|
||||
|
||||
def test_a_worded_differently_caption_reuses_the_existing_resultado(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint(
|
||||
[_field("Calidad de muestra", "SATISFACTORIO")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
|
||||
)
|
||||
assert matched.resultado_id == "citologia.calidad_muestra" and not matched.is_new
|
||||
assert matched.observacion["valor_id"] == "SATISFACTORIO"
|
||||
assert catalogo_toml.read_text(encoding="utf-8") == "" # nothing minted
|
||||
|
||||
|
||||
def test_an_unmatched_caption_in_a_known_estudio_is_minted_there(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint(
|
||||
[_field("Tipo de fijador", "Formol")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
|
||||
)
|
||||
assert matched.is_new and matched.resultado_id.startswith("citologia.")
|
||||
assert matched.observacion["valor_texto"] == "Formol"
|
||||
|
||||
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
|
||||
assert matched.resultado_id in {r.resultado_id for r in sincronizado.resultados}
|
||||
|
||||
|
||||
def test_an_unmatched_caption_with_no_estudio_falls_back_to_documento_externo(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint([_field("Observación suelta", "algo")], proyecto="cacu", catalogo=catalogo)
|
||||
assert matched.resultado_id == "documento_externo." + matched.resultado_id.split(".", 1)[1]
|
||||
|
||||
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
|
||||
assert "documento_externo" in {e.estudio_id for e in sincronizado.estudios}
|
||||
|
||||
|
||||
def test_the_inferred_tipo_valor_follows_the_value_shape(catalogo, catalogo_toml):
|
||||
fecha, numero, texto = match_or_mint(
|
||||
[_field("Fecha de algo", "15/01/2024"), _field("Cuenta de algo", "12.5"), _field("Nota libre", "ninguna")],
|
||||
proyecto="cacu", catalogo=catalogo, estudio_id="citologia",
|
||||
)
|
||||
assert fecha.observacion["valor_fecha"] == date(2024, 1, 15)
|
||||
assert numero.observacion["valor_numerico"] == 12.5
|
||||
assert texto.observacion["valor_texto"] == "ninguna"
|
||||
@@ -0,0 +1,77 @@
|
||||
"""`add_resultado`: adds a new field to a project's catalog TOML file on
|
||||
disk, for a caller (`webapi.imports.schemas.catalog_matching`) that found a
|
||||
field no catalog entry matches closely enough. Each test pins down one
|
||||
rule of that append; fails if any of them regresses into losing data or
|
||||
duplicating an entry that's already there.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo_file(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
|
||||
def escribir(contenido: str) -> None:
|
||||
(tmp_path / "prueba.toml").write_text(contenido, encoding="utf-8")
|
||||
|
||||
return escribir
|
||||
|
||||
|
||||
def test_a_new_resultado_is_appended_under_its_existing_estudio(catalogo_file):
|
||||
catalogo_file('[citologia]\netiqueta = "Citología"\n')
|
||||
|
||||
resultado_id = catalogos.add_resultado(
|
||||
"prueba", estudio_id="citologia", nombre="nuevo_campo", etiqueta="Nuevo campo", tipo_valor="texto"
|
||||
)
|
||||
|
||||
assert resultado_id == "citologia.nuevo_campo"
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["citologia"]["etiqueta"] == "Citología" # what was already there survives
|
||||
assert leido["citologia"]["resultados"]["nuevo_campo"] == {"etiqueta": "Nuevo campo", "tipo_valor": "texto"}
|
||||
|
||||
|
||||
def test_a_resultado_of_an_unknown_estudio_also_creates_the_estudio(catalogo_file):
|
||||
catalogo_file("")
|
||||
|
||||
catalogos.add_resultado(
|
||||
"prueba",
|
||||
estudio_id="documento_externo",
|
||||
nombre="campo",
|
||||
etiqueta="Campo",
|
||||
tipo_valor="fecha",
|
||||
estudio_etiqueta="Documento externo",
|
||||
)
|
||||
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["documento_externo"]["etiqueta"] == "Documento externo"
|
||||
assert leido["documento_externo"]["resultados"]["campo"]["tipo_valor"] == "fecha"
|
||||
|
||||
|
||||
def test_adding_the_same_resultado_twice_does_not_touch_the_file(catalogo_file):
|
||||
"""Fails if re-discovering the same field on a later row duplicates it
|
||||
or rewrites what a human already edited in the file."""
|
||||
original = '[citologia]\netiqueta = "Citología"\n\n[citologia.resultados.campo]\netiqueta = "Campo"\ntipo_valor = "texto"\n'
|
||||
catalogo_file(original)
|
||||
|
||||
catalogos.add_resultado("prueba", estudio_id="citologia", nombre="campo", etiqueta="Otra cosa", tipo_valor="numero")
|
||||
|
||||
assert catalogos.ruta_de_catalogo("prueba").read_text(encoding="utf-8") == original
|
||||
|
||||
|
||||
def test_an_unknown_tipo_valor_is_rejected(catalogo_file):
|
||||
catalogo_file("")
|
||||
with pytest.raises(catalogos.CatalogoInvalido):
|
||||
catalogos.add_resultado("prueba", estudio_id="x", nombre="y", etiqueta="Y", tipo_valor="no_existe")
|
||||
|
||||
|
||||
def test_a_quote_in_a_label_does_not_break_the_file(catalogo_file):
|
||||
"""Fails if a caption or label read off a document (arbitrary text)
|
||||
produces TOML the next `catalogo_desde_toml` can't parse."""
|
||||
catalogo_file("")
|
||||
catalogos.add_resultado(
|
||||
"prueba", estudio_id="nota", nombre="campo", etiqueta='Dx: "sospechoso"', tipo_valor="texto"
|
||||
)
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["nota"]["resultados"]["campo"]["etiqueta"] == 'Dx: "sospechoso"'
|
||||
@@ -0,0 +1,53 @@
|
||||
"""The dbt target and environment derived from the deployment's database URLs (`webapi.dbt_manifest`).
|
||||
|
||||
No dbt runs here: only the mapping the entrypoint relies on to compile the manifest against the right engine.
|
||||
No fixtures."""
|
||||
|
||||
import pytest
|
||||
|
||||
from webapi.dbt_manifest import dbt_executable, environment, target_of
|
||||
|
||||
URLS_MSSQL = {
|
||||
"cacu": "mssql+pymssql://usuario:clave@servidor:1433/isss_cacu",
|
||||
"cama": "mssql+pymssql://usuario:clave@servidor:1433/isss_cama",
|
||||
"tea": "mssql+pymssql://usuario:clave@servidor:1433/isss_tea",
|
||||
}
|
||||
|
||||
|
||||
def test_sqlite_urls_keep_the_image_manifest():
|
||||
"""SQLite URLs give the `sqlite` target, which the entrypoint treats as "keep the image's manifest". Fails if
|
||||
`target_of` stops recognising SQLite or maps it elsewhere."""
|
||||
urls = {d: f"sqlite:////data/{d}.db" for d in ("cacu", "cama", "tea")}
|
||||
assert target_of(urls) == "sqlite"
|
||||
assert environment(urls, "sqlite")["TEA_DB_PATH"] == "/data/tea.db"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scheme, target", [("mssql+pymssql", "sqlserver"), ("postgresql+psycopg2", "postgres"),
|
||||
("mysql+pymysql", "mysql"), ("mariadb+pymysql", "mysql")])
|
||||
def test_each_engine_maps_to_its_dbt_target(scheme, target):
|
||||
"""Every engine the platform runs on has a dbt target. Fails if a backend name is dropped from `TARGETS`."""
|
||||
urls = {d: f"{scheme}://u:p@h:1/{d}" for d in ("cacu", "cama", "tea")}
|
||||
assert target_of(urls) == target
|
||||
|
||||
|
||||
def test_mixed_engines_are_refused():
|
||||
"""One manifest serves the three domains, so their databases must share an engine. Fails if `target_of`
|
||||
silently picks one of several engines."""
|
||||
urls = {**URLS_MSSQL, "tea": "sqlite:////data/tea.db"}
|
||||
with pytest.raises(ValueError, match="one engine"):
|
||||
target_of(urls)
|
||||
|
||||
|
||||
def test_environment_feeds_profiles_yml():
|
||||
"""The server, port, credentials and each domain's database name reach dbt through the variables
|
||||
`Transformation/profiles.yml` reads. Fails if a variable name changes on either side."""
|
||||
env = environment(URLS_MSSQL, "sqlserver")
|
||||
assert env == {"CACU_DBT_DATABASE": "isss_cacu", "CAMA_DBT_DATABASE": "isss_cama", "TEA_DBT_DATABASE": "isss_tea",
|
||||
"DBT_HOST": "servidor", "DBT_PORT": "1433", "DBT_USER": "usuario", "DBT_PASSWORD": "clave"}
|
||||
|
||||
|
||||
def test_mysql_has_its_own_environment(tmp_path):
|
||||
"""dbt-mysql pins an older dbt-core, so the image keeps it in `.venv-mysql`. Fails if the executable lookup
|
||||
stops distinguishing MySQL."""
|
||||
assert dbt_executable(tmp_path, "mysql") == tmp_path / ".venv-mysql" / "bin" / "dbt"
|
||||
assert dbt_executable(tmp_path, "sqlserver") == tmp_path / ".venv" / "bin" / "dbt"
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Options that let one document source cope with however its rows are
|
||||
stored: columns carried through as field values, a column grouping rows
|
||||
into records, filters that pick which documents feed a target, documents
|
||||
kept as hex or base64 text, unreadable rows, and queries that a derived
|
||||
table can't hold as written.
|
||||
|
||||
Fixtures: `client` (the app wired to a fresh CaCu database) and
|
||||
`documents_table`, a SQLite table built per test whose rows carry two
|
||||
reports of one order, a third report of the same patient under another
|
||||
order, and an unrelated kind of report.
|
||||
"""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from extraction.testing import text_pdf
|
||||
from webapi.imports.connectors.document import document_bytes
|
||||
from webapi.imports.connectors.sql import SqlConnector, _without_trailing_order_by
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def documents_table(tmp_path):
|
||||
"""Rows 1 and 2 are two reports of order 10 of patient P-1, row 3 is
|
||||
a report of order 11 of the same patient, and row 4 is a report of a
|
||||
kind the CaCu cytology target doesn't take. No body prints the
|
||||
patient id the structured columns hold."""
|
||||
url = f"sqlite:///{tmp_path / 'docs.db'}"
|
||||
rows = [
|
||||
(1, "P-1", 10, "Prueba de VPH\nVPH alto riesgo: POSITIVO"),
|
||||
(2, "P-1", 10, "Prueba de VPH\nGenotipo 18: DETECTADO"),
|
||||
(3, "P-1", 11, "Prueba de VPH\nVPH alto riesgo: NEGATIVO"),
|
||||
(4, "P-1", 12, "Informe de otra especialidad\nSin datos de VPH"),
|
||||
]
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE docs (row_id INTEGER, patient INTEGER, order_ref INTEGER, body TEXT)"))
|
||||
for row in rows:
|
||||
conn.execute(text("INSERT INTO docs VALUES (:a, :b, :c, :d)"), dict(zip("abcd", row)))
|
||||
return url
|
||||
|
||||
|
||||
def _payload(url: str, **sql) -> dict:
|
||||
base = {"connection_string": url, "table": "docs", "column": "body", "key_column": "row_id"}
|
||||
return {"sql": {**base, **sql}, "target": "cacu.CitologiaCervical"}
|
||||
|
||||
|
||||
def _extract(client, payload: dict) -> dict:
|
||||
response = client.post("/imports/sources/document/extract", json=payload)
|
||||
assert response.status_code == 200, response.get_json()
|
||||
return response.get_json()
|
||||
|
||||
|
||||
def test_group_column_keeps_orders_apart_and_merges_within_one(client, documents_table):
|
||||
"""Rows sharing `group_column` become one record; the same patient's
|
||||
other order stays its own record. Fails if `group_column` stops
|
||||
reaching `record_keys`."""
|
||||
body = _extract(
|
||||
client,
|
||||
_payload(
|
||||
documents_table,
|
||||
fields={"pac_id_hospital": "patient", "ord_numero_hospital": "order_ref"},
|
||||
group_column="order_ref",
|
||||
)
|
||||
| {"exclude_pattern": "otra especialidad"},
|
||||
)
|
||||
by_key = {record["key"]: record for record in body["records"]}
|
||||
assert set(by_key) == {"10", "11"}
|
||||
assert by_key["10"]["fields"]["cit_vph_genotipo_18"]["value"] == 1
|
||||
assert by_key["11"]["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
|
||||
assert by_key["10"]["fields"]["pac_id_hospital"]["value"] == "P-1"
|
||||
|
||||
|
||||
def test_filters_leave_out_other_kinds_of_report_and_say_so(client, documents_table):
|
||||
"""`include_pattern` keeps only matching documents, matched without
|
||||
regard to case or accents, and the rest are listed as skipped. Fails
|
||||
if the filters stop applying or `skipped` stops reporting them."""
|
||||
body = _extract(
|
||||
client,
|
||||
_payload(documents_table, fields={"pac_id_hospital": "patient"}) | {"include_pattern": "prueba de vph"},
|
||||
)
|
||||
assert [skipped["document"] for skipped in body["skipped"]] == ["4"]
|
||||
|
||||
|
||||
def test_a_filter_that_matches_nothing_is_an_error(client, documents_table):
|
||||
"""Filtering out every document is reported instead of returning an
|
||||
empty import. Fails if `_extract` stops refusing an empty selection."""
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract", json=_payload(documents_table) | {"include_pattern": "no aparece"}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_an_invalid_filter_is_a_bad_request(client, documents_table):
|
||||
"""A filter that isn't a valid regular expression is rejected with a
|
||||
message naming it. Fails if `_compile_filter` lets `re.error` through."""
|
||||
response = client.post("/imports/sources/document/extract", json=_payload(documents_table) | {"exclude_pattern": "("})
|
||||
assert response.status_code == 400 and "exclude_pattern" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_documents_stored_as_hex_or_base64_text_are_decoded():
|
||||
"""A PDF kept in a text column as hex (with or without `0x`) or base64
|
||||
reaches the readers as the PDF itself, and ordinary text stays text.
|
||||
Fails if `document_bytes` stops recognizing either encoding."""
|
||||
pdf = text_pdf([["Expediente: X-1"]])
|
||||
assert document_bytes("0x" + pdf.hex()) == pdf
|
||||
assert document_bytes(pdf.hex().upper()) == pdf
|
||||
assert document_bytes(base64.b64encode(pdf).decode()) == pdf
|
||||
assert document_bytes("Expediente: X-1") == b"Expediente: X-1"
|
||||
|
||||
|
||||
def test_an_unreadable_row_is_skipped_not_fatal(client, tmp_path):
|
||||
"""One corrupt document among readable ones is listed as skipped while
|
||||
the rest are extracted. Fails if a single unreadable row aborts the
|
||||
whole source again."""
|
||||
url = f"sqlite:///{tmp_path / 'mixed.db'}"
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE docs (row_id INTEGER, body BLOB)"))
|
||||
conn.execute(text("INSERT INTO docs VALUES (1, :b)"), {"b": b"%PDF-1.4 truncated"})
|
||||
conn.execute(text("INSERT INTO docs VALUES (2, :b)"), {"b": text_pdf([["Expediente: X-2", "VPH alto riesgo: POSITIVO"]])})
|
||||
body = _extract(client, _payload(url))
|
||||
assert [record["key"] for record in body["records"]] == ["X-2"]
|
||||
assert [skipped["document"] for skipped in body["skipped"]] == ["1"]
|
||||
|
||||
|
||||
def test_repeated_key_column_values_still_name_rows_apart(tmp_path):
|
||||
"""Two rows with the same `key_column` value get distinct names, so
|
||||
neither one's fields or pages overwrite the other's. Fails if
|
||||
`_files_from_sql` stops suffixing repeated names."""
|
||||
from webapi.imports.connectors.document import _files_from_sql
|
||||
|
||||
url = f"sqlite:///{tmp_path / 'r.db'}"
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE docs (row_id INTEGER, body TEXT)"))
|
||||
conn.execute(text("INSERT INTO docs VALUES (7, 'uno'), (7, 'dos')"))
|
||||
documents = _files_from_sql({"connection_string": url, "table": "docs", "column": "body", "key_column": "row_id"})
|
||||
assert [name for name, _ in documents.files] == ["7", "7#2"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query,kept",
|
||||
[
|
||||
("SELECT a FROM t ORDER BY a", "SELECT a FROM t"),
|
||||
("SELECT TOP 5 a FROM t ORDER BY a", None),
|
||||
("SELECT a FROM t ORDER BY a OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY", None),
|
||||
("SELECT a, (SELECT TOP 1 b FROM u ORDER BY b) AS x FROM t", None),
|
||||
("SELECT 'ORDER BY' AS s FROM t ORDER BY s", "SELECT 'ORDER BY' AS s FROM t"),
|
||||
],
|
||||
)
|
||||
def test_an_unlimited_trailing_order_by_is_dropped_before_wrapping(query, kept):
|
||||
"""SQL Server refuses `ORDER BY` inside a derived table unless TOP or
|
||||
OFFSET goes with it, so one that only sorts is dropped; one that picks
|
||||
rows, or sits inside a subquery or a string, stays. Fails if
|
||||
`_without_trailing_order_by` drops an `ORDER BY` that chooses rows or
|
||||
keeps one that would make the wrapped query invalid."""
|
||||
assert _without_trailing_order_by(query, "mssql") == (kept or query)
|
||||
|
||||
|
||||
def test_a_named_instance_or_embedded_port_reaches_the_driver():
|
||||
"""`host\\instance` leaves the port unset for the server to resolve,
|
||||
and `host,port` or `host:port` fill it in. Fails if `server_url` stops
|
||||
parsing addresses or goes back to forcing the default port on a named
|
||||
instance."""
|
||||
named = SqlConnector.server_url({"engine": "mssql", "host": "db.example\\INST", "database": "d"})
|
||||
assert (named.host, named.port) == ("db.example\\INST", None)
|
||||
comma = SqlConnector.server_url({"engine": "mssql", "host": "db.example,1500", "database": "d"})
|
||||
assert (comma.host, comma.port) == ("db.example", 1500)
|
||||
colon = SqlConnector.server_url({"engine": "postgresql", "host": "db.example:6543", "database": "d"})
|
||||
assert (colon.host, colon.port) == ("db.example", 6543)
|
||||
@@ -0,0 +1,174 @@
|
||||
"""`DocumentConnector` reading its documents from a SQL source instead of
|
||||
uploaded files: one document per row, read from a column that may hold a
|
||||
PDF (a binary column) or already be plain text, both without a filesystem
|
||||
path in between. Fails if the bridge to `SqlConnector` breaks, or if a
|
||||
plain-text column stops reaching the same field extraction a PDF does.
|
||||
"""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from extraction.testing import text_pdf
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
REPORT = text_pdf(
|
||||
[["Expediente: SQL-0001", "Fecha de nacimiento: 12/03/1981", "VPH alto riesgo: POSITIVO"]]
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_studies_table(tmp_path):
|
||||
"""A source table with one row per study, its
|
||||
report in a binary column, plus a plain-text variant of the same
|
||||
report in another row, both alongside the row's own key column."""
|
||||
db_path = tmp_path / "estudios.db"
|
||||
url = f"sqlite:///{db_path}"
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
|
||||
conn.execute(
|
||||
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
|
||||
{"id": "ROW-1", "reporte": REPORT},
|
||||
)
|
||||
conn.execute(
|
||||
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
|
||||
{
|
||||
"id": "ROW-2",
|
||||
"reporte": "Expediente: SQL-0002\nFecha de nacimiento: 01/01/1990\nVPH alto riesgo: NEGATIVO",
|
||||
},
|
||||
)
|
||||
return url
|
||||
|
||||
|
||||
def _sql_payload(url: str, **overrides) -> dict:
|
||||
return {"connection_string": url, "table": "estudios", "column": "reporte", "key_column": "estudio_id", **overrides}
|
||||
|
||||
|
||||
def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table):
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
[first, second] = body["records"]
|
||||
assert first["key"] == "SQL-0001"
|
||||
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
assert first["sources"] == [{"document": "ROW-1", "page_numbers": [1]}]
|
||||
|
||||
|
||||
def test_a_plain_text_column_reaches_the_same_field_extraction(client, sqlite_studies_table):
|
||||
"""Fails if a source whose bundle is a plain string (not binary at
|
||||
all) stops producing fields, since a source's column may not always
|
||||
be a PDF (`extraction.readers.TextReader`)."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
[_, second] = body["records"]
|
||||
assert second["key"] == "SQL-0002"
|
||||
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
|
||||
assert second["sources"] == [{"document": "ROW-2", "page_numbers": [1]}]
|
||||
|
||||
|
||||
def test_sql_sourced_documents_commit_like_uploaded_ones(client, sqlite_studies_table):
|
||||
source = {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"sql": _sql_payload(sqlite_studies_table)},
|
||||
"label": "estudios",
|
||||
}
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
rows = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100) if r.pac_id_hospital.startswith("SQL-")}
|
||||
assert rows["SQL-0001"].cit_vph_resultado == "POSITIVO"
|
||||
assert rows["SQL-0002"].cit_vph_resultado == "NEGATIVO"
|
||||
|
||||
|
||||
def test_column_and_key_column_must_differ(client, sqlite_studies_table):
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table, key_column="reporte"), "target": "cacu.CitologiaCervical"},
|
||||
)
|
||||
assert response.status_code == 400 and "key_column" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_a_missing_column_is_a_bad_request(client, sqlite_studies_table):
|
||||
payload = _sql_payload(sqlite_studies_table)
|
||||
del payload["column"]
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract", json={"sql": payload, "target": "cacu.CitologiaCervical"}
|
||||
)
|
||||
assert response.status_code == 400 and "column" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(client, tmp_path, monkeypatch):
|
||||
"""Mixing sources: a field the import schema doesn't name (`Tipo de
|
||||
fijador`) but the project's catalog does still reaches the silver
|
||||
layer through the open-catalog path, alongside the recognized fields
|
||||
`commit_sources` writes as before, when the source asks for it with
|
||||
`catalog_fallback`. Fails if `/imports/commit` stops wiring that second
|
||||
path in, or runs it for a source that didn't ask.
|
||||
Its own table and patient (`SQL-EXTRA-1`), so it doesn't collide with
|
||||
the module's other tests sharing this `client`'s database."""
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import create_engine, text as sa_text
|
||||
from sqlmodel import select
|
||||
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
from core.cacu.paciente.model import Paciente
|
||||
from persistance.cacu import carga_repository, paciente_repository
|
||||
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
catalog = (
|
||||
'[citologia]\netiqueta = "Citología cervical"\n\n'
|
||||
'[citologia.resultados.tipo_de_fijador]\netiqueta = "Tipo de fijador"\ntipo_valor = "texto"\n'
|
||||
)
|
||||
(tmp_path / "cacu.toml").write_text(catalog, encoding="utf-8")
|
||||
paciente_repository.create(Paciente(pac_id_hospital="SQL-EXTRA-1", pac_fecha_nacimiento=date(1981, 3, 12)))
|
||||
|
||||
db_url = f"sqlite:///{tmp_path / 'estudios_extra.db'}"
|
||||
report = text_pdf([["Expediente: SQL-EXTRA-1", "VPH alto riesgo: POSITIVO", "Tipo de fijador: Formol"]])
|
||||
with create_engine(db_url).begin() as conn:
|
||||
conn.execute(sa_text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
|
||||
conn.execute(sa_text("INSERT INTO estudios (estudio_id, reporte) VALUES ('ROW-1', :r)"), {"r": report})
|
||||
|
||||
source = {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"sql": _sql_payload(db_url), "estudio_id": "citologia"},
|
||||
"label": "estudios_extra",
|
||||
}
|
||||
body = client.post("/imports/commit", json={"sources": [source]}).get_json()
|
||||
assert body["results"][0]["created"] == 1, body
|
||||
assert not [r for r in body.get("catalog_fallback", []) if r["label"] == "estudios_extra"]
|
||||
|
||||
body = client.post("/imports/commit", json={"sources": [{**source, "catalog_fallback": True}], "on_conflict": "upsert"}).get_json()
|
||||
[fallback] = [r for r in body["catalog_fallback"] if r["label"] == "estudios_extra"]
|
||||
assert (fallback["records_written"], fallback["fields_matched"], fallback["fields_minted"]) == (1, 1, 0)
|
||||
assert (tmp_path / "cacu.toml").read_text(encoding="utf-8") == catalog
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[written] = list(
|
||||
sesion.exec(select(carga_repository.observacion).where(carga_repository.observacion.pac_id.in_(
|
||||
select(Paciente.pac_id).where(Paciente.pac_id_hospital == "SQL-EXTRA-1")
|
||||
)))
|
||||
)
|
||||
assert written.resultado_id == "citologia.tipo_de_fijador" and written.valor_texto == "Formol"
|
||||
@@ -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
|
||||
@@ -0,0 +1,60 @@
|
||||
"""What this module covers: the FHIR R4 measure routes of `webapi.fhir` for CaCu and CaMa: every `Measure` of the
|
||||
domain and one `MeasureReport` of each, checked against FHIR's models (`fhir.resources`, R4B), and the patient routes
|
||||
absent outside TEA.
|
||||
|
||||
Fixtures: `domain_client`, a Flask app with only the domain's FHIR blueprint over its fixture database loaded through
|
||||
the cycle up to `event_models` (`conftest.base_de`); needs `DBT_MANIFEST`.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fhir.resources.R4B import get_fhir_model_class
|
||||
from flask import Flask
|
||||
|
||||
from conftest import base_de
|
||||
from webapi.fhir import fhir_blueprint
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=["cacu", "cama"])
|
||||
def domain_client(request, tmp_path_factory):
|
||||
manifest = os.environ.get("DBT_MANIFEST")
|
||||
if not manifest:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
base = base_de(request.param, tmp_path_factory.mktemp(request.param))
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
app = Flask(__name__)
|
||||
app.register_blueprint(fhir_blueprint(request.param, base.dominio, Path(manifest), with_patients=True),
|
||||
url_prefix=f"/{request.param}/fhir")
|
||||
yield request.param, app.test_client()
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def valid(resource: dict) -> dict:
|
||||
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
|
||||
for item in resource.get("entry", ()):
|
||||
get_fhir_model_class(item["resource"]["resourceType"]).model_validate(item["resource"])
|
||||
return resource
|
||||
|
||||
|
||||
def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client):
|
||||
"""Pins down: each Measure of the domain, and its report for 2025-S1, validate as FHIR R4 resources, compositions
|
||||
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"] == {"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()
|
||||
valid(response.get_json())
|
||||
|
||||
|
||||
def test_the_patient_routes_are_tea_s_only(domain_client):
|
||||
"""Pins down: `EpisodeOfCare` exists only on TEA's endpoint; elsewhere it's an OperationOutcome 404. Fails if
|
||||
the patient routes register for another domain."""
|
||||
domain, client = domain_client
|
||||
response = client.get(f"/{domain}/fhir/EpisodeOfCare")
|
||||
assert response.status_code == 404 and valid(response.get_json())["resourceType"] == "OperationOutcome"
|
||||
@@ -0,0 +1,236 @@
|
||||
"""What this module covers: TEA's FHIR R4 endpoint (`/tea/fhir/`): the capability statement, the measures as
|
||||
`Measure` and their answers as `MeasureReport` (one period and several), the follow-up list as `EpisodeOfCare` with
|
||||
its filters, paging and includes, the EEG summary and the patient summary; and that the alterations stay hidden until
|
||||
validated. Every resource is checked against FHIR's models (`fhir.resources`, R4B, which keeps R4's shape for these
|
||||
resources).
|
||||
|
||||
Fixtures: `client`, a Flask app in DEV (`DEV_REVISION`, so the patient routes exist) over TEA's fixture database
|
||||
(`staging.tea`) loaded through the cycle up to `event_models`; needs `DBT_MANIFEST`. `validated`, the switch that
|
||||
shows the alterations (`TEA_ALTERACIONES_VALIDADAS`).
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from fhir.resources.R4B import get_fhir_model_class
|
||||
|
||||
from conftest import base_de
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
mp = pytest.MonkeyPatch()
|
||||
mp.setenv("DEV_REVISION", "pruebas")
|
||||
mp.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False)
|
||||
base = base_de("tea", tmp_path_factory.mktemp("tea_fhir"))
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
base.motor.dispose()
|
||||
mp.undo()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def validated(monkeypatch):
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
|
||||
|
||||
def valid(resource: dict) -> dict:
|
||||
"""The resource, after checking it and every resource in it against FHIR's model of its type."""
|
||||
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
|
||||
for item in resource.get("entry", ()):
|
||||
get_fhir_model_class(item["resource"]["resourceType"]).model_validate(item["resource"])
|
||||
return resource
|
||||
|
||||
|
||||
def get(client, url: str, status: int = 200) -> dict:
|
||||
response = client.get(url)
|
||||
assert response.status_code == status, response.get_json()
|
||||
assert response.mimetype == "application/fhir+json"
|
||||
return valid(response.get_json())
|
||||
|
||||
|
||||
def resources(bundle: dict, kind: str | None = None, mode: str | None = None) -> list[dict]:
|
||||
return [e["resource"] for e in bundle["entry"] if (kind is None or e["resource"]["resourceType"] == kind)
|
||||
and (mode is None or e.get("search", {}).get("mode") == mode)]
|
||||
|
||||
|
||||
def test_the_capability_statement_lists_the_measures_and_the_patient_routes(client):
|
||||
"""Pins down: `metadata` is a valid CapabilityStatement naming Measure with `evaluate-measure` and, in DEV,
|
||||
EpisodeOfCare with its search parameters. Fails if a route drops out of it."""
|
||||
body = get(client, "/tea/fhir/metadata")
|
||||
kinds = {r["type"]: r for r in body["rest"][0]["resource"]}
|
||||
assert {"Measure", "MeasureReport", "EpisodeOfCare", "Patient"} <= set(kinds)
|
||||
assert {p["name"] for p in kinds["EpisodeOfCare"]["searchParam"]} >= {"date", "etapa", "fecha-etapa", "alteracion"}
|
||||
|
||||
|
||||
def test_the_measures_hide_m30_until_the_alterations_are_validated(client, monkeypatch):
|
||||
"""Pins down: the Measure list has the nine measures without alterations; M30 shows only with the switch on.
|
||||
Fails if M30 leaks before the domain expert validates the references, or the switch stops showing it."""
|
||||
ids = {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))}
|
||||
assert len(ids) == 9 and "M30-resultado-eeg" not in ids
|
||||
assert get(client, "/tea/fhir/Measure/M30_resultado_eeg", 404)["resourceType"] == "OperationOutcome"
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
assert "M30-resultado-eeg" in {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))}
|
||||
|
||||
|
||||
def test_the_routes_outside_fhir_hide_m30_too(client, monkeypatch):
|
||||
"""Pins down: `/tea/indicadores` neither lists nor answers M30 until the alterations are validated, and does both
|
||||
with the switch on. Fails if the measures answered outside `/tea/fhir/` stop waiting for the validation."""
|
||||
assert "M30_resultado_eeg" not in {m["id"] for m in client.get("/tea/indicadores").get_json()}
|
||||
assert client.get("/tea/indicadores/M30_resultado_eeg?periodos=2025-S1").status_code == 404
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
assert "M30_resultado_eeg" in {m["id"] for m in client.get("/tea/indicadores").get_json()}
|
||||
assert client.get("/tea/indicadores/M30_resultado_eeg?periodos=2025-S1").status_code == 200
|
||||
|
||||
|
||||
def test_a_measure_carries_what_the_page_needs(client):
|
||||
"""Pins down: a Measure has its absolute canonical, title, scoring (a C2 is a cohort), its strata and its category
|
||||
labels. Fails if the page's catalog fields stop reaching the Measure."""
|
||||
m28 = get(client, "/tea/fhir/Measure/M28_casos_por_estado")
|
||||
assert m28["url"] == "https://isssteleon.org/fhir/Measure/M28-casos-por-estado"
|
||||
assert m28["title"] == "Casos por estatus" and m28["scoring"]["coding"][0]["code"] == "cohort"
|
||||
assert {e["extension"][0]["valueCode"] for e in m28["extension"] if e["url"].endswith("/categoria")} == {
|
||||
"SOLO_MCHAT", "PSICOLOGIA", "NEUROPEDIATRIA", "EEG"}
|
||||
m24 = get(client, "/tea/fhir/Measure/M24_confirmacion_diagnostico")
|
||||
assert m24["group"][0]["stratifier"][0]["code"]["coding"][0]["code"] == "grupo_edad"
|
||||
assert "denominator-exclusion" in {p["code"]["coding"][0]["code"] for p in m24["group"][0]["population"]}
|
||||
|
||||
|
||||
def test_evaluate_measure_answers_one_period_as_a_measure_report(client):
|
||||
"""Pins down: `$evaluate-measure` with periodStart and periodEnd answers that period of `dim_periodo`: M28's first
|
||||
semester of 2025 counts six children by stage, as a cohort whose stages are a stratifier. Fails if the period
|
||||
lookup, the canonical or the C2 shape changes."""
|
||||
report = get(client, "/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure"
|
||||
"?periodStart=2025-01-01&periodEnd=2025-06-30")
|
||||
assert report["measure"].startswith("https://isssteleon.org/fhir/Measure/M28-casos-por-estado|")
|
||||
(group,) = report["group"]
|
||||
assert group["population"][0]["count"] == 6
|
||||
stages = {s["value"]["coding"][0]["code"]: s["population"][0]["count"] for s in group["stratifier"][0]["stratum"]}
|
||||
assert stages == {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 2}
|
||||
|
||||
|
||||
def test_a_proportion_reports_its_exclusion_and_its_strata_with_codings(client):
|
||||
"""Pins down: M24's report has the exclusion count (child 2's note without F84.0) and each age group as a coded
|
||||
stratum. Fails if `denominator-exclusion` or the stratum codings drop out."""
|
||||
report = get(client, "/tea/fhir/Measure/M24_confirmacion_diagnostico/$evaluate-measure?periodo=2025-04")
|
||||
counts = {p["code"]["coding"][0]["code"]: p["count"] for p in report["group"][0]["population"]}
|
||||
assert counts == {"denominator": 3, "numerator": 1, "denominator-exclusion": 1}
|
||||
values = {s["value"]["coding"][0]["code"] for s in report["group"][0]["stratifier"][0]["stratum"]}
|
||||
assert {"16_23", "30_36"} <= values
|
||||
|
||||
|
||||
def test_the_measure_report_search_answers_several_periods_with_paging(client):
|
||||
"""Pins down: `MeasureReport?measure=…&tipo-periodo=mes&period=ge…&period=le…` gives one report per month, and
|
||||
`_count` pages them with a `next` link. Fails if the search stops selecting `dim_periodo` by type and dates."""
|
||||
url = ("/tea/fhir/MeasureReport?measure=https://isssteleon.org/fhir/Measure/M26-dias-mchat-ados2"
|
||||
"&tipo-periodo=mes&period=ge2025-01-01&period=le2025-03-31")
|
||||
body = get(client, url)
|
||||
assert body["total"] == 3 and [r["period"]["start"] for r in resources(body)] == [
|
||||
"2025-01-01", "2025-02-01", "2025-03-01"]
|
||||
paged = get(client, url + "&_count=2")
|
||||
assert len(paged["entry"]) == 2 and any(link["relation"] == "next" for link in paged["link"])
|
||||
|
||||
|
||||
def test_the_follow_up_list_is_each_child_s_episode_at_the_cut_off(client):
|
||||
"""Pins down: `EpisodeOfCare?date=le…` gives each child who entered by the cut-off, at its stage then: at 31 May,
|
||||
children 1, 2, 3, 6 and 7 (child 5 enters in June), child 1 finished on its good EEG. A window from 1 June leaves
|
||||
child 1 out. Fails if the episode's status, stage or window drift from the measures' rules."""
|
||||
may = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-05-31"))
|
||||
assert len(may) == 5
|
||||
assert sorted(e["status"] for e in may) == ["active"] * 4 + ["finished"]
|
||||
assert all(e["meta"]["tag"][0]["code"] == "simulado" for e in may)
|
||||
june = resources(get(client, "/tea/fhir/EpisodeOfCare?date=ge2025-06-01&date=le2025-06-30"))
|
||||
assert len(june) == 5 and "finished" in {e["status"] for e in june}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("query", "n"), [
|
||||
("etapa=PSICOLOGIA", 1), ("grupo-edad=24_29", 2), ("mchat=ge12", 3), ("css=ge4", 3),
|
||||
("fecha-etapa=ge2025-06-01&fecha-etapa=le2025-06-30", 2), ("status=finished", 2), ("resultado-eeg=sin-eeg-valido", 3),
|
||||
])
|
||||
def test_the_follow_up_filters(client, query, n):
|
||||
"""Pins down each search parameter at the year's end, over the six children who entered by then: child 3 at
|
||||
psychology; children 2 and 6 in 24 to 29 months (finished episodes still list); M-CHAT of 12 or more for children
|
||||
1, 3 and 6; CSS of 4 or more for 1, 2 and 6; a stage dated in June for child 5 (its M-CHAT; its EEG doesn't count)
|
||||
and child 6 (EEG on 2 June); children 1 and 6 finished; children 2, 3 and 7 without a valid EEG. Fails if a filter
|
||||
stops reading its column."""
|
||||
assert get(client, f"/tea/fhir/EpisodeOfCare?date=le2025-12-31&{query}")["total"] == n
|
||||
|
||||
|
||||
def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client):
|
||||
"""Pins down: `_include` adds each child's Patient (birth date to the month), CarePlan with its steps, M-CHAT,
|
||||
ADOS-2 (the list shows its CSS and module), confirmed diagnosis and study EEG as a DiagnosticReport with its quality
|
||||
observations; no metric observation while the alterations are hidden. Fails if an included resource drops out or
|
||||
the alterations leak."""
|
||||
body = get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&status=finished&_include=*")
|
||||
included = resources(body, mode="include")
|
||||
kinds = {r["resourceType"] for r in included}
|
||||
assert {"Patient", "CarePlan", "Observation", "Condition", "DiagnosticReport", "Procedure"} <= kinds
|
||||
assert all(len(p["birthDate"]) == 7 for p in included if p["resourceType"] == "Patient")
|
||||
reports = [r for r in included if r["resourceType"] == "DiagnosticReport"]
|
||||
assert {r["conclusionCode"][0]["coding"][0]["code"] for r in reports} == {"BUENO"}
|
||||
assert all(len(r["result"]) == 5 for r in reports)
|
||||
ados2 = [r for r in included if r["resourceType"] == "Observation" and r["code"]["coding"][0]["code"] == "ados2"]
|
||||
assert ados2 and all(any(c["code"]["coding"][0]["code"] == "ados2.css" for c in r["component"]) for r in ados2)
|
||||
|
||||
|
||||
def test_the_alteration_filter_waits_for_the_validation(client, monkeypatch):
|
||||
"""Pins down: filtering by an alteration is refused while they're hidden, and works with the switch on (child 1's
|
||||
slow posterior rhythm). Fails if the filter leaks alterations before validation."""
|
||||
assert get(client, "/tea/fhir/EpisodeOfCare?alteracion=ritmo_posterior", 403)["resourceType"] == "OperationOutcome"
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
assert get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&alteracion=ritmo_posterior")["total"] == 1
|
||||
|
||||
|
||||
def test_the_eeg_summary_counts_valid_eegs_and_alterations_only_when_validated(client, monkeypatch):
|
||||
"""Pins down `$resumen-eeg`: children 1, 5 and 6 with a valid EEG, 2, 3 and 7 without; with the alterations
|
||||
validated, child 1 abnormal (posterior rhythm), 5 and 6 normal. Fails if the summary counts bad EEGs as valid or
|
||||
shows the split before validation."""
|
||||
def counts(body):
|
||||
return {p["name"]: p.get("valueInteger") for p in body["parameter"] if "valueInteger" in p}
|
||||
|
||||
hidden = get(client, "/tea/fhir/EpisodeOfCare/$resumen-eeg?date=le2025-12-31")
|
||||
assert counts(hidden) == {"con_eeg_valido": 3, "sin_eeg_valido": 3}
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
shown = get(client, "/tea/fhir/EpisodeOfCare/$resumen-eeg?date=le2025-12-31")
|
||||
assert counts(shown) == {"con_eeg_valido": 3, "sin_eeg_valido": 3, "normales": 2, "anormales": 1}
|
||||
|
||||
|
||||
def test_the_patient_summary_shows_the_first_ados2_and_the_study_eeg(client, monkeypatch):
|
||||
"""Pins down `$resumen-tea` for child 1: its Patient, its ADOS-2 (module, CSS, domain totals and items), its first
|
||||
good EEG (20 May, not the bad one of April nor the later one) with its quality; with the alterations validated,
|
||||
the metrics against their reference and the electrode values. Fails if the summary takes another EEG or shows the
|
||||
alterations before validation."""
|
||||
episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished"))
|
||||
(child_1,) = episodes
|
||||
path = f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea"
|
||||
bundle = get(client, path)
|
||||
assert bundle["type"] == "collection"
|
||||
(report,) = resources(bundle, "DiagnosticReport")
|
||||
assert report["effectiveDateTime"] == "2025-05-20" and report["conclusionCode"][0]["coding"][0]["code"] == "BUENO"
|
||||
ados2 = next(o for o in resources(bundle, "Observation") if o["id"].startswith("ados2-"))
|
||||
codes = {c["code"]["coding"][0]["code"] for c in ados2["component"]}
|
||||
assert {"ados2.modulo", "ados2.css", "SA", "RRB", "ados2.sa_b1"} <= codes
|
||||
assert not any("tea-eeg-metrica" in o["code"]["coding"][0]["system"] for o in resources(bundle, "Observation"))
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
shown = get(client, path)
|
||||
metrics = [o for o in resources(shown, "Observation") if o["code"]["coding"][0]["system"].endswith("tea-eeg-metrica")]
|
||||
rhythm = next(o for o in metrics if o["id"].startswith("ritmo-posterior-"))
|
||||
assert rhythm["interpretation"][0]["coding"][0]["code"] == "L" and rhythm["referenceRange"][0]["low"]["value"] == 4.5
|
||||
electrodes = next(o for o in metrics if o["id"].startswith("electrodos-ritmo-posterior-"))
|
||||
assert [c["code"]["coding"][0]["code"] for c in electrodes["component"]] == ["O1", "O2", "Pz"]
|
||||
|
||||
|
||||
def test_an_unknown_patient_or_parameter_is_an_operation_outcome(client):
|
||||
"""Pins down: errors are OperationOutcomes with the HTTP status: an unknown pseudonym (404), an unknown search
|
||||
parameter (400). Fails if an error goes back to `{"error": …}`."""
|
||||
assert get(client, "/tea/fhir/Patient/P-NADIE/$resumen-tea", 404)["issue"][0]["code"] == "not-found"
|
||||
assert get(client, "/tea/fhir/EpisodeOfCare?color=azul", 400)["issue"][0]["code"] == "invalid"
|
||||
@@ -1,8 +1,18 @@
|
||||
"""Endpoint tests for `/governance/*`."""
|
||||
"""Endpoint tests for `/governance/*`: model versions and their promotion, downloading what a version's run stored,
|
||||
notebooks run on a cohort build, and the OCR review queue.
|
||||
|
||||
Fixtures: `client`, the app over a CaCu and a governance database with one patient and a SQLite-backed MLflow in a
|
||||
temporary folder (module scope); `notebooks`, a cohort build's file under a `COHORTS_DIR`, the Jupyter renderer and
|
||||
notebooks run in the request instead of in the background. `_trained` registers a version the way training does: a run
|
||||
that records each routine and saves its model.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import date
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -81,42 +91,70 @@ def _register(client, tag: str, *, scenario: str = "tamizaje", **extra) -> dict:
|
||||
return response.get_json()
|
||||
|
||||
|
||||
def _upload(client, domain: str, scenario: str, version: str, kind: str = "BALANCE_CLASES", name: str = "smote.json", data: bytes = b"{}"):
|
||||
files = {"file": (__import__("io").BytesIO(data), name), "kind": kind}
|
||||
return client.post(f"/governance/model-versions/{domain}/{scenario}/{version}/artifacts", data=files, content_type="multipart/form-data")
|
||||
class Echo(mlflow.pyfunc.PythonModel):
|
||||
def predict(self, context, model_input, params=None):
|
||||
return model_input
|
||||
|
||||
|
||||
def _trained(tag: str, scenario: str, **reports) -> str:
|
||||
"""A PROD version as training leaves it: every routine recorded and the model saved."""
|
||||
from models.io.registry import registry
|
||||
from models.io.tracking import ROUTINE_KINDS, TrainingRun
|
||||
|
||||
run = TrainingRun(domain="cacu", scenario=scenario, environment="PROD", cohorte_armado_id=_armado(tag))
|
||||
for kind in ROUTINE_KINDS:
|
||||
run.log_routine(kind, {"method": "prueba"})
|
||||
run.log_model(Echo())
|
||||
return registry.register_run(run.finish(metrics={"auc": 0.8}), **reports)
|
||||
|
||||
|
||||
REPORTS = {"technical_validation_report_uri": "docs/tecnica.pdf", "clinical_validation_report_uri": "docs/clinica.pdf",
|
||||
"interpretability_report_uri": "docs/interpretabilidad.html"}
|
||||
|
||||
|
||||
def test_model_version_lifecycle_over_http(client):
|
||||
first = _register(client, "v1", scenario="lifecycle")
|
||||
assert first["status"] == "candidata"
|
||||
|
||||
checks = client.get(f"/governance/model-versions/cacu/lifecycle/{first['version']}/checks").get_json()
|
||||
"""A version registered over HTTP carries no routine records or model, so it can't be promoted; trained ones can,
|
||||
and promoting the second retires the first. Fails if the ML-01a/ML-01b checks start trusting what's declared
|
||||
over the API, or promotion stops retiring the previous version."""
|
||||
declared = _register(client, "v0", scenario="lifecycle")
|
||||
checks = client.get(f"/governance/model-versions/cacu/lifecycle/{declared['version']}/checks").get_json()
|
||||
assert checks["ready"] is False
|
||||
assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01b"]
|
||||
blocked = client.post(f"/governance/model-versions/cacu/lifecycle/{first['version']}/promote")
|
||||
assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01a", "ML-01b"]
|
||||
blocked = client.post(f"/governance/model-versions/cacu/lifecycle/{declared['version']}/promote")
|
||||
assert blocked.status_code == 409 and any(not c["passed"] for c in blocked.get_json()["checks"])
|
||||
|
||||
uploaded = _upload(client, "cacu", "lifecycle", first["version"])
|
||||
assert uploaded.status_code == 201
|
||||
assert client.post(f"/governance/model-versions/cacu/lifecycle/{first['version']}/promote").get_json()["status"] == "produccion"
|
||||
|
||||
second = _register(client, "v2", scenario="lifecycle", metrics={"auc": 0.86})
|
||||
_upload(client, "cacu", "lifecycle", second["version"])
|
||||
client.post(f"/governance/model-versions/cacu/lifecycle/{second['version']}/promote")
|
||||
first = _trained("v1", "lifecycle", **REPORTS)
|
||||
assert client.post(f"/governance/model-versions/cacu/lifecycle/{first}/promote").get_json()["status"] == "produccion"
|
||||
second = _trained("v2", "lifecycle", **REPORTS)
|
||||
client.post(f"/governance/model-versions/cacu/lifecycle/{second}/promote")
|
||||
listed = client.get("/governance/model-versions", query_string={"domain": "cacu", "scenario": "lifecycle"}).get_json()
|
||||
statuses = {v["version"]: v["status"] for v in listed["model_versions"]}
|
||||
assert statuses[first["version"]] == "retirada" and statuses[second["version"]] == "produccion"
|
||||
assert statuses[first] == "retirada" and statuses[second] == "produccion"
|
||||
|
||||
lineage = client.get(f"/governance/model-versions/cacu/lifecycle/{second['version']}/lineage").get_json()
|
||||
lineage = client.get(f"/governance/model-versions/cacu/lifecycle/{second}/lineage").get_json()
|
||||
assert lineage["cohorte_armado"]["huella"] == "huella-v2"
|
||||
assert lineage["cohorte_armado"]["datos_as_of"] == "2025-12-31"
|
||||
assert lineage["cohorte_exclusiones"] == [{"orden": 1, "paso": "candidatas", "n": 5}]
|
||||
assert lineage["artifacts"]
|
||||
assert lineage["routines"]["MUESTREO"] == {"method": "prueba"}
|
||||
|
||||
retired = client.post(f"/governance/model-versions/cacu/lifecycle/{second['version']}/retire").get_json()
|
||||
retired = client.post(f"/governance/model-versions/cacu/lifecycle/{second}/retire").get_json()
|
||||
assert retired["status"] == "retirada"
|
||||
|
||||
|
||||
def test_a_versions_files_download(client):
|
||||
"""ML-01b: a routine record downloads as itself, the model folder as a zip, and a path the run doesn't hold is 404.
|
||||
Fails if the endpoint stops going through `registry.artifact`."""
|
||||
version = _trained("v-desc", "descargas")
|
||||
base = f"/governance/model-versions/cacu/descargas/{version}/artifacts"
|
||||
record = client.get(f"{base}/rutinas/MUESTREO.json")
|
||||
assert record.status_code == 200 and record.get_json(force=True) == {"method": "prueba"}
|
||||
assert "attachment" in record.headers["Content-Disposition"]
|
||||
model = client.get(f"{base}/model")
|
||||
assert model.status_code == 200 and 'model.zip' in model.headers["Content-Disposition"]
|
||||
assert client.get(f"{base}/../../mlflow.db").status_code == 404
|
||||
assert client.get(f"{base}/rutinas/OTRO.json").status_code == 404
|
||||
|
||||
|
||||
def test_reports_can_be_attached_later(client):
|
||||
version = _register(client, "v3", scenario="reportes", clinical_validation_report_uri=None)
|
||||
response = client.patch(
|
||||
@@ -127,11 +165,8 @@ def test_reports_can_be_attached_later(client):
|
||||
assert client.patch(f"/governance/model-versions/cacu/reportes/{version['version']}/reports", json={"metrics": "{}"}).status_code == 400
|
||||
|
||||
|
||||
def test_bad_registrations_and_uploads_are_rejected(client):
|
||||
def test_bad_registrations_are_rejected(client):
|
||||
assert client.post("/governance/model-versions", json={"domain": "cacu"}).status_code == 400
|
||||
dev = client.post("/governance/model-versions", json={"domain": "cacu", "scenario": "malas-subidas", "environment": "DEV"}).get_json()
|
||||
assert _upload(client, "cacu", "malas-subidas", dev["version"], kind="NOPE").status_code == 400
|
||||
assert _upload(client, "cacu", "malas-subidas", dev["version"], kind="ONNX_CHECKPOINT", name="m.onnx", data=b"junk").status_code == 400
|
||||
|
||||
|
||||
def test_model_version_not_found(client):
|
||||
@@ -241,3 +276,88 @@ def test_ocr_correct_rejects_unknown_column(client):
|
||||
|
||||
def test_ocr_blob_not_found_for_unknown_row(client):
|
||||
assert client.get("/governance/ocr/cacu/citologia_cervical/999999/blob").status_code == 404
|
||||
|
||||
|
||||
def _notebook(*sources: str) -> bytes:
|
||||
cells = [{"cell_type": "code", "metadata": {}, "execution_count": None, "outputs": [], "source": s} for s in sources]
|
||||
return json.dumps({"cells": cells, "metadata": {}, "nbformat": 4, "nbformat_minor": 5}).encode()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def notebooks(tmp_path, monkeypatch):
|
||||
"""Build 4 of dbt's `cacu/cohorte_vigilancia` under `COHORTS_DIR`, the Jupyter renderer, and `submit` running the
|
||||
notebook before the request answers."""
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
from datetime import datetime, timezone
|
||||
from models.io.contracts import COHORT_SCHEMA
|
||||
from webapi.blueprints import governance
|
||||
|
||||
row = {"pac_id": 1, "fecha_indice": date(2025, 1, 1), "fecha": date(2025, 1, 1),
|
||||
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "procedimiento", "tipo": "citologia",
|
||||
"codigo": "citologia", "valor_codigo": None, "valor_numerico": None, "fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "S1"}
|
||||
table = pa.Table.from_pandas(pd.DataFrame([row], columns=COHORT_SCHEMA.names), schema=COHORT_SCHEMA, preserve_index=False)
|
||||
path = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt" / "4.parquet"
|
||||
path.parent.mkdir(parents=True)
|
||||
metadata = {"url": "cacu/cohorte_vigilancia", "producer": "dbt", "build": "4", "datos_as_of": "2025-12-31",
|
||||
"n_members": "1"}
|
||||
pq.write_table(table.replace_schema_metadata(metadata), path)
|
||||
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
|
||||
monkeypatch.setenv("NOTEBOOK_RENDERER", "jupyter")
|
||||
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / "artefactos"))
|
||||
monkeypatch.setattr(governance, "submit", lambda job, *args: job(*args))
|
||||
|
||||
|
||||
def _run(client, notebook: bytes, *, scenario="exploracion", **fields):
|
||||
form = {"file": (io.BytesIO(notebook), "analisis.ipynb"), "domain": "cacu", "scenario": scenario,
|
||||
"url": "cacu/cohorte_vigilancia", "source": "dbt", "build": "4", **fields}
|
||||
return client.post("/governance/experiments", data=form, content_type="multipart/form-data")
|
||||
|
||||
|
||||
def test_the_builds_a_notebook_can_run_on_are_listed(client, notebooks):
|
||||
"""Fails if `/cohort-files` stops listing exported builds from their files."""
|
||||
builds = client.get("/governance/cohort-files", query_string={"domain": "cacu"}).get_json()["builds"]
|
||||
assert builds == [{"url": "cacu/cohorte_vigilancia", "source": "dbt", "build": 4, "datos_as_of": "2025-12-31",
|
||||
"n_members": "1"}]
|
||||
|
||||
|
||||
def test_an_uploaded_notebook_runs_on_the_build_and_its_page_is_sandboxed(client, notebooks):
|
||||
"""The upload answers 202 with the run; the notebook reads the build through `models.notebook`; its page is served
|
||||
with a sandbox policy and its files download. Fails if the endpoint stops handing the build to the run or serves
|
||||
the notebook's page as part of the app's origin."""
|
||||
started = _run(client, _notebook("from models.notebook import experiment\n"
|
||||
"print('miembros', experiment().cohort().pac_id.nunique())"))
|
||||
assert started.status_code == 202, started.get_json()
|
||||
run_id = started.get_json()["run_id"]
|
||||
run = client.get(f"/governance/experiments/{run_id}").get_json()
|
||||
assert run["status"] == "terminado" and run["cohort"]["build"] == "4" and run["notebook"] == "analisis"
|
||||
page = client.get(f"/governance/experiments/{run_id}/page")
|
||||
assert "miembros 1" in page.get_data(as_text=True) and "sandbox" in page.headers["Content-Security-Policy"]
|
||||
source = client.get(f"/governance/experiments/{run_id}/artifacts/notebook/analisis.ipynb")
|
||||
assert source.status_code == 200 and "attachment" in source.headers["Content-Disposition"]
|
||||
listed = client.get("/governance/experiments", query_string={"domain": "cacu", "scenario": "exploracion"}).get_json()
|
||||
assert run_id in [r["run_id"] for r in listed["experiments"]]
|
||||
|
||||
|
||||
def test_a_failing_notebook_reports_its_error(client, notebooks):
|
||||
"""Fails if a notebook whose cell raises is reported as finished or without its error."""
|
||||
run_id = _run(client, _notebook("raise ValueError('sin datos')")).get_json()["run_id"]
|
||||
run = client.get(f"/governance/experiments/{run_id}").get_json()
|
||||
assert run["status"] == "fallido" and "sin datos" in run["error"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fields, notebook", [
|
||||
({"build": "99"}, None),
|
||||
({"url": "tea/otra"}, None),
|
||||
({"build": "x"}, None),
|
||||
({"version": "999"}, None),
|
||||
({}, b"no es json"),
|
||||
({}, b'{"cells": [], "nbformat": 3}'),
|
||||
])
|
||||
def test_bad_notebook_runs_are_refused(client, notebooks, fields, notebook):
|
||||
"""A build that isn't exported, a cohort of another domain, an unknown version, or a file that isn't a notebook is
|
||||
refused before anything runs. Fails if `/experiments` stops checking any of them."""
|
||||
response = _run(client, notebook or _notebook("1"), **fields)
|
||||
assert response.status_code in (400, 404)
|
||||
|
||||
@@ -124,7 +124,8 @@ def test_commit_multi_source_batch_mixes_file_and_sql_within_one_domain(client,
|
||||
|
||||
def test_commit_rejects_a_batch_mixing_domains(client):
|
||||
cacu_source = _csv_source(b"pac_id_hospital,pac_sexo\nH-MIX-1,F\n", target="cacu.Paciente")
|
||||
tea_source = _json_source([{"pac_id_hospital": "T-MIX-1", "pac_sexo": "F"}], target="tea.Pacientes")
|
||||
tea_source = _json_source([{"pac_id_hospital": "T-MIX-1"}], target="tea.Pacientes",
|
||||
column_mapping={"pac_id_hospital": "pac_id_hospital"})
|
||||
|
||||
response = client.post("/imports/commit", json={"sources": [cacu_source, tea_source], "on_conflict": "reject"})
|
||||
assert response.status_code == 400
|
||||
@@ -159,20 +160,21 @@ def test_commit_on_conflict_reject_then_upsert(client):
|
||||
|
||||
def test_commit_upsert_rejected_for_target_without_natural_key(client):
|
||||
source = _json_source(
|
||||
[{"psi_pac_id": 1}], target="tea.EvaluacionPsicologica", column_mapping={"psi_pac_id": "psi_pac_id"}
|
||||
[{"pac_id_hospital": "H-NO-KEY"}], target="cacu.BiometriaHematica",
|
||||
column_mapping={"pac_id_hospital": "pac_id_hospital"},
|
||||
)
|
||||
response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "upsert"})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client):
|
||||
mapping = {"pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"}
|
||||
first = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_sexo": "F"}],
|
||||
mapping = {"pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital", "pac_fecha_nacimiento": "pac_fecha_nacimiento"}
|
||||
first = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_fecha_nacimiento": "2023-05-01"}],
|
||||
target="tea.Pacientes", column_mapping=mapping)
|
||||
body = client.post("/imports/commit", json={"sources": [first], "on_conflict": "upsert"}).get_json()
|
||||
assert body["results"][0]["created"] == 1
|
||||
|
||||
again = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_sexo": "M"}],
|
||||
again = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_fecha_nacimiento": "2023-06-01"}],
|
||||
target="tea.Pacientes", column_mapping=mapping)
|
||||
body = client.post("/imports/commit", json={"sources": [again], "on_conflict": "upsert"}).get_json()
|
||||
assert body["results"][0]["created"] == 0
|
||||
@@ -180,20 +182,22 @@ def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client):
|
||||
|
||||
[paciente] = client.get("/data/tea.Pacientes").get_json()["rows"]
|
||||
assert paciente["pac_id"] == 9001 and paciente["pac_id_hospital"] == "T-SRC-1"
|
||||
assert paciente["pac_sexo"] == "M"
|
||||
assert paciente["pac_fecha_nacimiento"] == "2023-06-01"
|
||||
|
||||
|
||||
def test_an_import_into_a_domain_without_measures_queues_no_recomputation(client):
|
||||
"""The cycle computes no TEA measures, so a TEA import saves its rows and asks for no recomputation.
|
||||
def test_an_import_into_tea_queues_its_recomputation(client):
|
||||
"""Pins down: TEA's measures come from the cycle like CaCu's and CaMa's, so a TEA import saves its rows and
|
||||
asks for a recomputation of TEA.
|
||||
|
||||
Fails if the import queues every domain it writes to: the queue refuses TEA and the import answers 500.
|
||||
Fails if TEA leaves the queue's domains (`DOMAINS` in `webapi.recomputation`).
|
||||
"""
|
||||
source = _json_source([{"pac_id_hospital": "T-NO-RECALC", "pac_sexo": "F"}], target="tea.Pacientes")
|
||||
source = _json_source([{"pac_id_hospital": "T-RECALC"}], target="tea.Pacientes",
|
||||
column_mapping={"pac_id_hospital": "pac_id_hospital"})
|
||||
response = client.post("/imports/commit", json={"sources": [source]})
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["results"][0]["created"] == 1
|
||||
assert body["indicadores_en_recalculo"] is False
|
||||
assert body["indicadores_en_recalculo"] is True
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
- detect -> table/preview -> validate -> commit, for the ruled-table
|
||||
path, writing into `cacu.Paciente`.
|
||||
- detect -> page-image -> regions/extract -> validate -> commit, for the
|
||||
OCR/region path, writing into `tea.Pacientes`.
|
||||
OCR/region path, writing into `cacu.Paciente` as well.
|
||||
"""
|
||||
|
||||
import base64
|
||||
@@ -76,14 +76,16 @@ def _font(size: int = 34):
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def _build_scanned_form_pdf(id_hospital: str, sexo: str) -> bytes:
|
||||
"""A scanned-like page with two text blocks at known pixel positions and
|
||||
no text layer, so only the OCR/region path applies."""
|
||||
def _build_scanned_form_pdf(id_hospital: str, sexo: str, nacimiento: str = "1980-05-17") -> bytes:
|
||||
"""A scanned-like page with three text blocks on one line at known pixel
|
||||
positions and no text layer, so only the OCR/region path applies. The birth
|
||||
date is there because a patient row is not valid without it."""
|
||||
img = Image.new("RGB", (_IMG_W, _IMG_H), "white")
|
||||
draw = ImageDraw.Draw(img)
|
||||
font = _font()
|
||||
draw.text((40, 100), id_hospital, fill="black", font=font)
|
||||
draw.text((400, 100), sexo, fill="black", font=font)
|
||||
draw.text((560, 100), nacimiento, fill="black", font=font)
|
||||
|
||||
buffer = io.BytesIO()
|
||||
c = canvas.Canvas(buffer, pagesize=letter)
|
||||
@@ -99,6 +101,7 @@ def _build_scanned_form_pdf(id_hospital: str, sexo: str) -> bytes:
|
||||
|
||||
_ID_HOSPITAL_BBOX = (20 / _IMG_W, 60 / _IMG_H, 350 / _IMG_W, 180 / _IMG_H)
|
||||
_SEXO_BBOX = (380 / _IMG_W, 60 / _IMG_H, 500 / _IMG_W, 180 / _IMG_H)
|
||||
_NACIMIENTO_BBOX = (540 / _IMG_W, 60 / _IMG_H, 880 / _IMG_W, 180 / _IMG_H)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
@@ -201,7 +204,7 @@ def test_pdf_page_image_missing_file_returns_400(client):
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# OCR/region path: detect -> page-image -> regions/extract -> validate ->
|
||||
# commit (tea.Pacientes)
|
||||
# commit (cacu.Paciente)
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -229,6 +232,7 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client):
|
||||
regions = [
|
||||
{"target_field": "pac_id_hospital", "page_numbers": [1], "bbox": list(_ID_HOSPITAL_BBOX)},
|
||||
{"target_field": "pac_sexo", "page_numbers": [1], "bbox": list(_SEXO_BBOX)},
|
||||
{"target_field": "pac_fecha_nacimiento", "page_numbers": [1], "bbox": list(_NACIMIENTO_BBOX)},
|
||||
]
|
||||
extract_response = client.post(
|
||||
"/imports/sources/pdf/regions/extract",
|
||||
@@ -236,13 +240,13 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client):
|
||||
)
|
||||
assert extract_response.status_code == 200
|
||||
extract_body = extract_response.get_json()
|
||||
assert extract_body["rows"] == [{"pac_id_hospital": "H-PDF-OCR-1", "pac_sexo": "F"}]
|
||||
assert extract_body["rows"] == [{"pac_id_hospital": "H-PDF-OCR-1", "pac_sexo": "F", "pac_fecha_nacimiento": "1980-05-17"}]
|
||||
assert extract_body["warnings"] == []
|
||||
|
||||
source = {
|
||||
"source_type": "pdf",
|
||||
"target": "tea.Pacientes",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"},
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo", "pac_fecha_nacimiento": "pac_fecha_nacimiento"},
|
||||
"payload": {
|
||||
"file_base64": base64.b64encode(pdf_bytes).decode(),
|
||||
"mode": "regions",
|
||||
@@ -261,7 +265,7 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client):
|
||||
commit_body = commit_response.get_json()
|
||||
assert commit_body["ok"] is True
|
||||
result = commit_body["results"][0]
|
||||
assert result["target"] == "tea.Pacientes"
|
||||
assert result["target"] == "cacu.Paciente"
|
||||
assert result["created"] == 1
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""The live estimators the recomputation worker hands the cycle (`webapi.orchestration.estimators`,
|
||||
`webapi.recomputation`).
|
||||
|
||||
Fixtures: `base` (conftest) gives a migrated CaCu database with the synthetic staging; the registry and the live
|
||||
estimators are stubbed so no MLflow store or model is needed. The stub estimator is the cycle tests' `EstimadorFijo`.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from webapi.orchestration import estimators
|
||||
from webapi.recomputation import RecomputationQueue
|
||||
from tests.test_orquestacion_riesgos import URL, EstimadorFijo
|
||||
|
||||
|
||||
def test_only_cacu_has_a_live_estimator():
|
||||
"""CaMa and TEA have no registered model, so their cycles estimate nothing. Fails if a domain without a model
|
||||
gets an estimator that would then fail resolving a version."""
|
||||
assert estimators.live_estimators("cama") == {}
|
||||
assert estimators.live_estimators("tea") == {}
|
||||
|
||||
|
||||
def test_without_a_production_version_cacu_estimates_nothing(monkeypatch):
|
||||
"""No version in production means no estimator: `estimate` then no-ops instead of failing the whole cycle.
|
||||
Fails if `live_estimators` stops catching the registry's `LookupError`."""
|
||||
from models.io.registry import registry
|
||||
|
||||
monkeypatch.setattr(registry, "resolve", lambda *a, **k: (_ for _ in ()).throw(LookupError("none")))
|
||||
assert estimators.live_estimators("cacu") == {}
|
||||
|
||||
|
||||
def test_with_a_production_version_the_surveillance_cohort_gets_its_estimator(monkeypatch):
|
||||
"""With a version in production, the CaCu surveillance cohort is scored by `Cin2LogisticEstimator`, which
|
||||
reports nothing until it has estimated. Fails if the cohort url or the estimator contract changes."""
|
||||
from models.io.registry import registry
|
||||
|
||||
monkeypatch.setattr(registry, "resolve", lambda *a, **k: object())
|
||||
live = estimators.live_estimators("cacu")
|
||||
assert list(live) == [URL]
|
||||
estimator = live[URL]
|
||||
assert estimator.desenlace == "cin2_mas" and callable(estimator.estimar)
|
||||
with pytest.raises(RuntimeError):
|
||||
estimator.procedencia()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_the_worker_runs_the_cycle_with_the_live_estimators(base, tmp_path, monkeypatch):
|
||||
"""After an import the worker's run leaves a preliminary risk batch for every cohort with a live estimator.
|
||||
Fails if `RecomputationQueue.run` stops passing `live_estimators` to the context, or the batch is written
|
||||
as anything but `preliminary`."""
|
||||
monkeypatch.setattr(estimators, "live_estimators", lambda domain: {URL: EstimadorFijo()})
|
||||
result = RecomputationQueue(tmp_path / "indicadores").run("cacu", desde=2025, hasta=2025)
|
||||
assert result["estado"] == "ok", result
|
||||
assert [p["paso"] for p in result["pasos"]][-2:] == ["cohorts", "estimate"]
|
||||
with base.motor.connect() as con:
|
||||
assert con.execute(text("SELECT COUNT(*) FROM evaluacion_riesgo_lote")).scalar_one() == 1
|
||||
assert con.execute(text("SELECT MIN(estado) FROM evaluacion_riesgo")).scalar_one() == "preliminary"
|
||||
assert con.execute(text("SELECT COUNT(*) FROM evaluacion_riesgo")).scalar_one() > 0
|
||||
@@ -0,0 +1,284 @@
|
||||
"""Derived fields and document columns inside an ordinary mapping: target
|
||||
fields computed from several source columns (joined, split, picked, read
|
||||
out of a longer text or translated), files kept in a column of a CSV or
|
||||
SQL source read for the fields the plain mapping left empty, and the
|
||||
captions nothing used, as the import report lists them.
|
||||
|
||||
Fixtures: `client` (the app wired to a fresh CaCu database). Sources are
|
||||
built inline: CSV text through `_csv`, SQLite tables under `tmp_path`.
|
||||
"""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from extraction.testing import text_pdf
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.mapping.derived import build_derivation, parse_derived
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def _b64(raw: bytes) -> str:
|
||||
return base64.b64encode(raw).decode()
|
||||
|
||||
|
||||
def _csv(content: str, **source) -> dict:
|
||||
return {"source_type": "csv", "target": "cacu.Paciente", "payload": {"file_base64": _b64(content.encode())}, **source}
|
||||
|
||||
|
||||
ROW = {"nombre": " ana maría ", "paterno": "Pérez", "materno": "", "completo": "Ana María Pérez López", "dir": "Calle 5, CP 64000"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"rule,expected",
|
||||
[
|
||||
({"op": "concat", "columns": ["nombre", "paterno", "materno"]}, "ana maría Pérez"),
|
||||
({"op": "concat", "columns": ["paterno", "nombre"], "separator": ", ", "case": "upper"}, "PÉREZ, ANA MARÍA"),
|
||||
({"op": "template", "template": "{paterno} {materno} / {nombre}"}, "Pérez / ana maría"),
|
||||
({"op": "split", "column": "completo", "start": 0, "stop": -2}, "Ana María"),
|
||||
({"op": "split", "column": "completo", "start": -2, "stop": -1}, "Pérez"),
|
||||
({"op": "coalesce", "columns": ["materno", "paterno"]}, "Pérez"),
|
||||
({"op": "extract", "column": "dir", "pattern": r"CP\s*(\d{5})", "group": 1}, "64000"),
|
||||
({"op": "map", "column": "paterno", "values": {"pérez": "P"}}, "P"),
|
||||
({"op": "map", "column": "nombre", "values": {"x": "y"}, "keep_unmatched": False}, None),
|
||||
({"op": "column", "column": "paterno"}, "Pérez"),
|
||||
],
|
||||
)
|
||||
def test_each_operation_computes_its_value(rule, expected):
|
||||
"""Pins what every registered operation returns for one row, blanks
|
||||
skipped and spaces collapsed. Fails if an operation's semantics change
|
||||
(`start`/`stop` counting, separators, `case`, unmatched values)."""
|
||||
assert build_derivation(rule).apply(ROW) == expected
|
||||
|
||||
|
||||
def test_rules_are_checked_before_any_row_is_read():
|
||||
"""Unknown operations, missing parameters, bad patterns and fields the
|
||||
target lacks are refused up front. Fails if `parse_derived` lets a
|
||||
malformed rule through to fail row by row."""
|
||||
for bad in ({"op": "nope"}, {"op": "concat"}, {"op": "extract", "column": "a", "pattern": "("}, {"op": "split", "column": "a", "case": "x"}):
|
||||
with pytest.raises(ConnectorError):
|
||||
build_derivation(bad)
|
||||
with pytest.raises(ConnectorError):
|
||||
parse_derived({"no_such_field": "a"}, {"pac_sexo"})
|
||||
|
||||
|
||||
def test_short_forms_name_a_column_or_join_several():
|
||||
"""A rule given as a column name reads it; a list of columns joins them.
|
||||
Fails if `rule_from` stops accepting the short forms."""
|
||||
rules = parse_derived({"a": "paterno", "b": ["nombre", "paterno"]}, {"a", "b"})
|
||||
assert rules["a"].apply(ROW) == "Pérez" and rules["b"].apply(ROW) == "ana maría Pérez"
|
||||
|
||||
|
||||
def test_derived_fields_reach_validation_and_the_mapped_preview(client):
|
||||
"""A source whose id is split over two columns and whose sex comes
|
||||
coded validates cleanly once `derived` joins and translates them, and
|
||||
`/imports/mapped-preview` shows the rows as they would be written.
|
||||
Fails if `ImportSource.rows` stops applying `derived`."""
|
||||
source = _csv(
|
||||
"serie,numero,sx,cp,nac\nA,001,1,64000,1980-01-02\nB,002,2,64100,1975-03-04\n",
|
||||
column_mapping={"cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"},
|
||||
derived={
|
||||
"pac_id_hospital": {"op": "concat", "columns": ["serie", "numero"], "separator": "-"},
|
||||
"pac_sexo": {"op": "map", "column": "sx", "values": {"1": "F", "2": "M"}},
|
||||
},
|
||||
)
|
||||
rows = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
assert [(r["pac_id_hospital"], r["pac_sexo"]) for r in rows] == [("A-001", "F"), ("B-002", "M")]
|
||||
result = client.post("/imports/validate", json={"source": source}).get_json()
|
||||
assert result["error_count"] == 0, result["errors"]
|
||||
|
||||
|
||||
def test_a_field_cannot_be_both_mapped_and_derived(client):
|
||||
"""Fails if a field fed twice (mapping and `derived`) stops being refused."""
|
||||
source = _csv("a\n1\n", column_mapping={"a": "pac_id_hospital"}, derived={"pac_id_hospital": "a"})
|
||||
assert client.post("/imports/validate", json={"source": source}).status_code == 400
|
||||
|
||||
|
||||
def test_the_operations_are_listed_for_clients(client):
|
||||
"""`/imports/derivations` lists every operation with its parameters, so
|
||||
the import screen builds its forms from the server. Fails if an
|
||||
operation is registered without being described."""
|
||||
body = client.get("/imports/derivations").get_json()
|
||||
ops = {d["op"]: d for d in body["derivations"]}
|
||||
assert {"column", "concat", "template", "split", "coalesce", "extract", "map"} <= set(ops)
|
||||
assert [p["name"] for p in ops["split"]["params"]] == ["column", "separator", "start", "stop"]
|
||||
assert body["cases"] == ["upper", "lower", "title"]
|
||||
|
||||
|
||||
def _documents_table(tmp_path) -> str:
|
||||
"""Two rows of one order of patient P-7, one with its report as a PDF
|
||||
and one as base64 text, and a third row with no document."""
|
||||
url = f"sqlite:///{tmp_path / 'docs.db'}"
|
||||
report = text_pdf([["VPH alto riesgo: POSITIVO"]])
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE t (pid TEXT, orden INTEGER, archivo BLOB, texto TEXT)"))
|
||||
conn.execute(text("INSERT INTO t VALUES ('P-7', 5, :f, NULL)"), {"f": report})
|
||||
conn.execute(
|
||||
text("INSERT INTO t VALUES ('P-7', 5, NULL, :t)"), {"t": _b64(text_pdf([["Genotipo 16: DETECTADO"]]))}
|
||||
)
|
||||
conn.execute(text("INSERT INTO t VALUES ('P-8', 6, NULL, NULL)"))
|
||||
return url
|
||||
|
||||
|
||||
def _sql_source(url: str, **extra) -> dict:
|
||||
return {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"payload": {"connection_string": url, "table": "t"},
|
||||
"column_mapping": {"pid": "pac_id_hospital", "orden": "ord_numero_hospital"},
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def test_a_sql_preview_flags_the_columns_that_hold_documents(client, tmp_path):
|
||||
"""Binary files and files written as base64 text are both flagged;
|
||||
plain values aren't. Fails if `document_columns` stops reaching the
|
||||
preview."""
|
||||
url = _documents_table(tmp_path)
|
||||
body = client.post("/imports/sources/sql/preview", json={"connection_string": url, "table": "t"}).get_json()
|
||||
assert set(body["document_columns"]) == {"archivo", "texto"}
|
||||
|
||||
|
||||
def test_document_columns_fill_what_the_mapping_leaves_empty(client, tmp_path):
|
||||
"""The mapped id and order are kept; the documents of both rows of the
|
||||
order add the fields they print; a row without documents passes
|
||||
through mapped. Fails if `documents` stops reading cells of an
|
||||
ordinary mapping, or loses the rows that have none."""
|
||||
source = _sql_source(_documents_table(tmp_path), documents={"columns": ["archivo", "texto"], "group_by": "orden"})
|
||||
rows = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
by_patient = {row["pac_id_hospital"]: row for row in rows}
|
||||
assert by_patient["P-7"]["ord_numero_hospital"] == 5
|
||||
assert by_patient["P-7"]["cit_vph_resultado"] == "POSITIVO"
|
||||
assert by_patient["P-7"]["cit_vph_genotipo_16"] == 1
|
||||
assert by_patient["P-8"]["ord_numero_hospital"] == 6
|
||||
|
||||
|
||||
def test_documents_of_a_mapping_can_be_reviewed_and_committed(client, tmp_path):
|
||||
"""`/imports/sources/document/extract` with `{source}` reviews the same
|
||||
records the commit writes, with the record's pages in `file_field`.
|
||||
Fails if the review and the commit read document columns differently."""
|
||||
source = _sql_source(
|
||||
_documents_table(tmp_path),
|
||||
documents={"columns": "archivo", "group_by": "orden", "file_field": "cit_pdf_blob"},
|
||||
label="t",
|
||||
)
|
||||
report = client.post("/imports/sources/document/extract", json={"source": source}).get_json()
|
||||
[record] = report["records"]
|
||||
assert record["fields"]["pac_id_hospital"]["method"] == "columna_fuente"
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
stored = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100)}
|
||||
assert stored["P-7"].cit_vph_resultado == "POSITIVO"
|
||||
assert stored["P-7"].cit_pdf_blob.startswith(b"%PDF")
|
||||
|
||||
|
||||
def test_a_csv_column_of_base64_documents_is_read_like_a_sql_one(client):
|
||||
"""Document columns are not tied to SQL: a CSV whose column carries
|
||||
base64 PDFs feeds the same extraction. Fails if `documents` only works
|
||||
for one kind of source."""
|
||||
report = _b64(text_pdf([["VPH alto riesgo: NEGATIVO"]]))
|
||||
source = _csv(
|
||||
f"exp,doc\nC-1,{report}\n",
|
||||
target="cacu.CitologiaCervical",
|
||||
column_mapping={"exp": "pac_id_hospital"},
|
||||
documents={"columns": "doc"},
|
||||
)
|
||||
[row] = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
assert row["pac_id_hospital"] == "C-1" and row["cit_vph_resultado"] == "NEGATIVO"
|
||||
|
||||
|
||||
def _id_and_file_table(tmp_path) -> str:
|
||||
"""Each row has only an id and a file; every other value is printed
|
||||
in the file under captions no target field knows."""
|
||||
url = f"sqlite:///{tmp_path / 'files.db'}"
|
||||
report = text_pdf([["Tipo de persona: Mujer", "Domicilio actual: Calle 5, C.P. 64000", "Nacida el: 02/01/1980"]])
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE t (pid TEXT, archivo BLOB)"))
|
||||
conn.execute(text("INSERT INTO t VALUES ('Q-1', :f)"), {"f": report})
|
||||
return url
|
||||
|
||||
|
||||
def _paciente_from_file(url: str, **extra) -> dict:
|
||||
return {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"payload": {"connection_string": url, "table": "t"},
|
||||
"documents": {"columns": "archivo"},
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def test_captions_printed_in_documents_are_offered_as_columns(client, tmp_path):
|
||||
"""`/imports/sources/document/columns` lists the source's own columns
|
||||
and every caption its documents print, with their values. Fails if
|
||||
discovered captions stop becoming columns of the source."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/columns", json={"source": _paciente_from_file(_id_and_file_table(tmp_path))}
|
||||
).get_json()
|
||||
names = [column["name"] for column in body["columns"]]
|
||||
assert {"pid", "Tipo de persona", "Domicilio actual", "Nacida el"} <= set(names)
|
||||
[row] = body["sample_rows"]
|
||||
assert row["Tipo de persona"] == "Mujer"
|
||||
|
||||
|
||||
def test_mapping_and_rules_reach_what_the_documents_print(client, tmp_path):
|
||||
"""A caption maps onto a field like a column does, and derived rules
|
||||
translate or cut values read from the page. Fails if the mapping and
|
||||
`derived` stop running over the record's document values."""
|
||||
source = _paciente_from_file(
|
||||
_id_and_file_table(tmp_path),
|
||||
column_mapping={"pid": "pac_id_hospital", "Nacida el": "pac_fecha_nacimiento"},
|
||||
derived={
|
||||
"pac_sexo": {"op": "map", "column": "Tipo de persona", "values": {"mujer": "F", "hombre": "M"}},
|
||||
"pac_codigo_postal": {"op": "extract", "column": "Domicilio actual", "pattern": r"\d{5}"},
|
||||
},
|
||||
)
|
||||
[row] = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
assert (row["pac_id_hospital"], row["pac_sexo"], row["pac_codigo_postal"]) == ("Q-1", "F", "64000")
|
||||
assert row["pac_fecha_nacimiento"] == "02/01/1980"
|
||||
result = client.post("/imports/validate", json={"source": source}).get_json()
|
||||
assert result["error_count"] == 0, result["errors"]
|
||||
|
||||
|
||||
def _last_report() -> dict:
|
||||
from webapi.imports.audit import default_sink
|
||||
|
||||
return default_sink().read()[-1]
|
||||
|
||||
|
||||
def test_the_import_report_lists_unused_captions_never_their_values(client, tmp_path, monkeypatch):
|
||||
"""Captions the documents print that nothing in the import used are
|
||||
listed with how many records print them, and none of their values
|
||||
reaches the report. Below the minimum count they are only counted.
|
||||
Fails if `unused_captions` stops reaching the audit, lists a caption
|
||||
the mapping uses, or lets a value through."""
|
||||
import json
|
||||
|
||||
source = _paciente_from_file(
|
||||
_id_and_file_table(tmp_path), column_mapping={"pid": "pac_id_hospital", "Nacida el": "pac_fecha_nacimiento"}
|
||||
)
|
||||
monkeypatch.setenv("WEBAPI_REPORT_MIN_COUNT", "1")
|
||||
client.post("/imports/validate", json={"source": source})
|
||||
report = _last_report()["fuentes"][0]
|
||||
assert report["etiquetas_sin_usar"] == {"Tipo de persona": 1, "Domicilio actual": 1}
|
||||
text = json.dumps(_last_report(), ensure_ascii=False)
|
||||
assert "Mujer" not in text and "64000" not in text and "02/01/1980" not in text
|
||||
|
||||
monkeypatch.setenv("WEBAPI_REPORT_MIN_COUNT", "2")
|
||||
client.post("/imports/validate", json={"source": source})
|
||||
report = _last_report()["fuentes"][0]
|
||||
assert report["etiquetas_sin_usar"] == {} and report["etiquetas_sin_usar_poco_frecuentes"] == 2
|
||||
+75
-58
@@ -78,31 +78,35 @@ def test_unknown_engine_and_missing_host_are_rejected(client):
|
||||
# -- EEG -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_edf_preview_maps_onto_eeg_estudio(client):
|
||||
data = {"file": (io.BytesIO(eeg()), "estudio_007.edf"), "target": "tea.EegEstudio"}
|
||||
def test_edf_preview_maps_onto_eeg(client):
|
||||
"""Pins down: an EDF previews as one row with the study id, patient, date, channels and duration read from the
|
||||
file, and its columns suggest the `eeg` fields. Fails if the connector stops reading the header or the column
|
||||
matcher stops pairing them."""
|
||||
data = {"file": (io.BytesIO(eeg()), "estudio_007.edf"), "target": "tea.Eeg"}
|
||||
body = client.post("/imports/sources/file/preview", data=data, content_type="multipart/form-data").get_json()
|
||||
[row] = body["sample_rows"]
|
||||
assert row["id_registro_laboratorio"] == "LAB-778"
|
||||
assert row["paciente"] == "EXP-0042"
|
||||
assert row["fecha_estudio"] == "2024-01-15"
|
||||
assert row["edad_meses"] == 56.0
|
||||
assert row["ritmo_base_frecuencia"] == pytest.approx(10, abs=0.3)
|
||||
assert "3 canales a 128 Hz" in row["descripcion_senal"]
|
||||
assert row["canales"] == 3
|
||||
assert row["duracion_min"] == pytest.approx(8 / 60, abs=0.05)
|
||||
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
|
||||
assert suggested["estudio"] == "eeg_estudio"
|
||||
assert suggested["fecha_estudio"] == "eeg_fecha_estudio"
|
||||
assert suggested["ritmo_base_frecuencia"] == "eeg_ritmo_base_frecuencia"
|
||||
assert suggested["canales"] == "eeg_canales"
|
||||
|
||||
|
||||
def test_several_edf_files_load_into_eeg_estudio_with_the_file(client):
|
||||
def test_several_edf_files_load_into_eeg_with_the_file(client):
|
||||
"""Pins down: several EDF files commit as one `eeg` row each, keyed by the lab's study id (or the file name),
|
||||
with the file stored. Fails if the commit drops the file or the key."""
|
||||
source = {
|
||||
"source_type": "edf",
|
||||
"target": "tea.EegEstudio",
|
||||
"target": "tea.Eeg",
|
||||
"column_mapping": {
|
||||
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"fecha_estudio": "eeg_fecha_estudio",
|
||||
"duracion_min": "eeg_duracion_min",
|
||||
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
|
||||
"canales": "eeg_canales",
|
||||
"estudio": "eeg_estudio",
|
||||
},
|
||||
"payload": {"files": [{"name": "a.edf", "file_base64": b64(eeg())}, {"name": "b.edf", "file_base64": b64(eeg(recording="sin datos"))}]},
|
||||
@@ -110,19 +114,21 @@ def test_several_edf_files_load_into_eeg_estudio_with_the_file(client):
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.tea import eeg_estudio_repository
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
stored = {row.eeg_id_registro_laboratorio: row for row in eeg_estudio_repository.list()}
|
||||
stored = {row.eeg_id_registro_laboratorio: row for row in eeg_repository.list()}
|
||||
assert set(stored) == {"LAB-778", "b"}
|
||||
assert stored["LAB-778"].eeg_canales == 3
|
||||
assert stored["LAB-778"].eeg_estudio[:8].strip() == b"0"
|
||||
assert stored["LAB-778"].eeg_fecha_estudio == date(2024, 1, 15)
|
||||
|
||||
|
||||
def test_eeg_estudio_rejects_a_file_mne_cannot_read():
|
||||
def test_eeg_rejects_a_file_mne_cannot_read():
|
||||
"""Pins down: `eeg_estudio` only takes a file MNE can open. Fails if the schema stops validating the EDF."""
|
||||
from webapi.imports.schemas.service import validate_rows
|
||||
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
|
||||
from webapi.imports.schemas.tea.eeg import EegImportSchema
|
||||
|
||||
result = validate_rows(EegEstudioImportSchema, [{"eeg_estudio": b"definitely not an EDF file" * 20}])
|
||||
result = validate_rows(EegImportSchema, [{"eeg_estudio": b"definitely not an EDF file" * 20}])
|
||||
[row] = result.rejected
|
||||
assert row.errors[0].field == "eeg_estudio"
|
||||
|
||||
@@ -228,73 +234,48 @@ def test_patient_scattered_across_csv_and_scanned_forms_is_merged(client):
|
||||
|
||||
|
||||
EEG_REPORT = text_pdf(
|
||||
[
|
||||
["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-778", "Fecha de estudio: 15/01/2024",
|
||||
"Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"],
|
||||
["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."],
|
||||
],
|
||||
image_on_page=2,
|
||||
[["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-778", "Fecha de estudio: 15/01/2024"]],
|
||||
)
|
||||
|
||||
# A second study id, distinct from LAB-778 (already used by an earlier test
|
||||
# against this module-scoped client/database), for the merge test below.
|
||||
EEG_REPORT_2 = text_pdf(
|
||||
[
|
||||
["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-900", "Fecha de estudio: 20/02/2024",
|
||||
"Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"],
|
||||
["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."],
|
||||
],
|
||||
[["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-900", "Fecha de estudio: 20/02/2024"]],
|
||||
)
|
||||
|
||||
|
||||
def test_eeg_report_scattered_across_pages_merges_into_one_record(client):
|
||||
"""The report's demographics are on page 1, its conclusion on page 2 —
|
||||
non-contiguous fields the same way a multi-file upload would be, just
|
||||
without the file boundary. Proves the extractor merges by the lab's own
|
||||
study id, not by page adjacency."""
|
||||
def test_an_eeg_report_gives_its_study_id_and_date(client):
|
||||
"""Pins down: a report read with NLP lands on `eeg` by the lab's own study id, with the study date. Fails if
|
||||
the extractor stops keying EEG records by `eeg_id_registro_laboratorio` or stops reading the date."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"files": [{"name": "reporte.pdf", "file_base64": b64(EEG_REPORT)}], "target": "tea.EegEstudio"},
|
||||
json={"files": [{"name": "reporte.pdf", "file_base64": b64(EEG_REPORT)}], "target": "tea.Eeg"},
|
||||
).get_json()
|
||||
assert body["key_field"] == "eeg_id_registro_laboratorio"
|
||||
[record] = body["records"]
|
||||
assert record["key"] == "LAB-778"
|
||||
assert record["sources"] == [{"document": "reporte.pdf", "page_numbers": [1, 2]}]
|
||||
assert record["fields"]["eeg_simetria"]["value"] == "SIMETRICO"
|
||||
assert record["fields"]["eeg_fecha_estudio"]["value"] == "2024-01-15"
|
||||
assert "sin eventos epileptiformes" in record["fields"]["eeg_conclusion_texto"]["value"]
|
||||
assert [image["page_number"] for image in record["images"]] == [2]
|
||||
|
||||
|
||||
def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_estudio_row(client):
|
||||
"""The EDF connector computes signal fields from the file itself; the
|
||||
report PDF (read with NLP, across two pages) carries the clinician's
|
||||
interpretation. Different sources, same study — `eeg_id_registro_
|
||||
laboratorio` (the lab's own code, read from the EDF header by one side
|
||||
and from the report text by the other) is what lets them land on one
|
||||
`eeg_estudio` row instead of two half-populated ones."""
|
||||
def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_row(client):
|
||||
"""Pins down: the EDF and its report, two sources of the same study, land on one `eeg` row through the lab's
|
||||
study id (read from the EDF header by one and from the report text by the other). Fails if
|
||||
`merge_duplicates` stops matching them on `eeg_id_registro_laboratorio`."""
|
||||
edf_source = {
|
||||
"source_type": "edf",
|
||||
"target": "tea.EegEstudio",
|
||||
"target": "tea.Eeg",
|
||||
"label": "estudio.edf",
|
||||
"column_mapping": {
|
||||
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"fecha_estudio": "eeg_fecha_estudio",
|
||||
"duracion_min": "eeg_duracion_min",
|
||||
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
|
||||
"estudio": "eeg_estudio",
|
||||
},
|
||||
"payload": {"files": [{"name": "estudio.edf", "file_base64": b64(eeg(recording="Startdate 20-FEB-2024 LAB-900 Tec_Ruiz Nihon_Kohden"))}]},
|
||||
}
|
||||
document_source = _document_source(
|
||||
[("reporte.pdf", EEG_REPORT_2)],
|
||||
"tea.EegEstudio",
|
||||
{
|
||||
"eeg_id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"eeg_simetria": "eeg_simetria",
|
||||
"eeg_conclusion_texto": "eeg_conclusion_texto",
|
||||
"eeg_medico_interpreta": "eeg_medico_interpreta",
|
||||
},
|
||||
"tea.Eeg",
|
||||
{"eeg_id_registro_laboratorio": "eeg_id_registro_laboratorio", "eeg_fecha_estudio": "eeg_fecha_estudio"},
|
||||
)
|
||||
body = client.post(
|
||||
"/imports/commit", json={"sources": [edf_source, document_source], "merge_duplicates": True}
|
||||
@@ -303,16 +284,14 @@ def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_estudio_row(client):
|
||||
assert edf_result["created"] == 1, body
|
||||
assert doc_result["merged"] == 1, body # absorbed into the EDF source's row, not inserted again
|
||||
|
||||
from persistance.tea import eeg_estudio_repository
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
[row] = eeg_estudio_repository.list(eeg_id_registro_laboratorio="LAB-900")
|
||||
[row] = eeg_repository.list(eeg_id_registro_laboratorio="LAB-900")
|
||||
# From the EDF file itself:
|
||||
assert row.eeg_duracion_min is not None
|
||||
assert row.eeg_estudio[:8].strip() == b"0"
|
||||
# From the scanned report, on the very same row:
|
||||
assert row.eeg_simetria == "SIMETRICO"
|
||||
assert "sin eventos epileptiformes" in row.eeg_conclusion_texto
|
||||
assert row.eeg_medico_interpreta == "Dra. Ruiz"
|
||||
# From the report, on the very same row:
|
||||
assert row.eeg_fecha_estudio == date(2024, 2, 20)
|
||||
|
||||
|
||||
def test_citologia_table_and_scanned_report_merge_on_the_order_number(client):
|
||||
@@ -369,3 +348,41 @@ def test_embedded_image_in_the_report_maps_onto_the_target_dicom_column(client):
|
||||
[row] = mastografia_repository.list(pac_id_hospital="IMG-0001")
|
||||
assert "nódulo circunscrito" in row.mast_interpretacion
|
||||
assert row.mast_dicom_blob.startswith(b"\x89PNG")
|
||||
|
||||
|
||||
def test_a_tea_order_keeps_the_pdf_its_sql_source_carries(client, tmp_path):
|
||||
"""Pins down: `ord_pdf_blob` travels with the order from a SQL source into `ordenes_estudio`, byte for
|
||||
byte, and an order without a file stays without one. The source is a SQLite file in `tmp_path` holding a
|
||||
two-row `ordenes_estudio`. Fails if the import schema drops the field or the commit rewrites the bytes."""
|
||||
report = text_pdf([["EVALUACION PSICOLOGICA", "ADOS-2 Modulo 2"]])
|
||||
url = f"sqlite:///{tmp_path / 'hospital.db'}"
|
||||
table = sa.Table(
|
||||
"ordenes_estudio", sa.MetaData(),
|
||||
sa.Column("ord_id", sa.String(36), primary_key=True),
|
||||
sa.Column("ord_id_hospital", sa.String(64)),
|
||||
sa.Column("ord_tipo_estudio", sa.Text),
|
||||
sa.Column("ord_pdf_blob", sa.LargeBinary),
|
||||
)
|
||||
engine = sa.create_engine(url)
|
||||
table.create(engine)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(sa.insert(table), [
|
||||
{"ord_id": "ord-pdf-1", "ord_id_hospital": "ORD-PDF-1", "ord_tipo_estudio": "ADOS2", "ord_pdf_blob": report},
|
||||
{"ord_id": "ord-pdf-2", "ord_id_hospital": "ORD-PDF-2", "ord_tipo_estudio": "EEG", "ord_pdf_blob": None},
|
||||
])
|
||||
engine.dispose()
|
||||
source = {
|
||||
"source_type": "sql",
|
||||
"target": "tea.OrdenesEstudio",
|
||||
"column_mapping": {column.name: column.name for column in table.columns},
|
||||
"payload": {"connection_string": url, "table": "ordenes_estudio"},
|
||||
}
|
||||
|
||||
result = client.post("/imports/commit", json={"sources": [source], "on_conflict": "upsert"}).get_json()["results"][0]
|
||||
|
||||
assert (result["created"], result["rejected"]) == (2, 0), result
|
||||
|
||||
from persistance.tea import ordenes_estudio_repository
|
||||
|
||||
assert ordenes_estudio_repository.get("ord-pdf-1").ord_pdf_blob == report
|
||||
assert ordenes_estudio_repository.get("ord-pdf-2").ord_pdf_blob is None
|
||||
|
||||
@@ -27,7 +27,7 @@ CONSULTA = text("""
|
||||
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=["cacu", "cama"])
|
||||
@pytest.fixture(scope="module", params=["cacu", "cama", "tea"])
|
||||
def bases(request, tmp_path_factory):
|
||||
proyecto = request.param
|
||||
carpeta = tmp_path_factory.mktemp(proyecto)
|
||||
|
||||
@@ -84,10 +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.
|
||||
assert resumen["definitions"] == {"cacu": 10, "cama": 7}[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() == 7 # seven measures in each domain
|
||||
assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 8, "tea": 10}[base.proyecto]
|
||||
assert base.run("definitions")["definitions"]["borradas"] == 0
|
||||
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ def antes(deps: dict[str, set[str]], paso: str) -> set[str]:
|
||||
return previos
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama"])
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
|
||||
def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto):
|
||||
deps = dependencias(proyecto)
|
||||
assert deps["migrate"] == set()
|
||||
|
||||
@@ -26,6 +26,7 @@ from sqlmodel import select
|
||||
CAMBIO = {
|
||||
"cacu": ("citologiacervical", "cit_calidad_especimen", "INSATISFACTORIO"),
|
||||
"cama": ("mastografia", "mast_calidad_imagen", "OTRA CALIDAD"),
|
||||
"tea": ("mchat", "mch_puntaje", 19),
|
||||
}
|
||||
CORTE = date(2025, 12, 31)
|
||||
|
||||
@@ -74,7 +75,9 @@ def test_catalogos_deja_en_la_base_las_filas_del_toml(base):
|
||||
del_toml = {"estudios": len(catalogo.estudios), "resultados": len(catalogo.resultados),
|
||||
"valores": len(catalogo.valores)}
|
||||
|
||||
assert base.run("catalogs")["catalogs"] == {**del_toml, "retirados": 0}
|
||||
conteos = base.run("catalogs")["catalogs"]
|
||||
assert conteos.pop("mapeos_nuevos") > 0
|
||||
assert conteos == {**del_toml, "retirados": 0}
|
||||
assert filas_del_catalogo(base) == del_toml
|
||||
|
||||
|
||||
@@ -82,7 +85,8 @@ def test_volver_a_correr_catalogos_no_cambia_nada(base):
|
||||
base.run("catalogs")
|
||||
antes = filas_del_catalogo(base)
|
||||
|
||||
assert base.run("catalogs")["catalogs"]["retirados"] == 0
|
||||
conteos = base.run("catalogs")["catalogs"]
|
||||
assert (conteos["retirados"], conteos["mapeos_nuevos"]) == (0, 0)
|
||||
assert filas_del_catalogo(base) == antes
|
||||
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ def test_ningun_modulo_fuera_de_repositorios_abre_sesiones(modulo):
|
||||
assert not PROHIBIDO.findall(texto), f"{modulo} abre su propia sesión: debe usar ctx.repos"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True)])
|
||||
@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True), ("tea", True)])
|
||||
def test_cada_proyecto_tiene_sus_repositorios(proyecto, con_cohortes):
|
||||
repos = repositories_of(proyecto)
|
||||
assert (repos.gold.cohorts is not None) == con_cohortes
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
shape the WebApp's contract reads (`RiesgoPacienteCacu`), and its 404. The reads behind it are Persistance's, tested
|
||||
there.
|
||||
|
||||
Fixtures: `client`, a DEV client over the kit's CaCu demonstration database (`conftest.cliente_de`) plus `seeded`:
|
||||
a surveillance build with two of its patients, one of them with variables and a confirmed batch; `fuera_de_dev`, the
|
||||
same app without `DEV_REVISION`.
|
||||
Fixtures: `client`, the app without `DEV_REVISION` over the kit's CaCu demonstration database (`conftest.cliente_de`)
|
||||
plus `seeded`: a surveillance build with two of its patients, one of them with variables and a confirmed batch.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
@@ -19,8 +18,9 @@ HORIZON_KEYS = {"horizonte_anios", "probabilidad", "ic_bajo", "ic_alto", "estado
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
"""The app over the CaCu demonstration database, with no `DEV_REVISION` in the environment."""
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setenv("DEV_REVISION", "prueba")
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@@ -55,17 +55,11 @@ def seeded(client):
|
||||
return scored, unscored, outside
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fuera_de_dev(tmp_path_factory):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
def test_a_scored_member_has_the_contracts_shape(client, seeded):
|
||||
"""Pins down: the body has `simulado`, `cohorte` and `riesgo` with exactly the contract's fields, the horizons in
|
||||
ascending order, probabilities in 0..1 and the date as ISO-8601 UTC. Fails if a field is renamed or dropped, which
|
||||
would break the WebApp's validation."""
|
||||
"""Pins down: without `DEV_REVISION` the route exists, and the body has `simulado`, `cohorte` and `riesgo` with
|
||||
exactly the contract's fields, the horizons in ascending order, probabilities in 0..1 and the date as ISO-8601 UTC.
|
||||
Fails if the route depends on an environment variable again, or if a field is renamed or dropped, which would break
|
||||
the WebApp's validation."""
|
||||
response = client.get(f"/cacu/pacientes/{seeded[0]}/riesgo")
|
||||
|
||||
body = response.get_json()
|
||||
@@ -91,9 +85,3 @@ def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded):
|
||||
def test_an_unknown_patient_is_404(client, seeded):
|
||||
"""Pins down: a `pac_id` not in `persona` is 404. Fails if it answers with an empty body as if she existed."""
|
||||
assert client.get("/cacu/pacientes/987654321/riesgo").status_code == 404
|
||||
|
||||
|
||||
def test_outside_dev_the_route_does_not_exist(fuera_de_dev):
|
||||
"""Pins down: without `DEV_REVISION` the route isn't registered. Fails if patient-level risks are served outside
|
||||
the simulated DEV deployment."""
|
||||
assert fuera_de_dev.get("/cacu/pacientes/1/riesgo").status_code == 404
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Extraction's ranker in WebApi: the document review reports each field's
|
||||
alternatives, whether the record is about the target and which extraction
|
||||
version read it; an import whose records a person corrected teaches the
|
||||
domain's ranker once it is written (`webapi.imports.services.
|
||||
review_learning`); and `python -m webapi.nlp` scores and trains against an
|
||||
answer key.
|
||||
|
||||
Fixtures: `client` (the app over fresh CaCu, CaMa and TEA databases),
|
||||
`registry` (a SQLite MLflow per test with its files in `tmp_path`, the
|
||||
ranker and learning switched on, and learning run synchronously). Documents are made up inline with
|
||||
`text_pdf`.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
from concurrent.futures import Future
|
||||
|
||||
import pytest
|
||||
from extraction.testing import text_pdf
|
||||
|
||||
from webapi import nlp
|
||||
from webapi.imports.services import review_learning
|
||||
|
||||
REPORT = text_pdf([["LABORATORIO DE CITOLOGÍA", "Expediente: RV-0001", "No. de orden: 9001", "Prueba de VPH por PCR: POSITIVO",
|
||||
"Observaciones: se sugiere colposcopía; en caso de VPH negativo repetir en un año."]])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
wire_domain("cama")
|
||||
wire_domain("tea")
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
class _Now:
|
||||
"""An executor that runs each task as it is submitted."""
|
||||
|
||||
def submit(self, fn, *args):
|
||||
future = Future()
|
||||
future.set_result(fn(*args))
|
||||
return future
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def registry(tmp_path, monkeypatch):
|
||||
import mlflow
|
||||
|
||||
from models.io import extraction_ranker
|
||||
|
||||
uri = f"sqlite:///{tmp_path / 'mlflow.db'}"
|
||||
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
|
||||
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / "artefactos"))
|
||||
mlflow.set_tracking_uri(uri)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.setenv("EXTRACTION_RANKER", "auto")
|
||||
monkeypatch.setenv("EXTRACTION_LEARNING", "1")
|
||||
monkeypatch.setattr(extraction_ranker, "_cache", {})
|
||||
monkeypatch.setattr(review_learning, "_executor", _Now())
|
||||
from models.io.registry import registry as models_registry
|
||||
|
||||
yield models_registry
|
||||
|
||||
|
||||
def _source(**options) -> dict:
|
||||
return {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "ord_numero_hospital": "ord_numero_hospital",
|
||||
"cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"files": [{"name": "r.pdf", "file_base64": base64.b64encode(REPORT).decode()}], **options},
|
||||
"label": "documentos",
|
||||
}
|
||||
|
||||
|
||||
def test_the_review_reports_alternatives_topic_and_version(client):
|
||||
"""Fails if the review loses the other readings a person can pick, the
|
||||
subject check, or the extraction version that will be stored."""
|
||||
body = client.post("/imports/sources/document/extract", json={"files": _source()["payload"]["files"], "target": "cacu.CitologiaCervical"}).get_json()
|
||||
[record] = body["records"]
|
||||
assert record["on_topic"] is True
|
||||
assert record["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
assert record["fields"]["cit_vph_resultado"]["assertion"] == "afirmado"
|
||||
assert body["nlp_version"].startswith("extraction ")
|
||||
assert all(isinstance(options, list) for options in record["alternatives"].values())
|
||||
|
||||
|
||||
def test_a_corrected_import_teaches_the_ranker(client, registry):
|
||||
"""Committing a document source with a correction registers a new DEV
|
||||
version of the domain's ranker, learned from that record. Fails if
|
||||
`commit_sources` stops calling `learn_from_reviews` or the examples are
|
||||
lost on the way."""
|
||||
source = _source(overrides={"0": {"cit_vph_resultado": "NEGATIVO"}})
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()
|
||||
assert result["ok"], result
|
||||
[version] = registry.versions("cacu", "extraccion")
|
||||
assert version["status"] == "desarrollo"
|
||||
from models.io.extraction_ranker import current
|
||||
|
||||
assert current("cacu").examples > 0
|
||||
|
||||
|
||||
def test_imports_without_corrections_or_with_learning_off_teach_nothing(client, registry, monkeypatch):
|
||||
"""Fails if an untouched import, or one made with
|
||||
`EXTRACTION_LEARNING=0`, creates ranker versions."""
|
||||
client.post("/imports/commit", json={"sources": [_source()]})
|
||||
monkeypatch.setenv("EXTRACTION_LEARNING", "0")
|
||||
client.post("/imports/commit", json={"sources": [_source(overrides={"0": {"cit_vph_resultado": "NEGATIVO"}})]})
|
||||
assert registry.versions("cacu", "extraccion") == []
|
||||
|
||||
|
||||
def test_the_command_scores_and_trains_against_an_answer_key(tmp_path, registry):
|
||||
"""`evaluate` scores per field and overall without printing values
|
||||
unless asked; `train` estimates on held-out documents, then registers
|
||||
a version. Fails if the command's key format or outputs change."""
|
||||
folder = tmp_path / "documentos"
|
||||
folder.mkdir()
|
||||
(folder / "a.pdf").write_bytes(REPORT)
|
||||
(folder / "b.pdf").write_bytes(text_pdf([["Biopsia cervical dirigida", "Diagnóstico:", "NIC I"]]))
|
||||
key = {
|
||||
"a.pdf": {"cacu.CitologiaCervical": {"cit_vph_resultado": "POSITIVO", "pac_id_hospital": "RV-0001"}},
|
||||
"b.pdf": {"cacu.CitologiaCervical": {"cit_vph_resultado": None}, "cacu.BiopsiaCervical": {"bx_cin_grado": "LIEBG"}},
|
||||
}
|
||||
(tmp_path / "clave.json").write_text(json.dumps(key))
|
||||
paths = {"documents": str(folder), "key": str(tmp_path / "clave.json")}
|
||||
evaluated = nlp.command_evaluate(argparse.Namespace(**paths, with_values=False, no_ranker=True))
|
||||
assert evaluated["global"]["f1"] == 1.0
|
||||
assert evaluated["errores"] == []
|
||||
trained = nlp.command_train(argparse.Namespace(**paths))
|
||||
assert set(trained) == {"sin_ranker", "estimacion_dejando_uno_fuera", "versiones"}
|
||||
assert trained["versiones"] == {"cacu": "1"}
|
||||
+10
-9
@@ -48,14 +48,15 @@ def test_tea_pacientes_schema_is_fully_optional():
|
||||
assert schema.pac_id_hospital is None
|
||||
|
||||
|
||||
def test_tea_pacientes_schema_coerces_sexo_from_bare_enum_no_alias_dict():
|
||||
schema = PacientesImportSchema(pac_sexo="f")
|
||||
assert schema.pac_sexo == "F"
|
||||
def test_tea_neuropediatrics_note_takes_icd10_with_or_without_the_dot():
|
||||
"""Pins down: the note's ICD-10 is upper-cased and accepted with or without its dot; anything else is
|
||||
rejected. Fails if the pattern of `neu_cie_codigo` changes."""
|
||||
from webapi.imports.schemas.tea.evaluacion_neuropediatrica import EvaluacionNeuropediatricaImportSchema as Nota
|
||||
|
||||
|
||||
def test_tea_pacientes_schema_coerces_parentesco():
|
||||
schema = PacientesImportSchema(pac_parentesco="hijo")
|
||||
assert schema.pac_parentesco == "HIJO"
|
||||
assert Nota(neu_cie_codigo=" f84.0 ").neu_cie_codigo == "F84.0"
|
||||
assert Nota(neu_cie_codigo="F840").neu_cie_codigo == "F840"
|
||||
with pytest.raises(ValidationError):
|
||||
Nota(neu_cie_codigo="autismo")
|
||||
|
||||
|
||||
def test_classify_error_missing():
|
||||
@@ -243,5 +244,5 @@ def test_catalog_aliases_for_values_the_indicator_kit_uses():
|
||||
cito = CitologiaCervicalImportSchema(pac_id_hospital="H", cit_celulas_escamosas="NEGATIVO")
|
||||
assert cito.cit_celulas_escamosas == "NORMAL"
|
||||
assert CamaOrdenes(pac_id_hospital="H", ord_numero_hospital=1, ord_tipo_estudio="MASTOGRAFIA").ord_tipo_estudio == "MASTOGRAFIA"
|
||||
assert TeaOrdenes(ord_tipo_estudio="POTENCIALES_EVOCADOS").ord_tipo_estudio == "POTENCIALES_EVOCADOS_AUDITIVOS"
|
||||
assert TeaOrdenes(ord_tipo_estudio=" evaluacion_psicologica_tea ").ord_tipo_estudio == "EVALUACION_PSICOLOGICA_TEA"
|
||||
assert TeaOrdenes(ord_tipo_estudio="electroencefalograma").ord_tipo_estudio == "EEG"
|
||||
assert TeaOrdenes(ord_tipo_estudio=" evaluacion_psicologica_tea ").ord_tipo_estudio == "ADOS2"
|
||||
|
||||
@@ -5,7 +5,8 @@ from pydantic import ValidationError
|
||||
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema
|
||||
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
|
||||
from webapi.imports.schemas.tea.ados2 import Ados2ImportSchema
|
||||
from webapi.imports.schemas.tea.mchat import MchatImportSchema
|
||||
from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.episodio_clinico import EpisodioClinicoImportSchema
|
||||
|
||||
@@ -48,11 +49,21 @@ def test_cama_ordenes_estudio_requires_numero_hospital_and_coerces_tipo_estudio(
|
||||
assert schema.ord_tipo_estudio == "BIOPSIA_CHICA"
|
||||
|
||||
|
||||
# TEA entity with a bare Enum field (no *_ALIAS dict), so the schema builds
|
||||
# a Catalog from the Enum alone, as in tea/pacientes.py.
|
||||
def test_tea_eeg_estudio_coerces_simetria_from_bare_enum_no_alias_dict():
|
||||
schema = EegEstudioImportSchema(eeg_simetria="simetrico")
|
||||
assert schema.eeg_simetria == "SIMETRICO"
|
||||
def test_tea_ados2_coerces_module_and_classification_aliases():
|
||||
"""Pins down: the ADOS-2's module comes from the bare enum and its classification takes the old spelling
|
||||
`NO_TEA`. Fails if either catalog stops normalizing case or aliases."""
|
||||
schema = Ados2ImportSchema(ado_modulo="modulo_1", ado_clasificacion="no_tea")
|
||||
assert (schema.ado_modulo, schema.ado_clasificacion) == ("MODULO_1", "NO_ESPECTRO")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("schema", "field", "value"), [
|
||||
(MchatImportSchema, "mch_puntaje", 21), (Ados2ImportSchema, "ado_css", 0), (Ados2ImportSchema, "ado_sa_b1", 4),
|
||||
])
|
||||
def test_tea_scores_out_of_their_range_are_rejected(schema, field, value):
|
||||
"""Pins down: an M-CHAT score above 20, a CSS below 1 and an ADOS-2 item above 3 are validation errors. Fails if
|
||||
a bound of `Bounded` is dropped from the schemas."""
|
||||
with pytest.raises(ValidationError):
|
||||
schema(**{field: value})
|
||||
|
||||
|
||||
# CaCu entity with a real *_ALIAS-backed field (GRADO_CIN_ALIAS).
|
||||
|
||||
+17
-14
@@ -1,32 +1,29 @@
|
||||
"""La lista de seguimiento (T-24d): `GET /cacu/seguimiento`, solo en DEV y siempre simulada.
|
||||
"""La lista de seguimiento (T-24d): `GET /cacu/seguimiento`, siempre simulada.
|
||||
|
||||
Sobre la base de demostración del kit (`conftest.cliente_de`). La lista en sí se prueba en el kit
|
||||
(`tests/test_lista_seguimiento.py`); aquí, la ruta: cuándo existe, la forma y los códigos de error.
|
||||
(`tests/test_lista_seguimiento.py`); aquí, la ruta: que existe sin `DEV_REVISION`, la forma y los códigos
|
||||
de error. Fixtures: `client`, la app sin `DEV_REVISION` sobre la base de demostración de CaCu.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"}
|
||||
LLAVES_DEL_ITEM = {"id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
|
||||
LLAVES_DEL_ITEM = {"pac_id", "id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
|
||||
"dias_toma_diagnostico", "prioridad"} # fmt: skip
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setenv("DEV_REVISION", "prueba")
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fuera_de_dev(tmp_path_factory):
|
||||
"""La app sobre la base de demostración de CaCu, sin `DEV_REVISION` en el entorno."""
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
def test_en_dev_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
|
||||
def test_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
|
||||
"""Fija: sin `DEV_REVISION` la ruta existe, con la forma del contrato y `simulado: true`. Falla si la ruta
|
||||
vuelve a depender de una variable de entorno o cambia un campo."""
|
||||
response = client.get("/cacu/seguimiento?corte=2025-12-31")
|
||||
|
||||
assert response.status_code == 200 and response.mimetype == "application/json"
|
||||
@@ -34,7 +31,9 @@ def test_en_dev_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
|
||||
assert set(cuerpo) == LLAVES and cuerpo["simulado"] is True
|
||||
assert cuerpo["items"] and all(set(i) == LLAVES_DEL_ITEM for i in cuerpo["items"])
|
||||
assert all(i["prioridad"] is None for i in cuerpo["items"])
|
||||
assert "pac_id" not in response.get_data(as_text=True)
|
||||
# The patient key is the platform's `pac_id`, the one the risk route takes; the hospital's id never leaves.
|
||||
assert all(i["pac_id"].isdigit() and i["id_seudonimo"] == i["pac_id"] for i in cuerpo["items"])
|
||||
assert "pac_id_hospital" not in response.get_data(as_text=True)
|
||||
|
||||
|
||||
def test_el_pedido_se_respeta(client):
|
||||
@@ -63,5 +62,9 @@ def test_una_pagina_de_mas_da_404(client):
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_fuera_de_dev_la_ruta_no_existe(fuera_de_dev):
|
||||
assert fuera_de_dev.get("/cacu/seguimiento").status_code == 404
|
||||
def test_in_dev_esta_obsoleta():
|
||||
"""Fija: `in_dev()` avisa que está obsoleta. Falla si alguien vuelve a usarla como compuerta sin el aviso."""
|
||||
from webapi.follow_up.routes import in_dev
|
||||
|
||||
with pytest.warns(DeprecationWarning):
|
||||
in_dev()
|
||||
|
||||
+14
-14
@@ -76,31 +76,31 @@ def test_tea_children_keep_pointing_at_their_parents_source_ids(tea_client):
|
||||
sources = [
|
||||
_json([{"pac_id": 1, "pac_id_hospital": "T-1"}], "tea.Pacientes"),
|
||||
_json([{"ord_id": "ord-1", "ord_pac_id": 1, "ord_id_hospital": "O-1"}], "tea.OrdenesEstudio"),
|
||||
_json([{"psi_id": "psi-1", "psi_ord_id": "ord-1", "psi_pac_id": 1}], "tea.EvaluacionPsicologica"),
|
||||
_json([{"ins_psi_id": "psi-1", "ins_instrumento": "ADOS-2"}], "tea.InstrumentoAplicado"),
|
||||
_json([{"eeg_id": "eeg-1", "eeg_ord_id": "ord-1", "eeg_id_registro_laboratorio": "L-1"}], "tea.EegEstudio"),
|
||||
_json([{"seg_eeg_id": "eeg-1", "seg_duracion_s": 30}], "tea.EegSegmento"),
|
||||
_json([{"ado_id": "ado-1", "ado_ord_id": "ord-1", "ado_pac_id": 1}], "tea.Ados2"),
|
||||
_json([{"eeg_id": "eeg-1", "eeg_ord_id": "ord-1", "eeg_id_registro_laboratorio": "L-1"}], "tea.Eeg"),
|
||||
_json([{"met_id": "met-1", "met_eeg_id": "eeg-1", "met_codigo": "RITMO_POSTERIOR", "met_valor": 5.5}], "tea.EegMetrica"),
|
||||
_json([{"mel_met_id": "met-1", "mel_electrodo": "O1", "mel_valor": -1.2}], "tea.EegMetricaElectrodo"),
|
||||
]
|
||||
body = tea_client.post("/imports/commit", json={"sources": sources}).get_json()
|
||||
assert all(r["rejected"] == 0 for r in body["results"]), body
|
||||
|
||||
from persistance.tea import (
|
||||
eeg_estudio_repository,
|
||||
eeg_segmento_repository,
|
||||
evaluacion_psicologica_repository,
|
||||
instrumento_aplicado_repository,
|
||||
ados2_repository,
|
||||
eeg_metrica_electrodo_repository,
|
||||
eeg_metrica_repository,
|
||||
eeg_repository,
|
||||
)
|
||||
|
||||
assert eeg_estudio_repository.get(eeg_segmento_repository.list()[0].seg_eeg_id).eeg_id_registro_laboratorio == "L-1"
|
||||
evaluacion = evaluacion_psicologica_repository.get(instrumento_aplicado_repository.list()[0].ins_psi_id)
|
||||
assert evaluacion.psi_ord_id == "ord-1"
|
||||
metrica = eeg_metrica_repository.get(eeg_metrica_electrodo_repository.list()[0].mel_met_id)
|
||||
assert eeg_repository.get(metrica.met_eeg_id).eeg_id_registro_laboratorio == "L-1"
|
||||
assert ados2_repository.get("ado-1").ado_ord_id == "ord-1"
|
||||
|
||||
|
||||
def test_tea_rows_without_a_source_id_get_one(tea_client):
|
||||
eeg = _json([{"eeg_id_registro_laboratorio": "L-SIN-ID"}], "tea.EegEstudio")
|
||||
eeg = _json([{"eeg_id_registro_laboratorio": "L-SIN-ID"}], "tea.Eeg")
|
||||
assert tea_client.post("/imports/commit", json={"sources": [eeg]}).get_json()["results"][0]["created"] == 1
|
||||
|
||||
from persistance.tea import eeg_estudio_repository
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
[fila] = [e for e in eeg_estudio_repository.list() if e.eeg_id_registro_laboratorio == "L-SIN-ID"]
|
||||
[fila] = [e for e in eeg_repository.list() if e.eeg_id_registro_laboratorio == "L-SIN-ID"]
|
||||
assert len(fila.eeg_id) == 36
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""What this module covers: source forms as a function into the catalog's codes (`reference.source_mapping`):
|
||||
many forms to one code, no code for an unknown form, the same form read per source system and per date, and two
|
||||
codes for one form rejected when they're in force together; every catalog's TOML passing that check; and, in each
|
||||
domain's database, the catalog step seeding `cat_mapeo` without touching a stored row and `register` refusing a
|
||||
mapping that breaks the function.
|
||||
|
||||
Fixtures: `base` (conftest), each domain's migrated fixture database; the other tests build their rows.
|
||||
"""
|
||||
|
||||
import tomllib
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from webapi.orchestration.reference.catalogs import ruta_de_catalogo
|
||||
from webapi.orchestration.reference.source_mapping import (
|
||||
CATALOG, SourceForm, ambiguities, check_function, from_result, normalize, register, resolve,
|
||||
)
|
||||
|
||||
HER2 = "biopsia.her2"
|
||||
LAB_A = [SourceForm("lab_a", HER2, "3+", "H3", None, date(2026, 12, 31)),
|
||||
SourceForm("lab_a", HER2, "Positivo", "H3", None, date(2026, 12, 31))]
|
||||
LAB_B = [SourceForm("lab_b", HER2, "Positivo (score 3)", "H3", date(2027, 1, 1)),
|
||||
SourceForm("lab_b", HER2, "Positivo", "H2", date(2027, 1, 1))]
|
||||
|
||||
|
||||
def test_many_forms_give_one_code_and_an_unknown_form_none():
|
||||
"""Pins down: the mapping isn't injective and is partial: several spellings, compared without case, accents or
|
||||
extra spaces, give the same code; a spelling with no mapping gives None. Fails if `normalize` stops folding or
|
||||
`resolve` invents a code."""
|
||||
assert {resolve(LAB_A, "lab_a", HER2, f) for f in ("3+", " positivo ", "POSITIVO")} == {"H3"}
|
||||
assert resolve(LAB_A, "lab_a", HER2, "Equívoco") is None
|
||||
assert normalize(" Positívo (score 3) ") == "POSITIVO (SCORE 3)"
|
||||
|
||||
|
||||
def test_a_form_is_read_per_source_system_and_per_date():
|
||||
"""Pins down: "Positivo" is H3 at lab A and H2 at lab B, and a mapping applies only to documents dated within its
|
||||
validity. Fails if `resolve` ignores the system or the dates, letting one lab's spelling leak into another's."""
|
||||
rows = LAB_A + LAB_B
|
||||
assert resolve(rows, "lab_a", HER2, "Positivo", date(2026, 6, 1)) == "H3"
|
||||
assert resolve(rows, "lab_b", HER2, "Positivo", date(2027, 2, 1)) == "H2"
|
||||
assert resolve(rows, "lab_b", HER2, "Positivo", date(2026, 6, 1)) is None
|
||||
assert ambiguities(rows) == []
|
||||
|
||||
|
||||
def test_two_codes_for_one_form_in_force_together_are_rejected():
|
||||
"""Pins down: a form mapped to two codes with overlapping validity breaks the function: `check_function` names
|
||||
it and `resolve` gives None rather than either code. Two codes in validities that don't overlap, or the same
|
||||
code twice, are fine. Fails if the overlap test or the code comparison is dropped."""
|
||||
clash = SourceForm("lab_b", HER2, "positivo", "H3", date(2027, 6, 1))
|
||||
with pytest.raises(ValueError, match="se escribe igual para 'H2' y 'H3'"):
|
||||
check_function(LAB_B + [clash])
|
||||
assert resolve(LAB_B + [clash], "lab_b", HER2, "Positivo", date(2027, 7, 1)) is None
|
||||
corrected = [LAB_B[1]._replace(valid_to=date(2027, 5, 31)), clash]
|
||||
check_function(corrected)
|
||||
assert resolve(corrected, "lab_b", HER2, "Positivo", date(2027, 7, 1)) == "H3"
|
||||
check_function(LAB_B + [LAB_B[0]._replace(form="POSITIVO (SCORE 3)")])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
|
||||
def test_every_catalog_s_spellings_are_a_function(proyecto):
|
||||
"""Pins down: in each domain's TOML, every result's codes, labels and aliases map to one value each. Fails when
|
||||
an edit to a catalog gives one spelling two values."""
|
||||
estudios = tomllib.loads(ruta_de_catalogo(proyecto).read_text(encoding="utf-8"))
|
||||
rows = [row for estudio_id, estudio in estudios.items()
|
||||
for nombre, resultado in estudio.get("resultados", {}).items()
|
||||
for row in from_result(f"{estudio_id}.{nombre}", resultado)]
|
||||
check_function(rows)
|
||||
|
||||
|
||||
# --- the stored mappings, in each domain ---
|
||||
|
||||
|
||||
def a_coded_result(base) -> tuple[str, str, str]:
|
||||
"""A coded result of the domain's catalog with two values: (resultado_id, first valor_id, second valor_id)."""
|
||||
estudios = tomllib.loads(ruta_de_catalogo(base.proyecto).read_text(encoding="utf-8"))
|
||||
for estudio_id, estudio in estudios.items():
|
||||
for nombre, resultado in estudio.get("resultados", {}).items():
|
||||
valores = resultado.get("valores", ())
|
||||
if len(valores) >= 2:
|
||||
return f"{estudio_id}.{nombre}", valores[0]["valor"], valores[1]["valor"]
|
||||
raise AssertionError("el catálogo no tiene un resultado codificado con dos valores")
|
||||
|
||||
|
||||
def test_the_catalog_step_seeds_the_mappings_and_keeps_what_a_person_changed(base):
|
||||
"""Pins down: the catalog step adds the catalog's own mappings (each value's code among them) and, run again,
|
||||
adds nothing and leaves a person's row for a new form as it is. Fails if the step stops seeding or a deploy
|
||||
replaces stored rows."""
|
||||
base.run("catalogs")
|
||||
mappings = base.ctx.repos.silver.mappings
|
||||
resultado, primero, segundo = a_coded_result(base)
|
||||
sembradas = mappings.forms(sistema_fuente_id=CATALOG, resultado_id=resultado, clase="valor")
|
||||
assert {(m.forma, m.valor_id) for m in sembradas} >= {(primero, primero), (segundo, segundo)}
|
||||
register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma=" forma del curador ", registrado_por="curador",
|
||||
vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=segundo)
|
||||
assert base.run("catalogs")["catalogs"]["mapeos_nuevos"] == 0
|
||||
[mia] = mappings.forms(forma_normalizada="FORMA DEL CURADOR")
|
||||
assert (mia.forma, mia.valor_id, mia.registrado_por) == ("forma del curador", segundo, "curador")
|
||||
|
||||
|
||||
def test_register_refuses_a_second_code_for_a_form_in_force(base):
|
||||
"""Pins down: `register` checks the new row against the stored ones: the catalog's own code of one value can't
|
||||
be mapped to another value, and a lab's form can, once the first row's validity ends before the second's starts.
|
||||
Fails if the write path stops running `check_function`."""
|
||||
base.run("catalogs")
|
||||
mappings = base.ctx.repos.silver.mappings
|
||||
resultado, primero, segundo = a_coded_result(base)
|
||||
with pytest.raises(ValueError, match="se escribe igual"):
|
||||
register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma=primero, registrado_por="curador",
|
||||
vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=segundo)
|
||||
viejo = register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma="Código de laboratorio",
|
||||
registrado_por="curador", vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=primero)
|
||||
mappings.close(viejo.mapeo_id, date(2026, 12, 31))
|
||||
nuevo = register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma="codigo de LABORATORIO",
|
||||
registrado_por="curador", vigente_desde=date(2027, 1, 1), resultado_id=resultado, valor_id=segundo)
|
||||
filas = mappings.forms(forma_normalizada=normalize("Código de laboratorio"))
|
||||
assert [f.mapeo_id for f in filas] == [viejo.mapeo_id, nuevo.mapeo_id]
|
||||
@@ -0,0 +1,273 @@
|
||||
"""What this module covers: TEA's ten measures answered on request from dbt's semantic layer, on hand-written
|
||||
expectations for the synthetic children of `staging.tea`, period by period: who each period counts (the children in
|
||||
the screening during it, at their stage at its end, leaving after the period of their good EEG), the day counts, the
|
||||
EEGs by quality and the alterations of each child's first good EEG.
|
||||
|
||||
Fixtures: `base`, TEA's fixture database through the cycle up to `event_models` (dbt's views); `manifest`, dbt's
|
||||
`manifest.json` (`DBT_MANIFEST`; skipped without it). The expectations are worked out by hand from the children's
|
||||
dates in `staging/tea.py`; each test says which child makes each number.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from sqlmodel import select
|
||||
|
||||
import staging.tea as fixture
|
||||
from conftest import base_de
|
||||
from core.tea.models import Ados2, Eeg, EegMetrica, Mchat
|
||||
from webapi.compositions import answer_composition, composition_definitions
|
||||
from webapi.durations import answer_duration, duration_definitions
|
||||
from webapi.metrics import Question, answer, measure_definitions
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
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(scope="module")
|
||||
def base(tmp_path_factory, manifest):
|
||||
"""The seven children of `staging.tea`, loaded once, with dbt's TEA views created."""
|
||||
base = base_de("tea", tmp_path_factory.mktemp("tea"))
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def repositories(base) -> dict:
|
||||
d = base.dominio
|
||||
return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository,
|
||||
"history": d.history_repository, "queries": d.dbt_query_repository, "allow_undecided": True}
|
||||
|
||||
|
||||
def composition(base, manifest, measure_id, period, **question):
|
||||
url = f"tea/{measure_id}"
|
||||
result = answer_composition("tea", composition_definitions(manifest)[url], Question(url, period, **question),
|
||||
**repositories(base))
|
||||
return {k: v for k, v in result.categories.items() if v}
|
||||
|
||||
|
||||
def proportion(base, manifest, measure_id, period, **question):
|
||||
url = f"tea/{measure_id}"
|
||||
return answer("tea", measure_definitions(manifest)[url], Question(url, period, **question), **repositories(base))
|
||||
|
||||
|
||||
def duration(base, manifest, measure_id, period):
|
||||
url = f"tea/{measure_id}"
|
||||
return answer_duration("tea", duration_definitions(manifest)[url], Question(url, period), **repositories(base))
|
||||
|
||||
|
||||
STAGES = {
|
||||
"2025-01": {"SOLO_MCHAT": 2},
|
||||
"2025-02": {"SOLO_MCHAT": 1, "PSICOLOGIA": 2},
|
||||
"2025-03": {"PSICOLOGIA": 2, "NEUROPEDIATRIA": 1},
|
||||
"2025-04": {"PSICOLOGIA": 2, "NEUROPEDIATRIA": 2},
|
||||
"2025-05": {"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 1, "EEG": 1},
|
||||
"2025-06": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 1},
|
||||
"2025-07": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1},
|
||||
"2025-12": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1},
|
||||
"2025-S1": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 2},
|
||||
"2025-S2": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("period", sorted(STAGES))
|
||||
def test_m28_counts_every_child_in_the_screening_at_its_stage_at_the_period_s_end(base, manifest, period):
|
||||
"""Pins down M28: a period counts every cohort child who entered by its end and hadn't finished before its start,
|
||||
at the furthest step reached by its end, whether or not anything of theirs happened in it. Child 1 is at
|
||||
psychology in February and March's stage moves with its note; it reaches EEG in May and is gone from June. Child 2
|
||||
stays at neuropediatrics all year; child 5 stays at M-CHAT (no ADOS-2); child 6 reaches EEG on its note's day,
|
||||
2 June; child 4 (39 months) never counts; child 7 (no birth date) counts from May.
|
||||
|
||||
Fails if the population goes back to the children with a fact in the period, if a child stops leaving after the
|
||||
period of its good EEG, or if a step stops needing the previous one."""
|
||||
assert composition(base, manifest, "M28_casos_por_estado", period) == STAGES[period]
|
||||
|
||||
|
||||
def test_m28_an_event_cut_off_leaves_out_what_came_after_it(base, manifest):
|
||||
"""Pins down: facts dated after the event cut-off don't count. With a cut-off of 10 May, child 1's good EEG of
|
||||
20 May isn't there, so May counts it at neuropediatrics. Fails if the status rows stop applying the cut-off."""
|
||||
assert composition(base, manifest, "M28_casos_por_estado", "2025-05", event_cutoff=date(2025, 5, 10)) == {
|
||||
"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2}
|
||||
|
||||
|
||||
RESULTS = {
|
||||
"2025-01": {"EN_PROCESO": 2},
|
||||
"2025-03": {"CONFIRMADO": 1, "EN_PROCESO": 2},
|
||||
"2025-04": {"CONFIRMADO": 1, "EN_PROCESO": 2},
|
||||
"2025-06": {"CONFIRMADO": 1, "EN_PROCESO": 3},
|
||||
"2025-07": {"EN_PROCESO": 3},
|
||||
"2025-S1": {"CONFIRMADO": 2, "EN_PROCESO": 3},
|
||||
"2025-S2": {"EN_PROCESO": 3},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("period", sorted(RESULTS))
|
||||
def test_m23_counts_the_confirmed_and_in_process_but_not_a_note_without_f84_0(base, manifest, period):
|
||||
"""Pins down M23: the confirmed (a F84.0 note by the period's end) and those in process (no note yet). Child 2's
|
||||
note says F84 without the subcode: from April it's out of M23, though still in the screening. Child 5's F84.0 note
|
||||
of July doesn't confirm it without the ADOS-2: it stays in process. Fails if F84 counts as a confirmation, if a
|
||||
note without F84.0 counts as in process, or if a note counts before the psychology step."""
|
||||
assert composition(base, manifest, "M23_pacientes_evaluados", period) == RESULTS[period]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("period", "numerator", "denominator", "excluded"), [
|
||||
("2025-03", 1, 3, 0), ("2025-04", 1, 3, 1), ("2025-06", 1, 4, 1), ("2025-07", 0, 3, 1), ("2025-S1", 2, 5, 1),
|
||||
])
|
||||
def test_m24_is_the_confirmed_out_of_the_confirmed_and_in_process(base, manifest, period, numerator, denominator,
|
||||
excluded):
|
||||
"""Pins down M24: confirmed over confirmed plus in process, with child 2 (a note without F84.0) as its exclusion
|
||||
from April. In July child 5's F84.0 note, without the ADOS-2, leaves it in process. Fails if the denominator takes
|
||||
the children without TEA, the exclusion stops being counted, or a note confirms without the psychology step."""
|
||||
result = proportion(base, manifest, "M24_confirmacion_diagnostico", period)
|
||||
assert (result.numerator, result.denominator, result.excluded) == (numerator, denominator, excluded)
|
||||
|
||||
|
||||
def test_m24_is_stratified_by_the_age_group_at_the_first_m_chat(base, manifest):
|
||||
"""Pins down: the age group is the child's at its first M-CHAT, one per child, the page's windows. In March, child
|
||||
1 (19 months) is confirmed, child 2 (26) and child 3 (35) are in process. Fails if the stratum goes back to the age
|
||||
at the period's start or loses a window."""
|
||||
result = proportion(base, manifest, "M24_confirmacion_diagnostico", "2025-03")
|
||||
strata = {v: (c.numerator, c.denominator) for v, c in result.strata["grupo_edad"].items()}
|
||||
assert strata == {"16_23": (1, 1), "24_29": (0, 1), "30_36": (0, 1)}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("period", "with_eeg", "without_eeg", "confirmed"), [
|
||||
("2025-03", 0, 1, 1), ("2025-05", 1, 0, 1), ("2025-06", 1, 0, 1), ("2025-07", 0, 0, 0),
|
||||
("2025-S1", 2, 0, 2), ("2025-S2", 0, 0, 0),
|
||||
])
|
||||
def test_m21_and_m22_split_the_confirmed_by_a_good_eeg_by_the_period_s_end(base, manifest, period, with_eeg,
|
||||
without_eeg, confirmed):
|
||||
"""Pins down M21 and its complement M22: of the confirmed at the period's end, those whose chain reached a good EEG
|
||||
by then. Child 1 is confirmed in March without its EEG (20 May), and with it in May; child 5 has a F84.0 note and
|
||||
a good EEG in July but no ADOS-2, so it isn't confirmed and July has nobody. Fails if the EEG is read beyond the
|
||||
period's end, or the note or the EEG count outside the chain."""
|
||||
m21 = proportion(base, manifest, "M21_diagnosticados_con_eeg", period)
|
||||
m22 = proportion(base, manifest, "M22_diagnosticados_sin_eeg", period)
|
||||
assert (m21.numerator, m21.denominator) == (with_eeg, confirmed)
|
||||
assert (m22.numerator, m22.denominator) == (without_eeg, confirmed)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("measure_id", "period", "initial", "n", "median"), [
|
||||
("M26_dias_mchat_ados2", "2025-01", 2, 0, None),
|
||||
("M26_dias_mchat_ados2", "2025-02", 3, 2, 20.0),
|
||||
("M26_dias_mchat_ados2", "2025-03", 3, 3, 26.0),
|
||||
("M26_dias_mchat_ados2", "2025-S1", 6, 4, 20.5),
|
||||
("M27_dias_ados2_diagnostico", "2025-S1", 6, 3, 40.0),
|
||||
("M25_dias_mchat_diagnostico", "2025-S1", 6, 2, 59.5),
|
||||
("M25_dias_mchat_diagnostico", "2025-S2", 4, 0, None),
|
||||
])
|
||||
def test_the_day_counts_take_the_period_s_children_whose_interval_ended_by_its_end(base, manifest, measure_id, period,
|
||||
initial, n, median):
|
||||
"""Pins down M26, M27 and M25: every child the period counts is in the initial population; those whose interval
|
||||
ended by the period's end have days (repeated in each period that counts them), the rest count as without event.
|
||||
In February, child 1 (26 days) and child 3 (14) have their ADOS-2 and child 2 doesn't yet. Child 5's F84.0 note of
|
||||
1 July gives no days without the ADOS-2. Fails if the value is read beyond the period's end or the
|
||||
population goes back to the facts in the period."""
|
||||
result = duration(base, manifest, measure_id, period)
|
||||
assert (result.initial, result.n, result.median) == (initial, n, median)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("period", "expected"), [
|
||||
("2025-04", {"MALO": 1}), ("2025-05", {"BUENO": 1}), ("2025-09", {"BUENO": 1}),
|
||||
("2025-S1", {"BUENO": 2, "MALO": 1}), ("2025-S2", {"BUENO": 2}),
|
||||
])
|
||||
def test_m29_counts_the_period_s_eegs_good_or_bad(base, manifest, period, expected):
|
||||
"""Pins down M29: the EEGs of the cohort's children dated in the period, by exam, good or bad. Child 1's bad EEG of
|
||||
April and its second good one of September count; so does child 5's, though its chain never reaches it. Fails if
|
||||
M29 stops counting exams, or a bad EEG stops showing."""
|
||||
assert composition(base, manifest, "M29_calidad_eeg", period) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("period", "total", "ritmo_posterior"), [
|
||||
("2025-05", (1, 1), (1, 1)), ("2025-06", (0, 1), (0, 1)), ("2025-S1", (1, 2), (1, 2)), ("2025-S2", (0, 1), (0, 1)),
|
||||
])
|
||||
def test_m30_reads_the_alterations_of_each_child_s_first_good_eeg(base, manifest, period, total, ritmo_posterior):
|
||||
"""Pins down M30: of the children whose first good EEG falls in the period, those with an alteration in it, in
|
||||
total and in one group per alteration. Child 1's EEG of 20 May has a slow posterior rhythm (3.2 Hz at 23 months,
|
||||
against 4.5 to 7.0); its second good EEG of September doesn't count. Fails if a later EEG counts, or the groups
|
||||
stop being answered one by one."""
|
||||
result = proportion(base, manifest, "M30_resultado_eeg", period)
|
||||
assert (result.numerator, result.denominator) == total
|
||||
assert (result.groups["ritmo_posterior"].numerator, result.groups["ritmo_posterior"].denominator) == ritmo_posterior
|
||||
assert result.groups["husos_sueno_n2"].numerator == 0
|
||||
|
||||
|
||||
def test_m30_read_back_from_the_history_keeps_its_groups(base, manifest):
|
||||
"""Pins down: asking again reads the stored answer, groups included. Fails if a stored answer loses its groups or
|
||||
counts every group's units in the total."""
|
||||
first = proportion(base, manifest, "M30_resultado_eeg", "2025-S1")
|
||||
again = proportion(base, manifest, "M30_resultado_eeg", "2025-S1")
|
||||
assert again.stored_before and (again.numerator, again.denominator) == (first.numerator, first.denominator)
|
||||
assert again.groups == first.groups
|
||||
|
||||
|
||||
def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest):
|
||||
"""Pins down: a step known after the knowledge cut-off doesn't move the child. Child 1's good EEG and its metrics
|
||||
arrive in a second load; asked as of the first load, May still counts child 1 at neuropediatrics and it hasn't
|
||||
left in June. Fails if the status rows stop applying the knowledge cut-off to the steps or to the exit."""
|
||||
def without_the_good_eeg(session):
|
||||
fixture.insertar(session)
|
||||
session.flush()
|
||||
for model, key in ((EegMetrica, "met_eeg_id"), (Eeg, "eeg_id")):
|
||||
for row in session.exec(select(model).where(getattr(model, key) == "eeg-1b")):
|
||||
session.delete(row)
|
||||
|
||||
base = base_de("tea", tmp_path, without_the_good_eeg)
|
||||
try:
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
with base.motor.begin() as connection:
|
||||
(first_load,) = connection.execute(text("select max(fin) from carga")).one()
|
||||
known = datetime.fromisoformat(str(first_load)).replace(tzinfo=timezone.utc)
|
||||
with base.staging() as session:
|
||||
session.add(Eeg(eeg_id="eeg-1b", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_con_sueno=1,
|
||||
eeg_canales=19, eeg_duracion_min=25.0, eeg_canales_amplitud=0,
|
||||
eeg_canales_alta_frecuencia=1, eeg_canales_correlacion=0, eeg_canales_sin_senal=0,
|
||||
eeg_ruido_linea_db=3.5))
|
||||
session.commit()
|
||||
base.run("load", allow_undecided=True)
|
||||
later = replace(base, ctx=replace(base.ctx, allow_undecided=True))
|
||||
assert composition(later, manifest, "M28_casos_por_estado", "2025-05", knowledge_cutoff=known) == {
|
||||
"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2}
|
||||
assert composition(later, manifest, "M28_casos_por_estado", "2025-06", knowledge_cutoff=known)[
|
||||
"NEUROPEDIATRIA"] == 2
|
||||
assert composition(later, manifest, "M28_casos_por_estado", "2025-05")["EEG"] == 1
|
||||
finally:
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def test_a_knowledge_cut_off_keeps_what_was_known_when_an_earlier_fact_arrives_later(tmp_path, manifest):
|
||||
"""Pins down: an answer as of a load doesn't change when a later load brings an earlier-dated fact. A second load
|
||||
adds an ADOS-2 of 20 Feb for child 3 (its known one is of 28 Feb) and an M-CHAT of 1 Apr for child 7 (its known
|
||||
one is of 1 May). Asked as of the first load, March still counts child 3 at psychology and May still counts
|
||||
child 7; asked as of now, child 7 is in the screening from April. Fails if a child's first fact is chosen among
|
||||
every load's facts and then dropped for being known after the cut-off."""
|
||||
base = base_de("tea", tmp_path)
|
||||
try:
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
with base.motor.begin() as connection:
|
||||
(first_load,) = connection.execute(text("select max(fin) from carga")).one()
|
||||
known = datetime.fromisoformat(str(first_load)).replace(tzinfo=timezone.utc)
|
||||
with base.staging() as session:
|
||||
session.add(Ados2(ado_id="ado-3-earlier", ado_pac_id=3, ado_fecha=date(2025, 2, 20), ado_modulo="MODULO_2",
|
||||
ado_css=2))
|
||||
session.add(Mchat(mch_id="mch-7-earlier", mch_pac_id=7, mch_fecha=date(2025, 4, 1), mch_puntaje=7))
|
||||
session.commit()
|
||||
base.run("load", allow_undecided=True)
|
||||
later = replace(base, ctx=replace(base.ctx, allow_undecided=True))
|
||||
for period in ("2025-03", "2025-05"):
|
||||
assert composition(later, manifest, "M28_casos_por_estado", period, knowledge_cutoff=known) == STAGES[period]
|
||||
assert composition(later, manifest, "M28_casos_por_estado", "2025-04") == {
|
||||
"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2}
|
||||
finally:
|
||||
base.motor.dispose()
|
||||
+15
-12
@@ -10,7 +10,7 @@ from webapi.blueprints.data import data_bp
|
||||
from webapi.blueprints.governance import governance_bp
|
||||
from webapi.blueprints.imports import imports_bp
|
||||
from webapi.blueprints.reports import reports_bp
|
||||
from webapi.follow_up.routes import follow_up_blueprint, in_dev
|
||||
from webapi.follow_up.routes import follow_up_blueprint
|
||||
|
||||
|
||||
class IsoJSONProvider(DefaultJSONProvider):
|
||||
@@ -78,20 +78,23 @@ def create_app() -> Flask:
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.fhir import fhir_blueprint
|
||||
from webapi.kpis import kpis_blueprint
|
||||
|
||||
for domain in ("cacu", "cama"):
|
||||
app.register_blueprint(kpis_blueprint(domain, import_module(f"persistance.{domain}"),
|
||||
Path(os.environ["DBT_MANIFEST"])), url_prefix=f"/{domain}")
|
||||
# Patient-level follow-up list and individual risk: only in DEV, with simulated data.
|
||||
if in_dev():
|
||||
from persistance.db import get_cacu_session
|
||||
for domain in ("cacu", "cama", "tea"):
|
||||
repositories, manifest = import_module(f"persistance.{domain}"), Path(os.environ["DBT_MANIFEST"])
|
||||
app.register_blueprint(kpis_blueprint(domain, repositories, manifest), url_prefix=f"/{domain}")
|
||||
# The same measures in FHIR R4, with TEA's patient summary (simulated data, marked in every response).
|
||||
app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=True),
|
||||
url_prefix=f"/{domain}/fhir")
|
||||
# Patient-level follow-up list and individual risk, marked `simulado` in every response. Who may see them is
|
||||
# an access rule still to be defined, not an environment variable.
|
||||
from persistance import cacu as cacu_repositories
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
|
||||
from persistance import cacu as cacu_repositories
|
||||
from webapi.patient_risk import patient_risk_blueprint
|
||||
|
||||
from webapi.patient_risk import patient_risk_blueprint
|
||||
|
||||
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
|
||||
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
|
||||
return app
|
||||
|
||||
+106
-12
@@ -1,20 +1,32 @@
|
||||
"""Model governance (ML, MLD, EL and VAR requirements): model versions and
|
||||
their promotion, and the OCR extraction jobs with their manual review queue.
|
||||
their promotion, notebooks run on a cohort build, and the OCR extraction
|
||||
jobs with their manual review queue.
|
||||
|
||||
Versions and artifacts live in MLflow (`models.io.registry`); training runs
|
||||
elsewhere and registers its result through `POST /model-versions`, naming
|
||||
the indicator kit cohort build it was trained on (`cohorte_armado_id`).
|
||||
Notebooks (`models.pipelines.experiment`) run in the background on the build's
|
||||
file alone and are kept as MLflow runs.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from core.governance.enums import EstatusExtraccion
|
||||
from core.governance.models import ExtractionRun
|
||||
from core.ocr import OcrEstatus
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from models.io.lineage import DOMAINS
|
||||
from models.io.registry import REPORT_TAGS, PromotionBlocked, registry
|
||||
from models.io.storage import build_file, cohorts_root, exported_builds
|
||||
from models.ocr import OCR_JOBS, OcrJob, run_pending_extractions
|
||||
from models.pipelines import experiment
|
||||
from persistance.governance import extraction_run_repository
|
||||
from persistance.repository import Repository
|
||||
from persistance.settings import settings
|
||||
|
||||
governance_bp = Blueprint("governance", __name__)
|
||||
|
||||
@@ -108,19 +120,101 @@ def retire_model_version(domain: str, scenario: str, version: str):
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/artifacts")
|
||||
def upload_artifact(domain: str, scenario: str, version: str):
|
||||
"""Multipart `file` and `kind` (ArtifactKind); logged to the version's MLflow run."""
|
||||
from core.governance.enums import ArtifactKind
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>/artifacts/<path:path>")
|
||||
def download_artifact(domain: str, scenario: str, version: str, path: str):
|
||||
"""ML-01b: one file the version's training run stored; a folder (the saved model) as a zip."""
|
||||
name, data = registry.artifact(domain, scenario, version, path)
|
||||
return _download(name, data)
|
||||
|
||||
|
||||
# -- notebooks -------------------------------------------------------------------------
|
||||
|
||||
|
||||
def submit(job, *args):
|
||||
"""Runs a notebook in the background, one at a time per worker by default (`WEBAPI_NOTEBOOK_WORKERS`)."""
|
||||
return _notebooks.submit(job, *args)
|
||||
|
||||
|
||||
_notebooks = ThreadPoolExecutor(max_workers=int(os.environ.get("WEBAPI_NOTEBOOK_WORKERS", "1")), thread_name_prefix="notebook")
|
||||
|
||||
|
||||
def _cohorts_root(domain: str) -> Path:
|
||||
if domain not in DOMAINS:
|
||||
raise ValueError(f"dominio desconocido: {domain!r}")
|
||||
return cohorts_root(getattr(settings, f"{domain}_database_url"))
|
||||
|
||||
|
||||
@governance_bp.get("/cohort-files")
|
||||
def list_cohort_files():
|
||||
"""`?domain=`: the domain's cohort builds that have their file, the data a notebook can run on."""
|
||||
domain = request.args.get("domain", "")
|
||||
return jsonify({"builds": exported_builds(_cohorts_root(domain), domain)})
|
||||
|
||||
|
||||
@governance_bp.get("/experiments")
|
||||
def list_experiments():
|
||||
"""Notebook runs, newest first; `?domain=` and `?domain=&scenario=` narrow them."""
|
||||
return jsonify({"experiments": experiment.experiments(request.args.get("domain") or None,
|
||||
request.args.get("scenario") or None)})
|
||||
|
||||
|
||||
@governance_bp.post("/experiments")
|
||||
def run_experiment():
|
||||
"""Multipart `file` (a .ipynb), `domain`, `scenario`, `url`, `source` (kit|dbt), `build` and optionally `version`:
|
||||
runs the notebook on that build's file in the background and answers 202 with the run, still `en_curso`."""
|
||||
upload = request.files.get("file")
|
||||
if upload is None:
|
||||
return jsonify({"error": "falta file"}), 400
|
||||
kinds = [k.value for k in ArtifactKind]
|
||||
if request.form.get("kind") not in kinds:
|
||||
return jsonify({"error": f"kind debe ser uno de {kinds}"}), 400
|
||||
registry.add_artifact(domain, scenario, version, kind=ArtifactKind(request.form["kind"]), filename=upload.filename or "artefacto", data=upload.read())
|
||||
return jsonify(registry.describe(domain, scenario, version)), 201
|
||||
form = request.form
|
||||
missing = [k for k in ("domain", "scenario", "url", "source", "build") if not form.get(k)]
|
||||
if upload is None or missing:
|
||||
return jsonify({"error": f"faltan campos: {(['file'] if upload is None else []) + missing}"}), 400
|
||||
domain, scenario, version = form["domain"], form["scenario"], form.get("version") or None
|
||||
url = form["url"]
|
||||
if url.split("/", 1)[0] != domain:
|
||||
return jsonify({"error": f"la cohorte {url!r} no es del dominio {domain!r}"}), 400
|
||||
if not form["build"].isdigit():
|
||||
return jsonify({"error": "build debe ser un número"}), 400
|
||||
path = build_file(_cohorts_root(domain), url, form["source"], int(form["build"]))
|
||||
try:
|
||||
notebook = experiment.check_notebook(json.loads(upload.read()))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
return jsonify({"error": "el archivo no es un notebook de Jupyter (.ipynb)"}), 400
|
||||
if version:
|
||||
registry.get(domain, scenario, version)
|
||||
name = experiment.notebook_name(upload.filename or "notebook")
|
||||
run_id = experiment.start(notebook, name, path, domain, scenario, version)
|
||||
submit(experiment.execute, run_id, notebook, name, path, domain, scenario, version)
|
||||
return jsonify(experiment.describe(run_id)), 202
|
||||
|
||||
|
||||
@governance_bp.get("/experiments/<run_id>")
|
||||
def get_experiment(run_id: str):
|
||||
return jsonify(experiment.describe(run_id))
|
||||
|
||||
|
||||
@governance_bp.get("/experiments/<run_id>/page")
|
||||
def experiment_page(run_id: str):
|
||||
"""The notebook's rendered page. It's served sandboxed, as an origin of its own, since its scripts are the
|
||||
notebook's."""
|
||||
page = experiment.page(run_id)
|
||||
if page is None:
|
||||
return jsonify({"error": "el notebook todavía no tiene página"}), 404
|
||||
response = Response(page, mimetype="text/html")
|
||||
response.headers["Content-Security-Policy"] = "sandbox allow-scripts allow-popups"
|
||||
response.headers["X-Content-Type-Options"] = "nosniff"
|
||||
return response
|
||||
|
||||
|
||||
@governance_bp.get("/experiments/<run_id>/artifacts/<path:path>")
|
||||
def download_experiment_artifact(run_id: str, path: str):
|
||||
name, data = experiment.artifact(run_id, path)
|
||||
return _download(name, data)
|
||||
|
||||
|
||||
def _download(name: str, data: bytes):
|
||||
response = Response(data, mimetype="application/octet-stream")
|
||||
response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{quote(name)}"
|
||||
response.headers["X-Content-Type-Options"] = "nosniff"
|
||||
return response
|
||||
|
||||
|
||||
# -- OCR ---------------------------------------------------------------------------------
|
||||
|
||||
@@ -4,6 +4,7 @@ import json
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from extraction import BBox, ExtractionError
|
||||
from extraction.readers import reader_for
|
||||
@@ -11,13 +12,19 @@ from webapi.imports import audit as import_audit
|
||||
from webapi.imports.connectors import ConnectorError, build_connector, catalog, connector_class, kind_for_filename
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
from webapi.imports.connectors.pdf import PdfConnector
|
||||
from webapi.orchestration.reference.catalogs import CatalogoInvalido
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
from webapi.imports.services.catalog_commit_service import commit_discovered_fields
|
||||
from webapi.imports.mapping.derived import CASES, DERIVATIONS
|
||||
from webapi.imports.services.import_service import (
|
||||
DatabaseRefused,
|
||||
ImportRequestError,
|
||||
ImportSource,
|
||||
commit_sources,
|
||||
document_columns_preview,
|
||||
mapped_sample,
|
||||
serialize_errors,
|
||||
validate_source,
|
||||
)
|
||||
@@ -27,6 +34,7 @@ from webapi.imports.services.introspection_service import (
|
||||
document_report,
|
||||
extract_pdf_regions,
|
||||
preview_with_suggestions,
|
||||
suggest_mapping,
|
||||
)
|
||||
|
||||
imports_bp = Blueprint("imports", __name__)
|
||||
@@ -250,12 +258,17 @@ def pdf_regions_extract():
|
||||
def document_extract():
|
||||
"""Reads the documents, splits them into patient records and extracts
|
||||
the target's fields: `{files: [{name, file_base64}], target,
|
||||
segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?}`.
|
||||
segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?,
|
||||
include_pattern?, exclude_pattern?}`. `files` may be `sql` instead (a
|
||||
connection plus `table`/`query` and `DocumentColumns`' options), or the
|
||||
whole body may be `{source}`, an import source with `documents`.
|
||||
Each record comes back with per-field confidence and evidence, conflicts
|
||||
between sources, and the images found on its pages."""
|
||||
body = _json_body()
|
||||
if body.get("source"):
|
||||
return jsonify(document_report(body))
|
||||
_require(body, "target")
|
||||
if not body.get("files"):
|
||||
if not body.get("files") and not body.get("sql"):
|
||||
raise BadRequest("faltan los archivos")
|
||||
return jsonify(document_report(body))
|
||||
|
||||
@@ -279,6 +292,32 @@ def document_page_image():
|
||||
# -- validate and load -------------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.get("/derivations")
|
||||
def derivations():
|
||||
"""The operations a source's `derived` fields may use, with their
|
||||
parameters, so a client can build the form for each."""
|
||||
return jsonify({"derivations": [cls.describe() for cls in DERIVATIONS.values()], "cases": list(CASES)})
|
||||
|
||||
|
||||
@imports_bp.post("/mapped-preview")
|
||||
def mapped_preview():
|
||||
"""`{source, limit?}`: the source's first rows as they would be
|
||||
written, with its mapping, derived fields and defaults applied."""
|
||||
body = _json_body()
|
||||
return jsonify({"rows": mapped_sample(_require(body, "source"), limit=min(int(body.get("limit", 20)), 200))})
|
||||
|
||||
|
||||
@imports_bp.post("/sources/document/columns")
|
||||
def document_columns_of_source():
|
||||
"""`{source, target?}` for a source with `documents`: its own columns
|
||||
plus every field and caption its documents print, as a preview the
|
||||
mapping screen offers like any table's, with suggestions."""
|
||||
body = _json_body()
|
||||
preview = document_columns_preview(_require(body, "source"), limit=min(int(body.get("limit", 20)), 200))
|
||||
target = body.get("target") or body["source"].get("target")
|
||||
return jsonify({**preview, "suggested_mapping": suggest_mapping([c["name"] for c in preview["columns"]], target)})
|
||||
|
||||
|
||||
@imports_bp.post("/validate")
|
||||
def validate():
|
||||
source = _require(_json_body(), "source")
|
||||
@@ -302,6 +341,49 @@ def validate():
|
||||
)
|
||||
|
||||
|
||||
def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
|
||||
"""For every source that asks for it (`catalog_fallback: true`) and
|
||||
reads documents, writes the captions no known field claimed but the
|
||||
project's catalog does know straight into the silver layer
|
||||
(`catalog_commit_service`). Best-effort: the structured fields already
|
||||
landed through `commit_sources`, so a failure here is reported, not
|
||||
raised."""
|
||||
reports = []
|
||||
for raw in raw_sources:
|
||||
if not isinstance(raw, dict) or raw.get("catalog_fallback") is not True:
|
||||
continue
|
||||
if raw.get("source_type") != "document" and not raw.get("documents"):
|
||||
continue
|
||||
target = raw.get("target") or ""
|
||||
domain = target.split(".", 1)[0]
|
||||
if not domain:
|
||||
continue
|
||||
payload = {**(raw.get("payload") or {}), "target": target}
|
||||
try:
|
||||
if raw.get("documents"):
|
||||
connector, _, _ = ImportSource.parse(raw).document_connector()
|
||||
if connector is None:
|
||||
continue
|
||||
else:
|
||||
connector = build_connector("document", payload)
|
||||
result = commit_discovered_fields(connector.records, proyecto=domain, estudio_id=payload.get("estudio_id"))
|
||||
except (ConnectorError, ExtractionError, CatalogoInvalido, SQLAlchemyError, ImportRequestError) as exc:
|
||||
log.warning("catalog_fallback: %s no se pudo procesar: %s", raw.get("label") or target, exc)
|
||||
continue
|
||||
reports.append(
|
||||
{
|
||||
"label": raw.get("label"),
|
||||
"domain": result.proyecto,
|
||||
"records_written": result.records_written,
|
||||
"records_without_patient": result.records_without_patient,
|
||||
"fields_matched": result.fields_matched,
|
||||
"fields_minted": result.fields_minted,
|
||||
"fields_unmatched": result.fields_unmatched,
|
||||
}
|
||||
)
|
||||
return reports
|
||||
|
||||
|
||||
@imports_bp.post("/commit")
|
||||
def commit():
|
||||
"""`{sources: [...], on_conflict: "reject"|"upsert", merge_duplicates: bool}`.
|
||||
@@ -333,6 +415,7 @@ def commit():
|
||||
"ok": all(r.rejected == 0 for r in results),
|
||||
"audit_id": audit.id,
|
||||
"indicadores_en_recalculo": recalculating,
|
||||
"catalog_fallback": _commit_catalog_fallback(body.get("sources") or []),
|
||||
"results": [
|
||||
{
|
||||
"target": r.target,
|
||||
|
||||
@@ -29,6 +29,7 @@ from webapi.metrics import (
|
||||
MeasureQueries,
|
||||
Population,
|
||||
Question,
|
||||
StatusAtEnd,
|
||||
Stratum,
|
||||
_population,
|
||||
_semantic_model_of,
|
||||
@@ -80,6 +81,8 @@ class CompositionDefinition:
|
||||
basis: str
|
||||
rules: dict[str, str]
|
||||
strata: tuple[Stratum, ...]
|
||||
population: StatusAtEnd | None = None
|
||||
meta: dict = dataclasses.field(default_factory=dict, compare=False, hash=False)
|
||||
|
||||
@property
|
||||
def measure_id(self) -> str:
|
||||
@@ -121,6 +124,7 @@ def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]:
|
||||
tuple((b["valor"], b.get("menor_que")) for b in rule.get("bandas", ()))),
|
||||
group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})),
|
||||
strata=tuple(Stratum.of(name, s) for name, s in meta.get("estratos", {}).items()),
|
||||
population=StatusAtEnd.of(meta.get("poblacion")), meta=meta,
|
||||
)
|
||||
return definitions
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"""dbt's manifest for the deployment's engine.
|
||||
|
||||
The measures are served from `manifest.json` (`DBT_MANIFEST`), whose compiled SQL is the dialect of the dbt target it
|
||||
was compiled with. The image ships SQLite's; on another engine the entrypoint runs this module, which compiles the
|
||||
project in `TRANSFORMATION_DIR` against the configured databases (the adapters for MySQL, PostgreSQL and SQL Server
|
||||
open a connection to compile) and prints the path of the manifest to serve. On SQLite it prints nothing: the image's
|
||||
manifest is the right one.
|
||||
|
||||
The three domains must share one engine: one manifest covers every domain's models.
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy.engine import make_url
|
||||
|
||||
DOMAINS = ("cacu", "cama", "tea")
|
||||
TARGETS = {"sqlite": "sqlite", "mssql": "sqlserver", "postgresql": "postgres", "mysql": "mysql", "mariadb": "mysql"}
|
||||
|
||||
|
||||
def target_of(urls: dict[str, str]) -> str:
|
||||
"""The dbt target the domains' database URLs share. `ValueError` for an engine dbt has no target for, or when
|
||||
the domains don't share one engine."""
|
||||
targets = {domain: TARGETS.get(make_url(url).get_backend_name()) for domain, url in urls.items()}
|
||||
if unknown := [domain for domain, target in targets.items() if target is None]:
|
||||
raise ValueError(f"no dbt target for the engine of {', '.join(unknown)}")
|
||||
if len(set(targets.values())) != 1:
|
||||
raise ValueError("the domains' databases must be on one engine: one manifest serves the three domains")
|
||||
return next(iter(targets.values()))
|
||||
|
||||
|
||||
def environment(urls: dict[str, str], target: str) -> dict[str, str]:
|
||||
"""What `Transformation/profiles.yml` reads: the server and credentials from CaCu's URL (one server for the three
|
||||
domains), each domain's database name, and on SQLite each domain's file."""
|
||||
env: dict[str, str] = {}
|
||||
for domain, url in urls.items():
|
||||
parsed = make_url(url)
|
||||
if target == "sqlite":
|
||||
env[f"{domain.upper()}_DB_PATH"] = parsed.database or f"{domain}.db"
|
||||
else:
|
||||
env[f"{domain.upper()}_DBT_DATABASE"] = parsed.database or domain
|
||||
first = make_url(urls["cacu"])
|
||||
if target != "sqlite":
|
||||
env["DBT_HOST"] = first.host or "localhost"
|
||||
if first.port:
|
||||
env["DBT_PORT"] = str(first.port)
|
||||
env["DBT_USER"] = first.username or ""
|
||||
env["DBT_PASSWORD"] = first.password or ""
|
||||
return env
|
||||
|
||||
|
||||
def dbt_executable(root: Path, target: str) -> Path:
|
||||
"""dbt-mysql runs on an older dbt-core, so it lives in its own environment next to the main one."""
|
||||
return root / (".venv-mysql" if target == "mysql" else ".venv") / "bin" / "dbt"
|
||||
|
||||
|
||||
def compile_manifest(root: Path, target: str, env: dict[str, str], out_dir: Path) -> Path:
|
||||
"""Compiles every model with placeholders for the question's parameters (`--no-introspect`: the target's
|
||||
tables needn't exist yet) and returns the manifest's path."""
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
command = [str(dbt_executable(root, target)), "compile", "--project-dir", str(root), "--profiles-dir", str(root),
|
||||
"--profile", "cacu", "--target", target, "--no-introspect", "--target-path", str(out_dir)]
|
||||
subprocess.run(command, check=True, env={**os.environ, **env}, stdout=sys.stderr)
|
||||
return out_dir / "manifest.json"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
from persistance.settings import settings
|
||||
|
||||
urls = {domain: getattr(settings, f"{domain}_database_url") for domain in DOMAINS}
|
||||
target = target_of(urls)
|
||||
if target == "sqlite":
|
||||
return 0
|
||||
root = Path(os.environ.get("TRANSFORMATION_DIR") or Path(__file__).resolve().parents[2] / "Transformation")
|
||||
out_dir = Path(os.environ.get("DBT_MANIFEST_DIR", "/data/dbt"))
|
||||
print(compile_manifest(root, target, environment(urls, target), out_dir))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+10
-2
@@ -6,7 +6,8 @@ cut-offs apply to, and the horizon: a unit without a value whose horizon hasn't
|
||||
measured yet, so it's left out of the initial population. Days are differences of `dim_fecha.dia_num`, computed in
|
||||
dbt's event model; the cut-off's day is looked up the same way. Quartiles are ANSI (`inclusive_quartiles`).
|
||||
|
||||
The event cut-off defaults to the day of the last load, as the horizon needs a day to count to.
|
||||
The event cut-off defaults to the day of the last load, as the horizon needs a day to count to. With a population at
|
||||
the period's end (`webapi.metrics.StatusAtEnd`), a unit's interval has a value only if it ended by the period's end.
|
||||
"""
|
||||
|
||||
import dataclasses
|
||||
@@ -28,6 +29,7 @@ from webapi.metrics import (
|
||||
MeasureQueries,
|
||||
Population,
|
||||
Question,
|
||||
StatusAtEnd,
|
||||
_population,
|
||||
_semantic_model_of,
|
||||
key_of,
|
||||
@@ -90,6 +92,8 @@ class DurationDefinition:
|
||||
rules: dict[str, str]
|
||||
improvement_notation: str | None = None
|
||||
strata: tuple = ()
|
||||
population: StatusAtEnd | None = None
|
||||
meta: dict = dataclasses.field(default_factory=dict, compare=False, hash=False)
|
||||
|
||||
@property
|
||||
def measure_id(self) -> str:
|
||||
@@ -127,7 +131,8 @@ def duration_definitions(manifest: Path) -> dict[str, DurationDefinition]:
|
||||
rule["horizonte"].get("regla"), rule["horizonte"]["dia_inicio"],
|
||||
int(rule["horizonte"]["dias"]) if "dias" in rule["horizonte"] else None),
|
||||
group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})),
|
||||
improvement_notation=meta.get("improvement_notation"),
|
||||
improvement_notation=meta.get("improvement_notation"), population=StatusAtEnd.of(meta.get("poblacion")),
|
||||
meta=meta,
|
||||
)
|
||||
return definitions
|
||||
|
||||
@@ -145,6 +150,9 @@ class DurationQueries(MeasureQueries):
|
||||
o, q = self.d.observation, self.q
|
||||
conditions = [self._column(o.value).is_not(None)]
|
||||
conditions += [self._column(n) <= q.event_cutoff.isoformat() for n in o.dated_at]
|
||||
if self.status is not None:
|
||||
# Counted at the period's end: the interval has to have ended by then.
|
||||
conditions += [self._column(n) < self.events.c.periodo_fin for n in o.dated_at]
|
||||
if q.knowledge_cutoff is not None:
|
||||
conditions += [self._column(n) <= q.knowledge_cutoff for n in o.known_at]
|
||||
return and_(*conditions)
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
"""A domain's FHIR R4 endpoint, `/<domain>/fhir/`: its measures and, for TEA, its patients' screening.
|
||||
|
||||
GET metadata CapabilityStatement
|
||||
GET Measure, Measure/<id> the measures (dbt's definitions)
|
||||
GET Measure/<id>/$evaluate-measure one period: periodStart and periodEnd, or `periodo`
|
||||
GET MeasureReport?measure=&periodo=|period= several periods (one report each), with `tipo-periodo`
|
||||
POST Measure/$recalcular queues the domain's recomputation
|
||||
GET CodeSystem, CodeSystem/<id>, ValueSet/<id> the project's code systems
|
||||
GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only)
|
||||
GET Patient/<pseudonym>/$resumen-tea TEA's patient summary (DEV only)
|
||||
|
||||
Every question of a measure takes `corte_evento` and `corte_conocimiento` as in `webapi.kpis`. Errors are
|
||||
`OperationOutcome`s. Patient data are served only in DEV, on simulated data, each resource tagged `simulado`.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from flask import Blueprint, request
|
||||
from werkzeug.exceptions import HTTPException
|
||||
|
||||
from webapi.fhir.common import FHIR_VERSION, canonical, entry, fhir, outcome, page, searchset, simulated_data
|
||||
from webapi.fhir.measures import fhir_id, labels, measure_report, measure_resource, measure_url
|
||||
from webapi.fhir.terminology import code_systems, metric_value_set
|
||||
from webapi.kpis import ANSWERS, _date, _datetime, _last_load, definitions_of, scoring_of
|
||||
from webapi.metrics import Question, UndecidedRule
|
||||
|
||||
TEA_SEARCH = ("status", "date", "etapa", "fecha-etapa", "grupo-edad", "mchat", "css", "resultado-eeg", "alteracion")
|
||||
|
||||
|
||||
def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients: bool = False,
|
||||
now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint:
|
||||
"""The blueprint of a domain, to register with `url_prefix="/<domain>/fhir"`. `repositories` is the domain's
|
||||
`persistance.<domain>` module; `with_patients` adds TEA's patient routes (only in DEV)."""
|
||||
blueprint = Blueprint(f"{project}_fhir", __name__)
|
||||
titles = labels(manifest)
|
||||
patients = with_patients and project == "tea"
|
||||
|
||||
def definitions() -> dict:
|
||||
"""The domain's measures by their FHIR id; `definition()` also takes the dbt id."""
|
||||
return {fhir_id(d): d for d in definitions_of(project, manifest).values()}
|
||||
|
||||
def definition_of(measure_id: str):
|
||||
return definitions().get(measure_id.replace("_", "-"))
|
||||
|
||||
def measure(definition) -> dict:
|
||||
title, description = titles.get(definition.metric, (definition.measure_id, ""))
|
||||
return measure_resource(definition, title, description)
|
||||
|
||||
@blueprint.app_errorhandler(HTTPException)
|
||||
def http_error(error: HTTPException):
|
||||
"""Under `/<domain>/fhir/`, an error is an `OperationOutcome`, also for a route that doesn't exist there;
|
||||
elsewhere, Flask's own answer."""
|
||||
if "/fhir/" not in request.path and not request.path.endswith("/fhir"):
|
||||
return error
|
||||
code = {404: "not-found", 405: "not-supported"}.get(error.code, "exception")
|
||||
return outcome(error.code, code, error.description or error.name)
|
||||
|
||||
@blueprint.get("/metadata")
|
||||
def capability_statement():
|
||||
resources = [
|
||||
{"type": "Measure", "interaction": [{"code": "read"}, {"code": "search-type"}],
|
||||
"operation": [{"name": "evaluate-measure", "definition": "http://hl7.org/fhir/OperationDefinition/Measure-evaluate-measure"},
|
||||
{"name": "recalcular", "definition": canonical("OperationDefinition/recalcular")}]},
|
||||
{"type": "MeasureReport", "interaction": [{"code": "search-type"}],
|
||||
"searchParam": [{"name": n, "type": t} for n, t in (("measure", "reference"), ("period", "date"),
|
||||
("periodo", "token"), ("tipo-periodo", "token"))]},
|
||||
{"type": "CodeSystem", "interaction": [{"code": "read"}, {"code": "search-type"}]},
|
||||
]
|
||||
if patients:
|
||||
resources += [
|
||||
{"type": "EpisodeOfCare", "interaction": [{"code": "search-type"}],
|
||||
"searchParam": [{"name": n, "definition": canonical(f"SearchParameter/episode-{n}"),
|
||||
"type": "date" if n in ("date", "fecha-etapa") else
|
||||
"number" if n in ("mchat", "css") else "token"} for n in TEA_SEARCH],
|
||||
"searchInclude": ["*"],
|
||||
"operation": [{"name": "resumen-eeg", "definition": canonical("OperationDefinition/resumen-eeg")}]},
|
||||
{"type": "Patient", "operation": [{"name": "resumen-tea",
|
||||
"definition": canonical("OperationDefinition/resumen-tea")}]},
|
||||
{"type": "ValueSet", "interaction": [{"code": "read"}]},
|
||||
]
|
||||
return fhir({"resourceType": "CapabilityStatement", "status": "active", "date": now().date().isoformat(),
|
||||
"kind": "instance", "fhirVersion": FHIR_VERSION, "format": ["application/fhir+json"],
|
||||
"implementation": {"description": f"ISSSTELEON, {project.upper()}", "url": request.url_root},
|
||||
"rest": [{"mode": "server", "resource": resources}]})
|
||||
|
||||
@blueprint.get("/Measure")
|
||||
def measures():
|
||||
found = [measure(d) for _, d in sorted(definitions().items())]
|
||||
if url := request.args.get("url"):
|
||||
found = [m for m in found if m["url"] == url]
|
||||
count, offset = page()
|
||||
return fhir(searchset([entry(m) for m in found[offset:offset + count]], len(found), count, offset))
|
||||
|
||||
@blueprint.get("/Measure/<measure_id>")
|
||||
def read_measure(measure_id: str):
|
||||
definition = definition_of(measure_id)
|
||||
if definition is None:
|
||||
return outcome(404, "not-found", f"no hay un indicador {measure_id!r}")
|
||||
return fhir(measure(definition))
|
||||
|
||||
def ask(definition, period, event_cutoff, knowledge_cutoff):
|
||||
question = Question(definition.url, period.periodo_id, event_cutoff, knowledge_cutoff)
|
||||
answer_of, _ = ANSWERS[scoring_of(definition)]
|
||||
result = answer_of(project, definition, question, parameters=repositories.def_parametro_repository,
|
||||
periods=repositories.dim_periodo_repository, history=repositories.history_repository,
|
||||
queries=repositories.dbt_query_repository)
|
||||
return measure_report(definition, question, result, period, now())
|
||||
|
||||
def cutoffs():
|
||||
return (_date(request.args.get("corte_evento")),
|
||||
_datetime(request.args.get("corte_conocimiento")) or _last_load(repositories))
|
||||
|
||||
@blueprint.get("/Measure/<measure_id>/$evaluate-measure")
|
||||
def evaluate_measure(measure_id: str):
|
||||
definition = definition_of(measure_id)
|
||||
if definition is None:
|
||||
return outcome(404, "not-found", f"no hay un indicador {measure_id!r}")
|
||||
try:
|
||||
event_cutoff, knowledge_cutoff = cutoffs()
|
||||
period = _period_asked(repositories)
|
||||
except ValueError as error:
|
||||
return outcome(400, "invalid", str(error))
|
||||
except LookupError as error:
|
||||
return outcome(404, "not-found", str(error))
|
||||
try:
|
||||
return fhir(ask(definition, period, event_cutoff, knowledge_cutoff))
|
||||
except UndecidedRule as error:
|
||||
return outcome(409, "business-rule", str(error))
|
||||
|
||||
@blueprint.get("/MeasureReport")
|
||||
def measure_reports():
|
||||
asked = request.args.get("measure", "")
|
||||
by_url = {measure_url(d): d for d in definitions().values()}
|
||||
definition = by_url.get(asked.split("|")[0]) or definition_of(asked)
|
||||
if definition is None:
|
||||
return outcome(400, "required", "falta `measure` (el canónico o el id de un indicador)")
|
||||
try:
|
||||
event_cutoff, knowledge_cutoff = cutoffs()
|
||||
periods = _periods_searched(repositories)
|
||||
count, offset = page()
|
||||
except ValueError as error:
|
||||
return outcome(400, "invalid", str(error))
|
||||
except LookupError as error:
|
||||
return outcome(404, "not-found", str(error))
|
||||
try:
|
||||
reports = [ask(definition, p, event_cutoff, knowledge_cutoff) for p in periods[offset:offset + count]]
|
||||
except UndecidedRule as error:
|
||||
return outcome(409, "business-rule", str(error))
|
||||
return fhir(searchset([entry(r) for r in reports], len(periods), count, offset))
|
||||
|
||||
@blueprint.post("/Measure/$recalcular")
|
||||
def recompute():
|
||||
from webapi.recomputation import RecomputationQueue
|
||||
|
||||
RecomputationQueue().request_run(project)
|
||||
return outcome(202, "informational", f"se pidió recalcular los indicadores de {project}", severity="information")
|
||||
|
||||
@blueprint.get("/CodeSystem")
|
||||
def code_system_search():
|
||||
systems = list(code_systems(project).values())
|
||||
return fhir(searchset([entry(s) for s in systems], len(systems), len(systems) or 1, 0))
|
||||
|
||||
@blueprint.get("/CodeSystem/<system_id>")
|
||||
def read_code_system(system_id: str):
|
||||
system = code_systems(project).get(system_id)
|
||||
return fhir(system) if system else outcome(404, "not-found", f"no hay un sistema de códigos {system_id!r}")
|
||||
|
||||
if patients:
|
||||
_patient_routes(blueprint, repositories, now)
|
||||
return blueprint
|
||||
|
||||
|
||||
def _period_asked(repositories):
|
||||
"""The `dim_periodo` row the question names: `periodo`, or `periodStart` and `periodEnd` (inclusive)."""
|
||||
if periodo := request.args.get("periodo"):
|
||||
period = repositories.dim_periodo_repository.get(periodo)
|
||||
if period is None:
|
||||
raise LookupError(f"no hay un periodo {periodo!r}")
|
||||
return period
|
||||
start, end = request.args.get("periodStart"), request.args.get("periodEnd")
|
||||
if not (start and end):
|
||||
raise ValueError("falta el periodo: `periodStart` y `periodEnd`, o `periodo`")
|
||||
start, end = date.fromisoformat(start), date.fromisoformat(end)
|
||||
for period in repositories.dim_periodo_repository.list(limit=10000, inicio=start):
|
||||
if period.fin - timedelta(days=1) == end:
|
||||
return period
|
||||
raise LookupError(f"no hay un periodo de {start} a {end}")
|
||||
|
||||
|
||||
def _periods_searched(repositories) -> list:
|
||||
"""The periods of a `MeasureReport` search: `periodo` (comma-separated ids), or the periods of `tipo-periodo`
|
||||
within `period=ge…` and `period=le…`."""
|
||||
if ids := [p for p in request.args.get("periodo", "").split(",") if p]:
|
||||
periods = [repositories.dim_periodo_repository.get(i) for i in ids]
|
||||
if missing := [i for i, p in zip(ids, periods) if p is None]:
|
||||
raise LookupError(f"no hay un periodo {missing[0]!r}")
|
||||
return periods
|
||||
kind = request.args.get("tipo-periodo")
|
||||
if not kind:
|
||||
raise ValueError("falta `periodo` o `tipo-periodo` con `period`")
|
||||
low, high = date.min, date.max
|
||||
for value in request.args.getlist("period"):
|
||||
if value.startswith("ge"):
|
||||
low = date.fromisoformat(value[2:])
|
||||
elif value.startswith("le"):
|
||||
high = date.fromisoformat(value[2:])
|
||||
else:
|
||||
raise ValueError(f"`period` admite ge y le: {value!r}")
|
||||
found = repositories.dim_periodo_repository.list(limit=10000, tipo=kind)
|
||||
return sorted((p for p in found if p.inicio >= low and p.fin - timedelta(days=1) <= high), key=lambda p: p.inicio)
|
||||
|
||||
|
||||
def _bound(name: str) -> tuple[float | None, float | None]:
|
||||
"""A number search parameter's bounds: `mchat=ge8&mchat=le20`, or one exact value."""
|
||||
low = high = None
|
||||
for value in request.args.getlist(name):
|
||||
if value.startswith("ge"):
|
||||
low = float(value[2:])
|
||||
elif value.startswith("le"):
|
||||
high = float(value[2:])
|
||||
else:
|
||||
low = high = float(value)
|
||||
return low, high
|
||||
|
||||
|
||||
def _dates(name: str) -> tuple[date | None, date | None]:
|
||||
low = high = None
|
||||
for value in request.args.getlist(name):
|
||||
if value.startswith("ge"):
|
||||
low = date.fromisoformat(value[2:])
|
||||
elif value.startswith("le"):
|
||||
high = date.fromisoformat(value[2:])
|
||||
else:
|
||||
low = high = date.fromisoformat(value)
|
||||
return low, high
|
||||
|
||||
|
||||
def _patient_routes(blueprint: Blueprint, repositories, now) -> None:
|
||||
from webapi.fhir import tea
|
||||
|
||||
queries = repositories.dbt_query_repository
|
||||
|
||||
def matching():
|
||||
"""The episodes the search's parameters select, at its cut-off (`date=le…`, by default today)."""
|
||||
unknown = [k for k in request.args if not k.startswith("_") and k not in TEA_SEARCH]
|
||||
if unknown:
|
||||
raise ValueError(f"parámetro de búsqueda no admitido: {unknown[0]!r}")
|
||||
if request.args.get("alteracion") and not tea.alterations_validated():
|
||||
raise PermissionError("las alteraciones del EEG no se muestran hasta validar sus referencias")
|
||||
since, cutoff = _dates("date")
|
||||
cutoff = cutoff or now().date()
|
||||
stage_from, stage_to = _dates("fecha-etapa")
|
||||
mchat, css = _bound("mchat"), _bound("css")
|
||||
|
||||
def within(value, bounds):
|
||||
low, high = bounds
|
||||
return value is not None and (low is None or value >= low) and (high is None or value <= high)
|
||||
|
||||
found = []
|
||||
for e in tea.episodes(queries, cutoff):
|
||||
stage = e.stage
|
||||
if since is not None and e.finished and stage[1] < since:
|
||||
continue
|
||||
if (status := request.args.get("status")) and status != ("finished" if e.finished else "active"):
|
||||
continue
|
||||
if (etapa := request.args.get("etapa")) and (stage is None or stage[0] not in etapa.split(",")):
|
||||
continue
|
||||
if (stage_from or stage_to) and (stage is None or not within(stage[1].toordinal(), (
|
||||
stage_from and stage_from.toordinal(), stage_to and stage_to.toordinal()))):
|
||||
continue
|
||||
if (group := request.args.get("grupo-edad")) and e.child["grupo_edad"] not in group.split(","):
|
||||
continue
|
||||
if request.args.getlist("mchat") and not within(e.child["mchat"], mchat):
|
||||
continue
|
||||
if request.args.getlist("css") and not within(e.child["css_ados2"], css):
|
||||
continue
|
||||
if result := request.args.get("resultado-eeg"):
|
||||
shown = e.eeg_result if tea.alterations_validated() else (
|
||||
"sin-eeg-valido" if e.eeg_result == "sin-eeg-valido" else "valido")
|
||||
if shown not in result.split(","):
|
||||
continue
|
||||
if (alteration := request.args.get("alteracion")) and alteration not in e.alterations():
|
||||
continue
|
||||
found.append(e)
|
||||
return sorted(found, key=lambda e: e.pseudonym)
|
||||
|
||||
@blueprint.get("/EpisodeOfCare")
|
||||
def episodes_of_care():
|
||||
try:
|
||||
found = matching()
|
||||
count, offset = page()
|
||||
except ValueError as error:
|
||||
return tea_outcome(400, "invalid", error)
|
||||
except PermissionError as error:
|
||||
return tea_outcome(403, "forbidden", error)
|
||||
simulated = simulated_data()
|
||||
shown = found[offset:offset + count]
|
||||
entries = [entry(tea.episode_of_care(e, simulated)) for e in shown]
|
||||
if request.args.get("_include"):
|
||||
entries += [entry(r, "include") for e in shown for r in _included(tea, queries, e, simulated)]
|
||||
return fhir(searchset(entries, len(found), count, offset))
|
||||
|
||||
@blueprint.get("/EpisodeOfCare/$resumen-eeg")
|
||||
def eeg_summary():
|
||||
try:
|
||||
found = matching()
|
||||
except ValueError as error:
|
||||
return tea_outcome(400, "invalid", error)
|
||||
except PermissionError as error:
|
||||
return tea_outcome(403, "forbidden", error)
|
||||
valid = [e for e in found if e.eeg_result != "sin-eeg-valido"]
|
||||
parameters = [{"name": "con_eeg_valido", "valueInteger": len(valid)},
|
||||
{"name": "sin_eeg_valido", "valueInteger": len(found) - len(valid)}]
|
||||
if tea.alterations_validated():
|
||||
by_alteration: dict[str, int] = {}
|
||||
for e in valid:
|
||||
for code in e.alterations():
|
||||
by_alteration[code] = by_alteration.get(code, 0) + 1
|
||||
parameters += [{"name": "normales", "valueInteger": sum(e.eeg_result == "normal" for e in valid)},
|
||||
{"name": "anormales", "valueInteger": sum(e.eeg_result == "anormal" for e in valid)},
|
||||
*({"name": "por_alteracion", "part": [{"name": "alteracion", "valueCode": code},
|
||||
{"name": "pacientes", "valueInteger": n}]}
|
||||
for code, n in sorted(by_alteration.items()))]
|
||||
return fhir({"resourceType": "Parameters", "parameter": parameters})
|
||||
|
||||
@blueprint.get("/Patient/<pseudonym>/$resumen-tea")
|
||||
def patient_summary(pseudonym: str):
|
||||
pac_id = tea.patient_of(queries, pseudonym)
|
||||
if pac_id is None:
|
||||
return outcome(404, "not-found", f"no hay un paciente {pseudonym!r}")
|
||||
return fhir(tea.patient_summary(queries, pac_id, now().date(), simulated_data()))
|
||||
|
||||
@blueprint.get("/ValueSet/tea-alteracion")
|
||||
def alteration_types():
|
||||
return fhir(metric_value_set())
|
||||
|
||||
|
||||
def tea_outcome(status: int, code: str, error: Exception):
|
||||
return outcome(status, code, str(error))
|
||||
|
||||
|
||||
def _included(tea, queries, e, simulated: bool) -> list[dict]:
|
||||
"""What an episode's search includes: its patient, its steps, its M-CHAT, its ADOS-2, its diagnosis and its study
|
||||
EEG."""
|
||||
from sqlalchemy import select
|
||||
|
||||
pac_id = e.child["pac_id"]
|
||||
persons = tea._rows(queries, select(tea.PERSONS).where(tea.PERSONS.c.pac_id == pac_id))
|
||||
ados2 = tea.ados2_observation(tea._rows(queries, select(tea.ADOS2).where(tea.ADOS2.c.pac_id == pac_id)),
|
||||
e.pseudonym, simulated)
|
||||
resources = [tea.patient(pac_id, persons[0]["fecha_nacimiento"] if persons else None, simulated),
|
||||
tea.care_plan(e, simulated)]
|
||||
resources += [r for r in (tea.mchat_observation(e, simulated), ados2, tea.condition(e, simulated)) if r]
|
||||
if (eeg := e.study_eeg()) is not None:
|
||||
resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated)
|
||||
return resources
|
||||
@@ -0,0 +1,93 @@
|
||||
"""What every FHIR R4 answer of the WebApi shares: the media type, errors as `OperationOutcome`, search bundles with
|
||||
their paging links, the simulated-data tag and the project's canonical URLs."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from flask import Response, request
|
||||
|
||||
FHIR_VERSION = "4.0.1"
|
||||
MEDIA_TYPE = "application/fhir+json"
|
||||
BASE = "https://isssteleon.org/fhir"
|
||||
CODE_SYSTEM = f"{BASE}/CodeSystem"
|
||||
VALUE_SET = f"{BASE}/ValueSet"
|
||||
STRUCTURE = f"{BASE}/StructureDefinition"
|
||||
SIMULATED = {"system": f"{CODE_SYSTEM}/etiqueta", "code": "simulado", "display": "Datos simulados"}
|
||||
MAX_COUNT = 200
|
||||
DEFAULT_COUNT = 50
|
||||
|
||||
|
||||
def fhir(resource: dict, status: int = 200) -> Response:
|
||||
"""A resource as the answer, in FHIR's JSON media type."""
|
||||
return Response(json.dumps(resource, ensure_ascii=False), status=status, mimetype=MEDIA_TYPE)
|
||||
|
||||
|
||||
def outcome(status: int, code: str, diagnostics: str, severity: str = "error") -> Response:
|
||||
"""An error as an `OperationOutcome` (`code` from FHIR's issue-type), with the HTTP status it goes with."""
|
||||
return fhir({"resourceType": "OperationOutcome",
|
||||
"issue": [{"severity": severity, "code": code, "diagnostics": diagnostics}]}, status)
|
||||
|
||||
|
||||
def canonical(path: str) -> str:
|
||||
"""The absolute canonical of a project resource: `Measure/<id>`, `CodeSystem/<id>`…"""
|
||||
return f"{BASE}/{path}"
|
||||
|
||||
|
||||
def coding(system: str, code: str, display: str | None = None) -> dict:
|
||||
return {"system": system, "code": code, **({"display": display} if display else {})}
|
||||
|
||||
|
||||
def concept(system: str, code: str, display: str | None = None, text: str | None = None) -> dict:
|
||||
return {"coding": [coding(system, code, display)], **({"text": text} if text else {})}
|
||||
|
||||
|
||||
def tagged(resource: dict, simulated: bool) -> dict:
|
||||
"""The resource with the simulated-data tag in its `meta`, when its data are simulated."""
|
||||
if simulated:
|
||||
resource.setdefault("meta", {}).setdefault("tag", []).append(SIMULATED)
|
||||
return resource
|
||||
|
||||
|
||||
def simulated_data() -> bool:
|
||||
"""Patient data are simulated in the DEV deployment (`DEV_REVISION`), the only one that serves them."""
|
||||
return bool(os.environ.get("DEV_REVISION"))
|
||||
|
||||
|
||||
def page() -> tuple[int, int]:
|
||||
"""`_count` (at most `MAX_COUNT`) and `_offset` of the search. `ValueError` if one isn't a number."""
|
||||
count = int(request.args.get("_count", DEFAULT_COUNT))
|
||||
offset = int(request.args.get("_offset", 0))
|
||||
if count < 0 or offset < 0:
|
||||
raise ValueError("`_count` y `_offset` no pueden ser negativos")
|
||||
return min(count, MAX_COUNT), offset
|
||||
|
||||
|
||||
def searchset(entries: list[dict], total: int, count: int, offset: int) -> dict:
|
||||
"""A `searchset` Bundle with the page's entries, the total and the `self`, `next` and `previous` links."""
|
||||
def link(relation: str, at: int) -> dict:
|
||||
args = [(k, v) for k, v in request.args.items(multi=True) if k not in ("_count", "_offset")]
|
||||
return {"relation": relation, "url": f"{request.base_url}?{urlencode([*args, ('_count', count), ('_offset', at)])}"}
|
||||
|
||||
links = [link("self", offset)]
|
||||
if offset + count < total:
|
||||
links.append(link("next", offset + count))
|
||||
if offset > 0:
|
||||
links.append(link("previous", max(0, offset - count)))
|
||||
return {"resourceType": "Bundle", "type": "searchset", "total": total, "link": links, "entry": entries}
|
||||
|
||||
|
||||
def fhir_base() -> str:
|
||||
"""This request's FHIR endpoint, `…/<domain>/fhir/`: what a `fullUrl` is relative to."""
|
||||
url = request.base_url
|
||||
return url[:url.index("/fhir/") + len("/fhir/")] if "/fhir/" in url else url.rstrip("/") + "/"
|
||||
|
||||
|
||||
def entry(resource: dict, mode: str | None = "match") -> dict:
|
||||
"""A Bundle entry: its `fullUrl` when the resource has an id, and its search mode in a searchset."""
|
||||
item = {"resource": resource}
|
||||
if "id" in resource:
|
||||
item = {"fullUrl": f"{fhir_base()}{resource['resourceType']}/{resource['id']}", **item}
|
||||
if mode:
|
||||
item["search"] = {"mode": mode}
|
||||
return item
|
||||
@@ -0,0 +1,200 @@
|
||||
"""A domain's measures as FHIR R4 `Measure` resources, and their answers as `MeasureReport`s.
|
||||
|
||||
The definitions are dbt's (`webapi.kpis.definitions_of`); the `Measure` carries what the indicator page needs from
|
||||
each metric's `meta` (title, description, scoring, populations, strata, period types, figures and category labels as
|
||||
extensions). A report names its measure by the absolute canonical the `Measure` carries; each group and stratifier
|
||||
has a code; a composition (C2) is a `cohort` whose categories are a stratifier, and with strata, each stratum holds
|
||||
its category as a `component`. A duration reports the units without a value as their own population.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.compositions import CompositionAnswer, CompositionDefinition
|
||||
from webapi.durations import OBSERVATION, DurationAnswer, DurationDefinition
|
||||
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, canonical, concept
|
||||
from webapi.metrics import EVENT_CUTOFF, HISTORY_ENTRY, KNOWLEDGE_CUTOFF, POPULATION_SYSTEM, Answer, Counts
|
||||
|
||||
SCORING_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-scoring"
|
||||
IMPROVEMENT_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-improvement-notation"
|
||||
GROUP_SYSTEM = f"{CODE_SYSTEM}/grupo-medida"
|
||||
STRATIFIER_SYSTEM = f"{CODE_SYSTEM}/estratificador"
|
||||
EXCLUDED = "measure-population-exclusion"
|
||||
FIGURES = f"{STRUCTURE}/figuras"
|
||||
PERIOD_TYPES = f"{STRUCTURE}/tipos-periodo"
|
||||
CATEGORY_LABEL = f"{STRUCTURE}/categoria"
|
||||
CONTRACT = f"{STRUCTURE}/contrato"
|
||||
REQUIRES_VALIDATION = f"{STRUCTURE}/requiere-validacion"
|
||||
POPULATION_LABELS = {
|
||||
"initial-population": "Unidades del periodo", "numerator": "Numerador", "denominator": "Denominador",
|
||||
"denominator-exclusion": "Excluidos del denominador", "measure-observation": "Unidades con valor",
|
||||
EXCLUDED: "Unidades sin valor",
|
||||
}
|
||||
|
||||
|
||||
def scoring(definition) -> str:
|
||||
"""The FHIR scoring: a composition is a `cohort` (its categories are a stratifier)."""
|
||||
if isinstance(definition, CompositionDefinition):
|
||||
return "cohort"
|
||||
return "continuous-variable" if isinstance(definition, DurationDefinition) else "proportion"
|
||||
|
||||
|
||||
def labels(manifest: Path) -> dict[str, tuple[str, str]]:
|
||||
"""Each metric's (title, description) in the manifest: `meta.titulo` when the label had to differ."""
|
||||
metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()
|
||||
return {m["name"]: (m["config"].get("meta", {}).get("titulo") or m["label"], (m.get("description") or "").strip())
|
||||
for m in metrics}
|
||||
|
||||
|
||||
def fhir_id(definition) -> str:
|
||||
"""The measure's id as FHIR allows one (letters, digits, `-` and `.`): `M21_diagnosticados_con_eeg` ->
|
||||
`M21-diagnosticados-con-eeg`."""
|
||||
return definition.measure_id.replace("_", "-")
|
||||
|
||||
|
||||
def measure_url(definition) -> str:
|
||||
return canonical(f"Measure/{fhir_id(definition)}")
|
||||
|
||||
|
||||
def _populations(definition) -> list[dict]:
|
||||
"""Each population with the dbt metric that counts it as its criteria."""
|
||||
if scoring(definition) == "proportion":
|
||||
metrics = {**{c: definition.denominator.metric for c in definition.denominator.codes},
|
||||
**{c: definition.numerator.metric for c in definition.numerator.codes},
|
||||
**({c: definition.exclusion.metric for c in definition.exclusion.codes}
|
||||
if getattr(definition, "exclusion", None) else {})}
|
||||
else:
|
||||
codes = ["initial-population"] if scoring(definition) == "cohort" else ["initial-population", OBSERVATION,
|
||||
EXCLUDED]
|
||||
metrics = {c: definition.metric for c in codes}
|
||||
return [{"code": concept(POPULATION_SYSTEM, c), "description": POPULATION_LABELS.get(c, c),
|
||||
"criteria": {"language": "text/x-dbt-metric", "expression": metric}} for c, metric in metrics.items()]
|
||||
|
||||
|
||||
def measure_resource(definition, title: str, description: str) -> dict:
|
||||
"""The `Measure` of a definition: one group per group it publishes, each with its populations and strata."""
|
||||
meta = getattr(definition, "meta", {}) or {}
|
||||
strata = [{"code": concept(STRATIFIER_SYSTEM, s.name, text=s.spec.get("etiqueta", s.name))}
|
||||
for s in definition.strata]
|
||||
if isinstance(definition, CompositionDefinition):
|
||||
strata.insert(0, {"code": concept(STRATIFIER_SYSTEM, definition.category.value)})
|
||||
groups = [{"code": concept(GROUP_SYSTEM, definition.group), "population": _populations(definition),
|
||||
**({"stratifier": strata} if strata else {})}]
|
||||
groups += [{"code": concept(GROUP_SYSTEM, g.name, g.label), "population": _populations(definition)}
|
||||
for g in getattr(definition, "groups", ())]
|
||||
extensions = [{"url": CONTRACT, "valueCode": meta.get("contrato", "")},
|
||||
*({"url": PERIOD_TYPES, "valueCode": t} for t in meta.get("tipos_periodo", ())),
|
||||
*({"url": FIGURES, "valueString": f} for f in meta.get("figuras", ()))]
|
||||
category = meta.get("categoria", {})
|
||||
extensions += [{"url": CATEGORY_LABEL, "extension": [
|
||||
{"url": "codigo", "valueCode": code}, {"url": "etiqueta", "valueString": spec["etiqueta"]},
|
||||
{"url": "color", "valueString": spec["color"]}]} for code, spec in category.get("etiquetas", {}).items()]
|
||||
if meta.get("requiere_validacion"):
|
||||
extensions.append({"url": REQUIRES_VALIDATION, "valueCode": meta["requiere_validacion"]})
|
||||
resource = {
|
||||
"resourceType": "Measure", "id": fhir_id(definition), "url": measure_url(definition),
|
||||
"version": definition.version, "name": definition.metric, "title": title, "status": "active",
|
||||
"description": description or title, "extension": [e for e in extensions if e.get("valueCode", True)],
|
||||
"scoring": concept(SCORING_SYSTEM, scoring(definition)), "group": groups,
|
||||
}
|
||||
if definition.basis:
|
||||
resource["subjectCodeableConcept"] = concept(f"{CODE_SYSTEM}/unidad", definition.basis)
|
||||
if definition.improvement_notation:
|
||||
resource["improvementNotation"] = concept(IMPROVEMENT_SYSTEM, definition.improvement_notation)
|
||||
return resource
|
||||
|
||||
|
||||
def _count(code: str, n: int) -> dict:
|
||||
return {"code": concept(POPULATION_SYSTEM, code), "count": n}
|
||||
|
||||
|
||||
def _proportion_cells(definition, counts: Counts, excluded: int | None = None) -> dict:
|
||||
cells = {"population": [*(_count(c, counts.denominator) for c in definition.denominator.codes),
|
||||
*(_count(c, counts.numerator) for c in definition.numerator.codes)]}
|
||||
if excluded is not None and getattr(definition, "exclusion", None):
|
||||
cells["population"] += [_count(c, excluded) for c in definition.exclusion.codes]
|
||||
if counts.proportion is not None:
|
||||
cells["measureScore"] = {"value": counts.proportion}
|
||||
return cells
|
||||
|
||||
|
||||
def _label(spec: dict, value: str) -> str | None:
|
||||
"""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")
|
||||
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:
|
||||
return concept(f"{CODE_SYSTEM}/{stratifier.replace('_', '-')}", value, display)
|
||||
|
||||
|
||||
def _groups(definition, result) -> list[dict]:
|
||||
if isinstance(result, CompositionAnswer):
|
||||
group = {"code": concept(GROUP_SYSTEM, definition.group), "population": [_count("initial-population",
|
||||
result.total)]}
|
||||
labels_of = {c: s["etiqueta"] for c, s in definition.meta.get("categoria", {}).get("etiquetas", {}).items()}
|
||||
category = definition.category.value
|
||||
stratifiers = [{"code": [concept(STRATIFIER_SYSTEM, category)], "stratum": [
|
||||
{"value": _stratum_value(category, c, labels_of.get(c)), "population": [_count("initial-population", n)]}
|
||||
for c, n in sorted(result.categories.items())]}]
|
||||
for name, by_value in result.strata.items():
|
||||
stratifiers.append({"code": [concept(STRATIFIER_SYSTEM, name), concept(STRATIFIER_SYSTEM, category)],
|
||||
"stratum": [{"component": [
|
||||
{"code": concept(STRATIFIER_SYSTEM, name), "value": _stratum_value(name, v)},
|
||||
{"code": concept(STRATIFIER_SYSTEM, category), "value": _stratum_value(category, c)},
|
||||
], "population": [_count("initial-population", n)]}
|
||||
for v, cs in sorted(by_value.items()) for c, n in sorted(cs.items())]})
|
||||
group["stratifier"] = stratifiers
|
||||
return [group]
|
||||
if isinstance(result, DurationAnswer):
|
||||
group = {"code": concept(GROUP_SYSTEM, definition.group), "population": [
|
||||
_count("initial-population", result.initial), _count(OBSERVATION, result.n),
|
||||
_count(EXCLUDED, result.excluded)]}
|
||||
if result.median is not None:
|
||||
group["measureScore"] = {"value": result.median, "unit": "d", "extension": [
|
||||
{"url": f"{STRUCTURE}/q1", "valueDecimal": result.q1},
|
||||
{"url": f"{STRUCTURE}/q3", "valueDecimal": result.q3}]}
|
||||
return [group]
|
||||
assert isinstance(result, Answer)
|
||||
spec_of = {s.name: s.spec for s in definition.strata}
|
||||
group = {"code": concept(GROUP_SYSTEM, definition.group), **_proportion_cells(definition, result.total,
|
||||
result.excluded)}
|
||||
if result.strata:
|
||||
group["stratifier"] = [{"code": [concept(STRATIFIER_SYSTEM, name, text=spec_of[name].get("etiqueta"))],
|
||||
"stratum": [{"value": _stratum_value(name, value, _label(spec_of[name], value)),
|
||||
**_proportion_cells(definition, c)}
|
||||
for value, c in sorted(values.items())]}
|
||||
for name, values in result.strata.items()]
|
||||
groups = [group]
|
||||
labels_of = {g.name: g.label for g in getattr(definition, "groups", ())}
|
||||
groups += [{"code": concept(GROUP_SYSTEM, name, labels_of.get(name)), **_proportion_cells(definition, counts)}
|
||||
for name, counts in result.groups.items()]
|
||||
return groups
|
||||
|
||||
|
||||
def measure_report(definition, question, result, period, generated_at: datetime) -> dict:
|
||||
"""An answer as a FHIR R4 `MeasureReport` (summary), naming its measure by its absolute canonical."""
|
||||
cutoff = getattr(result, "event_cutoff", None) or question.event_cutoff
|
||||
extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}]
|
||||
if cutoff is not None:
|
||||
extensions.append({"url": EVENT_CUTOFF, "valueDate": cutoff.isoformat()})
|
||||
if question.knowledge_cutoff is not None:
|
||||
extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()})
|
||||
report = {
|
||||
"resourceType": "MeasureReport", "id": f"{fhir_id(definition)}-{result.report_id}", "status": "complete",
|
||||
"type": "summary", "measure": f"{measure_url(definition)}|{definition.version}",
|
||||
"date": generated_at.isoformat(),
|
||||
# FHIR's end is inclusive; a period of `dim_periodo` ends the day before `fin`.
|
||||
"period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()},
|
||||
"extension": extensions, "group": _groups(definition, result),
|
||||
}
|
||||
if definition.improvement_notation:
|
||||
report["improvementNotation"] = concept(IMPROVEMENT_SYSTEM, definition.improvement_notation)
|
||||
return report
|
||||
@@ -0,0 +1,358 @@
|
||||
"""TEA's patients as FHIR R4 resources: the follow-up list as `EpisodeOfCare`s and the patient summary.
|
||||
|
||||
Read from dbt's views (`tea_seguimiento`, `tea_paciente_*`), which hold dates, not states: every state here is taken
|
||||
at a date, the cut-off. A child's screening is an `EpisodeOfCare` from its first M-CHAT to its first good EEG, its
|
||||
stage the furthest step reached by the cut-off (`type`, with its date as an extension), its pending steps a
|
||||
`CarePlan`. The EEG the study uses is the child's first good EEG by the cut-off; without one, the latest, as not
|
||||
valid. `Patient.id` is the salted pseudonym: `pac_id` never leaves.
|
||||
|
||||
Until the domain expert validates the reference ranges, every alteration stays hidden (`alterations_validated`):
|
||||
the alteration filter, the abnormal/normal split, and the metric and electrode observations.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import column, select, table
|
||||
|
||||
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, concept, tagged
|
||||
|
||||
STEPS = (("SOLO_MCHAT", "fecha_mchat", "M-CHAT"), ("PSICOLOGIA", "fecha_psicologia", "Evaluación psicológica"),
|
||||
("NEUROPEDIATRIA", "fecha_neuropediatria", "Evaluación neuropediátrica"),
|
||||
("EEG", "fecha_eeg", "EEG de buena calidad"))
|
||||
CRITERIA = (("calidad_amplitud", "Canales con amplitud extrema", "canales"),
|
||||
("calidad_alta_frecuencia", "Ruido de alta frecuencia", "canales"),
|
||||
("calidad_correlacion", "Baja correlación entre canales", "canales"),
|
||||
("calidad_sin_senal", "Canales planos o sin señal", "canales"),
|
||||
("calidad_linea", "Ruido de la línea eléctrica", "dB"))
|
||||
ALTERED = ("aumentado", "disminuido")
|
||||
INTERPRETATION = "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation"
|
||||
ABSENT = "http://terminology.hl7.org/CodeSystem/data-absent-reason"
|
||||
ICD10 = "http://hl7.org/fhir/sid/icd-10"
|
||||
CATALOG = f"{CODE_SYSTEM}/tea-catalogo"
|
||||
STAGE_DATE = f"{STRUCTURE}/fecha-etapa"
|
||||
AGE_GROUP = f"{STRUCTURE}/grupo-edad"
|
||||
DEFAULT_SALT = "dev-simulado"
|
||||
|
||||
FOLLOW_UP = table("tea_seguimiento", *map(column, (
|
||||
"pac_id", "grupo_edad", "fecha_mchat", "mchat", "fecha_psicologia", "css_ados2", "modulo_ados2",
|
||||
"fecha_neuropediatria", "fecha_tea", "fecha_sin_tea", "fecha_eeg")))
|
||||
EEGS = table("tea_paciente_eegs", *map(column, (
|
||||
"procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "calidad", "valido",
|
||||
*(c for name, _, _ in CRITERIA for c in (name, f"{name}_bueno")))))
|
||||
METRICS = table("tea_paciente_eeg_metricas", *map(column, (
|
||||
"procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_max", "valor_z", "estado")))
|
||||
ELECTRODES = table("tea_paciente_eeg_electrodos", *map(column, ("procedimiento_id", "pac_id", "metrica", "electrodo",
|
||||
"valor")))
|
||||
ADOS2 = table("tea_paciente_ados2", *map(column, (
|
||||
"procedimiento_id", "pac_id", "fecha_ados2", "modulo", "algoritmo", "css", "clasificacion", "dominio", "reactivo",
|
||||
"etiqueta", "puntaje", "puntaje_algoritmo")))
|
||||
PERSONS = table("persona", column("pac_id"), column("fecha_nacimiento"))
|
||||
|
||||
|
||||
def alterations_validated() -> bool:
|
||||
"""Whether the domain expert validated the reference ranges, effect texts and quality thresholds
|
||||
(`TEA_ALTERACIONES_VALIDADAS=1`): until then no alteration is shown."""
|
||||
return os.environ.get("TEA_ALTERACIONES_VALIDADAS", "") in ("1", "true", "si")
|
||||
|
||||
|
||||
def salt() -> str:
|
||||
return os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT)
|
||||
|
||||
|
||||
def seudonimo(pac_id: int, sal: str) -> str:
|
||||
"""TEA's patient and episode ids: stable for a salt, without saying the `pac_id`. CaCu's follow-up list moved
|
||||
to the platform's `pac_id`; TEA keeps the pseudonym until its patient resources get their own identity."""
|
||||
return "P-" + hashlib.sha256(f"{sal}:{pac_id}".encode()).hexdigest()[:10].upper()
|
||||
|
||||
|
||||
def _date(value) -> date | None:
|
||||
if value is None or isinstance(value, date):
|
||||
return value
|
||||
return date.fromisoformat(str(value)[:10])
|
||||
|
||||
|
||||
def _rows(queries, query) -> list[dict]:
|
||||
columns, rows = queries.rows(query)
|
||||
return [dict(zip(columns, row)) for row in rows]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Episode:
|
||||
"""A child's screening at the cut-off: its follow-up row, the steps reached, the study's EEG and its metrics."""
|
||||
|
||||
child: dict
|
||||
cutoff: date
|
||||
eegs: list[dict]
|
||||
metrics: list[dict]
|
||||
|
||||
@property
|
||||
def pseudonym(self) -> str:
|
||||
return seudonimo(self.child["pac_id"], salt())
|
||||
|
||||
def reached(self) -> list[tuple[str, date, str]]:
|
||||
steps = []
|
||||
for code, field, label in STEPS:
|
||||
when = _date(self.child[field])
|
||||
if when is None or when > self.cutoff:
|
||||
break
|
||||
steps.append((code, when, label))
|
||||
return steps
|
||||
|
||||
@property
|
||||
def stage(self) -> tuple[str, date] | None:
|
||||
steps = self.reached()
|
||||
return (steps[-1][0], steps[-1][1]) if steps else None
|
||||
|
||||
@property
|
||||
def finished(self) -> bool:
|
||||
return any(code == "EEG" for code, _, _ in self.reached())
|
||||
|
||||
@property
|
||||
def pending(self) -> list[str]:
|
||||
done = {code for code, _, _ in self.reached()}
|
||||
return [label for code, _, label in STEPS if code not in done]
|
||||
|
||||
@property
|
||||
def diagnosis(self) -> bool | None:
|
||||
"""True with a F84.0 note by the cut-off, False with only notes without it, None without a note."""
|
||||
if (_date(self.child["fecha_tea"]) or date.max) <= self.cutoff:
|
||||
return True
|
||||
if (_date(self.child["fecha_sin_tea"]) or date.max) <= self.cutoff:
|
||||
return False
|
||||
return None
|
||||
|
||||
def study_eeg(self) -> dict | None:
|
||||
"""The first good EEG by the cut-off; without one, the latest by then (not valid)."""
|
||||
known = sorted((e for e in self.eegs if (_date(e["fecha_eeg"]) or date.max) <= self.cutoff),
|
||||
key=lambda e: (_date(e["fecha_eeg"]), e["procedimiento_id"]))
|
||||
good = [e for e in known if e["valido"] == 1]
|
||||
return good[0] if good else (known[-1] if known else None)
|
||||
|
||||
def alterations(self) -> list[str]:
|
||||
eeg = self.study_eeg()
|
||||
if eeg is None or eeg["valido"] != 1:
|
||||
return []
|
||||
return sorted(m["metrica"] for m in self.metrics
|
||||
if m["procedimiento_id"] == eeg["procedimiento_id"] and m["estado"] in ALTERED)
|
||||
|
||||
@property
|
||||
def eeg_result(self) -> str:
|
||||
eeg = self.study_eeg()
|
||||
if eeg is None or eeg["valido"] != 1:
|
||||
return "sin-eeg-valido"
|
||||
return "anormal" if self.alterations() else "normal"
|
||||
|
||||
|
||||
def episodes(queries, cutoff: date) -> list[Episode]:
|
||||
"""Every child of the cohort who entered the screening by the cut-off, with its EEGs and their metrics."""
|
||||
eegs, metrics = _rows(queries, select(EEGS)), _rows(queries, select(METRICS))
|
||||
by_child = {}
|
||||
for child in _rows(queries, select(FOLLOW_UP)):
|
||||
if (_date(child["fecha_mchat"]) or date.max) <= cutoff:
|
||||
by_child[child["pac_id"]] = Episode(child, cutoff, [], [])
|
||||
for eeg in eegs:
|
||||
if eeg["pac_id"] in by_child:
|
||||
by_child[eeg["pac_id"]].eegs.append(eeg)
|
||||
for metric in metrics:
|
||||
if metric["pac_id"] in by_child:
|
||||
by_child[metric["pac_id"]].metrics.append(metric)
|
||||
return list(by_child.values())
|
||||
|
||||
|
||||
def patient_of(queries, pseudonym: str) -> int | None:
|
||||
"""The `pac_id` behind a pseudonym, among the cohort's children."""
|
||||
for child in _rows(queries, select(FOLLOW_UP.c.pac_id)):
|
||||
if seudonimo(child["pac_id"], salt()) == pseudonym:
|
||||
return child["pac_id"]
|
||||
return None
|
||||
|
||||
|
||||
# --- resources -------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def patient(pac_id: int, birth: date | None, simulated: bool) -> dict:
|
||||
resource = {"resourceType": "Patient", "id": seudonimo(pac_id, salt())}
|
||||
if birth is not None:
|
||||
resource["birthDate"] = _date(birth).strftime("%Y-%m")
|
||||
return tagged(resource, simulated)
|
||||
|
||||
|
||||
def episode_of_care(e: Episode, simulated: bool) -> dict:
|
||||
stage = e.stage
|
||||
resource = {
|
||||
"resourceType": "EpisodeOfCare", "id": e.pseudonym, "status": "finished" if e.finished else "active",
|
||||
"patient": {"reference": f"Patient/{e.pseudonym}"},
|
||||
"period": {"start": _date(e.child["fecha_mchat"]).isoformat(),
|
||||
**({"end": stage[1].isoformat()} if e.finished else {})},
|
||||
"extension": [{"url": AGE_GROUP, "valueCoding": {"system": f"{CODE_SYSTEM}/grupo-edad",
|
||||
"code": e.child["grupo_edad"]}}],
|
||||
}
|
||||
if stage is not None:
|
||||
resource["type"] = [concept(f"{CODE_SYSTEM}/paso", stage[0])]
|
||||
resource["extension"].append({"url": STAGE_DATE, "valueDate": stage[1].isoformat()})
|
||||
return tagged(resource, simulated)
|
||||
|
||||
|
||||
def care_plan(e: Episode, simulated: bool) -> dict:
|
||||
"""The episode's steps, each `completed` with its date or `not-started`."""
|
||||
done = {code: when for code, when, _ in e.reached()}
|
||||
activities = [{"detail": {
|
||||
"code": concept(f"{CODE_SYSTEM}/paso", code, text=label),
|
||||
"status": "completed" if code in done else "not-started",
|
||||
**({"scheduledString": done[code].isoformat()} if code in done else {})}} for code, _, label in STEPS]
|
||||
return tagged({"resourceType": "CarePlan", "id": f"pasos-{e.pseudonym}", "status": "active" if not e.finished
|
||||
else "completed", "intent": "plan", "subject": {"reference": f"Patient/{e.pseudonym}"},
|
||||
"extension": [{"url": f"{STRUCTURE}/episodio", "valueReference": {
|
||||
"reference": f"EpisodeOfCare/{e.pseudonym}"}}],
|
||||
"activity": activities}, simulated)
|
||||
|
||||
|
||||
def mchat_observation(e: Episode, simulated: bool) -> dict | None:
|
||||
if e.child["mchat"] is None:
|
||||
return None
|
||||
return tagged({"resourceType": "Observation", "id": f"mchat-{e.pseudonym}", "status": "final",
|
||||
"code": concept(CATALOG, "mchat.puntaje", "M-CHAT-R/F: puntaje total"),
|
||||
"subject": {"reference": f"Patient/{e.pseudonym}"},
|
||||
"effectiveDateTime": _date(e.child["fecha_mchat"]).isoformat(),
|
||||
"valueInteger": int(e.child["mchat"])}, simulated)
|
||||
|
||||
|
||||
def condition(e: Episode, simulated: bool) -> dict | None:
|
||||
if not e.diagnosis:
|
||||
return None
|
||||
return tagged({"resourceType": "Condition", "id": f"tea-{e.pseudonym}",
|
||||
"code": concept(ICD10, "F84.0", "Autismo en la niñez"),
|
||||
"subject": {"reference": f"Patient/{e.pseudonym}"},
|
||||
"recordedDate": _date(e.child["fecha_tea"]).isoformat()}, simulated)
|
||||
|
||||
|
||||
def quality_observations(eeg: dict, pseudonym: str, simulated: bool) -> list[dict]:
|
||||
observations = []
|
||||
for name, label, unit in CRITERIA:
|
||||
if eeg[name] is None:
|
||||
continue
|
||||
value = ({"valueInteger": int(eeg[name])} if unit == "canales"
|
||||
else {"valueQuantity": {"value": float(eeg[name]), "unit": unit}})
|
||||
observations.append(tagged({
|
||||
"resourceType": "Observation", "id": f"{name.replace('_', '-')}-{eeg['procedimiento_id']}",
|
||||
"status": "final", "code": concept(CATALOG, f"eeg.{name}", label),
|
||||
"subject": {"reference": f"Patient/{pseudonym}"}, "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
|
||||
**value, "interpretation": [concept(f"{CODE_SYSTEM}/calidad", "BUENO" if eeg[f"{name}_bueno"] else "MALO")],
|
||||
}, simulated))
|
||||
return observations
|
||||
|
||||
|
||||
def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], pseudonym: str,
|
||||
simulated: bool) -> list[dict]:
|
||||
"""One `Observation` per metric (value, reference for the age at the EEG, H/L/N, the z-score as a component, or
|
||||
why it couldn't be evaluated) and one per metric with a component per electrode."""
|
||||
from webapi.fhir.terminology import TEA_EEG
|
||||
|
||||
observations = []
|
||||
for m in sorted((m for m in metrics if m["procedimiento_id"] == eeg["procedimiento_id"]), key=lambda m: m["metrica"]):
|
||||
spec = TEA_EEG["metricas"].get(m["metrica"], {"etiqueta": m["metrica"], "unidad": ""})
|
||||
code = concept(f"{CODE_SYSTEM}/tea-eeg-metrica", m["metrica"], spec["etiqueta"])
|
||||
resource = {"resourceType": "Observation", "id": f"{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}",
|
||||
"status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat()}
|
||||
if m["valor"] is None or m["valor_z"] is None:
|
||||
resource["dataAbsentReason"] = concept(ABSENT, "not-performed" if m["valor"] is None else "unknown")
|
||||
else:
|
||||
resource["valueQuantity"] = {"value": float(m["valor"]), "unit": spec["unidad"]}
|
||||
resource["interpretation"] = [concept(INTERPRETATION, {"aumentado": "H", "disminuido": "L"}.get(
|
||||
m["estado"], "N"))]
|
||||
resource["component"] = [{"code": concept(f"{CODE_SYSTEM}/puntaje", "z", "Puntaje z"),
|
||||
"valueQuantity": {"value": round(float(m["valor_z"]), 2)}}]
|
||||
if m["ref_min"] is not None:
|
||||
resource["referenceRange"] = [{"low": {"value": float(m["ref_min"]), "unit": spec["unidad"]},
|
||||
"high": {"value": float(m["ref_max"]), "unit": spec["unidad"]},
|
||||
"text": f"Grupo de edad al EEG: {m['grupo_edad_eeg']}"}]
|
||||
observations.append(tagged(resource, simulated))
|
||||
at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"]]
|
||||
if at:
|
||||
observations.append(tagged({
|
||||
"resourceType": "Observation", "id": f"electrodos-{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}",
|
||||
"status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
|
||||
"component": [{"code": concept(f"{CODE_SYSTEM}/electrodo-10-20", x["electrodo"]),
|
||||
"valueQuantity": {"value": float(x["valor"])}}
|
||||
for x in sorted(at, key=lambda x: x["electrodo"])]}, simulated))
|
||||
return observations
|
||||
|
||||
|
||||
def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool) -> list[dict]:
|
||||
"""The recording as a `Procedure` and its result as a `DiagnosticReport` with its observations; a bad EEG has
|
||||
no result beyond its quality, and the alterations stay out until validated."""
|
||||
quality = quality_observations(eeg, pseudonym, simulated)
|
||||
altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated)
|
||||
if eeg["valido"] == 1 and alterations_validated() else [])
|
||||
procedure = tagged({"resourceType": "Procedure", "id": f"eeg-{eeg['procedimiento_id']}", "status": "completed",
|
||||
"code": concept(CATALOG, "eeg", "Electroencefalograma"),
|
||||
"subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"performedDateTime": _date(eeg["fecha_eeg"]).isoformat()}, simulated)
|
||||
report = {"resourceType": "DiagnosticReport", "id": f"eeg-{eeg['procedimiento_id']}", "status": "final",
|
||||
"code": concept(CATALOG, "eeg", "Electroencefalograma"), "subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
|
||||
"result": [{"reference": f"Observation/{o['id']}"} for o in quality + altered],
|
||||
"conclusionCode": [concept(f"{CODE_SYSTEM}/calidad", eeg["calidad"])]}
|
||||
if eeg["duracion_min"] is not None or eeg["canales"] is not None:
|
||||
report["extension"] = [e for e in (
|
||||
{"url": f"{STRUCTURE}/duracion-min", "valueDecimal": float(eeg["duracion_min"])}
|
||||
if eeg["duracion_min"] is not None else None,
|
||||
{"url": f"{STRUCTURE}/canales", "valueInteger": int(eeg["canales"])} if eeg["canales"] is not None else None,
|
||||
) if e]
|
||||
if eeg["valido"] != 1:
|
||||
report["conclusion"] = "EEG de mala calidad: no es válido para el estudio."
|
||||
return [procedure, tagged(report, simulated), *quality, *altered]
|
||||
|
||||
|
||||
def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict | None:
|
||||
"""The first ADOS-2 as one `Observation`: module, algorithm, CSS, classification, the two domain totals and the
|
||||
items, each item with its algorithm score."""
|
||||
if not rows:
|
||||
return None
|
||||
first = min(rows, key=lambda r: (_date(r["fecha_ados2"]) or date.max, r["procedimiento_id"]))
|
||||
items = [r for r in rows if r["procedimiento_id"] == first["procedimiento_id"] and r["reactivo"]]
|
||||
components = []
|
||||
if first["modulo"]:
|
||||
components.append({"code": concept(CATALOG, "ados2.modulo", "Módulo"),
|
||||
"valueCodeableConcept": concept(CATALOG, f"ados2.modulo.{first['modulo']}")})
|
||||
if first["algoritmo"]:
|
||||
components.append({"code": concept(CATALOG, "ados2.algoritmo", "Algoritmo"), "valueString": first["algoritmo"]})
|
||||
if first["css"] is not None:
|
||||
components.append({"code": concept(CATALOG, "ados2.css", "Puntaje de severidad (CSS)"),
|
||||
"valueInteger": int(first["css"])})
|
||||
if first["clasificacion"]:
|
||||
components.append({"code": concept(CATALOG, "ados2.clasificacion", "Clasificación"),
|
||||
"valueCodeableConcept": concept(CATALOG, f"ados2.clasificacion.{first['clasificacion']}")})
|
||||
for domain, label in (("SA", "Afecto social"), ("RRB", "Comportamiento restringido y repetitivo")):
|
||||
total = sum(int(r["puntaje_algoritmo"]) for r in items if r["dominio"] == domain)
|
||||
components.append({"code": concept(f"{CODE_SYSTEM}/ados2-dominio", domain, label), "valueInteger": total})
|
||||
components += [{"code": concept(CATALOG, r["reactivo"], r["etiqueta"]), "valueInteger": int(r["puntaje"]),
|
||||
"extension": [{"url": f"{STRUCTURE}/puntaje-algoritmo", "valueInteger": int(r["puntaje_algoritmo"])},
|
||||
{"url": f"{STRUCTURE}/dominio", "valueCode": r["dominio"]}]}
|
||||
for r in sorted(items, key=lambda r: r["reactivo"])]
|
||||
return tagged({"resourceType": "Observation", "id": f"ados2-{first['procedimiento_id']}", "status": "final",
|
||||
"code": concept(CATALOG, "ados2", "ADOS-2"), "subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"effectiveDateTime": _date(first["fecha_ados2"]).isoformat(), "component": components}, simulated)
|
||||
|
||||
|
||||
def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict:
|
||||
"""The `$resumen-tea` collection: the patient, its first ADOS-2 and the EEG the study uses, as of today."""
|
||||
pseudonym = seudonimo(pac_id, salt())
|
||||
persons = _rows(queries, select(PERSONS).where(PERSONS.c.pac_id == pac_id))
|
||||
resources = [patient(pac_id, persons[0]["fecha_nacimiento"] if persons else None, simulated)]
|
||||
ados2 = ados2_observation(_rows(queries, select(ADOS2).where(ADOS2.c.pac_id == pac_id)), pseudonym, simulated)
|
||||
resources += [ados2] if ados2 else []
|
||||
(child,) = _rows(queries, select(FOLLOW_UP).where(FOLLOW_UP.c.pac_id == pac_id)) or [None]
|
||||
if child is not None:
|
||||
e = Episode(child, today, _rows(queries, select(EEGS).where(EEGS.c.pac_id == pac_id)),
|
||||
_rows(queries, select(METRICS).where(METRICS.c.pac_id == pac_id)))
|
||||
eeg = e.study_eeg()
|
||||
if eeg is not None:
|
||||
electrodes = _rows(queries, select(ELECTRODES).where(ELECTRODES.c.pac_id == pac_id))
|
||||
resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated)
|
||||
return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]}
|
||||
@@ -0,0 +1,53 @@
|
||||
# TEA's EEG vocabulary for the FHIR answers: what each metric's alteration may mean (`efectos`, by state), and where
|
||||
# each 10-20 electrode sits on the map the WebApp draws (x to the right, y forward, both from -1 to 1).
|
||||
# The effect texts are placeholders pending the domain expert's review, like the reference ranges in dbt's var `tea`.
|
||||
|
||||
[metricas.ritmo_posterior]
|
||||
etiqueta = "Ritmo posterior"
|
||||
unidad = "Hz"
|
||||
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
|
||||
efectos.disminuido = ["Ritmo más lento de lo esperado para la edad.", "Posible relación con retraso en la maduración cortical."]
|
||||
|
||||
[metricas.husos_sueno_n2]
|
||||
etiqueta = "Husos de sueño N2"
|
||||
unidad = "husos/min"
|
||||
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
|
||||
efectos.disminuido = ["Posible relación con alteraciones del sueño.", "Posible efecto en la consolidación de la memoria y el aprendizaje."]
|
||||
|
||||
[metricas.husos_sueno_n3]
|
||||
etiqueta = "Husos de sueño N3"
|
||||
unidad = "husos/min"
|
||||
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
|
||||
efectos.disminuido = ["Posible relación con alteraciones del sueño.", "Posible efecto en la consolidación de la memoria y el aprendizaje."]
|
||||
|
||||
[metricas.picos_paroxisticos]
|
||||
etiqueta = "Picos paroxísticos"
|
||||
unidad = "picos/min"
|
||||
efectos.aumentado = ["Actividad paroxística mayor de la esperada.", "Correlacionar con la clínica."]
|
||||
|
||||
[metricas.gradiente_anteroposterior]
|
||||
etiqueta = "Gradiente anteroposterior"
|
||||
unidad = "razón posterior/anterior"
|
||||
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
|
||||
efectos.disminuido = ["Organización anteroposterior menos marcada de lo esperado.", "Posible relación con retraso en la maduración cortical."]
|
||||
|
||||
[electrodos]
|
||||
Fp1 = [-0.25, 0.77]
|
||||
Fp2 = [0.25, 0.77]
|
||||
F7 = [-0.65, 0.47]
|
||||
F3 = [-0.33, 0.4]
|
||||
Fz = [0.0, 0.38]
|
||||
F4 = [0.33, 0.4]
|
||||
F8 = [0.65, 0.47]
|
||||
T3 = [-0.8, 0.0]
|
||||
C3 = [-0.4, 0.0]
|
||||
Cz = [0.0, 0.0]
|
||||
C4 = [0.4, 0.0]
|
||||
T4 = [0.8, 0.0]
|
||||
T5 = [-0.65, -0.47]
|
||||
P3 = [-0.33, -0.4]
|
||||
Pz = [0.0, -0.38]
|
||||
P4 = [0.33, -0.4]
|
||||
T6 = [0.65, -0.47]
|
||||
O1 = [-0.25, -0.77]
|
||||
O2 = [0.25, -0.77]
|
||||
@@ -0,0 +1,74 @@
|
||||
"""The project's code systems as FHIR R4 `CodeSystem` resources, generated from what defines them: the domain's
|
||||
catalog (`core/catalogos/<domain>.toml`: studies, results and their values), TEA's screening stages and diagnostic
|
||||
results, and TEA's EEG metrics with their effect texts (`tea_eeg.toml`)."""
|
||||
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.fhir.common import CODE_SYSTEM, canonical
|
||||
from webapi.orchestration.reference.catalogs import ruta_de_catalogo
|
||||
|
||||
TEA_EEG = tomllib.loads((Path(__file__).parent / "tea_eeg.toml").read_text(encoding="utf-8"))
|
||||
STAGES = (("SOLO_MCHAT", "Solo M-CHAT"), ("PSICOLOGIA", "Hasta evaluación psicológica"),
|
||||
("NEUROPEDIATRIA", "Hasta evaluación neuropediátrica"), ("EEG", "Con EEG"))
|
||||
DIAGNOSES = (("EN_PROCESO", "En proceso"), ("SIN_TEA", "Nota sin F84.0"), ("CONFIRMADO", "Diagnóstico confirmado"))
|
||||
QUALITY = (("BUENO", "Bueno"), ("MALO", "Malo"), ("SIN_ANALIZAR", "Sin analizar"))
|
||||
|
||||
|
||||
def _code_system(id_: str, title: str, concepts: list[dict], *, hierarchy: bool = False) -> dict:
|
||||
resource = {"resourceType": "CodeSystem", "id": id_, "url": f"{CODE_SYSTEM}/{id_}", "name": id_.replace("-", "_"),
|
||||
"title": title, "status": "active", "content": "complete", "concept": concepts}
|
||||
if hierarchy:
|
||||
resource["hierarchyMeaning"] = "part-of"
|
||||
return resource
|
||||
|
||||
|
||||
def catalog(domain: str) -> dict:
|
||||
"""The domain's catalog: each study, its results under it and each coded result's values under the result."""
|
||||
studies = tomllib.loads(ruta_de_catalogo(domain).read_text(encoding="utf-8"))
|
||||
concepts = []
|
||||
for study_id, study in studies.items():
|
||||
results = []
|
||||
for name, result in study.get("resultados", {}).items():
|
||||
values = [{"code": f"{study_id}.{name}.{v['valor']}", "display": v["etiqueta"]}
|
||||
for v in result.get("valores", ())]
|
||||
results.append({"code": f"{study_id}.{name}", "display": result["etiqueta"],
|
||||
**({"concept": values} if values else {})})
|
||||
concepts.append({"code": study_id, "display": study["etiqueta"], **({"concept": results} if results else {})})
|
||||
return _code_system(f"{domain}-catalogo", f"Catálogo de {domain.upper()}", concepts, hierarchy=True)
|
||||
|
||||
|
||||
def tea_code_systems() -> dict[str, dict]:
|
||||
metrics = [{"code": code, "display": spec["etiqueta"], "property": [
|
||||
{"code": "unidad", "valueString": spec["unidad"]},
|
||||
*({"code": f"efecto-{state}", "valueString": text} for state, texts in spec.get("efectos", {}).items()
|
||||
for text in texts)]} for code, spec in TEA_EEG["metricas"].items()]
|
||||
systems = [
|
||||
_code_system("paso", "Etapa del tamizaje de TEA", [{"code": c, "display": d} for c, d in STAGES]),
|
||||
_code_system("estado", "Resultado diagnóstico de TEA", [{"code": c, "display": d} for c, d in DIAGNOSES]),
|
||||
_code_system("calidad", "Calidad del EEG", [{"code": c, "display": d} for c, d in QUALITY]),
|
||||
{**_code_system("tea-eeg-metrica", "Métricas del EEG", metrics),
|
||||
"property": [{"code": "unidad", "type": "string"}, {"code": "efecto-aumentado", "type": "string"},
|
||||
{"code": "efecto-disminuido", "type": "string"}]},
|
||||
_code_system("electrodo-10-20", "Electrodos del sistema 10-20",
|
||||
[{"code": e, "display": e} for e in TEA_EEG["electrodos"]]),
|
||||
_code_system("grupo-edad", "Grupo de edad al primer M-CHAT", [
|
||||
{"code": "16_23", "display": "16 a 23 meses"}, {"code": "24_29", "display": "24 a 29 meses"},
|
||||
{"code": "30_36", "display": "30 a 36 meses"}, {"code": "sin_dato", "display": "Sin dato"}]),
|
||||
]
|
||||
return {s["id"]: s for s in systems}
|
||||
|
||||
|
||||
def code_systems(domain: str) -> dict[str, dict]:
|
||||
"""Every code system the domain's FHIR endpoint serves, by id."""
|
||||
systems = {f"{domain}-catalogo": catalog(domain)}
|
||||
if domain == "tea":
|
||||
systems.update(tea_code_systems())
|
||||
return systems
|
||||
|
||||
|
||||
def metric_value_set() -> dict:
|
||||
"""The alteration types: the EEG metrics' `ValueSet`."""
|
||||
return {"resourceType": "ValueSet", "id": "tea-alteracion", "url": canonical("ValueSet/tea-alteracion"),
|
||||
"name": "tea_alteracion", "title": "Tipos de alteración del EEG", "status": "active",
|
||||
"compose": {"include": [{"system": f"{CODE_SYSTEM}/tea-eeg-metrica"}]}}
|
||||
+12
-11
@@ -7,15 +7,16 @@ grupo de edad al corte, su estatus al corte (`cacu.seguimiento.estatus_al`, la m
|
||||
estrato), su citología y su VPH de la ventana y los días de la toma a su valoración (con las reglas
|
||||
de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula.
|
||||
|
||||
**Es dato por paciente.** Quien sirve la registra solo en DEV, con datos simulados, y toda respuesta
|
||||
lleva `simulado: true`. Nunca sale `pac_id` ni `pac_id_hospital`: `id_seudonimo` es un hash con sal.
|
||||
**Es dato por paciente.** Toda respuesta lleva `simulado: true`; quién puede verla lo decide una regla de
|
||||
acceso. Cada fila identifica a su paciente por `pac_id`, la llave de la plataforma (como texto decimal), la
|
||||
misma que usan los lotes de riesgo y `GET /cacu/pacientes/<pac_id>/riesgo`; `id_seudonimo` repite ese valor
|
||||
mientras los consumidores migran. Nunca sale `pac_id_hospital`.
|
||||
|
||||
Las reglas son de `parametros.toml` (`PARAMETROS_DE_LA_LISTA` y las del estrato `estatus_seguimiento`
|
||||
de `estratos.toml`) y salen en `reglas` con su estado. Recibe la sesión de quien sirve; no abre ninguna.
|
||||
"""
|
||||
|
||||
import calendar
|
||||
import hashlib
|
||||
import json
|
||||
import tomllib
|
||||
from datetime import date, timedelta
|
||||
@@ -85,7 +86,6 @@ class PaginaFuera(LookupError):
|
||||
def seguimiento_de(
|
||||
sesion: Session,
|
||||
*,
|
||||
sal: str,
|
||||
corte: date | None = None,
|
||||
meses: int | None = None,
|
||||
estatus: str | None = None,
|
||||
@@ -119,7 +119,7 @@ def seguimiento_de(
|
||||
corte = _acotado(sesion, corte or hoy or date.today(), tablas)
|
||||
desde = _meses_antes(corte, meses) + timedelta(days=1)
|
||||
estatus_de = _estatus_al_corte(sesion, corte, valores_estatus)
|
||||
items = _items(sesion, corte, desde, lista, estatus_de, sal, tablas)
|
||||
items = _items(sesion, corte, desde, lista, estatus_de, tablas)
|
||||
if estatus is not None:
|
||||
items = [i for i in items if i["estatus"]["codigo"] == estatus]
|
||||
|
||||
@@ -140,9 +140,9 @@ def seguimiento_de(
|
||||
}
|
||||
|
||||
|
||||
def seudonimo(pac_id: int, sal: str) -> str:
|
||||
"""El identificador que sale en la lista: estable para una sal, sin decir el `pac_id`."""
|
||||
return "P-" + hashlib.sha256(f"{sal}:{pac_id}".encode()).hexdigest()[:10].upper()
|
||||
def identificador(pac_id: int) -> str:
|
||||
"""El identificador que sale en la lista: el `pac_id` de la plataforma, como texto decimal."""
|
||||
return str(pac_id)
|
||||
|
||||
|
||||
def _validar_reglas(lista: dict) -> None:
|
||||
@@ -164,7 +164,7 @@ def _estatus_al_corte(sesion: Session, corte: date, valores: dict) -> dict[int,
|
||||
return {pac_id: estatus for pac_id, estatus in filas}
|
||||
|
||||
|
||||
def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]:
|
||||
def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
|
||||
"""Una fila por paciente con estudio en la ventana, de la más reciente a la más antigua."""
|
||||
estudios = _estudios(sesion, corte, lista["fecha_estudio"])
|
||||
en_ventana: dict[int, dict[str, list]] = {}
|
||||
@@ -187,7 +187,8 @@ def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]:
|
||||
mas_reciente = max(e["fecha"] for e in [*de_la_paciente["citologia"], *de_la_paciente["vph"]])
|
||||
estatus = estatus_de.get(pac_id, "INFO_INSUFICIENTE")
|
||||
items.append({
|
||||
"id_seudonimo": seudonimo(pac_id, sal),
|
||||
"pac_id": identificador(pac_id),
|
||||
"id_seudonimo": identificador(pac_id),
|
||||
"grupo_edad": edades.get(pac_id, SIN_DATO),
|
||||
"estatus": {"codigo": estatus, "etiqueta": _etiquetas_de_estatus()[estatus]},
|
||||
"ultima_citologia": None if cito is None else {
|
||||
@@ -201,7 +202,7 @@ def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]:
|
||||
"prioridad": None,
|
||||
"_orden": mas_reciente,
|
||||
})
|
||||
items.sort(key=lambda i: i["id_seudonimo"])
|
||||
items.sort(key=lambda i: int(i["pac_id"]))
|
||||
items.sort(key=lambda i: i.pop("_orden"), reverse=True)
|
||||
return items
|
||||
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
"""La lista de seguimiento de CaCu (T-24d): `GET /cacu/seguimiento`, solo en DEV.
|
||||
"""La lista de seguimiento de CaCu (T-24d): `GET /cacu/seguimiento`.
|
||||
|
||||
GET /cacu/seguimiento?corte=AAAA-MM-DD&meses=&estatus=&page=&page_size=
|
||||
|
||||
Es dato por paciente: **solo se registra en DEV** (con `DEV_REVISION`, que define el despliegue de
|
||||
`deploy/dev`) y con datos simulados; toda respuesta lleva `simulado: true`. Fuera de DEV la ruta no
|
||||
existe (404). La lista la arma el kit (`webapi.follow_up.listing`); aquí solo se valida,
|
||||
se abre la sesión y se traducen los errores.
|
||||
Es dato por paciente, sobre datos simulados: toda respuesta lleva `simulado: true`. La ruta se registra
|
||||
siempre; quién puede verla lo decidirá una regla de acceso. Cada fila trae el `pac_id` de la plataforma, el que
|
||||
usa la ruta de riesgo individual. La lista la arma `webapi.follow_up.listing`; aquí solo se valida, se abre la
|
||||
sesión y se traducen los errores.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import warnings
|
||||
from collections.abc import Callable
|
||||
from datetime import date
|
||||
|
||||
@@ -19,16 +20,16 @@ from webapi.follow_up.listing import PaginaFuera, PedidoInvalido, seguimiento_de
|
||||
from sqlmodel import Session
|
||||
|
||||
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
|
||||
DEFAULT_SALT = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno
|
||||
|
||||
|
||||
def in_dev() -> bool:
|
||||
"""Si esta WebApi corre en el despliegue de DEV (`deploy/dev/compose.yml` define `DEV_REVISION`)."""
|
||||
"""Obsoleta: las rutas por paciente ya no dependen de `DEV_REVISION` y nada la llama. Se quitará."""
|
||||
warnings.warn("in_dev() está obsoleta: las rutas por paciente se registran siempre", DeprecationWarning, stacklevel=2)
|
||||
return bool(os.environ.get("DEV_REVISION"))
|
||||
|
||||
|
||||
def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
|
||||
"""El blueprint de la lista, para registrarlo con `url_prefix="/cacu"` solo en DEV."""
|
||||
"""El blueprint de la lista, para registrarlo con `url_prefix="/cacu"`."""
|
||||
blueprint = Blueprint("cacu_seguimiento", __name__)
|
||||
|
||||
@blueprint.get("/seguimiento")
|
||||
@@ -39,7 +40,7 @@ def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
sesion = get_session()
|
||||
try:
|
||||
cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT), **pedido)
|
||||
cuerpo = seguimiento_de(sesion, **pedido)
|
||||
except PedidoInvalido as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
except PaginaFuera as error:
|
||||
|
||||
+33
-7
@@ -15,6 +15,7 @@ from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
@@ -23,7 +24,7 @@ from collections import Counter, defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Iterable
|
||||
from typing import TYPE_CHECKING, Any, Callable, Iterable
|
||||
|
||||
from webapi.imports.schemas.classify import ErrorCategory
|
||||
|
||||
@@ -31,7 +32,11 @@ if TYPE_CHECKING:
|
||||
from webapi.imports.schemas.service import BatchValidationResult
|
||||
from webapi.imports.services.import_service import ImportSource
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
# Longest caption, in words, that document discovery reports.
|
||||
CAPTION_MAX_WORDS = 6
|
||||
_SHAPE_MAX = 40
|
||||
_MESSAGE_MAX = 300
|
||||
_QUOTED = re.compile(r"'[^']*'|\"[^\"]*\"")
|
||||
@@ -57,11 +62,12 @@ def value_shape(value: Any) -> str:
|
||||
return shape + ("…" if len(text) > _SHAPE_MAX else "")
|
||||
|
||||
|
||||
def column_label(name: Any) -> str:
|
||||
def column_label(name: Any, *, max_words: int = 4) -> str:
|
||||
"""A source column name as it can be logged: verbatim when it looks like a
|
||||
header, its shape when it looks like data."""
|
||||
header, its shape when it looks like data. A document caption, already
|
||||
cut at a colon, may run to more words (`max_words`) than a header."""
|
||||
text = str(name).strip()
|
||||
if len(text) > _SHAPE_MAX or text.count(" ") > 3 or _VALUE_LIKE.search(text):
|
||||
if len(text) > _SHAPE_MAX or text.count(" ") >= max_words or _VALUE_LIKE.search(text):
|
||||
return value_shape(text)
|
||||
return text
|
||||
|
||||
@@ -128,9 +134,10 @@ class _SourceAudit:
|
||||
self.rows: dict[str, Any] = {"leidas": 0}
|
||||
self.links: dict[str, int] = {}
|
||||
self.warnings: Counter = Counter()
|
||||
self.captions: Counter = Counter()
|
||||
|
||||
def observe_rows(self, rows: Iterable[dict[str, Any] | None]) -> None:
|
||||
mapped = set(self.source.column_mapping.values()) | set(self.source.defaults)
|
||||
mapped = set(self.source.column_mapping.values()) | set(self.source.derived) | set(self.source.defaults)
|
||||
merged = 0
|
||||
for row in rows:
|
||||
self.rows["leidas"] += 1
|
||||
@@ -164,6 +171,15 @@ class _SourceAudit:
|
||||
self.rows.update(insertadas=created, actualizadas=updated, rechazadas_por_conflicto=conflicts)
|
||||
self.links = dict(linked)
|
||||
|
||||
def observe_captions(self, count: Callable[[], Counter]) -> None:
|
||||
"""Captions the source's documents print that the import didn't
|
||||
use (`ImportSource.unused_captions`). Best-effort: the report must
|
||||
never be what makes an import fail."""
|
||||
try:
|
||||
self.captions = Counter(count())
|
||||
except Exception:
|
||||
log.warning("no se pudieron contar las etiquetas sin usar de %s", self.source.target, exc_info=True)
|
||||
|
||||
def observe_warnings(self, warnings: Iterable[dict[str, Any]]) -> None:
|
||||
for warning in warnings:
|
||||
self.warnings[f"{warning.get('category')}:{warning.get('field')}"] += 1
|
||||
@@ -171,13 +187,14 @@ class _SourceAudit:
|
||||
def as_dict(self, threshold: int) -> dict[str, Any]:
|
||||
spec_fields = self.source.spec.schema.model_fields
|
||||
required = {name for name, info in spec_fields.items() if info.is_required()}
|
||||
mapped = set(self.source.column_mapping.values())
|
||||
mapped = set(self.source.column_mapping.values()) | set(self.source.derived)
|
||||
fixed = set(self.source.defaults)
|
||||
out: dict[str, Any] = {
|
||||
"destino": self.source.target,
|
||||
"origen": _source_origin(self.source),
|
||||
"mapeo": {
|
||||
"columnas_origen": sorted(column_label(c) for c in self.source.column_mapping),
|
||||
"columnas_origen": sorted(column_label(c) for c in self.source.source_columns),
|
||||
"campos_derivados": {name: rule.op for name, rule in sorted(self.source.derived.items())},
|
||||
"campos_mapeados": sorted(mapped),
|
||||
"campos_con_valor_fijo": sorted(fixed),
|
||||
"campos_sin_mapear": sorted(set(spec_fields) - mapped - fixed),
|
||||
@@ -190,6 +207,15 @@ class _SourceAudit:
|
||||
out["vinculos_resueltos"] = self.links
|
||||
if self.warnings:
|
||||
out["advertencias"] = dict(self.warnings)
|
||||
if self.captions:
|
||||
# Captions only, and only those enough records print: a caption
|
||||
# seen once or twice can be a misread line holding a value.
|
||||
out["etiquetas_sin_usar"] = {
|
||||
column_label(c, max_words=CAPTION_MAX_WORDS): n for c, n in self.captions.most_common() if n >= threshold
|
||||
}
|
||||
rare = sum(1 for n in self.captions.values() if n < threshold)
|
||||
if rare:
|
||||
out["etiquetas_sin_usar_poco_frecuentes"] = rare
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -1,19 +1,27 @@
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
import unicodedata
|
||||
from collections import OrderedDict
|
||||
from typing import Any, ClassVar
|
||||
from importlib.metadata import PackageNotFoundError
|
||||
from importlib.metadata import version as package_version
|
||||
from typing import Any, ClassVar, Iterator
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from extraction import DocumentExtractor, ExtractedRecord, ExtractionError, make_segmenter, read_document, reader_for
|
||||
from extraction.readers import PdfReader, combine_pages, supported_extensions
|
||||
from extraction.nlp.ranking import examples_for, same_value
|
||||
from extraction.segmentation import SEGMENTERS
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
from webapi.imports.connectors.document_columns import DocumentBatch, DocumentColumns, document_bytes # noqa: F401
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
from webapi.imports.connectors.tabular import DataFrameConnector
|
||||
from webapi.imports.schemas.field_specs import field_specs_for, key_field_for
|
||||
from webapi.imports.schemas.field_specs import field_specs_for, foreign_subjects_for, key_field_for, subject_for
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
DOCUMENT_COLUMN = "documento"
|
||||
@@ -21,6 +29,8 @@ IMAGE_COLUMN = "imagen"
|
||||
CONFIDENCE_COLUMN = "confianza_extraccion"
|
||||
SOURCES_COLUMN = "origen"
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _ResultCache:
|
||||
"""OCR over a stack of scans is slow, and the stateless API runs the
|
||||
@@ -28,11 +38,11 @@ class _ResultCache:
|
||||
per worker for the last few distinct requests."""
|
||||
|
||||
def __init__(self, size: int = 8):
|
||||
self._items: OrderedDict[str, list[ExtractedRecord]] = OrderedDict()
|
||||
self._items: OrderedDict[str, Any] = OrderedDict()
|
||||
self._size = size
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def get_or_compute(self, key: str, compute) -> list[ExtractedRecord]:
|
||||
def get_or_compute(self, key: str, compute) -> Any:
|
||||
with self._lock:
|
||||
if key in self._items:
|
||||
self._items.move_to_end(key)
|
||||
@@ -48,24 +58,50 @@ class _ResultCache:
|
||||
_CACHE = _ResultCache()
|
||||
|
||||
|
||||
def _files_from_sql(sql: dict[str, Any]) -> DocumentBatch:
|
||||
"""The documents of a SQL table or query (connected the same way
|
||||
`SqlConnector` is), read as `DocumentColumns` describes: `column` or
|
||||
`columns` hold them, and `key_column`/`name_by`, `group_column`/
|
||||
`group_by` and `fields` name, group and carry values for them."""
|
||||
if not sql.get("table") and not sql.get("query"):
|
||||
raise ConnectorError("falta table o query")
|
||||
spec = DocumentColumns.parse(sql)
|
||||
connector = SqlConnector.connect(sql)
|
||||
connector = (
|
||||
connector.select_query(sql["query"]) if sql.get("query") else connector.select_table(sql["table"], schema=sql.get("schema"))
|
||||
)
|
||||
return spec.assemble(connector.read_rows({column: column for column in spec.source_columns()}))
|
||||
|
||||
|
||||
@register_connector
|
||||
class DocumentConnector(DataFrameConnector):
|
||||
"""Clinical documents that are not tables: one report per patient,
|
||||
several pages per patient, many patients per file, scans, free text.
|
||||
several pages per patient, many patients per file, scans, free text —
|
||||
uploaded directly, or read one row at a time from a SQL source whose
|
||||
`payload` carries `sql` (a connection plus `table`/`query`, `column`
|
||||
and `key_column`) instead of `files`; either way, every row's content
|
||||
reaches the same extraction, PDF, image or plain text alike.
|
||||
|
||||
Every file is read page by page (text layer or OCR), split into
|
||||
per-patient records, and the target entity's fields are extracted from
|
||||
labels and narrative text. Records of the same patient found in other
|
||||
pages or files are merged. Each row also carries the record's pages as
|
||||
a PDF (`documento`), mappable to the entity's file column.
|
||||
Every file is read page by page (text layer or OCR; plain text as its
|
||||
own lines), split into per-patient records, and the target entity's
|
||||
fields are extracted from labels and narrative text. Records of the
|
||||
same patient found in other pages or files — or rows — are merged.
|
||||
Each row also carries the record's pages as a PDF (`documento`),
|
||||
mappable to the entity's file column, when the source produced one.
|
||||
|
||||
Corrections made while reviewing travel in `overrides`
|
||||
(`{"<row>": {"field": value}}`) and win over the extracted value.
|
||||
A SQL source's `sql.fields` (`{target_field: sql_column}`) carries other
|
||||
columns of the same row straight through as that row's values for those
|
||||
fields, overriding whatever the document's own text parses to — a
|
||||
source's own patient or study id is a structured join key, not a guess,
|
||||
so it wins even over a page that prints nothing recognizable, or
|
||||
prints something else entirely. Corrections made while reviewing
|
||||
travel in `overrides` (`{"<row>": {"field": value}}`) and win over
|
||||
both.
|
||||
"""
|
||||
|
||||
kind = "document"
|
||||
label = "Documentos clínicos"
|
||||
description = "Reportes, formatos y notas en PDF o imagen; los campos se extraen del texto libre"
|
||||
description = "Reportes, formatos y notas en PDF, imagen o texto; los campos se extraen del contenido"
|
||||
category = "document"
|
||||
icon = "document_scanner"
|
||||
extensions: ClassVar[tuple[str, ...]] = tuple(supported_extensions())
|
||||
@@ -80,6 +116,10 @@ class DocumentConnector(DataFrameConnector):
|
||||
ocr_mode: str = "auto",
|
||||
key_pattern: str | None = None,
|
||||
overrides: dict[str, dict[str, Any]] | None = None,
|
||||
source_fields: dict[str, dict[str, Any]] | None = None,
|
||||
record_keys: dict[str, str] | None = None,
|
||||
include_pattern: str | None = None,
|
||||
exclude_pattern: str | None = None,
|
||||
):
|
||||
if not files:
|
||||
raise ConnectorError("no se recibieron documentos")
|
||||
@@ -92,6 +132,12 @@ class DocumentConnector(DataFrameConnector):
|
||||
raise ConnectorError(f"ocr_mode desconocido {ocr_mode!r}")
|
||||
self.files = files
|
||||
self.target = target
|
||||
self.domain = target.split(".", 1)[0]
|
||||
self.subject = subject_for(entity)
|
||||
self.foreign = foreign_subjects_for(entity)
|
||||
# The entity's column for the extraction version that filled it, when it has one.
|
||||
self.nlp_field = next((name for name in entity.schema.model_fields if name.endswith("_nlp_version")), None)
|
||||
self.ranker = _ranker(self.domain)
|
||||
self.specs = field_specs_for(entity, key_pattern=key_pattern)
|
||||
self.key_field = key_field_for(entity)
|
||||
self.segmentation = segmentation
|
||||
@@ -99,19 +145,37 @@ class DocumentConnector(DataFrameConnector):
|
||||
self.ocr_mode = ocr_mode
|
||||
self.key_pattern = key_pattern
|
||||
self.overrides = {str(k): v for k, v in (overrides or {}).items()}
|
||||
self.source_fields = {str(k): v for k, v in (source_fields or {}).items()}
|
||||
self.record_keys = {str(k): str(v) for k, v in (record_keys or {}).items()}
|
||||
self.include_pattern = _compile_filter(include_pattern, "include_pattern")
|
||||
self.exclude_pattern = _compile_filter(exclude_pattern, "exclude_pattern")
|
||||
self.skipped: list[dict[str, str]] = []
|
||||
known = {spec.name for spec in self.specs}
|
||||
unknown = sorted({name for values in self.source_fields.values() for name in values} - known)
|
||||
if unknown:
|
||||
raise ConnectorError(f"fields desconocidos para {target}: {', '.join(unknown)}")
|
||||
self._df: pd.DataFrame | None = None
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "DocumentConnector":
|
||||
files = [(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)]
|
||||
if payload.get("sql"):
|
||||
documents = _files_from_sql(payload["sql"])
|
||||
else:
|
||||
documents = DocumentBatch(
|
||||
files=[(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)]
|
||||
)
|
||||
return cls(
|
||||
files,
|
||||
documents.files,
|
||||
target=payload["target"],
|
||||
segmentation=payload.get("segmentation", "auto"),
|
||||
pages_per_record=payload.get("pages_per_record", 1),
|
||||
ocr_mode=payload.get("ocr_mode", "auto"),
|
||||
key_pattern=payload.get("key_pattern") or None,
|
||||
overrides=payload.get("overrides"),
|
||||
source_fields=documents.source_fields,
|
||||
record_keys=documents.record_keys,
|
||||
include_pattern=payload.get("include_pattern") or None,
|
||||
exclude_pattern=payload.get("exclude_pattern") or None,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@@ -123,41 +187,119 @@ class DocumentConnector(DataFrameConnector):
|
||||
|
||||
@property
|
||||
def records(self) -> list[ExtractedRecord]:
|
||||
return _CACHE.get_or_compute(self._cache_key(), self._extract)
|
||||
records, self.skipped = _CACHE.get_or_compute(self._cache_key(), self._extract)
|
||||
return records
|
||||
|
||||
def _extract(self) -> list[ExtractedRecord]:
|
||||
try:
|
||||
documents = [read_document(name, raw, ocr_mode=self.ocr_mode) for name, raw in self.files]
|
||||
except ExtractionError as exc:
|
||||
raise ConnectorError(str(exc)) from exc
|
||||
def _extract(self) -> tuple[list[ExtractedRecord], list[dict[str, str]]]:
|
||||
documents, skipped = [], []
|
||||
for name, raw in self.files:
|
||||
try:
|
||||
document = read_document(name, raw, ocr_mode=self.ocr_mode)
|
||||
except ExtractionError as exc:
|
||||
skipped.append({"document": name, "reason": f"ilegible: {exc}"})
|
||||
continue
|
||||
reason = self._filtered_out(document)
|
||||
if reason:
|
||||
skipped.append({"document": name, "reason": reason})
|
||||
continue
|
||||
documents.append(document)
|
||||
if not documents:
|
||||
detail = "; ".join(f"{s['document']}: {s['reason']}" for s in skipped[:5])
|
||||
raise ConnectorError(f"ningún documento se pudo usar ({detail})")
|
||||
segmenter = make_segmenter(
|
||||
self.segmentation,
|
||||
key=next((s for s in self.specs if s.name == self.key_field), None),
|
||||
pages_per_record=self.pages_per_record,
|
||||
)
|
||||
return DocumentExtractor(self.specs, key_field=self.key_field, segmenter=segmenter).extract(documents)
|
||||
records = DocumentExtractor(
|
||||
self.specs, key_field=self.key_field, segmenter=segmenter, subject=self.subject, foreign=self.foreign, ranker=self.ranker
|
||||
).extract(documents, source_fields=self.source_fields, record_keys=self.record_keys)
|
||||
return records, skipped
|
||||
|
||||
@property
|
||||
def nlp_version(self) -> str:
|
||||
"""The extraction code's version and the ranker's (`extraccion:<n>`), when one was used."""
|
||||
try:
|
||||
code = package_version("extraction")
|
||||
except PackageNotFoundError:
|
||||
code = "dev"
|
||||
return f"extraction {code}" + (f" + {self.ranker.version}" if self.ranker is not None and self.ranker.version else "")
|
||||
|
||||
def _filtered_out(self, document) -> str | None:
|
||||
"""Why a document is left out by `include_pattern`/`exclude_pattern`,
|
||||
matched case- and accent-insensitively against all of its text,
|
||||
so a source mixing several kinds of report feeds each target only
|
||||
its own."""
|
||||
text = "\n".join(page.text for page in document.pages)
|
||||
plain = _unaccented(text)
|
||||
if self.include_pattern and not (self.include_pattern.search(text) or self.include_pattern.search(plain)):
|
||||
return "no coincide con include_pattern"
|
||||
if self.exclude_pattern and (self.exclude_pattern.search(text) or self.exclude_pattern.search(plain)):
|
||||
return "coincide con exclude_pattern"
|
||||
return None
|
||||
|
||||
def _cache_key(self) -> str:
|
||||
digest = hashlib.sha256()
|
||||
for name, raw in self.files:
|
||||
digest.update(name.encode())
|
||||
digest.update(hashlib.sha256(raw).digest())
|
||||
config = [self.target, self.segmentation, self.pages_per_record, self.ocr_mode, self.key_pattern]
|
||||
digest.update(json.dumps(config).encode())
|
||||
config = [
|
||||
self.target,
|
||||
self.nlp_version,
|
||||
self.segmentation,
|
||||
self.pages_per_record,
|
||||
self.ocr_mode,
|
||||
self.key_pattern,
|
||||
self.source_fields,
|
||||
self.record_keys,
|
||||
self.include_pattern.pattern if self.include_pattern else None,
|
||||
self.exclude_pattern.pattern if self.exclude_pattern else None,
|
||||
]
|
||||
digest.update(json.dumps(config, sort_keys=True, default=str).encode())
|
||||
return digest.hexdigest()
|
||||
|
||||
# -- rows -----------------------------------------------------------------
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
if self._df is None:
|
||||
columns = [spec.name for spec in self.specs] + [DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN]
|
||||
columns = (
|
||||
[spec.name for spec in self.specs]
|
||||
+ ([self.nlp_field] if self.nlp_field else [])
|
||||
+ self.caption_columns()
|
||||
+ [DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN]
|
||||
)
|
||||
rows = [self._row(index, record) for index, record in enumerate(self.records)]
|
||||
self._df = pd.DataFrame(rows, columns=columns, dtype=object)
|
||||
return self._df
|
||||
|
||||
def caption_columns(self) -> list[str]:
|
||||
"""Every caption the documents print that no field of the target
|
||||
claims, in the order first seen: columns of their own, mappable
|
||||
and usable in derived fields like any column of a table."""
|
||||
reserved = {spec.name for spec in self.specs} | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN}
|
||||
columns: list[str] = []
|
||||
for record in self.records:
|
||||
for found in record.discovered:
|
||||
name = _caption_column(found.caption, reserved)
|
||||
if name not in columns:
|
||||
columns.append(name)
|
||||
return columns
|
||||
|
||||
def record_rows(self) -> Iterator[tuple[dict[str, Any], list[str]]]:
|
||||
"""Each record's row (overrides applied, its captions as columns,
|
||||
its pages as `documento`) with the names of the documents it was
|
||||
read from."""
|
||||
for index, record in enumerate(self.records):
|
||||
yield self._row(index, record), [source.document for source in record.sources]
|
||||
|
||||
def _row(self, index: int, record: ExtractedRecord) -> dict[str, Any]:
|
||||
row: dict[str, Any] = record.row()
|
||||
reserved = {spec.name for spec in self.specs} | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN}
|
||||
for found in record.discovered:
|
||||
row.setdefault(_caption_column(found.caption, reserved), found.value)
|
||||
row.update(self.overrides.get(str(index), {}))
|
||||
if self.nlp_field and record.values:
|
||||
row[self.nlp_field] = self.nlp_version
|
||||
row[DOCUMENT_COLUMN] = self._record_pdf(record)
|
||||
row[IMAGE_COLUMN] = self._record_image(record)
|
||||
row[CONFIDENCE_COLUMN] = round(record.confidence, 3)
|
||||
@@ -207,7 +349,13 @@ class DocumentConnector(DataFrameConnector):
|
||||
"index": index,
|
||||
"key": record.key,
|
||||
"confidence": round(record.confidence, 3),
|
||||
"on_topic": record.on_topic,
|
||||
"fields": fields,
|
||||
"alternatives": {
|
||||
name: _alternatives(proposed, record.values.get(name))
|
||||
for name, proposed in record.candidates.items()
|
||||
if _alternatives(proposed, record.values.get(name))
|
||||
},
|
||||
"missing": [s.name for s in self.specs if s.required and s.name not in fields],
|
||||
"conflicts": [
|
||||
{"field": c.field, "kept": c.kept.to_dict(), "discarded": c.discarded.to_dict()}
|
||||
@@ -223,4 +371,109 @@ class DocumentConnector(DataFrameConnector):
|
||||
return report
|
||||
|
||||
def metadata(self) -> dict[str, Any]:
|
||||
return {"records": len(self.records), "key_field": self.key_field, "documents": [name for name, _ in self.files]}
|
||||
return {
|
||||
"records": len(self.records),
|
||||
"key_field": self.key_field,
|
||||
"documents": [name for name, _ in self.files],
|
||||
"skipped": self.skipped,
|
||||
"nlp_version": self.nlp_version,
|
||||
}
|
||||
|
||||
# -- learning -------------------------------------------------------------
|
||||
|
||||
def reviewed(self) -> list[tuple[ExtractedRecord, dict[str, Any]]]:
|
||||
"""The records a person corrected while reviewing, each with what is
|
||||
known to be right about it: the corrected fields, and every other
|
||||
field as it was extracted, since whoever corrected the record read
|
||||
it. Fields a correction emptied are known to be empty."""
|
||||
reviewed = []
|
||||
for index, record in enumerate(self.records):
|
||||
corrections = self.overrides.get(str(index))
|
||||
if not corrections:
|
||||
continue
|
||||
truth: dict[str, Any] = {name: value.value for name, value in record.values.items()}
|
||||
truth.update({name: (None if value in ("", None) else value) for name, value in corrections.items()})
|
||||
known = {spec.name for spec in self.specs}
|
||||
reviewed.append((record, {name: value for name, value in truth.items() if name in known}))
|
||||
return reviewed
|
||||
|
||||
def learning_examples(self) -> tuple[list, dict[str, int], int]:
|
||||
"""Examples for the ranker from the reviewed records
|
||||
(`extraction.nlp.ranking.examples_for`), per field how many right
|
||||
values no candidate had proposed, and how many records they came from."""
|
||||
examples: list = []
|
||||
unreachable: dict[str, int] = {}
|
||||
reviewed = self.reviewed()
|
||||
for record, truth in reviewed:
|
||||
examples.extend(examples_for(self.specs, record.candidates, truth))
|
||||
for name, value in truth.items():
|
||||
if value is not None and not any(same_value(c.value, value) for c in record.candidates.get(name, ())):
|
||||
unreachable[name] = unreachable.get(name, 0) + 1
|
||||
return examples, unreachable, len(reviewed)
|
||||
|
||||
|
||||
def _ranker(domain: str):
|
||||
"""The domain's extraction ranker in the model registry, or `None` (rank by
|
||||
confidence) when there is none or the registry can't be read."""
|
||||
try:
|
||||
from models.io.extraction_ranker import current
|
||||
|
||||
return current(domain)
|
||||
except Exception as exc: # noqa: BLE001 - extraction must work without the registry
|
||||
logger.warning("sin ranker de extracción para %s: %s", domain, exc)
|
||||
return None
|
||||
|
||||
|
||||
def _alternatives(proposed: list, chosen) -> list[dict[str, Any]]:
|
||||
"""The other values the extractors proposed for a field, best first, for a reviewer to pick from."""
|
||||
seen, found = set(), []
|
||||
for candidate in sorted(proposed, key=lambda c: -c.confidence):
|
||||
if chosen is not None and same_value(candidate.value, chosen.value):
|
||||
continue
|
||||
key = json.dumps(candidate.to_dict()["value"], default=str)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
found.append({**candidate.to_dict(), "confidence": round(candidate.confidence, 3)})
|
||||
return found[:5]
|
||||
|
||||
|
||||
def _caption_column(caption: str, reserved: set[str]) -> str:
|
||||
"""A discovered caption as a column name, kept apart from the target's
|
||||
own fields and the connector's bookkeeping columns."""
|
||||
name = " ".join(caption.split())
|
||||
return f"texto: {name}" if name in reserved else name
|
||||
|
||||
|
||||
def _compile_filter(pattern: str | None, name: str) -> re.Pattern | None:
|
||||
if not pattern:
|
||||
return None
|
||||
try:
|
||||
return re.compile(pattern, re.I)
|
||||
except re.error as exc:
|
||||
raise ConnectorError(f"{name} no es una expresión regular válida: {exc}") from exc
|
||||
|
||||
|
||||
def _unaccented(text: str) -> str:
|
||||
return "".join(ch for ch in unicodedata.normalize("NFKD", text) if not unicodedata.combining(ch))
|
||||
|
||||
|
||||
DOCUMENT_OPTIONS = ("segmentation", "pages_per_record", "ocr_mode", "key_pattern", "overrides", "include_pattern", "exclude_pattern")
|
||||
|
||||
|
||||
def document_options(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
"""The extraction settings `DocumentConnector` takes, out of a request."""
|
||||
return {name: raw[name] for name in DOCUMENT_OPTIONS if raw.get(name) not in (None, "")}
|
||||
|
||||
|
||||
def connector_for_batch(batch: DocumentBatch, target: str, options: dict[str, Any]) -> "DocumentConnector":
|
||||
"""A `DocumentConnector` over documents read from a source's columns,
|
||||
their row values restricted to the fields extraction knows."""
|
||||
entity = ENTITY_REGISTRY.get(target)
|
||||
if entity is None:
|
||||
raise ConnectorError(f"destino desconocido: {target!r}")
|
||||
known = {spec.name for spec in field_specs_for(entity)}
|
||||
source_fields = {name: {k: v for k, v in values.items() if k in known} for name, values in batch.source_fields.items()}
|
||||
return DocumentConnector(
|
||||
batch.files, target=target, source_fields=source_fields, record_keys=batch.record_keys, **document_options(options)
|
||||
)
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Documents stored in the columns of any tabular source: a SQL table or
|
||||
query, a CSV or Excel sheet, a JSON list. Each non-empty cell of a document
|
||||
column becomes one document; the rest of its row travels with it as values
|
||||
the extraction must trust over the page, and an optional grouping decides
|
||||
which documents form one record.
|
||||
|
||||
A cell may hold the file itself (binary), the same file written as hex or
|
||||
base64 text, or plain text; `document_bytes` tells them apart.
|
||||
"""
|
||||
import base64
|
||||
import binascii
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Iterable
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.mapping.derived import Derivation, rule_from
|
||||
|
||||
_HEX = re.compile(r"^(?:0x)?(?:[0-9a-fA-F]{2})+$")
|
||||
_BASE64 = re.compile(r"^[A-Za-z0-9+/\r\n]+={0,2}$")
|
||||
DOCUMENT_MAGIC = (b"%PDF", b"\x89PNG", b"\xff\xd8\xff", b"II*\x00", b"MM\x00*", b"BM", b"RIFF", b"GIF8")
|
||||
|
||||
|
||||
def document_bytes(raw: Any) -> bytes:
|
||||
"""A stored document as bytes. Binary values pass through; text is
|
||||
checked for a binary file written out as hex or base64 before being
|
||||
taken as plain UTF-8 text."""
|
||||
if isinstance(raw, memoryview):
|
||||
raw = raw.tobytes()
|
||||
if isinstance(raw, (bytes, bytearray)):
|
||||
return bytes(raw)
|
||||
text = str(raw).strip()
|
||||
if len(text) >= 16 and _HEX.match(text):
|
||||
decoded = bytes.fromhex(text[2:] if text[:2].lower() == "0x" else text)
|
||||
if decoded.startswith(DOCUMENT_MAGIC):
|
||||
return decoded
|
||||
if len(text) >= 16 and _BASE64.match(text):
|
||||
try:
|
||||
decoded = base64.b64decode(text, validate=False)
|
||||
except (binascii.Error, ValueError):
|
||||
decoded = b""
|
||||
if decoded.startswith(DOCUMENT_MAGIC):
|
||||
return decoded
|
||||
return text.encode("utf-8")
|
||||
|
||||
|
||||
def is_document(raw: Any) -> bool:
|
||||
"""Whether a cell holds a file a document reader opens (as opposed to
|
||||
a plain value), whatever way it was stored."""
|
||||
if raw is None or isinstance(raw, (int, float, bool)):
|
||||
return False
|
||||
return document_bytes(raw).startswith(DOCUMENT_MAGIC)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DocumentBatch:
|
||||
"""What the extractor receives: one `(name, bytes)` per document and,
|
||||
per document name, its authoritative values and the record it joins.
|
||||
`rows` and `row_numbers` keep, per document name, the values of the row
|
||||
it came from and that row's position (from 1)."""
|
||||
|
||||
files: list[tuple[str, bytes]] = field(default_factory=list)
|
||||
source_fields: dict[str, dict[str, Any]] = field(default_factory=dict)
|
||||
record_keys: dict[str, str] = field(default_factory=dict)
|
||||
rows: dict[str, dict[str, Any]] = field(default_factory=dict)
|
||||
row_numbers: dict[str, int] = field(default_factory=dict)
|
||||
without_documents: list[dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DocumentColumns:
|
||||
"""How to read documents out of a source's rows.
|
||||
|
||||
`columns`: the columns holding documents (one or several per row).
|
||||
`name_by`: names each row in reports (default: its row number).
|
||||
`group_by`: rows giving the same value form one record, apart from
|
||||
the same patient's other rows; without it, documents merge by the
|
||||
target's key field, as uploaded files do.
|
||||
`fields`: target fields filled from the row, trusted over the page.
|
||||
The last three take a column name, a list of columns or a `derived`
|
||||
rule (`webapi.imports.mapping.derived`)."""
|
||||
|
||||
columns: list[str]
|
||||
name_by: Derivation | None = None
|
||||
group_by: Derivation | None = None
|
||||
fields: dict[str, Derivation] = field(default_factory=dict)
|
||||
|
||||
@classmethod
|
||||
def parse(cls, raw: Any) -> "DocumentColumns":
|
||||
if not isinstance(raw, dict):
|
||||
raise ConnectorError("'documents' debe ser un objeto")
|
||||
columns = raw.get("columns", raw.get("column"))
|
||||
columns = [columns] if isinstance(columns, str) else list(columns or [])
|
||||
if not columns or not all(isinstance(column, str) and column for column in columns):
|
||||
raise ConnectorError("indique la columna (o columnas) con los documentos")
|
||||
fields = raw.get("fields") or {}
|
||||
if not isinstance(fields, dict):
|
||||
raise ConnectorError("'fields' debe ser un objeto {campo: columna o regla}")
|
||||
name_by = raw.get("name_by", raw.get("key_column"))
|
||||
group_by = raw.get("group_by", raw.get("group_column"))
|
||||
parsed = cls(
|
||||
columns=columns,
|
||||
name_by=rule_from(name_by) if name_by else None,
|
||||
group_by=rule_from(group_by) if group_by else None,
|
||||
fields={name: rule_from(rule, separator=" ") for name, rule in fields.items()},
|
||||
)
|
||||
roles = {"name_by (key_column)": [parsed.name_by], "group_by (group_column)": [parsed.group_by], "fields": list(parsed.fields.values())}
|
||||
for role, rules in roles.items():
|
||||
reused = set().union(*(rule.columns() for rule in rules if rule is not None)) & set(columns)
|
||||
if reused:
|
||||
raise ConnectorError(f"{sorted(reused)} contiene los documentos; no puede usarse también en {role}")
|
||||
return parsed
|
||||
|
||||
def columns_read_by_rules(self) -> set[str]:
|
||||
read: set[str] = set()
|
||||
for rule in [self.name_by, self.group_by, *self.fields.values()]:
|
||||
if rule is not None:
|
||||
read |= rule.columns()
|
||||
return read
|
||||
|
||||
def source_columns(self) -> set[str]:
|
||||
return set(self.columns) | self.columns_read_by_rules()
|
||||
|
||||
def assemble(
|
||||
self, raw_rows: Iterable[dict[str, Any]], mapped_rows: Iterable[dict[str, Any]] | None = None
|
||||
) -> DocumentBatch:
|
||||
"""`raw_rows` keyed by source column; `mapped_rows`, when the source
|
||||
also has a mapping, the same rows already mapped to target fields,
|
||||
whose values join `fields` as values to trust."""
|
||||
batch = DocumentBatch()
|
||||
seen: dict[str, int] = {}
|
||||
mapped = iter(mapped_rows) if mapped_rows is not None else None
|
||||
for number, raw in enumerate(raw_rows, start=1):
|
||||
values = dict(next(mapped)) if mapped is not None else {}
|
||||
values.update({name: rule.apply(raw) for name, rule in self.fields.items()})
|
||||
values = {name: value for name, value in values.items() if not _blank(value)}
|
||||
contents = [(column, raw.get(column)) for column in self.columns if not _blank(raw.get(column))]
|
||||
if not contents:
|
||||
batch.without_documents.append(values)
|
||||
continue
|
||||
base = _text(self.name_by.apply(raw)) if self.name_by else ""
|
||||
base = base or str(number)
|
||||
group = _text(self.group_by.apply(raw)) if self.group_by else ""
|
||||
for column, content in contents:
|
||||
name = base if len(self.columns) == 1 else f"{base}:{column}"
|
||||
seen[name] = seen.get(name, 0) + 1
|
||||
if seen[name] > 1:
|
||||
name = f"{name}#{seen[name]}"
|
||||
batch.files.append((name, document_bytes(content)))
|
||||
batch.source_fields[name] = values
|
||||
batch.rows[name] = values
|
||||
batch.row_numbers[name] = number
|
||||
if group:
|
||||
batch.record_keys[name] = group
|
||||
return batch
|
||||
|
||||
|
||||
def _blank(value: Any) -> bool:
|
||||
return value is None or (isinstance(value, str) and not value.strip())
|
||||
|
||||
|
||||
def _text(value: Any) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
value = int(value)
|
||||
return str(value).strip()
|
||||
@@ -1,4 +1,3 @@
|
||||
from datetime import date, timedelta
|
||||
from pathlib import PurePath
|
||||
from typing import Any
|
||||
|
||||
@@ -11,15 +10,12 @@ from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
|
||||
MAX_LISTED_EVENTS = 20
|
||||
|
||||
|
||||
@register_connector
|
||||
class EdfConnector(FileConnector):
|
||||
"""EEG recordings (`.edf`), one row per file, shaped for `tea.EegEstudio`:
|
||||
patient and dates from the header, an estimated background rhythm from
|
||||
the posterior channels, a text summary of the recording, and the file
|
||||
itself (column `estudio`, stored in `eeg_estudio.eeg_estudio`)."""
|
||||
"""EEG recordings (`.edf`), one row per file, shaped for `tea.Eeg`: the laboratory's study id, the patient
|
||||
and the study date from the header, the channels and duration of the recording, and the file itself (column
|
||||
`estudio`, stored in `eeg.eeg_estudio`). The quality criteria, sleep and metrics are the EEG analysis'."""
|
||||
|
||||
kind = "edf"
|
||||
label = "EEG (EDF)"
|
||||
@@ -57,49 +53,12 @@ class EdfConnector(FileConnector):
|
||||
eeg = EegRecording.read(raw)
|
||||
except ExtractionError as exc:
|
||||
raise ConnectorError(f"{name}: {exc}") from exc
|
||||
patient = eeg.patient
|
||||
study_date = eeg.start.date() if eeg.start else None
|
||||
rhythm = eeg.background_rhythm()
|
||||
return {
|
||||
"id_registro_laboratorio": eeg.recording_fields["admin_code"] or PurePath(name).stem,
|
||||
"paciente": patient.code,
|
||||
"sexo": patient.sex,
|
||||
"fecha_nacimiento_declarada": patient.birthdate,
|
||||
"edad_meses": age_in_months(patient.birthdate, study_date),
|
||||
"fecha_estudio": study_date,
|
||||
"duracion_min": round(eeg.duration_seconds / 60) if eeg.duration_seconds else None,
|
||||
"ritmo_base_frecuencia": rhythm["frequency_hz"],
|
||||
"ritmo_base_amplitud": rhythm["amplitude_uv"],
|
||||
"descripcion_senal": describe(eeg),
|
||||
"paciente": eeg.patient.code,
|
||||
"fecha_estudio": eeg.start.date() if eeg.start else None,
|
||||
"canales": len(eeg.channels),
|
||||
"duracion_min": round(eeg.duration_seconds / 60, 1) if eeg.duration_seconds else None,
|
||||
"archivo": name,
|
||||
"estudio": raw,
|
||||
}
|
||||
|
||||
|
||||
def describe(eeg: EegRecording) -> str:
|
||||
channels = eeg.channels
|
||||
parts = [
|
||||
f"{eeg.variant}, {len(channels)} canales a {channels[0].sample_rate:g} Hz" if channels else eeg.variant,
|
||||
f"duración {timedelta(seconds=round(eeg.duration_seconds))}",
|
||||
"montaje: " + ", ".join(c.label for c in channels),
|
||||
]
|
||||
fields = eeg.recording_fields
|
||||
if fields["equipment"]:
|
||||
parts.append(f"equipo: {fields['equipment']}")
|
||||
if fields["technician"]:
|
||||
parts.append(f"técnico: {fields['technician']}")
|
||||
events = eeg.annotations()
|
||||
if events:
|
||||
listed = "; ".join(f"{timedelta(seconds=round(e.onset_seconds))} {e.text}" for e in events[:MAX_LISTED_EVENTS])
|
||||
more = f" (+{len(events) - MAX_LISTED_EVENTS})" if len(events) > MAX_LISTED_EVENTS else ""
|
||||
parts.append(f"eventos: {listed}{more}")
|
||||
return ". ".join(parts) + "."
|
||||
|
||||
|
||||
def age_in_months(birthdate: date | None, on: date | None) -> float | None:
|
||||
if birthdate is None or on is None or on < birthdate:
|
||||
return None
|
||||
months = (on.year - birthdate.year) * 12 + (on.month - birthdate.month)
|
||||
if on.day < birthdate.day:
|
||||
months -= 1
|
||||
return float(months)
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
import datetime as _dt
|
||||
import importlib.util
|
||||
import re
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar, Iterator
|
||||
|
||||
import pandas as pd
|
||||
import sqlalchemy as sa
|
||||
import sqlglot
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from webapi.imports.connectors.base import Connector, PreviewResult, SourceColumn
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.sql_policy import SqlSourcePolicy
|
||||
from webapi.imports.connectors.sql_policy import SQLGLOT_DIALECTS, SqlSourcePolicy
|
||||
from webapi.imports.connectors.tabular import infer_type
|
||||
|
||||
|
||||
@@ -27,6 +29,7 @@ class SqlEngine:
|
||||
driver_module: str
|
||||
description: str = ""
|
||||
default_schema: str | None = None
|
||||
supports_instance_name: bool = False
|
||||
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
@@ -67,7 +70,10 @@ class SqlConnector(Connector):
|
||||
SqlEngine("mysql", "MySQL", "mysql+pymysql", 3306, "pymysql", "Servidor MySQL 5.7+ / 8"),
|
||||
SqlEngine("mariadb", "MariaDB", "mariadb+pymysql", 3306, "pymysql", "Servidor MariaDB"),
|
||||
SqlEngine("postgresql", "PostgreSQL", "postgresql+psycopg2", 5432, "psycopg2", "Servidor PostgreSQL", "public"),
|
||||
SqlEngine("mssql", "SQL Server", "mssql+pymssql", 1433, "pymssql", "Microsoft SQL Server 2017+ / Azure SQL", "dbo"),
|
||||
SqlEngine(
|
||||
"mssql", "SQL Server", "mssql+pymssql", 1433, "pymssql",
|
||||
"Microsoft SQL Server 2017+ / Azure SQL", "dbo", supports_instance_name=True,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -102,15 +108,27 @@ class SqlConnector(Connector):
|
||||
raise ConnectorError(f"el controlador de {engine.label} ({engine.driver_module}) no está instalado en el servidor")
|
||||
if not server.get("host") or not server.get("database"):
|
||||
raise ConnectorError("se requieren el servidor (host) y la base de datos")
|
||||
|
||||
host, instance, embedded_port = _parse_server_address(str(server["host"]))
|
||||
if instance and not engine.supports_instance_name:
|
||||
raise ConnectorError(f"{engine.label} no admite una instancia con nombre ({server['host']!r}); indique solo el host y, si aplica, el puerto")
|
||||
|
||||
explicit_port = server.get("port")
|
||||
try:
|
||||
port = int(server.get("port") or engine.default_port)
|
||||
port = int(explicit_port) if explicit_port not in (None, "") else embedded_port
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ConnectorError("el puerto debe ser un número") from exc
|
||||
|
||||
if instance:
|
||||
host = f"{host}\\{instance}"
|
||||
elif port is None:
|
||||
port = engine.default_port
|
||||
|
||||
return sa.engine.URL.create(
|
||||
engine.drivername,
|
||||
username=server.get("user") or None,
|
||||
password=server.get("password") or None,
|
||||
host=server["host"],
|
||||
host=host,
|
||||
port=port,
|
||||
database=server["database"],
|
||||
)
|
||||
@@ -205,7 +223,7 @@ class SqlConnector(Connector):
|
||||
if self._table is not None:
|
||||
return sa.select(self._table).subquery("source")
|
||||
if self._query:
|
||||
return _text_subquery(self._query)
|
||||
return _text_subquery(self._query, self.get_dialect())
|
||||
raise ConnectorError("no hay tabla ni consulta seleccionada")
|
||||
|
||||
def _columns(self, names: list[str], rows: list[dict[str, Any]]) -> list[SourceColumn]:
|
||||
@@ -235,12 +253,87 @@ class SqlConnector(Connector):
|
||||
conn.rollback()
|
||||
|
||||
|
||||
def _text_subquery(query: str) -> sa.Subquery:
|
||||
_ADDRESS_SCHEME_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9+.\-:]*?://")
|
||||
_ADDRESS_PORT_SEPARATORS = (",", ":")
|
||||
|
||||
|
||||
def _parse_server_address(raw: str) -> tuple[str, str | None, int | None]:
|
||||
"""Tolerates the ways a server address arrives typed or pasted from
|
||||
a SQL client, a JDBC string or a connection URI instead of a bare host: a
|
||||
leading scheme (`jdbc:sqlserver://`, `postgresql://`, `tcp:`), a
|
||||
trailing path/query/property list, surrounding whitespace, a SQL
|
||||
Server named instance (`host\\instance`), and a port given as
|
||||
`host:port` or SQL Server's `host,port` / `host\\instance,port`.
|
||||
|
||||
Returns `(host, instance, port)`, with `instance` and `port` `None`
|
||||
when absent, so the caller can leave the port unset for a named
|
||||
instance instead of forcing the engine's default one.
|
||||
"""
|
||||
address = _ADDRESS_SCHEME_RE.sub("", raw.strip(), count=1)
|
||||
if address.lower().startswith("tcp:"):
|
||||
address = address[len("tcp:") :]
|
||||
for cut in ("/", "?", ";"):
|
||||
address = address.split(cut, 1)[0]
|
||||
address = address.strip()
|
||||
|
||||
instance: str | None = None
|
||||
if "\\" in address:
|
||||
host, instance = (part.strip() for part in address.split("\\", 1))
|
||||
else:
|
||||
host = address
|
||||
|
||||
tail = instance or host
|
||||
port: int | None = None
|
||||
for sep in _ADDRESS_PORT_SEPARATORS:
|
||||
if tail.count(sep) == 1:
|
||||
prefix, suffix = (part.strip() for part in tail.split(sep))
|
||||
if suffix.isdigit():
|
||||
tail, port = prefix, int(suffix)
|
||||
break
|
||||
|
||||
if instance:
|
||||
instance = tail or None
|
||||
else:
|
||||
host = tail
|
||||
|
||||
return host, (instance or None), port
|
||||
|
||||
|
||||
def _text_subquery(query: str, dialect: str | None = None) -> sa.Subquery:
|
||||
"""Wraps policy-checked SELECT text as a derived table, so SQLAlchemy
|
||||
composes LIMIT/TOP and COUNT(*) for whichever dialect the source speaks."""
|
||||
query = _without_trailing_order_by(query, dialect)
|
||||
return sa.select(sa.literal_column("*")).select_from(sa.text(f"({query}) AS source_query")).subquery("source")
|
||||
|
||||
|
||||
_ORDER_BY = re.compile(r"\bORDER\s+BY\b", re.I)
|
||||
|
||||
|
||||
def _without_trailing_order_by(query: str, dialect: str | None) -> str:
|
||||
"""Drops a top-level `ORDER BY` that nothing limits: SQL Server refuses
|
||||
one inside a derived table, and row order means nothing to an import.
|
||||
Kept when TOP, LIMIT or OFFSET makes it choose the rows."""
|
||||
try:
|
||||
[root] = sqlglot.parse(query, read=SQLGLOT_DIALECTS.get(dialect, dialect))
|
||||
except Exception:
|
||||
return query
|
||||
if root is None or not root.args.get("order") or root.args.get("limit") or root.args.get("offset"):
|
||||
return query
|
||||
depth, quote, cut = 0, None, None
|
||||
for position, char in enumerate(query):
|
||||
if quote:
|
||||
quote = None if char == quote else quote
|
||||
elif char in "'\"[`":
|
||||
quote = "]" if char == "[" else char
|
||||
elif char == "(":
|
||||
depth += 1
|
||||
elif char == ")":
|
||||
depth -= 1
|
||||
elif depth == 0 and _ORDER_BY.match(query, position):
|
||||
cut = position
|
||||
return query[:cut].rstrip() if cut is not None else query
|
||||
|
||||
|
||||
def _sa_type_to_kind(sa_type: sa.types.TypeEngine) -> str:
|
||||
try:
|
||||
python_type = sa_type.python_type
|
||||
|
||||
@@ -22,7 +22,7 @@ from webapi.imports.connectors.errors import ConnectorError
|
||||
_DEFAULT_DIALECTS = "mysql,mariadb,postgresql,mssql"
|
||||
_DEFAULT_PORTS = {"mysql": 3306, "mariadb": 3306, "postgresql": 5432, "mssql": 1433}
|
||||
# SQLAlchemy dialect name -> sqlglot's name for it, where they differ.
|
||||
_SQLGLOT_DIALECTS = {"postgresql": "postgres", "mssql": "tsql", "mariadb": "mysql"}
|
||||
SQLGLOT_DIALECTS = {"postgresql": "postgres", "mssql": "tsql", "mariadb": "mysql"}
|
||||
# Anything that writes, wherever it sits in the tree: a top-level
|
||||
# `SELECT ... INTO table`/`INTO OUTFILE`, or a writable CTE
|
||||
# (`WITH t AS (DELETE FROM x RETURNING *) SELECT * FROM t` still parses as a
|
||||
@@ -73,7 +73,7 @@ class SqlSourcePolicy:
|
||||
if not statement:
|
||||
raise ConnectorError("la consulta no puede estar vacía")
|
||||
try:
|
||||
parsed = [node for node in sqlglot.parse(statement, read=_SQLGLOT_DIALECTS.get(dialect, dialect)) if node is not None]
|
||||
parsed = [node for node in sqlglot.parse(statement, read=SQLGLOT_DIALECTS.get(dialect, dialect)) if node is not None]
|
||||
except sqlglot.errors.ParseError as exc:
|
||||
raise ConnectorError(f"la consulta no es SQL válido: {exc}") from exc
|
||||
if len(parsed) != 1:
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
"""Target fields computed from one or more source columns, for sources whose
|
||||
columns don't line up one-to-one with the target: a name and surnames kept
|
||||
apart where the target wants one full name, or the reverse; an id spread
|
||||
over two columns; a code that must be read out of a longer text.
|
||||
|
||||
A source's `derived` maps each target field to one rule,
|
||||
`{"op": <name>, ...params}`, plus the optional `case` (`upper`, `lower`,
|
||||
`title`) applied to the result. To add an operation, subclass `Derivation`,
|
||||
declare its `params` and register it with `@register_derivation`.
|
||||
"""
|
||||
import re
|
||||
import string
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Param:
|
||||
"""One parameter of an operation, described so a client can build its form."""
|
||||
|
||||
name: str
|
||||
kind: str # column | columns | text | integer | mapping | boolean
|
||||
label: str
|
||||
required: bool = True
|
||||
default: Any = None
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {"name": self.name, "kind": self.kind, "label": self.label, "required": self.required, "default": self.default}
|
||||
|
||||
|
||||
CASES = {"upper": str.upper, "lower": str.lower, "title": str.title}
|
||||
|
||||
|
||||
class Derivation(ABC):
|
||||
op: ClassVar[str]
|
||||
label: ClassVar[str]
|
||||
description: ClassVar[str]
|
||||
params: ClassVar[tuple[Param, ...]]
|
||||
|
||||
def __init__(self, rule: dict[str, Any]):
|
||||
self.args: dict[str, Any] = {}
|
||||
for param in self.params:
|
||||
value = rule.get(param.name, param.default)
|
||||
if param.required and _blank(value):
|
||||
raise ConnectorError(f"la regla {self.op!r} requiere {param.name!r}")
|
||||
if param.kind == "columns" and value is not None and not isinstance(value, list):
|
||||
raise ConnectorError(f"{param.name!r} debe ser una lista de columnas")
|
||||
self.args[param.name] = value
|
||||
self.case = rule.get("case") or None
|
||||
if self.case is not None and self.case not in CASES:
|
||||
raise ConnectorError(f"case desconocido {self.case!r} (disponibles: {', '.join(CASES)})")
|
||||
|
||||
@abstractmethod
|
||||
def columns(self) -> set[str]:
|
||||
"""The source columns this rule reads."""
|
||||
|
||||
@abstractmethod
|
||||
def compute(self, row: dict[str, Any]) -> Any: ...
|
||||
|
||||
def apply(self, row: dict[str, Any]) -> Any:
|
||||
value = self.compute(row)
|
||||
if isinstance(value, str):
|
||||
value = " ".join(value.split())
|
||||
if self.case:
|
||||
value = CASES[self.case](value)
|
||||
return value or None
|
||||
return value
|
||||
|
||||
@classmethod
|
||||
def describe(cls) -> dict[str, Any]:
|
||||
return {
|
||||
"op": cls.op,
|
||||
"label": cls.label,
|
||||
"description": cls.description,
|
||||
"params": [param.to_dict() for param in cls.params],
|
||||
}
|
||||
|
||||
|
||||
DERIVATIONS: dict[str, type[Derivation]] = {}
|
||||
|
||||
|
||||
def register_derivation(cls: type[Derivation]) -> type[Derivation]:
|
||||
DERIVATIONS[cls.op] = cls
|
||||
return cls
|
||||
|
||||
|
||||
def build_derivation(rule: Any) -> Derivation:
|
||||
if not isinstance(rule, dict):
|
||||
raise ConnectorError("cada regla de 'derived' debe ser un objeto")
|
||||
cls = DERIVATIONS.get(rule.get("op", ""))
|
||||
if cls is None:
|
||||
raise ConnectorError(f"operación desconocida {rule.get('op')!r} (disponibles: {', '.join(DERIVATIONS)})")
|
||||
return cls(rule)
|
||||
|
||||
|
||||
def _blank(value: Any) -> bool:
|
||||
return value is None or (isinstance(value, str) and not value.strip()) or value == [] or value == {}
|
||||
|
||||
|
||||
def _index(value: Any) -> int | None:
|
||||
if value in (None, ""):
|
||||
return None
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ConnectorError(f"se esperaba un número entero, no {value!r}") from exc
|
||||
|
||||
|
||||
def _text(value: Any) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
value = int(value)
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
@register_derivation
|
||||
class Column(Derivation):
|
||||
op = "column"
|
||||
label = "Columna"
|
||||
description = "El valor de una columna, tal cual."
|
||||
params = (Param("column", "column", "Columna"),)
|
||||
|
||||
def columns(self) -> set[str]:
|
||||
return {self.args["column"]}
|
||||
|
||||
def compute(self, row: dict[str, Any]) -> Any:
|
||||
return row.get(self.args["column"])
|
||||
|
||||
|
||||
@register_derivation
|
||||
class Concat(Derivation):
|
||||
op = "concat"
|
||||
label = "Unir columnas"
|
||||
description = "Une los valores no vacíos de varias columnas, en orden, con un separador."
|
||||
params = (
|
||||
Param("columns", "columns", "Columnas"),
|
||||
Param("separator", "text", "Separador", required=False, default=" "),
|
||||
)
|
||||
|
||||
def columns(self) -> set[str]:
|
||||
return set(self.args["columns"])
|
||||
|
||||
def compute(self, row: dict[str, Any]) -> Any:
|
||||
parts = [_text(row.get(column)) for column in self.args["columns"]]
|
||||
separator = self.args["separator"] if self.args["separator"] is not None else " "
|
||||
return separator.join(part for part in parts if part)
|
||||
|
||||
|
||||
@register_derivation
|
||||
class Template(Derivation):
|
||||
op = "template"
|
||||
label = "Plantilla"
|
||||
description = "Arma un texto con columnas entre llaves: `{Nombre} {Apellido}`. Las columnas vacías se omiten."
|
||||
params = (Param("template", "text", "Plantilla"),)
|
||||
|
||||
def __init__(self, rule: dict[str, Any]):
|
||||
super().__init__(rule)
|
||||
try:
|
||||
self._names = [name for _, name, _, _ in string.Formatter().parse(self.args["template"]) if name]
|
||||
except ValueError as exc:
|
||||
raise ConnectorError(f"plantilla inválida: {exc}") from exc
|
||||
|
||||
def columns(self) -> set[str]:
|
||||
return set(self._names)
|
||||
|
||||
def compute(self, row: dict[str, Any]) -> Any:
|
||||
values = {name: _text(row.get(name)) for name in self._names}
|
||||
return string.Formatter().vformat(self.args["template"], (), _Fill(values))
|
||||
|
||||
|
||||
class _Fill(dict):
|
||||
def __missing__(self, key: str) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
@register_derivation
|
||||
class Split(Derivation):
|
||||
op = "split"
|
||||
label = "Tomar partes"
|
||||
description = (
|
||||
"Separa el valor de una columna y toma las partes de `start` a `stop` "
|
||||
"(se cuentan desde 0; negativas desde el final): de un nombre completo, "
|
||||
"el primer apellido es `start=-2, stop=-1`."
|
||||
)
|
||||
params = (
|
||||
Param("column", "column", "Columna"),
|
||||
Param("separator", "text", "Separador (vacío: espacios)", required=False, default=""),
|
||||
Param("start", "integer", "Desde", required=False, default=0),
|
||||
Param("stop", "integer", "Hasta (sin incluir)", required=False, default=None),
|
||||
)
|
||||
|
||||
def columns(self) -> set[str]:
|
||||
return {self.args["column"]}
|
||||
|
||||
def compute(self, row: dict[str, Any]) -> Any:
|
||||
text = _text(row.get(self.args["column"]))
|
||||
if not text:
|
||||
return None
|
||||
separator = self.args["separator"] or None
|
||||
parts = text.split(separator) if separator else text.split()
|
||||
start, stop = (_index(self.args[name]) for name in ("start", "stop"))
|
||||
return (separator or " ").join(part.strip() for part in parts[start:stop] if part.strip())
|
||||
|
||||
|
||||
@register_derivation
|
||||
class Coalesce(Derivation):
|
||||
op = "coalesce"
|
||||
label = "Primera con valor"
|
||||
description = "El valor de la primera columna, en orden, que no esté vacía."
|
||||
params = (Param("columns", "columns", "Columnas"),)
|
||||
|
||||
def columns(self) -> set[str]:
|
||||
return set(self.args["columns"])
|
||||
|
||||
def compute(self, row: dict[str, Any]) -> Any:
|
||||
for column in self.args["columns"]:
|
||||
value = row.get(column)
|
||||
if not _blank(value):
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
@register_derivation
|
||||
class Extract(Derivation):
|
||||
op = "extract"
|
||||
label = "Extraer con patrón"
|
||||
description = "La parte del valor que coincide con una expresión regular (o su grupo `group`)."
|
||||
params = (
|
||||
Param("column", "column", "Columna"),
|
||||
Param("pattern", "text", "Expresión regular"),
|
||||
Param("group", "integer", "Grupo", required=False, default=0),
|
||||
)
|
||||
|
||||
def __init__(self, rule: dict[str, Any]):
|
||||
super().__init__(rule)
|
||||
try:
|
||||
self._regex = re.compile(self.args["pattern"], re.I)
|
||||
except re.error as exc:
|
||||
raise ConnectorError(f"expresión regular inválida: {exc}") from exc
|
||||
|
||||
def columns(self) -> set[str]:
|
||||
return {self.args["column"]}
|
||||
|
||||
def compute(self, row: dict[str, Any]) -> Any:
|
||||
match = self._regex.search(_text(row.get(self.args["column"])))
|
||||
if not match:
|
||||
return None
|
||||
try:
|
||||
return match.group(_index(self.args["group"]) or 0)
|
||||
except IndexError as exc:
|
||||
raise ConnectorError(f"la expresión no tiene el grupo {self.args['group']}") from exc
|
||||
|
||||
|
||||
@register_derivation
|
||||
class Translate(Derivation):
|
||||
op = "map"
|
||||
label = "Traducir valores"
|
||||
description = "Cambia cada valor por otro según una tabla (`M` → `Masculino`), sin distinguir mayúsculas ni espacios."
|
||||
params = (
|
||||
Param("column", "column", "Columna"),
|
||||
Param("values", "mapping", "Tabla de valores"),
|
||||
Param("keep_unmatched", "boolean", "Conservar los que no estén en la tabla", required=False, default=True),
|
||||
)
|
||||
|
||||
def __init__(self, rule: dict[str, Any]):
|
||||
super().__init__(rule)
|
||||
if not isinstance(self.args["values"], dict):
|
||||
raise ConnectorError("'values' debe ser un objeto")
|
||||
self._table = {_text(key).casefold(): value for key, value in self.args["values"].items()}
|
||||
|
||||
def columns(self) -> set[str]:
|
||||
return {self.args["column"]}
|
||||
|
||||
def compute(self, row: dict[str, Any]) -> Any:
|
||||
value = row.get(self.args["column"])
|
||||
key = _text(value).casefold()
|
||||
if key in self._table:
|
||||
return self._table[key]
|
||||
return value if self.args["keep_unmatched"] is not False else None
|
||||
|
||||
|
||||
def rule_from(value: Any, *, separator: str = " | ") -> Derivation:
|
||||
"""A rule given in short form: a column name, a list of columns (joined
|
||||
with `separator`) or a full rule object."""
|
||||
if isinstance(value, str):
|
||||
return Column({"column": value})
|
||||
if isinstance(value, list):
|
||||
return Concat({"columns": value, "separator": separator})
|
||||
return build_derivation(value)
|
||||
|
||||
|
||||
def parse_derived(raw: Any, fields: set[str]) -> dict[str, Derivation]:
|
||||
"""`{target_field: rule}` validated against the target's fields."""
|
||||
if raw in (None, {}):
|
||||
return {}
|
||||
if not isinstance(raw, dict):
|
||||
raise ConnectorError("'derived' debe ser un objeto {campo: regla}")
|
||||
unknown = sorted(set(raw) - fields)
|
||||
if unknown:
|
||||
raise ConnectorError(f"campos desconocidos en 'derived': {unknown}")
|
||||
return {field: rule_from(rule, separator=" ") for field, rule in raw.items()}
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Matching OCR-discovered captions against a project's catalog, and
|
||||
minting new catalog entries when nothing matches well enough.
|
||||
|
||||
`discover_captions` (Extraction) finds `caption: value` lines no known
|
||||
`FieldSpec` already explains. For each one, this module decides whether an
|
||||
existing `resultado_id` means the same thing closely enough to reuse
|
||||
(`rapidfuzz`, tolerant of how a hospital's own report wording differs from
|
||||
the catalog's own), or whether it's a field the catalog doesn't have yet —
|
||||
in which case it's added (`add_resultado`), never silently dropped.
|
||||
"""
|
||||
import re
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
|
||||
from rapidfuzz import fuzz, process
|
||||
|
||||
from extraction.nlp import DiscoveredField
|
||||
from extraction.nlp.text import find_date, fold
|
||||
from webapi.orchestration.reference.catalogs import Catalogo, add_resultado
|
||||
from webapi.orchestration.silver.procedures import valor_de_observacion
|
||||
|
||||
# `token_sort_ratio`, not `WRatio`: `WRatio`'s partial-alignment bonus scores
|
||||
# two short, unrelated captions that merely share common words ("de", "del")
|
||||
# too high for this use (two genuinely different captions can clear 80).
|
||||
# Lower than `extraction.nlp.extractors.FUZZY_LABEL_THRESHOLD` (0-100 scale
|
||||
# here, that one 0-1): a caption is free text, not a single known label
|
||||
# tolerating only OCR noise, so it varies more from the catalog's wording.
|
||||
CAPTION_MATCH_THRESHOLD = 80.0
|
||||
CAPTION_SCORER = fuzz.token_sort_ratio
|
||||
FALLBACK_ESTUDIO_ID = "documento_externo"
|
||||
FALLBACK_ESTUDIO_ETIQUETA = "Documento externo"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MatchedField:
|
||||
"""One discovered caption, resolved to a `resultado_id` (existing or
|
||||
just minted) with its value already shaped for `observacion`."""
|
||||
|
||||
resultado_id: str
|
||||
is_new: bool
|
||||
observacion: dict
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _NewResultado:
|
||||
resultado_id: str
|
||||
tipo_valor: str
|
||||
|
||||
|
||||
def match_or_mint(
|
||||
discovered: list[DiscoveredField],
|
||||
*,
|
||||
proyecto: str,
|
||||
catalogo: Catalogo,
|
||||
estudio_id: str | None = None,
|
||||
mint: bool = True,
|
||||
) -> list[MatchedField]:
|
||||
"""One `MatchedField` per discovered caption, in order. With
|
||||
`mint=False`, a caption nothing in the catalog matches is left out
|
||||
instead of being added to the catalog file.
|
||||
|
||||
`estudio_id`, when the caller already knows it (the row's own
|
||||
study-type column, resolved through `codigos_hospital`), scopes which
|
||||
resultados are tried first and which estudio a minted field joins;
|
||||
without it, every resultado in the catalog is a candidate and a new
|
||||
field's estudio is guessed the same way, or falls back to
|
||||
`documento_externo`.
|
||||
"""
|
||||
labels = _resultado_labels(catalogo, estudio_id)
|
||||
valid_codes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"}
|
||||
by_resultado_id = {r.resultado_id: r for r in catalogo.resultados}
|
||||
resolved = []
|
||||
for field in discovered:
|
||||
found = _best_match(field.caption, labels)
|
||||
if found is not None:
|
||||
resultado, is_new = by_resultado_id[found], False
|
||||
elif not mint:
|
||||
continue
|
||||
else:
|
||||
resultado = _mint(field, proyecto=proyecto, estudio_id=estudio_id, catalogo=catalogo)
|
||||
is_new = True
|
||||
value = _coerce_value(field.value, resultado.tipo_valor)
|
||||
observacion = valor_de_observacion(
|
||||
value,
|
||||
field.value,
|
||||
tipo_valor=resultado.tipo_valor,
|
||||
en_catalogo=lambda v, r=resultado.resultado_id: (r, v) in valid_codes,
|
||||
)
|
||||
resolved.append(MatchedField(resultado.resultado_id, is_new, observacion))
|
||||
return resolved
|
||||
|
||||
|
||||
def _resultado_labels(catalogo: Catalogo, estudio_id: str | None) -> dict[str, str]:
|
||||
resultados = catalogo.resultados
|
||||
if estudio_id is not None:
|
||||
of_estudio = [r for r in resultados if r.estudio_id == estudio_id]
|
||||
if of_estudio:
|
||||
resultados = of_estudio
|
||||
return {r.resultado_id: fold(r.etiqueta) for r in resultados}
|
||||
|
||||
|
||||
def _best_match(caption: str, labels: dict[str, str]) -> str | None:
|
||||
if not labels:
|
||||
return None
|
||||
found = process.extractOne(fold(caption), labels, scorer=CAPTION_SCORER, score_cutoff=CAPTION_MATCH_THRESHOLD)
|
||||
return found[2] if found is not None else None
|
||||
|
||||
|
||||
def _mint(field: DiscoveredField, *, proyecto: str, estudio_id: str | None, catalogo: Catalogo) -> _NewResultado:
|
||||
estudio = estudio_id
|
||||
estudio_etiqueta = None
|
||||
if estudio is None:
|
||||
estudio_labels = {e.estudio_id: fold(e.etiqueta) for e in catalogo.estudios}
|
||||
found = process.extractOne(fold(field.caption), estudio_labels, scorer=CAPTION_SCORER, score_cutoff=CAPTION_MATCH_THRESHOLD)
|
||||
estudio = found[2] if found is not None else None
|
||||
if estudio is None:
|
||||
estudio, estudio_etiqueta = FALLBACK_ESTUDIO_ID, FALLBACK_ESTUDIO_ETIQUETA
|
||||
tipo_valor = _infer_tipo_valor(field.value)
|
||||
resultado_id = add_resultado(
|
||||
proyecto,
|
||||
estudio_id=estudio,
|
||||
nombre=_slug(field.caption),
|
||||
etiqueta=field.caption.strip(),
|
||||
tipo_valor=tipo_valor,
|
||||
estudio_etiqueta=estudio_etiqueta,
|
||||
)
|
||||
return _NewResultado(resultado_id, tipo_valor)
|
||||
|
||||
|
||||
def _slug(text: str) -> str:
|
||||
without_accents = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("ascii")
|
||||
return re.sub(r"[^a-z0-9]+", "_", without_accents.lower()).strip("_") or "campo"
|
||||
|
||||
|
||||
def _infer_tipo_valor(value: str) -> str:
|
||||
if find_date(value) is not None:
|
||||
return "fecha"
|
||||
if _is_number(value):
|
||||
return "numero"
|
||||
return "texto"
|
||||
|
||||
|
||||
def _is_number(value: str) -> bool:
|
||||
try:
|
||||
float(value.strip().replace(",", "."))
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def _coerce_value(value: str, tipo_valor: str):
|
||||
if tipo_valor == "fecha":
|
||||
found = find_date(value)
|
||||
return found[0] if found else None
|
||||
if tipo_valor in ("numero", "booleano"):
|
||||
try:
|
||||
return float(value.strip().replace(",", "."))
|
||||
except ValueError:
|
||||
return None
|
||||
return value
|
||||
@@ -7,7 +7,7 @@ from datetime import date, datetime
|
||||
from enum import Enum
|
||||
from typing import Annotated, Any, Optional, Type
|
||||
|
||||
from pydantic import BeforeValidator, StringConstraints, ValidationInfo
|
||||
from pydantic import BeforeValidator, Field, StringConstraints, ValidationInfo
|
||||
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
from extraction import ExtractionError
|
||||
@@ -140,7 +140,7 @@ CodigoPostal = Annotated[str, StringConstraints(pattern=r"^[0-9]{5}$")]
|
||||
|
||||
|
||||
def edf_file(v: Any) -> Any:
|
||||
"""`eeg_estudio.eeg_estudio`: an EDF file MNE can open (TEA amendment).
|
||||
"""`eeg.eeg_estudio`: an EDF file MNE can open (TEA amendment).
|
||||
JSON sources may carry it base64-encoded."""
|
||||
if v is None or (isinstance(v, str) and not v.strip()):
|
||||
return None
|
||||
@@ -168,3 +168,9 @@ FlexDate = Annotated[Optional[date], BeforeValidator(coerce_date)]
|
||||
RequiredDate = Annotated[date, BeforeValidator(required_date)]
|
||||
PostalCode = Annotated[Optional[CodigoPostal], BeforeValidator(coerce_postal_code)]
|
||||
EdfFile = Annotated[Optional[bytes], BeforeValidator(edf_file)]
|
||||
|
||||
|
||||
def Bounded(kind: type, low: float | None = None, high: float | None = None): # noqa: N802 (used like a type)
|
||||
"""An optional number within [low, high], either bound open when None: a score or a count out of range is a
|
||||
validation error, not a stored value."""
|
||||
return Optional[Annotated[kind, Field(ge=low, le=high)]]
|
||||
|
||||
@@ -8,7 +8,17 @@ import typing
|
||||
from datetime import date, datetime
|
||||
|
||||
from extraction.nlp import FieldKind, FieldSpec
|
||||
from extraction.nlp.vocabulary import CLINICAL_TERMS, FREE_TEXT_FIELDS, PATTERNS, labels_for
|
||||
from extraction.nlp.vocabulary import (
|
||||
ANCHORS,
|
||||
CLINICAL_TERMS,
|
||||
FREE_TEXT_FIELDS,
|
||||
NEGATED_VALUES,
|
||||
PATTERNS,
|
||||
SEVERITY,
|
||||
SUBJECTS,
|
||||
UNITS,
|
||||
labels_for,
|
||||
)
|
||||
from webapi.imports.schemas.registry import EntitySpec
|
||||
|
||||
# Surrogate keys, stored files and OCR bookkeeping are never read from a document.
|
||||
@@ -42,11 +52,28 @@ def field_specs_for(entity: EntitySpec, *, key_pattern: str | None = None) -> li
|
||||
scan_free_text=name in FREE_TEXT_FIELDS or (pattern is not None and pattern == key_pattern),
|
||||
multiline=kind is FieldKind.TEXT and bool(_LONG_TEXT.search(name)),
|
||||
required=info.is_required(),
|
||||
anchors=ANCHORS.get(name, ()),
|
||||
severity=SEVERITY.get(name, ()),
|
||||
negated_value=NEGATED_VALUES.get(name),
|
||||
unit=UNITS.get(name),
|
||||
)
|
||||
)
|
||||
return specs
|
||||
|
||||
|
||||
def subject_for(entity: EntitySpec) -> tuple[str, ...]:
|
||||
"""What a document feeding this entity is about (`vocabulary.SUBJECTS`)."""
|
||||
return SUBJECTS.get(entity.model.__table__.name, ())
|
||||
|
||||
|
||||
def foreign_subjects_for(entity: EntitySpec) -> tuple[str, ...]:
|
||||
"""What documents feeding other entities are about, less this one's own terms."""
|
||||
own = set(subject_for(entity))
|
||||
if not own:
|
||||
return ()
|
||||
return tuple(sorted({term for table, terms in SUBJECTS.items() if table != entity.model.__table__.name for term in terms} - own))
|
||||
|
||||
|
||||
def key_field_for(entity: EntitySpec) -> str | None:
|
||||
"""The field that identifies whose record a page belongs to."""
|
||||
fields = entity.schema.model_fields
|
||||
|
||||
@@ -24,18 +24,14 @@ from persistance.cama import ordenes_estudio_repository as cama_ordenes_estudio_
|
||||
from persistance.cama import paciente_repository as cama_paciente_repository
|
||||
from persistance.repository import Repository
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from persistance.tea import antecedentes_maternos_gestacion_repository as tea_antecedentes_maternos_gestacion_repository
|
||||
from persistance.tea import eeg_estudio_repository as tea_eeg_estudio_repository
|
||||
from persistance.tea import eeg_segmento_repository as tea_eeg_segmento_repository
|
||||
from persistance.tea import evaluacion_psicologica_repository as tea_evaluacion_psicologica_repository
|
||||
from persistance.tea import instrumento_aplicado_repository as tea_instrumento_aplicado_repository
|
||||
from persistance.tea import nota_medica_repository as tea_nota_medica_repository
|
||||
from persistance.tea import ados2_repository as tea_ados2_repository
|
||||
from persistance.tea import eeg_metrica_electrodo_repository as tea_eeg_metrica_electrodo_repository
|
||||
from persistance.tea import eeg_metrica_repository as tea_eeg_metrica_repository
|
||||
from persistance.tea import eeg_repository as tea_eeg_repository
|
||||
from persistance.tea import evaluacion_neuropediatrica_repository as tea_evaluacion_neuropediatrica_repository
|
||||
from persistance.tea import mchat_repository as tea_mchat_repository
|
||||
from persistance.tea import ordenes_estudio_repository as tea_ordenes_estudio_repository
|
||||
from persistance.tea import pacientes_repository as tea_pacientes_repository
|
||||
from persistance.tea import parto_neonatal_repository as tea_parto_neonatal_repository
|
||||
from persistance.tea import (
|
||||
potenciales_evocados_auditivos_repository as tea_potenciales_evocados_auditivos_repository,
|
||||
)
|
||||
from webapi.imports.schemas.cacu.biometria_hematica import (
|
||||
BiometriaHematicaImportSchema as CacuBiometriaHematicaImportSchema,
|
||||
)
|
||||
@@ -62,22 +58,16 @@ from webapi.imports.schemas.cama.ordenes_estudio import (
|
||||
OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cama.paciente import PacienteImportSchema as CamaPacienteImportSchema
|
||||
from webapi.imports.schemas.tea.antecedentes_maternos_gestacion import (
|
||||
AntecedentesMaternosGestacionImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
|
||||
from webapi.imports.schemas.tea.eeg_segmento import EegSegmentoImportSchema
|
||||
from webapi.imports.schemas.tea.evaluacion_psicologica import EvaluacionPsicologicaImportSchema
|
||||
from webapi.imports.schemas.tea.instrumento_aplicado import InstrumentoAplicadoImportSchema
|
||||
from webapi.imports.schemas.tea.nota_medica import NotaMedicaImportSchema as TeaNotaMedicaImportSchema
|
||||
from webapi.imports.schemas.tea.ados2 import Ados2ImportSchema
|
||||
from webapi.imports.schemas.tea.eeg import EegImportSchema
|
||||
from webapi.imports.schemas.tea.eeg_metrica import EegMetricaImportSchema
|
||||
from webapi.imports.schemas.tea.eeg_metrica_electrodo import EegMetricaElectrodoImportSchema
|
||||
from webapi.imports.schemas.tea.evaluacion_neuropediatrica import EvaluacionNeuropediatricaImportSchema
|
||||
from webapi.imports.schemas.tea.mchat import MchatImportSchema
|
||||
from webapi.imports.schemas.tea.ordenes_estudio import (
|
||||
OrdenesEstudioImportSchema as TeaOrdenesEstudioImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.tea.pacientes import PacientesImportSchema
|
||||
from webapi.imports.schemas.tea.parto_neonatal import PartoNeonatalImportSchema
|
||||
from webapi.imports.schemas.tea.potenciales_evocados_auditivos import (
|
||||
PotencialesEvocadosAuditivosImportSchema,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -131,8 +121,7 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
"cacu.EpisodioClinico": EntitySpec(
|
||||
schema=CacuEpisodioClinicoImportSchema,
|
||||
repository=cacu_episodio_clinico_repository,
|
||||
# No hospital-visible identifier of its own, like EvaluacionPsicologica
|
||||
# or PartoNeonatal; a patient can have several episodes.
|
||||
# No hospital-visible identifier of its own; a patient can have several episodes.
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cama.Paciente": EntitySpec(
|
||||
@@ -175,48 +164,37 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
repository=tea_ordenes_estudio_repository,
|
||||
conflict_fields=("ord_id_hospital",),
|
||||
),
|
||||
"tea.NotaMedica": EntitySpec(
|
||||
schema=TeaNotaMedicaImportSchema,
|
||||
repository=tea_nota_medica_repository,
|
||||
conflict_fields=("nm_id_hospital",),
|
||||
"tea.Mchat": EntitySpec(
|
||||
schema=MchatImportSchema,
|
||||
repository=tea_mchat_repository,
|
||||
conflict_fields=("mch_id",),
|
||||
),
|
||||
"tea.EvaluacionPsicologica": EntitySpec(
|
||||
schema=EvaluacionPsicologicaImportSchema,
|
||||
repository=tea_evaluacion_psicologica_repository,
|
||||
conflict_fields=None,
|
||||
"tea.Ados2": EntitySpec(
|
||||
schema=Ados2ImportSchema,
|
||||
repository=tea_ados2_repository,
|
||||
conflict_fields=("ado_id",),
|
||||
),
|
||||
"tea.PotencialesEvocadosAuditivos": EntitySpec(
|
||||
schema=PotencialesEvocadosAuditivosImportSchema,
|
||||
repository=tea_potenciales_evocados_auditivos_repository,
|
||||
conflict_fields=None,
|
||||
"tea.EvaluacionNeuropediatrica": EntitySpec(
|
||||
schema=EvaluacionNeuropediatricaImportSchema,
|
||||
repository=tea_evaluacion_neuropediatrica_repository,
|
||||
conflict_fields=("neu_id",),
|
||||
),
|
||||
"tea.EegEstudio": EntitySpec(
|
||||
schema=EegEstudioImportSchema,
|
||||
repository=tea_eeg_estudio_repository,
|
||||
# The EDF file and its scanned report describe the same study; both
|
||||
# the `edf` connector (from the file's own admin code) and a
|
||||
# `document` source (read from the report text) populate this field,
|
||||
# so merge_duplicates/on_conflict=upsert can land them on one row.
|
||||
"tea.Eeg": EntitySpec(
|
||||
schema=EegImportSchema,
|
||||
repository=tea_eeg_repository,
|
||||
# The EDF file and its report describe the same study; the `edf` connector (from the file's own admin
|
||||
# code) and a `document` source both fill this field, so merge_duplicates/on_conflict=upsert land them on
|
||||
# one row.
|
||||
conflict_fields=("eeg_id_registro_laboratorio",),
|
||||
),
|
||||
"tea.EegSegmento": EntitySpec(
|
||||
schema=EegSegmentoImportSchema,
|
||||
repository=tea_eeg_segmento_repository,
|
||||
conflict_fields=None,
|
||||
"tea.EegMetrica": EntitySpec(
|
||||
schema=EegMetricaImportSchema,
|
||||
repository=tea_eeg_metrica_repository,
|
||||
conflict_fields=("met_id",),
|
||||
),
|
||||
"tea.InstrumentoAplicado": EntitySpec(
|
||||
schema=InstrumentoAplicadoImportSchema,
|
||||
repository=tea_instrumento_aplicado_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.AntecedentesMaternosGestacion": EntitySpec(
|
||||
schema=AntecedentesMaternosGestacionImportSchema,
|
||||
repository=tea_antecedentes_maternos_gestacion_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.PartoNeonatal": EntitySpec(
|
||||
schema=PartoNeonatalImportSchema,
|
||||
repository=tea_parto_neonatal_repository,
|
||||
conflict_fields=None,
|
||||
"tea.EegMetricaElectrodo": EntitySpec(
|
||||
schema=EegMetricaElectrodoImportSchema,
|
||||
repository=tea_eeg_metrica_electrodo_repository,
|
||||
conflict_fields=("mel_id",),
|
||||
),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Import schema for `core.tea.models.Ados2`: module, algorithm, CSS, classification and the 28 algorithm items.
|
||||
|
||||
The domain subtotals and the total aren't imported: they're sums of the items' algorithm scores."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import CLASIFICACION_ADOS2_ALIAS, ClasificacionAdos2, ModuloAdos2
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Bounded, Catalog, CatalogValue, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_MODULO_ADOS2_CATALOG = Catalog(ModuloAdos2)
|
||||
_CLASIFICACION_ADOS2_CATALOG = Catalog(ClasificacionAdos2, CLASIFICACION_ADOS2_ALIAS)
|
||||
_ITEM = Bounded(int, 0, 3)
|
||||
|
||||
|
||||
class Ados2ImportSchema(ImportSchema):
|
||||
ado_id: SourceId = None
|
||||
ado_pac_id: Optional[int] = None
|
||||
ado_ord_id: OptionalStr = None
|
||||
ado_fecha: FlexDate = None
|
||||
ado_modulo: CatalogValue(_MODULO_ADOS2_CATALOG) = None
|
||||
ado_algoritmo: OptionalStr = None
|
||||
ado_css: Bounded(int, 1, 10) = None
|
||||
ado_clasificacion: CatalogValue(_CLASIFICACION_ADOS2_CATALOG) = None
|
||||
|
||||
# Social affect (SA)
|
||||
ado_sa_a2: _ITEM = None
|
||||
ado_sa_a6: _ITEM = None
|
||||
ado_sa_a7: _ITEM = None
|
||||
ado_sa_a8: _ITEM = None
|
||||
ado_sa_b1: _ITEM = None
|
||||
ado_sa_b2: _ITEM = None
|
||||
ado_sa_b3: _ITEM = None
|
||||
ado_sa_b4: _ITEM = None
|
||||
ado_sa_b5: _ITEM = None
|
||||
ado_sa_b6: _ITEM = None
|
||||
ado_sa_b7: _ITEM = None
|
||||
ado_sa_b8: _ITEM = None
|
||||
ado_sa_b9: _ITEM = None
|
||||
ado_sa_b10: _ITEM = None
|
||||
ado_sa_b11: _ITEM = None
|
||||
ado_sa_b12: _ITEM = None
|
||||
ado_sa_b13: _ITEM = None
|
||||
ado_sa_b14: _ITEM = None
|
||||
ado_sa_b15: _ITEM = None
|
||||
ado_sa_b16b: _ITEM = None
|
||||
ado_sa_b18: _ITEM = None
|
||||
|
||||
# Restricted and repetitive behaviour (RRB)
|
||||
ado_rrb_a3: _ITEM = None
|
||||
ado_rrb_a4: _ITEM = None
|
||||
ado_rrb_a5: _ITEM = None
|
||||
ado_rrb_d1: _ITEM = None
|
||||
ado_rrb_d2: _ITEM = None
|
||||
ado_rrb_d4: _ITEM = None
|
||||
ado_rrb_d5: _ITEM = None
|
||||
@@ -1,55 +0,0 @@
|
||||
"""Import schema for `core.tea.models.AntecedentesMaternosGestacion`. All fields
|
||||
optional, like TEA's Core; system-managed `amg_created_at`/`amg_updated_at`/`amg_fuente_sistema` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import (
|
||||
CategoriaPesoMaterno,
|
||||
FuenteAntecedenteMaterno,
|
||||
TipoEmbarazo,
|
||||
TrastornoHipertensivoGestacion,
|
||||
VolumenLiquidoAmniotico,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr
|
||||
|
||||
_FUENTE_ANTECEDENTE_MATERNO_CATALOG = Catalog(FuenteAntecedenteMaterno)
|
||||
_CATEGORIA_PESO_MATERNO_CATALOG = Catalog(CategoriaPesoMaterno)
|
||||
_TIPO_EMBARAZO_CATALOG = Catalog(TipoEmbarazo)
|
||||
_TRASTORNO_HIPERTENSIVO_GESTACION_CATALOG = Catalog(TrastornoHipertensivoGestacion)
|
||||
_VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG = Catalog(VolumenLiquidoAmniotico)
|
||||
|
||||
|
||||
class AntecedentesMaternosGestacionImportSchema(ImportSchema):
|
||||
amg_pac_id: Optional[int] = None
|
||||
amg_id_madre_seudonimo: OptionalStr = None
|
||||
amg_fuente_antecedente: CatalogValue(_FUENTE_ANTECEDENTE_MATERNO_CATALOG) = None
|
||||
amg_flag_vinculo_verificado: Optional[int] = None
|
||||
amg_imc_pregestacional: Optional[float] = None
|
||||
amg_categoria_peso_materno: CatalogValue(_CATEGORIA_PESO_MATERNO_CATALOG) = None
|
||||
amg_tabaquismo_gestacion: Optional[int] = None
|
||||
amg_acido_folico_preconcepcional: Optional[int] = None
|
||||
amg_intervalo_intergenesico_meses: Optional[int] = None
|
||||
amg_antecedente_aborto: Optional[int] = None
|
||||
amg_embarazo_multiple: CatalogValue(_TIPO_EMBARAZO_CATALOG) = None
|
||||
amg_infeccion_gestacion: Optional[int] = None
|
||||
amg_infeccion_tipo: OptionalStr = None
|
||||
amg_infeccion_hospitalizacion: Optional[int] = None
|
||||
amg_diabetes_gestacional: Optional[int] = None
|
||||
amg_hipertension_preeclampsia: CatalogValue(_TRASTORNO_HIPERTENSIVO_GESTACION_CATALOG) = None
|
||||
amg_hipotiroidismo: Optional[int] = None
|
||||
amg_hipertiroidismo: Optional[int] = None
|
||||
amg_incompatibilidad_rh: Optional[int] = None
|
||||
amg_crisis_convulsivas: Optional[int] = None
|
||||
amg_proceso_proinflamatorio: Optional[int] = None
|
||||
amg_enfermedad_autoinmune: Optional[int] = None
|
||||
amg_migrana: Optional[int] = None
|
||||
amg_asma: Optional[int] = None
|
||||
amg_hipoxia_materna: Optional[int] = None
|
||||
amg_estres_agudo: Optional[int] = None
|
||||
amg_trastorno_neurologico: Optional[int] = None
|
||||
amg_liquido_amniotico: CatalogValue(_VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG) = None
|
||||
amg_medicamentos_gestacion: OptionalStr = None
|
||||
amg_farmaco_riesgo_neurodesarrollo: Optional[int] = None
|
||||
amg_observaciones: OptionalStr = None
|
||||
amg_ocr_confianza: Optional[float] = None
|
||||
amg_nlp_version: OptionalStr = None
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Import schema for `core.tea.models.Eeg`: the study, its EDF and what the EEG analysis writes back (sleep,
|
||||
channels, duration and the five quality criteria)."""
|
||||
from typing import Optional
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Bounded, EdfFile, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_CHANNELS = Bounded(int, 0, None)
|
||||
|
||||
|
||||
class EegImportSchema(ImportSchema):
|
||||
# The source's own id, kept so the metrics that reference it still point at this record.
|
||||
eeg_id: SourceId = None
|
||||
eeg_pac_id: Optional[int] = None
|
||||
eeg_ord_id: OptionalStr = None
|
||||
eeg_id_registro_laboratorio: OptionalStr = None
|
||||
eeg_fecha_estudio: FlexDate = None
|
||||
eeg_con_sueno: Bounded(int, 0, 1) = None
|
||||
eeg_canales: Bounded(int, 1, 256) = None
|
||||
eeg_duracion_min: Bounded(float, 0, None) = None
|
||||
eeg_canales_amplitud: _CHANNELS = None
|
||||
eeg_canales_alta_frecuencia: _CHANNELS = None
|
||||
eeg_canales_correlacion: _CHANNELS = None
|
||||
eeg_canales_sin_senal: _CHANNELS = None
|
||||
eeg_ruido_linea_db: Bounded(float, 0, None) = None
|
||||
eeg_estudio: EdfFile = None
|
||||
@@ -1,69 +0,0 @@
|
||||
"""Import schema for `core.tea.models.EegEstudio`. All fields optional, like TEA's
|
||||
Core; system-managed `eeg_created_at`/`eeg_updated_at` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import (
|
||||
CalidadTecnicaEeg,
|
||||
ConclusionEeg,
|
||||
DistribucionAnormalidad,
|
||||
EstadoRegistroEeg,
|
||||
FuenteInterpretacionEeg,
|
||||
Lentificacion,
|
||||
RespuestaFotoestimulacion,
|
||||
Simetria,
|
||||
TipoGrafoelemento,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, EdfFile, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_FUENTE_INTERPRETACION_EEG_CATALOG = Catalog(FuenteInterpretacionEeg)
|
||||
_ESTADO_REGISTRO_EEG_CATALOG = Catalog(EstadoRegistroEeg)
|
||||
_CALIDAD_TECNICA_EEG_CATALOG = Catalog(CalidadTecnicaEeg)
|
||||
_SIMETRIA_CATALOG = Catalog(Simetria)
|
||||
_TIPO_GRAFOELEMENTO_CATALOG = Catalog(TipoGrafoelemento)
|
||||
_DISTRIBUCION_ANORMALIDAD_CATALOG = Catalog(DistribucionAnormalidad)
|
||||
_LENTIFICACION_CATALOG = Catalog(Lentificacion)
|
||||
_RESPUESTA_FOTOESTIMULACION_CATALOG = Catalog(RespuestaFotoestimulacion)
|
||||
_CONCLUSION_EEG_CATALOG = Catalog(ConclusionEeg)
|
||||
|
||||
|
||||
class EegEstudioImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id still point at this record.
|
||||
eeg_id: SourceId = None
|
||||
eeg_ord_id: OptionalStr = None
|
||||
eeg_pac_id: Optional[int] = None
|
||||
eeg_reporte_disponible: Optional[int] = None
|
||||
eeg_fuente_interpretacion: CatalogValue(_FUENTE_INTERPRETACION_EEG_CATALOG) = None
|
||||
eeg_fecha_nacimiento_archivo: FlexDate = None
|
||||
eeg_edad_meses: Optional[float] = None
|
||||
eeg_fecha_estudio: FlexDate = None
|
||||
eeg_fecha_reporte: FlexDate = None
|
||||
eeg_dias_respuesta: Optional[int] = None
|
||||
eeg_medico_interpreta: OptionalStr = None
|
||||
eeg_estado_registro: CatalogValue(_ESTADO_REGISTRO_EEG_CATALOG) = None
|
||||
eeg_privacion_sueno: Optional[int] = None
|
||||
eeg_sedacion: Optional[int] = None
|
||||
eeg_sedacion_farmaco: OptionalStr = None
|
||||
eeg_duracion_min: Optional[float] = None
|
||||
eeg_calidad_tecnica: CatalogValue(_CALIDAD_TECNICA_EEG_CATALOG) = None
|
||||
eeg_descripcion_senal: OptionalStr = None
|
||||
eeg_ritmo_base_frecuencia: Optional[float] = None
|
||||
eeg_ritmo_base_amplitud: Optional[int] = None
|
||||
eeg_simetria: CatalogValue(_SIMETRIA_CATALOG) = None
|
||||
eeg_anormalidad_presente: Optional[int] = None
|
||||
eeg_actividad_epileptiforme: Optional[int] = None
|
||||
eeg_tipo_grafoelemento: CatalogValue(_TIPO_GRAFOELEMENTO_CATALOG) = None
|
||||
eeg_distribucion_anormalidad: CatalogValue(_DISTRIBUCION_ANORMALIDAD_CATALOG) = None
|
||||
eeg_localizacion: OptionalStr = None
|
||||
eeg_activacion_sueno: Optional[int] = None
|
||||
eeg_lentificacion: CatalogValue(_LENTIFICACION_CATALOG) = None
|
||||
eeg_crisis_registradas: Optional[int] = None
|
||||
eeg_respuesta_fotoestimulacion: CatalogValue(_RESPUESTA_FOTOESTIMULACION_CATALOG) = None
|
||||
eeg_conclusion_texto: OptionalStr = None
|
||||
eeg_conclusion_categoria: CatalogValue(_CONCLUSION_EEG_CATALOG) = None
|
||||
eeg_id_registro_laboratorio: OptionalStr = None
|
||||
eeg_pdf_ruta: OptionalStr = None
|
||||
eeg_ocr_confianza: Optional[float] = None
|
||||
eeg_nlp_version: OptionalStr = None
|
||||
eeg_utilizable: Optional[int] = None
|
||||
eeg_estudio: EdfFile = None
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Import schema for `core.tea.models.EegMetrica`: a metric the EEG analysis measured. A blank value is a metric
|
||||
that can't be evaluated."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import MetricaEeg
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr, SourceId
|
||||
|
||||
_METRICA_CATALOG = Catalog(MetricaEeg)
|
||||
|
||||
|
||||
class EegMetricaImportSchema(ImportSchema):
|
||||
met_id: SourceId = None
|
||||
met_eeg_id: OptionalStr = None
|
||||
met_codigo: CatalogValue(_METRICA_CATALOG) = None
|
||||
met_valor: Optional[float] = None
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Import schema for `core.tea.models.EegMetricaElectrodo`: a metric's z-score at one 10-20 electrode."""
|
||||
from typing import Optional
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import OptionalStr, SourceId
|
||||
|
||||
|
||||
class EegMetricaElectrodoImportSchema(ImportSchema):
|
||||
mel_id: SourceId = None
|
||||
mel_met_id: OptionalStr = None
|
||||
mel_electrodo: OptionalStr = None
|
||||
mel_valor: Optional[float] = None
|
||||
@@ -1,21 +0,0 @@
|
||||
"""Import schema for `core.tea.models.EegSegmento`. All fields optional, like
|
||||
TEA's Core."""
|
||||
from typing import Optional
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import OptionalStr
|
||||
|
||||
|
||||
class EegSegmentoImportSchema(ImportSchema):
|
||||
seg_eeg_id: OptionalStr = None
|
||||
seg_estado: OptionalStr = None
|
||||
seg_inicio_s: Optional[float] = None
|
||||
seg_fin_s: Optional[float] = None
|
||||
seg_duracion_s: Optional[float] = None
|
||||
seg_fuente: OptionalStr = None
|
||||
seg_frecuencia_flash_hz: Optional[float] = None
|
||||
seg_n_destellos: Optional[int] = None
|
||||
seg_cobertura: Optional[float] = None
|
||||
seg_rms_uv: Optional[float] = None
|
||||
seg_emg: Optional[float] = None
|
||||
seg_p2p_max_uv: Optional[float] = None
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Import schema for `core.tea.models.EvaluacionNeuropediatrica`: the note and its ICD-10 diagnosis."""
|
||||
from typing import Annotated, Optional
|
||||
|
||||
from pydantic import BeforeValidator, StringConstraints
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import FlexDate, OptionalStr, SourceId, optional_str
|
||||
|
||||
|
||||
def _upper(v):
|
||||
v = optional_str(v)
|
||||
return v.strip().upper() if isinstance(v, str) else v
|
||||
|
||||
|
||||
# A letter, two digits and optionally a dot with one or two more (F84.0); the dot may be missing (F840).
|
||||
_CIE10 = Annotated[
|
||||
Optional[Annotated[str, StringConstraints(pattern=r"^[A-Z][0-9]{2}(\.?[0-9]{1,2})?$")]],
|
||||
BeforeValidator(_upper),
|
||||
]
|
||||
|
||||
|
||||
class EvaluacionNeuropediatricaImportSchema(ImportSchema):
|
||||
neu_id: SourceId = None
|
||||
neu_pac_id: Optional[int] = None
|
||||
neu_ord_id: OptionalStr = None
|
||||
neu_fecha: FlexDate = None
|
||||
neu_cie_codigo: _CIE10 = None
|
||||
@@ -1,86 +0,0 @@
|
||||
"""Import schema for `core.tea.models.EvaluacionPsicologica`, including the 28
|
||||
ADOS-2 item columns. All fields optional, like TEA's Core; system-managed `psi_created_at`/`psi_updated_at` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import (
|
||||
ClasificacionAdos2,
|
||||
InstrumentoTamizaje,
|
||||
ModuloAdos2,
|
||||
NivelRiesgoTamizaje,
|
||||
VentanaMadurativa,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
_INSTRUMENTO_TAMIZAJE_CATALOG = Catalog(InstrumentoTamizaje)
|
||||
_NIVEL_RIESGO_TAMIZAJE_CATALOG = Catalog(NivelRiesgoTamizaje)
|
||||
_MODULO_ADOS2_CATALOG = Catalog(ModuloAdos2)
|
||||
_CLASIFICACION_ADOS2_CATALOG = Catalog(ClasificacionAdos2)
|
||||
|
||||
|
||||
class EvaluacionPsicologicaImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id still point at this record.
|
||||
psi_id: SourceId = None
|
||||
psi_ord_id: OptionalStr = None
|
||||
psi_pac_id: Optional[int] = None
|
||||
psi_fecha_entrevista_inicial: FlexDate = None
|
||||
psi_fecha_ados2: FlexDate = None
|
||||
psi_fecha_evaluacion: FlexDate = None
|
||||
psi_psicologo: OptionalStr = None
|
||||
psi_edad_meses: Optional[float] = None
|
||||
psi_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
psi_instrumento_tamizaje: CatalogValue(_INSTRUMENTO_TAMIZAJE_CATALOG) = None
|
||||
psi_tamizaje_puntaje: Optional[int] = None
|
||||
psi_tamizaje_riesgo: CatalogValue(_NIVEL_RIESGO_TAMIZAJE_CATALOG) = None
|
||||
psi_ados2_modulo: CatalogValue(_MODULO_ADOS2_CATALOG) = None
|
||||
|
||||
# Items ADOS-2, dominio SA (Interaccion Social Reciproca)
|
||||
psi_ados2_sa_a2: Optional[int] = None
|
||||
psi_ados2_sa_a6: Optional[int] = None
|
||||
psi_ados2_sa_a7: Optional[int] = None
|
||||
psi_ados2_sa_a8: Optional[int] = None
|
||||
psi_ados2_sa_b1: Optional[int] = None
|
||||
psi_ados2_sa_b2: Optional[int] = None
|
||||
psi_ados2_sa_b3: Optional[int] = None
|
||||
psi_ados2_sa_b4: Optional[int] = None
|
||||
psi_ados2_sa_b5: Optional[int] = None
|
||||
psi_ados2_sa_b6: Optional[int] = None
|
||||
psi_ados2_sa_b7: Optional[int] = None
|
||||
psi_ados2_sa_b8: Optional[int] = None
|
||||
psi_ados2_sa_b9: Optional[int] = None
|
||||
psi_ados2_sa_b10: Optional[int] = None
|
||||
psi_ados2_sa_b11: Optional[int] = None
|
||||
psi_ados2_sa_b12: Optional[int] = None
|
||||
psi_ados2_sa_b13: Optional[int] = None
|
||||
psi_ados2_sa_b14: Optional[int] = None
|
||||
psi_ados2_sa_b15: Optional[int] = None
|
||||
psi_ados2_sa_b16b: Optional[int] = None
|
||||
psi_ados2_sa_b18: Optional[int] = None
|
||||
|
||||
# Items ADOS-2, dominio RRB (Conductas Restringidas y Repetitivas)
|
||||
psi_ados2_rrb_a3: Optional[int] = None
|
||||
psi_ados2_rrb_a4: Optional[int] = None
|
||||
psi_ados2_rrb_a5: Optional[int] = None
|
||||
psi_ados2_rrb_d1: Optional[int] = None
|
||||
psi_ados2_rrb_d2: Optional[int] = None
|
||||
psi_ados2_rrb_d4: Optional[int] = None
|
||||
psi_ados2_rrb_d5: Optional[int] = None
|
||||
|
||||
psi_ados2_sa: Optional[int] = None
|
||||
psi_ados2_rrb: Optional[int] = None
|
||||
psi_ados2_total: Optional[int] = None
|
||||
psi_ados2_css: Optional[int] = None
|
||||
psi_ados2_css_sa: Optional[int] = None
|
||||
psi_ados2_css_rrb: Optional[int] = None
|
||||
psi_ados2_clasificacion: CatalogValue(_CLASIFICACION_ADOS2_CATALOG) = None
|
||||
psi_rgd: Optional[int] = None
|
||||
psi_cociente_desarrollo: Optional[float] = None
|
||||
psi_css_umbral_aplicado: Optional[int] = None
|
||||
psi_caso_confirmado: Optional[int] = None
|
||||
psi_cars_total: Optional[float] = None
|
||||
psi_otros_instrumentos: OptionalStr = None
|
||||
psi_regresion_desarrollo: Optional[int] = None
|
||||
psi_diagnostico_texto: OptionalStr = None
|
||||
psi_ocr_confianza: Optional[float] = None
|
||||
psi_nlp_version: OptionalStr = None
|
||||
@@ -1,13 +0,0 @@
|
||||
"""Import schema for `core.tea.models.InstrumentoAplicado`. All fields
|
||||
optional, like TEA's Core."""
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import OptionalStr
|
||||
|
||||
|
||||
class InstrumentoAplicadoImportSchema(ImportSchema):
|
||||
ins_psi_id: OptionalStr = None
|
||||
ins_instrumento: OptionalStr = None
|
||||
ins_informante: OptionalStr = None
|
||||
ins_area: OptionalStr = None
|
||||
ins_interpretacion: OptionalStr = None
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Import schema for `core.tea.models.Mchat`: one M-CHAT-R/F and its total score."""
|
||||
from typing import Optional
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Bounded, FlexDate, OptionalStr, SourceId
|
||||
|
||||
|
||||
class MchatImportSchema(ImportSchema):
|
||||
mch_id: SourceId = None
|
||||
mch_pac_id: Optional[int] = None
|
||||
mch_ord_id: OptionalStr = None
|
||||
mch_fecha: FlexDate = None
|
||||
mch_puntaje: Bounded(int, 0, 20) = None
|
||||
@@ -1,46 +0,0 @@
|
||||
"""Import schema for `core.tea.models.NotaMedica`. All fields optional, like TEA's
|
||||
Core; system-managed `nm_created_at`/`nm_updated_at`/`nm_fuente_sistema` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import Especialidad, Pronostico, TipoNota, VentanaMadurativa
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad)
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
_PRONOSTICO_CATALOG = Catalog(Pronostico)
|
||||
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_pac_id: Optional[int] = None
|
||||
nm_id_hospital: OptionalStr = None
|
||||
nm_nota_previa_id: OptionalStr = None
|
||||
nm_tipo_nota: CatalogValue(_TIPO_NOTA_CATALOG) = None
|
||||
nm_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
nm_fecha: FlexDate = None
|
||||
nm_edad_meses: Optional[float] = None
|
||||
nm_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
nm_medico_tratante: OptionalStr = None
|
||||
nm_motivo_consulta: OptionalStr = None
|
||||
nm_interrogatorio: OptionalStr = None
|
||||
nm_regresion_referida: Optional[int] = None
|
||||
nm_antecedente_familiar_tea: Optional[int] = None
|
||||
nm_perimetro_cefalico: Optional[float] = None
|
||||
nm_diagnostico_texto: OptionalStr = None
|
||||
nm_cie_codigo: OptionalStr = None
|
||||
nm_cie_descripcion: OptionalStr = None
|
||||
nm_tratamiento_texto: OptionalStr = None
|
||||
nm_receta: OptionalStr = None
|
||||
nm_plan_estudios: OptionalStr = None
|
||||
nm_pronostico: CatalogValue(_PRONOSTICO_CATALOG) = None
|
||||
nm_observaciones: OptionalStr = None
|
||||
nm_masa_corporal: Optional[float] = None
|
||||
nm_talla: Optional[float] = None
|
||||
nm_imc_visita: Optional[float] = None
|
||||
nm_frecuencia_cardiaca: Optional[int] = None
|
||||
nm_frecuencia_respiratoria: Optional[int] = None
|
||||
nm_presion_arterial_sistolica: Optional[int] = None
|
||||
nm_presion_arterial_diastolica: Optional[int] = None
|
||||
nm_temperatura: Optional[float] = None
|
||||
nm_pdf_ruta: OptionalStr = None
|
||||
@@ -1,37 +1,18 @@
|
||||
"""Import schema for `core.tea.models.OrdenesEstudio`. All fields optional, like
|
||||
TEA's Core; system-managed `ord_*_created_at`/`ord_updated_at`/`ord_fuente_sistema` are excluded."""
|
||||
"""Import schema for `core.tea.models.OrdenesEstudio`: the order of an ADOS-2, a neuropediatrics note or an EEG."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import TIPO_ESTUDIO_ALIAS, Especialidad, EstatusEstudio, TipoEstudio, VentanaMadurativa
|
||||
from core.tea.enums import TIPO_ESTUDIO_ALIAS, TipoEstudio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad)
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
_ESTATUS_ESTUDIO_CATALOG = Catalog(EstatusEstudio)
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
|
||||
|
||||
class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id still point at this record.
|
||||
ord_id: SourceId = None
|
||||
ord_pac_id: Optional[int] = None
|
||||
ord_nota_medica_id: OptionalStr = None
|
||||
ord_id_hospital: OptionalStr = None
|
||||
ord_fecha: FlexDate = None
|
||||
ord_medico_solicitante: OptionalStr = None
|
||||
ord_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
ord_diagnostico_asignado: OptionalStr = None
|
||||
ord_cie_asignado: OptionalStr = None
|
||||
ord_dias_vigencia: Optional[int] = None
|
||||
ord_fecha_vencimiento: FlexDate = None
|
||||
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None
|
||||
ord_estatus: CatalogValue(_ESTATUS_ESTUDIO_CATALOG) = None
|
||||
ord_fecha_realizacion: FlexDate = None
|
||||
ord_fecha_resultado: FlexDate = None
|
||||
ord_dias_espera: Optional[int] = None
|
||||
ord_proveedor: OptionalStr = None
|
||||
ord_edad_meses: Optional[float] = None
|
||||
ord_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
ord_pdf_ruta: OptionalStr = None
|
||||
ord_observaciones: OptionalStr = None
|
||||
ord_fecha: FlexDate = None
|
||||
ord_pdf_blob: Optional[bytes] = None
|
||||
|
||||
@@ -1,24 +1,14 @@
|
||||
"""Import schema for `core.tea.models.Pacientes`. All fields optional, like TEA's
|
||||
Core; system-managed `pac_created_at`/`pac_updated_at`/`pac_fuente_sistema` are excluded.
|
||||
"""Import schema for `core.tea.models.Pacientes`.
|
||||
|
||||
`pac_id` is importable: every other TEA table references the patient by the
|
||||
source system's integer id, so it has to be kept, not renumbered."""
|
||||
`pac_id` is importable: every other TEA table references the patient by the source system's integer id, so it is
|
||||
kept, not renumbered."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import Parentesco, SexoBiologico
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_SEXO_CATALOG = Catalog(SexoBiologico)
|
||||
_PARENTESCO_CATALOG = Catalog(Parentesco)
|
||||
from webapi.imports.schemas.coercion import FlexDate, OptionalStr
|
||||
|
||||
|
||||
class PacientesImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: OptionalStr = None
|
||||
pac_id_titular: OptionalStr = None
|
||||
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
|
||||
pac_fecha_nacimiento: FlexDate = None
|
||||
pac_sexo: CatalogValue(_SEXO_CATALOG) = None
|
||||
pac_codigo_postal_vigente: OptionalStr = None
|
||||
pac_dependencia: OptionalStr = None
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
"""Import schema for `core.tea.models.PartoNeonatal`. All fields optional, like
|
||||
TEA's Core; system-managed `pnn_created_at`/`pnn_updated_at`/`pnn_fuente_sistema` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import (
|
||||
ClasificacionEdadGestacional,
|
||||
ComplicacionIntraparto,
|
||||
FuenteAntecedenteNeonatal,
|
||||
TamanoParaEdadGestacional,
|
||||
TipoParto,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr
|
||||
|
||||
_FUENTE_ANTECEDENTE_NEONATAL_CATALOG = Catalog(FuenteAntecedenteNeonatal)
|
||||
_TIPO_PARTO_CATALOG = Catalog(TipoParto)
|
||||
_COMPLICACION_INTRAPARTO_CATALOG = Catalog(ComplicacionIntraparto)
|
||||
_CLASIFICACION_EDAD_GESTACIONAL_CATALOG = Catalog(ClasificacionEdadGestacional)
|
||||
_TAMANO_PARA_EDAD_GESTACIONAL_CATALOG = Catalog(TamanoParaEdadGestacional)
|
||||
|
||||
|
||||
class PartoNeonatalImportSchema(ImportSchema):
|
||||
pnn_pac_id: Optional[int] = None
|
||||
pnn_fuente_antecedente: CatalogValue(_FUENTE_ANTECEDENTE_NEONATAL_CATALOG) = None
|
||||
pnn_tipo_parto: CatalogValue(_TIPO_PARTO_CATALOG) = None
|
||||
pnn_complicaciones_intraparto: Optional[int] = None
|
||||
pnn_complicacion_tipo: CatalogValue(_COMPLICACION_INTRAPARTO_CATALOG) = None
|
||||
pnn_peso_nacer_g: Optional[int] = None
|
||||
pnn_talla_nacer_cm: Optional[float] = None
|
||||
pnn_perimetro_cefalico_nacer_cm: Optional[float] = None
|
||||
pnn_edad_gestacional_sem: Optional[float] = None
|
||||
pnn_clasificacion_eg: CatalogValue(_CLASIFICACION_EDAD_GESTACIONAL_CATALOG) = None
|
||||
pnn_tamano_para_eg: CatalogValue(_TAMANO_PARA_EDAD_GESTACIONAL_CATALOG) = None
|
||||
pnn_peso_nacer_zscore: Optional[float] = None
|
||||
pnn_apgar_1min: Optional[int] = None
|
||||
pnn_apgar_5min: Optional[int] = None
|
||||
pnn_ingreso_ucin: Optional[int] = None
|
||||
pnn_dias_ucin: Optional[int] = None
|
||||
pnn_encefalopatia_hipoxico_isquemica: Optional[int] = None
|
||||
pnn_hipotermia_nacer: Optional[int] = None
|
||||
pnn_hiperbilirrubinemia: Optional[int] = None
|
||||
pnn_fototerapia: Optional[int] = None
|
||||
pnn_hipoglucemia_neonatal: Optional[int] = None
|
||||
pnn_anoxia: Optional[int] = None
|
||||
pnn_sindrome_congenito: Optional[int] = None
|
||||
pnn_sindrome_congenito_desc: OptionalStr = None
|
||||
pnn_flag_riesgo_neonatal: Optional[int] = None
|
||||
pnn_observaciones: OptionalStr = None
|
||||
pnn_ocr_confianza: Optional[float] = None
|
||||
pnn_nlp_version: OptionalStr = None
|
||||
@@ -1,26 +0,0 @@
|
||||
"""Import schema for `core.tea.models.PotencialesEvocadosAuditivos`. All fields
|
||||
optional, like TEA's Core; system-managed `pea_created_at`/`pea_updated_at` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import GradoHipoacusia
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_GRADO_HIPOACUSIA_CATALOG = Catalog(GradoHipoacusia)
|
||||
|
||||
|
||||
class PotencialesEvocadosAuditivosImportSchema(ImportSchema):
|
||||
pea_ord_id: OptionalStr = None
|
||||
pea_pac_id: Optional[int] = None
|
||||
pea_fecha_estudio: FlexDate = None
|
||||
pea_medico_interpreta: OptionalStr = None
|
||||
pea_umbral_od: Optional[int] = None
|
||||
pea_umbral_oi: Optional[int] = None
|
||||
pea_latencia_v_od: Optional[float] = None
|
||||
pea_latencia_v_oi: Optional[float] = None
|
||||
pea_interpico_i_v_od: Optional[float] = None
|
||||
pea_interpico_i_v_oi: Optional[float] = None
|
||||
pea_grado_hipoacusia: CatalogValue(_GRADO_HIPOACUSIA_CATALOG) = None
|
||||
pea_conclusion_texto: OptionalStr = None
|
||||
pea_flag_diferencial_auditivo: Optional[int] = None
|
||||
pea_ocr_confianza: Optional[float] = None
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Writes the catalog-fallback fields a document source's records carry
|
||||
(captions no known `FieldSpec` claimed, see `extraction.nlp.discovery`)
|
||||
into the silver layer directly: one synthetic `procedimiento` per record
|
||||
per estudio its resolved fields touch, with their `observacion`s matched
|
||||
against the project's catalog (`catalog_matching`). Only a source that
|
||||
asks for it (`catalog_fallback`) gets here, and only captions the catalog
|
||||
already knows are written: the catalog is versioned with the code, so a
|
||||
running import never adds to it. Captions nothing matches are counted;
|
||||
the import report lists them (`webapi.imports.audit`).
|
||||
|
||||
There is no staging row for these — the whole point is a field outside
|
||||
today's structured schemas — so this bypasses `DESDE_STAGING` and writes
|
||||
straight through the domain's existing `carga_repository`, the same one
|
||||
`webapi.orchestration`'s `load` step uses for staging-derived batches.
|
||||
|
||||
Marked clearly apart from every staging-derived procedimiento:
|
||||
`fuente_tabla` is the sentinel `FUENTE_CATALOGO_ABIERTO`, never a real
|
||||
staging table name. `fuente_id` is the record's own natural key (not a SQL
|
||||
row's surrogate id), so reprocessing the same record later — read again
|
||||
from the SQL source, re-uploaded as a file, or corrected by hand — updates
|
||||
the same rows in place instead of duplicating them; the structured fields
|
||||
a source also carries keep going through the unmodified staging/import
|
||||
path (`commit_sources`), independently of this.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
|
||||
from extraction import ExtractedRecord
|
||||
|
||||
from webapi.imports.schemas.catalog_matching import MatchedField, match_or_mint
|
||||
from webapi.orchestration.reference.catalogs import Catalogo, catalogo_desde_toml, ruta_de_catalogo
|
||||
from webapi.orchestration.silver.procedures import LotePlata
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
FUENTE_CATALOGO_ABIERTO = "catalogo_abierto"
|
||||
|
||||
|
||||
@dataclass
|
||||
class CatalogCommitResult:
|
||||
proyecto: str
|
||||
records_written: int = 0
|
||||
records_without_patient: int = 0
|
||||
fields_matched: int = 0
|
||||
fields_minted: int = 0
|
||||
fields_unmatched: int = 0
|
||||
|
||||
|
||||
def commit_discovered_fields(
|
||||
records: list[ExtractedRecord], *, proyecto: str, estudio_id: str | None = None, mint: bool = False
|
||||
) -> CatalogCommitResult:
|
||||
"""A patient without a row in `persona` is counted and skipped: this
|
||||
path only fills in fields for a patient already known, it doesn't
|
||||
create one. `mint` lets unmatched captions become new catalog entries,
|
||||
written to the catalog file; the import path never sets it."""
|
||||
dominio = import_module(f"persistance.{proyecto}")
|
||||
tablas = tablas_de(proyecto)
|
||||
ruta = ruta_de_catalogo(proyecto)
|
||||
catalogo = catalogo_desde_toml(ruta, tablas=tablas)
|
||||
|
||||
result = CatalogCommitResult(proyecto=proyecto)
|
||||
procedures, observations = [], []
|
||||
for record in records:
|
||||
if not record.discovered or record.key is None:
|
||||
continue
|
||||
patients = dominio.paciente_repository.list(pac_id_hospital=record.key, limit=1)
|
||||
if not patients:
|
||||
result.records_without_patient += 1
|
||||
continue
|
||||
pac_id = patients[0].pac_id
|
||||
|
||||
matched = match_or_mint(record.discovered, proyecto=proyecto, catalogo=catalogo, estudio_id=estudio_id, mint=mint)
|
||||
result.fields_unmatched += len(record.discovered) - len(matched)
|
||||
if not matched:
|
||||
continue
|
||||
if any(field.is_new for field in matched):
|
||||
catalogo = catalogo_desde_toml(ruta, tablas=tablas) # so a later record in this batch can match it too
|
||||
matched = _fold_duplicates(matched)
|
||||
|
||||
by_estudio: dict[str, list] = defaultdict(list)
|
||||
for field in matched:
|
||||
by_estudio[field.resultado_id.split(".", 1)[0]].append(field)
|
||||
result.fields_minted += int(field.is_new)
|
||||
result.fields_matched += int(not field.is_new)
|
||||
for estudio, fields in by_estudio.items():
|
||||
key = (FUENTE_CATALOGO_ABIERTO, record.key, estudio, "reporte")
|
||||
procedures.append({"llave": key, "padres": [], "pac_id": pac_id, "fecha": None, "fecha_del_padre": False})
|
||||
observations += [
|
||||
{"procedimiento": key, "pac_id": pac_id, "resultado_id": field.resultado_id, **field.observacion}
|
||||
for field in fields
|
||||
]
|
||||
result.records_written += 1
|
||||
|
||||
if procedures:
|
||||
_sync_catalog(dominio, proyecto, tablas)
|
||||
dominio.carga_repository.save_load(
|
||||
fuente=FUENTE_CATALOGO_ABIERTO, personas=(), plata=LotePlata(procedures, observations, {})
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _fold_duplicates(matched: list[MatchedField]) -> list[MatchedField]:
|
||||
"""A record's discovered captions can repeat the same resultado_id (a
|
||||
static label such as "FECHA" printed on several pages): `observacion`
|
||||
has one row per `(procedimiento, resultado_id)`, so only the first
|
||||
occurrence survives. `discover_captions` keeps every repeat on purpose
|
||||
and leaves folding to the caller (see its docstring)."""
|
||||
seen: set[str] = set()
|
||||
folded = []
|
||||
for field in matched:
|
||||
if field.resultado_id in seen:
|
||||
continue
|
||||
seen.add(field.resultado_id)
|
||||
folded.append(field)
|
||||
return folded
|
||||
|
||||
|
||||
def _sync_catalog(dominio, proyecto: str, tablas) -> None:
|
||||
"""A field minted by `match_or_mint` only exists in the TOML until this
|
||||
runs: `procedimiento.estudio_id` and `observacion`'s catalog both need
|
||||
the matching `cat_estudio`/`cat_resultado` row to already be there."""
|
||||
catalogo: Catalogo = catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas)
|
||||
dominio.catalog_repository.sync(catalogo.estudios, catalogo.resultados, catalogo.valores)
|
||||
@@ -8,6 +8,8 @@ sources of a batch target the same domain and the batch is written in one
|
||||
transaction: it lands completely or not at all.
|
||||
"""
|
||||
from dataclasses import dataclass, field
|
||||
from collections import Counter
|
||||
from itertools import islice
|
||||
from typing import Any, Iterator
|
||||
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
@@ -15,9 +17,20 @@ from sqlalchemy.exc import SQLAlchemyError
|
||||
from persistance.repository import ConflictPolicy
|
||||
from webapi.imports.audit import ImportAudit
|
||||
from webapi.imports.connectors import Connector, ConnectorError, build_connector
|
||||
from webapi.imports.connectors.document import (
|
||||
CONFIDENCE_COLUMN,
|
||||
DOCUMENT_COLUMN,
|
||||
IMAGE_COLUMN,
|
||||
SOURCES_COLUMN,
|
||||
DocumentConnector,
|
||||
connector_for_batch,
|
||||
)
|
||||
from webapi.imports.connectors.document_columns import DocumentColumns
|
||||
from webapi.imports.mapping.derived import Derivation, parse_derived
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY, EntitySpec
|
||||
from webapi.imports.schemas.service import BatchValidationResult, validate_rows
|
||||
from webapi.imports.services.link_resolver import LinkResolver, dependency_rank
|
||||
from webapi.imports.services.review_learning import learn_from_reviews
|
||||
|
||||
|
||||
class ImportRequestError(Exception):
|
||||
@@ -40,6 +53,8 @@ class ImportSource:
|
||||
defaults: dict[str, Any]
|
||||
payload: dict[str, Any]
|
||||
label: str | None = None
|
||||
derived: dict[str, Derivation] = field(default_factory=dict)
|
||||
documents: dict[str, Any] | None = None
|
||||
|
||||
@classmethod
|
||||
def parse(cls, raw: Any) -> "ImportSource":
|
||||
@@ -60,11 +75,24 @@ class ImportSource:
|
||||
unknown = sorted((set(mapping.values()) | set(defaults)) - fields)
|
||||
if unknown:
|
||||
raise ImportRequestError(f"{target} no tiene los campos {unknown}")
|
||||
targets = list(mapping.values())
|
||||
try:
|
||||
derived = parse_derived(raw.get("derived"), fields)
|
||||
except ConnectorError as exc:
|
||||
raise ImportRequestError(str(exc)) from exc
|
||||
targets = list(mapping.values()) + list(derived)
|
||||
duplicated = sorted({t for t in targets if targets.count(t) > 1})
|
||||
if duplicated:
|
||||
raise ImportRequestError(f"más de una columna de origen asignada a {duplicated}")
|
||||
if not mapping and not defaults:
|
||||
documents = raw.get("documents") or None
|
||||
if documents is not None:
|
||||
try:
|
||||
DocumentColumns.parse(documents)
|
||||
except ConnectorError as exc:
|
||||
raise ImportRequestError(str(exc)) from exc
|
||||
file_field = documents.get("file_field")
|
||||
if file_field and file_field not in fields:
|
||||
raise ImportRequestError(f"{target} no tiene el campo {file_field!r}")
|
||||
if not mapping and not defaults and not derived and not documents:
|
||||
raise ImportRequestError(f"la fuente de {target} no asigna ninguna columna")
|
||||
|
||||
payload = raw.get("payload")
|
||||
@@ -78,6 +106,8 @@ class ImportSource:
|
||||
defaults=defaults,
|
||||
payload=payload,
|
||||
label=raw.get("label"),
|
||||
derived=derived,
|
||||
documents=documents,
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -94,12 +124,106 @@ class ImportSource:
|
||||
except ConnectorError as exc:
|
||||
raise ImportRequestError(str(exc)) from exc
|
||||
|
||||
@property
|
||||
def source_columns(self) -> set[str]:
|
||||
"""Every source column the mapping, the derived fields and the
|
||||
document columns read."""
|
||||
columns = set(self.column_mapping)
|
||||
for rule in self.derived.values():
|
||||
columns |= rule.columns()
|
||||
if self.documents:
|
||||
columns |= DocumentColumns.parse(self.documents).source_columns()
|
||||
return columns
|
||||
|
||||
def _mapped(self, raw: dict[str, Any]) -> dict[str, Any]:
|
||||
row = {target: raw.get(column) for column, target in self.column_mapping.items()}
|
||||
for field_name, rule in self.derived.items():
|
||||
row[field_name] = rule.apply(raw)
|
||||
return row
|
||||
|
||||
def document_connector(
|
||||
self, raw_rows: list[dict[str, Any]] | None = None
|
||||
) -> tuple[DocumentConnector | None, list[dict[str, Any]], dict[str, dict[str, Any]]]:
|
||||
"""For a source with `documents`: the extraction over its document
|
||||
cells, the rows that had none (as read) and, per document, the row
|
||||
it came from. Values the mapping and `derived` take from the row's
|
||||
own columns go to the extraction as values to trust."""
|
||||
if raw_rows is None:
|
||||
raw_rows = list(self.connector().read_rows({column: column for column in self.source_columns}))
|
||||
spec = DocumentColumns.parse(self.documents)
|
||||
batch = spec.assemble(raw_rows, [self._mapped(raw) for raw in raw_rows])
|
||||
raw_by_document = {name: raw_rows[number - 1] for name, number in batch.row_numbers.items()}
|
||||
with_documents = set(batch.row_numbers.values())
|
||||
plain = [raw for number, raw in enumerate(raw_rows, start=1) if number not in with_documents]
|
||||
if not batch.files:
|
||||
return None, plain, raw_by_document
|
||||
return connector_for_batch(batch, self.target, self.documents), plain, raw_by_document
|
||||
|
||||
def record_namespaces(self, raw_rows: list[dict[str, Any]] | None = None) -> Iterator[tuple[dict[str, Any], dict[str, Any]]]:
|
||||
"""Per record of a source with `documents`: everything known about
|
||||
it by column name (its rows' own columns first, then every field
|
||||
and caption its documents gave) and what extraction produced."""
|
||||
connector, plain, raw_by_document = self.document_connector(raw_rows)
|
||||
if connector is not None:
|
||||
for extracted, documents in connector.record_rows():
|
||||
namespace: dict[str, Any] = {}
|
||||
for name in documents:
|
||||
for key, value in raw_by_document.get(name, {}).items():
|
||||
if _is_blank(namespace.get(key)):
|
||||
namespace[key] = value
|
||||
for key, value in extracted.items():
|
||||
if _is_blank(namespace.get(key)):
|
||||
namespace[key] = value
|
||||
yield namespace, extracted
|
||||
for raw in plain:
|
||||
yield raw, {}
|
||||
|
||||
def unused_captions(self) -> Counter:
|
||||
"""For a source that reads documents: per caption its documents
|
||||
print that neither a field claims nor the mapping or a derived
|
||||
field uses, how many records print it. Captions only, never their
|
||||
values, for the import report."""
|
||||
if self.source_type == "document":
|
||||
connector = self.connector()
|
||||
elif self.documents:
|
||||
connector, _, _ = self.document_connector()
|
||||
else:
|
||||
return Counter()
|
||||
if not isinstance(connector, DocumentConnector):
|
||||
return Counter()
|
||||
used = {column.casefold() for column in self.source_columns}
|
||||
counts: Counter = Counter()
|
||||
for record in connector.records:
|
||||
captions = {" ".join(found.caption.split()) for found in record.discovered}
|
||||
counts.update(caption for caption in captions if caption.casefold() not in used)
|
||||
return counts
|
||||
|
||||
def _document_rows(self, raw_rows: list[dict[str, Any]]) -> Iterator[dict[str, Any]]:
|
||||
"""Rows of a source with document columns: the mapping and `derived`
|
||||
applied to each record's namespace, so they reach what the
|
||||
documents print as well as the row's own columns; then every field
|
||||
extraction filled that they left empty, and the record's pages in
|
||||
`file_field`."""
|
||||
fields = set(self.spec.schema.model_fields)
|
||||
file_field = self.documents.get("file_field")
|
||||
for namespace, extracted in self.record_namespaces(raw_rows):
|
||||
row = self._mapped(namespace)
|
||||
for key, value in extracted.items():
|
||||
if key in fields and _is_blank(row.get(key)) and not _is_blank(value):
|
||||
row[key] = value
|
||||
if file_field and extracted:
|
||||
row[file_field] = extracted.get(DOCUMENT_COLUMN)
|
||||
yield row
|
||||
|
||||
def rows(self) -> Iterator[dict[str, Any]]:
|
||||
"""Mapped rows, with `defaults` filling any field the source left
|
||||
empty or didn't map at all (a constant "dependencia" for a file that
|
||||
has none, a fallback for blank cells)."""
|
||||
"""Mapped rows: each mapped column under its field, each `derived`
|
||||
field computed from the source columns it names, and `defaults`
|
||||
filling any field still empty or not mapped at all (a constant
|
||||
"dependencia" for a file that has none, a fallback for blank cells)."""
|
||||
try:
|
||||
for row in self.connector().read_rows(self.column_mapping):
|
||||
raw_rows = self.connector().read_rows({column: column for column in self.source_columns})
|
||||
mapped = self._document_rows(list(raw_rows)) if self.documents else (self._mapped(raw) for raw in raw_rows)
|
||||
for row in mapped:
|
||||
for field_name, value in self.defaults.items():
|
||||
if _is_blank(row.get(field_name)):
|
||||
row[field_name] = value
|
||||
@@ -111,6 +235,9 @@ class ImportSource:
|
||||
return validate_rows(self.spec.schema, self.rows())
|
||||
|
||||
|
||||
DOCUMENT_BOOKKEEPING = {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN}
|
||||
|
||||
|
||||
def _is_blank(value: Any) -> bool:
|
||||
return value is None or (isinstance(value, str) and not value.strip())
|
||||
|
||||
@@ -135,6 +262,33 @@ def _jsonable(value: Any) -> Any:
|
||||
return str(value)
|
||||
|
||||
|
||||
def document_columns_preview(raw_source: dict[str, Any], limit: int = 20) -> dict[str, Any]:
|
||||
"""The columns a source with `documents` offers to its mapping (its own
|
||||
columns and every field and caption its documents print), with sample
|
||||
values per record, shaped like a source preview."""
|
||||
source = ImportSource.parse({**raw_source, "column_mapping": raw_source.get("column_mapping") or {}})
|
||||
connector = source.connector()
|
||||
own = [column.name for column in connector.preview(limit=1).columns]
|
||||
raw_rows = list(connector.read_rows({column: column for column in set(own) | source.source_columns}))
|
||||
names: list[str] = list(own)
|
||||
rows = []
|
||||
for namespace, _ in source.record_namespaces(raw_rows):
|
||||
for key in namespace:
|
||||
if key not in names and key not in DOCUMENT_BOOKKEEPING:
|
||||
names.append(key)
|
||||
if len(rows) < limit:
|
||||
rows.append({key: _jsonable(value) for key, value in namespace.items() if key not in DOCUMENT_BOOKKEEPING})
|
||||
columns = [{"name": name, "inferred_type": "string"} for name in names]
|
||||
return {"columns": columns, "sample_rows": rows, "total_rows": None}
|
||||
|
||||
|
||||
def mapped_sample(raw_source: dict[str, Any], limit: int = 20) -> list[dict[str, Any]]:
|
||||
"""The first rows of a source as they would be written: mapping,
|
||||
derived fields and defaults applied, before validation."""
|
||||
source = ImportSource.parse(raw_source)
|
||||
return [{name: _jsonable(value) for name, value in row.items()} for row in islice(source.rows(), max(1, limit))]
|
||||
|
||||
|
||||
def validate_source(raw_source: dict[str, Any], audit: ImportAudit | None = None) -> BatchValidationResult:
|
||||
source = ImportSource.parse(raw_source)
|
||||
if audit is None:
|
||||
@@ -142,6 +296,7 @@ def validate_source(raw_source: dict[str, Any], audit: ImportAudit | None = None
|
||||
tracked = audit.source(source)
|
||||
rows = list(source.rows())
|
||||
tracked.observe_rows(rows)
|
||||
tracked.observe_captions(source.unused_captions)
|
||||
validation = validate_rows(source.spec.schema, rows)
|
||||
tracked.observe_validation(validation)
|
||||
return validation
|
||||
@@ -251,6 +406,7 @@ def commit_sources(
|
||||
source_audit.observe_rows(rows[position])
|
||||
source_audit.observe_validation(validated[position][1])
|
||||
source_audit.observe_warnings(merge_warnings.get(position, []))
|
||||
source_audit.observe_captions(sources[position].unused_captions)
|
||||
|
||||
session = sources[0].spec.repository.open_session()
|
||||
links = LinkResolver(session)
|
||||
@@ -310,4 +466,5 @@ def commit_sources(
|
||||
) from exc
|
||||
finally:
|
||||
session.close()
|
||||
learn_from_reviews(sources)
|
||||
return [results[i] for i in range(len(validated))]
|
||||
|
||||
@@ -7,6 +7,7 @@ import pandas as pd
|
||||
|
||||
from webapi.imports.connectors import Connector, ConnectorError
|
||||
from webapi.imports.connectors.document import DocumentConnector
|
||||
from webapi.imports.connectors.document_columns import is_document
|
||||
from webapi.imports.connectors.pdf import PdfConnector, RegionSpec
|
||||
from webapi.imports.connectors.tabular import columns_from_dataframe, rows_from_dataframe
|
||||
from webapi.imports.mapping import column_matcher
|
||||
@@ -35,9 +36,16 @@ def preview_with_suggestions(connector: Connector, target_key: str | None, *, li
|
||||
"suggested_mapping": suggest_mapping([c.name for c in preview.columns], target_key),
|
||||
"tables": [{"name": t.name, "options": t.options, "kind": t.kind} for t in connector.tables()],
|
||||
"source_metadata": connector.metadata(),
|
||||
"document_columns": document_columns(preview.columns, preview.sample_rows),
|
||||
}
|
||||
|
||||
|
||||
def document_columns(columns, rows: list[dict[str, Any]]) -> list[str]:
|
||||
"""The columns whose sampled cells hold files a document reader opens,
|
||||
so a client can offer to read them as documents."""
|
||||
return [column.name for column in columns if any(is_document(row.get(column.name)) for row in rows)]
|
||||
|
||||
|
||||
def detect_pdf(raw: bytes) -> dict[str, Any]:
|
||||
"""Page count, whether there is a text layer, and every ruled table
|
||||
pdfplumber found, best candidates first."""
|
||||
@@ -72,10 +80,27 @@ def extract_pdf_regions(raw: bytes, regions: list[dict[str, Any]], *, dpi: int =
|
||||
|
||||
|
||||
def document_report(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
connector = DocumentConnector.from_payload(payload)
|
||||
"""The extraction report of uploaded documents, of a document source's
|
||||
SQL table, or (with `source`) of the document columns of any import
|
||||
source, read through that source's own mapping."""
|
||||
if payload.get("source"):
|
||||
from webapi.imports.services.import_service import ImportSource
|
||||
|
||||
connector, _, _ = ImportSource.parse(payload["source"]).document_connector()
|
||||
if connector is None:
|
||||
raise ConnectorError("ninguna fila de la fuente tiene documentos")
|
||||
else:
|
||||
connector = DocumentConnector.from_payload(payload)
|
||||
preview = preview_with_suggestions(connector, connector.target, limit=500)
|
||||
fields = [
|
||||
{"name": spec.name, "kind": spec.kind.value, "required": spec.required, "labels": list(spec.labels)}
|
||||
for spec in connector.specs
|
||||
]
|
||||
return {**preview, "key_field": connector.key_field, "fields": fields, "records": connector.report()}
|
||||
return {
|
||||
**preview,
|
||||
"key_field": connector.key_field,
|
||||
"fields": fields,
|
||||
"records": connector.report(),
|
||||
"skipped": connector.skipped,
|
||||
"nlp_version": connector.nlp_version,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Learning from the corrections made while reviewing documents: once an
|
||||
import is written, each document source whose records a person corrected
|
||||
teaches its domain's extraction ranker (`models.io.extraction_ranker`), in
|
||||
the background so the import never waits for it, one batch at a time.
|
||||
|
||||
`EXTRACTION_LEARNING=0` turns it off.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from typing import Sequence
|
||||
|
||||
from webapi.imports.connectors.document import DocumentConnector
|
||||
|
||||
LEARNING_ENV = "EXTRACTION_LEARNING"
|
||||
SOURCE = "revision"
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="extraction-learning")
|
||||
|
||||
|
||||
def enabled() -> bool:
|
||||
return os.environ.get(LEARNING_ENV, "1").strip().lower() not in ("0", "false", "no")
|
||||
|
||||
|
||||
def _connector(source) -> DocumentConnector | None:
|
||||
if source.source_type == "document":
|
||||
connector = source.connector()
|
||||
elif source.documents:
|
||||
connector, _, _ = source.document_connector()
|
||||
else:
|
||||
return None
|
||||
return connector if isinstance(connector, DocumentConnector) else None
|
||||
|
||||
|
||||
def learn_from_reviews(sources: Sequence) -> list[Future]:
|
||||
"""Queues one learning step per corrected document source; returns them,
|
||||
for a caller that wants to wait."""
|
||||
if not enabled():
|
||||
return []
|
||||
futures = []
|
||||
for source in sources:
|
||||
try:
|
||||
connector = _connector(source)
|
||||
if connector is None or not connector.overrides:
|
||||
continue
|
||||
examples, unreachable, records = connector.learning_examples()
|
||||
except Exception: # noqa: BLE001 - the import is already written
|
||||
logger.exception("no se pudieron preparar ejemplos de %s", getattr(source, "target", "?"))
|
||||
continue
|
||||
if examples:
|
||||
documents = len(connector.files)
|
||||
futures.append(_executor.submit(_learn, connector.domain, examples, unreachable, records, documents))
|
||||
return futures
|
||||
|
||||
|
||||
def _learn(domain: str, examples: list, unreachable: dict[str, int], records: int, documents: int) -> str | None:
|
||||
from models.io.extraction_ranker import Batch, learn
|
||||
|
||||
try:
|
||||
return learn(domain, Batch(examples, SOURCE, documents, records, unreachable))
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("el ranker de extracción de %s no pudo aprender de la revisión", domain)
|
||||
return None
|
||||
+19
-4
@@ -10,6 +10,7 @@ durations (`webapi.durations`; without `corte_evento`, the day of the last load)
|
||||
import json
|
||||
from collections.abc import Callable
|
||||
from datetime import date, datetime, timezone
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from core.indicadores.tipos import FechaHoraUTC
|
||||
@@ -24,28 +25,42 @@ LOADS = table("carga", column("inicio", FechaHoraUTC))
|
||||
|
||||
|
||||
def definitions_of(project: str, manifest: Path) -> dict:
|
||||
"""Every measure the manifest defines for the domain, by its id (the end of its url)."""
|
||||
"""Every measure the manifest defines for the domain, by its id (the end of its url). A measure that waits for
|
||||
a validation (`meta.requiere_validacion`) is left out until it's given."""
|
||||
return {i: d for i, d in _defined(project, manifest).items() if not _awaits_validation(d)}
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _defined(project: str, manifest: Path) -> dict:
|
||||
every = {**measure_definitions(manifest), **composition_definitions(manifest), **duration_definitions(manifest)}
|
||||
return {d.measure_id: d for d in every.values() if d.url.startswith(f"{project}/")}
|
||||
|
||||
|
||||
def _awaits_validation(definition) -> bool:
|
||||
"""TEA's EEG alterations, the one validation so far, stay hidden until the domain expert validates them."""
|
||||
if not definition.meta.get("requiere_validacion"):
|
||||
return False
|
||||
from webapi.fhir.tea import alterations_validated
|
||||
|
||||
return not alterations_validated()
|
||||
|
||||
|
||||
def kpis_blueprint(project: str, repositories, manifest: Path, *,
|
||||
now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint:
|
||||
"""The blueprint of a domain, to register with `url_prefix="/<domain>"`. `repositories` is the domain's
|
||||
`persistance.<domain>` module."""
|
||||
blueprint = Blueprint(f"{project}_kpis", __name__)
|
||||
definitions = definitions_of(project, manifest)
|
||||
|
||||
@blueprint.get("/indicadores")
|
||||
def list_kpis():
|
||||
"""The measures answered on request: id, url, version and scoring."""
|
||||
return jsonify([{"id": i, "url": d.url, "version": d.version, "scoring": scoring_of(d)}
|
||||
for i, d in sorted(definitions.items())])
|
||||
for i, d in sorted(definitions_of(project, manifest).items())])
|
||||
|
||||
@blueprint.get("/indicadores/<measure_id>")
|
||||
def get_kpi(measure_id: str):
|
||||
"""A measure's periods as a FHIR Bundle of MeasureReports, computed on request and kept in the history."""
|
||||
definition = definitions.get(measure_id)
|
||||
definition = definitions_of(project, manifest).get(measure_id)
|
||||
if definition is None:
|
||||
return jsonify({"error": f"no hay un indicador {measure_id!r} calculado bajo pedido"}), 404
|
||||
try:
|
||||
|
||||
+218
-14
@@ -30,6 +30,7 @@ from sqlalchemy import (
|
||||
case,
|
||||
cast,
|
||||
column,
|
||||
desc,
|
||||
distinct,
|
||||
func,
|
||||
literal,
|
||||
@@ -37,6 +38,7 @@ from sqlalchemy import (
|
||||
select,
|
||||
table,
|
||||
text,
|
||||
true,
|
||||
)
|
||||
|
||||
AGGREGATION_VERSION = "md19.1" # the unit-row contract the publication views read
|
||||
@@ -44,7 +46,11 @@ 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"
|
||||
KNOWN_VERSION = "version_conocida"
|
||||
|
||||
|
||||
class UndecidedRule(ValueError):
|
||||
@@ -56,7 +62,8 @@ class Population:
|
||||
"""A simple metric: the units its measure counts, filtered, the FHIR populations it is, and its dates.
|
||||
|
||||
`dated_at` are dates the event cut-off applies to besides the model's own (a biopsy's report); `known_at`, the
|
||||
dates the knowledge cut-off applies to.
|
||||
dates the knowledge cut-off applies to. `at_end`, with a status at the period's end: dates that must have (or must
|
||||
not have) been reached by the period's end, each with when it became known.
|
||||
"""
|
||||
|
||||
metric: str
|
||||
@@ -65,6 +72,53 @@ class Population:
|
||||
codes: tuple[str, ...]
|
||||
dated_at: tuple[str, ...]
|
||||
known_at: tuple[str, ...]
|
||||
at_end: tuple["ReachedByEnd", ...] = ()
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ReachedByEnd:
|
||||
"""A date reached by the period's end (`reached`) or not: dated before the period's end and the event cut-off,
|
||||
and known by the knowledge cut-off."""
|
||||
|
||||
date: str
|
||||
known_at: str | None
|
||||
reached: bool
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class StatusAtEnd:
|
||||
"""Who a period counts and with which row: every unit that entered (`entry`) on or before the period's end and
|
||||
hadn't left (`exit`, known at `exit_known`) before its start, whether or not it has a fact in the period. Each
|
||||
unit is counted with its row of highest `order` dated on or before the period's end (its status then) and known
|
||||
by the cut-offs (`known_at`). With no `order`, the model has one row per unit."""
|
||||
|
||||
entry: str
|
||||
exit: str
|
||||
exit_known: str | None
|
||||
order: str | None
|
||||
known_at: tuple[str, ...]
|
||||
|
||||
@classmethod
|
||||
def of(cls, spec: dict | None) -> "StatusAtEnd | None":
|
||||
if spec is None:
|
||||
return None
|
||||
if spec["tipo"] != STATUS_AT_PERIOD_END:
|
||||
raise NotImplementedError(f"populations of kind {spec['tipo']!r} aren't answered")
|
||||
return cls(spec["ingreso"], spec["salida"], spec.get("salida_conocida_en"), spec.get("orden"),
|
||||
tuple(spec.get("conocida_en", ())))
|
||||
|
||||
def columns(self) -> set[str]:
|
||||
return {self.entry, self.exit, *((self.exit_known,) if self.exit_known else ()),
|
||||
*((self.order,) if self.order else ()), *self.known_at}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Group:
|
||||
"""One of several groups of a measure: its numerator is the measure's own with this filter instead."""
|
||||
|
||||
name: str
|
||||
label: str
|
||||
filter_sql: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -76,7 +130,11 @@ 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;
|
||||
- `del_elegido`: in a composition, the `valor` column of the fact that gave the unit its category.
|
||||
- `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.
|
||||
"""
|
||||
|
||||
name: str
|
||||
@@ -89,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):
|
||||
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)
|
||||
|
||||
@@ -112,11 +170,26 @@ class MeasureDefinition:
|
||||
rules: dict[str, str]
|
||||
strata: tuple[Stratum, ...]
|
||||
improvement_notation: str | None = None
|
||||
population: StatusAtEnd | None = None
|
||||
groups: tuple[Group, ...] = ()
|
||||
exclusion: Population | None = None
|
||||
meta: dict = dataclasses.field(default_factory=dict, compare=False, hash=False)
|
||||
|
||||
@property
|
||||
def measure_id(self) -> str:
|
||||
return self.url.rsplit("/", 1)[-1]
|
||||
|
||||
def for_group(self, group: Group) -> "MeasureDefinition":
|
||||
"""The definition as one of its groups: the denominator's units, filtered by the group."""
|
||||
numerator = dataclasses.replace(self.denominator, metric=f"{self.numerator.metric}:{group.name}",
|
||||
codes=self.numerator.codes, filter_sql=_both(self.denominator.filter_sql,
|
||||
group.filter_sql))
|
||||
return dataclasses.replace(self, numerator=numerator, group=group.name, groups=(), strata=(), exclusion=None)
|
||||
|
||||
|
||||
def _both(first: str | None, second: str | None) -> str | None:
|
||||
return " and ".join(f"({c})" for c in (first, second) if c) or None
|
||||
|
||||
|
||||
def measure_definitions(manifest: Path) -> dict[str, MeasureDefinition]:
|
||||
"""The ratio metrics of the manifest that declare a `measure_url`, by that url."""
|
||||
@@ -143,10 +216,20 @@ def measure_definitions(manifest: Path) -> dict[str, MeasureDefinition]:
|
||||
group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})),
|
||||
strata=tuple(Stratum.of(name, s) for name, s in meta.get("estratos", {}).items()),
|
||||
improvement_notation=meta.get("improvement_notation"),
|
||||
population=StatusAtEnd.of(meta.get("poblacion")),
|
||||
groups=tuple(Group(g["grupo"], g.get("etiqueta", g["grupo"]), _unraw(g["filtro"]))
|
||||
for g in meta.get("grupos", ())),
|
||||
exclusion=_population(metrics[meta["exclusion"]], model) if "exclusion" in meta else None,
|
||||
meta=meta,
|
||||
)
|
||||
return definitions
|
||||
|
||||
|
||||
def _unraw(template: str) -> str:
|
||||
"""A `meta` template as written, without the `{% raw %}` that keeps dbt from rendering it."""
|
||||
return template.replace("{% raw %}", "").replace("{% endraw %}", "")
|
||||
|
||||
|
||||
def _semantic_model_of(metric: dict, semantic: dict) -> dict:
|
||||
measure = metric["type_params"]["measure"]["name"]
|
||||
for model in semantic.values():
|
||||
@@ -167,6 +250,8 @@ def _population(metric: dict, model: dict) -> Population:
|
||||
filter_sql=" and ".join(f"({f['where_sql_template']})" for f in filters) or None,
|
||||
codes=tuple(meta["poblaciones_fhir"]), dated_at=tuple(meta.get("fechada_en", ())),
|
||||
known_at=tuple(meta.get("conocida_en", ())),
|
||||
at_end=tuple(ReachedByEnd(a["fecha"], a.get("conocida_en"), bool(a.get("alcanzada", True)))
|
||||
for a in meta.get("al_fin", ())),
|
||||
)
|
||||
|
||||
|
||||
@@ -195,12 +280,25 @@ class MeasureQueries:
|
||||
names = {definition.time_dimension, *definition.dimensions.values(), definition.numerator.measure_expr}
|
||||
# When a fact became known is a load's start (`carga.inicio`): compared with the type it's stored in.
|
||||
known = {definition.dimensions[n] for p in (definition.numerator, definition.denominator) for n in p.known_at}
|
||||
known |= {definition.dimensions[a.known_at] for p in (definition.numerator, definition.denominator)
|
||||
for a in p.at_end if a.known_at}
|
||||
for rule in (getattr(definition, "category", None), getattr(definition, "observation", None)):
|
||||
known |= {definition.dimensions[n] for n in (rule.known_at if rule else ())}
|
||||
self.status = getattr(definition, "population", None)
|
||||
if self.status is not None:
|
||||
names |= {definition.dimensions[n] for n in self.status.columns()}
|
||||
known |= {definition.dimensions[n] for n in (*self.status.known_at, self.status.exit_known) if n}
|
||||
version = (getattr(definition, "meta", None) or {}).get(KNOWN_VERSION)
|
||||
if version is not None:
|
||||
known.add(definition.dimensions[version])
|
||||
self.events = table(definition.relation, *(
|
||||
column(name, FechaHoraUTC) if name in known else column(name) for name in sorted(names)
|
||||
if name.isidentifier()))
|
||||
self.periods = period_table
|
||||
if version is not None:
|
||||
self.events = self._known_version(definition.dimensions[version])
|
||||
if self.status is not None:
|
||||
self.events = self._status_rows()
|
||||
self.birth_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_nacimiento")
|
||||
self.start_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_inicio")
|
||||
self.age_groups = table("dim_grupo_edad", *map(column, DIM_GRUPO_EDAD))
|
||||
@@ -223,9 +321,70 @@ class MeasureQueries:
|
||||
if self.q.knowledge_cutoff is not None:
|
||||
conditions += [self._column(name) <= self.q.knowledge_cutoff for name in population.known_at]
|
||||
conditions += [self._column(name).is_not(None) for name in population.known_at]
|
||||
for date in population.at_end:
|
||||
reached = self._reached_by_end(date.date, date.known_at)
|
||||
conditions.append(reached if date.reached else case((reached, 0), else_=1) == 1)
|
||||
return and_(*conditions) if conditions else None
|
||||
|
||||
def _reached_by_end(self, date: str, known_at: str | None):
|
||||
"""The date is reached by the period's end: dated before it and by the event cut-off, known by the
|
||||
knowledge cut-off. Only with a status at the period's end, whose rows carry the period's bounds."""
|
||||
if self.status is None:
|
||||
raise ValueError(f"{self.d.url}: `al_fin` needs a population at the period's end")
|
||||
value = self._column(date)
|
||||
conditions = [value.is_not(None), value < self.events.c.periodo_fin]
|
||||
if self.q.event_cutoff is not None:
|
||||
conditions.append(value <= self.q.event_cutoff.isoformat())
|
||||
if known_at is not None and self.q.knowledge_cutoff is not None:
|
||||
conditions += [self._column(known_at).is_not(None), self._column(known_at) <= self.q.knowledge_cutoff]
|
||||
return and_(*conditions)
|
||||
|
||||
def _known_version(self, version: str):
|
||||
"""Each unit's rows as they were known at the knowledge cut-off, for a model with one set of rows per unit
|
||||
and knowledge version (`meta.version_conocida`, the column that dates each version): the unit's latest
|
||||
version by the cut-off, or its latest of all without one. A subquery with the model's name, read as the
|
||||
model is."""
|
||||
base = self.events
|
||||
latest = func.rank().over(partition_by=base.c[self.d.numerator.measure_expr], order_by=desc(base.c[version]))
|
||||
versions = select(*base.c, latest.label("lugar_de_version"))
|
||||
if self.q.knowledge_cutoff is not None:
|
||||
versions = versions.where(base.c[version] <= self.q.knowledge_cutoff)
|
||||
versions = versions.subquery("versiones")
|
||||
return (select(*(c for c in versions.c if c.name != "lugar_de_version"))
|
||||
.where(versions.c.lugar_de_version == 1).subquery(self.d.relation))
|
||||
|
||||
def _status_rows(self):
|
||||
"""Each unit the period counts, with its row of highest order: a subquery with the model's name, so the
|
||||
rest of the SQL (filters, strata, counts) reads it as it reads the model, plus the period's bounds.
|
||||
|
||||
A unit is in when it entered by the period's end and hadn't left before its start; a later exit, or one not
|
||||
yet dated or known by the cut-offs, doesn't count. Its rows are those dated before the period's end and by
|
||||
the event cut-off, and known by the knowledge cut-off.
|
||||
"""
|
||||
rule, base, p = self.status, self.events, self.periods.c
|
||||
col = lambda name: base.c[self.d.dimensions[name]] # noqa: E731
|
||||
when, unit = base.c[self.d.time_dimension], base.c[self.d.numerator.measure_expr]
|
||||
conditions = [p.periodo_id == self.q.period_id, when.is_not(None), when < p.fin, col(rule.entry) < p.fin]
|
||||
left = [col(rule.exit).is_not(None), col(rule.exit) < p.inicio]
|
||||
if self.q.event_cutoff is not None:
|
||||
conditions.append(when <= self.q.event_cutoff.isoformat())
|
||||
left.append(col(rule.exit) <= self.q.event_cutoff.isoformat())
|
||||
if self.q.knowledge_cutoff is not None:
|
||||
conditions += [col(n) <= self.q.knowledge_cutoff for n in rule.known_at]
|
||||
if rule.exit_known:
|
||||
left += [col(rule.exit_known).is_not(None), col(rule.exit_known) <= self.q.knowledge_cutoff]
|
||||
conditions.append(case((and_(*left), 1), else_=0) == 0)
|
||||
order = [desc(col(rule.order))] if rule.order else [desc(when)]
|
||||
ranked = (select(*base.c, p.periodo_id.label("periodo_id"), p.inicio.label("periodo_inicio"),
|
||||
p.fin.label("periodo_fin"),
|
||||
func.row_number().over(partition_by=unit, order_by=order).label("lugar_al_fin"))
|
||||
.select_from(base.join(self.periods, true())).where(*conditions).subquery("al_fin_del_periodo"))
|
||||
return (select(*(c for c in ranked.c if c.name != "lugar_al_fin")).where(ranked.c.lugar_al_fin == 1)
|
||||
.subquery(self.d.relation))
|
||||
|
||||
def _in_question(self):
|
||||
if self.status is not None:
|
||||
return self.events.c.periodo_id == self.q.period_id
|
||||
when, p = self.events.c[self.d.time_dimension], self.periods.c
|
||||
conditions = [p.periodo_id == self.q.period_id]
|
||||
if self.q.event_cutoff is not None:
|
||||
@@ -233,12 +392,16 @@ class MeasureQueries:
|
||||
return and_(*conditions)
|
||||
|
||||
def _from(self, *, with_strata: bool):
|
||||
if self.status is not None:
|
||||
if with_strata and any(s.kind not in (COLUMN, OF_THE_CHOSEN) for s in self.d.strata):
|
||||
raise NotImplementedError(f"{self.d.url}: a status at the period's end takes column strata only")
|
||||
return self.events
|
||||
when, p = self.events.c[self.d.time_dimension], self.periods.c
|
||||
joined = self.events.join(self.periods, and_(when >= p.inicio, when < p.fin))
|
||||
if not with_strata:
|
||||
return joined
|
||||
for stratum in self.d.strata:
|
||||
if stratum.kind == OF_THE_CHOSEN:
|
||||
if stratum.kind in (OF_THE_CHOSEN, COLUMN):
|
||||
continue
|
||||
if stratum.kind == AGE_AT_PERIOD_START:
|
||||
joined = (joined
|
||||
@@ -252,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.
|
||||
@@ -263,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))
|
||||
@@ -283,6 +451,8 @@ class MeasureQueries:
|
||||
return func.coalesce(self.age_groups.c.etiqueta, NO_DATA)
|
||||
if stratum.kind == OF_THE_CHOSEN:
|
||||
return self._column(stratum.spec["valor"])
|
||||
if stratum.kind == COLUMN:
|
||||
return func.coalesce(self._column(stratum.spec["columna"]), NO_DATA)
|
||||
had = self._timeline(stratum).c
|
||||
|
||||
def holds(alternative: dict):
|
||||
@@ -306,9 +476,15 @@ class MeasureQueries:
|
||||
return (select(value, *self._cells()).select_from(self._from(with_strata=True))
|
||||
.where(self._in_question()).group_by(value))
|
||||
|
||||
def excluded(self) -> Select:
|
||||
"""The units of the measure's exclusion (`meta.exclusion`): in the period, but out of its denominator."""
|
||||
unit, condition = self.events.c[self.d.exclusion.measure_expr], self._filter(self.d.exclusion)
|
||||
counted = unit if condition is None else case((condition, unit))
|
||||
return select(func.count(distinct(counted))).select_from(self._from(with_strata=False)).where(self._in_question())
|
||||
|
||||
def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]:
|
||||
"""What `INSERT … SELECT` writes: each unit in each population code, then each unit's value of each stratum."""
|
||||
for population in (self.d.denominator, self.d.numerator):
|
||||
for population in (self.d.denominator, self.d.numerator, *((self.d.exclusion,) if self.d.exclusion else ())):
|
||||
unit = self.events.c[population.measure_expr]
|
||||
condition = self._filter(population)
|
||||
where = self._in_question() if condition is None else and_(self._in_question(), condition)
|
||||
@@ -372,6 +548,8 @@ class Answer:
|
||||
total: Counts
|
||||
strata: dict[str, dict[str, Counts]]
|
||||
stored_before: bool
|
||||
groups: dict[str, Counts] = dataclasses.field(default_factory=dict) # by group, for a measure with several
|
||||
excluded: int | None = None # the units of its exclusion, when it has one
|
||||
|
||||
@property
|
||||
def numerator(self) -> int:
|
||||
@@ -397,7 +575,8 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p
|
||||
key, key_sha = key_of(definition, question, values)
|
||||
stored = history.find(definition.url, key_sha)
|
||||
if stored is not None:
|
||||
return _from_counts(definition, stored, history.counts(stored))
|
||||
return _from_counts(definition, stored, history.counts(stored),
|
||||
history.group_counts(stored) if definition.groups else {})
|
||||
|
||||
period = periods.get(question.period_id)
|
||||
if period is None:
|
||||
@@ -408,6 +587,13 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p
|
||||
for stratum in definition.strata:
|
||||
_, cells = queries.rows(sql.counts_by_stratum(stratum))
|
||||
strata[stratum.name] = {value: Counts(n, d) for value, n, d in cells}
|
||||
excluded = queries.rows(sql.excluded())[1][0][0] if definition.exclusion else None
|
||||
group_sql, groups = [], {}
|
||||
for group in definition.groups:
|
||||
g = MeasureQueries(definition.for_group(group), question, values, periods.model.__table__)
|
||||
_, ((n, d),) = queries.rows(g.counts())
|
||||
groups[group.name] = Counts(n, d)
|
||||
group_sql.append(g)
|
||||
models = import_module(f"core.{project}.indicadores.models")
|
||||
(any_rule,) = parameters.list(limit=1)
|
||||
report = models.MeasureReport(
|
||||
@@ -418,15 +604,21 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p
|
||||
status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc),
|
||||
agregacion_version=AGGREGATION_VERSION,
|
||||
huella=hashlib.sha256(json.dumps([key_sha, numerator, denominator, sorted(
|
||||
(s, v, c.numerator, c.denominator) for s, cells in strata.items() for v, c in cells.items())]).encode()
|
||||
(s, v, c.numerator, c.denominator) for s, cells in strata.items() for v, c in cells.items()),
|
||||
excluded, sorted((g, c.numerator, c.denominator) for g, c in groups.items())]).encode()
|
||||
).hexdigest(),
|
||||
)
|
||||
report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad,
|
||||
models.MeasureReportUnidadEstrato))
|
||||
return Answer(report_id, Counts(numerator, denominator), strata, stored_before=False)
|
||||
|
||||
def rows(rid):
|
||||
for queries_of in (sql, *group_sql):
|
||||
yield from queries_of.rows(rid, models.MeasureReportUnidad, models.MeasureReportUnidadEstrato)
|
||||
|
||||
report_id = history.record(report, rows)
|
||||
return Answer(report_id, Counts(numerator, denominator), strata, stored_before=False, groups=groups,
|
||||
excluded=excluded)
|
||||
|
||||
|
||||
def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict) -> Answer:
|
||||
def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict, by_group: dict | None = None) -> Answer:
|
||||
numerator, denominator = (f"{definition.measure_id}.{c}" for c in (definition.numerator.codes[0],
|
||||
definition.denominator.codes[0]))
|
||||
cells: dict[tuple[str, str], list[int]] = {}
|
||||
@@ -440,7 +632,19 @@ def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict) ->
|
||||
for (stratum, value), (n, d) in cells.items():
|
||||
if stratum != TOTAL:
|
||||
strata.setdefault(stratum, {})[value] = Counts(n, d)
|
||||
return Answer(report_id, Counts(*cells.get((TOTAL, TOTAL), (0, 0))), strata, stored_before=True)
|
||||
excluded = None
|
||||
if definition.exclusion is not None:
|
||||
code = f"{definition.measure_id}.{definition.exclusion.codes[0]}"
|
||||
excluded = sum(n for (stratum, _, resultado, _), n in counts.items() if stratum == TOTAL and resultado == code)
|
||||
groups = {}
|
||||
if definition.groups:
|
||||
by_group = by_group or {}
|
||||
groups = {g.name: Counts(by_group.get((g.name, numerator), 0), by_group.get((g.name, denominator), 0))
|
||||
for g in definition.groups}
|
||||
totals = Counts(by_group.get((definition.group, numerator), 0), by_group.get((definition.group, denominator), 0))
|
||||
else:
|
||||
totals = Counts(*cells.get((TOTAL, TOTAL), (0, 0)))
|
||||
return Answer(report_id, totals, strata, stored_before=True, groups=groups, excluded=excluded)
|
||||
|
||||
|
||||
# --- the contract --------------------------------------------------------------------------------------------------
|
||||
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
"""Measuring and training document extraction against an answer key (VAR-04, VARM-05).
|
||||
|
||||
python -m webapi.nlp evaluate --documents <folder> --key <key.json> [--with-values] [--no-ranker]
|
||||
python -m webapi.nlp train --documents <folder> --key <key.json>
|
||||
|
||||
The key is JSON: per document file name, per import target, per field, the right value (`null` for a field that
|
||||
must stay empty); fields left out are not scored.
|
||||
|
||||
{"reporte_01.pdf": {"cacu.BiopsiaCervical": {"bx_cin_grado": "LIEBG", "bx_fecha_reporte": "2025-01-31"}}}
|
||||
|
||||
Each document is read as one record. `evaluate` prints precision, recall and F1 per field and overall, with the
|
||||
domain's current ranker (`models.io.extraction_ranker`) unless `--no-ranker`; errors list which document and
|
||||
field, and their values only with `--with-values`. `train` first estimates how a ranker trained on the key would do
|
||||
on documents it has not seen (leaving each document out in turn), then teaches the domain's ranker the whole key and
|
||||
registers it as a new DEV version, which a person promotes like any model.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from extraction import DocumentExtractor, read_document
|
||||
from extraction.nlp.evaluation import evaluate
|
||||
from extraction.nlp.ranking import LearnedRanker, examples_for, same_value
|
||||
from extraction.readers import supported_extensions
|
||||
from extraction.segmentation import WholeDocument
|
||||
from webapi.imports.schemas.field_specs import field_specs_for, foreign_subjects_for, key_field_for, subject_for
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
|
||||
def _documents(folder: Path, names) -> dict[str, Any]:
|
||||
extensions = tuple(supported_extensions())
|
||||
found = {}
|
||||
for name in names:
|
||||
path = folder / name
|
||||
if not path.is_file() or not path.name.lower().endswith(extensions):
|
||||
raise SystemExit(f"no se encontró el documento {name} en {folder}")
|
||||
found[name] = read_document(name, path.read_bytes())
|
||||
return found
|
||||
|
||||
|
||||
def _extractor(target: str, ranker) -> DocumentExtractor:
|
||||
entity = ENTITY_REGISTRY.get(target)
|
||||
if entity is None:
|
||||
raise SystemExit(f"destino desconocido: {target}")
|
||||
return DocumentExtractor(
|
||||
field_specs_for(entity), key_field=key_field_for(entity), segmenter=WholeDocument(), merger=None,
|
||||
subject=subject_for(entity), foreign=foreign_subjects_for(entity), ranker=ranker,
|
||||
)
|
||||
|
||||
|
||||
def _records(documents: dict[str, Any], key: dict[str, dict[str, dict[str, Any]]], rankers: dict[str, Any]):
|
||||
"""Per (document, target): the extracted record."""
|
||||
records = {}
|
||||
for name, targets in key.items():
|
||||
for target in targets:
|
||||
extractor = _extractor(target, rankers.get(target.split(".", 1)[0]))
|
||||
[records[(name, target)]] = extractor.extract([documents[name]])[:1] or [None]
|
||||
return records
|
||||
|
||||
|
||||
def _scores(records, key) -> dict[str, Any]:
|
||||
extracted = {f"{name} · {target}": {f: v.value for f, v in record.values.items()} for (name, target), record in records.items() if record}
|
||||
expected = {f"{name} · {target}": fields for name, targets in key.items() for target, fields in targets.items()}
|
||||
return evaluate(extracted, expected)
|
||||
|
||||
|
||||
def _examples(records, key) -> tuple[dict[str, list], dict[str, dict[str, int]]]:
|
||||
"""Per domain, the labelled examples of every record, and per field how many right values no candidate had."""
|
||||
examples: dict[str, list] = {}
|
||||
unreachable: dict[str, dict[str, int]] = {}
|
||||
for (name, target), record in records.items():
|
||||
if record is None:
|
||||
continue
|
||||
domain = target.split(".", 1)[0]
|
||||
specs = field_specs_for(ENTITY_REGISTRY[target])
|
||||
truth = key[name][target]
|
||||
examples.setdefault(domain, []).extend(examples_for(specs, record.candidates, truth))
|
||||
missing = unreachable.setdefault(domain, {})
|
||||
for field, value in truth.items():
|
||||
if value is not None and not any(same_value(c.value, value) for c in record.candidates.get(field, ())):
|
||||
missing[field] = missing.get(field, 0) + 1
|
||||
return examples, unreachable
|
||||
|
||||
|
||||
def _current_rankers(domains) -> dict[str, Any]:
|
||||
from models.io.extraction_ranker import current
|
||||
|
||||
return {domain: current(domain) for domain in domains}
|
||||
|
||||
|
||||
def command_evaluate(args) -> dict[str, Any]:
|
||||
key = json.loads(Path(args.key).read_text())
|
||||
documents = _documents(Path(args.documents), key)
|
||||
domains = {target.split(".", 1)[0] for targets in key.values() for target in targets}
|
||||
rankers = {} if args.no_ranker else _current_rankers(domains)
|
||||
result = _scores(_records(documents, key, rankers), key).to_dict(with_values=args.with_values)
|
||||
result["rankers"] = {domain: getattr(ranker, "version", None) for domain, ranker in rankers.items()}
|
||||
return result
|
||||
|
||||
|
||||
def command_train(args) -> dict[str, Any]:
|
||||
from models.io.extraction_ranker import Batch, learn
|
||||
|
||||
key = json.loads(Path(args.key).read_text())
|
||||
documents = _documents(Path(args.documents), key)
|
||||
records = _records(documents, key, {})
|
||||
held_out = {}
|
||||
for left_out in key:
|
||||
training = {k: v for k, v in records.items() if k[0] != left_out}
|
||||
examples, _ = _examples(training, key)
|
||||
rankers = {domain: _trained(batch) for domain, batch in examples.items()}
|
||||
held_out.update({k: v for k, v in _records({left_out: documents[left_out]}, {left_out: key[left_out]}, rankers).items()})
|
||||
estimate = _scores(held_out, key).to_dict()
|
||||
examples, unreachable = _examples(records, key)
|
||||
versions = {}
|
||||
for domain, batch in examples.items():
|
||||
documents_in_domain = len({name for (name, target) in records if target.startswith(f"{domain}.")})
|
||||
records_in_domain = sum(1 for (_, target) in records if target.startswith(f"{domain}."))
|
||||
versions[domain] = learn(domain, Batch(batch, "clave", documents_in_domain, records_in_domain, unreachable.get(domain, {})))
|
||||
return {
|
||||
"sin_ranker": _scores(records, key).to_dict()["global"],
|
||||
"estimacion_dejando_uno_fuera": estimate["global"],
|
||||
"versiones": versions,
|
||||
}
|
||||
|
||||
|
||||
def _trained(examples) -> LearnedRanker:
|
||||
ranker = LearnedRanker()
|
||||
ranker.learn(examples)
|
||||
return ranker
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="python -m webapi.nlp", description=__doc__.split("\n\n")[0])
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
for name in ("evaluate", "train"):
|
||||
command = commands.add_parser(name)
|
||||
command.add_argument("--documents", required=True, help="carpeta con los documentos")
|
||||
command.add_argument("--key", required=True, help="JSON con los valores correctos")
|
||||
if name == "evaluate":
|
||||
command.add_argument("--with-values", action="store_true", help="incluir los valores de cada error")
|
||||
command.add_argument("--no-ranker", action="store_true", help="ordenar candidatos solo por confianza")
|
||||
args = parser.parse_args(argv)
|
||||
result = command_evaluate(args) if args.command == "evaluate" else command_train(args)
|
||||
json.dump(result, sys.stdout, ensure_ascii=False, indent=1, default=str)
|
||||
sys.stdout.write("\n")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -13,9 +13,10 @@ from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.estimators import live_estimators
|
||||
from webapi.orchestration.runner import run
|
||||
|
||||
PROJECTS = ("cacu", "cama")
|
||||
PROJECTS = ("cacu", "cama", "tea")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> None:
|
||||
@@ -42,7 +43,8 @@ def main(argv: list[str] | None = None) -> None:
|
||||
print(f"lote {args.lote_id}: {cambiadas} evaluaciones {'anuladas' if args.void else 'confirmadas'}")
|
||||
return
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||
ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters)
|
||||
ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters,
|
||||
estimators=live_estimators(args.project))
|
||||
for paso in run(ctx, only=args.only):
|
||||
print(f"{paso.name:20} {paso.seconds:6.1f} s")
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ from webapi.orchestration.reference.support import (
|
||||
grupos_de_edad_de,
|
||||
)
|
||||
from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo
|
||||
from webapi.orchestration.reference.source_mapping import catalog_rows
|
||||
from webapi.orchestration.reference.rules import (
|
||||
RUTA_PARAMETROS,
|
||||
leer_parametros,
|
||||
@@ -66,9 +67,18 @@ def migrate(ctx: Context) -> str:
|
||||
|
||||
|
||||
def catalogs(migrate: str, ctx: Context) -> dict[str, int]:
|
||||
"""`core/catalogos/<proyecto>.toml` -> `cat_estudio`, `cat_resultado`, `cat_valor`: agrega, actualiza y retira; no borra."""
|
||||
"""`core/catalogos/<proyecto>.toml` -> `cat_estudio`, `cat_resultado`, `cat_valor`: agrega, actualiza y retira; no borra.
|
||||
|
||||
Then the catalog's own mappings (`cat_mapeo`, system `catalogo`): only the forms with no row yet are added, so a
|
||||
mapping edited in the application survives every deploy."""
|
||||
catalogo = catalogo_desde_toml(ruta_de_catalogo(ctx.project), tablas=tablas_de(ctx.project))
|
||||
return ctx.repos.silver.catalogs.sync(catalogo.estudios, catalogo.resultados, catalogo.valores)
|
||||
counts = ctx.repos.silver.catalogs.sync(catalogo.estudios, catalogo.resultados, catalogo.valores)
|
||||
mappings = ctx.repos.silver.mappings
|
||||
if mappings is not None:
|
||||
system, rows = catalog_rows(ctx.project, mappings)
|
||||
mappings.ensure_system(system)
|
||||
counts["mapeos_nuevos"] = mappings.seed(rows)
|
||||
return counts
|
||||
|
||||
|
||||
def load(catalogs: dict[str, int], ctx: Context) -> SQLModel:
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with the model version
|
||||
its domain has in production.
|
||||
|
||||
`estimate` hands an estimator the cohort build's wide frame (`estimar(columnas, filas)`, `procedencia()`,
|
||||
`desenlace`): one column per the cohort's own variables. A registered model's predictors are a different, larger
|
||||
set, read from the build's exported file (the same export `python -m models cohorts export` writes), so an
|
||||
estimator here ignores the wide frame and rebuilds the model's own input: the cycle's latest build for membership,
|
||||
the domain's timeline for the events, then the production version in MLflow to score it. `estimar`'s arguments go
|
||||
unused by design.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Provenance:
|
||||
modelo_nombre: str
|
||||
modelo_version: str
|
||||
mlflow_run_id: str
|
||||
modelo_sha: str | None
|
||||
|
||||
def como_dict(self) -> dict[str, str]:
|
||||
return {key: value for key, value in self.__dict__.items() if value}
|
||||
|
||||
|
||||
class Cin2LogisticEstimator:
|
||||
"""Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`, to
|
||||
test a candidate). Offered by `live_estimators` only once that version exists, so `procedencia` always has
|
||||
something to report when `estimate` calls it."""
|
||||
|
||||
def __init__(self, domain: str = "cacu", version: str | None = None):
|
||||
self.domain = domain
|
||||
self.version = version
|
||||
self.desenlace = "cin2_mas"
|
||||
self._provenance: Provenance | None = None
|
||||
|
||||
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]:
|
||||
import mlflow.pyfunc
|
||||
from persistance.settings import settings
|
||||
|
||||
from models.cacu.cin2_logistic.model import SETTINGS
|
||||
from models.io.registry import registered_name, registry
|
||||
from models.io.storage import cohorts_root, read_cohort
|
||||
from models.pipelines.export_cohort import export_kit_build
|
||||
from models.steps.risks import risk_rows
|
||||
|
||||
repos = import_module(f"persistance.{self.domain}")
|
||||
url = SETTINGS["cohort"]
|
||||
build_id = repos.cohort_repository.latest_build(url)
|
||||
resolved = registry.resolve(self.domain, SETTINGS["scenario"], self.version)
|
||||
root = cohorts_root(getattr(settings, f"{self.domain}_database_url"))
|
||||
path, _ = export_kit_build(repos.cohort_repository, repos.timeline_repository, root, self.domain, url, build_id)
|
||||
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(path))
|
||||
window = SETTINGS["outcome_window_months"]
|
||||
self.desenlace = f"cin2_{window}m"
|
||||
self._provenance = Provenance(
|
||||
modelo_nombre=registered_name(self.domain, SETTINGS["scenario"]), modelo_version=resolved.version,
|
||||
mlflow_run_id=resolved.run_id, modelo_sha=resolved.modelo_sha)
|
||||
return [tuple(row) for row in risk_rows(risks, window / 12)]
|
||||
|
||||
def procedencia(self) -> Provenance:
|
||||
if self._provenance is None:
|
||||
raise RuntimeError("estimar() runs before procedencia()")
|
||||
return self._provenance
|
||||
|
||||
|
||||
def live_estimators(domain: str) -> dict[str, Any]:
|
||||
"""The estimators of a domain's cohorts whose model has a version in production, by cohort url. Empty where
|
||||
none is in production yet, the same as no estimator being configured: `estimate` then does nothing."""
|
||||
if domain != "cacu":
|
||||
return {}
|
||||
from models.cacu.cin2_logistic.model import SETTINGS
|
||||
from models.io.registry import registry
|
||||
|
||||
try:
|
||||
registry.resolve(domain, SETTINGS["scenario"])
|
||||
except LookupError:
|
||||
return {}
|
||||
return {SETTINGS["cohort"]: Cin2LogisticEstimator(domain)}
|
||||
@@ -18,6 +18,7 @@ import core
|
||||
from core.indicadores.catalogos import TIPOS_DE_VALOR
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
from webapi.orchestration.reference.source_mapping import check_function, from_result
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
# Los catálogos viven en Core, junto a los modelos de sus tablas.
|
||||
@@ -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,
|
||||
@@ -77,6 +79,40 @@ def catalogo_desde_toml(ruta: Path, *, tablas: TablasKit) -> Catalogo:
|
||||
return Catalogo(estudios, resultados, valores)
|
||||
|
||||
|
||||
def add_resultado(
|
||||
proyecto: str, *, estudio_id: str, nombre: str, etiqueta: str, tipo_valor: str, estudio_etiqueta: str | None = None
|
||||
) -> str:
|
||||
"""Appends a new `resultado_id` to the project's TOML (not to the
|
||||
database): a `[estudio.resultados.nombre]` table, and the `[estudio]`
|
||||
table too if it didn't exist yet. The file stays the source: the next
|
||||
`catalogo_desde_toml` already brings it, and whoever syncs the table
|
||||
writes it.
|
||||
|
||||
Idempotent: if the resultado is already in the file, nothing is
|
||||
written and its `resultado_id` is returned as is. `nombre` must be a
|
||||
valid TOML key (whoever discovers the field builds it, e.g. from a
|
||||
slug of the text found).
|
||||
"""
|
||||
if tipo_valor not in TIPOS_DE_VALOR:
|
||||
raise CatalogoInvalido(f"{estudio_id}.{nombre}: tipo_valor {tipo_valor!r} no es uno de {', '.join(TIPOS_DE_VALOR)}.")
|
||||
ruta = ruta_de_catalogo(proyecto)
|
||||
existentes = _leer(ruta)
|
||||
resultado_id = f"{estudio_id}.{nombre}"
|
||||
if estudio_id in existentes and nombre in existentes[estudio_id].get("resultados", {}):
|
||||
return resultado_id
|
||||
blocks = []
|
||||
if estudio_id not in existentes:
|
||||
blocks.append(f'\n[{estudio_id}]\netiqueta = "{_escape(estudio_etiqueta or estudio_id)}"\n')
|
||||
blocks.append(f'\n[{estudio_id}.resultados.{nombre}]\netiqueta = "{_escape(etiqueta)}"\ntipo_valor = "{tipo_valor}"\n')
|
||||
with Path(ruta).open("a", encoding="utf-8") as archivo:
|
||||
archivo.write("".join(blocks))
|
||||
return resultado_id
|
||||
|
||||
|
||||
def _escape(text: str) -> str:
|
||||
return text.replace("\\", "\\\\").replace('"', '\\"')
|
||||
|
||||
|
||||
def codigos_hospital(proyecto: str) -> dict[str, str]:
|
||||
"""Código del hospital -> `estudio_id`, del catálogo del proyecto.
|
||||
|
||||
@@ -93,6 +129,60 @@ 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 its spellings a function into
|
||||
its values (`source_mapping.check_function`)."""
|
||||
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.")
|
||||
try:
|
||||
check_function(from_result(resultado_id, resultado))
|
||||
except ValueError as e:
|
||||
raise CatalogoInvalido(str(e)) from None
|
||||
|
||||
|
||||
def _leer(ruta: Path) -> dict:
|
||||
return tomllib.loads(Path(ruta).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@@ -51,12 +51,6 @@ valor = 1
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta T-21g: el horizonte de `cama/cohorte_tamizaje` (sin definir, MD-Q14). Decide clínica con modelos (MD-Q5)"
|
||||
|
||||
[tea.riesgos.horizonte_banda]
|
||||
# Años desde el M-CHAT índice: el horizonte del desenlace de la cohorte de tamizaje (48 meses).
|
||||
valor = 4
|
||||
estado = "provisional"
|
||||
fuente = "Responsable de TEA, 2026-10-21: 48 meses. Sin uso mientras la cohorte de TEA sea propuesta (T-21h)"
|
||||
|
||||
[comun.catalogos.banda_riesgo]
|
||||
# Las bandas del resumen de riesgos, de menor a mayor.
|
||||
valor = [
|
||||
@@ -90,10 +84,10 @@ estado = "provisional"
|
||||
fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). Cortes del grupo blanco (indicadores_kit_0), sin confirmar"
|
||||
|
||||
# ===========================================================================
|
||||
# TEA · los 18 indicadores de ulises (M2 a M19, K1 a K8)
|
||||
# TEA · the screening's indicators (M21 to M30)
|
||||
#
|
||||
# Copia de ulises/parametros.toml, con el prefijo "tea.". La clave es la
|
||||
# ruta con puntos: [tea.cohorte.edad_min_meses] -> "tea.cohorte.edad_min_meses".
|
||||
# The key is the dotted path: [tea.cohorte.edad_min_meses] -> "tea.cohorte.edad_min_meses".
|
||||
# The measures read their rules from dbt's var `tea` (Transformation/dbt_project.yml), which holds the same values.
|
||||
# Las listas y tablas se guardan en def_parametro como JSON.
|
||||
# El umbral de supresión es comun.umbral_supresion; tea.supresion.activa lo apaga.
|
||||
# Documentos citados (repositorio analisis-tea, carpeta docs/):
|
||||
@@ -102,9 +96,10 @@ fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-1
|
||||
# ===========================================================================
|
||||
|
||||
[tea.cohorte.edad_min_meses]
|
||||
# The cohort: children whose first M-CHAT was at 16 to 36 completed months.
|
||||
valor = 16
|
||||
estado = "confirmado"
|
||||
fuente = "contexto §1: ADOS-2 y EEG ligado, de 16 a 36 meses cumplidos a la fecha del EEG (director)"
|
||||
fuente = "Responsable del proyecto, 2026-11-11: edad cumplida al primer M-CHAT, de 16 a 36 meses"
|
||||
|
||||
[tea.cohorte.edad_max_meses]
|
||||
valor = 36
|
||||
@@ -117,97 +112,23 @@ valor = 30.4375
|
||||
estado = "confirmado"
|
||||
fuente = "analisis-tea/tea/comun.py, edad_meses"
|
||||
|
||||
[tea.cohorte.plazo_ados2_eeg_dias]
|
||||
# ADOS-2 y EEG a este número de días o menos, en cualquier orden: solo marca diagnostico_eeg_en_plazo.
|
||||
valor = 30
|
||||
estado = "confirmado"
|
||||
fuente = "contexto §1: más de un mes de diferencia afecta la validez (director)"
|
||||
|
||||
[tea.cohorte.ventanas]
|
||||
# Ventanas madurativas por meses cumplidos a la fecha del EEG, sin huecos.
|
||||
# Age groups, by completed months at the first M-CHAT, without gaps: the windows of the TEA page.
|
||||
valor = [
|
||||
{ clave = "V1_16_23", desde = 16, hasta = 23, etiqueta = "16 a 23 meses", color = "#9DBFE3" },
|
||||
{ clave = "V2_24_30", desde = 24, hasta = 30, etiqueta = "24 a 30 meses", color = "#5E93CC" },
|
||||
{ clave = "V3_31_36", desde = 31, hasta = 36, etiqueta = "31 a 36 meses", color = "#1B4A80" },
|
||||
{ clave = "16_23", desde = 16, hasta = 23, etiqueta = "16 a 23 meses", color = "#9DBFE3" },
|
||||
{ clave = "24_29", desde = 24, hasta = 29, etiqueta = "24 a 29 meses", color = "#5E93CC" },
|
||||
{ clave = "30_36", desde = 30, hasta = 36, etiqueta = "30 a 36 meses", color = "#1B4A80" },
|
||||
]
|
||||
estado = "confirmado"
|
||||
fuente = "contexto §1: revisión bibliográfica del proyecto. Colores: paleta de ejemplo (provisional)"
|
||||
|
||||
[tea.instrumentos.informantes_ramos]
|
||||
# Orden de preferencia cuando contestaron varios: la madre; si no contestó, el padre.
|
||||
valor = ["MADRE", "PADRE", "OTRO_CUIDADOR", "NO_REGISTRADO"]
|
||||
estado = "confirmado"
|
||||
fuente = "contexto §1 (equipo); psicología no registra al cuidador principal"
|
||||
|
||||
[tea.instrumentos.informantes_otros]
|
||||
valor = ["MADRE", "PADRE", "OTRO_CUIDADOR", "OBSERVACION_CLINICA", "MAESTRO", "NO_REGISTRADO"]
|
||||
estado = "confirmado"
|
||||
fuente = "analisis-tea/tea/config.py, INFORMANTE_PRIORIDAD['_otros']; confirmado por el responsable de TEA, 2026-10-21"
|
||||
|
||||
[tea.ramos.areas]
|
||||
# «TOTAL» no cuenta como área.
|
||||
valor = [
|
||||
{ clave = "COGNOSCITIVO", etiqueta = "Cognoscitivo" },
|
||||
{ clave = "LINGUISTICO", etiqueta = "Lingüístico" },
|
||||
{ clave = "FISICO", etiqueta = "Físico" },
|
||||
{ clave = "SOCIOEMOCIONAL", etiqueta = "Socioemocional" },
|
||||
{ clave = "ADAPTATIVO", etiqueta = "Adaptativo" },
|
||||
]
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2, catálogo de ins_area; contexto §1"
|
||||
|
||||
[tea.poblacion.css_min_tea]
|
||||
# M21 y M22: TEA positivo si el CSS del ADOS-2 es al menos este valor.
|
||||
valor = 3
|
||||
estado = "confirmado"
|
||||
fuente = "responsable de TEA, 2026-10-21: CSS de 3 a 4, espectro; de 5 a 10, autismo"
|
||||
fuente = "Responsable del proyecto, 2026-11-10: las ventanas de la página de TEA. Colores: paleta de ejemplo (provisional)"
|
||||
|
||||
[tea.diagnostico.cie_tea]
|
||||
# M24 y M25: códigos CIE-10 de la nota médica que confirman el diagnóstico, sin punto (F84.0 -> F840).
|
||||
# M21 to M25: ICD-10 codes of the neuropediatrics note that confirm the diagnosis, without the dot (F84.0 -> F840).
|
||||
# F84 without its subcode doesn't count.
|
||||
valor = ["F840"]
|
||||
estado = "confirmado"
|
||||
fuente = "usuario (2026-10-15): solo F84.0 (autismo)"
|
||||
|
||||
[tea.diagnostico.instrumentos_mchat]
|
||||
# M25: valores de psi_instrumento_tamizaje que son un M-CHAT.
|
||||
valor = ["M_CHAT_R", "M_CHAT_RF"]
|
||||
estado = "confirmado"
|
||||
fuente = "Core, enum InstrumentoTamizaje (psi_instrumento_tamizaje)"
|
||||
|
||||
[tea.atencion.plazo_referencia_evaluacion_dias]
|
||||
# K1: inicio de la evaluación a más tardar este número de días después de la referencia.
|
||||
valor = 90
|
||||
estado = "confirmado"
|
||||
fuente = "estandares: NICE QS51, enunciado 1 (3 meses)"
|
||||
|
||||
[tea.parto.apgar_corte]
|
||||
# Apgar a los 5 minutos: menor de este valor, igual, y mayor (8 a 10).
|
||||
valor = 7
|
||||
estado = "confirmado"
|
||||
fuente = "lista, M17: menor de 7, 7, y 8 a 10"
|
||||
|
||||
# Las cuatro reglas siguientes las usa el mapeo (tea/mapeo.py) al cargar:
|
||||
# un cambio pide volver a cargar.
|
||||
[tea.antecedentes_maternos.no_registrado]
|
||||
valor = "NO_REGISTRADO"
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2: NO_REGISTRADO = sin dato"
|
||||
|
||||
[tea.antecedentes_maternos.hipertension_ninguno]
|
||||
valor = "NINGUNO"
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2, catálogo de amg_hipertension_preeclampsia"
|
||||
|
||||
[tea.antecedentes_maternos.embarazo_no_unico]
|
||||
valor = ["GEMELAR", "TRIPLE_O_MAS"]
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2, catálogo de amg_embarazo_multiple"
|
||||
|
||||
[tea.antecedentes_maternos.liquido_anormal]
|
||||
valor = ["OLIGOHIDRAMNIOS", "POLIHIDRAMNIOS"]
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2, catálogo de amg_liquido_amniotico"
|
||||
|
||||
[tea.supresion.activa]
|
||||
# Apagada: el tablero es de uso interno del equipo y los médicos. Con false no se
|
||||
# suprime nada, aunque comun.umbral_supresion tenga valor.
|
||||
@@ -232,54 +153,6 @@ valor = { etiqueta = "Sin dato", color = "#C9CDD2" }
|
||||
estado = "confirmado"
|
||||
fuente = "lista: «sin dato» siempre se muestra como categoría propia"
|
||||
|
||||
[tea.catalogos.sexo]
|
||||
valor = [
|
||||
{ clave = "F", etiqueta = "Femenino", color = "#E0A030" },
|
||||
{ clave = "M", etiqueta = "Masculino", color = "#2F6DB3" },
|
||||
{ clave = "I", etiqueta = "Indeterminado", color = "#8A9199" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "spec v2, pac_sexo; colores provisionales"
|
||||
|
||||
[tea.catalogos.resultado_mchat]
|
||||
valor = [
|
||||
{ clave = "RIESGO_BAJO", etiqueta = "Riesgo bajo", color = "#F3E6D3" },
|
||||
{ clave = "RIESGO_MEDIO", etiqueta = "Riesgo medio", color = "#E8C28E" },
|
||||
{ clave = "RIESGO_ALTO", etiqueta = "Riesgo alto", color = "#B55A1F" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "spec v2, interpretación del M-CHAT-R/F (bajo 0–2, medio 3–7, alto 8–20); colores provisionales"
|
||||
|
||||
[tea.catalogos.interpretacion_ramos]
|
||||
valor = [
|
||||
{ clave = "DESARROLLO_ADECUADO", etiqueta = "Desarrollo adecuado", color = "#9DBFE3" },
|
||||
{ clave = "MONITOREO", etiqueta = "Monitoreo", color = "#E8C28E" },
|
||||
{ clave = "RETRASO", etiqueta = "Retraso", color = "#B55A1F" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "nota_para_cargas.md, interpretación de Ramos; colores provisionales"
|
||||
|
||||
[tea.catalogos.grado_hipoacusia]
|
||||
valor = [
|
||||
{ clave = "NORMAL", etiqueta = "Normal", color = "#F3E6D3" },
|
||||
{ clave = "LEVE", etiqueta = "Leve", color = "#E8C28E" },
|
||||
{ clave = "MODERADA", etiqueta = "Moderada", color = "#D98E4A" },
|
||||
{ clave = "SEVERA", etiqueta = "Severa", color = "#B55A1F" },
|
||||
{ clave = "PROFUNDA", etiqueta = "Profunda", color = "#B55A1F" },
|
||||
{ clave = "NO_CONCLUYENTE", etiqueta = "No concluyente", color = "#8A9199" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "spec v2, pea_grado_hipoacusia; colores provisionales"
|
||||
|
||||
[tea.catalogos.apgar_5min]
|
||||
valor = [
|
||||
{ clave = "MENOR_7", etiqueta = "Menor de 7", color = "#B55A1F" },
|
||||
{ clave = "SIETE", etiqueta = "7", color = "#E8C28E" },
|
||||
{ clave = "OCHO_A_DIEZ", etiqueta = "8 a 10", color = "#9DBFE3" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "lista, M17; colores provisionales"
|
||||
|
||||
# ===========================================================================
|
||||
# CaCu · reglas de IND1 (movidas de campo/parametros_campo.toml)
|
||||
# ===========================================================================
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
"""How a source writes the catalog's values: a partial, non-injective function into a fixed set of codes.
|
||||
|
||||
A source form (a spelling, an abbreviation, a lab's own code) maps to one `valor_id` of one result:
|
||||
|
||||
f : (source system, resultado_id, normalized form, document date) -> valor_id
|
||||
|
||||
- non-injective: many forms give the same code ("3+", "Positivo (score 3)" -> H3);
|
||||
- partial: a form with no mapping gives nothing, and the observation keeps it as `valor_fuente`, counted as out of
|
||||
catalog, until a mapping is added;
|
||||
- per source system and per date: the same form may mean different codes at two labs, and a mapping applies to the
|
||||
documents dated within its validity;
|
||||
- into a fixed set: a mapping only names a `valor_id` the catalog defines (`cat_valor`).
|
||||
|
||||
For `f` to be a function, two mappings in force on the same date can't give the same key two codes:
|
||||
`check_function` rejects that, and `resolve` returns nothing for a key it still finds ambiguous, so the observation
|
||||
goes back to the out-of-catalog queue instead of keeping a code.
|
||||
|
||||
The mappings are stored in `cat_sistema_fuente` and `cat_mapeo`: the `catalogs` step seeds the catalog's own
|
||||
(`catalog_rows`, system `catalogo`, always in force) and never changes a stored row, and `register` adds one after
|
||||
checking it against the rows of the same form.
|
||||
"""
|
||||
|
||||
import tomllib
|
||||
from collections import defaultdict
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Iterable, NamedTuple
|
||||
|
||||
from extraction.nlp.text import fold
|
||||
|
||||
CATALOG = "catalogo" # the source system of the mappings written in the catalog's TOML
|
||||
|
||||
|
||||
class SourceForm(NamedTuple):
|
||||
"""One mapping: how `system` writes `value_id` of `result_id`, in force from `valid_from` to `valid_to`."""
|
||||
|
||||
system: str
|
||||
result_id: str
|
||||
form: str
|
||||
value_id: str
|
||||
valid_from: date | None = None # None: since always
|
||||
valid_to: date | None = None # None: while current
|
||||
|
||||
@property
|
||||
def key(self) -> tuple[str, str, str]:
|
||||
return self.system, self.result_id, normalize(self.form)
|
||||
|
||||
def in_force(self, on: date | None) -> bool:
|
||||
return on is None or ((self.valid_from is None or self.valid_from <= on)
|
||||
and (self.valid_to is None or on <= self.valid_to))
|
||||
|
||||
|
||||
class AmbiguousForm(NamedTuple):
|
||||
"""Two mappings of the same key whose validities overlap and whose codes differ."""
|
||||
|
||||
first: SourceForm
|
||||
second: SourceForm
|
||||
|
||||
|
||||
def normalize(form: str) -> str:
|
||||
"""What is compared: uppercase, without accents, single spaces."""
|
||||
return " ".join(fold(form).split())
|
||||
|
||||
|
||||
def ambiguities(rows: Iterable[SourceForm]) -> list[AmbiguousForm]:
|
||||
"""Every pair of mappings that would give one key two codes on some date."""
|
||||
by_key: dict[tuple, list[SourceForm]] = defaultdict(list)
|
||||
for row in rows:
|
||||
by_key[row.key].append(row)
|
||||
found = []
|
||||
for same_key in by_key.values():
|
||||
for i, a in enumerate(same_key):
|
||||
found += [AmbiguousForm(a, b) for b in same_key[i + 1:] if a.value_id != b.value_id and _overlap(a, b)]
|
||||
return found
|
||||
|
||||
|
||||
def check_function(rows: Iterable[SourceForm]) -> None:
|
||||
"""Raises `ValueError` naming each form that maps to two codes while both mappings are in force."""
|
||||
found = ambiguities(rows)
|
||||
if found:
|
||||
raise ValueError("; ".join(f"{a.first.result_id}: {a.first.form!r} se escribe igual para "
|
||||
f"{a.first.value_id!r} y {a.second.value_id!r}" for a in found) + ".")
|
||||
|
||||
|
||||
def resolve(rows: Iterable[SourceForm], system: str, result_id: str, form: str, on: date | None = None) -> str | None:
|
||||
"""The code `form` maps to on `on` for `system`; None when no mapping in force matches it or two disagree."""
|
||||
key = (system, result_id, normalize(form))
|
||||
codes = {r.value_id for r in rows if r.key == key and r.in_force(on)}
|
||||
return codes.pop() if len(codes) == 1 else None
|
||||
|
||||
|
||||
def from_result(result_id: str, result: dict, system: str = CATALOG) -> list[SourceForm]:
|
||||
"""A catalog result's mappings: each value's code, label and aliases, in force always."""
|
||||
return [SourceForm(system, result_id, form, value["valor"])
|
||||
for value in result.get("valores", ())
|
||||
for form in (value["valor"], value.get("etiqueta", ""), *value.get("alias", ())) if form.strip()]
|
||||
|
||||
|
||||
def _overlap(a: SourceForm, b: SourceForm) -> bool:
|
||||
starts_before_b_ends = a.valid_from is None or b.valid_to is None or a.valid_from <= b.valid_to
|
||||
b_starts_before_a_ends = b.valid_from is None or a.valid_to is None or b.valid_from <= a.valid_to
|
||||
return starts_before_b_ends and b_starts_before_a_ends
|
||||
|
||||
|
||||
# --- the mappings stored in `cat_sistema_fuente` and `cat_mapeo` ---
|
||||
|
||||
CATALOG_SINCE = date(1900, 1, 1) # the catalog's own mappings hold for every document
|
||||
|
||||
|
||||
def as_source_form(row) -> SourceForm:
|
||||
"""A `cat_mapeo` row as the function sees it: a study code maps to its `estudio_id`, a spelling to its value."""
|
||||
return SourceForm(row.sistema_fuente_id, row.resultado_id or "", row.forma, row.valor_id or row.estudio_id,
|
||||
row.vigente_desde, row.vigente_hasta)
|
||||
|
||||
|
||||
def check_stored(same_form: list, new) -> None:
|
||||
"""`SourceMappingRepository.add`'s check: a study code or a spelling stays a function with the new row. A
|
||||
caption may introduce several results (a receptor and its percentage), so it isn't checked."""
|
||||
if new.clase == "etiqueta":
|
||||
return
|
||||
check_function([as_source_form(r) for r in same_form if r.clase == new.clase] + [as_source_form(new)])
|
||||
|
||||
|
||||
def register(repository, *, sistema_fuente_id: str, clase: str, forma: str, registrado_por: str,
|
||||
vigente_desde: date, estudio_id: str | None = None, resultado_id: str | None = None,
|
||||
valor_id: str | None = None, motivo: str | None = None):
|
||||
"""Adds one mapping, rejected with `ValueError` if it makes a form give two codes while both are in force."""
|
||||
row = repository.model(
|
||||
sistema_fuente_id=sistema_fuente_id, clase=clase, forma=forma.strip(), forma_normalizada=normalize(forma),
|
||||
estudio_id=estudio_id, resultado_id=resultado_id, valor_id=valor_id, vigente_desde=vigente_desde,
|
||||
registrado_por=registrado_por, registrado_en=datetime.now(timezone.utc), motivo=motivo)
|
||||
return repository.add(row, check=check_stored)
|
||||
|
||||
|
||||
def catalog_rows(project: str, repository) -> tuple[object, list]:
|
||||
"""The catalog's source system and its mappings, from the TOML: study codes, captions, and each value's code,
|
||||
label and aliases. What `SourceMappingRepository.seed` adds when they're missing."""
|
||||
from webapi.orchestration.reference.catalogs import ruta_de_catalogo
|
||||
|
||||
system = repository.sistema(sistema_fuente_id=CATALOG, etiqueta="Catálogo del proyecto", fuente_tabla=None,
|
||||
vigente_desde=CATALOG_SINCE)
|
||||
now = datetime.now(timezone.utc)
|
||||
rows = {}
|
||||
|
||||
def add(clase, forma, **target):
|
||||
row = repository.model(sistema_fuente_id=CATALOG, clase=clase, forma=forma, forma_normalizada=normalize(forma),
|
||||
vigente_desde=CATALOG_SINCE, registrado_por=CATALOG, registrado_en=now, **target)
|
||||
rows.setdefault((clase, target.get("resultado_id"), target.get("estudio_id"), row.forma_normalizada), row)
|
||||
|
||||
for study_id, study in tomllib.loads(ruta_de_catalogo(project).read_text(encoding="utf-8")).items():
|
||||
for code in study.get("codigos_hospital", ()):
|
||||
add("estudio", code, estudio_id=study_id)
|
||||
for name, result in study.get("resultados", {}).items():
|
||||
result_id = f"{study_id}.{name}"
|
||||
for caption in result.get("etiquetas_fuente", ()):
|
||||
add("etiqueta", caption, resultado_id=result_id)
|
||||
for form in from_result(result_id, result):
|
||||
add("valor", form.form, resultado_id=result_id, valor_id=form.value_id)
|
||||
return system, list(rows.values())
|
||||
@@ -21,6 +21,7 @@ from persistance.edges.silver import (
|
||||
ObservationRepository,
|
||||
TimelineRepository,
|
||||
LinksRepository,
|
||||
SourceMappingRepository,
|
||||
ViewsRepository,
|
||||
)
|
||||
from persistance.materializer import Materializer
|
||||
@@ -43,6 +44,7 @@ class Silver:
|
||||
observation: ObservationRepository
|
||||
links: LinksRepository
|
||||
timeline: TimelineRepository | None = None # the patients' timeline: dbt's view, as the models and the strata read it
|
||||
mappings: SourceMappingRepository | None = None # how each source writes the catalog's codes
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -80,6 +82,7 @@ def repositories_of(proyecto: str) -> Repositories:
|
||||
observation=dominio.observation_period_repository,
|
||||
links=dominio.links_repository,
|
||||
timeline=dominio.timeline_repository,
|
||||
mappings=dominio.source_mapping_repository,
|
||||
),
|
||||
materializer=dominio.materializer,
|
||||
gold=Gold(
|
||||
|
||||
@@ -25,8 +25,9 @@ def event_views(manifest: Path, project: str) -> list:
|
||||
"""`drop view if exists` and `create view … as <compiled SQL>` for every model the project's measures read,
|
||||
parents first.
|
||||
|
||||
Those are the project's models semantic models count over (`models/<project>/…`) and the timelines its strata
|
||||
read (`meta.estratos.*.linea`), with the non-ephemeral models they're built on; an ephemeral one is already inlined
|
||||
Those are the project's models semantic models count over (`models/<project>/…`), the timelines its strata
|
||||
read (`meta.estratos.*.linea`) and the views the WebApi reads (`meta.lee_la_webapi`), with the non-ephemeral
|
||||
models they're built on; an ephemeral one is already inlined
|
||||
in its child's compiled SQL. Another domain's models aren't created: their tables may not exist here.
|
||||
"""
|
||||
m = json.loads(manifest.read_text(encoding="utf-8"))
|
||||
@@ -37,6 +38,9 @@ def event_views(manifest: Path, project: str) -> list:
|
||||
roots |= {by_name[spec["linea"]] for metric in m["metrics"].values()
|
||||
if metric["config"].get("meta", {}).get("measure_url", "").startswith(f"{project}/")
|
||||
for spec in metric["config"]["meta"].get("estratos", {}).values() if "linea" in spec}
|
||||
# The views the WebApi reads directly (a follow-up list, a patient summary).
|
||||
roots |= {uid for uid, n in nodes.items() if n["resource_type"] == "model" and n["fqn"][1] == project
|
||||
and n["config"].get("meta", {}).get("lee_la_webapi")}
|
||||
ordered: list[str] = []
|
||||
|
||||
def visit(uid: str) -> None:
|
||||
@@ -69,10 +73,14 @@ def catalog_layers(project: str, manifest: Path) -> list[list]:
|
||||
contract = CONTRACTS[scoring_of(d)]
|
||||
measures.append(t.CatMeasure(measure_id=d.measure_id, url=d.url, version=d.version, titulo=labels[d.metric],
|
||||
contrato=contract, unidad=d.basis))
|
||||
codes = dict.fromkeys((*d.denominator.codes, *d.numerator.codes, *((OBSERVATION,) if contract == "C3r" else ())))
|
||||
exclusion = getattr(d, "exclusion", None)
|
||||
codes = dict.fromkeys((*d.denominator.codes, *d.numerator.codes, *((OBSERVATION,) if contract == "C3r" else ()),
|
||||
*(exclusion.codes if exclusion else ())))
|
||||
children += [t.CatMeasureResultado(resultado_id=f"{d.measure_id}.{c}", measure_id=d.measure_id, poblacion=c,
|
||||
etiqueta=c) for c in codes]
|
||||
children.append(t.CatMeasureGrupo(measure_id=d.measure_id, grupo=d.group, etiqueta=d.group, orden=0))
|
||||
children += [t.CatMeasureGrupo(measure_id=d.measure_id, grupo=g.name, etiqueta=g.label, orden=i)
|
||||
for i, g in enumerate(getattr(d, "groups", ()), 1)]
|
||||
children += [t.CatMeasureEstrato(measure_id=d.measure_id, estrato_id=s.name) for s in d.strata]
|
||||
stratum_rows = [t.CatEstrato(estrato_id=s, etiqueta=labels_of[s], unidad="paciente") for s in strata]
|
||||
return [stratum_rows + measures, children]
|
||||
|
||||
@@ -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 {})},
|
||||
)
|
||||
|
||||
@@ -14,6 +14,7 @@ llave lógica del procedimiento (`fuente_tabla`, `fuente_id`, `estudio_id`,
|
||||
|
||||
from collections.abc import Callable, Iterable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from types import SimpleNamespace
|
||||
from typing import NamedTuple
|
||||
|
||||
from webapi.orchestration.reference.catalogs import Catalogo
|
||||
@@ -59,6 +60,16 @@ class Hija:
|
||||
resultados: Mapping[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Junta:
|
||||
"""Another staging row whose columns the row's content takes: the row of `staging` whose `llave` equals the
|
||||
row's column `columna` (an electrode value takes its metric's code and EEG). Without a match, they're null."""
|
||||
|
||||
staging: type
|
||||
llave: str
|
||||
columna: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeStaging:
|
||||
"""Un procedimiento que sale de cada fila de una tabla de staging (staging directo, T-20c).
|
||||
@@ -72,6 +83,10 @@ class DeStaging:
|
||||
no es un reporte); no es un descarte.
|
||||
- `descartar(fila, pacientes)`: el motivo por el que la fila no entra, que se cuenta en
|
||||
`descartes`. `pacientes`: los `pac_id` de la tabla de pacientes del staging.
|
||||
- `juntas`: rows of other staging tables whose columns join the content before the derived ones.
|
||||
- `observa_en`: the row gives no procedure of its own; its observations go on the procedure this parent key
|
||||
names (a metric of an EEG is a result of the EEG's recording). `clase` is unused then.
|
||||
A result's template can name the content's columns (`eeg.{metrica}`) besides `{estudio}`.
|
||||
|
||||
Staging llega resuelto y completo (usuario, 2026-10-21): la carga no valida que no falte nada.
|
||||
Un procedimiento sin paciente ni padre queda huérfano y se cuenta al escribir (I-MD17).
|
||||
@@ -92,6 +107,8 @@ class DeStaging:
|
||||
paciente: str | None = "pac_id"
|
||||
solo_si: Callable | None = None
|
||||
descartar: Callable | None = None
|
||||
juntas: tuple[Junta, ...] = ()
|
||||
observa_en: Padre | None = None
|
||||
|
||||
|
||||
class LotePlata(NamedTuple):
|
||||
@@ -124,6 +141,7 @@ def plata_desde_staging(
|
||||
pacientes = set(pacientes)
|
||||
tipos, vigentes = _tipos_y_vigentes(catalogo)
|
||||
procedimientos, observaciones, descartes = [], [], {}
|
||||
indices: dict[tuple[str, str], dict] = {}
|
||||
for c in correspondencias:
|
||||
tabla = c.staging.__tablename__
|
||||
for fila in filas.get(tabla, ()):
|
||||
@@ -133,7 +151,13 @@ def plata_desde_staging(
|
||||
continue
|
||||
if c.solo_si is not None and not c.solo_si(fila):
|
||||
continue
|
||||
contenido = {**fila.model_dump(), **{nombre: f(fila) for nombre, f in c.derivadas.items()}}
|
||||
contenido = fila.model_dump()
|
||||
if c.juntas:
|
||||
for junta in c.juntas:
|
||||
unida = _junta(junta, filas, indices).get(contenido.get(junta.columna))
|
||||
contenido = {**(unida or dict.fromkeys(junta.staging.model_fields)), **contenido}
|
||||
fila = SimpleNamespace(**contenido)
|
||||
contenido = {**contenido, **{nombre: f(fila) for nombre, f in c.derivadas.items()}}
|
||||
contenido["pac_id"] = None if c.paciente is None else contenido.get(c.paciente)
|
||||
contenido.update({destino: contenido.get(origen) for destino, origen in c.columnas.items()})
|
||||
_repartir(c, tabla, tabla, fuente_id, contenido, tuple(c.columnas), codigos_hospital,
|
||||
@@ -168,6 +192,14 @@ def en_orden_de_padres(procedimientos: list[dict]) -> list[dict]:
|
||||
return sorted(procedimientos, key=lambda p: (de(p["llave"]), ORDEN_DE_CLASES.index(p["llave"][3])))
|
||||
|
||||
|
||||
def _junta(junta: Junta, filas: Mapping[str, Iterable], indices: dict) -> dict:
|
||||
"""The rows of the joined table by their key, as dictionaries; built once per batch."""
|
||||
clave = (junta.staging.__tablename__, junta.llave)
|
||||
if clave not in indices:
|
||||
indices[clave] = {getattr(f, junta.llave): f.model_dump() for f in filas.get(clave[0], ())}
|
||||
return indices[clave]
|
||||
|
||||
|
||||
def _tipos_y_vigentes(catalogo: Catalogo) -> tuple[dict, set]:
|
||||
tipos = {r.resultado_id: r.tipo_valor for r in catalogo.resultados}
|
||||
vigentes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"}
|
||||
@@ -183,6 +215,11 @@ def _repartir(c, nombre: str, fuente_tabla: str, fuente_id, contenido: dict, col
|
||||
motivo = f"{nombre}: {c.estudio_de} fuera de catálogo"
|
||||
descartes[motivo] = descartes.get(motivo, 0) + 1
|
||||
return
|
||||
if c.observa_en is not None:
|
||||
dueno = _parent(c.observa_en, contenido)
|
||||
if dueno is not None:
|
||||
observaciones += _observaciones(dueno, contenido, c.resultados, c.fuentes, tipos, vigentes)
|
||||
return
|
||||
llave = (fuente_tabla, str(fuente_id), estudio_id, c.clase)
|
||||
procedimientos.append({
|
||||
"llave": llave,
|
||||
@@ -225,7 +262,9 @@ def _observaciones(llave: Llave, contenido: dict, resultados: Mapping[str, str],
|
||||
tipos: dict, vigentes: set) -> list[dict]:
|
||||
filas = []
|
||||
for columna, plantilla in resultados.items():
|
||||
resultado_id = plantilla.format(estudio=llave[2])
|
||||
resultado_id = plantilla.format_map({**contenido, "estudio": llave[2]})
|
||||
if resultado_id not in tipos and "{" in plantilla.replace("{estudio}", ""):
|
||||
continue # a value of the row names a result the catalog doesn't have (an unknown metric)
|
||||
filas.append({
|
||||
"procedimiento": llave,
|
||||
"pac_id": contenido.get("pac_id"),
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""TEA in the two-table silver: what each staging row gives, as `DESDE_STAGING` (read by `carga_desde_staging`).
|
||||
|
||||
- an order is an `orden` of the study it asks for (`ord_tipo_estudio`, in Core's code or one of its aliases);
|
||||
- the M-CHAT is a `toma`, the ADOS-2 and the neuropediatrics note are `encuentro`s, the EEG is a `toma`; each
|
||||
hangs from its order when it has one;
|
||||
- an EEG metric is a result of its EEG's recording, not a procedure; a metric's electrode value is a `parte` of the
|
||||
EEG (`codigo_fuente` the electrode) with the metric's result. Both find their EEG through the metric's row.
|
||||
"""
|
||||
|
||||
from core.tea.enums import (
|
||||
CLASIFICACION_ADOS2_ALIAS,
|
||||
TIPO_ESTUDIO_ALIAS,
|
||||
ClasificacionAdos2,
|
||||
ModuloAdos2,
|
||||
TipoEstudio,
|
||||
)
|
||||
from core.tea.models import (
|
||||
ADOS2_ITEMS,
|
||||
Ados2,
|
||||
Eeg,
|
||||
EegMetrica,
|
||||
EegMetricaElectrodo,
|
||||
EvaluacionNeuropediatrica,
|
||||
Mchat,
|
||||
OrdenesEstudio,
|
||||
Pacientes,
|
||||
)
|
||||
|
||||
from webapi.orchestration.silver.procedures import DeStaging, Junta, Padre
|
||||
from webapi.orchestration.silver.values import INTENCION, cie, codigo_de_especialidad, texto_limpio
|
||||
|
||||
PACIENTES = Pacientes # where persons come from
|
||||
ORDENES = OrdenesEstudio.__tablename__
|
||||
EEG = Eeg.__tablename__
|
||||
|
||||
|
||||
def _codigo(columna: str, enum, alias: dict | None = None):
|
||||
codigos = {e.value for e in enum}
|
||||
return lambda f: codigo_de_especialidad(getattr(f, columna), alias or {}, codigos)
|
||||
|
||||
|
||||
def _su_orden(estudio_id: str, columna: str) -> Padre:
|
||||
"""The order a study row names by its `*_ord_id`."""
|
||||
return Padre(estudio_id=estudio_id, clase="orden", fuente_id=columna, tabla=ORDENES)
|
||||
|
||||
|
||||
def _metrica(f) -> str | None:
|
||||
"""A metric's result in the catalog: its code in lower case (`RITMO_POSTERIOR` -> `ritmo_posterior`)."""
|
||||
codigo = texto_limpio(f.met_codigo)
|
||||
return None if codigo is None else codigo.lower()
|
||||
|
||||
|
||||
SU_EEG = Padre(estudio_id="eeg", clase="toma", fuente_id="met_eeg_id", tabla=EEG)
|
||||
|
||||
|
||||
DESDE_STAGING = (
|
||||
DeStaging(
|
||||
OrdenesEstudio, "ord_id", "orden", estudio_de="tipo_estudio", fecha="ord_fecha", paciente="ord_pac_id",
|
||||
derivadas={
|
||||
"tipo_estudio": _codigo("ord_tipo_estudio", TipoEstudio, TIPO_ESTUDIO_ALIAS),
|
||||
"intencion": lambda f: INTENCION,
|
||||
},
|
||||
columnas={"id_hospital": "ord_id_hospital", "codigo_fuente": "ord_tipo_estudio"},
|
||||
resultados={"intencion": "orden.intencion"},
|
||||
),
|
||||
DeStaging(
|
||||
Mchat, "mch_id", "toma", estudio_id="mchat", fecha="mch_fecha", paciente="mch_pac_id",
|
||||
padres=(_su_orden("mchat", "mch_ord_id"),),
|
||||
resultados={"mch_puntaje": "mchat.puntaje"},
|
||||
),
|
||||
DeStaging(
|
||||
Ados2, "ado_id", "encuentro", estudio_id="ados2", fecha="ado_fecha", paciente="ado_pac_id",
|
||||
padres=(_su_orden("ados2", "ado_ord_id"),),
|
||||
derivadas={
|
||||
"modulo": _codigo("ado_modulo", ModuloAdos2),
|
||||
"clasificacion": _codigo("ado_clasificacion", ClasificacionAdos2, CLASIFICACION_ADOS2_ALIAS),
|
||||
"algoritmo": lambda f: texto_limpio(f.ado_algoritmo),
|
||||
},
|
||||
resultados={
|
||||
"modulo": "ados2.modulo",
|
||||
"algoritmo": "ados2.algoritmo",
|
||||
"clasificacion": "ados2.clasificacion",
|
||||
"ado_css": "ados2.css",
|
||||
**{f"ado_{item}": f"ados2.{item}" for item in ADOS2_ITEMS},
|
||||
},
|
||||
fuentes={"modulo": "ado_modulo", "clasificacion": "ado_clasificacion"},
|
||||
),
|
||||
DeStaging(
|
||||
EvaluacionNeuropediatrica, "neu_id", "encuentro", estudio_id="evaluacion_neuropediatrica",
|
||||
fecha="neu_fecha", paciente="neu_pac_id", padres=(_su_orden("evaluacion_neuropediatrica", "neu_ord_id"),),
|
||||
derivadas={"cie_codigo": lambda f: cie(f.neu_cie_codigo)},
|
||||
resultados={"cie_codigo": "evaluacion_neuropediatrica.diagnostico"},
|
||||
),
|
||||
DeStaging(
|
||||
Eeg, "eeg_id", "toma", estudio_id="eeg", fecha="eeg_fecha_estudio", paciente="eeg_pac_id",
|
||||
padres=(_su_orden("eeg", "eeg_ord_id"),), columnas={"id_hospital": "eeg_id_registro_laboratorio"},
|
||||
resultados={
|
||||
"eeg_con_sueno": "eeg.con_sueno",
|
||||
"eeg_canales": "eeg.canales",
|
||||
"eeg_duracion_min": "eeg.duracion_min",
|
||||
"eeg_canales_amplitud": "eeg.calidad_amplitud",
|
||||
"eeg_canales_alta_frecuencia": "eeg.calidad_alta_frecuencia",
|
||||
"eeg_canales_correlacion": "eeg.calidad_correlacion",
|
||||
"eeg_canales_sin_senal": "eeg.calidad_sin_senal",
|
||||
"eeg_ruido_linea_db": "eeg.calidad_linea",
|
||||
},
|
||||
),
|
||||
DeStaging(
|
||||
EegMetrica, "met_id", "toma", estudio_id="eeg", paciente=None, observa_en=SU_EEG,
|
||||
derivadas={"metrica": _metrica},
|
||||
resultados={"met_valor": "eeg.{metrica}"},
|
||||
),
|
||||
DeStaging(
|
||||
EegMetricaElectrodo, "mel_id", "parte", estudio_id="eeg", paciente=None,
|
||||
juntas=(Junta(EegMetrica, "met_id", "mel_met_id"),), padres=(SU_EEG,),
|
||||
derivadas={"metrica": _metrica},
|
||||
columnas={"codigo_fuente": "mel_electrodo"},
|
||||
resultados={"mel_valor": "eeg.{metrica}"},
|
||||
),
|
||||
)
|
||||
@@ -14,7 +14,7 @@ from importlib import import_module
|
||||
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
PROJECTS = ("cacu", "cama")
|
||||
PROJECTS = ("cacu", "cama", "tea")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""TEA's tables: in `Core`, in the domain's registry.
|
||||
|
||||
`TABLAS` is what the shared code receives to work with this project; TEA's person adds nothing (its `sexo` stays null).
|
||||
"""
|
||||
|
||||
from core.tea.indicadores.models import (
|
||||
CatMeasure,
|
||||
CatMeasureResultado,
|
||||
CatMeasureValor,
|
||||
CatMeasureGrupo,
|
||||
CatEstrato,
|
||||
CatEstratoValor,
|
||||
CatMeasureEstrato,
|
||||
MeasureReportUnidad,
|
||||
MeasureReportUnidadEstrato,
|
||||
CatEstudio,
|
||||
CatResultado,
|
||||
CatValor,
|
||||
Observacion,
|
||||
Procedimiento,
|
||||
CohorteArmado,
|
||||
CohorteExclusion,
|
||||
CohorteMiembro,
|
||||
CohorteVariable,
|
||||
EvaluacionRiesgo,
|
||||
EvaluacionRiesgoLote,
|
||||
Carga,
|
||||
DefParametro,
|
||||
DimFecha,
|
||||
DimGrupoEdad,
|
||||
DimPeriodo,
|
||||
MeasureReport,
|
||||
PeriodoObservacion,
|
||||
Persona,
|
||||
)
|
||||
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
__all__ = ["TABLAS", "COHORTES"]
|
||||
|
||||
TABLAS = TablasKit(
|
||||
Persona=Persona,
|
||||
PeriodoObservacion=PeriodoObservacion,
|
||||
Carga=Carga,
|
||||
DefParametro=DefParametro,
|
||||
DimPeriodo=DimPeriodo,
|
||||
DimFecha=DimFecha,
|
||||
DimGrupoEdad=DimGrupoEdad,
|
||||
MeasureReport=MeasureReport,
|
||||
CatEstudio=CatEstudio,
|
||||
CatResultado=CatResultado,
|
||||
CatValor=CatValor,
|
||||
Procedimiento=Procedimiento,
|
||||
Observacion=Observacion,
|
||||
CatMeasure=CatMeasure,
|
||||
CatMeasureResultado=CatMeasureResultado,
|
||||
CatMeasureValor=CatMeasureValor,
|
||||
CatMeasureGrupo=CatMeasureGrupo,
|
||||
CatEstrato=CatEstrato,
|
||||
CatEstratoValor=CatEstratoValor,
|
||||
CatMeasureEstrato=CatMeasureEstrato,
|
||||
MeasureReportUnidad=MeasureReportUnidad,
|
||||
MeasureReportUnidadEstrato=MeasureReportUnidadEstrato,
|
||||
)
|
||||
|
||||
# Cohorts for models and their risk estimates: TEA builds none yet, the tables are the domain's.
|
||||
COHORTES = TablasCohorte(
|
||||
CohorteArmado=CohorteArmado,
|
||||
CohorteMiembro=CohorteMiembro,
|
||||
CohorteExclusion=CohorteExclusion,
|
||||
CohorteVariable=CohorteVariable,
|
||||
EvaluacionRiesgoLote=EvaluacionRiesgoLote,
|
||||
EvaluacionRiesgo=EvaluacionRiesgo,
|
||||
)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user