Compare commits

...

36 Commits

Author SHA1 Message Date
edgar a24895bae6 Relock for the notebooks dependency group that models declares 2026-11-16 23:15:24 -06:00
edgar d5413b7e7a FHIR Measures carry each metric's technical sheet; the live estimator uses the scenario dataflow and the cohort check 2026-11-16 22:57:47 -06:00
Roberto Treviño Cervantes 9737b5a67f The follow-up list identifies each patient by the platform's pac_id, the key the risk route takes; TEA keeps its salted pseudonym 2026-11-15 05:40:08 -06:00
Roberto Treviño Cervantes 854a2e9c55 The recomputation worker estimates with the models in production and wakes on the marker directory; the scanned test form carries a birth date 2026-11-15 05:37:50 -06:00
Roberto Treviño Cervantes b8045e7481 dbt's manifest compiled at start-up for the deployment's engine; the image carries the dbt environments 2026-11-15 00:47:38 -06:00
Roberto Treviño Cervantes 6dce665d93 Merge remote-tracking branch 'origin/feature/163-tea-redesign' into feature/kit-exit-integration
# Conflicts:
#	Dockerfile
#	README.md
#	tests/staging/cama.py
#	tests/test_fhir_measures.py
#	tests/test_fhir_tea.py
#	tests/test_orquestacion_oro.py
#	tests/test_orquestacion_plata.py
#	uv.lock
#	webapi/__init__.py
#	webapi/fhir/__init__.py
#	webapi/fhir/measures.py
#	webapi/follow_up/routes.py
#	webapi/imports/schemas/tea/ordenes_estudio.py
#	webapi/metrics.py
#	webapi/orchestration/cycle.py
#	webapi/orchestration/reference/catalogs.py
#	webapi/orchestration/repositories.py
#	webapi/orchestration/silver/cama.py
#	webapi/orchestration/silver/orders_and_notes.py
2026-11-15 00:44:31 -06:00
rockdrigo 461d651805 TEA FHIR: an episode's _include brings its ADOS-2 observation 2026-11-13 17:03:23 -06:00
alberto 790879513b The image compiles dbt's manifest and sets DBT_MANIFEST, so the measure and FHIR routes are served 2026-11-13 15:31:29 -06:00
rockdrigo 73cbf0cfb8 The catalog step seeds each domain's mappings, and a mapping is written only if the function still holds
How: `catalog_rows` turns the TOML's study codes, captions and each value's code, label and aliases into the
`catalogo` system's rows; the `catalogs` step adds the system and the forms with no row yet
(`mapeos_nuevos`). `register` normalizes the form and adds the row through `SourceMappingRepository.add`
with `check_stored`, which runs `check_function` on the stored rows of the same form; captions aren't
checked, since one caption may introduce several results. `ctx.repos.silver.mappings` is the domain's
repository.

Implications: the database keeps every mapping across deploys; a person's change is never overwritten, and
a second code for a form in force is refused before it's written. Loads still read the TOML's aliases.
2026-11-13 15:31:21 -06:00
rockdrigo 64d3d721e3 Source forms as a partial, non-injective function into the catalog's codes, checked on the catalog
How: `reference.source_mapping` keys a mapping by source system, result, normalized form and validity;
`check_function` rejects a form that gives two codes while both mappings are in force, and `resolve` gives
the code in force on a date, or none when nothing or two disagreeing mappings match. The catalog's own
check of spellings (`_claves_de_extraccion`) now runs `check_function` on each result's codes, labels and
aliases.

Implications: the same rule serves the TOML today and any store of mappings with systems and dates; every
catalog passes it.
2026-11-13 15:29:52 -06:00
rockdrigo cea74e1566 uv.lock with models' dependencies on dev
How: `uv lock` after the rebase onto dev, whose models adds the notebook and governance requirements.

Implications: `uv sync` installs what the governance routes import (`models.io.storage.build_file` and the notebook runner).
2026-11-13 15:24:02 -06:00
rockdrigo 113b792a7b The import's catalog matching and commit read the WebApi's catalog, silver batch and table maps; add_resultado moves here
How: `catalog_matching`, `catalog_commit_service` and the imports blueprint import `Catalogo`,
`catalogo_desde_toml`, `ruta_de_catalogo`, `CatalogoInvalido`, `LotePlata`, `valor_de_observacion` and
`tablas_de` from `webapi.orchestration`; the commit writes through `carga_repository.save_load` and
`catalog_repository.sync`. `add_resultado` and its tests come over unchanged from the indicator kit.

Implications: the import path no longer needs the indicator kit, which isn't a dependency.
2026-11-13 15:24:02 -06:00
rockdrigo f183e495fb A timeline stratum read by the event cut-off, and labels for a timeline stratum's values
How: `linea_de_tiempo_al_corte` is `linea_de_tiempo_al_inicio_del_periodo` with what the timeline held by the
question's event cut-off (all of it without one) instead of before the period's start. FHIR's `_label` reads a
timeline stratum's labels from its `valores` entries and `resto_etiqueta`. Tests cover CaMa's tumour stratifiers:
the facts dbt derives, the surrogate subtype's rules, CAMA_BIRADS_CANCER_INVASOR broken down by them, and the
cut-off.

Implications: a patient's characteristic learned after the fact that put her in the period (a cancer's stage or
subtype, written after its biopsy) can stratify a measure, and stays reproducible through the cut-offs. CaMa
publishes eight measures and five strata.
2026-11-13 15:14:46 -06:00
rockdrigo 9775a22c57 CaMa's silver load reads results from the reports' text, mapped by the catalog
How: `silver.extracted.DesdeTexto` turns the catalog's `etiquetas_fuente` and each value's `alias` into
Extraction's field specs and into derived columns of a `DeStaging`. CaMa reads density and lesion size from the
mammography interpretation, histology, grade, receptors, HER2 and Ki-67 from the pathology PDF's text layer (no
OCR at load time), and the clinical stage from the note's texts. `resultados_extraibles` reads and checks the new
keys: captions are a non-empty list, aliases need captions, and no spelling names two values.

