Compare commits
69 Commits
wip/mapping
...
staging
| Author | SHA1 | Date | |
|---|---|---|---|
| 7d0213eda7 | |||
| 1710cd5ca2 | |||
| 3c28a43cb1 | |||
| 21e6533dab | |||
| b9adedbf6f | |||
| 0cbe390b25 | |||
| 0f00a975fa | |||
| f74ccf5496 | |||
| 72a8e76108 | |||
| 01ac568c22 | |||
| 429275547b | |||
| 28eba44e9c | |||
| fad503ef56 | |||
| b452a35759 | |||
| 1dcbb74247 | |||
| c7c4e01006 | |||
| 8499427650 | |||
| 70a018a8fb | |||
| fe9ba433ec | |||
| fce6ccd40a | |||
| ae1ee4633f | |||
| 2b2c290f58 | |||
| 168edb30f5 | |||
| f65d5f3f4d | |||
| f0133e4f90 | |||
| 329e93bec3 | |||
| e97ed1a5a0 | |||
| 460a5039f1 | |||
| 10964e9e45 | |||
| 8c582347f9 | |||
| 8984c901c8 | |||
| df7f529e39 | |||
| fff2765810 | |||
| 9852e397da | |||
| 615f63cb7c | |||
| dcdcc34c46 | |||
| 0ee2916e1c | |||
| 72c4b38593 | |||
| 37a7a102f2 | |||
| 2d0bb8eed3 | |||
| b8253dda56 | |||
| 0f10a36f0d | |||
| 0d74f3a513 | |||
| 5b1dd30356 | |||
| 50d53c86fd | |||
| 73fcccea80 | |||
| ba583b6391 | |||
| 705b356f3f | |||
| aabdfa4013 | |||
| 0079f38446 | |||
| 9e92e25813 | |||
| 46c66406df | |||
| a2727f06ad | |||
| b660c77191 | |||
| a15ca94564 | |||
| 6eec071f3a | |||
| 9c0bff0cfe | |||
| 8bc0b06e7b | |||
| 830d978a1b | |||
| b89b630c2e | |||
| fecb0247d1 | |||
| 4c8f3e620e | |||
| 7577c99c62 | |||
| a188bf66e1 | |||
| cca67c837d | |||
| d76cb6cb20 | |||
| 84da0eb5fb | |||
| ceca8a03b5 | |||
| 0355d21d47 |
+2
-1
@@ -5,5 +5,6 @@ __pycache__/
|
||||
.coverage
|
||||
*.egg-info/
|
||||
.env
|
||||
uv.lock
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
|
||||
+15
-12
@@ -1,6 +1,6 @@
|
||||
# Build context is the repo root (see docker-compose.yml) so the sibling
|
||||
# packages Core/, Persistance/, Extraction/, models/, indicadores_kit/ and
|
||||
# Orquestacion/ can be copied.
|
||||
# packages Core/, Persistance/, Extraction/, models/ and indicadores_kit/
|
||||
# can be copied.
|
||||
FROM python:3.12-slim
|
||||
|
||||
# Tesseract (with Spanish data) for scanned documents; pytesseract only wraps the binary.
|
||||
@@ -8,7 +8,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
tesseract-ocr tesseract-ocr-spa \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN pip install --no-cache-dir uv
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.7.9 /uv /uvx /bin/
|
||||
|
||||
WORKDIR /app
|
||||
COPY Core/ Core/
|
||||
@@ -16,22 +16,25 @@ COPY Persistance/ Persistance/
|
||||
COPY Extraction/ Extraction/
|
||||
COPY models/ models/
|
||||
COPY indicadores_kit/ indicadores_kit/
|
||||
COPY Orquestacion/ Orquestacion/
|
||||
COPY WebApi/ WebApi/
|
||||
|
||||
# Migrations need the MySQL/PostgreSQL drivers when *_DATABASE_URL points there.
|
||||
RUN cd Persistance && uv sync --no-dev --extra drivers
|
||||
# Drivers for the SQL import sources (MySQL/MariaDB, PostgreSQL, SQL Server).
|
||||
RUN cd WebApi && uv sync --no-dev --extra sql-drivers
|
||||
# The indicator pipeline (staging -> facts -> reports), run with
|
||||
# `python -m orquestacion ciclo <proyecto> ...` after an import.
|
||||
RUN cd Orquestacion && uv sync --no-dev --extra drivers
|
||||
# One environment for the API, the migrations and the indicator cycle. The SQL
|
||||
# drivers serve both the import sources and *_DATABASE_URL on MySQL/PostgreSQL/SQL Server.
|
||||
RUN cd WebApi && uv sync --locked --no-dev --extra sql-drivers
|
||||
|
||||
ENV CACU_DATABASE_URL=sqlite:////data/cacu.db
|
||||
ENV CAMA_DATABASE_URL=sqlite:////data/cama.db
|
||||
ENV TEA_DATABASE_URL=sqlite:////data/tea.db
|
||||
ENV GOVERNANCE_DATABASE_URL=sqlite:////data/governance.db
|
||||
ENV MODELS_ARTIFACT_ROOT=/data/artifacts
|
||||
# MLflow model registry and artifacts, next to the databases so backups cover them.
|
||||
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).
|
||||
ENV WEBAPI_REPORT_DIR=/data/reportes
|
||||
ENV INDICADORES_DIR=/data/indicadores
|
||||
ENV MLFLOW_DISABLE_AGENT_HINT=1
|
||||
|
||||
RUN chmod +x /app/WebApi/docker-entrypoint.sh
|
||||
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
# WebApi
|
||||
|
||||
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.
|
||||
|
||||
## Estructura
|
||||
|
||||
```
|
||||
webapi/
|
||||
├── __init__.py create_app(): blueprints, límites de carga, CORS, /health y /api
|
||||
├── blueprints/
|
||||
│ ├── imports.py /imports: fuentes, vista previa, validación y carga
|
||||
│ ├── 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
|
||||
├── 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
|
||||
│ └── audit.py bitácora agregada (sin datos de pacientes)
|
||||
├── indicadores.py rutas de indicadores (del equipo de indicadores)
|
||||
├── indicadores_vivos.py cola y servicio que recalcula indicadores tras cada carga
|
||||
└── seguimiento.py lista de seguimiento por paciente (solo con DEV_REVISION)
|
||||
```
|
||||
|
||||
Agregar un tipo de fuente es agregar una clase en `imports/connectors/` con
|
||||
`@register_connector`; `GET /imports/connectors` la anuncia a la interfaz.
|
||||
Agregar una tabla destino es agregar su esquema en `imports/schemas/<dominio>/`
|
||||
y una entrada en `imports/schemas/registry.py`.
|
||||
|
||||
## Rutas
|
||||
|
||||
`GET /api` lista todas las rutas con su descripción.
|
||||
|
||||
| Prefijo | Para qué |
|
||||
|---|---|
|
||||
| `/imports` | Catálogo de fuentes y destinos, vista previa (archivos, SQL, PDF, documentos, EEG), `POST /imports/validate` y `POST /imports/commit` |
|
||||
| `/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 |
|
||||
| `/health` | Verificación de vida |
|
||||
|
||||
Los errores de la solicitud se responden con `{"error": "..."}` y código 400
|
||||
(404 si no existe el recurso).
|
||||
|
||||
## Variables de entorno
|
||||
|
||||
| Variable | Por omisión | Uso |
|
||||
|---|---|---|
|
||||
| `CACU_DATABASE_URL`, `CAMA_DATABASE_URL`, `TEA_DATABASE_URL`, `GOVERNANCE_DATABASE_URL` | archivos SQLite | Bases de la aplicación (cualquier URL de SQLAlchemy) |
|
||||
| `MLFLOW_TRACKING_URI` | `./mlruns` | Registro de modelos de MLflow |
|
||||
| `MLFLOW_ARTIFACT_ROOT` | el de MLflow | Carpeta de artefactos de los experimentos nuevos |
|
||||
| `WEBAPI_MAX_UPLOAD_MB` | `200` | Tamaño máximo de una solicitud |
|
||||
| `WEBAPI_CORS_ORIGINS` | sin CORS | Orígenes permitidos, separados por comas |
|
||||
| `WEBAPI_SQL_ALLOWED_DIALECTS` | `mysql,mariadb,postgresql,mssql` | Motores aceptados como fuente SQL |
|
||||
| `WEBAPI_SQL_ALLOWED_HOSTS` | cualquiera | Servidores aceptados como fuente SQL |
|
||||
| `WEBAPI_REPORT_DIR` | `reportes` | Carpeta de la bitácora (`importaciones.jsonl`, `indicadores.jsonl`) |
|
||||
| `WEBAPI_REPORT_MIN_COUNT` | `5` | Filas mínimas para que un valor rechazado aparezca textual en la bitácora |
|
||||
| `INDICADORES_DIR` | `indicadores` | Cola y estado del recálculo |
|
||||
| `INDICADORES_DESDE`, `INDICADORES_HASTA` | hace 5 años, este año | Años que recalcula el servicio |
|
||||
| `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 |
|
||||
|
||||
## Ejecución
|
||||
|
||||
En local (las migraciones se aplican a mano):
|
||||
|
||||
```bash
|
||||
uv sync --extra sql-drivers
|
||||
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
|
||||
```
|
||||
|
||||
Con Docker, desde la raíz del repositorio: `docker compose up --build`. La
|
||||
imagen se construye con `WebApi/Dockerfile` (contexto: la raíz, para copiar
|
||||
los paquetes hermanos); `docker-entrypoint.sh` aplica las migraciones y
|
||||
arranca gunicorn, o el servicio de recálculo con el argumento `indicadores`.
|
||||
|
||||
## Pruebas
|
||||
|
||||
```bash
|
||||
uv sync --extra sql-drivers
|
||||
uv run pytest -q
|
||||
```
|
||||
|
||||
Las pruebas contra MySQL en vivo se activan con `MYSQL_TEST_URL`; sin ella
|
||||
se omiten.
|
||||
+12
-9
@@ -10,17 +10,20 @@ for url in "$CACU_DATABASE_URL" "$CAMA_DATABASE_URL" "$TEA_DATABASE_URL" "$GOVER
|
||||
esac
|
||||
done
|
||||
|
||||
# --no-sync: the image's environments were synced at build time; syncing at
|
||||
# startup would try to reach the package index (and pull dev deps).
|
||||
cd /app/Persistance
|
||||
uv run --no-sync alembic -c persistance/cacu/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c persistance/cama/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c persistance/tea/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c persistance/governance/alembic.ini upgrade head
|
||||
# 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
|
||||
fi
|
||||
|
||||
cd /app/WebApi
|
||||
# Container's own network namespace — no AirPlay conflict here, keep it on
|
||||
# the port the Dockerfile EXPOSEs and docker-compose.yml maps from.
|
||||
# --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
|
||||
uv run --no-sync alembic -c "/app/Persistance/persistance/$domain/alembic.ini" upgrade head
|
||||
done
|
||||
|
||||
PORT="${PORT:-5000}"
|
||||
# gunicorn, not Flask's development server. Long timeout: OCR over a
|
||||
# multi-page scanned PDF runs inside a single request.
|
||||
|
||||
@@ -5,10 +5,5 @@ from webapi import create_app
|
||||
app = create_app()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Default avoids port 5000 — on macOS that's squatted by the AirPlay
|
||||
# Receiver service (ControlCenter), which answers with a bare 403 and
|
||||
# makes this look like a broken server rather than "port taken."
|
||||
# Docker's entrypoint overrides this back to 5000 for the container's
|
||||
# own internal port (see docker-entrypoint.sh), which is fine since
|
||||
# that's an isolated network namespace, not the host.
|
||||
# 5000 is taken by AirPlay on macOS.
|
||||
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5050)))
|
||||
|
||||
+4
-1
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "webapi"
|
||||
version = "0.1.0"
|
||||
description = "Flask REST API fronting Persistance (reads) and models (train/predict) for CaCu, CaMa and TEA."
|
||||
description = "ISSSTELEON REST API: data import, indicators, import log and model governance for CaCu, CaMa and TEA."
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"flask>=3.0",
|
||||
@@ -9,6 +9,7 @@ dependencies = [
|
||||
"models[export]",
|
||||
"extraction",
|
||||
"indicadores-kit",
|
||||
"apache-hamilton>=1.90",
|
||||
"pandas>=2.0",
|
||||
"openpyxl>=3.1",
|
||||
"sqlalchemy>=2.0",
|
||||
@@ -18,6 +19,8 @@ dependencies = [
|
||||
"Pillow>=10.0",
|
||||
"flask-cors>=4.0",
|
||||
"gunicorn>=23.0",
|
||||
"sqlglot>=25.0",
|
||||
"rapidfuzz>=3.9",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
||||
+101
-1
@@ -4,16 +4,85 @@
|
||||
`persistance.db.get_<domain>_engine` functions are `@lru_cache`d, so changing
|
||||
`<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
|
||||
sintético del kit.
|
||||
"""
|
||||
import os
|
||||
import tempfile
|
||||
from dataclasses import dataclass, replace
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
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
|
||||
|
||||
# Tests use throwaway SQLite files as "arbitrary SQL sources"; production
|
||||
# excludes sqlite by default (see webapi.imports.connectors.sql_policy).
|
||||
os.environ.setdefault("WEBAPI_SQL_ALLOWED_DIALECTS", "sqlite,mysql,mariadb,postgresql,mssql,oracle")
|
||||
os.environ.setdefault("WEBAPI_SQL_ALLOWED_DIALECTS", "sqlite,mysql,mariadb,postgresql,mssql")
|
||||
# The import log and the indicator queue write files; keep them out of the tree.
|
||||
_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"))
|
||||
|
||||
ANIO = 2025
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Base:
|
||||
"""El proyecto, su contexto (con los repositorios de Persistance) y su dominio en Persistance."""
|
||||
|
||||
proyecto: str
|
||||
ctx: Contexto
|
||||
dominio: object
|
||||
motor: object
|
||||
|
||||
def correr(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)}
|
||||
|
||||
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:
|
||||
url = f"sqlite:///{carpeta / f'{proyecto}.db'}"
|
||||
apuntar(proyecto, url)
|
||||
ctx = Contexto(proyecto, ANIO, ANIO, repos=repositorios_de(proyecto))
|
||||
correr(ctx, solo=["migrar"])
|
||||
motor = create_engine(url)
|
||||
with Session(motor) as sesion:
|
||||
import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion)
|
||||
sesion.commit()
|
||||
return Base(proyecto, ctx, import_module(f"persistance.{proyecto}"), motor)
|
||||
|
||||
|
||||
@pytest.fixture(params=["cacu", "cama", "tea"])
|
||||
def proyecto(request):
|
||||
return request.param
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def base(proyecto, tmp_path):
|
||||
base = base_de(proyecto, tmp_path)
|
||||
yield base
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sin_supresion(tmp_path):
|
||||
"""`parametros.toml` con umbral de supresión 1, para ver los conteos pequeños del fixture."""
|
||||
ruta = tmp_path / "parametros.toml"
|
||||
ruta.write_text(RUTA_PARAMETROS.read_text(encoding="utf-8").replace("valor = 5", "valor = 1"), encoding="utf-8")
|
||||
return ruta
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -54,3 +123,34 @@ def _migrate(domain: str) -> None:
|
||||
|
||||
ini = Path(persistance.__file__).parent / domain / "alembic.ini"
|
||||
command.upgrade(Config(str(ini)), "head")
|
||||
|
||||
|
||||
# Indicator-route tests (vendored from the fork's WebApi tests): the kit's
|
||||
# demonstration database, seeded into a temporary SQLite file per domain.
|
||||
SEMESTRES = ["2025-S1", "2025-S2"]
|
||||
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
|
||||
|
||||
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()
|
||||
|
||||
@@ -5,19 +5,6 @@ import pytest
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core.cacu.models import Paciente
|
||||
from persistance import db as persistance_db
|
||||
|
||||
engine = persistance_db.get_cacu_engine()
|
||||
|
||||
from sqlmodel import Session
|
||||
|
||||
with Session(engine) as session:
|
||||
session.add(Paciente(pac_id_hospital="H-1", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1)))
|
||||
session.commit()
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
@@ -31,26 +18,3 @@ def test_health(client):
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"status": "ok"}
|
||||
|
||||
|
||||
def test_get_paciente(client):
|
||||
response = client.get("/cacu/pacientes/1")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["pac_id_hospital"] == "H-1"
|
||||
|
||||
|
||||
def test_get_paciente_not_found(client):
|
||||
response = client.get("/cacu/pacientes/999")
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_predict_not_implemented(client):
|
||||
response = client.post("/cacu/predict")
|
||||
assert response.status_code == 501
|
||||
|
||||
|
||||
def test_api_index_lists_routes_with_summaries():
|
||||
from webapi import create_app
|
||||
|
||||
routes = {r["path"]: r for r in create_app().test_client().get("/api").get_json()["routes"]}
|
||||
assert routes["/imports/connectors"]["methods"] == ["GET"]
|
||||
assert routes["/governance/model-versions/<domain>/<scenario>/<version>/promote"]["summary"].startswith("Puts the version in production")
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""`commit_discovered_fields`: writes captions no known field claims
|
||||
straight into `procedimiento`/`observacion`, tagged apart from every
|
||||
staging-derived row with `FUENTE_CATALOGO_ABIERTO`. Fails if a known
|
||||
patient's discovered fields stop landing there, or if an unmatched one
|
||||
stops growing the catalog instead of being silently dropped.
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from sqlmodel import select
|
||||
|
||||
from indicadores_kit.registry import catalogos
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
from extraction import ExtractedRecord
|
||||
from extraction.nlp import DiscoveredField, Evidence
|
||||
from webapi.imports.services.catalog_commit_service import FUENTE_CATALOGO_ABIERTO, commit_discovered_fields
|
||||
|
||||
EVIDENCE = Evidence("fila.pdf", 1, "")
|
||||
|
||||
|
||||
def _record(key: str, pairs: list[tuple[str, str]]) -> ExtractedRecord:
|
||||
return ExtractedRecord(
|
||||
values={}, sources=[], key=key, discovered=[DiscoveredField(c, v, EVIDENCE) for c, v in pairs]
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cacu_catalog(tmp_path, monkeypatch):
|
||||
"""`add_resultado`/`sincronizar` write real rows and a real file:
|
||||
kept off the checked-in `cacu.toml` and off any other domain's data."""
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
(tmp_path / "cacu.toml").write_text(
|
||||
'[citologia]\netiqueta = "Citología cervical"\n\n'
|
||||
'[citologia.resultados.calidad_muestra]\netiqueta = "Calidad de la muestra"\ntipo_valor = "texto"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
return tmp_path / "cacu.toml"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def known_patient(wire_domain):
|
||||
wire_domain("cacu")
|
||||
from core.cacu.paciente.model import Paciente
|
||||
from persistance.cacu import paciente_repository
|
||||
|
||||
paciente_repository.create(Paciente(pac_id_hospital="DOC-FB-1", pac_fecha_nacimiento=date(1990, 1, 1)))
|
||||
return "DOC-FB-1"
|
||||
|
||||
|
||||
def test_a_matched_field_is_written_on_the_existing_resultado(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||
assert observacion.resultado_id == "citologia.calidad_muestra"
|
||||
assert observacion.valor_texto == "Insatisfactoria"
|
||||
[procedimiento] = sesion.exec(select(carga_repository.procedimiento)).all()
|
||||
assert procedimiento.fuente_tabla == FUENTE_CATALOGO_ABIERTO
|
||||
assert procedimiento.fuente_id == known_patient
|
||||
|
||||
|
||||
def test_an_unmatched_field_mints_a_resultado_and_is_written_too(cacu_catalog, known_patient):
|
||||
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}
|
||||
|
||||
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"
|
||||
|
||||
|
||||
def test_a_patient_outside_persona_is_skipped_not_dropped_silently(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields(
|
||||
[_record("NOT-A-PATIENT", [("Calidad de muestra", "x")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert (result.records_written, result.records_without_patient) == (0, 1)
|
||||
|
||||
|
||||
def test_a_record_without_discovered_fields_is_ignored(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields([_record(known_patient, [])], proyecto="cacu", estudio_id="citologia")
|
||||
assert result.records_written == 0
|
||||
|
||||
|
||||
def test_a_repeated_caption_is_folded_not_written_twice(cacu_catalog, known_patient):
|
||||
"""A static label printed on several pages of the same document (a date,
|
||||
a signature line) discovers as one `DiscoveredField` per occurrence,
|
||||
on purpose (`discover_captions`'s docstring). Fails if this stops
|
||||
folding repeats before writing: `observacion` has one row per
|
||||
`(procedimiento, resultado_id)`, so a second occurrence of the same
|
||||
resultado_id raises `IntegrityError` and the whole record's fields —
|
||||
including the ones that weren't duplicated — are lost."""
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria"), ("Calidad de muestra", "Satisfactoria")])],
|
||||
proyecto="cacu",
|
||||
estudio_id="citologia",
|
||||
)
|
||||
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||
assert observacion.resultado_id == "citologia.calidad_muestra"
|
||||
assert observacion.valor_texto == "Insatisfactoria"
|
||||
@@ -0,0 +1,90 @@
|
||||
"""`catalog_matching.match_or_mint`: fails if it stops reusing an existing
|
||||
catalog field for an OCR caption that's clearly the same thing worded
|
||||
differently, or if an unmatched caption stops being added to the catalog
|
||||
and silently drops its value instead.
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from indicadores_kit.registry import catalogos
|
||||
from indicadores_kit.registry.catalogos import Catalogo
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
from extraction.nlp import DiscoveredField, Evidence
|
||||
from webapi.imports.schemas.catalog_matching import match_or_mint
|
||||
|
||||
EVIDENCE = Evidence("fila.pdf", 1, "")
|
||||
|
||||
|
||||
def _field(caption: str, value: str) -> DiscoveredField:
|
||||
return DiscoveredField(caption, value, EVIDENCE)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo() -> Catalogo:
|
||||
tablas = tablas_de("cacu")
|
||||
return Catalogo(
|
||||
estudios=[tablas.CatEstudio(estudio_id="citologia", etiqueta="Citología cervical")],
|
||||
resultados=[
|
||||
tablas.CatResultado(
|
||||
resultado_id="citologia.calidad_muestra", estudio_id="citologia",
|
||||
etiqueta="Calidad de la muestra", tipo_valor="codigo",
|
||||
),
|
||||
tablas.CatResultado(
|
||||
resultado_id="citologia.celulas_glandulares", estudio_id="citologia",
|
||||
etiqueta="Células glandulares", tipo_valor="texto",
|
||||
),
|
||||
],
|
||||
valores=[
|
||||
tablas.CatValor(
|
||||
resultado_id="citologia.calidad_muestra", valor_id="SATISFACTORIO",
|
||||
etiqueta="Satisfactoria", orden=1, estado="vigente",
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo_toml(tmp_path, monkeypatch):
|
||||
"""`add_resultado` writes to disk; keep it off the real `cacu.toml`."""
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
(tmp_path / "cacu.toml").write_text("", encoding="utf-8")
|
||||
return tmp_path / "cacu.toml"
|
||||
|
||||
|
||||
def test_a_worded_differently_caption_reuses_the_existing_resultado(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint(
|
||||
[_field("Calidad de muestra", "SATISFACTORIO")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
|
||||
)
|
||||
assert matched.resultado_id == "citologia.calidad_muestra" and not matched.is_new
|
||||
assert matched.observacion["valor_id"] == "SATISFACTORIO"
|
||||
assert catalogo_toml.read_text(encoding="utf-8") == "" # nothing minted
|
||||
|
||||
|
||||
def test_an_unmatched_caption_in_a_known_estudio_is_minted_there(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint(
|
||||
[_field("Tipo de fijador", "Formol")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
|
||||
)
|
||||
assert matched.is_new and matched.resultado_id.startswith("citologia.")
|
||||
assert matched.observacion["valor_texto"] == "Formol"
|
||||
|
||||
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
|
||||
assert matched.resultado_id in {r.resultado_id for r in sincronizado.resultados}
|
||||
|
||||
|
||||
def test_an_unmatched_caption_with_no_estudio_falls_back_to_documento_externo(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint([_field("Observación suelta", "algo")], proyecto="cacu", catalogo=catalogo)
|
||||
assert matched.resultado_id == "documento_externo." + matched.resultado_id.split(".", 1)[1]
|
||||
|
||||
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
|
||||
assert "documento_externo" in {e.estudio_id for e in sincronizado.estudios}
|
||||
|
||||
|
||||
def test_the_inferred_tipo_valor_follows_the_value_shape(catalogo, catalogo_toml):
|
||||
fecha, numero, texto = match_or_mint(
|
||||
[_field("Fecha de algo", "15/01/2024"), _field("Cuenta de algo", "12.5"), _field("Nota libre", "ninguna")],
|
||||
proyecto="cacu", catalogo=catalogo, estudio_id="citologia",
|
||||
)
|
||||
assert fecha.observacion["valor_fecha"] == date(2024, 1, 15)
|
||||
assert numero.observacion["valor_numerico"] == 12.5
|
||||
assert texto.observacion["valor_texto"] == "ninguna"
|
||||
@@ -13,7 +13,7 @@ from webapi.imports.connectors.sql import SqlConnector
|
||||
def test_csv_connector_reads_columns_and_rows():
|
||||
raw = b"nombre,edad\nAna,30\nLuis,40\n"
|
||||
connector = CsvConnector(raw)
|
||||
columns = {c.name: c.inferred_type for c in connector.get_columns()}
|
||||
columns = {c.name: c.inferred_type for c in connector.preview().columns}
|
||||
assert columns == {"nombre": "string", "edad": "integer"}
|
||||
preview = connector.preview(limit=1)
|
||||
assert preview.total_rows == 2
|
||||
@@ -26,7 +26,7 @@ def test_csv_connector_reads_columns_and_rows():
|
||||
def test_csv_connector_keeps_leading_zeros_and_blank_cells():
|
||||
raw = b"cp,exp\n01000,007\n,H-2\n"
|
||||
connector = CsvConnector(raw)
|
||||
assert {c.name: c.inferred_type for c in connector.get_columns()} == {"cp": "string", "exp": "string"}
|
||||
assert {c.name: c.inferred_type for c in connector.preview().columns} == {"cp": "string", "exp": "string"}
|
||||
rows = list(connector.read_rows({"cp": "pac_codigo_postal", "exp": "pac_id_hospital"}))
|
||||
assert rows == [
|
||||
{"pac_codigo_postal": "01000", "pac_id_hospital": "007"},
|
||||
@@ -36,14 +36,14 @@ def test_csv_connector_keeps_leading_zeros_and_blank_cells():
|
||||
|
||||
def test_csv_connector_single_column_file():
|
||||
connector = CsvConnector(b"id\nH3\nH4\n")
|
||||
assert [c.name for c in connector.get_columns()] == ["id"]
|
||||
assert [c.name for c in connector.preview().columns] == ["id"]
|
||||
assert connector.metadata()["delimiter"] == ","
|
||||
|
||||
|
||||
def test_csv_connector_sniffs_semicolons_and_strips_excel_bom():
|
||||
raw = "\ufeffExpediente;Sexo\nH-1;F\n".encode("utf-8")
|
||||
connector = CsvConnector(raw)
|
||||
assert [c.name for c in connector.get_columns()] == ["Expediente", "Sexo"]
|
||||
assert [c.name for c in connector.preview().columns] == ["Expediente", "Sexo"]
|
||||
assert connector.metadata() == {"delimiter": ";", "encoding": "utf-8-sig"}
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ def test_csv_connector_bad_bytes_raise_connector_error():
|
||||
def test_json_connector_reads_list_of_records():
|
||||
raw = b'[{"nombre": "Ana", "edad": 30}, {"nombre": "Luis", "edad": 40}]'
|
||||
connector = JsonConnector(raw)
|
||||
assert {c.name for c in connector.get_columns()} == {"nombre", "edad"}
|
||||
assert {c.name for c in connector.preview().columns} == {"nombre", "edad"}
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre"}))
|
||||
assert rows == [{"pac_nombre": "Ana"}, {"pac_nombre": "Luis"}]
|
||||
|
||||
@@ -69,7 +69,7 @@ def test_json_connector_reads_list_of_records():
|
||||
def test_json_connector_reads_wrapped_data_key():
|
||||
raw = b'{"data": [{"nombre": "Ana"}]}'
|
||||
connector = JsonConnector(raw)
|
||||
assert {c.name for c in connector.get_columns()} == {"nombre"}
|
||||
assert {c.name for c in connector.preview().columns} == {"nombre"}
|
||||
|
||||
|
||||
def test_json_connector_bad_json_raises_connector_error():
|
||||
@@ -83,7 +83,7 @@ def test_excel_connector_reads_columns_and_rows():
|
||||
pd.DataFrame({"nombre": ["Ana", "Luis"], "edad": [30, 40]}).to_excel(buffer, index=False, engine="openpyxl")
|
||||
connector = ExcelConnector(buffer.getvalue())
|
||||
assert connector.list_sheets() == ["Sheet1"]
|
||||
assert {c.name for c in connector.get_columns()} == {"nombre", "edad"}
|
||||
assert {c.name for c in connector.preview().columns} == {"nombre", "edad"}
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre"}))
|
||||
assert rows == [{"pac_nombre": "Ana"}, {"pac_nombre": "Luis"}]
|
||||
|
||||
|
||||
@@ -181,7 +181,7 @@ def test_select_table_then_connector_abc_roundtrip():
|
||||
candidate = connector.detect_tables()[0]
|
||||
connector.select_table(candidate.page_number, candidate.bbox)
|
||||
|
||||
columns = {c.name for c in connector.get_columns()}
|
||||
columns = {c.name for c in connector.preview().columns}
|
||||
assert columns == {"pac_id_hospital", "pac_sexo"}
|
||||
|
||||
preview = connector.preview(limit=1)
|
||||
@@ -204,7 +204,7 @@ def test_select_table_out_of_range_page_raises_connector_error():
|
||||
def test_read_rows_before_resolution_raises_connector_error():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F")]))
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.get_columns()
|
||||
connector.preview().columns
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
@@ -288,6 +288,19 @@ def test_two_page_apply_to_every_page_regions():
|
||||
assert _similar(result["name"][3], ROWS_PAGE_2[0][0])
|
||||
|
||||
|
||||
def test_regions_on_different_pages_still_give_rectangular_rows():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS, ROWS_PAGE_2]))
|
||||
regions = [
|
||||
RegionSpec(target_field="name", page_numbers=[1, 2], bbox=_norm_bbox("name")),
|
||||
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
||||
]
|
||||
result = connector.extract_regions(regions)
|
||||
|
||||
assert len(result["name"]) == len(result["age"]) == 6
|
||||
assert result["age"][3:] == [None, None, None]
|
||||
assert len(list(connector.read_rows({"name": "name", "age": "age"}))) == 6
|
||||
|
||||
|
||||
def test_extract_regions_before_resolution_then_read_rows_uses_region_mode():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
||||
regions = [
|
||||
@@ -295,7 +308,7 @@ def test_extract_regions_before_resolution_then_read_rows_uses_region_mode():
|
||||
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
||||
]
|
||||
connector.extract_regions(regions)
|
||||
columns = {c.name for c in connector.get_columns()}
|
||||
columns = {c.name for c in connector.preview().columns}
|
||||
assert columns == {"name", "age"}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
"""`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
|
||||
path in between. Fails if the bridge to `SqlConnector` breaks, or if a
|
||||
plain-text column stops reaching the same field extraction a PDF does.
|
||||
"""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from extraction.testing import text_pdf
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
REPORT = text_pdf(
|
||||
[["Expediente: SQL-0001", "Fecha de nacimiento: 12/03/1981", "VPH alto riesgo: POSITIVO"]]
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_studies_table(tmp_path):
|
||||
"""A source table shaped like ISSSTELEON's: one row per study, its
|
||||
report in a binary column, plus a plain-text variant of the same
|
||||
report in another row, both alongside the row's own key column."""
|
||||
db_path = tmp_path / "estudios.db"
|
||||
url = f"sqlite:///{db_path}"
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
|
||||
conn.execute(
|
||||
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
|
||||
{"id": "ROW-1", "reporte": REPORT},
|
||||
)
|
||||
conn.execute(
|
||||
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
|
||||
{
|
||||
"id": "ROW-2",
|
||||
"reporte": "Expediente: SQL-0002\nFecha de nacimiento: 01/01/1990\nVPH alto riesgo: NEGATIVO",
|
||||
},
|
||||
)
|
||||
return url
|
||||
|
||||
|
||||
def _sql_payload(url: str, **overrides) -> dict:
|
||||
return {"connection_string": url, "table": "estudios", "column": "reporte", "key_column": "estudio_id", **overrides}
|
||||
|
||||
|
||||
def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table):
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
[first, second] = body["records"]
|
||||
assert first["key"] == "SQL-0001"
|
||||
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
assert first["sources"] == [{"document": "ROW-1", "page_numbers": [1]}]
|
||||
|
||||
|
||||
def test_a_plain_text_column_reaches_the_same_field_extraction(client, sqlite_studies_table):
|
||||
"""Fails if a source whose bundle is a plain string (not binary at
|
||||
all) stops producing fields, since ISSSTELEON's column may not always
|
||||
be a PDF (`extraction.readers.TextReader`)."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
[_, second] = body["records"]
|
||||
assert second["key"] == "SQL-0002"
|
||||
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
|
||||
assert second["sources"] == [{"document": "ROW-2", "page_numbers": [1]}]
|
||||
|
||||
|
||||
def test_sql_sourced_documents_commit_like_uploaded_ones(client, sqlite_studies_table):
|
||||
source = {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"sql": _sql_payload(sqlite_studies_table)},
|
||||
"label": "estudios",
|
||||
}
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
rows = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100) if r.pac_id_hospital.startswith("SQL-")}
|
||||
assert rows["SQL-0001"].cit_vph_resultado == "POSITIVO"
|
||||
assert rows["SQL-0002"].cit_vph_resultado == "NEGATIVO"
|
||||
|
||||
|
||||
def test_column_and_key_column_must_differ(client, sqlite_studies_table):
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table, key_column="reporte"), "target": "cacu.CitologiaCervical"},
|
||||
)
|
||||
assert response.status_code == 400 and "key_column" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_a_missing_column_is_a_bad_request(client, sqlite_studies_table):
|
||||
payload = _sql_payload(sqlite_studies_table)
|
||||
del payload["column"]
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract", json={"sql": payload, "target": "cacu.CitologiaCervical"}
|
||||
)
|
||||
assert response.status_code == 400 and "column" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(client, tmp_path, monkeypatch):
|
||||
"""Mixing sources: a field the import schema doesn't name (`Tipo de
|
||||
fijador`) 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.
|
||||
Its own table and patient (`SQL-EXTRA-1`), so it doesn't collide with
|
||||
the module's other tests sharing this `client`'s database."""
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import create_engine, text as sa_text
|
||||
from sqlmodel import select
|
||||
|
||||
from indicadores_kit.registry import 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")
|
||||
paciente_repository.create(Paciente(pac_id_hospital="SQL-EXTRA-1", pac_fecha_nacimiento=date(1981, 3, 12)))
|
||||
|
||||
db_url = f"sqlite:///{tmp_path / 'estudios_extra.db'}"
|
||||
report = text_pdf([["Expediente: SQL-EXTRA-1", "VPH alto riesgo: POSITIVO", "Tipo de fijador: Formol"]])
|
||||
with create_engine(db_url).begin() as conn:
|
||||
conn.execute(sa_text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
|
||||
conn.execute(sa_text("INSERT INTO estudios (estudio_id, reporte) VALUES ('ROW-1', :r)"), {"r": report})
|
||||
|
||||
source = {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"sql": _sql_payload(db_url), "estudio_id": "citologia"},
|
||||
"label": "estudios_extra",
|
||||
}
|
||||
body = client.post("/imports/commit", json={"sources": [source]}).get_json()
|
||||
assert body["results"][0]["created"] == 1, body
|
||||
|
||||
[report] = [r for r in body["catalog_fallback"] if r["label"] == "estudios_extra"]
|
||||
assert report["records_written"] == 1 and report["fields_minted"] == 1
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[minted] = 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"
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Endpoint tests for `/governance/*` and the `/cacu/predict`,`/cama/predict`
|
||||
MLD-4/MLD-5 wiring through `models.prediction.PredictionService`."""
|
||||
"""Endpoint tests for `/governance/*`."""
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import date
|
||||
@@ -43,34 +42,35 @@ def client(wire_domain):
|
||||
del os.environ["MLFLOW_TRACKING_URI"]
|
||||
|
||||
|
||||
def test_predict_without_model_version_is_501(client):
|
||||
"""CaCuModel.predict is not implemented yet; no seeded MLflow version is
|
||||
needed to reach that state."""
|
||||
response = client.post("/cacu/predict", json={"pac_id_hospital": "H-1", "data": {"edad": 40}})
|
||||
assert response.status_code == 501
|
||||
|
||||
|
||||
def test_list_model_versions_empty(client):
|
||||
response = client.get("/governance/model-versions", query_string={"domain": "cacu", "scenario": "tamizaje-vacio"})
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"model_versions": []}
|
||||
|
||||
|
||||
def _cohort(tag: str) -> int:
|
||||
from core.governance.models import CohortVersion
|
||||
from persistance.governance import cohort_version_repository
|
||||
def _armado(tag: str) -> int:
|
||||
"""A CaCu cohort build with one attrition step; returns its `armado_id`."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
cohort = CohortVersion(
|
||||
domain="cacu", scenario="tamizaje", criteria_version="v1", version_hash=f"hash-{tag}",
|
||||
source_table="cacu.episodioclinico", n_source=5, n_included=5,
|
||||
)
|
||||
return cohort_version_repository.create(cohort).cohort_version_id
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteExclusion
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
with get_cacu_session() as session:
|
||||
armado = CohorteArmado(
|
||||
url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r", parametros="{}",
|
||||
datos_as_of=date(2025, 12, 31), huella=f"huella-{tag}", marco_sha="m", n_miembros=5,
|
||||
armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc))
|
||||
session.add(armado)
|
||||
session.flush()
|
||||
session.add(CohorteExclusion(armado_id=armado.armado_id, orden=1, paso="candidatas", n=5))
|
||||
session.commit()
|
||||
return armado.armado_id
|
||||
|
||||
|
||||
def _register(client, tag: str, *, scenario: str = "tamizaje", **extra) -> dict:
|
||||
body = {
|
||||
"domain": "cacu", "scenario": scenario, "environment": "PROD",
|
||||
"cohort_version_id": _cohort(tag), "metrics": {"auc": 0.8},
|
||||
"cohorte_armado_id": _armado(tag), "metrics": {"auc": 0.8},
|
||||
"technical_validation_report_uri": "docs/tecnica.pdf",
|
||||
"clinical_validation_report_uri": "docs/clinica.pdf",
|
||||
"interpretability_report_uri": "docs/interpretabilidad.html",
|
||||
@@ -108,12 +108,11 @@ def test_model_version_lifecycle_over_http(client):
|
||||
assert statuses[first["version"]] == "retirada" and statuses[second["version"]] == "produccion"
|
||||
|
||||
lineage = client.get(f"/governance/model-versions/cacu/lifecycle/{second['version']}/lineage").get_json()
|
||||
assert lineage["cohort_version"]["version_hash"] == "hash-v2"
|
||||
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"]
|
||||
|
||||
diff = client.get("/governance/model-versions/cacu/lifecycle/compare", query_string={"a": first["version"], "b": second["version"]}).get_json()
|
||||
assert diff["metrics"][0]["delta"] == pytest.approx(0.06)
|
||||
|
||||
retired = client.post(f"/governance/model-versions/cacu/lifecycle/{second['version']}/retire").get_json()
|
||||
assert retired["status"] == "retirada"
|
||||
|
||||
@@ -136,77 +135,12 @@ def test_bad_registrations_and_uploads_are_rejected(client):
|
||||
|
||||
|
||||
def test_model_version_not_found(client):
|
||||
assert client.get("/governance/model-versions/cacu/no-existe/999").status_code == 404
|
||||
assert client.get("/governance/model-versions/cacu/no-existe/999/checks").status_code == 404
|
||||
|
||||
|
||||
def test_cohort_scenarios_and_build(client, monkeypatch):
|
||||
from models import cohort
|
||||
|
||||
class Demo(cohort.CohortBuilder):
|
||||
domain, scenario, criteria_version = "cacu", "demo", "v1"
|
||||
criteria = [cohort.ExclusionCriterion("SIN_CIE", "sin_codigo", lambda e: not e.get("cie10_codigo"), applicable_in_production=True)]
|
||||
|
||||
def fetch_episodes(self):
|
||||
return [{"episodio_id": 1, "pac_id_hospital": "H-1", "cie10_codigo": "C53"}, {"episodio_id": 2, "pac_id_hospital": "H-2"}]
|
||||
|
||||
monkeypatch.setitem(cohort.COHORT_BUILDERS, ("cacu", "demo"), Demo)
|
||||
[scenario] = [s for s in client.get("/governance/cohort-scenarios").get_json()["scenarios"] if s["scenario"] == "demo"]
|
||||
assert scenario["criteria"][0]["code"] == "SIN_CIE"
|
||||
built = client.post("/governance/cohort-versions", json={"domain": "cacu", "scenario": "demo"})
|
||||
assert built.status_code == 201 and built.get_json()["n_included"] == 1
|
||||
assert client.post("/governance/cohort-versions", json={"domain": "cacu", "scenario": "nope"}).status_code == 404
|
||||
|
||||
|
||||
def test_promote_unknown_model_version_is_404(client):
|
||||
assert client.post("/governance/model-versions/cacu/no-existe/999/promote").status_code == 404
|
||||
|
||||
|
||||
def test_cohort_version_exclusions_endpoint(client):
|
||||
from core.governance.models import CohortExclusion, CohortExclusionCount, CohortVersion
|
||||
from persistance.governance import (
|
||||
cohort_exclusion_count_repository,
|
||||
cohort_exclusion_repository,
|
||||
cohort_version_repository,
|
||||
)
|
||||
|
||||
cohort = cohort_version_repository.create(
|
||||
CohortVersion(
|
||||
domain="cacu",
|
||||
scenario="tamizaje",
|
||||
criteria_version="v1",
|
||||
version_hash="hash123",
|
||||
source_table="cacu.episodioclinico",
|
||||
n_source=10,
|
||||
n_included=8,
|
||||
)
|
||||
)
|
||||
cohort_exclusion_repository.create(
|
||||
CohortExclusion(
|
||||
cohort_version_id=cohort.cohort_version_id,
|
||||
pac_id_hospital="H-9",
|
||||
criterion_code="EDAD_FUERA_DE_RANGO",
|
||||
reason_code="EDAD<25",
|
||||
)
|
||||
)
|
||||
cohort_exclusion_count_repository.create(
|
||||
CohortExclusionCount(
|
||||
cohort_version_id=cohort.cohort_version_id,
|
||||
criterion_code="EDAD_FUERA_DE_RANGO",
|
||||
reason_code="EDAD<25",
|
||||
count=2,
|
||||
)
|
||||
)
|
||||
|
||||
response = client.get(f"/governance/cohort-versions/{cohort.cohort_version_id}/exclusions")
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["counts"][0]["count"] == 2
|
||||
assert body["detail"][0]["pac_id_hospital"] == "H-9"
|
||||
|
||||
|
||||
def test_ocr_run_unknown_job_is_400(client):
|
||||
def test_ocr_run_unknown_job_is_404(client):
|
||||
response = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "no_such_entity"})
|
||||
assert response.status_code == 400
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_ocr_run_extracts_results_and_flags_unreadable_reports(client):
|
||||
|
||||
@@ -191,7 +191,7 @@ def test_a_failing_source_rolls_back_the_whole_batch(client, monkeypatch):
|
||||
},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "nothing was written" in response.get_json()["error"]
|
||||
assert "no se escribió nada" in response.get_json()["error"]
|
||||
assert not {"ATOM-1", "ATOM-2"} & set(_rows(client, "cacu.Paciente"))
|
||||
|
||||
|
||||
|
||||
@@ -6,6 +6,11 @@ import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
|
||||
def _patients(client) -> dict[str, dict]:
|
||||
rows = client.get("/data/cacu.Paciente", query_string={"limit": 500}).get_json()["rows"]
|
||||
return {row["pac_id_hospital"]: row for row in rows}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
@@ -81,8 +86,7 @@ def test_validate_reports_row_errors_without_writing(client):
|
||||
assert body["valid_count"] == 1
|
||||
assert body["error_count"] == 1
|
||||
assert body["errors"][0]["field"] == "pac_id_hospital"
|
||||
# not written
|
||||
assert client.get("/cacu/pacientes/999").status_code == 404
|
||||
assert "H-VALIDATE-1" not in _patients(client)
|
||||
|
||||
|
||||
def test_commit_multi_source_batch_mixes_file_and_sql_within_one_domain(client, tmp_path):
|
||||
@@ -115,12 +119,7 @@ def test_commit_multi_source_batch_mixes_file_and_sql_within_one_domain(client,
|
||||
assert body["ok"] is True
|
||||
assert [r["target"] for r in body["results"]] == ["cacu.Paciente", "cacu.Paciente"]
|
||||
assert sum(r["created"] for r in body["results"]) == 2
|
||||
|
||||
# First test in this file to write into cacu.Paciente, so autoincrement
|
||||
# ids 1/2 are deterministic (pytest runs this module's tests in
|
||||
# definition order).
|
||||
created_hospital_ids = {client.get(f"/cacu/pacientes/{i}").get_json()["pac_id_hospital"] for i in (1, 2)}
|
||||
assert created_hospital_ids == {"H-BATCH-1", "H-SQL-BATCH-1"}
|
||||
assert {"H-BATCH-1", "H-SQL-BATCH-1"} <= set(_patients(client))
|
||||
|
||||
|
||||
def test_commit_rejects_a_batch_mixing_domains(client):
|
||||
@@ -129,7 +128,7 @@ def test_commit_rejects_a_batch_mixing_domains(client):
|
||||
|
||||
response = client.post("/imports/commit", json={"sources": [cacu_source, tea_source], "on_conflict": "reject"})
|
||||
assert response.status_code == 400
|
||||
assert "domain" in response.get_json()["error"].lower()
|
||||
assert "dominios" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_commit_on_conflict_reject_then_upsert(client):
|
||||
@@ -179,8 +178,8 @@ def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client):
|
||||
assert body["results"][0]["created"] == 0
|
||||
assert body["results"][0]["updated"] == 1
|
||||
|
||||
paciente = client.get("/tea/pacientes/9001").get_json()
|
||||
assert paciente["pac_id_hospital"] == "T-SRC-1"
|
||||
[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"
|
||||
|
||||
|
||||
|
||||
@@ -13,7 +13,12 @@ import sqlalchemy as sa
|
||||
|
||||
MYSQL_TEST_URL = os.environ.get("MYSQL_TEST_URL")
|
||||
|
||||
pytestmark = pytest.mark.skipif(not MYSQL_TEST_URL, reason="MYSQL_TEST_URL not set — no real MySQL server to test against")
|
||||
pytestmark = pytest.mark.skipif(not MYSQL_TEST_URL, reason="MYSQL_TEST_URL not set")
|
||||
|
||||
|
||||
def _patients(client) -> dict[str, dict]:
|
||||
rows = client.get("/data/cacu.Paciente", query_string={"limit": 500}).get_json()["rows"]
|
||||
return {row["pac_id_hospital"]: row for row in rows}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -129,13 +134,18 @@ def test_commit_batch_mixes_mysql_json_and_csv_into_one_domain(client, mysql_leg
|
||||
# csv: 1 row, json: 1 row, mysql: 2 rows
|
||||
assert [r["created"] for r in body["results"]] == [1, 1, 2]
|
||||
|
||||
all_ids = {client.get(f"/cacu/pacientes/{i}").get_json()["pac_id_hospital"] for i in range(1, 5)}
|
||||
assert all_ids == {"CSV-MULTI-1", "JSON-MULTI-1", "MYSQL-MULTI-1", "MYSQL-MULTI-2"}
|
||||
assert {"CSV-MULTI-1", "JSON-MULTI-1", "MYSQL-MULTI-1", "MYSQL-MULTI-2"} <= set(_patients(client))
|
||||
|
||||
|
||||
def test_commit_upsert_against_mysql_source_updates_existing_row(client, mysql_legacy_source):
|
||||
# MYSQL-MULTI-1 already exists (created above with sexo 'F'). Mutate the
|
||||
# source row and re-import with on_conflict=upsert.
|
||||
sql_source = {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"expediente": "pac_id_hospital", "sexo_paciente": "pac_sexo"},
|
||||
"payload": {"connection_string": MYSQL_TEST_URL, "table": mysql_legacy_source},
|
||||
}
|
||||
assert client.post("/imports/commit", json={"sources": [sql_source], "on_conflict": "upsert"}).status_code == 200
|
||||
|
||||
engine = sa.create_engine(MYSQL_TEST_URL)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(
|
||||
@@ -143,22 +153,11 @@ def test_commit_upsert_against_mysql_source_updates_existing_row(client, mysql_l
|
||||
)
|
||||
engine.dispose()
|
||||
|
||||
sql_source = {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"expediente": "pac_id_hospital", "sexo_paciente": "pac_sexo"},
|
||||
"payload": {"connection_string": MYSQL_TEST_URL, "table": mysql_legacy_source},
|
||||
}
|
||||
response = client.post("/imports/commit", json={"sources": [sql_source], "on_conflict": "upsert"})
|
||||
assert response.status_code == 200
|
||||
result = response.get_json()["results"][0]
|
||||
# Both rows already exist from the previous test. Upsert reports
|
||||
# "updated" for every conflicting row whether or not its values changed,
|
||||
# per Repository.bulk_upsert's contract.
|
||||
# Upsert reports "updated" for every row that already existed, changed or not.
|
||||
assert result["updated"] == 2
|
||||
assert result["created"] == 0
|
||||
|
||||
updated = client.get("/cacu/pacientes/3").get_json()
|
||||
assert updated["pac_id_hospital"] == "MYSQL-MULTI-1"
|
||||
# 'M' is coerced through SEXO_BIOLOGICO_ALIAS into the canonical value.
|
||||
assert updated["pac_sexo"] == "Masculino"
|
||||
assert _patients(client)["MYSQL-MULTI-1"]["pac_sexo"] == "Masculino"
|
||||
|
||||
@@ -18,6 +18,11 @@ from reportlab.pdfgen import canvas
|
||||
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
|
||||
|
||||
|
||||
def _patients(client) -> dict[str, dict]:
|
||||
rows = client.get("/data/cacu.Paciente", query_string={"limit": 500}).get_json()["rows"]
|
||||
return {row["pac_id_hospital"]: row for row in rows}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
@@ -166,10 +171,7 @@ def test_pdf_table_round_trip_detect_preview_validate_commit(client):
|
||||
assert result["target"] == "cacu.Paciente"
|
||||
assert result["created"] == 2
|
||||
|
||||
# this is the first write into cacu.Paciente in this module's temp DB
|
||||
created = client.get("/cacu/pacientes/1")
|
||||
assert created.status_code == 200
|
||||
assert created.get_json()["pac_id_hospital"] == "H-PDF-TAB-1"
|
||||
assert "H-PDF-TAB-1" in _patients(client)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
"""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
|
||||
@@ -0,0 +1,229 @@
|
||||
"""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()
|
||||
@@ -1,183 +0,0 @@
|
||||
"""Endpoint tests for `/tea/indicadores`, `/cacu/indicadores` and
|
||||
`/cama/indicadores`: the read side of the bronze/silver/gold pipeline
|
||||
(Persistance/persistance/aristas, indicadores_kit). Seeds one patient,
|
||||
runs the real `cargar`/`registro`/`definiciones`/`calcular` steps, then
|
||||
hits the HTTP layer."""
|
||||
from datetime import date
|
||||
from functools import partial
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("tea")
|
||||
|
||||
from core.tea.models import Pacientes
|
||||
from persistance import db as persistance_db
|
||||
from persistance.tea import (
|
||||
staging_repository, carga_repository, def_parametro_repository,
|
||||
dim_periodo_repository, indicador_definicion_repository, calculo_repository,
|
||||
)
|
||||
from indicadores_kit.tea import etl
|
||||
from indicadores_kit.registry.parametros import leer_parametros, RUTA_PARAMETROS
|
||||
from indicadores_kit.registry.periodos import periodos_de_tipos
|
||||
from indicadores_kit.registry.measures import measures_de, rutas_de_measures
|
||||
from indicadores_kit.serving.definiciones import leer_definiciones
|
||||
from indicadores_kit.mart.calculo import medir_con_unidades
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
with __import__("sqlmodel").Session(persistance_db.get_tea_engine()) as session:
|
||||
session.add(Pacientes(pac_id_hospital="H-1", pac_fecha_nacimiento=date(2020, 1, 1), pac_sexo="F"))
|
||||
session.commit()
|
||||
|
||||
staging = staging_repository.leer(etl.STAGING)
|
||||
lote = etl.lote_de_estudios(**staging)
|
||||
carga_repository.guardar_lote(**lote.para_guardar())
|
||||
|
||||
tablas = tablas_de("tea")
|
||||
measures = measures_de("tea")
|
||||
tipos = sorted({t for m in measures.values() for t in m.extension.publicacion.tipos_periodo})
|
||||
def_parametro_repository.reemplazar(leer_parametros(RUTA_PARAMETROS, tablas=tablas))
|
||||
dim_periodo_repository.agregar_faltantes(periodos_de_tipos(tipos, 2024, 2024, tablas=tablas))
|
||||
indicador_definicion_repository.reemplazar(leer_definiciones(rutas_de_measures("tea"), tablas=tablas))
|
||||
nombre, medida = next(iter(measures.items()))
|
||||
for tipo in medida.extension.publicacion.tipos_periodo:
|
||||
for periodo_id in calculo_repository.periodos(tipo, date(2024, 1, 1), date(2025, 1, 1)):
|
||||
medir = partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas,
|
||||
corte=None, permitir_sin_definir=True)
|
||||
calculo_repository.calcular(medir)
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_list_indicadores(client):
|
||||
"""Only the 5 TEA measures not marked `oculto` in their own TOML publish
|
||||
to the catalog (the K01-K08/M02-M19 family is draft/internal); a hidden
|
||||
id still answers `/datos` directly, see `test_indicador_datos_...`."""
|
||||
response = client.get("/tea/indicadores")
|
||||
assert response.status_code == 200
|
||||
indicadores = response.get_json()
|
||||
assert isinstance(indicadores, list)
|
||||
assert len(indicadores) == 5
|
||||
assert {"id", "titulo", "contrato", "unidad", "sentido", "tipos_periodo", "estratos", "figuras"} <= indicadores[0].keys()
|
||||
|
||||
|
||||
def test_indicador_datos_returns_valid_json_no_bare_nan(client):
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos?periodos=2024-S1,2024-S2")
|
||||
assert response.status_code == 200
|
||||
# Pandas renders missing scores as NaN; the response must not leak the
|
||||
# bare (invalid-JSON) token -- it has to come through as `null`.
|
||||
assert "NaN" not in response.get_data(as_text=True)
|
||||
body = response.get_json()
|
||||
assert body["id"] == "K01_evaluacion_3_meses"
|
||||
assert set(body["periodos"]) == {"2024-S1", "2024-S2"}
|
||||
assert {row["periodo"] for row in body["filas"]} == {"2024-S1", "2024-S2"}
|
||||
|
||||
|
||||
def test_indicador_datos_without_periodos_defaults_to_available_ones(client):
|
||||
"""Unlike the old endpoint, omitting `periodos` is not an error: it
|
||||
reports whatever periods already have a computed report."""
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["periodos"]
|
||||
|
||||
|
||||
def test_indicador_datos_unknown_indicador_is_404(client):
|
||||
response = client.get("/tea/indicadores/NOPE/datos?periodos=2024-S1")
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_indicador_datos_malformed_periodo_is_400(client):
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos?periodos=no-es-un-periodo")
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_indicador_periodos_endpoint(client):
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/periodos")
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["id"] == "K01_evaluacion_3_meses"
|
||||
assert isinstance(body["periodos"], list)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cacu_client(wire_domain):
|
||||
"""CaCu reproduces a real id mismatch TEA's fixture doesn't: some of its
|
||||
TOML files are named in lowercase (`cacu_biopsias.toml`, the
|
||||
`measures_de` dict key) while their `measure.url` ends in uppercase
|
||||
(`cacu/CACU_BIOPSIAS`, the id `indicador_definicion.indicador` and the
|
||||
catalog publish) -- caught live by driving the WebApp dashboard against
|
||||
a real CaCu indicator, not by the TEA-only fixture above."""
|
||||
wire_domain("cacu")
|
||||
|
||||
from sqlmodel import Session
|
||||
from persistance import db as persistance_db
|
||||
from persistance.cacu import (
|
||||
staging_repository, carga_repository, def_parametro_repository as cacu_def_parametro_repository,
|
||||
dim_periodo_repository, indicador_definicion_repository, calculo_repository, vistas_repository,
|
||||
)
|
||||
from indicadores_kit.cacu import etl, fixtures
|
||||
from indicadores_kit.cdm.etl import lote_de_resultados
|
||||
from indicadores_kit.esquema import ddl_de_vistas
|
||||
from indicadores_kit.registry.parametros import leer_parametros, RUTA_PARAMETROS
|
||||
from indicadores_kit.registry.periodos import periodos_de_tipos
|
||||
from indicadores_kit.registry.measures import measures_de, rutas_de_measures
|
||||
from indicadores_kit.serving.definiciones import leer_definiciones
|
||||
from indicadores_kit.mart.calculo import medir_con_unidades
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
with Session(persistance_db.get_cacu_engine()) as session:
|
||||
fixtures.insertar(session)
|
||||
session.commit()
|
||||
|
||||
tablas = tablas_de("cacu")
|
||||
staging = staging_repository.leer(etl.STAGING)
|
||||
lote = etl.lote_de_estudios(**staging)
|
||||
carga_repository.guardar_lote(**lote.para_guardar())
|
||||
pacientes = staging_repository.leer({"pacientes": etl.STAGING["pacientes"]})["pacientes"]
|
||||
lote_resultados = lote_de_resultados(
|
||||
pacientes, staging_repository.leer(etl.STAGING_DE_RESULTADOS), etl.FUENTES_DE_RESULTADOS, tablas=tablas,
|
||||
)
|
||||
carga_repository.guardar_lote(**lote_resultados.para_guardar())
|
||||
vistas_repository.construir(ddl_de_vistas("cacu"))
|
||||
|
||||
measures = measures_de("cacu")
|
||||
tipos = sorted({t for m in measures.values() for t in m.extension.publicacion.tipos_periodo})
|
||||
cacu_def_parametro_repository.reemplazar(leer_parametros(RUTA_PARAMETROS, tablas=tablas))
|
||||
dim_periodo_repository.agregar_faltantes(periodos_de_tipos(tipos, 2025, 2025, tablas=tablas))
|
||||
indicador_definicion_repository.reemplazar(leer_definiciones(rutas_de_measures("cacu"), tablas=tablas))
|
||||
for medida in measures.values():
|
||||
for tipo in medida.extension.publicacion.tipos_periodo:
|
||||
for periodo_id in calculo_repository.periodos(tipo, date(2025, 1, 1), date(2026, 1, 1)):
|
||||
medir = partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas,
|
||||
corte=None, permitir_sin_definir=True)
|
||||
calculo_repository.calcular(medir)
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_indicador_datos_uses_the_toml_key_not_measure_url(cacu_client):
|
||||
"""`cacu_biopsias`'s own `measure.url` ends in `CACU_BIOPSIAS` (uppercase),
|
||||
but `registrar_indicadores` publishes and looks measures up by
|
||||
`measures_de()`'s dict key (the lowercase TOML file stem) throughout, so
|
||||
the mismatch never reaches a client -- unlike the old, since-replaced
|
||||
`webapi.indicadores`, which published the uppercase `measure.url` id and
|
||||
needed its own `_measure_por_indicador` lookup to reconcile the two."""
|
||||
catalogo = cacu_client.get("/cacu/indicadores").get_json()
|
||||
assert any(i["id"] == "cacu_biopsias" for i in catalogo)
|
||||
assert not any(i["id"] == "CACU_BIOPSIAS" for i in catalogo)
|
||||
|
||||
response = cacu_client.get("/cacu/indicadores/cacu_biopsias/datos?periodos=2025-S1,2025-S2")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["filas"]
|
||||
@@ -0,0 +1,169 @@
|
||||
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
|
||||
@@ -19,8 +19,10 @@ def client(wire_domain):
|
||||
|
||||
|
||||
def test_imported_rows_are_what_models_reads_and_model_writes_are_what_the_api_serves(client):
|
||||
"""Rows imported over HTTP are read back through `models`' repository, and a row written there is served by
|
||||
the API. Fails if `resolve_repository` stops returning the objects WebApi writes with."""
|
||||
from core.cama.models import Mastografia
|
||||
from models.cama import CaMaModel
|
||||
from models.io.storage import resolve_repository
|
||||
|
||||
csv = b"Expediente,BIRADS\nRT-1,BI-RADS 4\nRT-2,2\n"
|
||||
response = client.post(
|
||||
@@ -38,11 +40,11 @@ def test_imported_rows_are_what_models_reads_and_model_writes_are_what_the_api_s
|
||||
)
|
||||
assert response.get_json()["results"][0]["created"] == 2
|
||||
|
||||
model = CaMaModel()
|
||||
seen = {row["pac_id_hospital"]: row["mast_birads"] for row in model.dataset("mastografia")}
|
||||
repository = resolve_repository("cama", "mastografia")
|
||||
seen = {row.pac_id_hospital: row.mast_birads for row in repository.iter_all()}
|
||||
assert seen == {"RT-1": "B4", "RT-2": "B2"}
|
||||
|
||||
model.repository("mastografia").create(Mastografia(pac_id_hospital="RT-FROM-MODEL", mast_birads="B1"))
|
||||
repository.create(Mastografia(pac_id_hospital="RT-FROM-MODEL", mast_birads="B1"))
|
||||
served = client.get("/data/cama.Mastografia").get_json()
|
||||
assert served["total"] == 3
|
||||
assert "RT-FROM-MODEL" in {row["pac_id_hospital"] for row in served["rows"]}
|
||||
|
||||
@@ -100,7 +100,6 @@ def test_several_edf_files_load_into_eeg_estudio_with_the_file(client):
|
||||
"target": "tea.EegEstudio",
|
||||
"column_mapping": {
|
||||
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"paciente": "eeg_pac_id",
|
||||
"fecha_estudio": "eeg_fecha_estudio",
|
||||
"duracion_min": "eeg_duracion_min",
|
||||
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"""El ciclo deja los mismos reportes que la base de demostración del kit.
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
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
|
||||
|
||||
ANIO = 2025
|
||||
# Lo que guarda cada reporte (T-19e): sus unidades de §6f. El número publicado sale de ellas (las vistas).
|
||||
CONSULTA = text("""
|
||||
SELECT r.measure_url, r.measure_version, r.periodo_id, r.fecha_corte, r.huella,
|
||||
u.grupo, u.unidad_id, u.resultado_id, u.valor_id, ROUND(u.numero, 12)
|
||||
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"])
|
||||
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
|
||||
# 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"])
|
||||
motor = create_engine(url)
|
||||
with Session(motor) as sesion:
|
||||
import_module(f"indicadores_kit.{proyecto}.fixtures").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
|
||||
|
||||
|
||||
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")
|
||||
|
||||
|
||||
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):
|
||||
_, ctx, motor, _, _ = bases
|
||||
with motor.connect() as con:
|
||||
antes = con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one()
|
||||
correr(ctx)
|
||||
with motor.connect() as con:
|
||||
assert con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() == antes
|
||||
|
||||
|
||||
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
|
||||
return
|
||||
(armado_id, nuevo), = [p.resumen for p in pasos if p.nombre == "cohortes"][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
|
||||
@@ -0,0 +1,192 @@
|
||||
"""Los pasos de oro sobre la base del dominio: el registro, las definiciones y el cálculo.
|
||||
|
||||
Vienen del kit (`test_pasos` y `test_produccion`, MD-16). El reporte se lee por los
|
||||
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 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",)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
tablas = tablas_de(base.proyecto)
|
||||
esperados = periodos_de_tipos(tipos_de_periodo(base.proyecto), 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
|
||||
|
||||
valores = valores_del_archivo(RUTA_PARAMETROS)
|
||||
desde = date.fromisoformat(valores["comun.dim_fecha.desde"])
|
||||
fechas = base.dominio.dim_fecha_repository
|
||||
hasta = date(max(ANIO + 1, date.today().year), 12, 31) # o el año del corte (hoy), si es mayor
|
||||
assert fechas.count() == (hasta - desde).days + 1
|
||||
grupos = [g.etiqueta for g in base.dominio.dim_grupo_edad_repository.list(limit=100)]
|
||||
cortes = valores.get(f"{base.proyecto}.grupos_edad")
|
||||
esperados = [] if cortes is None else [g.etiqueta for g in grupos_de_cortes(cortes, tablas=tablas_de(base.proyecto))]
|
||||
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")
|
||||
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)
|
||||
|
||||
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"]
|
||||
|
||||
assert resumen["definiciones"] == len(measures_de(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
|
||||
|
||||
|
||||
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
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Las dependencias entre los pasos de cada proyecto, como las lee Hamilton de los parámetros."""
|
||||
|
||||
import pytest
|
||||
from hamilton import driver
|
||||
|
||||
from webapi.orquestacion import ciclo, pasos_de
|
||||
|
||||
|
||||
def dependencias(proyecto: str) -> dict[str, set[str]]:
|
||||
dr = driver.Builder().with_modules(ciclo).with_config({"con_cohortes": 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()
|
||||
if anterior not in previos:
|
||||
previos.add(anterior)
|
||||
pendientes.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")
|
||||
|
||||
|
||||
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"))
|
||||
for proyecto in ("cama", "tea"):
|
||||
assert not {"cohortes", "estimar"} & set(pasos_de(proyecto))
|
||||
@@ -0,0 +1,269 @@
|
||||
"""Los pasos de plata sobre la base del dominio: los catálogos, cargar (staging directo, T-20c), las vistas y observar.
|
||||
|
||||
Vienen del kit (`test_pasos`, `test_produccion` y `test_observacion`, MD-16): el kit
|
||||
ya no tiene pasos, y lo que se prueba aquí es cómo los pasos componen sus
|
||||
funciones con los repositorios de Persistance.
|
||||
"""
|
||||
|
||||
import json
|
||||
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 (
|
||||
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 sqlalchemy import inspect, text
|
||||
from sqlmodel import select
|
||||
|
||||
# Un cambio en staging y la fila de la plata que toca: (tabla de staging, columna, valor nuevo).
|
||||
CAMBIO = {
|
||||
"cacu": ("citologiacervical", "cit_calidad_especimen", "INSATISFACTORIO"),
|
||||
"cama": ("mastografia", "mast_calidad_imagen", "OTRA CALIDAD"),
|
||||
"tea": ("evaluacion_psicologica", "psi_fecha_ados2", date(2024, 12, 1)),
|
||||
}
|
||||
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)
|
||||
|
||||
|
||||
def contar(base, sql: str) -> int:
|
||||
with base.motor.connect() as con:
|
||||
return con.execute(text(sql)).scalar_one()
|
||||
|
||||
|
||||
def plata_de(base) -> tuple[int, int]:
|
||||
return contar(base, "SELECT COUNT(*) FROM procedimiento"), contar(base, "SELECT COUNT(*) FROM observacion_clinica")
|
||||
|
||||
|
||||
def cambiar_staging(base) -> str:
|
||||
"""Aplica `CAMBIO` a la primera fila de su tabla de staging. Devuelve su llave."""
|
||||
tabla, columna, nuevo = CAMBIO[base.proyecto]
|
||||
(modelo,) = [m for m in tablas_de_staging(base.proyecto) if m.__tablename__ == tabla]
|
||||
(llave,) = modelo.__table__.primary_key.columns
|
||||
with base.staging() as sesion:
|
||||
fila = sesion.exec(select(modelo).order_by(llave)).first()
|
||||
setattr(fila, columna, nuevo)
|
||||
sesion.commit()
|
||||
return str(getattr(fila, llave.name))
|
||||
|
||||
|
||||
# --- catalogos ---
|
||||
|
||||
|
||||
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
|
||||
with base.staging() as sesion:
|
||||
return {
|
||||
"estudios": len(sesion.exec(select(plata.model)).all()),
|
||||
"resultados": len(sesion.exec(select(plata.resultado)).all()),
|
||||
"valores": len(sesion.exec(select(plata.valor)).all()),
|
||||
}
|
||||
|
||||
|
||||
def test_catalogos_deja_en_la_base_las_filas_del_toml(base):
|
||||
catalogo = catalogo_desde_toml(ruta_de_catalogo(base.proyecto), tablas=tablas_de(base.proyecto))
|
||||
del_toml = {"estudios": len(catalogo.estudios), "resultados": len(catalogo.resultados),
|
||||
"valores": len(catalogo.valores)}
|
||||
|
||||
assert base.correr("catalogos")["catalogos"] == {**del_toml, "retirados": 0}
|
||||
assert filas_del_catalogo(base) == del_toml
|
||||
|
||||
|
||||
def test_volver_a_correr_catalogos_no_cambia_nada(base):
|
||||
base.correr("catalogos")
|
||||
antes = filas_del_catalogo(base)
|
||||
|
||||
assert base.correr("catalogos")["catalogos"]["retirados"] == 0
|
||||
assert filas_del_catalogo(base) == antes
|
||||
|
||||
|
||||
# --- cargar (staging directo) ---
|
||||
|
||||
|
||||
def test_cargar_lleva_el_staging_a_persona_y_la_plata(base):
|
||||
base.correr("catalogos")
|
||||
carga = base.correr("cargar")["cargar"]
|
||||
|
||||
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(
|
||||
{"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
|
||||
# Desde F6 (ADR-MD-009) no hay tablas por tipo: la base solo tiene las del kit, staging y lo restringido.
|
||||
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")
|
||||
antes = plata_de(base)
|
||||
|
||||
segunda = base.correr("cargar")["cargar"]
|
||||
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"):
|
||||
assert contar(base, f"SELECT COUNT(*) FROM {tabla} WHERE carga_id = {segunda.carga_id}") == 0
|
||||
|
||||
|
||||
def test_un_cambio_en_staging_toca_un_procedimiento(base):
|
||||
base.correr("catalogos", "cargar")
|
||||
antes = plata_de(base)
|
||||
cambiar_staging(base)
|
||||
|
||||
segunda = base.correr("cargar")["cargar"]
|
||||
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"]
|
||||
|
||||
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"]
|
||||
|
||||
|
||||
# --- observar ---
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def con_regla(tmp_path, proyecto):
|
||||
"""Una copia de `parametros.toml` con el inicio de los datos del proyecto en ese valor y estado."""
|
||||
|
||||
def escribir(valor="2023-01-01", estado="provisional"):
|
||||
texto = RUTA_PARAMETROS.read_text(encoding="utf-8")
|
||||
cabecera = f"[{clave_de_inicio(proyecto)}]"
|
||||
antes, despues = texto.split(cabecera)
|
||||
despues = despues.replace('valor = "2023-01-01"', f'valor = "{valor}"', 1).replace(
|
||||
'estado = "sin_definir"', f'estado = "{estado}"', 1)
|
||||
ruta = tmp_path / "con_regla.toml"
|
||||
ruta.write_text(antes + cabecera + despues, encoding="utf-8")
|
||||
return ruta
|
||||
|
||||
return escribir
|
||||
|
||||
|
||||
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"))
|
||||
|
||||
cuantos = base.correr("observar", corte=CORTE)["observar"]
|
||||
|
||||
periodos = base.dominio.periodo_observacion_repository.list()
|
||||
assert cuantos == len(periodos) == base.dominio.persona_repository.count()
|
||||
assert {(p.fecha_inicio, p.fecha_fin, p.tipo_periodo) for p in periodos} == {
|
||||
(date(2024, 6, 1), CORTE, TIPO_EXTRACCION)}
|
||||
|
||||
|
||||
@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.correr("observar")
|
||||
|
||||
carga = ultima_carga(base)
|
||||
assert {p.fecha_fin for p in base.dominio.periodo_observacion_repository.list()} == {
|
||||
(carga.fin or carga.inicio).date()}
|
||||
|
||||
|
||||
@observables
|
||||
def test_observar_se_puede_repetir_sin_duplicar(base, con_regla):
|
||||
base.correr("cargar", "registro", parametros=con_regla())
|
||||
|
||||
primera = base.correr("observar", corte=date(2025, 6, 30))["observar"]
|
||||
segunda = base.correr("observar", corte=CORTE)["observar"]
|
||||
|
||||
assert primera == segunda == base.dominio.periodo_observacion_repository.count()
|
||||
assert {p.fecha_fin for p in base.dominio.periodo_observacion_repository.list()} == {CORTE}
|
||||
|
||||
|
||||
@observables
|
||||
def test_la_regla_de_inicio_sin_definir_hay_que_pedirla_a_proposito(base):
|
||||
base.correr("cargar", "registro")
|
||||
|
||||
with pytest.raises(ParametroSinDefinir, match="inicio_datos"):
|
||||
base.correr("observar", corte=CORTE)
|
||||
assert base.correr("observar", corte=CORTE, permitir_sin_definir=True)["observar"] == (
|
||||
base.dominio.persona_repository.count())
|
||||
|
||||
|
||||
@observables
|
||||
def test_sin_el_registro_observar_dice_que_falta(base):
|
||||
base.correr("cargar")
|
||||
|
||||
with pytest.raises(KeyError, match="preparar_registro|registro"):
|
||||
base.correr("observar", corte=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"))
|
||||
|
||||
with pytest.raises(ValueError, match="anterior al inicio"):
|
||||
base.correr("observar", corte=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())
|
||||
|
||||
with pytest.raises(ObservacionSinCorte):
|
||||
base.correr("observar")
|
||||
|
||||
|
||||
# --- La carga doble (F5, ADR-MD-007): CaCu, CaMa y TEA ---
|
||||
|
||||
# --- verificar_plata (calidad de la plata de dos tablas) ---
|
||||
|
||||
@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"]
|
||||
|
||||
# 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`.
|
||||
i_md16 = contar(base, "SELECT COUNT(*) FROM observacion_clinica WHERE valor_fuente IN ('NEGATIVO', 'CIN1', 'CIN2')")
|
||||
fuera = contar(base, "SELECT COUNT(*) FROM observacion_clinica WHERE valor_id IS NULL AND valor_fuente IS NOT NULL")
|
||||
assert i_md16 > 0
|
||||
assert (conteos["reporte_sin_padre"], conteos["de_otro_estudio"]) == (0, 0)
|
||||
assert conteos["fuera_de_catalogo"] == fuera
|
||||
@@ -0,0 +1,30 @@
|
||||
"""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
|
||||
qué base apunta Persistance (`<PROYECTO>_DATABASE_URL` en memoria); no es un paso.
|
||||
"""
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from webapi.orquestacion.repositorios import repositorios_de
|
||||
|
||||
PAQUETE = Path(__file__).parents[1] / "webapi" / "orquestacion"
|
||||
EXENTOS = {"conexion.py"}
|
||||
PROHIBIDO = re.compile(r"fabrica_por_defecto|get_(cacu|cama|tea)_session|get_\{|Session\(|persistance\.db")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("modulo", sorted(str(p.relative_to(PAQUETE)) for p in PAQUETE.rglob("*.py") if p.name not in EXENTOS and ".ipynb_checkpoints" not in p.parts))
|
||||
def test_ningun_modulo_fuera_de_repositorios_abre_sesiones(modulo):
|
||||
texto = (PAQUETE / modulo).read_text(encoding="utf-8")
|
||||
assert not PROHIBIDO.findall(texto), f"{modulo} abre su propia sesión: debe usar ctx.repos"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True), ("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"
|
||||
@@ -0,0 +1,115 @@
|
||||
"""El paso `estimar` y la orden `confirmar-riesgos` (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.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from webapi.orquestacion.__main__ import confirmar_riesgos, main
|
||||
|
||||
URL = "cacu/cohorte_vigilancia"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Procedencia:
|
||||
modelo_nombre: str = "prueba"
|
||||
modelo_version: str = "1"
|
||||
mlflow_run_id: str = "sin-mlflow"
|
||||
modelo_sha: str = "sha-de-prueba"
|
||||
|
||||
def como_dict(self):
|
||||
return dict(self.__dict__)
|
||||
|
||||
|
||||
class EstimadorFijo:
|
||||
"""Cumple el contrato: un riesgo por miembro, `probabilidad` (0.1) al `horizonte` (0)."""
|
||||
|
||||
desenlace = "cin2_mas"
|
||||
|
||||
def __init__(self, cohorte_url=URL, horizonte=0.0, probabilidad=0.1):
|
||||
self.cohorte_url, self.horizonte, self.probabilidad = cohorte_url, horizonte, probabilidad
|
||||
self.columnas = None
|
||||
|
||||
def procedencia(self):
|
||||
return Procedencia()
|
||||
|
||||
def estimar(self, columnas, filas):
|
||||
self.columnas = columnas
|
||||
return [(fila[0], self.horizonte, self.probabilidad, None, None) for fila in filas]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cacu(base):
|
||||
base.correr("catalogos", "cargar", "cohortes", permitir_sin_definir=True)
|
||||
return base
|
||||
|
||||
|
||||
def cuenta(base, sql):
|
||||
with base.motor.connect() as con:
|
||||
return con.execute(text(sql)).scalar_one()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
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]
|
||||
|
||||
miembros = cuenta(cacu, "SELECT n_miembros FROM cohorte_armado ORDER BY armado_id DESC LIMIT 1")
|
||||
assert nuevo and miembros > 0
|
||||
assert estimador.columnas[:2] == ["pac_id", "fecha_indice"] # el marco ancho de `leer_marco`
|
||||
assert cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}") == miembros
|
||||
assert cuenta(cacu, "SELECT COUNT(DISTINCT estado) FROM evaluacion_riesgo") == 1
|
||||
assert cuenta(cacu, "SELECT MIN(estado) FROM evaluacion_riesgo") == "preliminary"
|
||||
|
||||
|
||||
@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]
|
||||
|
||||
assert cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL] == (primero, False)
|
||||
assert cacu.correr("estimar")["estimar"] == {}
|
||||
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]
|
||||
miembros = cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}")
|
||||
|
||||
main(["confirmar-riesgos", "cacu", str(lote_id), "--motivo", "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 cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'entered-in-error'") == miembros
|
||||
|
||||
|
||||
# Por proyecto: la cohorte, el horizonte de sus bandas y su resumen por banda. Desde T-21h solo CaCu arma
|
||||
# su cohorte; las de TEA y CaMa son propuestas y su punta a punta está en `models` y en el kit.
|
||||
DE_PUNTA_A_PUNTA = {
|
||||
"cacu": (URL, 0.0, "cacu/CACU_RIESGO_BANDA"),
|
||||
}
|
||||
|
||||
|
||||
@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
|
||||
@@ -0,0 +1,64 @@
|
||||
"""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.
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from importlib import import_module
|
||||
|
||||
from indicadores_kit.oro.cohortes.armado import filas_de_linea
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
from sqlmodel import Session
|
||||
|
||||
CORTE = date(2025, 12, 31)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
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.
|
||||
|
||||
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)
|
||||
assert {row["pac_id"] for row in rows} == set(patients)
|
||||
assert rows == kit_rows(base, pacientes=patients, hasta=CORTE)
|
||||
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,87 @@
|
||||
"""What this module covers: `GET /cacu/pacientes/<pac_id>/riesgo` (`webapi.patient_risk`): when the route exists, the
|
||||
shape the WebApp's contract reads (`RiesgoPacienteCacu`), and its 404. The reads behind it are Persistance's, tested
|
||||
there.
|
||||
|
||||
Fixtures: `client`, the app without `DEV_REVISION` over the kit's CaCu demonstration database (`conftest.cliente_de`)
|
||||
plus `seeded`: a surveillance build with two of its patients, one of them with variables and a confirmed batch.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
COHORT_KEYS = {"url", "version", "fecha_indice", "tipo_censura", "c", "l", "r", "pap_0", "hpv_0"}
|
||||
RISK_KEYS = {"lote_id", "modelo_nombre", "modelo_version", "evaluado_en", "estado_lote", "horizontes"}
|
||||
HORIZON_KEYS = {"horizonte_anios", "probabilidad", "ic_bajo", "ic_alto", "estado"}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
"""The app over the CaCu demonstration database, with no `DEV_REVISION` in the environment."""
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def seeded(client):
|
||||
"""Two patients of the demo data in a new surveillance build; the first has `pap_0`, `c` and a batch with risks at
|
||||
1 and 3 years, confirmed. Returns (scored patient, member without risks, patient outside the build)."""
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, CohorteVariable
|
||||
from persistance import cacu
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
scored, unscored, outside = [p.pac_id for p in cacu.persona_repository.list(limit=3)]
|
||||
with get_cacu_session() as session:
|
||||
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2026, 12, 31), huella="risk-route", marco_sha="m",
|
||||
n_miembros=2, armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc))
|
||||
session.add(build)
|
||||
session.flush()
|
||||
session.add_all([CohorteMiembro(armado_id=build.armado_id, pac_id=p, fecha_indice=date(2025, 3, 1),
|
||||
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(p))
|
||||
for p in (scored, unscored)])
|
||||
session.flush()
|
||||
session.add_all([CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="pap_0", valor_codigo="ASC-US"),
|
||||
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(
|
||||
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")
|
||||
return scored, unscored, outside
|
||||
|
||||
|
||||
def test_a_scored_member_has_the_contracts_shape(client, seeded):
|
||||
"""Pins down: without `DEV_REVISION` the route exists, and the body has `simulado`, `cohorte` and `riesgo` with
|
||||
exactly the contract's fields, the horizons in ascending order, probabilities in 0..1 and the date as ISO-8601 UTC.
|
||||
Fails if the route depends on an environment variable again, or if a field is renamed or dropped, which would break
|
||||
the WebApp's validation."""
|
||||
response = client.get(f"/cacu/pacientes/{seeded[0]}/riesgo")
|
||||
|
||||
body = response.get_json()
|
||||
assert response.status_code == 200 and body["simulado"] is True
|
||||
assert set(body["cohorte"]) == COHORT_KEYS and set(body["riesgo"]) == RISK_KEYS
|
||||
assert (body["cohorte"]["pap_0"], body["cohorte"]["c"], body["cohorte"]["hpv_0"]) == ("ASC-US", 0.0, None)
|
||||
assert body["riesgo"]["evaluado_en"] == "2026-10-01T00:00:00Z" and body["riesgo"]["estado_lote"] == "final"
|
||||
horizons = body["riesgo"]["horizontes"]
|
||||
assert all(set(h) == HORIZON_KEYS for h in horizons)
|
||||
assert [(h["horizonte_anios"], h["probabilidad"], h["estado"]) for h in horizons] == [(1.0, 0.1, "final"), (3.0, 0.3, "final")]
|
||||
|
||||
|
||||
def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded):
|
||||
"""Pins down: a member nobody scored has `cohorte` and `riesgo: null`; a patient outside the latest build has both
|
||||
null. Fails if either case errors or invents a risk."""
|
||||
member = client.get(f"/cacu/pacientes/{seeded[1]}/riesgo").get_json()
|
||||
outside = client.get(f"/cacu/pacientes/{seeded[2]}/riesgo").get_json()
|
||||
|
||||
assert member["cohorte"] is not None and member["riesgo"] is None
|
||||
assert outside == {"simulado": True, "cohorte": None, "riesgo": None}
|
||||
|
||||
|
||||
def test_an_unknown_patient_is_404(client, seeded):
|
||||
"""Pins down: a `pac_id` not in `persona` is 404. Fails if it answers with an empty body as if she existed."""
|
||||
assert client.get("/cacu/pacientes/987654321/riesgo").status_code == 404
|
||||
@@ -0,0 +1,138 @@
|
||||
"""The aggregate import log and the live indicator recomputation."""
|
||||
import base64
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
MAPPING = {
|
||||
"pac_id_hospital": "pac_id_hospital",
|
||||
"pac_sexo": "pac_sexo",
|
||||
"pac_fecha_nacimiento": "pac_fecha_nacimiento",
|
||||
"pac_codigo_postal": "pac_codigo_postal",
|
||||
}
|
||||
|
||||
|
||||
def _csv(rows: list[str]) -> dict:
|
||||
body = "\n".join(["pac_id_hospital,pac_sexo,pac_fecha_nacimiento,pac_codigo_postal", *rows]).encode()
|
||||
return {
|
||||
"source_type": "csv",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": MAPPING,
|
||||
"payload": {"file_base64": base64.b64encode(body).decode(), "options": {"file_name": "Garcia_Lopez.csv"}},
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain, tmp_path_factory):
|
||||
wire_domain("cacu")
|
||||
import os
|
||||
|
||||
os.environ["WEBAPI_REPORT_DIR"] = str(tmp_path_factory.mktemp("reportes"))
|
||||
os.environ["INDICADORES_DIR"] = str(tmp_path_factory.mktemp("indicadores"))
|
||||
os.environ["INDICADORES_DESDE"] = "2025"
|
||||
os.environ["INDICADORES_HASTA"] = "2025"
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def _log():
|
||||
from webapi.imports.audit import default_sink
|
||||
|
||||
return default_sink().read()
|
||||
|
||||
|
||||
def test_commit_is_logged_as_aggregates_only(client):
|
||||
rows = [f"RPT-{i},F,1980-01-0{i % 9 + 1},64000" for i in range(4)]
|
||||
rows += [f"RPT-BAD-{i},POSITIVO,15/13/1980,64000" for i in range(6)]
|
||||
rows += ["RPT-RARE,QWERTY,1980-01-01,"]
|
||||
response = client.post("/imports/commit", json={"sources": [_csv(rows)], "on_conflict": "reject"})
|
||||
body = response.get_json()
|
||||
assert response.status_code == 200
|
||||
assert body["results"][0]["created"] == 4
|
||||
assert body["indicadores_en_recalculo"] is True
|
||||
|
||||
record = _log()[-1]
|
||||
assert record["id"] == body["audit_id"]
|
||||
assert (record["operacion"], record["dominio"], record["resultado"]) == ("carga", "cacu", "completada")
|
||||
source = record["fuentes"][0]
|
||||
assert source["origen"] == {"tipo": "csv", "extensiones": [".csv"]}
|
||||
assert source["filas"]["leidas"] == 11
|
||||
assert source["filas"]["insertadas"] == 4
|
||||
assert source["filas"]["rechazadas_en_validacion"] == 7
|
||||
sexo = source["campos"]["pac_sexo"]
|
||||
assert sexo["valores_fuera_de_catalogo"] == {"POSITIVO": 6}
|
||||
assert sexo["valores_fuera_de_catalogo_poco_frecuentes"] == 1
|
||||
assert source["campos"]["pac_fecha_nacimiento"]["formatos_rechazados"] == {"99/99/9999": 6}
|
||||
assert source["campos"]["pac_codigo_postal"]["vacios"] == 1
|
||||
|
||||
raw = json.dumps(record)
|
||||
for secret in ("RPT-", "Garcia", "QWERTY", "15/13/1980"):
|
||||
assert secret not in raw
|
||||
|
||||
|
||||
def test_failed_request_and_validation_are_logged(client):
|
||||
bad = _csv(["RPT-X,F,1980-01-01,64000"])
|
||||
bad["target"] = "cacu.NoExiste"
|
||||
assert client.post("/imports/commit", json={"sources": [bad]}).status_code == 400
|
||||
assert _log()[-1]["resultado"] == "solicitud_invalida"
|
||||
|
||||
assert client.post("/imports/validate", json={"source": _csv(["RPT-V,F,1980-01-01,64000"])}).status_code == 200
|
||||
last = _log()[-1]
|
||||
assert (last["operacion"], last["resultado"]) == ("validacion", "completada")
|
||||
assert last["fuentes"][0]["filas"]["validas"] == 1
|
||||
|
||||
|
||||
def test_report_endpoints(client):
|
||||
body = client.get("/reportes/importaciones").get_json()
|
||||
paciente = body["resumen"]["destinos"]["cacu.Paciente"]
|
||||
assert paciente["cargas_completadas"] == 1
|
||||
assert paciente["filas_en_cargas_completadas"]["insertadas"] == 4
|
||||
assert body["intentos"][0]["operacion"] == "validacion"
|
||||
download = client.get("/reportes/importaciones/descarga")
|
||||
assert len(download.get_data(as_text=True).strip().splitlines()) == len(_log())
|
||||
|
||||
|
||||
def test_indicators_recompute_from_imported_rows(client):
|
||||
from webapi.indicadores_vivos import ColaDeRecalculo
|
||||
|
||||
cola = ColaDeRecalculo()
|
||||
assert client.get("/reportes/indicadores").get_json()["cacu"]["pendiente"] is True
|
||||
assert cola.atender() == ["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 client.post("/reportes/indicadores/cacu/recalcular").status_code == 202
|
||||
assert client.post("/reportes/indicadores/xx/recalcular").status_code == 404
|
||||
|
||||
|
||||
def test_headerless_file_does_not_leak_its_first_record():
|
||||
"""Without a header row the first record becomes the column names."""
|
||||
from webapi.imports.audit import column_label
|
||||
|
||||
for header in ("pac_id_hospital", "fecha_nacimiento", "cit_vph_genotipo_16", "Sexo", "Código postal"):
|
||||
assert column_label(header) == header
|
||||
for value, shape in (("N-0001", "A-9999"), ("1980-01-01", "9999-99-99"), ("64000", "99999"),
|
||||
("H123", "A999"), ("ana@x.mx", "AAA@A.AA")):
|
||||
assert column_label(value) == shape
|
||||
note = "Paciente refiere dolor pélvico desde hace tres semanas"
|
||||
assert note not in column_label(note)
|
||||
|
||||
|
||||
def test_headerless_csv_logs_shapes(client):
|
||||
body = "N-0001,F,1980-01-01\nN-0002,F,1981-02-02\n".encode()
|
||||
source = {
|
||||
"source_type": "csv", "target": "cacu.Paciente",
|
||||
"column_mapping": {"N-0001": "pac_id_hospital", "F": "pac_sexo", "1980-01-01": "pac_fecha_nacimiento"},
|
||||
"payload": {"file_base64": base64.b64encode(body).decode()},
|
||||
}
|
||||
client.post("/imports/validate", json={"source": source})
|
||||
raw = json.dumps(_log()[-1])
|
||||
assert "N-0001" not in raw and "1980-01-01" not in raw
|
||||
assert "A-9999" in raw
|
||||
+31
-17
@@ -1,7 +1,7 @@
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from webapi.imports.mapping.column_matcher import ColumnMatcher
|
||||
from webapi.imports.mapping.column_matcher import suggest_mapping
|
||||
from webapi.imports.schemas.cacu.paciente import PacienteImportSchema
|
||||
from webapi.imports.schemas.classify import ErrorCategory, classify_error
|
||||
from webapi.imports.schemas.service import validate_rows
|
||||
@@ -88,10 +88,9 @@ def test_validate_rows_never_aborts_on_a_bad_row():
|
||||
|
||||
|
||||
def test_column_matcher_exact_normalized_synonym_fuzzy_none():
|
||||
matcher = ColumnMatcher()
|
||||
targets = ["pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"]
|
||||
|
||||
suggestions = matcher.suggest(
|
||||
suggestions = suggest_mapping(
|
||||
["pac_id_hospital", "Sexo", "fecha_nacimiento", "columna_sin_relacion_xyz"], targets
|
||||
)
|
||||
by_source = {s.source_column: s for s in suggestions}
|
||||
@@ -110,9 +109,8 @@ def test_column_matcher_exact_normalized_synonym_fuzzy_none():
|
||||
|
||||
|
||||
def test_column_matcher_enforces_one_to_one():
|
||||
matcher = ColumnMatcher()
|
||||
# two source columns that would both match "pac_sexo" exactly-ish
|
||||
suggestions = matcher.suggest(["pac_sexo", "sexo"], ["pac_sexo"])
|
||||
suggestions = suggest_mapping(["pac_sexo", "sexo"], ["pac_sexo"])
|
||||
matched_targets = [s.target_field for s in suggestions if s.target_field]
|
||||
assert matched_targets == ["pac_sexo"] # only the first claims it
|
||||
|
||||
@@ -134,14 +132,14 @@ def test_coerce_date_accepts_iso_day_first_and_timestamps_but_not_impossible_dat
|
||||
|
||||
def test_catalog_is_case_insensitive_accepts_member_names_and_rejects_unknowns():
|
||||
from core.cacu.enums import SEXO_BIOLOGICO_ALIAS, SexoBiologico
|
||||
from webapi.imports.schemas.coercion import Catalog, coerce_alias
|
||||
from webapi.imports.schemas.coercion import Catalog
|
||||
|
||||
catalog = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
assert coerce_alias(" femenino ", catalog) == "Femenino"
|
||||
assert coerce_alias("m", catalog) == "Masculino"
|
||||
assert coerce_alias("", catalog) is None
|
||||
assert catalog.coerce(" femenino ") == "Femenino"
|
||||
assert catalog.coerce("m") == "Masculino"
|
||||
assert catalog.coerce("") is None
|
||||
with pytest.raises(ValueError, match="no está en el catálogo"):
|
||||
coerce_alias("X", catalog)
|
||||
catalog.coerce("X")
|
||||
|
||||
|
||||
def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog():
|
||||
@@ -150,11 +148,11 @@ def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog():
|
||||
only models the base B0-B6 categories; without an alias for them, every
|
||||
such report was silently unimportable."""
|
||||
from core.cama.mastografia.enums import BIRADS, BIRADS_ALIAS
|
||||
from webapi.imports.schemas.coercion import Catalog, coerce_alias
|
||||
from webapi.imports.schemas.coercion import Catalog
|
||||
|
||||
catalog = Catalog(BIRADS, BIRADS_ALIAS)
|
||||
for value in ("4A", "BI-RADS 4B", "bi-rads 4c"):
|
||||
assert coerce_alias(value, catalog) == "B4"
|
||||
assert catalog.coerce(value) == "B4"
|
||||
|
||||
|
||||
def test_postal_code_restores_leading_zero_from_numeric_sources():
|
||||
@@ -167,11 +165,10 @@ def test_postal_code_restores_leading_zero_from_numeric_sources():
|
||||
|
||||
|
||||
def test_column_matcher_handles_accents_prefixes_and_global_one_to_one():
|
||||
matcher = ColumnMatcher()
|
||||
targets = ["pac_id_hospital", "pac_sexo", "pac_codigo_postal", "pac_fecha_nacimiento"]
|
||||
by_source = {
|
||||
s.source_column: s
|
||||
for s in matcher.suggest(["Fech nacim", "Género", "C.P.", "Expediente", "fecha_nacimiento"], targets)
|
||||
for s in suggest_mapping(["Fech nacim", "Género", "C.P.", "Expediente", "fecha_nacimiento"], targets)
|
||||
}
|
||||
assert by_source["Género"].target_field == "pac_sexo"
|
||||
assert by_source["C.P."].target_field == "pac_codigo_postal"
|
||||
@@ -183,7 +180,7 @@ def test_column_matcher_handles_accents_prefixes_and_global_one_to_one():
|
||||
|
||||
|
||||
def test_column_matcher_matches_names_without_the_table_prefix():
|
||||
suggestion = ColumnMatcher().suggest(["hemoglobina_g_dl", "birads"], ["hemoglobina_g_dl", "mast_birads"])
|
||||
suggestion = suggest_mapping(["hemoglobina_g_dl", "birads"], ["hemoglobina_g_dl", "mast_birads"])
|
||||
assert [(s.target_field, s.reason) for s in suggestion] == [("hemoglobina_g_dl", "exact"), ("mast_birads", "unprefixed")]
|
||||
|
||||
|
||||
@@ -206,14 +203,14 @@ def test_column_matcher_real_world_headers(target, source, expected):
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
fields = list(ENTITY_REGISTRY[target].schema.model_fields)
|
||||
assert ColumnMatcher().suggest([source], fields)[0].target_field == expected
|
||||
assert suggest_mapping([source], fields)[0].target_field == expected
|
||||
|
||||
|
||||
def test_column_matcher_does_not_guess_from_shared_letters_alone():
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
fields = list(ENTITY_REGISTRY["cacu.NotaMedica"].schema.model_fields)
|
||||
assert ColumnMatcher().suggest(["Observaciones del servicio xyz", "Clave única"], fields)[1].target_field is None
|
||||
assert suggest_mapping(["Observaciones del servicio xyz", "Clave única"], fields)[1].target_field is None
|
||||
|
||||
|
||||
def test_catalog_for_exposes_field_catalog_and_errors_stay_on_field():
|
||||
@@ -231,3 +228,20 @@ def test_catalog_for_exposes_field_catalog_and_errors_stay_on_field():
|
||||
assert classified.field == "pac_sexo"
|
||||
assert classified.category == ErrorCategory.OUT_OF_CATALOG
|
||||
assert "no está en el catálogo" in classified.message
|
||||
|
||||
|
||||
def test_catalog_aliases_for_values_the_indicator_kit_uses():
|
||||
"""Hospital spellings the indicator kit's own synthetic sources use must
|
||||
not be rejected at import."""
|
||||
from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.citologia_cervical import CitologiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import OrdenesEstudioImportSchema as CamaOrdenes
|
||||
from webapi.imports.schemas.tea.ordenes_estudio import OrdenesEstudioImportSchema as TeaOrdenes
|
||||
|
||||
assert BiopsiaCervicalImportSchema(pac_id_hospital="H", bx_cin_grado="CIN1").bx_cin_grado == "LIEBG"
|
||||
assert BiopsiaCervicalImportSchema(pac_id_hospital="H", bx_cin_grado="nic 3").bx_cin_grado == "LIEAG"
|
||||
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"
|
||||
|
||||
@@ -7,6 +7,7 @@ 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.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.episodio_clinico import EpisodioClinicoImportSchema
|
||||
|
||||
|
||||
# Domains whose Core layer is fully permissive (every field Optional);
|
||||
@@ -30,34 +31,6 @@ def test_every_registered_schema_is_constructible(entity_key):
|
||||
schema_cls()
|
||||
|
||||
|
||||
def test_entity_registry_has_twenty_two_entries():
|
||||
assert len(ENTITY_REGISTRY) == 22
|
||||
|
||||
|
||||
def test_entity_registry_keys_cover_all_three_domains():
|
||||
keys = set(ENTITY_REGISTRY.keys())
|
||||
assert "cacu.Paciente" in keys
|
||||
assert "cacu.OrdenesEstudio" in keys
|
||||
assert "cacu.CitologiaCervical" in keys
|
||||
assert "cacu.BiopsiaCervical" in keys
|
||||
assert "cacu.NotaMedica" in keys
|
||||
assert "cacu.BiometriaHematica" in keys
|
||||
assert "cama.Paciente" in keys
|
||||
assert "cama.OrdenesEstudio" in keys
|
||||
assert "cama.Mastografia" in keys
|
||||
assert "cama.BiopsiaMama" in keys
|
||||
assert "cama.NotaMedica" in keys
|
||||
assert "cama.BiometriaHematica" in keys
|
||||
assert "tea.Pacientes" in keys
|
||||
assert "tea.OrdenesEstudio" in keys
|
||||
assert "tea.NotaMedica" in keys
|
||||
assert "tea.EvaluacionPsicologica" in keys
|
||||
assert "tea.PotencialesEvocadosAuditivos" in keys
|
||||
assert "tea.EegEstudio" in keys
|
||||
assert "tea.AntecedentesMaternosGestacion" in keys
|
||||
assert "tea.PartoNeonatal" in keys
|
||||
|
||||
|
||||
# --- Spot checks -----------------------------------------------------------
|
||||
# CaMa entity with a required, unique integer ord_numero_hospital and an
|
||||
# *_ALIAS-backed enum field.
|
||||
@@ -90,3 +63,16 @@ def test_cacu_biopsia_cervical_coerces_cin_grado_alias():
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
BiopsiaCervicalImportSchema(bx_cin_grado="LIEBG") # pac_id_hospital missing
|
||||
|
||||
|
||||
# CaCu EpisodioClinico: requires pac_id_hospital and coerces tipo_episodio/
|
||||
# especialidad_medica through their respective *_ALIAS catalogs.
|
||||
def test_cacu_episodio_clinico_requires_pac_id_hospital_and_coerces_catalogs():
|
||||
with pytest.raises(ValidationError):
|
||||
EpisodioClinicoImportSchema(tipo_episodio="SCREENING") # pac_id_hospital missing
|
||||
|
||||
schema = EpisodioClinicoImportSchema(
|
||||
pac_id_hospital="H-1", tipo_episodio="SCREENING", especialidad_medica="MEDICINA FAMILIAR",
|
||||
)
|
||||
assert schema.tipo_episodio == "TAMIZAJE"
|
||||
assert schema.especialidad_medica == "MEDICINA_FAMILIAR"
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""La lista de seguimiento (T-24d): `GET /cacu/seguimiento`, siempre simulada.
|
||||
|
||||
Sobre la base de demostración del kit (`conftest.cliente_de`). La lista en sí se prueba en el kit
|
||||
(`tests/test_lista_seguimiento.py`); aquí, la ruta: que existe sin `DEV_REVISION`, la forma y los códigos
|
||||
de error. Fixtures: `client`, la app sin `DEV_REVISION` sobre la base de demostración de CaCu.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"}
|
||||
LLAVES_DEL_ITEM = {"id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
|
||||
"dias_toma_diagnostico", "prioridad"} # fmt: skip
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
"""La app sobre la base de demostración de CaCu, sin `DEV_REVISION` en el entorno."""
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
def test_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
|
||||
"""Fija: sin `DEV_REVISION` la ruta existe, con la forma del contrato y `simulado: true`. Falla si la ruta
|
||||
vuelve a depender de una variable de entorno o cambia un campo."""
|
||||
response = client.get("/cacu/seguimiento?corte=2025-12-31")
|
||||
|
||||
assert response.status_code == 200 and response.mimetype == "application/json"
|
||||
cuerpo = response.get_json()
|
||||
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)
|
||||
|
||||
|
||||
def test_el_pedido_se_respeta(client):
|
||||
cuerpo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=6&page=1&page_size=2&estatus=PRE_COLPOSCOPIA").get_json()
|
||||
|
||||
assert cuerpo["ventana"]["meses"] == 6 and cuerpo["paginacion"]["page_size"] == 2
|
||||
assert len(cuerpo["items"]) <= 2 and all(i["estatus"]["codigo"] == "PRE_COLPOSCOPIA" for i in cuerpo["items"])
|
||||
assert cuerpo["filtros"] == {"estatus": "PRE_COLPOSCOPIA"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
["?corte=2025-13", "?corte=ayer", "?meses=2", "?meses=tres", "?estatus=OTRO", "?page=0", "?page_size=500"],
|
||||
)
|
||||
def test_un_pedido_mal_escrito_o_fuera_de_rango_da_400(client, query):
|
||||
response = client.get(f"/cacu/seguimiento{query}")
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_una_pagina_de_mas_da_404(client):
|
||||
response = client.get("/cacu/seguimiento?corte=2025-12-31&page=9999")
|
||||
|
||||
assert response.status_code == 404
|
||||
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
|
||||
|
||||
with pytest.warns(DeprecationWarning):
|
||||
en_dev()
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Rows that reference a parent by the source's own id (a biopsy's `mast_id`,
|
||||
a hospital table's `pac_id`) must land on the right parent, whatever order or
|
||||
numbering the parents arrive in."""
|
||||
import base64
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _json(records, target, mapping=None):
|
||||
mapping = mapping or {k: k for k in records[0]}
|
||||
return {"source_type": "json", "target": target, "column_mapping": mapping,
|
||||
"payload": {"file_base64": base64.b64encode(json.dumps(records).encode()).decode()}}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cama")
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_biopsy_keeps_pointing_at_its_mammogram(client):
|
||||
pacientes = [{"pac_id": 70, "pac_id_hospital": "SRC-A", "pac_fecha_nacimiento": "1970-01-01"},
|
||||
{"pac_id": 50, "pac_id_hospital": "SRC-B", "pac_fecha_nacimiento": "1971-01-01"}]
|
||||
# Hospital ids out of insertion order: an auto-numbered table would swap them.
|
||||
mastografias = [{"mast_id": 902, "pac_id": 50, "pac_id_hospital": "SRC-B", "mast_birads": "B4"},
|
||||
{"mast_id": 901, "pac_id": 70, "pac_id_hospital": "SRC-A", "mast_birads": "B1"}]
|
||||
biopsias = [{"bx_id": 1, "mast_id": 902, "pac_id": 50, "pac_id_hospital": "SRC-B"}]
|
||||
sources = [_json(pacientes, "cama.Paciente"), _json(mastografias, "cama.Mastografia"),
|
||||
_json(biopsias, "cama.BiopsiaMama", {"mast_id": "mast_id", "pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital"})]
|
||||
body = client.post("/imports/commit", json={"sources": sources}).get_json()
|
||||
assert all(r["rejected"] == 0 for r in body["results"]), body
|
||||
|
||||
from persistance.cama import biopsia_mama_repository, mastografia_repository, paciente_repository
|
||||
|
||||
pacientes = {p.pac_id_hospital: p.pac_id for p in paciente_repository.list()}
|
||||
assert pacientes == {"SRC-A": 70, "SRC-B": 50}
|
||||
biopsia = biopsia_mama_repository.list()[0]
|
||||
mamografia = mastografia_repository.get(biopsia.mast_id)
|
||||
assert mamografia.pac_id == biopsia.pac_id == 50
|
||||
|
||||
|
||||
def test_natural_key_wins_over_a_foreign_internal_id(client):
|
||||
"""The patient came from a CSV without ids; the hospital table sends its own pac_id."""
|
||||
pacientes = [{"pac_id_hospital": "CSV-1", "pac_fecha_nacimiento": "1980-01-01"}]
|
||||
client.post("/imports/commit", json={"sources": [_json(pacientes, "cama.Paciente")]})
|
||||
notas = [{"pac_id": 999, "pac_id_hospital": "CSV-1", "nm_id_hospital": "N-1"}]
|
||||
result = client.post("/imports/commit", json={"sources": [_json(notas, "cama.NotaMedica")]}).get_json()["results"][0]
|
||||
assert result["created"] == 1, result
|
||||
assert result["linked"] == {"pac_id": 1}
|
||||
|
||||
from persistance.cama import nota_medica_repository, paciente_repository
|
||||
|
||||
paciente = next(p for p in paciente_repository.list() if p.pac_id_hospital == "CSV-1")
|
||||
nota = next(n for n in nota_medica_repository.list() if n.nm_id_hospital == "N-1")
|
||||
assert nota.pac_id == paciente.pac_id != 999
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def tea_client(wire_domain):
|
||||
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
|
||||
|
||||
|
||||
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"),
|
||||
]
|
||||
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,
|
||||
)
|
||||
|
||||
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"
|
||||
|
||||
|
||||
def test_tea_rows_without_a_source_id_get_one(tea_client):
|
||||
eeg = _json([{"eeg_id_registro_laboratorio": "L-SIN-ID"}], "tea.EegEstudio")
|
||||
assert tea_client.post("/imports/commit", json={"sources": [eeg]}).get_json()["results"][0]["created"] == 1
|
||||
|
||||
from persistance.tea import eeg_estudio_repository
|
||||
|
||||
[fila] = [e for e in eeg_estudio_repository.list() if e.eeg_id_registro_laboratorio == "L-SIN-ID"]
|
||||
assert len(fila.eeg_id) == 36
|
||||
@@ -9,18 +9,18 @@ from webapi.imports.connectors.sql import SqlConnector
|
||||
from webapi.imports.connectors.sql_policy import SqlSourcePolicy
|
||||
|
||||
PRODUCTION_POLICY = SqlSourcePolicy(
|
||||
allowed_dialects=frozenset({"mysql", "mariadb", "postgresql", "mssql", "oracle"}), allowed_hosts=None
|
||||
allowed_dialects=frozenset({"mysql", "mariadb", "postgresql", "mssql"}), allowed_hosts=None
|
||||
)
|
||||
|
||||
|
||||
def test_sqlite_is_refused_by_default_policy(tmp_path):
|
||||
with pytest.raises(ConnectorError, match="dialect 'sqlite' is not allowed"):
|
||||
with pytest.raises(ConnectorError, match="'sqlite' no está permitido"):
|
||||
SqlConnector(f"sqlite:///{tmp_path / 'x.db'}", policy=PRODUCTION_POLICY)
|
||||
|
||||
|
||||
def test_host_allowlist_is_enforced():
|
||||
policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=frozenset({"10.0.10.50"}))
|
||||
with pytest.raises(ConnectorError, match="not in the allowed"):
|
||||
with pytest.raises(ConnectorError, match="no está entre los permitidos"):
|
||||
policy.check_url("mysql+pymysql://u:p@evil.example.com/db")
|
||||
assert policy.check_url("mysql+pymysql://u:p@10.0.10.50/db").host == "10.0.10.50"
|
||||
|
||||
@@ -31,16 +31,25 @@ def test_refuses_the_applications_own_database(monkeypatch, tmp_path):
|
||||
own = tmp_path / "cacu.db"
|
||||
monkeypatch.setattr(persistance_settings.settings, "cacu_database_url", f"sqlite:///{own}")
|
||||
policy = SqlSourcePolicy(allowed_dialects=frozenset({"sqlite"}), allowed_hosts=None)
|
||||
with pytest.raises(ConnectorError, match="own database"):
|
||||
with pytest.raises(ConnectorError, match="propia aplicación"):
|
||||
policy.check_url(f"sqlite:///{own}")
|
||||
|
||||
monkeypatch.setattr(persistance_settings.settings, "cama_database_url", "mysql+pymysql://app:pw@db.internal:3306/isss_cama")
|
||||
mysql_policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=None)
|
||||
with pytest.raises(ConnectorError, match="own database"):
|
||||
with pytest.raises(ConnectorError, match="propia aplicación"):
|
||||
mysql_policy.check_url("mysql+pymysql://someone_else:pw@DB.internal:3306/isss_cama")
|
||||
mysql_policy.check_url("mysql+pymysql://app:pw@db.internal:3306/hospital_legacy")
|
||||
|
||||
|
||||
def test_an_explicit_default_port_does_not_bypass_the_own_database_check(monkeypatch):
|
||||
from persistance import settings as persistance_settings
|
||||
|
||||
monkeypatch.setattr(persistance_settings.settings, "cacu_database_url", "mysql+pymysql://app:pw@db/isss_cacu")
|
||||
policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=None)
|
||||
with pytest.raises(ConnectorError, match="propia aplicación"):
|
||||
policy.check_url("mysql+pymysql://app:pw@db:3306/isss_cacu")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
@@ -56,12 +65,44 @@ def test_only_single_select_queries_pass(query):
|
||||
SqlSourcePolicy.check_query(query)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["SELECT * FROM t;", " with x as (select 1 as a) select a from x", "/* c */ SELECT 1"])
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
["SELECT * FROM t;", " with x as (select 1 as a) select a from x", "/* c */ SELECT 1", "SELECT 'a;b' AS literal"],
|
||||
)
|
||||
def test_select_queries_pass(query):
|
||||
assert SqlSourcePolicy.check_query(query)
|
||||
|
||||
|
||||
def test_connection_is_read_only_even_for_a_select_shaped_write(tmp_path):
|
||||
def test_a_writable_cte_is_rejected_by_parsing_the_query_not_matching_keywords():
|
||||
"""`WITH d AS (DELETE FROM t RETURNING a) SELECT a FROM d` is a syntactic
|
||||
SELECT at the top level, so a check that only looks at the first keyword
|
||||
lets it through; parsing the query and inspecting the tree catches the
|
||||
write hiding inside the CTE."""
|
||||
with pytest.raises(ConnectorError, match="no puede escribir"):
|
||||
SqlSourcePolicy.check_query("WITH d AS (DELETE FROM t RETURNING a) SELECT a FROM d")
|
||||
|
||||
|
||||
def test_select_into_a_new_table_is_rejected():
|
||||
"""SQL Server's `SELECT ... INTO` creates a table — a write a keyword
|
||||
check would miss entirely, since the statement still starts with SELECT."""
|
||||
with pytest.raises(ConnectorError, match="no puede escribir"):
|
||||
SqlSourcePolicy.check_query("SELECT * INTO nueva_tabla FROM t", dialect="mssql")
|
||||
|
||||
|
||||
def test_mysql_select_into_outfile_is_rejected():
|
||||
"""MySQL's `SELECT ... INTO OUTFILE` writes a file to the server's own
|
||||
filesystem. sqlglot's MySQL grammar doesn't model this clause at all, so
|
||||
it fails to parse — rejected as invalid SQL, which is the safe default
|
||||
for anything that can't be positively confirmed to be a plain read."""
|
||||
with pytest.raises(ConnectorError):
|
||||
SqlSourcePolicy.check_query("SELECT * FROM t INTO OUTFILE '/tmp/x.csv'", dialect="mysql")
|
||||
|
||||
|
||||
def test_connection_is_read_only_even_for_a_write_the_query_parser_could_miss(tmp_path):
|
||||
"""Defense in depth: even if a future sqlglot version or an edge-case
|
||||
dialect quirk let a write-shaped query past `check_query`, the
|
||||
connection itself is read-only and the transaction is always rolled
|
||||
back, so the underlying database still refuses to execute it."""
|
||||
db = tmp_path / "src.db"
|
||||
engine = sa.create_engine(f"sqlite:///{db}")
|
||||
with engine.begin() as conn:
|
||||
@@ -69,9 +110,11 @@ def test_connection_is_read_only_even_for_a_select_shaped_write(tmp_path):
|
||||
conn.execute(sa.text("INSERT INTO t VALUES (1), (2)"))
|
||||
|
||||
connector = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None))
|
||||
# Bypass check_query directly to isolate the read-only connection itself,
|
||||
# rather than testing the parser twice.
|
||||
connector._query, connector._table = "WITH d AS (DELETE FROM t RETURNING a) SELECT a FROM d", None
|
||||
with pytest.raises(ConnectorError):
|
||||
# Passes the keyword check, but the read-only connection refuses it.
|
||||
connector.select_query("WITH d AS (DELETE FROM t RETURNING a) SELECT a FROM d").preview()
|
||||
connector.preview()
|
||||
with engine.connect() as conn:
|
||||
assert conn.execute(sa.text("SELECT COUNT(*) FROM t")).scalar_one() == 2
|
||||
|
||||
|
||||
+13
-1
@@ -10,7 +10,9 @@ 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
|
||||
|
||||
|
||||
class IsoJSONProvider(DefaultJSONProvider):
|
||||
@@ -66,7 +68,7 @@ def create_app() -> Flask:
|
||||
@app.errorhandler(413)
|
||||
def too_large(_exc):
|
||||
limit_mb = app.config["MAX_CONTENT_LENGTH"] // (1024 * 1024)
|
||||
return jsonify({"error": f"request larger than {limit_mb} MB"}), 413
|
||||
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")
|
||||
@@ -74,5 +76,15 @@ def create_app() -> Flask:
|
||||
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")
|
||||
# Patient-level follow-up list and individual risk, marked `simulado` in every response. Who may see them is
|
||||
# an access rule still to be defined, not an environment variable.
|
||||
from persistance import cacu as cacu_repositories
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
from webapi.patient_risk import patient_risk_blueprint
|
||||
|
||||
app.register_blueprint(blueprint_de_seguimiento(get_cacu_session), url_prefix="/cacu")
|
||||
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
|
||||
return app
|
||||
|
||||
@@ -1,41 +1,7 @@
|
||||
from flask import Blueprint, jsonify, request
|
||||
from flask import Blueprint
|
||||
|
||||
from models.cacu import CaCuModel
|
||||
from models.prediction import ApplicabilityRejected, PredictionService
|
||||
from persistance.cacu import paciente_repository
|
||||
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)
|
||||
|
||||
|
||||
@cacu_bp.get("/pacientes/<int:pac_id>")
|
||||
def get_paciente(pac_id: int):
|
||||
"""Read one CaCu patient by primary key."""
|
||||
paciente = paciente_repository.get(pac_id)
|
||||
if paciente is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify(paciente.model_dump())
|
||||
|
||||
|
||||
@cacu_bp.post("/predict")
|
||||
def predict():
|
||||
"""Predict and record the result against the active `ModelVersion` (MLD-4/MLD-5).
|
||||
|
||||
Returns 501 while `CaCuModel.predict` is not implemented."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
service = PredictionService(CaCuModel(), domain="cacu", scenario=body.get("scenario", "tamizaje"))
|
||||
try:
|
||||
prediction = service.predict_and_record(
|
||||
body.get("data"),
|
||||
pac_id_hospital=body.get("pac_id_hospital", ""),
|
||||
episodio_id=body.get("episodio_id"),
|
||||
)
|
||||
except NotImplementedError as exc:
|
||||
return jsonify({"error": str(exc)}), 501
|
||||
except ApplicabilityRejected as exc:
|
||||
return jsonify({"error": str(exc)}), 422
|
||||
except RuntimeError as exc:
|
||||
return jsonify({"error": str(exc)}), 503
|
||||
return jsonify(prediction.model_dump())
|
||||
|
||||
@@ -1,38 +1,7 @@
|
||||
from flask import Blueprint, jsonify, request
|
||||
from flask import Blueprint
|
||||
|
||||
from models.cama import CaMaModel
|
||||
from models.prediction import ApplicabilityRejected, PredictionService
|
||||
from persistance.cama import paciente_repository
|
||||
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)
|
||||
|
||||
|
||||
@cama_bp.get("/pacientes/<int:pac_id>")
|
||||
def get_paciente(pac_id: int):
|
||||
paciente = paciente_repository.get(pac_id)
|
||||
if paciente is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify(paciente.model_dump())
|
||||
|
||||
|
||||
@cama_bp.post("/predict")
|
||||
def predict():
|
||||
"""Predict and record the result against the active `ModelVersion` (MLD-4/MLD-5)."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
service = PredictionService(CaMaModel(), domain="cama", scenario=body.get("scenario", "tamizaje"))
|
||||
try:
|
||||
prediction = service.predict_and_record(
|
||||
body.get("data"),
|
||||
pac_id_hospital=body.get("pac_id_hospital", ""),
|
||||
episodio_id=body.get("episodio_id"),
|
||||
)
|
||||
except NotImplementedError as exc:
|
||||
return jsonify({"error": str(exc)}), 501
|
||||
except ApplicabilityRejected as exc:
|
||||
return jsonify({"error": str(exc)}), 422
|
||||
except RuntimeError as exc:
|
||||
return jsonify({"error": str(exc)}), 503
|
||||
return jsonify(prediction.model_dump())
|
||||
|
||||
@@ -13,12 +13,12 @@ _MAX_PAGE = 500
|
||||
def list_rows(target: str):
|
||||
spec = ENTITY_REGISTRY.get(target)
|
||||
if spec is None:
|
||||
return jsonify({"error": f"unknown target: {target!r}"}), 404
|
||||
return jsonify({"error": f"destino desconocido: {target!r}"}), 404
|
||||
try:
|
||||
limit = min(max(int(request.args.get("limit", 50)), 1), _MAX_PAGE)
|
||||
offset = max(int(request.args.get("offset", 0)), 0)
|
||||
except ValueError:
|
||||
return jsonify({"error": "limit/offset must be integers"}), 400
|
||||
return jsonify({"error": "limit y offset deben ser números enteros"}), 400
|
||||
rows = spec.repository.list(limit=limit, offset=offset)
|
||||
return jsonify(
|
||||
{
|
||||
|
||||
+28
-102
@@ -1,29 +1,19 @@
|
||||
"""Model governance (ML, MLD, EL and VAR requirements): model versions and
|
||||
their promotion, cohorts, predictions, and the OCR extraction jobs with
|
||||
their manual review queue.
|
||||
their promotion, and the OCR extraction jobs with their manual review queue.
|
||||
|
||||
Training, versioning and artifact storage live in MLflow (`models.registry`
|
||||
is a thin layer over it); training runs anywhere, registering the result
|
||||
through `POST /model-versions`. Browsing/downloading a logged artifact goes
|
||||
straight to the MLflow tracking server's own UI/API, not through here.
|
||||
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`).
|
||||
"""
|
||||
from dataclasses import asdict
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
|
||||
from core.governance.enums import EstatusExtraccion
|
||||
from core.governance.models import ExtractionRun
|
||||
from core.ocr import OcrEstatus
|
||||
from models.cohort import COHORT_BUILDERS, describe_builder
|
||||
from models.ocr import OCR_JOBS, OcrColumnSpec, run_pending_extractions
|
||||
from models.registry import REPORT_TAGS, PromotionBlocked, registry
|
||||
from persistance.governance import (
|
||||
cohort_exclusion_count_repository,
|
||||
cohort_exclusion_repository,
|
||||
cohort_version_repository,
|
||||
extraction_run_repository,
|
||||
model_prediction_repository,
|
||||
)
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from models.io.registry import REPORT_TAGS, PromotionBlocked, registry
|
||||
from models.ocr import OCR_JOBS, OcrJob, run_pending_extractions
|
||||
from persistance.governance import extraction_run_repository
|
||||
from persistance.repository import Repository
|
||||
|
||||
governance_bp = Blueprint("governance", __name__)
|
||||
@@ -39,9 +29,11 @@ def _bad_request(exc: ValueError):
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
|
||||
def _ocr_job_or_404(domain: str | None, entity: str | None) -> tuple[Repository, OcrColumnSpec] | None:
|
||||
def _ocr_job(domain: str | None, entity: str | None) -> OcrJob:
|
||||
job = OCR_JOBS.get((domain, entity))
|
||||
return (job.repository, job.columns) if job else None
|
||||
if job is None:
|
||||
raise LookupError(f"no hay un trabajo de OCR registrado para (domain={domain!r}, entity={entity!r})")
|
||||
return job
|
||||
|
||||
|
||||
def _pk_name(repository: Repository) -> str:
|
||||
@@ -61,7 +53,7 @@ def list_model_versions():
|
||||
@governance_bp.post("/model-versions")
|
||||
def register_model_version():
|
||||
"""Registers a trained version: `{domain, scenario,
|
||||
environment: DEV|PROD, cohort_version_id?, metrics?, hyperparameters?,
|
||||
environment: DEV|PROD, cohorte_armado_id?, metrics?, hyperparameters?,
|
||||
technical_validation_report_uri?, clinical_validation_report_uri?,
|
||||
interpretability_report_uri?}`."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
@@ -72,7 +64,7 @@ def register_model_version():
|
||||
domain=body["domain"],
|
||||
scenario=body["scenario"],
|
||||
environment=body["environment"],
|
||||
cohort_version_id=body.get("cohort_version_id"),
|
||||
cohorte_armado_id=body.get("cohorte_armado_id"),
|
||||
metrics=body.get("metrics"),
|
||||
hyperparameters=body.get("hyperparameters"),
|
||||
**{k: body[k] for k in REPORT_TAGS if k in body},
|
||||
@@ -80,11 +72,6 @@ def register_model_version():
|
||||
return jsonify(registry.describe(body["domain"], body["scenario"], version)), 201
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>")
|
||||
def get_model_version(domain: str, scenario: str, version: str):
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.patch("/model-versions/<domain>/<scenario>/<version>/reports")
|
||||
def attach_reports(domain: str, scenario: str, version: str):
|
||||
"""MLD-01/01b/03 documents, usually written after training."""
|
||||
@@ -121,19 +108,9 @@ def retire_model_version(domain: str, scenario: str, version: str):
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/compare")
|
||||
def compare_model_versions(domain: str, scenario: str):
|
||||
a, b = request.args.get("a"), request.args.get("b")
|
||||
if not a or not b:
|
||||
return jsonify({"error": "a y b deben ser versiones de MLflow"}), 400
|
||||
return jsonify(registry.compare(domain, scenario, a, b))
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/artifacts")
|
||||
def upload_artifact(domain: str, scenario: str, version: str):
|
||||
"""Multipart: `file`, `kind` (ArtifactKind) — logs it to the version's
|
||||
MLflow run. Browse/download logged artifacts via the MLflow tracking
|
||||
server directly, not through here."""
|
||||
"""Multipart `file` and `kind` (ArtifactKind); logged to the version's MLflow run."""
|
||||
from core.governance.enums import ArtifactKind
|
||||
|
||||
upload = request.files.get("file")
|
||||
@@ -146,48 +123,7 @@ def upload_artifact(domain: str, scenario: str, version: str):
|
||||
return jsonify(registry.describe(domain, scenario, version)), 201
|
||||
|
||||
|
||||
# -- cohorts ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/cohort-scenarios")
|
||||
def list_cohort_scenarios():
|
||||
"""Scenarios with a registered `CohortBuilder` (see models.cohort.register_cohort_builder)."""
|
||||
return jsonify({"scenarios": [describe_builder(cls) for cls in COHORT_BUILDERS.values()]})
|
||||
|
||||
|
||||
@governance_bp.post("/cohort-versions")
|
||||
def build_cohort_version():
|
||||
"""Builds and freezes a new cohort version: `{domain, scenario, description?}`."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
builder = COHORT_BUILDERS.get((body.get("domain"), body.get("scenario")))
|
||||
if builder is None:
|
||||
return jsonify({"error": f"no hay un CohortBuilder registrado para ({body.get('domain')!r}, {body.get('scenario')!r})"}), 404
|
||||
return jsonify(builder().build(description=body.get("description")).model_dump()), 201
|
||||
|
||||
|
||||
@governance_bp.get("/cohort-versions")
|
||||
def list_cohort_versions():
|
||||
filters = {k: v for k, v in request.args.items() if k in {"domain", "scenario"}}
|
||||
versions = cohort_version_repository.list(limit=200, **filters)
|
||||
return jsonify({"cohort_versions": [v.model_dump() for v in versions]})
|
||||
|
||||
|
||||
@governance_bp.get("/cohort-versions/<int:cohort_version_id>/exclusions")
|
||||
def get_cohort_exclusions(cohort_version_id: int):
|
||||
"""EL-05/EL-07: per-criterion counts and the per-episode log behind them."""
|
||||
counts = cohort_exclusion_count_repository.list(limit=1000, cohort_version_id=cohort_version_id)
|
||||
detail = cohort_exclusion_repository.list(limit=1000, cohort_version_id=cohort_version_id)
|
||||
return jsonify({"counts": [c.model_dump() for c in counts], "detail": [d.model_dump() for d in detail]})
|
||||
|
||||
|
||||
# -- predictions and OCR -------------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/predictions")
|
||||
def list_predictions():
|
||||
filters = {k: v for k, v in request.args.items() if k in {"domain", "pac_id_hospital", "mlflow_run_id", "modelo_nombre", "modelo_version"}}
|
||||
predictions = model_prediction_repository.list(limit=200, **filters)
|
||||
return jsonify({"predictions": [p.model_dump() for p in predictions]})
|
||||
# -- OCR ---------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/ocr/jobs")
|
||||
@@ -209,13 +145,9 @@ def list_ocr_jobs():
|
||||
def list_ocr_rows(domain: str, entity: str):
|
||||
"""Rows of an OCR job filtered by `status`: `review` (the default, rows
|
||||
flagged `requiere_revision`), `pending`, `failed`, `done` or `all`.
|
||||
|
||||
Filtering happens in Python because `Repository.list` only supports
|
||||
equality filters; a review queue is small."""
|
||||
job = _ocr_job_or_404(domain, entity)
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
|
||||
repository, spec = job
|
||||
Filtering happens in Python: `Repository.list` only supports equality."""
|
||||
job = _ocr_job(domain, entity)
|
||||
repository, spec = job.repository, job.columns
|
||||
|
||||
status = request.args.get("status", "review")
|
||||
limit = int(request.args.get("limit", 100))
|
||||
@@ -238,7 +170,7 @@ def list_ocr_rows(domain: str, entity: str):
|
||||
return estatus == OcrEstatus.REALIZADO.value
|
||||
return True
|
||||
|
||||
candidates = [row for row in repository.list(limit=2000) if matches(row)]
|
||||
candidates = [row for row in repository.iter_all() if matches(row)]
|
||||
page = candidates[offset : offset + limit]
|
||||
rows = [
|
||||
{
|
||||
@@ -259,13 +191,11 @@ def list_ocr_rows(domain: str, entity: str):
|
||||
@governance_bp.get("/ocr/<domain>/<entity>/<int:pk>/blob")
|
||||
def get_ocr_blob(domain: str, entity: str, pk: int):
|
||||
"""Raw bytes of the row's stored PDF, for the review UI's page viewer."""
|
||||
job = _ocr_job_or_404(domain, entity)
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
|
||||
repository, spec = job
|
||||
job = _ocr_job(domain, entity)
|
||||
repository, spec = job.repository, job.columns
|
||||
row = repository.get(pk)
|
||||
if row is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify({"error": "no se encontró el registro"}), 404
|
||||
blob = getattr(row, spec.blob_field, None)
|
||||
if blob is None:
|
||||
return jsonify({"error": "esta fila no tiene un PDF almacenado"}), 404
|
||||
@@ -277,10 +207,8 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
|
||||
"""Stores values entered by a reviewer for an OCR row. Marks the row
|
||||
done with method "manual" (VAR-03), clears `requiere_revision`, and logs
|
||||
an `ExtractionRun` like an automated run (VAR-07/08)."""
|
||||
job = _ocr_job_or_404(domain, entity)
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
|
||||
repository, spec = job
|
||||
job = _ocr_job(domain, entity)
|
||||
repository, spec = job.repository, job.columns
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
values = body.get("values")
|
||||
@@ -294,7 +222,7 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
|
||||
with repository.open_session() as session:
|
||||
tracked = session.get(repository.model, pk)
|
||||
if tracked is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify({"error": "no se encontró el registro"}), 404
|
||||
for column, value in values.items():
|
||||
setattr(tracked, column, value)
|
||||
setattr(tracked, spec.estatus_field, OcrEstatus.REALIZADO.value)
|
||||
@@ -313,7 +241,7 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
|
||||
entity=entity,
|
||||
entity_pk=str(pk),
|
||||
column_extracted=",".join(sorted(values)),
|
||||
transform_description="Corrección manual vía UI de gobernanza — usuario revisó el PDF y escribió el valor directamente.",
|
||||
transform_description="Corrección manual",
|
||||
estatus=EstatusExtraccion.COMPLETADA,
|
||||
)
|
||||
)
|
||||
@@ -327,9 +255,7 @@ def run_ocr():
|
||||
body = request.get_json(silent=True) or {}
|
||||
domain = body.get("domain")
|
||||
entity = body.get("entity")
|
||||
job = OCR_JOBS.get((domain, entity))
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 400
|
||||
job = _ocr_job(domain, entity)
|
||||
|
||||
try:
|
||||
summary = run_pending_extractions(
|
||||
|
||||
@@ -1,23 +1,30 @@
|
||||
"""Import routes. They only parse the request and shape the response; the
|
||||
work happens in `webapi.imports`. Errors map to HTTP 400 in one place."""
|
||||
import json
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from extraction import BBox, ExtractionError
|
||||
from extraction.readers import reader_for
|
||||
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.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.services.import_service import (
|
||||
DatabaseRefused,
|
||||
ImportRequestError,
|
||||
commit_sources,
|
||||
serialize_errors,
|
||||
validate_source,
|
||||
)
|
||||
from webapi.indicadores_vivos import ColaDeRecalculo
|
||||
from webapi.imports.services.introspection_service import (
|
||||
detect_pdf,
|
||||
document_report,
|
||||
@@ -26,6 +33,7 @@ from webapi.imports.services.introspection_service import (
|
||||
)
|
||||
|
||||
imports_bp = Blueprint("imports", __name__)
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BadRequest(Exception):
|
||||
@@ -43,20 +51,20 @@ def _bad_request(exc: Exception):
|
||||
def _json_body() -> dict:
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
raise BadRequest("request body must be a JSON object")
|
||||
raise BadRequest("el cuerpo de la solicitud debe ser un objeto JSON")
|
||||
return body
|
||||
|
||||
|
||||
def _require(mapping: dict, key: str):
|
||||
value = mapping.get(key)
|
||||
if value in (None, ""):
|
||||
raise BadRequest(f"missing {key}")
|
||||
raise BadRequest(f"falta {key}")
|
||||
return value
|
||||
|
||||
|
||||
def _uploaded_file() -> tuple[str, bytes]:
|
||||
if "file" not in request.files:
|
||||
raise BadRequest("missing file")
|
||||
raise BadRequest("falta el archivo")
|
||||
upload = request.files["file"]
|
||||
return upload.filename or "", upload.read()
|
||||
|
||||
@@ -65,12 +73,12 @@ def _form_int(key: str, default: int | None = None) -> int:
|
||||
raw = request.form.get(key)
|
||||
if raw is None:
|
||||
if default is None:
|
||||
raise BadRequest(f"missing {key}")
|
||||
raise BadRequest(f"falta {key}")
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError as exc:
|
||||
raise BadRequest(f"{key} must be an integer") from exc
|
||||
raise BadRequest(f"{key} debe ser un número entero") from exc
|
||||
|
||||
|
||||
def _form_json(key: str, default=None):
|
||||
@@ -80,7 +88,16 @@ def _form_json(key: str, default=None):
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise BadRequest(f"{key} must be JSON: {exc}") from exc
|
||||
raise BadRequest(f"{key} debe ser JSON válido: {exc}") from exc
|
||||
|
||||
|
||||
def _outcome(exc: Exception) -> str:
|
||||
"""How an attempt that raised is logged."""
|
||||
if isinstance(exc, DatabaseRefused):
|
||||
return "rechazada_por_la_base"
|
||||
if isinstance(exc, (BadRequest, ConnectorError, ExtractionError, ImportRequestError)):
|
||||
return "solicitud_invalida"
|
||||
return "fallida"
|
||||
|
||||
|
||||
# -- catalog -------------------------------------------------------------------
|
||||
@@ -137,7 +154,7 @@ def preview_file():
|
||||
kind = request.form.get("source_kind") or kind_for_filename(name)
|
||||
cls = connector_class(kind)
|
||||
if not issubclass(cls, FileConnector):
|
||||
raise BadRequest(f"{kind!r} is not a file source")
|
||||
raise BadRequest(f"{kind!r} no es una fuente de archivo")
|
||||
options = _form_json("options", {}) or {}
|
||||
if "file_name" in cls.option_names:
|
||||
options.setdefault("file_name", name)
|
||||
@@ -215,7 +232,7 @@ def pdf_table_preview():
|
||||
page_number = _form_int("page_number")
|
||||
bbox = _form_json("bbox")
|
||||
if not isinstance(bbox, list) or len(bbox) != 4:
|
||||
raise BadRequest("missing page_number or bbox")
|
||||
raise BadRequest("falta page_number o bbox")
|
||||
connector = PdfConnector(raw)
|
||||
connector.select_table(page_number, tuple(float(v) for v in bbox))
|
||||
return jsonify(preview_with_suggestions(connector, request.form.get("target")))
|
||||
@@ -237,12 +254,14 @@ 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).
|
||||
Each record comes back with per-field confidence and evidence, conflicts
|
||||
between sources, and the images found on its pages."""
|
||||
body = _json_body()
|
||||
_require(body, "target")
|
||||
if not body.get("files"):
|
||||
raise BadRequest("missing files")
|
||||
if not body.get("files") and not body.get("sql"):
|
||||
raise BadRequest("faltan los archivos")
|
||||
return jsonify(document_report(body))
|
||||
|
||||
|
||||
@@ -258,7 +277,7 @@ def document_page_image():
|
||||
if bbox is None:
|
||||
return Response(reader.render_page(raw, page_number, dpi=dpi), mimetype="image/png")
|
||||
if not isinstance(bbox, list) or len(bbox) != 4:
|
||||
raise BadRequest("bbox must be [x0, y0, x1, y1]")
|
||||
raise BadRequest("bbox debe ser [x0, y0, x1, y1]")
|
||||
return Response(reader.render_region(raw, page_number, BBox(*map(float, bbox)), dpi=dpi), mimetype="image/png")
|
||||
|
||||
|
||||
@@ -267,7 +286,17 @@ def document_page_image():
|
||||
|
||||
@imports_bp.post("/validate")
|
||||
def validate():
|
||||
result = validate_source(_require(_json_body(), "source"))
|
||||
source = _require(_json_body(), "source")
|
||||
audit = import_audit.ImportAudit("validacion")
|
||||
try:
|
||||
result = validate_source(source, audit=audit)
|
||||
except Exception as exc:
|
||||
audit.fail(exc, _outcome(exc))
|
||||
raise
|
||||
else:
|
||||
audit.succeed()
|
||||
finally:
|
||||
import_audit.record(audit)
|
||||
return jsonify(
|
||||
{
|
||||
"total_rows": result.total_rows,
|
||||
@@ -278,20 +307,73 @@ 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."""
|
||||
reports = []
|
||||
for raw in raw_sources:
|
||||
if not isinstance(raw, dict) or raw.get("source_type") != "document":
|
||||
continue
|
||||
target = raw.get("target") or ""
|
||||
domain = target.split(".", 1)[0]
|
||||
if not domain:
|
||||
continue
|
||||
payload = {**(raw.get("payload") or {}), "target": target}
|
||||
try:
|
||||
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:
|
||||
log.warning("catalog_fallback: %s no se pudo procesar: %s", raw.get("label") or target, exc)
|
||||
continue
|
||||
reports.append(
|
||||
{
|
||||
"label": raw.get("label"),
|
||||
"domain": result.proyecto,
|
||||
"records_written": result.records_written,
|
||||
"records_without_patient": result.records_without_patient,
|
||||
"fields_matched": result.fields_matched,
|
||||
"fields_minted": result.fields_minted,
|
||||
}
|
||||
)
|
||||
return reports
|
||||
|
||||
|
||||
@imports_bp.post("/commit")
|
||||
def commit():
|
||||
"""`{sources: [...], on_conflict: "reject"|"upsert", merge_duplicates: bool}`.
|
||||
With `merge_duplicates`, rows of different sources sharing a natural key
|
||||
are combined into one record before writing."""
|
||||
body = _json_body()
|
||||
results = commit_sources(
|
||||
_require(body, "sources"),
|
||||
on_conflict=body.get("on_conflict", "reject"),
|
||||
merge=bool(body.get("merge_duplicates", False)),
|
||||
)
|
||||
on_conflict = body.get("on_conflict", "reject")
|
||||
merge = bool(body.get("merge_duplicates", False))
|
||||
audit = import_audit.ImportAudit("carga", {"on_conflict": on_conflict, "merge_duplicates": merge})
|
||||
try:
|
||||
results = commit_sources(_require(body, "sources"), on_conflict=on_conflict, merge=merge, audit=audit)
|
||||
except Exception as exc:
|
||||
audit.fail(exc, _outcome(exc))
|
||||
raise
|
||||
else:
|
||||
audit.succeed()
|
||||
finally:
|
||||
import_audit.record(audit)
|
||||
recalculating = False
|
||||
if audit.domain and any(r.created or r.updated for r in results):
|
||||
try:
|
||||
ColaDeRecalculo().solicitar(audit.domain)
|
||||
recalculating = True
|
||||
except OSError:
|
||||
# The rows are already saved; failing here would invite a duplicate retry.
|
||||
log.exception("no se pudo solicitar el recálculo de %s", audit.domain)
|
||||
return jsonify(
|
||||
{
|
||||
"ok": all(r.rejected == 0 for r in results),
|
||||
"audit_id": audit.id,
|
||||
"indicadores_en_recalculo": recalculating,
|
||||
"catalog_fallback": _commit_catalog_fallback(body.get("sources") or []),
|
||||
"results": [
|
||||
{
|
||||
"target": r.target,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Aggregate reports: the log of import attempts and the state of the live
|
||||
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
|
||||
|
||||
reportes_bp = Blueprint("reportes", __name__)
|
||||
|
||||
|
||||
@reportes_bp.get("/importaciones")
|
||||
def importaciones():
|
||||
"""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()
|
||||
domain = request.args.get("dominio")
|
||||
if domain:
|
||||
records = [r for r in records if r.get("dominio") == domain]
|
||||
try:
|
||||
limit = max(0, int(request.args.get("limite", 50)))
|
||||
except ValueError:
|
||||
return jsonify({"error": "limite debe ser un número"}), 400
|
||||
return jsonify({"resumen": import_audit.summarize(records), "intentos": list(reversed(records))[:limit]})
|
||||
|
||||
|
||||
@reportes_bp.get("/importaciones/descarga")
|
||||
def importaciones_descarga():
|
||||
"""The raw log, one JSON object per line."""
|
||||
sink = import_audit.default_sink()
|
||||
body = sink.path.read_bytes() if sink.path.exists() else b""
|
||||
return Response(
|
||||
body,
|
||||
mimetype="application/x-ndjson",
|
||||
headers={"Content-Disposition": "attachment; filename=importaciones.jsonl"},
|
||||
)
|
||||
|
||||
|
||||
@reportes_bp.get("/indicadores")
|
||||
def indicadores_estado():
|
||||
"""Per domain: state of the last recomputation and whether another is pending."""
|
||||
return jsonify(ColaDeRecalculo().estado())
|
||||
|
||||
|
||||
@reportes_bp.post("/indicadores/<dominio>/recalcular")
|
||||
def indicadores_recalcular(dominio: str):
|
||||
if dominio not in DOMINIOS:
|
||||
return jsonify({"error": f"dominio desconocido: {dominio}"}), 404
|
||||
ColaDeRecalculo().solicitar(dominio)
|
||||
return jsonify({"pendiente": True}), 202
|
||||
@@ -1,40 +1,7 @@
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from models.prediction import ApplicabilityRejected, PredictionService
|
||||
from models.tea import TeaModel
|
||||
from flask import Blueprint
|
||||
from persistance.db import get_tea_session
|
||||
from persistance.tea import pacientes_repository
|
||||
|
||||
from webapi.indicadores import registrar_indicadores
|
||||
|
||||
tea_bp = Blueprint("tea", __name__)
|
||||
registrar_indicadores(tea_bp, "tea", get_tea_session)
|
||||
|
||||
|
||||
@tea_bp.get("/pacientes/<int:pac_id>")
|
||||
def get_paciente(pac_id: int):
|
||||
paciente = pacientes_repository.get(pac_id)
|
||||
if paciente is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify(paciente.model_dump())
|
||||
|
||||
|
||||
@tea_bp.post("/predict")
|
||||
def predict():
|
||||
"""Predict and record the result against the active `ModelVersion` (MLD-4/MLD-5).
|
||||
|
||||
Returns 501 while `TeaModel.predict` is not implemented."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
service = PredictionService(TeaModel(), domain="tea", scenario=body.get("scenario", "tamizaje"))
|
||||
try:
|
||||
prediction = service.predict_and_record(
|
||||
body.get("data"),
|
||||
pac_id_hospital=body.get("pac_id_hospital", ""),
|
||||
episodio_id=body.get("episodio_id"),
|
||||
)
|
||||
except NotImplementedError as exc:
|
||||
return jsonify({"error": str(exc)}), 501
|
||||
except ApplicabilityRejected as exc:
|
||||
return jsonify({"error": str(exc)}), 422
|
||||
except RuntimeError as exc:
|
||||
return jsonify({"error": str(exc)}), 503
|
||||
return jsonify(prediction.model_dump())
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
"""Aggregate log of every import attempt (validations and commits).
|
||||
|
||||
Each attempt becomes one JSON line in `importaciones.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.
|
||||
A rejected catalog value is written verbatim only when at least
|
||||
`WEBAPI_REPORT_MIN_COUNT` rows share it, so a rare (identifying) value never
|
||||
appears.
|
||||
|
||||
`ImportAudit` collects the facts while the import runs; `JsonlAuditSink`
|
||||
appends the finished record.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
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 webapi.imports.schemas.classify import ErrorCategory
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from webapi.imports.schemas.service import BatchValidationResult
|
||||
from webapi.imports.services.import_service import ImportSource
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
_SHAPE_MAX = 40
|
||||
_MESSAGE_MAX = 300
|
||||
_QUOTED = re.compile(r"'[^']*'|\"[^\"]*\"")
|
||||
# A "column name" that is really a value: a file without a header row makes
|
||||
# its first record the header. Dates, numbers, codes such as "N-0001", long
|
||||
# text or prose are logged by shape only.
|
||||
_VALUE_LIKE = re.compile(r"^[\d\s./:-]+$|\d{4,}|^[A-Za-z]{0,3}[-_ ]?\d+$|@")
|
||||
|
||||
|
||||
def report_dir() -> Path:
|
||||
return Path(os.environ.get("WEBAPI_REPORT_DIR", "reportes"))
|
||||
|
||||
|
||||
def min_count() -> int:
|
||||
return int(os.environ.get("WEBAPI_REPORT_MIN_COUNT", "5"))
|
||||
|
||||
|
||||
def value_shape(value: Any) -> str:
|
||||
"""Letters become `A`, digits `9`; punctuation and spaces stay. Tells the
|
||||
format of a value without its content."""
|
||||
text = str(value)
|
||||
shape = "".join("9" if c.isdigit() else "A" if c.isalpha() else c for c in text[:_SHAPE_MAX])
|
||||
return shape + ("…" if len(text) > _SHAPE_MAX else "")
|
||||
|
||||
|
||||
def column_label(name: Any) -> str:
|
||||
"""A source column name as it can be logged: verbatim when it looks like a
|
||||
header, its shape when it looks like data."""
|
||||
text = str(name).strip()
|
||||
if len(text) > _SHAPE_MAX or text.count(" ") > 3 or _VALUE_LIKE.search(text):
|
||||
return value_shape(text)
|
||||
return text
|
||||
|
||||
|
||||
def sanitize_message(message: str) -> str:
|
||||
"""Error messages from drivers and parsers may quote values (MySQL's
|
||||
"Duplicate entry 'N-0001'"); quoted text is dropped."""
|
||||
return _QUOTED.sub("'…'", str(message))[:_MESSAGE_MAX]
|
||||
|
||||
|
||||
def _blank(value: Any) -> bool:
|
||||
return value is None or (isinstance(value, str) and not value.strip())
|
||||
|
||||
|
||||
def _source_origin(source: ImportSource) -> dict[str, Any]:
|
||||
"""What kind of source it was, without names, hosts or credentials."""
|
||||
payload = source.payload
|
||||
origin: dict[str, Any] = {"tipo": source.source_type}
|
||||
files = payload.get("files")
|
||||
if isinstance(files, list):
|
||||
names = [f.get("name") or "" for f in files if isinstance(f, dict)]
|
||||
else:
|
||||
names = [(payload.get("options") or {}).get("file_name") or payload.get("file_name") or ""]
|
||||
extensions = sorted({Path(n).suffix.lower() for n in names if Path(n).suffix})
|
||||
if extensions:
|
||||
origin["extensiones"] = extensions
|
||||
if isinstance(files, list):
|
||||
origin["archivos"] = len(files)
|
||||
if source.source_type == "sql":
|
||||
server = payload.get("server") if isinstance(payload.get("server"), dict) else {}
|
||||
scheme = str(payload.get("connection_string") or "").split(":", 1)[0].split("+", 1)[0]
|
||||
origin["motor"] = server.get("engine") or scheme or None
|
||||
origin["consulta_propia"] = bool(payload.get("query"))
|
||||
return origin
|
||||
|
||||
|
||||
@dataclass
|
||||
class _FieldStats:
|
||||
with_value: int = 0
|
||||
empty: int = 0
|
||||
errors: Counter = field(default_factory=Counter)
|
||||
shapes: Counter = field(default_factory=Counter)
|
||||
catalog_values: Counter = field(default_factory=Counter)
|
||||
|
||||
def as_dict(self, threshold: int) -> dict[str, Any]:
|
||||
out: dict[str, Any] = {"con_valor": self.with_value, "vacios": self.empty}
|
||||
if self.errors:
|
||||
out["errores"] = dict(self.errors)
|
||||
if self.shapes:
|
||||
out["formatos_rechazados"] = dict(self.shapes.most_common(10))
|
||||
frequent = {v: n for v, n in self.catalog_values.most_common(20) if n >= threshold}
|
||||
if frequent:
|
||||
out["valores_fuera_de_catalogo"] = frequent
|
||||
rare = sum(n for n in self.catalog_values.values() if n < threshold)
|
||||
if rare:
|
||||
out["valores_fuera_de_catalogo_poco_frecuentes"] = rare
|
||||
return out
|
||||
|
||||
|
||||
class _SourceAudit:
|
||||
def __init__(self, source: ImportSource):
|
||||
self.source = source
|
||||
self.fields: dict[str, _FieldStats] = defaultdict(_FieldStats)
|
||||
self.rows: dict[str, Any] = {"leidas": 0}
|
||||
self.links: dict[str, int] = {}
|
||||
self.warnings: Counter = Counter()
|
||||
|
||||
def observe_rows(self, rows: Iterable[dict[str, Any] | None]) -> None:
|
||||
mapped = set(self.source.column_mapping.values()) | set(self.source.defaults)
|
||||
merged = 0
|
||||
for row in rows:
|
||||
self.rows["leidas"] += 1
|
||||
if row is None:
|
||||
merged += 1
|
||||
continue
|
||||
for name in mapped:
|
||||
stats = self.fields[name]
|
||||
if _blank(row.get(name)):
|
||||
stats.empty += 1
|
||||
else:
|
||||
stats.with_value += 1
|
||||
if merged:
|
||||
self.rows["combinadas_con_otra_fuente"] = merged
|
||||
|
||||
def observe_validation(self, validation: BatchValidationResult) -> None:
|
||||
self.rows["validas"] = validation.valid_count
|
||||
self.rows["rechazadas_en_validacion"] = validation.error_count
|
||||
for row_errors in validation.rejected:
|
||||
for error in row_errors.errors:
|
||||
stats = self.fields[error.field]
|
||||
stats.errors[error.category.value] += 1
|
||||
if _blank(error.raw_value):
|
||||
continue
|
||||
if error.category is ErrorCategory.OUT_OF_CATALOG and len(str(error.raw_value)) <= _SHAPE_MAX:
|
||||
stats.catalog_values[str(error.raw_value).strip().upper()] += 1
|
||||
elif error.category in (ErrorCategory.TYPE_INVALID, ErrorCategory.UNKNOWN, ErrorCategory.OUT_OF_CATALOG):
|
||||
stats.shapes[value_shape(error.raw_value)] += 1
|
||||
|
||||
def observe_write(self, *, created: int, updated: int, conflicts: int, linked: dict[str, int]) -> None:
|
||||
self.rows.update(insertadas=created, actualizadas=updated, rechazadas_por_conflicto=conflicts)
|
||||
self.links = dict(linked)
|
||||
|
||||
def observe_warnings(self, warnings: Iterable[dict[str, Any]]) -> None:
|
||||
for warning in warnings:
|
||||
self.warnings[f"{warning.get('category')}:{warning.get('field')}"] += 1
|
||||
|
||||
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())
|
||||
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),
|
||||
"campos_mapeados": sorted(mapped),
|
||||
"campos_con_valor_fijo": sorted(fixed),
|
||||
"campos_sin_mapear": sorted(set(spec_fields) - mapped - fixed),
|
||||
"requeridos_sin_mapear": sorted(required - mapped - fixed),
|
||||
},
|
||||
"filas": self.rows,
|
||||
"campos": {name: stats.as_dict(threshold) for name, stats in sorted(self.fields.items())},
|
||||
}
|
||||
if self.links:
|
||||
out["vinculos_resueltos"] = self.links
|
||||
if self.warnings:
|
||||
out["advertencias"] = dict(self.warnings)
|
||||
return out
|
||||
|
||||
|
||||
class ImportAudit:
|
||||
"""The aggregate record of one attempt. `operation` is "validacion" or "carga"."""
|
||||
|
||||
def __init__(self, operation: str, options: dict[str, Any] | None = None):
|
||||
self.id = str(uuid.uuid4())
|
||||
self.operation = operation
|
||||
self.options = options or {}
|
||||
self.started = time.monotonic()
|
||||
self.date = datetime.now(timezone.utc)
|
||||
self.sources: list[_SourceAudit] = []
|
||||
self.outcome = "en_curso"
|
||||
self.error: dict[str, str] | None = None
|
||||
|
||||
def source(self, source: ImportSource) -> _SourceAudit:
|
||||
audit = _SourceAudit(source)
|
||||
self.sources.append(audit)
|
||||
return audit
|
||||
|
||||
def succeed(self, outcome: str = "completada") -> None:
|
||||
self.outcome = outcome
|
||||
|
||||
def fail(self, exc: BaseException, outcome: str = "fallida") -> None:
|
||||
self.outcome = outcome
|
||||
self.error = {"tipo": type(exc).__name__, "mensaje": sanitize_message(str(exc))}
|
||||
|
||||
@property
|
||||
def domain(self) -> str | None:
|
||||
return self.sources[0].source.domain if self.sources else None
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
threshold = min_count()
|
||||
record: dict[str, Any] = {
|
||||
"version": SCHEMA_VERSION,
|
||||
"id": self.id,
|
||||
"fecha": self.date.isoformat(timespec="seconds"),
|
||||
"operacion": self.operation,
|
||||
"dominio": self.domain,
|
||||
"resultado": self.outcome,
|
||||
"duracion_s": round(time.monotonic() - self.started, 2),
|
||||
"opciones": self.options,
|
||||
"fuentes": [s.as_dict(threshold) for s in self.sources],
|
||||
}
|
||||
if self.error:
|
||||
record["error"] = self.error
|
||||
totals = Counter()
|
||||
for s in self.sources:
|
||||
for key, value in s.rows.items():
|
||||
totals[key] += value
|
||||
record["totales"] = dict(totals)
|
||||
return record
|
||||
|
||||
|
||||
class JsonlAuditSink:
|
||||
"""One JSON object per line; appends are locked so several gunicorn
|
||||
workers can share the file."""
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
|
||||
def write(self, record: dict[str, Any]) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
line = json.dumps(record, ensure_ascii=False, default=str) + "\n"
|
||||
with open(self.path, "a", encoding="utf-8") as handle:
|
||||
fcntl.flock(handle, fcntl.LOCK_EX)
|
||||
try:
|
||||
handle.write(line)
|
||||
finally:
|
||||
fcntl.flock(handle, fcntl.LOCK_UN)
|
||||
|
||||
def read(self) -> list[dict[str, Any]]:
|
||||
if not self.path.exists():
|
||||
return []
|
||||
records = []
|
||||
with open(self.path, encoding="utf-8") as handle:
|
||||
for line in handle:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
records.append(json.loads(line))
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
return records
|
||||
|
||||
|
||||
def default_sink() -> JsonlAuditSink:
|
||||
return JsonlAuditSink(report_dir() / "importaciones.jsonl")
|
||||
|
||||
|
||||
def record(audit: ImportAudit) -> None:
|
||||
"""Writes the record; a full disk must not turn a successful import into an error."""
|
||||
try:
|
||||
default_sink().write(audit.as_dict())
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def summarize(records: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""Totals per target over every logged attempt: how many rows arrived,
|
||||
how many were written, and which fields failed most and how."""
|
||||
by_target: dict[str, dict[str, Any]] = {}
|
||||
attempts = Counter()
|
||||
for rec in records:
|
||||
attempts[f"{rec.get('operacion')}:{rec.get('resultado')}"] += 1
|
||||
for src in rec.get("fuentes", []):
|
||||
target = by_target.setdefault(
|
||||
src["destino"],
|
||||
{"intentos": 0, "cargas_completadas": 0, "filas": Counter(), "errores_por_campo": defaultdict(Counter),
|
||||
"formatos_rechazados": defaultdict(Counter), "requeridos_sin_mapear": Counter(), "origenes": Counter()},
|
||||
)
|
||||
target["intentos"] += 1
|
||||
if rec.get("operacion") == "carga" and rec.get("resultado") == "completada":
|
||||
target["cargas_completadas"] += 1
|
||||
for key, value in src.get("filas", {}).items():
|
||||
target["filas"][key] += value
|
||||
target["origenes"][src.get("origen", {}).get("tipo") or "?"] += 1
|
||||
for name in src.get("mapeo", {}).get("requeridos_sin_mapear", []):
|
||||
target["requeridos_sin_mapear"][name] += 1
|
||||
for name, stats in src.get("campos", {}).items():
|
||||
target["errores_por_campo"][name].update(stats.get("errores", {}))
|
||||
target["formatos_rechazados"][name].update(stats.get("formatos_rechazados", {}))
|
||||
return {
|
||||
"intentos": dict(attempts),
|
||||
"ultimo": records[-1]["fecha"] if records else None,
|
||||
"destinos": {
|
||||
key: {
|
||||
"intentos": t["intentos"],
|
||||
"cargas_completadas": t["cargas_completadas"],
|
||||
"filas_en_cargas_completadas": dict(t["filas"]),
|
||||
"origenes": dict(t["origenes"]),
|
||||
"requeridos_sin_mapear": dict(t["requeridos_sin_mapear"]),
|
||||
"errores_por_campo": {k: dict(v) for k, v in t["errores_por_campo"].items() if v},
|
||||
"formatos_rechazados": {k: dict(v.most_common(10)) for k, v in t["formatos_rechazados"].items() if v},
|
||||
}
|
||||
for key, t in sorted(by_target.items())
|
||||
},
|
||||
}
|
||||
@@ -53,9 +53,6 @@ class Connector(ABC):
|
||||
"""Builds a ready-to-read connector from the JSON a client sends
|
||||
in an import request's `payload`."""
|
||||
|
||||
@abstractmethod
|
||||
def get_columns(self) -> list[SourceColumn]: ...
|
||||
|
||||
@abstractmethod
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult: ...
|
||||
|
||||
@@ -88,6 +85,6 @@ def decode_file(payload: dict[str, Any], key: str = "file_base64") -> bytes:
|
||||
try:
|
||||
return base64.b64decode(payload[key], validate=True)
|
||||
except KeyError as exc:
|
||||
raise ConnectorError(f"missing {key}") from exc
|
||||
raise ConnectorError(f"falta {key}") from exc
|
||||
except (binascii.Error, ValueError, TypeError) as exc:
|
||||
raise ConnectorError(f"{key} is not valid base64: {exc}") from exc
|
||||
raise ConnectorError(f"{key} no es base64 válido: {exc}") from exc
|
||||
|
||||
@@ -30,7 +30,7 @@ class CsvConnector(FileConnector):
|
||||
def __init__(self, raw: bytes, *, delimiter: str | None = None, encoding: str | None = None):
|
||||
self._encoding, text = _decode(raw, encoding)
|
||||
if "\x00" in text:
|
||||
raise ConnectorError("file looks binary, not a delimited text file")
|
||||
raise ConnectorError("el archivo parece binario, no un texto delimitado")
|
||||
self._delimiter = delimiter or _sniff_delimiter(text)
|
||||
try:
|
||||
self._df = pd.read_csv(
|
||||
@@ -42,7 +42,7 @@ class CsvConnector(FileConnector):
|
||||
skipinitialspace=True,
|
||||
)
|
||||
except Exception as exc: # pandas raises a variety of error types
|
||||
raise ConnectorError(f"could not parse CSV: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo leer el CSV: {exc}") from exc
|
||||
self._df.columns = [str(c).strip() for c in self._df.columns]
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
@@ -58,7 +58,7 @@ def _decode(raw: bytes, encoding: str | None) -> tuple[str, str]:
|
||||
return candidate, raw.decode(candidate)
|
||||
except (UnicodeDecodeError, LookupError):
|
||||
continue
|
||||
raise ConnectorError(f"could not decode CSV as {encoding or ' / '.join(_FALLBACK_ENCODINGS)}")
|
||||
raise ConnectorError(f"no se pudo decodificar el CSV como {encoding or ' / '.join(_FALLBACK_ENCODINGS)}")
|
||||
|
||||
|
||||
def _sniff_delimiter(text: str) -> str:
|
||||
|
||||
@@ -12,6 +12,7 @@ from extraction.segmentation import SEGMENTERS
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
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.registry import ENTITY_REGISTRY
|
||||
@@ -48,16 +49,49 @@ 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"):
|
||||
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")
|
||||
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
|
||||
|
||||
|
||||
@register_connector
|
||||
class DocumentConnector(DataFrameConnector):
|
||||
"""Clinical documents that are not tables: one report per patient,
|
||||
several pages per patient, many patients per file, scans, free text.
|
||||
several pages per patient, many patients per file, scans, free text —
|
||||
uploaded directly, or read one row at a time from a SQL source whose
|
||||
`payload` carries `sql` (a connection plus `table`/`query`, `column`
|
||||
and `key_column`) instead of `files`; either way, every row's content
|
||||
reaches the same extraction, PDF, image or plain text alike.
|
||||
|
||||
Every file is read page by page (text layer or OCR), split into
|
||||
per-patient records, and the target entity's fields are extracted from
|
||||
labels and narrative text. Records of the same patient found in other
|
||||
pages or files are merged. Each row also carries the record's pages as
|
||||
a PDF (`documento`), mappable to the entity's file column.
|
||||
Every file is read page by page (text layer or OCR; plain text as its
|
||||
own lines), split into per-patient records, and the target entity's
|
||||
fields are extracted from labels and narrative text. Records of the
|
||||
same patient found in other pages or files — or rows — are merged.
|
||||
Each row also carries the record's pages as a PDF (`documento`),
|
||||
mappable to the entity's file column, when the source produced one.
|
||||
|
||||
Corrections made while reviewing travel in `overrides`
|
||||
(`{"<row>": {"field": value}}`) and win over the extracted value.
|
||||
@@ -65,7 +99,7 @@ class DocumentConnector(DataFrameConnector):
|
||||
|
||||
kind = "document"
|
||||
label = "Documentos clínicos"
|
||||
description = "Reportes, formatos y notas en PDF o imagen; los campos se extraen del texto libre"
|
||||
description = "Reportes, formatos y notas en PDF, imagen o texto; los campos se extraen del contenido"
|
||||
category = "document"
|
||||
icon = "document_scanner"
|
||||
extensions: ClassVar[tuple[str, ...]] = tuple(supported_extensions())
|
||||
@@ -82,14 +116,14 @@ class DocumentConnector(DataFrameConnector):
|
||||
overrides: dict[str, dict[str, Any]] | None = None,
|
||||
):
|
||||
if not files:
|
||||
raise ConnectorError("no documents given")
|
||||
raise ConnectorError("no se recibieron documentos")
|
||||
entity = ENTITY_REGISTRY.get(target)
|
||||
if entity is None:
|
||||
raise ConnectorError(f"unknown target: {target!r}")
|
||||
raise ConnectorError(f"destino desconocido: {target!r}")
|
||||
if segmentation not in SEGMENTERS:
|
||||
raise ConnectorError(f"unknown segmentation {segmentation!r} (available: {', '.join(SEGMENTERS)})")
|
||||
raise ConnectorError(f"segmentación desconocida {segmentation!r} (disponibles: {', '.join(SEGMENTERS)})")
|
||||
if ocr_mode not in ("auto", "always", "never"):
|
||||
raise ConnectorError(f"unknown ocr_mode {ocr_mode!r}")
|
||||
raise ConnectorError(f"ocr_mode desconocido {ocr_mode!r}")
|
||||
self.files = files
|
||||
self.target = target
|
||||
self.specs = field_specs_for(entity, key_pattern=key_pattern)
|
||||
@@ -103,7 +137,12 @@ class DocumentConnector(DataFrameConnector):
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "DocumentConnector":
|
||||
files = [(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)]
|
||||
if payload.get("sql"):
|
||||
files = _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)
|
||||
]
|
||||
return cls(
|
||||
files,
|
||||
target=payload["target"],
|
||||
@@ -175,12 +214,9 @@ class DocumentConnector(DataFrameConnector):
|
||||
return combine_pages(parts) if parts else None
|
||||
|
||||
def _record_image(self, record: ExtractedRecord) -> bytes | None:
|
||||
"""A PNG of the clearest picture embedded on the record's pages (a
|
||||
mammogram, a lesion photo) — mappable onto a target's own image
|
||||
column (e.g. `mast_dicom_blob`), the same way `documento` maps onto
|
||||
a PDF column. A `scan` is the page itself, not a distinct picture,
|
||||
so a `figure` wins when both are present; with several figures, the
|
||||
first one found is used."""
|
||||
"""A PNG of the first picture embedded on the record's pages (a mammogram,
|
||||
a lesion photo), mappable onto an image column such as `mast_dicom_blob`.
|
||||
A `figure` wins over a `scan`, which is the whole page."""
|
||||
by_name = dict(self.files)
|
||||
candidates = [(document, image) for document, image in record.images if document in by_name]
|
||||
if not candidates:
|
||||
|
||||
@@ -29,19 +29,20 @@ class EdfConnector(FileConnector):
|
||||
extensions = ("edf",)
|
||||
option_names = ("file_name",)
|
||||
|
||||
def __init__(self, raw: bytes, *, file_name: str = "registro.edf"):
|
||||
self.files = [(file_name, raw)]
|
||||
def __init__(self, files: list[tuple[str, bytes]]):
|
||||
self.files = files
|
||||
self._df: pd.DataFrame | None = None
|
||||
|
||||
@classmethod
|
||||
def from_bytes(cls, raw: bytes, options: dict[str, Any] | None = None) -> "EdfConnector":
|
||||
return cls([((options or {}).get("file_name") or "registro.edf", raw)])
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "EdfConnector":
|
||||
"""Accepts one file (`file_base64` + `options.file_name`) or several
|
||||
(`files: [{name, file_base64}]`)."""
|
||||
"""One file (`file_base64` + `options.file_name`) or several (`files: [{name, file_base64}]`)."""
|
||||
if not payload.get("files"):
|
||||
return super().from_payload(payload)
|
||||
connector = cls(b"", file_name="")
|
||||
connector.files = [(f.get("name") or f"registro_{i}.edf", decode_file(f)) for i, f in enumerate(payload["files"], 1)]
|
||||
return connector
|
||||
return cls([(f.get("name") or f"registro_{i}.edf", decode_file(f)) for i, f in enumerate(payload["files"], 1)])
|
||||
|
||||
def metadata(self) -> dict[str, Any]:
|
||||
return {"files": [name for name, _ in self.files]}
|
||||
|
||||
@@ -25,15 +25,15 @@ class ExcelConnector(FileConnector):
|
||||
try:
|
||||
self._workbook = pd.ExcelFile(io.BytesIO(raw), engine="openpyxl")
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not open Excel file: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo abrir el archivo de Excel: {exc}") from exc
|
||||
|
||||
self._sheet = sheet_name if sheet_name not in (None, "") else self._workbook.sheet_names[0]
|
||||
if isinstance(self._sheet, str) and self._sheet not in self._workbook.sheet_names:
|
||||
raise ConnectorError(f"sheet {self._sheet!r} not found — available: {self._workbook.sheet_names}")
|
||||
raise ConnectorError(f"no existe la hoja {self._sheet!r} (disponibles: {self._workbook.sheet_names})")
|
||||
try:
|
||||
self._df = self._workbook.parse(self._sheet, dtype=object)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not read sheet {self._sheet!r}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo leer la hoja {self._sheet!r}: {exc}") from exc
|
||||
self._df.columns = [str(c).strip() for c in self._df.columns]
|
||||
|
||||
def list_sheets(self) -> list[str]:
|
||||
|
||||
@@ -26,19 +26,19 @@ class JsonConnector(FileConnector):
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not parse JSON: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo leer el JSON: {exc}") from exc
|
||||
|
||||
if record_path:
|
||||
try:
|
||||
for key in record_path.split("."):
|
||||
data = data[key]
|
||||
except (KeyError, TypeError, IndexError) as exc:
|
||||
raise ConnectorError(f"record_path {record_path!r} not found: {exc}") from exc
|
||||
raise ConnectorError(f"no se encontró record_path {record_path!r}: {exc}") from exc
|
||||
|
||||
if isinstance(data, dict):
|
||||
data = data.get("data", [data])
|
||||
if not isinstance(data, list) or not all(isinstance(record, dict) for record in data):
|
||||
raise ConnectorError("JSON source must resolve to a list of objects")
|
||||
raise ConnectorError("el JSON debe dar una lista de objetos")
|
||||
|
||||
self._record_path = record_path
|
||||
self._df = pd.DataFrame([_flatten(record) for record in data], dtype=object)
|
||||
|
||||
@@ -54,7 +54,7 @@ class RegionSpec:
|
||||
try:
|
||||
return cls(str(raw["target_field"]), [int(n) for n in raw["page_numbers"]], tuple(float(v) for v in raw["bbox"]))
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise ConnectorError(f"invalid region: {exc}") from exc
|
||||
raise ConnectorError(f"región inválida: {exc}") from exc
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -81,7 +81,7 @@ class PdfConnector(DataFrameConnector):
|
||||
elif mode == "regions":
|
||||
connector.extract_regions([RegionSpec.parse(r) for r in payload["regions"]], dpi=int(payload.get("dpi", _DEFAULT_DPI)))
|
||||
else:
|
||||
raise ConnectorError(f"unknown pdf mode: {mode!r}")
|
||||
raise ConnectorError(f"modo de PDF desconocido: {mode!r}")
|
||||
return connector
|
||||
|
||||
def __init__(self, file_bytes: bytes):
|
||||
@@ -89,7 +89,7 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
self._pdf = pdfplumber.open(io.BytesIO(file_bytes))
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not open PDF: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo abrir el PDF: {exc}") from exc
|
||||
|
||||
self._table_grid: list[list[str | None]] | None = None
|
||||
self._region_rows: dict[str, list[str | None]] | None = None
|
||||
@@ -120,12 +120,12 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
tables = page.find_tables()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not detect tables on page {page.page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron detectar tablas en la página {page.page_number}: {exc}") from exc
|
||||
for table in tables:
|
||||
try:
|
||||
grid = table.extract()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not extract table on page {page.page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo extraer la tabla de la página {page.page_number}: {exc}") from exc
|
||||
if len(grid) < 2:
|
||||
continue # header + >=1 data row required
|
||||
candidates.append(
|
||||
@@ -145,9 +145,9 @@ class PdfConnector(DataFrameConnector):
|
||||
cropped = page.within_bbox(bbox, strict=False)
|
||||
grid = cropped.extract_table()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not extract table at {bbox} on page {page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo extraer la tabla en {bbox} de la página {page_number}: {exc}") from exc
|
||||
if not grid or len(grid) < 2:
|
||||
raise ConnectorError(f"no usable table found at {bbox} on page {page_number}")
|
||||
raise ConnectorError(f"no se encontró una tabla utilizable en {bbox} de la página {page_number}")
|
||||
self._table_grid = grid
|
||||
self._region_rows = None
|
||||
|
||||
@@ -161,14 +161,14 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
image = page.to_image(resolution=dpi).original
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not render page {page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo dibujar la página {page_number}: {exc}") from exc
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
def extract_regions(self, regions: list[RegionSpec], dpi: int = _DEFAULT_DPI) -> dict[str, list[str | None]]:
|
||||
if not regions:
|
||||
raise ConnectorError("no regions given")
|
||||
raise ConnectorError("no se indicaron regiones")
|
||||
_check_dpi(dpi)
|
||||
|
||||
by_page: dict[int, list[RegionSpec]] = {}
|
||||
@@ -183,8 +183,9 @@ class PdfConnector(DataFrameConnector):
|
||||
page = self._page(page_number)
|
||||
lines = self._lines_for_page(page, by_page[page_number], dpi)
|
||||
for row in self._cluster_rows(lines, page_number):
|
||||
for region in by_page[page_number]:
|
||||
result[region.target_field].append(row.get(region.target_field))
|
||||
# Every field gets a cell per row, even regions not drawn on this page.
|
||||
for field_name in result:
|
||||
result[field_name].append(row.get(field_name))
|
||||
|
||||
self._region_rows = result
|
||||
self._table_grid = None
|
||||
@@ -210,7 +211,7 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
region_lines = page.within_bbox(point_bbox, strict=False).extract_text_lines()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not extract text for region {region.target_field!r}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo extraer el texto de la región {region.target_field!r}: {exc}") from exc
|
||||
for line in region_lines:
|
||||
text = (line.get("text") or "").strip()
|
||||
if not text:
|
||||
@@ -228,7 +229,7 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
rendered_image = page.to_image(resolution=dpi).original
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not render page {page.page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo dibujar la página {page.page_number}: {exc}") from exc
|
||||
img_w, img_h = rendered_image.size
|
||||
crop_box = (
|
||||
max(0, round(x0n * img_w)),
|
||||
@@ -242,7 +243,7 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
data = pytesseract.image_to_data(cropped, output_type=Output.DICT, lang=DEFAULT_LANG, config=_OCR_CONFIG)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"OCR failed for region {region.target_field!r}: {exc}") from exc
|
||||
raise ConnectorError(f"falló el OCR de la región {region.target_field!r}: {exc}") from exc
|
||||
for words in group_words(data):
|
||||
text = " ".join(w["text"] for w in words).strip()
|
||||
if not text:
|
||||
@@ -306,7 +307,7 @@ class PdfConnector(DataFrameConnector):
|
||||
self.warnings.append(
|
||||
ExtractionWarning(
|
||||
page_number=page_number,
|
||||
message=f"alignment conflict on field(s) {duplicated}: cluster split at largest internal gap",
|
||||
message=f"conflicto de alineación en {duplicated}: el grupo se dividió en el mayor espacio interno",
|
||||
)
|
||||
)
|
||||
return self._split_conflicts(left, page_number) + self._split_conflicts(right, page_number)
|
||||
@@ -322,13 +323,13 @@ class PdfConnector(DataFrameConnector):
|
||||
return pd.DataFrame(data_rows, columns=columns)
|
||||
if self._region_rows is not None:
|
||||
return pd.DataFrame(self._region_rows)
|
||||
raise ConnectorError("no table or region resolved — call select_table() or extract_regions() first")
|
||||
raise ConnectorError("no hay tabla ni regiones seleccionadas")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _page(self, page_number: int):
|
||||
if not (1 <= page_number <= self.page_count):
|
||||
raise ConnectorError(f"page_number out of range: {page_number}")
|
||||
raise ConnectorError(f"page_number fuera de rango: {page_number}")
|
||||
return self._pdf.pages[page_number - 1]
|
||||
|
||||
@staticmethod
|
||||
@@ -340,7 +341,7 @@ class PdfConnector(DataFrameConnector):
|
||||
|
||||
def _check_dpi(dpi: int) -> None:
|
||||
if not (_MIN_DPI <= dpi <= _MAX_DPI):
|
||||
raise ConnectorError(f"dpi must be between {_MIN_DPI} and {_MAX_DPI}, got {dpi}")
|
||||
raise ConnectorError(f"dpi debe estar entre {_MIN_DPI} y {_MAX_DPI} (se recibió {dpi})")
|
||||
|
||||
|
||||
def _table_confidence(grid: list[list[str | None]]) -> float:
|
||||
|
||||
@@ -16,17 +16,17 @@ def register_connector(cls: type[Connector]) -> type[Connector]:
|
||||
def connector_class(kind: str | None) -> type[Connector]:
|
||||
cls = CONNECTORS.get(kind or "")
|
||||
if cls is None:
|
||||
raise ConnectorError(f"unknown source kind {kind!r} (available: {', '.join(sorted(CONNECTORS))})")
|
||||
raise ConnectorError(f"tipo de fuente desconocido {kind!r} (disponibles: {', '.join(sorted(CONNECTORS))})")
|
||||
return cls
|
||||
|
||||
|
||||
def build_connector(kind: str | None, payload: dict[str, Any]) -> Connector:
|
||||
if not isinstance(payload, dict):
|
||||
raise ConnectorError("payload must be an object")
|
||||
raise ConnectorError("payload debe ser un objeto")
|
||||
try:
|
||||
return connector_class(kind).from_payload(payload)
|
||||
except KeyError as exc:
|
||||
raise ConnectorError(f"missing field in payload: {exc}") from exc
|
||||
raise ConnectorError(f"falta un campo en payload: {exc}") from exc
|
||||
|
||||
|
||||
def kind_for_filename(filename: str) -> str | None:
|
||||
|
||||
@@ -91,21 +91,21 @@ class SqlConnector(Connector):
|
||||
return cls(cls.server_url(payload["server"]))
|
||||
if payload.get("connection_string"):
|
||||
return cls(payload["connection_string"])
|
||||
raise ConnectorError("missing server or connection_string")
|
||||
raise ConnectorError("falta server o connection_string")
|
||||
|
||||
@classmethod
|
||||
def server_url(cls, server: dict[str, Any]) -> sa.engine.URL:
|
||||
engine = cls.ENGINES.get(server.get("engine", ""))
|
||||
if engine is None:
|
||||
raise ConnectorError(f"unknown engine {server.get('engine')!r} (available: {', '.join(cls.ENGINES)})")
|
||||
raise ConnectorError(f"motor desconocido {server.get('engine')!r} (disponibles: {', '.join(cls.ENGINES)})")
|
||||
if not engine.available:
|
||||
raise ConnectorError(f"the {engine.label} driver ({engine.driver_module}) is not installed on the server")
|
||||
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("host and database are required")
|
||||
raise ConnectorError("se requieren el servidor (host) y la base de datos")
|
||||
try:
|
||||
port = int(server.get("port") or engine.default_port)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ConnectorError("port must be a number") from exc
|
||||
raise ConnectorError("el puerto debe ser un número") from exc
|
||||
return sa.engine.URL.create(
|
||||
engine.drivername,
|
||||
username=server.get("user") or None,
|
||||
@@ -121,7 +121,7 @@ class SqlConnector(Connector):
|
||||
try:
|
||||
self._engine = sa.create_engine(url, poolclass=NullPool)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"invalid connection string: {exc}") from exc
|
||||
raise ConnectorError(f"cadena de conexión inválida: {exc}") from exc
|
||||
self._table: sa.Table | None = None
|
||||
self._query: str | None = None
|
||||
|
||||
@@ -134,7 +134,7 @@ class SqlConnector(Connector):
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not connect: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo conectar: {exc}") from exc
|
||||
|
||||
def get_dialect(self) -> str:
|
||||
return self._engine.dialect.name
|
||||
@@ -143,39 +143,36 @@ class SqlConnector(Connector):
|
||||
try:
|
||||
return sa.inspect(self._engine).get_schema_names()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not list schemas: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron listar los esquemas: {exc}") from exc
|
||||
|
||||
def list_tables(self, *, schema: str | None = None) -> list[str]:
|
||||
try:
|
||||
inspector = sa.inspect(self._engine)
|
||||
return inspector.get_table_names(schema=schema) + inspector.get_view_names(schema=schema)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not list tables: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron listar las tablas: {exc}") from exc
|
||||
|
||||
def list_columns(self, table_name: str, *, schema: str | None = None) -> list[SourceColumn]:
|
||||
try:
|
||||
columns = sa.inspect(self._engine).get_columns(table_name, schema=schema)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not list columns: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron listar las columnas: {exc}") from exc
|
||||
return [SourceColumn(name=c["name"], inferred_type=_sa_type_to_kind(c["type"])) for c in columns]
|
||||
|
||||
def select_table(self, table_name: str, *, schema: str | None = None) -> "SqlConnector":
|
||||
try:
|
||||
self._table = sa.Table(table_name, sa.MetaData(), schema=schema, autoload_with=self._engine)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not open table {table_name!r}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo abrir la tabla {table_name!r}: {exc}") from exc
|
||||
self._query = None
|
||||
return self
|
||||
|
||||
def select_query(self, query: str) -> "SqlConnector":
|
||||
self._query, self._table = self._policy.check_query(query), None
|
||||
self._query, self._table = self._policy.check_query(query, dialect=self.get_dialect()), None
|
||||
return self
|
||||
|
||||
# -- Connector ----------------------------------------------------------
|
||||
|
||||
def get_columns(self) -> list[SourceColumn]:
|
||||
return self.preview(limit=200).columns
|
||||
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult:
|
||||
statement = self._selectable()
|
||||
try:
|
||||
@@ -187,7 +184,7 @@ class SqlConnector(Connector):
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not read rows: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron leer las filas: {exc}") from exc
|
||||
return PreviewResult(columns=self._columns(names, rows), sample_rows=rows, total_rows=total)
|
||||
|
||||
def read_rows(self, column_mapping: dict[str, str]) -> Iterator[dict[str, Any]]:
|
||||
@@ -200,7 +197,7 @@ class SqlConnector(Connector):
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not read rows: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron leer las filas: {exc}") from exc
|
||||
|
||||
# -- internals ----------------------------------------------------------
|
||||
|
||||
@@ -209,7 +206,7 @@ class SqlConnector(Connector):
|
||||
return sa.select(self._table).subquery("source")
|
||||
if self._query:
|
||||
return _text_subquery(self._query)
|
||||
raise ConnectorError("no table or query selected — call select_table()/select_query() first")
|
||||
raise ConnectorError("no hay tabla ni consulta seleccionada")
|
||||
|
||||
def _columns(self, names: list[str], rows: list[dict[str, Any]]) -> list[SourceColumn]:
|
||||
if self._table is not None:
|
||||
|
||||
@@ -10,16 +10,24 @@ to, so:
|
||||
read-only connection, not instead of it).
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
import sqlglot
|
||||
from sqlglot import exp
|
||||
from sqlalchemy.engine import URL, make_url
|
||||
from sqlalchemy.exc import ArgumentError
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
|
||||
_DEFAULT_DIALECTS = "mysql,mariadb,postgresql,mssql,oracle"
|
||||
_LEADING_COMMENTS = re.compile(r"^\s*((--[^\n]*\n)|(/\*.*?\*/)|\s)*", re.S)
|
||||
_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"}
|
||||
# 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
|
||||
# top-level SELECT, so checking only the root node's type is not enough).
|
||||
_WRITE_NODES = (exp.Into, exp.Insert, exp.Update, exp.Delete)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -40,28 +48,42 @@ class SqlSourcePolicy:
|
||||
try:
|
||||
url = connection if isinstance(connection, URL) else make_url(connection)
|
||||
except ArgumentError as exc:
|
||||
raise ConnectorError(f"invalid connection string: {exc}") from exc
|
||||
raise ConnectorError(f"cadena de conexión inválida: {exc}") from exc
|
||||
dialect = url.get_backend_name()
|
||||
if dialect not in self.allowed_dialects:
|
||||
raise ConnectorError(
|
||||
f"dialect {dialect!r} is not allowed for import sources (allowed: {', '.join(sorted(self.allowed_dialects))})"
|
||||
f"el motor {dialect!r} no está permitido como fuente (permitidos: {', '.join(sorted(self.allowed_dialects))})"
|
||||
)
|
||||
if self.allowed_hosts is not None and (url.host or "").lower() not in self.allowed_hosts:
|
||||
raise ConnectorError(f"host {url.host!r} is not in the allowed import-source hosts")
|
||||
raise ConnectorError(f"el servidor {url.host!r} no está entre los permitidos como fuente")
|
||||
if _same_database(url, _own_database_urls()):
|
||||
raise ConnectorError("this connection points at the application's own database — not a valid import source")
|
||||
raise ConnectorError("esta conexión apunta a una base de datos de la propia aplicación; no puede ser una fuente")
|
||||
return url
|
||||
|
||||
@staticmethod
|
||||
def check_query(query: str) -> str:
|
||||
statement = query.strip().rstrip(";").strip()
|
||||
if ";" in statement:
|
||||
raise ConnectorError("custom SQL must be a single statement")
|
||||
body = _LEADING_COMMENTS.sub("", statement, count=1)
|
||||
first_word = body.split(None, 1)[0].upper() if body else ""
|
||||
if first_word not in ("SELECT", "WITH"):
|
||||
raise ConnectorError("custom SQL must be a SELECT (or WITH ... SELECT) query")
|
||||
return statement
|
||||
def check_query(query: str, *, dialect: str | None = None) -> str:
|
||||
"""Parses the query with `sqlglot` (in the source's own SQL dialect,
|
||||
when known) and inspects the resulting syntax tree, rather than
|
||||
matching keywords on the raw text — a string check can't tell a
|
||||
read-only `SELECT` from one hiding a write, e.g. MySQL's
|
||||
`SELECT ... INTO OUTFILE` (writes a file to the server) or a
|
||||
PostgreSQL CTE performing the write (`WITH t AS (DELETE FROM x
|
||||
RETURNING *) SELECT * FROM t` is a syntactic SELECT at the top)."""
|
||||
statement = query.strip()
|
||||
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]
|
||||
except sqlglot.errors.ParseError as exc:
|
||||
raise ConnectorError(f"la consulta no es SQL válido: {exc}") from exc
|
||||
if len(parsed) != 1:
|
||||
raise ConnectorError("la consulta debe ser una sola instrucción")
|
||||
root = parsed[0]
|
||||
if not isinstance(root, (exp.Select, exp.Union, exp.Intersect, exp.Except)):
|
||||
raise ConnectorError("la consulta debe ser un SELECT (o WITH ... SELECT)")
|
||||
if root.find(*_WRITE_NODES) is not None:
|
||||
raise ConnectorError("la consulta no puede escribir en el servidor de origen")
|
||||
return statement.rstrip(";").strip()
|
||||
|
||||
|
||||
def _own_database_urls() -> list[URL]:
|
||||
@@ -85,6 +107,8 @@ def _same_database(candidate: URL, own: list[URL]) -> bool:
|
||||
def key(url: URL) -> tuple:
|
||||
if url.get_backend_name() == "sqlite":
|
||||
return ("sqlite", os.path.realpath(url.database or ""))
|
||||
return (url.get_backend_name(), (url.host or "localhost").lower(), url.port, (url.database or "").lower())
|
||||
backend = url.get_backend_name()
|
||||
port = url.port or _DEFAULT_PORTS.get(backend)
|
||||
return (backend, (url.host or "localhost").lower(), port, (url.database or "").lower())
|
||||
|
||||
return key(candidate) in {key(url) for url in own}
|
||||
|
||||
@@ -16,9 +16,6 @@ class DataFrameConnector(Connector):
|
||||
@abstractmethod
|
||||
def _dataframe(self) -> pd.DataFrame: ...
|
||||
|
||||
def get_columns(self) -> list[SourceColumn]:
|
||||
return columns_from_dataframe(self._dataframe())
|
||||
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult:
|
||||
df = self._dataframe()
|
||||
return PreviewResult(
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
"""Auto-match suggestions for the column-mapping UI, based on stdlib `difflib`."""
|
||||
"""Auto-match suggestions for the column-mapping UI, based on `rapidfuzz`."""
|
||||
|
||||
import difflib
|
||||
import re
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
|
||||
from rapidfuzz import fuzz
|
||||
|
||||
# Keys are target fields; values are normalized source-column names (see
|
||||
# `_normalize`: lowercase, no accents, spaces/dashes/dots -> "_").
|
||||
SYNONYMS: dict[str, set[str]] = {
|
||||
"pac_id_hospital": {
|
||||
"id_hospital", "hospital_id", "expediente", "num_expediente", "no_expediente", "numero_expediente",
|
||||
"exp", "nss", "id_paciente", "paciente_id", "folio_paciente", "clave_paciente",
|
||||
# A source may name the patient column after the entity.
|
||||
"paciente",
|
||||
},
|
||||
"pac_fecha_nacimiento": {"fecha_nacimiento", "dob", "birth_date", "fecha_nac", "fec_nac", "f_nac", "f_nacimiento", "nacimiento"},
|
||||
"pac_sexo": {"sexo", "genero", "gender", "sex"},
|
||||
@@ -31,15 +34,11 @@ SYNONYMS: dict[str, set[str]] = {
|
||||
"bx_cin_grado": {"grado_cin", "cin", "resultado_histopatologico", "diagnostico_histopatologico"},
|
||||
"bh_fecha": {"fecha", "tomada", "fecha_toma", "fecha_muestra"},
|
||||
}
|
||||
# A source may name the patient column after the entity ("Paciente" holding
|
||||
# the expediente).
|
||||
SYNONYMS["pac_id_hospital"] |= {"paciente", "clave_paciente"}
|
||||
|
||||
# Scores per match kind; the 1:1 assignment takes the best-scoring pairs first.
|
||||
_EXACT, _NORMALIZED, _SYNONYM, _UNPREFIXED = 1.0, 0.9, 0.8, 0.75
|
||||
_WORD_FLOOR, _FUZZY_CAP = 0.5, 0.7
|
||||
# Words that carry no meaning for matching ("Fecha *de* solicitud") and are
|
||||
# too short to be anything but units ("kg", "g/dl").
|
||||
# Words that carry no meaning for matching ("Fecha *de* solicitud").
|
||||
_STOPWORDS = {"de", "del", "la", "el", "los", "las", "en", "por", "para", "con"}
|
||||
_NEAR_WORD = 0.8
|
||||
|
||||
@@ -63,6 +62,7 @@ def _normalize(name: str) -> str:
|
||||
|
||||
|
||||
def _words(normalized: str) -> list[str]:
|
||||
"""Meaningful words; two letters or fewer are units ("kg") or noise."""
|
||||
return [w for w in re.split(r"[^a-z0-9]+", normalized) if len(w) > 2 and w not in _STOPWORDS]
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ def _word_score(source_words: list[str], target_words: list[str]) -> float:
|
||||
return 0.0
|
||||
total = 0.0
|
||||
for word in source_words:
|
||||
best = max(difflib.SequenceMatcher(None, word, other).ratio() for other in target_words)
|
||||
best = max(fuzz.ratio(word, other) / 100.0 for other in target_words)
|
||||
if best >= _NEAR_WORD:
|
||||
total += best
|
||||
return total / max(len(source_words), len(target_words))
|
||||
@@ -89,7 +89,7 @@ def _unprefixed(target: str) -> str:
|
||||
return rest if rest else head
|
||||
|
||||
|
||||
class ColumnMatcher:
|
||||
def suggest_mapping(source_columns: list[str], target_fields: list[str]) -> list[MatchSuggestion]:
|
||||
"""Exact name -> normalized (case/accents/separators) -> static synonym
|
||||
table -> name without the table prefix -> word-level similarity -> no
|
||||
match.
|
||||
@@ -97,68 +97,60 @@ class ColumnMatcher:
|
||||
The 1:1 assignment is global: all (source, target) pairs are scored and
|
||||
claimed best-first, so a weak fuzzy match early in the file cannot take
|
||||
a target from an exact match later in it."""
|
||||
candidates: list[tuple[float, int, str, str, str]] = []
|
||||
for position, source in enumerate(source_columns):
|
||||
for target in target_fields:
|
||||
scored = _score(source, target)
|
||||
if scored is not None:
|
||||
score, reason = scored
|
||||
# -position: on equal scores the earlier source column wins.
|
||||
candidates.append((score, -position, source, target, reason))
|
||||
|
||||
def suggest(self, source_columns: list[str], target_fields: list[str]) -> list[MatchSuggestion]:
|
||||
candidates: list[tuple[float, int, str, str, str]] = []
|
||||
for position, source in enumerate(source_columns):
|
||||
for target in target_fields:
|
||||
scored = self._score(source, target)
|
||||
if scored is not None:
|
||||
score, reason = scored
|
||||
# -position: on equal scores the earlier source column wins.
|
||||
candidates.append((score, -position, source, target, reason))
|
||||
claimed_sources: dict[str, MatchSuggestion] = {}
|
||||
claimed_targets: set[str] = set()
|
||||
for score, _, source, target, reason in sorted(candidates, reverse=True):
|
||||
if source in claimed_sources or target in claimed_targets:
|
||||
continue
|
||||
claimed_sources[source] = MatchSuggestion(source, target, round(score, 2), reason)
|
||||
claimed_targets.add(target)
|
||||
|
||||
claimed_sources: dict[str, MatchSuggestion] = {}
|
||||
claimed_targets: set[str] = set()
|
||||
for score, _, source, target, reason in sorted(candidates, reverse=True):
|
||||
if source in claimed_sources or target in claimed_targets:
|
||||
continue
|
||||
claimed_sources[source] = MatchSuggestion(source, target, round(score, 2), reason)
|
||||
claimed_targets.add(target)
|
||||
return [claimed_sources.get(source, MatchSuggestion(source, None, 0.0, "none")) for source in source_columns]
|
||||
|
||||
return [claimed_sources.get(source, MatchSuggestion(source, None, 0.0, "none")) for source in source_columns]
|
||||
|
||||
@classmethod
|
||||
def _score(cls, source: str, target: str) -> tuple[float, str] | None:
|
||||
if source == target:
|
||||
return _EXACT, "exact"
|
||||
# A dotted (flattened JSON) name also matches by its last segment:
|
||||
# "paciente.expediente" is an expediente.
|
||||
variants = [source] + ([source.rsplit(".", 1)[-1]] if "." in source else [])
|
||||
scored = [s for s in (cls._score_one(v, target) for v in variants) if s is not None]
|
||||
return max(scored, key=lambda s: s[0]) if scored else None
|
||||
def _score(source: str, target: str) -> tuple[float, str] | None:
|
||||
if source == target:
|
||||
return _EXACT, "exact"
|
||||
# A dotted (flattened JSON) name also matches by its last segment:
|
||||
# "paciente.expediente" is an expediente.
|
||||
variants = [source] + ([source.rsplit(".", 1)[-1]] if "." in source else [])
|
||||
scored = [s for s in (_score_one(v, target) for v in variants) if s is not None]
|
||||
return max(scored, key=lambda s: s[0]) if scored else None
|
||||
|
||||
@staticmethod
|
||||
def _score_one(source: str, target: str) -> tuple[float, str] | None:
|
||||
normalized_source, normalized_target = _normalize(source), _normalize(target)
|
||||
if normalized_source == normalized_target:
|
||||
return _NORMALIZED, "normalized"
|
||||
if normalized_source in SYNONYMS.get(target, set()):
|
||||
return _SYNONYM, "synonym"
|
||||
unprefixed_target = _unprefixed(normalized_target)
|
||||
if normalized_source == unprefixed_target:
|
||||
return _UNPREFIXED, "unprefixed"
|
||||
# Not every field has a table prefix (`hemoglobina_g_dl`), so words
|
||||
# are compared against both the full and the unprefixed name. When
|
||||
# the target *does* have real content beyond its prefix ("eeg" in
|
||||
# "eeg_estudio"), that prefix is dropped from the full-name words
|
||||
# first: every column in the table shares it, so a source word
|
||||
# matching only that (e.g. "eeg_id" ~ "eeg_estudio", both just
|
||||
# carrying "eeg") is not real evidence of a relationship. When the
|
||||
# target has no content beyond its prefix (it isn't really a
|
||||
# "prefix_field" name, e.g. "hemoglobina_g_dl"), nothing is dropped.
|
||||
unprefixed_target_words = _words(unprefixed_target)
|
||||
prefix_token = normalized_target.split("_", 1)[0]
|
||||
target_words_full = (
|
||||
[w for w in _words(normalized_target) if w != prefix_token]
|
||||
if unprefixed_target_words
|
||||
else _words(normalized_target)
|
||||
)
|
||||
source_words = _words(normalized_source)
|
||||
words = max(_word_score(source_words, target_words_full), _word_score(source_words, unprefixed_target_words))
|
||||
if words >= _WORD_FLOOR:
|
||||
# 0.5..0.7 by word overlap, plus a tiny whole-string tiebreak so
|
||||
# "fecha_reporte" prefers bx_fecha_reporte over another one-word overlap.
|
||||
ratio = difflib.SequenceMatcher(None, normalized_source, unprefixed_target).ratio()
|
||||
return min(0.5 + (words - _WORD_FLOOR) * 0.36 + ratio * 0.02, _FUZZY_CAP), "fuzzy"
|
||||
return None
|
||||
|
||||
def _score_one(source: str, target: str) -> tuple[float, str] | None:
|
||||
normalized_source, normalized_target = _normalize(source), _normalize(target)
|
||||
if normalized_source == normalized_target:
|
||||
return _NORMALIZED, "normalized"
|
||||
if normalized_source in SYNONYMS.get(target, set()):
|
||||
return _SYNONYM, "synonym"
|
||||
unprefixed_target = _unprefixed(normalized_target)
|
||||
if normalized_source == unprefixed_target:
|
||||
return _UNPREFIXED, "unprefixed"
|
||||
# Words are compared against the full and the unprefixed name, since not every
|
||||
# field has a table prefix (`hemoglobina_g_dl`). The prefix itself is shared by
|
||||
# every column of the table ("eeg_id" ~ "eeg_estudio"), so it is not evidence.
|
||||
unprefixed_target_words = _words(unprefixed_target)
|
||||
prefix_token = normalized_target.split("_", 1)[0]
|
||||
target_words_full = (
|
||||
[w for w in _words(normalized_target) if w != prefix_token]
|
||||
if unprefixed_target_words
|
||||
else _words(normalized_target)
|
||||
)
|
||||
source_words = _words(normalized_source)
|
||||
words = max(_word_score(source_words, target_words_full), _word_score(source_words, unprefixed_target_words))
|
||||
if words >= _WORD_FLOOR:
|
||||
# 0.5..0.7 by word overlap, plus a tiny whole-string tiebreak so
|
||||
# "fecha_reporte" prefers bx_fecha_reporte over another one-word overlap.
|
||||
ratio = fuzz.ratio(normalized_source, unprefixed_target) / 100.0
|
||||
return min(0.5 + (words - _WORD_FLOOR) * 0.36 + ratio * 0.02, _FUZZY_CAP), "fuzzy"
|
||||
return None
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
"""Import schema for `core.cacu.models.BiometriaHematica` (full blood count panel)."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId
|
||||
|
||||
|
||||
class BiometriaHematicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
bh_fecha: Optional[date] = None
|
||||
bh_fecha: FlexDate = None
|
||||
|
||||
eritrocitos_mill_ul: Optional[float] = None
|
||||
hemoglobina_g_dl: Optional[float] = None
|
||||
@@ -35,13 +32,3 @@ class BiometriaHematicaImportSchema(ImportSchema):
|
||||
|
||||
plaquetas_mil_ul: Optional[float] = None
|
||||
vpm_fl: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("bh_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,34 +1,21 @@
|
||||
"""Import schema for `core.cacu.models.BiopsiaCervical`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import GRADO_CIN_ALIAS, GradoCIN
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_GRADO_CIN_CATALOG = Catalog(GradoCIN, GRADO_CIN_ALIAS)
|
||||
|
||||
|
||||
class BiopsiaCervicalImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
cit_id: Optional[int] = None
|
||||
bx_fecha_solicitud: Optional[date] = None
|
||||
bx_fecha_reporte: Optional[date] = None
|
||||
bx_fecha_solicitud: FlexDate = None
|
||||
bx_fecha_reporte: FlexDate = None
|
||||
bx_observaciones: Optional[str] = None
|
||||
bx_cin_grado: CatalogValue(_GRADO_CIN_CATALOG) = None
|
||||
bx_pdf_blob: Optional[bytes] = None
|
||||
bx_ocr_confianza: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("bx_fecha_solicitud", "bx_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -3,25 +3,25 @@
|
||||
`cit_calidad_especimen` stays a plain string: Core's alias dict for it maps to
|
||||
`bool`, not to a canonical string, so it can't back a catalog.
|
||||
"""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import CELULAS_ESCAMOSAS_ALIAS, CelulasEscamosas, ResultadoVPH
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_CELULAS_ESCAMOSAS_CATALOG = Catalog(CelulasEscamosas, CELULAS_ESCAMOSAS_ALIAS)
|
||||
_RESULTADO_VPH_CATALOG = Catalog(ResultadoVPH)
|
||||
|
||||
|
||||
class CitologiaCervicalImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
cit_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
cit_fecha_toma: Optional[date] = None
|
||||
cit_fecha_reporte: Optional[date] = None
|
||||
cit_fecha_toma: FlexDate = None
|
||||
cit_fecha_reporte: FlexDate = None
|
||||
cit_calidad_especimen: Optional[str] = None
|
||||
cit_pdf_blob: Optional[bytes] = None
|
||||
cit_observaciones: Optional[str] = None
|
||||
@@ -36,13 +36,3 @@ class CitologiaCervicalImportSchema(ImportSchema):
|
||||
cit_vph_resultado: CatalogValue(_RESULTADO_VPH_CATALOG) = None
|
||||
cit_vph_genotipo_16: Optional[int] = None
|
||||
cit_vph_genotipo_18: Optional[int] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("cit_fecha_toma", "cit_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Import schema for `core.cacu.models.EpisodioClinico`.
|
||||
|
||||
`nm_id` and `episodio_anterior_id` are true internal surrogate foreign keys
|
||||
with no natural-key sibling column on this table (unlike `pac_id`/
|
||||
`pac_id_hospital` or `ord_id`/`ord_numero_hospital`), so `LinkResolver` has
|
||||
no way to fill them from an external source. They stay out of this schema;
|
||||
per the model's own docstring, linking an episode to the note/order it came
|
||||
from and to its predecessor is the job of the not-yet-built IND-02/IND-03
|
||||
episode-correlation logic, not a plain field-mapping import.
|
||||
"""
|
||||
from typing import Optional
|
||||
|
||||
from core.cacu.enums import ESPECIALIDAD_ALIAS, Especialidad, TIPO_EPISODIO_ALIAS, TipoEpisodio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_TIPO_EPISODIO_CATALOG = Catalog(TipoEpisodio, TIPO_EPISODIO_ALIAS)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
|
||||
|
||||
class EpisodioClinicoImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
tipo_episodio: CatalogValue(_TIPO_EPISODIO_CATALOG) = None
|
||||
cie10_codigo: Optional[str] = None
|
||||
especialidad_medica: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
evento_fecha: FlexDate = None
|
||||
ventana_inicio: FlexDate = None
|
||||
ventana_fin: FlexDate = None
|
||||
@@ -1,12 +1,9 @@
|
||||
"""Import schema for `core.cacu.models.NotaMedica`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import ESPECIALIDAD_ALIAS, Especialidad, TIPO_NOTA_ALIAS, TipoNota
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId, RequiredStr
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
@@ -14,12 +11,12 @@ _TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
nm_id_hospital: str
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
nm_id_hospital: RequiredStr
|
||||
nm_nota_previa_id: Optional[str] = None
|
||||
nm_tipo_nota: CatalogValue(_TIPO_NOTA_CATALOG) = None
|
||||
nm_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
nm_fecha: Optional[date] = None
|
||||
nm_fecha: FlexDate = None
|
||||
nm_medico_tratante: Optional[str] = None
|
||||
nm_motivo_consulta: Optional[str] = None
|
||||
nm_interrogatorio: Optional[str] = None
|
||||
@@ -39,18 +36,3 @@ class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_presion_arterial_sistolica: Optional[int] = None
|
||||
nm_presion_arterial_diastolica: Optional[int] = None
|
||||
nm_temperatura: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("nm_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_nm_id_hospital(cls, v):
|
||||
return required_str(v, field_name="nm_id_hospital")
|
||||
|
||||
@field_validator("nm_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,36 +1,26 @@
|
||||
"""Import schema for `core.cacu.models.OrdenesEstudio` (one order per row, one study type each)."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import TIPO_ESTUDIO_ALIAS, TipoEstudio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
|
||||
|
||||
class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
ord_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: int
|
||||
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None
|
||||
ord_fecha: Optional[date] = None
|
||||
ord_fecha_solicitud: Optional[date] = None
|
||||
ord_fecha_resultado: Optional[date] = None
|
||||
ord_fecha: FlexDate = None
|
||||
ord_fecha_solicitud: FlexDate = None
|
||||
ord_fecha_resultado: FlexDate = None
|
||||
ord_estatus: Optional[str] = None
|
||||
ord_diagnostico: Optional[str] = None
|
||||
ord_observaciones: Optional[str] = None
|
||||
ord_especialidad: Optional[str] = None
|
||||
ord_medico_solicitante: Optional[str] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("ord_fecha", "ord_fecha_solicitud", "ord_fecha_resultado", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"""Import schema for `core.cacu.models.Paciente`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import DEPENDENCIA_ALIAS, Dependencia, PARENTESCO_ALIAS, Parentesco, SEXO_BIOLOGICO_ALIAS, SexoBiologico
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, CodigoPostal, HospitalId, coerce_postal_code, required_date, required_str
|
||||
from webapi.imports.schemas.coercion import (
|
||||
Catalog,
|
||||
CatalogValue,
|
||||
PostalCode,
|
||||
RequiredDate,
|
||||
RequiredHospitalId,
|
||||
)
|
||||
|
||||
# Dependencia/Parentesco: Core marks both catalogs as tentative.
|
||||
_DEPENDENCIA_CATALOG = Catalog(Dependencia, DEPENDENCIA_ALIAS, strict=False)
|
||||
@@ -15,25 +18,13 @@ _SEXO_BIOLOGICO_CATALOG = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
|
||||
|
||||
class PacienteImportSchema(ImportSchema):
|
||||
pac_id_hospital: HospitalId
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
|
||||
# IND-01: required, since age at each event of interest is derived from it.
|
||||
pac_fecha_nacimiento: date
|
||||
pac_codigo_postal: Optional[CodigoPostal] = None
|
||||
pac_fecha_nacimiento: RequiredDate
|
||||
pac_codigo_postal: PostalCode = None
|
||||
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
|
||||
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("pac_fecha_nacimiento", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha_nacimiento(cls, v):
|
||||
return required_date(v, field_name="pac_fecha_nacimiento")
|
||||
|
||||
@field_validator("pac_codigo_postal", mode="before")
|
||||
@classmethod
|
||||
def _coerce_codigo_postal(cls, v):
|
||||
return coerce_postal_code(v)
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
"""Import schema for `core.cama.models.BiometriaHematica` (full blood count panel)."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId
|
||||
|
||||
|
||||
class BiometriaHematicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
bh_fecha: Optional[date] = None
|
||||
bh_fecha: FlexDate = None
|
||||
|
||||
eritrocitos_mill_ul: Optional[float] = None
|
||||
hemoglobina_g_dl: Optional[float] = None
|
||||
@@ -35,13 +32,3 @@ class BiometriaHematicaImportSchema(ImportSchema):
|
||||
|
||||
plaquetas_mil_ul: Optional[float] = None
|
||||
vpm_fl: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("bh_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,34 +1,21 @@
|
||||
"""Import schema for `core.cama.models.BiopsiaMama`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import GradoHistologicoMama
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_GRADO_HISTOLOGICO_MAMA_CATALOG = Catalog(GradoHistologicoMama)
|
||||
|
||||
|
||||
class BiopsiaMamaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_id: Optional[int] = None
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
mast_id: Optional[int] = None
|
||||
bx_fecha_solicitud: Optional[date] = None
|
||||
bx_fecha_reporte: Optional[date] = None
|
||||
bx_fecha_solicitud: FlexDate = None
|
||||
bx_fecha_reporte: FlexDate = None
|
||||
bx_grado_histologico: CatalogValue(_GRADO_HISTOLOGICO_MAMA_CATALOG) = None
|
||||
bx_pdf_blob: Optional[bytes] = None
|
||||
bx_ocr_confianza: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("bx_fecha_solicitud", "bx_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Import schema for `core.cama.models.EpisodioClinico`. Same structure as
|
||||
`webapi.imports.schemas.cacu.episodio_clinico.EpisodioClinicoImportSchema`
|
||||
(see its docstring for why `nm_id`/`episodio_anterior_id` are excluded).
|
||||
"""
|
||||
from typing import Optional
|
||||
|
||||
from core.cama.enums import ESPECIALIDAD_ALIAS, Especialidad, TIPO_EPISODIO_ALIAS, TipoEpisodio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_TIPO_EPISODIO_CATALOG = Catalog(TipoEpisodio, TIPO_EPISODIO_ALIAS)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
|
||||
|
||||
class EpisodioClinicoImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
tipo_episodio: CatalogValue(_TIPO_EPISODIO_CATALOG) = None
|
||||
cie10_codigo: Optional[str] = None
|
||||
especialidad_medica: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
evento_fecha: FlexDate = None
|
||||
ventana_inicio: FlexDate = None
|
||||
ventana_fin: FlexDate = None
|
||||
@@ -1,34 +1,24 @@
|
||||
"""Import schema for `core.cama.models.Mastografia`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import BIRADS, BIRADS_ALIAS
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_BIRADS_CATALOG = Catalog(BIRADS, BIRADS_ALIAS)
|
||||
|
||||
|
||||
class MastografiaImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
mast_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_id: Optional[int] = None
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
mast_fecha_toma: Optional[date] = None
|
||||
mast_fecha_reporte: Optional[date] = None
|
||||
mast_fecha_toma: FlexDate = None
|
||||
mast_fecha_reporte: FlexDate = None
|
||||
mast_calidad_imagen: Optional[str] = None
|
||||
mast_birads: CatalogValue(_BIRADS_CATALOG) = None
|
||||
mast_dicom_blob: Optional[bytes] = None
|
||||
mast_interpretacion: Optional[str] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("mast_fecha_toma", "mast_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
"""Import schema for `core.cama.models.NotaMedica`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import ESPECIALIDAD_ALIAS, Especialidad, TIPO_NOTA_ALIAS, TipoNota
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId, RequiredStr
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
@@ -14,12 +11,12 @@ _TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
nm_id_hospital: str
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
nm_id_hospital: RequiredStr
|
||||
nm_nota_previa_id: Optional[str] = None
|
||||
nm_tipo_nota: CatalogValue(_TIPO_NOTA_CATALOG) = None
|
||||
nm_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
nm_fecha: Optional[date] = None
|
||||
nm_fecha: FlexDate = None
|
||||
nm_medico_tratante: Optional[str] = None
|
||||
nm_motivo_consulta: Optional[str] = None
|
||||
nm_interrogatorio: Optional[str] = None
|
||||
@@ -39,18 +36,3 @@ class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_presion_arterial_sistolica: Optional[int] = None
|
||||
nm_presion_arterial_diastolica: Optional[int] = None
|
||||
nm_temperatura: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("nm_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_nm_id_hospital(cls, v):
|
||||
return required_str(v, field_name="nm_id_hospital")
|
||||
|
||||
@field_validator("nm_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,36 +1,26 @@
|
||||
"""Import schema for `core.cama.models.OrdenesEstudio` (one order per row, one study type each)."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import TIPO_ESTUDIO_ALIAS, TipoEstudio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
|
||||
|
||||
class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
ord_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: int
|
||||
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None
|
||||
ord_fecha: Optional[date] = None
|
||||
ord_fecha_solicitud: Optional[date] = None
|
||||
ord_fecha_resultado: Optional[date] = None
|
||||
ord_fecha: FlexDate = None
|
||||
ord_fecha_solicitud: FlexDate = None
|
||||
ord_fecha_resultado: FlexDate = None
|
||||
ord_estatus: Optional[str] = None
|
||||
ord_diagnostico: Optional[str] = None
|
||||
ord_observaciones: Optional[str] = None
|
||||
ord_especialidad: Optional[str] = None
|
||||
ord_medico_solicitante: Optional[str] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("ord_fecha", "ord_fecha_solicitud", "ord_fecha_resultado", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"""Import schema for `core.cama.models.Paciente`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import DEPENDENCIA_ALIAS, Dependencia, PARENTESCO_ALIAS, Parentesco, SEXO_BIOLOGICO_ALIAS, SexoBiologico
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, CodigoPostal, HospitalId, coerce_postal_code, required_date, required_str
|
||||
from webapi.imports.schemas.coercion import (
|
||||
Catalog,
|
||||
CatalogValue,
|
||||
PostalCode,
|
||||
RequiredDate,
|
||||
RequiredHospitalId,
|
||||
)
|
||||
|
||||
# Dependencia/Parentesco: Core marks both catalogs as tentative.
|
||||
_DEPENDENCIA_CATALOG = Catalog(Dependencia, DEPENDENCIA_ALIAS, strict=False)
|
||||
@@ -15,25 +18,13 @@ _SEXO_BIOLOGICO_CATALOG = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
|
||||
|
||||
class PacienteImportSchema(ImportSchema):
|
||||
pac_id_hospital: HospitalId
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
|
||||
# IND-01: required, since age at each event of interest is derived from it.
|
||||
pac_fecha_nacimiento: date
|
||||
pac_codigo_postal: Optional[CodigoPostal] = None
|
||||
pac_fecha_nacimiento: RequiredDate
|
||||
pac_codigo_postal: PostalCode = None
|
||||
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
|
||||
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("pac_codigo_postal", mode="before")
|
||||
@classmethod
|
||||
def _coerce_codigo_postal(cls, v):
|
||||
return coerce_postal_code(v)
|
||||
|
||||
@field_validator("pac_fecha_nacimiento", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha_nacimiento(cls, v):
|
||||
return required_date(v, field_name="pac_fecha_nacimiento")
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Matching OCR-discovered captions against a project's catalog, and
|
||||
minting new catalog entries when nothing matches well enough.
|
||||
|
||||
`discover_captions` (Extraction) finds `caption: value` lines no known
|
||||
`FieldSpec` already explains. For each one, this module decides whether an
|
||||
existing `resultado_id` means the same thing closely enough to reuse
|
||||
(`rapidfuzz`, tolerant of how a hospital's own report wording differs from
|
||||
the catalog's own), or whether it's a field the catalog doesn't have yet —
|
||||
in which case it's added (`add_resultado`), never silently dropped.
|
||||
"""
|
||||
import re
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
|
||||
from rapidfuzz import fuzz, process
|
||||
|
||||
from extraction.nlp import DiscoveredField
|
||||
from extraction.nlp.text import find_date, fold
|
||||
from indicadores_kit.plata.procedimiento import valor_de_observacion
|
||||
from indicadores_kit.registry.catalogos import Catalogo, add_resultado
|
||||
|
||||
# `token_sort_ratio`, not `WRatio`: `WRatio`'s partial-alignment bonus scores
|
||||
# two short, unrelated captions that merely share common words ("de", "del")
|
||||
# too high for this use (two genuinely different captions can clear 80).
|
||||
# Lower than `extraction.nlp.extractors.FUZZY_LABEL_THRESHOLD` (0-100 scale
|
||||
# here, that one 0-1): a caption is free text, not a single known label
|
||||
# tolerating only OCR noise, so it varies more from the catalog's wording.
|
||||
CAPTION_MATCH_THRESHOLD = 80.0
|
||||
CAPTION_SCORER = fuzz.token_sort_ratio
|
||||
FALLBACK_ESTUDIO_ID = "documento_externo"
|
||||
FALLBACK_ESTUDIO_ETIQUETA = "Documento externo"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MatchedField:
|
||||
"""One discovered caption, resolved to a `resultado_id` (existing or
|
||||
just minted) with its value already shaped for `observacion`."""
|
||||
|
||||
resultado_id: str
|
||||
is_new: bool
|
||||
observacion: dict
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _NewResultado:
|
||||
resultado_id: str
|
||||
tipo_valor: str
|
||||
|
||||
|
||||
def match_or_mint(
|
||||
discovered: list[DiscoveredField], *, proyecto: str, catalogo: Catalogo, estudio_id: str | None = None
|
||||
) -> list[MatchedField]:
|
||||
"""One `MatchedField` per discovered caption, in order.
|
||||
|
||||
`estudio_id`, when the caller already knows it (the row's own
|
||||
study-type column, resolved through `codigos_hospital`), scopes which
|
||||
resultados are tried first and which estudio a minted field joins;
|
||||
without it, every resultado in the catalog is a candidate and a new
|
||||
field's estudio is guessed the same way, or falls back to
|
||||
`documento_externo`.
|
||||
"""
|
||||
labels = _resultado_labels(catalogo, estudio_id)
|
||||
valid_codes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"}
|
||||
by_resultado_id = {r.resultado_id: r for r in catalogo.resultados}
|
||||
resolved = []
|
||||
for field in discovered:
|
||||
found = _best_match(field.caption, labels)
|
||||
if found is not None:
|
||||
resultado, is_new = by_resultado_id[found], False
|
||||
else:
|
||||
resultado = _mint(field, proyecto=proyecto, estudio_id=estudio_id, catalogo=catalogo)
|
||||
is_new = True
|
||||
value = _coerce_value(field.value, resultado.tipo_valor)
|
||||
observacion = valor_de_observacion(
|
||||
value,
|
||||
field.value,
|
||||
tipo_valor=resultado.tipo_valor,
|
||||
en_catalogo=lambda v, r=resultado.resultado_id: (r, v) in valid_codes,
|
||||
)
|
||||
resolved.append(MatchedField(resultado.resultado_id, is_new, observacion))
|
||||
return resolved
|
||||
|
||||
|
||||
def _resultado_labels(catalogo: Catalogo, estudio_id: str | None) -> dict[str, str]:
|
||||
resultados = catalogo.resultados
|
||||
if estudio_id is not None:
|
||||
of_estudio = [r for r in resultados if r.estudio_id == estudio_id]
|
||||
if of_estudio:
|
||||
resultados = of_estudio
|
||||
return {r.resultado_id: fold(r.etiqueta) for r in resultados}
|
||||
|
||||
|
||||
def _best_match(caption: str, labels: dict[str, str]) -> str | None:
|
||||
if not labels:
|
||||
return None
|
||||
found = process.extractOne(fold(caption), labels, scorer=CAPTION_SCORER, score_cutoff=CAPTION_MATCH_THRESHOLD)
|
||||
return found[2] if found is not None else None
|
||||
|
||||
|
||||
def _mint(field: DiscoveredField, *, proyecto: str, estudio_id: str | None, catalogo: Catalogo) -> _NewResultado:
|
||||
estudio = estudio_id
|
||||
estudio_etiqueta = None
|
||||
if estudio is None:
|
||||
estudio_labels = {e.estudio_id: fold(e.etiqueta) for e in catalogo.estudios}
|
||||
found = process.extractOne(fold(field.caption), estudio_labels, scorer=CAPTION_SCORER, score_cutoff=CAPTION_MATCH_THRESHOLD)
|
||||
estudio = found[2] if found is not None else None
|
||||
if estudio is None:
|
||||
estudio, estudio_etiqueta = FALLBACK_ESTUDIO_ID, FALLBACK_ESTUDIO_ETIQUETA
|
||||
tipo_valor = _infer_tipo_valor(field.value)
|
||||
resultado_id = add_resultado(
|
||||
proyecto,
|
||||
estudio_id=estudio,
|
||||
nombre=_slug(field.caption),
|
||||
etiqueta=field.caption.strip(),
|
||||
tipo_valor=tipo_valor,
|
||||
estudio_etiqueta=estudio_etiqueta,
|
||||
)
|
||||
return _NewResultado(resultado_id, tipo_valor)
|
||||
|
||||
|
||||
def _slug(text: str) -> str:
|
||||
without_accents = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("ascii")
|
||||
return re.sub(r"[^a-z0-9]+", "_", without_accents.lower()).strip("_") or "campo"
|
||||
|
||||
|
||||
def _infer_tipo_valor(value: str) -> str:
|
||||
if find_date(value) is not None:
|
||||
return "fecha"
|
||||
if _is_number(value):
|
||||
return "numero"
|
||||
return "texto"
|
||||
|
||||
|
||||
def _is_number(value: str) -> bool:
|
||||
try:
|
||||
float(value.strip().replace(",", "."))
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def _coerce_value(value: str, tipo_valor: str):
|
||||
if tipo_valor == "fecha":
|
||||
found = find_date(value)
|
||||
return found[0] if found else None
|
||||
if tipo_valor in ("numero", "booleano"):
|
||||
try:
|
||||
return float(value.strip().replace(",", "."))
|
||||
except ValueError:
|
||||
return None
|
||||
return value
|
||||
@@ -7,7 +7,7 @@ from datetime import date, datetime
|
||||
from enum import Enum
|
||||
from typing import Annotated, Any, Optional, Type
|
||||
|
||||
from pydantic import BeforeValidator, StringConstraints
|
||||
from pydantic import BeforeValidator, StringConstraints, ValidationInfo
|
||||
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
from extraction import ExtractionError
|
||||
@@ -18,9 +18,9 @@ from extraction.signals import EegRecording
|
||||
HospitalId = Annotated[str, StringConstraints(max_length=HOSPITAL_ID_LENGTH)]
|
||||
|
||||
|
||||
def required_str(v: Any, *, field_name: str) -> str:
|
||||
def required_str(v: Any, info: ValidationInfo) -> str:
|
||||
if v is None or str(v).strip() == "":
|
||||
raise ValueError(f"{field_name} es requerido")
|
||||
raise ValueError(f"{info.field_name} es requerido")
|
||||
return str(v).strip()
|
||||
|
||||
|
||||
@@ -31,21 +31,13 @@ def optional_str(v: Any) -> Any:
|
||||
return text or None
|
||||
|
||||
|
||||
def rounded_int(v: Any) -> Any:
|
||||
"""A minutes/count field stored as an `int` column, whose source may
|
||||
report a float (e.g. a duration measured to tenths of a minute)."""
|
||||
if v is None or (isinstance(v, str) and v.strip() == ""):
|
||||
return None
|
||||
return round(float(v))
|
||||
|
||||
|
||||
_DAY_FIRST_FORMATS = ("%d/%m/%Y", "%d-%m-%Y", "%d.%m.%Y", "%Y/%m/%d")
|
||||
|
||||
|
||||
def required_date(v: Any, *, field_name: str) -> Any:
|
||||
def required_date(v: Any, info: ValidationInfo) -> Any:
|
||||
coerced = coerce_date(v)
|
||||
if coerced is None:
|
||||
raise ValueError(f"{field_name} es requerido")
|
||||
raise ValueError(f"{info.field_name} es requerido")
|
||||
return coerced
|
||||
|
||||
|
||||
@@ -75,16 +67,6 @@ def coerce_date(v: Any) -> Any:
|
||||
return v
|
||||
|
||||
|
||||
def coerce_datetime(v: Any) -> Any:
|
||||
if v is None or (isinstance(v, str) and not v.strip()):
|
||||
return None
|
||||
if isinstance(v, datetime):
|
||||
return v
|
||||
if isinstance(v, str):
|
||||
return datetime.fromisoformat(v.strip())
|
||||
return v
|
||||
|
||||
|
||||
class Catalog:
|
||||
"""A closed set of valid values for one field: an `Enum`'s values plus any
|
||||
aliases for them, matched case-insensitively. Built from the Enum because
|
||||
@@ -140,10 +122,6 @@ def CatalogValue(catalog: Catalog): # noqa: N802 (used in annotations, like a t
|
||||
return Annotated[Optional[str], BeforeValidator(catalog.coerce), catalog]
|
||||
|
||||
|
||||
def coerce_alias(v: Any, catalog: Catalog) -> Any:
|
||||
return catalog.coerce(v)
|
||||
|
||||
|
||||
def coerce_postal_code(v: Any) -> Any:
|
||||
"""Mexican postal codes are 5 digits. A numeric source (Excel cell, SQL
|
||||
INT column) has already dropped the leading zero, so restore it."""
|
||||
@@ -178,3 +156,15 @@ def edf_file(v: Any) -> Any:
|
||||
except ExtractionError as exc:
|
||||
raise ValueError(f"no es un archivo EDF válido: {exc}") from exc
|
||||
return bytes(v)
|
||||
|
||||
|
||||
# Field types. Blank cells become None; required ones say which field is missing.
|
||||
OptionalStr = Annotated[Optional[str], BeforeValidator(optional_str)]
|
||||
# A TEA record's own id as the source sends it (its primary key is String(36)).
|
||||
SourceId = Annotated[Optional[Annotated[str, StringConstraints(max_length=36)]], BeforeValidator(optional_str)]
|
||||
RequiredStr = Annotated[str, BeforeValidator(required_str)]
|
||||
RequiredHospitalId = Annotated[HospitalId, BeforeValidator(required_str)]
|
||||
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)]
|
||||
|
||||
@@ -6,45 +6,24 @@ Keys are `"<domain>.<ModelName>"`, since some names (`NotaMedica`) repeat
|
||||
across domains.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from typing import Sequence, Type
|
||||
from typing import Sequence
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from core.cacu.models import BiometriaHematica as CacuBiometriaHematica
|
||||
from core.cacu.models import BiopsiaCervical as CacuBiopsiaCervical
|
||||
from core.cacu.models import CitologiaCervical as CacuCitologiaCervical
|
||||
from core.cacu.models import NotaMedica as CacuNotaMedica
|
||||
from core.cacu.models import OrdenesEstudio as CacuOrdenesEstudio
|
||||
from core.cacu.models import Paciente as CacuPaciente
|
||||
from core.cama.models import BiometriaHematica as CamaBiometriaHematica
|
||||
from core.cama.models import BiopsiaMama as CamaBiopsiaMama
|
||||
from core.cama.models import Mastografia as CamaMastografia
|
||||
from core.cama.models import NotaMedica as CamaNotaMedica
|
||||
from core.cama.models import OrdenesEstudio as CamaOrdenesEstudio
|
||||
from core.cama.models import Paciente as CamaPaciente
|
||||
from core.tea.models import AntecedentesMaternosGestacion as TeaAntecedentesMaternosGestacion
|
||||
from core.tea.models import EegEstudio as TeaEegEstudio
|
||||
from core.tea.models import EegSegmento as TeaEegSegmento
|
||||
from core.tea.models import EvaluacionPsicologica as TeaEvaluacionPsicologica
|
||||
from core.tea.models import InstrumentoAplicado as TeaInstrumentoAplicado
|
||||
from core.tea.models import NotaMedica as TeaNotaMedica
|
||||
from core.tea.models import OrdenesEstudio as TeaOrdenesEstudio
|
||||
from core.tea.models import Pacientes as TeaPacientes
|
||||
from core.tea.models import PartoNeonatal as TeaPartoNeonatal
|
||||
from core.tea.models import PotencialesEvocadosAuditivos as TeaPotencialesEvocadosAuditivos
|
||||
from persistance.cacu import biometria_hematica_repository as cacu_biometria_hematica_repository
|
||||
from persistance.cacu import biopsia_cervical_repository as cacu_biopsia_cervical_repository
|
||||
from persistance.cacu import citologia_cervical_repository as cacu_citologia_cervical_repository
|
||||
from persistance.cacu import episodio_clinico_repository as cacu_episodio_clinico_repository
|
||||
from persistance.cacu import nota_medica_repository as cacu_nota_medica_repository
|
||||
from persistance.cacu import ordenes_estudio_repository as cacu_ordenes_estudio_repository
|
||||
from persistance.cacu import paciente_repository as cacu_paciente_repository
|
||||
from persistance.cama import biometria_hematica_repository as cama_biometria_hematica_repository
|
||||
from persistance.cama import biopsia_mama_repository as cama_biopsia_mama_repository
|
||||
from persistance.cama import episodio_clinico_repository as cama_episodio_clinico_repository
|
||||
from persistance.cama import mastografia_repository as cama_mastografia_repository
|
||||
from persistance.cama import nota_medica_repository as cama_nota_medica_repository
|
||||
from persistance.cama import ordenes_estudio_repository as cama_ordenes_estudio_repository
|
||||
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
|
||||
@@ -62,6 +41,9 @@ from webapi.imports.schemas.cacu.biometria_hematica import (
|
||||
)
|
||||
from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.citologia_cervical import CitologiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.episodio_clinico import (
|
||||
EpisodioClinicoImportSchema as CacuEpisodioClinicoImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cacu.nota_medica import NotaMedicaImportSchema as CacuNotaMedicaImportSchema
|
||||
from webapi.imports.schemas.cacu.ordenes_estudio import (
|
||||
OrdenesEstudioImportSchema as CacuOrdenesEstudioImportSchema,
|
||||
@@ -71,6 +53,9 @@ from webapi.imports.schemas.cama.biometria_hematica import (
|
||||
BiometriaHematicaImportSchema as CamaBiometriaHematicaImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cama.biopsia_mama import BiopsiaMamaImportSchema
|
||||
from webapi.imports.schemas.cama.episodio_clinico import (
|
||||
EpisodioClinicoImportSchema as CamaEpisodioClinicoImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cama.mastografia import MastografiaImportSchema
|
||||
from webapi.imports.schemas.cama.nota_medica import NotaMedicaImportSchema as CamaNotaMedicaImportSchema
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import (
|
||||
@@ -97,119 +82,116 @@ from webapi.imports.schemas.tea.potenciales_evocados_auditivos import (
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EntitySpec:
|
||||
schema: Type[BaseModel]
|
||||
model: type
|
||||
schema: type[ImportSchema]
|
||||
repository: Repository
|
||||
conflict_fields: Sequence[str] | None
|
||||
|
||||
@property
|
||||
def model(self) -> type:
|
||||
return self.repository.model
|
||||
|
||||
|
||||
ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
"cacu.Paciente": EntitySpec(
|
||||
schema=CacuPacienteImportSchema,
|
||||
model=CacuPaciente,
|
||||
repository=cacu_paciente_repository,
|
||||
conflict_fields=("pac_id_hospital",),
|
||||
),
|
||||
"tea.Pacientes": EntitySpec(
|
||||
schema=PacientesImportSchema,
|
||||
model=TeaPacientes,
|
||||
repository=tea_pacientes_repository,
|
||||
# The source's own id; TEA's child tables reference it directly.
|
||||
conflict_fields=("pac_id",),
|
||||
),
|
||||
"cacu.OrdenesEstudio": EntitySpec(
|
||||
schema=CacuOrdenesEstudioImportSchema,
|
||||
model=CacuOrdenesEstudio,
|
||||
repository=cacu_ordenes_estudio_repository,
|
||||
conflict_fields=("ord_numero_hospital",),
|
||||
),
|
||||
"cacu.CitologiaCervical": EntitySpec(
|
||||
schema=CitologiaCervicalImportSchema,
|
||||
model=CacuCitologiaCervical,
|
||||
repository=cacu_citologia_cervical_repository,
|
||||
conflict_fields=("pac_id_hospital", "ord_numero_hospital"),
|
||||
),
|
||||
"cacu.BiopsiaCervical": EntitySpec(
|
||||
schema=BiopsiaCervicalImportSchema,
|
||||
model=CacuBiopsiaCervical,
|
||||
repository=cacu_biopsia_cervical_repository,
|
||||
conflict_fields=("pac_id_hospital", "ord_numero_hospital"),
|
||||
),
|
||||
"cacu.NotaMedica": EntitySpec(
|
||||
schema=CacuNotaMedicaImportSchema,
|
||||
model=CacuNotaMedica,
|
||||
repository=cacu_nota_medica_repository,
|
||||
conflict_fields=("pac_id_hospital", "nm_id_hospital"),
|
||||
),
|
||||
"cacu.BiometriaHematica": EntitySpec(
|
||||
schema=CacuBiometriaHematicaImportSchema,
|
||||
model=CacuBiometriaHematica,
|
||||
repository=cacu_biometria_hematica_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"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.
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cama.Paciente": EntitySpec(
|
||||
schema=CamaPacienteImportSchema,
|
||||
model=CamaPaciente,
|
||||
repository=cama_paciente_repository,
|
||||
conflict_fields=("pac_id_hospital",),
|
||||
),
|
||||
"cama.OrdenesEstudio": EntitySpec(
|
||||
schema=CamaOrdenesEstudioImportSchema,
|
||||
model=CamaOrdenesEstudio,
|
||||
repository=cama_ordenes_estudio_repository,
|
||||
conflict_fields=("ord_numero_hospital",),
|
||||
),
|
||||
"cama.Mastografia": EntitySpec(
|
||||
schema=MastografiaImportSchema,
|
||||
model=CamaMastografia,
|
||||
repository=cama_mastografia_repository,
|
||||
conflict_fields=("pac_id_hospital", "ord_numero_hospital"),
|
||||
),
|
||||
"cama.BiopsiaMama": EntitySpec(
|
||||
schema=BiopsiaMamaImportSchema,
|
||||
model=CamaBiopsiaMama,
|
||||
repository=cama_biopsia_mama_repository,
|
||||
conflict_fields=("pac_id_hospital", "ord_numero_hospital"),
|
||||
),
|
||||
"cama.NotaMedica": EntitySpec(
|
||||
schema=CamaNotaMedicaImportSchema,
|
||||
model=CamaNotaMedica,
|
||||
repository=cama_nota_medica_repository,
|
||||
conflict_fields=("pac_id_hospital", "nm_id_hospital"),
|
||||
),
|
||||
"cama.BiometriaHematica": EntitySpec(
|
||||
schema=CamaBiometriaHematicaImportSchema,
|
||||
model=CamaBiometriaHematica,
|
||||
repository=cama_biometria_hematica_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cama.EpisodioClinico": EntitySpec(
|
||||
schema=CamaEpisodioClinicoImportSchema,
|
||||
repository=cama_episodio_clinico_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.OrdenesEstudio": EntitySpec(
|
||||
schema=TeaOrdenesEstudioImportSchema,
|
||||
model=TeaOrdenesEstudio,
|
||||
repository=tea_ordenes_estudio_repository,
|
||||
conflict_fields=("ord_id_hospital",),
|
||||
),
|
||||
"tea.NotaMedica": EntitySpec(
|
||||
schema=TeaNotaMedicaImportSchema,
|
||||
model=TeaNotaMedica,
|
||||
repository=tea_nota_medica_repository,
|
||||
conflict_fields=("nm_id_hospital",),
|
||||
),
|
||||
"tea.EvaluacionPsicologica": EntitySpec(
|
||||
schema=EvaluacionPsicologicaImportSchema,
|
||||
model=TeaEvaluacionPsicologica,
|
||||
repository=tea_evaluacion_psicologica_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.PotencialesEvocadosAuditivos": EntitySpec(
|
||||
schema=PotencialesEvocadosAuditivosImportSchema,
|
||||
model=TeaPotencialesEvocadosAuditivos,
|
||||
repository=tea_potenciales_evocados_auditivos_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.EegEstudio": EntitySpec(
|
||||
schema=EegEstudioImportSchema,
|
||||
model=TeaEegEstudio,
|
||||
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
|
||||
@@ -219,25 +201,21 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
),
|
||||
"tea.EegSegmento": EntitySpec(
|
||||
schema=EegSegmentoImportSchema,
|
||||
model=TeaEegSegmento,
|
||||
repository=tea_eeg_segmento_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.InstrumentoAplicado": EntitySpec(
|
||||
schema=InstrumentoAplicadoImportSchema,
|
||||
model=TeaInstrumentoAplicado,
|
||||
repository=tea_instrumento_aplicado_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.AntecedentesMaternosGestacion": EntitySpec(
|
||||
schema=AntecedentesMaternosGestacionImportSchema,
|
||||
model=TeaAntecedentesMaternosGestacion,
|
||||
repository=tea_antecedentes_maternos_gestacion_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.PartoNeonatal": EntitySpec(
|
||||
schema=PartoNeonatalImportSchema,
|
||||
model=TeaPartoNeonatal,
|
||||
repository=tea_parto_neonatal_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
optional, like TEA's Core; system-managed `amg_created_at`/`amg_updated_at`/`amg_fuente_sistema` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import (
|
||||
CategoriaPesoMaterno,
|
||||
FuenteAntecedenteMaterno,
|
||||
@@ -12,7 +10,7 @@ from core.tea.enums import (
|
||||
VolumenLiquidoAmniotico,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr
|
||||
|
||||
_FUENTE_ANTECEDENTE_MATERNO_CATALOG = Catalog(FuenteAntecedenteMaterno)
|
||||
_CATEGORIA_PESO_MATERNO_CATALOG = Catalog(CategoriaPesoMaterno)
|
||||
@@ -23,7 +21,7 @@ _VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG = Catalog(VolumenLiquidoAmniotico)
|
||||
|
||||
class AntecedentesMaternosGestacionImportSchema(ImportSchema):
|
||||
amg_pac_id: Optional[int] = None
|
||||
amg_id_madre_seudonimo: Optional[str] = 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
|
||||
@@ -34,7 +32,7 @@ class AntecedentesMaternosGestacionImportSchema(ImportSchema):
|
||||
amg_antecedente_aborto: Optional[int] = None
|
||||
amg_embarazo_multiple: CatalogValue(_TIPO_EMBARAZO_CATALOG) = None
|
||||
amg_infeccion_gestacion: Optional[int] = None
|
||||
amg_infeccion_tipo: Optional[str] = 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
|
||||
@@ -50,17 +48,8 @@ class AntecedentesMaternosGestacionImportSchema(ImportSchema):
|
||||
amg_estres_agudo: Optional[int] = None
|
||||
amg_trastorno_neurologico: Optional[int] = None
|
||||
amg_liquido_amniotico: CatalogValue(_VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG) = None
|
||||
amg_medicamentos_gestacion: Optional[str] = None
|
||||
amg_medicamentos_gestacion: OptionalStr = None
|
||||
amg_farmaco_riesgo_neurodesarrollo: Optional[int] = None
|
||||
amg_observaciones: Optional[str] = None
|
||||
amg_observaciones: OptionalStr = None
|
||||
amg_ocr_confianza: Optional[float] = None
|
||||
amg_nlp_version: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"amg_id_madre_seudonimo", "amg_infeccion_tipo",
|
||||
"amg_medicamentos_gestacion", "amg_observaciones", "amg_nlp_version",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
amg_nlp_version: OptionalStr = None
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
"""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 datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import (
|
||||
CalidadTecnicaEeg,
|
||||
ConclusionEeg,
|
||||
@@ -17,7 +14,7 @@ from core.tea.enums import (
|
||||
TipoGrafoelemento,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import edf_file, Catalog, CatalogValue, coerce_date, optional_str, rounded_int
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, EdfFile, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_FUENTE_INTERPRETACION_EEG_CATALOG = Catalog(FuenteInterpretacionEeg)
|
||||
_ESTADO_REGISTRO_EEG_CATALOG = Catalog(EstadoRegistroEeg)
|
||||
@@ -31,23 +28,25 @@ _CONCLUSION_EEG_CATALOG = Catalog(ConclusionEeg)
|
||||
|
||||
|
||||
class EegEstudioImportSchema(ImportSchema):
|
||||
eeg_ord_id: Optional[str] = None
|
||||
eeg_pac_id: Optional[str] = None
|
||||
# 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: Optional[date] = None
|
||||
eeg_fecha_nacimiento_archivo: FlexDate = None
|
||||
eeg_edad_meses: Optional[float] = None
|
||||
eeg_fecha_estudio: Optional[date] = None
|
||||
eeg_fecha_reporte: Optional[date] = None
|
||||
eeg_fecha_estudio: FlexDate = None
|
||||
eeg_fecha_reporte: FlexDate = None
|
||||
eeg_dias_respuesta: Optional[int] = None
|
||||
eeg_medico_interpreta: Optional[str] = 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: Optional[str] = None
|
||||
eeg_duracion_min: 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: Optional[str] = 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
|
||||
@@ -55,41 +54,16 @@ class EegEstudioImportSchema(ImportSchema):
|
||||
eeg_actividad_epileptiforme: Optional[int] = None
|
||||
eeg_tipo_grafoelemento: CatalogValue(_TIPO_GRAFOELEMENTO_CATALOG) = None
|
||||
eeg_distribucion_anormalidad: CatalogValue(_DISTRIBUCION_ANORMALIDAD_CATALOG) = None
|
||||
eeg_localizacion: Optional[str] = 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: Optional[str] = None
|
||||
eeg_conclusion_texto: OptionalStr = None
|
||||
eeg_conclusion_categoria: CatalogValue(_CONCLUSION_EEG_CATALOG) = None
|
||||
eeg_id_registro_laboratorio: Optional[str] = None
|
||||
eeg_pdf_ruta: Optional[str] = None
|
||||
eeg_id_registro_laboratorio: OptionalStr = None
|
||||
eeg_pdf_ruta: OptionalStr = None
|
||||
eeg_ocr_confianza: Optional[float] = None
|
||||
eeg_nlp_version: Optional[str] = None
|
||||
eeg_nlp_version: OptionalStr = None
|
||||
eeg_utilizable: Optional[int] = None
|
||||
eeg_estudio: Optional[bytes] = None
|
||||
|
||||
@field_validator(
|
||||
"eeg_ord_id", "eeg_pac_id", "eeg_medico_interpreta", "eeg_sedacion_farmaco",
|
||||
"eeg_descripcion_senal", "eeg_localizacion", "eeg_conclusion_texto",
|
||||
"eeg_id_registro_laboratorio", "eeg_pdf_ruta", "eeg_nlp_version",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("eeg_fecha_nacimiento_archivo", "eeg_fecha_estudio", "eeg_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@field_validator("eeg_duracion_min", mode="before")
|
||||
@classmethod
|
||||
def _coerce_duracion_min(cls, v):
|
||||
return rounded_int(v)
|
||||
|
||||
@field_validator("eeg_estudio", mode="before")
|
||||
@classmethod
|
||||
def _valid_edf(cls, v):
|
||||
return edf_file(v)
|
||||
eeg_estudio: EdfFile = None
|
||||
|
||||
@@ -2,27 +2,20 @@
|
||||
TEA's Core."""
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import optional_str
|
||||
from webapi.imports.schemas.coercion import OptionalStr
|
||||
|
||||
|
||||
class EegSegmentoImportSchema(ImportSchema):
|
||||
seg_eeg_id: Optional[str] = None
|
||||
seg_estado: Optional[str] = None
|
||||
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: Optional[str] = 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
|
||||
|
||||
@field_validator("seg_eeg_id", "seg_estado", "seg_fuente", mode="before")
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
"""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 datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import (
|
||||
ClasificacionAdos2,
|
||||
InstrumentoTamizaje,
|
||||
@@ -13,7 +10,7 @@ from core.tea.enums import (
|
||||
VentanaMadurativa,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
_INSTRUMENTO_TAMIZAJE_CATALOG = Catalog(InstrumentoTamizaje)
|
||||
@@ -23,12 +20,14 @@ _CLASIFICACION_ADOS2_CATALOG = Catalog(ClasificacionAdos2)
|
||||
|
||||
|
||||
class EvaluacionPsicologicaImportSchema(ImportSchema):
|
||||
psi_ord_id: Optional[str] = None
|
||||
# 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: Optional[date] = None
|
||||
psi_fecha_ados2: Optional[date] = None
|
||||
psi_fecha_evaluacion: Optional[date] = None
|
||||
psi_psicologo: Optional[str] = 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
|
||||
@@ -80,22 +79,8 @@ class EvaluacionPsicologicaImportSchema(ImportSchema):
|
||||
psi_css_umbral_aplicado: Optional[int] = None
|
||||
psi_caso_confirmado: Optional[int] = None
|
||||
psi_cars_total: Optional[float] = None
|
||||
psi_otros_instrumentos: Optional[str] = None
|
||||
psi_otros_instrumentos: OptionalStr = None
|
||||
psi_regresion_desarrollo: Optional[int] = None
|
||||
psi_diagnostico_texto: Optional[str] = None
|
||||
psi_diagnostico_texto: OptionalStr = None
|
||||
psi_ocr_confianza: Optional[float] = None
|
||||
psi_nlp_version: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"psi_ord_id", "psi_psicologo", "psi_otros_instrumentos",
|
||||
"psi_diagnostico_texto", "psi_nlp_version",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("psi_fecha_entrevista_inicial", "psi_fecha_ados2", "psi_fecha_evaluacion", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
psi_nlp_version: OptionalStr = None
|
||||
|
||||
@@ -1,24 +1,13 @@
|
||||
"""Import schema for `core.tea.models.InstrumentoAplicado`. All fields
|
||||
optional, like TEA's Core."""
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import optional_str
|
||||
from webapi.imports.schemas.coercion import OptionalStr
|
||||
|
||||
|
||||
class InstrumentoAplicadoImportSchema(ImportSchema):
|
||||
ins_psi_id: Optional[str] = None
|
||||
ins_instrumento: Optional[str] = None
|
||||
ins_informante: Optional[str] = None
|
||||
ins_area: Optional[str] = None
|
||||
ins_interpretacion: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"ins_psi_id", "ins_instrumento", "ins_informante", "ins_area", "ins_interpretacion",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
ins_psi_id: OptionalStr = None
|
||||
ins_instrumento: OptionalStr = None
|
||||
ins_informante: OptionalStr = None
|
||||
ins_area: OptionalStr = None
|
||||
ins_interpretacion: OptionalStr = None
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
"""Import schema for `core.tea.models.NotaMedica`. All fields optional, like TEA's
|
||||
Core; system-managed `nm_created_at`/`nm_updated_at`/`nm_fuente_sistema` are excluded."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import Especialidad, Pronostico, TipoNota, VentanaMadurativa
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad)
|
||||
@@ -17,27 +14,27 @@ _PRONOSTICO_CATALOG = Catalog(Pronostico)
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_pac_id: Optional[int] = None
|
||||
nm_id_hospital: Optional[str] = None
|
||||
nm_nota_previa_id: Optional[str] = None
|
||||
nm_id_hospital: OptionalStr = None
|
||||
nm_nota_previa_id: OptionalStr = None
|
||||
nm_tipo_nota: CatalogValue(_TIPO_NOTA_CATALOG) = None
|
||||
nm_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
nm_fecha: Optional[date] = None
|
||||
nm_fecha: FlexDate = None
|
||||
nm_edad_meses: Optional[float] = None
|
||||
nm_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
nm_medico_tratante: Optional[str] = None
|
||||
nm_motivo_consulta: Optional[str] = None
|
||||
nm_interrogatorio: Optional[str] = None
|
||||
nm_medico_tratante: OptionalStr = None
|
||||
nm_motivo_consulta: OptionalStr = None
|
||||
nm_interrogatorio: OptionalStr = None
|
||||
nm_regresion_referida: Optional[int] = None
|
||||
nm_antecedente_familiar_tea: Optional[int] = None
|
||||
nm_perimetro_cefalico: Optional[float] = None
|
||||
nm_diagnostico_texto: Optional[str] = None
|
||||
nm_cie_codigo: Optional[str] = None
|
||||
nm_cie_descripcion: Optional[str] = None
|
||||
nm_tratamiento_texto: Optional[str] = None
|
||||
nm_receta: Optional[str] = None
|
||||
nm_plan_estudios: Optional[str] = None
|
||||
nm_diagnostico_texto: OptionalStr = None
|
||||
nm_cie_codigo: OptionalStr = None
|
||||
nm_cie_descripcion: OptionalStr = None
|
||||
nm_tratamiento_texto: OptionalStr = None
|
||||
nm_receta: OptionalStr = None
|
||||
nm_plan_estudios: OptionalStr = None
|
||||
nm_pronostico: CatalogValue(_PRONOSTICO_CATALOG) = None
|
||||
nm_observaciones: Optional[str] = None
|
||||
nm_observaciones: OptionalStr = None
|
||||
nm_masa_corporal: Optional[float] = None
|
||||
nm_talla: Optional[float] = None
|
||||
nm_imc_visita: Optional[float] = None
|
||||
@@ -46,20 +43,4 @@ class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_presion_arterial_sistolica: Optional[int] = None
|
||||
nm_presion_arterial_diastolica: Optional[int] = None
|
||||
nm_temperatura: Optional[float] = None
|
||||
nm_pdf_ruta: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"nm_id_hospital", "nm_nota_previa_id", "nm_medico_tratante",
|
||||
"nm_motivo_consulta", "nm_interrogatorio", "nm_diagnostico_texto", "nm_cie_codigo",
|
||||
"nm_cie_descripcion", "nm_tratamiento_texto", "nm_receta", "nm_plan_estudios",
|
||||
"nm_observaciones", "nm_pdf_ruta",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("nm_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
nm_pdf_ruta: OptionalStr = None
|
||||
|
||||
@@ -1,53 +1,37 @@
|
||||
"""Import schema for `core.tea.models.OrdenesEstudio`. All fields optional, like
|
||||
TEA's Core; system-managed `ord_*_created_at`/`ord_updated_at`/`ord_fuente_sistema` are excluded."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import Especialidad, EstatusEstudio, TipoEstudio, VentanaMadurativa
|
||||
from core.tea.enums import TIPO_ESTUDIO_ALIAS, Especialidad, EstatusEstudio, TipoEstudio, VentanaMadurativa
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad)
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio)
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
_ESTATUS_ESTUDIO_CATALOG = Catalog(EstatusEstudio)
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
|
||||
|
||||
class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id still point at this record.
|
||||
ord_id: SourceId = None
|
||||
ord_pac_id: Optional[int] = None
|
||||
ord_nota_medica_id: Optional[str] = None
|
||||
ord_id_hospital: Optional[str] = None
|
||||
ord_fecha: Optional[date] = None
|
||||
ord_medico_solicitante: Optional[str] = None
|
||||
ord_nota_medica_id: OptionalStr = None
|
||||
ord_id_hospital: OptionalStr = None
|
||||
ord_fecha: FlexDate = None
|
||||
ord_medico_solicitante: OptionalStr = None
|
||||
ord_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
ord_diagnostico_asignado: Optional[str] = None
|
||||
ord_cie_asignado: Optional[str] = None
|
||||
ord_diagnostico_asignado: OptionalStr = None
|
||||
ord_cie_asignado: OptionalStr = None
|
||||
ord_dias_vigencia: Optional[int] = None
|
||||
ord_fecha_vencimiento: Optional[date] = None
|
||||
ord_fecha_vencimiento: FlexDate = None
|
||||
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None
|
||||
ord_estatus: CatalogValue(_ESTATUS_ESTUDIO_CATALOG) = None
|
||||
ord_fecha_realizacion: Optional[date] = None
|
||||
ord_fecha_resultado: Optional[date] = None
|
||||
ord_fecha_realizacion: FlexDate = None
|
||||
ord_fecha_resultado: FlexDate = None
|
||||
ord_dias_espera: Optional[int] = None
|
||||
ord_proveedor: Optional[str] = None
|
||||
ord_proveedor: OptionalStr = None
|
||||
ord_edad_meses: Optional[float] = None
|
||||
ord_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
ord_pdf_ruta: Optional[str] = None
|
||||
ord_observaciones: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"ord_nota_medica_id", "ord_id_hospital", "ord_medico_solicitante",
|
||||
"ord_diagnostico_asignado", "ord_cie_asignado", "ord_proveedor", "ord_pdf_ruta",
|
||||
"ord_observaciones",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("ord_fecha", "ord_fecha_vencimiento", "ord_fecha_realizacion", "ord_fecha_resultado", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
ord_pdf_ruta: OptionalStr = None
|
||||
ord_observaciones: OptionalStr = None
|
||||
|
||||
@@ -3,14 +3,11 @@ Core; system-managed `pac_created_at`/`pac_updated_at`/`pac_fuente_sistema` are
|
||||
|
||||
`pac_id` is importable: every other TEA table references the patient by the
|
||||
source system's integer id, so it has to be kept, not renumbered."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import Parentesco, SexoBiologico
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_SEXO_CATALOG = Catalog(SexoBiologico)
|
||||
_PARENTESCO_CATALOG = Catalog(Parentesco)
|
||||
@@ -18,20 +15,10 @@ _PARENTESCO_CATALOG = Catalog(Parentesco)
|
||||
|
||||
class PacientesImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: Optional[str] = None
|
||||
pac_id_titular: Optional[str] = None
|
||||
pac_id_hospital: OptionalStr = None
|
||||
pac_id_titular: OptionalStr = None
|
||||
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
|
||||
pac_fecha_nacimiento: Optional[date] = None
|
||||
pac_fecha_nacimiento: FlexDate = None
|
||||
pac_sexo: CatalogValue(_SEXO_CATALOG) = None
|
||||
pac_codigo_postal_vigente: Optional[str] = None
|
||||
pac_dependencia: Optional[str] = None
|
||||
|
||||
@field_validator("pac_id_hospital", "pac_id_titular", "pac_codigo_postal_vigente", "pac_dependencia", mode="before")
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("pac_fecha_nacimiento", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha_nacimiento(cls, v):
|
||||
return coerce_date(v)
|
||||
pac_codigo_postal_vigente: OptionalStr = None
|
||||
pac_dependencia: OptionalStr = None
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
TEA's Core; system-managed `pnn_created_at`/`pnn_updated_at`/`pnn_fuente_sistema` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import (
|
||||
ClasificacionEdadGestacional,
|
||||
ComplicacionIntraparto,
|
||||
@@ -12,7 +10,7 @@ from core.tea.enums import (
|
||||
TipoParto,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr
|
||||
|
||||
_FUENTE_ANTECEDENTE_NEONATAL_CATALOG = Catalog(FuenteAntecedenteNeonatal)
|
||||
_TIPO_PARTO_CATALOG = Catalog(TipoParto)
|
||||
@@ -45,16 +43,8 @@ class PartoNeonatalImportSchema(ImportSchema):
|
||||
pnn_hipoglucemia_neonatal: Optional[int] = None
|
||||
pnn_anoxia: Optional[int] = None
|
||||
pnn_sindrome_congenito: Optional[int] = None
|
||||
pnn_sindrome_congenito_desc: Optional[str] = None
|
||||
pnn_sindrome_congenito_desc: OptionalStr = None
|
||||
pnn_flag_riesgo_neonatal: Optional[int] = None
|
||||
pnn_observaciones: Optional[str] = None
|
||||
pnn_observaciones: OptionalStr = None
|
||||
pnn_ocr_confianza: Optional[float] = None
|
||||
pnn_nlp_version: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"pnn_sindrome_congenito_desc", "pnn_observaciones", "pnn_nlp_version",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
pnn_nlp_version: OptionalStr = None
|
||||
|
||||
@@ -1,22 +1,19 @@
|
||||
"""Import schema for `core.tea.models.PotencialesEvocadosAuditivos`. All fields
|
||||
optional, like TEA's Core; system-managed `pea_created_at`/`pea_updated_at` are excluded."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import GradoHipoacusia
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_GRADO_HIPOACUSIA_CATALOG = Catalog(GradoHipoacusia)
|
||||
|
||||
|
||||
class PotencialesEvocadosAuditivosImportSchema(ImportSchema):
|
||||
pea_ord_id: Optional[str] = None
|
||||
pea_ord_id: OptionalStr = None
|
||||
pea_pac_id: Optional[int] = None
|
||||
pea_fecha_estudio: Optional[date] = None
|
||||
pea_medico_interpreta: Optional[str] = None
|
||||
pea_fecha_estudio: FlexDate = None
|
||||
pea_medico_interpreta: OptionalStr = None
|
||||
pea_umbral_od: Optional[int] = None
|
||||
pea_umbral_oi: Optional[int] = None
|
||||
pea_latencia_v_od: Optional[float] = None
|
||||
@@ -24,19 +21,6 @@ class PotencialesEvocadosAuditivosImportSchema(ImportSchema):
|
||||
pea_interpico_i_v_od: Optional[float] = None
|
||||
pea_interpico_i_v_oi: Optional[float] = None
|
||||
pea_grado_hipoacusia: CatalogValue(_GRADO_HIPOACUSIA_CATALOG) = None
|
||||
pea_conclusion_texto: Optional[str] = None
|
||||
pea_conclusion_texto: OptionalStr = None
|
||||
pea_flag_diferencial_auditivo: Optional[int] = None
|
||||
pea_ocr_confianza: Optional[float] = None
|
||||
|
||||
@field_validator(
|
||||
"pea_ord_id", "pea_medico_interpreta", "pea_conclusion_texto",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("pea_fecha_estudio", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Writes the catalog-fallback fields a document source's records carry
|
||||
(captions no known `FieldSpec` claimed, see `extraction.nlp.discovery`)
|
||||
into the silver layer directly: one synthetic `procedimiento` per record
|
||||
per estudio its resolved fields touch, with their `observacion`s matched
|
||||
or minted against the project's catalog (`catalog_matching`).
|
||||
|
||||
There is no staging row for these — the whole point is a field outside
|
||||
today's structured schemas — so this bypasses `DESDE_STAGING` and writes
|
||||
straight through the domain's existing `carga_repository`, the same one
|
||||
`webapi.orquestacion`'s `cargar` step uses for staging-derived batches.
|
||||
|
||||
Marked clearly apart from every staging-derived procedimiento:
|
||||
`fuente_tabla` is the sentinel `FUENTE_CATALOGO_ABIERTO`, never a real
|
||||
staging table name. `fuente_id` is the record's own natural key (not a SQL
|
||||
row's surrogate id), so reprocessing the same record later — read again
|
||||
from the SQL source, re-uploaded as a file, or corrected by hand — updates
|
||||
the same rows in place instead of duplicating them; the structured fields
|
||||
a source also carries keep going through the unmodified staging/import
|
||||
path (`commit_sources`), independently of this.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
|
||||
from extraction import ExtractedRecord
|
||||
from indicadores_kit.plata.procedimiento import LotePlata
|
||||
from indicadores_kit.registry.catalogos import Catalogo, catalogo_desde_toml, ruta_de_catalogo
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
from webapi.imports.schemas.catalog_matching import MatchedField, match_or_mint
|
||||
|
||||
FUENTE_CATALOGO_ABIERTO = "catalogo_abierto"
|
||||
|
||||
|
||||
@dataclass
|
||||
class CatalogCommitResult:
|
||||
proyecto: str
|
||||
records_written: int = 0
|
||||
records_without_patient: int = 0
|
||||
fields_matched: int = 0
|
||||
fields_minted: int = 0
|
||||
|
||||
|
||||
def commit_discovered_fields(
|
||||
records: list[ExtractedRecord], *, proyecto: str, estudio_id: str | None = None
|
||||
) -> CatalogCommitResult:
|
||||
"""A patient without a row in `persona` is counted and skipped: this
|
||||
path only fills in fields for a patient already known, it doesn't
|
||||
create one."""
|
||||
dominio = import_module(f"persistance.{proyecto}")
|
||||
tablas = tablas_de(proyecto)
|
||||
ruta = ruta_de_catalogo(proyecto)
|
||||
catalogo = catalogo_desde_toml(ruta, tablas=tablas)
|
||||
|
||||
result = CatalogCommitResult(proyecto=proyecto)
|
||||
procedures, observations = [], []
|
||||
for record in records:
|
||||
if not record.discovered or record.key is None:
|
||||
continue
|
||||
patients = dominio.paciente_repository.list(pac_id_hospital=record.key, limit=1)
|
||||
if not patients:
|
||||
result.records_without_patient += 1
|
||||
continue
|
||||
pac_id = patients[0].pac_id
|
||||
|
||||
matched = match_or_mint(record.discovered, proyecto=proyecto, catalogo=catalogo, estudio_id=estudio_id)
|
||||
if any(field.is_new for field in matched):
|
||||
catalogo = catalogo_desde_toml(ruta, tablas=tablas) # so a later record in this batch can match it too
|
||||
matched = _fold_duplicates(matched)
|
||||
|
||||
by_estudio: dict[str, list] = defaultdict(list)
|
||||
for field in matched:
|
||||
by_estudio[field.resultado_id.split(".", 1)[0]].append(field)
|
||||
result.fields_minted += int(field.is_new)
|
||||
result.fields_matched += int(not field.is_new)
|
||||
for estudio, fields in by_estudio.items():
|
||||
key = (FUENTE_CATALOGO_ABIERTO, record.key, estudio, "reporte")
|
||||
procedures.append({"llave": key, "padres": [], "pac_id": pac_id, "fecha": None, "fecha_del_padre": False})
|
||||
observations += [
|
||||
{"procedimiento": key, "pac_id": pac_id, "resultado_id": field.resultado_id, **field.observacion}
|
||||
for field in fields
|
||||
]
|
||||
result.records_written += 1
|
||||
|
||||
if procedures:
|
||||
_sync_catalog(dominio, proyecto, tablas)
|
||||
dominio.carga_repository.guardar_carga(
|
||||
fuente=FUENTE_CATALOGO_ABIERTO, personas=(), plata=LotePlata(procedures, observations, {})
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _fold_duplicates(matched: list[MatchedField]) -> list[MatchedField]:
|
||||
"""A record's discovered captions can repeat the same resultado_id (a
|
||||
static label such as "FECHA" printed on several pages): `observacion`
|
||||
has one row per `(procedimiento, resultado_id)`, so only the first
|
||||
occurrence survives. `discover_captions` keeps every repeat on purpose
|
||||
and leaves folding to the caller (see its docstring)."""
|
||||
seen: set[str] = set()
|
||||
folded = []
|
||||
for field in matched:
|
||||
if field.resultado_id in seen:
|
||||
continue
|
||||
seen.add(field.resultado_id)
|
||||
folded.append(field)
|
||||
return folded
|
||||
|
||||
|
||||
def _sync_catalog(dominio, proyecto: str, tablas) -> None:
|
||||
"""A field minted by `match_or_mint` only exists in the TOML until this
|
||||
runs: `procedimiento.estudio_id` and `observacion`'s catalog both need
|
||||
the matching `cat_estudio`/`cat_resultado` row to already be there."""
|
||||
catalogo: Catalogo = catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas)
|
||||
dominio.catalogo_repository.sincronizar(catalogo.estudios, catalogo.resultados, catalogo.valores)
|
||||
@@ -13,6 +13,7 @@ from typing import Any, Iterator
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from persistance.repository import ConflictPolicy
|
||||
from webapi.imports.audit import ImportAudit
|
||||
from webapi.imports.connectors import Connector, ConnectorError, build_connector
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY, EntitySpec
|
||||
from webapi.imports.schemas.service import BatchValidationResult, validate_rows
|
||||
@@ -24,6 +25,10 @@ class ImportRequestError(Exception):
|
||||
bad connection string or an invalid on_conflict. Mapped to HTTP 400."""
|
||||
|
||||
|
||||
class DatabaseRefused(ImportRequestError):
|
||||
"""The database rejected the batch at write time; nothing was written."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ImportSource:
|
||||
"""One parsed and structurally validated entry of a request's `sources`."""
|
||||
@@ -39,32 +44,32 @@ class ImportSource:
|
||||
@classmethod
|
||||
def parse(cls, raw: Any) -> "ImportSource":
|
||||
if not isinstance(raw, dict):
|
||||
raise ImportRequestError("each source must be an object")
|
||||
raise ImportRequestError("cada fuente debe ser un objeto")
|
||||
target = raw.get("target")
|
||||
if not target:
|
||||
raise ImportRequestError("source is missing 'target'")
|
||||
raise ImportRequestError("a la fuente le falta 'target'")
|
||||
spec = ENTITY_REGISTRY.get(target)
|
||||
if spec is None:
|
||||
raise ImportRequestError(f"unknown target: {target!r}")
|
||||
raise ImportRequestError(f"destino desconocido: {target!r}")
|
||||
|
||||
fields = set(spec.schema.model_fields)
|
||||
mapping = raw.get("column_mapping") or {}
|
||||
defaults = raw.get("defaults") or {}
|
||||
if not isinstance(mapping, dict) or not isinstance(defaults, dict):
|
||||
raise ImportRequestError("'column_mapping' and 'defaults' must be objects")
|
||||
raise ImportRequestError("'column_mapping' y 'defaults' deben ser objetos")
|
||||
unknown = sorted((set(mapping.values()) | set(defaults)) - fields)
|
||||
if unknown:
|
||||
raise ImportRequestError(f"{target} has no field(s) {unknown}")
|
||||
raise ImportRequestError(f"{target} no tiene los campos {unknown}")
|
||||
targets = list(mapping.values())
|
||||
duplicated = sorted({t for t in targets if targets.count(t) > 1})
|
||||
if duplicated:
|
||||
raise ImportRequestError(f"more than one source column mapped to {duplicated}")
|
||||
raise ImportRequestError(f"más de una columna de origen asignada a {duplicated}")
|
||||
if not mapping and not defaults:
|
||||
raise ImportRequestError(f"source for {target} maps no columns")
|
||||
raise ImportRequestError(f"la fuente de {target} no asigna ninguna columna")
|
||||
|
||||
payload = raw.get("payload")
|
||||
if not isinstance(payload, dict):
|
||||
raise ImportRequestError("source is missing 'payload'")
|
||||
raise ImportRequestError("a la fuente le falta 'payload'")
|
||||
return cls(
|
||||
source_type=raw.get("source_type", ""),
|
||||
target=target,
|
||||
@@ -130,8 +135,16 @@ def _jsonable(value: Any) -> Any:
|
||||
return str(value)
|
||||
|
||||
|
||||
def validate_source(raw_source: dict[str, Any]) -> BatchValidationResult:
|
||||
return ImportSource.parse(raw_source).validate()
|
||||
def validate_source(raw_source: dict[str, Any], audit: ImportAudit | None = None) -> BatchValidationResult:
|
||||
source = ImportSource.parse(raw_source)
|
||||
if audit is None:
|
||||
return source.validate()
|
||||
tracked = audit.source(source)
|
||||
rows = list(source.rows())
|
||||
tracked.observe_rows(rows)
|
||||
validation = validate_rows(source.spec.schema, rows)
|
||||
tracked.observe_validation(validation)
|
||||
return validation
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -150,12 +163,12 @@ class SourceCommitResult:
|
||||
|
||||
def _parse_batch(raw_sources: Any) -> list[ImportSource]:
|
||||
if not isinstance(raw_sources, list) or not raw_sources:
|
||||
raise ImportRequestError("'sources' must be a non-empty list")
|
||||
raise ImportRequestError("'sources' debe ser una lista no vacía")
|
||||
sources = [ImportSource.parse(raw) for raw in raw_sources]
|
||||
domains = sorted({source.domain for source in sources})
|
||||
if len(domains) > 1:
|
||||
raise ImportRequestError(
|
||||
f"a batch cannot mix domains — got {domains}, every source must target the same one"
|
||||
f"un lote no puede mezclar dominios ({', '.join(domains)}): todas las fuentes deben ir al mismo"
|
||||
)
|
||||
return sources
|
||||
|
||||
@@ -205,35 +218,39 @@ def merge_duplicates(sources: list[ImportSource], rows: list[list[dict[str, Any]
|
||||
|
||||
|
||||
def _key_part(value: Any) -> Any:
|
||||
"""Normalized for comparison across sources: a CSV's natural key is
|
||||
always a string ("5001"), while a typed source (the document extractor,
|
||||
a SQL column) can hand back an int or a date for the very same value.
|
||||
Stringifying both sides is what lets rows that describe the same record
|
||||
actually match, instead of silently landing as two separate ones."""
|
||||
"""Normalized for comparison across sources: a CSV key is the string "5001"
|
||||
where a typed source gives the int 5001."""
|
||||
if _is_blank(value):
|
||||
return None
|
||||
return str(value).strip().upper()
|
||||
|
||||
|
||||
def commit_sources(raw_sources: Any, *, on_conflict: str, merge: bool = False) -> list[SourceCommitResult]:
|
||||
def commit_sources(
|
||||
raw_sources: Any, *, on_conflict: str, merge: bool = False, audit: ImportAudit | None = None
|
||||
) -> list[SourceCommitResult]:
|
||||
"""Writes a batch in one transaction. With `merge`, rows of different
|
||||
sources sharing a natural key are combined first (see `merge_duplicates`)."""
|
||||
try:
|
||||
policy = ConflictPolicy(on_conflict)
|
||||
except ValueError as exc:
|
||||
raise ImportRequestError(f"invalid on_conflict: {on_conflict!r}") from exc
|
||||
raise ImportRequestError(f"on_conflict inválido: {on_conflict!r}") from exc
|
||||
|
||||
sources = _parse_batch(raw_sources)
|
||||
tracked = [audit.source(source) for source in sources] if audit else []
|
||||
if policy is ConflictPolicy.UPSERT:
|
||||
keyless = sorted({s.target for s in sources if not s.spec.conflict_fields})
|
||||
if keyless:
|
||||
raise ImportRequestError(f"{', '.join(keyless)} has no natural key — on_conflict=upsert is not valid for it")
|
||||
raise ImportRequestError(f"{', '.join(keyless)} no tiene llave natural: on_conflict=upsert no aplica")
|
||||
|
||||
# Read + validate everything before opening the write transaction, so a
|
||||
# slow source (OCR, a remote SQL table) never holds database locks.
|
||||
rows: list[list[dict[str, Any] | None]] = [list(source.rows()) for source in sources]
|
||||
merged, merge_warnings = merge_duplicates(sources, rows) if merge else ({}, {})
|
||||
validated = [(source, validate_rows(source.spec.schema, source_rows)) for source, source_rows in zip(sources, rows)]
|
||||
for position, source_audit in enumerate(tracked):
|
||||
source_audit.observe_rows(rows[position])
|
||||
source_audit.observe_validation(validated[position][1])
|
||||
source_audit.observe_warnings(merge_warnings.get(position, []))
|
||||
|
||||
session = sources[0].spec.repository.open_session()
|
||||
links = LinkResolver(session)
|
||||
@@ -258,7 +275,7 @@ def commit_sources(raw_sources: Any, *, on_conflict: str, merge: bool = False) -
|
||||
"row_index": validation.accepted_rows[outcome.index].row_index,
|
||||
"field": ",".join(source.spec.conflict_fields or ()),
|
||||
"category": "conflict",
|
||||
"message": outcome.error or "conflict",
|
||||
"message": outcome.error or "conflicto",
|
||||
"raw_value": _jsonable(
|
||||
validation.accepted_rows[outcome.index].data.get((source.spec.conflict_fields or ("",))[0])
|
||||
),
|
||||
@@ -279,10 +296,18 @@ def commit_sources(raw_sources: Any, *, on_conflict: str, merge: bool = False) -
|
||||
merged=merged.get(position, 0),
|
||||
warnings=merge_warnings.get(position, []),
|
||||
)
|
||||
if tracked:
|
||||
tracked[position].observe_write(
|
||||
created=write.created_count, updated=write.updated_count,
|
||||
conflicts=write.rejected_count, linked=linked,
|
||||
)
|
||||
session.commit()
|
||||
except SQLAlchemyError as exc:
|
||||
session.rollback()
|
||||
raise ImportRequestError(f"the database refused the batch, nothing was written: {exc.__class__.__name__}: {exc.orig if hasattr(exc, 'orig') else exc}") from exc
|
||||
detail = exc.orig if hasattr(exc, "orig") else exc
|
||||
raise DatabaseRefused(
|
||||
f"la base de datos rechazó el lote y no se escribió nada: {exc.__class__.__name__}: {detail}"
|
||||
) from exc
|
||||
finally:
|
||||
session.close()
|
||||
return [results[i] for i in range(len(validated))]
|
||||
|
||||
@@ -9,7 +9,7 @@ from webapi.imports.connectors import Connector, ConnectorError
|
||||
from webapi.imports.connectors.document import DocumentConnector
|
||||
from webapi.imports.connectors.pdf import PdfConnector, RegionSpec
|
||||
from webapi.imports.connectors.tabular import columns_from_dataframe, rows_from_dataframe
|
||||
from webapi.imports.mapping.column_matcher import ColumnMatcher
|
||||
from webapi.imports.mapping import column_matcher
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
|
||||
@@ -18,8 +18,8 @@ def suggest_mapping(source_columns: list[str], target_key: str | None) -> list[d
|
||||
return []
|
||||
spec = ENTITY_REGISTRY.get(target_key)
|
||||
if spec is None:
|
||||
raise ConnectorError(f"unknown target: {target_key!r}")
|
||||
matches = ColumnMatcher().suggest(source_columns, list(spec.schema.model_fields.keys()))
|
||||
raise ConnectorError(f"destino desconocido: {target_key!r}")
|
||||
matches = column_matcher.suggest_mapping(source_columns, list(spec.schema.model_fields.keys()))
|
||||
return [
|
||||
{"source_column": m.source_column, "target_field": m.target_field, "confidence": m.confidence, "reason": m.reason}
|
||||
for m in matches
|
||||
|
||||
@@ -5,8 +5,8 @@ same batch.
|
||||
|
||||
Links are derived from Core's columns: an entity with both `pac_id` and
|
||||
`pac_id_hospital` links to its domain's `Paciente`, and one with both
|
||||
`ord_id` and `ord_numero_hospital` links to its `OrdenesEstudio`. TEA uses
|
||||
UUID keys without such pairs, so it gets no links.
|
||||
`ord_id` and `ord_numero_hospital` links to its `OrdenesEstudio`. TEA's child
|
||||
tables carry the source's patient id itself (`*_pac_id`), so it needs none.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from functools import cache
|
||||
@@ -55,7 +55,12 @@ def dependency_rank(target_key: str) -> int:
|
||||
class LinkResolver:
|
||||
"""Looks up parent primary keys by natural key within the batch's session,
|
||||
so parents written earlier in the same uncommitted transaction are found.
|
||||
A missing parent leaves the FK null, which Core allows."""
|
||||
|
||||
The natural key wins over an id the source sent: a hospital table carries
|
||||
the hospital's internal ids, which only match ours when the parent was
|
||||
loaded with its own id. An id is kept as sent only when there is no
|
||||
natural key or its parent isn't loaded; a missing parent leaves the FK
|
||||
null, which Core allows."""
|
||||
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
@@ -65,12 +70,13 @@ class LinkResolver:
|
||||
linked = []
|
||||
for link in links_for(target_key):
|
||||
value = row.get(link.via_field)
|
||||
if row.get(link.fk_field) is not None or value is None:
|
||||
if value is None:
|
||||
continue
|
||||
pk = self._lookup(link, value)
|
||||
if pk is not None:
|
||||
if row.get(link.fk_field) != pk:
|
||||
linked.append(link.fk_field)
|
||||
row[link.fk_field] = pk
|
||||
linked.append(link.fk_field)
|
||||
return linked
|
||||
|
||||
def _lookup(self, link: ForeignKeyLink, value: Any) -> Any:
|
||||
|
||||
+43
-11
@@ -2,17 +2,22 @@
|
||||
|
||||
`registrar_indicadores` agrega a un blueprint:
|
||||
|
||||
GET /indicadores catálogo de indicadores
|
||||
GET /indicadores catálogo de indicadores (con sus `filtros`)
|
||||
GET /indicadores/<id>/periodos periodos con reporte
|
||||
GET /indicadores/<id>/datos?periodos=&estrato= los números, sin figura
|
||||
GET /indicadores/<id>/datos?periodos=&estrato=&filtro= los números, sin figura
|
||||
GET /indicadores/<id>/metadatos ficha metodológica
|
||||
GET /indicadores/<id>/figuras/<figura>?periodos=&tema=
|
||||
GET /indicadores/<id>/figuras/<figura>?periodos=&tema=&filtro=
|
||||
|
||||
Las definiciones salen del kit (`measures_de`), los datos de
|
||||
`indicadores_kit.serving.datos` y las figuras de
|
||||
`indicadores_kit.serving.figuras`; aquí solo se valida, se abre la sesión y
|
||||
se traducen los errores a códigos HTTP. La forma de cada respuesta es un
|
||||
contrato con el frontend: no se quita ni se renombra un campo.
|
||||
|
||||
`?filtro=estrato:valor[,estrato:valor]` (T-19f) cuenta lo mismo solo con las
|
||||
unidades que tienen esos valores: el mismo contrato, y en `/datos` la llave
|
||||
`filtros`. Solo se aceptan los filtros que el indicador declara
|
||||
(`extension.filtros`) y los valores de su catálogo; si no, 400.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -21,7 +26,8 @@ from collections.abc import Callable
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from indicadores_kit.registry.measures import Measure, measures_de
|
||||
from indicadores_kit.serving.datos import datos_de, metadatos_de, periodos_de, resumen_de
|
||||
from indicadores_kit.serving.contratos import FiltroNoDeclarado
|
||||
from indicadores_kit.serving.datos import datos_de, filtros_de, metadatos_de, periodos_de, resumen_de
|
||||
from indicadores_kit.serving.figuras import (
|
||||
TEMAS,
|
||||
figura_json,
|
||||
@@ -59,6 +65,21 @@ def _tipo_de(periodo: str, tipos: list[str]) -> str | None:
|
||||
return next((tipo for tipo in tipos if FORMATOS[tipo][0].fullmatch(periodo)), None)
|
||||
|
||||
|
||||
def filtros_pedidos(texto: str | None) -> dict[str, str]:
|
||||
"""`estrato:valor[,estrato:valor]` -> `{estrato: valor}`. Vacío si no se pidió; `ValueError` si viene mal escrito."""
|
||||
if not texto:
|
||||
return {}
|
||||
filtros = {}
|
||||
for parte in texto.split(","):
|
||||
estrato, separador, valor = parte.partition(":")
|
||||
if not separador or not estrato or not valor:
|
||||
raise ValueError(f"filtro mal escrito {parte!r}; use estrato:valor")
|
||||
if estrato in filtros:
|
||||
raise ValueError(f"el filtro {estrato!r} va dos veces")
|
||||
filtros[estrato] = valor
|
||||
return filtros
|
||||
|
||||
|
||||
def periodos_pedidos(texto: str | None, medida: Measure) -> tuple[list[str], str | None]:
|
||||
"""Los periodos de `?periodos=` y su tipo. Sin parámetro (o vacío): `([], None)`.
|
||||
|
||||
@@ -92,11 +113,16 @@ def registrar_indicadores(
|
||||
|
||||
def listar_indicadores():
|
||||
# Los marcados `oculto` en su TOML no salen en el catálogo; su id sigue respondiendo.
|
||||
return _json([
|
||||
resumen_de(id_, medida)
|
||||
for id_, medida in definiciones.items()
|
||||
if not medida.extension.publicacion.oculto
|
||||
])
|
||||
# `filtros` (T-24f): los que admite cada uno, con sus valores del catálogo, para armar `?filtro=`.
|
||||
sesion = get_session()
|
||||
try:
|
||||
return _json([
|
||||
{**resumen_de(id_, medida), "filtros": filtros_de(sesion, medida)}
|
||||
for id_, medida in definiciones.items()
|
||||
if not medida.extension.publicacion.oculto
|
||||
])
|
||||
finally:
|
||||
sesion.close()
|
||||
|
||||
def _periodos_o_los_que_haya(sesion: Session, medida: Measure, periodos: list[str]) -> list[str]:
|
||||
"""Los pedidos; sin pedir ninguno, los que tienen reporte del primer tipo que publica."""
|
||||
@@ -139,6 +165,7 @@ def registrar_indicadores(
|
||||
)
|
||||
try:
|
||||
periodos, _ = periodos_pedidos(request.args.get("periodos"), medida)
|
||||
filtros = filtros_pedidos(request.args.get("filtro"))
|
||||
except ValueError as error:
|
||||
return _error(str(error), 400)
|
||||
|
||||
@@ -147,7 +174,9 @@ def registrar_indicadores(
|
||||
periodos = _periodos_o_los_que_haya(sesion, medida, periodos)
|
||||
if not periodos:
|
||||
return _error("el indicador no tiene reportes calculados", 404)
|
||||
datos = datos_de(sesion, medida, periodos, tablas=tablas, estrato=estrato)
|
||||
datos = datos_de(sesion, medida, periodos, tablas=tablas, estrato=estrato, filtros=filtros or None)
|
||||
except FiltroNoDeclarado as error:
|
||||
return _error(str(error), 400)
|
||||
except KeyError:
|
||||
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||
raise
|
||||
@@ -171,6 +200,7 @@ def registrar_indicadores(
|
||||
return _error(f"tema desconocido {tema!r}; use claro u oscuro", 400)
|
||||
try:
|
||||
periodos, tipo = periodos_pedidos(request.args.get("periodos"), medida)
|
||||
filtros = filtros_pedidos(request.args.get("filtro"))
|
||||
except ValueError as error:
|
||||
return _error(str(error), 400)
|
||||
|
||||
@@ -180,7 +210,9 @@ def registrar_indicadores(
|
||||
periodos = periodos or periodos_por_defecto(sesion, medida, figura, tablas=tablas)
|
||||
if not periodos:
|
||||
return _error("el indicador no tiene reportes calculados", 404)
|
||||
texto = figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema)
|
||||
texto = figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema, filtros=filtros or None)
|
||||
except FiltroNoDeclarado as error:
|
||||
return _error(str(error), 400)
|
||||
except KeyError:
|
||||
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||
raise
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
"""Recomputes a domain's indicators after its staging tables change.
|
||||
|
||||
A successful import asks for a recomputation (`ColaDeRecalculo.solicitar`),
|
||||
which only drops a marker file. A separate process (`python -m
|
||||
webapi.indicadores_vivos`, the `indicadores` compose service) picks the
|
||||
markers up and runs that domain's cycle (`webapi.orquestacion.correr`): catalogs ->
|
||||
staging to facts -> views -> registry -> definitions -> reports.
|
||||
Requests that arrive while a domain is running are folded into one more run.
|
||||
|
||||
State lives in files under `INDICADORES_DIR`: `pendiente/<dominio>` markers
|
||||
and `estado.json`; each run is also appended, as counts only, to
|
||||
`indicadores.jsonl` in the import report directory.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message
|
||||
|
||||
DOMINIOS = ("cacu", "cama", "tea")
|
||||
_SUMMARY_MAX = 400
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def _short(value: Any) -> str:
|
||||
text = str(value)
|
||||
return text if len(text) <= _SUMMARY_MAX else text[:_SUMMARY_MAX] + "…"
|
||||
|
||||
|
||||
class ColaDeRecalculo:
|
||||
"""Marker-file queue and status of the indicator recomputations."""
|
||||
|
||||
def __init__(self, base: Path | None = None):
|
||||
self.base = Path(base or os.environ.get("INDICADORES_DIR", "indicadores"))
|
||||
|
||||
@property
|
||||
def _pending(self) -> Path:
|
||||
return self.base / "pendiente"
|
||||
|
||||
@property
|
||||
def _status_path(self) -> Path:
|
||||
return self.base / "estado.json"
|
||||
|
||||
def solicitar(self, dominio: str) -> None:
|
||||
if dominio not in DOMINIOS:
|
||||
raise ValueError(f"dominio desconocido: {dominio!r}")
|
||||
self._pending.mkdir(parents=True, exist_ok=True)
|
||||
(self._pending / dominio).write_text(_now(), encoding="utf-8")
|
||||
|
||||
def pendientes(self) -> list[str]:
|
||||
if not self._pending.exists():
|
||||
return []
|
||||
return sorted(p.name for p in self._pending.iterdir() if p.name in DOMINIOS)
|
||||
|
||||
def tomar(self, dominio: str) -> bool:
|
||||
"""Consumes the marker; a request made from now on queues one more run."""
|
||||
try:
|
||||
(self._pending / dominio).unlink()
|
||||
return True
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
|
||||
def estado(self) -> dict[str, Any]:
|
||||
try:
|
||||
status = json.loads(self._status_path.read_text(encoding="utf-8"))
|
||||
except (FileNotFoundError, json.JSONDecodeError):
|
||||
status = {}
|
||||
pending = set(self.pendientes())
|
||||
return {d: {**status.get(d, {"estado": "sin_correr"}), "pendiente": d in pending} for d in DOMINIOS}
|
||||
|
||||
def _guardar_estado(self, dominio: str, entrada: dict[str, Any]) -> None:
|
||||
self.base.mkdir(parents=True, exist_ok=True)
|
||||
lock = self.base / ".estado.lock"
|
||||
with open(lock, "w") as handle:
|
||||
fcntl.flock(handle, fcntl.LOCK_EX)
|
||||
try:
|
||||
status = json.loads(self._status_path.read_text(encoding="utf-8"))
|
||||
except (FileNotFoundError, json.JSONDecodeError):
|
||||
status = {}
|
||||
status[dominio] = entrada
|
||||
tmp = self._status_path.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(status, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
|
||||
tmp.replace(self._status_path)
|
||||
|
||||
def correr(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
|
||||
"""Runs the domain's graph (without `migrar`: the API migrates on startup)."""
|
||||
from webapi.orquestacion import Contexto, correr, pasos_de
|
||||
|
||||
desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5))
|
||||
hasta = hasta or int(os.environ.get("INDICADORES_HASTA", date.today().year))
|
||||
inicio = _now()
|
||||
started = time.monotonic()
|
||||
self._guardar_estado(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]})
|
||||
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
|
||||
try:
|
||||
ctx = Contexto(dominio, desde, hasta, permitir_sin_definir=True)
|
||||
pasos = correr(ctx, solo=[p for p in pasos_de(dominio) if p != "migrar"])
|
||||
entrada.update(
|
||||
estado="ok",
|
||||
pasos=[{"paso": p.nombre, "segundos": round(p.segundos, 2), "resumen": _short(p.resumen)} for p in pasos],
|
||||
)
|
||||
except Exception as exc: # the worker must survive a failing domain
|
||||
log.exception("recálculo de %s falló", dominio)
|
||||
entrada.update(estado="error", error={"tipo": type(exc).__name__, "mensaje": sanitize_message(str(exc))})
|
||||
entrada.update(fin=_now(), duracion_s=round(time.monotonic() - started, 2))
|
||||
self._guardar_estado(dominio, entrada)
|
||||
try:
|
||||
JsonlAuditSink(report_dir() / "indicadores.jsonl").write({"dominio": dominio, **entrada})
|
||||
except OSError:
|
||||
pass
|
||||
return entrada
|
||||
|
||||
def atender(self) -> list[str]:
|
||||
"""Runs every pending domain once; returns the ones it ran."""
|
||||
ran = []
|
||||
for dominio in self.pendientes():
|
||||
if self.tomar(dominio):
|
||||
self.correr(dominio)
|
||||
ran.append(dominio)
|
||||
return ran
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
cola = ColaDeRecalculo()
|
||||
interval = float(os.environ.get("INDICADORES_INTERVALO_S", "20"))
|
||||
if os.environ.get("INDICADORES_AL_INICIAR", "1") == "1":
|
||||
for dominio in DOMINIOS:
|
||||
cola.solicitar(dominio)
|
||||
stop = threading.Event()
|
||||
signal.signal(signal.SIGTERM, lambda *_: stop.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: stop.set())
|
||||
log.info("indicadores en vivo: revisando cada %.0f s en %s", interval, cola.base)
|
||||
while True:
|
||||
for dominio in cola.atender():
|
||||
log.info("%s: %s", dominio, cola.estado()[dominio].get("estado"))
|
||||
if stop.wait(interval):
|
||||
break
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,39 @@
|
||||
"""El ciclo de indicadores de cada proyecto (CaCu, CaMa, TEA): del staging que deja
|
||||
la ingesta a los reportes que publica el tablero. Lo corre
|
||||
[Hamilton](https://hamilton.apache.org/).
|
||||
|
||||
Cada paso es una función de `ciclo.py`. Recibe el `Contexto` y, como parámetros,
|
||||
los pasos que deben correr antes; Hamilton arma el grafo con esos nombres. Los
|
||||
pasos no se pasan datos: todo va por la base, a través de los repositorios de
|
||||
Persistance (`ctx.repos`), así que cada uno se puede correr solo. El cálculo es
|
||||
del kit (`indicadores_kit`); aquí solo se decide qué se lee, a qué repositorio
|
||||
se le pasa y en qué orden.
|
||||
|
||||
migrar -> catalogos, registro, definiciones
|
||||
catalogos -> cargar
|
||||
cargar -> vistas, cohortes
|
||||
vistas + registro + definiciones -> calcular
|
||||
calcular -> observar, verificar_plata
|
||||
cohortes -> estimar (solo donde hay cohortes: hoy, CaCu)
|
||||
|
||||
uv run python -m webapi.orquestacion ciclo cacu --desde 2024 --hasta 2026
|
||||
uv run python -m webapi.orquestacion ciclo tea --desde 2025 --hasta 2025 --solo calcular
|
||||
uv run python -m webapi.orquestacion confirmar-riesgos cacu 3 --motivo "revisado por clínica"
|
||||
|
||||
El servicio `indicadores` (`webapi.indicadores_vivos`) corre este mismo ciclo,
|
||||
sin `migrar`, cada vez que una importación escribe datos.
|
||||
|
||||
Módulo | Qué hace
|
||||
---------------|---------
|
||||
`ciclo.py` | Los pasos
|
||||
`ejecutor.py` | `correr(ctx, solo=...)`: arma el driver de Hamilton y corre los pasos pedidos en orden
|
||||
`contexto.py` | El `Contexto`: proyecto, años, corte, parámetros y repositorios
|
||||
`repositorios.py` | `repositorios_de(proyecto)`: los repositorios de Persistance, por capa
|
||||
`proyecto.py` | Tipos de periodo y definiciones de cohorte de un proyecto
|
||||
`conexion.py` | Apunta Persistance a otra base en el mismo proceso (pruebas)
|
||||
"""
|
||||
|
||||
from webapi.orquestacion.contexto import Contexto
|
||||
from webapi.orquestacion.ejecutor import Paso, correr, pasos_de
|
||||
|
||||
__all__ = ["Contexto", "Paso", "correr", "pasos_de"]
|
||||
@@ -0,0 +1,63 @@
|
||||
"""La línea de comandos de la orquestación.
|
||||
|
||||
uv run python -m webapi.orquestacion ciclo cacu --desde 2024 --hasta 2026 [--corte 2026-01-01] [--permitir-sin-definir]
|
||||
uv run python -m webapi.orquestacion ciclo tea --desde 2025 --hasta 2025 --solo calcular
|
||||
uv run python -m webapi.orquestacion confirmar-riesgos cacu 3 --motivo "revisado por clínica" [--anular]
|
||||
|
||||
La base es la de `<PROYECTO>_DATABASE_URL`, como en Persistance.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.orquestacion.contexto import Contexto
|
||||
from webapi.orquestacion.ejecutor import correr
|
||||
|
||||
PROYECTOS = ("cacu", "cama", "tea")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> None:
|
||||
lector = argparse.ArgumentParser(prog="orquestacion", description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ordenes = lector.add_subparsers(dest="orden", required=True)
|
||||
c = ordenes.add_parser("ciclo", help="corre los pasos del proyecto en orden")
|
||||
c.add_argument("proyecto", choices=PROYECTOS)
|
||||
c.add_argument("--desde", type=int, required=True, help="primer año de periodos")
|
||||
c.add_argument("--hasta", type=int, required=True, help="último año de periodos")
|
||||
c.add_argument("--corte", type=date.fromisoformat, default=None)
|
||||
c.add_argument("--permitir-sin-definir", action="store_true")
|
||||
c.add_argument("--parametros", type=Path, default=None, help="otro archivo de parámetros (por omisión, el del kit)")
|
||||
c.add_argument("--solo", nargs="+", default=None, help="solo estos pasos")
|
||||
r = ordenes.add_parser("confirmar-riesgos", help="confirma (final) o anula un lote de riesgos (ADR-MD-008)")
|
||||
r.add_argument("proyecto", choices=PROYECTOS)
|
||||
r.add_argument("lote_id", type=int)
|
||||
r.add_argument("--motivo", required=True, help="por qué se confirma o se anula; queda en cada evaluación")
|
||||
r.add_argument("--anular", action="store_true", help="anular (entered-in-error) en vez de confirmar")
|
||||
args = lector.parse_args(argv)
|
||||
|
||||
if args.orden == "confirmar-riesgos":
|
||||
cambiadas = confirmar_riesgos(args.proyecto, args.lote_id, args.motivo, anular=args.anular)
|
||||
print(f"lote {args.lote_id}: {cambiadas} evaluaciones {'anuladas' if args.anular else 'confirmadas'}")
|
||||
return
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||
ctx = Contexto(args.proyecto, args.desde, args.hasta, args.corte, args.permitir_sin_definir, args.parametros)
|
||||
for paso in correr(ctx, solo=args.solo):
|
||||
print(f"{paso.nombre:20} {paso.segundos:6.1f} s")
|
||||
|
||||
|
||||
def confirmar_riesgos(proyecto: str, lote_id: int, motivo: str, *, anular: bool = False) -> int:
|
||||
"""Pasa las evaluaciones vigentes del lote a `final` (o a `entered-in-error`), cada una con una versión nueva.
|
||||
|
||||
No es un paso del ciclo: es una decisión de alguien, con su motivo (ADR-MD-008).
|
||||
"""
|
||||
from persistance.aristas.oro import ERROR, FINAL
|
||||
|
||||
from webapi.orquestacion.repositorios import repositorios_de
|
||||
|
||||
return repositorios_de(proyecto).oro.cohorte.cambiar_estado(lote_id, ERROR if anular else FINAL, motivo)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,231 @@
|
||||
"""Los pasos del ciclo de un proyecto, como funciones de Hamilton.
|
||||
|
||||
Cada paso recibe el `Contexto` y, como parámetros, los pasos que tienen que
|
||||
correr antes; de esos nombres sale el grafo. Los pasos no se pasan datos entre
|
||||
sí: todo va por la base, a través de `ctx.repos`, así que cada uno se puede
|
||||
correr solo (`ejecutor.correr(ctx, solo=[...])`).
|
||||
|
||||
El kit calcula (funciones puras, o funciones de una sesión) y los repositorios
|
||||
de `persistance.aristas` escriben, cada operación en una sesión (ADR-MD-005).
|
||||
Bronce lo escribe la ingesta, fuera del ciclo.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import date
|
||||
from functools import partial
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
from hamilton.function_modifiers import config
|
||||
from indicadores_kit.calidad.plata import verificar_plata as calidad_de_la_plata
|
||||
from indicadores_kit.esquema import ddl_de_vistas
|
||||
from indicadores_kit.oro.calculo import fecha_de_ultima_carga, medir_con_unidades
|
||||
from indicadores_kit.oro.cohortes.armado import armado_de, leer_marco, ultimo_armado
|
||||
from indicadores_kit.oro.cohortes.definicion import leer_definicion
|
||||
from indicadores_kit.plata.carga import carga_desde_staging, tablas_de_staging
|
||||
from indicadores_kit.plata.periodo_observacion import periodos_de_observacion
|
||||
from indicadores_kit.registry.apoyo import (
|
||||
CLAVE_DIM_FECHA_DESDE,
|
||||
filas_de_dim_fecha,
|
||||
grupos_de_edad_de,
|
||||
)
|
||||
from indicadores_kit.registry.catalogos import catalogo_desde_toml, ruta_de_catalogo
|
||||
from indicadores_kit.registry.measures import measures_de, rutas_de_measures
|
||||
from indicadores_kit.registry.parametros import (
|
||||
RUTA_PARAMETROS,
|
||||
leer_parametros,
|
||||
valores_del_archivo,
|
||||
)
|
||||
from indicadores_kit.registry.periodos import periodos_de_tipos
|
||||
from indicadores_kit.registry.publicacion import semillas_de
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
from persistance.aristas.plata import guardar_carga_en
|
||||
from sqlmodel import SQLModel, select
|
||||
|
||||
from webapi.orquestacion.contexto import Contexto
|
||||
from webapi.orquestacion.proyecto import definiciones_de_cohorte, tipos_de_periodo
|
||||
|
||||
registro_de_eventos = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def migrar(ctx: Contexto) -> str:
|
||||
"""`alembic upgrade head` del dominio, con el `alembic.ini` de Persistance."""
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
import persistance
|
||||
|
||||
ini = Path(persistance.__file__).parent / ctx.proyecto / "alembic.ini"
|
||||
raiz = logging.getLogger()
|
||||
manejadores, nivel = raiz.handlers[:], raiz.level
|
||||
estado = [(r, r.disabled) for r in logging.root.manager.loggerDict.values() if isinstance(r, logging.Logger)]
|
||||
command.upgrade(Config(str(ini)), "head")
|
||||
# `env.py` llama a `fileConfig`, que apaga los registradores ya creados y cambia los de la raíz.
|
||||
for registrador, apagado in estado:
|
||||
registrador.disabled = apagado
|
||||
raiz.handlers[:], raiz.level = manejadores, nivel
|
||||
return "head"
|
||||
|
||||
|
||||
def catalogos(migrar: str, ctx: Contexto) -> dict[str, int]:
|
||||
"""`core/catalogos/<proyecto>.toml` -> `cat_estudio`, `cat_resultado`, `cat_valor`: agrega, actualiza y retira; no borra."""
|
||||
catalogo = catalogo_desde_toml(ruta_de_catalogo(ctx.proyecto), tablas=tablas_de(ctx.proyecto))
|
||||
return ctx.repos.plata.catalogos.sincronizar(catalogo.estudios, catalogo.resultados, catalogo.valores)
|
||||
|
||||
|
||||
def cargar(catalogos: dict[str, int], ctx: Contexto) -> SQLModel:
|
||||
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c).
|
||||
|
||||
Incremental por la llave lógica de cada procedimiento (`guardar_carga_en`): repetir no cambia nada.
|
||||
"""
|
||||
tablas, staging = tablas_de(ctx.proyecto), tablas_de_staging(ctx.proyecto)
|
||||
|
||||
def leer(sesion):
|
||||
filas = {modelo.__tablename__: list(sesion.exec(select(modelo))) for modelo in staging}
|
||||
return carga_desde_staging(filas, proyecto=ctx.proyecto)
|
||||
|
||||
def escribir(sesion, datos):
|
||||
return guardar_carga_en(sesion, carga=tablas.Carga, persona=tablas.Persona, procedimiento=tablas.Procedimiento,
|
||||
observacion=tablas.Observacion, fuente=datos.fuente, personas=datos.personas,
|
||||
plata=datos.plata)
|
||||
|
||||
return ctx.repos.materializador.materializar(leer, escribir)
|
||||
|
||||
|
||||
def vistas(cargar: SQLModel, ctx: Contexto) -> int:
|
||||
"""Las vistas de versión vigente y las del proyecto: la DDL la arma el kit y la corre el repositorio."""
|
||||
return len(ctx.repos.plata.vistas.construir(ddl_de_vistas(ctx.proyecto)))
|
||||
|
||||
|
||||
def registro(migrar: str, ctx: Contexto) -> list[str]:
|
||||
"""`parametros.toml` (o `ctx.parametros`) -> `def_parametro` (se reemplaza), los periodos que falten en
|
||||
`dim_periodo` y las tablas de apoyo `dim_fecha` y `dim_grupo_edad` (se reemplazan; I-MD27).
|
||||
|
||||
El archivo se lee y valida antes de escribir. Los periodos no se reemplazan:
|
||||
los reportes guardados apuntan a ellos. `dim_fecha` va de `comun.dim_fecha.desde` al fin
|
||||
de `ctx.anio_fin` o del año del corte, el mayor; `dim_grupo_edad`, de los cortes de `<proyecto>.grupos_edad`, si el
|
||||
proyecto los tiene (TEA no).
|
||||
"""
|
||||
tablas, tipos = tablas_de(ctx.proyecto), tipos_de_periodo(ctx.proyecto)
|
||||
ruta = ctx.parametros or RUTA_PARAMETROS
|
||||
parametros = leer_parametros(ruta, tablas=tablas)
|
||||
periodos = periodos_de_tipos(tipos, ctx.anio_inicio, ctx.anio_fin, tablas=tablas)
|
||||
valores = valores_del_archivo(ruta)
|
||||
# Hasta el fin del último año del ciclo o del año del corte (por omisión, la última carga: hoy), el que sea mayor.
|
||||
hasta = date(max(ctx.anio_fin, (ctx.corte or date.today()).year), 12, 31)
|
||||
desde = date.fromisoformat(valores[CLAVE_DIM_FECHA_DESDE])
|
||||
grupos = grupos_de_edad_de(ctx.proyecto, valores, tablas=tablas)
|
||||
oro = ctx.repos.oro
|
||||
oro.parametros.reemplazar(parametros)
|
||||
oro.periodos.agregar_faltantes(periodos)
|
||||
if oro.fechas is not None and not _cubre(oro.fechas, desde, hasta):
|
||||
oro.fechas.reemplazar_en_bloque(filas_de_dim_fecha(valores, hasta, proyecto=ctx.proyecto))
|
||||
if oro.grupos_edad is not None and grupos is not None:
|
||||
oro.grupos_edad.reemplazar(grupos)
|
||||
return tipos
|
||||
|
||||
|
||||
def _cubre(fechas, desde: date, hasta: date) -> bool:
|
||||
"""`dim_fecha` ya es exactamente de `desde` a `hasta`: tiene los dos extremos y un día por fecha."""
|
||||
return (fechas.get(desde) is not None and fechas.get(hasta) is not None
|
||||
and fechas.count() == (hasta - desde).days + 1)
|
||||
|
||||
|
||||
def definiciones(migrar: str, ctx: Contexto) -> dict[str, int]:
|
||||
"""Las definiciones del proyecto -> el catálogo de publicación de §6f (`cat_measure*`, `cat_estrato*`).
|
||||
|
||||
Se sincroniza: lo que una unidad de un reporte usa no se borra (T-19b). Se leen y validan todos los
|
||||
archivos antes de escribir: uno inválido no toca las tablas.
|
||||
"""
|
||||
tablas, rutas = tablas_de(ctx.proyecto), rutas_de_measures(ctx.proyecto)
|
||||
semillas = semillas_de(ctx.proyecto, rutas, valores_del_archivo(ctx.parametros or RUTA_PARAMETROS), tablas=tablas)
|
||||
return {"definiciones": len(semillas.measures), **ctx.repos.oro.publicacion.sincronizar(semillas.por_capas())}
|
||||
|
||||
|
||||
def calcular(vistas: int, registro: list[str], definiciones: dict[str, int], ctx: Contexto) -> dict[str, list[int]]:
|
||||
"""Cada definición en cada periodo de cada tipo que publica, dentro de los años del contexto.
|
||||
|
||||
Cada reporte se mide y se guarda en una sola sesión (`CalculoRepository.calcular`).
|
||||
"""
|
||||
desde, hasta = date(ctx.anio_inicio, 1, 1), date(ctx.anio_fin + 1, 1, 1)
|
||||
calculo, tablas = ctx.repos.oro.calculo, tablas_de(ctx.proyecto)
|
||||
reportes = {}
|
||||
for nombre, medida in measures_de(ctx.proyecto).items():
|
||||
for tipo in medida.extension.publicacion.tipos_periodo:
|
||||
for periodo_id in calculo.periodos(tipo, desde, hasta):
|
||||
medir = partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas,
|
||||
corte=ctx.corte, permitir_sin_definir=ctx.permitir_sin_definir)
|
||||
reportes.setdefault(nombre, []).append(calculo.calcular(medir))
|
||||
return reportes
|
||||
|
||||
|
||||
# `observar` y `verificar_plata` van después de `calcular` para que una regla suya sin definir no lo detenga (I-MD1).
|
||||
def observar(cargar: SQLModel, registro: list[str], calcular: dict[str, list[int]], ctx: Contexto) -> int:
|
||||
"""`periodo_observacion`: desde y hasta cuándo hay datos de cada paciente."""
|
||||
return ctx.repos.plata.observacion.observar(partial(
|
||||
periodos_de_observacion, proyecto=ctx.proyecto, corte=ctx.corte,
|
||||
permitir_sin_definir=ctx.permitir_sin_definir,
|
||||
))
|
||||
|
||||
|
||||
def verificar_plata(cargar: SQLModel, catalogos: dict[str, int], calcular: dict[str, list[int]],
|
||||
ctx: Contexto) -> dict[str, int]:
|
||||
"""Lo que está mal en `procedimiento` y `observacion` (`plata.calidad`). Solo lee; avisa en el registro."""
|
||||
conteos = ctx.repos.plata.vinculos.verificar(partial(calidad_de_la_plata, tablas=tablas_de(ctx.proyecto)))
|
||||
for nombre, n in conteos.items():
|
||||
if n:
|
||||
registro_de_eventos.warning("%s, plata de dos tablas: %d %s.", ctx.proyecto, n, nombre.replace("_", " "))
|
||||
return conteos
|
||||
|
||||
|
||||
@config.when(con_cohortes=True)
|
||||
def cohortes(cargar: SQLModel, ctx: Contexto) -> dict[str, tuple[int, bool]]:
|
||||
"""Arma cada cohorte del proyecto con la ventana de los años del contexto y el corte (o la última carga)."""
|
||||
tablas = tablas_de(ctx.proyecto)
|
||||
tablas_cohorte = import_module(f"indicadores_kit.{ctx.proyecto}.tablas").COHORTES
|
||||
fuentes = import_module(f"indicadores_kit.{ctx.proyecto}.linea_de_tiempo").FUENTES_PLATA
|
||||
inicio, fin = date(ctx.anio_inicio, 1, 1), date(ctx.anio_fin + 1, 1, 1)
|
||||
|
||||
def armado(definicion, sesion):
|
||||
corte = ctx.corte or fecha_de_ultima_carga(sesion, tablas)
|
||||
return armado_de(sesion, definicion, inicio, fin, corte, tablas=tablas, cohortes=tablas_cohorte,
|
||||
fuentes=fuentes)
|
||||
|
||||
armados = {}
|
||||
for ruta in definiciones_de_cohorte(ctx.proyecto):
|
||||
definicion = leer_definicion(ruta)
|
||||
armados[definicion.url] = ctx.repos.oro.cohorte.armar(partial(armado, definicion))
|
||||
return armados
|
||||
|
||||
|
||||
@config.when(con_cohortes=True)
|
||||
def estimar(cohortes: dict[str, tuple[int, bool]], ctx: Contexto) -> dict[str, tuple[int, bool]]:
|
||||
"""El riesgo de los miembros del armado más reciente de cada cohorte que tiene estimador (ADR-MD-008).
|
||||
|
||||
Lee el marco ancho del armado (`leer_marco`) en una sesión de lectura, se lo da al estimador
|
||||
(`ctx.estimadores[url]`: `estimar(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como
|
||||
un lote `preliminary` (`CohorteRepository.guardar_lote`). Estimar lo mismo otra vez no duplica.
|
||||
Devuelve, por cohorte, (`lote_id`, si es nuevo). Confirmar o anular un lote es la orden
|
||||
`confirmar-riesgos`, no este paso.
|
||||
"""
|
||||
tablas_cohorte = import_module(f"indicadores_kit.{ctx.proyecto}.tablas").COHORTES
|
||||
lotes = {}
|
||||
for ruta in definiciones_de_cohorte(ctx.proyecto):
|
||||
definicion = leer_definicion(ruta)
|
||||
estimador = ctx.estimadores.get(definicion.url)
|
||||
if estimador is None:
|
||||
continue
|
||||
|
||||
def marco(sesion, definicion=definicion):
|
||||
armado_id = ultimo_armado(sesion, definicion.url, cohortes=tablas_cohorte)
|
||||
return armado_id, None if armado_id is None else leer_marco(sesion, armado_id, definicion,
|
||||
cohortes=tablas_cohorte)
|
||||
|
||||
armado_id, ancho = ctx.repos.oro.cohorte.leer(marco)
|
||||
if armado_id is None:
|
||||
continue
|
||||
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
|
||||
lotes[definicion.url] = ctx.repos.oro.cohorte.guardar_lote(
|
||||
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
|
||||
)
|
||||
return lotes
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Apuntar Persistance a la base de un proyecto. Es lo que hace `<PROYECTO>_DATABASE_URL`.
|
||||
|
||||
Persistance lee su configuración al importarse; para cambiar de base en el
|
||||
mismo proceso (pruebas, dev-data) se cambia el ajuste en memoria y se limpia la
|
||||
caché del motor. Igual que `dev_data.ingesta.apuntar`.
|
||||
"""
|
||||
|
||||
from persistance.settings import settings
|
||||
|
||||
from persistance import db
|
||||
|
||||
|
||||
def apuntar(proyecto: str, url: str) -> None:
|
||||
motor = getattr(db, f"get_{proyecto}_engine")
|
||||
if motor.cache_info().currsize:
|
||||
motor().dispose()
|
||||
setattr(settings, f"{proyecto}_database_url", url)
|
||||
motor.cache_clear()
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Lo que recibe cada paso del ciclo."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Contexto:
|
||||
"""Lo que recibe un paso: el proyecto y las opciones del ciclo.
|
||||
|
||||
`anio_inicio` y `anio_fin` son los años de los periodos que se registran y
|
||||
calculan. `corte` es la fecha hasta la que llegan los datos; sin ella, cada
|
||||
paso del kit toma la de la última carga. `permitir_sin_definir` deja correr
|
||||
con parámetros que nadie ha decidido: hay que pedirlo a propósito, como en
|
||||
el kit. `parametros` es el archivo de parámetros que carga `registro`; sin
|
||||
él, el `parametros.toml` del kit. `repos` es todo lo que el paso usa
|
||||
para tocar la base: nunca abre una sesión por su cuenta (`repositorios.py`).
|
||||
"""
|
||||
|
||||
proyecto: str
|
||||
anio_inicio: int
|
||||
anio_fin: int
|
||||
corte: date | None = None
|
||||
permitir_sin_definir: bool = False
|
||||
parametros: Path | None = None
|
||||
# Los estimadores de riesgo por cohorte (`cohorte_url` -> objeto con `estimar(columnas, filas)`, `procedencia()`
|
||||
# y `desenlace`; ADR-MD-008). Sin ellos, el paso `estimar` no hace nada.
|
||||
estimadores: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False)
|
||||
# Los repositorios del proyecto (`repositorios.Repositorios`); el ejecutor los pone si faltan.
|
||||
repos: Any = field(default=None, compare=False, repr=False)
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Corre los pasos de un proyecto (`ciclo.py`) con Hamilton.
|
||||
|
||||
Si un paso falla, los anteriores quedan hechos (cada operación de un
|
||||
repositorio es su propia transacción) y se puede volver a correr: los pasos no
|
||||
duplican. Si el contexto no trae repositorios, se le ponen los de Persistance
|
||||
para el proyecto (`repositorios_de`).
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import Any
|
||||
|
||||
from hamilton import driver
|
||||
from hamilton.execution.graph_functions import topologically_sort_nodes
|
||||
from hamilton.lifecycle import NodeExecutionHook
|
||||
|
||||
from webapi.orquestacion import ciclo
|
||||
from webapi.orquestacion.contexto import Contexto
|
||||
from webapi.orquestacion.proyecto import definiciones_de_cohorte
|
||||
from webapi.orquestacion.repositorios import repositorios_de
|
||||
|
||||
registro = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Paso:
|
||||
"""Lo que dejó un paso: su resumen y cuánto tardó."""
|
||||
|
||||
nombre: str
|
||||
resumen: Any
|
||||
segundos: float
|
||||
|
||||
|
||||
class _Bitacora(NodeExecutionHook):
|
||||
"""Anota cada paso que corre, en el orden en que corre."""
|
||||
|
||||
def __init__(self):
|
||||
self.pasos: list[Paso] = []
|
||||
self._inicio = 0.0
|
||||
|
||||
def run_before_node_execution(self, **_):
|
||||
self._inicio = time.monotonic()
|
||||
|
||||
def run_after_node_execution(self, *, node_name: str, result: Any, success: bool, **_):
|
||||
if success:
|
||||
self.pasos.append(Paso(node_name, result, time.monotonic() - self._inicio))
|
||||
registro.info("%s: %s en %.1f s", node_name, _corto(result), self.pasos[-1].segundos)
|
||||
|
||||
|
||||
def _driver(proyecto: str, *adaptadores) -> driver.Driver:
|
||||
return (driver.Builder()
|
||||
.with_modules(ciclo)
|
||||
.with_config({"con_cohortes": bool(definiciones_de_cohorte(proyecto))})
|
||||
.with_adapters(*adaptadores)
|
||||
.build())
|
||||
|
||||
|
||||
def _en_orden(dr: driver.Driver) -> list[str]:
|
||||
return [n.name for n in topologically_sort_nodes(list(dr.graph.get_nodes())) if not n.user_defined]
|
||||
|
||||
|
||||
def pasos_de(proyecto: str) -> list[str]:
|
||||
"""Los pasos del proyecto en un orden que respeta sus dependencias (los de cohortes, solo donde hay definiciones)."""
|
||||
return _en_orden(_driver(proyecto))
|
||||
|
||||
|
||||
def correr(ctx: Contexto, *, solo: Sequence[str] | None = None) -> list[Paso]:
|
||||
"""Corre el ciclo del proyecto en el orden de sus dependencias. `solo`: los pasos a correr; los demás no corren.
|
||||
|
||||
Los pasos que no corren se le dan a Hamilton ya resueltos. Así entre dos pedidos puede no quedar dependencia
|
||||
(`cargar` y `calcular` sin `vistas`), por eso se le piden en el orden del grafo completo.
|
||||
"""
|
||||
if ctx.repos is None:
|
||||
ctx = replace(ctx, repos=repositorios_de(ctx.proyecto))
|
||||
bitacora = _Bitacora()
|
||||
dr = _driver(ctx.proyecto, bitacora)
|
||||
todos = _en_orden(dr)
|
||||
pedidos = [p for p in todos if solo is None or p in solo]
|
||||
dr.execute(pedidos, inputs={"ctx": ctx}, overrides={p: None for p in todos if p not in pedidos})
|
||||
return bitacora.pasos
|
||||
|
||||
|
||||
def _corto(resumen: Any) -> str:
|
||||
if isinstance(resumen, dict):
|
||||
return f"{len(resumen)} elementos"
|
||||
return str(resumen)
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Lo que el ciclo necesita saber de las definiciones del kit para un proyecto."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from indicadores_kit.oro.cohortes.definicion import RAIZ
|
||||
from indicadores_kit.registry.measures import measures_de
|
||||
|
||||
|
||||
def tipos_de_periodo(proyecto: str) -> list[str]:
|
||||
"""Los tipos de periodo que publican las definiciones del proyecto (semestre y, en CaCu y CaMa, mes)."""
|
||||
return sorted({t for m in measures_de(proyecto).values() for t in m.extension.publicacion.tipos_periodo})
|
||||
|
||||
|
||||
def definiciones_de_cohorte(proyecto: str) -> list[Path]:
|
||||
"""Los TOML de cohortes que el ciclo arma (`<proyecto>/cohortes/*.toml`): hoy solo CaCu (vigilancia). Las de `cohortes/propuestas/` no (T-21h)."""
|
||||
return sorted((RAIZ / proyecto / "cohortes").glob("*.toml"))
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user