Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| df921f13cd |
@@ -1,10 +1,2 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
*.egg-info/
|
||||
.env
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
# Build context is the repo root (see docker-compose.yml) so the sibling
|
||||
# packages Core/, Persistance/, Extraction/ and models/
|
||||
# can be copied.
|
||||
FROM python:3.12-slim
|
||||
|
||||
# Tesseract (with Spanish data) for scanned documents; pytesseract only wraps the binary.
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
tesseract-ocr tesseract-ocr-spa \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.7.9 /uv /uvx /bin/
|
||||
|
||||
WORKDIR /app
|
||||
COPY Core/ Core/
|
||||
COPY Persistance/ Persistance/
|
||||
COPY Extraction/ Extraction/
|
||||
COPY models/ models/
|
||||
COPY WebApi/ WebApi/
|
||||
|
||||
# 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
|
||||
# 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.recomputation).
|
||||
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
|
||||
|
||||
EXPOSE 5000
|
||||
ENTRYPOINT ["/app/WebApi/docker-entrypoint.sh"]
|
||||
@@ -1,99 +0,0 @@
|
||||
# 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 y `models` para las cohortes. Los indicadores se definen en dbt (`Transformation`) y se
|
||||
responden bajo pedido (`/<dominio>/indicadores`); `orchestration` carga la plata, las tablas de
|
||||
referencia y las vistas de dbt.
|
||||
|
||||
## Estructura
|
||||
|
||||
```
|
||||
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)
|
||||
├── recomputation.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.recomputation # 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.
|
||||
@@ -1,35 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
mkdir -p /data
|
||||
|
||||
# SQLite won't create a missing parent directory for its database file.
|
||||
for url in "$CACU_DATABASE_URL" "$CAMA_DATABASE_URL" "$TEA_DATABASE_URL" "$GOVERNANCE_DATABASE_URL"; do
|
||||
case "$url" in
|
||||
sqlite:///*) mkdir -p "$(dirname "${url#sqlite:///}")" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# The live indicator worker (webapi.recomputation) shares the image; the
|
||||
# API container runs the migrations, so the worker starts after it.
|
||||
if [ "$1" = "indicadores" ]; then
|
||||
cd /app/WebApi
|
||||
exec uv run --no-sync python -m webapi.recomputation
|
||||
fi
|
||||
|
||||
cd /app/WebApi
|
||||
# --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.
|
||||
exec uv run --no-sync gunicorn \
|
||||
--bind "0.0.0.0:${PORT}" \
|
||||
--workers "${WEBAPI_WORKERS:-2}" \
|
||||
--timeout "${WEBAPI_TIMEOUT:-600}" \
|
||||
--access-logfile - \
|
||||
"webapi:create_app()"
|
||||
@@ -1,9 +0,0 @@
|
||||
import os
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 5000 is taken by AirPlay on macOS.
|
||||
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5050)))
|
||||
+11
-42
@@ -1,48 +1,17 @@
|
||||
[project]
|
||||
name = "webapi"
|
||||
version = "0.1.0"
|
||||
description = "ISSSTELEON REST API: data import, indicators, import log and model governance for CaCu, CaMa and TEA."
|
||||
version = "0.0.0"
|
||||
description = "FastAPI: FHIR routes, control routes, the auth dependency."
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"flask>=3.0",
|
||||
"persistance",
|
||||
"models[export]",
|
||||
"extraction",
|
||||
"apache-hamilton>=1.90",
|
||||
"pandas>=2.0",
|
||||
"openpyxl>=3.1",
|
||||
"sqlalchemy>=2.0",
|
||||
"pydantic>=2.0",
|
||||
"pdfplumber>=0.11",
|
||||
"pytesseract>=0.3.10",
|
||||
"Pillow>=10.0",
|
||||
"flask-cors>=4.0",
|
||||
"gunicorn>=23.0",
|
||||
"sqlglot>=25.0",
|
||||
"rapidfuzz>=3.9",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
sql-drivers = [
|
||||
"psycopg2-binary>=2.9",
|
||||
"pymysql>=1.1",
|
||||
"pymssql>=2.3",
|
||||
]
|
||||
|
||||
[tool.uv.sources]
|
||||
persistance = { path = "../Persistance", editable = true }
|
||||
models = { path = "../models", editable = true }
|
||||
extraction = { path = "../Extraction", editable = true }
|
||||
dependencies = ["core", "persistance", "fastapi[standard]", "dagster-graphql"]
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
requires = ["uv_build>=0.12,<0.13"]
|
||||
build-backend = "uv_build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["webapi"]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=8.0.0",
|
||||
"reportlab>=4.0",
|
||||
]
|
||||
[tool.uv.build-backend]
|
||||
module-name = "webapi"
|
||||
module-root = ""
|
||||
[tool.uv.sources]
|
||||
core = { workspace = true }
|
||||
persistance = { workspace = true }
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
"""Shared test wiring.
|
||||
|
||||
`persistance.settings.settings` is a module-level singleton and the
|
||||
`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.orchestration`:
|
||||
una base del dominio por prueba, migrada por el paso `migrate`, 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 webapi.orchestration.reference.rules import RUTA_PARAMETROS
|
||||
from webapi.orchestration import Context, run
|
||||
from webapi.orchestration.connection import point_to
|
||||
from webapi.orchestration.repositories import repositories_of
|
||||
|
||||
# Tests use throwaway SQLite files as "arbitrary SQL sources"; production
|
||||
# excludes sqlite by default (see webapi.imports.connectors.sql_policy).
|
||||
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: Context
|
||||
dominio: object
|
||||
motor: object
|
||||
|
||||
def run(self, *pasos: str, **cambios) -> dict:
|
||||
"""Corre estos pasos (en el orden del ciclo) con el contexto cambiado. Devuelve el resumen de cada una."""
|
||||
return {p.name: p.summary for p in run(replace(self.ctx, **cambios), only=pasos)}
|
||||
|
||||
def staging(self):
|
||||
"""Una sesión sobre la base, para cambiar el staging como lo haría la ingesta."""
|
||||
return Session(self.motor)
|
||||
|
||||
|
||||
def base_de(proyecto: str, carpeta, datos=None) -> Base:
|
||||
"""A migrated domain database in `carpeta`, with the kit's synthetic staging or, with `datos`, what it inserts."""
|
||||
url = f"sqlite:///{carpeta / f'{proyecto}.db'}"
|
||||
point_to(proyecto, url)
|
||||
manifest = os.environ.get("DBT_MANIFEST")
|
||||
ctx = Context(proyecto, ANIO, ANIO, dbt_manifest=Path(manifest) if manifest else None, repos=repositories_of(proyecto))
|
||||
run(ctx, only=["migrate"])
|
||||
motor = create_engine(url)
|
||||
with Session(motor) as sesion:
|
||||
(datos or import_module(f"staging.{proyecto}").insertar)(sesion)
|
||||
sesion.commit()
|
||||
return Base(proyecto, ctx, import_module(f"persistance.{proyecto}"), motor)
|
||||
|
||||
|
||||
@pytest.fixture(params=["cacu", "cama"])
|
||||
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")
|
||||
def wire_domain():
|
||||
"""Factory fixture: `wire_domain("cacu")` points the domain at a fresh temp
|
||||
SQLite file for this module and returns its path. Temp files are removed
|
||||
when the module finishes."""
|
||||
created_paths: list[str] = []
|
||||
|
||||
def _wire(domain: str) -> str:
|
||||
db_path = tempfile.NamedTemporaryFile(suffix=".db", delete=False).name
|
||||
url = f"sqlite:///{db_path}"
|
||||
os.environ[f"{domain.upper()}_DATABASE_URL"] = url
|
||||
|
||||
from persistance import db as persistance_db
|
||||
from persistance import settings as persistance_settings
|
||||
|
||||
setattr(persistance_settings.settings, f"{domain}_database_url", url)
|
||||
getattr(persistance_db, f"get_{domain}_engine").cache_clear()
|
||||
created_paths.append(db_path)
|
||||
_migrate(domain)
|
||||
return db_path
|
||||
|
||||
yield _wire
|
||||
|
||||
for path in created_paths:
|
||||
os.unlink(path)
|
||||
|
||||
|
||||
def _migrate(domain: str) -> None:
|
||||
"""Builds the schema with the Alembic migrations rather than
|
||||
`metadata.create_all`, so tests run against the deployed schema and a
|
||||
broken migration fails the suite."""
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
import persistance
|
||||
|
||||
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 the cycle loaded from the kit's synthetic staging."""
|
||||
carpeta = tmp_path_factory.mktemp(proyecto)
|
||||
base = base_de(proyecto, carpeta)
|
||||
base.run("catalogs", "load", "views", "registry", "definitions", "event_models", allow_undecided=True)
|
||||
try:
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as cliente:
|
||||
yield cliente
|
||||
finally:
|
||||
base.motor.dispose()
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
# Casos de CACU_CONFIRMACION_CITOLOGIA (confirmación por biopsia según resultado citológico, C2).
|
||||
# La unidad es la paciente cuya última citología válida del periodo es de alto grado
|
||||
# (`cacu.citologia_alto_grado`); la última válida es la de EU7 (`cacu.calidad_insatisfactoria`).
|
||||
# Cada categoría es `cat:<grado>` de la biopsia más grave que originó esa citología (ligada por
|
||||
# `cit_id`); sin biopsia reportada al corte, `cat:SIN_BIOPSIA`; con biopsia sin grado, `cat:SIN_DATO`.
|
||||
# `estratos` dice el valor de cada paciente en `citologia_alto_grado`: la fila del panel. Sin `corte`,
|
||||
# es el día de la carga del caso (2026-01-01).
|
||||
|
||||
measure = "cacu/CACU_CONFIRMACION_CITOLOGIA"
|
||||
|
||||
[[caso]]
|
||||
nombre = "una paciente con ASC-H y biopsia LIEAG cuenta en LIEAG dentro de la fila ASC-H"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "ASC-H" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "LIEAG" },
|
||||
{ tabla = "citologiacervical", cit_id = 2, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 2, pac_id = 2, cit_id = 2, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "NORMAL" },
|
||||
]
|
||||
espera."2025-S1" = { "cat:LIEAG" = 1, "cat:NORMAL" = 1 }
|
||||
unidades."2025-S1" = { "cat:LIEAG" = ["1"], "cat:NORMAL" = ["2"] } # la 2 es un falso positivo de la fila LIEAG
|
||||
estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H", "2" = "LIEAG" }
|
||||
|
||||
[[caso]]
|
||||
nombre = "la última citología válida manda y no la peor"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "CIS" },
|
||||
{ tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "ASC-H" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 2, bx_fecha_reporte = 2025-06-01, bx_cin_grado = "LIEBG" },
|
||||
]
|
||||
espera."2025-S1" = { "cat:LIEBG" = 1 }
|
||||
estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H" }
|
||||
|
||||
[[caso]]
|
||||
nombre = "con varias biopsias de la toma cuenta la más grave y no la más reciente"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" },
|
||||
{ tabla = "biopsiacervical", bx_id = 2, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-04-01, bx_cin_grado = "LIEBG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 3, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-05-01, bx_cin_grado = "NORMAL" },
|
||||
]
|
||||
espera."2025-S1" = { "cat:CIS" = 1, "cat:LIEBG" = 0, "cat:NORMAL" = 0 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "una biopsia con grado gana a una sin grado; solo sin grado es sin dato"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "NORMAL" },
|
||||
{ tabla = "biopsiacervical", bx_id = 2, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-04-01 },
|
||||
{ tabla = "citologiacervical", cit_id = 2, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "CIS" },
|
||||
{ tabla = "biopsiacervical", bx_id = 3, pac_id = 2, cit_id = 2, bx_fecha_reporte = 2025-03-01 },
|
||||
]
|
||||
espera."2025-S1" = { "cat:NORMAL" = 1, "cat:SIN_DATO" = 1, "cat:SIN_BIOPSIA" = 0 }
|
||||
unidades."2025-S1" = { "cat:SIN_DATO" = ["2"] }
|
||||
|
||||
[[caso]]
|
||||
nombre = "una biopsia reportada después del corte todavía no existe: sin biopsia aún"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "LIEAG" },
|
||||
]
|
||||
corte = 2025-07-31
|
||||
espera."2025-S1" = { "cat:SIN_BIOPSIA" = 1, "cat:LIEAG" = 0 }
|
||||
estratos."2025-S1".citologia_alto_grado = { "1" = "LIEAG" }
|
||||
|
||||
[[caso]]
|
||||
nombre = "el día del corte la biopsia ya existe"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "LIEAG" },
|
||||
]
|
||||
corte = 2025-08-01
|
||||
espera."2025-S1" = { "cat:SIN_BIOPSIA" = 0, "cat:LIEAG" = 1 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "una biopsia de otra toma no cuenta"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" },
|
||||
{ tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "ASC-H" },
|
||||
{ tabla = "biopsiacervical", bx_id = 2, pac_id = 1, bx_fecha_reporte = 2025-06-01, bx_cin_grado = "LIEAG" },
|
||||
]
|
||||
espera."2025-S1" = { "cat:SIN_BIOPSIA" = 1, "cat:CIS" = 0, "cat:LIEAG" = 0 }
|
||||
estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H" }
|
||||
|
||||
[[caso]]
|
||||
nombre = "una insatisfactoria posterior no es la última válida"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "LIEAG" },
|
||||
{ tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "INSATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "NORMAL" },
|
||||
]
|
||||
espera."2025-S1" = { "cat:LIEAG" = 1 }
|
||||
estratos."2025-S1".citologia_alto_grado = { "1" = "LIEAG" }
|
||||
|
||||
[[caso]]
|
||||
nombre = "una paciente cuya última citología es NORMAL no entra aunque antes tuviera LIEAG"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" },
|
||||
{ tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "NORMAL" },
|
||||
{ tabla = "citologiacervical", cit_id = 3, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "ASC-US" },
|
||||
]
|
||||
espera."2025-S1" = { "cat:CIS" = 0, "cat:SIN_BIOPSIA" = 0, "cat:NORMAL" = 0 }
|
||||
estratos."2025-S1".citologia_alto_grado = {}
|
||||
|
||||
[[caso]]
|
||||
nombre = "la citología cuenta en el periodo de su toma y no en el del reporte de la biopsia"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-20, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-25, cit_celulas_escamosas = "CIS" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "CARCINOMA" },
|
||||
]
|
||||
espera."2025-S1" = { "cat:CARCINOMA" = 1 }
|
||||
espera."2025-S2" = { "cat:CARCINOMA" = 0 }
|
||||
estratos."2025-S1".citologia_alto_grado = { "1" = "CIS" }
|
||||
-87
@@ -1,87 +0,0 @@
|
||||
# Casos de CACU_RIESGO_BANDA (pacientes en vigilancia por banda de riesgo, C2). PROPUESTA (MD-Q5).
|
||||
# Cuenta a las miembros del armado del lote vigente (el mayor con alguna evaluación `final` al
|
||||
# horizonte) con fecha índice en el periodo, por la banda de la versión más reciente de su
|
||||
# evaluación. Con los parámetros de `parametros.toml`: BAJO < 0.04 <= INTERMEDIO < 0.25 <= ALTO,
|
||||
# horizonte 0. `cat:SIN_DATO`: sin evaluación `final` en el lote.
|
||||
|
||||
measure = "cacu/CACU_RIESGO_BANDA"
|
||||
|
||||
[plantillas]
|
||||
armado = [
|
||||
{ tabla = "cohorte_armado", armado_id = 1, url = "cacu/cohorte_vigilancia", version = "0.1.0", definicion_sha = "d", reglas_sha = "r", parametros = "{}", datos_as_of = 2025-12-31, huella = "a1", marco_sha = "m1", n_miembros = 4, armado_en = 2026-01-01T00:00:00Z },
|
||||
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 1, fecha_indice = 2025-02-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "1" },
|
||||
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 2, fecha_indice = 2025-03-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "2" },
|
||||
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 3, fecha_indice = 2025-04-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "3" },
|
||||
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 4, fecha_indice = 2025-08-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "4" },
|
||||
]
|
||||
lote_final = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 3, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, horizonte_anios = 0.0, probabilidad = 0.1, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 4, horizonte_anios = 0.0, probabilidad = 0.3, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
|
||||
[[caso]]
|
||||
nombre = "cada paciente en la banda de su riesgo; sin evaluación es sin dato"
|
||||
incluye = ["armado", "lote_final"]
|
||||
filas = []
|
||||
espera."2025-S1" = { "cat:BAJO" = 1, "cat:INTERMEDIO" = 1, "cat:ALTO" = 0, "cat:SIN_DATO" = 1 }
|
||||
unidades."2025-S1" = { "cat:SIN_DATO" = [3] }
|
||||
|
||||
[[caso]]
|
||||
nombre = "el periodo es el de la fecha índice"
|
||||
incluye = ["armado", "lote_final"]
|
||||
filas = []
|
||||
espera."2025-S2" = { "cat:ALTO" = 1, "cat:BAJO" = 0 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "los cortes son parámetros"
|
||||
incluye = ["armado", "lote_final"]
|
||||
filas = []
|
||||
parametros = { "comun.riesgos.corte_intermedio" = 0.01, "comun.riesgos.corte_alto" = 0.05 }
|
||||
espera."2025-S1" = { "cat:BAJO" = 0, "cat:INTERMEDIO" = 1, "cat:ALTO" = 1 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "un lote preliminar más nuevo no desplaza al vigente"
|
||||
incluye = ["armado", "lote_final"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 2, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "2", mlflow_run_id = "sin-mlflow", modelo_sha = "s2", desenlace = "c", evaluado_en = 2026-02-01T00:00:00Z, n_evaluaciones = 1, huella = "l2" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 2, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.9, version = 1, estado = "preliminary", registrado_en = 2026-02-01T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 1, "cat:ALTO" = 0 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "una evaluación anulada en su versión 2 queda sin dato"
|
||||
incluye = ["armado", "lote_final"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, horizonte_anios = 0.0, probabilidad = 0.1, version = 2, estado = "entered-in-error", motivo = "caso", registrado_en = 2026-01-03T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:INTERMEDIO" = 0, "cat:SIN_DATO" = 2 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "una evaluación a otro horizonte no cuenta"
|
||||
incluye = ["armado"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 1.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "sin lote confirmado no hay población"
|
||||
incluye = ["armado"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "preliminary", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "el lote de otra cohorte no cuenta"
|
||||
filas = [
|
||||
{ tabla = "cohorte_armado", armado_id = 1, url = "cacu/otra", version = "0.1.0", definicion_sha = "d", reglas_sha = "r", parametros = "{}", datos_as_of = 2025-12-31, huella = "a1", marco_sha = "m1", n_miembros = 1, armado_en = 2026-01-01T00:00:00Z },
|
||||
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 1, fecha_indice = 2025-02-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "1" },
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0 }
|
||||
-1264
File diff suppressed because it is too large
Load Diff
-387
@@ -1,387 +0,0 @@
|
||||
[
|
||||
{
|
||||
"pac_id": "1",
|
||||
"fecha": "2025-02-03",
|
||||
"clase": "orden",
|
||||
"tipo": "orden",
|
||||
"codigo": "orden",
|
||||
"valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "ordenesestudio",
|
||||
"fuente_id": "1"
|
||||
},
|
||||
{
|
||||
"pac_id": "1",
|
||||
"fecha": "2025-02-10",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "SATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "1"
|
||||
},
|
||||
{
|
||||
"pac_id": "1",
|
||||
"fecha": "2025-02-20",
|
||||
"clase": "medicion",
|
||||
"tipo": "bethesda",
|
||||
"codigo": "bethesda",
|
||||
"valor_codigo": "NEGATIVO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "1"
|
||||
},
|
||||
{
|
||||
"pac_id": "1",
|
||||
"fecha": "2025-03-01",
|
||||
"clase": "diagnostico",
|
||||
"tipo": "nota_medica",
|
||||
"codigo": "nota_medica",
|
||||
"valor_codigo": "N871",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "notamedica",
|
||||
"fuente_id": "3"
|
||||
},
|
||||
{
|
||||
"pac_id": "1",
|
||||
"fecha": "2025-10-02",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "SATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "9"
|
||||
},
|
||||
{
|
||||
"pac_id": "2",
|
||||
"fecha": "2025-03-05",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "INSATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "2"
|
||||
},
|
||||
{
|
||||
"pac_id": "2",
|
||||
"fecha": "2025-09-15",
|
||||
"clase": "diagnostico",
|
||||
"tipo": "nota_medica",
|
||||
"codigo": "nota_medica",
|
||||
"valor_codigo": "C53",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "notamedica",
|
||||
"fuente_id": "4"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2024-12-01",
|
||||
"clase": "diagnostico",
|
||||
"tipo": "nota_medica",
|
||||
"codigo": "nota_medica",
|
||||
"valor_codigo": "C539",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "notamedica",
|
||||
"fuente_id": "2"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-01-20",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "INSATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "3"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-02-01",
|
||||
"clase": "medicion",
|
||||
"tipo": "bethesda",
|
||||
"codigo": "bethesda",
|
||||
"valor_codigo": "ASC-US",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "3"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-02-01",
|
||||
"clase": "medicion",
|
||||
"tipo": "vph",
|
||||
"codigo": "vph",
|
||||
"valor_codigo": "POSITIVO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "3"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-02-01",
|
||||
"clase": "medicion",
|
||||
"tipo": "vph_genotipo_16_18",
|
||||
"codigo": "vph_genotipo_16_18",
|
||||
"valor_codigo": null,
|
||||
"valor_numerico": "1.0",
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "3"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-04-10",
|
||||
"clase": "orden",
|
||||
"tipo": "orden",
|
||||
"codigo": "orden",
|
||||
"valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "ordenesestudio",
|
||||
"fuente_id": "2"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-04-15",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "SATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "4"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-04-25",
|
||||
"clase": "medicion",
|
||||
"tipo": "bethesda",
|
||||
"codigo": "bethesda",
|
||||
"valor_codigo": "LIEBG",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "4"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-04-25",
|
||||
"clase": "medicion",
|
||||
"tipo": "vph",
|
||||
"codigo": "vph",
|
||||
"valor_codigo": "POSITIVO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "4"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-04-25",
|
||||
"clase": "medicion",
|
||||
"tipo": "vph_genotipo_16_18",
|
||||
"codigo": "vph_genotipo_16_18",
|
||||
"valor_codigo": null,
|
||||
"valor_numerico": "0.0",
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "4"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-05-01",
|
||||
"clase": "orden",
|
||||
"tipo": "orden",
|
||||
"codigo": "orden",
|
||||
"valor_codigo": null,
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "biopsiacervical",
|
||||
"fuente_id": "1"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-05-20",
|
||||
"clase": "medicion",
|
||||
"tipo": "biopsia",
|
||||
"codigo": "cin",
|
||||
"valor_codigo": "CIN1",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "biopsiacervical",
|
||||
"fuente_id": "1"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-05-30",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "SATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "5"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-06-09",
|
||||
"clase": "medicion",
|
||||
"tipo": "bethesda",
|
||||
"codigo": "bethesda",
|
||||
"valor_codigo": "NEGATIVO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "5"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-06-25",
|
||||
"clase": "orden",
|
||||
"tipo": "orden",
|
||||
"codigo": "orden",
|
||||
"valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "ordenesestudio",
|
||||
"fuente_id": "3"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-07-01",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "SATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "6"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-07-11",
|
||||
"clase": "medicion",
|
||||
"tipo": "bethesda",
|
||||
"codigo": "bethesda",
|
||||
"valor_codigo": "LIEAG",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "6"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-07-11",
|
||||
"clase": "medicion",
|
||||
"tipo": "vph",
|
||||
"codigo": "vph",
|
||||
"valor_codigo": "POSITIVO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "6"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-07-11",
|
||||
"clase": "medicion",
|
||||
"tipo": "vph_genotipo_16_18",
|
||||
"codigo": "vph_genotipo_16_18",
|
||||
"valor_codigo": null,
|
||||
"valor_numerico": "1.0",
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "6"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-07-15",
|
||||
"clase": "orden",
|
||||
"tipo": "orden",
|
||||
"codigo": "orden",
|
||||
"valor_codigo": null,
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "biopsiacervical",
|
||||
"fuente_id": "2"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-08-01",
|
||||
"clase": "medicion",
|
||||
"tipo": "biopsia",
|
||||
"codigo": "cin",
|
||||
"valor_codigo": "CIN2",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "biopsiacervical",
|
||||
"fuente_id": "2"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-08-10",
|
||||
"clase": "diagnostico",
|
||||
"tipo": "nota_medica",
|
||||
"codigo": "nota_medica",
|
||||
"valor_codigo": "D069",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "notamedica",
|
||||
"fuente_id": "1"
|
||||
},
|
||||
{
|
||||
"pac_id": "5",
|
||||
"fecha": "2025-08-12",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "SATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "7"
|
||||
},
|
||||
{
|
||||
"pac_id": "5",
|
||||
"fecha": "2025-08-22",
|
||||
"clase": "medicion",
|
||||
"tipo": "bethesda",
|
||||
"codigo": "bethesda",
|
||||
"valor_codigo": "NEGATIVO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "7"
|
||||
},
|
||||
{
|
||||
"pac_id": "5",
|
||||
"fecha": "2025-08-22",
|
||||
"clase": "medicion",
|
||||
"tipo": "vph",
|
||||
"codigo": "vph",
|
||||
"valor_codigo": "NEGATIVO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "7"
|
||||
},
|
||||
{
|
||||
"pac_id": "5",
|
||||
"fecha": "2025-09-01",
|
||||
"clase": "orden",
|
||||
"tipo": "orden",
|
||||
"codigo": "orden",
|
||||
"valor_codigo": null,
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "biopsiacervical",
|
||||
"fuente_id": "3"
|
||||
},
|
||||
{
|
||||
"pac_id": "5",
|
||||
"fecha": "2025-12-01",
|
||||
"clase": "orden",
|
||||
"tipo": "orden",
|
||||
"codigo": "orden",
|
||||
"valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "ordenesestudio",
|
||||
"fuente_id": "4"
|
||||
},
|
||||
{
|
||||
"pac_id": "6",
|
||||
"fecha": "2025-09-01",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "INSATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "8"
|
||||
}
|
||||
]
|
||||
Vendored
-7735
File diff suppressed because it is too large
Load Diff
Vendored
-6242
File diff suppressed because it is too large
Load Diff
@@ -1 +0,0 @@
|
||||
"""Synthetic staging rows for the tests, one module per domain: written by hand, never real data."""
|
||||
@@ -1,187 +0,0 @@
|
||||
"""Filas sintéticas del staging de CaCu, escritas a mano. Nunca datos reales.
|
||||
|
||||
Seis pacientes y nueve citologías en dos semestres de 2025. Los textos de
|
||||
calidad son provisionales: los valores reales están sin confirmar.
|
||||
|
||||
Pacientes tamizadas: 4 en 2025-S1 y 4 en 2025-S2; de ellas, con muestra
|
||||
insatisfactoria, 2 y 1. Lo que da cada indicador va abajo (`ESPERADO_*`).
|
||||
|
||||
Casos que ejercita: H-003 tiene dos citologías en S1 y cuenta una vez;
|
||||
H-004 tiene una el 1 de julio, que ya es S2; H-001 aparece en los dos
|
||||
semestres.
|
||||
|
||||
Resultados (v0.5.0, T-4): seis citologías tienen reporte y cuatro, VPH;
|
||||
las dos insatisfactorias de H-002 y H-006 no tienen reporte, y la última
|
||||
de H-001 todavía no. Tres biopsias, cada una con la citología que la
|
||||
originó: dos reportadas y una pendiente. Los textos de resultado también
|
||||
son provisionales.
|
||||
|
||||
Cinco notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico
|
||||
(`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`).
|
||||
|
||||
Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core.cacu.models import BiopsiaCervical, CitologiaCervical, NotaMedica, OrdenesEstudio, Paciente
|
||||
from sqlmodel import Session, select
|
||||
|
||||
SATISFACTORIO = "SATISFACTORIO"
|
||||
INSATISFACTORIO = "INSATISFACTORIO"
|
||||
|
||||
PACIENTES = ("H-001", "H-002", "H-003", "H-004", "H-005", "H-006")
|
||||
|
||||
# (pac_id_hospital, fecha de toma, calidad del espécimen)
|
||||
CITOLOGIAS = (
|
||||
("H-001", date(2025, 2, 10), SATISFACTORIO),
|
||||
("H-002", date(2025, 3, 5), INSATISFACTORIO),
|
||||
("H-003", date(2025, 1, 20), INSATISFACTORIO),
|
||||
("H-003", date(2025, 4, 15), SATISFACTORIO),
|
||||
("H-004", date(2025, 5, 30), SATISFACTORIO),
|
||||
("H-004", date(2025, 7, 1), SATISFACTORIO),
|
||||
("H-005", date(2025, 8, 12), SATISFACTORIO),
|
||||
("H-006", date(2025, 9, 1), INSATISFACTORIO),
|
||||
("H-001", date(2025, 10, 2), SATISFACTORIO),
|
||||
)
|
||||
|
||||
# Índice en CITOLOGIAS -> (fecha de reporte, células escamosas, VPH, genotipo 16, genotipo 18).
|
||||
RESULTADOS = {
|
||||
0: (date(2025, 2, 20), "NEGATIVO", None, None, None),
|
||||
2: (date(2025, 2, 1), "ASC-US", "POSITIVO", 1, 0),
|
||||
3: (date(2025, 4, 25), "LIEBG", "POSITIVO", 0, 0),
|
||||
4: (date(2025, 6, 9), "NEGATIVO", None, None, None),
|
||||
5: (date(2025, 7, 11), "LIEAG", "POSITIVO", 0, 1),
|
||||
6: (date(2025, 8, 22), "NEGATIVO", "NEGATIVO", None, None),
|
||||
}
|
||||
|
||||
# (índice de la citología que la originó, fecha de solicitud, fecha de reporte, grado CIN)
|
||||
BIOPSIAS = (
|
||||
(3, date(2025, 5, 1), date(2025, 5, 20), "CIN1"),
|
||||
(5, date(2025, 7, 15), date(2025, 8, 1), "CIN2"),
|
||||
(6, date(2025, 9, 1), None, None),
|
||||
)
|
||||
|
||||
# Notas médicas: (paciente, fecha de la nota, CIE-10 y especialidad como los escribe el hospital).
|
||||
COLPOSCOPIA, ONCOLOGIA, FAMILIAR = "CLINICA DE MUJER Y COLPOSCOPIA", "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR"
|
||||
NOTAS = (
|
||||
("H-004", date(2025, 8, 10), "D06.9", COLPOSCOPIA), # 72 días de su toma de mayo y 40 de la de julio
|
||||
("H-003", date(2024, 12, 1), "C53.9", FAMILIAR), # cáncer anterior a sus dos tomas: no es un caso nuevo
|
||||
("H-001", date(2025, 3, 1), "N87.1", FAMILIAR), # displasia, pero de medicina familiar: no resuelve
|
||||
("H-002", date(2025, 9, 15), "C53", ONCOLOGIA), # a 194 días de su toma: fuera del horizonte
|
||||
("H-005", date(2026, 1, 20), "c539", COLPOSCOPIA), # 161 días de su toma, pero después del corte de fin de año
|
||||
)
|
||||
|
||||
# Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital).
|
||||
# La segunda no es de tamizaje; la especialidad de la tercera no está en el catálogo de Core
|
||||
# y queda sin reconocer; la cuarta está pedida y todavía no tiene citología.
|
||||
ORDENES = (
|
||||
(50001, "H-001", date(2025, 2, 3), "MEDICINA FAMILIAR"),
|
||||
(50002, "H-003", date(2025, 4, 10), "CLINICA DE MUJER Y COLPOSCOPIA"),
|
||||
(50003, "H-004", date(2025, 6, 25), "Dermatología"),
|
||||
(50004, "H-005", date(2025, 12, 1), "MEDICINA FAMILIAR"),
|
||||
)
|
||||
|
||||
# Índice en CITOLOGIAS -> número de su orden. Las demás citologías no traen número; la de
|
||||
# H-005 trae uno que no existe entre las órdenes.
|
||||
ORDEN_DE_CITOLOGIA = {0: 50001, 3: 50002, 5: 50003, 6: 59999}
|
||||
|
||||
# periodo -> (denominador, numerador) de IND1, con la lista de `cacu.citologia_anomala`
|
||||
# (ASC-US, ASC-H, LIEBG, LIEAG, CIS). En S1 solo H-003 (su ASC-US y su LIEBG; cuenta una
|
||||
# vez); en S2 solo H-004 (su LIEAG del 1 de julio).
|
||||
ESPERADO_IND1 = {"2025-S1": (4, 1), "2025-S2": (4, 1)}
|
||||
|
||||
# (periodo, fecha de corte) -> (población inicial, n, q1, mediana, q3) de CACU_EU_TIEMPO_REPORTE,
|
||||
# con horizonte de 60 días. Días de toma a resultado: S1 10, 12, 10, 10 (la toma del 5 de
|
||||
# marzo no tiene resultado y a fin de año ya pasó el horizonte: cuenta en la inicial y no en
|
||||
# n); S2 10, 10. A mediados de octubre las tomas de septiembre y octubre sin resultado siguen
|
||||
# dentro del horizonte: no se miden. A mediados de agosto el resultado del 22 todavía no existe.
|
||||
ESPERADO_CACU_TIEMPO = {
|
||||
("2025-S1", "2025-12-31"): (5, 4, 10.0, 10.0, 10.5),
|
||||
("2025-S2", "2025-12-31"): (4, 2, 10.0, 10.0, 10.0),
|
||||
("2025-S2", "2025-10-15"): (2, 2, 10.0, 10.0, 10.0),
|
||||
("2025-S2", "2025-08-15"): (1, 1, 10.0, 10.0, 10.0),
|
||||
}
|
||||
|
||||
# periodo -> (denominador, numerador) de CACU_EU13, con la lista de arranque de
|
||||
# `cacu.deteccion_grados` (LIEAG, CIS, CARCINOMA). Los grados de las biopsias de
|
||||
# este fixture (CIN1, CIN2) son textos provisionales que no están en esa lista:
|
||||
# el numerador es cero. El distinto de cero se prueba con filas escritas a mano
|
||||
# en `cacu/familias/eu13/casos.toml`.
|
||||
ESPERADO_CACU_EU13 = {"2025-S1": (4, 0), "2025-S2": (4, 0)}
|
||||
|
||||
# periodo -> {categoría: pacientes} de CACU_EU7 (solo las que tienen alguna). En S1, H-003
|
||||
# cuenta con el LIEBG de abril (su ASC-US de enero es de una muestra insatisfactoria y,
|
||||
# además, anterior) y H-002 no tiene resultado; en S2, H-006 no tiene resultado y la de
|
||||
# octubre de H-001 todavía no. «NEGATIVO» es un texto provisional de este fixture: no está
|
||||
# en el catálogo (que usa NORMAL, como Core) y sale después de SIN_DATO.
|
||||
ESPERADO_CACU_EU7 = {
|
||||
"2025-S1": {"NEGATIVO": 2, "LIEBG": 1, "SIN_DATO": 1},
|
||||
"2025-S2": {"NEGATIVO": 1, "LIEAG": 1, "SIN_DATO": 2},
|
||||
}
|
||||
|
||||
|
||||
def insertar(sesion: Session) -> None:
|
||||
"""Inserta pacientes, órdenes, citologías y biopsias. `pac_id` se resuelve por `pac_id_hospital`."""
|
||||
pacientes = {
|
||||
hospital: Paciente(
|
||||
pac_id_hospital=hospital, pac_sexo="Femenino", pac_fecha_nacimiento=date(1980, 1, 1)
|
||||
)
|
||||
for hospital in PACIENTES
|
||||
}
|
||||
sesion.add_all(pacientes.values())
|
||||
sesion.flush()
|
||||
sesion.add_all(
|
||||
OrdenesEstudio(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
ord_numero_hospital=numero,
|
||||
ord_tipo_estudio="SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
|
||||
ord_fecha=fecha,
|
||||
ord_especialidad=especialidad,
|
||||
)
|
||||
for numero, hospital, fecha, especialidad in ORDENES
|
||||
)
|
||||
citologias = []
|
||||
for indice, (hospital, toma, calidad) in enumerate(CITOLOGIAS):
|
||||
reporte, escamosas, vph, genotipo_16, genotipo_18 = RESULTADOS.get(indice, (None,) * 5)
|
||||
citologias.append(
|
||||
CitologiaCervical(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
ord_numero_hospital=ORDEN_DE_CITOLOGIA.get(indice),
|
||||
cit_fecha_toma=toma,
|
||||
cit_calidad_especimen=calidad,
|
||||
cit_fecha_reporte=reporte,
|
||||
cit_celulas_escamosas=escamosas,
|
||||
cit_vph_resultado=vph,
|
||||
cit_vph_genotipo_16=genotipo_16,
|
||||
cit_vph_genotipo_18=genotipo_18,
|
||||
)
|
||||
)
|
||||
sesion.add_all(citologias)
|
||||
sesion.flush()
|
||||
for indice, solicitud, reporte, grado in BIOPSIAS:
|
||||
citologia = citologias[indice]
|
||||
sesion.add(
|
||||
BiopsiaCervical(
|
||||
pac_id=citologia.pac_id,
|
||||
pac_id_hospital=citologia.pac_id_hospital,
|
||||
cit_id=citologia.cit_id,
|
||||
bx_fecha_solicitud=solicitud,
|
||||
bx_fecha_reporte=reporte,
|
||||
bx_cin_grado=grado,
|
||||
)
|
||||
)
|
||||
sesion.add_all(
|
||||
NotaMedica(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
nm_id_hospital=f"NM-{numero:03d}",
|
||||
nm_fecha=fecha,
|
||||
nm_cie_codigo=cie,
|
||||
nm_especialidad=especialidad,
|
||||
)
|
||||
for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1)
|
||||
)
|
||||
sesion.commit()
|
||||
@@ -1,171 +0,0 @@
|
||||
"""Filas sintéticas del staging de CaMa, escritas a mano. Nunca datos reales.
|
||||
|
||||
Seis pacientes y nueve mastografías en dos semestres de 2025. Los textos
|
||||
de calidad son provisionales: los valores reales están sin confirmar.
|
||||
|
||||
Mastografías: 5 en 2025-S1 y 4 en 2025-S2; de ellas, satisfactorias, 4 y 2.
|
||||
Lo que da cada indicador va abajo (`ESPERADO_*`).
|
||||
|
||||
Casos que ejercita: H-001 tiene dos mastografías en S1 y cuentan las dos;
|
||||
una del 1 de julio ya es S2; una de S2 no tiene calidad y cuenta en el
|
||||
denominador pero no en el numerador.
|
||||
|
||||
Resultados (v0.5.0, T-4): cada mastografía trae su BI-RADS; tiene fecha
|
||||
de reporte una semana después de la toma, salvo la que no tiene calidad
|
||||
ni BI-RADS y la última, todavía sin reporte.
|
||||
|
||||
Tres biopsias, cada una con la mastografía que la originó: dos con
|
||||
reporte y grado, y una solicitada que todavía no lo tiene.
|
||||
|
||||
Seis notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico
|
||||
(`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`).
|
||||
|
||||
H-001 y H-003 también están en el fixture de CaCu, con otro `pac_id`:
|
||||
lo único común entre los dos sistemas es `pac_id_hospital`.
|
||||
|
||||
Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio.
|
||||
"""
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
|
||||
from sqlmodel import Session, select
|
||||
|
||||
SATISFACTORIO = "SATISFACTORIO"
|
||||
INSATISFACTORIO = "INSATISFACTORIO"
|
||||
|
||||
PACIENTES = ("H-101", "H-102", "H-001", "H-003", "H-103", "H-104")
|
||||
|
||||
# (pac_id_hospital, fecha de toma, calidad de imagen, BI-RADS)
|
||||
MASTOGRAFIAS = (
|
||||
("H-101", date(2025, 1, 15), SATISFACTORIO, "B1"),
|
||||
("H-102", date(2025, 2, 20), SATISFACTORIO, "B2"),
|
||||
("H-001", date(2025, 3, 10), INSATISFACTORIO, "B0"),
|
||||
("H-001", date(2025, 4, 2), SATISFACTORIO, "B1"),
|
||||
("H-003", date(2025, 6, 30), SATISFACTORIO, "B4A"),
|
||||
("H-103", date(2025, 7, 1), SATISFACTORIO, "B1"),
|
||||
("H-103", date(2025, 9, 9), None, None),
|
||||
("H-104", date(2025, 11, 11), INSATISFACTORIO, "B0"),
|
||||
("H-102", date(2025, 12, 31), SATISFACTORIO, "B2"),
|
||||
)
|
||||
|
||||
# (índice de la mastografía que la originó, fecha de solicitud, fecha de reporte, grado histológico)
|
||||
BIOPSIAS = (
|
||||
(2, date(2025, 3, 20), date(2025, 4, 5), "BENIGNO"),
|
||||
(4, date(2025, 7, 10), date(2025, 7, 28), "CARCINOMA_INVASOR"),
|
||||
(7, date(2025, 11, 20), None, None),
|
||||
)
|
||||
|
||||
# Notas médicas: (paciente, fecha de la nota, CIE-10 y especialidad como los escribe el hospital).
|
||||
# La de H-003 llega con minúscula y punto; la de H-104 no tiene fecha y la de H-101 es de
|
||||
# medicina familiar, que no resuelve la toma.
|
||||
ONCOLOGIA, FAMILIAR = "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR"
|
||||
NOTAS = (
|
||||
("H-003", date(2025, 8, 4), "c50.4", ONCOLOGIA), # 35 días de su B4A del 30 de junio
|
||||
("H-001", date(2025, 3, 1), "D05.1", FAMILIAR), # cáncer anterior a sus dos tomas: no es un caso nuevo
|
||||
("H-102", date(2025, 9, 30), "C50.9", ONCOLOGIA), # a 222 días de su toma de febrero: fuera del horizonte
|
||||
("H-103", date(2025, 7, 20), "C50.9", ONCOLOGIA), # 19 días de su toma del 1 de julio
|
||||
("H-101", date(2025, 1, 15), "Z12.3", FAMILIAR), # normal, pero de medicina familiar: no resuelve
|
||||
("H-104", None, "C50", ONCOLOGIA), # sin fecha: no cuenta
|
||||
)
|
||||
|
||||
# Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital).
|
||||
# La segunda no es de tamizaje; la tercera está pedida y todavía no tiene mastografía.
|
||||
ORDENES = (
|
||||
(60001, "H-101", date(2025, 1, 10), "MEDICINA FAMILIAR"),
|
||||
(60002, "H-003", date(2025, 6, 20), "CIRUGIA ONCOLOGICA"),
|
||||
(60003, "H-104", date(2025, 12, 5), "MEDICINA FAMILIAR"),
|
||||
)
|
||||
|
||||
# Índice en MASTOGRAFIAS -> número de su orden. Las demás no traen número; la de H-102 trae
|
||||
# uno que no existe entre las órdenes.
|
||||
ORDEN_DE_MASTOGRAFIA = {0: 60001, 4: 60002, 1: 69999}
|
||||
|
||||
# periodo -> {categoría: pacientes} de CAMA_BIRADS (solo las que tienen alguna).
|
||||
# H-001 tiene B0 y B1 en S1: cuenta en B0, la más grave. H-103 tiene B1 y una toma sin
|
||||
# reporte: cuenta en B1. H-102 tiene en S2 solo una toma sin reporte: SIN_DATO.
|
||||
ESPERADO_CAMA_BIRADS = {
|
||||
"2025-S1": {"B0": 1, "B1": 1, "B2": 1, "B4A": 1},
|
||||
"2025-S2": {"B0": 1, "B1": 1, "SIN_DATO": 1},
|
||||
}
|
||||
|
||||
# (periodo, fecha de corte) -> (población inicial, n, q1, mediana, q3) de CAMA_EU38A, con
|
||||
# horizonte de 60 días. Todo reporte llega siete días después de la toma. A fin de año la
|
||||
# toma del 9 de septiembre ya pasó el horizonte sin reporte (cuenta en la inicial y no en n)
|
||||
# y la del 31 de diciembre sigue en observación. El 15 de septiembre ninguna toma de S2
|
||||
# posterior a julio tiene reporte ni ha vencido: solo se mide la del 1 de julio.
|
||||
ESPERADO_CAMA_EU38A = {
|
||||
("2025-S1", "2025-12-31"): (5, 5, 7.0, 7.0, 7.0),
|
||||
("2025-S2", "2025-12-31"): (3, 2, 7.0, 7.0, 7.0),
|
||||
("2025-S2", "2025-09-15"): (1, 1, 7.0, 7.0, 7.0),
|
||||
}
|
||||
|
||||
# periodo -> (denominador, numerador) de CAMA_CONFIRMACION_BIRADS45, con la lista de arranque de
|
||||
# `cama.birads_sospecha` (B4 con o sin subcategoría, B5). La única mastografía de sospecha es la B4A de H-003 del 30 de
|
||||
# junio, y su biopsia se reportó el 28 de julio: cuenta en S1, el semestre de la mastografía.
|
||||
# Las otras dos biopsias salen de mastografías B0, que no están en la lista. En S2 no hay
|
||||
# ninguna de sospecha: sin denominador, el reporte sale suprimido y no se compara.
|
||||
ESPERADO_CAMA_CONFIRMACION_BIRADS45 = {"2025-S1": (1, 1)}
|
||||
|
||||
|
||||
def insertar(sesion: Session) -> None:
|
||||
"""Inserta pacientes, órdenes, mastografías, biopsias y notas. `pac_id` se resuelve por `pac_id_hospital`."""
|
||||
pacientes = {
|
||||
hospital: Paciente(
|
||||
pac_id_hospital=hospital, pac_sexo="Femenino", pac_fecha_nacimiento=date(1975, 1, 1)
|
||||
)
|
||||
for hospital in PACIENTES
|
||||
}
|
||||
sesion.add_all(pacientes.values())
|
||||
sesion.flush()
|
||||
sesion.add_all(
|
||||
OrdenesEstudio(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
ord_numero_hospital=numero,
|
||||
ord_tipo_estudio="MASTOGRAFIA",
|
||||
ord_fecha=fecha,
|
||||
ord_especialidad=especialidad,
|
||||
)
|
||||
for numero, hospital, fecha, especialidad in ORDENES
|
||||
)
|
||||
mastografias = []
|
||||
for indice, (hospital, toma, calidad, birads) in enumerate(MASTOGRAFIAS):
|
||||
sin_reporte = birads is None or indice == len(MASTOGRAFIAS) - 1
|
||||
mastografias.append(
|
||||
Mastografia(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
ord_numero_hospital=ORDEN_DE_MASTOGRAFIA.get(indice),
|
||||
mast_fecha_toma=toma,
|
||||
mast_calidad_imagen=calidad,
|
||||
mast_birads=birads,
|
||||
mast_fecha_reporte=None if sin_reporte else toma + timedelta(days=7),
|
||||
)
|
||||
)
|
||||
sesion.add_all(mastografias)
|
||||
sesion.flush()
|
||||
for indice, solicitud, reporte, grado in BIOPSIAS:
|
||||
mastografia = mastografias[indice]
|
||||
sesion.add(
|
||||
BiopsiaMama(
|
||||
pac_id=mastografia.pac_id,
|
||||
pac_id_hospital=mastografia.pac_id_hospital,
|
||||
mast_id=mastografia.mast_id,
|
||||
bx_fecha_solicitud=solicitud,
|
||||
bx_fecha_reporte=reporte,
|
||||
bx_grado_histologico=grado,
|
||||
)
|
||||
)
|
||||
sesion.add_all(
|
||||
NotaMedica(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
nm_id_hospital=f"NM-{numero:03d}",
|
||||
nm_fecha=fecha,
|
||||
nm_cie_codigo=cie,
|
||||
nm_especialidad=especialidad,
|
||||
)
|
||||
for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1)
|
||||
)
|
||||
sesion.commit()
|
||||
@@ -0,0 +1,26 @@
|
||||
from dagster import DagsterRunStatus
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from webapi.main import app, dagster
|
||||
|
||||
|
||||
class FakeDagster:
|
||||
def get_run_status(self, run_id):
|
||||
return DagsterRunStatus.SUCCESS
|
||||
|
||||
|
||||
def test_health():
|
||||
assert TestClient(app).get("/health").json() == {"status": "ok"}
|
||||
|
||||
|
||||
def test_run_status_reads_dagster():
|
||||
app.dependency_overrides[dagster] = FakeDagster
|
||||
try:
|
||||
r = TestClient(app).get("/runs/abc")
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
assert r.json() == {"id": "abc", "status": "SUCCESS"}
|
||||
|
||||
|
||||
def test_domains():
|
||||
assert TestClient(app).get("/domains").json() == ["cacu", "cama", "tea"]
|
||||
@@ -1,20 +0,0 @@
|
||||
import pytest
|
||||
|
||||
|
||||
@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 client:
|
||||
yield client
|
||||
|
||||
|
||||
def test_health(client):
|
||||
response = client.get("/health")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"status": "ok"}
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
"""What this module covers: CaMa's measures answered on request from dbt's semantic layer, against what the kit
|
||||
computed on the same fixture data: every measure, every period, its units and its numbers.
|
||||
|
||||
Fixtures: `base`, the CaMa fixture database through the cycle up to `event_models` (dbt's views); `manifest`, dbt's
|
||||
`manifest.json` (`DBT_MANIFEST`; skipped without it); `fixtures/kit_oracle_cama.json`, the kit's units and published
|
||||
numbers for each measure and period (counts only; suppression off).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from conftest import base_de
|
||||
from webapi.compositions import answer_composition, composition_definitions
|
||||
from webapi.durations import answer_duration, duration_definitions
|
||||
from webapi.metrics import Question, answer, measure_definitions
|
||||
|
||||
ORACLE = json.loads((Path(__file__).parent / "fixtures" / "kit_oracle_cama.json").read_text(encoding="utf-8"))
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manifest():
|
||||
path = os.environ.get("DBT_MANIFEST")
|
||||
if not path:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
return Path(path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def base(tmp_path, sin_supresion, manifest):
|
||||
base = base_de("cama", tmp_path)
|
||||
base.run(*UNTIL_MODELS, parameters=sin_supresion, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def repositories(base) -> dict:
|
||||
d = base.dominio
|
||||
return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository,
|
||||
"history": d.history_repository, "queries": d.dbt_query_repository, "allow_undecided": True}
|
||||
|
||||
|
||||
def units(base, report_id: int) -> list[list]:
|
||||
with base.motor.connect() as connection:
|
||||
return sorted(map(list, connection.execute(text(
|
||||
"select grupo, resultado_id, unidad_id, pac_id, valor_id, numero from measure_report_unidad "
|
||||
"where report_id = :r"), {"r": report_id}).all()))
|
||||
|
||||
|
||||
def published_rows(expected) -> list[dict]:
|
||||
return [dict(zip(expected["published_columns"], row)) for row in expected["published"]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", sorted(ORACLE))
|
||||
def test_each_measure_is_the_kit_s_in_every_period(base, manifest, url):
|
||||
"""Pins down every CaMa measure in every period: the kit's units (with each one's category or days) and its
|
||||
numbers: a composition's count per category, a proportion's numerator and denominator, a duration's n, median,
|
||||
quartiles and excluded where the kit didn't suppress them. Fails if an event model, a semantic definition or the
|
||||
construct it uses drifts from what the kit meant."""
|
||||
for kind, of in (("proportion", measure_definitions), ("composition", composition_definitions),
|
||||
("duration", duration_definitions)):
|
||||
if url in of(manifest):
|
||||
definition = of(manifest)[url]
|
||||
break
|
||||
for period_id, expected in ORACLE[url]["periodos"].items():
|
||||
question = Question(url, period_id)
|
||||
rows = published_rows(expected)
|
||||
if kind == "composition":
|
||||
result = answer_composition("cama", definition, question, **repositories(base))
|
||||
assert {k: v for k, v in result.categories.items() if v} == {
|
||||
r["categoria"]: r["n"] for r in rows if r["estrato_id"] == "total" and r["n"]}, period_id
|
||||
elif kind == "proportion":
|
||||
result = answer("cama", definition, question, **repositories(base))
|
||||
(total,) = [r for r in rows if r["estrato_id"] == "total"] or [{"numerador": 0, "denominador": 0}]
|
||||
assert (result.numerator, result.denominator) == (total["numerador"] or 0, total["denominador"] or 0), period_id
|
||||
else:
|
||||
result = answer_duration("cama", definition, question, **repositories(base))
|
||||
(total,) = [r for r in rows if r["estrato_id"] == "total"]
|
||||
if not total["suprimido"]:
|
||||
assert (result.n, result.median, result.q1, result.q3, result.excluded) == (
|
||||
total["n"], total["mediana"], total["q1"], total["q3"], total["n_excluido"]), period_id
|
||||
assert units(base, result.report_id) == expected["units"], period_id
|
||||
@@ -1,127 +0,0 @@
|
||||
import io
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from webapi.imports.connectors.csv_ import CsvConnector
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.excel import ExcelConnector
|
||||
from webapi.imports.connectors.json_ import JsonConnector
|
||||
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.preview().columns}
|
||||
assert columns == {"nombre": "string", "edad": "integer"}
|
||||
preview = connector.preview(limit=1)
|
||||
assert preview.total_rows == 2
|
||||
assert len(preview.sample_rows) == 1
|
||||
# Cells stay text; typing is the import schema's job (see CsvConnector).
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre", "edad": "pac_edad"}))
|
||||
assert rows == [{"pac_nombre": "Ana", "pac_edad": "30"}, {"pac_nombre": "Luis", "pac_edad": "40"}]
|
||||
|
||||
|
||||
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.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"},
|
||||
{"pac_codigo_postal": None, "pac_id_hospital": "H-2"},
|
||||
]
|
||||
|
||||
|
||||
def test_csv_connector_single_column_file():
|
||||
connector = CsvConnector(b"id\nH3\nH4\n")
|
||||
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.preview().columns] == ["Expediente", "Sexo"]
|
||||
assert connector.metadata() == {"delimiter": ";", "encoding": "utf-8-sig"}
|
||||
|
||||
|
||||
def test_csv_connector_falls_back_to_cp1252():
|
||||
raw = "nombre\nPeña\n".encode("cp1252")
|
||||
connector = CsvConnector(raw)
|
||||
assert list(connector.read_rows({"nombre": "n"})) == [{"n": "Peña"}]
|
||||
|
||||
|
||||
def test_csv_connector_bad_bytes_raise_connector_error():
|
||||
with pytest.raises(ConnectorError):
|
||||
CsvConnector(b"\xff\xfe\x00\x01not valid utf-8 csv bytes")
|
||||
|
||||
|
||||
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.preview().columns} == {"nombre", "edad"}
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre"}))
|
||||
assert rows == [{"pac_nombre": "Ana"}, {"pac_nombre": "Luis"}]
|
||||
|
||||
|
||||
def test_json_connector_reads_wrapped_data_key():
|
||||
raw = b'{"data": [{"nombre": "Ana"}]}'
|
||||
connector = JsonConnector(raw)
|
||||
assert {c.name for c in connector.preview().columns} == {"nombre"}
|
||||
|
||||
|
||||
def test_json_connector_bad_json_raises_connector_error():
|
||||
with pytest.raises(ConnectorError):
|
||||
JsonConnector(b"{not valid json")
|
||||
|
||||
|
||||
def test_excel_connector_reads_columns_and_rows():
|
||||
pd = pytest.importorskip("pandas")
|
||||
buffer = io.BytesIO()
|
||||
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.preview().columns} == {"nombre", "edad"}
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre"}))
|
||||
assert rows == [{"pac_nombre": "Ana"}, {"pac_nombre": "Luis"}]
|
||||
|
||||
|
||||
def test_excel_connector_bad_bytes_raise_connector_error():
|
||||
with pytest.raises(ConnectorError):
|
||||
ExcelConnector(b"not an excel file")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_source_url(tmp_path):
|
||||
db_path = tmp_path / "source.db"
|
||||
url = f"sqlite:///{db_path}"
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE patients (nombre TEXT, edad INTEGER)"))
|
||||
conn.execute(text("INSERT INTO patients (nombre, edad) VALUES ('Ana', 30), ('Luis', 40)"))
|
||||
return url
|
||||
|
||||
|
||||
def test_sql_connector_introspection_and_rows(sqlite_source_url):
|
||||
connector = SqlConnector(sqlite_source_url)
|
||||
connector.test_connection()
|
||||
assert connector.get_dialect() == "sqlite"
|
||||
assert "patients" in connector.list_tables()
|
||||
columns = {c.name for c in connector.list_columns("patients")}
|
||||
assert columns == {"nombre", "edad"}
|
||||
|
||||
connector.select_table("patients")
|
||||
preview = connector.preview()
|
||||
assert preview.total_rows == 2
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre", "edad": "pac_edad"}))
|
||||
assert rows == [{"pac_nombre": "Ana", "pac_edad": 30}, {"pac_nombre": "Luis", "pac_edad": 40}]
|
||||
|
||||
|
||||
def test_sql_connector_bad_connection_string_raises_connector_error():
|
||||
# may fail either at construction (unknown dialect) or at connect time;
|
||||
# both must surface as ConnectorError rather than a raw sqlalchemy error
|
||||
with pytest.raises(ConnectorError):
|
||||
connector = SqlConnector("not-a-real://connection-string")
|
||||
connector.test_connection()
|
||||
@@ -1,91 +0,0 @@
|
||||
"""Exercises `SqlConnector` against a real MySQL server, covering
|
||||
MySQL-specific reflection (native `ENUM` columns, `pymysql` quirks, DATE
|
||||
types) that the SQLite-based tests don't reach. Skipped unless
|
||||
`MYSQL_TEST_URL` is set.
|
||||
|
||||
To stand one up locally:
|
||||
docker run -d --name isssteleon-mysql-test \
|
||||
-e MYSQL_ROOT_PASSWORD=<root_pw> -e MYSQL_DATABASE=hospital_legacy \
|
||||
-e MYSQL_USER=<user> -e MYSQL_PASSWORD=<pw> -p 3307:3306 mysql:8.0
|
||||
export MYSQL_TEST_URL="mysql+pymysql://<user>:<pw>@127.0.0.1:3307/hospital_legacy"
|
||||
"""
|
||||
import os
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
|
||||
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")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def legacy_table():
|
||||
"""A legacy table whose columns are unrelated to Core's naming, as in a
|
||||
third-party database we don't control."""
|
||||
engine = sa.create_engine(MYSQL_TEST_URL)
|
||||
table_name = "test_connectors_mysql_fixture"
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
|
||||
conn.execute(
|
||||
sa.text(
|
||||
f"CREATE TABLE {table_name} ("
|
||||
" legacy_id VARCHAR(40) NOT NULL PRIMARY KEY,"
|
||||
" legacy_sexo ENUM('F','M'),"
|
||||
" legacy_nacimiento DATE"
|
||||
") ENGINE=InnoDB"
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
sa.text(
|
||||
f"INSERT INTO {table_name} (legacy_id, legacy_sexo, legacy_nacimiento) VALUES "
|
||||
"('MYFIX-1', 'F', '1990-01-15'), ('MYFIX-2', 'M', '1985-06-20')"
|
||||
)
|
||||
)
|
||||
yield table_name
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_connects_and_reports_mysql_dialect():
|
||||
connector = SqlConnector(MYSQL_TEST_URL)
|
||||
connector.test_connection()
|
||||
assert connector.get_dialect() == "mysql"
|
||||
|
||||
|
||||
def test_introspects_real_mysql_schema(legacy_table):
|
||||
connector = SqlConnector(MYSQL_TEST_URL)
|
||||
assert legacy_table in connector.list_tables()
|
||||
columns = {c.name: c.inferred_type for c in connector.list_columns(legacy_table)}
|
||||
assert columns["legacy_id"] == "string"
|
||||
assert columns["legacy_nacimiento"] == "date"
|
||||
# A native MySQL ENUM column is reflected as a string-like type.
|
||||
assert columns["legacy_sexo"] == "string"
|
||||
|
||||
|
||||
def test_reads_rows_with_column_mapping_against_real_mysql(legacy_table):
|
||||
connector = SqlConnector(MYSQL_TEST_URL)
|
||||
connector.select_table(legacy_table)
|
||||
preview = connector.preview()
|
||||
assert preview.total_rows == 2
|
||||
|
||||
rows = list(
|
||||
connector.read_rows({"legacy_id": "pac_id_hospital", "legacy_sexo": "pac_sexo", "legacy_nacimiento": "pac_fecha_nacimiento"})
|
||||
)
|
||||
by_id = {r["pac_id_hospital"]: r for r in rows}
|
||||
assert by_id["MYFIX-1"]["pac_sexo"] == "F"
|
||||
# Rows come straight from the driver, so a MySQL DATE is a `date`.
|
||||
import datetime as _dt
|
||||
|
||||
assert by_id["MYFIX-1"]["pac_fecha_nacimiento"] == _dt.date(1990, 1, 15)
|
||||
|
||||
|
||||
def test_bad_mysql_credentials_raise_connector_error():
|
||||
bad_url = MYSQL_TEST_URL.rsplit("@", 1)[-1]
|
||||
connector = SqlConnector(f"mysql+pymysql://nobody:wrongpassword@{bad_url}")
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.test_connection()
|
||||
@@ -1,327 +0,0 @@
|
||||
"""Tests for `PdfConnector`. PDF fixtures are generated at test time with
|
||||
reportlab.
|
||||
|
||||
- `build_table_pdf()`: a ruled table with selectable text, for the table
|
||||
detection path.
|
||||
- `build_scanned_like_pdf()` / `build_three_column_pdf()`: text rendered into
|
||||
an image that fills the page, so there is no text layer and only the
|
||||
OCR/region path applies. The three-column variant uses known values per
|
||||
row so alignment can be checked.
|
||||
"""
|
||||
|
||||
import difflib
|
||||
import io
|
||||
|
||||
import pytest
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.utils import ImageReader
|
||||
from reportlab.pdfgen import canvas
|
||||
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.pdf import PdfConnector, RegionSpec
|
||||
|
||||
# The synthetic "scanned" pages are drawn onto an image this size, then
|
||||
# stretched to fill the whole (letter-size) PDF page, so a normalized
|
||||
# 0..1 bbox computed from these pixel coordinates lines up with the region
|
||||
# regardless of the DPI used to re-render the page for OCR.
|
||||
IMG_W, IMG_H = 900, 1200
|
||||
COL_X = {"name": 40, "age": 340, "city": 620}
|
||||
COL_WIDTH = 260
|
||||
ROW_YS = [120, 320, 520]
|
||||
ROW_HEIGHT = 100
|
||||
|
||||
|
||||
def _font(size: int = 34) -> ImageFont.ImageFont:
|
||||
for path in (
|
||||
"/System/Library/Fonts/Helvetica.ttc",
|
||||
"/System/Library/Fonts/Supplemental/Arial.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||
):
|
||||
try:
|
||||
return ImageFont.truetype(path, size)
|
||||
except Exception:
|
||||
continue
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def build_table_pdf(rows: list[tuple[str, str]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
doc = SimpleDocTemplate(buffer, pagesize=letter)
|
||||
data = [["pac_id_hospital", "pac_sexo"], *[[a, b] for a, b in rows]]
|
||||
table = Table(data)
|
||||
table.setStyle(
|
||||
TableStyle(
|
||||
[
|
||||
("GRID", (0, 0), (-1, -1), 1, colors.black),
|
||||
("FONTSIZE", (0, 0), (-1, -1), 12),
|
||||
("BOTTOMPADDING", (0, 0), (-1, -1), 8),
|
||||
("TOPPADDING", (0, 0), (-1, -1), 8),
|
||||
]
|
||||
)
|
||||
)
|
||||
doc.build([table])
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _page_image(lines: list[str]) -> Image.Image:
|
||||
img = Image.new("RGB", (IMG_W, IMG_H), "white")
|
||||
draw = ImageDraw.Draw(img)
|
||||
font = _font()
|
||||
y = 40
|
||||
for line in lines:
|
||||
draw.text((40, y), line, fill="black", font=font)
|
||||
y += 60
|
||||
return img
|
||||
|
||||
|
||||
def build_scanned_like_pdf(pages_lines: list[list[str]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
c = canvas.Canvas(buffer, pagesize=letter)
|
||||
page_w, page_h = letter
|
||||
for lines in pages_lines:
|
||||
img = _page_image(lines)
|
||||
reader_buf = io.BytesIO()
|
||||
img.save(reader_buf, format="PNG")
|
||||
reader_buf.seek(0)
|
||||
c.drawImage(ImageReader(reader_buf), 0, 0, width=page_w, height=page_h)
|
||||
c.showPage()
|
||||
c.save()
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _three_column_page_image(rows: list[tuple[str, str, str]]) -> Image.Image:
|
||||
img = Image.new("RGB", (IMG_W, IMG_H), "white")
|
||||
draw = ImageDraw.Draw(img)
|
||||
font = _font()
|
||||
for y, (name, age, city) in zip(ROW_YS, rows):
|
||||
draw.text((COL_X["name"], y), name, fill="black", font=font)
|
||||
draw.text((COL_X["age"], y), age, fill="black", font=font)
|
||||
draw.text((COL_X["city"], y), city, fill="black", font=font)
|
||||
return img
|
||||
|
||||
|
||||
def build_three_column_pdf(pages_rows: list[list[tuple[str, str, str]]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
c = canvas.Canvas(buffer, pagesize=letter)
|
||||
page_w, page_h = letter
|
||||
for rows in pages_rows:
|
||||
img = _three_column_page_image(rows)
|
||||
reader_buf = io.BytesIO()
|
||||
img.save(reader_buf, format="PNG")
|
||||
reader_buf.seek(0)
|
||||
c.drawImage(ImageReader(reader_buf), 0, 0, width=page_w, height=page_h)
|
||||
c.showPage()
|
||||
c.save()
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _norm_bbox(field: str) -> tuple[float, float, float, float]:
|
||||
x0 = COL_X[field]
|
||||
x1 = x0 + COL_WIDTH
|
||||
y0 = ROW_YS[0] - 60
|
||||
y1 = ROW_YS[-1] + ROW_HEIGHT
|
||||
return (x0 / IMG_W, y0 / IMG_H, x1 / IMG_W, y1 / IMG_H)
|
||||
|
||||
|
||||
def _similar(a: str, b: str, threshold: float = 0.7) -> bool:
|
||||
return difflib.SequenceMatcher(None, a.strip().lower(), b.strip().lower()).ratio() >= threshold
|
||||
|
||||
|
||||
ROWS = [("Ana Garcia", "30", "Monterrey"), ("Luis Perez", "40", "Saltillo"), ("Marta Ruiz", "50", "Torreon")]
|
||||
ROWS_PAGE_2 = [("Elena Diaz", "60", "Chihuahua"), ("Jorge Nava", "22", "Durango"), ("Sofia Reyes", "35", "Culiacan")]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Classification
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_has_text_layer_true_for_table_pdf():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M")]))
|
||||
assert connector.has_text_layer() is True
|
||||
|
||||
|
||||
def test_has_text_layer_false_for_scanned_pdf():
|
||||
connector = PdfConnector(build_scanned_like_pdf([["Ana Garcia", "Luis Perez"]]))
|
||||
assert connector.has_text_layer() is False
|
||||
|
||||
|
||||
def test_malformed_pdf_bytes_raise_connector_error():
|
||||
with pytest.raises(ConnectorError):
|
||||
PdfConnector(b"not a pdf at all")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Ruled table detection
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_detect_tables_finds_candidate_with_right_shape_on_table_pdf():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M"), ("H-TAB-3", "F")]))
|
||||
candidates = connector.detect_tables()
|
||||
assert len(candidates) == 1
|
||||
candidate = candidates[0]
|
||||
assert candidate.page_number == 1
|
||||
assert len(candidate.grid) == 4 # header + 3 data rows
|
||||
assert len(candidate.grid[0]) == 2
|
||||
assert candidate.grid[0] == ["pac_id_hospital", "pac_sexo"]
|
||||
assert candidate.grid[1][0] == "H-TAB-1"
|
||||
|
||||
|
||||
def test_detect_tables_empty_on_scanned_pdf():
|
||||
connector = PdfConnector(build_scanned_like_pdf([["Ana Garcia", "Luis Perez"]]))
|
||||
assert connector.detect_tables() == []
|
||||
|
||||
|
||||
def test_select_table_then_connector_abc_roundtrip():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M")]))
|
||||
candidate = connector.detect_tables()[0]
|
||||
connector.select_table(candidate.page_number, candidate.bbox)
|
||||
|
||||
columns = {c.name for c in connector.preview().columns}
|
||||
assert columns == {"pac_id_hospital", "pac_sexo"}
|
||||
|
||||
preview = connector.preview(limit=1)
|
||||
assert preview.total_rows == 2
|
||||
assert len(preview.sample_rows) == 1
|
||||
|
||||
rows = list(connector.read_rows({"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"}))
|
||||
assert rows == [
|
||||
{"pac_id_hospital": "H-TAB-1", "pac_sexo": "F"},
|
||||
{"pac_id_hospital": "H-TAB-2", "pac_sexo": "M"},
|
||||
]
|
||||
|
||||
|
||||
def test_select_table_out_of_range_page_raises_connector_error():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F")]))
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.select_table(99, (0, 0, 100, 100))
|
||||
|
||||
|
||||
def test_read_rows_before_resolution_raises_connector_error():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F")]))
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.preview().columns
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Rendering
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_render_page_image_returns_valid_png_with_expected_aspect_ratio():
|
||||
connector = PdfConnector(build_scanned_like_pdf([["hello"]]))
|
||||
png_bytes = connector.render_page_image(1, dpi=150)
|
||||
image = Image.open(io.BytesIO(png_bytes))
|
||||
assert image.format == "PNG"
|
||||
page_w, page_h = letter
|
||||
expected_ratio = page_w / page_h
|
||||
actual_ratio = image.width / image.height
|
||||
assert abs(actual_ratio - expected_ratio) < 0.01
|
||||
|
||||
|
||||
def test_render_page_image_out_of_range_raises_connector_error():
|
||||
connector = PdfConnector(build_scanned_like_pdf([["hello"]]))
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.render_page_image(7)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# OCR / region path
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_single_region_ocr_matches_known_column():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
||||
region = RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name"))
|
||||
result = connector.extract_regions([region])
|
||||
assert len(result["name"]) == 3
|
||||
for actual, (expected, _, _) in zip(result["name"], ROWS):
|
||||
assert _similar(actual, expected), f"{actual!r} not close enough to {expected!r}"
|
||||
|
||||
|
||||
def test_multi_region_row_alignment_matches_ground_truth():
|
||||
"""Three columns OCR'd independently must recombine into the rows they
|
||||
came from."""
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
||||
regions = [
|
||||
RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name")),
|
||||
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
||||
RegionSpec(target_field="city", page_numbers=[1], bbox=_norm_bbox("city")),
|
||||
]
|
||||
result = connector.extract_regions(regions)
|
||||
|
||||
assert len(result["name"]) == len(result["age"]) == len(result["city"]) == 3
|
||||
for i, (expected_name, expected_age, expected_city) in enumerate(ROWS):
|
||||
assert _similar(result["name"][i], expected_name), f"row {i} name mismatch: {result['name'][i]!r}"
|
||||
assert _similar(result["age"][i], expected_age), f"row {i} age mismatch: {result['age'][i]!r}"
|
||||
assert _similar(result["city"][i], expected_city), f"row {i} city mismatch: {result['city'][i]!r}"
|
||||
|
||||
rows = list(
|
||||
connector.read_rows({"name": "name", "age": "age", "city": "city"})
|
||||
)
|
||||
assert len(rows) == 3
|
||||
assert _similar(rows[0]["name"], ROWS[0][0])
|
||||
|
||||
|
||||
def test_two_page_apply_to_every_page_regions():
|
||||
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, 2], bbox=_norm_bbox("age")),
|
||||
RegionSpec(target_field="city", page_numbers=[1, 2], bbox=_norm_bbox("city")),
|
||||
]
|
||||
result = connector.extract_regions(regions)
|
||||
|
||||
all_rows = ROWS + ROWS_PAGE_2
|
||||
assert len(result["name"]) == 6
|
||||
for i, (expected_name, expected_age, expected_city) in enumerate(all_rows):
|
||||
assert _similar(result["name"][i], expected_name), f"row {i}: {result['name']}"
|
||||
assert _similar(result["age"][i], expected_age)
|
||||
assert _similar(result["city"][i], expected_city)
|
||||
|
||||
# page 1's rows precede page 2's, not just correct as a set
|
||||
assert _similar(result["name"][0], ROWS[0][0])
|
||||
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 = [
|
||||
RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name")),
|
||||
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
||||
]
|
||||
connector.extract_regions(regions)
|
||||
columns = {c.name for c in connector.preview().columns}
|
||||
assert columns == {"name", "age"}
|
||||
|
||||
|
||||
def test_split_conflict_records_warning_without_dropping_data():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
||||
connector.warnings = []
|
||||
lines = [
|
||||
{"target_field": "a", "y": 100, "height": 20, "text": "A1"},
|
||||
{"target_field": "b", "y": 108, "height": 20, "text": "B1"},
|
||||
{"target_field": "a", "y": 116, "height": 20, "text": "A2"},
|
||||
]
|
||||
rows = connector._cluster_rows(lines, page_number=1)
|
||||
total_values = sum(len(row) for row in rows)
|
||||
assert total_values == 3 # nothing silently dropped
|
||||
assert len(connector.warnings) == 1
|
||||
assert connector.warnings[0].page_number == 1
|
||||
@@ -1,243 +0,0 @@
|
||||
"""Endpoint tests for `/governance/*`."""
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
wire_domain("governance")
|
||||
|
||||
# A local, SQLite-backed MLflow tracking store for this module — no
|
||||
# server, no network. `chdir` into the same temp dir: an experiment with
|
||||
# no explicit artifact_location falls back to `./mlruns` relative to the
|
||||
# CWD (production never sets one either; the real MLflow server picks it).
|
||||
import mlflow
|
||||
|
||||
tmp_dir = tempfile.mkdtemp()
|
||||
uri = f"sqlite:///{os.path.join(tmp_dir, 'mlflow.db')}"
|
||||
os.environ["MLFLOW_TRACKING_URI"] = uri
|
||||
mlflow.set_tracking_uri(uri)
|
||||
previous_cwd = os.getcwd()
|
||||
os.chdir(tmp_dir)
|
||||
|
||||
from core.cacu.models import Paciente
|
||||
from persistance import db as persistance_db
|
||||
|
||||
with __import__("sqlmodel").Session(persistance_db.get_cacu_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()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
os.chdir(previous_cwd)
|
||||
del os.environ["MLFLOW_TRACKING_URI"]
|
||||
|
||||
|
||||
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 _armado(tag: str) -> int:
|
||||
"""A CaCu cohort build with one attrition step; returns its `armado_id`."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
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",
|
||||
"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",
|
||||
**extra,
|
||||
}
|
||||
response = client.post("/governance/model-versions", json=body)
|
||||
assert response.status_code == 201, response.get_json()
|
||||
return response.get_json()
|
||||
|
||||
|
||||
def _upload(client, domain: str, scenario: str, version: str, kind: str = "BALANCE_CLASES", name: str = "smote.json", data: bytes = b"{}"):
|
||||
files = {"file": (__import__("io").BytesIO(data), name), "kind": kind}
|
||||
return client.post(f"/governance/model-versions/{domain}/{scenario}/{version}/artifacts", data=files, content_type="multipart/form-data")
|
||||
|
||||
|
||||
def test_model_version_lifecycle_over_http(client):
|
||||
first = _register(client, "v1", scenario="lifecycle")
|
||||
assert first["status"] == "candidata"
|
||||
|
||||
checks = client.get(f"/governance/model-versions/cacu/lifecycle/{first['version']}/checks").get_json()
|
||||
assert checks["ready"] is False
|
||||
assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01b"]
|
||||
blocked = client.post(f"/governance/model-versions/cacu/lifecycle/{first['version']}/promote")
|
||||
assert blocked.status_code == 409 and any(not c["passed"] for c in blocked.get_json()["checks"])
|
||||
|
||||
uploaded = _upload(client, "cacu", "lifecycle", first["version"])
|
||||
assert uploaded.status_code == 201
|
||||
assert client.post(f"/governance/model-versions/cacu/lifecycle/{first['version']}/promote").get_json()["status"] == "produccion"
|
||||
|
||||
second = _register(client, "v2", scenario="lifecycle", metrics={"auc": 0.86})
|
||||
_upload(client, "cacu", "lifecycle", second["version"])
|
||||
client.post(f"/governance/model-versions/cacu/lifecycle/{second['version']}/promote")
|
||||
listed = client.get("/governance/model-versions", query_string={"domain": "cacu", "scenario": "lifecycle"}).get_json()
|
||||
statuses = {v["version"]: v["status"] for v in listed["model_versions"]}
|
||||
assert statuses[first["version"]] == "retirada" and statuses[second["version"]] == "produccion"
|
||||
|
||||
lineage = client.get(f"/governance/model-versions/cacu/lifecycle/{second['version']}/lineage").get_json()
|
||||
assert lineage["cohorte_armado"]["huella"] == "huella-v2"
|
||||
assert lineage["cohorte_armado"]["datos_as_of"] == "2025-12-31"
|
||||
assert lineage["cohorte_exclusiones"] == [{"orden": 1, "paso": "candidatas", "n": 5}]
|
||||
assert lineage["artifacts"]
|
||||
|
||||
retired = client.post(f"/governance/model-versions/cacu/lifecycle/{second['version']}/retire").get_json()
|
||||
assert retired["status"] == "retirada"
|
||||
|
||||
|
||||
def test_reports_can_be_attached_later(client):
|
||||
version = _register(client, "v3", scenario="reportes", clinical_validation_report_uri=None)
|
||||
response = client.patch(
|
||||
f"/governance/model-versions/cacu/reportes/{version['version']}/reports",
|
||||
json={"clinical_validation_report_uri": "docs/clinica-v3.pdf"},
|
||||
)
|
||||
assert response.get_json()["tags"]["clinical_validation_report_uri"] == "docs/clinica-v3.pdf"
|
||||
assert client.patch(f"/governance/model-versions/cacu/reportes/{version['version']}/reports", json={"metrics": "{}"}).status_code == 400
|
||||
|
||||
|
||||
def test_bad_registrations_and_uploads_are_rejected(client):
|
||||
assert client.post("/governance/model-versions", json={"domain": "cacu"}).status_code == 400
|
||||
dev = client.post("/governance/model-versions", json={"domain": "cacu", "scenario": "malas-subidas", "environment": "DEV"}).get_json()
|
||||
assert _upload(client, "cacu", "malas-subidas", dev["version"], kind="NOPE").status_code == 400
|
||||
assert _upload(client, "cacu", "malas-subidas", dev["version"], kind="ONNX_CHECKPOINT", name="m.onnx", data=b"junk").status_code == 400
|
||||
|
||||
|
||||
def test_model_version_not_found(client):
|
||||
assert client.get("/governance/model-versions/cacu/no-existe/999/checks").status_code == 404
|
||||
|
||||
|
||||
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 == 404
|
||||
|
||||
|
||||
def test_ocr_run_extracts_results_and_flags_unreadable_reports(client):
|
||||
from core.cacu.models import CitologiaCervical
|
||||
from extraction.testing import text_pdf
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
from persistance.governance import extraction_run_repository
|
||||
|
||||
report = text_pdf([["LABORATORIO DE BIOLOGIA MOLECULAR", "Expediente: H-OCR-1", "VPH alto riesgo: POSITIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: DETECTADO"]])
|
||||
good = citologia_cervical_repository.create(CitologiaCervical(pac_id_hospital="H-OCR-1", cit_vph_pdf_blob=report))
|
||||
bad = citologia_cervical_repository.create(CitologiaCervical(pac_id_hospital="H-OCR-2", cit_vph_pdf_blob=b"%PDF-fake"))
|
||||
|
||||
body = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "citologia_cervical"}).get_json()
|
||||
assert body["processed"] >= 1 and body["failed"] >= 1
|
||||
|
||||
good = citologia_cervical_repository.get(good.cit_id)
|
||||
assert (good.cit_vph_resultado, good.cit_vph_genotipo_16, good.cit_vph_genotipo_18) == ("POSITIVO", 0, 1)
|
||||
assert good.cit_vph_ocr_estatus == "REALIZADO" and good.cit_vph_ocr_requiere_revision is False
|
||||
assert good.cit_vph_ocr_metodo_principal == "pdf-texto" and good.cit_vph_ocr_confianza >= 0.8
|
||||
bad = citologia_cervical_repository.get(bad.cit_id)
|
||||
assert bad.cit_vph_ocr_estatus == "FALLIDO" and bad.cit_vph_ocr_requiere_revision is True
|
||||
assert extraction_run_repository.count(entity_pk=str(good.cit_id)) == 1
|
||||
|
||||
again = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "citologia_cervical"}).get_json()
|
||||
assert again["skipped_already_done"] >= 1
|
||||
|
||||
|
||||
def test_list_ocr_jobs(client):
|
||||
body = client.get("/governance/ocr/jobs").get_json()
|
||||
keys = {(j["domain"], j["entity"]) for j in body["jobs"]}
|
||||
assert ("cacu", "citologia_cervical") in keys
|
||||
assert ("cacu", "biopsia_cervical") in keys
|
||||
assert ("cama", "biopsia_mama") in keys
|
||||
cacu_vph = next(j for j in body["jobs"] if (j["domain"], j["entity"]) == ("cacu", "citologia_cervical"))
|
||||
assert set(cacu_vph["result_fields"]) == {"cit_vph_resultado", "cit_vph_genotipo_16", "cit_vph_genotipo_18"}
|
||||
|
||||
|
||||
def test_ocr_rows_unknown_job_is_404(client):
|
||||
assert client.get("/governance/ocr/cacu/no_such_entity/rows").status_code == 404
|
||||
|
||||
|
||||
def test_ocr_review_queue_blob_and_manual_correction(client):
|
||||
from core.cacu.models import CitologiaCervical
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
row = citologia_cervical_repository.create(
|
||||
CitologiaCervical(
|
||||
pac_id_hospital="H-1",
|
||||
cit_vph_pdf_blob=b"%PDF-review-me",
|
||||
cit_vph_ocr_estatus="FALLIDO",
|
||||
cit_vph_ocr_requiere_revision=True,
|
||||
)
|
||||
)
|
||||
|
||||
review = client.get("/governance/ocr/cacu/citologia_cervical/rows", query_string={"status": "review"})
|
||||
assert review.status_code == 200
|
||||
review_body = review.get_json()
|
||||
assert row.cit_id in {r["id"] for r in review_body["rows"]}
|
||||
|
||||
blob_response = client.get(f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/blob")
|
||||
assert blob_response.status_code == 200
|
||||
assert blob_response.data == b"%PDF-review-me"
|
||||
assert blob_response.content_type == "application/pdf"
|
||||
|
||||
correction = client.post(
|
||||
f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/correct",
|
||||
json={"values": {"cit_vph_resultado": "POSITIVO"}, "confianza": 1.0},
|
||||
)
|
||||
assert correction.status_code == 200
|
||||
corrected = correction.get_json()
|
||||
assert corrected["cit_vph_resultado"] == "POSITIVO"
|
||||
assert corrected["cit_vph_ocr_estatus"] == "REALIZADO"
|
||||
assert corrected["cit_vph_ocr_requiere_revision"] is False
|
||||
assert corrected["cit_vph_ocr_metodo_principal"] == "manual"
|
||||
|
||||
done = client.get("/governance/ocr/cacu/citologia_cervical/rows", query_string={"status": "review"})
|
||||
assert row.cit_id not in {r["id"] for r in done.get_json()["rows"]}
|
||||
|
||||
from persistance.governance import extraction_run_repository
|
||||
|
||||
runs = extraction_run_repository.list(entity="citologia_cervical")
|
||||
assert any("manual" in (r.transform_description or "").lower() for r in runs)
|
||||
|
||||
|
||||
def test_ocr_correct_rejects_unknown_column(client):
|
||||
from core.cacu.models import CitologiaCervical
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
row = citologia_cervical_repository.create(
|
||||
CitologiaCervical(pac_id_hospital="H-2", cit_vph_pdf_blob=b"%PDF-2")
|
||||
)
|
||||
response = client.post(
|
||||
f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/correct",
|
||||
json={"values": {"pac_id_hospital": "HACKED"}},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_ocr_blob_not_found_for_unknown_row(client):
|
||||
assert client.get("/governance/ocr/cacu/citologia_cervical/999999/blob").status_code == 404
|
||||
@@ -1,265 +0,0 @@
|
||||
"""End-to-end tests (Flask test client, SQLite) of how a batch fills the
|
||||
database from several sources: strict catalogs, upserts that keep unmapped
|
||||
columns, defaults, atomic batches, itemized conflicts, and 400s for malformed
|
||||
requests."""
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def _b64(raw: bytes) -> str:
|
||||
return base64.b64encode(raw).decode()
|
||||
|
||||
|
||||
def _csv(text: str, mapping: dict, *, target="cacu.Paciente", **extra) -> dict:
|
||||
return {"source_type": "csv", "target": target, "column_mapping": mapping, "payload": {"file_base64": _b64(text.encode())}, **extra}
|
||||
|
||||
|
||||
def _rows(client, target):
|
||||
return {r["pac_id_hospital"]: r for r in client.get(f"/data/{target}?limit=500").get_json()["rows"]}
|
||||
|
||||
|
||||
def test_catalog_values_are_enforced_and_aliases_resolved(client):
|
||||
source = _csv(
|
||||
"exp,sexo,dep,nac\nCAT-1,f,calles y caminos,1990-01-01\nCAT-2,GARBAGE,,1990-01-01\nCAT-3,Masculino,SECRETARIA DE SALUD,1990-01-01\n",
|
||||
{"exp": "pac_id_hospital", "sexo": "pac_sexo", "dep": "pac_dependencia", "nac": "pac_fecha_nacimiento"},
|
||||
)
|
||||
body = client.post("/imports/validate", json={"source": source}).get_json()
|
||||
assert body["valid_count"] == 2
|
||||
assert [(e["row_index"], e["field"], e["category"], e["raw_value"]) for e in body["errors"]] == [
|
||||
(1, "pac_sexo", "out_of_catalog", "GARBAGE")
|
||||
]
|
||||
|
||||
client.post("/imports/commit", json={"sources": [source]})
|
||||
rows = _rows(client, "cacu.Paciente")
|
||||
assert rows["CAT-1"]["pac_sexo"] == "Femenino"
|
||||
assert rows["CAT-1"]["pac_dependencia"] == "CALLES Y CAMINOS" # alias normalized
|
||||
# Dependencia is a tentative catalog in Core, so unknown values are kept.
|
||||
assert rows["CAT-3"]["pac_dependencia"] == "SECRETARIA DE SALUD"
|
||||
|
||||
|
||||
def test_postal_codes_keep_leading_zeros_and_are_validated(client):
|
||||
source = _csv(
|
||||
"exp,cp,nac\nCP-1,01000,1990-01-01\nCP-2,6400,1990-01-01\nCP-3,64000a,1990-01-01\n",
|
||||
{"exp": "pac_id_hospital", "cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"},
|
||||
)
|
||||
body = client.post("/imports/commit", json={"sources": [source]}).get_json()
|
||||
assert body["results"][0]["created"] == 1
|
||||
rows = _rows(client, "cacu.Paciente")
|
||||
assert rows["CP-1"]["pac_codigo_postal"] == "01000"
|
||||
assert "CP-2" not in rows and "CP-3" not in rows # 4 digits / non-digit
|
||||
|
||||
|
||||
def test_upsert_only_touches_mapped_columns(client):
|
||||
client.post(
|
||||
"/imports/commit",
|
||||
json={"sources": [_csv("exp,sexo,nac\nUP-1,F,15/01/1990\n", {"exp": "pac_id_hospital", "sexo": "pac_sexo", "nac": "pac_fecha_nacimiento"})]},
|
||||
)
|
||||
# pac_fecha_nacimiento is required (IND-01), so every row, insert or
|
||||
# upsert, must carry it. pac_sexo is the field that must stay untouched
|
||||
# when a later source doesn't map it.
|
||||
body = client.post(
|
||||
"/imports/commit",
|
||||
json={
|
||||
"sources": [
|
||||
_csv(
|
||||
"exp,cp,nac\nUP-1,64000,15/01/1990\n",
|
||||
{"exp": "pac_id_hospital", "cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"},
|
||||
)
|
||||
],
|
||||
"on_conflict": "upsert",
|
||||
},
|
||||
).get_json()
|
||||
assert body["results"][0]["updated"] == 1
|
||||
row = _rows(client, "cacu.Paciente")["UP-1"]
|
||||
assert (row["pac_sexo"], row["pac_fecha_nacimiento"], row["pac_codigo_postal"]) == ("Femenino", "1990-01-15", "64000")
|
||||
|
||||
|
||||
def test_defaults_fill_unmapped_fields_and_blank_cells(client):
|
||||
source = _csv(
|
||||
"exp,dep,nac\nDEF-1,,1990-01-01\nDEF-2,GOBIERNO,1990-01-01\n",
|
||||
{"exp": "pac_id_hospital", "dep": "pac_dependencia", "nac": "pac_fecha_nacimiento"},
|
||||
defaults={"pac_dependencia": "CALLES Y CAMINOS", "pac_parentesco": "afiliado"},
|
||||
)
|
||||
assert client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]["created"] == 2
|
||||
rows = _rows(client, "cacu.Paciente")
|
||||
assert rows["DEF-1"]["pac_dependencia"] == "CALLES Y CAMINOS"
|
||||
assert rows["DEF-2"]["pac_dependencia"] == "GOBIERNO"
|
||||
# Defaults go through the same validation/normalization as mapped cells.
|
||||
assert rows["DEF-1"]["pac_parentesco"] == rows["DEF-2"]["pac_parentesco"] == "Afiliado"
|
||||
|
||||
|
||||
def test_several_sources_compose_several_tables_in_one_batch(client):
|
||||
"""One Excel workbook feeds two tables (a source per sheet), a CSV adds
|
||||
more patients, and a JSON source feeds a third table, all in one batch
|
||||
and one transaction."""
|
||||
workbook = openpyxl.Workbook()
|
||||
pacientes = workbook.active
|
||||
pacientes.title = "Pacientes"
|
||||
pacientes.append(["Expediente", "Sexo", "Nacimiento"])
|
||||
pacientes.append(["MIX-1", "F", "1990-01-01"])
|
||||
ordenes = workbook.create_sheet("Ordenes")
|
||||
ordenes.append(["Folio", "Expediente", "Tipo"])
|
||||
ordenes.append([9001, "MIX-1", "Solicitud de Papanicolao en Base Liquida"])
|
||||
buffer = io.BytesIO()
|
||||
workbook.save(buffer)
|
||||
xlsx = _b64(buffer.getvalue())
|
||||
|
||||
preview = client.post(
|
||||
"/imports/sources/file/preview",
|
||||
data={"file": (io.BytesIO(buffer.getvalue()), "libro.xlsx"), "source_kind": "excel", "target": "cacu.OrdenesEstudio", "options": json.dumps({"sheet_name": "Ordenes"})},
|
||||
content_type="multipart/form-data",
|
||||
).get_json()
|
||||
assert preview["source_metadata"] == {"sheets": ["Pacientes", "Ordenes"], "sheet_name": "Ordenes"}
|
||||
assert [c["name"] for c in preview["columns"]] == ["Folio", "Expediente", "Tipo"]
|
||||
|
||||
batch = [
|
||||
{"source_type": "excel", "label": "libro.xlsx › Pacientes", "target": "cacu.Paciente", "column_mapping": {"Expediente": "pac_id_hospital", "Sexo": "pac_sexo", "Nacimiento": "pac_fecha_nacimiento"}, "payload": {"file_base64": xlsx, "options": {"sheet_name": "Pacientes"}}},
|
||||
_csv("id,genero,nac\nMIX-2,M,1990-01-01\n", {"id": "pac_id_hospital", "genero": "pac_sexo", "nac": "pac_fecha_nacimiento"}, label="extra.csv"),
|
||||
{"source_type": "excel", "target": "cacu.OrdenesEstudio", "column_mapping": {"Folio": "ord_numero_hospital", "Expediente": "pac_id_hospital", "Tipo": "ord_tipo_estudio"}, "payload": {"file_base64": xlsx, "options": {"sheet_name": "Ordenes"}}},
|
||||
{"source_type": "json", "target": "cacu.BiometriaHematica", "column_mapping": {"paciente.exp": "pac_id_hospital", "hb": "hemoglobina_g_dl"}, "payload": {"file_base64": _b64(json.dumps([{"paciente": {"exp": "MIX-1"}, "hb": 13.5}]).encode())}},
|
||||
]
|
||||
body = client.post("/imports/commit", json={"sources": batch}).get_json()
|
||||
assert body["ok"] is True
|
||||
assert [(r["label"], r["target"], r["created"]) for r in body["results"]] == [
|
||||
("libro.xlsx › Pacientes", "cacu.Paciente", 1),
|
||||
("extra.csv", "cacu.Paciente", 1),
|
||||
(None, "cacu.OrdenesEstudio", 1),
|
||||
(None, "cacu.BiometriaHematica", 1),
|
||||
]
|
||||
assert {"MIX-1", "MIX-2"} <= set(_rows(client, "cacu.Paciente"))
|
||||
orden = client.get("/data/cacu.OrdenesEstudio").get_json()["rows"][0]
|
||||
assert orden["ord_numero_hospital"] == 9001
|
||||
|
||||
|
||||
def test_conflicts_are_itemized_with_their_row(client):
|
||||
body = client.post(
|
||||
"/imports/commit",
|
||||
json={
|
||||
"sources": [
|
||||
_csv(
|
||||
"exp,nac\nDUP-1,1990-01-01\nDUP-1,1990-01-01\n",
|
||||
{"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"},
|
||||
)
|
||||
]
|
||||
},
|
||||
).get_json()
|
||||
result = body["results"][0]
|
||||
assert (result["created"], result["rejected"]) == (1, 1)
|
||||
assert result["errors"] == [
|
||||
{"row_index": 1, "field": "pac_id_hospital", "category": "conflict", "message": "conflict on ('pac_id_hospital',)", "raw_value": "DUP-1"}
|
||||
]
|
||||
|
||||
|
||||
def test_a_failing_source_rolls_back_the_whole_batch(client, monkeypatch):
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from persistance.repository import Repository
|
||||
|
||||
original = Repository.bulk_upsert
|
||||
calls = {"n": 0}
|
||||
|
||||
def flaky(self, objs, **kwargs):
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 2:
|
||||
raise OperationalError("INSERT ...", {}, Exception("disk full"))
|
||||
return original(self, objs, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Repository, "bulk_upsert", flaky)
|
||||
response = client.post(
|
||||
"/imports/commit",
|
||||
json={
|
||||
"sources": [
|
||||
_csv("exp,nac\nATOM-1,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}),
|
||||
_csv("exp,nac\nATOM-2,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}),
|
||||
]
|
||||
},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "no se escribió nada" in response.get_json()["error"]
|
||||
assert not {"ATOM-1", "ATOM-2"} & set(_rows(client, "cacu.Paciente"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
[
|
||||
{"sources": [{"source_type": "csv", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "YQ=="}}]},
|
||||
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "payload": {"file_base64": "YQ=="}}]},
|
||||
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "%%%not-base64"}}]},
|
||||
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "no_such_field"}, "payload": {"file_base64": "YQ=="}}]},
|
||||
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "pac_sexo", "b": "pac_sexo"}, "payload": {"file_base64": "YQ=="}}]},
|
||||
{"sources": "nope"},
|
||||
{"sources": [{"source_type": "pdf", "target": "cacu.Paciente", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "YQ==", "mode": "regions", "regions": [], "dpi": 5000}}]},
|
||||
],
|
||||
)
|
||||
def test_malformed_commits_are_400_not_500(client, payload):
|
||||
response = client.post("/imports/commit", json=payload)
|
||||
assert response.status_code == 400, response.get_json()
|
||||
assert response.get_json()["error"]
|
||||
|
||||
|
||||
def test_page_image_rejects_absurd_dpi(client):
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
buffer = io.BytesIO()
|
||||
pdf = canvas.Canvas(buffer)
|
||||
pdf.drawString(72, 720, "hola")
|
||||
pdf.save()
|
||||
response = client.post(
|
||||
"/imports/sources/pdf/page-image",
|
||||
data={"file": (io.BytesIO(buffer.getvalue()), "a.pdf"), "page_number": "1", "dpi": "5000"},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "dpi" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_data_endpoint_pages_through_the_repository(client):
|
||||
body = client.get("/data/cacu.Paciente?limit=2").get_json()
|
||||
assert body["limit"] == 2 and len(body["rows"]) == 2 and body["total"] >= 2
|
||||
assert client.get("/data/cacu.Nope").status_code == 404
|
||||
|
||||
|
||||
def test_children_are_linked_to_parents_loaded_in_the_same_batch_whatever_the_order(client):
|
||||
"""Biopsies listed before their patients still get `pac_id` filled, since
|
||||
parents are written first within the batch's transaction. A child whose
|
||||
patient doesn't exist keeps a null FK."""
|
||||
from webapi.imports.services.link_resolver import dependency_rank, links_for
|
||||
|
||||
assert [link.fk_field for link in links_for("cacu.BiopsiaCervical")] == ["pac_id"]
|
||||
assert links_for("cacu.Paciente") == ()
|
||||
assert [link.fk_field for link in links_for("cama.Mastografia")] == ["pac_id", "ord_id"]
|
||||
assert dependency_rank("cama.Paciente") < dependency_rank("cama.OrdenesEstudio") < dependency_rank("cama.Mastografia")
|
||||
|
||||
batch = [
|
||||
_csv("exp,grado\nLINK-1,NORMAL\nNO-SUCH-PATIENT,NORMAL\n", {"exp": "pac_id_hospital", "grado": "bx_cin_grado"}, target="cacu.BiopsiaCervical"),
|
||||
_csv("exp,nac\nLINK-1,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}),
|
||||
]
|
||||
body = client.post("/imports/commit", json={"sources": batch}).get_json()
|
||||
assert [r["target"] for r in body["results"]] == ["cacu.BiopsiaCervical", "cacu.Paciente"]
|
||||
assert body["results"][0]["linked"] == {"pac_id": 1}
|
||||
|
||||
patient = _rows(client, "cacu.Paciente")["LINK-1"]
|
||||
biopsies = {r["pac_id_hospital"]: r for r in client.get("/data/cacu.BiopsiaCervical?limit=500").get_json()["rows"]}
|
||||
assert biopsies["LINK-1"]["pac_id"] == patient["pac_id"]
|
||||
assert biopsies["NO-SUCH-PATIENT"]["pac_id"] is None
|
||||
|
||||
|
||||
def test_data_endpoint_reports_columns_in_table_order(client):
|
||||
body = client.get("/data/cacu.Paciente?limit=1").get_json()
|
||||
assert body["columns"][:2] == ["pac_id", "pac_id_hospital"]
|
||||
@@ -1,240 +0,0 @@
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
|
||||
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")
|
||||
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
|
||||
|
||||
|
||||
_PACIENTE_MAPPING = {
|
||||
"pac_id_hospital": "pac_id_hospital",
|
||||
"pac_sexo": "pac_sexo",
|
||||
"pac_fecha_nacimiento": "pac_fecha_nacimiento",
|
||||
}
|
||||
|
||||
|
||||
def _csv_source(csv_bytes: bytes, *, target: str, column_mapping: dict | None = None) -> dict:
|
||||
return {
|
||||
"source_type": "csv",
|
||||
"target": target,
|
||||
"column_mapping": column_mapping or _PACIENTE_MAPPING,
|
||||
"payload": {"file_base64": base64.b64encode(csv_bytes).decode()},
|
||||
}
|
||||
|
||||
|
||||
def _json_source(records: list[dict], *, target: str, column_mapping: dict | None = None) -> dict:
|
||||
raw = json.dumps(records).encode()
|
||||
return {
|
||||
"source_type": "json",
|
||||
"target": target,
|
||||
"column_mapping": column_mapping or _PACIENTE_MAPPING,
|
||||
"payload": {"file_base64": base64.b64encode(raw).decode()},
|
||||
}
|
||||
|
||||
|
||||
def test_get_targets_lists_registered_entities(client):
|
||||
response = client.get("/imports/targets")
|
||||
assert response.status_code == 200
|
||||
keys = {t["key"] for t in response.get_json()["targets"]}
|
||||
assert {"cacu.Paciente", "tea.Pacientes"} <= keys
|
||||
cacu_target = next(t for t in response.get_json()["targets"] if t["key"] == "cacu.Paciente")
|
||||
assert cacu_target["conflict_fields"] == ["pac_id_hospital"]
|
||||
assert any(f["name"] == "pac_id_hospital" and f["required"] for f in cacu_target["fields"])
|
||||
|
||||
|
||||
def test_file_preview_returns_columns_sample_rows_and_suggested_mapping(client):
|
||||
csv_bytes = b"pac_id_hospital,Sexo\nH-PREVIEW-1,F\n"
|
||||
data = {
|
||||
"file": (io.BytesIO(csv_bytes), "pacientes.csv"),
|
||||
"source_kind": "csv",
|
||||
"target": "cacu.Paciente",
|
||||
}
|
||||
response = client.post("/imports/sources/file/preview", data=data, content_type="multipart/form-data")
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert {c["name"] for c in body["columns"]} == {"pac_id_hospital", "Sexo"}
|
||||
assert body["total_rows"] == 1
|
||||
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
|
||||
assert suggested["pac_id_hospital"] == "pac_id_hospital"
|
||||
assert suggested["Sexo"] == "pac_sexo"
|
||||
|
||||
|
||||
def test_validate_reports_row_errors_without_writing(client):
|
||||
csv_bytes = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-VALIDATE-1,F,1990-01-01\n,M,1990-01-01\n"
|
||||
response = client.post("/imports/validate", json={"source": _csv_source(csv_bytes, target="cacu.Paciente")})
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["total_rows"] == 2
|
||||
assert body["valid_count"] == 1
|
||||
assert body["error_count"] == 1
|
||||
assert body["errors"][0]["field"] == "pac_id_hospital"
|
||||
assert "H-VALIDATE-1" not in _patients(client)
|
||||
|
||||
|
||||
def test_commit_multi_source_batch_mixes_file_and_sql_within_one_domain(client, tmp_path):
|
||||
# A batch can mix file and SQL sources targeting the same domain: here a
|
||||
# CSV and a live SQL connection both land in cacu.Paciente in one commit.
|
||||
# Uses its own SQL fixture (distinct hospital id) because the row in
|
||||
# `sql_source_db` is also used by another test against this cacu.db.
|
||||
source_db_path = tmp_path / "batch_source.db"
|
||||
source_engine = create_engine(f"sqlite:///{source_db_path}")
|
||||
with source_engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE hospital_patients (id_hospital TEXT, sexo TEXT, nacimiento TEXT)"))
|
||||
conn.execute(
|
||||
text(
|
||||
"INSERT INTO hospital_patients (id_hospital, sexo, nacimiento) VALUES ('H-SQL-BATCH-1', 'M', '1990-01-01')"
|
||||
)
|
||||
)
|
||||
|
||||
cacu_csv = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-BATCH-1,F,1990-01-01\n"
|
||||
csv_source = _csv_source(cacu_csv, target="cacu.Paciente")
|
||||
sql_source = {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"id_hospital": "pac_id_hospital", "sexo": "pac_sexo", "nacimiento": "pac_fecha_nacimiento"},
|
||||
"payload": {"connection_string": f"sqlite:///{source_db_path}", "table": "hospital_patients"},
|
||||
}
|
||||
|
||||
response = client.post("/imports/commit", json={"sources": [csv_source, sql_source], "on_conflict": "reject"})
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
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
|
||||
assert {"H-BATCH-1", "H-SQL-BATCH-1"} <= set(_patients(client))
|
||||
|
||||
|
||||
def test_commit_rejects_a_batch_mixing_domains(client):
|
||||
cacu_source = _csv_source(b"pac_id_hospital,pac_sexo\nH-MIX-1,F\n", target="cacu.Paciente")
|
||||
tea_source = _json_source([{"pac_id_hospital": "T-MIX-1", "pac_sexo": "F"}], target="tea.Pacientes")
|
||||
|
||||
response = client.post("/imports/commit", json={"sources": [cacu_source, tea_source], "on_conflict": "reject"})
|
||||
assert response.status_code == 400
|
||||
assert "dominios" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_commit_on_conflict_reject_then_upsert(client):
|
||||
first_csv = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-CONFLICT-1,F,1990-01-01\n"
|
||||
first = client.post(
|
||||
"/imports/commit",
|
||||
json={"sources": [_csv_source(first_csv, target="cacu.Paciente")], "on_conflict": "reject"},
|
||||
)
|
||||
assert first.get_json()["results"][0]["created"] == 1
|
||||
|
||||
reject_again = client.post(
|
||||
"/imports/commit",
|
||||
json={"sources": [_csv_source(first_csv, target="cacu.Paciente")], "on_conflict": "reject"},
|
||||
)
|
||||
reject_body = reject_again.get_json()["results"][0]
|
||||
assert reject_body["created"] == 0
|
||||
assert reject_body["rejected"] == 1
|
||||
|
||||
upsert_csv = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-CONFLICT-1,M,1990-01-01\n"
|
||||
upsert = client.post(
|
||||
"/imports/commit",
|
||||
json={"sources": [_csv_source(upsert_csv, target="cacu.Paciente")], "on_conflict": "upsert"},
|
||||
)
|
||||
upsert_body = upsert.get_json()["results"][0]
|
||||
assert upsert_body["created"] == 0
|
||||
assert upsert_body["updated"] == 1
|
||||
|
||||
|
||||
def test_commit_upsert_rejected_for_target_without_natural_key(client):
|
||||
source = _json_source(
|
||||
[{"psi_pac_id": 1}], target="tea.EvaluacionPsicologica", column_mapping={"psi_pac_id": "psi_pac_id"}
|
||||
)
|
||||
response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "upsert"})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client):
|
||||
mapping = {"pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"}
|
||||
first = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_sexo": "F"}],
|
||||
target="tea.Pacientes", column_mapping=mapping)
|
||||
body = client.post("/imports/commit", json={"sources": [first], "on_conflict": "upsert"}).get_json()
|
||||
assert body["results"][0]["created"] == 1
|
||||
|
||||
again = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_sexo": "M"}],
|
||||
target="tea.Pacientes", column_mapping=mapping)
|
||||
body = client.post("/imports/commit", json={"sources": [again], "on_conflict": "upsert"}).get_json()
|
||||
assert body["results"][0]["created"] == 0
|
||||
assert body["results"][0]["updated"] == 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"
|
||||
|
||||
|
||||
def test_an_import_into_a_domain_without_measures_queues_no_recomputation(client):
|
||||
"""The cycle computes no TEA measures, so a TEA import saves its rows and asks for no recomputation.
|
||||
|
||||
Fails if the import queues every domain it writes to: the queue refuses TEA and the import answers 500.
|
||||
"""
|
||||
source = _json_source([{"pac_id_hospital": "T-NO-RECALC", "pac_sexo": "F"}], target="tea.Pacientes")
|
||||
response = client.post("/imports/commit", json={"sources": [source]})
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["results"][0]["created"] == 1
|
||||
assert body["indicadores_en_recalculo"] is False
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sql_source_db(tmp_path):
|
||||
db_path = tmp_path / "external_source.db"
|
||||
url = f"sqlite:///{db_path}"
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE hospital_patients (id_hospital TEXT, sexo TEXT, nacimiento TEXT)"))
|
||||
conn.execute(
|
||||
text("INSERT INTO hospital_patients (id_hospital, sexo, nacimiento) VALUES ('H-SQL-1', 'F', '1990-01-01')")
|
||||
)
|
||||
return url
|
||||
|
||||
|
||||
def test_sql_source_introspection_preview_and_commit(client, sql_source_db):
|
||||
test_conn = client.post("/imports/sources/sql/test-connection", json={"connection_string": sql_source_db})
|
||||
assert test_conn.status_code == 200
|
||||
assert test_conn.get_json()["dialect"] == "sqlite"
|
||||
|
||||
tables = client.post("/imports/sources/sql/tables", json={"connection_string": sql_source_db})
|
||||
assert "hospital_patients" in tables.get_json()["tables"]
|
||||
|
||||
columns = client.post(
|
||||
"/imports/sources/sql/columns", json={"connection_string": sql_source_db, "table": "hospital_patients"}
|
||||
)
|
||||
assert {c["name"] for c in columns.get_json()["columns"]} == {"id_hospital", "sexo", "nacimiento"}
|
||||
|
||||
preview = client.post(
|
||||
"/imports/sources/sql/preview",
|
||||
json={"connection_string": sql_source_db, "table": "hospital_patients", "target": "cacu.Paciente"},
|
||||
)
|
||||
assert preview.status_code == 200
|
||||
assert preview.get_json()["total_rows"] == 1
|
||||
|
||||
sql_import_source = {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"id_hospital": "pac_id_hospital", "sexo": "pac_sexo", "nacimiento": "pac_fecha_nacimiento"},
|
||||
"payload": {"connection_string": sql_source_db, "table": "hospital_patients"},
|
||||
}
|
||||
commit_response = client.post("/imports/commit", json={"sources": [sql_import_source], "on_conflict": "reject"})
|
||||
assert commit_response.status_code == 200
|
||||
assert commit_response.get_json()["results"][0]["created"] == 1
|
||||
@@ -1,163 +0,0 @@
|
||||
"""Fills `cacu.Paciente` from a MySQL legacy table, a CSV and a JSON file in
|
||||
one batch, through the HTTP endpoints with the `pymysql` driver.
|
||||
|
||||
Skipped unless `MYSQL_TEST_URL` is set; see `tests/test_connectors_mysql.py`
|
||||
for a local setup.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
|
||||
import pytest
|
||||
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")
|
||||
|
||||
|
||||
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")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def mysql_legacy_source():
|
||||
"""A legacy MySQL table whose column names and types are unrelated to
|
||||
`Core`'s `Paciente`."""
|
||||
engine = sa.create_engine(MYSQL_TEST_URL)
|
||||
table_name = "test_multisource_legacy_patients"
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
|
||||
conn.execute(
|
||||
sa.text(
|
||||
f"CREATE TABLE {table_name} ("
|
||||
" expediente VARCHAR(40) NOT NULL PRIMARY KEY,"
|
||||
" sexo_paciente ENUM('F','M')"
|
||||
") ENGINE=InnoDB"
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
sa.text(
|
||||
f"INSERT INTO {table_name} (expediente, sexo_paciente) VALUES "
|
||||
"('MYSQL-MULTI-1', 'F'), ('MYSQL-MULTI-2', 'M')"
|
||||
)
|
||||
)
|
||||
yield table_name
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_sql_source_http_endpoints_browse_real_mysql_schema(client, mysql_legacy_source):
|
||||
"""The schema-browsing flow the WebApp SQL wizard drives (test-connection
|
||||
-> schemas -> tables -> columns -> preview) against MySQL."""
|
||||
test_conn = client.post("/imports/sources/sql/test-connection", json={"connection_string": MYSQL_TEST_URL})
|
||||
assert test_conn.status_code == 200
|
||||
assert test_conn.get_json()["dialect"] == "mysql"
|
||||
|
||||
schemas = client.post("/imports/sources/sql/schemas", json={"connection_string": MYSQL_TEST_URL})
|
||||
assert "hospital_legacy" in schemas.get_json()["schemas"]
|
||||
|
||||
tables = client.post(
|
||||
"/imports/sources/sql/tables", json={"connection_string": MYSQL_TEST_URL, "schema": "hospital_legacy"}
|
||||
)
|
||||
assert mysql_legacy_source in tables.get_json()["tables"]
|
||||
|
||||
columns = client.post(
|
||||
"/imports/sources/sql/columns",
|
||||
json={"connection_string": MYSQL_TEST_URL, "table": mysql_legacy_source, "schema": "hospital_legacy"},
|
||||
)
|
||||
assert {c["name"] for c in columns.get_json()["columns"]} == {"expediente", "sexo_paciente"}
|
||||
|
||||
preview = client.post(
|
||||
"/imports/sources/sql/preview",
|
||||
json={
|
||||
"connection_string": MYSQL_TEST_URL,
|
||||
"table": mysql_legacy_source,
|
||||
"schema": "hospital_legacy",
|
||||
"target": "cacu.Paciente",
|
||||
},
|
||||
)
|
||||
assert preview.status_code == 200
|
||||
body = preview.get_json()
|
||||
assert body["total_rows"] == 2
|
||||
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
|
||||
# "expediente" is a column_matcher synonym for pac_id_hospital.
|
||||
assert suggested.get("expediente") == "pac_id_hospital"
|
||||
|
||||
|
||||
def test_commit_batch_mixes_mysql_json_and_csv_into_one_domain(client, mysql_legacy_source):
|
||||
csv_bytes = b"pac_id_hospital,pac_sexo\nCSV-MULTI-1,F\n"
|
||||
csv_source = {
|
||||
"source_type": "csv",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"},
|
||||
"payload": {"file_base64": base64.b64encode(csv_bytes).decode()},
|
||||
}
|
||||
|
||||
json_records = [{"id_hospital": "JSON-MULTI-1", "sexo": "M"}]
|
||||
json_source = {
|
||||
"source_type": "json",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"id_hospital": "pac_id_hospital", "sexo": "pac_sexo"},
|
||||
"payload": {"file_base64": base64.b64encode(json.dumps(json_records).encode()).decode()},
|
||||
}
|
||||
|
||||
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": [csv_source, json_source, sql_source], "on_conflict": "reject"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["ok"] is True
|
||||
assert [r["target"] for r in body["results"]] == ["cacu.Paciente"] * 3
|
||||
# csv: 1 row, json: 1 row, mysql: 2 rows
|
||||
assert [r["created"] for r in body["results"]] == [1, 1, 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):
|
||||
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(
|
||||
sa.text(f"UPDATE {mysql_legacy_source} SET sexo_paciente = 'M' WHERE expediente = 'MYSQL-MULTI-1'")
|
||||
)
|
||||
engine.dispose()
|
||||
|
||||
response = client.post("/imports/commit", json={"sources": [sql_source], "on_conflict": "upsert"})
|
||||
assert response.status_code == 200
|
||||
result = response.get_json()["results"][0]
|
||||
# Upsert reports "updated" for every row that already existed, changed or not.
|
||||
assert result["updated"] == 2
|
||||
assert result["created"] == 0
|
||||
# 'M' is coerced through SEXO_BIOLOGICO_ALIAS into the canonical value.
|
||||
assert _patients(client)["MYSQL-MULTI-1"]["pac_sexo"] == "Masculino"
|
||||
@@ -1,275 +0,0 @@
|
||||
"""Endpoint tests for the PDF routes. One round trip per resolution path:
|
||||
- detect -> table/preview -> validate -> commit, for the ruled-table
|
||||
path, writing into `cacu.Paciente`.
|
||||
- detect -> page-image -> regions/extract -> validate -> commit, for the
|
||||
OCR/region path, writing into `tea.Pacientes`.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.utils import ImageReader
|
||||
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")
|
||||
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
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Fixture PDFs
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def _build_table_pdf(rows: list[tuple[str, str, str]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
doc = SimpleDocTemplate(buffer, pagesize=letter)
|
||||
data = [["pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"], *[list(row) for row in rows]]
|
||||
table = Table(data)
|
||||
table.setStyle(
|
||||
TableStyle(
|
||||
[
|
||||
("GRID", (0, 0), (-1, -1), 1, colors.black),
|
||||
("FONTSIZE", (0, 0), (-1, -1), 12),
|
||||
("BOTTOMPADDING", (0, 0), (-1, -1), 8),
|
||||
("TOPPADDING", (0, 0), (-1, -1), 8),
|
||||
]
|
||||
)
|
||||
)
|
||||
doc.build([table])
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
_IMG_W, _IMG_H = 900, 1200
|
||||
|
||||
|
||||
def _font(size: int = 34):
|
||||
for path in (
|
||||
"/System/Library/Fonts/Helvetica.ttc",
|
||||
"/System/Library/Fonts/Supplemental/Arial.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||
):
|
||||
try:
|
||||
return ImageFont.truetype(path, size)
|
||||
except Exception:
|
||||
continue
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def _build_scanned_form_pdf(id_hospital: str, sexo: str) -> bytes:
|
||||
"""A scanned-like page with two text blocks at known pixel positions and
|
||||
no text layer, so only the OCR/region path applies."""
|
||||
img = Image.new("RGB", (_IMG_W, _IMG_H), "white")
|
||||
draw = ImageDraw.Draw(img)
|
||||
font = _font()
|
||||
draw.text((40, 100), id_hospital, fill="black", font=font)
|
||||
draw.text((400, 100), sexo, fill="black", font=font)
|
||||
|
||||
buffer = io.BytesIO()
|
||||
c = canvas.Canvas(buffer, pagesize=letter)
|
||||
page_w, page_h = letter
|
||||
reader_buf = io.BytesIO()
|
||||
img.save(reader_buf, format="PNG")
|
||||
reader_buf.seek(0)
|
||||
c.drawImage(ImageReader(reader_buf), 0, 0, width=page_w, height=page_h)
|
||||
c.showPage()
|
||||
c.save()
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
_ID_HOSPITAL_BBOX = (20 / _IMG_W, 60 / _IMG_H, 350 / _IMG_W, 180 / _IMG_H)
|
||||
_SEXO_BBOX = (380 / _IMG_W, 60 / _IMG_H, 500 / _IMG_W, 180 / _IMG_H)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Table path: detect -> table/preview -> validate -> commit (cacu.Paciente)
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_pdf_table_round_trip_detect_preview_validate_commit(client):
|
||||
pdf_bytes = _build_table_pdf([("H-PDF-TAB-1", "F", "1990-01-01"), ("H-PDF-TAB-2", "M", "1985-06-15")])
|
||||
|
||||
detect_response = client.post(
|
||||
"/imports/sources/pdf/detect",
|
||||
data={"file": (io.BytesIO(pdf_bytes), "table.pdf")},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert detect_response.status_code == 200
|
||||
detect_body = detect_response.get_json()
|
||||
assert detect_body["page_count"] == 1
|
||||
assert detect_body["has_text_layer"] is True
|
||||
assert len(detect_body["table_candidates"]) == 1
|
||||
candidate = detect_body["table_candidates"][0]
|
||||
assert candidate["row_count"] == 2
|
||||
assert candidate["column_count"] == 3
|
||||
|
||||
preview_response = client.post(
|
||||
"/imports/sources/pdf/table/preview",
|
||||
data={
|
||||
"file": (io.BytesIO(pdf_bytes), "table.pdf"),
|
||||
"page_number": str(candidate["page_number"]),
|
||||
"bbox": json.dumps(candidate["bbox"]),
|
||||
"target": "cacu.Paciente",
|
||||
},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert preview_response.status_code == 200
|
||||
preview_body = preview_response.get_json()
|
||||
assert {c["name"] for c in preview_body["columns"]} == {"pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"}
|
||||
assert preview_body["total_rows"] == 2
|
||||
suggested = {m["source_column"]: m["target_field"] for m in preview_body["suggested_mapping"]}
|
||||
assert suggested["pac_id_hospital"] == "pac_id_hospital"
|
||||
|
||||
source = {
|
||||
"source_type": "pdf",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {
|
||||
"pac_id_hospital": "pac_id_hospital",
|
||||
"pac_sexo": "pac_sexo",
|
||||
"pac_fecha_nacimiento": "pac_fecha_nacimiento",
|
||||
},
|
||||
"payload": {
|
||||
"file_base64": base64.b64encode(pdf_bytes).decode(),
|
||||
"mode": "table",
|
||||
"page_number": candidate["page_number"],
|
||||
"bbox": candidate["bbox"],
|
||||
},
|
||||
}
|
||||
|
||||
validate_response = client.post("/imports/validate", json={"source": source})
|
||||
assert validate_response.status_code == 200
|
||||
validate_body = validate_response.get_json()
|
||||
assert validate_body["total_rows"] == 2
|
||||
assert validate_body["valid_count"] == 2
|
||||
assert validate_body["error_count"] == 0
|
||||
|
||||
commit_response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "reject"})
|
||||
assert commit_response.status_code == 200
|
||||
commit_body = commit_response.get_json()
|
||||
assert commit_body["ok"] is True
|
||||
result = commit_body["results"][0]
|
||||
assert result["target"] == "cacu.Paciente"
|
||||
assert result["created"] == 2
|
||||
|
||||
assert "H-PDF-TAB-1" in _patients(client)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# page-image endpoint
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_pdf_page_image_returns_png(client):
|
||||
pdf_bytes = _build_scanned_form_pdf("H-IMG-1", "F")
|
||||
response = client.post(
|
||||
"/imports/sources/pdf/page-image",
|
||||
data={"file": (io.BytesIO(pdf_bytes), "form.pdf"), "page_number": "1"},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.content_type == "image/png"
|
||||
image = Image.open(io.BytesIO(response.data))
|
||||
assert image.format == "PNG"
|
||||
|
||||
|
||||
def test_pdf_page_image_missing_file_returns_400(client):
|
||||
response = client.post(
|
||||
"/imports/sources/pdf/page-image", data={"page_number": "1"}, content_type="multipart/form-data"
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# OCR/region path: detect -> page-image -> regions/extract -> validate ->
|
||||
# commit (tea.Pacientes)
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_pdf_region_round_trip_detect_image_extract_validate_commit(client):
|
||||
pdf_bytes = _build_scanned_form_pdf("H-PDF-OCR-1", "F")
|
||||
|
||||
detect_response = client.post(
|
||||
"/imports/sources/pdf/detect",
|
||||
data={"file": (io.BytesIO(pdf_bytes), "form.pdf")},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert detect_response.status_code == 200
|
||||
detect_body = detect_response.get_json()
|
||||
assert detect_body["has_text_layer"] is False
|
||||
assert detect_body["table_candidates"] == []
|
||||
|
||||
image_response = client.post(
|
||||
"/imports/sources/pdf/page-image",
|
||||
data={"file": (io.BytesIO(pdf_bytes), "form.pdf"), "page_number": "1"},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert image_response.status_code == 200
|
||||
assert Image.open(io.BytesIO(image_response.data)).format == "PNG"
|
||||
|
||||
regions = [
|
||||
{"target_field": "pac_id_hospital", "page_numbers": [1], "bbox": list(_ID_HOSPITAL_BBOX)},
|
||||
{"target_field": "pac_sexo", "page_numbers": [1], "bbox": list(_SEXO_BBOX)},
|
||||
]
|
||||
extract_response = client.post(
|
||||
"/imports/sources/pdf/regions/extract",
|
||||
json={"file_base64": base64.b64encode(pdf_bytes).decode(), "regions": regions},
|
||||
)
|
||||
assert extract_response.status_code == 200
|
||||
extract_body = extract_response.get_json()
|
||||
assert extract_body["rows"] == [{"pac_id_hospital": "H-PDF-OCR-1", "pac_sexo": "F"}]
|
||||
assert extract_body["warnings"] == []
|
||||
|
||||
source = {
|
||||
"source_type": "pdf",
|
||||
"target": "tea.Pacientes",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"},
|
||||
"payload": {
|
||||
"file_base64": base64.b64encode(pdf_bytes).decode(),
|
||||
"mode": "regions",
|
||||
"regions": regions,
|
||||
},
|
||||
}
|
||||
|
||||
validate_response = client.post("/imports/validate", json={"source": source})
|
||||
assert validate_response.status_code == 200
|
||||
validate_body = validate_response.get_json()
|
||||
assert validate_body["total_rows"] == 1
|
||||
assert validate_body["valid_count"] == 1
|
||||
|
||||
commit_response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "reject"})
|
||||
assert commit_response.status_code == 200
|
||||
commit_body = commit_response.get_json()
|
||||
assert commit_body["ok"] is True
|
||||
result = commit_body["results"][0]
|
||||
assert result["target"] == "tea.Pacientes"
|
||||
assert result["created"] == 1
|
||||
|
||||
|
||||
def test_pdf_detect_missing_file_returns_400(client):
|
||||
response = client.post("/imports/sources/pdf/detect", data={}, content_type="multipart/form-data")
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_pdf_regions_extract_missing_field_returns_400(client):
|
||||
response = client.post("/imports/sources/pdf/regions/extract", json={"regions": []})
|
||||
assert response.status_code == 400
|
||||
@@ -1,135 +0,0 @@
|
||||
"""What this module covers: `webapi.kpis`, the route that answers a measure's periods on request as a FHIR `Bundle`
|
||||
of `MeasureReport`s.
|
||||
|
||||
Fixtures: `base`, `manifest` and `kit` from `test_metrics_on_request` (the CaCu fixture database through the cycle,
|
||||
dbt's manifest, the kit's snapshot; skipped without `DBT_MANIFEST`); `client`, a Flask app with only this domain's KPI
|
||||
blueprint.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
|
||||
from test_metrics_on_request import EU7, EU13, IND1, base, kit, manifest, reports # noqa: F401
|
||||
from webapi.kpis import kpis_blueprint
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(base, manifest): # noqa: F811
|
||||
app = Flask(__name__)
|
||||
app.register_blueprint(kpis_blueprint("cacu", base.dominio, manifest), url_prefix="/cacu")
|
||||
return app.test_client()
|
||||
|
||||
|
||||
def counts(resource: dict) -> dict[str, int]:
|
||||
(group,) = resource["group"]
|
||||
return {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
|
||||
|
||||
|
||||
def history_entry(resource: dict) -> int:
|
||||
(entry,) = [e for e in resource["extension"] if e["url"].endswith("/reporte-id")]
|
||||
return entry["valueInteger"]
|
||||
|
||||
|
||||
def test_a_measure_s_periods_come_as_a_bundle_of_measure_reports(base, client, kit): # noqa: F811
|
||||
"""Pins down the contract: one `MeasureReport` per period asked, in order, with the kit's numbers. Fails if the
|
||||
route stops answering each period, changes the shape, or the counts drift from what the cycle published."""
|
||||
response = client.get("/cacu/indicadores/IND1?periodos=2025-S1,2025-S2")
|
||||
bundle = response.get_json(force=True)
|
||||
|
||||
assert response.status_code == 200 and response.mimetype == "application/fhir+json"
|
||||
assert (bundle["resourceType"], bundle["type"], bundle["total"]) == ("Bundle", "searchset", 2)
|
||||
for entry, period_id in zip(bundle["entry"], ("2025-S1", "2025-S2")):
|
||||
report = entry["resource"]
|
||||
assert report["resourceType"] == "MeasureReport" and report["measure"] == "cacu/IND1|0.3.2"
|
||||
numerator, denominator = kit[IND1][period_id]["published"]["total|total"]
|
||||
assert counts(report) == {"initial-population": denominator, "denominator": denominator,
|
||||
"numerator": numerator}
|
||||
if os.environ.get("MEASURE_REPORT_OUT"):
|
||||
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_ind1.json").write_text(
|
||||
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
def test_without_a_knowledge_cutoff_the_last_load_makes_the_answer_stable(base, client): # noqa: F811
|
||||
"""Pins down: by default the knowledge cut-off is the last load's start, so asking again before the next load
|
||||
reads the stored answer. Fails if the default becomes "now", which would store a new answer per request."""
|
||||
first = client.get("/cacu/indicadores/IND1?periodos=2025-S1").get_json(force=True)
|
||||
before = reports(base)
|
||||
second = client.get("/cacu/indicadores/IND1?periodos=2025-S1").get_json(force=True)
|
||||
|
||||
assert history_entry(second["entry"][0]["resource"]) == history_entry(first["entry"][0]["resource"])
|
||||
assert reports(base) == before
|
||||
|
||||
|
||||
def test_a_measure_with_strata_brings_its_stratifier(client):
|
||||
"""Pins down: EU13's reports carry its strata, by age and by follow-up status. Fails if the route drops one."""
|
||||
bundle = client.get("/cacu/indicadores/CACU_EU13?periodos=2025-S1").get_json(force=True)
|
||||
stratifiers = bundle["entry"][0]["resource"]["group"][0]["stratifier"]
|
||||
|
||||
assert [s["code"][0]["text"] for s in stratifiers] == ["grupo_edad", "estatus_seguimiento"]
|
||||
if os.environ.get("MEASURE_REPORT_OUT"):
|
||||
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_eu13.json").write_text(
|
||||
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
def test_the_list_names_what_is_answered_on_request(client):
|
||||
"""Pins down: `/indicadores` lists the measures the manifest defines for the domain. Fails if one is missing."""
|
||||
listed = {m["id"] for m in client.get("/cacu/indicadores").get_json()}
|
||||
|
||||
assert listed == {IND1.split("/")[1], EU13.split("/")[1], EU7.split("/")[1], "CACU_EU_TIEMPO_REPORTE",
|
||||
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_CONFIRMACION_CITOLOGIA",
|
||||
"CACU_RIESGO_BANDA"}
|
||||
|
||||
|
||||
def test_a_duration_comes_as_a_report_with_its_median_and_quartiles(client):
|
||||
"""Pins down the route for durations: the samples measurable and measured as populations, the median as the
|
||||
score in days with the quartiles as its extensions, and the event cut-off it was asked at (the last load's day
|
||||
by default). 2025-S2's samples resolved in 40 and 161 days. Fails if a duration stops being served or its
|
||||
contract changes."""
|
||||
bundle = client.get("/cacu/indicadores/CACU_DIAS_TOMA_DIAGNOSTICO?periodos=2025-S2").get_json(force=True)
|
||||
(entry,) = bundle["entry"]
|
||||
report = entry["resource"]
|
||||
(group,) = report["group"]
|
||||
assert report["measure"] == "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3"
|
||||
assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == {
|
||||
"initial-population": 4, "measure-observation": 2}
|
||||
assert group["measureScore"]["value"] == 100.5 and group["measureScore"]["unit"] == "d"
|
||||
assert [e["valueDecimal"] for e in group["measureScore"]["extension"]] == [70.25, 130.75]
|
||||
assert any(e["url"].endswith("corte-evento") for e in report["extension"])
|
||||
if os.environ.get("MEASURE_REPORT_OUT"):
|
||||
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_dias.json").write_text(
|
||||
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("path", "status"), [
|
||||
("/cacu/indicadores/NOPE?periodos=2025-S1", 404),
|
||||
("/cacu/indicadores/IND1", 400),
|
||||
("/cacu/indicadores/IND1?periodos=2025-S1&corte_evento=30-06-2025", 400),
|
||||
("/cacu/indicadores/IND1?periodos=2025-S1&corte_conocimiento=ayer", 400),
|
||||
("/cacu/indicadores/IND1?periodos=2031-S1", 404),
|
||||
])
|
||||
def test_a_bad_question_gets_a_clear_error(client, path, status):
|
||||
"""Pins down the errors: an unknown measure or period is 404, a missing or misspelled parameter 400. Fails if one
|
||||
of them becomes a 500."""
|
||||
response = client.get(path)
|
||||
|
||||
assert response.status_code == status and "error" in response.get_json()
|
||||
|
||||
|
||||
def test_a_composition_comes_with_its_categories(client, kit):
|
||||
"""Pins down: EU7's reports carry the categories as a `resultado` stratifier, with the kit's counts, under the
|
||||
route's default knowledge cut-off (the last load). Fails if the route stops telling compositions from
|
||||
proportions, or a result's knowledge date stops being compared as the type it's stored in."""
|
||||
bundle = client.get("/cacu/indicadores/CACU_EU7?periodos=2025-S1,2025-S2").get_json(force=True)
|
||||
stratifiers = [e["resource"]["group"][0]["stratifier"][0] for e in bundle["entry"]]
|
||||
|
||||
assert [s["code"] for s in stratifiers] == [[{"text": "resultado"}]] * 2
|
||||
for stratifier, period_id in zip(stratifiers, ("2025-S1", "2025-S2")):
|
||||
expected = {k.split("|")[2]: n for k, n in kit[EU7][period_id]["published"].items() if k.startswith("total|")}
|
||||
assert {s["value"]["text"]: s["population"][0]["count"] for s in stratifier["stratum"]} == expected
|
||||
if os.environ.get("MEASURE_REPORT_OUT"):
|
||||
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_eu7.json").write_text(
|
||||
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
@@ -1,100 +0,0 @@
|
||||
"""What this module covers: compositions answered from dbt's semantic layer on the hand-written cases their rules were
|
||||
written with, one database per case: CACU_CONFIRMACION_CITOLOGIA (`fixtures/casos_confirmacion_citologia.toml`: the
|
||||
last valid sample decides, the most severe biopsy of that sample by the cut-off is the category, a biopsy of another
|
||||
sample doesn't count) and CACU_RIESGO_BANDA (`fixtures/casos_riesgo_banda.toml`: the current batch of estimates, the
|
||||
latest version of each, the bands by the rules' cut points).
|
||||
|
||||
Fixtures: each case's database, migrated, with only its rows: staging rows through the load (a patient for each
|
||||
`pac_id` named) and cohort builds and risk estimates as they are; its rule overrides in `def_parametro`; dbt's views
|
||||
created by the cycle (`catalogs` … `event_models`; needs `DBT_MANIFEST`).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import tomllib
|
||||
from dataclasses import replace
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from conftest import base_de
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, EvaluacionRiesgo, EvaluacionRiesgoLote
|
||||
from core.cacu.models import BiopsiaCervical, CitologiaCervical, Paciente
|
||||
from webapi.compositions import answer_composition, composition_definitions
|
||||
from webapi.metrics import Question
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
FILES = ("casos_confirmacion_citologia.toml", "casos_riesgo_banda.toml")
|
||||
TABLES = {m.__tablename__: m for m in (CitologiaCervical, BiopsiaCervical, CohorteArmado, CohorteMiembro,
|
||||
EvaluacionRiesgoLote, EvaluacionRiesgo)}
|
||||
STAGING = ("citologiacervical", "biopsiacervical")
|
||||
# Rows go in by their parents first.
|
||||
ORDER = ("citologiacervical", "biopsiacervical", "cohorte_armado", "cohorte_miembro", "evaluacion_riesgo_lote",
|
||||
"evaluacion_riesgo")
|
||||
|
||||
|
||||
def cases():
|
||||
for name in FILES:
|
||||
document = tomllib.loads((FIXTURES / name).read_text(encoding="utf-8"))
|
||||
templates = document.get("plantillas", {})
|
||||
for case in document["caso"]:
|
||||
rows = [row for t in case.get("incluye", ()) for row in templates[t]] + case["filas"]
|
||||
yield pytest.param(document["measure"], {**case, "filas": rows}, id=case["nombre"])
|
||||
|
||||
|
||||
def rows_of(case: dict):
|
||||
"""What the case's rows insert: a patient for each `pac_id`, then every row by its parents first."""
|
||||
def insert(session):
|
||||
for pac_id in sorted({row["pac_id"] for row in case["filas"] if "pac_id" in row}):
|
||||
session.add(Paciente(pac_id=pac_id, pac_id_hospital=f"H-{pac_id:03d}", pac_sexo="Femenino",
|
||||
pac_fecha_nacimiento=date(1980, 1, 1)))
|
||||
session.flush()
|
||||
for row in sorted(case["filas"], key=lambda r: ORDER.index(r["tabla"])):
|
||||
data = {k: v for k, v in row.items() if k != "tabla"}
|
||||
if row["tabla"] in STAGING:
|
||||
data["pac_id_hospital"] = f"H-{row['pac_id']:03d}"
|
||||
session.add(TABLES[row["tabla"]](**data))
|
||||
session.flush()
|
||||
session.commit()
|
||||
return insert
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("url", "case"), list(cases()))
|
||||
def test_each_case_answers_what_its_rules_say(tmp_path, sin_supresion, url, case):
|
||||
"""Pins down each hand-written case: the count in each category it names (zero included), the patients in the
|
||||
categories it lists and their stratum values, at its cut-off and with its rules. Fails if the measure stops
|
||||
meaning what the case says; the case's name says which rule."""
|
||||
manifest = os.environ.get("DBT_MANIFEST")
|
||||
if not manifest:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
base = base_de("cacu", tmp_path, rows_of(case))
|
||||
base.run("catalogs", "load", "registry", "definitions", "event_models", parameters=sin_supresion,
|
||||
allow_undecided=True)
|
||||
with base.motor.begin() as connection:
|
||||
for key, value in case.get("parametros", {}).items():
|
||||
connection.execute(text("update def_parametro set valor = :v where clave = :k"),
|
||||
{"v": json.dumps(value), "k": key})
|
||||
definition = composition_definitions(Path(manifest))[url]
|
||||
d = base.dominio
|
||||
for period_id in sorted({*case.get("espera", {}), *case.get("unidades", {}), *case.get("estratos", {})}):
|
||||
result = answer_composition(
|
||||
"cacu", definition, Question(url, period_id, case.get("corte")), parameters=d.def_parametro_repository,
|
||||
periods=d.dim_periodo_repository, history=d.history_repository, queries=d.dbt_query_repository,
|
||||
allow_undecided=True)
|
||||
for category, n in case.get("espera", {}).get(period_id, {}).items():
|
||||
assert result.categories.get(category.removeprefix("cat:"), 0) == n, (period_id, category)
|
||||
with base.motor.connect() as connection:
|
||||
units = connection.execute(text(
|
||||
"select valor_id, unidad_id from measure_report_unidad where report_id = :r"),
|
||||
{"r": result.report_id}).all()
|
||||
strata = connection.execute(text(
|
||||
"select estrato_id, unidad_id, estrato_valor from measure_report_unidad_estrato where report_id = :r"),
|
||||
{"r": result.report_id}).all()
|
||||
for category, expected in case.get("unidades", {}).get(period_id, {}).items():
|
||||
assert sorted(u for v, u in units if v == category.removeprefix("cat:")) == sorted(map(str, expected)), (
|
||||
period_id, category)
|
||||
for stratum, expected in case.get("estratos", {}).get(period_id, {}).items():
|
||||
assert {u: v for s, u, v in strata if s == stratum} == expected, (period_id, stratum)
|
||||
base.motor.dispose()
|
||||
@@ -1,474 +0,0 @@
|
||||
"""What this module covers: `webapi.metrics` and `webapi.compositions`, CaCu's measures answered on request from
|
||||
dbt's semantic definitions, with the period and both cut-offs in the question, and `MeasureHistoryRepository`, which
|
||||
keeps each answer under its key.
|
||||
|
||||
Fixtures: `base`, the CaCu fixture database through the cycle up to `event_models` (which creates dbt's event models);
|
||||
`manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `kit`, what the kit computed for IND1, EU13
|
||||
and EU7 on the same fixture data (`fixtures/kit_cacu_snapshot.json`): the oracle these answers were proven against.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from conftest import base_de
|
||||
from core.cacu.models import BiopsiaCervical, CitologiaCervical
|
||||
from webapi.compositions import answer_composition, composition_definitions, composition_report
|
||||
from webapi.metrics import Question, answer, measure_definitions, measure_report
|
||||
from webapi.orchestration import run
|
||||
|
||||
IND1, EU13, EU7 = "cacu/IND1", "cacu/CACU_EU13", "cacu/CACU_EU7"
|
||||
STATUS = "estatus_seguimiento"
|
||||
HASTA_MODELOS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
PERIODS = [f"2025-{m:02d}" for m in range(1, 13)] + ["2025-S1", "2025-S2"]
|
||||
SNAPSHOT = Path(__file__).parent / "fixtures" / "kit_cacu_snapshot.json"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manifest():
|
||||
path = os.environ.get("DBT_MANIFEST")
|
||||
if not path:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
return Path(path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def base(tmp_path, sin_supresion, manifest):
|
||||
base = base_de("cacu", tmp_path)
|
||||
base.run(*HASTA_MODELOS, parameters=sin_supresion, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def kit():
|
||||
return json.loads(SNAPSHOT.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def definition(manifest):
|
||||
return measure_definitions(manifest)[IND1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def eu13(manifest):
|
||||
return measure_definitions(manifest)[EU13]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def eu7(manifest):
|
||||
return composition_definitions(manifest)[EU7]
|
||||
|
||||
|
||||
def repositories(base) -> dict:
|
||||
d = base.dominio
|
||||
return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository,
|
||||
"history": d.history_repository, "queries": d.dbt_query_repository, "allow_undecided": True}
|
||||
|
||||
|
||||
def ask(base, definition, period_id, *, event_cutoff=None, knowledge_cutoff=None):
|
||||
question = Question(definition.url, period_id, event_cutoff, knowledge_cutoff)
|
||||
if definition.url == EU7:
|
||||
return answer_composition("cacu", definition, question, **repositories(base))
|
||||
return answer("cacu", definition, question, **repositories(base))
|
||||
|
||||
|
||||
def units(base, report_id: int) -> list[list]:
|
||||
with base.motor.connect() as connection:
|
||||
return sorted(map(list, connection.execute(text(
|
||||
"select grupo, resultado_id, unidad_id, pac_id, valor_id from measure_report_unidad where report_id = :r"),
|
||||
{"r": report_id}).all()))
|
||||
|
||||
|
||||
def strata_rows(base, report_id: int, stratum: str = "grupo_edad") -> list[list]:
|
||||
with base.motor.connect() as connection:
|
||||
return sorted(map(list, connection.execute(text(
|
||||
"select unidad_id, estrato_valor from measure_report_unidad_estrato where report_id = :r "
|
||||
"and estrato_id = :e"), {"r": report_id, "e": stratum}).all()))
|
||||
|
||||
|
||||
def proportion_cells(result) -> dict:
|
||||
"""An answer as the snapshot keeps what `v_c1` published: `{"stratum|value": [numerator, denominator]}`."""
|
||||
cells = {"total|total": [result.numerator, result.denominator]}
|
||||
for stratum, values in result.strata.items():
|
||||
cells |= {f"{stratum}|{v}": [c.numerator, c.denominator] for v, c in values.items()}
|
||||
return cells
|
||||
|
||||
|
||||
def composition_cells(result) -> dict:
|
||||
"""An answer as the snapshot keeps what `v_c2` published: `{"stratum|value|category": n}`."""
|
||||
cells = {f"total|total|{c}": n for c, n in result.categories.items()}
|
||||
for stratum, values in result.strata.items():
|
||||
cells |= {f"{stratum}|{v}|{c}": n for v, cs in values.items() for c, n in cs.items()}
|
||||
return cells
|
||||
|
||||
|
||||
def without(cells: dict, stratum: str) -> dict:
|
||||
return {k: v for k, v in cells.items() if not k.startswith(f"{stratum}|")}
|
||||
|
||||
|
||||
def reports(base) -> int:
|
||||
with base.motor.connect() as connection:
|
||||
return connection.execute(text("select count(*) from measure_report")).scalar_one()
|
||||
|
||||
|
||||
def reload(base, change) -> None:
|
||||
"""Changes the staging as the ingestion would and runs `load`: a new load, known later than everything before."""
|
||||
time.sleep(0.01)
|
||||
with Session(base.motor) as session:
|
||||
change(session)
|
||||
session.commit()
|
||||
run(base.ctx, only=["load"])
|
||||
|
||||
|
||||
def test_ind1_answers_what_the_kit_computed(base, definition, kit):
|
||||
"""Pins down: with no cut-off, every period's IND1 has the kit's units and its numbers. Fails if the semantic
|
||||
definition (event model, metrics, filter) stops meaning what the kit's IND1 meant."""
|
||||
for period_id in PERIODS:
|
||||
result, expected = ask(base, definition, period_id), kit[IND1][period_id]
|
||||
assert units(base, result.report_id) == expected["units"], period_id
|
||||
assert proportion_cells(result)["total|total"] == expected["published"].get("total|total", [0, 0]), period_id
|
||||
|
||||
|
||||
def test_eu13_with_its_age_strata_answers_what_the_kit_computed(base, eu13, kit):
|
||||
"""Pins down: EU13 gives the kit's units, each patient's age group at the period's start and the numbers by age
|
||||
in every period. Fails if the event model, the report date's condition or the age from `dim_fecha` drift."""
|
||||
for period_id in PERIODS:
|
||||
result, expected = ask(base, eu13, period_id), kit[EU13][period_id]
|
||||
assert units(base, result.report_id) == expected["units"], period_id
|
||||
assert strata_rows(base, result.report_id) == expected["grupo_edad"], period_id
|
||||
assert without(proportion_cells(result), STATUS) == (expected["published"] or {"total|total": [0, 0]}), period_id
|
||||
|
||||
|
||||
def test_eu7_puts_each_patient_in_her_last_valid_result_as_the_kit_did(base, eu7, kit):
|
||||
"""Pins down EU7, a composition: each patient in the category of her last valid sample (with a result and a
|
||||
satisfactory specimen) or SIN_DATO, with her age group, and the kit's counts by category, total and by age.
|
||||
Fails if the ranking (validity, then the latest sample, then the source id) or the validity rule drifts."""
|
||||
for period_id in PERIODS:
|
||||
result, expected = ask(base, eu7, period_id), kit[EU7][period_id]
|
||||
assert units(base, result.report_id) == expected["units"], period_id
|
||||
assert strata_rows(base, result.report_id) == expected["grupo_edad"], period_id
|
||||
assert without(composition_cells(result), STATUS) == expected["published"], period_id
|
||||
|
||||
|
||||
def test_every_stratum_value_written_is_in_the_catalog(base, eu13, eu7):
|
||||
"""Pins down: the strata an answer writes satisfy their foreign key to `cat_estrato_valor`, which SQLite doesn't
|
||||
enforce unless asked and SQL Server always does. Fails if `MeasureHistoryRepository.record` stops adding the
|
||||
stratum values the catalog lacks."""
|
||||
for d in (eu13, eu7):
|
||||
ask(base, d, "2025-S1")
|
||||
with base.motor.connect() as connection:
|
||||
written = connection.execute(text("select count(*) from measure_report_unidad_estrato")).scalar()
|
||||
broken = connection.execute(text("pragma foreign_key_check('measure_report_unidad_estrato')")).all()
|
||||
assert written > 0
|
||||
assert broken == []
|
||||
|
||||
|
||||
def test_a_stored_answer_reads_back_the_same(base, definition, eu13, eu7):
|
||||
"""Pins down: asking again reads the stored answer from its units' counts, with no view, and it's the same
|
||||
answer, strata included. Fails if `MeasureHistoryRepository.counts` and the computation stop agreeing."""
|
||||
for d in (definition, eu13, eu7):
|
||||
first = ask(base, d, "2025-S1", event_cutoff=date(2025, 6, 30))
|
||||
before = reports(base)
|
||||
again = ask(base, d, "2025-S1", event_cutoff=date(2025, 6, 30))
|
||||
assert (again.report_id, again.stored_before, reports(base)) == (first.report_id, True, before)
|
||||
if d is eu7:
|
||||
assert (again.categories, again.strata) == (first.categories, first.strata)
|
||||
else:
|
||||
assert proportion_cells(again) == proportion_cells(first)
|
||||
|
||||
|
||||
def test_the_event_cutoff_leaves_out_later_facts(base, definition, kit):
|
||||
"""Pins down: S1 cut at March 31 counts the patients of January to March: the union of the kit's monthly units.
|
||||
Fails if the cut-off stops filtering the event date."""
|
||||
result = ask(base, definition, "2025-S1", event_cutoff=date(2025, 3, 31))
|
||||
months = sorted({tuple(u) for m in (1, 2, 3) for u in kit[IND1][f"2025-{m:02d}"]["units"]})
|
||||
|
||||
assert units(base, result.report_id) == [list(u) for u in months]
|
||||
|
||||
|
||||
def test_a_late_fact_counts_only_under_a_later_knowledge_cutoff(base, definition):
|
||||
"""Pins down: a cytology of S1 loaded later doesn't change what was known before its load; asked with a later
|
||||
knowledge cut-off, it counts. Fails if `conocida_en` stops being a condition of the question."""
|
||||
known = datetime.now(timezone.utc)
|
||||
before = ask(base, definition, "2025-S1", knowledge_cutoff=known)
|
||||
|
||||
def late_cytology(session):
|
||||
h005 = session.exec(select(CitologiaCervical).where(CitologiaCervical.pac_id_hospital == "H-005")).first()
|
||||
session.add(CitologiaCervical(pac_id=h005.pac_id, pac_id_hospital="H-005", cit_fecha_toma=date(2025, 3, 10),
|
||||
cit_calidad_especimen="SATISFACTORIO", cit_fecha_reporte=date(2025, 3, 20),
|
||||
cit_celulas_escamosas="LIEAG"))
|
||||
reload(base, late_cytology)
|
||||
|
||||
again = ask(base, definition, "2025-S1", knowledge_cutoff=known)
|
||||
fresh_then = ask(base, definition, "2025-S1", knowledge_cutoff=known, event_cutoff=date(2025, 6, 30))
|
||||
now = ask(base, definition, "2025-S1", knowledge_cutoff=datetime.now(timezone.utc))
|
||||
|
||||
assert again.report_id == before.report_id
|
||||
assert (fresh_then.numerator, fresh_then.denominator) == (before.numerator, before.denominator)
|
||||
assert (now.numerator, now.denominator) == (before.numerator + 1, before.denominator + 1)
|
||||
|
||||
|
||||
def test_a_changed_fact_is_kept_by_the_history_not_by_the_knowledge_cutoff(base, definition):
|
||||
"""Pins down the limit of the knowledge cut-off: silver keeps one version of each row, so after H-004's LIEAG of
|
||||
July becomes NEGATIVO, recomputing S2 as known before the change can't give the old numerator; only the stored
|
||||
answer still does. Fails if silver starts keeping versions (`dbt snapshot`): then expect the old one."""
|
||||
known = datetime.now(timezone.utc)
|
||||
shown = ask(base, definition, "2025-S2", knowledge_cutoff=known)
|
||||
assert shown.numerator == 1
|
||||
|
||||
def corrected(session):
|
||||
row = session.exec(select(CitologiaCervical).where(
|
||||
CitologiaCervical.pac_id_hospital == "H-004", CitologiaCervical.cit_fecha_toma == date(2025, 7, 1))).one()
|
||||
row.cit_celulas_escamosas = "NEGATIVO"
|
||||
reload(base, corrected)
|
||||
|
||||
stored = ask(base, definition, "2025-S2", knowledge_cutoff=known)
|
||||
recomputed_then = ask(base, definition, "2025-S2", knowledge_cutoff=known, event_cutoff=date(2025, 12, 31))
|
||||
|
||||
assert (stored.report_id, stored.numerator) == (shown.report_id, 1)
|
||||
assert recomputed_then.numerator == 0 # the July result now counts as known after `known`: it's left out
|
||||
assert ask(base, definition, "2025-S2", knowledge_cutoff=datetime.now(timezone.utc)).numerator == 0
|
||||
|
||||
|
||||
def test_eu13_counts_a_qualifying_biopsy_by_its_sample_and_its_report_date(base, eu13):
|
||||
"""Pins down EU13's numerator, which the fixture leaves at 0: once H-004's biopsy of August 1 (from the July 1
|
||||
sample) is LIEAG she counts in 2025-07 and 2025-S2, and an event cut-off before the report leaves her out.
|
||||
Fails if the numerator stops following the sample's period, the grade rule, or the report's date."""
|
||||
def lieag(session):
|
||||
biopsy = session.exec(select(BiopsiaCervical).where(BiopsiaCervical.pac_id_hospital == "H-004")).one()
|
||||
biopsy.bx_cin_grado = "LIEAG"
|
||||
reload(base, lieag)
|
||||
|
||||
assert ask(base, eu13, "2025-07").numerator == 1
|
||||
assert ask(base, eu13, "2025-S2").numerator == 1
|
||||
assert ask(base, eu13, "2025-S2", event_cutoff=date(2025, 7, 31)).numerator == 0
|
||||
|
||||
|
||||
def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7):
|
||||
"""Pins down the contract WebApi serves: a FHIR `MeasureReport` with the measure's url and version, FHIR's
|
||||
inclusive period end, each population's count, the score, strata as a `stratifier`, and a composition's
|
||||
categories as one more. Fails if a population, the score, a stratum or a category stops matching the answer."""
|
||||
period = base.dominio.dim_periodo_repository.get("2025-S1")
|
||||
at = datetime(2026, 1, 2, tzinfo=timezone.utc)
|
||||
|
||||
report = measure_report(definition, Question(IND1, "2025-S1"), ask(base, definition, "2025-S1"), period, at)
|
||||
(group,) = report["group"]
|
||||
assert report["measure"] == "cacu/IND1|0.3.2"
|
||||
assert report["period"] == {"start": "2025-01-01", "end": "2025-06-30"}
|
||||
assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == {
|
||||
"initial-population": 4, "denominator": 4, "numerator": 1}
|
||||
assert group["measureScore"] == {"value": 0.25}
|
||||
assert report["improvementNotation"]["coding"][0]["code"] == "decrease"
|
||||
|
||||
stratifiers = measure_report(eu13, Question(EU13, "2025-S1"), ask(base, eu13, "2025-S1"), period,
|
||||
at)["group"][0]["stratifier"]
|
||||
assert [s["code"] for s in stratifiers] == [[{"text": "grupo_edad"}], [{"text": STATUS}]]
|
||||
|
||||
composition = composition_report(eu7, Question(EU7, "2025-S1"), ask(base, eu7, "2025-S1"), period, at)
|
||||
by_result = composition["group"][0]["stratifier"][0]
|
||||
assert by_result["code"] == [{"text": "resultado"}]
|
||||
assert {s["value"]["text"]: s["population"][0]["count"] for s in by_result["stratum"]} == {
|
||||
"LIEBG": 1, "NEGATIVO": 2, "SIN_DATO": 1}
|
||||
if os.environ.get("MEASURE_REPORT_OUT"):
|
||||
Path(os.environ["MEASURE_REPORT_OUT"]).write_text(json.dumps(composition, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
ORACLE = Path(__file__).parent / "fixtures" / "kit_oracle_cacu.json"
|
||||
TIEMPO_REPORTE = "cacu/CACU_EU_TIEMPO_REPORTE"
|
||||
DIAS_TOMA_DIAGNOSTICO = "cacu/CACU_DIAS_TOMA_DIAGNOSTICO"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", [TIEMPO_REPORTE, DIAS_TOMA_DIAGNOSTICO])
|
||||
def test_each_duration_is_the_kit_s_in_every_period(base, manifest, url):
|
||||
"""Pins down the duration construct, for the time to the result and the time to the first note that resolves
|
||||
the sample: each sample of the period is measurable unless it has no value and its horizon hasn't passed by the
|
||||
cut-off (and, to diagnosis, unless a cervical cancer note came before it); the measured ones carry their days
|
||||
(`dim_fecha.dia_num` differences); n, the median and the quartiles (inclusive, ANSI) and the excluded are the
|
||||
kit's where it didn't suppress them (suppression isn't part of the prototype). Fails if the horizon, the day
|
||||
arithmetic, the resolving note, the exclusion or the quartiles' interpolation drift."""
|
||||
from webapi.durations import answer_duration, duration_definitions
|
||||
|
||||
expected = json.loads(ORACLE.read_text(encoding="utf-8"))[url]
|
||||
definition = duration_definitions(manifest)[url]
|
||||
for period_id, kit_report in expected["periodos"].items():
|
||||
result = answer_duration("cacu", definition, Question(url, period_id), **repositories(base))
|
||||
assert units_with_numbers(base, result.report_id) == kit_report["units"], period_id
|
||||
published = dict(zip(kit_report["published_columns"], next(
|
||||
row for row in kit_report["published"] if row[1] == "total")))
|
||||
if published["suprimido"]:
|
||||
continue
|
||||
assert (result.n, result.median, result.q1, result.q3, result.excluded) == (
|
||||
published["n"], published["mediana"], published["q1"], published["q3"], published["n_excluido"]), period_id
|
||||
|
||||
|
||||
def units_with_numbers(base, report_id: int) -> list[list]:
|
||||
with base.motor.connect() as connection:
|
||||
return sorted(map(list, connection.execute(text(
|
||||
"select grupo, resultado_id, unidad_id, pac_id, valor_id, numero from measure_report_unidad "
|
||||
"where report_id = :r"), {"r": report_id}).all()))
|
||||
|
||||
|
||||
def test_the_follow_up_status_is_the_kit_s_in_every_period(base, eu13, eu7):
|
||||
"""Pins down: EU13's and EU7's `estatus_seguimiento` gives each unit the kit's status at the period's start, and
|
||||
the kit's published numbers by status. Fails if the timeline stratum, the procedures it infers or the order of
|
||||
the values drift. The fixture's patients are all PRE_COLPOSCOPIA; the other statuses are pinned down by
|
||||
`test_the_follow_up_status_follows_the_timeline`."""
|
||||
oracle = json.loads(ORACLE.read_text(encoding="utf-8"))
|
||||
for period_id in PERIODS:
|
||||
for definition in (eu13, eu7):
|
||||
result, expected = ask(base, definition, period_id), oracle[definition.url]["periodos"][period_id]
|
||||
assert strata_rows(base, result.report_id, STATUS) == sorted(
|
||||
[u, v] for u, s, v in expected["strata"] if s == STATUS), (definition.url, period_id)
|
||||
rows = [dict(zip(expected["published_columns"], r)) for r in expected["published"]]
|
||||
if definition is eu13:
|
||||
published = {f"{STATUS}|{r['estrato_valor']}": [r["numerador"], r["denominador"]]
|
||||
for r in rows if r["estrato_id"] == STATUS}
|
||||
ours = {k: v for k, v in proportion_cells(result).items() if k.startswith(f"{STATUS}|")}
|
||||
else:
|
||||
published = {f"{STATUS}|{r['estrato_valor']}|{r['categoria']}": r["n"]
|
||||
for r in rows if r["estrato_id"] == STATUS and r["n"]}
|
||||
ours = {k: v for k, v in composition_cells(result).items() if k.startswith(f"{STATUS}|")}
|
||||
assert ours == published, (definition.url, period_id)
|
||||
|
||||
|
||||
def kit_status(base, reference: str) -> dict[str, str]:
|
||||
"""What the kit's `estatus_al` says each patient's status was before `reference`, with the kit's rules."""
|
||||
import tomllib
|
||||
|
||||
from webapi.follow_up.status import estatus_al, reglas_de
|
||||
from webapi.orchestration.reference.rules import RUTA_PARAMETROS
|
||||
from webapi.follow_up.listing import leer_estrato
|
||||
from sqlalchemy import bindparam
|
||||
|
||||
rules = tomllib.loads(RUTA_PARAMETROS.read_text(encoding="utf-8"))
|
||||
|
||||
def rule(key):
|
||||
node = rules
|
||||
for part in key.split("."):
|
||||
node = node[part]
|
||||
return node["valor"]
|
||||
|
||||
values = {name: rule(key) for name, key in leer_estrato("cacu", STATUS).parametros.items()}
|
||||
status = estatus_al(bindparam("referencia"), reglas_de(values))
|
||||
query = select(status.c.pac_id, status.c.estatus)
|
||||
named = set(query.compile().params)
|
||||
with base.motor.connect() as connection:
|
||||
rows = connection.execute(query, {n: v for n, v in {**values, "referencia": reference}.items() if n in named})
|
||||
return {str(pac_id): value for pac_id, value in rows}
|
||||
|
||||
|
||||
def follow_up(session) -> None:
|
||||
"""Notes and orders that move three of the fixture's patients along follow-up, in a load of their own.
|
||||
|
||||
Patient 1 (sampled 2025-02-10): a valuation visit, a colposcopy note by its reason (with an accent) and a biopsy
|
||||
order that day, then a treatment note: POST_TRATAMIENTO from then on. Patient 4 (sampled 2025-05-30): a
|
||||
valuation visit, then a colposcopy note whose ICD-10 came «S/C» but whose diagnosis text names HPV:
|
||||
POST_COLPOSCOPIA. Patient 3 (sampled 2025-01-20): a colposcopy note with no valuation before it, which doesn't
|
||||
count, and her first cytology ordered by a specialty outside surveillance: no status holds, INFO_INSUFICIENTE.
|
||||
"""
|
||||
from core.cacu.indicadores.models import Carga, Observacion, Procedimiento
|
||||
|
||||
load = Carga(fuente="seguimiento", inicio=datetime.now(timezone.utc))
|
||||
session.add(load)
|
||||
session.flush()
|
||||
|
||||
def procedure(pac_id, study, kind, when, key, **observed) -> Procedimiento:
|
||||
p = Procedimiento(fuente_tabla="seguimiento", fuente_id=key, carga_id=load.carga_id, pac_id=pac_id,
|
||||
estudio_id=study, clase=kind, fecha=date.fromisoformat(when))
|
||||
session.add(p)
|
||||
session.flush()
|
||||
for result, (column_name, value) in observed.items():
|
||||
session.add(Observacion(procedimiento_id=p.procedimiento_id, carga_id=load.carga_id, pac_id=pac_id,
|
||||
resultado_id=result.replace("__", "."), **{column_name: value}))
|
||||
return p
|
||||
|
||||
def note(pac_id, when, key, *, cie, specialty="CLINICA_MUJER_COLPOSCOPIA", reason=None, text_dx=None):
|
||||
observed = {"nota_medica__diagnostico": ("valor_texto", cie),
|
||||
"nota_medica__especialidad": ("valor_id", specialty)}
|
||||
if reason:
|
||||
observed["nota_medica__motivo"] = ("valor_texto", reason)
|
||||
if text_dx:
|
||||
observed["nota_medica__diagnostico_texto"] = ("valor_texto", text_dx)
|
||||
procedure(pac_id, "nota_medica", "encuentro", when, key, **observed)
|
||||
|
||||
note(1, "2025-02-20", "n1a", cie="R876")
|
||||
note(1, "2025-03-03", "n1b", cie="Z000", reason="Acude a colposcopía")
|
||||
procedure(1, "biopsia", "orden", "2025-03-03", "o1")
|
||||
note(1, "2025-04-01", "n1c", cie="D06", specialty="CIRUGIA_ONCOLOGICA")
|
||||
note(4, "2025-06-05", "n4a", cie="R876")
|
||||
note(4, "2025-06-10", "n4b", cie="S/C", text_dx="Virus del papiloma humano")
|
||||
note(3, "2025-01-25", "n3a", cie="Z000", reason="COLPOSCOPIA")
|
||||
order = procedure(3, "citologia", "orden", "2025-01-19", "c3",
|
||||
orden__especialidad=("valor_id", "CIRUGIA_ONCOLOGICA"))
|
||||
(sample,) = session.exec(select(Procedimiento).where(
|
||||
Procedimiento.pac_id == 3, Procedimiento.estudio_id == "citologia", Procedimiento.clase == "toma",
|
||||
Procedimiento.fecha == date(2025, 1, 20))).all()
|
||||
sample.padre_id = order.procedimiento_id
|
||||
|
||||
|
||||
def test_the_follow_up_status_follows_the_timeline(base, eu13, eu7):
|
||||
"""Pins down: with colposcopies and a treatment on the timeline, every unit of EU13 and EU7 in every period gets
|
||||
the status the kit's `estatus_al` gives her at the period's start, and all four statuses come out; asked with a
|
||||
knowledge cut-off before those facts arrived, they're PRE_COLPOSCOPIA again. Fails if an inferred procedure
|
||||
(the valuation requirement, the same-day order, the accent-blind reason, the diagnosis text), the timeline
|
||||
stratum or the values' order stops meaning what the kit's rules mean."""
|
||||
with base.motor.connect() as connection:
|
||||
before_load = connection.execute(text("select max(inicio) from carga")).scalar_one()
|
||||
with Session(base.motor) as session:
|
||||
follow_up(session)
|
||||
session.commit()
|
||||
|
||||
seen = set()
|
||||
for period_id in PERIODS:
|
||||
start = base.dominio.dim_periodo_repository.get(period_id).inicio.isoformat()
|
||||
expected = kit_status(base, start)
|
||||
for definition in (eu13, eu7):
|
||||
ours = dict(strata_rows(base, ask(base, definition, period_id).report_id, STATUS))
|
||||
assert ours == {unit: expected[unit] for unit in ours}, (definition.url, period_id)
|
||||
seen |= set(ours.values())
|
||||
assert seen == {"PRE_COLPOSCOPIA", "POST_COLPOSCOPIA", "POST_TRATAMIENTO", "INFO_INSUFICIENTE"}
|
||||
|
||||
known_then = datetime.fromisoformat(before_load)
|
||||
earlier = ask(base, eu13, "2025-10", knowledge_cutoff=known_then)
|
||||
assert set(dict(strata_rows(base, earlier.report_id, STATUS)).values()) == {"PRE_COLPOSCOPIA"}
|
||||
|
||||
|
||||
def test_a_sample_waiting_for_its_diagnosis_within_the_horizon_is_not_measured_yet(base, manifest):
|
||||
"""Pins down the cut-off of the time to diagnosis: in 2025-S2 cut at September 30, the July sample resolved in
|
||||
August is measured (40 days); the August sample, resolved only in January, and the September one, with no note,
|
||||
are still within 180 days, so they aren't measured yet; the October sample is after the cut. Fails if a note
|
||||
after the cut-off counts, or a pending sample enters the initial population."""
|
||||
from webapi.durations import answer_duration, duration_definitions
|
||||
|
||||
definition = duration_definitions(manifest)[DIAS_TOMA_DIAGNOSTICO]
|
||||
result = answer_duration("cacu", definition, Question(DIAS_TOMA_DIAGNOSTICO, "2025-S2", date(2025, 9, 30)),
|
||||
**repositories(base))
|
||||
assert (result.initial, result.n, result.median, result.excluded) == (1, 1, 40.0, 0)
|
||||
|
||||
|
||||
CONFIRMACION = "cacu/CACU_CONFIRMACION_CITOLOGIA"
|
||||
|
||||
|
||||
def test_the_confirmation_by_biopsy_is_the_kit_s_in_every_period(base, manifest):
|
||||
"""Pins down the composition that follows the chosen fact: each patient whose last valid sample of the period is
|
||||
high grade, in the grade of the most severe biopsy that sample led to by the cut-off (SIN_BIOPSIA without one),
|
||||
by that sample's result; units, strata and counts are the kit's in every period. Fails if the two-level ranking,
|
||||
the admission on the chosen sample, the severity order or the chosen-row stratum drift."""
|
||||
oracle = json.loads(ORACLE.read_text(encoding="utf-8"))[CONFIRMACION]
|
||||
definition = composition_definitions(manifest)[CONFIRMACION]
|
||||
for period_id, expected in oracle["periodos"].items():
|
||||
result = answer_composition("cacu", definition, Question(CONFIRMACION, period_id), **repositories(base))
|
||||
assert units(base, result.report_id) == [u[:5] for u in expected["units"]], period_id
|
||||
assert strata_rows(base, result.report_id, "citologia_alto_grado") == sorted(
|
||||
[u, v] for u, s, v in expected["strata"] if s == "citologia_alto_grado"), period_id
|
||||
rows = [dict(zip(expected["published_columns"], r)) for r in expected["published"]]
|
||||
published = {f"{r['estrato_id']}|{r['estrato_valor']}|{r['categoria']}": r["n"] for r in rows if r["n"]}
|
||||
assert {k: v for k, v in composition_cells(result).items() if v} == published, period_id
|
||||
@@ -1,50 +0,0 @@
|
||||
"""WebApi and `models` talk to each other through the database, both ways,
|
||||
over the same Repository objects: rows imported over HTTP are what a
|
||||
model trains on, and rows a model writes are what the API serves."""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@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_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.io.storage import resolve_repository
|
||||
|
||||
csv = b"Expediente,BIRADS\nRT-1,BI-RADS 4\nRT-2,2\n"
|
||||
response = client.post(
|
||||
"/imports/commit",
|
||||
json={
|
||||
"sources": [
|
||||
{
|
||||
"source_type": "csv",
|
||||
"target": "cama.Mastografia",
|
||||
"column_mapping": {"Expediente": "pac_id_hospital", "BIRADS": "mast_birads"},
|
||||
"payload": {"file_base64": base64.b64encode(csv).decode()},
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
assert response.get_json()["results"][0]["created"] == 2
|
||||
|
||||
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"}
|
||||
|
||||
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"]}
|
||||
@@ -1,371 +0,0 @@
|
||||
"""Connector catalog, SQL Server, EEG files and clinical documents, end to end."""
|
||||
import base64
|
||||
import io
|
||||
from datetime import date
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import mssql
|
||||
|
||||
from extraction.testing import edf_file, scanned_pdf, text_pdf
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
wire_domain("cama")
|
||||
wire_domain("tea")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def b64(raw: bytes) -> str:
|
||||
return base64.b64encode(raw).decode()
|
||||
|
||||
|
||||
def eeg(seconds: int = 8, rate: int = 128, **kwargs) -> bytes:
|
||||
t = np.arange(rate * seconds) / rate
|
||||
alpha = 40 * np.sin(2 * np.pi * 10 * t)
|
||||
return edf_file(signals={"EEG O1-REF": alpha, "EEG O2-REF": alpha, "EEG Fp1-REF": 20 * np.sin(2 * np.pi * 20 * t)}, sample_rate=rate, **kwargs)
|
||||
|
||||
|
||||
# -- catalog ------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_catalog_lists_every_connector(client):
|
||||
connectors = {c["kind"]: c for c in client.get("/imports/connectors").get_json()["connectors"]}
|
||||
assert {"csv", "excel", "json", "pdf", "document", "edf", "sql"} <= set(connectors)
|
||||
assert connectors["edf"]["extensions"] == ["edf"]
|
||||
assert "pdf" in connectors["document"]["extensions"] and "tif" in connectors["document"]["extensions"]
|
||||
assert {s["id"] for s in connectors["document"]["segmentations"]} == {"auto", "document", "pages", "key"}
|
||||
engines = {e["id"]: e for e in connectors["sql"]["engines"]}
|
||||
assert engines["mssql"]["label"] == "SQL Server" and engines["mssql"]["default_port"] == 1433
|
||||
assert engines["mssql"]["available"] is True
|
||||
|
||||
|
||||
# -- SQL Server ----------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_sql_server_url_is_built_from_form_fields():
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
|
||||
url = SqlConnector.server_url({"engine": "mssql", "host": "his.local", "database": "HIS", "user": "lector", "password": "p@ss:/w"})
|
||||
assert url.drivername == "mssql+pymssql"
|
||||
assert url.port == 1433
|
||||
assert url.password == "p@ss:/w"
|
||||
|
||||
|
||||
def test_sql_server_preview_compiles_to_top(monkeypatch):
|
||||
from webapi.imports.connectors.sql import _text_subquery
|
||||
|
||||
statement = sa.select(_text_subquery("SELECT * FROM pacientes")).limit(5)
|
||||
compiled = str(statement.compile(dialect=mssql.dialect(), compile_kwargs={"literal_binds": True}))
|
||||
assert "TOP 5" in compiled and "LIMIT" not in compiled
|
||||
|
||||
|
||||
def test_unknown_engine_and_missing_host_are_rejected(client):
|
||||
assert client.post("/imports/sources/sql/test-connection", json={"server": {"engine": "db2", "host": "x", "database": "y"}}).status_code == 400
|
||||
response = client.post("/imports/sources/sql/test-connection", json={"server": {"engine": "mssql", "database": "y"}})
|
||||
assert response.status_code == 400 and "host" in response.get_json()["error"]
|
||||
|
||||
|
||||
# -- EEG -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_edf_preview_maps_onto_eeg_estudio(client):
|
||||
data = {"file": (io.BytesIO(eeg()), "estudio_007.edf"), "target": "tea.EegEstudio"}
|
||||
body = client.post("/imports/sources/file/preview", data=data, content_type="multipart/form-data").get_json()
|
||||
[row] = body["sample_rows"]
|
||||
assert row["id_registro_laboratorio"] == "LAB-778"
|
||||
assert row["paciente"] == "EXP-0042"
|
||||
assert row["fecha_estudio"] == "2024-01-15"
|
||||
assert row["edad_meses"] == 56.0
|
||||
assert row["ritmo_base_frecuencia"] == pytest.approx(10, abs=0.3)
|
||||
assert "3 canales a 128 Hz" in row["descripcion_senal"]
|
||||
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
|
||||
assert suggested["estudio"] == "eeg_estudio"
|
||||
assert suggested["fecha_estudio"] == "eeg_fecha_estudio"
|
||||
assert suggested["ritmo_base_frecuencia"] == "eeg_ritmo_base_frecuencia"
|
||||
|
||||
|
||||
def test_several_edf_files_load_into_eeg_estudio_with_the_file(client):
|
||||
source = {
|
||||
"source_type": "edf",
|
||||
"target": "tea.EegEstudio",
|
||||
"column_mapping": {
|
||||
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"fecha_estudio": "eeg_fecha_estudio",
|
||||
"duracion_min": "eeg_duracion_min",
|
||||
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
|
||||
"estudio": "eeg_estudio",
|
||||
},
|
||||
"payload": {"files": [{"name": "a.edf", "file_base64": b64(eeg())}, {"name": "b.edf", "file_base64": b64(eeg(recording="sin datos"))}]},
|
||||
}
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.tea import eeg_estudio_repository
|
||||
|
||||
stored = {row.eeg_id_registro_laboratorio: row for row in eeg_estudio_repository.list()}
|
||||
assert set(stored) == {"LAB-778", "b"}
|
||||
assert stored["LAB-778"].eeg_estudio[:8].strip() == b"0"
|
||||
assert stored["LAB-778"].eeg_fecha_estudio == date(2024, 1, 15)
|
||||
|
||||
|
||||
def test_eeg_estudio_rejects_a_file_mne_cannot_read():
|
||||
from webapi.imports.schemas.service import validate_rows
|
||||
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
|
||||
|
||||
result = validate_rows(EegEstudioImportSchema, [{"eeg_estudio": b"definitely not an EDF file" * 20}])
|
||||
[row] = result.rejected
|
||||
assert row.errors[0].field == "eeg_estudio"
|
||||
|
||||
|
||||
# -- clinical documents -----------------------------------------------------------------
|
||||
|
||||
|
||||
def _document_source(files: list[tuple[str, bytes]], target: str, mapping: dict, **options) -> dict:
|
||||
return {
|
||||
"source_type": "document",
|
||||
"target": target,
|
||||
"column_mapping": mapping,
|
||||
"payload": {"files": [{"name": n, "file_base64": b64(r)} for n, r in files], **options},
|
||||
"label": "documentos",
|
||||
}
|
||||
|
||||
|
||||
REPORTS = text_pdf(
|
||||
[
|
||||
["HOSPITAL REGIONAL - LABORATORIO DE PATOLOGIA", "Expediente: DOC-0001 Sexo: Femenino", "Fecha de nacimiento: 12/03/1981",
|
||||
"VPH alto riesgo: POSITIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: DETECTADO"],
|
||||
["Observaciones: muestra adecuada,", "con escaso moco cervical."],
|
||||
["Expediente: DOC-0002 Sexo: F", "Fecha de nacimiento: 1 de mayo de 1975",
|
||||
"Se identifica ADN de virus del papiloma humano de alto riesgo: NEGATIVO"],
|
||||
],
|
||||
image_on_page=2,
|
||||
)
|
||||
|
||||
|
||||
def test_document_extract_reports_records_evidence_and_images(client):
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"files": [{"name": "lote.pdf", "file_base64": b64(REPORTS)}], "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
assert body["key_field"] == "pac_id_hospital"
|
||||
first, second = body["records"]
|
||||
assert first["key"] == "DOC-0001" and first["sources"] == [{"document": "lote.pdf", "page_numbers": [1, 2]}]
|
||||
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
assert first["fields"]["cit_vph_genotipo_16"]["value"] == 0
|
||||
assert first["fields"]["cit_vph_genotipo_18"]["value"] == 1
|
||||
assert first["fields"]["cit_observaciones"]["value"] == "muestra adecuada, con escaso moco cervical."
|
||||
assert first["fields"]["cit_vph_resultado"]["page_number"] == 1
|
||||
assert [image["page_number"] for image in first["images"]] == [2]
|
||||
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
|
||||
assert second["fields"]["cit_vph_resultado"]["method"] == "texto_libre"
|
||||
|
||||
|
||||
def test_document_page_and_image_render(client):
|
||||
data = {"file": (io.BytesIO(REPORTS), "lote.pdf"), "page_number": "2", "bbox": "[0.4, 0.4, 0.8, 0.7]"}
|
||||
response = client.post("/imports/sources/document/page-image", data=data, content_type="multipart/form-data")
|
||||
assert response.status_code == 200 and response.mimetype == "image/png"
|
||||
|
||||
|
||||
def test_documents_commit_with_overrides_and_the_record_pdf(client):
|
||||
mapping = {
|
||||
"pac_id_hospital": "pac_id_hospital",
|
||||
"cit_vph_resultado": "cit_vph_resultado",
|
||||
"cit_vph_genotipo_18": "cit_vph_genotipo_18",
|
||||
"documento": "cit_vph_pdf_blob",
|
||||
}
|
||||
source = _document_source([("lote.pdf", REPORTS)], "cacu.CitologiaCervical", mapping, overrides={"1": {"cit_vph_resultado": "INDETERMINADO"}})
|
||||
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("DOC-")}
|
||||
assert rows["DOC-0001"].cit_vph_resultado == "POSITIVO"
|
||||
assert rows["DOC-0002"].cit_vph_resultado == "INDETERMINADO"
|
||||
assert rows["DOC-0001"].cit_vph_pdf_blob.startswith(b"%PDF")
|
||||
|
||||
|
||||
def test_patient_scattered_across_csv_and_scanned_forms_is_merged(client):
|
||||
csv = b"expediente,sexo,codigo_postal\nMIX-0001,F,64000\nMIX-0002,M,01000\n"
|
||||
scan = scanned_pdf([["FICHA DE IDENTIFICACION", "Expediente: MIX-0001", "Fecha de nacimiento: 15/08/1979", "Sexo: Masculino"]])
|
||||
sources = [
|
||||
{
|
||||
"source_type": "csv",
|
||||
"target": "cacu.Paciente",
|
||||
"label": "padron.csv",
|
||||
"column_mapping": {"expediente": "pac_id_hospital", "sexo": "pac_sexo", "codigo_postal": "pac_codigo_postal"},
|
||||
"payload": {"file_base64": b64(csv)},
|
||||
},
|
||||
_document_source(
|
||||
[("ficha.pdf", scan)],
|
||||
"cacu.Paciente",
|
||||
{"pac_id_hospital": "pac_id_hospital", "pac_fecha_nacimiento": "pac_fecha_nacimiento", "pac_sexo": "pac_sexo"},
|
||||
),
|
||||
]
|
||||
# On its own the CSV lacks the required birth date.
|
||||
assert client.post("/imports/validate", json={"source": sources[0]}).get_json()["error_count"] == 2
|
||||
|
||||
padron, ficha = client.post("/imports/commit", json={"sources": sources, "merge_duplicates": True}).get_json()["results"]
|
||||
assert (padron["created"], padron["rejected"]) == (1, 1) # MIX-0002 has no birth date anywhere
|
||||
assert (ficha["merged"], ficha["created"]) == (1, 0)
|
||||
assert [(w["field"], w["raw_value"]) for w in ficha["warnings"]] == [("pac_sexo", "Masculino")]
|
||||
|
||||
from persistance.cacu import paciente_repository
|
||||
|
||||
[patient] = paciente_repository.list(pac_id_hospital="MIX-0001")
|
||||
assert patient.pac_fecha_nacimiento == date(1979, 8, 15)
|
||||
assert patient.pac_codigo_postal == "64000"
|
||||
|
||||
|
||||
EEG_REPORT = text_pdf(
|
||||
[
|
||||
["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-778", "Fecha de estudio: 15/01/2024",
|
||||
"Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"],
|
||||
["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."],
|
||||
],
|
||||
image_on_page=2,
|
||||
)
|
||||
|
||||
# A second study id, distinct from LAB-778 (already used by an earlier test
|
||||
# against this module-scoped client/database), for the merge test below.
|
||||
EEG_REPORT_2 = text_pdf(
|
||||
[
|
||||
["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-900", "Fecha de estudio: 20/02/2024",
|
||||
"Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"],
|
||||
["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."],
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_eeg_report_scattered_across_pages_merges_into_one_record(client):
|
||||
"""The report's demographics are on page 1, its conclusion on page 2 —
|
||||
non-contiguous fields the same way a multi-file upload would be, just
|
||||
without the file boundary. Proves the extractor merges by the lab's own
|
||||
study id, not by page adjacency."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"files": [{"name": "reporte.pdf", "file_base64": b64(EEG_REPORT)}], "target": "tea.EegEstudio"},
|
||||
).get_json()
|
||||
assert body["key_field"] == "eeg_id_registro_laboratorio"
|
||||
[record] = body["records"]
|
||||
assert record["key"] == "LAB-778"
|
||||
assert record["sources"] == [{"document": "reporte.pdf", "page_numbers": [1, 2]}]
|
||||
assert record["fields"]["eeg_simetria"]["value"] == "SIMETRICO"
|
||||
assert record["fields"]["eeg_fecha_estudio"]["value"] == "2024-01-15"
|
||||
assert "sin eventos epileptiformes" in record["fields"]["eeg_conclusion_texto"]["value"]
|
||||
assert [image["page_number"] for image in record["images"]] == [2]
|
||||
|
||||
|
||||
def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_estudio_row(client):
|
||||
"""The EDF connector computes signal fields from the file itself; the
|
||||
report PDF (read with NLP, across two pages) carries the clinician's
|
||||
interpretation. Different sources, same study — `eeg_id_registro_
|
||||
laboratorio` (the lab's own code, read from the EDF header by one side
|
||||
and from the report text by the other) is what lets them land on one
|
||||
`eeg_estudio` row instead of two half-populated ones."""
|
||||
edf_source = {
|
||||
"source_type": "edf",
|
||||
"target": "tea.EegEstudio",
|
||||
"label": "estudio.edf",
|
||||
"column_mapping": {
|
||||
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"fecha_estudio": "eeg_fecha_estudio",
|
||||
"duracion_min": "eeg_duracion_min",
|
||||
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
|
||||
"estudio": "eeg_estudio",
|
||||
},
|
||||
"payload": {"files": [{"name": "estudio.edf", "file_base64": b64(eeg(recording="Startdate 20-FEB-2024 LAB-900 Tec_Ruiz Nihon_Kohden"))}]},
|
||||
}
|
||||
document_source = _document_source(
|
||||
[("reporte.pdf", EEG_REPORT_2)],
|
||||
"tea.EegEstudio",
|
||||
{
|
||||
"eeg_id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"eeg_simetria": "eeg_simetria",
|
||||
"eeg_conclusion_texto": "eeg_conclusion_texto",
|
||||
"eeg_medico_interpreta": "eeg_medico_interpreta",
|
||||
},
|
||||
)
|
||||
body = client.post(
|
||||
"/imports/commit", json={"sources": [edf_source, document_source], "merge_duplicates": True}
|
||||
).get_json()
|
||||
edf_result, doc_result = body["results"]
|
||||
assert edf_result["created"] == 1, body
|
||||
assert doc_result["merged"] == 1, body # absorbed into the EDF source's row, not inserted again
|
||||
|
||||
from persistance.tea import eeg_estudio_repository
|
||||
|
||||
[row] = eeg_estudio_repository.list(eeg_id_registro_laboratorio="LAB-900")
|
||||
# From the EDF file itself:
|
||||
assert row.eeg_duracion_min is not None
|
||||
assert row.eeg_estudio[:8].strip() == b"0"
|
||||
# From the scanned report, on the very same row:
|
||||
assert row.eeg_simetria == "SIMETRICO"
|
||||
assert "sin eventos epileptiformes" in row.eeg_conclusion_texto
|
||||
assert row.eeg_medico_interpreta == "Dra. Ruiz"
|
||||
|
||||
|
||||
def test_citologia_table_and_scanned_report_merge_on_the_order_number(client):
|
||||
"""The order/date come from a structured table (a CSV export of the lab's
|
||||
own HIS); the VPH result comes from NLP over the scanned report PDF.
|
||||
`(pac_id_hospital, ord_numero_hospital)` is what lets them land on one
|
||||
`citologiacervical` row instead of two half-populated ones."""
|
||||
csv = b"expediente,orden,fecha_toma\nMRG-0001,5001,2024-03-01\n"
|
||||
report = text_pdf([["LABORATORIO DE CITOLOGIA", "Expediente: MRG-0001", "No. de orden: 5001", "VPH alto riesgo: POSITIVO"]])
|
||||
sources = [
|
||||
{
|
||||
"source_type": "csv",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"label": "padron.csv",
|
||||
"column_mapping": {"expediente": "pac_id_hospital", "orden": "ord_numero_hospital", "fecha_toma": "cit_fecha_toma"},
|
||||
"payload": {"file_base64": b64(csv)},
|
||||
},
|
||||
_document_source(
|
||||
[("reporte.pdf", report)],
|
||||
"cacu.CitologiaCervical",
|
||||
{"pac_id_hospital": "pac_id_hospital", "ord_numero_hospital": "ord_numero_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
),
|
||||
]
|
||||
tabla, documento = client.post("/imports/commit", json={"sources": sources, "merge_duplicates": True}).get_json()["results"]
|
||||
assert tabla["created"] == 1, tabla
|
||||
assert documento["merged"] == 1, documento # absorbed into the table row, not inserted again
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
[row] = citologia_cervical_repository.list(pac_id_hospital="MRG-0001")
|
||||
# From the structured table:
|
||||
assert row.ord_numero_hospital == 5001
|
||||
assert row.cit_fecha_toma == date(2024, 3, 1)
|
||||
# From the scanned report, on the very same row:
|
||||
assert row.cit_vph_resultado == "POSITIVO"
|
||||
|
||||
|
||||
def test_embedded_image_in_the_report_maps_onto_the_target_dicom_column(client):
|
||||
"""The report has a picture of the mammogram alongside its narrative
|
||||
text; `imagen` (like `documento`, the combined PDF) is mappable onto any
|
||||
target column, so it lands in `mast_dicom_blob` next to the fields read
|
||||
from the surrounding text."""
|
||||
report = text_pdf(
|
||||
[["LABORATORIO DE IMAGENOLOGIA", "Expediente: IMG-0001", "Interpretación: nódulo circunscrito en cuadrante superior externo."]],
|
||||
image_on_page=1,
|
||||
)
|
||||
mapping = {"pac_id_hospital": "pac_id_hospital", "mast_interpretacion": "mast_interpretacion", "imagen": "mast_dicom_blob"}
|
||||
source = _document_source([("reporte.pdf", report)], "cama.Mastografia", mapping)
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 1, result
|
||||
|
||||
from persistance.cama import mastografia_repository
|
||||
|
||||
[row] = mastografia_repository.list(pac_id_hospital="IMG-0001")
|
||||
assert "nódulo circunscrito" in row.mast_interpretacion
|
||||
assert row.mast_dicom_blob.startswith(b"\x89PNG")
|
||||
@@ -1,82 +0,0 @@
|
||||
"""What this module covers: the whole cycle on the CaCu fixture database, in order, once and again.
|
||||
|
||||
Fixtures: `bases`, one database loaded by the cycle from the kit's synthetic staging, with dbt's manifest
|
||||
(`DBT_MANIFEST`) for the definitions and the event models. The cycle computes no measure: they're answered on request
|
||||
(`test_metrics_on_request`), so running it again adds no report.
|
||||
"""
|
||||
|
||||
import os
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from importlib import import_module
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.orchestration import Context, run
|
||||
from webapi.orchestration.connection import point_to
|
||||
|
||||
ANIO = 2025
|
||||
# Lo que guarda cada reporte (T-19e): sus unidades de §6f. El número publicado sale de ellas (las vistas).
|
||||
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)""")
|
||||
|
||||
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=["cacu", "cama"])
|
||||
def bases(request, tmp_path_factory):
|
||||
proyecto = request.param
|
||||
carpeta = tmp_path_factory.mktemp(proyecto)
|
||||
url = f"sqlite:///{carpeta / 'orquestada.db'}"
|
||||
point_to(proyecto, url)
|
||||
# `observe` lee una regla sin definir en los dos proyectos (I-MD1): se pide a propósito, como `montar` de
|
||||
# dev-data. Ningún cálculo la usa: la base de demostración calcula sin permitirlo y da lo mismo.
|
||||
ctx = Context(proyecto, ANIO, ANIO, allow_undecided=True, dbt_manifest=Path(os.environ["DBT_MANIFEST"]))
|
||||
run(ctx, only=["migrate"])
|
||||
motor = create_engine(url)
|
||||
with Session(motor) as sesion:
|
||||
import_module(f"staging.{proyecto}").insertar(sesion)
|
||||
sesion.commit()
|
||||
pasos = run(ctx)
|
||||
return proyecto, ctx, motor, None, pasos
|
||||
|
||||
|
||||
def test_corre_todos_los_pasos_en_orden(bases):
|
||||
proyecto, _, _, _, pasos = bases
|
||||
nombres = [p.name for p in pasos]
|
||||
# `migrate` otra vez: con la base al día no hace nada. Los catálogos, antes de cargar (decisión 6 de §9).
|
||||
assert nombres[0] == "migrate" and nombres.index("catalogs") < nombres.index("load")
|
||||
assert nombres.index("load") < nombres.index("event_models") and "calcular" not in nombres
|
||||
|
||||
|
||||
|
||||
|
||||
def test_volver_a_correr_no_agrega_reportes(bases):
|
||||
"""Pins down: the cycle computes no measure (they're answered on request): running it adds no report."""
|
||||
_, ctx, motor, _, _ = bases
|
||||
with motor.connect() as con:
|
||||
antes = con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one()
|
||||
run(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 "cohorts" not in [p.name for p in pasos] # T-21h: TEA y CaMa, solo propuestas
|
||||
return
|
||||
(armado_id, nuevo), = [p.summary for p in pasos if p.name == "cohorts"][0].values()
|
||||
with motor.connect() as con:
|
||||
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == 1
|
||||
assert con.execute(text("SELECT n_miembros FROM cohorte_armado")).scalar_one() == con.execute(
|
||||
text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
"""Los pasos de oro sobre la base del dominio: el registro y las definiciones (el catálogo, del manifiesto de dbt).
|
||||
|
||||
Vienen del kit (`test_pasos` y `test_produccion`, MD-16). El reporte se lee por los
|
||||
repositorios de Persistance, como lo leería `WebApi`.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from webapi.orchestration.silver.loads import tablas_de_staging
|
||||
from webapi.orchestration.reference.age_groups import grupos_de_cortes
|
||||
from webapi.orchestration.reference.rules import RUTA_PARAMETROS, valores_del_archivo
|
||||
from webapi.orchestration.reference.periods import periodos_de_tipos
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
from webapi.orchestration.project import period_types
|
||||
|
||||
from conftest import ANIO
|
||||
|
||||
# El indicador de ejemplo, su grupo total y lo que da: {periodo: (denominador, numerador)}.
|
||||
def cargas(proyecto) -> tuple[str, ...]:
|
||||
"""El paso que lleva el staging a la plata (staging directo, T-20c)."""
|
||||
return ("load",)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_el_registro_se_puede_repetir_y_agrega_los_periodos_que_faltan(base):
|
||||
base.run("registry")
|
||||
base.run("registry", year_from=ANIO - 1)
|
||||
|
||||
tablas = tablas_de(base.proyecto)
|
||||
esperados = periodos_de_tipos(period_types(base.proyecto, base.ctx.dbt_manifest), ANIO - 1, ANIO, tablas=tablas)
|
||||
assert base.dominio.dim_periodo_repository.count() == len(esperados)
|
||||
assert base.dominio.measure_report_repository.count() == 0
|
||||
|
||||
|
||||
def test_el_registro_llena_dim_fecha_y_dim_grupo_edad_desde_los_toml(base):
|
||||
"""I-MD27 (T-24f): de `comun.dim_fecha.desde` al fin del último año, y los grupos de `<proyecto>.grupos_edad`."""
|
||||
base.run("registry")
|
||||
base.run("registry", year_to=ANIO + 1) # repetir deja la tabla igual, con el año nuevo
|
||||
|
||||
valores = valores_del_archivo(RUTA_PARAMETROS)
|
||||
desde = date.fromisoformat(valores["comun.dim_fecha.desde"])
|
||||
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_un_archivo_de_parametros_invalido_no_toca_el_registro(base, tmp_path):
|
||||
base.run("registry")
|
||||
periodos = base.dominio.dim_periodo_repository.count()
|
||||
malo = tmp_path / "malo.toml"
|
||||
malo.write_text('[comun.x]\nvalor = 1\nestado = "provisional"\n', encoding="utf-8")
|
||||
|
||||
with pytest.raises(ValueError, match="fuente"):
|
||||
base.run("registry", year_from=ANIO - 1, year_to=ANIO + 1, parameters=malo)
|
||||
|
||||
assert base.dominio.def_parametro_repository.get("comun.x") is None
|
||||
assert base.dominio.def_parametro_repository.get("comun.umbral_supresion") is not None
|
||||
assert base.dominio.dim_periodo_repository.count() == periodos
|
||||
|
||||
|
||||
def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
|
||||
"""Pins down: `definitions` seeds the publication catalog from dbt's manifest, once. Fails if a stratum or a
|
||||
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
|
||||
resumen = base.run("definitions")["definitions"]
|
||||
|
||||
# CaCu: three strata and its seven measures; CaMa: its seven measures, without strata.
|
||||
assert resumen["definitions"] == {"cacu": 10, "cama": 7}[base.proyecto]
|
||||
# Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado.
|
||||
assert base.dominio.cat_measure_repository.count() == 7 # seven measures in each domain
|
||||
assert base.run("definitions")["definitions"]["borradas"] == 0
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
"""Las dependencias entre los pasos de cada proyecto, como las lee Hamilton de los parámetros."""
|
||||
|
||||
import pytest
|
||||
from hamilton import driver
|
||||
|
||||
from webapi.orchestration import cycle, steps_of
|
||||
|
||||
|
||||
def dependencias(proyecto: str) -> dict[str, set[str]]:
|
||||
dr = driver.Builder().with_modules(cycle).with_config({"with_cohorts": proyecto == "cacu"}).build()
|
||||
return {n.name: {d.name for d in n.dependencies} - {"ctx"} for n in dr.graph.get_nodes() if n.name != "ctx"}
|
||||
|
||||
|
||||
def antes(deps: dict[str, set[str]], paso: str) -> set[str]:
|
||||
"""Todos los pasos que corren antes de `paso`."""
|
||||
previos = set()
|
||||
pending = list(deps[paso])
|
||||
while pending:
|
||||
anterior = pending.pop()
|
||||
if anterior not in previos:
|
||||
previos.add(anterior)
|
||||
pending.extend(deps[anterior])
|
||||
return previos
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama"])
|
||||
def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto):
|
||||
deps = dependencias(proyecto)
|
||||
assert deps["migrate"] == set()
|
||||
assert {"migrate", "catalogs"} <= antes(deps, "load") # decisión 6 de §9
|
||||
assert {"load"} <= antes(deps, "event_models")
|
||||
assert {"registry"} <= antes(deps, "observe")
|
||||
assert {"load", "catalogs"} <= antes(deps, "check_silver")
|
||||
|
||||
|
||||
def test_solo_cacu_arma_cohortes_y_estima_por_ahora():
|
||||
"""T-21h: las cohortes de TEA y CaMa son propuestas (`cohortes/propuestas/`); queda su infraestructura."""
|
||||
assert {"cohorts", "estimate"} <= set(steps_of("cacu"))
|
||||
for proyecto in ("cama", "tea"):
|
||||
assert not {"cohorts", "estimate"} & set(steps_of(proyecto))
|
||||
@@ -1,250 +0,0 @@
|
||||
"""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 webapi.orchestration.silver.loads import tablas_de_staging
|
||||
from webapi.orchestration.silver.observation_periods import (
|
||||
TIPO_EXTRACCION,
|
||||
ObservacionSinCorte,
|
||||
clave_de_inicio,
|
||||
)
|
||||
from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo
|
||||
from webapi.orchestration.reference.rules import RUTA_PARAMETROS, ParametroSinDefinir
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
from sqlalchemy import inspect, text
|
||||
from sqlmodel import select
|
||||
|
||||
# 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"),
|
||||
}
|
||||
CORTE = date(2025, 12, 31)
|
||||
|
||||
|
||||
def ultima_carga(base):
|
||||
return max(base.ctx.repos.silver.loads.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.silver.catalogs
|
||||
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.run("catalogs")["catalogs"] == {**del_toml, "retirados": 0}
|
||||
assert filas_del_catalogo(base) == del_toml
|
||||
|
||||
|
||||
def test_volver_a_correr_catalogos_no_cambia_nada(base):
|
||||
base.run("catalogs")
|
||||
antes = filas_del_catalogo(base)
|
||||
|
||||
assert base.run("catalogs")["catalogs"]["retirados"] == 0
|
||||
assert filas_del_catalogo(base) == antes
|
||||
|
||||
|
||||
# --- cargar (staging directo) ---
|
||||
|
||||
|
||||
def test_cargar_lleva_el_staging_a_persona_y_la_plata(base):
|
||||
base.run("catalogs")
|
||||
carga = base.run("load")["load"]
|
||||
|
||||
procedimientos, observaciones = plata_de(base)
|
||||
assert procedimientos and observaciones
|
||||
assert carga.fin is not None and (carga.filas_nuevas, carga.filas_cambiadas, carga.filas_sin_cambio) == (
|
||||
procedimientos, 0, 0)
|
||||
assert contar(base, "SELECT COUNT(*) FROM persona") == len(base.ctx.repos.bronze.staging.read(
|
||||
{"p": tablas_de_staging(base.proyecto)[0]})["p"])
|
||||
# Ningún reporte ni parte sin su toma (salvo los huérfanos, que no se escriben).
|
||||
assert contar(base, "SELECT COUNT(*) FROM procedimiento WHERE clase IN ('reporte', 'parte') AND padre_id IS NULL") == 0
|
||||
# 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
|
||||
|
||||
|
||||
|
||||
|
||||
def test_volver_a_cargar_sin_cambios_no_toca_nada(base):
|
||||
base.run("catalogs", "load")
|
||||
antes = plata_de(base)
|
||||
|
||||
segunda = base.run("load")["load"]
|
||||
assert (segunda.filas_nuevas, segunda.filas_cambiadas, segunda.filas_sin_cambio) == (0, 0, antes[0])
|
||||
assert plata_de(base) == antes
|
||||
for tabla in ("procedimiento", "observacion_clinica"):
|
||||
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.run("catalogs", "load")
|
||||
antes = plata_de(base)
|
||||
cambiar_staging(base)
|
||||
|
||||
segunda = base.run("load")["load"]
|
||||
assert (segunda.filas_nuevas, segunda.filas_cambiadas, segunda.filas_sin_cambio) == (0, 1, antes[0] - 1)
|
||||
assert plata_de(base) == antes
|
||||
|
||||
|
||||
|
||||
|
||||
# --- vistas ---
|
||||
|
||||
|
||||
def test_las_vistas_se_construyen_y_se_pueden_repetir(base):
|
||||
primera = base.run("views")["views"]
|
||||
|
||||
assert base.run("views")["views"] == primera
|
||||
# Only `v_persona`: the published numbers are answered on request, so the publication views aren't built.
|
||||
assert sorted(inspect(base.motor).get_view_names()) == ["v_persona"]
|
||||
|
||||
|
||||
# --- observar ---
|
||||
|
||||
|
||||
@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.run("load", "registry", parameters=con_regla("2024-06-01"))
|
||||
|
||||
cuantos = base.run("observe", cutoff=CORTE)["observe"]
|
||||
|
||||
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.run("load", "registry", parameters=con_regla())
|
||||
|
||||
base.run("observe")
|
||||
|
||||
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.run("load", "registry", parameters=con_regla())
|
||||
|
||||
primera = base.run("observe", cutoff=date(2025, 6, 30))["observe"]
|
||||
segunda = base.run("observe", cutoff=CORTE)["observe"]
|
||||
|
||||
assert primera == segunda == base.dominio.periodo_observacion_repository.count()
|
||||
assert {p.fecha_fin for p in base.dominio.periodo_observacion_repository.list()} == {CORTE}
|
||||
|
||||
|
||||
@observables
|
||||
def test_la_regla_de_inicio_sin_definir_hay_que_pedirla_a_proposito(base):
|
||||
base.run("load", "registry")
|
||||
|
||||
with pytest.raises(ParametroSinDefinir, match="inicio_datos"):
|
||||
base.run("observe", cutoff=CORTE)
|
||||
assert base.run("observe", cutoff=CORTE, allow_undecided=True)["observe"] == (
|
||||
base.dominio.persona_repository.count())
|
||||
|
||||
|
||||
@observables
|
||||
def test_sin_el_registro_observar_dice_que_falta(base):
|
||||
base.run("load")
|
||||
|
||||
with pytest.raises(KeyError, match="preparar_registro|registro"):
|
||||
base.run("observe", cutoff=CORTE)
|
||||
|
||||
|
||||
@observables
|
||||
def test_un_corte_anterior_al_inicio_de_los_datos_se_rechaza(base, con_regla):
|
||||
base.run("load", "registry", parameters=con_regla("2024-06-01"))
|
||||
|
||||
with pytest.raises(ValueError, match="anterior al inicio"):
|
||||
base.run("observe", cutoff=date(2024, 5, 31))
|
||||
assert base.dominio.periodo_observacion_repository.count() == 0
|
||||
|
||||
|
||||
@observables
|
||||
def test_sin_corte_y_sin_cargas_no_hay_de_donde_tomarlo(base, con_regla):
|
||||
base.run("registry", parameters=con_regla())
|
||||
|
||||
with pytest.raises(ObservacionSinCorte):
|
||||
base.run("observe")
|
||||
|
||||
|
||||
# --- 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.run("catalogs", "load", "check_silver")["check_silver"]
|
||||
|
||||
# I-MD16 (textos del fixture fuera del catálogo) e I-MD18 (especialidades que el alias no reconoce): en la
|
||||
# plata, una observación de código sin `valor_id` y con su `valor_fuente`.
|
||||
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
|
||||
@@ -1,30 +0,0 @@
|
||||
"""La regla de §6: ningún paso abre una sesión; todo va por `ctx.repos`.
|
||||
|
||||
Las subclases viven en `persistance/edges/` y Persistance las instancia con su
|
||||
fábrica de sesión (ADR-MD-005). Solo `connection.py` nombra a `persistance.db`: cambia a
|
||||
qué base apunta Persistance (`<PROYECTO>_DATABASE_URL` en memoria); no es un paso.
|
||||
"""
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from webapi.orchestration.repositories import repositories_of
|
||||
|
||||
PAQUETE = Path(__file__).parents[1] / "webapi" / "orchestration"
|
||||
EXENTOS = {"connection.py"}
|
||||
PROHIBIDO = re.compile(r"fabrica_por_defecto|get_(cacu|cama|tea)_session|get_\{|Session\(|persistance\.db")
|
||||
|
||||
|
||||
@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)])
|
||||
def test_cada_proyecto_tiene_sus_repositorios(proyecto, con_cohortes):
|
||||
repos = repositories_of(proyecto)
|
||||
assert (repos.gold.cohorts is not None) == con_cohortes
|
||||
assert repos.gold.calculation.model.__tablename__ == "measure_report"
|
||||
@@ -1,97 +0,0 @@
|
||||
"""El paso `estimate` y la orden `confirm-risks` (ADR-MD-008), con un estimador de prueba.
|
||||
|
||||
El estimador se inyecta en el contexto; aquí se usa uno que cumple el contrato `EstimadorDeRiesgo` sin MLflow.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from webapi.orchestration.__main__ import confirm_risks, 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.run("catalogs", "load", "event_models", "cohorts", allow_undecided=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.run("estimate", estimators={URL: estimador})["estimate"][URL]
|
||||
|
||||
miembros = cuenta(cacu, "SELECT n_miembros FROM cohorte_armado ORDER BY armado_id DESC LIMIT 1")
|
||||
assert nuevo and miembros > 0
|
||||
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.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
|
||||
|
||||
assert cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] == (primero, False)
|
||||
assert cacu.run("estimate")["estimate"] == {}
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_confirmar_y_anular_un_lote_agregan_una_version(cacu, capsys):
|
||||
(lote_id, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
|
||||
miembros = cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}")
|
||||
|
||||
main(["confirm-risks", "cacu", str(lote_id), "--reason", "revisado"])
|
||||
assert f"{miembros} evaluaciones confirmadas" in capsys.readouterr().out
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'final' AND version = 2") == miembros
|
||||
|
||||
assert confirm_risks("cacu", lote_id, "error de captura", void=True) == miembros
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'entered-in-error'") == miembros
|
||||
|
||||
|
||||
# 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"),
|
||||
}
|
||||
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
"""What this module covers: the timeline `repositories_of` wires into `ctx.repos.silver` is dbt's view
|
||||
`cacu_linea_de_tiempo`, the one the models' pipelines, the cohort builds and the measures' strata read: silver's
|
||||
facts as the indicator kit's own timeline gave them, plus the procedures dbt infers from them.
|
||||
|
||||
Fixtures: `base` (from `conftest.py`), the CaCu fixture database, loaded and with dbt's views created
|
||||
(`catalogs`, `load`, `event_models`; needs `DBT_MANIFEST`); `kit_rows`, the rows the kit's timeline query gave on
|
||||
that data (`fixtures/kit_cacu_timeline.json`, without `conocida_en`, which is each run's load time).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
CORTE = date(2025, 12, 31)
|
||||
INFERRED = {"colposcopia", "tratamiento", "citologia_de_vigilancia", "diagnostico", "antecedente"}
|
||||
KIT_ROWS = Path(__file__).parent / "fixtures" / "kit_cacu_timeline.json"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def proyecto():
|
||||
return "cacu"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def loaded(base):
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
base.run("catalogs", "load", "event_models")
|
||||
return base
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def kit_rows():
|
||||
return json.loads(KIT_ROWS.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def as_kit(rows) -> list[dict]:
|
||||
"""Rows as the snapshot keeps them: text values, no load time, without the inferred procedures."""
|
||||
return [{k: None if v is None else str(v) for k, v in row.items() if k != "conocida_en"}
|
||||
for row in rows if row["tipo"] not in INFERRED]
|
||||
|
||||
|
||||
def test_the_timeline_is_the_kit_s_plus_the_inferred_procedures(loaded, kit_rows):
|
||||
"""Pins down: the wired repository reads dbt's view, which holds every row the kit's timeline held, in its
|
||||
order and with a date as `fecha`, plus inferred procedures. Fails if the orchestration binds another query, or
|
||||
the view stops giving one of the kit's rows."""
|
||||
rows = loaded.ctx.repos.silver.timeline.read(until=CORTE)
|
||||
assert as_kit(rows) == kit_rows
|
||||
assert {row["tipo"] for row in rows} & INFERRED
|
||||
assert all(isinstance(row["fecha"], date) for row in rows)
|
||||
|
||||
|
||||
def test_the_patient_filter_keeps_only_those_patients(loaded, kit_rows):
|
||||
"""Pins down: `patients` keeps those patients' rows, all of them. Fails if the filter is dropped or misapplied."""
|
||||
patients = sorted({int(row["pac_id"]) for row in kit_rows})[:2]
|
||||
rows = loaded.ctx.repos.silver.timeline.read(patients=patients, until=CORTE)
|
||||
assert {row["pac_id"] for row in rows} == set(patients)
|
||||
assert as_kit(rows) == [row for row in kit_rows if int(row["pac_id"]) in patients]
|
||||
|
||||
|
||||
def test_known_until_cuts_at_what_was_loaded(loaded):
|
||||
"""Pins down: `known_until` compares with the load's time as a datetime: before the load nothing is known,
|
||||
after it everything is. Fails if the cut is ignored, applied to the clinical date, or compared as text."""
|
||||
timeline = loaded.ctx.repos.silver.timeline
|
||||
everything = timeline.read(until=CORTE)
|
||||
known = {row["conocida_en"] for row in everything}
|
||||
assert all(isinstance(at, datetime) and at.tzinfo is not None for at in known)
|
||||
assert timeline.read(until=CORTE, known_until=min(known) - timedelta(seconds=1)) == []
|
||||
assert timeline.read(until=CORTE, known_until=datetime.now(timezone.utc) + timedelta(days=1)) == everything
|
||||
@@ -1,99 +0,0 @@
|
||||
"""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`, a DEV client over the kit's CaCu demonstration database (`conftest.cliente_de`) plus `seeded`:
|
||||
a surveillance build with two of its patients, one of them with variables and a confirmed batch; `fuera_de_dev`, the
|
||||
same app without `DEV_REVISION`.
|
||||
"""
|
||||
|
||||
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):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setenv("DEV_REVISION", "prueba")
|
||||
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.cohort_repository.save_batch(
|
||||
build_id, {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"},
|
||||
"cin2_12m", [(scored, 3.0, 0.3, None, None), (scored, 1.0, 0.1, None, None)],
|
||||
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
|
||||
cacu.cohort_repository.change_state(batch, "final", "revisado")
|
||||
return scored, unscored, outside
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fuera_de_dev(tmp_path_factory):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
def test_a_scored_member_has_the_contracts_shape(client, seeded):
|
||||
"""Pins down: the body has `simulado`, `cohorte` and `riesgo` with exactly the contract's fields, the horizons in
|
||||
ascending order, probabilities in 0..1 and the date as ISO-8601 UTC. Fails if a field is renamed or dropped, which
|
||||
would break the WebApp's validation."""
|
||||
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
|
||||
|
||||
|
||||
def test_outside_dev_the_route_does_not_exist(fuera_de_dev):
|
||||
"""Pins down: without `DEV_REVISION` the route isn't registered. Fails if patient-level risks are served outside
|
||||
the simulated DEV deployment."""
|
||||
assert fuera_de_dev.get("/cacu/pacientes/1/riesgo").status_code == 404
|
||||
@@ -1,140 +0,0 @@
|
||||
"""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.recomputation import RecomputationQueue
|
||||
|
||||
cola = RecomputationQueue()
|
||||
assert client.get("/reportes/indicadores").get_json()["cacu"]["pendiente"] is True
|
||||
assert cola.serve() == ["cacu"]
|
||||
estado = client.get("/reportes/indicadores").get_json()["cacu"]
|
||||
assert estado["estado"] == "ok", estado
|
||||
assert estado["pendiente"] is False
|
||||
assert {p["paso"] for p in estado["pasos"]} >= {"load", "event_models"}
|
||||
assert {m["id"] for m in client.get("/cacu/indicadores").get_json()} == {
|
||||
"IND1", "CACU_EU13", "CACU_EU7", "CACU_CONFIRMACION_CITOLOGIA", "CACU_EU_TIEMPO_REPORTE",
|
||||
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_RIESGO_BANDA"}
|
||||
|
||||
assert client.post("/reportes/indicadores/cacu/recalcular").status_code == 202
|
||||
assert client.post("/reportes/indicadores/xx/recalcular").status_code == 404
|
||||
|
||||
|
||||
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
|
||||
@@ -1,247 +0,0 @@
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
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
|
||||
from webapi.imports.schemas.tea.pacientes import PacientesImportSchema
|
||||
|
||||
|
||||
def test_paciente_schema_required_field_missing():
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
PacienteImportSchema(pac_sexo="F")
|
||||
errors = excinfo.value.errors()
|
||||
assert any(e["loc"] == ("pac_id_hospital",) for e in errors)
|
||||
|
||||
|
||||
def test_paciente_schema_coerces_sexo_alias():
|
||||
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_sexo="f", pac_fecha_nacimiento="1990-01-15")
|
||||
assert schema.pac_sexo == "Femenino"
|
||||
|
||||
schema2 = PacienteImportSchema(pac_id_hospital="H-2", pac_sexo="MASCULINO", pac_fecha_nacimiento="1990-01-15")
|
||||
assert schema2.pac_sexo == "Masculino"
|
||||
|
||||
|
||||
def test_paciente_schema_rejects_unknown_sexo():
|
||||
with pytest.raises(ValidationError):
|
||||
# pac_sexo has no enum constraint on the storage model, but this is
|
||||
# still a plain string field; feed something structurally invalid
|
||||
# (a date field) to prove type validation happens
|
||||
PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="not-a-date")
|
||||
|
||||
|
||||
def test_paciente_schema_coerces_date_from_iso_string():
|
||||
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="2020-01-15")
|
||||
assert schema.pac_fecha_nacimiento.isoformat() == "2020-01-15"
|
||||
|
||||
|
||||
def test_paciente_schema_coerces_date_from_datetime_object():
|
||||
from datetime import datetime
|
||||
|
||||
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento=datetime(2020, 1, 15, 10, 30))
|
||||
assert schema.pac_fecha_nacimiento.isoformat() == "2020-01-15"
|
||||
|
||||
|
||||
def test_tea_pacientes_schema_is_fully_optional():
|
||||
schema = PacientesImportSchema()
|
||||
assert schema.pac_id_hospital is None
|
||||
|
||||
|
||||
def test_tea_pacientes_schema_coerces_sexo_from_bare_enum_no_alias_dict():
|
||||
schema = PacientesImportSchema(pac_sexo="f")
|
||||
assert schema.pac_sexo == "F"
|
||||
|
||||
|
||||
def test_tea_pacientes_schema_coerces_parentesco():
|
||||
schema = PacientesImportSchema(pac_parentesco="hijo")
|
||||
assert schema.pac_parentesco == "HIJO"
|
||||
|
||||
|
||||
def test_classify_error_missing():
|
||||
try:
|
||||
PacienteImportSchema(pac_sexo="F")
|
||||
except ValidationError as exc:
|
||||
classified = [classify_error(e) for e in exc.errors()]
|
||||
assert any(c.category == ErrorCategory.MISSING and c.field == "pac_id_hospital" for c in classified)
|
||||
|
||||
|
||||
def test_classify_error_type_invalid():
|
||||
try:
|
||||
PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="not-a-date")
|
||||
except ValidationError as exc:
|
||||
classified = [classify_error(e) for e in exc.errors()]
|
||||
assert any(c.category == ErrorCategory.TYPE_INVALID for c in classified)
|
||||
|
||||
|
||||
def test_validate_rows_never_aborts_on_a_bad_row():
|
||||
rows = [
|
||||
{"pac_id_hospital": "H-1", "pac_sexo": "F", "pac_fecha_nacimiento": "1990-01-15"},
|
||||
{"pac_sexo": "M"}, # missing required fields
|
||||
{"pac_id_hospital": "H-3", "pac_fecha_nacimiento": "1990-01-15"},
|
||||
]
|
||||
result = validate_rows(PacienteImportSchema, rows)
|
||||
assert result.total_rows == 3
|
||||
assert result.valid_count == 2
|
||||
assert result.error_count == 1
|
||||
assert result.rejected[0].row_index == 1
|
||||
|
||||
|
||||
def test_column_matcher_exact_normalized_synonym_fuzzy_none():
|
||||
targets = ["pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"]
|
||||
|
||||
suggestions = suggest_mapping(
|
||||
["pac_id_hospital", "Sexo", "fecha_nacimiento", "columna_sin_relacion_xyz"], targets
|
||||
)
|
||||
by_source = {s.source_column: s for s in suggestions}
|
||||
|
||||
assert by_source["pac_id_hospital"].reason == "exact"
|
||||
assert by_source["pac_id_hospital"].target_field == "pac_id_hospital"
|
||||
|
||||
assert by_source["Sexo"].reason == "synonym"
|
||||
assert by_source["Sexo"].target_field == "pac_sexo"
|
||||
|
||||
assert by_source["fecha_nacimiento"].reason in ("synonym", "fuzzy")
|
||||
assert by_source["fecha_nacimiento"].target_field == "pac_fecha_nacimiento"
|
||||
|
||||
assert by_source["columna_sin_relacion_xyz"].target_field is None
|
||||
assert by_source["columna_sin_relacion_xyz"].reason == "none"
|
||||
|
||||
|
||||
def test_column_matcher_enforces_one_to_one():
|
||||
# two source columns that would both match "pac_sexo" exactly-ish
|
||||
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
|
||||
|
||||
|
||||
def test_coerce_date_accepts_iso_day_first_and_timestamps_but_not_impossible_dates():
|
||||
from datetime import date, datetime
|
||||
|
||||
from webapi.imports.schemas.coercion import coerce_date
|
||||
|
||||
assert coerce_date("1990-01-15") == date(1990, 1, 15)
|
||||
assert coerce_date("15/01/1990") == date(1990, 1, 15)
|
||||
assert coerce_date("15-01-1990") == date(1990, 1, 15)
|
||||
assert coerce_date("1990-01-15 00:00:00") == date(1990, 1, 15)
|
||||
assert coerce_date(datetime(1990, 1, 15, 8, 30)) == date(1990, 1, 15)
|
||||
assert coerce_date(" ") is None
|
||||
with pytest.raises(ValueError, match="no es una fecha válida"):
|
||||
coerce_date("31/02/1990")
|
||||
|
||||
|
||||
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
|
||||
|
||||
catalog = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
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"):
|
||||
catalog.coerce("X")
|
||||
|
||||
|
||||
|
||||
|
||||
def test_postal_code_restores_leading_zero_from_numeric_sources():
|
||||
from webapi.imports.schemas.coercion import coerce_postal_code
|
||||
|
||||
assert coerce_postal_code(1000) == "01000"
|
||||
assert coerce_postal_code(64000.0) == "64000"
|
||||
assert coerce_postal_code(" 01000 ") == "01000"
|
||||
assert coerce_postal_code("") is None
|
||||
|
||||
def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog():
|
||||
"""`extraction.nlp.vocabulary.CLINICAL_TERMS` extracts BI-RADS 4A/4B/4C
|
||||
from narrative text (a standard ACR BI-RADS subcategory), but the schema
|
||||
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
|
||||
|
||||
catalog = Catalog(BIRADS, BIRADS_ALIAS)
|
||||
for value in ("4A", "BI-RADS 4B", "bi-rads 4c"):
|
||||
assert catalog.coerce(value) == "B4"
|
||||
|
||||
def test_column_matcher_handles_accents_prefixes_and_global_one_to_one():
|
||||
targets = ["pac_id_hospital", "pac_sexo", "pac_codigo_postal", "pac_fecha_nacimiento"]
|
||||
by_source = {
|
||||
s.source_column: s
|
||||
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"
|
||||
assert by_source["Expediente"].target_field == "pac_id_hospital"
|
||||
# The synonym "fecha_nacimiento" wins pac_fecha_nacimiento even
|
||||
# though the weaker fuzzy "Fech nacim" comes first in the file.
|
||||
assert by_source["fecha_nacimiento"].target_field == "pac_fecha_nacimiento"
|
||||
assert by_source["Fech nacim"].target_field is None
|
||||
|
||||
|
||||
def test_column_matcher_matches_names_without_the_table_prefix():
|
||||
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")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"target, source, expected",
|
||||
[
|
||||
# Match on shared meaning, not shared suffixes ("solicitaDO" vs "solicitaNTE").
|
||||
("cacu.OrdenesEstudio", "Estudio solicitado", "ord_tipo_estudio"),
|
||||
("cacu.OrdenesEstudio", "Paciente", "pac_id_hospital"),
|
||||
("cacu.NotaMedica", "Servicio", "nm_especialidad"),
|
||||
("cacu.NotaMedica", "Fecha consulta", "nm_fecha"),
|
||||
("cacu.NotaMedica", "Peso (kg)", "nm_masa_corporal"),
|
||||
# Flattened JSON paths match by their last segment; unprefixed fields by their words.
|
||||
("cacu.BiometriaHematica", "paciente.expediente", "pac_id_hospital"),
|
||||
("cacu.BiometriaHematica", "resultados.hemoglobina", "hemoglobina_g_dl"),
|
||||
("cacu.BiopsiaCervical", "Fecha de reporte", "bx_fecha_reporte"),
|
||||
],
|
||||
)
|
||||
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 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 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():
|
||||
from webapi.imports.schemas.coercion import Catalog
|
||||
|
||||
catalog = PacienteImportSchema.catalog_for("pac_sexo")
|
||||
assert isinstance(catalog, Catalog)
|
||||
assert catalog.choices["F"] == "Femenino"
|
||||
assert PacienteImportSchema.catalog_for("pac_codigo_postal") is None
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
PacienteImportSchema(pac_id_hospital="H-1", pac_sexo="X", pac_fecha_nacimiento="1990-01-15")
|
||||
(error,) = excinfo.value.errors()
|
||||
classified = classify_error(error)
|
||||
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"
|
||||
@@ -1,80 +0,0 @@
|
||||
"""Smoke-tests that every `ENTITY_REGISTRY` import schema is importable and
|
||||
constructible, plus spot checks of enum-alias coercion."""
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema
|
||||
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
|
||||
from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.episodio_clinico import EpisodioClinicoImportSchema
|
||||
|
||||
|
||||
# Domains whose Core layer is fully permissive (every field Optional);
|
||||
# see `tea/pacientes.py`'s docstring. CaCu/CaMa entities all carry at least
|
||||
# one business-required field (`pac_id_hospital` and friends).
|
||||
_FULLY_OPTIONAL_PREFIXES = ("tea.",)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("entity_key", list(ENTITY_REGISTRY.keys()))
|
||||
def test_every_registered_schema_is_constructible(entity_key):
|
||||
spec = ENTITY_REGISTRY[entity_key]
|
||||
schema_cls = spec.schema
|
||||
|
||||
if entity_key.startswith(_FULLY_OPTIONAL_PREFIXES):
|
||||
# Fully permissive: an empty row must construct cleanly.
|
||||
instance = schema_cls()
|
||||
assert instance is not None
|
||||
else:
|
||||
# Has at least one required field: an empty row must be rejected.
|
||||
with pytest.raises(ValidationError):
|
||||
schema_cls()
|
||||
|
||||
|
||||
# --- Spot checks -----------------------------------------------------------
|
||||
# CaMa entity with a required, unique integer ord_numero_hospital and an
|
||||
# *_ALIAS-backed enum field.
|
||||
|
||||
|
||||
def test_cama_ordenes_estudio_requires_numero_hospital_and_coerces_tipo_estudio():
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
CamaOrdenesEstudioImportSchema(pac_id_hospital="H-1")
|
||||
errors = excinfo.value.errors()
|
||||
assert any(e["loc"] == ("ord_numero_hospital",) for e in errors)
|
||||
|
||||
schema = CamaOrdenesEstudioImportSchema(
|
||||
pac_id_hospital="H-1", ord_numero_hospital=12345, ord_tipo_estudio="biopsia chica"
|
||||
)
|
||||
assert schema.ord_tipo_estudio == "BIOPSIA_CHICA"
|
||||
|
||||
|
||||
# TEA entity with a bare Enum field (no *_ALIAS dict), so the schema builds
|
||||
# a Catalog from the Enum alone, as in tea/pacientes.py.
|
||||
def test_tea_eeg_estudio_coerces_simetria_from_bare_enum_no_alias_dict():
|
||||
schema = EegEstudioImportSchema(eeg_simetria="simetrico")
|
||||
assert schema.eeg_simetria == "SIMETRICO"
|
||||
|
||||
|
||||
# CaCu entity with a real *_ALIAS-backed field (GRADO_CIN_ALIAS).
|
||||
def test_cacu_biopsia_cervical_coerces_cin_grado_alias():
|
||||
schema = BiopsiaCervicalImportSchema(
|
||||
pac_id_hospital="H-1",
|
||||
bx_cin_grado="LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO",
|
||||
)
|
||||
assert schema.bx_cin_grado == "LIEBG"
|
||||
|
||||
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"
|
||||
@@ -1,67 +0,0 @@
|
||||
"""La lista de seguimiento (T-24d): `GET /cacu/seguimiento`, solo en DEV y siempre simulada.
|
||||
|
||||
Sobre la base de demostración del kit (`conftest.cliente_de`). La lista en sí se prueba en el kit
|
||||
(`tests/test_lista_seguimiento.py`); aquí, la ruta: cuándo existe, la forma y los códigos de error.
|
||||
"""
|
||||
|
||||
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):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setenv("DEV_REVISION", "prueba")
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fuera_de_dev(tmp_path_factory):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
def test_en_dev_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
|
||||
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_fuera_de_dev_la_ruta_no_existe(fuera_de_dev):
|
||||
assert fuera_de_dev.get("/cacu/seguimiento").status_code == 404
|
||||
@@ -1,106 +0,0 @@
|
||||
"""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
|
||||
@@ -1,139 +0,0 @@
|
||||
"""The SQL connector is the one import path where the client chooses what
|
||||
the server connects to; these tests pin its guard rails (see
|
||||
webapi.imports.connectors.sql_policy)."""
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
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"}), allowed_hosts=None
|
||||
)
|
||||
|
||||
|
||||
def test_sqlite_is_refused_by_default_policy(tmp_path):
|
||||
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="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"
|
||||
|
||||
|
||||
def test_refuses_the_applications_own_database(monkeypatch, tmp_path):
|
||||
from persistance import settings as persistance_settings
|
||||
|
||||
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="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="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",
|
||||
[
|
||||
"DELETE FROM paciente",
|
||||
"select 1; drop table paciente",
|
||||
"UPDATE t SET a = 1",
|
||||
"-- harmless\nDROP TABLE t",
|
||||
"",
|
||||
],
|
||||
)
|
||||
def test_only_single_select_queries_pass(query):
|
||||
with pytest.raises(ConnectorError):
|
||||
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", "SELECT 'a;b' AS literal"],
|
||||
)
|
||||
def test_select_queries_pass(query):
|
||||
assert SqlSourcePolicy.check_query(query)
|
||||
|
||||
|
||||
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:
|
||||
conn.execute(sa.text("CREATE TABLE t (a INTEGER)"))
|
||||
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):
|
||||
connector.preview()
|
||||
with engine.connect() as conn:
|
||||
assert conn.execute(sa.text("SELECT COUNT(*) FROM t")).scalar_one() == 2
|
||||
|
||||
|
||||
def test_preview_only_fetches_the_limit_but_counts_everything(tmp_path):
|
||||
db = tmp_path / "big.db"
|
||||
engine = sa.create_engine(f"sqlite:///{db}")
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text("CREATE TABLE t (id INTEGER, cp TEXT)"))
|
||||
conn.execute(sa.text("INSERT INTO t VALUES " + ",".join(f"({i}, '0{i:04d}')" for i in range(500))))
|
||||
|
||||
connector = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None)).select_table("t")
|
||||
preview = connector.preview(limit=5)
|
||||
assert len(preview.sample_rows) == 5
|
||||
assert preview.total_rows == 500
|
||||
assert {c.name: c.inferred_type for c in preview.columns} == {"id": "integer", "cp": "string"}
|
||||
|
||||
custom = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None)).select_query(
|
||||
"SELECT id AS expediente FROM t WHERE id < 10"
|
||||
)
|
||||
assert custom.preview(limit=3).total_rows == 10
|
||||
assert list(custom.read_rows({"expediente": "pac_id_hospital"}))[:2] == [{"pac_id_hospital": 0}, {"pac_id_hospital": 1}]
|
||||
@@ -1,97 +0,0 @@
|
||||
import datetime as _dt
|
||||
import os
|
||||
from decimal import Decimal
|
||||
|
||||
from flask import Flask, jsonify
|
||||
from flask.json.provider import DefaultJSONProvider
|
||||
|
||||
from webapi.blueprints.cacu import cacu_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.reports import reports_bp
|
||||
from webapi.follow_up.routes import follow_up_blueprint, in_dev
|
||||
|
||||
|
||||
class IsoJSONProvider(DefaultJSONProvider):
|
||||
"""ISO-8601 dates (Flask's default is RFC 822); files are never sent
|
||||
inline in JSON, only their size."""
|
||||
|
||||
@staticmethod
|
||||
def default(o):
|
||||
if isinstance(o, (_dt.datetime, _dt.date, _dt.time)):
|
||||
return o.isoformat()
|
||||
if isinstance(o, Decimal):
|
||||
return float(o)
|
||||
if isinstance(o, (bytes, bytearray)):
|
||||
return f"<{len(o)} bytes>"
|
||||
return DefaultJSONProvider.default(o)
|
||||
|
||||
|
||||
def create_app() -> Flask:
|
||||
app = Flask(__name__)
|
||||
app.json = IsoJSONProvider(app)
|
||||
# File sources travel inside the request; cap them per request.
|
||||
app.config["MAX_CONTENT_LENGTH"] = int(os.environ.get("WEBAPI_MAX_UPLOAD_MB", "200")) * 1024 * 1024
|
||||
|
||||
# The web client goes through a proxy; browser clients on other origins
|
||||
# are allowed with WEBAPI_CORS_ORIGINS (comma-separated).
|
||||
cors_origins = os.environ.get("WEBAPI_CORS_ORIGINS")
|
||||
if cors_origins:
|
||||
from flask_cors import CORS
|
||||
|
||||
CORS(app, origins=[origin.strip() for origin in cors_origins.split(",")])
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/api")
|
||||
def api_index():
|
||||
"""Every route with its methods and summary, for programmatic clients."""
|
||||
routes = []
|
||||
for rule in sorted(app.url_map.iter_rules(), key=lambda r: r.rule):
|
||||
if rule.endpoint == "static":
|
||||
continue
|
||||
doc = (app.view_functions[rule.endpoint].__doc__ or "").strip()
|
||||
routes.append(
|
||||
{
|
||||
"path": rule.rule,
|
||||
"methods": sorted(rule.methods - {"HEAD", "OPTIONS"}),
|
||||
"summary": " ".join(doc.split("\n\n")[0].split()),
|
||||
}
|
||||
)
|
||||
return jsonify({"routes": routes})
|
||||
|
||||
@app.errorhandler(413)
|
||||
def too_large(_exc):
|
||||
limit_mb = app.config["MAX_CONTENT_LENGTH"] // (1024 * 1024)
|
||||
return jsonify({"error": f"la solicitud excede {limit_mb} MB"}), 413
|
||||
|
||||
app.register_blueprint(cacu_bp, url_prefix="/cacu")
|
||||
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(reports_bp, url_prefix="/reportes")
|
||||
# The measures, answered on request from dbt's semantic definitions: the deployment ships their manifest.
|
||||
if os.environ.get("DBT_MANIFEST"):
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.kpis import kpis_blueprint
|
||||
|
||||
for domain in ("cacu", "cama"):
|
||||
app.register_blueprint(kpis_blueprint(domain, import_module(f"persistance.{domain}"),
|
||||
Path(os.environ["DBT_MANIFEST"])), url_prefix=f"/{domain}")
|
||||
# Patient-level follow-up list and individual risk: only in DEV, with simulated data.
|
||||
if in_dev():
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
|
||||
from persistance import cacu as cacu_repositories
|
||||
|
||||
from webapi.patient_risk import patient_risk_blueprint
|
||||
|
||||
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
|
||||
return app
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
"""The one dependency every route goes through. Open for now; this is where auth will go."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Caller:
|
||||
id: str = "anonymous"
|
||||
|
||||
|
||||
def caller() -> Caller:
|
||||
return Caller()
|
||||
@@ -1,3 +0,0 @@
|
||||
from flask import Blueprint
|
||||
|
||||
cacu_bp = Blueprint("cacu", __name__)
|
||||
@@ -1,33 +0,0 @@
|
||||
"""Generic paginated read access to every importable table through its
|
||||
`Repository`, so clients can inspect what an import wrote."""
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
data_bp = Blueprint("data", __name__)
|
||||
|
||||
_MAX_PAGE = 500
|
||||
|
||||
|
||||
@data_bp.get("/<target>")
|
||||
def list_rows(target: str):
|
||||
spec = ENTITY_REGISTRY.get(target)
|
||||
if spec is None:
|
||||
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 y offset deben ser números enteros"}), 400
|
||||
rows = spec.repository.list(limit=limit, offset=offset)
|
||||
return jsonify(
|
||||
{
|
||||
"target": target,
|
||||
"total": spec.repository.count(),
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
# Table order (JSON objects get their keys sorted on the way out).
|
||||
"columns": [column.name for column in spec.model.__table__.columns],
|
||||
"rows": [row.model_dump() for row in rows],
|
||||
}
|
||||
)
|
||||
@@ -1,281 +0,0 @@
|
||||
"""Model governance (ML, MLD, EL and VAR requirements): model versions and
|
||||
their promotion, and the OCR extraction jobs with their manual review queue.
|
||||
|
||||
Versions and artifacts live in MLflow (`models.io.registry`); training runs
|
||||
elsewhere and registers its result through `POST /model-versions`, naming
|
||||
the indicator kit cohort build it was trained on (`cohorte_armado_id`).
|
||||
"""
|
||||
from dataclasses import asdict
|
||||
|
||||
from core.governance.enums import EstatusExtraccion
|
||||
from core.governance.models import ExtractionRun
|
||||
from core.ocr import OcrEstatus
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from models.io.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__)
|
||||
|
||||
|
||||
@governance_bp.errorhandler(LookupError)
|
||||
def _not_found(exc: LookupError):
|
||||
return jsonify({"error": str(exc)}), 404
|
||||
|
||||
|
||||
@governance_bp.errorhandler(ValueError)
|
||||
def _bad_request(exc: ValueError):
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
|
||||
def _ocr_job(domain: str | None, entity: str | None) -> OcrJob:
|
||||
job = OCR_JOBS.get((domain, entity))
|
||||
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:
|
||||
return next(iter(repository.model.__table__.primary_key.columns)).name
|
||||
|
||||
|
||||
# -- model versions ----------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions")
|
||||
def list_model_versions():
|
||||
"""`?domain=` alone matches every scenario of that domain; `?domain=&scenario=`
|
||||
matches one; neither matches everything."""
|
||||
return jsonify({"model_versions": registry.versions(request.args.get("domain"), request.args.get("scenario"))})
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions")
|
||||
def register_model_version():
|
||||
"""Registers a trained version: `{domain, scenario,
|
||||
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 {}
|
||||
missing = [k for k in ("domain", "scenario", "environment") if not body.get(k)]
|
||||
if missing:
|
||||
return jsonify({"error": f"faltan campos: {missing}"}), 400
|
||||
version = registry.register(
|
||||
domain=body["domain"],
|
||||
scenario=body["scenario"],
|
||||
environment=body["environment"],
|
||||
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},
|
||||
)
|
||||
return jsonify(registry.describe(body["domain"], body["scenario"], version)), 201
|
||||
|
||||
|
||||
@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."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
registry.attach_reports(domain, scenario, version, **body)
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>/lineage")
|
||||
def model_version_lineage(domain: str, scenario: str, version: str):
|
||||
return jsonify(registry.lineage(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>/checks")
|
||||
def model_version_checks(domain: str, scenario: str, version: str):
|
||||
checks = registry.checks(domain, scenario, version)
|
||||
return jsonify({"ready": all(c.passed for c in checks), "checks": [asdict(c) for c in checks]})
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/promote")
|
||||
def promote_model_version(domain: str, scenario: str, version: str):
|
||||
"""Puts the version in production, tagging the previous one of its
|
||||
scenario `retirada_en`. 409 with the failing checks when it isn't ready."""
|
||||
try:
|
||||
registry.promote(domain, scenario, version)
|
||||
except PromotionBlocked as blocked:
|
||||
return jsonify({"error": str(blocked), "checks": [asdict(c) for c in blocked.checks]}), 409
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/retire")
|
||||
def retire_model_version(domain: str, scenario: str, version: str):
|
||||
registry.retire(domain, scenario, version)
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/artifacts")
|
||||
def upload_artifact(domain: str, scenario: str, version: str):
|
||||
"""Multipart `file` and `kind` (ArtifactKind); logged to the version's MLflow run."""
|
||||
from core.governance.enums import ArtifactKind
|
||||
|
||||
upload = request.files.get("file")
|
||||
if upload is None:
|
||||
return jsonify({"error": "falta file"}), 400
|
||||
kinds = [k.value for k in ArtifactKind]
|
||||
if request.form.get("kind") not in kinds:
|
||||
return jsonify({"error": f"kind debe ser uno de {kinds}"}), 400
|
||||
registry.add_artifact(domain, scenario, version, kind=ArtifactKind(request.form["kind"]), filename=upload.filename or "artefacto", data=upload.read())
|
||||
return jsonify(registry.describe(domain, scenario, version)), 201
|
||||
|
||||
|
||||
# -- OCR ---------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/ocr/jobs")
|
||||
def list_ocr_jobs():
|
||||
"""The configured OCR jobs, with the result columns each one fills."""
|
||||
jobs = [
|
||||
{
|
||||
"domain": job.domain,
|
||||
"entity": job.entity,
|
||||
"label": job.label,
|
||||
"result_fields": list(job.columns.result_field_map.values()),
|
||||
}
|
||||
for job in OCR_JOBS.values()
|
||||
]
|
||||
return jsonify({"jobs": jobs})
|
||||
|
||||
|
||||
@governance_bp.get("/ocr/<domain>/<entity>/rows")
|
||||
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: `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))
|
||||
offset = int(request.args.get("offset", 0))
|
||||
pk_name = _pk_name(repository)
|
||||
|
||||
def matches(row) -> bool:
|
||||
if getattr(row, spec.blob_field, None) is None:
|
||||
return False
|
||||
estatus = getattr(row, spec.estatus_field, None)
|
||||
if status == "all":
|
||||
return True
|
||||
if status == "review":
|
||||
return bool(getattr(row, spec.requiere_revision_field, None))
|
||||
if status == "pending":
|
||||
return estatus in (None, OcrEstatus.PENDIENTE.value)
|
||||
if status == "failed":
|
||||
return estatus == OcrEstatus.FALLIDO.value
|
||||
if status == "done":
|
||||
return estatus == OcrEstatus.REALIZADO.value
|
||||
return True
|
||||
|
||||
candidates = [row for row in repository.iter_all() if matches(row)]
|
||||
page = candidates[offset : offset + limit]
|
||||
rows = [
|
||||
{
|
||||
"id": getattr(row, pk_name),
|
||||
"pac_id_hospital": getattr(row, "pac_id_hospital", None),
|
||||
"values": {column: getattr(row, column, None) for column in spec.result_field_map.values()},
|
||||
"confianza": getattr(row, spec.confianza_field, None),
|
||||
"estatus": getattr(row, spec.estatus_field, None),
|
||||
"requiere_revision": getattr(row, spec.requiere_revision_field, None),
|
||||
"metodo_principal": getattr(row, spec.metodo_principal_field, None),
|
||||
"metodo_alternativo": getattr(row, spec.metodo_alternativo_field, None),
|
||||
}
|
||||
for row in page
|
||||
]
|
||||
return jsonify({"rows": rows, "total": len(candidates)})
|
||||
|
||||
|
||||
@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(domain, entity)
|
||||
repository, spec = job.repository, job.columns
|
||||
row = repository.get(pk)
|
||||
if row is None:
|
||||
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
|
||||
return Response(blob, mimetype="application/pdf")
|
||||
|
||||
|
||||
@governance_bp.post("/ocr/<domain>/<entity>/<int:pk>/correct")
|
||||
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(domain, entity)
|
||||
repository, spec = job.repository, job.columns
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
values = body.get("values")
|
||||
if not isinstance(values, dict) or not values:
|
||||
return jsonify({"error": "'values' es requerido y debe tener al menos un campo"}), 400
|
||||
allowed = set(spec.result_field_map.values())
|
||||
unknown = set(values) - allowed
|
||||
if unknown:
|
||||
return jsonify({"error": f"columnas no permitidas para esta entidad: {sorted(unknown)}"}), 400
|
||||
|
||||
with repository.open_session() as session:
|
||||
tracked = session.get(repository.model, pk)
|
||||
if tracked is None:
|
||||
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)
|
||||
setattr(tracked, spec.requiere_revision_field, False)
|
||||
setattr(tracked, spec.metodo_principal_field, "manual")
|
||||
setattr(tracked, spec.metodo_alternativo_field, None)
|
||||
setattr(tracked, spec.confianza_field, float(body["confianza"]) if "confianza" in body else 1.0)
|
||||
session.add(tracked)
|
||||
session.commit()
|
||||
session.refresh(tracked)
|
||||
updated = tracked.model_dump()
|
||||
|
||||
extraction_run_repository.create(
|
||||
ExtractionRun(
|
||||
domain=domain,
|
||||
entity=entity,
|
||||
entity_pk=str(pk),
|
||||
column_extracted=",".join(sorted(values)),
|
||||
transform_description="Corrección manual",
|
||||
estatus=EstatusExtraccion.COMPLETADA,
|
||||
)
|
||||
)
|
||||
return jsonify(updated)
|
||||
|
||||
|
||||
@governance_bp.post("/ocr/run")
|
||||
def run_ocr():
|
||||
"""Runs an OCR job over pending rows. Rows already `REALIZADO` are
|
||||
skipped, so repeated calls are safe (VAR-09)."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
domain = body.get("domain")
|
||||
entity = body.get("entity")
|
||||
job = _ocr_job(domain, entity)
|
||||
|
||||
try:
|
||||
summary = run_pending_extractions(
|
||||
job.repository,
|
||||
job.columns,
|
||||
job.extractor(),
|
||||
domain=domain,
|
||||
entity=entity,
|
||||
governance_repository=extraction_run_repository,
|
||||
source_description=body.get("source_description"),
|
||||
limit=int(body.get("limit", 500)),
|
||||
)
|
||||
except NotImplementedError as exc:
|
||||
return jsonify({"error": str(exc)}), 501
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"processed": summary.processed,
|
||||
"skipped_already_done": summary.skipped_already_done,
|
||||
"failed": summary.failed,
|
||||
"needs_review": summary.needs_review,
|
||||
}
|
||||
)
|
||||
@@ -1,352 +0,0 @@
|
||||
"""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 extraction import BBox, ExtractionError
|
||||
from extraction.readers import reader_for
|
||||
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.import_service import (
|
||||
DatabaseRefused,
|
||||
ImportRequestError,
|
||||
commit_sources,
|
||||
serialize_errors,
|
||||
validate_source,
|
||||
)
|
||||
from webapi.recomputation import DOMAINS, RecomputationQueue
|
||||
from webapi.imports.services.introspection_service import (
|
||||
detect_pdf,
|
||||
document_report,
|
||||
extract_pdf_regions,
|
||||
preview_with_suggestions,
|
||||
)
|
||||
|
||||
imports_bp = Blueprint("imports", __name__)
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BadRequest(Exception):
|
||||
"""Missing or malformed request parameter."""
|
||||
|
||||
|
||||
@imports_bp.errorhandler(BadRequest)
|
||||
@imports_bp.errorhandler(ConnectorError)
|
||||
@imports_bp.errorhandler(ExtractionError)
|
||||
@imports_bp.errorhandler(ImportRequestError)
|
||||
def _bad_request(exc: Exception):
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
|
||||
def _json_body() -> dict:
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
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"falta {key}")
|
||||
return value
|
||||
|
||||
|
||||
def _uploaded_file() -> tuple[str, bytes]:
|
||||
if "file" not in request.files:
|
||||
raise BadRequest("falta el archivo")
|
||||
upload = request.files["file"]
|
||||
return upload.filename or "", upload.read()
|
||||
|
||||
|
||||
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"falta {key}")
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError as exc:
|
||||
raise BadRequest(f"{key} debe ser un número entero") from exc
|
||||
|
||||
|
||||
def _form_json(key: str, default=None):
|
||||
raw = request.form.get(key)
|
||||
if raw in (None, ""):
|
||||
return default
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except json.JSONDecodeError as 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 -------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.get("/connectors")
|
||||
def get_connectors():
|
||||
"""Every source kind the server can read, with what the client needs to
|
||||
offer it (accepted extensions, SQL engines and whether their driver is
|
||||
installed, document segmentation strategies)."""
|
||||
return jsonify({"connectors": catalog()})
|
||||
|
||||
|
||||
@imports_bp.get("/targets")
|
||||
def get_targets():
|
||||
targets = []
|
||||
for key, spec in ENTITY_REGISTRY.items():
|
||||
schema_json = spec.schema.model_json_schema()
|
||||
required = set(schema_json.get("required", []))
|
||||
fields = [
|
||||
{"name": name, "required": name in required, "type": _json_schema_type(prop)}
|
||||
for name, prop in schema_json.get("properties", {}).items()
|
||||
]
|
||||
domain, _, table = key.partition(".")
|
||||
targets.append(
|
||||
{
|
||||
"key": key,
|
||||
"domain": domain,
|
||||
"table": table,
|
||||
"conflict_fields": list(spec.conflict_fields) if spec.conflict_fields else None,
|
||||
"fields": fields,
|
||||
}
|
||||
)
|
||||
return jsonify({"targets": targets})
|
||||
|
||||
|
||||
def _json_schema_type(prop: dict) -> str:
|
||||
"""`Optional[X]` renders as `anyOf: [X, null]`: report X and its format."""
|
||||
candidates = prop.get("anyOf") or [prop]
|
||||
for candidate in candidates:
|
||||
if candidate.get("type") and candidate["type"] != "null":
|
||||
return candidate.get("format") or candidate["type"]
|
||||
return "string"
|
||||
|
||||
|
||||
# -- generic preview --------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/sources/file/preview")
|
||||
def preview_file():
|
||||
"""Multipart upload of any file connector (`source_kind` may be omitted
|
||||
and is then inferred from the file name)."""
|
||||
name, raw = _uploaded_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} no es una fuente de archivo")
|
||||
options = _form_json("options", {}) or {}
|
||||
if "file_name" in cls.option_names:
|
||||
options.setdefault("file_name", name)
|
||||
connector = cls.from_bytes(raw, options)
|
||||
return jsonify(preview_with_suggestions(connector, request.form.get("target")))
|
||||
|
||||
|
||||
@imports_bp.post("/sources/<kind>/preview")
|
||||
def preview_source(kind: str):
|
||||
"""JSON preview for any connector: `{"payload": {...}, "target": "cacu.Paciente"}`,
|
||||
the same payload an import source carries."""
|
||||
body = _json_body()
|
||||
payload = _require(body, "payload")
|
||||
if kind == "document":
|
||||
payload = {**payload, "target": payload.get("target") or body.get("target")}
|
||||
return jsonify(preview_with_suggestions(build_connector(kind, payload), body.get("target")))
|
||||
|
||||
|
||||
# -- SQL browsing -------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/test-connection")
|
||||
def sql_test_connection():
|
||||
connector = SqlConnector.connect(_json_body())
|
||||
connector.test_connection()
|
||||
return jsonify({"ok": True, "dialect": connector.get_dialect()})
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/schemas")
|
||||
def sql_schemas():
|
||||
return jsonify({"schemas": SqlConnector.connect(_json_body()).list_schemas()})
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/tables")
|
||||
def sql_tables():
|
||||
body = _json_body()
|
||||
return jsonify({"tables": SqlConnector.connect(body).list_tables(schema=body.get("schema"))})
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/columns")
|
||||
def sql_columns():
|
||||
body = _json_body()
|
||||
columns = SqlConnector.connect(body).list_columns(_require(body, "table"), schema=body.get("schema"))
|
||||
return jsonify({"columns": [{"name": c.name, "inferred_type": c.inferred_type} for c in columns]})
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/preview")
|
||||
def sql_preview():
|
||||
body = _json_body()
|
||||
connector = SqlConnector.connect(body)
|
||||
if body.get("query"):
|
||||
connector.select_query(body["query"])
|
||||
else:
|
||||
connector.select_table(_require(body, "table"), schema=body.get("schema"))
|
||||
return jsonify(preview_with_suggestions(connector, body.get("target")))
|
||||
|
||||
|
||||
# -- PDF tables -------------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/sources/pdf/detect")
|
||||
def pdf_detect():
|
||||
return jsonify(detect_pdf(_uploaded_file()[1]))
|
||||
|
||||
|
||||
@imports_bp.post("/sources/pdf/page-image")
|
||||
def pdf_page_image():
|
||||
png = PdfConnector(_uploaded_file()[1]).render_page_image(_form_int("page_number"), dpi=_form_int("dpi", 150))
|
||||
return Response(png, mimetype="image/png")
|
||||
|
||||
|
||||
@imports_bp.post("/sources/pdf/table/preview")
|
||||
def pdf_table_preview():
|
||||
raw = _uploaded_file()[1]
|
||||
page_number = _form_int("page_number")
|
||||
bbox = _form_json("bbox")
|
||||
if not isinstance(bbox, list) or len(bbox) != 4:
|
||||
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")))
|
||||
|
||||
|
||||
@imports_bp.post("/sources/pdf/regions/extract")
|
||||
def pdf_regions_extract():
|
||||
body = _json_body()
|
||||
raw = decode_file(body)
|
||||
regions = _require(body, "regions")
|
||||
return jsonify(extract_pdf_regions(raw, regions, dpi=int(body.get("dpi", 150)), target_key=body.get("target")))
|
||||
|
||||
|
||||
# -- documents ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/sources/document/extract")
|
||||
def document_extract():
|
||||
"""Reads the documents, splits them into patient records and extracts
|
||||
the target's fields: `{files: [{name, file_base64}], target,
|
||||
segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?}`.
|
||||
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("faltan los archivos")
|
||||
return jsonify(document_report(body))
|
||||
|
||||
|
||||
@imports_bp.post("/sources/document/page-image")
|
||||
def document_page_image():
|
||||
"""PNG of one page of any supported document; with `bbox` (normalized,
|
||||
JSON list) only that region, e.g. an embedded image."""
|
||||
name, raw = _uploaded_file()
|
||||
reader = reader_for(name, raw)
|
||||
page_number = _form_int("page_number")
|
||||
dpi = min(max(_form_int("dpi", 150), 50), 300)
|
||||
bbox = _form_json("bbox")
|
||||
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 debe ser [x0, y0, x1, y1]")
|
||||
return Response(reader.render_region(raw, page_number, BBox(*map(float, bbox)), dpi=dpi), mimetype="image/png")
|
||||
|
||||
|
||||
# -- validate and load -------------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/validate")
|
||||
def validate():
|
||||
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,
|
||||
"valid_count": result.valid_count,
|
||||
"error_count": result.error_count,
|
||||
"errors": serialize_errors(result),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@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()
|
||||
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 in DOMAINS and any(r.created or r.updated for r in results):
|
||||
try:
|
||||
RecomputationQueue().request_run(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,
|
||||
"results": [
|
||||
{
|
||||
"target": r.target,
|
||||
"label": r.label,
|
||||
"total": r.total,
|
||||
"created": r.created,
|
||||
"updated": r.updated,
|
||||
"rejected": r.rejected,
|
||||
"merged": r.merged,
|
||||
"errors": r.errors,
|
||||
"warnings": r.warnings,
|
||||
"linked": r.linked,
|
||||
}
|
||||
for r in results
|
||||
],
|
||||
}
|
||||
)
|
||||
@@ -1,49 +0,0 @@
|
||||
"""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.recomputation import DOMAINS, RecomputationQueue
|
||||
|
||||
reports_bp = Blueprint("reportes", __name__)
|
||||
|
||||
|
||||
@reports_bp.get("/importaciones")
|
||||
def import_log():
|
||||
"""Totals per target over every logged attempt, plus the latest attempts
|
||||
(`?limite=50`, newest first; `?dominio=cacu` to filter)."""
|
||||
records = import_audit.default_sink().read()
|
||||
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]})
|
||||
|
||||
|
||||
@reports_bp.get("/importaciones/descarga")
|
||||
def import_log_download():
|
||||
"""The raw log, one JSON object per line."""
|
||||
sink = import_audit.default_sink()
|
||||
body = sink.path.read_bytes() if sink.path.exists() else b""
|
||||
return Response(
|
||||
body,
|
||||
mimetype="application/x-ndjson",
|
||||
headers={"Content-Disposition": "attachment; filename=importaciones.jsonl"},
|
||||
)
|
||||
|
||||
|
||||
@reports_bp.get("/indicadores")
|
||||
def recomputation_status():
|
||||
"""Per domain: state of the last recomputation and whether another is pending."""
|
||||
return jsonify(RecomputationQueue().status())
|
||||
|
||||
|
||||
@reports_bp.post("/indicadores/<dominio>/recalcular")
|
||||
def recompute(dominio: str):
|
||||
if dominio not in DOMAINS:
|
||||
return jsonify({"error": f"dominio desconocido: {dominio}"}), 404
|
||||
RecomputationQueue().request_run(dominio)
|
||||
return jsonify({"pendiente": True}), 202
|
||||
@@ -1,329 +0,0 @@
|
||||
"""A composition answered on request: how a period's units split across the categories of their latest valid fact.
|
||||
|
||||
The definition is a simple metric of dbt's semantic layer (the units counted) whose `meta` says `scoring:
|
||||
composition` and gives the category rule (`categoria`): which column is the category, what makes a fact valid
|
||||
(a template like a metric's `filter`), the dates the event and knowledge cut-offs apply to, and the order that picks
|
||||
each unit's latest fact. Which fact is a unit's latest depends on the question (its period and cut-offs), so it's
|
||||
computed in the answer, with `ROW_NUMBER()`, not stored in the model. The rest (the question, the history, strata
|
||||
by age at the period's start) is `webapi.metrics`'.
|
||||
"""
|
||||
|
||||
import dataclasses
|
||||
import hashlib
|
||||
import json
|
||||
from collections.abc import Iterable
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
from core.indicadores.tipos import FechaHoraUTC
|
||||
from jinja2 import Environment
|
||||
from sqlalchemy import Select, String, and_, bindparam, case, cast, column, desc, distinct, func, literal, select, table, text
|
||||
|
||||
from webapi.metrics import (
|
||||
AGGREGATION_VERSION,
|
||||
HISTORY_ENTRY,
|
||||
EVENT_CUTOFF,
|
||||
KNOWLEDGE_CUTOFF,
|
||||
POPULATION_SYSTEM,
|
||||
MeasureQueries,
|
||||
Population,
|
||||
Question,
|
||||
Stratum,
|
||||
_population,
|
||||
_semantic_model_of,
|
||||
key_of,
|
||||
rule_values,
|
||||
)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class FollowUp:
|
||||
"""A fact that follows the chosen one (a biopsy of the chosen sample): the category comes from the first of
|
||||
them by `order`, among those that exist and were dated and known by the cut-offs; `none` if there's none."""
|
||||
|
||||
exists: str
|
||||
dated_at: tuple[str, ...]
|
||||
known_at: tuple[str, ...]
|
||||
order: tuple[str, ...]
|
||||
none: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Category:
|
||||
value: str
|
||||
no_data: str
|
||||
valid_sql: str
|
||||
dated_at: tuple[str, ...]
|
||||
known_at: tuple[str, ...]
|
||||
order: tuple[str, ...]
|
||||
admits_sql: str | None = None # which units count, judged on their chosen fact
|
||||
follow_up: FollowUp | None = None
|
||||
# A number's band instead of the value itself: (band, rule of its upper bound), in order; the last has no bound.
|
||||
bands: tuple[tuple[str, str | None], ...] = ()
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class CompositionDefinition:
|
||||
"""A composition, shaped so `MeasureQueries` can build its period, cut-offs and strata."""
|
||||
|
||||
url: str
|
||||
version: str
|
||||
metric: str
|
||||
relation: str
|
||||
model_checksum: str
|
||||
time_dimension: str
|
||||
dimensions: dict[str, str]
|
||||
units: Population
|
||||
category: Category
|
||||
group: str
|
||||
basis: str
|
||||
rules: dict[str, str]
|
||||
strata: tuple[Stratum, ...]
|
||||
|
||||
@property
|
||||
def measure_id(self) -> str:
|
||||
return self.url.rsplit("/", 1)[-1]
|
||||
|
||||
@property
|
||||
def numerator(self) -> Population:
|
||||
return self.units
|
||||
|
||||
@property
|
||||
def denominator(self) -> Population:
|
||||
return self.units
|
||||
|
||||
improvement_notation = None
|
||||
|
||||
|
||||
def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]:
|
||||
"""The simple metrics of the manifest whose `meta` declares a composition, by `measure_url`."""
|
||||
m = json.loads(manifest.read_text(encoding="utf-8"))
|
||||
semantic = {node["name"]: node for node in m["semantic_models"].values()}
|
||||
models = {node["unique_id"]: node for node in m["nodes"].values()}
|
||||
definitions = {}
|
||||
for metric in m["metrics"].values():
|
||||
meta = metric["config"].get("meta", {})
|
||||
if metric["type"] != "simple" or meta.get("scoring") != "composition":
|
||||
continue
|
||||
model = _semantic_model_of(metric, semantic)
|
||||
node = models[model["depends_on"]["nodes"][0]]
|
||||
rule = meta["categoria"]
|
||||
definitions[meta["measure_url"]] = CompositionDefinition(
|
||||
url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"], relation=node["alias"],
|
||||
model_checksum=node["checksum"]["checksum"], time_dimension=model["defaults"]["agg_time_dimension"],
|
||||
dimensions={**{e["name"]: e["expr"] or e["name"] for e in model["entities"]},
|
||||
**{d["name"]: d["expr"] or d["name"] for d in model["dimensions"]}},
|
||||
units=_population(metric, model),
|
||||
category=Category(rule["valor"], rule["sin_dato"], rule["valido"], tuple(rule.get("fechada_en", ())),
|
||||
tuple(rule.get("conocida_en", ())), tuple(rule["orden"]), rule.get("admite"),
|
||||
_follow_up(rule.get("seguimiento")),
|
||||
tuple((b["valor"], b.get("menor_que")) for b in rule.get("bandas", ()))),
|
||||
group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})),
|
||||
strata=tuple(Stratum.of(name, s) for name, s in meta.get("estratos", {}).items()),
|
||||
)
|
||||
return definitions
|
||||
|
||||
|
||||
def _follow_up(rule: dict | None) -> FollowUp | None:
|
||||
if rule is None:
|
||||
return None
|
||||
return FollowUp(rule["existe"], tuple(rule.get("fechada_en", ())), tuple(rule.get("conocida_en", ())),
|
||||
tuple(rule["orden"]), rule["sin_seguimiento"])
|
||||
|
||||
|
||||
class CompositionQueries(MeasureQueries):
|
||||
"""Each unit's category in the period, from the latest of its facts, valid ones first."""
|
||||
|
||||
def __init__(self, definition: CompositionDefinition, question: Question, rule_values: dict, period_table):
|
||||
super().__init__(definition, question, rule_values, period_table)
|
||||
c, f = definition.category, definition.category.follow_up
|
||||
names = [c.value, *c.order, *c.dated_at, *c.known_at,
|
||||
*((f.exists, *f.order, *f.dated_at, *f.known_at) if f else ()),
|
||||
*(s.spec["valor"] for s in definition.strata if s.kind == "del_elegido")]
|
||||
known = {definition.dimensions[n] for n in (*c.known_at, *(f.known_at if f else ()))}
|
||||
for name in {definition.dimensions[n] for n in names} - set(self.events.c.keys()):
|
||||
self.events.append_column(column(name, FechaHoraUTC) if name in known else column(name))
|
||||
|
||||
def _template(self, sql: str):
|
||||
"""A `meta` condition, rendered like a metric's `filter`, with the rules it names bound (a list as `in`)."""
|
||||
rendered = Environment().from_string(sql).render(
|
||||
Dimension=lambda ref: f"{self.d.relation}.{self.d.dimensions[ref.split('__')[-1]]}")
|
||||
names = [n for n in self.values if f":{n}" in rendered]
|
||||
return text(f"({rendered})").bindparams(*(
|
||||
bindparam(n, self.values[n], expanding=isinstance(self.values[n], (list, tuple))) for n in names))
|
||||
|
||||
def _value(self):
|
||||
"""The category's value: the column's, or the band its number falls in, by the question's rules."""
|
||||
c = self.d.category
|
||||
if not c.bands:
|
||||
return self._column(c.value)
|
||||
number = self._column(c.value)
|
||||
*bounded, (last, _) = c.bands
|
||||
return case(*((number < self.values[rule], literal(band)) for band, rule in bounded), else_=literal(last))
|
||||
|
||||
def _counted(self):
|
||||
"""The follow-up fact of this row exists and was dated and known by the cut-offs."""
|
||||
f = self.d.category.follow_up
|
||||
conditions = [self._column(f.exists).is_not(None)]
|
||||
if self.q.event_cutoff is not None:
|
||||
conditions += [self._column(n) <= self.q.event_cutoff.isoformat() for n in f.dated_at]
|
||||
if self.q.knowledge_cutoff is not None:
|
||||
conditions += [self._column(n) <= self.q.knowledge_cutoff for n in f.known_at]
|
||||
return and_(*conditions)
|
||||
|
||||
def _valid(self):
|
||||
c = self.d.category
|
||||
conditions = [self._template(c.valid_sql)]
|
||||
for name in c.dated_at:
|
||||
conditions.append(self._column(name).is_not(None))
|
||||
if self.q.event_cutoff is not None:
|
||||
conditions.append(self._column(name) <= self.q.event_cutoff.isoformat())
|
||||
if self.q.knowledge_cutoff is not None:
|
||||
conditions += [self._column(name) <= self.q.knowledge_cutoff for name in c.known_at]
|
||||
return and_(*conditions)
|
||||
|
||||
def latest(self, *, with_strata: bool = False):
|
||||
"""One row per unit: its category (`categoria`) and, with strata, its value of each (`estrato_<name>`)."""
|
||||
unit = self.events.c[self.d.units.measure_expr]
|
||||
c, f = self.d.category, self.d.category.follow_up
|
||||
valid = self._valid()
|
||||
order = [desc(case((valid, 1), else_=0)), *(desc(self._column(n)) for n in c.order)]
|
||||
value = self._value()
|
||||
category = case((valid, value))
|
||||
if f is not None:
|
||||
counted = self._counted()
|
||||
order += [desc(case((counted, 1), else_=0)), *(desc(self._column(n)) for n in f.order)]
|
||||
category = case((valid & ~counted, literal(f.none)), (valid, value))
|
||||
admitted = valid if c.admits_sql is None else and_(valid, self._template(c.admits_sql))
|
||||
where = self._in_question()
|
||||
units = self._filter(self.d.units)
|
||||
if units is not None:
|
||||
where = and_(where, units)
|
||||
strata = [self.stratum_value(s).label(f"estrato_{s.name}") for s in self.d.strata] if with_strata else []
|
||||
ranked = (select(unit.label("unidad"), category.label("categoria"), case((admitted, 1), else_=0).label("admitida"),
|
||||
*strata, func.row_number().over(partition_by=unit, order_by=order).label("lugar"))
|
||||
.select_from(self._from(with_strata=with_strata)).where(where).subquery("por_unidad"))
|
||||
chosen = [ranked.c.lugar == 1] + ([ranked.c.admitida == 1] if c.admits_sql is not None else [])
|
||||
return (select(ranked.c.unidad, func.coalesce(ranked.c.categoria, c.no_data).label("categoria"),
|
||||
*(ranked.c[f"estrato_{s.name}"] for s in self.d.strata if with_strata))
|
||||
.where(*chosen).subquery("ultima"))
|
||||
|
||||
def category_counts(self) -> Select:
|
||||
latest = self.latest()
|
||||
return (select(latest.c.categoria, func.count(distinct(latest.c.unidad)))
|
||||
.group_by(latest.c.categoria).order_by(latest.c.categoria))
|
||||
|
||||
def counts_by_stratum(self, stratum: Stratum) -> Select:
|
||||
latest = self.latest(with_strata=True)
|
||||
value = latest.c[f"estrato_{stratum.name}"]
|
||||
return (select(value, latest.c.categoria, func.count(distinct(latest.c.unidad)))
|
||||
.group_by(value, latest.c.categoria))
|
||||
|
||||
def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]:
|
||||
latest = self.latest(with_strata=True)
|
||||
(code,) = self.d.units.codes
|
||||
yield unit_model, select(
|
||||
literal(report_id).label("report_id"), literal(self.d.group).label("grupo"),
|
||||
cast(latest.c.unidad, String(64)).label("unidad_id"),
|
||||
literal(f"{self.d.measure_id}.{code}").label("resultado_id"),
|
||||
(latest.c.unidad if self.d.basis == "paciente" else literal(None)).label("pac_id"),
|
||||
latest.c.categoria.label("valor_id"),
|
||||
)
|
||||
for stratum in self.d.strata:
|
||||
yield stratum_model, select(
|
||||
literal(report_id).label("report_id"), cast(latest.c.unidad, String(64)).label("unidad_id"),
|
||||
literal(stratum.name).label("estrato_id"), latest.c[f"estrato_{stratum.name}"].label("estrato_valor"),
|
||||
)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class CompositionAnswer:
|
||||
report_id: int
|
||||
categories: dict[str, int]
|
||||
strata: dict[str, dict[str, dict[str, int]]]
|
||||
stored_before: bool
|
||||
|
||||
@property
|
||||
def total(self) -> int:
|
||||
return sum(self.categories.values())
|
||||
|
||||
|
||||
def answer_composition(project: str, definition: CompositionDefinition, question: Question, *, parameters, periods,
|
||||
history, queries, allow_undecided: bool = False,
|
||||
now: datetime | None = None) -> CompositionAnswer:
|
||||
"""The stored answer, or a new one: the database ranks each unit's facts, counts and writes the units."""
|
||||
values = rule_values(parameters, definition, allow_undecided)
|
||||
key, key_sha = key_of(definition, question, values)
|
||||
stored = history.find(definition.url, key_sha)
|
||||
if stored is not None:
|
||||
return _from_counts(stored, history.counts(stored))
|
||||
|
||||
period = periods.get(question.period_id)
|
||||
if period is None:
|
||||
raise LookupError(f"dim_periodo has no period {question.period_id!r}")
|
||||
sql = CompositionQueries(definition, question, values, periods.model.__table__)
|
||||
_, rows = queries.rows(sql.category_counts())
|
||||
categories = {category: n for category, n in rows}
|
||||
strata = {}
|
||||
for stratum in definition.strata:
|
||||
_, cells = queries.rows(sql.counts_by_stratum(stratum))
|
||||
for value, category, n in cells:
|
||||
strata.setdefault(stratum.name, {}).setdefault(value, {})[category] = n
|
||||
models = import_module(f"core.{project}.indicadores.models")
|
||||
(any_rule,) = parameters.list(limit=1)
|
||||
report = models.MeasureReport(
|
||||
measure_url=definition.url, measure_version=definition.version,
|
||||
kit_version=f"metric:{definition.metric}:{definition.model_checksum[:12]}", toml_sha=any_rule.toml_sha,
|
||||
parametros=key, parametros_sha=key_sha, fecha_corte=question.event_cutoff,
|
||||
periodo_id=period.periodo_id, periodo_inicio=period.inicio, periodo_fin=period.fin,
|
||||
status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc),
|
||||
agregacion_version=AGGREGATION_VERSION,
|
||||
huella=hashlib.sha256(json.dumps([key_sha, sorted(categories.items()), sorted(
|
||||
(s, v, c, n) for s, by in strata.items() for v, cs in by.items() for c, n in cs.items())]).encode()
|
||||
).hexdigest(),
|
||||
)
|
||||
report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad,
|
||||
models.MeasureReportUnidadEstrato))
|
||||
return CompositionAnswer(report_id, categories, strata, stored_before=False)
|
||||
|
||||
|
||||
def _from_counts(report_id: int, counts: dict) -> CompositionAnswer:
|
||||
categories, strata = {}, {}
|
||||
for (stratum, value, _, category), n in counts.items():
|
||||
if stratum == "total":
|
||||
categories[category] = n
|
||||
else:
|
||||
strata.setdefault(stratum, {}).setdefault(value, {})[category] = n
|
||||
return CompositionAnswer(report_id, categories, strata, stored_before=True)
|
||||
|
||||
|
||||
def composition_report(definition: CompositionDefinition, question: Question, result: CompositionAnswer, period,
|
||||
generated_at: datetime) -> dict:
|
||||
"""The answer as a FHIR R4 `MeasureReport`: the units counted, and a stratifier by category (and by each stratum)."""
|
||||
(code,) = definition.units.codes
|
||||
|
||||
def stratum(value: str, n: int) -> dict:
|
||||
return {"value": {"text": value}, "population": [
|
||||
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": n}]}
|
||||
|
||||
stratifiers = [{"code": [{"text": definition.category.value}],
|
||||
"stratum": [stratum(c, n) for c, n in sorted(result.categories.items())]}]
|
||||
for name, by_value in result.strata.items():
|
||||
stratifiers.append({"code": [{"text": name}],
|
||||
"stratum": [stratum(v, sum(cs.values())) for v, cs in sorted(by_value.items())]})
|
||||
group = {"id": definition.group, "population": [
|
||||
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": result.total},
|
||||
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": code}]}, "count": result.total},
|
||||
], "stratifier": stratifiers}
|
||||
extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}]
|
||||
if question.event_cutoff is not None:
|
||||
extensions.append({"url": EVENT_CUTOFF, "valueDate": question.event_cutoff.isoformat()})
|
||||
if question.knowledge_cutoff is not None:
|
||||
extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()})
|
||||
return {
|
||||
"resourceType": "MeasureReport", "status": "complete", "type": "summary",
|
||||
"measure": f"{definition.url}|{definition.version}", "date": generated_at.isoformat(),
|
||||
"period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()},
|
||||
"extension": extensions, "group": [group],
|
||||
}
|
||||
@@ -1,291 +0,0 @@
|
||||
"""A duration answered on request: the days each unit takes from one fact to the next, summarized by quartiles.
|
||||
|
||||
The definition is a simple metric of dbt's semantic layer (the units counted) whose `meta` says `scoring:
|
||||
continuous-variable` and gives the observation rule (`observacion`): the column with each unit's days, the dates the
|
||||
cut-offs apply to, and the horizon: a unit without a value whose horizon hasn't passed by the event cut-off isn't
|
||||
measured yet, so it's left out of the initial population. Days are differences of `dim_fecha.dia_num`, computed in
|
||||
dbt's event model; the cut-off's day is looked up the same way. Quartiles are ANSI (`inclusive_quartiles`).
|
||||
|
||||
The event cut-off defaults to the day of the last load, as the horizon needs a day to count to.
|
||||
"""
|
||||
|
||||
import dataclasses
|
||||
import hashlib
|
||||
import json
|
||||
from collections.abc import Iterable
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import Integer, Select, String, and_, case, cast, column, func, literal, not_, null, select, table, true
|
||||
|
||||
from webapi.metrics import (
|
||||
AGGREGATION_VERSION,
|
||||
EVENT_CUTOFF,
|
||||
HISTORY_ENTRY,
|
||||
KNOWLEDGE_CUTOFF,
|
||||
POPULATION_SYSTEM,
|
||||
MeasureQueries,
|
||||
Population,
|
||||
Question,
|
||||
_population,
|
||||
_semantic_model_of,
|
||||
key_of,
|
||||
rule_values,
|
||||
)
|
||||
|
||||
OBSERVATION = "measure-observation"
|
||||
LOADS = table("carga", column("inicio"), column("fin"))
|
||||
DAYS = table("dim_fecha", column("fecha"), column("dia_num"))
|
||||
|
||||
|
||||
def inclusive_quartiles(values) -> Select:
|
||||
"""(n, q1, median, q3) of a subquery's `numero`, by the inclusive method in ANSI SQL.
|
||||
|
||||
The quartile `q` is at position `(n - 1) q` of the sorted values (from 0), interpolating between its two
|
||||
neighbors, as `statistics.quantiles(method="inclusive")`; with one value, the three are it. Window functions,
|
||||
`CAST` and `CASE` only: the same SQL on every engine.
|
||||
"""
|
||||
ranked = select(values.c.numero,
|
||||
(func.row_number().over(order_by=values.c.numero) - 1).label("i"),
|
||||
func.count().over().label("n")).subquery("ordenados")
|
||||
cells = []
|
||||
for name, q in (("q1", 0.25), ("mediana", 0.5), ("q3", 0.75)):
|
||||
position = (ranked.c.n - 1) * q
|
||||
floor = cast(position, Integer)
|
||||
fraction = position - floor
|
||||
cells.append((func.sum(case((ranked.c.i == floor, ranked.c.numero * (1 - fraction)), else_=0.0))
|
||||
+ func.sum(case((ranked.c.i == floor + 1, ranked.c.numero * fraction), else_=0.0))).label(name))
|
||||
return select(func.count(ranked.c.numero).label("n"), *cells)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Observation:
|
||||
value: str
|
||||
dated_at: tuple[str, ...]
|
||||
known_at: tuple[str, ...]
|
||||
horizon_rule: str | None
|
||||
start_day: str
|
||||
horizon_days: int | None = None # a fixed horizon, when the model used the same one to find the next fact
|
||||
|
||||
def horizon(self, values: dict) -> int:
|
||||
return self.horizon_days if self.horizon_rule is None else values[self.horizon_rule]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class DurationDefinition:
|
||||
"""A duration, shaped so `MeasureQueries` can build its period and cut-offs."""
|
||||
|
||||
url: str
|
||||
version: str
|
||||
metric: str
|
||||
relation: str
|
||||
model_checksum: str
|
||||
time_dimension: str
|
||||
dimensions: dict[str, str]
|
||||
units: Population
|
||||
observation: Observation
|
||||
group: str
|
||||
basis: str
|
||||
rules: dict[str, str]
|
||||
improvement_notation: str | None = None
|
||||
strata: tuple = ()
|
||||
|
||||
@property
|
||||
def measure_id(self) -> str:
|
||||
return self.url.rsplit("/", 1)[-1]
|
||||
|
||||
@property
|
||||
def numerator(self) -> Population:
|
||||
return self.units
|
||||
|
||||
@property
|
||||
def denominator(self) -> Population:
|
||||
return self.units
|
||||
|
||||
|
||||
def duration_definitions(manifest: Path) -> dict[str, DurationDefinition]:
|
||||
"""The simple metrics of the manifest whose `meta` declares a duration, by `measure_url`."""
|
||||
m = json.loads(manifest.read_text(encoding="utf-8"))
|
||||
semantic = {node["name"]: node for node in m["semantic_models"].values()}
|
||||
models = {node["unique_id"]: node for node in m["nodes"].values()}
|
||||
definitions = {}
|
||||
for metric in m["metrics"].values():
|
||||
meta = metric["config"].get("meta", {})
|
||||
if metric["type"] != "simple" or meta.get("scoring") != "continuous-variable":
|
||||
continue
|
||||
model = _semantic_model_of(metric, semantic)
|
||||
node = models[model["depends_on"]["nodes"][0]]
|
||||
rule = meta["observacion"]
|
||||
definitions[meta["measure_url"]] = DurationDefinition(
|
||||
url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"], relation=node["alias"],
|
||||
model_checksum=node["checksum"]["checksum"], time_dimension=model["defaults"]["agg_time_dimension"],
|
||||
dimensions={**{e["name"]: e["expr"] or e["name"] for e in model["entities"]},
|
||||
**{d["name"]: d["expr"] or d["name"] for d in model["dimensions"]}},
|
||||
units=_population(metric, model),
|
||||
observation=Observation(rule["valor"], tuple(rule.get("fechada_en", ())), tuple(rule.get("conocida_en", ())),
|
||||
rule["horizonte"].get("regla"), rule["horizonte"]["dia_inicio"],
|
||||
int(rule["horizonte"]["dias"]) if "dias" in rule["horizonte"] else None),
|
||||
group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})),
|
||||
improvement_notation=meta.get("improvement_notation"),
|
||||
)
|
||||
return definitions
|
||||
|
||||
|
||||
class DurationQueries(MeasureQueries):
|
||||
"""Each unit of the period: measured or not yet, and its days if it has them."""
|
||||
|
||||
def __init__(self, definition: DurationDefinition, question: Question, rule_values: dict, period_table):
|
||||
super().__init__(definition, question, rule_values, period_table)
|
||||
o = definition.observation
|
||||
for name in {definition.dimensions[n] for n in (o.value, o.start_day, *o.dated_at)} - set(self.events.c.keys()):
|
||||
self.events.append_column(column(name))
|
||||
|
||||
def _has_value(self):
|
||||
o, q = self.d.observation, self.q
|
||||
conditions = [self._column(o.value).is_not(None)]
|
||||
conditions += [self._column(n) <= q.event_cutoff.isoformat() for n in o.dated_at]
|
||||
if q.knowledge_cutoff is not None:
|
||||
conditions += [self._column(n) <= q.knowledge_cutoff for n in o.known_at]
|
||||
return and_(*conditions)
|
||||
|
||||
def per_unit(self):
|
||||
"""One row per unit in the period: `unidad`, `numero` (its days, or null) and whether it's still `pendiente`."""
|
||||
o = self.d.observation
|
||||
cutoff_day = select(DAYS.c.dia_num).where(DAYS.c.fecha == self.q.event_cutoff.isoformat()).scalar_subquery()
|
||||
has_value = self._has_value()
|
||||
pending = and_(not_(has_value),
|
||||
cutoff_day - self._column(o.start_day) < o.horizon(self.values))
|
||||
where = self._in_question()
|
||||
units = self._filter(self.d.units)
|
||||
if units is not None:
|
||||
where = and_(where, units)
|
||||
unit = self.events.c[self.d.units.measure_expr]
|
||||
return (select(unit.label("unidad"), case((has_value, self._column(o.value)), else_=null()).label("numero"),
|
||||
case((pending, 1), else_=0).label("pendiente"))
|
||||
.select_from(self._from(with_strata=False)).where(where).distinct().subquery("por_unidad"))
|
||||
|
||||
def summary(self) -> Select:
|
||||
units = self.per_unit()
|
||||
measured = select(units.c.numero).where(units.c.numero.is_not(None)).subquery("medidos")
|
||||
quartiles = inclusive_quartiles(measured).subquery("cuartiles")
|
||||
initial = select(func.count(units.c.unidad).label("inicial")).where(units.c.pendiente == 0).subquery("inicial")
|
||||
# Two one-row subqueries side by side.
|
||||
return (select(initial.c.inicial, quartiles.c.n, quartiles.c.q1, quartiles.c.mediana, quartiles.c.q3)
|
||||
.select_from(initial.join(quartiles, true())))
|
||||
|
||||
def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]:
|
||||
units = self.per_unit()
|
||||
(initial,) = self.d.units.codes
|
||||
for code, where, number in ((initial, units.c.pendiente == 0, null()),
|
||||
(OBSERVATION, units.c.numero.is_not(None), units.c.numero)):
|
||||
yield unit_model, select(
|
||||
literal(report_id).label("report_id"), literal(self.d.group).label("grupo"),
|
||||
cast(units.c.unidad, String(64)).label("unidad_id"),
|
||||
literal(f"{self.d.measure_id}.{code}").label("resultado_id"),
|
||||
(units.c.unidad if self.d.basis == "paciente" else literal(None)).label("pac_id"),
|
||||
cast(number, unit_model.__table__.c.numero.type).label("numero"),
|
||||
).where(where)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class DurationAnswer:
|
||||
report_id: int
|
||||
initial: int
|
||||
n: int
|
||||
q1: float | None
|
||||
median: float | None
|
||||
q3: float | None
|
||||
stored_before: bool
|
||||
event_cutoff: date | None = None # the one it was computed at: the question's, or the last load's day
|
||||
|
||||
@property
|
||||
def excluded(self) -> int:
|
||||
return self.initial - self.n
|
||||
|
||||
|
||||
def last_load_day(queries) -> date | None:
|
||||
"""The day of the latest load: its `fin`, or its `inicio` if it didn't finish."""
|
||||
_, ((last,),) = queries.rows(select(func.max(func.coalesce(LOADS.c.fin, LOADS.c.inicio))))
|
||||
return None if last is None else date.fromisoformat(str(last)[:10])
|
||||
|
||||
|
||||
def answer_duration(project: str, definition: DurationDefinition, question: Question, *, parameters, periods,
|
||||
history, queries, allow_undecided: bool = False, now: datetime | None = None) -> DurationAnswer:
|
||||
"""The stored answer, or a new one: the database decides each unit, counts, takes the quartiles and stores."""
|
||||
if question.event_cutoff is None:
|
||||
question = dataclasses.replace(question, event_cutoff=last_load_day(queries))
|
||||
values = rule_values(parameters, definition, allow_undecided)
|
||||
if definition.observation.horizon_rule is None:
|
||||
values["horizonte_dias"] = definition.observation.horizon_days
|
||||
key, key_sha = key_of(definition, question, values)
|
||||
models = import_module(f"core.{project}.indicadores.models")
|
||||
stored = history.find(definition.url, key_sha)
|
||||
if stored is not None:
|
||||
return dataclasses.replace(_from_stored(definition, stored, queries, models.MeasureReportUnidad),
|
||||
event_cutoff=question.event_cutoff)
|
||||
|
||||
period = periods.get(question.period_id)
|
||||
if period is None:
|
||||
raise LookupError(f"dim_periodo has no period {question.period_id!r}")
|
||||
sql = DurationQueries(definition, question, values, periods.model.__table__)
|
||||
_, ((initial, n, q1, median, q3),) = queries.rows(sql.summary())
|
||||
(any_rule,) = parameters.list(limit=1)
|
||||
report = models.MeasureReport(
|
||||
measure_url=definition.url, measure_version=definition.version,
|
||||
kit_version=f"metric:{definition.metric}:{definition.model_checksum[:12]}", toml_sha=any_rule.toml_sha,
|
||||
parametros=key, parametros_sha=key_sha, fecha_corte=question.event_cutoff,
|
||||
periodo_id=period.periodo_id, periodo_inicio=period.inicio, periodo_fin=period.fin,
|
||||
status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc),
|
||||
agregacion_version=AGGREGATION_VERSION,
|
||||
huella=hashlib.sha256(json.dumps([key_sha, initial, n, q1, median, q3]).encode()).hexdigest(),
|
||||
)
|
||||
report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad,
|
||||
models.MeasureReportUnidadEstrato))
|
||||
return DurationAnswer(report_id, initial, n, *_numbers(n, q1, median, q3), stored_before=False,
|
||||
event_cutoff=question.event_cutoff)
|
||||
|
||||
|
||||
def _numbers(n, q1, median, q3):
|
||||
return (None, None, None) if not n else (float(q1), float(median), float(q3))
|
||||
|
||||
|
||||
def _from_stored(definition: DurationDefinition, report_id: int, queries, unit_model) -> DurationAnswer:
|
||||
"""A stored duration read back from its units: the initial ones counted, the quartiles of their days."""
|
||||
u = unit_model.__table__.c
|
||||
initial = f"{definition.measure_id}.{definition.units.codes[0]}"
|
||||
observed = select(u.numero).where(u.report_id == report_id, u.resultado_id == f"{definition.measure_id}.{OBSERVATION}")
|
||||
_, ((n, q1, median, q3),) = queries.rows(inclusive_quartiles(observed.subquery("medidos")))
|
||||
_, ((count,),) = queries.rows(select(func.count()).where(u.report_id == report_id, u.resultado_id == initial))
|
||||
return DurationAnswer(report_id, count, n, *_numbers(n, q1, median, q3), stored_before=True)
|
||||
|
||||
|
||||
def duration_report(definition: DurationDefinition, question: Question, result: DurationAnswer, period,
|
||||
generated_at: datetime) -> dict:
|
||||
"""The answer as a FHIR R4 `MeasureReport`: the units measurable and measured, the median as the score, and the
|
||||
quartiles as its components."""
|
||||
group = {"id": definition.group, "population": [
|
||||
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": result.initial},
|
||||
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": OBSERVATION}]}, "count": result.n},
|
||||
]}
|
||||
if result.median is not None:
|
||||
group["measureScore"] = {"value": result.median, "unit": "d",
|
||||
"extension": [{"url": "https://isssteleon.org/fhir/StructureDefinition/q1",
|
||||
"valueDecimal": result.q1},
|
||||
{"url": "https://isssteleon.org/fhir/StructureDefinition/q3",
|
||||
"valueDecimal": result.q3}]}
|
||||
extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id},
|
||||
{"url": EVENT_CUTOFF, "valueDate": (result.event_cutoff or question.event_cutoff).isoformat()}]
|
||||
if question.knowledge_cutoff is not None:
|
||||
extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()})
|
||||
report = {
|
||||
"resourceType": "MeasureReport", "status": "complete", "type": "summary",
|
||||
"measure": f"{definition.url}|{definition.version}", "date": generated_at.isoformat(),
|
||||
"period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()},
|
||||
"extension": extensions, "group": [group],
|
||||
}
|
||||
if definition.improvement_notation:
|
||||
report["improvementNotation"] = {"coding": [{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": definition.improvement_notation}]}
|
||||
return report
|
||||
@@ -1,7 +0,0 @@
|
||||
"""CaCu's follow-up list (`GET /cacu/seguimiento`): one row per patient, with her ASCCP status and her latest studies.
|
||||
|
||||
routes.py the route: validates the request and answers
|
||||
listing.py the list: who enters it, what each row shows
|
||||
status.py the ASCCP status of each patient at a date
|
||||
silver.py, pivot.py, view.py, functions.py the silver queries they read
|
||||
"""
|
||||
@@ -1,53 +0,0 @@
|
||||
# Los estratos que un indicador puede declarar en `extension.estratos`.
|
||||
# Cada uno es una función de SQLAlchemy que devuelve una CTE con
|
||||
# (unidad_id, estrato); el cálculo la cruza con las poblaciones sin
|
||||
# tocarlas (mart/estratos.py).
|
||||
#
|
||||
# expression "modulo.del.kit:funcion"
|
||||
# unidad la unidad de los indicadores a los que sirve (`basis`)
|
||||
# fechas lo que el estrato cruza con dim_fecha, si lo lee
|
||||
# parametros sus reglas: parámetro de la consulta -> clave de parametros.toml (la
|
||||
# función las recibe resueltas y entran a la huella del reporte)
|
||||
# valores sus valores con su etiqueta, en orden, si no salen de otra regla
|
||||
# etiqueta cómo se llama en pantalla (la leyenda, el selector de filtros); sin ella, su nombre
|
||||
#
|
||||
# Sección `comun`: para todos los proyectos; `<proyecto>`: solo ese, y
|
||||
# gana sobre `comun` si se llaman igual.
|
||||
|
||||
[comun.grupo_edad]
|
||||
etiqueta = "Grupo de edad"
|
||||
expression = "comun.estratos.grupo_edad:estrato"
|
||||
unidad = "paciente"
|
||||
fechas = { hechos = ["v_persona.fecha_nacimiento"], parametros = ["periodo_inicio"] }
|
||||
|
||||
# Estatus de seguimiento ASCCP de la paciente (T-24c): `cacu/seguimiento.py`. Sus reglas son de
|
||||
# `parametros.toml` (§2bis) y entran a la huella del reporte. Excluyente y exhaustivo: sin `sin_dato`.
|
||||
[cacu.estatus_seguimiento]
|
||||
etiqueta = "Estatus de seguimiento"
|
||||
expression = "cacu.seguimiento:estrato"
|
||||
unidad = "paciente"
|
||||
valores = [
|
||||
{ valor = "PRE_COLPOSCOPIA", etiqueta = "Pre colposcopia" },
|
||||
{ valor = "POST_COLPOSCOPIA", etiqueta = "Post colposcopia" },
|
||||
{ valor = "POST_TRATAMIENTO", etiqueta = "Post tratamiento" },
|
||||
{ valor = "INFO_INSUFICIENTE", etiqueta = "Información insuficiente" },
|
||||
]
|
||||
|
||||
[cacu.estatus_seguimiento.parametros]
|
||||
seguimiento_marco = "cacu.seguimiento.marco"
|
||||
seguimiento_referencia = "cacu.seguimiento.referencia"
|
||||
seguimiento_precedencia = "cacu.seguimiento.precedencia"
|
||||
seguimiento_evidencias = "cacu.seguimiento.colposcopia.evidencias"
|
||||
seguimiento_requisito = "cacu.seguimiento.colposcopia.requisito"
|
||||
seguimiento_biopsia_requisito = "cacu.seguimiento.colposcopia.biopsia_requisito"
|
||||
seguimiento_cie_valoracion = "cacu.diagnostico.cie"
|
||||
seguimiento_especialidades_valoracion = "cacu.diagnostico.especialidades"
|
||||
seguimiento_horizonte_valoracion = "cacu.horizontes.toma_diagnostico_dias"
|
||||
seguimiento_motivos = "cacu.seguimiento.colposcopia.motivos"
|
||||
seguimiento_especialidades_colposcopia = "cacu.seguimiento.colposcopia.especialidades"
|
||||
seguimiento_cie_colposcopia = "cacu.seguimiento.colposcopia.cie"
|
||||
seguimiento_diagnosticos = "cacu.seguimiento.colposcopia.diagnosticos"
|
||||
seguimiento_fuentes_tratamiento = "cacu.seguimiento.tratamiento.fuentes"
|
||||
seguimiento_cie_tratamiento = "cacu.seguimiento.tratamiento.cie"
|
||||
seguimiento_insuficiente = "cacu.seguimiento.insuficiente.regla"
|
||||
seguimiento_especialidades_vigilancia = "cacu.seguimiento.vigilancia.especialidades"
|
||||
@@ -1,100 +0,0 @@
|
||||
"""Lo que cada motor escribe distinto, como una función con una regla por motor.
|
||||
|
||||
SQLAlchemy traduce la sintaxis, no las funciones de fecha. Aquí van las
|
||||
que el kit necesita. Agregar un motor es agregar su regla; ninguna
|
||||
definición cambia. Sin regla para un motor queda la forma neutra, que es
|
||||
la que lee el registro de huellas y no se puede ejecutar. Solo la regla
|
||||
de SQLite se ejecuta en las pruebas (D-S5).
|
||||
"""
|
||||
|
||||
from sqlalchemy import Integer
|
||||
from sqlalchemy.ext.compiler import compiles
|
||||
from sqlalchemy.sql.expression import FunctionElement
|
||||
|
||||
|
||||
class dias_entre(FunctionElement):
|
||||
"""Días enteros de `inicio` a `fin`: `dias_entre(inicio, fin)`."""
|
||||
|
||||
type = Integer()
|
||||
inherit_cache = True
|
||||
|
||||
|
||||
def _partes(elemento, compilador, opciones) -> tuple[str, str]:
|
||||
inicio, fin = list(elemento.clauses)
|
||||
return compilador.process(inicio, **opciones), compilador.process(fin, **opciones)
|
||||
|
||||
|
||||
@compiles(dias_entre)
|
||||
def _neutra(elemento, compilador, **opciones) -> str:
|
||||
inicio, fin = _partes(elemento, compilador, opciones)
|
||||
return f"dias_entre({inicio}, {fin})"
|
||||
|
||||
|
||||
@compiles(dias_entre, "sqlite")
|
||||
def _sqlite(elemento, compilador, **opciones) -> str:
|
||||
inicio, fin = _partes(elemento, compilador, opciones)
|
||||
return f"CAST(julianday({fin}) - julianday({inicio}) AS INTEGER)"
|
||||
|
||||
|
||||
@compiles(dias_entre, "postgresql")
|
||||
def _postgresql(elemento, compilador, **opciones) -> str:
|
||||
inicio, fin = _partes(elemento, compilador, opciones)
|
||||
return f"(CAST({fin} AS DATE) - CAST({inicio} AS DATE))"
|
||||
|
||||
|
||||
@compiles(dias_entre, "mysql", "mariadb")
|
||||
def _mysql(elemento, compilador, **opciones) -> str:
|
||||
inicio, fin = _partes(elemento, compilador, opciones)
|
||||
return f"DATEDIFF({fin}, {inicio})"
|
||||
|
||||
|
||||
@compiles(dias_entre, "mssql")
|
||||
def _mssql(elemento, compilador, **opciones) -> str:
|
||||
inicio, fin = _partes(elemento, compilador, opciones)
|
||||
return f"DATEDIFF(day, {inicio}, {fin})"
|
||||
|
||||
|
||||
class entero_de_json(FunctionElement):
|
||||
"""Un entero de un objeto JSON guardado como texto: `entero_de_json(columna, "clave")`.
|
||||
|
||||
PostgreSQL no aplica `->>` a `text` y SQL Server no tiene tipo JSON: cada
|
||||
motor lee la clave con su propia función.
|
||||
"""
|
||||
|
||||
type = Integer()
|
||||
inherit_cache = True
|
||||
|
||||
|
||||
def _columna_y_clave(elemento, compilador, opciones) -> tuple[str, str]:
|
||||
columna, clave = list(elemento.clauses)
|
||||
return compilador.process(columna, **opciones), clave.value
|
||||
|
||||
|
||||
@compiles(entero_de_json)
|
||||
def _entero_neutro(elemento, compilador, **opciones) -> str:
|
||||
columna, clave = _columna_y_clave(elemento, compilador, opciones)
|
||||
return f"entero_de_json({columna}, '{clave}')"
|
||||
|
||||
|
||||
@compiles(entero_de_json, "sqlite")
|
||||
def _entero_sqlite(elemento, compilador, **opciones) -> str:
|
||||
columna, clave = _columna_y_clave(elemento, compilador, opciones)
|
||||
return f"CAST(json_extract({columna}, '$.{clave}') AS INTEGER)"
|
||||
|
||||
|
||||
@compiles(entero_de_json, "mysql", "mariadb")
|
||||
def _entero_mysql(elemento, compilador, **opciones) -> str:
|
||||
columna, clave = _columna_y_clave(elemento, compilador, opciones)
|
||||
return f"CAST(JSON_UNQUOTE(JSON_EXTRACT({columna}, '$.{clave}')) AS SIGNED)"
|
||||
|
||||
|
||||
@compiles(entero_de_json, "postgresql")
|
||||
def _entero_postgresql(elemento, compilador, **opciones) -> str:
|
||||
columna, clave = _columna_y_clave(elemento, compilador, opciones)
|
||||
return f"CAST(CAST({columna} AS JSON) ->> '{clave}' AS INTEGER)"
|
||||
|
||||
|
||||
@compiles(entero_de_json, "mssql")
|
||||
def _entero_mssql(elemento, compilador, **opciones) -> str:
|
||||
columna, clave = _columna_y_clave(elemento, compilador, opciones)
|
||||
return f"CAST(JSON_VALUE({columna}, '$.{clave}') AS INT)"
|
||||
@@ -1,296 +0,0 @@
|
||||
"""La lista de seguimiento de CaCu (T-24d): `GET /cacu/seguimiento`, una fila por paciente.
|
||||
|
||||
El contrato es T-24a. Es una consulta al
|
||||
vuelo sobre la plata, no un `measure_report`: no guarda nada. Entra cada paciente con al menos un
|
||||
estudio (`cacu.seguimiento.estudios`) en la ventana de `meses` hasta el corte; por cada una, su
|
||||
grupo de edad al corte, su estatus al corte (`cacu.seguimiento.estatus_al`, la misma regla del
|
||||
estrato), su citología y su VPH de la ventana y los días de la toma a su valoración (con las reglas
|
||||
de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula.
|
||||
|
||||
**Es dato por paciente.** Quien sirve la registra solo en DEV, con datos simulados, y toda respuesta
|
||||
lleva `simulado: true`. Nunca sale `pac_id` ni `pac_id_hospital`: `id_seudonimo` es un hash con sal.
|
||||
|
||||
Las reglas son de `parametros.toml` (`PARAMETROS_DE_LA_LISTA` y las del estrato `estatus_seguimiento`
|
||||
de `estratos.toml`) y salen en `reglas` con su estado. Recibe la sesión de quien sirve; no abre ninguna.
|
||||
"""
|
||||
|
||||
import calendar
|
||||
import hashlib
|
||||
import json
|
||||
import tomllib
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.follow_up.silver import citologias, notas
|
||||
from webapi.follow_up.status import ESTATUS, estatus_al, exigir_opcion, exigir_opciones, reglas_de
|
||||
from webapi.orchestration.tables.cacu import TABLAS
|
||||
from webapi.follow_up.view import P
|
||||
from webapi.orchestration.reference.age_groups import grupos_de_cortes
|
||||
from webapi.orchestration.reference.rules import valor_de
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
RAIZ = Path(__file__).resolve().parent # `estratos.toml` is next to this module
|
||||
SIN_DATO = "sin_dato"
|
||||
|
||||
|
||||
def leer_estrato(proyecto: str, nombre: str) -> SimpleNamespace:
|
||||
"""The stratum's rules and values in `estratos.toml` (the project's, or the common one)."""
|
||||
with open(RAIZ / "estratos.toml", "rb") as archivo:
|
||||
secciones = tomllib.load(archivo)
|
||||
for seccion in (proyecto, "comun"):
|
||||
if nombre in secciones.get(seccion, {}):
|
||||
entrada = secciones[seccion][nombre]
|
||||
return SimpleNamespace(parametros=entrada.get("parametros", {}), valores=entrada.get("valores", []))
|
||||
raise KeyError(f"No hay estrato {nombre!r} para {proyecto!r} en estratos.toml.")
|
||||
|
||||
|
||||
def ejecutar(sesion: Session, consulta, parametros: dict):
|
||||
"""Runs with the parameters the query names."""
|
||||
nombrados = set(consulta.compile().params)
|
||||
return sesion.execute(consulta, {n: v for n, v in parametros.items() if n in nombrados})
|
||||
|
||||
VENTANAS = (1, 3, 6, 12)
|
||||
FECHAS_DE_ESTUDIO = ("toma", "reporte")
|
||||
ESTUDIOS = ("citologia", "vph")
|
||||
RESULTADOS_MOSTRADOS = ("ultimo", "mas_grave")
|
||||
PAGINA_MAXIMA = 200
|
||||
# Nombre en esta lista -> clave en `parametros.toml`.
|
||||
PARAMETROS_DE_LA_LISTA = {
|
||||
"ventana_meses": "cacu.seguimiento.ventana_meses",
|
||||
"fecha_estudio": "cacu.seguimiento.fecha_estudio",
|
||||
"estudios": "cacu.seguimiento.estudios",
|
||||
"resultado_mostrado": "cacu.seguimiento.resultado_mostrado",
|
||||
"grupos_edad": "cacu.grupos_edad",
|
||||
"catalogo": "cacu.catalogos.citologia",
|
||||
"cie_diagnostico": "cacu.diagnostico.cie",
|
||||
"especialidades_diagnostico": "cacu.diagnostico.especialidades",
|
||||
"cie_antecedente": "cacu.diagnostico.cie_antecedente",
|
||||
"horizonte_dias": "cacu.horizontes.toma_diagnostico_dias",
|
||||
}
|
||||
ESTRATO = "estatus_seguimiento"
|
||||
|
||||
|
||||
class PedidoInvalido(ValueError):
|
||||
"""Un parámetro del pedido fuera de lo que admite el contrato (400)."""
|
||||
|
||||
|
||||
class PaginaFuera(LookupError):
|
||||
"""Una página mayor que la última, habiendo pacientes (404)."""
|
||||
|
||||
|
||||
def seguimiento_de(
|
||||
sesion: Session,
|
||||
*,
|
||||
sal: str,
|
||||
corte: date | None = None,
|
||||
meses: int | None = None,
|
||||
estatus: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
hoy: date | None = None,
|
||||
tablas: TablasKit = TABLAS,
|
||||
) -> dict:
|
||||
"""La lista de seguimiento al `corte`, lista para `json.dumps` (contrato §2).
|
||||
|
||||
`corte` por omisión es `hoy`; en los dos casos se acota a la última fecha con datos de la plata.
|
||||
`meses` por omisión es `cacu.seguimiento.ventana_meses`.
|
||||
|
||||
Raises:
|
||||
PedidoInvalido: `meses`, `estatus`, `page` o `page_size` fuera de rango.
|
||||
PaginaFuera: `page` mayor que la última página, habiendo pacientes.
|
||||
ReglaDesconocida: una regla de `parametros.toml` con una opción que el código no sabe aplicar.
|
||||
"""
|
||||
lista = {nombre: valor_de(sesion, clave, tablas=tablas) for nombre, clave in PARAMETROS_DE_LA_LISTA.items()}
|
||||
del_estatus = leer_estrato("cacu", ESTRATO).parametros
|
||||
valores_estatus = {nombre: valor_de(sesion, clave, tablas=tablas) for nombre, clave in del_estatus.items()}
|
||||
_validar_reglas(lista)
|
||||
meses = lista["ventana_meses"] if meses is None else meses
|
||||
if meses not in VENTANAS:
|
||||
raise PedidoInvalido(f"meses = {meses!r}: se admite {list(VENTANAS)}.")
|
||||
if estatus is not None and estatus not in ESTATUS:
|
||||
raise PedidoInvalido(f"estatus desconocido {estatus!r}; hay {list(ESTATUS)}.")
|
||||
if page < 1 or not 1 <= page_size <= PAGINA_MAXIMA:
|
||||
raise PedidoInvalido(f"page empieza en 1 y page_size va de 1 a {PAGINA_MAXIMA}.")
|
||||
|
||||
corte = _acotado(sesion, corte or hoy or date.today(), tablas)
|
||||
desde = _meses_antes(corte, meses) + timedelta(days=1)
|
||||
estatus_de = _estatus_al_corte(sesion, corte, valores_estatus)
|
||||
items = _items(sesion, corte, desde, lista, estatus_de, sal, tablas)
|
||||
if estatus is not None:
|
||||
items = [i for i in items if i["estatus"]["codigo"] == estatus]
|
||||
|
||||
total = len(items)
|
||||
paginas = -(-total // page_size)
|
||||
if total and page > paginas:
|
||||
raise PaginaFuera(f"page {page} pasa de la última ({paginas}).")
|
||||
etiquetas = _etiquetas_de_estatus()
|
||||
return {
|
||||
"simulado": True,
|
||||
"corte": corte.isoformat(),
|
||||
"ventana": {"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()},
|
||||
"filtros": {"estatus": estatus},
|
||||
"estatus_disponibles": [{"codigo": c, "etiqueta": e} for c, e in etiquetas.items()],
|
||||
"reglas": _reglas_usadas(sesion, [*PARAMETROS_DE_LA_LISTA.values(), *del_estatus.values()], tablas),
|
||||
"paginacion": {"page": page, "page_size": page_size, "total_items": total, "total_pages": paginas},
|
||||
"items": items[(page - 1) * page_size : page * page_size],
|
||||
}
|
||||
|
||||
|
||||
def seudonimo(pac_id: int, sal: str) -> str:
|
||||
"""El identificador que sale en la lista: estable para una sal, sin decir el `pac_id`."""
|
||||
return "P-" + hashlib.sha256(f"{sal}:{pac_id}".encode()).hexdigest()[:10].upper()
|
||||
|
||||
|
||||
def _validar_reglas(lista: dict) -> None:
|
||||
exigir_opcion("cacu.seguimiento.ventana_meses", lista["ventana_meses"], VENTANAS)
|
||||
exigir_opcion("cacu.seguimiento.fecha_estudio", lista["fecha_estudio"], FECHAS_DE_ESTUDIO)
|
||||
exigir_opciones("cacu.seguimiento.estudios", lista["estudios"], ESTUDIOS)
|
||||
exigir_opcion("cacu.seguimiento.resultado_mostrado", lista["resultado_mostrado"], RESULTADOS_MOSTRADOS)
|
||||
|
||||
|
||||
def _acotado(sesion: Session, corte: date, tablas: TablasKit) -> date:
|
||||
"""El corte, sin pasar de la última fecha con datos de la plata (si hay datos)."""
|
||||
ultima = sesion.execute(select(func.max(tablas.Procedimiento.fecha))).scalar()
|
||||
return corte if ultima is None else min(corte, _fecha(ultima))
|
||||
|
||||
|
||||
def _estatus_al_corte(sesion: Session, corte: date, valores: dict) -> dict[int, str]:
|
||||
cte = estatus_al(P("corte_seguimiento"), reglas_de(valores), incluye_referencia=True)
|
||||
filas = ejecutar(sesion, select(cte.c.pac_id, cte.c.estatus), {**valores, "corte_seguimiento": corte.isoformat()})
|
||||
return {pac_id: estatus for pac_id, estatus in filas}
|
||||
|
||||
|
||||
def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]:
|
||||
"""Una fila por paciente con estudio en la ventana, de la más reciente a la más antigua."""
|
||||
estudios = _estudios(sesion, corte, lista["fecha_estudio"])
|
||||
en_ventana: dict[int, dict[str, list]] = {}
|
||||
for e in estudios:
|
||||
if desde <= e["fecha"] <= corte:
|
||||
de_la_paciente = en_ventana.setdefault(e["pac_id"], {"citologia": [], "vph": []})
|
||||
if "citologia" in lista["estudios"]:
|
||||
de_la_paciente["citologia"].append(e)
|
||||
if "vph" in lista["estudios"] and e["vph"] is not None:
|
||||
de_la_paciente["vph"].append(e)
|
||||
gravedad = {c["clave"]: i for i, c in enumerate(lista["catalogo"])}
|
||||
edades = _grupo_de_edad(sesion, corte, lista["grupos_edad"], tablas)
|
||||
notas_de = _notas_por_paciente(sesion, corte)
|
||||
items = []
|
||||
for pac_id, de_la_paciente in en_ventana.items():
|
||||
if not de_la_paciente["citologia"] and not de_la_paciente["vph"]:
|
||||
continue
|
||||
cito = _mostrada(de_la_paciente["citologia"], lista["resultado_mostrado"], gravedad)
|
||||
vph = max(de_la_paciente["vph"], key=lambda e: e["fecha"], default=None)
|
||||
mas_reciente = max(e["fecha"] for e in [*de_la_paciente["citologia"], *de_la_paciente["vph"]])
|
||||
estatus = estatus_de.get(pac_id, "INFO_INSUFICIENTE")
|
||||
items.append({
|
||||
"id_seudonimo": seudonimo(pac_id, sal),
|
||||
"grupo_edad": edades.get(pac_id, SIN_DATO),
|
||||
"estatus": {"codigo": estatus, "etiqueta": _etiquetas_de_estatus()[estatus]},
|
||||
"ultima_citologia": None if cito is None else {
|
||||
"fecha": cito["fecha"].isoformat(), "bethesda": cito["resultado"], "calidad": cito["calidad"],
|
||||
},
|
||||
"ultimo_vph": None if vph is None else {
|
||||
"fecha": vph["fecha"].isoformat(), "resultado": vph["vph"],
|
||||
"genotipo_16_18": None if vph["genotipo_16_18"] is None else bool(vph["genotipo_16_18"]),
|
||||
},
|
||||
"dias_toma_diagnostico": None if cito is None else _dias_a_la_valoracion(cito, notas_de, lista),
|
||||
"prioridad": None,
|
||||
"_orden": mas_reciente,
|
||||
})
|
||||
items.sort(key=lambda i: i["id_seudonimo"])
|
||||
items.sort(key=lambda i: i.pop("_orden"), reverse=True)
|
||||
return items
|
||||
|
||||
|
||||
def _estudios(sesion: Session, corte: date, fecha_estudio: str) -> list[dict]:
|
||||
"""Cada toma de citología hasta el corte, con lo que ya se sabía al corte (un resultado posterior no existe)."""
|
||||
c = citologias()
|
||||
filas = sesion.execute(select(
|
||||
c.c.pac_id, c.c.fecha_toma, c.c.fecha_reporte, c.c.calidad_muestra, c.c.resultado, c.c.vph, c.c.genotipo_16_18,
|
||||
)).all()
|
||||
estudios = []
|
||||
for pac_id, toma, reporte, calidad, resultado, vph, genotipo in filas:
|
||||
toma, reporte = _fecha(toma), None if reporte is None else _fecha(reporte)
|
||||
conocido = reporte is not None and reporte <= corte
|
||||
fecha = toma if fecha_estudio == "toma" else reporte
|
||||
if fecha is None or toma > corte or (fecha_estudio == "reporte" and not conocido):
|
||||
continue
|
||||
estudios.append({
|
||||
"pac_id": pac_id, "fecha": fecha, "toma": toma, "calidad": calidad,
|
||||
"resultado": resultado if conocido else None,
|
||||
"vph": vph if conocido else None, "genotipo_16_18": genotipo if conocido else None,
|
||||
})
|
||||
return estudios
|
||||
|
||||
|
||||
def _mostrada(citologias_: list[dict], resultado_mostrado: str, gravedad: dict[str, int]) -> dict | None:
|
||||
if not citologias_:
|
||||
return None
|
||||
if resultado_mostrado == "ultimo":
|
||||
return max(citologias_, key=lambda e: e["fecha"])
|
||||
return max(citologias_, key=lambda e: (gravedad.get(e["resultado"], -1), e["fecha"]))
|
||||
|
||||
|
||||
def _grupo_de_edad(sesion: Session, corte: date, cortes, tablas: TablasKit) -> dict[int, str]:
|
||||
"""El grupo de edad de cada paciente con fecha de nacimiento, con la edad cumplida al corte."""
|
||||
grupos = grupos_de_cortes(cortes, tablas=tablas)
|
||||
edades = {}
|
||||
for pac_id, nacimiento in sesion.execute(select(tablas.Persona.pac_id, tablas.Persona.fecha_nacimiento)):
|
||||
if nacimiento is None:
|
||||
continue
|
||||
nacimiento = _fecha(nacimiento)
|
||||
edad = corte.year - nacimiento.year - ((corte.month, corte.day) < (nacimiento.month, nacimiento.day))
|
||||
edades[pac_id] = next((g.etiqueta for g in grupos if g.edad_min <= edad <= g.edad_max), SIN_DATO)
|
||||
return edades
|
||||
|
||||
|
||||
def _notas_por_paciente(sesion: Session, corte: date) -> dict[int, list[tuple[date, str, str]]]:
|
||||
n = notas()
|
||||
de = {}
|
||||
filas = sesion.execute(select(n.c.pac_id, n.c.fecha, n.c.cie_codigo, n.c.especialidad))
|
||||
for pac_id, fecha, cie, especialidad in filas:
|
||||
if fecha is not None and _fecha(fecha) <= corte:
|
||||
de.setdefault(pac_id, []).append((_fecha(fecha), cie, especialidad))
|
||||
return de
|
||||
|
||||
|
||||
def _dias_a_la_valoracion(cito: dict, notas_de: dict, lista: dict) -> int | None:
|
||||
"""Días de la toma a la primera nota que la resuelve, con las reglas de CACU_DIAS_TOMA_DIAGNOSTICO; nulo si aún no.
|
||||
|
||||
También nulo si la paciente ya tenía un diagnóstico de cáncer antes de la toma: esa toma no se mide.
|
||||
"""
|
||||
toma, propias = cito["toma"], notas_de.get(cito["pac_id"], [])
|
||||
if any(f < toma and cie in lista["cie_antecedente"] for f, cie, _ in propias):
|
||||
return None
|
||||
dias = [
|
||||
(f - toma).days for f, cie, especialidad in propias
|
||||
if f > toma and (f - toma).days < lista["horizonte_dias"]
|
||||
and cie in lista["cie_diagnostico"] and especialidad in lista["especialidades_diagnostico"]
|
||||
]
|
||||
return min(dias, default=None)
|
||||
|
||||
|
||||
def _reglas_usadas(sesion: Session, claves: list[str], tablas: TablasKit) -> list[dict]:
|
||||
filas = [sesion.get(tablas.DefParametro, clave) for clave in dict.fromkeys(claves)]
|
||||
return [{"clave": f.clave, "valor": json.loads(f.valor), "estado": f.estado} for f in filas if f is not None]
|
||||
|
||||
|
||||
def _etiquetas_de_estatus() -> dict[str, str]:
|
||||
"""Código -> etiqueta, en orden de presentación: los `valores` del estrato en `estratos.toml`."""
|
||||
return {v["valor"]: v["etiqueta"] for v in leer_estrato("cacu", ESTRATO).valores}
|
||||
|
||||
|
||||
def _meses_antes(fecha: date, meses: int) -> date:
|
||||
"""La misma fecha `meses` meses antes; si ese mes es más corto, su último día."""
|
||||
total = fecha.year * 12 + fecha.month - 1 - meses
|
||||
anio, mes = divmod(total, 12)
|
||||
return date(anio, mes + 1, min(fecha.day, calendar.monthrange(anio, mes + 1)[1]))
|
||||
|
||||
|
||||
def _fecha(valor) -> date:
|
||||
"""Una fecha de la base, venga como `date` o como texto ISO (SQLite)."""
|
||||
return valor if isinstance(valor, date) else date.fromisoformat(str(valor)[:10])
|
||||
@@ -1,110 +0,0 @@
|
||||
"""Bloques de consulta sobre la plata de dos tablas (F5, ADR-MD-007).
|
||||
|
||||
Una consulta de indicador no escribe a mano los `JOIN` entre `procedimiento` y
|
||||
`observacion`: pide un **pivote**, una fila por procedimiento de un estudio y una
|
||||
clase, con una columna por resultado del catálogo. El valor de cada columna sale de
|
||||
la columna de `observacion` que le toca según `tipo_valor`:
|
||||
|
||||
codigo valor_id, o el texto tal como llegó si no está en el catálogo (valor_fuente)
|
||||
booleano valor_numerico, como entero (0 o 1)
|
||||
numero valor_numerico
|
||||
fecha valor_fecha
|
||||
texto valor_texto
|
||||
externo valor_texto
|
||||
|
||||
Las fechas salen sin tipo (`sin_tipo`), como en las vistas por tipo, para que los parámetros
|
||||
de periodo se liguen igual que antes. Con eso, el vocabulario de cada proyecto (`<p>/consultas/plata.py`) se rearma como
|
||||
CTE, sin vistas en la base: las dos tablas ya son el estado actual (sin versiones de
|
||||
fila). Solo se arman expresiones de SQLAlchemy; no se lee ni se escribe nada.
|
||||
"""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from functools import cache
|
||||
|
||||
from sqlalchemy import Integer, Subquery, and_, case, cast, func, select, type_coerce
|
||||
from sqlalchemy.types import NullType
|
||||
|
||||
from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo
|
||||
from webapi.orchestration.tables import PROJECTS, TablasKit, tablas_de
|
||||
|
||||
COLUMNAS_DEL_PROCEDIMIENTO = ("procedimiento_id", "padre_id", "pac_id", "fecha", "fuente_tabla", "fuente_id")
|
||||
|
||||
|
||||
class TipoDeResultadoAmbiguo(ValueError):
|
||||
"""Un mismo `resultado_id` con dos `tipo_valor` distintos en dos catálogos."""
|
||||
|
||||
|
||||
@cache
|
||||
def tipos_de_resultado() -> dict[str, str]:
|
||||
"""`resultado_id` -> `tipo_valor`, de los catálogos de los tres proyectos (deben coincidir donde se repiten)."""
|
||||
tipos: dict[str, str] = {}
|
||||
for proyecto in PROJECTS:
|
||||
for resultado in catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas_de(proyecto)).resultados:
|
||||
previo = tipos.setdefault(resultado.resultado_id, resultado.tipo_valor)
|
||||
if previo != resultado.tipo_valor:
|
||||
raise TipoDeResultadoAmbiguo(f"{resultado.resultado_id}: {previo} y {resultado.tipo_valor}.")
|
||||
return tipos
|
||||
|
||||
|
||||
def sin_tipo(columna):
|
||||
"""Una fecha sin tipo de SQLAlchemy, como las columnas de las vistas por tipo (`consultas.vista.vista`).
|
||||
|
||||
Así un parámetro de la definición (`P("periodo_inicio")`) se liga como lo da el cálculo (texto ISO)
|
||||
y no como `Date`, y las consultas de los indicadores comparan fechas igual que antes (T-18r).
|
||||
"""
|
||||
return type_coerce(columna, NullType()).label(columna.key) if hasattr(columna, "key") else type_coerce(columna, NullType())
|
||||
|
||||
|
||||
def valor(observacion, tipo_valor: str):
|
||||
"""La expresión del valor de una observación según su tipo."""
|
||||
if tipo_valor == "codigo":
|
||||
return func.coalesce(observacion.c.valor_id, observacion.c.valor_fuente)
|
||||
if tipo_valor == "booleano":
|
||||
return cast(observacion.c.valor_numerico, Integer)
|
||||
if tipo_valor == "numero":
|
||||
return observacion.c.valor_numerico
|
||||
if tipo_valor == "fecha":
|
||||
return sin_tipo(observacion.c.valor_fecha)
|
||||
return observacion.c.valor_texto
|
||||
|
||||
|
||||
def pivote(
|
||||
tablas: TablasKit, estudio_id: str, clase: str, resultados: Mapping[str, str | tuple[str, str]] | None = None, *,
|
||||
nombre: str | None = None, columnas: tuple[str, ...] = (),
|
||||
) -> Subquery:
|
||||
"""Una fila por procedimiento del estudio y la clase, con una columna por resultado.
|
||||
|
||||
`resultados`: nombre de la columna -> `resultado_id` (`{"resultado": "citologia.bethesda"}`), o
|
||||
-> `(resultado_id, columna)` para leer una columna de `observacion` en particular
|
||||
(`("nota_medica.especialidad", "valor_id")`: el código, nulo si no se reconoció).
|
||||
Las columnas del procedimiento van siempre: `procedimiento_id`, `padre_id`, `pac_id`,
|
||||
`fecha`, `fuente_tabla` y `fuente_id`, más las de `columnas` (`("orden_numero",)`). Un resultado
|
||||
sin observación da nulo.
|
||||
"""
|
||||
resultados = dict(resultados or {})
|
||||
p = tablas.Procedimiento.__table__
|
||||
o = tablas.Observacion.__table__.alias(f"o_{estudio_id}_{clase}")
|
||||
tipos = tipos_de_resultado()
|
||||
columnas = [sin_tipo(p.c[c]) if c == "fecha" else p.c[c] for c in (*COLUMNAS_DEL_PROCEDIMIENTO, *columnas)]
|
||||
if not resultados:
|
||||
consulta = select(*columnas).where(p.c.estudio_id == estudio_id, p.c.clase == clase)
|
||||
return consulta.subquery(nombre or f"{estudio_id}_{clase}")
|
||||
pares = {columna: r if isinstance(r, tuple) else (r, None) for columna, r in resultados.items()}
|
||||
pivoteadas = [
|
||||
func.max(case((o.c.resultado_id == resultado_id,
|
||||
o.c[especifica] if especifica else valor(o, tipos[resultado_id])))).label(columna)
|
||||
for columna, (resultado_id, especifica) in pares.items()
|
||||
]
|
||||
consulta = (
|
||||
select(*columnas, *pivoteadas)
|
||||
.select_from(p.outerjoin(o, and_(o.c.procedimiento_id == p.c.procedimiento_id,
|
||||
o.c.resultado_id.in_([r for r, _ in pares.values()]))))
|
||||
.where(p.c.estudio_id == estudio_id, p.c.clase == clase)
|
||||
.group_by(*(p.c[c.key] if c.key == "fecha" else c for c in columnas))
|
||||
)
|
||||
return consulta.subquery(nombre or f"{estudio_id}_{clase}")
|
||||
|
||||
|
||||
def hijos_de(padre: Subquery, hijo: Subquery):
|
||||
"""La condición de unión de un procedimiento con sus hijos (el reporte con su toma)."""
|
||||
return hijo.c.padre_id == padre.c.procedimiento_id
|
||||
@@ -1,68 +0,0 @@
|
||||
"""La lista de seguimiento de CaCu (T-24d): `GET /cacu/seguimiento`, solo en DEV.
|
||||
|
||||
GET /cacu/seguimiento?corte=AAAA-MM-DD&meses=&estatus=&page=&page_size=
|
||||
|
||||
Es dato por paciente: **solo se registra en DEV** (con `DEV_REVISION`, que define el despliegue de
|
||||
`deploy/dev`) y con datos simulados; toda respuesta lleva `simulado: true`. Fuera de DEV la ruta no
|
||||
existe (404). La lista la arma el kit (`webapi.follow_up.listing`); aquí solo se valida,
|
||||
se abre la sesión y se traducen los errores.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from datetime import date
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from webapi.follow_up.listing import PaginaFuera, PedidoInvalido, seguimiento_de
|
||||
from sqlmodel import Session
|
||||
|
||||
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
|
||||
DEFAULT_SALT = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno
|
||||
|
||||
|
||||
def in_dev() -> bool:
|
||||
"""Si esta WebApi corre en el despliegue de DEV (`deploy/dev/compose.yml` define `DEV_REVISION`)."""
|
||||
return bool(os.environ.get("DEV_REVISION"))
|
||||
|
||||
|
||||
def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
|
||||
"""El blueprint de la lista, para registrarlo con `url_prefix="/cacu"` solo en DEV."""
|
||||
blueprint = Blueprint("cacu_seguimiento", __name__)
|
||||
|
||||
@blueprint.get("/seguimiento")
|
||||
def get_seguimiento():
|
||||
try:
|
||||
pedido = _requested(request.args)
|
||||
except ValueError as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
sesion = get_session()
|
||||
try:
|
||||
cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT), **pedido)
|
||||
except PedidoInvalido as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
except PaginaFuera as error:
|
||||
return jsonify({"error": str(error)}), 404
|
||||
finally:
|
||||
sesion.close()
|
||||
return Response(json.dumps(cuerpo, ensure_ascii=False), mimetype="application/json")
|
||||
|
||||
return blueprint
|
||||
|
||||
|
||||
def _requested(args) -> dict:
|
||||
"""Los parámetros de la consulta, con su tipo. `ValueError` si uno viene mal escrito."""
|
||||
pedido = {}
|
||||
if corte := args.get("corte"):
|
||||
if not FECHA.fullmatch(corte):
|
||||
raise ValueError(f"corte mal escrito {corte!r}; use AAAA-MM-DD")
|
||||
pedido["corte"] = date.fromisoformat(corte)
|
||||
for nombre in ("meses", "page", "page_size"):
|
||||
if (texto := args.get(nombre)) not in (None, ""):
|
||||
if not texto.isdigit():
|
||||
raise ValueError(f"{nombre} debe ser un entero; llegó {texto!r}")
|
||||
pedido[nombre] = int(texto)
|
||||
if estatus := args.get("estatus"):
|
||||
pedido["estatus"] = estatus
|
||||
return pedido
|
||||
@@ -1,99 +0,0 @@
|
||||
"""El vocabulario de CaCu sobre la plata de dos tablas (F5, ADR-MD-007): citologías, biopsias, notas y órdenes.
|
||||
|
||||
Lo que leen las familias reescritas, armado con `plata.consultas.pivote` como subconsultas
|
||||
(sin vistas en la base). Los nombres de columna son los del concepto, no los de una tabla
|
||||
por tipo: `fecha_toma`, `resultado`, `grado`. Cada uno lleva `procedimiento_id` y
|
||||
`pac_id`; los que cuelgan de una toma llevan también la de su toma.
|
||||
"""
|
||||
|
||||
from sqlalchemy import Subquery, select
|
||||
|
||||
from webapi.orchestration.tables.cacu import TABLAS
|
||||
from webapi.follow_up.pivot import hijos_de, pivote
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
|
||||
def citologias(tablas: TablasKit = TABLAS) -> Subquery:
|
||||
"""Una fila por citología tomada, con su calidad, su resultado (Bethesda) y su VPH si ya los tiene.
|
||||
|
||||
Lo mismo que la vista por tipo `v_citologia_con_resultado`, desde las dos tablas.
|
||||
"""
|
||||
toma = pivote(tablas, "citologia", "toma", {"calidad_muestra": "citologia.calidad_muestra"},
|
||||
columnas=("orden_numero",), nombre="toma_citologia")
|
||||
reporte = pivote(tablas, "citologia", "reporte", {"resultado": "citologia.bethesda"}, nombre="reporte_citologia")
|
||||
vph = pivote(tablas, "vph", "reporte", {
|
||||
"vph": "vph.resultado", "genotipo_16_18": "vph.genotipo_16_18",
|
||||
"genotipo_16": "vph.genotipo_16", "genotipo_18": "vph.genotipo_18",
|
||||
}, nombre="reporte_vph")
|
||||
return select(
|
||||
toma.c.procedimiento_id, toma.c.fuente_tabla, toma.c.fuente_id, toma.c.pac_id,
|
||||
toma.c.fecha.label("fecha_toma"), toma.c.calidad_muestra, toma.c.orden_numero,
|
||||
reporte.c.fecha.label("fecha_reporte"), reporte.c.resultado,
|
||||
vph.c.vph, vph.c.genotipo_16_18, vph.c.genotipo_16, vph.c.genotipo_18,
|
||||
).select_from(
|
||||
toma.outerjoin(reporte, hijos_de(toma, reporte)).outerjoin(vph, hijos_de(toma, vph))
|
||||
).subquery("citologias")
|
||||
|
||||
|
||||
def biopsias(tablas: TablasKit = TABLAS) -> Subquery:
|
||||
"""Una fila por biopsia reportada, con su grado, su solicitud y la citología que la originó (si se encontró).
|
||||
|
||||
Desde T-22h la biopsia es una orden (`biopsia`, `orden`: la solicitud, con su fecha y su número de orden)
|
||||
y su reporte, una hija de ella: la toma queda dos niveles arriba (toma, orden, reporte).
|
||||
"""
|
||||
reporte = pivote(tablas, "biopsia", "reporte", {"grado": "biopsia.grado"}, nombre="reporte_biopsia")
|
||||
orden = pivote(tablas, "biopsia", "orden", columnas=("orden_numero",), nombre="orden_biopsia")
|
||||
toma = pivote(tablas, "citologia", "toma", nombre="toma_de_la_biopsia")
|
||||
return select(
|
||||
reporte.c.procedimiento_id, reporte.c.fuente_tabla, reporte.c.fuente_id, reporte.c.pac_id,
|
||||
reporte.c.fecha.label("fecha_reporte"), reporte.c.grado, orden.c.fecha.label("fecha_solicitud"), orden.c.orden_numero,
|
||||
toma.c.procedimiento_id.label("toma_id"), toma.c.pac_id.label("toma_pac_id"), toma.c.fecha.label("fecha_toma"),
|
||||
).select_from(
|
||||
reporte.outerjoin(orden, hijos_de(orden, reporte)).outerjoin(toma, hijos_de(toma, orden))
|
||||
).subquery("biopsias")
|
||||
|
||||
|
||||
def notas(tablas: TablasKit = TABLAS) -> Subquery:
|
||||
"""Una fila por nota médica: su fecha, su CIE-10 y la especialidad que la escribió (código; nulo si no se reconoció)."""
|
||||
nota = pivote(tablas, "nota_medica", "encuentro", {
|
||||
"cie_codigo": "nota_medica.diagnostico",
|
||||
"especialidad": ("nota_medica.especialidad", "valor_id"),
|
||||
"especialidad_fuente": ("nota_medica.especialidad", "valor_fuente"),
|
||||
}, nombre="nota_medica")
|
||||
return select(
|
||||
nota.c.procedimiento_id, nota.c.fuente_tabla, nota.c.fuente_id, nota.c.pac_id, nota.c.fecha,
|
||||
nota.c.cie_codigo, nota.c.especialidad, nota.c.especialidad_fuente,
|
||||
).subquery("notas")
|
||||
|
||||
|
||||
def notas_con_textos(tablas: TablasKit = TABLAS) -> Subquery:
|
||||
"""Las notas con su motivo de consulta y su diagnóstico en texto (tal como llegan) y su identificador del hospital.
|
||||
|
||||
Aparte de `notas` para no mover la huella de las definiciones que ya la leen (T-24b, T-24c).
|
||||
"""
|
||||
nota = pivote(tablas, "nota_medica", "encuentro", {
|
||||
"cie_codigo": "nota_medica.diagnostico",
|
||||
"especialidad": ("nota_medica.especialidad", "valor_id"),
|
||||
"motivo": "nota_medica.motivo",
|
||||
"diagnostico_texto": "nota_medica.diagnostico_texto",
|
||||
}, columnas=("id_hospital",), nombre="nota_con_textos")
|
||||
return select(
|
||||
nota.c.procedimiento_id, nota.c.pac_id, nota.c.fecha, nota.c.cie_codigo, nota.c.especialidad,
|
||||
nota.c.motivo, nota.c.diagnostico_texto, nota.c.id_hospital,
|
||||
).subquery("notas_con_textos")
|
||||
|
||||
|
||||
def ordenes_de_biopsia(tablas: TablasKit = TABLAS) -> Subquery:
|
||||
"""Una fila por biopsia solicitada (la orden, con o sin reporte; T-22h): de quién y la fecha de la solicitud."""
|
||||
orden = pivote(tablas, "biopsia", "orden", nombre="orden_de_biopsia")
|
||||
return select(orden.c.procedimiento_id, orden.c.pac_id, orden.c.fecha).subquery("ordenes_de_biopsia")
|
||||
|
||||
|
||||
def tomas_con_especialidad(tablas: TablasKit = TABLAS) -> Subquery:
|
||||
"""Una fila por citología tomada, con la especialidad de la orden de la que cuelga (nula si no tiene o no se reconoce)."""
|
||||
toma = pivote(tablas, "citologia", "toma", nombre="toma_con_especialidad")
|
||||
orden = pivote(tablas, "citologia", "orden", {"especialidad": ("orden.especialidad", "valor_id")},
|
||||
nombre="orden_de_la_toma")
|
||||
return select(toma.c.procedimiento_id, toma.c.pac_id, toma.c.fecha, orden.c.especialidad).select_from(
|
||||
toma.outerjoin(orden, hijos_de(orden, toma))
|
||||
).subquery("tomas_con_especialidad")
|
||||
@@ -1,281 +0,0 @@
|
||||
"""El estatus de seguimiento ASCCP de cada paciente a una fecha (T-24c; plan de seguimiento, §5.2).
|
||||
|
||||
`estatus_al(referencia, reglas)` es la única regla: una CTE `(pac_id, estatus)` con un renglón
|
||||
por persona. La usan el estrato `estatus_seguimiento` (`estrato`, a la referencia de cada
|
||||
reporte), la lista de seguimiento (T-24d, al corte que pida el dashboard) y las cohortes (a su
|
||||
fecha índice). Mira solo lo ocurrido antes de la referencia, así que el estatus de un periodo
|
||||
pasado no cambia cuando la paciente avanza.
|
||||
|
||||
POST_TRATAMIENTO una nota con un CIE-10 de tratamiento, posterior a su primera colposcopia
|
||||
POST_COLPOSCOPIA alguna evidencia de colposcopia (`EVIDENCIAS`); una nota de colposcopia cuenta si
|
||||
es de «Clínica de la Mujer y Colposcopia» y, por regla, posterior a una cita de
|
||||
valoración (la nota que resuelve una toma, como en CACU_DIAS_TOMA_DIAGNOSTICO); una
|
||||
orden o una biopsia, por regla, si es del mismo día que una nota de colposcopia (la
|
||||
colposcopia es la madre de la biopsia)
|
||||
INFO_INSUFICIENTE la historia no alcanza (`cacu.seguimiento.insuficiente.regla`); también el resto
|
||||
PRE_COLPOSCOPIA ninguna de las anteriores y, si se conoce la especialidad de sus citologías,
|
||||
alguna es de vigilancia
|
||||
|
||||
Ninguna regla está escrita aquí: todas son de `parametros.toml` (`cacu.seguimiento.*`, §2bis); qué
|
||||
parámetro de la consulta es qué clave lo declara `estratos.toml` (`[cacu.estatus_seguimiento.parametros]`),
|
||||
y llegan como `reglas`. Las listas (CIE-10, especialidades, evidencias) van ligadas como
|
||||
parámetros (S-K76); los textos del motivo y del diagnóstico se comparan por contención, en
|
||||
mayúsculas y sin acentos; la precedencia, la referencia y la regla de insuficiente arman la
|
||||
consulta. Una opción que el código no sabe aplicar falla con `ReglaDesconocida`.
|
||||
"""
|
||||
|
||||
import unicodedata
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy import (
|
||||
CTE, ColumnElement, and_, bindparam, case, exists, func, literal, literal_column, or_, select, union_all,
|
||||
)
|
||||
|
||||
from webapi.follow_up.silver import biopsias, notas_con_textos, ordenes_de_biopsia, tomas_con_especialidad
|
||||
from webapi.orchestration.tables.cacu import TABLAS
|
||||
from webapi.follow_up.functions import dias_entre
|
||||
from webapi.follow_up.view import P, vista
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
ESTATUS = ("POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA")
|
||||
RESTO = "INFO_INSUFICIENTE" # quien no cumple ninguno: el estrato es exhaustivo (§5.3)
|
||||
MARCOS = ("estatus", "ronda")
|
||||
REFERENCIAS = {"inicio_periodo": "periodo_inicio", "fecha_corte": "fecha_corte"} # opción -> parámetro del reporte
|
||||
EVIDENCIAS = ("motivo", "cie", "diagnostico_texto", "orden_biopsia", "biopsia")
|
||||
FUENTES_DE_TRATAMIENTO = ("nota_posterior_a_colposcopia",)
|
||||
REGLAS_DE_INSUFICIENTE = ("inicio_datos_posterior_a_alta", "sin_alta_registrada", "ambos", "nunca")
|
||||
REQUISITOS_DE_COLPOSCOPIA = ("valoracion_previa", "ninguno")
|
||||
REQUISITOS_DE_BIOPSIA = ("mismo_dia_que_colposcopia", "ninguno")
|
||||
|
||||
V_PERSONA = vista("v_persona", "pac_id")
|
||||
SIN_ACENTO = {"Á": "A", "É": "E", "Í": "I", "Ó": "O", "Ú": "U", "Ü": "U", "á": "a", "é": "e", "í": "i", "ó": "o",
|
||||
"ú": "u", "ü": "u"} # fmt: skip
|
||||
|
||||
|
||||
class ReglaDesconocida(ValueError):
|
||||
"""Una regla de `cacu.seguimiento.*` con una opción que el código no sabe aplicar."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Reglas:
|
||||
"""Las reglas que dan forma a la consulta, ya validadas. Las listas no van aquí: se ligan al ejecutar."""
|
||||
|
||||
referencia: str # el parámetro del reporte: `periodo_inicio` o `fecha_corte`
|
||||
precedencia: tuple[str, ...]
|
||||
motivos: tuple[str, ...] # normalizados
|
||||
diagnosticos: tuple[str, ...] # normalizados
|
||||
insuficiente: str
|
||||
valoracion_previa: bool # una nota de colposcopia cuenta solo después de una cita de valoración
|
||||
biopsia_mismo_dia: bool # la orden y la biopsia cuentan solo el día de una nota de colposcopia
|
||||
|
||||
|
||||
def reglas_de(valores: Mapping) -> Reglas:
|
||||
"""Valida las reglas (`{parámetro de la consulta: valor}`, los de `estratos.toml`) contra las opciones admitidas."""
|
||||
exigir_opciones("cacu.seguimiento.marco", valores["seguimiento_marco"], MARCOS)
|
||||
if "estatus" not in valores["seguimiento_marco"]:
|
||||
raise ReglaDesconocida("cacu.seguimiento.marco no incluye «estatus»: el estrato no se publica.")
|
||||
if "ronda" in valores["seguimiento_marco"]:
|
||||
raise ReglaDesconocida("cacu.seguimiento.marco: «ronda» (UE) todavía no se sabe aplicar.")
|
||||
exigir_opcion("cacu.seguimiento.referencia", valores["seguimiento_referencia"], tuple(REFERENCIAS))
|
||||
precedencia = tuple(valores["seguimiento_precedencia"])
|
||||
if sorted(precedencia) != sorted(ESTATUS):
|
||||
raise ReglaDesconocida(
|
||||
f"cacu.seguimiento.precedencia debe ordenar los cuatro estatus, sin repetir: {ESTATUS}; "
|
||||
f"llegó {precedencia}."
|
||||
)
|
||||
exigir_opciones("cacu.seguimiento.colposcopia.evidencias", valores["seguimiento_evidencias"], EVIDENCIAS)
|
||||
exigir_opciones(
|
||||
"cacu.seguimiento.tratamiento.fuentes", valores["seguimiento_fuentes_tratamiento"], FUENTES_DE_TRATAMIENTO
|
||||
)
|
||||
exigir_opcion("cacu.seguimiento.insuficiente.regla", valores["seguimiento_insuficiente"], REGLAS_DE_INSUFICIENTE)
|
||||
exigir_opcion("cacu.seguimiento.colposcopia.requisito", valores["seguimiento_requisito"], REQUISITOS_DE_COLPOSCOPIA)
|
||||
exigir_opcion(
|
||||
"cacu.seguimiento.colposcopia.biopsia_requisito",
|
||||
valores["seguimiento_biopsia_requisito"],
|
||||
REQUISITOS_DE_BIOPSIA,
|
||||
)
|
||||
return Reglas(
|
||||
referencia=REFERENCIAS[valores["seguimiento_referencia"]],
|
||||
precedencia=precedencia,
|
||||
motivos=tuple(normalizado(m) for m in valores["seguimiento_motivos"]),
|
||||
diagnosticos=tuple(normalizado(d) for d in valores["seguimiento_diagnosticos"]),
|
||||
insuficiente=valores["seguimiento_insuficiente"],
|
||||
valoracion_previa=valores["seguimiento_requisito"] == "valoracion_previa",
|
||||
biopsia_mismo_dia=valores["seguimiento_biopsia_requisito"] == "mismo_dia_que_colposcopia",
|
||||
)
|
||||
|
||||
|
||||
def estrato(valores: Mapping) -> CTE:
|
||||
"""El estrato `estatus_seguimiento` (`estratos.toml`): `(unidad_id, estrato)`, a la referencia del reporte."""
|
||||
reglas = reglas_de(valores)
|
||||
estatus = estatus_al(P(reglas.referencia), reglas, incluye_referencia=reglas.referencia == "fecha_corte")
|
||||
return select(estatus.c.pac_id.label("unidad_id"), estatus.c.estatus.label("estrato")).cte(
|
||||
"estrato_estatus_seguimiento"
|
||||
)
|
||||
|
||||
|
||||
def estatus_al(
|
||||
referencia: ColumnElement, reglas: Reglas, *, incluye_referencia: bool = False, tablas: TablasKit = TABLAS
|
||||
) -> CTE:
|
||||
"""La CTE `(pac_id, estatus)`: un renglón por persona, con lo ocurrido antes de `referencia`.
|
||||
|
||||
`referencia` es una fecha de SQL (un parámetro: `P("periodo_inicio")`, `P("corte")`). Con
|
||||
`incluye_referencia`, cuenta también lo de ese día (un corte); sin él, solo lo anterior (el inicio
|
||||
de un periodo). Los parámetros `seguimiento_*` de las listas se ligan al ejecutar.
|
||||
"""
|
||||
|
||||
def antes(fecha) -> ColumnElement:
|
||||
return fecha <= referencia if incluye_referencia else fecha < referencia
|
||||
|
||||
nota, orden, reporte, toma = (
|
||||
notas_con_textos(tablas), ordenes_de_biopsia(tablas), biopsias(tablas), tomas_con_especialidad(tablas)
|
||||
)
|
||||
# La cita de valoración: la nota que resuelve una toma, con las reglas de CACU_DIAS_TOMA_DIAGNOSTICO.
|
||||
valoracion = (
|
||||
select(nota.c.pac_id, func.min(nota.c.fecha).label("primera"))
|
||||
.select_from(nota.join(toma, toma.c.pac_id == nota.c.pac_id))
|
||||
.where(
|
||||
antes(nota.c.fecha),
|
||||
nota.c.fecha > toma.c.fecha,
|
||||
dias_entre(toma.c.fecha, nota.c.fecha) < P("seguimiento_horizonte_valoracion"),
|
||||
nota.c.cie_codigo.in_(P("seguimiento_cie_valoracion", lista=True)),
|
||||
nota.c.especialidad.in_(P("seguimiento_especialidades_valoracion", lista=True)),
|
||||
)
|
||||
.group_by(nota.c.pac_id)
|
||||
.cte("seguimiento_valoracion")
|
||||
)
|
||||
# Una nota de colposcopia: de su especialidad y, por regla, posterior a la primera valoración.
|
||||
de_colposcopia = and_(
|
||||
antes(nota.c.fecha),
|
||||
nota.c.especialidad.in_(P("seguimiento_especialidades_colposcopia", lista=True)),
|
||||
nota.c.fecha > valoracion.c.primera if reglas.valoracion_previa else _siempre(),
|
||||
)
|
||||
con_valoracion = nota.outerjoin(valoracion, valoracion.c.pac_id == nota.c.pac_id)
|
||||
# Los días con una nota de colposcopia válida: la orden de biopsia se expide ese día (su madre).
|
||||
visitas = select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where(de_colposcopia).cte(
|
||||
"seguimiento_visitas_de_colposcopia"
|
||||
)
|
||||
|
||||
def de_una_visita(pac_id, fecha) -> ColumnElement:
|
||||
if not reglas.biopsia_mismo_dia:
|
||||
return _siempre()
|
||||
return exists().where(visitas.c.pac_id == pac_id, visitas.c.fecha == fecha)
|
||||
|
||||
evidencias = union_all(
|
||||
select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where(
|
||||
_habilitada("motivo"), de_colposcopia, _contiene(nota.c.motivo, reglas.motivos, "motivo")
|
||||
),
|
||||
select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where(
|
||||
_habilitada("cie"), de_colposcopia, nota.c.cie_codigo.in_(P("seguimiento_cie_colposcopia", lista=True)),
|
||||
),
|
||||
select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where(
|
||||
_habilitada("diagnostico_texto"), de_colposcopia,
|
||||
_contiene(nota.c.diagnostico_texto, reglas.diagnosticos, "diagnostico"),
|
||||
),
|
||||
select(orden.c.pac_id, orden.c.fecha).where(
|
||||
_habilitada("orden_biopsia"), antes(orden.c.fecha), de_una_visita(orden.c.pac_id, orden.c.fecha)
|
||||
),
|
||||
select(reporte.c.pac_id, reporte.c.fecha_reporte.label("fecha")).where(
|
||||
_habilitada("biopsia"), antes(reporte.c.fecha_reporte),
|
||||
de_una_visita(reporte.c.pac_id, reporte.c.fecha_solicitud),
|
||||
),
|
||||
).subquery("evidencias_de_colposcopia")
|
||||
colposcopia = (
|
||||
select(evidencias.c.pac_id, func.min(evidencias.c.fecha).label("primera"))
|
||||
.group_by(evidencias.c.pac_id)
|
||||
.cte("seguimiento_colposcopia")
|
||||
)
|
||||
tratamiento = (
|
||||
select(nota.c.pac_id)
|
||||
.distinct()
|
||||
.select_from(nota.join(colposcopia, colposcopia.c.pac_id == nota.c.pac_id))
|
||||
.where(
|
||||
antes(nota.c.fecha),
|
||||
nota.c.fecha > colposcopia.c.primera,
|
||||
nota.c.cie_codigo.in_(P("seguimiento_cie_tratamiento", lista=True)),
|
||||
)
|
||||
.cte("seguimiento_tratamiento")
|
||||
)
|
||||
# Fuera de vigilancia: todas sus citologías tienen especialidad conocida y ninguna es de vigilancia.
|
||||
de_vigilancia = or_(
|
||||
toma.c.especialidad.is_(None), toma.c.especialidad.in_(P("seguimiento_especialidades_vigilancia", lista=True))
|
||||
)
|
||||
fuera_de_vigilancia = (
|
||||
select(toma.c.pac_id)
|
||||
.where(antes(toma.c.fecha))
|
||||
.group_by(toma.c.pac_id)
|
||||
.having(func.sum(case((de_vigilancia, 1), else_=0)) == 0)
|
||||
.cte("seguimiento_fuera_de_vigilancia")
|
||||
)
|
||||
persona = V_PERSONA
|
||||
cumple = {
|
||||
"POST_TRATAMIENTO": tratamiento.c.pac_id.is_not(None),
|
||||
"POST_COLPOSCOPIA": colposcopia.c.pac_id.is_not(None),
|
||||
"INFO_INSUFICIENTE": _insuficiente(reglas.insuficiente),
|
||||
"PRE_COLPOSCOPIA": fuera_de_vigilancia.c.pac_id.is_(None),
|
||||
}
|
||||
estatus = case(*((cumple[e], literal(e)) for e in reglas.precedencia), else_=literal(RESTO))
|
||||
return (
|
||||
select(persona.c.pac_id, estatus.label("estatus"))
|
||||
.select_from(
|
||||
persona.outerjoin(tratamiento, tratamiento.c.pac_id == persona.c.pac_id)
|
||||
.outerjoin(colposcopia, colposcopia.c.pac_id == persona.c.pac_id)
|
||||
.outerjoin(fuera_de_vigilancia, fuera_de_vigilancia.c.pac_id == persona.c.pac_id)
|
||||
)
|
||||
.cte("seguimiento_estatus")
|
||||
)
|
||||
|
||||
|
||||
def normalizado(texto: str) -> str:
|
||||
"""Un texto para comparar: sin espacios al borde, sin acentos y en mayúsculas (la Ñ se queda)."""
|
||||
return "".join(SIN_ACENTO.get(c, c) for c in unicodedata.normalize("NFC", texto.strip())).upper()
|
||||
|
||||
|
||||
def _normalizado_sql(columna: ColumnElement) -> ColumnElement:
|
||||
"""`normalizado` en SQL: sin acentos (antes de `upper`, que en SQLite solo sabe ASCII) y en mayúsculas."""
|
||||
for con, sin in SIN_ACENTO.items():
|
||||
columna = func.replace(columna, con, sin)
|
||||
return func.upper(columna)
|
||||
|
||||
|
||||
def _contiene(columna: ColumnElement, textos: tuple[str, ...], nombre: str) -> ColumnElement:
|
||||
"""La columna, normalizada, contiene alguno de los textos (ya normalizados). Sin textos, nunca."""
|
||||
if not textos:
|
||||
return _nunca()
|
||||
normal = _normalizado_sql(columna)
|
||||
return or_(*(normal.contains(bindparam(f"seguimiento_{nombre}_{i}", t)) for i, t in enumerate(textos)))
|
||||
|
||||
|
||||
def _habilitada(evidencia: str) -> ColumnElement:
|
||||
"""La evidencia está en `cacu.seguimiento.colposcopia.evidencias` (ligada al ejecutar)."""
|
||||
return literal(evidencia).in_(P("seguimiento_evidencias", lista=True))
|
||||
|
||||
|
||||
def _insuficiente(regla: str) -> ColumnElement:
|
||||
"""La regla de historia insuficiente. Hoy no hay fecha de alta (usuario, 2026-10-22): se asume posterior al
|
||||
inicio de los datos, así que `inicio_datos_posterior_a_alta` no marca a nadie y `sin_alta_registrada`, a todas."""
|
||||
return _siempre() if regla in ("sin_alta_registrada", "ambos") else _nunca()
|
||||
|
||||
|
||||
def _siempre() -> ColumnElement:
|
||||
"""Una condición verdadera. No `true()`: SQL Server la escribe como `1`, que no es condición."""
|
||||
return literal_column("1") == literal_column("1")
|
||||
|
||||
|
||||
def _nunca() -> ColumnElement:
|
||||
"""Una condición falsa (ver `_siempre`)."""
|
||||
return literal_column("1") == literal_column("0")
|
||||
|
||||
|
||||
def exigir_opcion(clave: str, valor, admitidas: tuple) -> None:
|
||||
"""La regla `clave` vale una de las opciones que el código sabe aplicar; si no, `ReglaDesconocida`."""
|
||||
if valor not in admitidas:
|
||||
raise ReglaDesconocida(f"{clave} = {valor!r}: el código sabe aplicar {list(admitidas)}.")
|
||||
|
||||
|
||||
def exigir_opciones(clave: str, valores, admitidas: tuple) -> None:
|
||||
"""Cada valor de la regla `clave` es una opción que el código sabe aplicar; si no, `ReglaDesconocida`."""
|
||||
desconocidas = [v for v in valores if v not in admitidas]
|
||||
if desconocidas:
|
||||
raise ReglaDesconocida(f"{clave}: {desconocidas} no se saben aplicar; el código sabe {list(admitidas)}.")
|
||||
@@ -1,26 +0,0 @@
|
||||
"""De dónde lee una definición: una vista o una tabla por su nombre, y sus parámetros.
|
||||
|
||||
Una definición de indicador lee la plata genérica por su vocabulario
|
||||
(`<proyecto>/consultas/plata.py`) y las tablas de apoyo (`dim_fecha`,
|
||||
`dim_grupo_edad`, `v_persona`) por `vista`. Desde F6 (ADR-MD-009) no hay
|
||||
tablas de hechos por tipo ni sus vistas `v_<tabla>_actual`.
|
||||
|
||||
Las consultas son objetos de SQLAlchemy: el SQL lo escribe SQLAlchemy
|
||||
para el motor de la sesión.
|
||||
"""
|
||||
|
||||
from sqlalchemy import BindParameter, FromClause, bindparam, column, table
|
||||
|
||||
|
||||
def vista(nombre: str, *columnas: str) -> FromClause:
|
||||
"""Una vista o una tabla por su nombre y sus columnas, para las que no salen de un modelo."""
|
||||
return table(nombre, *(column(nombre_columna) for nombre_columna in columnas))
|
||||
|
||||
|
||||
def P(nombre: str, *, lista: bool = False) -> BindParameter:
|
||||
"""Un parámetro de una definición. `lista`: su valor es una lista y va en un `IN`.
|
||||
|
||||
El valor no entra al SQL: se liga al ejecutar, así que la definición
|
||||
no cambia cuando cambia una regla del TOML (S-K76).
|
||||
"""
|
||||
return bindparam(nombre, expanding=lista)
|
||||
@@ -1,332 +0,0 @@
|
||||
"""Aggregate log of every import attempt (validations and commits).
|
||||
|
||||
Each attempt becomes one JSON line in `import_log.jsonl` under
|
||||
`WEBAPI_REPORT_DIR`. A record only carries counts, field names, source
|
||||
column names and value *shapes* ("9999-99-99" for a date in an unexpected
|
||||
format): never a row, a file name, a connection string or an identifier.
|
||||
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())
|
||||
},
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
"""Import sources. Each module registers its connector class on import;
|
||||
the order here is the order the catalog lists them in."""
|
||||
from webapi.imports.connectors import csv_, excel, json_, pdf, document, edf, sql # noqa: F401 (catalog order)
|
||||
from webapi.imports.connectors.base import Connector, PreviewResult, SourceColumn, SourceTable
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import (
|
||||
CONNECTORS,
|
||||
build_connector,
|
||||
catalog,
|
||||
connector_class,
|
||||
kind_for_filename,
|
||||
register_connector,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"CONNECTORS",
|
||||
"Connector",
|
||||
"ConnectorError",
|
||||
"PreviewResult",
|
||||
"SourceColumn",
|
||||
"SourceTable",
|
||||
"build_connector",
|
||||
"catalog",
|
||||
"connector_class",
|
||||
"kind_for_filename",
|
||||
"register_connector",
|
||||
]
|
||||
@@ -1,90 +0,0 @@
|
||||
import base64
|
||||
import binascii
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, ClassVar, Iterator
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SourceColumn:
|
||||
name: str
|
||||
inferred_type: str # "string" | "integer" | "float" | "boolean" | "date" | "datetime" | "binary" | "unknown"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PreviewResult:
|
||||
columns: list[SourceColumn]
|
||||
sample_rows: list[dict[str, Any]]
|
||||
total_rows: int | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SourceTable:
|
||||
"""One table a source offers: an Excel sheet, a section of an EDF
|
||||
file. `options` is what to send back to read that table."""
|
||||
|
||||
name: str
|
||||
options: dict[str, Any] = field(default_factory=dict)
|
||||
kind: str = "table"
|
||||
|
||||
|
||||
class Connector(ABC):
|
||||
"""A data source that can be read as columns and rows.
|
||||
|
||||
Adding a source means subclassing this (or `FileConnector` for an
|
||||
uploaded file), setting the class attributes below, implementing
|
||||
`from_payload`, and decorating the class with `@register_connector`.
|
||||
The import pipeline, the `/imports/connectors` catalog and the web
|
||||
client pick it up from there.
|
||||
"""
|
||||
|
||||
kind: ClassVar[str]
|
||||
label: ClassVar[str]
|
||||
description: ClassVar[str] = ""
|
||||
category: ClassVar[str] # "file" | "database" | "document" | "signal"
|
||||
icon: ClassVar[str] = "table_view"
|
||||
extensions: ClassVar[tuple[str, ...]] = ()
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "Connector":
|
||||
"""Builds a ready-to-read connector from the JSON a client sends
|
||||
in an import request's `payload`."""
|
||||
|
||||
@abstractmethod
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult: ...
|
||||
|
||||
@abstractmethod
|
||||
def read_rows(self, column_mapping: dict[str, str]) -> Iterator[dict[str, Any]]:
|
||||
"""`column_mapping`: source column -> target field. Yields one dict
|
||||
per row keyed by target field. Values are not validated here."""
|
||||
|
||||
def tables(self) -> list[SourceTable]:
|
||||
"""The tables this source offers, when it has more than one."""
|
||||
return []
|
||||
|
||||
def metadata(self) -> dict[str, Any]:
|
||||
"""Source-specific facts worth showing (a CSV's delimiter, ...)."""
|
||||
return {}
|
||||
|
||||
@classmethod
|
||||
def describe(cls) -> dict[str, Any]:
|
||||
return {
|
||||
"kind": cls.kind,
|
||||
"label": cls.label,
|
||||
"description": cls.description,
|
||||
"category": cls.category,
|
||||
"icon": cls.icon,
|
||||
"extensions": list(cls.extensions),
|
||||
}
|
||||
|
||||
|
||||
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"falta {key}") from exc
|
||||
except (binascii.Error, ValueError, TypeError) as exc:
|
||||
raise ConnectorError(f"{key} no es base64 válido: {exc}") from exc
|
||||
@@ -1,72 +0,0 @@
|
||||
import csv
|
||||
import io
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
|
||||
_CANDIDATE_DELIMITERS = ",;\t|"
|
||||
# utf-8-sig strips the BOM Excel prepends when it exports "CSV UTF-8" (it
|
||||
# would otherwise end up glued to the first column's name); cp1252 is what
|
||||
# Excel on Windows writes for plain "CSV" in a Spanish locale.
|
||||
_FALLBACK_ENCODINGS = ("utf-8-sig", "cp1252")
|
||||
|
||||
|
||||
@register_connector
|
||||
class CsvConnector(FileConnector):
|
||||
"""Every cell is read as text: pandas' type guessing would turn the
|
||||
postal code `01000` into `1000` before validation sees it."""
|
||||
|
||||
kind = "csv"
|
||||
label = "Texto / CSV"
|
||||
description = "Archivos delimitados por comas, punto y coma o tabuladores"
|
||||
category = "file"
|
||||
icon = "table_view"
|
||||
extensions = ("csv", "txt", "tsv")
|
||||
option_names = ("delimiter", "encoding")
|
||||
|
||||
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("el archivo parece binario, no un texto delimitado")
|
||||
self._delimiter = delimiter or _sniff_delimiter(text)
|
||||
try:
|
||||
self._df = pd.read_csv(
|
||||
io.StringIO(text),
|
||||
sep=self._delimiter,
|
||||
dtype=str,
|
||||
keep_default_na=False,
|
||||
na_values=[""],
|
||||
skipinitialspace=True,
|
||||
)
|
||||
except Exception as exc: # pandas raises a variety of error types
|
||||
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:
|
||||
return self._df
|
||||
|
||||
def metadata(self) -> dict:
|
||||
return {"delimiter": self._delimiter, "encoding": self._encoding}
|
||||
|
||||
|
||||
def _decode(raw: bytes, encoding: str | None) -> tuple[str, str]:
|
||||
for candidate in (encoding,) if encoding else _FALLBACK_ENCODINGS:
|
||||
try:
|
||||
return candidate, raw.decode(candidate)
|
||||
except (UnicodeDecodeError, LookupError):
|
||||
continue
|
||||
raise ConnectorError(f"no se pudo decodificar el CSV como {encoding or ' / '.join(_FALLBACK_ENCODINGS)}")
|
||||
|
||||
|
||||
def _sniff_delimiter(text: str) -> str:
|
||||
"""`csv.Sniffer` restricted to real delimiters. pandas' own `sep=None`
|
||||
sniffing picks letters as delimiters on single-column files (`id\\nH3`
|
||||
parsed as columns `['Unnamed: 0', 'd']`)."""
|
||||
sample = "\n".join(text.splitlines()[:50])
|
||||
try:
|
||||
return csv.Sniffer().sniff(sample, delimiters=_CANDIDATE_DELIMITERS).delimiter
|
||||
except csv.Error:
|
||||
return ","
|
||||
@@ -1,226 +0,0 @@
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from extraction import DocumentExtractor, ExtractedRecord, ExtractionError, make_segmenter, read_document, reader_for
|
||||
from extraction.readers import PdfReader, combine_pages, supported_extensions
|
||||
from extraction.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.tabular import DataFrameConnector
|
||||
from webapi.imports.schemas.field_specs import field_specs_for, key_field_for
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
DOCUMENT_COLUMN = "documento"
|
||||
IMAGE_COLUMN = "imagen"
|
||||
CONFIDENCE_COLUMN = "confianza_extraccion"
|
||||
SOURCES_COLUMN = "origen"
|
||||
|
||||
|
||||
class _ResultCache:
|
||||
"""OCR over a stack of scans is slow, and the stateless API runs the
|
||||
same extraction for preview, validation and commit. Results are kept
|
||||
per worker for the last few distinct requests."""
|
||||
|
||||
def __init__(self, size: int = 8):
|
||||
self._items: OrderedDict[str, list[ExtractedRecord]] = OrderedDict()
|
||||
self._size = size
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def get_or_compute(self, key: str, compute) -> list[ExtractedRecord]:
|
||||
with self._lock:
|
||||
if key in self._items:
|
||||
self._items.move_to_end(key)
|
||||
return self._items[key]
|
||||
value = compute()
|
||||
with self._lock:
|
||||
self._items[key] = value
|
||||
while len(self._items) > self._size:
|
||||
self._items.popitem(last=False)
|
||||
return value
|
||||
|
||||
|
||||
_CACHE = _ResultCache()
|
||||
|
||||
|
||||
@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.
|
||||
|
||||
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.
|
||||
|
||||
Corrections made while reviewing travel in `overrides`
|
||||
(`{"<row>": {"field": value}}`) and win over the extracted value.
|
||||
"""
|
||||
|
||||
kind = "document"
|
||||
label = "Documentos clínicos"
|
||||
description = "Reportes, formatos y notas en PDF o imagen; los campos se extraen del texto libre"
|
||||
category = "document"
|
||||
icon = "document_scanner"
|
||||
extensions: ClassVar[tuple[str, ...]] = tuple(supported_extensions())
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
files: list[tuple[str, bytes]],
|
||||
*,
|
||||
target: str,
|
||||
segmentation: str = "auto",
|
||||
pages_per_record: int = 1,
|
||||
ocr_mode: str = "auto",
|
||||
key_pattern: str | None = None,
|
||||
overrides: dict[str, dict[str, Any]] | None = None,
|
||||
):
|
||||
if not files:
|
||||
raise ConnectorError("no se recibieron documentos")
|
||||
entity = ENTITY_REGISTRY.get(target)
|
||||
if entity is None:
|
||||
raise ConnectorError(f"destino desconocido: {target!r}")
|
||||
if segmentation not in SEGMENTERS:
|
||||
raise ConnectorError(f"segmentación desconocida {segmentation!r} (disponibles: {', '.join(SEGMENTERS)})")
|
||||
if ocr_mode not in ("auto", "always", "never"):
|
||||
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)
|
||||
self.key_field = key_field_for(entity)
|
||||
self.segmentation = segmentation
|
||||
self.pages_per_record = max(1, int(pages_per_record))
|
||||
self.ocr_mode = ocr_mode
|
||||
self.key_pattern = key_pattern
|
||||
self.overrides = {str(k): v for k, v in (overrides or {}).items()}
|
||||
self._df: pd.DataFrame | None = None
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "DocumentConnector":
|
||||
files = [(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)]
|
||||
return cls(
|
||||
files,
|
||||
target=payload["target"],
|
||||
segmentation=payload.get("segmentation", "auto"),
|
||||
pages_per_record=payload.get("pages_per_record", 1),
|
||||
ocr_mode=payload.get("ocr_mode", "auto"),
|
||||
key_pattern=payload.get("key_pattern") or None,
|
||||
overrides=payload.get("overrides"),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def describe(cls) -> dict[str, Any]:
|
||||
segmentations = [{"id": name, "label": segmenter.label} for name, segmenter in SEGMENTERS.items()]
|
||||
return {**super().describe(), "segmentations": segmentations}
|
||||
|
||||
# -- extraction -----------------------------------------------------------
|
||||
|
||||
@property
|
||||
def records(self) -> list[ExtractedRecord]:
|
||||
return _CACHE.get_or_compute(self._cache_key(), self._extract)
|
||||
|
||||
def _extract(self) -> list[ExtractedRecord]:
|
||||
try:
|
||||
documents = [read_document(name, raw, ocr_mode=self.ocr_mode) for name, raw in self.files]
|
||||
except ExtractionError as exc:
|
||||
raise ConnectorError(str(exc)) from exc
|
||||
segmenter = make_segmenter(
|
||||
self.segmentation,
|
||||
key=next((s for s in self.specs if s.name == self.key_field), None),
|
||||
pages_per_record=self.pages_per_record,
|
||||
)
|
||||
return DocumentExtractor(self.specs, key_field=self.key_field, segmenter=segmenter).extract(documents)
|
||||
|
||||
def _cache_key(self) -> str:
|
||||
digest = hashlib.sha256()
|
||||
for name, raw in self.files:
|
||||
digest.update(name.encode())
|
||||
digest.update(hashlib.sha256(raw).digest())
|
||||
config = [self.target, self.segmentation, self.pages_per_record, self.ocr_mode, self.key_pattern]
|
||||
digest.update(json.dumps(config).encode())
|
||||
return digest.hexdigest()
|
||||
|
||||
# -- rows -----------------------------------------------------------------
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
if self._df is None:
|
||||
columns = [spec.name for spec in self.specs] + [DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN]
|
||||
rows = [self._row(index, record) for index, record in enumerate(self.records)]
|
||||
self._df = pd.DataFrame(rows, columns=columns, dtype=object)
|
||||
return self._df
|
||||
|
||||
def _row(self, index: int, record: ExtractedRecord) -> dict[str, Any]:
|
||||
row: dict[str, Any] = record.row()
|
||||
row.update(self.overrides.get(str(index), {}))
|
||||
row[DOCUMENT_COLUMN] = self._record_pdf(record)
|
||||
row[IMAGE_COLUMN] = self._record_image(record)
|
||||
row[CONFIDENCE_COLUMN] = round(record.confidence, 3)
|
||||
row[SOURCES_COLUMN] = "; ".join(f"{s.document} p. {', '.join(map(str, s.page_numbers))}" for s in record.sources)
|
||||
return row
|
||||
|
||||
def _record_pdf(self, record: ExtractedRecord) -> bytes | None:
|
||||
"""The record's pages from every PDF it was found in, as one PDF."""
|
||||
by_name = dict(self.files)
|
||||
parts = [
|
||||
(by_name[source.document], source.page_numbers)
|
||||
for source in record.sources
|
||||
if source.document in by_name and PdfReader.accepts(source.document, by_name[source.document][:8])
|
||||
]
|
||||
return combine_pages(parts) if parts else None
|
||||
|
||||
def _record_image(self, record: ExtractedRecord) -> bytes | None:
|
||||
"""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:
|
||||
return None
|
||||
figures = [c for c in candidates if c[1].kind == "figure"]
|
||||
document, image = figures[0] if figures else candidates[0]
|
||||
raw = by_name[document]
|
||||
try:
|
||||
return reader_for(document, raw).render_region(raw, image.page_number, image.bbox)
|
||||
except ExtractionError:
|
||||
return None
|
||||
|
||||
# -- review ---------------------------------------------------------------
|
||||
|
||||
def report(self) -> list[dict[str, Any]]:
|
||||
"""Per record: every extracted value with its confidence, method and
|
||||
the line it was read from, conflicts between sources, and the
|
||||
images found on its pages."""
|
||||
report = []
|
||||
for index, record in enumerate(self.records):
|
||||
overrides = self.overrides.get(str(index), {})
|
||||
fields = {name: value.to_dict() for name, value in record.values.items()}
|
||||
for name, value in overrides.items():
|
||||
fields[name] = {**fields.get(name, {}), "value": value, "method": "manual", "confidence": 1.0}
|
||||
report.append(
|
||||
{
|
||||
"index": index,
|
||||
"key": record.key,
|
||||
"confidence": round(record.confidence, 3),
|
||||
"fields": fields,
|
||||
"missing": [s.name for s in self.specs if s.required and s.name not in fields],
|
||||
"conflicts": [
|
||||
{"field": c.field, "kept": c.kept.to_dict(), "discarded": c.discarded.to_dict()}
|
||||
for c in record.conflicts
|
||||
],
|
||||
"sources": [{"document": s.document, "page_numbers": s.page_numbers} for s in record.sources],
|
||||
"images": [
|
||||
{"document": name, "page_number": image.page_number, "bbox": image.bbox.as_list(), "kind": image.kind}
|
||||
for name, image in record.images
|
||||
],
|
||||
}
|
||||
)
|
||||
return report
|
||||
|
||||
def metadata(self) -> dict[str, Any]:
|
||||
return {"records": len(self.records), "key_field": self.key_field, "documents": [name for name, _ in self.files]}
|
||||
@@ -1,105 +0,0 @@
|
||||
from datetime import date, timedelta
|
||||
from pathlib import PurePath
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from extraction import ExtractionError
|
||||
from extraction.signals import EegRecording
|
||||
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.tabular import FileConnector
|
||||
|
||||
MAX_LISTED_EVENTS = 20
|
||||
|
||||
|
||||
@register_connector
|
||||
class EdfConnector(FileConnector):
|
||||
"""EEG recordings (`.edf`), one row per file, shaped for `tea.EegEstudio`:
|
||||
patient and dates from the header, an estimated background rhythm from
|
||||
the posterior channels, a text summary of the recording, and the file
|
||||
itself (column `estudio`, stored in `eeg_estudio.eeg_estudio`)."""
|
||||
|
||||
kind = "edf"
|
||||
label = "EEG (EDF)"
|
||||
description = "Registros de electroencefalografía en European Data Format"
|
||||
category = "signal"
|
||||
icon = "monitor_heart"
|
||||
extensions = ("edf",)
|
||||
option_names = ("file_name",)
|
||||
|
||||
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":
|
||||
"""One file (`file_base64` + `options.file_name`) or several (`files: [{name, file_base64}]`)."""
|
||||
if not payload.get("files"):
|
||||
return super().from_payload(payload)
|
||||
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]}
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
if self._df is None:
|
||||
self._df = pd.DataFrame([self._row(name, raw) for name, raw in self.files], dtype=object)
|
||||
return self._df
|
||||
|
||||
def _row(self, name: str, raw: bytes) -> dict[str, Any]:
|
||||
try:
|
||||
eeg = EegRecording.read(raw)
|
||||
except ExtractionError as exc:
|
||||
raise ConnectorError(f"{name}: {exc}") from exc
|
||||
patient = eeg.patient
|
||||
study_date = eeg.start.date() if eeg.start else None
|
||||
rhythm = eeg.background_rhythm()
|
||||
return {
|
||||
"id_registro_laboratorio": eeg.recording_fields["admin_code"] or PurePath(name).stem,
|
||||
"paciente": patient.code,
|
||||
"sexo": patient.sex,
|
||||
"fecha_nacimiento_declarada": patient.birthdate,
|
||||
"edad_meses": age_in_months(patient.birthdate, study_date),
|
||||
"fecha_estudio": study_date,
|
||||
"duracion_min": round(eeg.duration_seconds / 60) if eeg.duration_seconds else None,
|
||||
"ritmo_base_frecuencia": rhythm["frequency_hz"],
|
||||
"ritmo_base_amplitud": rhythm["amplitude_uv"],
|
||||
"descripcion_senal": describe(eeg),
|
||||
"archivo": name,
|
||||
"estudio": raw,
|
||||
}
|
||||
|
||||
|
||||
def describe(eeg: EegRecording) -> str:
|
||||
channels = eeg.channels
|
||||
parts = [
|
||||
f"{eeg.variant}, {len(channels)} canales a {channels[0].sample_rate:g} Hz" if channels else eeg.variant,
|
||||
f"duración {timedelta(seconds=round(eeg.duration_seconds))}",
|
||||
"montaje: " + ", ".join(c.label for c in channels),
|
||||
]
|
||||
fields = eeg.recording_fields
|
||||
if fields["equipment"]:
|
||||
parts.append(f"equipo: {fields['equipment']}")
|
||||
if fields["technician"]:
|
||||
parts.append(f"técnico: {fields['technician']}")
|
||||
events = eeg.annotations()
|
||||
if events:
|
||||
listed = "; ".join(f"{timedelta(seconds=round(e.onset_seconds))} {e.text}" for e in events[:MAX_LISTED_EVENTS])
|
||||
more = f" (+{len(events) - MAX_LISTED_EVENTS})" if len(events) > MAX_LISTED_EVENTS else ""
|
||||
parts.append(f"eventos: {listed}{more}")
|
||||
return ". ".join(parts) + "."
|
||||
|
||||
|
||||
def age_in_months(birthdate: date | None, on: date | None) -> float | None:
|
||||
if birthdate is None or on is None or on < birthdate:
|
||||
return None
|
||||
months = (on.year - birthdate.year) * 12 + (on.month - birthdate.month)
|
||||
if on.day < birthdate.day:
|
||||
months -= 1
|
||||
return float(months)
|
||||
@@ -1,3 +0,0 @@
|
||||
class ConnectorError(Exception):
|
||||
"""Raised by any `Connector` subclass for malformed input, a bad
|
||||
connection string, an unreadable file, etc."""
|
||||
@@ -1,49 +0,0 @@
|
||||
import io
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.base import SourceTable
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
|
||||
|
||||
@register_connector
|
||||
class ExcelConnector(FileConnector):
|
||||
"""`dtype=object` keeps each cell as the value openpyxl read; column
|
||||
typing would turn an integer column with a blank cell into floats."""
|
||||
|
||||
kind = "excel"
|
||||
label = "Libro de Excel"
|
||||
description = "Cada hoja del libro se ofrece como tabla"
|
||||
category = "file"
|
||||
icon = "grid_on"
|
||||
extensions = ("xlsx", "xlsm")
|
||||
option_names = ("sheet_name",)
|
||||
|
||||
def __init__(self, raw: bytes, *, sheet_name: str | int | None = None):
|
||||
try:
|
||||
self._workbook = pd.ExcelFile(io.BytesIO(raw), engine="openpyxl")
|
||||
except Exception as 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"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"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]:
|
||||
return list(self._workbook.sheet_names)
|
||||
|
||||
def tables(self) -> list[SourceTable]:
|
||||
return [SourceTable(name, {"sheet_name": name}, kind="sheet") for name in self.list_sheets()]
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
return self._df
|
||||
|
||||
def metadata(self) -> dict:
|
||||
return {"sheets": self.list_sheets(), "sheet_name": self._sheet}
|
||||
@@ -1,61 +0,0 @@
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
|
||||
|
||||
@register_connector
|
||||
class JsonConnector(FileConnector):
|
||||
"""Nested objects are flattened to dotted column names
|
||||
(`paciente.sexo`) into an object-dtype DataFrame, so JSON's own types
|
||||
survive (`json_normalize` turns a sometimes-missing integer into floats)."""
|
||||
|
||||
kind = "json"
|
||||
label = "JSON"
|
||||
description = "Lista de registros; los objetos anidados se aplanan"
|
||||
category = "file"
|
||||
icon = "data_object"
|
||||
extensions = ("json",)
|
||||
option_names = ("record_path",)
|
||||
|
||||
def __init__(self, raw: bytes, *, record_path: str | None = None):
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except Exception as 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"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("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)
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
return self._df
|
||||
|
||||
def metadata(self) -> dict:
|
||||
return {"record_path": self._record_path}
|
||||
|
||||
|
||||
def _flatten(record: dict[str, Any], prefix: str = "") -> dict[str, Any]:
|
||||
flat: dict[str, Any] = {}
|
||||
for key, value in record.items():
|
||||
name = f"{prefix}{key}"
|
||||
if isinstance(value, dict):
|
||||
flat.update(_flatten(value, f"{name}."))
|
||||
else:
|
||||
flat[name] = value
|
||||
return flat
|
||||
@@ -1,354 +0,0 @@
|
||||
"""PDF tables. Two ways to turn a PDF into rows:
|
||||
|
||||
- `select_table`: a ruled table found by pdfplumber in the text layer;
|
||||
- `extract_regions`: one drawn box per column over the rendered page. Each
|
||||
box is read from the text layer or OCR'd, and lines from all boxes on a
|
||||
page are aligned into rows by their vertical position.
|
||||
|
||||
Documents that are not tables (one report per patient, free text) go
|
||||
through `DocumentConnector` instead.
|
||||
"""
|
||||
import io
|
||||
import statistics
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
import pdfplumber
|
||||
import pytesseract
|
||||
from pytesseract import Output
|
||||
|
||||
from extraction.ocr import DEFAULT_LANG, group_words
|
||||
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.tabular import DataFrameConnector
|
||||
|
||||
_DEFAULT_SAMPLE_PAGES = 3
|
||||
_DEFAULT_CHAR_THRESHOLD = 20
|
||||
_DEFAULT_DPI = 150
|
||||
# Rendering memory grows with dpi². Past ~300 dpi OCR gains nothing and a
|
||||
# single request could exhaust the worker.
|
||||
_MIN_DPI, _MAX_DPI = 50, 300
|
||||
# PSM 6 (one uniform block): a region is a narrow column of stacked lines;
|
||||
# full-page segmentation (PSM 3) drops short crops such as a lone "F".
|
||||
_OCR_CONFIG = "--psm 6"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TableCandidate:
|
||||
page_number: int # 1-indexed
|
||||
bbox: tuple[float, float, float, float] # PDF points, pdfplumber's native space
|
||||
grid: list[list[str | None]] # header row + data rows
|
||||
confidence: float # ranking heuristic only, not ML
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RegionSpec:
|
||||
target_field: str
|
||||
page_numbers: list[int] # 1-indexed
|
||||
bbox: tuple[float, float, float, float] # normalized 0..1 over the rendered page
|
||||
|
||||
@classmethod
|
||||
def parse(cls, raw: dict[str, Any]) -> "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"región inválida: {exc}") from exc
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExtractionWarning:
|
||||
page_number: int
|
||||
message: str
|
||||
|
||||
|
||||
@register_connector
|
||||
class PdfConnector(DataFrameConnector):
|
||||
kind = "pdf"
|
||||
label = "PDF (tablas)"
|
||||
description = "Tablas detectadas o columnas dibujadas sobre la página (OCR para escaneos)"
|
||||
category = "document"
|
||||
icon = "picture_as_pdf"
|
||||
extensions = ("pdf",)
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "PdfConnector":
|
||||
connector = cls(decode_file(payload))
|
||||
mode = payload.get("mode", "table")
|
||||
if mode == "table":
|
||||
connector.select_table(int(payload["page_number"]), tuple(float(v) for v in payload["bbox"]))
|
||||
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"modo de PDF desconocido: {mode!r}")
|
||||
return connector
|
||||
|
||||
def __init__(self, file_bytes: bytes):
|
||||
self.file_bytes = file_bytes
|
||||
try:
|
||||
self._pdf = pdfplumber.open(io.BytesIO(file_bytes))
|
||||
except Exception as 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
|
||||
self.warnings: list[ExtractionWarning] = []
|
||||
|
||||
@property
|
||||
def page_count(self) -> int:
|
||||
return len(self._pdf.pages)
|
||||
|
||||
def has_text_layer(self, sample_pages: int = _DEFAULT_SAMPLE_PAGES, char_threshold: int = _DEFAULT_CHAR_THRESHOLD) -> bool:
|
||||
return any(self._page_has_text(page, char_threshold) for page in self._pdf.pages[:sample_pages])
|
||||
|
||||
@staticmethod
|
||||
def _page_has_text(page, char_threshold: int = _DEFAULT_CHAR_THRESHOLD) -> bool:
|
||||
try:
|
||||
text = page.extract_text() or ""
|
||||
except Exception:
|
||||
return False
|
||||
return len(text.strip()) >= char_threshold
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Ruled tables found by pdfplumber in the text layer
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def detect_tables(self) -> list[TableCandidate]:
|
||||
candidates: list[TableCandidate] = []
|
||||
for page in self._pdf.pages:
|
||||
try:
|
||||
tables = page.find_tables()
|
||||
except Exception as 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"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(
|
||||
TableCandidate(
|
||||
page_number=page.page_number,
|
||||
bbox=tuple(table.bbox),
|
||||
grid=grid,
|
||||
confidence=_table_confidence(grid),
|
||||
)
|
||||
)
|
||||
candidates.sort(key=lambda c: c.confidence, reverse=True)
|
||||
return candidates
|
||||
|
||||
def select_table(self, page_number: int, bbox: tuple[float, float, float, float]) -> None:
|
||||
page = self._page(page_number)
|
||||
try:
|
||||
cropped = page.within_bbox(bbox, strict=False)
|
||||
grid = cropped.extract_table()
|
||||
except Exception as 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 se encontró una tabla utilizable en {bbox} de la página {page_number}")
|
||||
self._table_grid = grid
|
||||
self._region_rows = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Drawn regions over the rendered page, read from text or OCR, then aligned
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def render_page_image(self, page_number: int, dpi: int = _DEFAULT_DPI) -> bytes:
|
||||
_check_dpi(dpi)
|
||||
page = self._page(page_number)
|
||||
try:
|
||||
image = page.to_image(resolution=dpi).original
|
||||
except Exception as 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 se indicaron regiones")
|
||||
_check_dpi(dpi)
|
||||
|
||||
by_page: dict[int, list[RegionSpec]] = {}
|
||||
for region in regions:
|
||||
for page_number in region.page_numbers:
|
||||
by_page.setdefault(page_number, []).append(region)
|
||||
|
||||
self.warnings = []
|
||||
result: dict[str, list[str | None]] = {region.target_field: [] for region in regions}
|
||||
|
||||
for page_number in sorted(by_page):
|
||||
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):
|
||||
# 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
|
||||
return result
|
||||
|
||||
def _lines_for_page(self, page, regions_on_page: list[RegionSpec], dpi: int) -> list[dict[str, Any]]:
|
||||
"""Collect `(target_field, y, height, text)` lines for every region
|
||||
on one page. Y is in page pixels at `dpi` whether the region was read
|
||||
from the text layer or OCR'd, so lines from all regions can be aligned."""
|
||||
scale = dpi / 72.0
|
||||
use_text_layer = self._page_has_text(page)
|
||||
rendered_image = None
|
||||
lines: list[dict[str, Any]] = []
|
||||
|
||||
for region in regions_on_page:
|
||||
x0n, y0n, x1n, y1n = region.bbox
|
||||
|
||||
if use_text_layer:
|
||||
point_bbox = self._clamp_to_page(
|
||||
(x0n * page.width, y0n * page.height, x1n * page.width, y1n * page.height),
|
||||
page,
|
||||
)
|
||||
try:
|
||||
region_lines = page.within_bbox(point_bbox, strict=False).extract_text_lines()
|
||||
except Exception as 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:
|
||||
continue
|
||||
lines.append(
|
||||
{
|
||||
"target_field": region.target_field,
|
||||
"y": ((line["top"] + line["bottom"]) / 2) * scale,
|
||||
"height": (line["bottom"] - line["top"]) * scale,
|
||||
"text": text,
|
||||
}
|
||||
)
|
||||
else:
|
||||
if rendered_image is None:
|
||||
try:
|
||||
rendered_image = page.to_image(resolution=dpi).original
|
||||
except Exception as 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)),
|
||||
max(0, round(y0n * img_h)),
|
||||
min(img_w, round(x1n * img_w)),
|
||||
min(img_h, round(y1n * img_h)),
|
||||
)
|
||||
if crop_box[2] <= crop_box[0] or crop_box[3] <= crop_box[1]:
|
||||
continue
|
||||
cropped = rendered_image.crop(crop_box)
|
||||
try:
|
||||
data = pytesseract.image_to_data(cropped, output_type=Output.DICT, lang=DEFAULT_LANG, config=_OCR_CONFIG)
|
||||
except Exception as 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:
|
||||
continue
|
||||
top_local = min(w["top"] for w in words)
|
||||
bottom_local = max(w["top"] + w["height"] for w in words)
|
||||
lines.append(
|
||||
{
|
||||
"target_field": region.target_field,
|
||||
"y": crop_box[1] + (top_local + bottom_local) / 2,
|
||||
"height": bottom_local - top_local,
|
||||
"text": text,
|
||||
}
|
||||
)
|
||||
return lines
|
||||
|
||||
def _cluster_rows(self, lines: list[dict[str, Any]], page_number: int) -> list[dict[str, str]]:
|
||||
if not lines:
|
||||
return []
|
||||
heights = [line["height"] for line in lines if line["height"] > 0]
|
||||
median_height = statistics.median(heights) if heights else 10.0
|
||||
gap_tolerance = 0.6 * median_height
|
||||
|
||||
ordered = sorted(lines, key=lambda line: line["y"])
|
||||
clusters: list[list[dict[str, Any]]] = [[ordered[0]]]
|
||||
for line in ordered[1:]:
|
||||
if line["y"] - clusters[-1][-1]["y"] <= gap_tolerance:
|
||||
clusters[-1].append(line)
|
||||
else:
|
||||
clusters.append([line])
|
||||
|
||||
resolved: list[list[dict[str, Any]]] = []
|
||||
for cluster in clusters:
|
||||
resolved.extend(self._split_conflicts(cluster, page_number))
|
||||
|
||||
rows = []
|
||||
for cluster in resolved:
|
||||
row: dict[str, str] = {}
|
||||
for line in cluster:
|
||||
if line["target_field"] in row:
|
||||
row[line["target_field"]] = f"{row[line['target_field']]} {line['text']}".strip()
|
||||
else:
|
||||
row[line["target_field"]] = line["text"]
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
def _split_conflicts(self, cluster: list[dict[str, Any]], page_number: int) -> list[list[dict[str, Any]]]:
|
||||
"""A row cluster holds at most one line per target field. When two
|
||||
lines of the same region land in one cluster, split it at its largest
|
||||
internal gap (recursively) and record a warning rather than drop data."""
|
||||
fields = [line["target_field"] for line in cluster]
|
||||
if len(fields) == len(set(fields)) or len(cluster) < 2:
|
||||
return [cluster]
|
||||
|
||||
ordered = sorted(cluster, key=lambda line: line["y"])
|
||||
gaps = [(ordered[i + 1]["y"] - ordered[i]["y"], i) for i in range(len(ordered) - 1)]
|
||||
_, split_at = max(gaps, key=lambda g: g[0])
|
||||
left, right = ordered[: split_at + 1], ordered[split_at + 1 :]
|
||||
|
||||
duplicated = sorted({f for f in fields if fields.count(f) > 1})
|
||||
self.warnings.append(
|
||||
ExtractionWarning(
|
||||
page_number=page_number,
|
||||
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)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Connector interface, usable once select_table() or extract_regions() ran
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
if self._table_grid is not None:
|
||||
header, *data_rows = self._table_grid
|
||||
columns = [name if name else f"column_{i}" for i, name in enumerate(header)]
|
||||
return pd.DataFrame(data_rows, columns=columns)
|
||||
if self._region_rows is not None:
|
||||
return pd.DataFrame(self._region_rows)
|
||||
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 fuera de rango: {page_number}")
|
||||
return self._pdf.pages[page_number - 1]
|
||||
|
||||
@staticmethod
|
||||
def _clamp_to_page(bbox: tuple[float, float, float, float], page) -> tuple[float, float, float, float]:
|
||||
x0, top, x1, bottom = bbox
|
||||
px0, ptop, px1, pbottom = page.bbox
|
||||
return (max(x0, px0), max(top, ptop), min(x1, px1), min(bottom, pbottom))
|
||||
|
||||
|
||||
def _check_dpi(dpi: int) -> None:
|
||||
if not (_MIN_DPI <= dpi <= _MAX_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:
|
||||
"""Ranking heuristic for the UI: capped row count plus non-empty cell rate."""
|
||||
data_rows = len(grid) - 1
|
||||
total_cells = sum(len(row) for row in grid) or 1
|
||||
filled_cells = sum(1 for row in grid for cell in row if cell not in (None, ""))
|
||||
fill_rate = filled_cells / total_cells
|
||||
row_score = min(data_rows / 5, 1.0)
|
||||
return round(0.5 * row_score + 0.5 * fill_rate, 4)
|
||||
@@ -1,38 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
from webapi.imports.connectors.base import Connector
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
|
||||
CONNECTORS: dict[str, type[Connector]] = {}
|
||||
|
||||
|
||||
def register_connector(cls: type[Connector]) -> type[Connector]:
|
||||
if cls.kind in CONNECTORS:
|
||||
raise ValueError(f"connector kind {cls.kind!r} is already registered by {CONNECTORS[cls.kind].__name__}")
|
||||
CONNECTORS[cls.kind] = cls
|
||||
return cls
|
||||
|
||||
|
||||
def connector_class(kind: str | None) -> type[Connector]:
|
||||
cls = CONNECTORS.get(kind or "")
|
||||
if cls is None:
|
||||
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 debe ser un objeto")
|
||||
try:
|
||||
return connector_class(kind).from_payload(payload)
|
||||
except KeyError as exc:
|
||||
raise ConnectorError(f"falta un campo en payload: {exc}") from exc
|
||||
|
||||
|
||||
def kind_for_filename(filename: str) -> str | None:
|
||||
extension = filename.lower().rsplit(".", 1)[-1]
|
||||
return next((kind for kind, cls in CONNECTORS.items() if extension in cls.extensions), None)
|
||||
|
||||
|
||||
def catalog() -> list[dict[str, Any]]:
|
||||
return [cls.describe() for cls in CONNECTORS.values()]
|
||||
@@ -1,259 +0,0 @@
|
||||
import datetime as _dt
|
||||
import importlib.util
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar, Iterator
|
||||
|
||||
import pandas as pd
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from webapi.imports.connectors.base import Connector, PreviewResult, SourceColumn
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.sql_policy import SqlSourcePolicy
|
||||
from webapi.imports.connectors.tabular import infer_type
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SqlEngine:
|
||||
"""A database server the connection form offers. Supporting another
|
||||
server is one entry in `SqlConnector.ENGINES` plus its driver package."""
|
||||
|
||||
id: str
|
||||
label: str
|
||||
drivername: str
|
||||
default_port: int
|
||||
driver_module: str
|
||||
description: str = ""
|
||||
default_schema: str | None = None
|
||||
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
return importlib.util.find_spec(self.driver_module) is not None
|
||||
|
||||
def describe(self) -> dict[str, Any]:
|
||||
return {
|
||||
"id": self.id,
|
||||
"label": self.label,
|
||||
"description": self.description,
|
||||
"default_port": self.default_port,
|
||||
"default_schema": self.default_schema,
|
||||
"available": self.available,
|
||||
}
|
||||
|
||||
|
||||
@register_connector
|
||||
class SqlConnector(Connector):
|
||||
"""Reads a table or a SELECT from a client's database server.
|
||||
|
||||
Browsing (`list_schemas`/`list_tables`/`list_columns`) lives here only;
|
||||
the import pipeline uses the `Connector` methods once `select_table` or
|
||||
`select_query` has been called. Rows come straight from SQLAlchemy, so
|
||||
they keep the driver's types, previews fetch only `limit` rows and
|
||||
`read_rows` streams. Connections are read-only (see `_reading`) and
|
||||
unpooled, since every request builds its own connector.
|
||||
"""
|
||||
|
||||
kind = "sql"
|
||||
label = "Base de datos"
|
||||
description = "Tabla o consulta de un servidor SQL"
|
||||
category = "database"
|
||||
icon = "storage"
|
||||
|
||||
ENGINES: ClassVar[dict[str, SqlEngine]] = {
|
||||
engine.id: engine
|
||||
for engine in (
|
||||
SqlEngine("mysql", "MySQL", "mysql+pymysql", 3306, "pymysql", "Servidor MySQL 5.7+ / 8"),
|
||||
SqlEngine("mariadb", "MariaDB", "mariadb+pymysql", 3306, "pymysql", "Servidor MariaDB"),
|
||||
SqlEngine("postgresql", "PostgreSQL", "postgresql+psycopg2", 5432, "psycopg2", "Servidor PostgreSQL", "public"),
|
||||
SqlEngine("mssql", "SQL Server", "mssql+pymssql", 1433, "pymssql", "Microsoft SQL Server 2017+ / Azure SQL", "dbo"),
|
||||
)
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def describe(cls) -> dict[str, Any]:
|
||||
return {**super().describe(), "engines": [engine.describe() for engine in cls.ENGINES.values()]}
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "SqlConnector":
|
||||
connector = cls.connect(payload)
|
||||
if payload.get("query"):
|
||||
return connector.select_query(payload["query"])
|
||||
return connector.select_table(payload["table"], schema=payload.get("schema"))
|
||||
|
||||
@classmethod
|
||||
def connect(cls, payload: dict[str, Any]) -> "SqlConnector":
|
||||
"""A connector without a table selected yet, for browsing. Takes
|
||||
either `server` (engine, host, port, database, user, password) or a
|
||||
raw SQLAlchemy `connection_string`."""
|
||||
if payload.get("server"):
|
||||
return cls(cls.server_url(payload["server"]))
|
||||
if payload.get("connection_string"):
|
||||
return cls(payload["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"motor desconocido {server.get('engine')!r} (disponibles: {', '.join(cls.ENGINES)})")
|
||||
if not engine.available:
|
||||
raise ConnectorError(f"el controlador de {engine.label} ({engine.driver_module}) no está instalado en el servidor")
|
||||
if not server.get("host") or not server.get("database"):
|
||||
raise ConnectorError("se requieren el servidor (host) y la base de datos")
|
||||
try:
|
||||
port = int(server.get("port") or engine.default_port)
|
||||
except (TypeError, ValueError) as 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,
|
||||
password=server.get("password") or None,
|
||||
host=server["host"],
|
||||
port=port,
|
||||
database=server["database"],
|
||||
)
|
||||
|
||||
def __init__(self, connection: str | sa.engine.URL, *, policy: SqlSourcePolicy | None = None):
|
||||
self._policy = policy or SqlSourcePolicy.from_env()
|
||||
url = self._policy.check_url(connection)
|
||||
try:
|
||||
self._engine = sa.create_engine(url, poolclass=NullPool)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"cadena de conexión inválida: {exc}") from exc
|
||||
self._table: sa.Table | None = None
|
||||
self._query: str | None = None
|
||||
|
||||
# -- browsing ---------------------------------------------------------
|
||||
|
||||
def test_connection(self) -> None:
|
||||
try:
|
||||
with self._reading() as conn:
|
||||
conn.execute(sa.text("SELECT 1"))
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"no se pudo conectar: {exc}") from exc
|
||||
|
||||
def get_dialect(self) -> str:
|
||||
return self._engine.dialect.name
|
||||
|
||||
def list_schemas(self) -> list[str]:
|
||||
try:
|
||||
return sa.inspect(self._engine).get_schema_names()
|
||||
except Exception as 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"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"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"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, dialect=self.get_dialect()), None
|
||||
return self
|
||||
|
||||
# -- Connector ----------------------------------------------------------
|
||||
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult:
|
||||
statement = self._selectable()
|
||||
try:
|
||||
with self._reading() as conn:
|
||||
result = conn.execute(sa.select(statement).limit(limit))
|
||||
names = list(result.keys())
|
||||
rows = [dict(row) for row in result.mappings()]
|
||||
total = conn.execute(sa.select(sa.func.count()).select_from(statement)).scalar_one()
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as 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]]:
|
||||
statement = sa.select(self._selectable())
|
||||
try:
|
||||
with self._reading() as conn:
|
||||
result = conn.execution_options(stream_results=True, yield_per=1000).execute(statement)
|
||||
for row in result.mappings():
|
||||
yield {target: row.get(source) for source, target in column_mapping.items()}
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"no se pudieron leer las filas: {exc}") from exc
|
||||
|
||||
# -- internals ----------------------------------------------------------
|
||||
|
||||
def _selectable(self) -> sa.Subquery:
|
||||
if self._table is not None:
|
||||
return sa.select(self._table).subquery("source")
|
||||
if self._query:
|
||||
return _text_subquery(self._query)
|
||||
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:
|
||||
by_name = {c.name: c for c in self._table.columns}
|
||||
return [SourceColumn(n, _sa_type_to_kind(by_name[n].type) if n in by_name else "string") for n in names]
|
||||
return [SourceColumn(n, infer_type(pd.Series([r.get(n) for r in rows], dtype=object))) for n in names]
|
||||
|
||||
@contextmanager
|
||||
def _reading(self):
|
||||
"""A connection that can't write: read-only mode where the dialect
|
||||
has one, and an unconditional rollback, so not even a SELECT calling
|
||||
a side-effecting function can commit anything. SQL Server has no
|
||||
read-only session mode; the rollback and `SqlSourcePolicy`'s
|
||||
single-SELECT rule cover it."""
|
||||
with self._engine.connect() as conn:
|
||||
dialect = conn.dialect.name
|
||||
if dialect in ("mysql", "mariadb"):
|
||||
conn.exec_driver_sql("SET SESSION TRANSACTION READ ONLY")
|
||||
elif dialect == "postgresql":
|
||||
conn.exec_driver_sql("SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY")
|
||||
elif dialect == "sqlite":
|
||||
conn.exec_driver_sql("PRAGMA query_only = ON")
|
||||
try:
|
||||
yield conn
|
||||
finally:
|
||||
conn.rollback()
|
||||
|
||||
|
||||
def _text_subquery(query: str) -> sa.Subquery:
|
||||
"""Wraps policy-checked SELECT text as a derived table, so SQLAlchemy
|
||||
composes LIMIT/TOP and COUNT(*) for whichever dialect the source speaks."""
|
||||
return sa.select(sa.literal_column("*")).select_from(sa.text(f"({query}) AS source_query")).subquery("source")
|
||||
|
||||
|
||||
def _sa_type_to_kind(sa_type: sa.types.TypeEngine) -> str:
|
||||
try:
|
||||
python_type = sa_type.python_type
|
||||
except (NotImplementedError, AttributeError):
|
||||
return "string"
|
||||
if python_type is bool:
|
||||
return "boolean"
|
||||
if python_type is int:
|
||||
return "integer"
|
||||
if python_type is float:
|
||||
return "float"
|
||||
if python_type is _dt.datetime:
|
||||
return "datetime"
|
||||
if python_type is _dt.date:
|
||||
return "date"
|
||||
return "string"
|
||||
@@ -1,114 +0,0 @@
|
||||
"""What a client-supplied connection or query may reach. The SQL
|
||||
connector is the one place where the client picks what the server connects
|
||||
to, so:
|
||||
|
||||
- dialects are allowlisted (`WEBAPI_SQL_ALLOWED_DIALECTS`); sqlite is off
|
||||
by default because its URL is a path on this server's filesystem;
|
||||
- hosts can be allowlisted (`WEBAPI_SQL_ALLOWED_HOSTS`, comma-separated);
|
||||
- the application's own databases are never a valid source;
|
||||
- custom SQL must be a single SELECT/WITH statement (on top of the
|
||||
read-only connection, not instead of it).
|
||||
"""
|
||||
import os
|
||||
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"
|
||||
_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)
|
||||
class SqlSourcePolicy:
|
||||
allowed_dialects: frozenset[str]
|
||||
allowed_hosts: frozenset[str] | None
|
||||
|
||||
@classmethod
|
||||
def from_env(cls) -> "SqlSourcePolicy":
|
||||
dialects = os.environ.get("WEBAPI_SQL_ALLOWED_DIALECTS", _DEFAULT_DIALECTS)
|
||||
hosts = os.environ.get("WEBAPI_SQL_ALLOWED_HOSTS")
|
||||
return cls(
|
||||
allowed_dialects=frozenset(d.strip().lower() for d in dialects.split(",") if d.strip()),
|
||||
allowed_hosts=frozenset(h.strip().lower() for h in hosts.split(",") if h.strip()) if hosts else None,
|
||||
)
|
||||
|
||||
def check_url(self, connection: "str | URL") -> URL:
|
||||
try:
|
||||
url = connection if isinstance(connection, URL) else make_url(connection)
|
||||
except ArgumentError as 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"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"el servidor {url.host!r} no está entre los permitidos como fuente")
|
||||
if _same_database(url, _own_database_urls()):
|
||||
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, *, 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]:
|
||||
from persistance.settings import settings
|
||||
|
||||
urls = []
|
||||
for raw in (
|
||||
settings.cacu_database_url,
|
||||
settings.cama_database_url,
|
||||
settings.tea_database_url,
|
||||
settings.governance_database_url,
|
||||
):
|
||||
try:
|
||||
urls.append(make_url(raw))
|
||||
except ArgumentError:
|
||||
continue
|
||||
return urls
|
||||
|
||||
|
||||
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 ""))
|
||||
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}
|
||||
@@ -1,119 +0,0 @@
|
||||
"""Connectors whose rows fit in one pandas DataFrame (CSV, Excel, JSON,
|
||||
PDF, EDF, documents): they only have to build the DataFrame."""
|
||||
|
||||
import datetime as _dt
|
||||
import math
|
||||
import re
|
||||
from abc import abstractmethod
|
||||
from typing import Any, ClassVar, Iterator
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from webapi.imports.connectors.base import Connector, PreviewResult, SourceColumn, decode_file
|
||||
|
||||
|
||||
class DataFrameConnector(Connector):
|
||||
@abstractmethod
|
||||
def _dataframe(self) -> pd.DataFrame: ...
|
||||
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult:
|
||||
df = self._dataframe()
|
||||
return PreviewResult(
|
||||
columns=columns_from_dataframe(df),
|
||||
sample_rows=rows_from_dataframe(df.head(limit)),
|
||||
total_rows=len(df),
|
||||
)
|
||||
|
||||
def read_rows(self, column_mapping: dict[str, str]) -> Iterator[dict[str, Any]]:
|
||||
for row in rows_from_dataframe(self._dataframe()):
|
||||
yield {target: row.get(source) for source, target in column_mapping.items()}
|
||||
|
||||
|
||||
class FileConnector(DataFrameConnector):
|
||||
"""An uploaded file. Subclasses implement `__init__(raw, **options)`
|
||||
and list the keyword options a client may pass in `option_names`."""
|
||||
|
||||
option_names: ClassVar[tuple[str, ...]] = ()
|
||||
|
||||
@classmethod
|
||||
def from_bytes(cls, raw: bytes, options: dict[str, Any] | None = None) -> "FileConnector":
|
||||
options = {k: v for k, v in (options or {}).items() if k in cls.option_names and v not in (None, "")}
|
||||
return cls(raw, **options)
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "FileConnector":
|
||||
return cls.from_bytes(decode_file(payload), payload.get("options") or {})
|
||||
|
||||
|
||||
def columns_from_dataframe(df: pd.DataFrame) -> list[SourceColumn]:
|
||||
return [SourceColumn(name=str(name), inferred_type=infer_type(df[name])) for name in df.columns]
|
||||
|
||||
|
||||
_INT_RE = re.compile(r"^[+-]?\d+$")
|
||||
_FLOAT_RE = re.compile(r"^[+-]?(\d+\.\d*|\.\d+|\d+)([eE][+-]?\d+)?$")
|
||||
_DATE_RE = re.compile(r"^(\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4})$")
|
||||
_DATETIME_RE = re.compile(r"^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2})?")
|
||||
_BOOL_VALUES = {"true", "false", "si", "sí", "no", "verdadero", "falso"}
|
||||
|
||||
|
||||
def infer_type(series: "pd.Series") -> str:
|
||||
"""Display hint for the UI only; values are never converted here."""
|
||||
kind = series.dtype.kind
|
||||
if kind in ("i", "u"):
|
||||
return "integer"
|
||||
if kind == "f":
|
||||
return "float"
|
||||
if kind == "b":
|
||||
return "boolean"
|
||||
if kind == "M":
|
||||
return "datetime"
|
||||
values = [v for v in series.head(500).tolist() if v is not None and not (isinstance(v, float) and math.isnan(v))]
|
||||
if not values:
|
||||
return "string"
|
||||
return _infer_from_values(values)
|
||||
|
||||
|
||||
def _infer_from_values(values: list[Any]) -> str:
|
||||
if all(isinstance(v, bool) for v in values):
|
||||
return "boolean"
|
||||
if all(isinstance(v, int) and not isinstance(v, bool) for v in values):
|
||||
return "integer"
|
||||
if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in values):
|
||||
return "float"
|
||||
if all(isinstance(v, _dt.datetime) for v in values):
|
||||
return "datetime"
|
||||
if all(isinstance(v, _dt.date) for v in values):
|
||||
return "date"
|
||||
if all(isinstance(v, (bytes, bytearray)) for v in values):
|
||||
return "binary"
|
||||
if not all(isinstance(v, str) for v in values):
|
||||
return "string"
|
||||
texts = [v.strip() for v in values]
|
||||
# A leading zero ("01000", "007") means the value is a code, not a number.
|
||||
if all(_INT_RE.match(t) for t in texts) and not any(len(t.lstrip("+-")) > 1 and t.lstrip("+-").startswith("0") for t in texts):
|
||||
return "integer"
|
||||
if all(_FLOAT_RE.match(t) for t in texts) and any("." in t or "e" in t.lower() for t in texts):
|
||||
return "float"
|
||||
if all(_DATETIME_RE.match(t) for t in texts):
|
||||
return "datetime"
|
||||
if all(_DATE_RE.match(t) for t in texts):
|
||||
return "date"
|
||||
if all(t.lower() in _BOOL_VALUES for t in texts):
|
||||
return "boolean"
|
||||
return "string"
|
||||
|
||||
|
||||
def rows_from_dataframe(df: pd.DataFrame) -> list[dict[str, Any]]:
|
||||
return [{key: clean_value(value) for key, value in row.items()} for row in df.to_dict(orient="records")]
|
||||
|
||||
|
||||
def clean_value(value: Any) -> Any:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return None
|
||||
if value is pd.NaT:
|
||||
return None
|
||||
if hasattr(value, "to_pydatetime"): # pandas.Timestamp
|
||||
return value.to_pydatetime()
|
||||
return value
|
||||
@@ -1,156 +0,0 @@
|
||||
"""Auto-match suggestions for the column-mapping UI, based on `rapidfuzz`."""
|
||||
|
||||
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"},
|
||||
"pac_codigo_postal": {"codigo_postal", "cod_postal", "cp", "c_p", "zip", "zip_code"},
|
||||
"pac_dependencia": {"dependencia", "tipo_derechohabiente", "derechohabiencia", "afiliacion"},
|
||||
"pac_parentesco": {"parentesco", "relacion"},
|
||||
"ord_numero_hospital": {"folio", "folio_orden", "numero_orden", "no_orden", "orden", "num_orden"},
|
||||
"ord_tipo_estudio": {"estudio", "tipo_estudio", "estudio_solicitado"},
|
||||
"ord_medico_solicitante": {"medico", "medico_solicitante", "solicitante"},
|
||||
"nm_id_hospital": {"folio_nota", "id_nota", "numero_nota", "no_nota"},
|
||||
"nm_fecha": {"fecha", "fecha_consulta", "fecha_nota"},
|
||||
"nm_especialidad": {"servicio", "especialidad"},
|
||||
"nm_motivo_consulta": {"motivo", "motivo_consulta"},
|
||||
"nm_diagnostico_texto": {"dx", "diagnostico"},
|
||||
"nm_masa_corporal": {"peso", "peso_kg", "peso_(kg)"},
|
||||
"nm_talla": {"talla", "talla_m", "talla_(m)", "estatura"},
|
||||
"nm_medico_tratante": {"medico", "medico_tratante"},
|
||||
"bx_cin_grado": {"grado_cin", "cin", "resultado_histopatologico", "diagnostico_histopatologico"},
|
||||
"bh_fecha": {"fecha", "tomada", "fecha_toma", "fecha_muestra"},
|
||||
}
|
||||
|
||||
# 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").
|
||||
_STOPWORDS = {"de", "del", "la", "el", "los", "las", "en", "por", "para", "con"}
|
||||
_NEAR_WORD = 0.8
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MatchSuggestion:
|
||||
source_column: str
|
||||
target_field: str | None
|
||||
confidence: float
|
||||
reason: str # "exact" | "normalized" | "synonym" | "unprefixed" | "fuzzy" | "none"
|
||||
|
||||
|
||||
def _normalize(name: str) -> str:
|
||||
without_accents = "".join(
|
||||
c for c in unicodedata.normalize("NFKD", name) if not unicodedata.combining(c)
|
||||
)
|
||||
cleaned = without_accents.strip().lower()
|
||||
for separator in ("-", ".", "/"):
|
||||
cleaned = cleaned.replace(separator, " ")
|
||||
return "_".join(cleaned.split())
|
||||
|
||||
|
||||
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]
|
||||
|
||||
|
||||
def _word_score(source_words: list[str], target_words: list[str]) -> float:
|
||||
"""Word-level similarity: each source word scores its best match among
|
||||
the target words (exact 1.0, near-miss spellings ≥0.8, else 0), divided
|
||||
by the longer word list. Comparing words rather than whole strings
|
||||
rewards shared meaning ("estudio solicitado" ~ "tipo_estudio") instead of
|
||||
shared suffixes ("estudio_solicitado" ~ "medico_solicitante")."""
|
||||
if not source_words or not target_words:
|
||||
return 0.0
|
||||
total = 0.0
|
||||
for word in source_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))
|
||||
|
||||
|
||||
def _unprefixed(target: str) -> str:
|
||||
"""`pac_sexo` -> `sexo`: Core's field names carry a table prefix that
|
||||
source systems never use."""
|
||||
head, _, rest = target.partition("_")
|
||||
return rest if rest else head
|
||||
|
||||
|
||||
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.
|
||||
|
||||
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))
|
||||
|
||||
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]
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
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,21 +0,0 @@
|
||||
"""Common base for every import schema."""
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
from webapi.imports.schemas.coercion import Catalog
|
||||
|
||||
|
||||
class ImportSchema(BaseModel):
|
||||
"""Shared pydantic config for all import schemas.
|
||||
|
||||
`coerce_numbers_to_str`: a numeric source column (SQL INT, Excel number,
|
||||
JSON number) feeding a text field is legitimate: expediente `12345` is "12345".
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(coerce_numbers_to_str=True)
|
||||
|
||||
@classmethod
|
||||
def catalog_for(cls, field_name: str) -> Catalog | None:
|
||||
field = cls.model_fields.get(field_name)
|
||||
if field is None:
|
||||
return None
|
||||
return next((m for m in field.metadata if isinstance(m, Catalog)), None)
|
||||
@@ -1,34 +0,0 @@
|
||||
"""Import schema for `core.cacu.models.BiometriaHematica` (full blood count panel)."""
|
||||
from typing import Optional
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId
|
||||
|
||||
|
||||
class BiometriaHematicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
bh_fecha: FlexDate = None
|
||||
|
||||
eritrocitos_mill_ul: Optional[float] = None
|
||||
hemoglobina_g_dl: Optional[float] = None
|
||||
hematocrito_pct: Optional[float] = None
|
||||
vcm_fl: Optional[float] = None
|
||||
hcm_pg: Optional[float] = None
|
||||
chcm_g_dl: Optional[float] = None
|
||||
rdw_pct: Optional[float] = None
|
||||
leucocitos_mil_ul: Optional[float] = None
|
||||
|
||||
linfocitos_pct: Optional[float] = None
|
||||
monocitos_pct: Optional[float] = None
|
||||
basofilos_pct: Optional[float] = None
|
||||
eosinofilos_pct: Optional[float] = None
|
||||
neutrofilos_pct: Optional[float] = None
|
||||
mielocitos_pct: Optional[float] = None
|
||||
metamielocitos_pct: Optional[float] = None
|
||||
neutrofilos_banda_pct: Optional[float] = None
|
||||
neutrofilos_segmentados_pct: Optional[float] = None
|
||||
|
||||
plaquetas_mil_ul: Optional[float] = None
|
||||
vpm_fl: Optional[float] = None
|
||||
@@ -1,21 +0,0 @@
|
||||
"""Import schema for `core.cacu.models.BiopsiaCervical`."""
|
||||
from typing import Optional
|
||||
|
||||
from core.cacu.enums import GRADO_CIN_ALIAS, GradoCIN
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
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: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
cit_id: Optional[int] = 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
|
||||
@@ -1,38 +0,0 @@
|
||||
"""Import schema for `core.cacu.models.CitologiaCervical`.
|
||||
|
||||
`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 typing import Optional
|
||||
|
||||
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, 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: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = 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
|
||||
cit_condiciones_ginecoobs: Optional[str] = None
|
||||
cit_exploracion: Optional[str] = None
|
||||
cit_dx_lesion: Optional[str] = None
|
||||
cit_celulas_glandulares: Optional[str] = None
|
||||
cit_carcinoma_invasor: Optional[str] = None
|
||||
cit_celulas_escamosas: CatalogValue(_CELULAS_ESCAMOSAS_CATALOG) = None
|
||||
cit_vph_pdf_blob: Optional[bytes] = None
|
||||
cit_vph_ocr_confianza: Optional[float] = None
|
||||
cit_vph_resultado: CatalogValue(_RESULTADO_VPH_CATALOG) = None
|
||||
cit_vph_genotipo_16: Optional[int] = None
|
||||
cit_vph_genotipo_18: Optional[int] = None
|
||||
@@ -1,29 +0,0 @@
|
||||
"""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,38 +0,0 @@
|
||||
"""Import schema for `core.cacu.models.NotaMedica`."""
|
||||
from typing import Optional
|
||||
|
||||
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, FlexDate, RequiredHospitalId, RequiredStr
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
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: FlexDate = None
|
||||
nm_medico_tratante: Optional[str] = None
|
||||
nm_motivo_consulta: Optional[str] = None
|
||||
nm_interrogatorio: Optional[str] = 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_pronostico: Optional[str] = None
|
||||
nm_observaciones: Optional[str] = None
|
||||
nm_masa_corporal: Optional[float] = None
|
||||
nm_talla: Optional[float] = None
|
||||
nm_imc_visita: Optional[float] = None
|
||||
nm_frecuencia_cardiaca: Optional[int] = None
|
||||
nm_frecuencia_respiratoria: Optional[int] = None
|
||||
nm_presion_arterial_sistolica: Optional[int] = None
|
||||
nm_presion_arterial_diastolica: Optional[int] = None
|
||||
nm_temperatura: Optional[float] = None
|
||||
@@ -1,26 +0,0 @@
|
||||
"""Import schema for `core.cacu.models.OrdenesEstudio` (one order per row, one study type each)."""
|
||||
from typing import Optional
|
||||
|
||||
from core.cacu.enums import TIPO_ESTUDIO_ALIAS, TipoEstudio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
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: RequiredHospitalId
|
||||
ord_numero_hospital: int
|
||||
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = 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
|
||||
@@ -1,30 +0,0 @@
|
||||
"""Import schema for `core.cacu.models.Paciente`."""
|
||||
from typing import Optional
|
||||
|
||||
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,
|
||||
PostalCode,
|
||||
RequiredDate,
|
||||
RequiredHospitalId,
|
||||
)
|
||||
|
||||
# Dependencia/Parentesco: Core marks both catalogs as tentative.
|
||||
_DEPENDENCIA_CATALOG = Catalog(Dependencia, DEPENDENCIA_ALIAS, strict=False)
|
||||
_PARENTESCO_CATALOG = Catalog(Parentesco, PARENTESCO_ALIAS, strict=False)
|
||||
_SEXO_BIOLOGICO_CATALOG = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
|
||||
|
||||
class PacienteImportSchema(ImportSchema):
|
||||
# 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: RequiredDate
|
||||
pac_codigo_postal: PostalCode = None
|
||||
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
|
||||
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
|
||||
@@ -1,34 +0,0 @@
|
||||
"""Import schema for `core.cama.models.BiometriaHematica` (full blood count panel)."""
|
||||
from typing import Optional
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId
|
||||
|
||||
|
||||
class BiometriaHematicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
bh_fecha: FlexDate = None
|
||||
|
||||
eritrocitos_mill_ul: Optional[float] = None
|
||||
hemoglobina_g_dl: Optional[float] = None
|
||||
hematocrito_pct: Optional[float] = None
|
||||
vcm_fl: Optional[float] = None
|
||||
hcm_pg: Optional[float] = None
|
||||
chcm_g_dl: Optional[float] = None
|
||||
rdw_pct: Optional[float] = None
|
||||
leucocitos_mil_ul: Optional[float] = None
|
||||
|
||||
linfocitos_pct: Optional[float] = None
|
||||
monocitos_pct: Optional[float] = None
|
||||
basofilos_pct: Optional[float] = None
|
||||
eosinofilos_pct: Optional[float] = None
|
||||
neutrofilos_pct: Optional[float] = None
|
||||
mielocitos_pct: Optional[float] = None
|
||||
metamielocitos_pct: Optional[float] = None
|
||||
neutrofilos_banda_pct: Optional[float] = None
|
||||
neutrofilos_segmentados_pct: Optional[float] = None
|
||||
|
||||
plaquetas_mil_ul: Optional[float] = None
|
||||
vpm_fl: Optional[float] = None
|
||||
@@ -1,21 +0,0 @@
|
||||
"""Import schema for `core.cama.models.BiopsiaMama`."""
|
||||
from typing import Optional
|
||||
|
||||
from core.cama.enums import GradoHistologicoMama
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
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: RequiredHospitalId
|
||||
ord_id: Optional[int] = None
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
mast_id: Optional[int] = 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
|
||||
@@ -1,23 +0,0 @@
|
||||
"""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,24 +0,0 @@
|
||||
"""Import schema for `core.cama.models.Mastografia`."""
|
||||
from typing import Optional
|
||||
|
||||
from core.cama.enums import BIRADS, BIRADS_ALIAS
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
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: RequiredHospitalId
|
||||
ord_id: Optional[int] = None
|
||||
ord_numero_hospital: Optional[int] = 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
|
||||
@@ -1,38 +0,0 @@
|
||||
"""Import schema for `core.cama.models.NotaMedica`."""
|
||||
from typing import Optional
|
||||
|
||||
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, FlexDate, RequiredHospitalId, RequiredStr
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
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: FlexDate = None
|
||||
nm_medico_tratante: Optional[str] = None
|
||||
nm_motivo_consulta: Optional[str] = None
|
||||
nm_interrogatorio: Optional[str] = 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_pronostico: Optional[str] = None
|
||||
nm_observaciones: Optional[str] = None
|
||||
nm_masa_corporal: Optional[float] = None
|
||||
nm_talla: Optional[float] = None
|
||||
nm_imc_visita: Optional[float] = None
|
||||
nm_frecuencia_cardiaca: Optional[int] = None
|
||||
nm_frecuencia_respiratoria: Optional[int] = None
|
||||
nm_presion_arterial_sistolica: Optional[int] = None
|
||||
nm_presion_arterial_diastolica: Optional[int] = None
|
||||
nm_temperatura: Optional[float] = None
|
||||
@@ -1,26 +0,0 @@
|
||||
"""Import schema for `core.cama.models.OrdenesEstudio` (one order per row, one study type each)."""
|
||||
from typing import Optional
|
||||
|
||||
from core.cama.enums import TIPO_ESTUDIO_ALIAS, TipoEstudio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
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: RequiredHospitalId
|
||||
ord_numero_hospital: int
|
||||
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = 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
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user