Implications: a code comes with the spelling it matched as `valor_fuente`; an unknown spelling is kept as
`valor_fuente` with no code, counted as out of catalog, and becomes a code on the next load once its alias is in
the catalog. Nothing is renamed in the stored data and no table or column changes. The synthetic CaMa staging
gains a mammography text, a pathology PDF and a note with a stage.
2026-11-13 15:14:46 -06:00
alberto 7d5c79f520 TEA: an answer as of a knowledge cut-off reads each child's version known then, and the measures waiting for a validation stay hidden outside FHIR too 2026-11-13 15:14:46 -06:00
edgar e224b8b2aa TEA on its new staging: silver load, ten measures answered on request with the status at the period's end, several groups and column strata, and FHIR R4 endpoints for measures, follow-up and patient summary 2026-11-13 15:14:46 -06:00
edgar 205bc214fa Every stratum value an answer writes is in the stratum-value catalog 2026-11-13 15:14:29 -06:00
edgar 4fc822d5c7 The kit's silver load, reference tables, table maps and follow-up list move into the WebApi; the kit is no longer a dependency 2026-11-13 15:14:29 -06:00
edgar 73b1db1121 English names: orchestration (cycle, context, runner, repositories), its steps, fields and CLI, recomputation, follow_up and reports 2026-11-13 15:13:52 -06:00
edgar ea228da7b4 CaCu's and CaMa's measures answered on request from dbt's semantic layer as FHIR MeasureReports, with the period and both cut-offs in the question; the route is /<domain>/indicadores 2026-11-13 15:13:27 -06:00
alberto e19121bc42 TEA: an order carries its study's report as a PDF through the import 2026-11-13 15:03:02 -06:00
Roberto Treviño Cervantes 8f84253205 updating nlp policies; more robust recognition beyond rules 2026-11-13 11:52:36 -06:00
Roberto Treviño Cervantes ce67de17bc fix governance reqs; allow for sandboxed jupyter notebooks for testing 2026-11-13 11:52:36 -06:00
Roberto Treviño Cervantes e41a2b7127 improve ingestion system to match isssteleon setup 2026-11-13 11:52:36 -06:00
alberto 0f9433949f TEA: an answer as of a knowledge cut-off reads each child's version known then, and the measures waiting for a validation stay hidden outside FHIR too 2026-11-12 19:47:19 -06:00
edgar a0407e41d6 TEA on its new staging: silver load, ten measures answered on request with the status at the period's end, several groups and column strata, and FHIR R4 endpoints for measures, follow-up and patient summary 2026-11-12 15:21:25 -06:00
Roberto Treviño Cervantes 59fe94ad97 Parse pasted server addresses and carry SQL columns as document fields 2026-11-12 01:13:34 -06:00
Roberto Treviño Cervantes edd12df144 Merge staging into dev 2026-11-12 01:11:24 -06:00
Roberto Treviño Cervantes 96a29cfb19 import files in columns 2026-11-11 11:09:48 -06:00
Roberto Treviño Cervantes 7d0213eda7 Fold repeated captions before writing catalog-matching observations 2026-11-11 08:33:08 -06:00
Roberto Treviño Cervantes 1710cd5ca2 Merge import files in columns into staging 2026-11-11 07:26:52 -06:00
Roberto Treviño Cervantes 3c28a43cb1 Merge dev into staging 2026-11-11 07:26:52 -06:00
edgar c430a5bd11 Every stratum value an answer writes is in the stratum-value catalog 2026-11-08 17:28:24 -06:00
edgar 270e229a51 The kit's silver load, reference tables, table maps and follow-up list move into the WebApi; the kit is no longer a dependency 2026-11-08 17:28:24 -06:00
edgar 82504bd0bf English names: orchestration (cycle, context, runner, repositories), its steps, fields and CLI, recomputation, follow_up and reports 2026-11-08 17:28:24 -06:00
edgar 2296598896 CaCu's and CaMa's measures answered on request from dbt's semantic layer as FHIR MeasureReports, with the period and both cut-offs in the question; the route is /<domain>/indicadores 2026-11-08 17:28:24 -06:00
158 changed files with 29381 additions and 2878 deletions
+25 -4
View File
@@ -1,6 +1,22 @@
# Build context is the repo root (see docker-compose.yml) so the sibling
# packages Core/, Persistance/, Extraction/, models/ and indicadores_kit/
# can be copied.
# packages Core/, Persistance/, Extraction/ and models/
# 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.
@@ -15,7 +31,6 @@ COPY Core/ Core/
COPY Persistance/ Persistance/
COPY Extraction/ Extraction/
COPY models/ models/
COPY indicadores_kit/ indicadores_kit/
COPY WebApi/ WebApi/
# One environment for the API, the migrations and the indicator cycle. The SQL
@@ -31,10 +46,16 @@ ENV MLFLOW_TRACKING_URI=sqlite:////data/mlflow.db
ENV MLFLOW_ARTIFACT_ROOT=/data/mlflow-artefactos
# No usage telemetry from MLflow: the server runs on a closed network.
ENV MLFLOW_DISABLE_TELEMETRY=true DO_NOT_TRACK=true
# Aggregate import log and the live indicator queue (webapi.indicadores_vivos).
# Aggregate import log and the live indicator queue (webapi.recomputation).
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
+28 -7
View File
@@ -4,8 +4,9 @@ API REST de ISSSTELEON en Flask. Importa datos clínicos de varias fuentes a
las bases de CaCu, CaMa y TEA, publica los indicadores ya calculados, guarda
una bitácora agregada de cada importación y expone la gobernanza de modelos
y de OCR. Usa `Persistance` para las bases, `Extraction` para documentos y
EEG, `indicadores_kit` para leer los indicadores y `orquestacion` para
recalcularlos.
EEG y `models` para las cohortes. Los indicadores se definen en dbt (`Transformation`) y se
responden bajo pedido (`/<dominio>/indicadores`); `orchestration` carga la plata, las tablas de
referencia y las vistas de dbt.
## Estructura
@@ -17,15 +18,17 @@ 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)
├── indicadores_vivos.py cola y servicio que recalcula indicadores tras cada carga
├── recomputation.py cola y servicio que recalcula indicadores tras cada carga
└── seguimiento.py lista de seguimiento por paciente (solo con DEV_REVISION)
```
@@ -44,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
@@ -68,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
@@ -79,7 +91,16 @@ for d in cacu cama tea governance; do
uv run alembic -c ../Persistance/persistance/$d/alembic.ini upgrade head
done
uv run python main.py # http://localhost:5050
uv run python -m webapi.indicadores_vivos # recálculo de indicadores, en otra terminal
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
+29 -6
View File
@@ -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
# The live indicator worker (webapi.indicadores_vivos) 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.indicadores_vivos
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
exec uv run --no-sync python -m webapi.recomputation
fi
# 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
cd /app/WebApi
# --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 -3
View File
@@ -6,9 +6,8 @@ requires-python = ">=3.12"
dependencies = [
"flask>=3.0",
"persistance",
"models[export]",
"models[notebooks]",
"extraction",
"indicadores-kit",
"apache-hamilton>=1.90",
"pandas>=2.0",
"openpyxl>=3.1",
@@ -21,6 +20,7 @@ dependencies = [
"gunicorn>=23.0",
"sqlglot>=25.0",
"rapidfuzz>=3.9",
"watchdog>=6.0",
]
[project.optional-dependencies]
@@ -34,7 +34,6 @@ sql-drivers = [
persistance = { path = "../Persistance", editable = true }
models = { path = "../models", editable = true }
extraction = { path = "../Extraction", editable = true }
indicadores-kit = { path = "../indicadores_kit", editable = true }
[build-system]
requires = ["hatchling"]
@@ -45,6 +44,7 @@ packages = ["webapi"]
[dependency-groups]
dev = [
"fhir-resources>=8",
"pytest>=8.0.0",
"reportlab>=4.0",
]
+32 -35
View File
@@ -5,8 +5,8 @@
`<DOMAIN>_DATABASE_URL` alone has no effect once an engine exists.
`wire_domain` resets all three (env var, singleton, cache).
The `base`/`base_de` family (below `ANIO`) is for `webapi.orquestacion`:
una base del dominio por prueba, migrada por el paso `migrar`, con el staging
The `base`/`base_de` family (below `ANIO`) is for `webapi.orchestration`:
una base del dominio por prueba, migrada por el paso `migrate`, con el staging
sintético del kit.
"""
import os
@@ -19,10 +19,10 @@ import pytest
from sqlalchemy import create_engine
from sqlmodel import Session
from indicadores_kit.registry.parametros import RUTA_PARAMETROS
from webapi.orquestacion import Contexto, correr
from webapi.orquestacion.conexion import apuntar
from webapi.orquestacion.repositorios import repositorios_de
from webapi.orchestration.reference.rules import RUTA_PARAMETROS
from webapi.orchestration import Context, run
from webapi.orchestration.connection import point_to
from webapi.orchestration.repositories import repositories_of
# Tests use throwaway SQLite files as "arbitrary SQL sources"; production
# excludes sqlite by default (see webapi.imports.connectors.sql_policy).
@@ -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
@@ -40,27 +44,29 @@ class Base:
"""El proyecto, su contexto (con los repositorios de Persistance) y su dominio en Persistance."""
proyecto: str
ctx: Contexto
ctx: Context
dominio: object
motor: object
def correr(self, *pasos: str, **cambios) -> dict:
def run(self, *pasos: str, **cambios) -> dict:
"""Corre estos pasos (en el orden del ciclo) con el contexto cambiado. Devuelve el resumen de cada una."""
return {p.nombre: p.resumen for p in correr(replace(self.ctx, **cambios), solo=pasos)}
return {p.name: p.summary for p in run(replace(self.ctx, **cambios), only=pasos)}
def staging(self):
"""Una sesión sobre la base, para cambiar el staging como lo haría la ingesta."""
return Session(self.motor)
def base_de(proyecto: str, carpeta) -> Base:
def base_de(proyecto: str, carpeta, datos=None) -> Base:
"""A migrated domain database in `carpeta`, with the kit's synthetic staging or, with `datos`, what it inserts."""
url = f"sqlite:///{carpeta / f'{proyecto}.db'}"
apuntar(proyecto, url)
ctx = Contexto(proyecto, ANIO, ANIO, repos=repositorios_de(proyecto))
correr(ctx, solo=["migrar"])
point_to(proyecto, url)
manifest = os.environ.get("DBT_MANIFEST")
ctx = Context(proyecto, ANIO, ANIO, dbt_manifest=Path(manifest) if manifest else None, repos=repositories_of(proyecto))
run(ctx, only=["migrate"])
motor = create_engine(url)
with Session(motor) as sesion:
import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion)
(datos or import_module(f"staging.{proyecto}").insertar)(sesion)
sesion.commit()
return Base(proyecto, ctx, import_module(f"persistance.{proyecto}"), motor)
@@ -132,25 +138,16 @@ MESES = ["2025-01", "2025-02", "2025-03"]
def cliente_de(proyecto: str, tmp_path_factory):
"""Yields a client over a temporary SQLite database seeded with the kit's demonstration data."""
from indicadores_kit.demostracion import base_de_prueba
from persistance import db
from persistance.settings import settings
"""Yields a client over a temporary SQLite database the cycle loaded from the kit's synthetic staging."""
carpeta = tmp_path_factory.mktemp(proyecto)
base = base_de(proyecto, carpeta)
base.run("catalogs", "load", "views", "registry", "definitions", "event_models", allow_undecided=True)
try:
from webapi import create_app
ruta = tmp_path_factory.mktemp(proyecto) / f"{proyecto}.db"
obtener_motor = getattr(db, f"get_{proyecto}_engine")
with pytest.MonkeyPatch.context() as mp:
mp.setattr(settings, f"{proyecto}_database_url", f"sqlite:///{ruta}")
obtener_motor.cache_clear()
try:
base_de_prueba(obtener_motor(), proyecto)
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as cliente:
yield cliente
finally:
obtener_motor().dispose()
obtener_motor.cache_clear()
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as cliente:
yield cliente
finally:
base.motor.dispose()
+114
View File
@@ -0,0 +1,114 @@
# Casos de CACU_CONFIRMACION_CITOLOGIA (confirmación por biopsia según resultado citológico, C2).
# La unidad es la paciente cuya última citología válida del periodo es de alto grado
# (`cacu.citologia_alto_grado`); la última válida es la de EU7 (`cacu.calidad_insatisfactoria`).
# Cada categoría es `cat:<grado>` de la biopsia más grave que originó esa citología (ligada por
# `cit_id`); sin biopsia reportada al corte, `cat:SIN_BIOPSIA`; con biopsia sin grado, `cat:SIN_DATO`.
# `estratos` dice el valor de cada paciente en `citologia_alto_grado`: la fila del panel. Sin `corte`,
# es el día de la carga del caso (2026-01-01).
measure = "cacu/CACU_CONFIRMACION_CITOLOGIA"
[[caso]]
nombre = "una paciente con ASC-H y biopsia LIEAG cuenta en LIEAG dentro de la fila ASC-H"
filas = [
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "ASC-H" },
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "LIEAG" },
{ tabla = "citologiacervical", cit_id = 2, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
{ tabla = "biopsiacervical", bx_id = 2, pac_id = 2, cit_id = 2, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "NORMAL" },
]
espera."2025-S1" = { "cat:LIEAG" = 1, "cat:NORMAL" = 1 }
unidades."2025-S1" = { "cat:LIEAG" = ["1"], "cat:NORMAL" = ["2"] } # la 2 es un falso positivo de la fila LIEAG
estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H", "2" = "LIEAG" }
[[caso]]
nombre = "la última citología válida manda y no la peor"
filas = [
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "CIS" },
{ tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "ASC-H" },
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 2, bx_fecha_reporte = 2025-06-01, bx_cin_grado = "LIEBG" },
]
espera."2025-S1" = { "cat:LIEBG" = 1 }
estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H" }
[[caso]]
nombre = "con varias biopsias de la toma cuenta la más grave y no la más reciente"
filas = [
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" },
{ tabla = "biopsiacervical", bx_id = 2, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-04-01, bx_cin_grado = "LIEBG" },
{ tabla = "biopsiacervical", bx_id = 3, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-05-01, bx_cin_grado = "NORMAL" },
]
espera."2025-S1" = { "cat:CIS" = 1, "cat:LIEBG" = 0, "cat:NORMAL" = 0 }
[[caso]]
nombre = "una biopsia con grado gana a una sin grado; solo sin grado es sin dato"
filas = [
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "NORMAL" },
{ tabla = "biopsiacervical", bx_id = 2, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-04-01 },
{ tabla = "citologiacervical", cit_id = 2, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "CIS" },
{ tabla = "biopsiacervical", bx_id = 3, pac_id = 2, cit_id = 2, bx_fecha_reporte = 2025-03-01 },
]
espera."2025-S1" = { "cat:NORMAL" = 1, "cat:SIN_DATO" = 1, "cat:SIN_BIOPSIA" = 0 }
unidades."2025-S1" = { "cat:SIN_DATO" = ["2"] }
[[caso]]
nombre = "una biopsia reportada después del corte todavía no existe: sin biopsia aún"
filas = [
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-10, cit_celulas_escamosas = "LIEAG" },
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "LIEAG" },
]
corte = 2025-07-31
espera."2025-S1" = { "cat:SIN_BIOPSIA" = 1, "cat:LIEAG" = 0 }
estratos."2025-S1".citologia_alto_grado = { "1" = "LIEAG" }
[[caso]]
nombre = "el día del corte la biopsia ya existe"
filas = [
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-10, cit_celulas_escamosas = "LIEAG" },
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "LIEAG" },
]
corte = 2025-08-01
espera."2025-S1" = { "cat:SIN_BIOPSIA" = 0, "cat:LIEAG" = 1 }
[[caso]]
nombre = "una biopsia de otra toma no cuenta"
filas = [
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" },
{ tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "ASC-H" },
{ tabla = "biopsiacervical", bx_id = 2, pac_id = 1, bx_fecha_reporte = 2025-06-01, bx_cin_grado = "LIEAG" },
]
espera."2025-S1" = { "cat:SIN_BIOPSIA" = 1, "cat:CIS" = 0, "cat:LIEAG" = 0 }
estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H" }
[[caso]]
nombre = "una insatisfactoria posterior no es la última válida"
filas = [
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "LIEAG" },
{ tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "INSATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "NORMAL" },
]
espera."2025-S1" = { "cat:LIEAG" = 1 }
estratos."2025-S1".citologia_alto_grado = { "1" = "LIEAG" }
[[caso]]
nombre = "una paciente cuya última citología es NORMAL no entra aunque antes tuviera LIEAG"
filas = [
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" },
{ tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "NORMAL" },
{ tabla = "citologiacervical", cit_id = 3, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "ASC-US" },
]
espera."2025-S1" = { "cat:CIS" = 0, "cat:SIN_BIOPSIA" = 0, "cat:NORMAL" = 0 }
estratos."2025-S1".citologia_alto_grado = {}
[[caso]]
nombre = "la citología cuenta en el periodo de su toma y no en el del reporte de la biopsia"
filas = [
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-20, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-25, cit_celulas_escamosas = "CIS" },
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "CARCINOMA" },
]
espera."2025-S1" = { "cat:CARCINOMA" = 1 }
espera."2025-S2" = { "cat:CARCINOMA" = 0 }
estratos."2025-S1".citologia_alto_grado = { "1" = "CIS" }
+87
View File
@@ -0,0 +1,87 @@
# Casos de CACU_RIESGO_BANDA (pacientes en vigilancia por banda de riesgo, C2). PROPUESTA (MD-Q5).
# Cuenta a las miembros del armado del lote vigente (el mayor con alguna evaluación `final` al
# horizonte) con fecha índice en el periodo, por la banda de la versión más reciente de su
# evaluación. Con los parámetros de `parametros.toml`: BAJO < 0.04 <= INTERMEDIO < 0.25 <= ALTO,
# horizonte 0. `cat:SIN_DATO`: sin evaluación `final` en el lote.
measure = "cacu/CACU_RIESGO_BANDA"
[plantillas]
armado = [
{ tabla = "cohorte_armado", armado_id = 1, url = "cacu/cohorte_vigilancia", version = "0.1.0", definicion_sha = "d", reglas_sha = "r", parametros = "{}", datos_as_of = 2025-12-31, huella = "a1", marco_sha = "m1", n_miembros = 4, armado_en = 2026-01-01T00:00:00Z },
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 1, fecha_indice = 2025-02-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "1" },
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 2, fecha_indice = 2025-03-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "2" },
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 3, fecha_indice = 2025-04-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "3" },
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 4, fecha_indice = 2025-08-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "4" },
]
lote_final = [
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 3, huella = "l1" },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, horizonte_anios = 0.0, probabilidad = 0.1, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 4, horizonte_anios = 0.0, probabilidad = 0.3, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
]
[[caso]]
nombre = "cada paciente en la banda de su riesgo; sin evaluación es sin dato"
incluye = ["armado", "lote_final"]
filas = []
espera."2025-S1" = { "cat:BAJO" = 1, "cat:INTERMEDIO" = 1, "cat:ALTO" = 0, "cat:SIN_DATO" = 1 }
unidades."2025-S1" = { "cat:SIN_DATO" = [3] }
[[caso]]
nombre = "el periodo es el de la fecha índice"
incluye = ["armado", "lote_final"]
filas = []
espera."2025-S2" = { "cat:ALTO" = 1, "cat:BAJO" = 0 }
[[caso]]
nombre = "los cortes son parámetros"
incluye = ["armado", "lote_final"]
filas = []
parametros = { "comun.riesgos.corte_intermedio" = 0.01, "comun.riesgos.corte_alto" = 0.05 }
espera."2025-S1" = { "cat:BAJO" = 0, "cat:INTERMEDIO" = 1, "cat:ALTO" = 1 }
[[caso]]
nombre = "un lote preliminar más nuevo no desplaza al vigente"
incluye = ["armado", "lote_final"]
filas = [
{ tabla = "evaluacion_riesgo_lote", lote_id = 2, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "2", mlflow_run_id = "sin-mlflow", modelo_sha = "s2", desenlace = "c", evaluado_en = 2026-02-01T00:00:00Z, n_evaluaciones = 1, huella = "l2" },
{ tabla = "evaluacion_riesgo", lote_id = 2, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.9, version = 1, estado = "preliminary", registrado_en = 2026-02-01T00:00:00Z },
]
espera."2025-S1" = { "cat:BAJO" = 1, "cat:ALTO" = 0 }
[[caso]]
nombre = "una evaluación anulada en su versión 2 queda sin dato"
incluye = ["armado", "lote_final"]
filas = [
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, horizonte_anios = 0.0, probabilidad = 0.1, version = 2, estado = "entered-in-error", motivo = "caso", registrado_en = 2026-01-03T00:00:00Z },
]
espera."2025-S1" = { "cat:INTERMEDIO" = 0, "cat:SIN_DATO" = 2 }
[[caso]]
nombre = "una evaluación a otro horizonte no cuenta"
incluye = ["armado"]
filas = [
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 1.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
]
espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 }
[[caso]]
nombre = "sin lote confirmado no hay población"
incluye = ["armado"]
filas = [
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "preliminary", registrado_en = 2026-01-02T00:00:00Z },
]
espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 }
[[caso]]
nombre = "el lote de otra cohorte no cuenta"
filas = [
{ tabla = "cohorte_armado", armado_id = 1, url = "cacu/otra", version = "0.1.0", definicion_sha = "d", reglas_sha = "r", parametros = "{}", datos_as_of = 2025-12-31, huella = "a1", marco_sha = "m1", n_miembros = 1, armado_en = 2026-01-01T00:00:00Z },
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 1, fecha_indice = 2025-02-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "1" },
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
]
espera."2025-S1" = { "cat:BAJO" = 0 }
File diff suppressed because it is too large Load Diff
+387
View File
@@ -0,0 +1,387 @@
[
{
"pac_id": "1",
"fecha": "2025-02-03",
"clase": "orden",
"tipo": "orden",
"codigo": "orden",
"valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
"valor_numerico": null,
"fuente_tabla": "ordenesestudio",
"fuente_id": "1"
},
{
"pac_id": "1",
"fecha": "2025-02-10",
"clase": "procedimiento",
"tipo": "citologia",
"codigo": "citologia_cervical",
"valor_codigo": "SATISFACTORIO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "1"
},
{
"pac_id": "1",
"fecha": "2025-02-20",
"clase": "medicion",
"tipo": "bethesda",
"codigo": "bethesda",
"valor_codigo": "NEGATIVO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "1"
},
{
"pac_id": "1",
"fecha": "2025-03-01",
"clase": "diagnostico",
"tipo": "nota_medica",
"codigo": "nota_medica",
"valor_codigo": "N871",
"valor_numerico": null,
"fuente_tabla": "notamedica",
"fuente_id": "3"
},
{
"pac_id": "1",
"fecha": "2025-10-02",
"clase": "procedimiento",
"tipo": "citologia",
"codigo": "citologia_cervical",
"valor_codigo": "SATISFACTORIO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "9"
},
{
"pac_id": "2",
"fecha": "2025-03-05",
"clase": "procedimiento",
"tipo": "citologia",
"codigo": "citologia_cervical",
"valor_codigo": "INSATISFACTORIO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "2"
},
{
"pac_id": "2",
"fecha": "2025-09-15",
"clase": "diagnostico",
"tipo": "nota_medica",
"codigo": "nota_medica",
"valor_codigo": "C53",
"valor_numerico": null,
"fuente_tabla": "notamedica",
"fuente_id": "4"
},
{
"pac_id": "3",
"fecha": "2024-12-01",
"clase": "diagnostico",
"tipo": "nota_medica",
"codigo": "nota_medica",
"valor_codigo": "C539",
"valor_numerico": null,
"fuente_tabla": "notamedica",
"fuente_id": "2"
},
{
"pac_id": "3",
"fecha": "2025-01-20",
"clase": "procedimiento",
"tipo": "citologia",
"codigo": "citologia_cervical",
"valor_codigo": "INSATISFACTORIO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "3"
},
{
"pac_id": "3",
"fecha": "2025-02-01",
"clase": "medicion",
"tipo": "bethesda",
"codigo": "bethesda",
"valor_codigo": "ASC-US",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "3"
},
{
"pac_id": "3",
"fecha": "2025-02-01",
"clase": "medicion",
"tipo": "vph",
"codigo": "vph",
"valor_codigo": "POSITIVO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "3"
},
{
"pac_id": "3",
"fecha": "2025-02-01",
"clase": "medicion",
"tipo": "vph_genotipo_16_18",
"codigo": "vph_genotipo_16_18",
"valor_codigo": null,
"valor_numerico": "1.0",
"fuente_tabla": "citologiacervical",
"fuente_id": "3"
},
{
"pac_id": "3",
"fecha": "2025-04-10",
"clase": "orden",
"tipo": "orden",
"codigo": "orden",
"valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
"valor_numerico": null,
"fuente_tabla": "ordenesestudio",
"fuente_id": "2"
},
{
"pac_id": "3",
"fecha": "2025-04-15",
"clase": "procedimiento",
"tipo": "citologia",
"codigo": "citologia_cervical",
"valor_codigo": "SATISFACTORIO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "4"
},
{
"pac_id": "3",
"fecha": "2025-04-25",
"clase": "medicion",
"tipo": "bethesda",
"codigo": "bethesda",
"valor_codigo": "LIEBG",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "4"
},
{
"pac_id": "3",
"fecha": "2025-04-25",
"clase": "medicion",
"tipo": "vph",
"codigo": "vph",
"valor_codigo": "POSITIVO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "4"
},
{
"pac_id": "3",
"fecha": "2025-04-25",
"clase": "medicion",
"tipo": "vph_genotipo_16_18",
"codigo": "vph_genotipo_16_18",
"valor_codigo": null,
"valor_numerico": "0.0",
"fuente_tabla": "citologiacervical",
"fuente_id": "4"
},
{
"pac_id": "3",
"fecha": "2025-05-01",
"clase": "orden",
"tipo": "orden",
"codigo": "orden",
"valor_codigo": null,
"valor_numerico": null,
"fuente_tabla": "biopsiacervical",
"fuente_id": "1"
},
{
"pac_id": "3",
"fecha": "2025-05-20",
"clase": "medicion",
"tipo": "biopsia",
"codigo": "cin",
"valor_codigo": "CIN1",
"valor_numerico": null,
"fuente_tabla": "biopsiacervical",
"fuente_id": "1"
},
{
"pac_id": "4",
"fecha": "2025-05-30",
"clase": "procedimiento",
"tipo": "citologia",
"codigo": "citologia_cervical",
"valor_codigo": "SATISFACTORIO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "5"
},
{
"pac_id": "4",
"fecha": "2025-06-09",
"clase": "medicion",
"tipo": "bethesda",
"codigo": "bethesda",
"valor_codigo": "NEGATIVO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "5"
},
{
"pac_id": "4",
"fecha": "2025-06-25",
"clase": "orden",
"tipo": "orden",
"codigo": "orden",
"valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
"valor_numerico": null,
"fuente_tabla": "ordenesestudio",
"fuente_id": "3"
},
{
"pac_id": "4",
"fecha": "2025-07-01",
"clase": "procedimiento",
"tipo": "citologia",
"codigo": "citologia_cervical",
"valor_codigo": "SATISFACTORIO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "6"
},
{
"pac_id": "4",
"fecha": "2025-07-11",
"clase": "medicion",
"tipo": "bethesda",
"codigo": "bethesda",
"valor_codigo": "LIEAG",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "6"
},
{
"pac_id": "4",
"fecha": "2025-07-11",
"clase": "medicion",
"tipo": "vph",
"codigo": "vph",
"valor_codigo": "POSITIVO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "6"
},
{
"pac_id": "4",
"fecha": "2025-07-11",
"clase": "medicion",
"tipo": "vph_genotipo_16_18",
"codigo": "vph_genotipo_16_18",
"valor_codigo": null,
"valor_numerico": "1.0",
"fuente_tabla": "citologiacervical",
"fuente_id": "6"
},
{
"pac_id": "4",
"fecha": "2025-07-15",
"clase": "orden",
"tipo": "orden",
"codigo": "orden",
"valor_codigo": null,
"valor_numerico": null,
"fuente_tabla": "biopsiacervical",
"fuente_id": "2"
},
{
"pac_id": "4",
"fecha": "2025-08-01",
"clase": "medicion",
"tipo": "biopsia",
"codigo": "cin",
"valor_codigo": "CIN2",
"valor_numerico": null,
"fuente_tabla": "biopsiacervical",
"fuente_id": "2"
},
{
"pac_id": "4",
"fecha": "2025-08-10",
"clase": "diagnostico",
"tipo": "nota_medica",
"codigo": "nota_medica",
"valor_codigo": "D069",
"valor_numerico": null,
"fuente_tabla": "notamedica",
"fuente_id": "1"
},
{
"pac_id": "5",
"fecha": "2025-08-12",
"clase": "procedimiento",
"tipo": "citologia",
"codigo": "citologia_cervical",
"valor_codigo": "SATISFACTORIO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "7"
},
{
"pac_id": "5",
"fecha": "2025-08-22",
"clase": "medicion",
"tipo": "bethesda",
"codigo": "bethesda",
"valor_codigo": "NEGATIVO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "7"
},
{
"pac_id": "5",
"fecha": "2025-08-22",
"clase": "medicion",
"tipo": "vph",
"codigo": "vph",
"valor_codigo": "NEGATIVO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "7"
},
{
"pac_id": "5",
"fecha": "2025-09-01",
"clase": "orden",
"tipo": "orden",
"codigo": "orden",
"valor_codigo": null,
"valor_numerico": null,
"fuente_tabla": "biopsiacervical",
"fuente_id": "3"
},
{
"pac_id": "5",
"fecha": "2025-12-01",
"clase": "orden",
"tipo": "orden",
"codigo": "orden",
"valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
"valor_numerico": null,
"fuente_tabla": "ordenesestudio",
"fuente_id": "4"
},
{
"pac_id": "6",
"fecha": "2025-09-01",
"clase": "procedimiento",
"tipo": "citologia",
"codigo": "citologia_cervical",
"valor_codigo": "INSATISFACTORIO",
"valor_numerico": null,
"fuente_tabla": "citologiacervical",
"fuente_id": "8"
}
]
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
"""Synthetic staging rows for the tests, one module per domain: written by hand, never real data."""
+187
View File
@@ -0,0 +1,187 @@
"""Filas sintéticas del staging de CaCu, escritas a mano. Nunca datos reales.
Seis pacientes y nueve citologías en dos semestres de 2025. Los textos de
calidad son provisionales: los valores reales están sin confirmar.
Pacientes tamizadas: 4 en 2025-S1 y 4 en 2025-S2; de ellas, con muestra
insatisfactoria, 2 y 1. Lo que da cada indicador va abajo (`ESPERADO_*`).
Casos que ejercita: H-003 tiene dos citologías en S1 y cuenta una vez;
H-004 tiene una el 1 de julio, que ya es S2; H-001 aparece en los dos
semestres.
Resultados (v0.5.0, T-4): seis citologías tienen reporte y cuatro, VPH;
las dos insatisfactorias de H-002 y H-006 no tienen reporte, y la última
de H-001 todavía no. Tres biopsias, cada una con la citología que la
originó: dos reportadas y una pendiente. Los textos de resultado también
son provisionales.
Cinco 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`).
Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio.
"""
from datetime import date
from core.cacu.models import BiopsiaCervical, CitologiaCervical, NotaMedica, OrdenesEstudio, Paciente
from sqlmodel import Session, select
SATISFACTORIO = "SATISFACTORIO"
INSATISFACTORIO = "INSATISFACTORIO"
PACIENTES = ("H-001", "H-002", "H-003", "H-004", "H-005", "H-006")
# (pac_id_hospital, fecha de toma, calidad del espécimen)
CITOLOGIAS = (
("H-001", date(2025, 2, 10), SATISFACTORIO),
("H-002", date(2025, 3, 5), INSATISFACTORIO),
("H-003", date(2025, 1, 20), INSATISFACTORIO),
("H-003", date(2025, 4, 15), SATISFACTORIO),
("H-004", date(2025, 5, 30), SATISFACTORIO),
("H-004", date(2025, 7, 1), SATISFACTORIO),
("H-005", date(2025, 8, 12), SATISFACTORIO),
("H-006", date(2025, 9, 1), INSATISFACTORIO),
("H-001", date(2025, 10, 2), SATISFACTORIO),
)
# Índice en CITOLOGIAS -> (fecha de reporte, células escamosas, VPH, genotipo 16, genotipo 18).
RESULTADOS = {
0: (date(2025, 2, 20), "NEGATIVO", None, None, None),
2: (date(2025, 2, 1), "ASC-US", "POSITIVO", 1, 0),
3: (date(2025, 4, 25), "LIEBG", "POSITIVO", 0, 0),
4: (date(2025, 6, 9), "NEGATIVO", None, None, None),
5: (date(2025, 7, 11), "LIEAG", "POSITIVO", 0, 1),
6: (date(2025, 8, 22), "NEGATIVO", "NEGATIVO", None, None),
}
# (índice de la citología que la originó, fecha de solicitud, fecha de reporte, grado CIN)
BIOPSIAS = (
(3, date(2025, 5, 1), date(2025, 5, 20), "CIN1"),
(5, date(2025, 7, 15), date(2025, 8, 1), "CIN2"),
(6, date(2025, 9, 1), None, None),
)
# Notas médicas: (paciente, fecha de la nota, CIE-10 y especialidad como los escribe el hospital).
COLPOSCOPIA, ONCOLOGIA, FAMILIAR = "CLINICA DE MUJER Y COLPOSCOPIA", "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR"
NOTAS = (
("H-004", date(2025, 8, 10), "D06.9", COLPOSCOPIA), # 72 días de su toma de mayo y 40 de la de julio
("H-003", date(2024, 12, 1), "C53.9", FAMILIAR), # cáncer anterior a sus dos tomas: no es un caso nuevo
("H-001", date(2025, 3, 1), "N87.1", FAMILIAR), # displasia, pero de medicina familiar: no resuelve
("H-002", date(2025, 9, 15), "C53", ONCOLOGIA), # a 194 días de su toma: fuera del horizonte
("H-005", date(2026, 1, 20), "c539", COLPOSCOPIA), # 161 días de su toma, pero después del corte de fin de año
)
# Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital).
# La segunda no es de tamizaje; la especialidad de la tercera no está en el catálogo de Core
# y queda sin reconocer; la cuarta está pedida y todavía no tiene citología.
ORDENES = (
(50001, "H-001", date(2025, 2, 3), "MEDICINA FAMILIAR"),
(50002, "H-003", date(2025, 4, 10), "CLINICA DE MUJER Y COLPOSCOPIA"),
(50003, "H-004", date(2025, 6, 25), "Dermatología"),
(50004, "H-005", date(2025, 12, 1), "MEDICINA FAMILIAR"),
)
# Índice en CITOLOGIAS -> número de su orden. Las demás citologías no traen número; la de
# H-005 trae uno que no existe entre las órdenes.
ORDEN_DE_CITOLOGIA = {0: 50001, 3: 50002, 5: 50003, 6: 59999}
# periodo -> (denominador, numerador) de IND1, con la lista de `cacu.citologia_anomala`
# (ASC-US, ASC-H, LIEBG, LIEAG, CIS). En S1 solo H-003 (su ASC-US y su LIEBG; cuenta una
# vez); en S2 solo H-004 (su LIEAG del 1 de julio).
ESPERADO_IND1 = {"2025-S1": (4, 1), "2025-S2": (4, 1)}
# (periodo, fecha de corte) -> (población inicial, n, q1, mediana, q3) de CACU_EU_TIEMPO_REPORTE,
# con horizonte de 60 días. Días de toma a resultado: S1 10, 12, 10, 10 (la toma del 5 de
# marzo no tiene resultado y a fin de año ya pasó el horizonte: cuenta en la inicial y no en
# n); S2 10, 10. A mediados de octubre las tomas de septiembre y octubre sin resultado siguen
# dentro del horizonte: no se miden. A mediados de agosto el resultado del 22 todavía no existe.
ESPERADO_CACU_TIEMPO = {
("2025-S1", "2025-12-31"): (5, 4, 10.0, 10.0, 10.5),
("2025-S2", "2025-12-31"): (4, 2, 10.0, 10.0, 10.0),
("2025-S2", "2025-10-15"): (2, 2, 10.0, 10.0, 10.0),
("2025-S2", "2025-08-15"): (1, 1, 10.0, 10.0, 10.0),
}
# periodo -> (denominador, numerador) de CACU_EU13, con la lista de arranque de
# `cacu.deteccion_grados` (LIEAG, CIS, CARCINOMA). Los grados de las biopsias de
# este fixture (CIN1, CIN2) son textos provisionales que no están en esa lista:
# el numerador es cero. El distinto de cero se prueba con filas escritas a mano
# en `cacu/familias/eu13/casos.toml`.
ESPERADO_CACU_EU13 = {"2025-S1": (4, 0), "2025-S2": (4, 0)}
# periodo -> {categoría: pacientes} de CACU_EU7 (solo las que tienen alguna). En S1, H-003
# cuenta con el LIEBG de abril (su ASC-US de enero es de una muestra insatisfactoria y,
# además, anterior) y H-002 no tiene resultado; en S2, H-006 no tiene resultado y la de
# octubre de H-001 todavía no. «NEGATIVO» es un texto provisional de este fixture: no está
# en el catálogo (que usa NORMAL, como Core) y sale después de SIN_DATO.
ESPERADO_CACU_EU7 = {
"2025-S1": {"NEGATIVO": 2, "LIEBG": 1, "SIN_DATO": 1},
"2025-S2": {"NEGATIVO": 1, "LIEAG": 1, "SIN_DATO": 2},
}
def insertar(sesion: Session) -> None:
"""Inserta pacientes, órdenes, citologías y biopsias. `pac_id` se resuelve por `pac_id_hospital`."""
pacientes = {
hospital: Paciente(
pac_id_hospital=hospital, pac_sexo="Femenino", pac_fecha_nacimiento=date(1980, 1, 1)
)
for hospital in PACIENTES
}
sesion.add_all(pacientes.values())
sesion.flush()
sesion.add_all(
OrdenesEstudio(
pac_id=pacientes[hospital].pac_id,
pac_id_hospital=hospital,
ord_numero_hospital=numero,
ord_tipo_estudio="SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
ord_fecha=fecha,
ord_especialidad=especialidad,
)
for numero, hospital, fecha, especialidad in ORDENES
)
citologias = []
for indice, (hospital, toma, calidad) in enumerate(CITOLOGIAS):
reporte, escamosas, vph, genotipo_16, genotipo_18 = RESULTADOS.get(indice, (None,) * 5)
citologias.append(
CitologiaCervical(
pac_id=pacientes[hospital].pac_id,
pac_id_hospital=hospital,
ord_numero_hospital=ORDEN_DE_CITOLOGIA.get(indice),
cit_fecha_toma=toma,
cit_calidad_especimen=calidad,
cit_fecha_reporte=reporte,
cit_celulas_escamosas=escamosas,
cit_vph_resultado=vph,
cit_vph_genotipo_16=genotipo_16,
cit_vph_genotipo_18=genotipo_18,
)
)
sesion.add_all(citologias)
sesion.flush()
for indice, solicitud, reporte, grado in BIOPSIAS:
citologia = citologias[indice]
sesion.add(
BiopsiaCervical(
pac_id=citologia.pac_id,
pac_id_hospital=citologia.pac_id_hospital,
cit_id=citologia.cit_id,
bx_fecha_solicitud=solicitud,
bx_fecha_reporte=reporte,
bx_cin_grado=grado,
)
)
sesion.add_all(
NotaMedica(
pac_id=pacientes[hospital].pac_id,
pac_id_hospital=hospital,
nm_id_hospital=f"NM-{numero:03d}",
nm_fecha=fecha,
nm_cie_codigo=cie,
nm_especialidad=especialidad,
)
for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1)
)
sesion.commit()
+213
View File
@@ -0,0 +1,213 @@
"""Filas sintéticas del staging de CaMa, escritas a mano. Nunca datos reales.
Seis pacientes y nueve mastografías en dos semestres de 2025. Los textos
de calidad son provisionales: los valores reales están sin confirmar.
Mastografías: 5 en 2025-S1 y 4 en 2025-S2; de ellas, satisfactorias, 4 y 2.
Lo que da cada indicador va abajo (`ESPERADO_*`).
Casos que ejercita: H-001 tiene dos mastografías en S1 y cuentan las dos;
una del 1 de julio ya es S2; una de S2 no tiene calidad y cuenta en el
denominador pero no en el numerador.
Resultados (v0.5.0, T-4): cada mastografía trae su BI-RADS; tiene fecha
de reporte una semana después de la toma, salvo la que no tiene calidad
ni BI-RADS y la última, todavía sin reporte.
Tres biopsias, cada una con la mastografía que la originó: dos con
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
from sqlmodel import Session, select
SATISFACTORIO = "SATISFACTORIO"
INSATISFACTORIO = "INSATISFACTORIO"
PACIENTES = ("H-101", "H-102", "H-001", "H-003", "H-103", "H-104")
# (pac_id_hospital, fecha de toma, calidad de imagen, BI-RADS)
MASTOGRAFIAS = (
("H-101", date(2025, 1, 15), SATISFACTORIO, "B1"),
("H-102", date(2025, 2, 20), SATISFACTORIO, "B2"),
("H-001", date(2025, 3, 10), INSATISFACTORIO, "B0"),
("H-001", date(2025, 4, 2), SATISFACTORIO, "B1"),
("H-003", date(2025, 6, 30), SATISFACTORIO, "B4A"),
("H-103", date(2025, 7, 1), SATISFACTORIO, "B1"),
("H-103", date(2025, 9, 9), None, None),
("H-104", date(2025, 11, 11), INSATISFACTORIO, "B0"),
("H-102", date(2025, 12, 31), SATISFACTORIO, "B2"),
)
# (índice de la mastografía que la originó, fecha de solicitud, fecha de reporte, grado histológico)
BIOPSIAS = (
(2, date(2025, 3, 20), date(2025, 4, 5), "BENIGNO"),
(4, date(2025, 7, 10), date(2025, 7, 28), "CARCINOMA_INVASOR"),
(7, date(2025, 11, 20), None, None),
)
# Notas médicas: (paciente, fecha de la nota, CIE-10 y especialidad como los escribe el hospital).
# La de H-003 llega con minúscula y punto; la de H-104 no tiene fecha y la de H-101 es de
# medicina familiar, que no resuelve la toma.
ONCOLOGIA, FAMILIAR = "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR"
NOTAS = (
("H-003", date(2025, 8, 4), "c50.4", ONCOLOGIA), # 35 días de su B4A del 30 de junio
("H-001", date(2025, 3, 1), "D05.1", FAMILIAR), # cáncer anterior a sus dos tomas: no es un caso nuevo
("H-102", date(2025, 9, 30), "C50.9", ONCOLOGIA), # a 222 días de su toma de febrero: fuera del horizonte
("H-103", date(2025, 7, 20), "C50.9", ONCOLOGIA), # 19 días de su toma del 1 de julio
("H-101", date(2025, 1, 15), "Z12.3", FAMILIAR), # normal, pero de medicina familiar: no resuelve
("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 = (
(60001, "H-101", date(2025, 1, 10), "MEDICINA FAMILIAR"),
(60002, "H-003", date(2025, 6, 20), "CIRUGIA ONCOLOGICA"),
(60003, "H-104", date(2025, 12, 5), "MEDICINA FAMILIAR"),
)
# Índice en MASTOGRAFIAS -> número de su orden. Las demás no traen número; la de H-102 trae
# uno que no existe entre las órdenes.
ORDEN_DE_MASTOGRAFIA = {0: 60001, 4: 60002, 1: 69999}
# periodo -> {categoría: pacientes} de CAMA_BIRADS (solo las que tienen alguna).
# H-001 tiene B0 y B1 en S1: cuenta en B0, la más grave. H-103 tiene B1 y una toma sin
# reporte: cuenta en B1. H-102 tiene en S2 solo una toma sin reporte: SIN_DATO.
ESPERADO_CAMA_BIRADS = {
"2025-S1": {"B0": 1, "B1": 1, "B2": 1, "B4A": 1},
"2025-S2": {"B0": 1, "B1": 1, "SIN_DATO": 1},
}
# (periodo, fecha de corte) -> (población inicial, n, q1, mediana, q3) de CAMA_EU38A, con
# horizonte de 60 días. Todo reporte llega siete días después de la toma. A fin de año la
# toma del 9 de septiembre ya pasó el horizonte sin reporte (cuenta en la inicial y no en n)
# y la del 31 de diciembre sigue en observación. El 15 de septiembre ninguna toma de S2
# posterior a julio tiene reporte ni ha vencido: solo se mide la del 1 de julio.
ESPERADO_CAMA_EU38A = {
("2025-S1", "2025-12-31"): (5, 5, 7.0, 7.0, 7.0),
("2025-S2", "2025-12-31"): (3, 2, 7.0, 7.0, 7.0),
("2025-S2", "2025-09-15"): (1, 1, 7.0, 7.0, 7.0),
}
# periodo -> (denominador, numerador) de CAMA_CONFIRMACION_BIRADS45, con la lista de arranque de
# `cama.birads_sospecha` (B4 con o sin subcategoría, B5). La única mastografía de sospecha es la B4A de H-003 del 30 de
# junio, y su biopsia se reportó el 28 de julio: cuenta en S1, el semestre de la mastografía.
# Las otras dos biopsias salen de mastografías B0, que no están en la lista. En S2 no hay
# ninguna de sospecha: sin denominador, el reporte sale suprimido y no se compara.
ESPERADO_CAMA_CONFIRMACION_BIRADS45 = {"2025-S1": (1, 1)}
def insertar(sesion: Session) -> None:
"""Inserta pacientes, órdenes, mastografías, biopsias y notas. `pac_id` se resuelve por `pac_id_hospital`."""
pacientes = {
hospital: Paciente(
pac_id_hospital=hospital, pac_sexo="Femenino", pac_fecha_nacimiento=date(1975, 1, 1)
)
for hospital in PACIENTES
}
sesion.add_all(pacientes.values())
sesion.flush()
sesion.add_all(
OrdenesEstudio(
pac_id=pacientes[hospital].pac_id,
pac_id_hospital=hospital,
ord_numero_hospital=numero,
ord_tipo_estudio="MASTOGRAFIA",
ord_fecha=fecha,
ord_especialidad=especialidad,
)
for numero, hospital, fecha, especialidad in ORDENES
)
mastografias = []
for indice, (hospital, toma, calidad, birads) in enumerate(MASTOGRAFIAS):
sin_reporte = birads is None or indice == len(MASTOGRAFIAS) - 1
mastografias.append(
Mastografia(
pac_id=pacientes[hospital].pac_id,
pac_id_hospital=hospital,
ord_numero_hospital=ORDEN_DE_MASTOGRAFIA.get(indice),
mast_fecha_toma=toma,
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 numero, (indice, solicitud, reporte, grado) in enumerate(BIOPSIAS):
mastografia = mastografias[indice]
sesion.add(
BiopsiaMama(
pac_id=mastografia.pac_id,
pac_id_hospital=mastografia.pac_id_hospital,
mast_id=mastografia.mast_id,
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(
NotaMedica(
pac_id=pacientes[hospital].pac_id,
pac_id_hospital=hospital,
nm_id_hospital=f"NM-{numero:03d}",
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)
)
sesion.commit()
+139
View File
@@ -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)
+87
View File
@@ -0,0 +1,87 @@
"""What this module covers: CaMa's measures answered on request from dbt's semantic layer, against what the kit
computed on the same fixture data: every measure, every period, its units and its numbers.
Fixtures: `base`, the CaMa fixture database through the cycle up to `event_models` (dbt's views); `manifest`, dbt's
`manifest.json` (`DBT_MANIFEST`; skipped without it); `fixtures/kit_oracle_cama.json`, the kit's units and published
numbers for each measure and period (counts only; suppression off).
"""
import json
import os
from dataclasses import replace
from pathlib import Path
import pytest
from sqlalchemy import text
from conftest import base_de
from webapi.compositions import answer_composition, composition_definitions
from webapi.durations import answer_duration, duration_definitions
from webapi.metrics import Question, answer, measure_definitions
ORACLE = json.loads((Path(__file__).parent / "fixtures" / "kit_oracle_cama.json").read_text(encoding="utf-8"))
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 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 units(base, report_id: int) -> list[list]:
with base.motor.connect() as connection:
return sorted(map(list, connection.execute(text(
"select grupo, resultado_id, unidad_id, pac_id, valor_id, numero from measure_report_unidad "
"where report_id = :r"), {"r": report_id}).all()))
def published_rows(expected) -> list[dict]:
return [dict(zip(expected["published_columns"], row)) for row in expected["published"]]
@pytest.mark.parametrize("url", sorted(ORACLE))
def test_each_measure_is_the_kit_s_in_every_period(base, manifest, url):
"""Pins down every CaMa measure in every period: the kit's units (with each one's category or days) and its
numbers: a composition's count per category, a proportion's numerator and denominator, a duration's n, median,
quartiles and excluded where the kit didn't suppress them. Fails if an event model, a semantic definition or the
construct it uses drifts from what the kit meant."""
for kind, of in (("proportion", measure_definitions), ("composition", composition_definitions),
("duration", duration_definitions)):
if url in of(manifest):
definition = of(manifest)[url]
break
for period_id, expected in ORACLE[url]["periodos"].items():
question = Question(url, period_id)
rows = published_rows(expected)
if kind == "composition":
result = answer_composition("cama", definition, question, **repositories(base))
assert {k: v for k, v in result.categories.items() if v} == {
r["categoria"]: r["n"] for r in rows if r["estrato_id"] == "total" and r["n"]}, period_id
elif kind == "proportion":
result = answer("cama", definition, question, **repositories(base))
(total,) = [r for r in rows if r["estrato_id"] == "total"] or [{"numerador": 0, "denominador": 0}]
assert (result.numerator, result.denominator) == (total["numerador"] or 0, total["denominador"] or 0), period_id
else:
result = answer_duration("cama", definition, question, **repositories(base))
(total,) = [r for r in rows if r["estrato_id"] == "total"]
if not total["suprimido"]:
assert (result.n, result.median, result.q1, result.q3, result.excluded) == (
total["n"], total["mediana"], total["q1"], total["q3"], total["n_excluido"]), period_id
assert units(base, result.report_id) == expected["units"], period_id
+116
View File
@@ -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)
+34 -14
View File
@@ -9,8 +9,8 @@ from datetime import date
import pytest
from sqlmodel import select
from indicadores_kit.registry import catalogos
from indicadores_kit.tablas import tablas_de
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
@@ -27,7 +27,7 @@ def _record(key: str, pairs: list[tuple[str, str]]) -> ExtractedRecord:
@pytest.fixture
def cacu_catalog(tmp_path, monkeypatch):
"""`add_resultado`/`sincronizar` write real rows and a real file:
"""`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(
@@ -65,24 +65,21 @@ def test_a_matched_field_is_written_on_the_existing_resultado(cacu_catalog, know
assert procedimiento.fuente_id == known_patient
def test_an_unmatched_field_mints_a_resultado_and_is_written_too(cacu_catalog, 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.fields_minted == 1
nombres = set(catalogos._leer(cacu_catalog)["citologia"]["resultados"])
assert nombres == {"calidad_muestra", "tipo_de_fijador"} # the fixture's field, plus the minted one
minted_id = "citologia.tipo_de_fijador"
catalogo = catalogos.catalogo_desde_toml(cacu_catalog, tablas=tablas_de("cacu"))
assert minted_id in {r.resultado_id for r in catalogo.resultados}
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:
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
assert observacion.resultado_id == minted_id
assert observacion.valor_texto == "Formol"
assert sesion.exec(select(carga_repository.observacion)).all() == []
def test_a_patient_outside_persona_is_skipped_not_dropped_silently(cacu_catalog, known_patient):
@@ -95,3 +92,26 @@ def test_a_patient_outside_persona_is_skipped_not_dropped_silently(cacu_catalog,
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"
+3 -3
View File
@@ -6,9 +6,9 @@ and silently drops its value instead.
from datetime import date
import pytest
from indicadores_kit.registry import catalogos
from indicadores_kit.registry.catalogos import Catalogo
from indicadores_kit.tablas import tablas_de
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
+77
View File
@@ -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"'
+53
View File
@@ -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"
+180
View File
@@ -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)
+21 -12
View File
@@ -1,6 +1,6 @@
"""`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 (`varbinary(max)`) or already be plain text, both without a filesystem
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.
"""
@@ -31,7 +31,7 @@ REPORT = text_pdf(
@pytest.fixture
def sqlite_studies_table(tmp_path):
"""A source table shaped like ISSSTELEON's: one row per study, its
"""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"
@@ -70,7 +70,7 @@ def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table)
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 ISSSTELEON's column may not always
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",
@@ -119,9 +119,11 @@ def test_a_missing_column_is_a_bad_request(client, sqlite_studies_table):
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`) still reaches the silver layer through the open-catalog
path, alongside the recognized fields `commit_sources` writes as
before. Fails if `/imports/commit` stops wiring that second path in.
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
@@ -129,12 +131,16 @@ def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(cl
from sqlalchemy import create_engine, text as sa_text
from sqlmodel import select
from indicadores_kit.registry import catalogos
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)
(tmp_path / "cacu.toml").write_text('[citologia]\netiqueta = "Citología cervical"\n', encoding="utf-8")
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'}"
@@ -152,14 +158,17 @@ def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(cl
}
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"]
[report] = [r for r in body["catalog_fallback"] if r["label"] == "estudios_extra"]
assert report["records_written"] == 1 and report["fields_minted"] == 1
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:
[minted] = list(
[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 minted.resultado_id == "citologia.tipo_de_fijador" and minted.valor_texto == "Formol"
assert written.resultado_id == "citologia.tipo_de_fijador" and written.valor_texto == "Formol"
+178
View File
@@ -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
+84
View File
@@ -0,0 +1,84 @@
"""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"
def test_a_measure_carries_its_technical_sheet(domain_client):
"""Pins down: what a metric's `meta` writes for the technical sheet reaches its Measure: `ficha` and
`figuras_detalle` as extensions, `referencias` as `relatedArtifact` and `descripcion_poblaciones` as the
populations' descriptions. Fails if `measure_resource` stops reading one of them, or CACU_EU7's or
CAMA_BIOPSIAS' `meta` loses it."""
domain, client = domain_client
measure_id = {"cacu": "CACU-EU7", "cama": "CAMA-BIOPSIAS"}[domain]
measure = client.get(f"/{domain}/fhir/Measure/{measure_id}").get_json()
by_name = {}
for extension in measure["extension"]:
by_name.setdefault(extension["url"].rsplit("/", 1)[-1], []).append(extension)
sheet = {e["url"]: e["valueString"] for e in by_name["ficha"][0]["extension"]}
assert sheet["para"] == "Médico" and sheet["pregunta"].startswith("¿Cómo se distribuyen")
if domain == "cacu":
assert measure["relatedArtifact"] == [{
"type": "citation", "display": "European Guidelines for QA in Cervical Cancer Screening, 2ª ed. (2008)",
"citation": "indicador 7"}]
texts = {e["extension"][0]["valueString"]: e["extension"][1:] for e in by_name["figura-detalle"]}
assert set(texts) == {"fig_c2_barras", "fig_c2_donas"}
assert [e["url"] for e in texts["fig_c2_donas"]][:2] == ["descripcion", "como-leer"]
population = measure["group"][0]["population"][0]
assert population["description"].startswith("Pacientes con al menos una citología tomada en el periodo.")
+236
View File
@@ -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"
+145 -25
View File
@@ -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)
+23 -6
View File
@@ -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,7 +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_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 TEA leaves the queue's domains (`DOMAINS` in `webapi.recomputation`).
"""
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 True
@pytest.fixture
+13 -9
View File
@@ -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
-338
View File
@@ -1,338 +0,0 @@
"""Rutas de indicadores de CACU: base SQLite temporal sembrada con los fixtures del kit."""
import pytest
from conftest import MESES, SEMESTRES, cliente_de
from indicadores_kit.registry.measures import RAIZ, measures_de
from indicadores_kit.serving.figuras import figuras_de
PROYECTO = "cacu"
INDICADOR = "ind1"
DEFINICIONES = measures_de(PROYECTO)
(FIGURA,) = figuras_de(DEFINICIONES[INDICADOR])
@pytest.fixture(scope="module")
def client(tmp_path_factory):
yield from cliente_de(PROYECTO, tmp_path_factory)
def _figura(client, indicador: str = INDICADOR, figura: str = FIGURA, query: str = ""):
return client.get(f"/{PROYECTO}/indicadores/{indicador}/figuras/{figura}{query}")
def _x(respuesta) -> list[str]:
return [x for trazo in respuesta.get_json()["data"] for x in trazo["x"]]
def test_listar_indicadores(client):
response = client.get(f"/{PROYECTO}/indicadores")
assert response.status_code == 200
lista = response.get_json()
visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto]
assert [fila["id"] for fila in lista] == sorted(visibles)
for fila in lista:
medida = DEFINICIONES[fila["id"]]
assert fila["titulo"] == medida.title
assert fila["contrato"] == medida.extension.contrato
assert fila["figuras"] == figuras_de(medida)
assert fila["tipos_periodo"] == ["semestre", "mes"]
def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client):
"""Los que su TOML marca `oculto` (p. ej. cacu_riesgo_banda hasta MD-Q5) no salen en el catálogo, pero responden."""
ocultos = {nombre for nombre, medida in DEFINICIONES.items() if medida.extension.publicacion.oculto}
assert ocultos
ids = {fila["id"] for fila in client.get(f"/{PROYECTO}/indicadores").get_json()}
assert ids == set(DEFINICIONES) - ocultos
for indicador in ocultos:
assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 200
def test_un_indicador_retirado_da_404(client):
"""T-22a (ADR-MD-009): los retirados (`<proyecto>/retirados/` del kit) ni se calculan ni se sirven."""
retirados = [ruta.stem for ruta in (RAIZ / PROYECTO / "retirados").glob("*.toml")]
assert retirados
for indicador in retirados:
assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 404
def test_figura_con_semestres(client):
response = _figura(client, query=f"?periodos={','.join(SEMESTRES)}&tema=oscuro")
assert response.status_code == 200
assert response.mimetype == "application/json"
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES[INDICADOR].title
assert set(_x(response)) == set(SEMESTRES)
def test_figura_sin_periodos_usa_los_semestres_con_reporte(client):
response = _figura(client)
assert response.status_code == 200
assert set(_x(response)) == set(SEMESTRES) # el primer tipo que publica; los meses no entran
def test_figura_con_meses(client):
response = _figura(client, query=f"?periodos={','.join(MESES)}")
assert response.status_code == 200
assert set(_x(response)) == set(MESES)
@pytest.mark.parametrize(
"query",
[
"?tema=rojo",
"?periodos=2025-1",
"?periodos=2025-S3",
"?periodos=2025-13x",
"?periodos=2025-S1,",
"?periodos=abc",
"?periodos=2025-T1", # un tipo que el indicador no publica
"?periodos=2025-S1,2025-03", # tipos mezclados
],
)
def test_figura_con_parametros_mal_formados_da_400(client, query):
response = _figura(client, query=query)
assert response.status_code == 400
assert "error" in response.get_json()
@pytest.mark.parametrize(
("indicador", "figura", "query"),
[
("CACU_NO_EXISTE", FIGURA, ""),
(INDICADOR, "fig_c3r_caja", ""), # figura de otro contrato
(INDICADOR, "fig_no_existe", ""),
(INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte
(INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"),
(INDICADOR, FIGURA, "?periodos=2024-11"), # un mes sin reporte
],
)
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
response = _figura(client, indicador, figura, query)
assert response.status_code == 404
assert "error" in response.get_json()
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
from webapi import indicadores
def falla(*args, **kwargs):
raise KeyError("columna")
monkeypatch.setattr(indicadores, "figura_json", falla)
with pytest.raises(KeyError):
_figura(client, query="?periodos=2025-S1")
# --- Todos los indicadores del proyecto ---
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
def test_figura_de_cada_indicador(client, indicador):
for figura in figuras_de(DEFINICIONES[indicador]):
response = _figura(client, indicador, figura)
assert response.status_code == 200, (indicador, figura)
assert set(response.get_json()) >= {"data", "layout"}
def test_una_distribucion_sin_periodos_es_la_del_semestre_mas_reciente(client):
assert figuras_de(DEFINICIONES["cacu_eu7"]) == ["fig_c2_barras", "fig_c2_donas"]
por_defecto = _figura(client, "cacu_eu7", "fig_c2_donas")
del_ultimo = _figura(client, "cacu_eu7", "fig_c2_donas", f"?periodos={SEMESTRES[-1]}")
de_todos = _figura(client, "cacu_eu7", "fig_c2_donas", f"?periodos={','.join(SEMESTRES)}")
assert por_defecto.get_json() == del_ultimo.get_json()
assert len(de_todos.get_json()["data"]) == len(SEMESTRES) * len(por_defecto.get_json()["data"])
# --- El catálogo, los periodos, los datos y los metadatos ---
CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos", "filtros"}
def _ruta(client, indicador: str, ruta: str, query: str = ""):
return client.get(f"/{PROYECTO}/indicadores/{indicador}/{ruta}{query}")
def test_el_catalogo_trae_lo_necesario_para_pedir_lo_demas(client):
lista = client.get(f"/{PROYECTO}/indicadores").get_json()
assert all(set(fila) == CATALOGO for fila in lista)
for fila in lista:
medida = DEFINICIONES[fila["id"]]
assert (fila["version"], fila["unidad"], fila["sentido"]) == (medida.version, medida.basis, medida.improvementNotation)
assert fila["estratos"] == medida.extension.estratos
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
medida = DEFINICIONES[indicador]
periodos = _ruta(client, indicador, "periodos")
datos = _ruta(client, indicador, "datos")
metadatos = _ruta(client, indicador, "metadatos")
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
assert all(r.mimetype == "application/json" for r in (periodos, datos, metadatos))
assert all(r.get_json()["id"] == indicador for r in (periodos, datos, metadatos))
de_semestre = [p["periodo"] for p in periodos.get_json()["periodos"] if p["tipo"] == "semestre"]
assert de_semestre == SEMESTRES
cuerpo = datos.get_json()
assert (cuerpo["contrato"], cuerpo["tipo_periodo"], cuerpo["periodos"]) == (medida.extension.contrato, "semestre", SEMESTRES)
assert cuerpo["filas"] and all(fila["estrato"] is None for fila in cuerpo["filas"])
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
assert metadatos.get_json()["tipo_calculo"] == medida.scoring
def test_datos_con_meses(client):
response = _ruta(client, INDICADOR, "datos", f"?periodos={','.join(MESES)}")
assert response.status_code == 200
assert response.get_json()["tipo_periodo"] == "mes"
assert [fila["periodo"] for fila in response.get_json()["filas"]] == MESES
def test_los_datos_dicen_de_que_reporte_salen(client):
cuerpo = _ruta(client, INDICADOR, "datos", "?periodos=2025-S1").get_json()
periodos = _ruta(client, INDICADOR, "periodos").get_json()["periodos"]
(reporte,) = cuerpo["reportes"]
assert reporte["report_id"] == next(p["report_id"] for p in periodos if p["periodo"] == "2025-S1")
assert (reporte["periodo_inicio"], reporte["periodo_fin"]) == ("2025-01-01", "2025-07-01")
assert cuerpo["version"] == DEFINICIONES[INDICADOR].version
@pytest.mark.parametrize("query", ["?periodos=2025-S3", "?periodos=2025-S1,2025-03", "?estrato=no_existe"])
def test_datos_con_parametros_mal_formados_da_400(client, query):
response = _ruta(client, INDICADOR, "datos", query)
assert response.status_code == 400
assert "error" in response.get_json()
@pytest.mark.parametrize(
("indicador", "ruta", "query"),
[
("NO_EXISTE", "datos", ""),
("NO_EXISTE", "periodos", ""),
("NO_EXISTE", "metadatos", ""),
(INDICADOR, "datos", "?periodos=2030-S1"),
],
)
def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indicador, ruta, query):
response = _ruta(client, indicador, ruta, query)
assert response.status_code == 404
assert "error" in response.get_json()
# --- Los filtros (T-19f) ---
@pytest.mark.parametrize("query", ["?filtro=grupo_edad", "?filtro=:25-34", "?filtro=grupo_edad:25-34,grupo_edad:35-44",
"?filtro=grupo_edad:25-34", "?filtro=ronda:1"])
def test_un_filtro_mal_escrito_o_no_declarado_da_400(client, query):
"""IND1 no declara filtros (EU7 y EU13 sí, desde T-24f): todo `?filtro=` da 400, en datos y en figuras."""
for response in (_ruta(client, INDICADOR, "datos", query), _figura(client, query=query)):
assert response.status_code == 400
assert "error" in response.get_json()
def test_sin_filtro_los_datos_no_traen_la_llave_filtros(client):
assert "filtros" not in _ruta(client, INDICADOR, "datos").get_json()
def test_los_filtros_se_leen_como_estrato_y_valor():
from webapi.indicadores import filtros_pedidos
assert filtros_pedidos(None) == {} and filtros_pedidos("") == {}
assert filtros_pedidos("grupo_edad:25-34,ronda:1") == {"grupo_edad": "25-34", "ronda": "1"}
with pytest.raises(ValueError, match="mal escrito"):
filtros_pedidos("grupo_edad")
# --- La ficha técnica (T-24e) ---
# Las llaves de /metadatos antes de T-24e: no se quita ni se renombra ninguna.
METADATOS = {
"id", "titulo", "version", "estado", "contrato", "tipo_calculo", "unidad", "sentido", "descripcion",
"tipos_periodo", "figuras", "estratos", "grupos", "categorias", "grupos_de_categoria", "estandares",
"ficha", "parametros",
} # fmt: skip
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
def test_los_metadatos_traen_referencias_poblaciones_y_figuras_sin_perder_llaves(client, indicador):
cuerpo = _ruta(client, indicador, "metadatos").get_json()
assert set(cuerpo) == METADATOS | {"referencias", "poblaciones", "figuras_detalle"}
assert cuerpo["poblaciones"]
assert [d["figura"] for d in cuerpo["figuras_detalle"]] == cuerpo["figuras"]
if not DEFINICIONES[indicador].extension.publicacion.oculto:
assert all(d["descripcion"] and d["como_leer"] for d in cuerpo["figuras_detalle"])
assert all(set(p) == {"grupo", "codigo", "descripcion"} and p["descripcion"] for p in cuerpo["poblaciones"])
def test_la_ficha_de_eu7_cita_el_lineamiento_europeo(client):
cuerpo = _ruta(client, "cacu_eu7", "metadatos").get_json()
assert cuerpo["referencias"] == [{
"tipo": "citation",
"etiqueta": "European Guidelines for QA in Cervical Cancer Screening, 2ª ed. (2008)",
"ref": "indicador 7",
}] # fmt: skip
assert cuerpo["poblaciones"] == [{
"grupo": "total",
"codigo": "measure-observation",
"descripcion": DEFINICIONES["cacu_eu7"].group[0].population[0].description,
}] # fmt: skip
# --- EU7 por estrato (T-24f): la dona y sus barras ---
def test_eu7_por_estatus_da_categoria_por_valor_con_etiquetas_y_totales(client):
cuerpo = _ruta(client, "cacu_eu7", "datos", "?estrato=estatus_seguimiento").get_json()
assert cuerpo["estrato"] == "estatus_seguimiento" and cuerpo["valores_estrato"]
assert set(cuerpo["etiquetas_estrato"]) == set(cuerpo["valores_estrato"])
assert {f["estrato"] for f in cuerpo["filas"]} == set(cuerpo["valores_estrato"])
assert {t["estrato"] for t in cuerpo["totales_estrato"]} == set(cuerpo["valores_estrato"])
def test_eu7_se_puede_filtrar_por_grupo_de_edad(client):
valor = _ruta(client, "cacu_eu7", "datos", "?estrato=grupo_edad").get_json()["valores_estrato"][0]
response = _ruta(client, "cacu_eu7", "datos", f"?filtro=grupo_edad:{valor}")
assert response.status_code == 200
assert response.get_json()["filtros"] == {"grupo_edad": valor}
def test_el_catalogo_publica_los_filtros_con_sus_valores(client):
"""T-24f (contrato de T-24a §3): con ellos se arma `?filtro=estrato:valor`."""
por_id = {fila["id"]: fila for fila in client.get(f"/{PROYECTO}/indicadores").get_json()}
assert por_id[INDICADOR]["filtros"] == [] # IND1 no declara filtros
(edad, estatus) = por_id["cacu_eu7"]["filtros"]
assert (edad["estrato"], edad["etiqueta"]) == ("grupo_edad", "Grupo de edad")
assert [v["valor"] for v in edad["valores"]][-1] == "sin_dato"
assert (estatus["estrato"], estatus["etiqueta"]) == ("estatus_seguimiento", "Estatus de seguimiento")
assert estatus["valores"] == [
{"valor": "PRE_COLPOSCOPIA", "etiqueta": "Pre colposcopia"},
{"valor": "POST_COLPOSCOPIA", "etiqueta": "Post colposcopia"},
{"valor": "POST_TRATAMIENTO", "etiqueta": "Post tratamiento"},
{"valor": "INFO_INSUFICIENTE", "etiqueta": "Información insuficiente"},
]
valor = edad["valores"][0]["valor"]
assert _ruta(client, "cacu_eu7", "datos", f"?filtro=grupo_edad:{valor}").status_code == 200
-229
View File
@@ -1,229 +0,0 @@
"""Rutas de indicadores de CAMA: base SQLite temporal sembrada con los fixtures del kit."""
import pytest
from conftest import MESES, SEMESTRES, cliente_de
from indicadores_kit.registry.measures import RAIZ, measures_de
from indicadores_kit.serving.figuras import figuras_de
PROYECTO = "cama"
INDICADOR = "cama_confirmacion_birads45"
DEFINICIONES = measures_de(PROYECTO)
(FIGURA,) = figuras_de(DEFINICIONES[INDICADOR])
@pytest.fixture(scope="module")
def client(tmp_path_factory):
yield from cliente_de(PROYECTO, tmp_path_factory)
def _figura(client, indicador: str = INDICADOR, figura: str = FIGURA, query: str = ""):
return client.get(f"/{PROYECTO}/indicadores/{indicador}/figuras/{figura}{query}")
def _x(respuesta) -> list[str]:
return [x for trazo in respuesta.get_json()["data"] for x in trazo["x"]]
def test_listar_indicadores(client):
response = client.get(f"/{PROYECTO}/indicadores")
assert response.status_code == 200
lista = response.get_json()
visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto]
assert [fila["id"] for fila in lista] == sorted(visibles)
for fila in lista:
medida = DEFINICIONES[fila["id"]]
assert fila["titulo"] == medida.title
assert fila["contrato"] == medida.extension.contrato
assert fila["figuras"] == figuras_de(medida)
assert fila["tipos_periodo"] == ["semestre", "mes"]
def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client):
"""Provisional (oct 2026): cama_birads no se muestra.
cama_birads lo sustituyen cama_birads_456_paciente y cama_birads_456_mastografia.
cama_confirmacion_birads45 vuelve a mostrarse: su tarjeta destacada y su
gráfica de tendencia (usuario, 2026-10-16).
"""
ocultos = {"cama_birads"} # cama_riesgo_banda es propuesta desde T-21h: no se calcula ni se sirve
ids = {fila["id"] for fila in client.get(f"/{PROYECTO}/indicadores").get_json()}
assert ids == set(DEFINICIONES) - ocultos
for indicador in ocultos:
assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 200
def test_un_indicador_retirado_da_404(client):
"""T-22a (ADR-MD-009): los retirados (`<proyecto>/retirados/` del kit) ni se calculan ni se sirven."""
retirados = [ruta.stem for ruta in (RAIZ / PROYECTO / "retirados").glob("*.toml")]
assert retirados
for indicador in retirados:
assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 404
def test_figura_con_semestres(client):
response = _figura(client, query=f"?periodos={','.join(SEMESTRES)}&tema=oscuro")
assert response.status_code == 200
assert response.mimetype == "application/json"
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES[INDICADOR].title
assert set(_x(response)) == set(SEMESTRES)
def test_figura_sin_periodos_usa_los_semestres_con_reporte(client):
response = _figura(client)
assert response.status_code == 200
assert set(_x(response)) == set(SEMESTRES) # el primer tipo que publica; los meses no entran
def test_figura_con_meses(client):
response = _figura(client, query=f"?periodos={','.join(MESES)}")
assert response.status_code == 200
assert set(_x(response)) == set(MESES)
@pytest.mark.parametrize(
"query",
[
"?tema=rojo",
"?periodos=2025-1",
"?periodos=2025-S3",
"?periodos=2025-13x",
"?periodos=2025-S1,",
"?periodos=abc",
"?periodos=2025-T1", # un tipo que el indicador no publica
"?periodos=2025-S1,2025-03", # tipos mezclados
],
)
def test_figura_con_parametros_mal_formados_da_400(client, query):
response = _figura(client, query=query)
assert response.status_code == 400
assert "error" in response.get_json()
@pytest.mark.parametrize(
("indicador", "figura", "query"),
[
("CAMA_NO_EXISTE", FIGURA, ""),
(INDICADOR, "fig_c3r_caja", ""), # figura de otro contrato
(INDICADOR, "fig_no_existe", ""),
(INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte
(INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"),
(INDICADOR, FIGURA, "?periodos=2024-11"), # un mes sin reporte
],
)
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
response = _figura(client, indicador, figura, query)
assert response.status_code == 404
assert "error" in response.get_json()
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
from webapi import indicadores
def falla(*args, **kwargs):
raise KeyError("columna")
monkeypatch.setattr(indicadores, "figura_json", falla)
with pytest.raises(KeyError):
_figura(client, query="?periodos=2025-S1")
# --- Todos los indicadores del proyecto ---
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
def test_figura_de_cada_indicador(client, indicador):
for figura in figuras_de(DEFINICIONES[indicador]):
response = _figura(client, indicador, figura)
assert response.status_code == 200, (indicador, figura)
assert set(response.get_json()) >= {"data", "layout"}
# --- El catálogo, los periodos, los datos y los metadatos ---
CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos", "filtros"}
def _ruta(client, indicador: str, ruta: str, query: str = ""):
return client.get(f"/{PROYECTO}/indicadores/{indicador}/{ruta}{query}")
def test_el_catalogo_trae_lo_necesario_para_pedir_lo_demas(client):
lista = client.get(f"/{PROYECTO}/indicadores").get_json()
assert all(set(fila) == CATALOGO for fila in lista)
for fila in lista:
medida = DEFINICIONES[fila["id"]]
assert (fila["version"], fila["unidad"], fila["sentido"]) == (medida.version, medida.basis, medida.improvementNotation)
assert fila["estratos"] == medida.extension.estratos
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
medida = DEFINICIONES[indicador]
periodos = _ruta(client, indicador, "periodos")
datos = _ruta(client, indicador, "datos")
metadatos = _ruta(client, indicador, "metadatos")
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
assert all(r.mimetype == "application/json" for r in (periodos, datos, metadatos))
assert all(r.get_json()["id"] == indicador for r in (periodos, datos, metadatos))
de_semestre = [p["periodo"] for p in periodos.get_json()["periodos"] if p["tipo"] == "semestre"]
assert de_semestre == SEMESTRES
cuerpo = datos.get_json()
assert (cuerpo["contrato"], cuerpo["tipo_periodo"], cuerpo["periodos"]) == (medida.extension.contrato, "semestre", SEMESTRES)
assert cuerpo["filas"] and all(fila["estrato"] is None for fila in cuerpo["filas"])
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
assert metadatos.get_json()["tipo_calculo"] == medida.scoring
def test_datos_con_meses(client):
response = _ruta(client, INDICADOR, "datos", f"?periodos={','.join(MESES)}")
assert response.status_code == 200
assert response.get_json()["tipo_periodo"] == "mes"
assert [fila["periodo"] for fila in response.get_json()["filas"]] == MESES
def test_los_datos_dicen_de_que_reporte_salen(client):
cuerpo = _ruta(client, INDICADOR, "datos", "?periodos=2025-S1").get_json()
periodos = _ruta(client, INDICADOR, "periodos").get_json()["periodos"]
(reporte,) = cuerpo["reportes"]
assert reporte["report_id"] == next(p["report_id"] for p in periodos if p["periodo"] == "2025-S1")
assert (reporte["periodo_inicio"], reporte["periodo_fin"]) == ("2025-01-01", "2025-07-01")
assert cuerpo["version"] == DEFINICIONES[INDICADOR].version
@pytest.mark.parametrize("query", ["?periodos=2025-S3", "?periodos=2025-S1,2025-03", "?estrato=no_existe"])
def test_datos_con_parametros_mal_formados_da_400(client, query):
response = _ruta(client, INDICADOR, "datos", query)
assert response.status_code == 400
assert "error" in response.get_json()
@pytest.mark.parametrize(
("indicador", "ruta", "query"),
[
("NO_EXISTE", "datos", ""),
("NO_EXISTE", "periodos", ""),
("NO_EXISTE", "metadatos", ""),
(INDICADOR, "datos", "?periodos=2030-S1"),
],
)
def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indicador, ruta, query):
response = _ruta(client, indicador, ruta, query)
assert response.status_code == 404
assert "error" in response.get_json()
-169
View File
@@ -1,169 +0,0 @@
import pytest
from indicadores_kit.registry.measures import RAIZ, measures_de
from indicadores_kit.serving.figuras import figuras_de
from indicadores_kit.tea import fixtures
DEFINICIONES = measures_de("tea")
PERIODOS = ",".join(fixtures.PERIODOS)
@pytest.fixture(scope="module")
def client(tmp_path_factory):
"""Una base de TEA temporal, con los 20 indicadores calculados (16 en el catálogo), por `TEA_DATABASE_URL`."""
# Dentro de la fixture: la configuración de Persistance se lee al importarla,
# y test_app.py debe alcanzar a fijar CACU_DATABASE_URL antes.
from persistance.db import get_tea_engine
from persistance.settings import settings
ruta = tmp_path_factory.mktemp("tea") / "tea.db"
with pytest.MonkeyPatch.context() as mp:
mp.setattr(settings, "tea_database_url", f"sqlite:///{ruta}")
get_tea_engine.cache_clear()
try:
fixtures.base_de_prueba(get_tea_engine())
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as cliente:
yield cliente
finally:
get_tea_engine().dispose()
get_tea_engine.cache_clear()
def _figura(client, indicador: str, figura: str, query: str = ""):
return client.get(f"/tea/indicadores/{indicador}/figuras/{figura}{query}")
def test_listar_indicadores(client):
response = client.get("/tea/indicadores")
assert response.status_code == 200
lista = response.get_json()
visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto]
assert [fila["id"] for fila in lista] == sorted(visibles)
for fila in lista:
medida = DEFINICIONES[fila["id"]]
assert fila["titulo"] == medida.title
assert fila["contrato"] == medida.extension.contrato
assert fila["figuras"] == figuras_de(medida)
def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client):
"""Provisional (oct 2026): solo se muestran M21, M22 y los tres destacados (M23 a M25)."""
visibles = {
"M21_diagnosticados_con_eeg",
"M22_diagnosticados_sin_eeg",
"M23_pacientes_evaluados",
"M24_confirmacion_diagnostico",
"M25_dias_mchat_diagnostico",
}
ids = {fila["id"] for fila in client.get("/tea/indicadores").get_json()}
assert ids == visibles
for oculto in sorted(set(DEFINICIONES) - visibles):
assert client.get(f"/tea/indicadores/{oculto}/metadatos").status_code == 200
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
def test_figura_de_cada_indicador(client, indicador):
for figura in figuras_de(DEFINICIONES[indicador]):
response = _figura(client, indicador, figura, f"?periodos={PERIODOS}&tema=oscuro")
assert response.status_code == 200, figura
assert response.mimetype == "application/json"
assert "data" in response.get_json()
def test_figura_sin_periodos_usa_todos_los_reportes(client):
(figura,) = figuras_de(DEFINICIONES["M21_diagnosticados_con_eeg"])
response = _figura(client, "M21_diagnosticados_con_eeg", figura)
assert response.status_code == 200
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES["M21_diagnosticados_con_eeg"].title
@pytest.mark.parametrize(
"query",
[
"?tema=rojo",
"?periodos=2025-1",
"?periodos=2025-S1,",
"?periodos=abc",
"?periodos=,",
],
)
def test_figura_con_parametros_mal_formados_da_400(client, query):
response = _figura(client, "M21_diagnosticados_con_eeg", "fig_c1_grupos", query)
assert response.status_code == 400
assert "error" in response.get_json()
@pytest.mark.parametrize(
("indicador", "figura", "query"),
[
("K99_no_existe", "fig_c1_grupos", ""),
("M21_diagnosticados_con_eeg", "fig_c3r_caja", ""), # figura de otro contrato
("M21_diagnosticados_con_eeg", "fig_no_existe", ""),
("M21_diagnosticados_con_eeg", "fig_c1_grupos", "?periodos=2030-S1"), # sin reporte
("M21_diagnosticados_con_eeg", "fig_c1_grupos", f"?periodos={PERIODOS},2030-S2"),
],
)
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
response = _figura(client, indicador, figura, query)
assert response.status_code == 404
assert "error" in response.get_json()
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
from webapi import indicadores
def falla(*args, **kwargs):
raise KeyError("columna")
monkeypatch.setattr(indicadores, "figura_json", falla)
with pytest.raises(KeyError):
_figura(client, "M21_diagnosticados_con_eeg", "fig_c1_grupos", "?periodos=2025-S1")
# --- Los periodos, los datos y los metadatos ---
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
medida = DEFINICIONES[indicador]
periodos = client.get(f"/tea/indicadores/{indicador}/periodos")
datos = client.get(f"/tea/indicadores/{indicador}/datos?periodos={PERIODOS}")
metadatos = client.get(f"/tea/indicadores/{indicador}/metadatos")
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
assert [p["periodo"] for p in periodos.get_json()["periodos"]] == sorted(fixtures.PERIODOS)
cuerpo = datos.get_json()
assert (cuerpo["id"], cuerpo["contrato"]) == (indicador, medida.extension.contrato)
assert cuerpo["filas"] and {fila["periodo"] for fila in cuerpo["filas"]} == set(fixtures.PERIODOS)
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
assert metadatos.get_json()["ficha"]["codigo"] == medida.extension.ficha.codigo
def test_los_grupos_de_los_datos_van_en_el_orden_de_la_ficha(client):
response = client.get(f"/tea/indicadores/M21_diagnosticados_con_eeg/datos?periodos={PERIODOS}")
grupos = list(response.get_json()["grupos"])
assert grupos != sorted(grupos) # el orden de la ficha, no el alfabético
assert grupos[-1] == "TOTAL"
def test_un_indicador_retirado_da_404(client):
"""T-22a (ADR-MD-009): los retirados (`tea/retirados/` del kit) ni se calculan ni se sirven."""
retirados = [ruta.stem for ruta in (RAIZ / "tea" / "retirados").glob("*.toml")]
assert len(retirados) == 18
for indicador in retirados:
assert client.get(f"/tea/indicadores/{indicador}/metadatos").status_code == 404
+135
View File
@@ -0,0 +1,135 @@
"""What this module covers: `webapi.kpis`, the route that answers a measure's periods on request as a FHIR `Bundle`
of `MeasureReport`s.
Fixtures: `base`, `manifest` and `kit` from `test_metrics_on_request` (the CaCu fixture database through the cycle,
dbt's manifest, the kit's snapshot; skipped without `DBT_MANIFEST`); `client`, a Flask app with only this domain's KPI
blueprint.
"""
import json
import os
from pathlib import Path
import pytest
from flask import Flask
from test_metrics_on_request import EU7, EU13, IND1, base, kit, manifest, reports # noqa: F401
from webapi.kpis import kpis_blueprint
@pytest.fixture
def client(base, manifest): # noqa: F811
app = Flask(__name__)
app.register_blueprint(kpis_blueprint("cacu", base.dominio, manifest), url_prefix="/cacu")
return app.test_client()
def counts(resource: dict) -> dict[str, int]:
(group,) = resource["group"]
return {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
def history_entry(resource: dict) -> int:
(entry,) = [e for e in resource["extension"] if e["url"].endswith("/reporte-id")]
return entry["valueInteger"]
def test_a_measure_s_periods_come_as_a_bundle_of_measure_reports(base, client, kit): # noqa: F811
"""Pins down the contract: one `MeasureReport` per period asked, in order, with the kit's numbers. Fails if the
route stops answering each period, changes the shape, or the counts drift from what the cycle published."""
response = client.get("/cacu/indicadores/IND1?periodos=2025-S1,2025-S2")
bundle = response.get_json(force=True)
assert response.status_code == 200 and response.mimetype == "application/fhir+json"
assert (bundle["resourceType"], bundle["type"], bundle["total"]) == ("Bundle", "searchset", 2)
for entry, period_id in zip(bundle["entry"], ("2025-S1", "2025-S2")):
report = entry["resource"]
assert report["resourceType"] == "MeasureReport" and report["measure"] == "cacu/IND1|0.3.2"
numerator, denominator = kit[IND1][period_id]["published"]["total|total"]
assert counts(report) == {"initial-population": denominator, "denominator": denominator,
"numerator": numerator}
if os.environ.get("MEASURE_REPORT_OUT"):
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_ind1.json").write_text(
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
def test_without_a_knowledge_cutoff_the_last_load_makes_the_answer_stable(base, client): # noqa: F811
"""Pins down: by default the knowledge cut-off is the last load's start, so asking again before the next load
reads the stored answer. Fails if the default becomes "now", which would store a new answer per request."""
first = client.get("/cacu/indicadores/IND1?periodos=2025-S1").get_json(force=True)
before = reports(base)
second = client.get("/cacu/indicadores/IND1?periodos=2025-S1").get_json(force=True)
assert history_entry(second["entry"][0]["resource"]) == history_entry(first["entry"][0]["resource"])
assert reports(base) == before
def test_a_measure_with_strata_brings_its_stratifier(client):
"""Pins down: EU13's reports carry its strata, by age and by follow-up status. Fails if the route drops one."""
bundle = client.get("/cacu/indicadores/CACU_EU13?periodos=2025-S1").get_json(force=True)
stratifiers = bundle["entry"][0]["resource"]["group"][0]["stratifier"]
assert [s["code"][0]["text"] for s in stratifiers] == ["grupo_edad", "estatus_seguimiento"]
if os.environ.get("MEASURE_REPORT_OUT"):
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_eu13.json").write_text(
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
def test_the_list_names_what_is_answered_on_request(client):
"""Pins down: `/indicadores` lists the measures the manifest defines for the domain. Fails if one is missing."""
listed = {m["id"] for m in client.get("/cacu/indicadores").get_json()}
assert listed == {IND1.split("/")[1], EU13.split("/")[1], EU7.split("/")[1], "CACU_EU_TIEMPO_REPORTE",
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_CONFIRMACION_CITOLOGIA",
"CACU_RIESGO_BANDA"}
def test_a_duration_comes_as_a_report_with_its_median_and_quartiles(client):
"""Pins down the route for durations: the samples measurable and measured as populations, the median as the
score in days with the quartiles as its extensions, and the event cut-off it was asked at (the last load's day
by default). 2025-S2's samples resolved in 40 and 161 days. Fails if a duration stops being served or its
contract changes."""
bundle = client.get("/cacu/indicadores/CACU_DIAS_TOMA_DIAGNOSTICO?periodos=2025-S2").get_json(force=True)
(entry,) = bundle["entry"]
report = entry["resource"]
(group,) = report["group"]
assert report["measure"] == "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3"
assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == {
"initial-population": 4, "measure-observation": 2}
assert group["measureScore"]["value"] == 100.5 and group["measureScore"]["unit"] == "d"
assert [e["valueDecimal"] for e in group["measureScore"]["extension"]] == [70.25, 130.75]
assert any(e["url"].endswith("corte-evento") for e in report["extension"])
if os.environ.get("MEASURE_REPORT_OUT"):
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_dias.json").write_text(
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
@pytest.mark.parametrize(("path", "status"), [
("/cacu/indicadores/NOPE?periodos=2025-S1", 404),
("/cacu/indicadores/IND1", 400),
("/cacu/indicadores/IND1?periodos=2025-S1&corte_evento=30-06-2025", 400),
("/cacu/indicadores/IND1?periodos=2025-S1&corte_conocimiento=ayer", 400),
("/cacu/indicadores/IND1?periodos=2031-S1", 404),
])
def test_a_bad_question_gets_a_clear_error(client, path, status):
"""Pins down the errors: an unknown measure or period is 404, a missing or misspelled parameter 400. Fails if one
of them becomes a 500."""
response = client.get(path)
assert response.status_code == status and "error" in response.get_json()
def test_a_composition_comes_with_its_categories(client, kit):
"""Pins down: EU7's reports carry the categories as a `resultado` stratifier, with the kit's counts, under the
route's default knowledge cut-off (the last load). Fails if the route stops telling compositions from
proportions, or a result's knowledge date stops being compared as the type it's stored in."""
bundle = client.get("/cacu/indicadores/CACU_EU7?periodos=2025-S1,2025-S2").get_json(force=True)
stratifiers = [e["resource"]["group"][0]["stratifier"][0] for e in bundle["entry"]]
assert [s["code"] for s in stratifiers] == [[{"text": "resultado"}]] * 2
for stratifier, period_id in zip(stratifiers, ("2025-S1", "2025-S2")):
expected = {k.split("|")[2]: n for k, n in kit[EU7][period_id]["published"].items() if k.startswith("total|")}
assert {s["value"]["text"]: s["population"][0]["count"] for s in stratifier["stratum"]} == expected
if os.environ.get("MEASURE_REPORT_OUT"):
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_eu7.json").write_text(
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
+58
View File
@@ -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
+284
View File
@@ -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
+100
View File
@@ -0,0 +1,100 @@
"""What this module covers: compositions answered from dbt's semantic layer on the hand-written cases their rules were
written with, one database per case: CACU_CONFIRMACION_CITOLOGIA (`fixtures/casos_confirmacion_citologia.toml`: the
last valid sample decides, the most severe biopsy of that sample by the cut-off is the category, a biopsy of another
sample doesn't count) and CACU_RIESGO_BANDA (`fixtures/casos_riesgo_banda.toml`: the current batch of estimates, the
latest version of each, the bands by the rules' cut points).
Fixtures: each case's database, migrated, with only its rows: staging rows through the load (a patient for each
`pac_id` named) and cohort builds and risk estimates as they are; its rule overrides in `def_parametro`; dbt's views
created by the cycle (`catalogs` … `event_models`; needs `DBT_MANIFEST`).
"""
import json
import os
import tomllib
from dataclasses import replace
from datetime import date
from pathlib import Path
import pytest
from sqlalchemy import text
from conftest import base_de
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, EvaluacionRiesgo, EvaluacionRiesgoLote
from core.cacu.models import BiopsiaCervical, CitologiaCervical, Paciente
from webapi.compositions import answer_composition, composition_definitions
from webapi.metrics import Question
FIXTURES = Path(__file__).parent / "fixtures"
FILES = ("casos_confirmacion_citologia.toml", "casos_riesgo_banda.toml")
TABLES = {m.__tablename__: m for m in (CitologiaCervical, BiopsiaCervical, CohorteArmado, CohorteMiembro,
EvaluacionRiesgoLote, EvaluacionRiesgo)}
STAGING = ("citologiacervical", "biopsiacervical")
# Rows go in by their parents first.
ORDER = ("citologiacervical", "biopsiacervical", "cohorte_armado", "cohorte_miembro", "evaluacion_riesgo_lote",
"evaluacion_riesgo")
def cases():
for name in FILES:
document = tomllib.loads((FIXTURES / name).read_text(encoding="utf-8"))
templates = document.get("plantillas", {})
for case in document["caso"]:
rows = [row for t in case.get("incluye", ()) for row in templates[t]] + case["filas"]
yield pytest.param(document["measure"], {**case, "filas": rows}, id=case["nombre"])
def rows_of(case: dict):
"""What the case's rows insert: a patient for each `pac_id`, then every row by its parents first."""
def insert(session):
for pac_id in sorted({row["pac_id"] for row in case["filas"] if "pac_id" in row}):
session.add(Paciente(pac_id=pac_id, pac_id_hospital=f"H-{pac_id:03d}", pac_sexo="Femenino",
pac_fecha_nacimiento=date(1980, 1, 1)))
session.flush()
for row in sorted(case["filas"], key=lambda r: ORDER.index(r["tabla"])):
data = {k: v for k, v in row.items() if k != "tabla"}
if row["tabla"] in STAGING:
data["pac_id_hospital"] = f"H-{row['pac_id']:03d}"
session.add(TABLES[row["tabla"]](**data))
session.flush()
session.commit()
return insert
@pytest.mark.parametrize(("url", "case"), list(cases()))
def test_each_case_answers_what_its_rules_say(tmp_path, sin_supresion, url, case):
"""Pins down each hand-written case: the count in each category it names (zero included), the patients in the
categories it lists and their stratum values, at its cut-off and with its rules. Fails if the measure stops
meaning what the case says; the case's name says which rule."""
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("cacu", tmp_path, rows_of(case))
base.run("catalogs", "load", "registry", "definitions", "event_models", parameters=sin_supresion,
allow_undecided=True)
with base.motor.begin() as connection:
for key, value in case.get("parametros", {}).items():
connection.execute(text("update def_parametro set valor = :v where clave = :k"),
{"v": json.dumps(value), "k": key})
definition = composition_definitions(Path(manifest))[url]
d = base.dominio
for period_id in sorted({*case.get("espera", {}), *case.get("unidades", {}), *case.get("estratos", {})}):
result = answer_composition(
"cacu", definition, Question(url, period_id, case.get("corte")), parameters=d.def_parametro_repository,
periods=d.dim_periodo_repository, history=d.history_repository, queries=d.dbt_query_repository,
allow_undecided=True)
for category, n in case.get("espera", {}).get(period_id, {}).items():
assert result.categories.get(category.removeprefix("cat:"), 0) == n, (period_id, category)
with base.motor.connect() as connection:
units = connection.execute(text(
"select valor_id, unidad_id from measure_report_unidad where report_id = :r"),
{"r": result.report_id}).all()
strata = connection.execute(text(
"select estrato_id, unidad_id, estrato_valor from measure_report_unidad_estrato where report_id = :r"),
{"r": result.report_id}).all()
for category, expected in case.get("unidades", {}).get(period_id, {}).items():
assert sorted(u for v, u in units if v == category.removeprefix("cat:")) == sorted(map(str, expected)), (
period_id, category)
for stratum, expected in case.get("estratos", {}).get(period_id, {}).items():
assert {u: v for s, u, v in strata if s == stratum} == expected, (period_id, stratum)
base.motor.dispose()
+474
View File
@@ -0,0 +1,474 @@
"""What this module covers: `webapi.metrics` and `webapi.compositions`, CaCu's measures answered on request from
dbt's semantic definitions, with the period and both cut-offs in the question, and `MeasureHistoryRepository`, which
keeps each answer under its key.
Fixtures: `base`, the CaCu fixture database through the cycle up to `event_models` (which creates dbt's event models);
`manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `kit`, what the kit computed for IND1, EU13
and EU7 on the same fixture data (`fixtures/kit_cacu_snapshot.json`): the oracle these answers were proven against.
"""
import json
import os
import time
from dataclasses import replace
from datetime import date, datetime, timezone
from pathlib import Path
import pytest
from sqlalchemy import text
from sqlmodel import Session, select
from conftest import base_de
from core.cacu.models import BiopsiaCervical, CitologiaCervical
from webapi.compositions import answer_composition, composition_definitions, composition_report
from webapi.metrics import Question, answer, measure_definitions, measure_report
from webapi.orchestration import run
IND1, EU13, EU7 = "cacu/IND1", "cacu/CACU_EU13", "cacu/CACU_EU7"
STATUS = "estatus_seguimiento"
HASTA_MODELOS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
PERIODS = [f"2025-{m:02d}" for m in range(1, 13)] + ["2025-S1", "2025-S2"]
SNAPSHOT = Path(__file__).parent / "fixtures" / "kit_cacu_snapshot.json"
@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("cacu", tmp_path)
base.run(*HASTA_MODELOS, parameters=sin_supresion, allow_undecided=True)
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
base.motor.dispose()
@pytest.fixture
def kit():
return json.loads(SNAPSHOT.read_text(encoding="utf-8"))
@pytest.fixture
def definition(manifest):
return measure_definitions(manifest)[IND1]
@pytest.fixture
def eu13(manifest):
return measure_definitions(manifest)[EU13]
@pytest.fixture
def eu7(manifest):
return composition_definitions(manifest)[EU7]
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 ask(base, definition, period_id, *, event_cutoff=None, knowledge_cutoff=None):
question = Question(definition.url, period_id, event_cutoff, knowledge_cutoff)
if definition.url == EU7:
return answer_composition("cacu", definition, question, **repositories(base))
return answer("cacu", definition, question, **repositories(base))
def units(base, report_id: int) -> list[list]:
with base.motor.connect() as connection:
return sorted(map(list, connection.execute(text(
"select grupo, resultado_id, unidad_id, pac_id, valor_id from measure_report_unidad where report_id = :r"),
{"r": report_id}).all()))
def strata_rows(base, report_id: int, stratum: str = "grupo_edad") -> list[list]:
with base.motor.connect() as connection:
return sorted(map(list, connection.execute(text(
"select unidad_id, estrato_valor from measure_report_unidad_estrato where report_id = :r "
"and estrato_id = :e"), {"r": report_id, "e": stratum}).all()))
def proportion_cells(result) -> dict:
"""An answer as the snapshot keeps what `v_c1` published: `{"stratum|value": [numerator, denominator]}`."""
cells = {"total|total": [result.numerator, result.denominator]}
for stratum, values in result.strata.items():
cells |= {f"{stratum}|{v}": [c.numerator, c.denominator] for v, c in values.items()}
return cells
def composition_cells(result) -> dict:
"""An answer as the snapshot keeps what `v_c2` published: `{"stratum|value|category": n}`."""
cells = {f"total|total|{c}": n for c, n in result.categories.items()}
for stratum, values in result.strata.items():
cells |= {f"{stratum}|{v}|{c}": n for v, cs in values.items() for c, n in cs.items()}
return cells
def without(cells: dict, stratum: str) -> dict:
return {k: v for k, v in cells.items() if not k.startswith(f"{stratum}|")}
def reports(base) -> int:
with base.motor.connect() as connection:
return connection.execute(text("select count(*) from measure_report")).scalar_one()
def reload(base, change) -> None:
"""Changes the staging as the ingestion would and runs `load`: a new load, known later than everything before."""
time.sleep(0.01)
with Session(base.motor) as session:
change(session)
session.commit()
run(base.ctx, only=["load"])
def test_ind1_answers_what_the_kit_computed(base, definition, kit):
"""Pins down: with no cut-off, every period's IND1 has the kit's units and its numbers. Fails if the semantic
definition (event model, metrics, filter) stops meaning what the kit's IND1 meant."""
for period_id in PERIODS:
result, expected = ask(base, definition, period_id), kit[IND1][period_id]
assert units(base, result.report_id) == expected["units"], period_id
assert proportion_cells(result)["total|total"] == expected["published"].get("total|total", [0, 0]), period_id
def test_eu13_with_its_age_strata_answers_what_the_kit_computed(base, eu13, kit):
"""Pins down: EU13 gives the kit's units, each patient's age group at the period's start and the numbers by age
in every period. Fails if the event model, the report date's condition or the age from `dim_fecha` drift."""
for period_id in PERIODS:
result, expected = ask(base, eu13, period_id), kit[EU13][period_id]
assert units(base, result.report_id) == expected["units"], period_id
assert strata_rows(base, result.report_id) == expected["grupo_edad"], period_id
assert without(proportion_cells(result), STATUS) == (expected["published"] or {"total|total": [0, 0]}), period_id
def test_eu7_puts_each_patient_in_her_last_valid_result_as_the_kit_did(base, eu7, kit):
"""Pins down EU7, a composition: each patient in the category of her last valid sample (with a result and a
satisfactory specimen) or SIN_DATO, with her age group, and the kit's counts by category, total and by age.
Fails if the ranking (validity, then the latest sample, then the source id) or the validity rule drifts."""
for period_id in PERIODS:
result, expected = ask(base, eu7, period_id), kit[EU7][period_id]
assert units(base, result.report_id) == expected["units"], period_id
assert strata_rows(base, result.report_id) == expected["grupo_edad"], period_id
assert without(composition_cells(result), STATUS) == expected["published"], period_id
def test_every_stratum_value_written_is_in_the_catalog(base, eu13, eu7):
"""Pins down: the strata an answer writes satisfy their foreign key to `cat_estrato_valor`, which SQLite doesn't
enforce unless asked and SQL Server always does. Fails if `MeasureHistoryRepository.record` stops adding the
stratum values the catalog lacks."""
for d in (eu13, eu7):
ask(base, d, "2025-S1")
with base.motor.connect() as connection:
written = connection.execute(text("select count(*) from measure_report_unidad_estrato")).scalar()
broken = connection.execute(text("pragma foreign_key_check('measure_report_unidad_estrato')")).all()
assert written > 0
assert broken == []
def test_a_stored_answer_reads_back_the_same(base, definition, eu13, eu7):
"""Pins down: asking again reads the stored answer from its units' counts, with no view, and it's the same
answer, strata included. Fails if `MeasureHistoryRepository.counts` and the computation stop agreeing."""
for d in (definition, eu13, eu7):
first = ask(base, d, "2025-S1", event_cutoff=date(2025, 6, 30))
before = reports(base)
again = ask(base, d, "2025-S1", event_cutoff=date(2025, 6, 30))
assert (again.report_id, again.stored_before, reports(base)) == (first.report_id, True, before)
if d is eu7:
assert (again.categories, again.strata) == (first.categories, first.strata)
else:
assert proportion_cells(again) == proportion_cells(first)
def test_the_event_cutoff_leaves_out_later_facts(base, definition, kit):
"""Pins down: S1 cut at March 31 counts the patients of January to March: the union of the kit's monthly units.
Fails if the cut-off stops filtering the event date."""
result = ask(base, definition, "2025-S1", event_cutoff=date(2025, 3, 31))
months = sorted({tuple(u) for m in (1, 2, 3) for u in kit[IND1][f"2025-{m:02d}"]["units"]})
assert units(base, result.report_id) == [list(u) for u in months]
def test_a_late_fact_counts_only_under_a_later_knowledge_cutoff(base, definition):
"""Pins down: a cytology of S1 loaded later doesn't change what was known before its load; asked with a later
knowledge cut-off, it counts. Fails if `conocida_en` stops being a condition of the question."""
known = datetime.now(timezone.utc)
before = ask(base, definition, "2025-S1", knowledge_cutoff=known)
def late_cytology(session):
h005 = session.exec(select(CitologiaCervical).where(CitologiaCervical.pac_id_hospital == "H-005")).first()
session.add(CitologiaCervical(pac_id=h005.pac_id, pac_id_hospital="H-005", cit_fecha_toma=date(2025, 3, 10),
cit_calidad_especimen="SATISFACTORIO", cit_fecha_reporte=date(2025, 3, 20),
cit_celulas_escamosas="LIEAG"))
reload(base, late_cytology)
again = ask(base, definition, "2025-S1", knowledge_cutoff=known)
fresh_then = ask(base, definition, "2025-S1", knowledge_cutoff=known, event_cutoff=date(2025, 6, 30))
now = ask(base, definition, "2025-S1", knowledge_cutoff=datetime.now(timezone.utc))
assert again.report_id == before.report_id
assert (fresh_then.numerator, fresh_then.denominator) == (before.numerator, before.denominator)
assert (now.numerator, now.denominator) == (before.numerator + 1, before.denominator + 1)
def test_a_changed_fact_is_kept_by_the_history_not_by_the_knowledge_cutoff(base, definition):
"""Pins down the limit of the knowledge cut-off: silver keeps one version of each row, so after H-004's LIEAG of
July becomes NEGATIVO, recomputing S2 as known before the change can't give the old numerator; only the stored
answer still does. Fails if silver starts keeping versions (`dbt snapshot`): then expect the old one."""
known = datetime.now(timezone.utc)
shown = ask(base, definition, "2025-S2", knowledge_cutoff=known)
assert shown.numerator == 1
def corrected(session):
row = session.exec(select(CitologiaCervical).where(
CitologiaCervical.pac_id_hospital == "H-004", CitologiaCervical.cit_fecha_toma == date(2025, 7, 1))).one()
row.cit_celulas_escamosas = "NEGATIVO"
reload(base, corrected)
stored = ask(base, definition, "2025-S2", knowledge_cutoff=known)
recomputed_then = ask(base, definition, "2025-S2", knowledge_cutoff=known, event_cutoff=date(2025, 12, 31))
assert (stored.report_id, stored.numerator) == (shown.report_id, 1)
assert recomputed_then.numerator == 0 # the July result now counts as known after `known`: it's left out
assert ask(base, definition, "2025-S2", knowledge_cutoff=datetime.now(timezone.utc)).numerator == 0
def test_eu13_counts_a_qualifying_biopsy_by_its_sample_and_its_report_date(base, eu13):
"""Pins down EU13's numerator, which the fixture leaves at 0: once H-004's biopsy of August 1 (from the July 1
sample) is LIEAG she counts in 2025-07 and 2025-S2, and an event cut-off before the report leaves her out.
Fails if the numerator stops following the sample's period, the grade rule, or the report's date."""
def lieag(session):
biopsy = session.exec(select(BiopsiaCervical).where(BiopsiaCervical.pac_id_hospital == "H-004")).one()
biopsy.bx_cin_grado = "LIEAG"
reload(base, lieag)
assert ask(base, eu13, "2025-07").numerator == 1
assert ask(base, eu13, "2025-S2").numerator == 1
assert ask(base, eu13, "2025-S2", event_cutoff=date(2025, 7, 31)).numerator == 0
def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7):
"""Pins down the contract WebApi serves: a FHIR `MeasureReport` with the measure's url and version, FHIR's
inclusive period end, each population's count, the score, strata as a `stratifier`, and a composition's
categories as one more. Fails if a population, the score, a stratum or a category stops matching the answer."""
period = base.dominio.dim_periodo_repository.get("2025-S1")
at = datetime(2026, 1, 2, tzinfo=timezone.utc)
report = measure_report(definition, Question(IND1, "2025-S1"), ask(base, definition, "2025-S1"), period, at)
(group,) = report["group"]
assert report["measure"] == "cacu/IND1|0.3.2"
assert report["period"] == {"start": "2025-01-01", "end": "2025-06-30"}
assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == {
"initial-population": 4, "denominator": 4, "numerator": 1}
assert group["measureScore"] == {"value": 0.25}
assert report["improvementNotation"]["coding"][0]["code"] == "decrease"
stratifiers = measure_report(eu13, Question(EU13, "2025-S1"), ask(base, eu13, "2025-S1"), period,
at)["group"][0]["stratifier"]
assert [s["code"] for s in stratifiers] == [[{"text": "grupo_edad"}], [{"text": STATUS}]]
composition = composition_report(eu7, Question(EU7, "2025-S1"), ask(base, eu7, "2025-S1"), period, at)
by_result = composition["group"][0]["stratifier"][0]
assert by_result["code"] == [{"text": "resultado"}]
assert {s["value"]["text"]: s["population"][0]["count"] for s in by_result["stratum"]} == {
"LIEBG": 1, "NEGATIVO": 2, "SIN_DATO": 1}
if os.environ.get("MEASURE_REPORT_OUT"):
Path(os.environ["MEASURE_REPORT_OUT"]).write_text(json.dumps(composition, indent=2), encoding="utf-8")
ORACLE = Path(__file__).parent / "fixtures" / "kit_oracle_cacu.json"
TIEMPO_REPORTE = "cacu/CACU_EU_TIEMPO_REPORTE"
DIAS_TOMA_DIAGNOSTICO = "cacu/CACU_DIAS_TOMA_DIAGNOSTICO"
@pytest.mark.parametrize("url", [TIEMPO_REPORTE, DIAS_TOMA_DIAGNOSTICO])
def test_each_duration_is_the_kit_s_in_every_period(base, manifest, url):
"""Pins down the duration construct, for the time to the result and the time to the first note that resolves
the sample: each sample of the period is measurable unless it has no value and its horizon hasn't passed by the
cut-off (and, to diagnosis, unless a cervical cancer note came before it); the measured ones carry their days
(`dim_fecha.dia_num` differences); n, the median and the quartiles (inclusive, ANSI) and the excluded are the
kit's where it didn't suppress them (suppression isn't part of the prototype). Fails if the horizon, the day
arithmetic, the resolving note, the exclusion or the quartiles' interpolation drift."""
from webapi.durations import answer_duration, duration_definitions
expected = json.loads(ORACLE.read_text(encoding="utf-8"))[url]
definition = duration_definitions(manifest)[url]
for period_id, kit_report in expected["periodos"].items():
result = answer_duration("cacu", definition, Question(url, period_id), **repositories(base))
assert units_with_numbers(base, result.report_id) == kit_report["units"], period_id
published = dict(zip(kit_report["published_columns"], next(
row for row in kit_report["published"] if row[1] == "total")))
if published["suprimido"]:
continue
assert (result.n, result.median, result.q1, result.q3, result.excluded) == (
published["n"], published["mediana"], published["q1"], published["q3"], published["n_excluido"]), period_id
def units_with_numbers(base, report_id: int) -> list[list]:
with base.motor.connect() as connection:
return sorted(map(list, connection.execute(text(
"select grupo, resultado_id, unidad_id, pac_id, valor_id, numero from measure_report_unidad "
"where report_id = :r"), {"r": report_id}).all()))
def test_the_follow_up_status_is_the_kit_s_in_every_period(base, eu13, eu7):
"""Pins down: EU13's and EU7's `estatus_seguimiento` gives each unit the kit's status at the period's start, and
the kit's published numbers by status. Fails if the timeline stratum, the procedures it infers or the order of
the values drift. The fixture's patients are all PRE_COLPOSCOPIA; the other statuses are pinned down by
`test_the_follow_up_status_follows_the_timeline`."""
oracle = json.loads(ORACLE.read_text(encoding="utf-8"))
for period_id in PERIODS:
for definition in (eu13, eu7):
result, expected = ask(base, definition, period_id), oracle[definition.url]["periodos"][period_id]
assert strata_rows(base, result.report_id, STATUS) == sorted(
[u, v] for u, s, v in expected["strata"] if s == STATUS), (definition.url, period_id)
rows = [dict(zip(expected["published_columns"], r)) for r in expected["published"]]
if definition is eu13:
published = {f"{STATUS}|{r['estrato_valor']}": [r["numerador"], r["denominador"]]
for r in rows if r["estrato_id"] == STATUS}
ours = {k: v for k, v in proportion_cells(result).items() if k.startswith(f"{STATUS}|")}
else:
published = {f"{STATUS}|{r['estrato_valor']}|{r['categoria']}": r["n"]
for r in rows if r["estrato_id"] == STATUS and r["n"]}
ours = {k: v for k, v in composition_cells(result).items() if k.startswith(f"{STATUS}|")}
assert ours == published, (definition.url, period_id)
def kit_status(base, reference: str) -> dict[str, str]:
"""What the kit's `estatus_al` says each patient's status was before `reference`, with the kit's rules."""
import tomllib
from webapi.follow_up.status import estatus_al, reglas_de
from webapi.orchestration.reference.rules import RUTA_PARAMETROS
from webapi.follow_up.listing import leer_estrato
from sqlalchemy import bindparam
rules = tomllib.loads(RUTA_PARAMETROS.read_text(encoding="utf-8"))
def rule(key):
node = rules
for part in key.split("."):
node = node[part]
return node["valor"]
values = {name: rule(key) for name, key in leer_estrato("cacu", STATUS).parametros.items()}
status = estatus_al(bindparam("referencia"), reglas_de(values))
query = select(status.c.pac_id, status.c.estatus)
named = set(query.compile().params)
with base.motor.connect() as connection:
rows = connection.execute(query, {n: v for n, v in {**values, "referencia": reference}.items() if n in named})
return {str(pac_id): value for pac_id, value in rows}
def follow_up(session) -> None:
"""Notes and orders that move three of the fixture's patients along follow-up, in a load of their own.
Patient 1 (sampled 2025-02-10): a valuation visit, a colposcopy note by its reason (with an accent) and a biopsy
order that day, then a treatment note: POST_TRATAMIENTO from then on. Patient 4 (sampled 2025-05-30): a
valuation visit, then a colposcopy note whose ICD-10 came «S/C» but whose diagnosis text names HPV:
POST_COLPOSCOPIA. Patient 3 (sampled 2025-01-20): a colposcopy note with no valuation before it, which doesn't
count, and her first cytology ordered by a specialty outside surveillance: no status holds, INFO_INSUFICIENTE.
"""
from core.cacu.indicadores.models import Carga, Observacion, Procedimiento
load = Carga(fuente="seguimiento", inicio=datetime.now(timezone.utc))
session.add(load)
session.flush()
def procedure(pac_id, study, kind, when, key, **observed) -> Procedimiento:
p = Procedimiento(fuente_tabla="seguimiento", fuente_id=key, carga_id=load.carga_id, pac_id=pac_id,
estudio_id=study, clase=kind, fecha=date.fromisoformat(when))
session.add(p)
session.flush()
for result, (column_name, value) in observed.items():
session.add(Observacion(procedimiento_id=p.procedimiento_id, carga_id=load.carga_id, pac_id=pac_id,
resultado_id=result.replace("__", "."), **{column_name: value}))
return p
def note(pac_id, when, key, *, cie, specialty="CLINICA_MUJER_COLPOSCOPIA", reason=None, text_dx=None):
observed = {"nota_medica__diagnostico": ("valor_texto", cie),
"nota_medica__especialidad": ("valor_id", specialty)}
if reason:
observed["nota_medica__motivo"] = ("valor_texto", reason)
if text_dx:
observed["nota_medica__diagnostico_texto"] = ("valor_texto", text_dx)
procedure(pac_id, "nota_medica", "encuentro", when, key, **observed)
note(1, "2025-02-20", "n1a", cie="R876")
note(1, "2025-03-03", "n1b", cie="Z000", reason="Acude a colposcopía")
procedure(1, "biopsia", "orden", "2025-03-03", "o1")
note(1, "2025-04-01", "n1c", cie="D06", specialty="CIRUGIA_ONCOLOGICA")
note(4, "2025-06-05", "n4a", cie="R876")
note(4, "2025-06-10", "n4b", cie="S/C", text_dx="Virus del papiloma humano")
note(3, "2025-01-25", "n3a", cie="Z000", reason="COLPOSCOPIA")
order = procedure(3, "citologia", "orden", "2025-01-19", "c3",
orden__especialidad=("valor_id", "CIRUGIA_ONCOLOGICA"))
(sample,) = session.exec(select(Procedimiento).where(
Procedimiento.pac_id == 3, Procedimiento.estudio_id == "citologia", Procedimiento.clase == "toma",
Procedimiento.fecha == date(2025, 1, 20))).all()
sample.padre_id = order.procedimiento_id
def test_the_follow_up_status_follows_the_timeline(base, eu13, eu7):
"""Pins down: with colposcopies and a treatment on the timeline, every unit of EU13 and EU7 in every period gets
the status the kit's `estatus_al` gives her at the period's start, and all four statuses come out; asked with a
knowledge cut-off before those facts arrived, they're PRE_COLPOSCOPIA again. Fails if an inferred procedure
(the valuation requirement, the same-day order, the accent-blind reason, the diagnosis text), the timeline
stratum or the values' order stops meaning what the kit's rules mean."""
with base.motor.connect() as connection:
before_load = connection.execute(text("select max(inicio) from carga")).scalar_one()
with Session(base.motor) as session:
follow_up(session)
session.commit()
seen = set()
for period_id in PERIODS:
start = base.dominio.dim_periodo_repository.get(period_id).inicio.isoformat()
expected = kit_status(base, start)
for definition in (eu13, eu7):
ours = dict(strata_rows(base, ask(base, definition, period_id).report_id, STATUS))
assert ours == {unit: expected[unit] for unit in ours}, (definition.url, period_id)
seen |= set(ours.values())
assert seen == {"PRE_COLPOSCOPIA", "POST_COLPOSCOPIA", "POST_TRATAMIENTO", "INFO_INSUFICIENTE"}
known_then = datetime.fromisoformat(before_load)
earlier = ask(base, eu13, "2025-10", knowledge_cutoff=known_then)
assert set(dict(strata_rows(base, earlier.report_id, STATUS)).values()) == {"PRE_COLPOSCOPIA"}
def test_a_sample_waiting_for_its_diagnosis_within_the_horizon_is_not_measured_yet(base, manifest):
"""Pins down the cut-off of the time to diagnosis: in 2025-S2 cut at September 30, the July sample resolved in
August is measured (40 days); the August sample, resolved only in January, and the September one, with no note,
are still within 180 days, so they aren't measured yet; the October sample is after the cut. Fails if a note
after the cut-off counts, or a pending sample enters the initial population."""
from webapi.durations import answer_duration, duration_definitions
definition = duration_definitions(manifest)[DIAS_TOMA_DIAGNOSTICO]
result = answer_duration("cacu", definition, Question(DIAS_TOMA_DIAGNOSTICO, "2025-S2", date(2025, 9, 30)),
**repositories(base))
assert (result.initial, result.n, result.median, result.excluded) == (1, 1, 40.0, 0)
CONFIRMACION = "cacu/CACU_CONFIRMACION_CITOLOGIA"
def test_the_confirmation_by_biopsy_is_the_kit_s_in_every_period(base, manifest):
"""Pins down the composition that follows the chosen fact: each patient whose last valid sample of the period is
high grade, in the grade of the most severe biopsy that sample led to by the cut-off (SIN_BIOPSIA without one),
by that sample's result; units, strata and counts are the kit's in every period. Fails if the two-level ranking,
the admission on the chosen sample, the severity order or the chosen-row stratum drift."""
oracle = json.loads(ORACLE.read_text(encoding="utf-8"))[CONFIRMACION]
definition = composition_definitions(manifest)[CONFIRMACION]
for period_id, expected in oracle["periodos"].items():
result = answer_composition("cacu", definition, Question(CONFIRMACION, period_id), **repositories(base))
assert units(base, result.report_id) == [u[:5] for u in expected["units"]], period_id
assert strata_rows(base, result.report_id, "citologia_alto_grado") == sorted(
[u, v] for u, s, v in expected["strata"] if s == "citologia_alto_grado"), period_id
rows = [dict(zip(expected["published_columns"], r)) for r in expected["published"]]
published = {f"{r['estrato_id']}|{r['estrato_valor']}|{r['categoria']}": r["n"] for r in rows if r["n"]}
assert {k: v for k, v in composition_cells(result).items() if v} == published, period_id
+75 -58
View File
@@ -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
+23 -65
View File
@@ -1,23 +1,21 @@
"""El ciclo deja los mismos reportes que la base de demostración del kit.
"""What this module covers: the whole cycle on the CaCu fixture database, in order, once and again.
Dos bases con el mismo staging (los fixtures del kit):
- una armada por la orquestación: Alembic, carga, vistas, registro y cálculo;
- otra por `indicadores_kit.demostracion.base_de_prueba`, que es la que usa la compuerta.
Los reportes tienen que coincidir valor por valor. Volver a correr el ciclo no
agrega reportes.
Fixtures: `bases`, one database loaded by the cycle from the kit's synthetic staging, with dbt's manifest
(`DBT_MANIFEST`) for the definitions and the event models. The cycle computes no measure: they're answered on request
(`test_metrics_on_request`), so running it again adds no report.
"""
import os
from datetime import date
from pathlib import Path
from importlib import import_module
import pytest
from sqlalchemy import create_engine, text
from sqlmodel import Session
from indicadores_kit.demostracion import base_de_prueba
from webapi.orquestacion import Contexto, correr
from webapi.orquestacion.conexion import apuntar
from webapi.orchestration import Context, run
from webapi.orchestration.connection import point_to
ANIO = 2025
# Lo que guarda cada reporte (T-19e): sus unidades de §6f. El número publicado sale de ellas (las vistas).
@@ -27,9 +25,6 @@ CONSULTA = text("""
FROM measure_report_unidad u JOIN measure_report r USING (report_id)""")
def valores(motor) -> list[tuple]:
with motor.connect() as con:
return sorted(tuple(str(x) for x in fila) for fila in con.execute(CONSULTA))
@pytest.fixture(scope="module", params=["cacu", "cama", "tea"])
@@ -37,41 +32,35 @@ def bases(request, tmp_path_factory):
proyecto = request.param
carpeta = tmp_path_factory.mktemp(proyecto)
url = f"sqlite:///{carpeta / 'orquestada.db'}"
apuntar(proyecto, url)
# `observar` lee una regla sin definir en los dos proyectos (I-MD1): se pide a propósito, como `montar` de
point_to(proyecto, url)
# `observe` lee una regla sin definir en los dos proyectos (I-MD1): se pide a propósito, como `montar` de
# dev-data. Ningún cálculo la usa: la base de demostración calcula sin permitirlo y da lo mismo.
ctx = Contexto(proyecto, ANIO, ANIO, permitir_sin_definir=True)
correr(ctx, solo=["migrar"])
ctx = Context(proyecto, ANIO, ANIO, allow_undecided=True, dbt_manifest=Path(os.environ["DBT_MANIFEST"]))
run(ctx, only=["migrate"])
motor = create_engine(url)
with Session(motor) as sesion:
import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion)
import_module(f"staging.{proyecto}").insertar(sesion)
sesion.commit()
pasos = correr(ctx)
demostracion = create_engine(f"sqlite:///{carpeta / 'demostracion.db'}")
base_de_prueba(demostracion, proyecto)
return proyecto, ctx, motor, demostracion, pasos
pasos = run(ctx)
return proyecto, ctx, motor, None, pasos
def test_corre_todos_los_pasos_en_orden(bases):
proyecto, _, _, _, pasos = bases
nombres = [p.nombre for p in pasos]
# `migrar` otra vez: con la base al día no hace nada. Los catálogos, antes de cargar (decisión 6 de §9).
assert nombres[0] == "migrar" and nombres.index("catalogos") < nombres.index("cargar")
assert nombres.index("calcular") < nombres.index("observar")
nombres = [p.name for p in pasos]
# `migrate` otra vez: con la base al día no hace nada. Los catálogos, antes de cargar (decisión 6 de §9).
assert nombres[0] == "migrate" and nombres.index("catalogs") < nombres.index("load")
assert nombres.index("load") < nombres.index("event_models") and "calcular" not in nombres
def test_los_reportes_son_los_de_la_base_de_demostracion(bases):
_, _, motor, demostracion, _ = bases
orquestados, esperados = valores(motor), valores(demostracion)
assert orquestados, "el ciclo no calculó nada"
assert orquestados == esperados
def test_volver_a_correr_no_agrega_reportes(bases):
"""Pins down: the cycle computes no measure (they're answered on request): running it adds no report."""
_, ctx, motor, _, _ = bases
with motor.connect() as con:
antes = con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one()
correr(ctx)
run(ctx)
with motor.connect() as con:
assert con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() == antes
@@ -79,46 +68,15 @@ def test_volver_a_correr_no_agrega_reportes(bases):
def test_en_cacu_arma_su_cohorte_una_vez(bases):
proyecto, ctx, motor, _, pasos = bases
if proyecto != "cacu":
assert "cohortes" not in [p.nombre for p in pasos] # T-21h: TEA y CaMa, solo propuestas
assert "cohorts" not in [p.name for p in pasos] # T-21h: TEA y CaMa, solo propuestas
return
(armado_id, nuevo), = [p.resumen for p in pasos if p.nombre == "cohortes"][0].values()
(armado_id, nuevo), = [p.summary for p in pasos if p.name == "cohorts"][0].values()
with motor.connect() as con:
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == 1
assert con.execute(text("SELECT n_miembros FROM cohorte_armado")).scalar_one() == con.execute(
text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one()
def test_cada_reporte_guarda_sus_unidades(bases):
"""Todo reporte lleva la huella de sus unidades de §6f (T-19b, T-19e): sin ella, las vistas lo darían en 0."""
_, _, motor, _, _ = bases
with motor.connect() as con:
sin = con.execute(text("SELECT COUNT(*) FROM measure_report WHERE huella IS NULL")).scalar_one()
con_unidades = con.execute(text("SELECT COUNT(DISTINCT report_id) FROM measure_report_unidad")).scalar_one()
assert sin == 0 and con_unidades > 0
def test_cada_reporte_se_mide_y_se_guarda_en_una_sola_sesion(bases):
"""La regla de §6 en `calcular`: antes eran dos sesiones (medir y guardar)."""
from functools import partial
from indicadores_kit.oro.calculo import medir_con_unidades
from indicadores_kit.registry.measures import measures_de
from indicadores_kit.tablas import tablas_de
from persistance.aristas.oro import CalculoRepository
proyecto, _, motor, _, _ = bases
tablas = tablas_de(proyecto)
abiertas = []
def fabrica():
abiertas.append(1)
return Session(motor)
calculo = CalculoRepository(fabrica, tablas.MeasureReport, periodo=tablas.DimPeriodo)
medida = next(iter(measures_de(proyecto).values()))
tipo = medida.extension.publicacion.tipos_periodo[0]
periodo_id = calculo.periodos(tipo, date(ANIO, 1, 1), date(ANIO + 1, 1, 1))[0]
abiertas.clear()
calculo.calcular(partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas))
assert len(abiertas) == 1
+24 -118
View File
@@ -1,4 +1,4 @@
"""Los pasos de oro sobre la base del dominio: el registro, las definiciones y el cálculo.
"""Los pasos de oro sobre la base del dominio: el registro y las definiciones (el catálogo, del manifiesto de dbt).
Vienen del kit (`test_pasos` y `test_produccion`, MD-16). El reporte se lee por los
repositorios de Persistance, como lo leería `WebApi`.
@@ -7,107 +7,50 @@ repositorios de Persistance, como lo leería `WebApi`.
from datetime import date
import pytest
from sqlalchemy import text
from sqlmodel import select
from indicadores_kit.cacu import fixtures as fixtures_cacu
from indicadores_kit.cama import fixtures as fixtures_cama
from indicadores_kit.plata.carga import tablas_de_staging
from indicadores_kit.registry.measures import leer_measure, measures_de, ruta_de_measure
from indicadores_kit.registry.edades import grupos_de_cortes
from indicadores_kit.registry.parametros import RUTA_PARAMETROS, valores_del_archivo
from indicadores_kit.registry.periodos import periodos_de_tipos
from indicadores_kit.serving.contratos import ultimo_reporte
from indicadores_kit.tablas import tablas_de
from indicadores_kit.tea import fixtures as fixtures_tea
from webapi.orquestacion.proyecto import tipos_de_periodo
from webapi.orchestration.silver.loads import tablas_de_staging
from webapi.orchestration.reference.age_groups import grupos_de_cortes
from webapi.orchestration.reference.rules import RUTA_PARAMETROS, valores_del_archivo
from webapi.orchestration.reference.periods import periodos_de_tipos
from webapi.orchestration.tables import tablas_de
from webapi.orchestration.project import period_types
from conftest import ANIO
# El indicador de ejemplo, su grupo total y lo que da: {periodo: (denominador, numerador)}.
EJEMPLO = {"cacu": "ind1", "cama": "cama_confirmacion_birads45", "tea": "M24_confirmacion_diagnostico"}
TOTAL = {"cacu": "principal", "cama": "principal", "tea": "TOTAL"}
ESPERADO = {
"cacu": fixtures_cacu.ESPERADO_IND1,
"cama": fixtures_cama.ESPERADO_CAMA_CONFIRMACION_BIRADS45,
"tea": {p: v["TOTAL"][:2] for p, v in fixtures_tea.ESPERADO["M24_confirmacion_diagnostico"].items()},
}
# Un dato de staging que cambia el numerador del ejemplo: (tabla de STAGING, columna con que se busca, su valor,
# columna que cambia, valor nuevo). CaCu: la citología NEGATIVO de H-001 pasa a LIEAG (anómala). CaMa: la
# mastografía B0 del 10 de marzo, que ya tiene biopsia, pasa a B4A (de sospecha). TEA: la nota R62.0 de T-03 pasa
# a F84.0 (confirma el diagnóstico).
CAMBIO = {
"cacu": ("citologiacervical", "cit_fecha_toma", date(2025, 2, 10), "cit_celulas_escamosas", "LIEAG"),
"cama": ("mastografia", "mast_fecha_toma", date(2025, 3, 10), "mast_birads", "B4A"),
"tea": ("nota_medica", "nm_id", "nm-03", "nm_cie_codigo", "F84.0"),
}
def cargas(proyecto) -> tuple[str, ...]:
"""El paso que lleva el staging a la plata (staging directo, T-20c)."""
return ("cargar",)
return ("load",)
def hasta_calcular(proyecto) -> tuple[str, ...]:
return ("catalogos", *cargas(proyecto), "vistas", "registro", "definiciones", "calcular")
def cambiar_staging(base) -> None:
tabla, llave, valor_llave, columna, nuevo = CAMBIO[base.proyecto]
modelo = {m.__tablename__: m for m in tablas_de_staging(base.proyecto)}[tabla]
with base.staging() as sesion:
(fila,) = sesion.exec(select(modelo).where(getattr(modelo, llave) == valor_llave)).all()
setattr(fila, columna, nuevo)
sesion.commit()
def ejemplo(proyecto):
return leer_measure(ruta_de_measure(proyecto, EJEMPLO[proyecto]))
def conteos(base, report_id: int) -> tuple[int, int]:
"""(denominador sin exclusiones, numerador) del grupo total, de lo que publica `v_c1` (T-19e)."""
with base.motor.connect() as con:
return tuple(con.execute(text(
"SELECT denominador, numerador FROM v_c1 WHERE report_id = :r AND grupo = :g AND estrato_id = 'total'"),
{"r": report_id, "g": TOTAL[base.proyecto]}).one())
def reportes_del_ejemplo(base, periodo_id="2025-S1", nombre=None) -> list:
measure = leer_measure(ruta_de_measure(base.proyecto, nombre)) if nombre else ejemplo(base.proyecto)
return [r for r in base.dominio.measure_report_repository.list(limit=10_000)
if r.measure_url == measure.url and r.periodo_id == periodo_id]
def ultimo(base, periodo_id="2025-S1") -> int:
with base.staging() as sesion:
return ultimo_reporte(sesion, ejemplo(base.proyecto), periodo_id, tablas=tablas_de(base.proyecto))
def test_de_staging_al_reporte_leido_por_repository(base, sin_supresion):
reportes = base.correr(*hasta_calcular(base.proyecto), parametros=sin_supresion, permitir_sin_definir=True)["calcular"]
assert set(reportes) == set(measures_de(base.proyecto))
for periodo, esperado in ESPERADO[base.proyecto].items():
(reporte,) = reportes_del_ejemplo(base, periodo)
assert reporte.report_id in reportes[EJEMPLO[base.proyecto]]
assert conteos(base, reporte.report_id) == esperado
def test_el_registro_se_puede_repetir_y_agrega_los_periodos_que_faltan(base):
base.correr("registro")
base.correr("registro", anio_inicio=ANIO - 1)
base.run("registry")
base.run("registry", year_from=ANIO - 1)
tablas = tablas_de(base.proyecto)
esperados = periodos_de_tipos(tipos_de_periodo(base.proyecto), ANIO - 1, ANIO, tablas=tablas)
esperados = periodos_de_tipos(period_types(base.proyecto, base.ctx.dbt_manifest), ANIO - 1, ANIO, tablas=tablas)
assert base.dominio.dim_periodo_repository.count() == len(esperados)
assert base.dominio.measure_report_repository.count() == 0
def test_el_registro_llena_dim_fecha_y_dim_grupo_edad_desde_los_toml(base):
"""I-MD27 (T-24f): de `comun.dim_fecha.desde` al fin del último año, y los grupos de `<proyecto>.grupos_edad`."""
base.correr("registro")
base.correr("registro", anio_fin=ANIO + 1) # repetir deja la tabla igual, con el año nuevo
base.run("registry")
base.run("registry", year_to=ANIO + 1) # repetir deja la tabla igual, con el año nuevo
valores = valores_del_archivo(RUTA_PARAMETROS)
desde = date.fromisoformat(valores["comun.dim_fecha.desde"])
@@ -120,73 +63,36 @@ def test_el_registro_llena_dim_fecha_y_dim_grupo_edad_desde_los_toml(base):
assert sorted(grupos) == sorted(esperados) # TEA no tiene cortes: vacía
def test_con_reportes_guardados_se_cambia_un_parametro_y_se_agrega_un_anio(base, sin_supresion):
"""Antes (I-K54) esto fallaba: reemplazar dim_periodo violaba la llave de measure_report."""
base.correr(*hasta_calcular(base.proyecto), permitir_sin_definir=True)
reportes = base.dominio.measure_report_repository.count()
base.correr("registro", anio_fin=ANIO + 1, parametros=sin_supresion)
assert base.dominio.def_parametro_repository.get("comun.umbral_supresion").valor == "1"
tablas = tablas_de(base.proyecto)
esperados = periodos_de_tipos(tipos_de_periodo(base.proyecto), ANIO, ANIO + 1, tablas=tablas)
assert base.dominio.dim_periodo_repository.count() == len(esperados)
assert base.dominio.measure_report_repository.count() == reportes
def test_un_archivo_de_parametros_invalido_no_toca_el_registro(base, tmp_path):
base.correr("registro")
base.run("registry")
periodos = base.dominio.dim_periodo_repository.count()
malo = tmp_path / "malo.toml"
malo.write_text('[comun.x]\nvalor = 1\nestado = "provisional"\n', encoding="utf-8")
with pytest.raises(ValueError, match="fuente"):
base.correr("registro", anio_inicio=ANIO - 1, anio_fin=ANIO + 1, parametros=malo)
base.run("registry", year_from=ANIO - 1, year_to=ANIO + 1, parameters=malo)
assert base.dominio.def_parametro_repository.get("comun.x") is None
assert base.dominio.def_parametro_repository.get("comun.umbral_supresion") is not None
assert base.dominio.dim_periodo_repository.count() == periodos
def test_las_definiciones_son_las_de_los_toml(base):
resumen = base.correr("definiciones")["definiciones"]
def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
"""Pins down: `definitions` seeds the publication catalog from dbt's manifest, once. Fails if a stratum or a
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
resumen = base.run("definitions")["definitions"]
assert resumen["definiciones"] == len(measures_de(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() == len(measures_de(base.proyecto))
assert base.correr("definiciones")["definiciones"]["borradas"] == 0
assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 8, "tea": 10}[base.proyecto]
assert base.run("definitions")["definitions"]["borradas"] == 0
def test_recalcular_tras_una_carga_sin_cambios_no_agrega_reportes(base):
"""T-2 de v0.4.0 (D-5): lo idéntico no se guarda otra vez."""
base.correr(*hasta_calcular(base.proyecto), permitir_sin_definir=True)
antes = base.dominio.measure_report_repository.count()
base.correr(*cargas(base.proyecto), "calcular", permitir_sin_definir=True)
assert base.dominio.measure_report_repository.count() == antes
(reporte,) = reportes_del_ejemplo(base)
assert ultimo(base) == reporte.report_id and reporte.parametros_sha is not None
def test_con_un_dato_nuevo_recalcular_agrega_un_reporte_y_se_lee_el_ultimo(base, sin_supresion):
base.correr(*hasta_calcular(base.proyecto), parametros=sin_supresion, permitir_sin_definir=True)
(primero,) = reportes_del_ejemplo(base)
cambiar_staging(base)
base.correr(*cargas(base.proyecto), "calcular", parametros=sin_supresion, permitir_sin_definir=True)
reportes = sorted(reportes_del_ejemplo(base), key=lambda r: r.report_id)
assert [r.report_id for r in reportes][0] == primero.report_id and len(reportes) == 2
assert ultimo(base) == reportes[1].report_id
assert conteos(base, reportes[0].report_id)[1] != conteos(base, reportes[1].report_id)[1]
def test_el_corte_no_distingue_los_reportes_de_un_indicador_que_no_lo_usa(base):
"""MV-3: `measure_report.fecha_corte` existe tras migrar; un indicador que no la usa la deja nula."""
base.correr(*hasta_calcular(base.proyecto), corte=date(2025, 3, 31), permitir_sin_definir=True)
base.correr("calcular", corte=date(2025, 12, 31), permitir_sin_definir=True)
# El ejemplo de CaMa usa el corte (`:fecha_corte`); ahí se mira otro que no lo usa.
(reporte,) = reportes_del_ejemplo(base, nombre={"cama": "cama_biopsias"}.get(base.proyecto))
assert reporte.fecha_corte is None
+13 -13
View File
@@ -3,38 +3,38 @@
import pytest
from hamilton import driver
from webapi.orquestacion import ciclo, pasos_de
from webapi.orchestration import cycle, steps_of
def dependencias(proyecto: str) -> dict[str, set[str]]:
dr = driver.Builder().with_modules(ciclo).with_config({"con_cohortes": proyecto == "cacu"}).build()
dr = driver.Builder().with_modules(cycle).with_config({"with_cohorts": proyecto == "cacu"}).build()
return {n.name: {d.name for d in n.dependencies} - {"ctx"} for n in dr.graph.get_nodes() if n.name != "ctx"}
def antes(deps: dict[str, set[str]], paso: str) -> set[str]:
"""Todos los pasos que corren antes de `paso`."""
previos = set()
pendientes = list(deps[paso])
while pendientes:
anterior = pendientes.pop()
pending = list(deps[paso])
while pending:
anterior = pending.pop()
if anterior not in previos:
previos.add(anterior)
pendientes.extend(deps[anterior])
pending.extend(deps[anterior])
return previos
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto):
deps = dependencias(proyecto)
assert deps["migrar"] == set()
assert {"migrar", "catalogos"} <= antes(deps, "cargar") # decisión 6 de §9
assert {"cargar", "vistas", "registro", "definiciones"} <= antes(deps, "calcular")
assert {"registro", "calcular"} <= antes(deps, "observar")
assert {"cargar", "calcular"} <= antes(deps, "verificar_plata")
assert deps["migrate"] == set()
assert {"migrate", "catalogs"} <= antes(deps, "load") # decisión 6 de §9
assert {"load"} <= antes(deps, "event_models")
assert {"registry"} <= antes(deps, "observe")
assert {"load", "catalogs"} <= antes(deps, "check_silver")
def test_solo_cacu_arma_cohortes_y_estima_por_ahora():
"""T-21h: las cohortes de TEA y CaMa son propuestas (`cohortes/propuestas/`); queda su infraestructura."""
assert {"cohortes", "estimar"} <= set(pasos_de("cacu"))
assert {"cohorts", "estimate"} <= set(steps_of("cacu"))
for proyecto in ("cama", "tea"):
assert not {"cohortes", "estimar"} & set(pasos_de(proyecto))
assert not {"cohorts", "estimate"} & set(steps_of(proyecto))
+42 -57
View File
@@ -10,16 +10,15 @@ from datetime import date
import pytest
from conftest import base_de
from indicadores_kit.plata.carga import tablas_de_staging
from indicadores_kit.plata.periodo_observacion import (
from webapi.orchestration.silver.loads import tablas_de_staging
from webapi.orchestration.silver.observation_periods import (
TIPO_EXTRACCION,
ObservacionSinCorte,
clave_de_inicio,
)
from indicadores_kit.registry.catalogos import catalogo_desde_toml, ruta_de_catalogo
from indicadores_kit.registry.parametros import RUTA_PARAMETROS, ParametroSinDefinir
from indicadores_kit.tablas import tablas_de
from indicadores_kit.tea import fixtures as fixtures_tea
from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo
from webapi.orchestration.reference.rules import RUTA_PARAMETROS, ParametroSinDefinir
from webapi.orchestration.tables import tablas_de
from sqlalchemy import inspect, text
from sqlmodel import select
@@ -27,13 +26,13 @@ from sqlmodel import select
CAMBIO = {
"cacu": ("citologiacervical", "cit_calidad_especimen", "INSATISFACTORIO"),
"cama": ("mastografia", "mast_calidad_imagen", "OTRA CALIDAD"),
"tea": ("evaluacion_psicologica", "psi_fecha_ados2", date(2024, 12, 1)),
"tea": ("mchat", "mch_puntaje", 19),
}
CORTE = date(2025, 12, 31)
def ultima_carga(base):
return max(base.ctx.repos.plata.carga.list(limit=100), key=lambda c: c.carga_id)
return max(base.ctx.repos.silver.loads.list(limit=100), key=lambda c: c.carga_id)
def contar(base, sql: str) -> int:
@@ -62,7 +61,7 @@ def cambiar_staging(base) -> str:
def filas_del_catalogo(base) -> dict[str, int]:
"""Cuántas filas tiene cada tabla de catálogo en la base."""
plata = base.ctx.repos.plata.catalogos
plata = base.ctx.repos.silver.catalogs
with base.staging() as sesion:
return {
"estudios": len(sesion.exec(select(plata.model)).all()),
@@ -76,15 +75,18 @@ 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.correr("catalogos")["catalogos"] == {**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
def test_volver_a_correr_catalogos_no_cambia_nada(base):
base.correr("catalogos")
base.run("catalogs")
antes = filas_del_catalogo(base)
assert base.correr("catalogos")["catalogos"]["retirados"] == 0
conteos = base.run("catalogs")["catalogs"]
assert (conteos["retirados"], conteos["mapeos_nuevos"]) == (0, 0)
assert filas_del_catalogo(base) == antes
@@ -92,14 +94,14 @@ def test_volver_a_correr_catalogos_no_cambia_nada(base):
def test_cargar_lleva_el_staging_a_persona_y_la_plata(base):
base.correr("catalogos")
carga = base.correr("cargar")["cargar"]
base.run("catalogs")
carga = base.run("load")["load"]
procedimientos, observaciones = plata_de(base)
assert procedimientos and observaciones
assert carga.fin is not None and (carga.filas_nuevas, carga.filas_cambiadas, carga.filas_sin_cambio) == (
procedimientos, 0, 0)
assert contar(base, "SELECT COUNT(*) FROM persona") == len(base.ctx.repos.bronce.staging.leer(
assert contar(base, "SELECT COUNT(*) FROM persona") == len(base.ctx.repos.bronze.staging.read(
{"p": tablas_de_staging(base.proyecto)[0]})["p"])
# Ningún reporte ni parte sin su toma (salvo los huérfanos, que no se escriben).
assert contar(base, "SELECT COUNT(*) FROM procedimiento WHERE clase IN ('reporte', 'parte') AND padre_id IS NULL") == 0
@@ -107,20 +109,13 @@ def test_cargar_lleva_el_staging_a_persona_y_la_plata(base):
assert contar(base, "SELECT COUNT(*) FROM sqlite_master WHERE name = 'orden_estudio_servicio'") == 0
@pytest.mark.parametrize("proyecto", ["tea"])
def test_los_descartes_y_los_huerfanos_quedan_en_la_carga(base):
base.correr("catalogos", "cargar")
descartes = json.loads(ultima_carga(base).descartes)
assert {m: n for m, n in descartes.items() if m.startswith("eeg")} == fixtures_tea.DESCARTES
assert descartes["huerfanos"] > 0 # los segmentos de los EEG que no entraron (I-MD17)
def test_volver_a_cargar_sin_cambios_no_toca_nada(base):
base.correr("catalogos", "cargar")
base.run("catalogs", "load")
antes = plata_de(base)
segunda = base.correr("cargar")["cargar"]
segunda = base.run("load")["load"]
assert (segunda.filas_nuevas, segunda.filas_cambiadas, segunda.filas_sin_cambio) == (0, 0, antes[0])
assert plata_de(base) == antes
for tabla in ("procedimiento", "observacion_clinica"):
@@ -128,36 +123,26 @@ def test_volver_a_cargar_sin_cambios_no_toca_nada(base):
def test_un_cambio_en_staging_toca_un_procedimiento(base):
base.correr("catalogos", "cargar")
base.run("catalogs", "load")
antes = plata_de(base)
cambiar_staging(base)
segunda = base.correr("cargar")["cargar"]
segunda = base.run("load")["load"]
assert (segunda.filas_nuevas, segunda.filas_cambiadas, segunda.filas_sin_cambio) == (0, 1, antes[0] - 1)
assert plata_de(base) == antes
def test_cada_proyecto_carga_con_su_base_en_el_mismo_proceso(tmp_path):
fuentes = {}
for proyecto in ("cacu", "cama", "tea"):
base = base_de(proyecto, tmp_path)
base.correr("catalogos", "cargar")
fuentes[proyecto] = ultima_carga(base).fuente
base.motor.dispose()
assert fuentes["cacu"].startswith("citologiacervical") and fuentes["cama"].startswith("mastografia")
assert "eeg_estudio" in fuentes["tea"]
# --- vistas ---
def test_las_vistas_se_construyen_y_se_pueden_repetir(base):
primera = base.correr("vistas")["vistas"]
primera = base.run("views")["views"]
assert base.correr("vistas")["vistas"] == primera
# Desde F6 (ADR-MD-009) no hay vistas por tipo: `v_persona` y, desde MD-19, las del número publicado.
assert sorted(inspect(base.motor).get_view_names()) == ["v_c1", "v_c2", "v_c3r", "v_measure_report_vigente", "v_persona"]
assert base.run("views")["views"] == primera
# Only `v_persona`: the published numbers are answered on request, so the publication views aren't built.
assert sorted(inspect(base.motor).get_view_names()) == ["v_persona"]
# --- observar ---
@@ -185,9 +170,9 @@ observables = pytest.mark.parametrize("proyecto", ["cacu", "cama"])
@observables
def test_observar_deja_un_periodo_de_extraccion_por_paciente(base, con_regla):
base.correr("cargar", "registro", parametros=con_regla("2024-06-01"))
base.run("load", "registry", parameters=con_regla("2024-06-01"))
cuantos = base.correr("observar", corte=CORTE)["observar"]
cuantos = base.run("observe", cutoff=CORTE)["observe"]
periodos = base.dominio.periodo_observacion_repository.list()
assert cuantos == len(periodos) == base.dominio.persona_repository.count()
@@ -197,9 +182,9 @@ def test_observar_deja_un_periodo_de_extraccion_por_paciente(base, con_regla):
@observables
def test_sin_corte_la_observacion_termina_el_dia_de_la_ultima_carga(base, con_regla):
base.correr("cargar", "registro", parametros=con_regla())
base.run("load", "registry", parameters=con_regla())
base.correr("observar")
base.run("observe")
carga = ultima_carga(base)
assert {p.fecha_fin for p in base.dominio.periodo_observacion_repository.list()} == {
@@ -208,10 +193,10 @@ def test_sin_corte_la_observacion_termina_el_dia_de_la_ultima_carga(base, con_re
@observables
def test_observar_se_puede_repetir_sin_duplicar(base, con_regla):
base.correr("cargar", "registro", parametros=con_regla())
base.run("load", "registry", parameters=con_regla())
primera = base.correr("observar", corte=date(2025, 6, 30))["observar"]
segunda = base.correr("observar", corte=CORTE)["observar"]
primera = base.run("observe", cutoff=date(2025, 6, 30))["observe"]
segunda = base.run("observe", cutoff=CORTE)["observe"]
assert primera == segunda == base.dominio.periodo_observacion_repository.count()
assert {p.fecha_fin for p in base.dominio.periodo_observacion_repository.list()} == {CORTE}
@@ -219,37 +204,37 @@ def test_observar_se_puede_repetir_sin_duplicar(base, con_regla):
@observables
def test_la_regla_de_inicio_sin_definir_hay_que_pedirla_a_proposito(base):
base.correr("cargar", "registro")
base.run("load", "registry")
with pytest.raises(ParametroSinDefinir, match="inicio_datos"):
base.correr("observar", corte=CORTE)
assert base.correr("observar", corte=CORTE, permitir_sin_definir=True)["observar"] == (
base.run("observe", cutoff=CORTE)
assert base.run("observe", cutoff=CORTE, allow_undecided=True)["observe"] == (
base.dominio.persona_repository.count())
@observables
def test_sin_el_registro_observar_dice_que_falta(base):
base.correr("cargar")
base.run("load")
with pytest.raises(KeyError, match="preparar_registro|registro"):
base.correr("observar", corte=CORTE)
base.run("observe", cutoff=CORTE)
@observables
def test_un_corte_anterior_al_inicio_de_los_datos_se_rechaza(base, con_regla):
base.correr("cargar", "registro", parametros=con_regla("2024-06-01"))
base.run("load", "registry", parameters=con_regla("2024-06-01"))
with pytest.raises(ValueError, match="anterior al inicio"):
base.correr("observar", corte=date(2024, 5, 31))
base.run("observe", cutoff=date(2024, 5, 31))
assert base.dominio.periodo_observacion_repository.count() == 0
@observables
def test_sin_corte_y_sin_cargas_no_hay_de_donde_tomarlo(base, con_regla):
base.correr("registro", parametros=con_regla())
base.run("registry", parameters=con_regla())
with pytest.raises(ObservacionSinCorte):
base.correr("observar")
base.run("observe")
# --- La carga doble (F5, ADR-MD-007): CaCu, CaMa y TEA ---
@@ -258,7 +243,7 @@ def test_sin_corte_y_sin_cargas_no_hay_de_donde_tomarlo(base, con_regla):
@pytest.mark.parametrize("proyecto", ["cacu"])
def test_verificar_plata_en_cacu_cuenta_los_valores_fuera_de_catalogo_del_fixture(base):
conteos = base.correr("catalogos", "cargar", "verificar_plata")["verificar_plata"]
conteos = base.run("catalogs", "load", "check_silver")["check_silver"]
# I-MD16 (textos del fixture fuera del catálogo) e I-MD18 (especialidades que el alias no reconoce): en la
# plata, una observación de código sin `valor_id` y con su `valor_fuente`.
@@ -1,7 +1,7 @@
"""La regla de §6: ningún paso abre una sesión; todo va por `ctx.repos`.
Las subclases viven en `persistance/aristas/` y Persistance las instancia con su
fábrica de sesión (ADR-MD-005). Solo `conexion.py` nombra a `persistance.db`: cambia a
Las subclases viven en `persistance/edges/` y Persistance las instancia con su
fábrica de sesión (ADR-MD-005). Solo `connection.py` nombra a `persistance.db`: cambia a
qué base apunta Persistance (`<PROYECTO>_DATABASE_URL` en memoria); no es un paso.
"""
@@ -10,10 +10,10 @@ from pathlib import Path
import pytest
from webapi.orquestacion.repositorios import repositorios_de
from webapi.orchestration.repositories import repositories_of
PAQUETE = Path(__file__).parents[1] / "webapi" / "orquestacion"
EXENTOS = {"conexion.py"}
PAQUETE = Path(__file__).parents[1] / "webapi" / "orchestration"
EXENTOS = {"connection.py"}
PROHIBIDO = re.compile(r"fabrica_por_defecto|get_(cacu|cama|tea)_session|get_\{|Session\(|persistance\.db")
@@ -25,6 +25,6 @@ def test_ningun_modulo_fuera_de_repositorios_abre_sesiones(modulo):
@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True), ("tea", True)])
def test_cada_proyecto_tiene_sus_repositorios(proyecto, con_cohortes):
repos = repositorios_de(proyecto)
assert (repos.oro.cohorte is not None) == con_cohortes
assert repos.oro.calculo.model.__tablename__ == "measure_report"
repos = repositories_of(proyecto)
assert (repos.gold.cohorts is not None) == con_cohortes
assert repos.gold.calculation.model.__tablename__ == "measure_report"
+10 -28
View File
@@ -1,4 +1,4 @@
"""El paso `estimar` y la orden `confirmar-riesgos` (ADR-MD-008), con un estimador de prueba.
"""El paso `estimate` y la orden `confirm-risks` (ADR-MD-008), con un estimador de prueba.
El estimador se inyecta en el contexto; aquí se usa uno que cumple el contrato `EstimadorDeRiesgo` sin MLflow.
"""
@@ -8,7 +8,7 @@ from dataclasses import dataclass
import pytest
from sqlalchemy import text
from webapi.orquestacion.__main__ import confirmar_riesgos, main
from webapi.orchestration.__main__ import confirm_risks, main
URL = "cacu/cohorte_vigilancia"
@@ -43,7 +43,7 @@ class EstimadorFijo:
@pytest.fixture
def cacu(base):
base.correr("catalogos", "cargar", "cohortes", permitir_sin_definir=True)
base.run("catalogs", "load", "event_models", "cohorts", allow_undecided=True)
return base
@@ -56,7 +56,7 @@ def cuenta(base, sql):
def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
estimador = EstimadorFijo()
(lote_id, nuevo) = cacu.correr("estimar", estimadores={URL: estimador})["estimar"][URL]
(lote_id, nuevo) = cacu.run("estimate", estimators={URL: estimador})["estimate"][URL]
miembros = cuenta(cacu, "SELECT n_miembros FROM cohorte_armado ORDER BY armado_id DESC LIMIT 1")
assert nuevo and miembros > 0
@@ -68,23 +68,23 @@ def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
@pytest.mark.parametrize("proyecto", ["cacu"])
def test_estimar_otra_vez_no_duplica_y_sin_estimadores_no_hace_nada(cacu):
(primero, _) = cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL]
(primero, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
assert cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL] == (primero, False)
assert cacu.correr("estimar")["estimar"] == {}
assert cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] == (primero, False)
assert cacu.run("estimate")["estimate"] == {}
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 1
@pytest.mark.parametrize("proyecto", ["cacu"])
def test_confirmar_y_anular_un_lote_agregan_una_version(cacu, capsys):
(lote_id, _) = cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL]
(lote_id, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
miembros = cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}")
main(["confirmar-riesgos", "cacu", str(lote_id), "--motivo", "revisado"])
main(["confirm-risks", "cacu", str(lote_id), "--reason", "revisado"])
assert f"{miembros} evaluaciones confirmadas" in capsys.readouterr().out
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'final' AND version = 2") == miembros
assert confirmar_riesgos("cacu", lote_id, "error de captura", anular=True) == miembros
assert confirm_risks("cacu", lote_id, "error de captura", void=True) == miembros
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'entered-in-error'") == miembros
@@ -95,21 +95,3 @@ DE_PUNTA_A_PUNTA = {
}
@pytest.mark.parametrize("proyecto", sorted(DE_PUNTA_A_PUNTA))
def test_el_lote_confirmado_sale_en_el_resumen_por_banda(base, proyecto, sin_supresion):
"""De punta a punta: la cohorte, estimar a su horizonte, confirmar y el resumen por banda."""
url, horizonte, measure = DE_PUNTA_A_PUNTA[proyecto]
base.correr("catalogos", "cargar", "cohortes", permitir_sin_definir=True)
estimador = EstimadorFijo(url, horizonte=horizonte, probabilidad=0.3) # 0.3 >= corte_alto: ALTO
(lote_id, _) = base.correr("estimar", estimadores={url: estimador})["estimar"][url]
confirmar_riesgos(proyecto, lote_id, "revisado")
# Sin supresión: los fixtures tienen menos miembros por semestre que el umbral (CaMa la tiene activa).
base.correr("vistas", "registro", "definiciones", "calcular", parametros=sin_supresion, permitir_sin_definir=True)
en_el_anio = cuenta(base, f"""SELECT COUNT(*) FROM cohorte_miembro
WHERE strftime('%Y', fecha_indice) = '{base.ctx.anio_inicio}'""")
altos = cuenta(base, f"""SELECT COALESCE(SUM(v.n), 0) FROM v_c2 v
JOIN v_measure_report_vigente r ON r.report_id = v.report_id
WHERE r.measure_url = '{measure}' AND r.periodo_id LIKE '%-S_'
AND v.categoria = 'ALTO' AND v.estrato_id = 'total'""")
assert en_el_anio > 0 and altos == en_el_anio
+55 -47
View File
@@ -1,64 +1,72 @@
"""What this module covers: the timeline repository that `repositorios_de` wires into `ctx.repos.plata`
reads the same rows as the kit's own query, in each project.
"""What this module covers: the timeline `repositories_of` wires into `ctx.repos.silver` is dbt's view
`cacu_linea_de_tiempo`, the one the models' pipelines, the cohort builds and the measures' strata read: silver's
facts as the indicator kit's own timeline gave them, plus the procedures dbt infers from them.
Fixtures: `base` (from `conftest.py`), a project database for each of CaCu, CaMa and TEA; each test loads
its catalogs and data with `base.correr("catalogos", "cargar")`. `kit_rows` reads the same timeline
straight through the kit (`filas_de_linea`) to compare against.
Fixtures: `base` (from `conftest.py`), the CaCu fixture database, loaded and with dbt's views created
(`catalogs`, `load`, `event_models`; needs `DBT_MANIFEST`); `kit_rows`, the rows the kit's timeline query gave on
that data (`fixtures/kit_cacu_timeline.json`, without `conocida_en`, which is each run's load time).
"""
import json
import os
from datetime import date, datetime, timedelta, timezone
from importlib import import_module
from pathlib import Path
from indicadores_kit.oro.cohortes.armado import filas_de_linea
from indicadores_kit.tablas import tablas_de
from sqlmodel import Session
import pytest
CORTE = date(2025, 12, 31)
INFERRED = {"colposcopia", "tratamiento", "citologia_de_vigilancia", "diagnostico", "antecedente"}
KIT_ROWS = Path(__file__).parent / "fixtures" / "kit_cacu_timeline.json"
def kit_rows(base, **filters):
"""The project's timeline read through the kit with `filters` (the kit's Spanish keywords)."""
fuentes = import_module(f"indicadores_kit.{base.proyecto}.linea_de_tiempo").FUENTES_PLATA
with Session(base.motor) as session:
return filas_de_linea(session, tablas_de(base.proyecto), fuentes, **filters)
@pytest.fixture
def proyecto():
return "cacu"
def test_the_whole_timeline_matches_the_kit(base):
"""Pins down: with only a clinical cut-off, the wired repository returns exactly the kit's rows, and
there are some.
Fails if the orchestration binds another query, another project's tables or sources, or `until`
stops reaching the kit as `hasta`.
"""
base.correr("catalogos", "cargar")
rows = base.ctx.repos.plata.timeline.read(until=CORTE)
assert rows
assert rows == kit_rows(base, hasta=CORTE)
@pytest.fixture
def loaded(base):
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
base.run("catalogs", "load", "event_models")
return base
def test_the_patient_filter_matches_the_kit(base):
"""Pins down: `patients` reaches the kit as `pacientes`: only those patients come back, with the
kit's rows.
@pytest.fixture
def kit_rows():
return json.loads(KIT_ROWS.read_text(encoding="utf-8"))
Fails if the patient filter is dropped or renamed on the way to the kit's query.
"""
base.correr("catalogos", "cargar")
patients = sorted({row["pac_id"] for row in kit_rows(base)})[:2]
rows = base.ctx.repos.plata.timeline.read(patients=patients, until=CORTE)
def as_kit(rows) -> list[dict]:
"""Rows as the snapshot keeps them: text values, no load time, without the inferred procedures."""
return [{k: None if v is None else str(v) for k, v in row.items() if k != "conocida_en"}
for row in rows if row["tipo"] not in INFERRED]
def test_the_timeline_is_the_kit_s_plus_the_inferred_procedures(loaded, kit_rows):
"""Pins down: the wired repository reads dbt's view, which holds every row the kit's timeline held, in its
order and with a date as `fecha`, plus inferred procedures. Fails if the orchestration binds another query, or
the view stops giving one of the kit's rows."""
rows = loaded.ctx.repos.silver.timeline.read(until=CORTE)
assert as_kit(rows) == kit_rows
assert {row["tipo"] for row in rows} & INFERRED
assert all(isinstance(row["fecha"], date) for row in rows)
def test_the_patient_filter_keeps_only_those_patients(loaded, kit_rows):
"""Pins down: `patients` keeps those patients' rows, all of them. Fails if the filter is dropped or misapplied."""
patients = sorted({int(row["pac_id"]) for row in kit_rows})[:2]
rows = loaded.ctx.repos.silver.timeline.read(patients=patients, until=CORTE)
assert {row["pac_id"] for row in rows} == set(patients)
assert rows == kit_rows(base, pacientes=patients, hasta=CORTE)
assert as_kit(rows) == [row for row in kit_rows if int(row["pac_id"]) in patients]
def test_known_until_cuts_at_what_was_loaded(base):
"""Pins down: `known_until` reaches the kit as `conocida_hasta`: before the load nothing is known,
after it everything is, the same as reading without the cut.
Fails if the load cut-off is ignored, or applied to the clinical date instead of the load time.
"""
before = datetime.now(timezone.utc) - timedelta(days=1)
base.correr("catalogos", "cargar")
after = datetime.now(timezone.utc) + timedelta(days=1)
timeline = base.ctx.repos.plata.timeline
assert timeline.read(until=CORTE, known_until=before) == []
assert timeline.read(until=CORTE, known_until=after) == kit_rows(base, hasta=CORTE, conocida_hasta=after)
assert timeline.read(until=CORTE, known_until=after) == timeline.read(until=CORTE)
def test_known_until_cuts_at_what_was_loaded(loaded):
"""Pins down: `known_until` compares with the load's time as a datetime: before the load nothing is known,
after it everything is. Fails if the cut is ignored, applied to the clinical date, or compared as text."""
timeline = loaded.ctx.repos.silver.timeline
everything = timeline.read(until=CORTE)
known = {row["conocida_en"] for row in everything}
assert all(isinstance(at, datetime) and at.tzinfo is not None for at in known)
assert timeline.read(until=CORTE, known_until=min(known) - timedelta(seconds=1)) == []
assert timeline.read(until=CORTE, known_until=datetime.now(timezone.utc) + timedelta(days=1)) == everything
+2 -2
View File
@@ -47,11 +47,11 @@ def seeded(client):
CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="c", valor_numerico=0.0)])
session.commit()
build_id = build.armado_id
batch, _ = cacu.cohorte_repository.guardar_lote(
batch, _ = cacu.cohort_repository.save_batch(
build_id, {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"},
"cin2_12m", [(scored, 3.0, 0.3, None, None), (scored, 1.0, 0.1, None, None)],
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
cacu.cohorte_repository.cambiar_estado(batch, "final", "revisado")
cacu.cohort_repository.change_state(batch, "final", "revisado")
return scored, unscored, outside
+7 -5
View File
@@ -97,16 +97,18 @@ def test_report_endpoints(client):
def test_indicators_recompute_from_imported_rows(client):
from webapi.indicadores_vivos import ColaDeRecalculo
from webapi.recomputation import RecomputationQueue
cola = ColaDeRecalculo()
cola = RecomputationQueue()
assert client.get("/reportes/indicadores").get_json()["cacu"]["pendiente"] is True
assert cola.atender() == ["cacu"]
assert cola.serve() == ["cacu"]
estado = client.get("/reportes/indicadores").get_json()["cacu"]
assert estado["estado"] == "ok", estado
assert estado["pendiente"] is False
assert {p["paso"] for p in estado["pasos"]} >= {"cargar", "calcular"}
assert client.get("/cacu/indicadores").get_json()
assert {p["paso"] for p in estado["pasos"]} >= {"load", "event_models"}
assert {m["id"] for m in client.get("/cacu/indicadores").get_json()} == {
"IND1", "CACU_EU13", "CACU_EU7", "CACU_CONFIRMACION_CITOLOGIA", "CACU_EU_TIEMPO_REPORTE",
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_RIESGO_BANDA"}
assert client.post("/reportes/indicadores/cacu/recalcular").status_code == 202
assert client.post("/reportes/indicadores/xx/recalcular").status_code == 404
+136
View File
@@ -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"}
+20 -19
View File
@@ -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():
@@ -142,6 +143,16 @@ def test_catalog_is_case_insensitive_accepts_member_names_and_rejects_unknowns()
catalog.coerce("X")
def test_postal_code_restores_leading_zero_from_numeric_sources():
from webapi.imports.schemas.coercion import coerce_postal_code
assert coerce_postal_code(1000) == "01000"
assert coerce_postal_code(64000.0) == "64000"
assert coerce_postal_code(" 01000 ") == "01000"
assert coerce_postal_code("") is None
def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog():
"""`extraction.nlp.vocabulary.CLINICAL_TERMS` extracts BI-RADS 4A/4B/4C
from narrative text (a standard ACR BI-RADS subcategory), but the schema
@@ -154,16 +165,6 @@ def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog():
for value in ("4A", "BI-RADS 4B", "bi-rads 4c"):
assert catalog.coerce(value) == "B4"
def test_postal_code_restores_leading_zero_from_numeric_sources():
from webapi.imports.schemas.coercion import coerce_postal_code
assert coerce_postal_code(1000) == "01000"
assert coerce_postal_code(64000.0) == "64000"
assert coerce_postal_code(" 01000 ") == "01000"
assert coerce_postal_code("") is None
def test_column_matcher_handles_accents_prefixes_and_global_one_to_one():
targets = ["pac_id_hospital", "pac_sexo", "pac_codigo_postal", "pac_fecha_nacimiento"]
by_source = {
@@ -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"
+19 -6
View File
@@ -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
@@ -34,6 +35,8 @@ def test_every_registered_schema_is_constructible(entity_key):
# --- Spot checks -----------------------------------------------------------
# CaMa entity with a required, unique integer ord_numero_hospital and an
# *_ALIAS-backed enum field.
def test_cama_ordenes_estudio_requires_numero_hospital_and_coerces_tipo_estudio():
with pytest.raises(ValidationError) as excinfo:
CamaOrdenesEstudioImportSchema(pac_id_hospital="H-1")
@@ -46,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).
+8 -6
View File
@@ -9,7 +9,7 @@ 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
@@ -31,7 +31,9 @@ def test_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):
@@ -60,9 +62,9 @@ def test_una_pagina_de_mas_da_404(client):
assert "error" in response.get_json()
def test_en_dev_esta_obsoleta():
"""Fija: `en_dev()` avisa que está obsoleta. Falla si alguien vuelve a usarla como compuerta sin el aviso."""
from webapi.seguimiento import en_dev
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):
en_dev()
in_dev()
+14 -14
View File
@@ -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
+116
View File
@@ -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]
+273
View File
@@ -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()
Generated
+794 -125
View File
File diff suppressed because it is too large Load Diff
+18 -8
View File
@@ -6,13 +6,11 @@ from flask import Flask, jsonify
from flask.json.provider import DefaultJSONProvider
from webapi.blueprints.cacu import cacu_bp
from webapi.blueprints.cama import cama_bp
from webapi.blueprints.data import data_bp
from webapi.blueprints.governance import governance_bp
from webapi.blueprints.imports import imports_bp
from webapi.blueprints.reportes import reportes_bp
from webapi.blueprints.tea import tea_bp
from webapi.seguimiento import blueprint_de_seguimiento
from webapi.blueprints.reports import reports_bp
from webapi.follow_up.routes import follow_up_blueprint
class IsoJSONProvider(DefaultJSONProvider):
@@ -71,12 +69,24 @@ def create_app() -> Flask:
return jsonify({"error": f"la solicitud excede {limit_mb} MB"}), 413
app.register_blueprint(cacu_bp, url_prefix="/cacu")
app.register_blueprint(cama_bp, url_prefix="/cama")
app.register_blueprint(tea_bp, url_prefix="/tea")
app.register_blueprint(imports_bp, url_prefix="/imports")
app.register_blueprint(data_bp, url_prefix="/data")
app.register_blueprint(governance_bp, url_prefix="/governance")
app.register_blueprint(reportes_bp, url_prefix="/reportes")
app.register_blueprint(reports_bp, url_prefix="/reportes")
# The measures, answered on request from dbt's semantic definitions: the deployment ships their manifest.
if os.environ.get("DBT_MANIFEST"):
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", "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
@@ -84,7 +94,7 @@ def create_app() -> Flask:
from webapi.patient_risk import patient_risk_blueprint
app.register_blueprint(blueprint_de_seguimiento(get_cacu_session), 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
-4
View File
@@ -1,7 +1,3 @@
from flask import Blueprint
from persistance.db import get_cacu_session
from webapi.indicadores import registrar_indicadores
cacu_bp = Blueprint("cacu", __name__)
registrar_indicadores(cacu_bp, "cacu", get_cacu_session)
-7
View File
@@ -1,7 +0,0 @@
from flask import Blueprint
from persistance.db import get_cama_session
from webapi.indicadores import registrar_indicadores
cama_bp = Blueprint("cama", __name__)
registrar_indicadores(cama_bp, "cama", get_cama_session)
+106 -12
View File
@@ -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 ---------------------------------------------------------------------------------
+58 -16
View File
@@ -8,28 +8,33 @@ from sqlalchemy.exc import SQLAlchemyError
from extraction import BBox, ExtractionError
from extraction.readers import reader_for
from indicadores_kit.registry.catalogos import CatalogoInvalido
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,
)
from webapi.indicadores_vivos import ColaDeRecalculo
from webapi.recomputation import DOMAINS, RecomputationQueue
from webapi.imports.services.introspection_service import (
detect_pdf,
document_report,
extract_pdf_regions,
preview_with_suggestions,
suggest_mapping,
)
imports_bp = Blueprint("imports", __name__)
@@ -253,12 +258,15 @@ 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?}`.
`files` may be `sql` instead: `{connection details, table|query, column,
key_column}`, one document per row (a PDF or plain-text column).
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") and not body.get("sql"):
raise BadRequest("faltan los archivos")
@@ -284,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")
@@ -308,15 +342,17 @@ def validate():
def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
"""For every `document` source in the request (uploaded, or reading a
SQL column — same connector either way), writes the captions no known
field claimed straight into the silver layer (`catalog_commit_service`),
matched or minted against the project's catalog. Best-effort: the
structured fields already landed through `commit_sources`, so a failure
here is reported, not raised."""
"""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("source_type") != "document":
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]
@@ -324,9 +360,14 @@ def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
continue
payload = {**(raw.get("payload") or {}), "target": target}
try:
connector = build_connector("document", payload)
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) as exc:
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(
@@ -337,6 +378,7 @@ def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
"records_without_patient": result.records_without_patient,
"fields_matched": result.fields_matched,
"fields_minted": result.fields_minted,
"fields_unmatched": result.fields_unmatched,
}
)
return reports
@@ -361,9 +403,9 @@ def commit():
finally:
import_audit.record(audit)
recalculating = False
if audit.domain and any(r.created or r.updated for r in results):
if audit.domain in DOMAINS and any(r.created or r.updated for r in results):
try:
ColaDeRecalculo().solicitar(audit.domain)
RecomputationQueue().request_run(audit.domain)
recalculating = True
except OSError:
# The rows are already saved; failing here would invite a duplicate retry.
@@ -3,13 +3,13 @@ indicator recomputation. Nothing here returns row-level data."""
from flask import Blueprint, Response, jsonify, request
from webapi.imports import audit as import_audit
from webapi.indicadores_vivos import DOMINIOS, ColaDeRecalculo
from webapi.recomputation import DOMAINS, RecomputationQueue
reportes_bp = Blueprint("reportes", __name__)
reports_bp = Blueprint("reportes", __name__)
@reportes_bp.get("/importaciones")
def importaciones():
@reports_bp.get("/importaciones")
def import_log():
"""Totals per target over every logged attempt, plus the latest attempts
(`?limite=50`, newest first; `?dominio=cacu` to filter)."""
records = import_audit.default_sink().read()
@@ -23,8 +23,8 @@ def importaciones():
return jsonify({"resumen": import_audit.summarize(records), "intentos": list(reversed(records))[:limit]})
@reportes_bp.get("/importaciones/descarga")
def importaciones_descarga():
@reports_bp.get("/importaciones/descarga")
def import_log_download():
"""The raw log, one JSON object per line."""
sink = import_audit.default_sink()
body = sink.path.read_bytes() if sink.path.exists() else b""
@@ -35,15 +35,15 @@ def importaciones_descarga():
)
@reportes_bp.get("/indicadores")
def indicadores_estado():
@reports_bp.get("/indicadores")
def recomputation_status():
"""Per domain: state of the last recomputation and whether another is pending."""
return jsonify(ColaDeRecalculo().estado())
return jsonify(RecomputationQueue().status())
@reportes_bp.post("/indicadores/<dominio>/recalcular")
def indicadores_recalcular(dominio: str):
if dominio not in DOMINIOS:
@reports_bp.post("/indicadores/<dominio>/recalcular")
def recompute(dominio: str):
if dominio not in DOMAINS:
return jsonify({"error": f"dominio desconocido: {dominio}"}), 404
ColaDeRecalculo().solicitar(dominio)
RecomputationQueue().request_run(dominio)
return jsonify({"pendiente": True}), 202
-7
View File
@@ -1,7 +0,0 @@
from flask import Blueprint
from persistance.db import get_tea_session
from webapi.indicadores import registrar_indicadores
tea_bp = Blueprint("tea", __name__)
registrar_indicadores(tea_bp, "tea", get_tea_session)
+333
View File
@@ -0,0 +1,333 @@
"""A composition answered on request: how a period's units split across the categories of their latest valid fact.
The definition is a simple metric of dbt's semantic layer (the units counted) whose `meta` says `scoring:
composition` and gives the category rule (`categoria`): which column is the category, what makes a fact valid
(a template like a metric's `filter`), the dates the event and knowledge cut-offs apply to, and the order that picks
each unit's latest fact. Which fact is a unit's latest depends on the question (its period and cut-offs), so it's
computed in the answer, with `ROW_NUMBER()`, not stored in the model. The rest (the question, the history, strata
by age at the period's start) is `webapi.metrics`'.
"""
import dataclasses
import hashlib
import json
from collections.abc import Iterable
from datetime import datetime, timedelta, timezone
from importlib import import_module
from pathlib import Path
from core.indicadores.tipos import FechaHoraUTC
from jinja2 import Environment
from sqlalchemy import Select, String, and_, bindparam, case, cast, column, desc, distinct, func, literal, select, table, text
from webapi.metrics import (
AGGREGATION_VERSION,
HISTORY_ENTRY,
EVENT_CUTOFF,
KNOWLEDGE_CUTOFF,
POPULATION_SYSTEM,
MeasureQueries,
Population,
Question,
StatusAtEnd,
Stratum,
_population,
_semantic_model_of,
key_of,
rule_values,
)
@dataclasses.dataclass(frozen=True)
class FollowUp:
"""A fact that follows the chosen one (a biopsy of the chosen sample): the category comes from the first of
them by `order`, among those that exist and were dated and known by the cut-offs; `none` if there's none."""
exists: str
dated_at: tuple[str, ...]
known_at: tuple[str, ...]
order: tuple[str, ...]
none: str
@dataclasses.dataclass(frozen=True)
class Category:
value: str
no_data: str
valid_sql: str
dated_at: tuple[str, ...]
known_at: tuple[str, ...]
order: tuple[str, ...]
admits_sql: str | None = None # which units count, judged on their chosen fact
follow_up: FollowUp | None = None
# A number's band instead of the value itself: (band, rule of its upper bound), in order; the last has no bound.
bands: tuple[tuple[str, str | None], ...] = ()
@dataclasses.dataclass(frozen=True)
class CompositionDefinition:
"""A composition, shaped so `MeasureQueries` can build its period, cut-offs and strata."""
url: str
version: str
metric: str
relation: str
model_checksum: str
time_dimension: str
dimensions: dict[str, str]
units: Population
category: Category
group: str
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:
return self.url.rsplit("/", 1)[-1]
@property
def numerator(self) -> Population:
return self.units
@property
def denominator(self) -> Population:
return self.units
improvement_notation = None
def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]:
"""The simple metrics of the manifest whose `meta` declares a composition, by `measure_url`."""
m = json.loads(manifest.read_text(encoding="utf-8"))
semantic = {node["name"]: node for node in m["semantic_models"].values()}
models = {node["unique_id"]: node for node in m["nodes"].values()}
definitions = {}
for metric in m["metrics"].values():
meta = metric["config"].get("meta", {})
if metric["type"] != "simple" or meta.get("scoring") != "composition":
continue
model = _semantic_model_of(metric, semantic)
node = models[model["depends_on"]["nodes"][0]]
rule = meta["categoria"]
definitions[meta["measure_url"]] = CompositionDefinition(
url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"], relation=node["alias"],
model_checksum=node["checksum"]["checksum"], time_dimension=model["defaults"]["agg_time_dimension"],
dimensions={**{e["name"]: e["expr"] or e["name"] for e in model["entities"]},
**{d["name"]: d["expr"] or d["name"] for d in model["dimensions"]}},
units=_population(metric, model),
category=Category(rule["valor"], rule["sin_dato"], rule["valido"], tuple(rule.get("fechada_en", ())),
tuple(rule.get("conocida_en", ())), tuple(rule["orden"]), rule.get("admite"),
_follow_up(rule.get("seguimiento")),
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
def _follow_up(rule: dict | None) -> FollowUp | None:
if rule is None:
return None
return FollowUp(rule["existe"], tuple(rule.get("fechada_en", ())), tuple(rule.get("conocida_en", ())),
tuple(rule["orden"]), rule["sin_seguimiento"])
class CompositionQueries(MeasureQueries):
"""Each unit's category in the period, from the latest of its facts, valid ones first."""
def __init__(self, definition: CompositionDefinition, question: Question, rule_values: dict, period_table):
super().__init__(definition, question, rule_values, period_table)
c, f = definition.category, definition.category.follow_up
names = [c.value, *c.order, *c.dated_at, *c.known_at,
*((f.exists, *f.order, *f.dated_at, *f.known_at) if f else ()),
*(s.spec["valor"] for s in definition.strata if s.kind == "del_elegido")]
known = {definition.dimensions[n] for n in (*c.known_at, *(f.known_at if f else ()))}
for name in {definition.dimensions[n] for n in names} - set(self.events.c.keys()):
self.events.append_column(column(name, FechaHoraUTC) if name in known else column(name))
def _template(self, sql: str):
"""A `meta` condition, rendered like a metric's `filter`, with the rules it names bound (a list as `in`)."""
rendered = Environment().from_string(sql).render(
Dimension=lambda ref: f"{self.d.relation}.{self.d.dimensions[ref.split('__')[-1]]}")
names = [n for n in self.values if f":{n}" in rendered]
return text(f"({rendered})").bindparams(*(
bindparam(n, self.values[n], expanding=isinstance(self.values[n], (list, tuple))) for n in names))
def _value(self):
"""The category's value: the column's, or the band its number falls in, by the question's rules."""
c = self.d.category
if not c.bands:
return self._column(c.value)
number = self._column(c.value)
*bounded, (last, _) = c.bands
return case(*((number < self.values[rule], literal(band)) for band, rule in bounded), else_=literal(last))
def _counted(self):
"""The follow-up fact of this row exists and was dated and known by the cut-offs."""
f = self.d.category.follow_up
conditions = [self._column(f.exists).is_not(None)]
if self.q.event_cutoff is not None:
conditions += [self._column(n) <= self.q.event_cutoff.isoformat() for n in f.dated_at]
if self.q.knowledge_cutoff is not None:
conditions += [self._column(n) <= self.q.knowledge_cutoff for n in f.known_at]
return and_(*conditions)
def _valid(self):
c = self.d.category
conditions = [self._template(c.valid_sql)]
for name in c.dated_at:
conditions.append(self._column(name).is_not(None))
if self.q.event_cutoff is not None:
conditions.append(self._column(name) <= self.q.event_cutoff.isoformat())
if self.q.knowledge_cutoff is not None:
conditions += [self._column(name) <= self.q.knowledge_cutoff for name in c.known_at]
return and_(*conditions)
def latest(self, *, with_strata: bool = False):
"""One row per unit: its category (`categoria`) and, with strata, its value of each (`estrato_<name>`)."""
unit = self.events.c[self.d.units.measure_expr]
c, f = self.d.category, self.d.category.follow_up
valid = self._valid()
order = [desc(case((valid, 1), else_=0)), *(desc(self._column(n)) for n in c.order)]
value = self._value()
category = case((valid, value))
if f is not None:
counted = self._counted()
order += [desc(case((counted, 1), else_=0)), *(desc(self._column(n)) for n in f.order)]
category = case((valid & ~counted, literal(f.none)), (valid, value))
admitted = valid if c.admits_sql is None else and_(valid, self._template(c.admits_sql))
where = self._in_question()
units = self._filter(self.d.units)
if units is not None:
where = and_(where, units)
strata = [self.stratum_value(s).label(f"estrato_{s.name}") for s in self.d.strata] if with_strata else []
ranked = (select(unit.label("unidad"), category.label("categoria"), case((admitted, 1), else_=0).label("admitida"),
*strata, func.row_number().over(partition_by=unit, order_by=order).label("lugar"))
.select_from(self._from(with_strata=with_strata)).where(where).subquery("por_unidad"))
chosen = [ranked.c.lugar == 1] + ([ranked.c.admitida == 1] if c.admits_sql is not None else [])
return (select(ranked.c.unidad, func.coalesce(ranked.c.categoria, c.no_data).label("categoria"),
*(ranked.c[f"estrato_{s.name}"] for s in self.d.strata if with_strata))
.where(*chosen).subquery("ultima"))
def category_counts(self) -> Select:
latest = self.latest()
return (select(latest.c.categoria, func.count(distinct(latest.c.unidad)))
.group_by(latest.c.categoria).order_by(latest.c.categoria))
def counts_by_stratum(self, stratum: Stratum) -> Select:
latest = self.latest(with_strata=True)
value = latest.c[f"estrato_{stratum.name}"]
return (select(value, latest.c.categoria, func.count(distinct(latest.c.unidad)))
.group_by(value, latest.c.categoria))
def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]:
latest = self.latest(with_strata=True)
(code,) = self.d.units.codes
yield unit_model, select(
literal(report_id).label("report_id"), literal(self.d.group).label("grupo"),
cast(latest.c.unidad, String(64)).label("unidad_id"),
literal(f"{self.d.measure_id}.{code}").label("resultado_id"),
(latest.c.unidad if self.d.basis == "paciente" else literal(None)).label("pac_id"),
latest.c.categoria.label("valor_id"),
)
for stratum in self.d.strata:
yield stratum_model, select(
literal(report_id).label("report_id"), cast(latest.c.unidad, String(64)).label("unidad_id"),
literal(stratum.name).label("estrato_id"), latest.c[f"estrato_{stratum.name}"].label("estrato_valor"),
)
@dataclasses.dataclass(frozen=True)
class CompositionAnswer:
report_id: int
categories: dict[str, int]
strata: dict[str, dict[str, dict[str, int]]]
stored_before: bool
@property
def total(self) -> int:
return sum(self.categories.values())
def answer_composition(project: str, definition: CompositionDefinition, question: Question, *, parameters, periods,
history, queries, allow_undecided: bool = False,
now: datetime | None = None) -> CompositionAnswer:
"""The stored answer, or a new one: the database ranks each unit's facts, counts and writes the units."""
values = rule_values(parameters, definition, allow_undecided)
key, key_sha = key_of(definition, question, values)
stored = history.find(definition.url, key_sha)
if stored is not None:
return _from_counts(stored, history.counts(stored))
period = periods.get(question.period_id)
if period is None:
raise LookupError(f"dim_periodo has no period {question.period_id!r}")
sql = CompositionQueries(definition, question, values, periods.model.__table__)
_, rows = queries.rows(sql.category_counts())
categories = {category: n for category, n in rows}
strata = {}
for stratum in definition.strata:
_, cells = queries.rows(sql.counts_by_stratum(stratum))
for value, category, n in cells:
strata.setdefault(stratum.name, {}).setdefault(value, {})[category] = n
models = import_module(f"core.{project}.indicadores.models")
(any_rule,) = parameters.list(limit=1)
report = models.MeasureReport(
measure_url=definition.url, measure_version=definition.version,
kit_version=f"metric:{definition.metric}:{definition.model_checksum[:12]}", toml_sha=any_rule.toml_sha,
parametros=key, parametros_sha=key_sha, fecha_corte=question.event_cutoff,
periodo_id=period.periodo_id, periodo_inicio=period.inicio, periodo_fin=period.fin,
status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc),
agregacion_version=AGGREGATION_VERSION,
huella=hashlib.sha256(json.dumps([key_sha, sorted(categories.items()), sorted(
(s, v, c, n) for s, by in strata.items() for v, cs in by.items() for c, n in cs.items())]).encode()
).hexdigest(),
)
report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad,
models.MeasureReportUnidadEstrato))
return CompositionAnswer(report_id, categories, strata, stored_before=False)
def _from_counts(report_id: int, counts: dict) -> CompositionAnswer:
categories, strata = {}, {}
for (stratum, value, _, category), n in counts.items():
if stratum == "total":
categories[category] = n
else:
strata.setdefault(stratum, {}).setdefault(value, {})[category] = n
return CompositionAnswer(report_id, categories, strata, stored_before=True)
def composition_report(definition: CompositionDefinition, question: Question, result: CompositionAnswer, period,
generated_at: datetime) -> dict:
"""The answer as a FHIR R4 `MeasureReport`: the units counted, and a stratifier by category (and by each stratum)."""
(code,) = definition.units.codes
def stratum(value: str, n: int) -> dict:
return {"value": {"text": value}, "population": [
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": n}]}
stratifiers = [{"code": [{"text": definition.category.value}],
"stratum": [stratum(c, n) for c, n in sorted(result.categories.items())]}]
for name, by_value in result.strata.items():
stratifiers.append({"code": [{"text": name}],
"stratum": [stratum(v, sum(cs.values())) for v, cs in sorted(by_value.items())]})
group = {"id": definition.group, "population": [
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": result.total},
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": code}]}, "count": result.total},
], "stratifier": stratifiers}
extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}]
if question.event_cutoff is not None:
extensions.append({"url": EVENT_CUTOFF, "valueDate": question.event_cutoff.isoformat()})
if question.knowledge_cutoff is not None:
extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()})
return {
"resourceType": "MeasureReport", "status": "complete", "type": "summary",
"measure": f"{definition.url}|{definition.version}", "date": generated_at.isoformat(),
"period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()},
"extension": extensions, "group": [group],
}
+83
View File
@@ -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())
+299
View File
@@ -0,0 +1,299 @@
"""A duration answered on request: the days each unit takes from one fact to the next, summarized by quartiles.
The definition is a simple metric of dbt's semantic layer (the units counted) whose `meta` says `scoring:
continuous-variable` and gives the observation rule (`observacion`): the column with each unit's days, the dates the
cut-offs apply to, and the horizon: a unit without a value whose horizon hasn't passed by the event cut-off isn'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. 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
import hashlib
import json
from collections.abc import Iterable
from datetime import date, datetime, timedelta, timezone
from importlib import import_module
from pathlib import Path
from sqlalchemy import Integer, Select, String, and_, case, cast, column, func, literal, not_, null, select, table, true
from webapi.metrics import (
AGGREGATION_VERSION,
EVENT_CUTOFF,
HISTORY_ENTRY,
KNOWLEDGE_CUTOFF,
POPULATION_SYSTEM,
MeasureQueries,
Population,
Question,
StatusAtEnd,
_population,
_semantic_model_of,
key_of,
rule_values,
)
OBSERVATION = "measure-observation"
LOADS = table("carga", column("inicio"), column("fin"))
DAYS = table("dim_fecha", column("fecha"), column("dia_num"))
def inclusive_quartiles(values) -> Select:
"""(n, q1, median, q3) of a subquery's `numero`, by the inclusive method in ANSI SQL.
The quartile `q` is at position `(n - 1) q` of the sorted values (from 0), interpolating between its two
neighbors, as `statistics.quantiles(method="inclusive")`; with one value, the three are it. Window functions,
`CAST` and `CASE` only: the same SQL on every engine.
"""
ranked = select(values.c.numero,
(func.row_number().over(order_by=values.c.numero) - 1).label("i"),
func.count().over().label("n")).subquery("ordenados")
cells = []
for name, q in (("q1", 0.25), ("mediana", 0.5), ("q3", 0.75)):
position = (ranked.c.n - 1) * q
floor = cast(position, Integer)
fraction = position - floor
cells.append((func.sum(case((ranked.c.i == floor, ranked.c.numero * (1 - fraction)), else_=0.0))
+ func.sum(case((ranked.c.i == floor + 1, ranked.c.numero * fraction), else_=0.0))).label(name))
return select(func.count(ranked.c.numero).label("n"), *cells)
@dataclasses.dataclass(frozen=True)
class Observation:
value: str
dated_at: tuple[str, ...]
known_at: tuple[str, ...]
horizon_rule: str | None
start_day: str
horizon_days: int | None = None # a fixed horizon, when the model used the same one to find the next fact
def horizon(self, values: dict) -> int:
return self.horizon_days if self.horizon_rule is None else values[self.horizon_rule]
@dataclasses.dataclass(frozen=True)
class DurationDefinition:
"""A duration, shaped so `MeasureQueries` can build its period and cut-offs."""
url: str
version: str
metric: str
relation: str
model_checksum: str
time_dimension: str
dimensions: dict[str, str]
units: Population
observation: Observation
group: str
basis: str
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:
return self.url.rsplit("/", 1)[-1]
@property
def numerator(self) -> Population:
return self.units
@property
def denominator(self) -> Population:
return self.units
def duration_definitions(manifest: Path) -> dict[str, DurationDefinition]:
"""The simple metrics of the manifest whose `meta` declares a duration, by `measure_url`."""
m = json.loads(manifest.read_text(encoding="utf-8"))
semantic = {node["name"]: node for node in m["semantic_models"].values()}
models = {node["unique_id"]: node for node in m["nodes"].values()}
definitions = {}
for metric in m["metrics"].values():
meta = metric["config"].get("meta", {})
if metric["type"] != "simple" or meta.get("scoring") != "continuous-variable":
continue
model = _semantic_model_of(metric, semantic)
node = models[model["depends_on"]["nodes"][0]]
rule = meta["observacion"]
definitions[meta["measure_url"]] = DurationDefinition(
url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"], relation=node["alias"],
model_checksum=node["checksum"]["checksum"], time_dimension=model["defaults"]["agg_time_dimension"],
dimensions={**{e["name"]: e["expr"] or e["name"] for e in model["entities"]},
**{d["name"]: d["expr"] or d["name"] for d in model["dimensions"]}},
units=_population(metric, model),
observation=Observation(rule["valor"], tuple(rule.get("fechada_en", ())), tuple(rule.get("conocida_en", ())),
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"), population=StatusAtEnd.of(meta.get("poblacion")),
meta=meta,
)
return definitions
class DurationQueries(MeasureQueries):
"""Each unit of the period: measured or not yet, and its days if it has them."""
def __init__(self, definition: DurationDefinition, question: Question, rule_values: dict, period_table):
super().__init__(definition, question, rule_values, period_table)
o = definition.observation
for name in {definition.dimensions[n] for n in (o.value, o.start_day, *o.dated_at)} - set(self.events.c.keys()):
self.events.append_column(column(name))
def _has_value(self):
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)
def per_unit(self):
"""One row per unit in the period: `unidad`, `numero` (its days, or null) and whether it's still `pendiente`."""
o = self.d.observation
cutoff_day = select(DAYS.c.dia_num).where(DAYS.c.fecha == self.q.event_cutoff.isoformat()).scalar_subquery()
has_value = self._has_value()
pending = and_(not_(has_value),
cutoff_day - self._column(o.start_day) < o.horizon(self.values))
where = self._in_question()
units = self._filter(self.d.units)
if units is not None:
where = and_(where, units)
unit = self.events.c[self.d.units.measure_expr]
return (select(unit.label("unidad"), case((has_value, self._column(o.value)), else_=null()).label("numero"),
case((pending, 1), else_=0).label("pendiente"))
.select_from(self._from(with_strata=False)).where(where).distinct().subquery("por_unidad"))
def summary(self) -> Select:
units = self.per_unit()
measured = select(units.c.numero).where(units.c.numero.is_not(None)).subquery("medidos")
quartiles = inclusive_quartiles(measured).subquery("cuartiles")
initial = select(func.count(units.c.unidad).label("inicial")).where(units.c.pendiente == 0).subquery("inicial")
# Two one-row subqueries side by side.
return (select(initial.c.inicial, quartiles.c.n, quartiles.c.q1, quartiles.c.mediana, quartiles.c.q3)
.select_from(initial.join(quartiles, true())))
def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]:
units = self.per_unit()
(initial,) = self.d.units.codes
for code, where, number in ((initial, units.c.pendiente == 0, null()),
(OBSERVATION, units.c.numero.is_not(None), units.c.numero)):
yield unit_model, select(
literal(report_id).label("report_id"), literal(self.d.group).label("grupo"),
cast(units.c.unidad, String(64)).label("unidad_id"),
literal(f"{self.d.measure_id}.{code}").label("resultado_id"),
(units.c.unidad if self.d.basis == "paciente" else literal(None)).label("pac_id"),
cast(number, unit_model.__table__.c.numero.type).label("numero"),
).where(where)
@dataclasses.dataclass(frozen=True)
class DurationAnswer:
report_id: int
initial: int
n: int
q1: float | None
median: float | None
q3: float | None
stored_before: bool
event_cutoff: date | None = None # the one it was computed at: the question's, or the last load's day
@property
def excluded(self) -> int:
return self.initial - self.n
def last_load_day(queries) -> date | None:
"""The day of the latest load: its `fin`, or its `inicio` if it didn't finish."""
_, ((last,),) = queries.rows(select(func.max(func.coalesce(LOADS.c.fin, LOADS.c.inicio))))
return None if last is None else date.fromisoformat(str(last)[:10])
def answer_duration(project: str, definition: DurationDefinition, question: Question, *, parameters, periods,
history, queries, allow_undecided: bool = False, now: datetime | None = None) -> DurationAnswer:
"""The stored answer, or a new one: the database decides each unit, counts, takes the quartiles and stores."""
if question.event_cutoff is None:
question = dataclasses.replace(question, event_cutoff=last_load_day(queries))
values = rule_values(parameters, definition, allow_undecided)
if definition.observation.horizon_rule is None:
values["horizonte_dias"] = definition.observation.horizon_days
key, key_sha = key_of(definition, question, values)
models = import_module(f"core.{project}.indicadores.models")
stored = history.find(definition.url, key_sha)
if stored is not None:
return dataclasses.replace(_from_stored(definition, stored, queries, models.MeasureReportUnidad),
event_cutoff=question.event_cutoff)
period = periods.get(question.period_id)
if period is None:
raise LookupError(f"dim_periodo has no period {question.period_id!r}")
sql = DurationQueries(definition, question, values, periods.model.__table__)
_, ((initial, n, q1, median, q3),) = queries.rows(sql.summary())
(any_rule,) = parameters.list(limit=1)
report = models.MeasureReport(
measure_url=definition.url, measure_version=definition.version,
kit_version=f"metric:{definition.metric}:{definition.model_checksum[:12]}", toml_sha=any_rule.toml_sha,
parametros=key, parametros_sha=key_sha, fecha_corte=question.event_cutoff,
periodo_id=period.periodo_id, periodo_inicio=period.inicio, periodo_fin=period.fin,
status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc),
agregacion_version=AGGREGATION_VERSION,
huella=hashlib.sha256(json.dumps([key_sha, initial, n, q1, median, q3]).encode()).hexdigest(),
)
report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad,
models.MeasureReportUnidadEstrato))
return DurationAnswer(report_id, initial, n, *_numbers(n, q1, median, q3), stored_before=False,
event_cutoff=question.event_cutoff)
def _numbers(n, q1, median, q3):
return (None, None, None) if not n else (float(q1), float(median), float(q3))
def _from_stored(definition: DurationDefinition, report_id: int, queries, unit_model) -> DurationAnswer:
"""A stored duration read back from its units: the initial ones counted, the quartiles of their days."""
u = unit_model.__table__.c
initial = f"{definition.measure_id}.{definition.units.codes[0]}"
observed = select(u.numero).where(u.report_id == report_id, u.resultado_id == f"{definition.measure_id}.{OBSERVATION}")
_, ((n, q1, median, q3),) = queries.rows(inclusive_quartiles(observed.subquery("medidos")))
_, ((count,),) = queries.rows(select(func.count()).where(u.report_id == report_id, u.resultado_id == initial))
return DurationAnswer(report_id, count, n, *_numbers(n, q1, median, q3), stored_before=True)
def duration_report(definition: DurationDefinition, question: Question, result: DurationAnswer, period,
generated_at: datetime) -> dict:
"""The answer as a FHIR R4 `MeasureReport`: the units measurable and measured, the median as the score, and the
quartiles as its components."""
group = {"id": definition.group, "population": [
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": result.initial},
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": OBSERVATION}]}, "count": result.n},
]}
if result.median is not None:
group["measureScore"] = {"value": result.median, "unit": "d",
"extension": [{"url": "https://isssteleon.org/fhir/StructureDefinition/q1",
"valueDecimal": result.q1},
{"url": "https://isssteleon.org/fhir/StructureDefinition/q3",
"valueDecimal": result.q3}]}
extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id},
{"url": EVENT_CUTOFF, "valueDate": (result.event_cutoff or question.event_cutoff).isoformat()}]
if question.knowledge_cutoff is not None:
extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()})
report = {
"resourceType": "MeasureReport", "status": "complete", "type": "summary",
"measure": f"{definition.url}|{definition.version}", "date": generated_at.isoformat(),
"period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()},
"extension": extensions, "group": [group],
}
if definition.improvement_notation:
report["improvementNotation"] = {"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": definition.improvement_notation}]}
return report
+358
View File
@@ -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
+93
View File
@@ -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
+217
View File
@@ -0,0 +1,217 @@
"""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) and its technical sheet: `meta.ficha` and `meta.figuras_detalle` as extensions, `meta.referencias` as
`relatedArtifact` and `meta.descripcion_poblaciones` as each population's description. 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"
SHEET = f"{STRUCTURE}/ficha"
FIGURE_TEXT = f"{STRUCTURE}/figura-detalle"
SHEET_FIELDS = ("codigo", "para", "unidad", "pregunta", "definicion", "nota")
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}
texts = (getattr(definition, "meta", None) or {}).get("descripcion_poblaciones", {})
return [{"code": concept(POPULATION_SYSTEM, c), "description": texts.get(c) or 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"]})
sheet = meta.get("ficha", {})
if sheet:
extensions.append({"url": SHEET, "extension": [{"url": f, "valueString": sheet[f]}
for f in SHEET_FIELDS if sheet.get(f)]})
extensions += [{"url": FIGURE_TEXT, "extension": [
{"url": "figura", "valueString": figure}, {"url": "descripcion", "valueString": text["descripcion"]},
*({"url": "como-leer", "valueString": line} for line in text.get("como_leer", ()))]}
for figure, text in meta.get("figuras_detalle", {}).items()]
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 meta.get("referencias"):
resource["relatedArtifact"] = [
{"type": r.get("tipo", "citation"), "display": r["etiqueta"], **({"citation": r["ref"]} if r.get("ref") else {})}
for r in meta["referencias"]]
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
+358
View File
@@ -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]}
+53
View File
@@ -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]
+74
View File
@@ -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"}]}}
+7
View File
@@ -0,0 +1,7 @@
"""CaCu's follow-up list (`GET /cacu/seguimiento`): one row per patient, with her ASCCP status and her latest studies.
routes.py the route: validates the request and answers
listing.py the list: who enters it, what each row shows
status.py the ASCCP status of each patient at a date
silver.py, pivot.py, view.py, functions.py the silver queries they read
"""
+53
View File
@@ -0,0 +1,53 @@
# Los estratos que un indicador puede declarar en `extension.estratos`.
# Cada uno es una función de SQLAlchemy que devuelve una CTE con
# (unidad_id, estrato); el cálculo la cruza con las poblaciones sin
# tocarlas (mart/estratos.py).
#
# expression "modulo.del.kit:funcion"
# unidad la unidad de los indicadores a los que sirve (`basis`)
# fechas lo que el estrato cruza con dim_fecha, si lo lee
# parametros sus reglas: parámetro de la consulta -> clave de parametros.toml (la
# función las recibe resueltas y entran a la huella del reporte)
# valores sus valores con su etiqueta, en orden, si no salen de otra regla
# etiqueta cómo se llama en pantalla (la leyenda, el selector de filtros); sin ella, su nombre
#
# Sección `comun`: para todos los proyectos; `<proyecto>`: solo ese, y
# gana sobre `comun` si se llaman igual.
[comun.grupo_edad]
etiqueta = "Grupo de edad"
expression = "comun.estratos.grupo_edad:estrato"
unidad = "paciente"
fechas = { hechos = ["v_persona.fecha_nacimiento"], parametros = ["periodo_inicio"] }
# Estatus de seguimiento ASCCP de la paciente (T-24c): `cacu/seguimiento.py`. Sus reglas son de
# `parametros.toml` (§2bis) y entran a la huella del reporte. Excluyente y exhaustivo: sin `sin_dato`.
[cacu.estatus_seguimiento]
etiqueta = "Estatus de seguimiento"
expression = "cacu.seguimiento:estrato"
unidad = "paciente"
valores = [
{ valor = "PRE_COLPOSCOPIA", etiqueta = "Pre colposcopia" },
{ valor = "POST_COLPOSCOPIA", etiqueta = "Post colposcopia" },
{ valor = "POST_TRATAMIENTO", etiqueta = "Post tratamiento" },
{ valor = "INFO_INSUFICIENTE", etiqueta = "Información insuficiente" },
]
[cacu.estatus_seguimiento.parametros]
seguimiento_marco = "cacu.seguimiento.marco"
seguimiento_referencia = "cacu.seguimiento.referencia"
seguimiento_precedencia = "cacu.seguimiento.precedencia"
seguimiento_evidencias = "cacu.seguimiento.colposcopia.evidencias"
seguimiento_requisito = "cacu.seguimiento.colposcopia.requisito"
seguimiento_biopsia_requisito = "cacu.seguimiento.colposcopia.biopsia_requisito"
seguimiento_cie_valoracion = "cacu.diagnostico.cie"
seguimiento_especialidades_valoracion = "cacu.diagnostico.especialidades"
seguimiento_horizonte_valoracion = "cacu.horizontes.toma_diagnostico_dias"
seguimiento_motivos = "cacu.seguimiento.colposcopia.motivos"
seguimiento_especialidades_colposcopia = "cacu.seguimiento.colposcopia.especialidades"
seguimiento_cie_colposcopia = "cacu.seguimiento.colposcopia.cie"
seguimiento_diagnosticos = "cacu.seguimiento.colposcopia.diagnosticos"
seguimiento_fuentes_tratamiento = "cacu.seguimiento.tratamiento.fuentes"
seguimiento_cie_tratamiento = "cacu.seguimiento.tratamiento.cie"
seguimiento_insuficiente = "cacu.seguimiento.insuficiente.regla"
seguimiento_especialidades_vigilancia = "cacu.seguimiento.vigilancia.especialidades"
+100
View File
@@ -0,0 +1,100 @@
"""Lo que cada motor escribe distinto, como una función con una regla por motor.
SQLAlchemy traduce la sintaxis, no las funciones de fecha. Aquí van las
que el kit necesita. Agregar un motor es agregar su regla; ninguna
definición cambia. Sin regla para un motor queda la forma neutra, que es
la que lee el registro de huellas y no se puede ejecutar. Solo la regla
de SQLite se ejecuta en las pruebas (D-S5).
"""
from sqlalchemy import Integer
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import FunctionElement
class dias_entre(FunctionElement):
"""Días enteros de `inicio` a `fin`: `dias_entre(inicio, fin)`."""
type = Integer()
inherit_cache = True
def _partes(elemento, compilador, opciones) -> tuple[str, str]:
inicio, fin = list(elemento.clauses)
return compilador.process(inicio, **opciones), compilador.process(fin, **opciones)
@compiles(dias_entre)
def _neutra(elemento, compilador, **opciones) -> str:
inicio, fin = _partes(elemento, compilador, opciones)
return f"dias_entre({inicio}, {fin})"
@compiles(dias_entre, "sqlite")
def _sqlite(elemento, compilador, **opciones) -> str:
inicio, fin = _partes(elemento, compilador, opciones)
return f"CAST(julianday({fin}) - julianday({inicio}) AS INTEGER)"
@compiles(dias_entre, "postgresql")
def _postgresql(elemento, compilador, **opciones) -> str:
inicio, fin = _partes(elemento, compilador, opciones)
return f"(CAST({fin} AS DATE) - CAST({inicio} AS DATE))"
@compiles(dias_entre, "mysql", "mariadb")
def _mysql(elemento, compilador, **opciones) -> str:
inicio, fin = _partes(elemento, compilador, opciones)
return f"DATEDIFF({fin}, {inicio})"
@compiles(dias_entre, "mssql")
def _mssql(elemento, compilador, **opciones) -> str:
inicio, fin = _partes(elemento, compilador, opciones)
return f"DATEDIFF(day, {inicio}, {fin})"
class entero_de_json(FunctionElement):
"""Un entero de un objeto JSON guardado como texto: `entero_de_json(columna, "clave")`.
PostgreSQL no aplica `->>` a `text` y SQL Server no tiene tipo JSON: cada
motor lee la clave con su propia función.
"""
type = Integer()
inherit_cache = True
def _columna_y_clave(elemento, compilador, opciones) -> tuple[str, str]:
columna, clave = list(elemento.clauses)
return compilador.process(columna, **opciones), clave.value
@compiles(entero_de_json)
def _entero_neutro(elemento, compilador, **opciones) -> str:
columna, clave = _columna_y_clave(elemento, compilador, opciones)
return f"entero_de_json({columna}, '{clave}')"
@compiles(entero_de_json, "sqlite")
def _entero_sqlite(elemento, compilador, **opciones) -> str:
columna, clave = _columna_y_clave(elemento, compilador, opciones)
return f"CAST(json_extract({columna}, '$.{clave}') AS INTEGER)"
@compiles(entero_de_json, "mysql", "mariadb")
def _entero_mysql(elemento, compilador, **opciones) -> str:
columna, clave = _columna_y_clave(elemento, compilador, opciones)
return f"CAST(JSON_UNQUOTE(JSON_EXTRACT({columna}, '$.{clave}')) AS SIGNED)"
@compiles(entero_de_json, "postgresql")
def _entero_postgresql(elemento, compilador, **opciones) -> str:
columna, clave = _columna_y_clave(elemento, compilador, opciones)
return f"CAST(CAST({columna} AS JSON) ->> '{clave}' AS INTEGER)"
@compiles(entero_de_json, "mssql")
def _entero_mssql(elemento, compilador, **opciones) -> str:
columna, clave = _columna_y_clave(elemento, compilador, opciones)
return f"CAST(JSON_VALUE({columna}, '$.{clave}') AS INT)"
+297
View File
@@ -0,0 +1,297 @@
"""La lista de seguimiento de CaCu (T-24d): `GET /cacu/seguimiento`, una fila por paciente.
El contrato es T-24a. Es una consulta al
vuelo sobre la plata, no un `measure_report`: no guarda nada. Entra cada paciente con al menos un
estudio (`cacu.seguimiento.estudios`) en la ventana de `meses` hasta el corte; por cada una, su
grupo de edad al corte, su estatus al corte (`cacu.seguimiento.estatus_al`, la misma regla del
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.** 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 json
import tomllib
from datetime import date, timedelta
from pathlib import Path
from types import SimpleNamespace
from sqlalchemy import func, select
from sqlmodel import Session
from webapi.follow_up.silver import citologias, notas
from webapi.follow_up.status import ESTATUS, estatus_al, exigir_opcion, exigir_opciones, reglas_de
from webapi.orchestration.tables.cacu import TABLAS
from webapi.follow_up.view import P
from webapi.orchestration.reference.age_groups import grupos_de_cortes
from webapi.orchestration.reference.rules import valor_de
from webapi.orchestration.tables import TablasKit
RAIZ = Path(__file__).resolve().parent # `estratos.toml` is next to this module
SIN_DATO = "sin_dato"
def leer_estrato(proyecto: str, nombre: str) -> SimpleNamespace:
"""The stratum's rules and values in `estratos.toml` (the project's, or the common one)."""
with open(RAIZ / "estratos.toml", "rb") as archivo:
secciones = tomllib.load(archivo)
for seccion in (proyecto, "comun"):
if nombre in secciones.get(seccion, {}):
entrada = secciones[seccion][nombre]
return SimpleNamespace(parametros=entrada.get("parametros", {}), valores=entrada.get("valores", []))
raise KeyError(f"No hay estrato {nombre!r} para {proyecto!r} en estratos.toml.")
def ejecutar(sesion: Session, consulta, parametros: dict):
"""Runs with the parameters the query names."""
nombrados = set(consulta.compile().params)
return sesion.execute(consulta, {n: v for n, v in parametros.items() if n in nombrados})
VENTANAS = (1, 3, 6, 12)
FECHAS_DE_ESTUDIO = ("toma", "reporte")
ESTUDIOS = ("citologia", "vph")
RESULTADOS_MOSTRADOS = ("ultimo", "mas_grave")
PAGINA_MAXIMA = 200
# Nombre en esta lista -> clave en `parametros.toml`.
PARAMETROS_DE_LA_LISTA = {
"ventana_meses": "cacu.seguimiento.ventana_meses",
"fecha_estudio": "cacu.seguimiento.fecha_estudio",
"estudios": "cacu.seguimiento.estudios",
"resultado_mostrado": "cacu.seguimiento.resultado_mostrado",
"grupos_edad": "cacu.grupos_edad",
"catalogo": "cacu.catalogos.citologia",
"cie_diagnostico": "cacu.diagnostico.cie",
"especialidades_diagnostico": "cacu.diagnostico.especialidades",
"cie_antecedente": "cacu.diagnostico.cie_antecedente",
"horizonte_dias": "cacu.horizontes.toma_diagnostico_dias",
}
ESTRATO = "estatus_seguimiento"
class PedidoInvalido(ValueError):
"""Un parámetro del pedido fuera de lo que admite el contrato (400)."""
class PaginaFuera(LookupError):
"""Una página mayor que la última, habiendo pacientes (404)."""
def seguimiento_de(
sesion: Session,
*,
corte: date | None = None,
meses: int | None = None,
estatus: str | None = None,
page: int = 1,
page_size: int = 50,
hoy: date | None = None,
tablas: TablasKit = TABLAS,
) -> dict:
"""La lista de seguimiento al `corte`, lista para `json.dumps` (contrato §2).
`corte` por omisión es `hoy`; en los dos casos se acota a la última fecha con datos de la plata.
`meses` por omisión es `cacu.seguimiento.ventana_meses`.
Raises:
PedidoInvalido: `meses`, `estatus`, `page` o `page_size` fuera de rango.
PaginaFuera: `page` mayor que la última página, habiendo pacientes.
ReglaDesconocida: una regla de `parametros.toml` con una opción que el código no sabe aplicar.
"""
lista = {nombre: valor_de(sesion, clave, tablas=tablas) for nombre, clave in PARAMETROS_DE_LA_LISTA.items()}
del_estatus = leer_estrato("cacu", ESTRATO).parametros
valores_estatus = {nombre: valor_de(sesion, clave, tablas=tablas) for nombre, clave in del_estatus.items()}
_validar_reglas(lista)
meses = lista["ventana_meses"] if meses is None else meses
if meses not in VENTANAS:
raise PedidoInvalido(f"meses = {meses!r}: se admite {list(VENTANAS)}.")
if estatus is not None and estatus not in ESTATUS:
raise PedidoInvalido(f"estatus desconocido {estatus!r}; hay {list(ESTATUS)}.")
if page < 1 or not 1 <= page_size <= PAGINA_MAXIMA:
raise PedidoInvalido(f"page empieza en 1 y page_size va de 1 a {PAGINA_MAXIMA}.")
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, tablas)
if estatus is not None:
items = [i for i in items if i["estatus"]["codigo"] == estatus]
total = len(items)
paginas = -(-total // page_size)
if total and page > paginas:
raise PaginaFuera(f"page {page} pasa de la última ({paginas}).")
etiquetas = _etiquetas_de_estatus()
return {
"simulado": True,
"corte": corte.isoformat(),
"ventana": {"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()},
"filtros": {"estatus": estatus},
"estatus_disponibles": [{"codigo": c, "etiqueta": e} for c, e in etiquetas.items()],
"reglas": _reglas_usadas(sesion, [*PARAMETROS_DE_LA_LISTA.values(), *del_estatus.values()], tablas),
"paginacion": {"page": page, "page_size": page_size, "total_items": total, "total_pages": paginas},
"items": items[(page - 1) * page_size : page * page_size],
}
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:
exigir_opcion("cacu.seguimiento.ventana_meses", lista["ventana_meses"], VENTANAS)
exigir_opcion("cacu.seguimiento.fecha_estudio", lista["fecha_estudio"], FECHAS_DE_ESTUDIO)
exigir_opciones("cacu.seguimiento.estudios", lista["estudios"], ESTUDIOS)
exigir_opcion("cacu.seguimiento.resultado_mostrado", lista["resultado_mostrado"], RESULTADOS_MOSTRADOS)
def _acotado(sesion: Session, corte: date, tablas: TablasKit) -> date:
"""El corte, sin pasar de la última fecha con datos de la plata (si hay datos)."""
ultima = sesion.execute(select(func.max(tablas.Procedimiento.fecha))).scalar()
return corte if ultima is None else min(corte, _fecha(ultima))
def _estatus_al_corte(sesion: Session, corte: date, valores: dict) -> dict[int, str]:
cte = estatus_al(P("corte_seguimiento"), reglas_de(valores), incluye_referencia=True)
filas = ejecutar(sesion, select(cte.c.pac_id, cte.c.estatus), {**valores, "corte_seguimiento": corte.isoformat()})
return {pac_id: estatus for pac_id, estatus in filas}
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]] = {}
for e in estudios:
if desde <= e["fecha"] <= corte:
de_la_paciente = en_ventana.setdefault(e["pac_id"], {"citologia": [], "vph": []})
if "citologia" in lista["estudios"]:
de_la_paciente["citologia"].append(e)
if "vph" in lista["estudios"] and e["vph"] is not None:
de_la_paciente["vph"].append(e)
gravedad = {c["clave"]: i for i, c in enumerate(lista["catalogo"])}
edades = _grupo_de_edad(sesion, corte, lista["grupos_edad"], tablas)
notas_de = _notas_por_paciente(sesion, corte)
items = []
for pac_id, de_la_paciente in en_ventana.items():
if not de_la_paciente["citologia"] and not de_la_paciente["vph"]:
continue
cito = _mostrada(de_la_paciente["citologia"], lista["resultado_mostrado"], gravedad)
vph = max(de_la_paciente["vph"], key=lambda e: e["fecha"], default=None)
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({
"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 {
"fecha": cito["fecha"].isoformat(), "bethesda": cito["resultado"], "calidad": cito["calidad"],
},
"ultimo_vph": None if vph is None else {
"fecha": vph["fecha"].isoformat(), "resultado": vph["vph"],
"genotipo_16_18": None if vph["genotipo_16_18"] is None else bool(vph["genotipo_16_18"]),
},
"dias_toma_diagnostico": None if cito is None else _dias_a_la_valoracion(cito, notas_de, lista),
"prioridad": None,
"_orden": mas_reciente,
})
items.sort(key=lambda i: int(i["pac_id"]))
items.sort(key=lambda i: i.pop("_orden"), reverse=True)
return items
def _estudios(sesion: Session, corte: date, fecha_estudio: str) -> list[dict]:
"""Cada toma de citología hasta el corte, con lo que ya se sabía al corte (un resultado posterior no existe)."""
c = citologias()
filas = sesion.execute(select(
c.c.pac_id, c.c.fecha_toma, c.c.fecha_reporte, c.c.calidad_muestra, c.c.resultado, c.c.vph, c.c.genotipo_16_18,
)).all()
estudios = []
for pac_id, toma, reporte, calidad, resultado, vph, genotipo in filas:
toma, reporte = _fecha(toma), None if reporte is None else _fecha(reporte)
conocido = reporte is not None and reporte <= corte
fecha = toma if fecha_estudio == "toma" else reporte
if fecha is None or toma > corte or (fecha_estudio == "reporte" and not conocido):
continue
estudios.append({
"pac_id": pac_id, "fecha": fecha, "toma": toma, "calidad": calidad,
"resultado": resultado if conocido else None,
"vph": vph if conocido else None, "genotipo_16_18": genotipo if conocido else None,
})
return estudios
def _mostrada(citologias_: list[dict], resultado_mostrado: str, gravedad: dict[str, int]) -> dict | None:
if not citologias_:
return None
if resultado_mostrado == "ultimo":
return max(citologias_, key=lambda e: e["fecha"])
return max(citologias_, key=lambda e: (gravedad.get(e["resultado"], -1), e["fecha"]))
def _grupo_de_edad(sesion: Session, corte: date, cortes, tablas: TablasKit) -> dict[int, str]:
"""El grupo de edad de cada paciente con fecha de nacimiento, con la edad cumplida al corte."""
grupos = grupos_de_cortes(cortes, tablas=tablas)
edades = {}
for pac_id, nacimiento in sesion.execute(select(tablas.Persona.pac_id, tablas.Persona.fecha_nacimiento)):
if nacimiento is None:
continue
nacimiento = _fecha(nacimiento)
edad = corte.year - nacimiento.year - ((corte.month, corte.day) < (nacimiento.month, nacimiento.day))
edades[pac_id] = next((g.etiqueta for g in grupos if g.edad_min <= edad <= g.edad_max), SIN_DATO)
return edades
def _notas_por_paciente(sesion: Session, corte: date) -> dict[int, list[tuple[date, str, str]]]:
n = notas()
de = {}
filas = sesion.execute(select(n.c.pac_id, n.c.fecha, n.c.cie_codigo, n.c.especialidad))
for pac_id, fecha, cie, especialidad in filas:
if fecha is not None and _fecha(fecha) <= corte:
de.setdefault(pac_id, []).append((_fecha(fecha), cie, especialidad))
return de
def _dias_a_la_valoracion(cito: dict, notas_de: dict, lista: dict) -> int | None:
"""Días de la toma a la primera nota que la resuelve, con las reglas de CACU_DIAS_TOMA_DIAGNOSTICO; nulo si aún no.
También nulo si la paciente ya tenía un diagnóstico de cáncer antes de la toma: esa toma no se mide.
"""
toma, propias = cito["toma"], notas_de.get(cito["pac_id"], [])
if any(f < toma and cie in lista["cie_antecedente"] for f, cie, _ in propias):
return None
dias = [
(f - toma).days for f, cie, especialidad in propias
if f > toma and (f - toma).days < lista["horizonte_dias"]
and cie in lista["cie_diagnostico"] and especialidad in lista["especialidades_diagnostico"]
]
return min(dias, default=None)
def _reglas_usadas(sesion: Session, claves: list[str], tablas: TablasKit) -> list[dict]:
filas = [sesion.get(tablas.DefParametro, clave) for clave in dict.fromkeys(claves)]
return [{"clave": f.clave, "valor": json.loads(f.valor), "estado": f.estado} for f in filas if f is not None]
def _etiquetas_de_estatus() -> dict[str, str]:
"""Código -> etiqueta, en orden de presentación: los `valores` del estrato en `estratos.toml`."""
return {v["valor"]: v["etiqueta"] for v in leer_estrato("cacu", ESTRATO).valores}
def _meses_antes(fecha: date, meses: int) -> date:
"""La misma fecha `meses` meses antes; si ese mes es más corto, su último día."""
total = fecha.year * 12 + fecha.month - 1 - meses
anio, mes = divmod(total, 12)
return date(anio, mes + 1, min(fecha.day, calendar.monthrange(anio, mes + 1)[1]))
def _fecha(valor) -> date:
"""Una fecha de la base, venga como `date` o como texto ISO (SQLite)."""
return valor if isinstance(valor, date) else date.fromisoformat(str(valor)[:10])
+110
View File
@@ -0,0 +1,110 @@
"""Bloques de consulta sobre la plata de dos tablas (F5, ADR-MD-007).
Una consulta de indicador no escribe a mano los `JOIN` entre `procedimiento` y
`observacion`: pide un **pivote**, una fila por procedimiento de un estudio y una
clase, con una columna por resultado del catálogo. El valor de cada columna sale de
la columna de `observacion` que le toca según `tipo_valor`:
codigo valor_id, o el texto tal como llegó si no está en el catálogo (valor_fuente)
booleano valor_numerico, como entero (0 o 1)
numero valor_numerico
fecha valor_fecha
texto valor_texto
externo valor_texto
Las fechas salen sin tipo (`sin_tipo`), como en las vistas por tipo, para que los parámetros
de periodo se liguen igual que antes. Con eso, el vocabulario de cada proyecto (`<p>/consultas/plata.py`) se rearma como
CTE, sin vistas en la base: las dos tablas ya son el estado actual (sin versiones de
fila). Solo se arman expresiones de SQLAlchemy; no se lee ni se escribe nada.
"""
from collections.abc import Mapping
from functools import cache
from sqlalchemy import Integer, Subquery, and_, case, cast, func, select, type_coerce
from sqlalchemy.types import NullType
from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo
from webapi.orchestration.tables import PROJECTS, TablasKit, tablas_de
COLUMNAS_DEL_PROCEDIMIENTO = ("procedimiento_id", "padre_id", "pac_id", "fecha", "fuente_tabla", "fuente_id")
class TipoDeResultadoAmbiguo(ValueError):
"""Un mismo `resultado_id` con dos `tipo_valor` distintos en dos catálogos."""
@cache
def tipos_de_resultado() -> dict[str, str]:
"""`resultado_id` -> `tipo_valor`, de los catálogos de los tres proyectos (deben coincidir donde se repiten)."""
tipos: dict[str, str] = {}
for proyecto in PROJECTS:
for resultado in catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas_de(proyecto)).resultados:
previo = tipos.setdefault(resultado.resultado_id, resultado.tipo_valor)
if previo != resultado.tipo_valor:
raise TipoDeResultadoAmbiguo(f"{resultado.resultado_id}: {previo} y {resultado.tipo_valor}.")
return tipos
def sin_tipo(columna):
"""Una fecha sin tipo de SQLAlchemy, como las columnas de las vistas por tipo (`consultas.vista.vista`).
Así un parámetro de la definición (`P("periodo_inicio")`) se liga como lo da el cálculo (texto ISO)
y no como `Date`, y las consultas de los indicadores comparan fechas igual que antes (T-18r).
"""
return type_coerce(columna, NullType()).label(columna.key) if hasattr(columna, "key") else type_coerce(columna, NullType())
def valor(observacion, tipo_valor: str):
"""La expresión del valor de una observación según su tipo."""
if tipo_valor == "codigo":
return func.coalesce(observacion.c.valor_id, observacion.c.valor_fuente)
if tipo_valor == "booleano":
return cast(observacion.c.valor_numerico, Integer)
if tipo_valor == "numero":
return observacion.c.valor_numerico
if tipo_valor == "fecha":
return sin_tipo(observacion.c.valor_fecha)
return observacion.c.valor_texto
def pivote(
tablas: TablasKit, estudio_id: str, clase: str, resultados: Mapping[str, str | tuple[str, str]] | None = None, *,
nombre: str | None = None, columnas: tuple[str, ...] = (),
) -> Subquery:
"""Una fila por procedimiento del estudio y la clase, con una columna por resultado.
`resultados`: nombre de la columna -> `resultado_id` (`{"resultado": "citologia.bethesda"}`), o
-> `(resultado_id, columna)` para leer una columna de `observacion` en particular
(`("nota_medica.especialidad", "valor_id")`: el código, nulo si no se reconoció).
Las columnas del procedimiento van siempre: `procedimiento_id`, `padre_id`, `pac_id`,
`fecha`, `fuente_tabla` y `fuente_id`, más las de `columnas` (`("orden_numero",)`). Un resultado
sin observación da nulo.
"""
resultados = dict(resultados or {})
p = tablas.Procedimiento.__table__
o = tablas.Observacion.__table__.alias(f"o_{estudio_id}_{clase}")
tipos = tipos_de_resultado()
columnas = [sin_tipo(p.c[c]) if c == "fecha" else p.c[c] for c in (*COLUMNAS_DEL_PROCEDIMIENTO, *columnas)]
if not resultados:
consulta = select(*columnas).where(p.c.estudio_id == estudio_id, p.c.clase == clase)
return consulta.subquery(nombre or f"{estudio_id}_{clase}")
pares = {columna: r if isinstance(r, tuple) else (r, None) for columna, r in resultados.items()}
pivoteadas = [
func.max(case((o.c.resultado_id == resultado_id,
o.c[especifica] if especifica else valor(o, tipos[resultado_id])))).label(columna)
for columna, (resultado_id, especifica) in pares.items()
]
consulta = (
select(*columnas, *pivoteadas)
.select_from(p.outerjoin(o, and_(o.c.procedimiento_id == p.c.procedimiento_id,
o.c.resultado_id.in_([r for r, _ in pares.values()]))))
.where(p.c.estudio_id == estudio_id, p.c.clase == clase)
.group_by(*(p.c[c.key] if c.key == "fecha" else c for c in columnas))
)
return consulta.subquery(nombre or f"{estudio_id}_{clase}")
def hijos_de(padre: Subquery, hijo: Subquery):
"""La condición de unión de un procedimiento con sus hijos (el reporte con su toma)."""
return hijo.c.padre_id == padre.c.procedimiento_id
@@ -3,8 +3,9 @@
GET /cacu/seguimiento?corte=AAAA-MM-DD&meses=&estatus=&page=&page_size=
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. La lista la arma el kit (`indicadores_kit.serving.seguimiento`); aquí solo se valida,
se abre la sesión y se traducen los errores.
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
@@ -15,32 +16,31 @@ from collections.abc import Callable
from datetime import date
from flask import Blueprint, Response, jsonify, request
from indicadores_kit.serving.seguimiento import PaginaFuera, PedidoInvalido, seguimiento_de
from webapi.follow_up.listing import PaginaFuera, PedidoInvalido, seguimiento_de
from sqlmodel import Session
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
SAL_POR_OMISION = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno
def en_dev() -> bool:
def in_dev() -> bool:
"""Obsoleta: las rutas por paciente ya no dependen de `DEV_REVISION` y nada la llama. Se quitará."""
warnings.warn("en_dev() está obsoleta: las rutas por paciente se registran siempre", DeprecationWarning, stacklevel=2)
warnings.warn("in_dev() está obsoleta: las rutas por paciente se registran siempre", DeprecationWarning, stacklevel=2)
return bool(os.environ.get("DEV_REVISION"))
def blueprint_de_seguimiento(get_session: Callable[[], Session]) -> Blueprint:
def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
"""El blueprint de la lista, para registrarlo con `url_prefix="/cacu"`."""
blueprint = Blueprint("cacu_seguimiento", __name__)
@blueprint.get("/seguimiento")
def get_seguimiento():
try:
pedido = _pedido(request.args)
pedido = _requested(request.args)
except ValueError as error:
return jsonify({"error": str(error)}), 400
sesion = get_session()
try:
cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", SAL_POR_OMISION), **pedido)
cuerpo = seguimiento_de(sesion, **pedido)
except PedidoInvalido as error:
return jsonify({"error": str(error)}), 400
except PaginaFuera as error:
@@ -52,7 +52,7 @@ def blueprint_de_seguimiento(get_session: Callable[[], Session]) -> Blueprint:
return blueprint
def _pedido(args) -> dict:
def _requested(args) -> dict:
"""Los parámetros de la consulta, con su tipo. `ValueError` si uno viene mal escrito."""
pedido = {}
if corte := args.get("corte"):
+99
View File
@@ -0,0 +1,99 @@
"""El vocabulario de CaCu sobre la plata de dos tablas (F5, ADR-MD-007): citologías, biopsias, notas y órdenes.
Lo que leen las familias reescritas, armado con `plata.consultas.pivote` como subconsultas
(sin vistas en la base). Los nombres de columna son los del concepto, no los de una tabla
por tipo: `fecha_toma`, `resultado`, `grado`. Cada uno lleva `procedimiento_id` y
`pac_id`; los que cuelgan de una toma llevan también la de su toma.
"""
from sqlalchemy import Subquery, select
from webapi.orchestration.tables.cacu import TABLAS
from webapi.follow_up.pivot import hijos_de, pivote
from webapi.orchestration.tables import TablasKit
def citologias(tablas: TablasKit = TABLAS) -> Subquery:
"""Una fila por citología tomada, con su calidad, su resultado (Bethesda) y su VPH si ya los tiene.
Lo mismo que la vista por tipo `v_citologia_con_resultado`, desde las dos tablas.
"""
toma = pivote(tablas, "citologia", "toma", {"calidad_muestra": "citologia.calidad_muestra"},
columnas=("orden_numero",), nombre="toma_citologia")
reporte = pivote(tablas, "citologia", "reporte", {"resultado": "citologia.bethesda"}, nombre="reporte_citologia")
vph = pivote(tablas, "vph", "reporte", {
"vph": "vph.resultado", "genotipo_16_18": "vph.genotipo_16_18",
"genotipo_16": "vph.genotipo_16", "genotipo_18": "vph.genotipo_18",
}, nombre="reporte_vph")
return select(
toma.c.procedimiento_id, toma.c.fuente_tabla, toma.c.fuente_id, toma.c.pac_id,
toma.c.fecha.label("fecha_toma"), toma.c.calidad_muestra, toma.c.orden_numero,
reporte.c.fecha.label("fecha_reporte"), reporte.c.resultado,
vph.c.vph, vph.c.genotipo_16_18, vph.c.genotipo_16, vph.c.genotipo_18,
).select_from(
toma.outerjoin(reporte, hijos_de(toma, reporte)).outerjoin(vph, hijos_de(toma, vph))
).subquery("citologias")
def biopsias(tablas: TablasKit = TABLAS) -> Subquery:
"""Una fila por biopsia reportada, con su grado, su solicitud y la citología que la originó (si se encontró).
Desde T-22h la biopsia es una orden (`biopsia`, `orden`: la solicitud, con su fecha y su número de orden)
y su reporte, una hija de ella: la toma queda dos niveles arriba (toma, orden, reporte).
"""
reporte = pivote(tablas, "biopsia", "reporte", {"grado": "biopsia.grado"}, nombre="reporte_biopsia")
orden = pivote(tablas, "biopsia", "orden", columnas=("orden_numero",), nombre="orden_biopsia")
toma = pivote(tablas, "citologia", "toma", nombre="toma_de_la_biopsia")
return select(
reporte.c.procedimiento_id, reporte.c.fuente_tabla, reporte.c.fuente_id, reporte.c.pac_id,
reporte.c.fecha.label("fecha_reporte"), reporte.c.grado, orden.c.fecha.label("fecha_solicitud"), orden.c.orden_numero,
toma.c.procedimiento_id.label("toma_id"), toma.c.pac_id.label("toma_pac_id"), toma.c.fecha.label("fecha_toma"),
).select_from(
reporte.outerjoin(orden, hijos_de(orden, reporte)).outerjoin(toma, hijos_de(toma, orden))
).subquery("biopsias")
def notas(tablas: TablasKit = TABLAS) -> Subquery:
"""Una fila por nota médica: su fecha, su CIE-10 y la especialidad que la escribió (código; nulo si no se reconoció)."""
nota = pivote(tablas, "nota_medica", "encuentro", {
"cie_codigo": "nota_medica.diagnostico",
"especialidad": ("nota_medica.especialidad", "valor_id"),
"especialidad_fuente": ("nota_medica.especialidad", "valor_fuente"),
}, nombre="nota_medica")
return select(
nota.c.procedimiento_id, nota.c.fuente_tabla, nota.c.fuente_id, nota.c.pac_id, nota.c.fecha,
nota.c.cie_codigo, nota.c.especialidad, nota.c.especialidad_fuente,
).subquery("notas")
def notas_con_textos(tablas: TablasKit = TABLAS) -> Subquery:
"""Las notas con su motivo de consulta y su diagnóstico en texto (tal como llegan) y su identificador del hospital.
Aparte de `notas` para no mover la huella de las definiciones que ya la leen (T-24b, T-24c).
"""
nota = pivote(tablas, "nota_medica", "encuentro", {
"cie_codigo": "nota_medica.diagnostico",
"especialidad": ("nota_medica.especialidad", "valor_id"),
"motivo": "nota_medica.motivo",
"diagnostico_texto": "nota_medica.diagnostico_texto",
}, columnas=("id_hospital",), nombre="nota_con_textos")
return select(
nota.c.procedimiento_id, nota.c.pac_id, nota.c.fecha, nota.c.cie_codigo, nota.c.especialidad,
nota.c.motivo, nota.c.diagnostico_texto, nota.c.id_hospital,
).subquery("notas_con_textos")
def ordenes_de_biopsia(tablas: TablasKit = TABLAS) -> Subquery:
"""Una fila por biopsia solicitada (la orden, con o sin reporte; T-22h): de quién y la fecha de la solicitud."""
orden = pivote(tablas, "biopsia", "orden", nombre="orden_de_biopsia")
return select(orden.c.procedimiento_id, orden.c.pac_id, orden.c.fecha).subquery("ordenes_de_biopsia")
def tomas_con_especialidad(tablas: TablasKit = TABLAS) -> Subquery:
"""Una fila por citología tomada, con la especialidad de la orden de la que cuelga (nula si no tiene o no se reconoce)."""
toma = pivote(tablas, "citologia", "toma", nombre="toma_con_especialidad")
orden = pivote(tablas, "citologia", "orden", {"especialidad": ("orden.especialidad", "valor_id")},
nombre="orden_de_la_toma")
return select(toma.c.procedimiento_id, toma.c.pac_id, toma.c.fecha, orden.c.especialidad).select_from(
toma.outerjoin(orden, hijos_de(orden, toma))
).subquery("tomas_con_especialidad")
+281
View File
@@ -0,0 +1,281 @@
"""El estatus de seguimiento ASCCP de cada paciente a una fecha (T-24c; plan de seguimiento, §5.2).
`estatus_al(referencia, reglas)` es la única regla: una CTE `(pac_id, estatus)` con un renglón
por persona. La usan el estrato `estatus_seguimiento` (`estrato`, a la referencia de cada
reporte), la lista de seguimiento (T-24d, al corte que pida el dashboard) y las cohortes (a su
fecha índice). Mira solo lo ocurrido antes de la referencia, así que el estatus de un periodo
pasado no cambia cuando la paciente avanza.
POST_TRATAMIENTO una nota con un CIE-10 de tratamiento, posterior a su primera colposcopia
POST_COLPOSCOPIA alguna evidencia de colposcopia (`EVIDENCIAS`); una nota de colposcopia cuenta si
es de «Clínica de la Mujer y Colposcopia» y, por regla, posterior a una cita de
valoración (la nota que resuelve una toma, como en CACU_DIAS_TOMA_DIAGNOSTICO); una
orden o una biopsia, por regla, si es del mismo día que una nota de colposcopia (la
colposcopia es la madre de la biopsia)
INFO_INSUFICIENTE la historia no alcanza (`cacu.seguimiento.insuficiente.regla`); también el resto
PRE_COLPOSCOPIA ninguna de las anteriores y, si se conoce la especialidad de sus citologías,
alguna es de vigilancia
Ninguna regla está escrita aquí: todas son de `parametros.toml` (`cacu.seguimiento.*`, §2bis); qué
parámetro de la consulta es qué clave lo declara `estratos.toml` (`[cacu.estatus_seguimiento.parametros]`),
y llegan como `reglas`. Las listas (CIE-10, especialidades, evidencias) van ligadas como
parámetros (S-K76); los textos del motivo y del diagnóstico se comparan por contención, en
mayúsculas y sin acentos; la precedencia, la referencia y la regla de insuficiente arman la
consulta. Una opción que el código no sabe aplicar falla con `ReglaDesconocida`.
"""
import unicodedata
from collections.abc import Mapping
from dataclasses import dataclass
from sqlalchemy import (
CTE, ColumnElement, and_, bindparam, case, exists, func, literal, literal_column, or_, select, union_all,
)
from webapi.follow_up.silver import biopsias, notas_con_textos, ordenes_de_biopsia, tomas_con_especialidad
from webapi.orchestration.tables.cacu import TABLAS
from webapi.follow_up.functions import dias_entre
from webapi.follow_up.view import P, vista
from webapi.orchestration.tables import TablasKit
ESTATUS = ("POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA")
RESTO = "INFO_INSUFICIENTE" # quien no cumple ninguno: el estrato es exhaustivo (§5.3)
MARCOS = ("estatus", "ronda")
REFERENCIAS = {"inicio_periodo": "periodo_inicio", "fecha_corte": "fecha_corte"} # opción -> parámetro del reporte
EVIDENCIAS = ("motivo", "cie", "diagnostico_texto", "orden_biopsia", "biopsia")
FUENTES_DE_TRATAMIENTO = ("nota_posterior_a_colposcopia",)
REGLAS_DE_INSUFICIENTE = ("inicio_datos_posterior_a_alta", "sin_alta_registrada", "ambos", "nunca")
REQUISITOS_DE_COLPOSCOPIA = ("valoracion_previa", "ninguno")
REQUISITOS_DE_BIOPSIA = ("mismo_dia_que_colposcopia", "ninguno")
V_PERSONA = vista("v_persona", "pac_id")
SIN_ACENTO = {"Á": "A", "É": "E", "Í": "I", "Ó": "O", "Ú": "U", "Ü": "U", "á": "a", "é": "e", "í": "i", "ó": "o",
"ú": "u", "ü": "u"} # fmt: skip
class ReglaDesconocida(ValueError):
"""Una regla de `cacu.seguimiento.*` con una opción que el código no sabe aplicar."""
@dataclass(frozen=True)
class Reglas:
"""Las reglas que dan forma a la consulta, ya validadas. Las listas no van aquí: se ligan al ejecutar."""
referencia: str # el parámetro del reporte: `periodo_inicio` o `fecha_corte`
precedencia: tuple[str, ...]
motivos: tuple[str, ...] # normalizados
diagnosticos: tuple[str, ...] # normalizados
insuficiente: str
valoracion_previa: bool # una nota de colposcopia cuenta solo después de una cita de valoración
biopsia_mismo_dia: bool # la orden y la biopsia cuentan solo el día de una nota de colposcopia
def reglas_de(valores: Mapping) -> Reglas:
"""Valida las reglas (`{parámetro de la consulta: valor}`, los de `estratos.toml`) contra las opciones admitidas."""
exigir_opciones("cacu.seguimiento.marco", valores["seguimiento_marco"], MARCOS)
if "estatus" not in valores["seguimiento_marco"]:
raise ReglaDesconocida("cacu.seguimiento.marco no incluye «estatus»: el estrato no se publica.")
if "ronda" in valores["seguimiento_marco"]:
raise ReglaDesconocida("cacu.seguimiento.marco: «ronda» (UE) todavía no se sabe aplicar.")
exigir_opcion("cacu.seguimiento.referencia", valores["seguimiento_referencia"], tuple(REFERENCIAS))
precedencia = tuple(valores["seguimiento_precedencia"])
if sorted(precedencia) != sorted(ESTATUS):
raise ReglaDesconocida(
f"cacu.seguimiento.precedencia debe ordenar los cuatro estatus, sin repetir: {ESTATUS}; "
f"llegó {precedencia}."
)
exigir_opciones("cacu.seguimiento.colposcopia.evidencias", valores["seguimiento_evidencias"], EVIDENCIAS)
exigir_opciones(
"cacu.seguimiento.tratamiento.fuentes", valores["seguimiento_fuentes_tratamiento"], FUENTES_DE_TRATAMIENTO
)
exigir_opcion("cacu.seguimiento.insuficiente.regla", valores["seguimiento_insuficiente"], REGLAS_DE_INSUFICIENTE)
exigir_opcion("cacu.seguimiento.colposcopia.requisito", valores["seguimiento_requisito"], REQUISITOS_DE_COLPOSCOPIA)
exigir_opcion(
"cacu.seguimiento.colposcopia.biopsia_requisito",
valores["seguimiento_biopsia_requisito"],
REQUISITOS_DE_BIOPSIA,
)
return Reglas(
referencia=REFERENCIAS[valores["seguimiento_referencia"]],
precedencia=precedencia,
motivos=tuple(normalizado(m) for m in valores["seguimiento_motivos"]),
diagnosticos=tuple(normalizado(d) for d in valores["seguimiento_diagnosticos"]),
insuficiente=valores["seguimiento_insuficiente"],
valoracion_previa=valores["seguimiento_requisito"] == "valoracion_previa",
biopsia_mismo_dia=valores["seguimiento_biopsia_requisito"] == "mismo_dia_que_colposcopia",
)
def estrato(valores: Mapping) -> CTE:
"""El estrato `estatus_seguimiento` (`estratos.toml`): `(unidad_id, estrato)`, a la referencia del reporte."""
reglas = reglas_de(valores)
estatus = estatus_al(P(reglas.referencia), reglas, incluye_referencia=reglas.referencia == "fecha_corte")
return select(estatus.c.pac_id.label("unidad_id"), estatus.c.estatus.label("estrato")).cte(
"estrato_estatus_seguimiento"
)
def estatus_al(
referencia: ColumnElement, reglas: Reglas, *, incluye_referencia: bool = False, tablas: TablasKit = TABLAS
) -> CTE:
"""La CTE `(pac_id, estatus)`: un renglón por persona, con lo ocurrido antes de `referencia`.
`referencia` es una fecha de SQL (un parámetro: `P("periodo_inicio")`, `P("corte")`). Con
`incluye_referencia`, cuenta también lo de ese día (un corte); sin él, solo lo anterior (el inicio
de un periodo). Los parámetros `seguimiento_*` de las listas se ligan al ejecutar.
"""
def antes(fecha) -> ColumnElement:
return fecha <= referencia if incluye_referencia else fecha < referencia
nota, orden, reporte, toma = (
notas_con_textos(tablas), ordenes_de_biopsia(tablas), biopsias(tablas), tomas_con_especialidad(tablas)
)
# La cita de valoración: la nota que resuelve una toma, con las reglas de CACU_DIAS_TOMA_DIAGNOSTICO.
valoracion = (
select(nota.c.pac_id, func.min(nota.c.fecha).label("primera"))
.select_from(nota.join(toma, toma.c.pac_id == nota.c.pac_id))
.where(
antes(nota.c.fecha),
nota.c.fecha > toma.c.fecha,
dias_entre(toma.c.fecha, nota.c.fecha) < P("seguimiento_horizonte_valoracion"),
nota.c.cie_codigo.in_(P("seguimiento_cie_valoracion", lista=True)),
nota.c.especialidad.in_(P("seguimiento_especialidades_valoracion", lista=True)),
)
.group_by(nota.c.pac_id)
.cte("seguimiento_valoracion")
)
# Una nota de colposcopia: de su especialidad y, por regla, posterior a la primera valoración.
de_colposcopia = and_(
antes(nota.c.fecha),
nota.c.especialidad.in_(P("seguimiento_especialidades_colposcopia", lista=True)),
nota.c.fecha > valoracion.c.primera if reglas.valoracion_previa else _siempre(),
)
con_valoracion = nota.outerjoin(valoracion, valoracion.c.pac_id == nota.c.pac_id)
# Los días con una nota de colposcopia válida: la orden de biopsia se expide ese día (su madre).
visitas = select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where(de_colposcopia).cte(
"seguimiento_visitas_de_colposcopia"
)
def de_una_visita(pac_id, fecha) -> ColumnElement:
if not reglas.biopsia_mismo_dia:
return _siempre()
return exists().where(visitas.c.pac_id == pac_id, visitas.c.fecha == fecha)
evidencias = union_all(
select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where(
_habilitada("motivo"), de_colposcopia, _contiene(nota.c.motivo, reglas.motivos, "motivo")
),
select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where(
_habilitada("cie"), de_colposcopia, nota.c.cie_codigo.in_(P("seguimiento_cie_colposcopia", lista=True)),
),
select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where(
_habilitada("diagnostico_texto"), de_colposcopia,
_contiene(nota.c.diagnostico_texto, reglas.diagnosticos, "diagnostico"),
),
select(orden.c.pac_id, orden.c.fecha).where(
_habilitada("orden_biopsia"), antes(orden.c.fecha), de_una_visita(orden.c.pac_id, orden.c.fecha)
),
select(reporte.c.pac_id, reporte.c.fecha_reporte.label("fecha")).where(
_habilitada("biopsia"), antes(reporte.c.fecha_reporte),
de_una_visita(reporte.c.pac_id, reporte.c.fecha_solicitud),
),
).subquery("evidencias_de_colposcopia")
colposcopia = (
select(evidencias.c.pac_id, func.min(evidencias.c.fecha).label("primera"))
.group_by(evidencias.c.pac_id)
.cte("seguimiento_colposcopia")
)
tratamiento = (
select(nota.c.pac_id)
.distinct()
.select_from(nota.join(colposcopia, colposcopia.c.pac_id == nota.c.pac_id))
.where(
antes(nota.c.fecha),
nota.c.fecha > colposcopia.c.primera,
nota.c.cie_codigo.in_(P("seguimiento_cie_tratamiento", lista=True)),
)
.cte("seguimiento_tratamiento")
)
# Fuera de vigilancia: todas sus citologías tienen especialidad conocida y ninguna es de vigilancia.
de_vigilancia = or_(
toma.c.especialidad.is_(None), toma.c.especialidad.in_(P("seguimiento_especialidades_vigilancia", lista=True))
)
fuera_de_vigilancia = (
select(toma.c.pac_id)
.where(antes(toma.c.fecha))
.group_by(toma.c.pac_id)
.having(func.sum(case((de_vigilancia, 1), else_=0)) == 0)
.cte("seguimiento_fuera_de_vigilancia")
)
persona = V_PERSONA
cumple = {
"POST_TRATAMIENTO": tratamiento.c.pac_id.is_not(None),
"POST_COLPOSCOPIA": colposcopia.c.pac_id.is_not(None),
"INFO_INSUFICIENTE": _insuficiente(reglas.insuficiente),
"PRE_COLPOSCOPIA": fuera_de_vigilancia.c.pac_id.is_(None),
}
estatus = case(*((cumple[e], literal(e)) for e in reglas.precedencia), else_=literal(RESTO))
return (
select(persona.c.pac_id, estatus.label("estatus"))
.select_from(
persona.outerjoin(tratamiento, tratamiento.c.pac_id == persona.c.pac_id)
.outerjoin(colposcopia, colposcopia.c.pac_id == persona.c.pac_id)
.outerjoin(fuera_de_vigilancia, fuera_de_vigilancia.c.pac_id == persona.c.pac_id)
)
.cte("seguimiento_estatus")
)
def normalizado(texto: str) -> str:
"""Un texto para comparar: sin espacios al borde, sin acentos y en mayúsculas (la Ñ se queda)."""
return "".join(SIN_ACENTO.get(c, c) for c in unicodedata.normalize("NFC", texto.strip())).upper()
def _normalizado_sql(columna: ColumnElement) -> ColumnElement:
"""`normalizado` en SQL: sin acentos (antes de `upper`, que en SQLite solo sabe ASCII) y en mayúsculas."""
for con, sin in SIN_ACENTO.items():
columna = func.replace(columna, con, sin)
return func.upper(columna)
def _contiene(columna: ColumnElement, textos: tuple[str, ...], nombre: str) -> ColumnElement:
"""La columna, normalizada, contiene alguno de los textos (ya normalizados). Sin textos, nunca."""
if not textos:
return _nunca()
normal = _normalizado_sql(columna)
return or_(*(normal.contains(bindparam(f"seguimiento_{nombre}_{i}", t)) for i, t in enumerate(textos)))
def _habilitada(evidencia: str) -> ColumnElement:
"""La evidencia está en `cacu.seguimiento.colposcopia.evidencias` (ligada al ejecutar)."""
return literal(evidencia).in_(P("seguimiento_evidencias", lista=True))
def _insuficiente(regla: str) -> ColumnElement:
"""La regla de historia insuficiente. Hoy no hay fecha de alta (usuario, 2026-10-22): se asume posterior al
inicio de los datos, así que `inicio_datos_posterior_a_alta` no marca a nadie y `sin_alta_registrada`, a todas."""
return _siempre() if regla in ("sin_alta_registrada", "ambos") else _nunca()
def _siempre() -> ColumnElement:
"""Una condición verdadera. No `true()`: SQL Server la escribe como `1`, que no es condición."""
return literal_column("1") == literal_column("1")
def _nunca() -> ColumnElement:
"""Una condición falsa (ver `_siempre`)."""
return literal_column("1") == literal_column("0")
def exigir_opcion(clave: str, valor, admitidas: tuple) -> None:
"""La regla `clave` vale una de las opciones que el código sabe aplicar; si no, `ReglaDesconocida`."""
if valor not in admitidas:
raise ReglaDesconocida(f"{clave} = {valor!r}: el código sabe aplicar {list(admitidas)}.")
def exigir_opciones(clave: str, valores, admitidas: tuple) -> None:
"""Cada valor de la regla `clave` es una opción que el código sabe aplicar; si no, `ReglaDesconocida`."""
desconocidas = [v for v in valores if v not in admitidas]
if desconocidas:
raise ReglaDesconocida(f"{clave}: {desconocidas} no se saben aplicar; el código sabe {list(admitidas)}.")
+26
View File
@@ -0,0 +1,26 @@
"""De dónde lee una definición: una vista o una tabla por su nombre, y sus parámetros.
Una definición de indicador lee la plata genérica por su vocabulario
(`<proyecto>/consultas/plata.py`) y las tablas de apoyo (`dim_fecha`,
`dim_grupo_edad`, `v_persona`) por `vista`. Desde F6 (ADR-MD-009) no hay
tablas de hechos por tipo ni sus vistas `v_<tabla>_actual`.
Las consultas son objetos de SQLAlchemy: el SQL lo escribe SQLAlchemy
para el motor de la sesión.
"""
from sqlalchemy import BindParameter, FromClause, bindparam, column, table
def vista(nombre: str, *columnas: str) -> FromClause:
"""Una vista o una tabla por su nombre y sus columnas, para las que no salen de un modelo."""
return table(nombre, *(column(nombre_columna) for nombre_columna in columnas))
def P(nombre: str, *, lista: bool = False) -> BindParameter:
"""Un parámetro de una definición. `lista`: su valor es una lista y va en un `IN`.
El valor no entra al SQL: se liga al ejecutar, así que la definición
no cambia cuando cambia una regla del TOML (S-K76).
"""
return bindparam(nombre, expanding=lista)
+34 -8
View File
@@ -1,6 +1,6 @@
"""Aggregate log of every import attempt (validations and commits).
Each attempt becomes one JSON line in `importaciones.jsonl` under
Each attempt becomes one JSON line in `import_log.jsonl` under
`WEBAPI_REPORT_DIR`. A record only carries counts, field names, source
column names and value *shapes* ("9999-99-99" for a date in an unexpected
format): never a row, a file name, a connection string or an identifier.
@@ -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
+257 -43
View File
@@ -1,20 +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"
@@ -22,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
@@ -29,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)
@@ -49,32 +58,19 @@ class _ResultCache:
_CACHE = _ResultCache()
def _files_from_sql(sql: dict[str, Any]) -> list[tuple[str, bytes]]:
"""One `(name, bytes)` per row of a SQL source (connected the same way
`SqlConnector` is): `column` is the field bundle (a `varbinary(max)`
PDF, or already a plain string — `read_document` reads either), and
`key_column` names the row (a patient or study id) for tracing. Any
column type `SqlConnector` can read works; it's not limited to PDFs."""
column = sql.get("column")
if not column:
raise ConnectorError("falta column")
if not sql.get("query") and not sql.get("table"):
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")
key_column = sql.get("key_column") or column
if key_column == column:
raise ConnectorError("key_column debe ser distinta de column")
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"))
)
files = []
for row in connector.read_rows({column: "contenido", key_column: "clave"}):
raw = row.get("contenido")
if raw is None:
continue
name = str(row.get("clave", len(files) + 1))
files.append((name, raw if isinstance(raw, bytes) else str(raw).encode("utf-8")))
return files
return spec.assemble(connector.read_rows({column: column for column in spec.source_columns()}))
@register_connector
@@ -93,8 +89,14 @@ class DocumentConnector(DataFrameConnector):
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"
@@ -114,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")
@@ -126,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
@@ -133,24 +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":
if payload.get("sql"):
files = _files_from_sql(payload["sql"])
documents = _files_from_sql(payload["sql"])
else:
files = [
(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)
]
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
@@ -162,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)
@@ -246,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()}
@@ -262,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()
+7 -48
View File
@@ -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)
+99 -6
View File
@@ -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
+2 -2
View File
@@ -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:
+305
View File
@@ -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()}
+13 -4
View File
@@ -16,8 +16,8 @@ from rapidfuzz import fuzz, process
from extraction.nlp import DiscoveredField
from extraction.nlp.text import find_date, fold
from indicadores_kit.plata.procedimiento import valor_de_observacion
from indicadores_kit.registry.catalogos import Catalogo, add_resultado
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")
@@ -48,9 +48,16 @@ class _NewResultado:
def match_or_mint(
discovered: list[DiscoveredField], *, proyecto: str, catalogo: Catalogo, estudio_id: str | None = None
discovered: list[DiscoveredField],
*,
proyecto: str,
catalogo: Catalogo,
estudio_id: str | None = None,
mint: bool = True,
) -> list[MatchedField]:
"""One `MatchedField` per discovered caption, in order.
"""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
@@ -67,6 +74,8 @@ def match_or_mint(
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
+8 -2
View File
@@ -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)]]
+28 -1
View File
@@ -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
+39 -61
View File
@@ -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",),
),
}
+55
View File
@@ -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
+26
View File
@@ -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
-69
View File
@@ -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
+16
View File
@@ -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

Some files were not shown because too many files have changed in this diff Show More