add import audit trail, live indicator recompute, reportes endpoints; production hardening
This commit is contained in:
+2
-1
@@ -5,5 +5,6 @@ __pycache__/
|
||||
.coverage
|
||||
*.egg-info/
|
||||
.env
|
||||
uv.lock
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
|
||||
+9
-9
@@ -8,7 +8,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
tesseract-ocr tesseract-ocr-spa \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN pip install --no-cache-dir uv
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.7.9 /uv /uvx /bin/
|
||||
|
||||
WORKDIR /app
|
||||
COPY Core/ Core/
|
||||
@@ -19,19 +19,19 @@ COPY indicadores_kit/ indicadores_kit/
|
||||
COPY Orquestacion/ Orquestacion/
|
||||
COPY WebApi/ WebApi/
|
||||
|
||||
# Migrations need the MySQL/PostgreSQL drivers when *_DATABASE_URL points there.
|
||||
RUN cd Persistance && uv sync --no-dev --extra drivers
|
||||
# Drivers for the SQL import sources (MySQL/MariaDB, PostgreSQL, SQL Server).
|
||||
RUN cd WebApi && uv sync --no-dev --extra sql-drivers
|
||||
# The indicator pipeline (staging -> facts -> reports), run with
|
||||
# `python -m orquestacion ciclo <proyecto> ...` after an import.
|
||||
RUN cd Orquestacion && uv sync --no-dev --extra drivers
|
||||
# One environment for the API, the migrations and the indicator cycle. The SQL
|
||||
# drivers serve both the import sources and *_DATABASE_URL on MySQL/PostgreSQL/SQL Server.
|
||||
RUN cd WebApi && uv sync --locked --no-dev --extra sql-drivers
|
||||
|
||||
ENV CACU_DATABASE_URL=sqlite:////data/cacu.db
|
||||
ENV CAMA_DATABASE_URL=sqlite:////data/cama.db
|
||||
ENV TEA_DATABASE_URL=sqlite:////data/tea.db
|
||||
ENV GOVERNANCE_DATABASE_URL=sqlite:////data/governance.db
|
||||
ENV MODELS_ARTIFACT_ROOT=/data/artifacts
|
||||
# MLflow model registry and artifacts, next to the databases so backups cover them.
|
||||
ENV MLFLOW_TRACKING_URI=sqlite:////data/mlflow.db
|
||||
ENV MLFLOW_ARTIFACT_ROOT=/data/mlflow-artefactos
|
||||
# No usage telemetry from MLflow: the server runs on a closed network.
|
||||
ENV MLFLOW_DISABLE_TELEMETRY=true DO_NOT_TRACK=true
|
||||
# Aggregate import log and the live indicator queue (webapi.indicadores_vivos).
|
||||
ENV WEBAPI_REPORT_DIR=/data/reportes
|
||||
ENV INDICADORES_DIR=/data/indicadores
|
||||
|
||||
@@ -1,385 +1,98 @@
|
||||
# WebApi
|
||||
|
||||
API REST en Flask para CaCu, CaMa y TEA. Lee datos con `../Persistance`,
|
||||
sirve figuras de indicadores con `../indicadores_kit` y llama a los modelos
|
||||
de `../models`.
|
||||
API REST de ISSSTELEON en Flask. Importa datos clínicos de varias fuentes a
|
||||
las bases de CaCu, CaMa y TEA, publica los indicadores ya calculados, guarda
|
||||
una bitácora agregada de cada importación y expone la gobernanza de modelos
|
||||
y de OCR. Usa `Persistance` para las bases, `Extraction` para documentos y
|
||||
EEG, `indicadores_kit` para leer los indicadores y `orquestacion` para
|
||||
recalcularlos.
|
||||
|
||||
## Estructura
|
||||
|
||||
```
|
||||
WebApi/
|
||||
├── main.py crea la app y la levanta en 0.0.0.0:5000
|
||||
├── webapi/
|
||||
│ ├── __init__.py create_app(): /health y los tres blueprints
|
||||
│ ├── indicadores.py rutas de indicadores, datos y figuras, comunes a los tres proyectos
|
||||
│ └── blueprints/
|
||||
│ ├── cacu.py cacu_bp, prefijo /cacu
|
||||
│ ├── cama.py cama_bp, prefijo /cama
|
||||
│ └── tea.py tea_bp, prefijo /tea
|
||||
├── tests/
|
||||
│ ├── conftest.py siembra una base de CaCu o CaMa con los fixtures del kit
|
||||
│ ├── test_app.py /health y rutas de CaCu, con SQLite temporal
|
||||
│ ├── test_cacu.py indicadores de CaCu, con SQLite temporal
|
||||
│ ├── test_cama.py indicadores de CaMa, con SQLite temporal
|
||||
│ └── test_tea.py rutas de TEA, con SQLite temporal y sus 5 indicadores
|
||||
├── Dockerfile imagen; el contexto es la raíz del repo padre
|
||||
└── docker-entrypoint.sh migra las tres bases y arranca main.py
|
||||
webapi/
|
||||
├── __init__.py create_app(): blueprints, límites de carga, CORS, /health y /api
|
||||
├── blueprints/
|
||||
│ ├── imports.py /imports: fuentes, vista previa, validación y carga
|
||||
│ ├── data.py /data: lectura paginada de cada tabla importable
|
||||
│ ├── cacu.py, cama.py, tea.py /<dominio>/indicadores
|
||||
│ ├── reportes.py /reportes: bitácora de importaciones y estado del recálculo
|
||||
│ └── governance.py /governance: versiones de modelos y cola de OCR
|
||||
├── imports/
|
||||
│ ├── connectors/ una clase por tipo de fuente (@register_connector)
|
||||
│ ├── schemas/ un esquema pydantic por tabla destino; registry.py los enlista
|
||||
│ ├── mapping/ sugerencia de mapeo de columnas
|
||||
│ ├── services/ validación, combinación de fuentes, enlace de llaves y escritura
|
||||
│ └── audit.py bitácora agregada (sin datos de pacientes)
|
||||
├── indicadores.py rutas de indicadores (del equipo de indicadores)
|
||||
├── indicadores_vivos.py cola y servicio que recalcula indicadores tras cada carga
|
||||
└── seguimiento.py lista de seguimiento por paciente (solo con DEV_REVISION)
|
||||
```
|
||||
|
||||
Un blueprint por dominio, con rutas de ejemplo (paciente y `predict`).
|
||||
Los tres sirven además los indicadores del kit: cada blueprint llama a
|
||||
`registrar_indicadores(blueprint, proyecto, get_<proyecto>_session)` de
|
||||
`webapi/indicadores.py`, que agrega el catálogo, los periodos, los datos,
|
||||
los metadatos y las figuras.
|
||||
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`.
|
||||
|
||||
## Flujo de datos
|
||||
## Rutas
|
||||
|
||||
Ruta de lectura simple (`/cacu/pacientes/<id>`):
|
||||
`GET /api` lista todas las rutas con su descripción.
|
||||
|
||||
```
|
||||
request -> blueprint -> repositorio de Persistance -> modelo -> JSON
|
||||
```
|
||||
| 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 |
|
||||
|
||||
El repositorio abre y cierra su propia sesión.
|
||||
Los errores de la solicitud se responden con `{"error": "..."}` y código 400
|
||||
(404 si no existe el recurso).
|
||||
|
||||
Ruta de figura (la misma para `/cacu`, `/cama` y `/tea`):
|
||||
## Variables de entorno
|
||||
|
||||
```
|
||||
GET /<proyecto>/indicadores/<id>/figuras/<figura>?periodos=&tema=
|
||||
│
|
||||
├─ valida indicador y figura (404 si no existen; figuras_de(medida))
|
||||
├─ valida tema y periodos (400 si están mal)
|
||||
├─ sesion = get_<proyecto>_session()
|
||||
├─ sin periodos: periodos_por_defecto(...): los del primer tipo que publica;
|
||||
│ en una figura de un solo periodo (donas, barras), solo el más reciente
|
||||
│ con algo que dibujar
|
||||
├─ figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema, filtros=filtros)
|
||||
│ indicadores_kit (serving/contratos.py):
|
||||
│ 1. el reporte vigente de cada periodo, de la vista v_measure_report_vigente
|
||||
│ 2. las celdas del total, de la vista de su contrato: v_c1, v_c2 o v_c3r
|
||||
│ (con ?filtro=, la misma consulta con solo esas unidades, no la vista)
|
||||
│ 3. etiquetas, colores y pie, de def_parametro; y arma el JSON de Plotly
|
||||
└─ finally: sesion.close()
|
||||
│
|
||||
v
|
||||
Response(texto, mimetype="application/json")
|
||||
```
|
||||
| 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 |
|
||||
|
||||
Las rutas de datos, periodos y metadatos siguen los mismos pasos, con
|
||||
`datos_de`, `periodos_de` y `metadatos_de` de
|
||||
`indicadores_kit.serving.datos` en lugar de `figura_json`.
|
||||
## Ejecución
|
||||
|
||||
Ninguna ruta lee `measure_report_unidad` directamente ni calcula: los números
|
||||
ya salen agregados y suprimidos de las vistas. Las vistas las crea la arista
|
||||
`vistas` de `Orquestacion` (`indicadores_kit/esquema.py: ddl_de_vistas`), no la
|
||||
migración: una base solo migrada no las tiene, y una base calculada antes de
|
||||
MD-19 no tiene unidades. En los dos casos hay que correr el ciclo (camino B).
|
||||
|
||||
La sesión se cierra siempre, en `finally`. Un `KeyError` interno no se
|
||||
convierte en 404: sube como error 500. Un `LookupError` (periodo sin
|
||||
reporte) sí da 404.
|
||||
|
||||
## Uso
|
||||
|
||||
### Instalar y probar
|
||||
En local (las migraciones se aplican a mano):
|
||||
|
||||
```bash
|
||||
cd WebApi
|
||||
uv sync
|
||||
uv run pytest
|
||||
uv sync --extra sql-drivers
|
||||
for d in cacu cama tea governance; do
|
||||
uv run alembic -c ../Persistance/persistance/$d/alembic.ini upgrade head
|
||||
done
|
||||
uv run python main.py # http://localhost:5050
|
||||
uv run python -m webapi.indicadores_vivos # recálculo de indicadores, en otra terminal
|
||||
```
|
||||
|
||||
`WebApi` depende de `../Persistance`, `../models` y `../indicadores_kit`
|
||||
(rutas editables en `pyproject.toml`). Requiere Python 3.12 o más.
|
||||
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`.
|
||||
|
||||
### Variables de entorno
|
||||
|
||||
Las lee `Persistance` (ver su README). Por defecto cada base es un archivo
|
||||
SQLite **relativo al directorio actual**.
|
||||
|
||||
| Variable | Valor por defecto |
|
||||
| --- | --- |
|
||||
| `CACU_DATABASE_URL` | `sqlite:///cacu.db` |
|
||||
| `CAMA_DATABASE_URL` | `sqlite:///cama.db` |
|
||||
| `TEA_DATABASE_URL` | `sqlite:///tea.db` |
|
||||
| `DEV_REVISION` | sin valor. La define el despliegue de DEV (`deploy/dev/compose.yml`); con ella se registra `/cacu/seguimiento` |
|
||||
| `SEGUIMIENTO_SAL` | `dev-simulado`: la sal del seudónimo de `/cacu/seguimiento` |
|
||||
|
||||
Atención: con el valor por defecto, `alembic` en `Persistance/` escribe
|
||||
`Persistance/<proyecto>.db` y la API en `WebApi/` abre `WebApi/<proyecto>.db`.
|
||||
Son dos bases distintas. La API crea la segunda vacía y falla con
|
||||
`no such table: measure_report`. Use siempre una ruta absoluta
|
||||
(`sqlite:////` con cuatro barras) y la misma en todos los pasos, en cada
|
||||
proyecto que vaya a servir:
|
||||
## Pruebas
|
||||
|
||||
```bash
|
||||
export TEA_DATABASE_URL=sqlite:////ruta/absoluta/tea.db
|
||||
export CACU_DATABASE_URL=sqlite:////ruta/absoluta/cacu.db
|
||||
export CAMA_DATABASE_URL=sqlite:////ruta/absoluta/cama.db
|
||||
uv sync --extra sql-drivers
|
||||
uv run pytest -q
|
||||
```
|
||||
|
||||
### Correr en local
|
||||
|
||||
La API solo lee. Antes de pedir una figura, la base de TEA necesita las
|
||||
tablas, los datos y los reportes calculados. Hay dos caminos.
|
||||
|
||||
**A. Base de demostración (datos sintéticos del kit).** Una sola orden
|
||||
crea las tablas, llena las tablas fuente con datos sintéticos y calcula los 5
|
||||
indicadores en `2025-S1` y `2025-S2`. Necesita un archivo nuevo o vacío; no corra
|
||||
`alembic` antes en ese archivo.
|
||||
|
||||
```bash
|
||||
cd WebApi
|
||||
export TEA_DATABASE_URL=sqlite:////ruta/absoluta/tea_demo.db
|
||||
uv run python -c "import os; from sqlalchemy import create_engine; from indicadores_kit.tea.fixtures import base_de_prueba; base_de_prueba(create_engine(os.environ['TEA_DATABASE_URL']))"
|
||||
uv run python main.py # http://localhost:5000
|
||||
```
|
||||
|
||||
**B. Datos reales.** La base del dominio (tablas fuente, plata, reportes y
|
||||
vistas) la monta `Orquestacion`, con la misma `<PROYECTO>_DATABASE_URL`:
|
||||
|
||||
```bash
|
||||
cd Orquestacion
|
||||
# ... con las tablas fuente de TEA ya llenas (pacientes, evaluacion_psicologica, eeg_estudio, ...)
|
||||
TEA_DATABASE_URL=sqlite:////ruta/tea.db uv run --frozen python -m orquestacion ciclo tea --desde 2024 --hasta 2026
|
||||
cd ../WebApi
|
||||
TEA_DATABASE_URL=sqlite:////ruta/tea.db uv run python main.py # http://localhost:5000
|
||||
```
|
||||
|
||||
Volver a correr el ciclo no duplica cargas ni reportes. CaCu y CaMa, igual
|
||||
(`ciclo cacu`, `ciclo cama`): el ciclo registra los semestres y los meses
|
||||
que publica cada indicador. La secuencia y sus pruebas están en
|
||||
`Orquestacion/` (`tests/test_ciclo.py`).
|
||||
|
||||
### Correr con Docker
|
||||
|
||||
Desde la raíz del repo padre:
|
||||
|
||||
```bash
|
||||
docker compose up --build
|
||||
```
|
||||
|
||||
`docker-compose.yml` construye `WebApi/Dockerfile` con la raíz como
|
||||
contexto, publica el puerto 5000 y guarda las bases en el volumen `webapi_data` (`/data/cacu.db`,
|
||||
`/data/cama.db`, `/data/tea.db`). `docker-entrypoint.sh` corre
|
||||
`alembic upgrade head` en los tres dominios y después `main.py`. Las
|
||||
tablas quedan vacías: cargue y calcule como en el camino B. También
|
||||
levanta `webapp` en el puerto 4200.
|
||||
|
||||
El despliegue de desarrollo del servidor no usa este archivo sino
|
||||
`deploy/dev/` (proyecto `isssteleon-dev`): `webapi` en el puerto 9603 y
|
||||
`webapp` en el 9604, con las bases en el volumen `isssteleon-dev_datos`
|
||||
montado de solo lectura en `/data`. Ahí no corre ningún cálculo: sirve un
|
||||
dataset ya generado, fijado a la revisión `DATASET_REVISION` de
|
||||
`deploy/dev/control.py`, y antes de arrancar comprueba que los gitlinks de
|
||||
WebApp, WebApi, indicadores_kit y models sean los de esa revisión. Si alguno
|
||||
cambia, el despliegue se bloquea hasta regenerar el dataset (ver
|
||||
`deploy/dev/README.md`).
|
||||
|
||||
### Rutas
|
||||
|
||||
| Método | Ruta | Respuesta |
|
||||
| --- | --- | --- |
|
||||
| GET | `/health` | 200 `{"status": "ok"}` |
|
||||
| GET | `/cacu/pacientes/<int:pac_id>` | 200 paciente; 404 `{"error": "not found"}` |
|
||||
| POST | `/cacu/predict` | 200 `{"prediction": ...}`; 501 si el modelo no está listo |
|
||||
| GET | `/cama/pacientes/<int:pac_id>` | igual que CaCu |
|
||||
| POST | `/cama/predict` | igual que CaCu |
|
||||
| GET | `/tea/pacientes/<int:pac_id>` | 200 paciente; 404 `{"error": "not found"}` |
|
||||
| POST | `/tea/predict` | igual que CaCu |
|
||||
| GET | `/<proyecto>/indicadores` | 200 lista de indicadores (`proyecto` = `cacu`, `cama` o `tea`), cada uno con sus `filtros` y sus valores |
|
||||
| GET | `/<proyecto>/indicadores/<indicador>/periodos` | 200 periodos con reporte; 404 |
|
||||
| GET | `/<proyecto>/indicadores/<indicador>/datos` | 200 los números, sin figura; 400 o 404 |
|
||||
| GET | `/<proyecto>/indicadores/<indicador>/metadatos` | 200 ficha metodológica; 404 |
|
||||
| GET | `/<proyecto>/indicadores/<indicador>/figuras/<figura>` | 200 JSON de la figura; 400 o 404 |
|
||||
| GET | `/cacu/seguimiento?corte=&meses=&estatus=&page=&page_size=` | **solo en DEV**: la lista de seguimiento (datos simulados); 400 o 404 |
|
||||
|
||||
Las rutas de `pac_id` solo aceptan enteros. Con otro valor (`/tea/pacientes/abc`)
|
||||
Flask no encuentra la ruta y da 404.
|
||||
|
||||
Ejemplos:
|
||||
|
||||
```bash
|
||||
curl localhost:5000/health
|
||||
curl localhost:5000/tea/pacientes/1
|
||||
curl localhost:5000/tea/indicadores
|
||||
curl "localhost:5000/tea/indicadores/M21_diagnosticados_con_eeg/figuras/fig_c1_grupos"
|
||||
curl "localhost:5000/tea/indicadores/M21_diagnosticados_con_eeg/figuras/fig_c1_grupos?periodos=2025-S1,2025-S2&tema=oscuro"
|
||||
curl localhost:5000/tea/indicadores/M21_diagnosticados_con_eeg/periodos
|
||||
curl "localhost:5000/tea/indicadores/M21_diagnosticados_con_eeg/datos?periodos=2025-S1,2025-S2"
|
||||
curl localhost:5000/tea/indicadores/M21_diagnosticados_con_eeg/metadatos
|
||||
curl localhost:5000/cacu/indicadores
|
||||
curl localhost:5000/cacu/indicadores/ind1/datos
|
||||
curl "localhost:5000/cacu/indicadores/ind1/figuras/fig_c1_puntos?periodos=2025-01,2025-02,2025-03"
|
||||
curl "localhost:5000/cacu/indicadores/cacu_eu7/figuras/fig_c2_donas?periodos=2025-S1"
|
||||
```
|
||||
|
||||
`/<proyecto>/indicadores` devuelve, por indicador: `id`, `titulo`,
|
||||
`version`, `contrato`, `unidad`, `sentido`, `figuras`, `estratos` y
|
||||
`tipos_periodo` (los que publica la definición en `extension.publicacion`). El
|
||||
`id` es el nombre del archivo TOML (`cacu_eu7`), no el `measure_id` de las
|
||||
tablas (`CACU_EU7`). Los indicadores marcados `oculto` en su TOML no salen en
|
||||
la lista, pero su `id` sigue respondiendo. La lista no dice qué filtros admite
|
||||
cada indicador.
|
||||
|
||||
Las figuras dependen del contrato y de si la definición tiene ficha
|
||||
(`extension.ficha`, `serving/figuras.py: figuras_de`):
|
||||
|
||||
| Contrato | Definición | Figuras | Eje |
|
||||
| --- | --- | --- | --- |
|
||||
| C1 | sin ficha (CaCu `ind1`, `cacu_eu13`; CaMa) | `fig_c1_puntos` | un punto por periodo |
|
||||
| C1 | con ficha (TEA) | `fig_c1_grupos` | una barra por grupo, una serie por periodo |
|
||||
| C2 | con ficha de un solo grupo (los tres proyectos) | `fig_c2_donas`, `fig_c2_barras` | una distribución; sin `periodos`, la del más reciente con datos |
|
||||
| C3r | con ficha (los tres proyectos) | `fig_c3r_caja` | una caja por grupo y periodo |
|
||||
|
||||
Parámetros de la figura:
|
||||
|
||||
- `periodos`: lista separada por comas, todos de un mismo tipo y de un tipo
|
||||
que el indicador publique: `AAAA-S1` o `AAAA-S2` (semestre), `AAAA-MM`
|
||||
(mes), y así los demás de `registry/periodos.py`. Sin el parámetro se
|
||||
usan todos los periodos con reporte del primer tipo que publica la
|
||||
definición.
|
||||
- `tema`: `claro` (por defecto) u `oscuro`.
|
||||
|
||||
Códigos de la figura:
|
||||
|
||||
| Código | Causa |
|
||||
| --- | --- |
|
||||
| 200 | JSON de la figura |
|
||||
| 400 | `tema` desconocido, o `periodos` mal formado: coma al final, tipo que el indicador no publica, tipos mezclados |
|
||||
| 404 | indicador desconocido; figura que no es del contrato del indicador; el indicador no tiene reportes; algún periodo pedido no tiene reporte |
|
||||
| 500 | error interno (por ejemplo un `KeyError`) |
|
||||
|
||||
### Datos, periodos y metadatos
|
||||
|
||||
Para mostrar el número o graficar desde el frontend, sin Plotly. Salen de
|
||||
las mismas filas que las figuras y ya traen la supresión aplicada.
|
||||
|
||||
| Ruta | Qué devuelve |
|
||||
| --- | --- |
|
||||
| `/periodos` | `id`, `version` y `periodos`: por cada periodo con reporte, su `tipo`, sus fechas, su `report_id`, `generado_en` y `fecha_corte` |
|
||||
| `/datos?periodos=&estrato=&filtro=` | `id`, `titulo`, `version`, `contrato`, `unidad`, `tipo_periodo`, `periodos`, `estrato`, `valores_estrato`, `grupos`, `categorias` y `grupos_de_categoria` (vacías salvo en C2), `notas` (el pie), `reportes` con la procedencia de cada periodo y `filas` (una por periodo y grupo, o por categoría en C2); `filtros`, solo si se pidió uno |
|
||||
| `/metadatos` | la ficha, la unidad, los estándares y las reglas que usa el indicador, con su estado; `referencias` (las citas del TOML, p. ej. el lineamiento europeo) y `poblaciones` (el texto de cada población) y `figuras_detalle` (qué muestra cada figura y cómo leerla, del TOML del indicador) |
|
||||
|
||||
`periodos` se pide igual que en la figura. `estrato` es uno de los
|
||||
`estratos` del indicador y solo desglosa un C1 sin ficha; hoy ningún
|
||||
indicador declara estratos, así que todo `?estrato=` da 400. Toda fila de `/datos` trae `periodo`, `grupo`,
|
||||
`estrato` y `suprimido`, y después las columnas de su `contrato`:
|
||||
|
||||
| Contrato | Columnas |
|
||||
| --- | --- |
|
||||
| C1 (proporción) | `numerador`, `denominador`, `valor` (0 a 100), `ic_bajo`, `ic_alto` (Wilson al 95 %), `n_sin_evento`, `n_excluido` |
|
||||
| C2 (distribución) | `categoria`, `n`, `orden` |
|
||||
| C3r (tiempos) | `n`, `mediana`, `q1`, `q3`, `n_sin_evento`, `n_excluido`, `unidad` |
|
||||
|
||||
Una celda suprimida va con `suprimido` en 1 y sus números en `null`. En
|
||||
`reportes`, `periodo_fin` es el primer día que ya no entra en el periodo.
|
||||
|
||||
La forma de estas respuestas es un contrato con el frontend: no se quita
|
||||
ni se renombra un campo; solo se agregan.
|
||||
|
||||
**Filtros** (`?filtro=estrato:valor`, varios separados por coma; MD-19): `/datos`
|
||||
y `/figuras/<f>` dan el mismo contrato, contado solo con las unidades que tienen
|
||||
esos valores de estrato. Se combina con `periodos` y con `estrato` (el desglose).
|
||||
`/datos` agrega la llave `"filtros": {"grupo_edad": "25-34"}`, solo cuando se pidió
|
||||
filtro. La supresión se recalcula sobre las unidades filtradas, con el mismo
|
||||
umbral: un filtro nunca deja ver una celda chica. Un indicador solo se puede
|
||||
filtrar por los estratos que declara en `extension.filtros` de su TOML; hoy
|
||||
ninguno lo hace (`cat_measure_estrato` queda vacía), así que todo `?filtro=` da 400.
|
||||
El único estrato con valores en el catálogo es `grupo_edad`.
|
||||
|
||||
```bash
|
||||
curl "localhost:5000/cacu/indicadores/ind1/datos?periodos=2025-S1&filtro=grupo_edad:25-34"
|
||||
```
|
||||
|
||||
Códigos: 400 si `periodos` está mal formado, `estrato` no es del
|
||||
indicador, o un `filtro` está mal escrito (`grupo_edad`, `:x`, el mismo
|
||||
estrato dos veces), su estrato no es filtro del indicador o su valor no
|
||||
está en el catálogo (`cat_estrato_valor`); 404 si el indicador no existe, no tiene reportes o algún
|
||||
periodo pedido no lo tiene.
|
||||
|
||||
### La lista de seguimiento de CaCu (solo DEV)
|
||||
|
||||
`GET /cacu/seguimiento` da una fila por paciente con algún estudio (citología o VPH) en la ventana
|
||||
de `meses` hasta el `corte`: su seudónimo, su grupo de edad, su estatus ASCCP al corte (la misma regla
|
||||
del estrato `estatus_seguimiento`), su citología y su VPH de la ventana y los días de la toma a su
|
||||
valoración; `prioridad` va nula. La arma `indicadores_kit.serving.seguimiento`; las reglas son de
|
||||
`parametros.toml` y salen en `reglas` con su estado. Contrato: `_docs/contratos/cacu_seguimiento_y_estratos.md` §2.
|
||||
|
||||
**Es dato por paciente:** la ruta solo existe con `DEV_REVISION` (el despliegue de DEV), los datos
|
||||
son simulados y toda respuesta lleva `simulado: true`. Nunca sale `pac_id` ni `pac_id_hospital`.
|
||||
|
||||
```bash
|
||||
curl "localhost:5000/cacu/seguimiento?corte=2026-09-30&meses=3&estatus=POST_COLPOSCOPIA&page=1&page_size=50"
|
||||
```
|
||||
|
||||
Códigos: 400 si `corte` no es `AAAA-MM-DD`, `meses` no es 1, 3, 6 o 12, `estatus` no es uno de los
|
||||
cuatro, o `page` y `page_size` están fuera de rango (`page_size` de 1 a 200); 404 si `page` pasa de la
|
||||
última página, o fuera de DEV.
|
||||
|
||||
## Cómo extender
|
||||
|
||||
### Agregar una ruta a un blueprint existente
|
||||
|
||||
1. Abre `webapi/blueprints/<dominio>.py`.
|
||||
2. Agrega la función con `@<dominio>_bp.get(...)` o `.post(...)`.
|
||||
3. Para leer una tabla, importa el repositorio de `persistance.<dominio>`.
|
||||
4. Si abres una sesión tú mismo (`get_<dominio>_session()`), ciérrala
|
||||
siempre en `finally`.
|
||||
5. Responde errores con `jsonify({"error": mensaje}), codigo`.
|
||||
6. Agrega pruebas (ver abajo) y la ruta a la tabla de este README.
|
||||
|
||||
### Agregar un blueprint (un dominio nuevo)
|
||||
|
||||
1. Crea `webapi/blueprints/<dominio>.py` con `Blueprint("<dominio>", __name__)`.
|
||||
2. Regístralo en `create_app()` de `webapi/__init__.py` con
|
||||
`app.register_blueprint(<dominio>_bp, url_prefix="/<dominio>")`.
|
||||
3. Agrega el dominio en `Persistance` primero (ver su README) y la variable
|
||||
`<DOMINIO>_DATABASE_URL` en el `Dockerfile`.
|
||||
4. Agrega su migración al `docker-entrypoint.sh`.
|
||||
|
||||
### Escribir pruebas
|
||||
|
||||
Las pruebas usan una base SQLite temporal, fijada con la variable de
|
||||
entorno o con el objeto `settings`. `Persistance` lee la configuración al
|
||||
importarse. Por eso importa `persistance` **dentro** de la fixture, no al
|
||||
inicio del archivo.
|
||||
|
||||
Patrón de `tests/test_app.py` (CaCu, con variable de entorno):
|
||||
|
||||
```python
|
||||
@pytest.fixture(scope="module")
|
||||
def client():
|
||||
db_path = tempfile.NamedTemporaryFile(suffix=".db", delete=False).name
|
||||
os.environ["CACU_DATABASE_URL"] = f"sqlite:///{db_path}"
|
||||
|
||||
from persistance.db import get_cacu_engine # import dentro de la fixture
|
||||
...
|
||||
from webapi import create_app
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as client:
|
||||
yield client
|
||||
```
|
||||
|
||||
Patrón de `tests/test_tea.py`, `test_cacu.py` y `test_cama.py` (con `monkeypatch` de `settings`;
|
||||
CaCu y CaMa lo comparten en `tests/conftest.py`):
|
||||
|
||||
```python
|
||||
from persistance.db import get_tea_engine
|
||||
from persistance.settings import settings
|
||||
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(settings, "tea_database_url", f"sqlite:///{ruta}")
|
||||
get_tea_engine.cache_clear() # el engine está en caché
|
||||
fixtures.base_de_prueba(get_tea_engine())
|
||||
...
|
||||
get_tea_engine().dispose()
|
||||
get_tea_engine.cache_clear()
|
||||
```
|
||||
|
||||
`fixtures.base_de_prueba` es de `indicadores_kit.tea.fixtures`: crea las
|
||||
tablas y deja sus 5 indicadores calculados.
|
||||
|
||||
Si cambias la URL después de crear el engine, llama a
|
||||
`get_<dominio>_engine.cache_clear()`.
|
||||
Las pruebas contra MySQL en vivo se activan con `MYSQL_TEST_URL`; sin ella
|
||||
se omiten.
|
||||
|
||||
+6
-10
@@ -17,17 +17,13 @@ if [ "$1" = "indicadores" ]; then
|
||||
exec uv run --no-sync python -m webapi.indicadores_vivos
|
||||
fi
|
||||
|
||||
# --no-sync: the image's environments were synced at build time; syncing at
|
||||
# startup would try to reach the package index (and pull dev deps).
|
||||
cd /app/Persistance
|
||||
uv run --no-sync alembic -c persistance/cacu/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c persistance/cama/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c persistance/tea/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c persistance/governance/alembic.ini upgrade head
|
||||
|
||||
cd /app/WebApi
|
||||
# Container's own network namespace — no AirPlay conflict here, keep it on
|
||||
# the port the Dockerfile EXPOSEs and docker-compose.yml maps from.
|
||||
# --no-sync: the environment was synced at build time; syncing at startup
|
||||
# would try to reach the package index (and pull dev deps).
|
||||
for domain in cacu cama tea governance; do
|
||||
uv run --no-sync alembic -c "/app/Persistance/persistance/$domain/alembic.ini" upgrade head
|
||||
done
|
||||
|
||||
PORT="${PORT:-5000}"
|
||||
# gunicorn, not Flask's development server. Long timeout: OCR over a
|
||||
# multi-page scanned PDF runs inside a single request.
|
||||
|
||||
@@ -5,10 +5,5 @@ from webapi import create_app
|
||||
app = create_app()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Default avoids port 5000 — on macOS that's squatted by the AirPlay
|
||||
# Receiver service (ControlCenter), which answers with a bare 403 and
|
||||
# makes this look like a broken server rather than "port taken."
|
||||
# Docker's entrypoint overrides this back to 5000 for the container's
|
||||
# own internal port (see docker-entrypoint.sh), which is fine since
|
||||
# that's an isolated network namespace, not the host.
|
||||
# 5000 is taken by AirPlay on macOS.
|
||||
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5050)))
|
||||
|
||||
+1
-2
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "webapi"
|
||||
version = "0.1.0"
|
||||
description = "Flask REST API fronting Persistance (reads) and models (train/predict) for CaCu, CaMa and TEA."
|
||||
description = "ISSSTELEON REST API: data import, indicators, import log and model governance for CaCu, CaMa and TEA."
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"flask>=3.0",
|
||||
@@ -19,7 +19,6 @@ dependencies = [
|
||||
"Pillow>=10.0",
|
||||
"flask-cors>=4.0",
|
||||
"gunicorn>=23.0",
|
||||
"apache-hamilton>=1.90",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
||||
+4
-16
@@ -13,7 +13,7 @@ import pytest
|
||||
|
||||
# Tests use throwaway SQLite files as "arbitrary SQL sources"; production
|
||||
# excludes sqlite by default (see webapi.imports.connectors.sql_policy).
|
||||
os.environ.setdefault("WEBAPI_SQL_ALLOWED_DIALECTS", "sqlite,mysql,mariadb,postgresql,mssql,oracle")
|
||||
os.environ.setdefault("WEBAPI_SQL_ALLOWED_DIALECTS", "sqlite,mysql,mariadb,postgresql,mssql")
|
||||
# The import log and the indicator queue write files; keep them out of the tree.
|
||||
_STATE_DIR = tempfile.mkdtemp(prefix="webapi-tests-")
|
||||
os.environ.setdefault("WEBAPI_REPORT_DIR", os.path.join(_STATE_DIR, "reportes"))
|
||||
@@ -66,21 +66,9 @@ SEMESTRES = ["2025-S1", "2025-S2"]
|
||||
MESES = ["2025-01", "2025-02", "2025-03"]
|
||||
|
||||
|
||||
def sembrar_base(proyecto: str, motor) -> None:
|
||||
"""La base de demostración del kit: staging sintético, carga y todos los indicadores calculados.
|
||||
|
||||
Lo mismo que hace `indicadores_kit.tea.fixtures.base_de_prueba` para
|
||||
TEA: cada definición de `measures_de(proyecto)` queda calculada en los
|
||||
periodos de 2025 que publica (`SEMESTRES`, y los doce meses si publica
|
||||
meses).
|
||||
"""
|
||||
from indicadores_kit.demostracion import base_de_prueba
|
||||
|
||||
base_de_prueba(motor, proyecto)
|
||||
|
||||
|
||||
def cliente_de(proyecto: str, tmp_path_factory):
|
||||
"""Generador para la fixture `client` de un proyecto: una base SQLite temporal ya sembrada."""
|
||||
"""Yields a client over a temporary SQLite database seeded with the kit's demonstration data."""
|
||||
from indicadores_kit.demostracion import base_de_prueba
|
||||
from persistance import db
|
||||
from persistance.settings import settings
|
||||
|
||||
@@ -90,7 +78,7 @@ def cliente_de(proyecto: str, tmp_path_factory):
|
||||
mp.setattr(settings, f"{proyecto}_database_url", f"sqlite:///{ruta}")
|
||||
obtener_motor.cache_clear()
|
||||
try:
|
||||
sembrar_base(proyecto, obtener_motor())
|
||||
base_de_prueba(obtener_motor(), proyecto)
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
|
||||
@@ -5,19 +5,6 @@ import pytest
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core.cacu.models import Paciente
|
||||
from persistance import db as persistance_db
|
||||
|
||||
engine = persistance_db.get_cacu_engine()
|
||||
|
||||
from sqlmodel import Session
|
||||
|
||||
with Session(engine) as session:
|
||||
session.add(Paciente(pac_id_hospital="H-1", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1)))
|
||||
session.commit()
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
@@ -31,26 +18,3 @@ def test_health(client):
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"status": "ok"}
|
||||
|
||||
|
||||
def test_get_paciente(client):
|
||||
response = client.get("/cacu/pacientes/1")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["pac_id_hospital"] == "H-1"
|
||||
|
||||
|
||||
def test_get_paciente_not_found(client):
|
||||
response = client.get("/cacu/pacientes/999")
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_predict_not_implemented(client):
|
||||
response = client.post("/cacu/predict")
|
||||
assert response.status_code == 501
|
||||
|
||||
|
||||
def test_api_index_lists_routes_with_summaries():
|
||||
from webapi import create_app
|
||||
|
||||
routes = {r["path"]: r for r in create_app().test_client().get("/api").get_json()["routes"]}
|
||||
assert routes["/imports/connectors"]["methods"] == ["GET"]
|
||||
assert routes["/governance/model-versions/<domain>/<scenario>/<version>/promote"]["summary"].startswith("Puts the version in production")
|
||||
|
||||
@@ -13,7 +13,7 @@ from webapi.imports.connectors.sql import SqlConnector
|
||||
def test_csv_connector_reads_columns_and_rows():
|
||||
raw = b"nombre,edad\nAna,30\nLuis,40\n"
|
||||
connector = CsvConnector(raw)
|
||||
columns = {c.name: c.inferred_type for c in connector.get_columns()}
|
||||
columns = {c.name: c.inferred_type for c in connector.preview().columns}
|
||||
assert columns == {"nombre": "string", "edad": "integer"}
|
||||
preview = connector.preview(limit=1)
|
||||
assert preview.total_rows == 2
|
||||
@@ -26,7 +26,7 @@ def test_csv_connector_reads_columns_and_rows():
|
||||
def test_csv_connector_keeps_leading_zeros_and_blank_cells():
|
||||
raw = b"cp,exp\n01000,007\n,H-2\n"
|
||||
connector = CsvConnector(raw)
|
||||
assert {c.name: c.inferred_type for c in connector.get_columns()} == {"cp": "string", "exp": "string"}
|
||||
assert {c.name: c.inferred_type for c in connector.preview().columns} == {"cp": "string", "exp": "string"}
|
||||
rows = list(connector.read_rows({"cp": "pac_codigo_postal", "exp": "pac_id_hospital"}))
|
||||
assert rows == [
|
||||
{"pac_codigo_postal": "01000", "pac_id_hospital": "007"},
|
||||
@@ -36,14 +36,14 @@ def test_csv_connector_keeps_leading_zeros_and_blank_cells():
|
||||
|
||||
def test_csv_connector_single_column_file():
|
||||
connector = CsvConnector(b"id\nH3\nH4\n")
|
||||
assert [c.name for c in connector.get_columns()] == ["id"]
|
||||
assert [c.name for c in connector.preview().columns] == ["id"]
|
||||
assert connector.metadata()["delimiter"] == ","
|
||||
|
||||
|
||||
def test_csv_connector_sniffs_semicolons_and_strips_excel_bom():
|
||||
raw = "\ufeffExpediente;Sexo\nH-1;F\n".encode("utf-8")
|
||||
connector = CsvConnector(raw)
|
||||
assert [c.name for c in connector.get_columns()] == ["Expediente", "Sexo"]
|
||||
assert [c.name for c in connector.preview().columns] == ["Expediente", "Sexo"]
|
||||
assert connector.metadata() == {"delimiter": ";", "encoding": "utf-8-sig"}
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ def test_csv_connector_bad_bytes_raise_connector_error():
|
||||
def test_json_connector_reads_list_of_records():
|
||||
raw = b'[{"nombre": "Ana", "edad": 30}, {"nombre": "Luis", "edad": 40}]'
|
||||
connector = JsonConnector(raw)
|
||||
assert {c.name for c in connector.get_columns()} == {"nombre", "edad"}
|
||||
assert {c.name for c in connector.preview().columns} == {"nombre", "edad"}
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre"}))
|
||||
assert rows == [{"pac_nombre": "Ana"}, {"pac_nombre": "Luis"}]
|
||||
|
||||
@@ -69,7 +69,7 @@ def test_json_connector_reads_list_of_records():
|
||||
def test_json_connector_reads_wrapped_data_key():
|
||||
raw = b'{"data": [{"nombre": "Ana"}]}'
|
||||
connector = JsonConnector(raw)
|
||||
assert {c.name for c in connector.get_columns()} == {"nombre"}
|
||||
assert {c.name for c in connector.preview().columns} == {"nombre"}
|
||||
|
||||
|
||||
def test_json_connector_bad_json_raises_connector_error():
|
||||
@@ -83,7 +83,7 @@ def test_excel_connector_reads_columns_and_rows():
|
||||
pd.DataFrame({"nombre": ["Ana", "Luis"], "edad": [30, 40]}).to_excel(buffer, index=False, engine="openpyxl")
|
||||
connector = ExcelConnector(buffer.getvalue())
|
||||
assert connector.list_sheets() == ["Sheet1"]
|
||||
assert {c.name for c in connector.get_columns()} == {"nombre", "edad"}
|
||||
assert {c.name for c in connector.preview().columns} == {"nombre", "edad"}
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre"}))
|
||||
assert rows == [{"pac_nombre": "Ana"}, {"pac_nombre": "Luis"}]
|
||||
|
||||
|
||||
@@ -181,7 +181,7 @@ def test_select_table_then_connector_abc_roundtrip():
|
||||
candidate = connector.detect_tables()[0]
|
||||
connector.select_table(candidate.page_number, candidate.bbox)
|
||||
|
||||
columns = {c.name for c in connector.get_columns()}
|
||||
columns = {c.name for c in connector.preview().columns}
|
||||
assert columns == {"pac_id_hospital", "pac_sexo"}
|
||||
|
||||
preview = connector.preview(limit=1)
|
||||
@@ -204,7 +204,7 @@ def test_select_table_out_of_range_page_raises_connector_error():
|
||||
def test_read_rows_before_resolution_raises_connector_error():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F")]))
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.get_columns()
|
||||
connector.preview().columns
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
@@ -288,6 +288,19 @@ def test_two_page_apply_to_every_page_regions():
|
||||
assert _similar(result["name"][3], ROWS_PAGE_2[0][0])
|
||||
|
||||
|
||||
def test_regions_on_different_pages_still_give_rectangular_rows():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS, ROWS_PAGE_2]))
|
||||
regions = [
|
||||
RegionSpec(target_field="name", page_numbers=[1, 2], bbox=_norm_bbox("name")),
|
||||
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
||||
]
|
||||
result = connector.extract_regions(regions)
|
||||
|
||||
assert len(result["name"]) == len(result["age"]) == 6
|
||||
assert result["age"][3:] == [None, None, None]
|
||||
assert len(list(connector.read_rows({"name": "name", "age": "age"}))) == 6
|
||||
|
||||
|
||||
def test_extract_regions_before_resolution_then_read_rows_uses_region_mode():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
||||
regions = [
|
||||
@@ -295,7 +308,7 @@ def test_extract_regions_before_resolution_then_read_rows_uses_region_mode():
|
||||
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
||||
]
|
||||
connector.extract_regions(regions)
|
||||
columns = {c.name for c in connector.get_columns()}
|
||||
columns = {c.name for c in connector.preview().columns}
|
||||
assert columns == {"name", "age"}
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Endpoint tests for `/governance/*` and the `/cacu/predict`,`/cama/predict`
|
||||
MLD-4/MLD-5 wiring through `models.prediction.PredictionService`."""
|
||||
"""Endpoint tests for `/governance/*`."""
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import date
|
||||
@@ -43,34 +42,35 @@ def client(wire_domain):
|
||||
del os.environ["MLFLOW_TRACKING_URI"]
|
||||
|
||||
|
||||
def test_predict_without_model_version_is_501(client):
|
||||
"""CaCuModel.predict is not implemented yet; no seeded MLflow version is
|
||||
needed to reach that state."""
|
||||
response = client.post("/cacu/predict", json={"pac_id_hospital": "H-1", "data": {"edad": 40}})
|
||||
assert response.status_code == 501
|
||||
|
||||
|
||||
def test_list_model_versions_empty(client):
|
||||
response = client.get("/governance/model-versions", query_string={"domain": "cacu", "scenario": "tamizaje-vacio"})
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"model_versions": []}
|
||||
|
||||
|
||||
def _cohort(tag: str) -> int:
|
||||
from core.governance.models import CohortVersion
|
||||
from persistance.governance import cohort_version_repository
|
||||
def _armado(tag: str) -> int:
|
||||
"""A CaCu cohort build with one attrition step; returns its `armado_id`."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
cohort = CohortVersion(
|
||||
domain="cacu", scenario="tamizaje", criteria_version="v1", version_hash=f"hash-{tag}",
|
||||
source_table="cacu.episodioclinico", n_source=5, n_included=5,
|
||||
)
|
||||
return cohort_version_repository.create(cohort).cohort_version_id
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteExclusion
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
with get_cacu_session() as session:
|
||||
armado = CohorteArmado(
|
||||
url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r", parametros="{}",
|
||||
datos_as_of=date(2025, 12, 31), huella=f"huella-{tag}", marco_sha="m", n_miembros=5,
|
||||
armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc))
|
||||
session.add(armado)
|
||||
session.flush()
|
||||
session.add(CohorteExclusion(armado_id=armado.armado_id, orden=1, paso="candidatas", n=5))
|
||||
session.commit()
|
||||
return armado.armado_id
|
||||
|
||||
|
||||
def _register(client, tag: str, *, scenario: str = "tamizaje", **extra) -> dict:
|
||||
body = {
|
||||
"domain": "cacu", "scenario": scenario, "environment": "PROD",
|
||||
"cohort_version_id": _cohort(tag), "metrics": {"auc": 0.8},
|
||||
"cohorte_armado_id": _armado(tag), "metrics": {"auc": 0.8},
|
||||
"technical_validation_report_uri": "docs/tecnica.pdf",
|
||||
"clinical_validation_report_uri": "docs/clinica.pdf",
|
||||
"interpretability_report_uri": "docs/interpretabilidad.html",
|
||||
@@ -108,12 +108,11 @@ def test_model_version_lifecycle_over_http(client):
|
||||
assert statuses[first["version"]] == "retirada" and statuses[second["version"]] == "produccion"
|
||||
|
||||
lineage = client.get(f"/governance/model-versions/cacu/lifecycle/{second['version']}/lineage").get_json()
|
||||
assert lineage["cohort_version"]["version_hash"] == "hash-v2"
|
||||
assert lineage["cohorte_armado"]["huella"] == "huella-v2"
|
||||
assert lineage["cohorte_armado"]["datos_as_of"] == "2025-12-31"
|
||||
assert lineage["cohorte_exclusiones"] == [{"orden": 1, "paso": "candidatas", "n": 5}]
|
||||
assert lineage["artifacts"]
|
||||
|
||||
diff = client.get("/governance/model-versions/cacu/lifecycle/compare", query_string={"a": first["version"], "b": second["version"]}).get_json()
|
||||
assert diff["metrics"][0]["delta"] == pytest.approx(0.06)
|
||||
|
||||
retired = client.post(f"/governance/model-versions/cacu/lifecycle/{second['version']}/retire").get_json()
|
||||
assert retired["status"] == "retirada"
|
||||
|
||||
@@ -136,77 +135,12 @@ def test_bad_registrations_and_uploads_are_rejected(client):
|
||||
|
||||
|
||||
def test_model_version_not_found(client):
|
||||
assert client.get("/governance/model-versions/cacu/no-existe/999").status_code == 404
|
||||
assert client.get("/governance/model-versions/cacu/no-existe/999/checks").status_code == 404
|
||||
|
||||
|
||||
def test_cohort_scenarios_and_build(client, monkeypatch):
|
||||
from models import cohort
|
||||
|
||||
class Demo(cohort.CohortBuilder):
|
||||
domain, scenario, criteria_version = "cacu", "demo", "v1"
|
||||
criteria = [cohort.ExclusionCriterion("SIN_CIE", "sin_codigo", lambda e: not e.get("cie10_codigo"), applicable_in_production=True)]
|
||||
|
||||
def fetch_episodes(self):
|
||||
return [{"episodio_id": 1, "pac_id_hospital": "H-1", "cie10_codigo": "C53"}, {"episodio_id": 2, "pac_id_hospital": "H-2"}]
|
||||
|
||||
monkeypatch.setitem(cohort.COHORT_BUILDERS, ("cacu", "demo"), Demo)
|
||||
[scenario] = [s for s in client.get("/governance/cohort-scenarios").get_json()["scenarios"] if s["scenario"] == "demo"]
|
||||
assert scenario["criteria"][0]["code"] == "SIN_CIE"
|
||||
built = client.post("/governance/cohort-versions", json={"domain": "cacu", "scenario": "demo"})
|
||||
assert built.status_code == 201 and built.get_json()["n_included"] == 1
|
||||
assert client.post("/governance/cohort-versions", json={"domain": "cacu", "scenario": "nope"}).status_code == 404
|
||||
|
||||
|
||||
def test_promote_unknown_model_version_is_404(client):
|
||||
assert client.post("/governance/model-versions/cacu/no-existe/999/promote").status_code == 404
|
||||
|
||||
|
||||
def test_cohort_version_exclusions_endpoint(client):
|
||||
from core.governance.models import CohortExclusion, CohortExclusionCount, CohortVersion
|
||||
from persistance.governance import (
|
||||
cohort_exclusion_count_repository,
|
||||
cohort_exclusion_repository,
|
||||
cohort_version_repository,
|
||||
)
|
||||
|
||||
cohort = cohort_version_repository.create(
|
||||
CohortVersion(
|
||||
domain="cacu",
|
||||
scenario="tamizaje",
|
||||
criteria_version="v1",
|
||||
version_hash="hash123",
|
||||
source_table="cacu.episodioclinico",
|
||||
n_source=10,
|
||||
n_included=8,
|
||||
)
|
||||
)
|
||||
cohort_exclusion_repository.create(
|
||||
CohortExclusion(
|
||||
cohort_version_id=cohort.cohort_version_id,
|
||||
pac_id_hospital="H-9",
|
||||
criterion_code="EDAD_FUERA_DE_RANGO",
|
||||
reason_code="EDAD<25",
|
||||
)
|
||||
)
|
||||
cohort_exclusion_count_repository.create(
|
||||
CohortExclusionCount(
|
||||
cohort_version_id=cohort.cohort_version_id,
|
||||
criterion_code="EDAD_FUERA_DE_RANGO",
|
||||
reason_code="EDAD<25",
|
||||
count=2,
|
||||
)
|
||||
)
|
||||
|
||||
response = client.get(f"/governance/cohort-versions/{cohort.cohort_version_id}/exclusions")
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["counts"][0]["count"] == 2
|
||||
assert body["detail"][0]["pac_id_hospital"] == "H-9"
|
||||
|
||||
|
||||
def test_ocr_run_unknown_job_is_400(client):
|
||||
def test_ocr_run_unknown_job_is_404(client):
|
||||
response = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "no_such_entity"})
|
||||
assert response.status_code == 400
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_ocr_run_extracts_results_and_flags_unreadable_reports(client):
|
||||
|
||||
@@ -191,7 +191,7 @@ def test_a_failing_source_rolls_back_the_whole_batch(client, monkeypatch):
|
||||
},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "nothing was written" in response.get_json()["error"]
|
||||
assert "no se escribió nada" in response.get_json()["error"]
|
||||
assert not {"ATOM-1", "ATOM-2"} & set(_rows(client, "cacu.Paciente"))
|
||||
|
||||
|
||||
|
||||
@@ -6,6 +6,11 @@ import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
|
||||
def _patients(client) -> dict[str, dict]:
|
||||
rows = client.get("/data/cacu.Paciente", query_string={"limit": 500}).get_json()["rows"]
|
||||
return {row["pac_id_hospital"]: row for row in rows}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
@@ -81,8 +86,7 @@ def test_validate_reports_row_errors_without_writing(client):
|
||||
assert body["valid_count"] == 1
|
||||
assert body["error_count"] == 1
|
||||
assert body["errors"][0]["field"] == "pac_id_hospital"
|
||||
# not written
|
||||
assert client.get("/cacu/pacientes/999").status_code == 404
|
||||
assert "H-VALIDATE-1" not in _patients(client)
|
||||
|
||||
|
||||
def test_commit_multi_source_batch_mixes_file_and_sql_within_one_domain(client, tmp_path):
|
||||
@@ -115,12 +119,7 @@ def test_commit_multi_source_batch_mixes_file_and_sql_within_one_domain(client,
|
||||
assert body["ok"] is True
|
||||
assert [r["target"] for r in body["results"]] == ["cacu.Paciente", "cacu.Paciente"]
|
||||
assert sum(r["created"] for r in body["results"]) == 2
|
||||
|
||||
# First test in this file to write into cacu.Paciente, so autoincrement
|
||||
# ids 1/2 are deterministic (pytest runs this module's tests in
|
||||
# definition order).
|
||||
created_hospital_ids = {client.get(f"/cacu/pacientes/{i}").get_json()["pac_id_hospital"] for i in (1, 2)}
|
||||
assert created_hospital_ids == {"H-BATCH-1", "H-SQL-BATCH-1"}
|
||||
assert {"H-BATCH-1", "H-SQL-BATCH-1"} <= set(_patients(client))
|
||||
|
||||
|
||||
def test_commit_rejects_a_batch_mixing_domains(client):
|
||||
@@ -129,7 +128,7 @@ def test_commit_rejects_a_batch_mixing_domains(client):
|
||||
|
||||
response = client.post("/imports/commit", json={"sources": [cacu_source, tea_source], "on_conflict": "reject"})
|
||||
assert response.status_code == 400
|
||||
assert "domain" in response.get_json()["error"].lower()
|
||||
assert "dominios" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_commit_on_conflict_reject_then_upsert(client):
|
||||
@@ -179,8 +178,8 @@ def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client):
|
||||
assert body["results"][0]["created"] == 0
|
||||
assert body["results"][0]["updated"] == 1
|
||||
|
||||
paciente = client.get("/tea/pacientes/9001").get_json()
|
||||
assert paciente["pac_id_hospital"] == "T-SRC-1"
|
||||
[paciente] = client.get("/data/tea.Pacientes").get_json()["rows"]
|
||||
assert paciente["pac_id"] == 9001 and paciente["pac_id_hospital"] == "T-SRC-1"
|
||||
assert paciente["pac_sexo"] == "M"
|
||||
|
||||
|
||||
|
||||
@@ -13,7 +13,12 @@ import sqlalchemy as sa
|
||||
|
||||
MYSQL_TEST_URL = os.environ.get("MYSQL_TEST_URL")
|
||||
|
||||
pytestmark = pytest.mark.skipif(not MYSQL_TEST_URL, reason="MYSQL_TEST_URL not set — no real MySQL server to test against")
|
||||
pytestmark = pytest.mark.skipif(not MYSQL_TEST_URL, reason="MYSQL_TEST_URL not set")
|
||||
|
||||
|
||||
def _patients(client) -> dict[str, dict]:
|
||||
rows = client.get("/data/cacu.Paciente", query_string={"limit": 500}).get_json()["rows"]
|
||||
return {row["pac_id_hospital"]: row for row in rows}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -129,13 +134,18 @@ def test_commit_batch_mixes_mysql_json_and_csv_into_one_domain(client, mysql_leg
|
||||
# csv: 1 row, json: 1 row, mysql: 2 rows
|
||||
assert [r["created"] for r in body["results"]] == [1, 1, 2]
|
||||
|
||||
all_ids = {client.get(f"/cacu/pacientes/{i}").get_json()["pac_id_hospital"] for i in range(1, 5)}
|
||||
assert all_ids == {"CSV-MULTI-1", "JSON-MULTI-1", "MYSQL-MULTI-1", "MYSQL-MULTI-2"}
|
||||
assert {"CSV-MULTI-1", "JSON-MULTI-1", "MYSQL-MULTI-1", "MYSQL-MULTI-2"} <= set(_patients(client))
|
||||
|
||||
|
||||
def test_commit_upsert_against_mysql_source_updates_existing_row(client, mysql_legacy_source):
|
||||
# MYSQL-MULTI-1 already exists (created above with sexo 'F'). Mutate the
|
||||
# source row and re-import with on_conflict=upsert.
|
||||
sql_source = {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"expediente": "pac_id_hospital", "sexo_paciente": "pac_sexo"},
|
||||
"payload": {"connection_string": MYSQL_TEST_URL, "table": mysql_legacy_source},
|
||||
}
|
||||
assert client.post("/imports/commit", json={"sources": [sql_source], "on_conflict": "upsert"}).status_code == 200
|
||||
|
||||
engine = sa.create_engine(MYSQL_TEST_URL)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(
|
||||
@@ -143,22 +153,11 @@ def test_commit_upsert_against_mysql_source_updates_existing_row(client, mysql_l
|
||||
)
|
||||
engine.dispose()
|
||||
|
||||
sql_source = {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"expediente": "pac_id_hospital", "sexo_paciente": "pac_sexo"},
|
||||
"payload": {"connection_string": MYSQL_TEST_URL, "table": mysql_legacy_source},
|
||||
}
|
||||
response = client.post("/imports/commit", json={"sources": [sql_source], "on_conflict": "upsert"})
|
||||
assert response.status_code == 200
|
||||
result = response.get_json()["results"][0]
|
||||
# Both rows already exist from the previous test. Upsert reports
|
||||
# "updated" for every conflicting row whether or not its values changed,
|
||||
# per Repository.bulk_upsert's contract.
|
||||
# Upsert reports "updated" for every row that already existed, changed or not.
|
||||
assert result["updated"] == 2
|
||||
assert result["created"] == 0
|
||||
|
||||
updated = client.get("/cacu/pacientes/3").get_json()
|
||||
assert updated["pac_id_hospital"] == "MYSQL-MULTI-1"
|
||||
# 'M' is coerced through SEXO_BIOLOGICO_ALIAS into the canonical value.
|
||||
assert updated["pac_sexo"] == "Masculino"
|
||||
assert _patients(client)["MYSQL-MULTI-1"]["pac_sexo"] == "Masculino"
|
||||
|
||||
@@ -18,6 +18,11 @@ from reportlab.pdfgen import canvas
|
||||
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
|
||||
|
||||
|
||||
def _patients(client) -> dict[str, dict]:
|
||||
rows = client.get("/data/cacu.Paciente", query_string={"limit": 500}).get_json()["rows"]
|
||||
return {row["pac_id_hospital"]: row for row in rows}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
@@ -166,10 +171,7 @@ def test_pdf_table_round_trip_detect_preview_validate_commit(client):
|
||||
assert result["target"] == "cacu.Paciente"
|
||||
assert result["created"] == 2
|
||||
|
||||
# this is the first write into cacu.Paciente in this module's temp DB
|
||||
created = client.get("/cacu/pacientes/1")
|
||||
assert created.status_code == 200
|
||||
assert created.get_json()["pac_id_hospital"] == "H-PDF-TAB-1"
|
||||
assert "H-PDF-TAB-1" in _patients(client)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
@@ -120,14 +120,6 @@ def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, quer
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_paciente_por_id_entero(client):
|
||||
response = client.get("/tea/pacientes/1")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["pac_id_hospital"] == "T-01"
|
||||
|
||||
assert client.get("/tea/pacientes/abc").status_code == 404
|
||||
|
||||
|
||||
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
||||
from webapi import indicadores
|
||||
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
"""The Hamilton pipeline computes exactly what Orquestacion's own executor does."""
|
||||
from importlib import import_module
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Session
|
||||
|
||||
|
||||
def _seed_and_run(proyecto, tmp_path, run):
|
||||
from orquestacion.arista import Contexto
|
||||
from orquestacion.conexion import apuntar
|
||||
from orquestacion.ejecutor import correr as correr_orquestacion
|
||||
from orquestacion.repositorios import repositorios_de
|
||||
|
||||
url = f"sqlite:///{tmp_path / f'{proyecto}.db'}"
|
||||
apuntar(proyecto, url)
|
||||
ctx = Contexto(proyecto, 2025, 2025, permitir_sin_definir=True, repos=repositorios_de(proyecto))
|
||||
correr_orquestacion(ctx, solo=["migrar"])
|
||||
with Session(sa.create_engine(url)) as sesion:
|
||||
import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion)
|
||||
sesion.commit()
|
||||
run(ctx)
|
||||
engine = sa.create_engine(url)
|
||||
with engine.connect() as conn:
|
||||
reports = conn.execute(sa.text(
|
||||
"SELECT measure_url, periodo_id, status, tipo FROM measure_report ORDER BY 1, 2, 3, 4")).all()
|
||||
units = conn.execute(sa.text(
|
||||
"SELECT r.measure_url, r.periodo_id, u.grupo, u.unidad_id, u.resultado_id, u.valor_id, u.numero "
|
||||
"FROM measure_report_unidad u JOIN measure_report r USING (report_id) ORDER BY 1, 2, 3, 4, 5")).all()
|
||||
engine.dispose()
|
||||
return reports, units
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "tea"])
|
||||
def test_hamilton_matches_the_orquestacion_executor(proyecto, tmp_path_factory):
|
||||
from orquestacion.ejecutor import correr as correr_orquestacion
|
||||
|
||||
from webapi.pipeline import correr as correr_hamilton
|
||||
|
||||
nombres = None
|
||||
|
||||
def by_executor(ctx):
|
||||
nonlocal nombres
|
||||
nombres = [p.arista for p in correr_orquestacion(ctx) if p.arista != "migrar"]
|
||||
|
||||
expected = _seed_and_run(proyecto, tmp_path_factory.mktemp("orquestacion"), by_executor)
|
||||
got = _seed_and_run(proyecto, tmp_path_factory.mktemp("hamilton"),
|
||||
lambda ctx: correr_hamilton(ctx, solo=nombres))
|
||||
assert expected[0] and expected[1]
|
||||
assert got == expected
|
||||
+1
-22
@@ -105,7 +105,7 @@ def test_indicators_recompute_from_imported_rows(client):
|
||||
estado = client.get("/reportes/indicadores").get_json()["cacu"]
|
||||
assert estado["estado"] == "ok", estado
|
||||
assert estado["pendiente"] is False
|
||||
assert {p["arista"] for p in estado["pasos"]} >= {"cargar", "calcular"}
|
||||
assert {p["paso"] for p in estado["pasos"]} >= {"cargar", "calcular"}
|
||||
assert client.get("/cacu/indicadores").get_json()
|
||||
|
||||
assert client.post("/reportes/indicadores/cacu/recalcular").status_code == 202
|
||||
@@ -136,24 +136,3 @@ def test_headerless_csv_logs_shapes(client):
|
||||
raw = json.dumps(_log()[-1])
|
||||
assert "N-0001" not in raw and "1980-01-01" not in raw
|
||||
assert "A-9999" in raw
|
||||
|
||||
|
||||
def test_hamilton_pipeline_orders_the_kit_steps_like_the_graph():
|
||||
"""Same steps, same dependency order as Orquestacion's own graph."""
|
||||
from orquestacion.arista import Contexto
|
||||
from orquestacion.aristas import FUENTES, aristas_de
|
||||
from orquestacion.grafo import orden
|
||||
|
||||
from webapi.pipeline import _order, modulo
|
||||
from hamilton import driver
|
||||
|
||||
for proyecto in ("tea", "cacu", "cama"):
|
||||
aristas = aristas_de(proyecto)
|
||||
dr = driver.Builder().with_modules(modulo(Contexto(proyecto, 2025, 2025), aristas)).build()
|
||||
nombres = [a.nombre for a in aristas]
|
||||
hamilton_order = _order(dr, nombres)
|
||||
graph_order = [a.nombre for a in orden(aristas, FUENTES)]
|
||||
assert set(hamilton_order) == set(graph_order)
|
||||
for arista in aristas:
|
||||
for anterior in dr.graph.nodes[arista.nombre].dependencies:
|
||||
assert hamilton_order.index(anterior.name) < hamilton_order.index(arista.nombre)
|
||||
|
||||
+14
-17
@@ -1,7 +1,7 @@
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from webapi.imports.mapping.column_matcher import ColumnMatcher
|
||||
from webapi.imports.mapping.column_matcher import suggest_mapping
|
||||
from webapi.imports.schemas.cacu.paciente import PacienteImportSchema
|
||||
from webapi.imports.schemas.classify import ErrorCategory, classify_error
|
||||
from webapi.imports.schemas.service import validate_rows
|
||||
@@ -88,10 +88,9 @@ def test_validate_rows_never_aborts_on_a_bad_row():
|
||||
|
||||
|
||||
def test_column_matcher_exact_normalized_synonym_fuzzy_none():
|
||||
matcher = ColumnMatcher()
|
||||
targets = ["pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"]
|
||||
|
||||
suggestions = matcher.suggest(
|
||||
suggestions = suggest_mapping(
|
||||
["pac_id_hospital", "Sexo", "fecha_nacimiento", "columna_sin_relacion_xyz"], targets
|
||||
)
|
||||
by_source = {s.source_column: s for s in suggestions}
|
||||
@@ -110,9 +109,8 @@ def test_column_matcher_exact_normalized_synonym_fuzzy_none():
|
||||
|
||||
|
||||
def test_column_matcher_enforces_one_to_one():
|
||||
matcher = ColumnMatcher()
|
||||
# two source columns that would both match "pac_sexo" exactly-ish
|
||||
suggestions = matcher.suggest(["pac_sexo", "sexo"], ["pac_sexo"])
|
||||
suggestions = suggest_mapping(["pac_sexo", "sexo"], ["pac_sexo"])
|
||||
matched_targets = [s.target_field for s in suggestions if s.target_field]
|
||||
assert matched_targets == ["pac_sexo"] # only the first claims it
|
||||
|
||||
@@ -134,14 +132,14 @@ def test_coerce_date_accepts_iso_day_first_and_timestamps_but_not_impossible_dat
|
||||
|
||||
def test_catalog_is_case_insensitive_accepts_member_names_and_rejects_unknowns():
|
||||
from core.cacu.enums import SEXO_BIOLOGICO_ALIAS, SexoBiologico
|
||||
from webapi.imports.schemas.coercion import Catalog, coerce_alias
|
||||
from webapi.imports.schemas.coercion import Catalog
|
||||
|
||||
catalog = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
assert coerce_alias(" femenino ", catalog) == "Femenino"
|
||||
assert coerce_alias("m", catalog) == "Masculino"
|
||||
assert coerce_alias("", catalog) is None
|
||||
assert catalog.coerce(" femenino ") == "Femenino"
|
||||
assert catalog.coerce("m") == "Masculino"
|
||||
assert catalog.coerce("") is None
|
||||
with pytest.raises(ValueError, match="no está en el catálogo"):
|
||||
coerce_alias("X", catalog)
|
||||
catalog.coerce("X")
|
||||
|
||||
|
||||
def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog():
|
||||
@@ -150,11 +148,11 @@ def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog():
|
||||
only models the base B0-B6 categories; without an alias for them, every
|
||||
such report was silently unimportable."""
|
||||
from core.cama.mastografia.enums import BIRADS, BIRADS_ALIAS
|
||||
from webapi.imports.schemas.coercion import Catalog, coerce_alias
|
||||
from webapi.imports.schemas.coercion import Catalog
|
||||
|
||||
catalog = Catalog(BIRADS, BIRADS_ALIAS)
|
||||
for value in ("4A", "BI-RADS 4B", "bi-rads 4c"):
|
||||
assert coerce_alias(value, catalog) == "B4"
|
||||
assert catalog.coerce(value) == "B4"
|
||||
|
||||
|
||||
def test_postal_code_restores_leading_zero_from_numeric_sources():
|
||||
@@ -167,11 +165,10 @@ def test_postal_code_restores_leading_zero_from_numeric_sources():
|
||||
|
||||
|
||||
def test_column_matcher_handles_accents_prefixes_and_global_one_to_one():
|
||||
matcher = ColumnMatcher()
|
||||
targets = ["pac_id_hospital", "pac_sexo", "pac_codigo_postal", "pac_fecha_nacimiento"]
|
||||
by_source = {
|
||||
s.source_column: s
|
||||
for s in matcher.suggest(["Fech nacim", "Género", "C.P.", "Expediente", "fecha_nacimiento"], targets)
|
||||
for s in suggest_mapping(["Fech nacim", "Género", "C.P.", "Expediente", "fecha_nacimiento"], targets)
|
||||
}
|
||||
assert by_source["Género"].target_field == "pac_sexo"
|
||||
assert by_source["C.P."].target_field == "pac_codigo_postal"
|
||||
@@ -183,7 +180,7 @@ def test_column_matcher_handles_accents_prefixes_and_global_one_to_one():
|
||||
|
||||
|
||||
def test_column_matcher_matches_names_without_the_table_prefix():
|
||||
suggestion = ColumnMatcher().suggest(["hemoglobina_g_dl", "birads"], ["hemoglobina_g_dl", "mast_birads"])
|
||||
suggestion = suggest_mapping(["hemoglobina_g_dl", "birads"], ["hemoglobina_g_dl", "mast_birads"])
|
||||
assert [(s.target_field, s.reason) for s in suggestion] == [("hemoglobina_g_dl", "exact"), ("mast_birads", "unprefixed")]
|
||||
|
||||
|
||||
@@ -206,14 +203,14 @@ def test_column_matcher_real_world_headers(target, source, expected):
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
fields = list(ENTITY_REGISTRY[target].schema.model_fields)
|
||||
assert ColumnMatcher().suggest([source], fields)[0].target_field == expected
|
||||
assert suggest_mapping([source], fields)[0].target_field == expected
|
||||
|
||||
|
||||
def test_column_matcher_does_not_guess_from_shared_letters_alone():
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
fields = list(ENTITY_REGISTRY["cacu.NotaMedica"].schema.model_fields)
|
||||
assert ColumnMatcher().suggest(["Observaciones del servicio xyz", "Clave única"], fields)[1].target_field is None
|
||||
assert suggest_mapping(["Observaciones del servicio xyz", "Clave única"], fields)[1].target_field is None
|
||||
|
||||
|
||||
def test_catalog_for_exposes_field_catalog_and_errors_stay_on_field():
|
||||
|
||||
@@ -31,36 +31,6 @@ def test_every_registered_schema_is_constructible(entity_key):
|
||||
schema_cls()
|
||||
|
||||
|
||||
def test_entity_registry_has_twenty_four_entries():
|
||||
assert len(ENTITY_REGISTRY) == 24
|
||||
|
||||
|
||||
def test_entity_registry_keys_cover_all_three_domains():
|
||||
keys = set(ENTITY_REGISTRY.keys())
|
||||
assert "cacu.Paciente" in keys
|
||||
assert "cacu.OrdenesEstudio" in keys
|
||||
assert "cacu.CitologiaCervical" in keys
|
||||
assert "cacu.BiopsiaCervical" in keys
|
||||
assert "cacu.NotaMedica" in keys
|
||||
assert "cacu.BiometriaHematica" in keys
|
||||
assert "cacu.EpisodioClinico" in keys
|
||||
assert "cama.Paciente" in keys
|
||||
assert "cama.OrdenesEstudio" in keys
|
||||
assert "cama.Mastografia" in keys
|
||||
assert "cama.BiopsiaMama" in keys
|
||||
assert "cama.NotaMedica" in keys
|
||||
assert "cama.BiometriaHematica" in keys
|
||||
assert "cama.EpisodioClinico" in keys
|
||||
assert "tea.Pacientes" in keys
|
||||
assert "tea.OrdenesEstudio" in keys
|
||||
assert "tea.NotaMedica" in keys
|
||||
assert "tea.EvaluacionPsicologica" in keys
|
||||
assert "tea.PotencialesEvocadosAuditivos" in keys
|
||||
assert "tea.EegEstudio" in keys
|
||||
assert "tea.AntecedentesMaternosGestacion" in keys
|
||||
assert "tea.PartoNeonatal" in keys
|
||||
|
||||
|
||||
# --- Spot checks -----------------------------------------------------------
|
||||
# CaMa entity with a required, unique integer ord_numero_hospital and an
|
||||
# *_ALIAS-backed enum field.
|
||||
|
||||
@@ -59,3 +59,48 @@ def test_natural_key_wins_over_a_foreign_internal_id(client):
|
||||
paciente = next(p for p in paciente_repository.list() if p.pac_id_hospital == "CSV-1")
|
||||
nota = next(n for n in nota_medica_repository.list() if n.nm_id_hospital == "N-1")
|
||||
assert nota.pac_id == paciente.pac_id != 999
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def tea_client(wire_domain):
|
||||
wire_domain("tea")
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_tea_children_keep_pointing_at_their_parents_source_ids(tea_client):
|
||||
sources = [
|
||||
_json([{"pac_id": 1, "pac_id_hospital": "T-1"}], "tea.Pacientes"),
|
||||
_json([{"ord_id": "ord-1", "ord_pac_id": 1, "ord_id_hospital": "O-1"}], "tea.OrdenesEstudio"),
|
||||
_json([{"psi_id": "psi-1", "psi_ord_id": "ord-1", "psi_pac_id": 1}], "tea.EvaluacionPsicologica"),
|
||||
_json([{"ins_psi_id": "psi-1", "ins_instrumento": "ADOS-2"}], "tea.InstrumentoAplicado"),
|
||||
_json([{"eeg_id": "eeg-1", "eeg_ord_id": "ord-1", "eeg_id_registro_laboratorio": "L-1"}], "tea.EegEstudio"),
|
||||
_json([{"seg_eeg_id": "eeg-1", "seg_duracion_s": 30}], "tea.EegSegmento"),
|
||||
]
|
||||
body = tea_client.post("/imports/commit", json={"sources": sources}).get_json()
|
||||
assert all(r["rejected"] == 0 for r in body["results"]), body
|
||||
|
||||
from persistance.tea import (
|
||||
eeg_estudio_repository,
|
||||
eeg_segmento_repository,
|
||||
evaluacion_psicologica_repository,
|
||||
instrumento_aplicado_repository,
|
||||
)
|
||||
|
||||
assert eeg_estudio_repository.get(eeg_segmento_repository.list()[0].seg_eeg_id).eeg_id_registro_laboratorio == "L-1"
|
||||
evaluacion = evaluacion_psicologica_repository.get(instrumento_aplicado_repository.list()[0].ins_psi_id)
|
||||
assert evaluacion.psi_ord_id == "ord-1"
|
||||
|
||||
|
||||
def test_tea_rows_without_a_source_id_get_one(tea_client):
|
||||
eeg = _json([{"eeg_id_registro_laboratorio": "L-SIN-ID"}], "tea.EegEstudio")
|
||||
assert tea_client.post("/imports/commit", json={"sources": [eeg]}).get_json()["results"][0]["created"] == 1
|
||||
|
||||
from persistance.tea import eeg_estudio_repository
|
||||
|
||||
[fila] = [e for e in eeg_estudio_repository.list() if e.eeg_id_registro_laboratorio == "L-SIN-ID"]
|
||||
assert len(fila.eeg_id) == 36
|
||||
|
||||
@@ -9,18 +9,18 @@ from webapi.imports.connectors.sql import SqlConnector
|
||||
from webapi.imports.connectors.sql_policy import SqlSourcePolicy
|
||||
|
||||
PRODUCTION_POLICY = SqlSourcePolicy(
|
||||
allowed_dialects=frozenset({"mysql", "mariadb", "postgresql", "mssql", "oracle"}), allowed_hosts=None
|
||||
allowed_dialects=frozenset({"mysql", "mariadb", "postgresql", "mssql"}), allowed_hosts=None
|
||||
)
|
||||
|
||||
|
||||
def test_sqlite_is_refused_by_default_policy(tmp_path):
|
||||
with pytest.raises(ConnectorError, match="dialect 'sqlite' is not allowed"):
|
||||
with pytest.raises(ConnectorError, match="'sqlite' no está permitido"):
|
||||
SqlConnector(f"sqlite:///{tmp_path / 'x.db'}", policy=PRODUCTION_POLICY)
|
||||
|
||||
|
||||
def test_host_allowlist_is_enforced():
|
||||
policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=frozenset({"10.0.10.50"}))
|
||||
with pytest.raises(ConnectorError, match="not in the allowed"):
|
||||
with pytest.raises(ConnectorError, match="no está entre los permitidos"):
|
||||
policy.check_url("mysql+pymysql://u:p@evil.example.com/db")
|
||||
assert policy.check_url("mysql+pymysql://u:p@10.0.10.50/db").host == "10.0.10.50"
|
||||
|
||||
@@ -31,16 +31,25 @@ def test_refuses_the_applications_own_database(monkeypatch, tmp_path):
|
||||
own = tmp_path / "cacu.db"
|
||||
monkeypatch.setattr(persistance_settings.settings, "cacu_database_url", f"sqlite:///{own}")
|
||||
policy = SqlSourcePolicy(allowed_dialects=frozenset({"sqlite"}), allowed_hosts=None)
|
||||
with pytest.raises(ConnectorError, match="own database"):
|
||||
with pytest.raises(ConnectorError, match="propia aplicación"):
|
||||
policy.check_url(f"sqlite:///{own}")
|
||||
|
||||
monkeypatch.setattr(persistance_settings.settings, "cama_database_url", "mysql+pymysql://app:pw@db.internal:3306/isss_cama")
|
||||
mysql_policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=None)
|
||||
with pytest.raises(ConnectorError, match="own database"):
|
||||
with pytest.raises(ConnectorError, match="propia aplicación"):
|
||||
mysql_policy.check_url("mysql+pymysql://someone_else:pw@DB.internal:3306/isss_cama")
|
||||
mysql_policy.check_url("mysql+pymysql://app:pw@db.internal:3306/hospital_legacy")
|
||||
|
||||
|
||||
def test_an_explicit_default_port_does_not_bypass_the_own_database_check(monkeypatch):
|
||||
from persistance import settings as persistance_settings
|
||||
|
||||
monkeypatch.setattr(persistance_settings.settings, "cacu_database_url", "mysql+pymysql://app:pw@db/isss_cacu")
|
||||
policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=None)
|
||||
with pytest.raises(ConnectorError, match="propia aplicación"):
|
||||
policy.check_url("mysql+pymysql://app:pw@db:3306/isss_cacu")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
|
||||
+1
-1
@@ -68,7 +68,7 @@ def create_app() -> Flask:
|
||||
@app.errorhandler(413)
|
||||
def too_large(_exc):
|
||||
limit_mb = app.config["MAX_CONTENT_LENGTH"] // (1024 * 1024)
|
||||
return jsonify({"error": f"request larger than {limit_mb} MB"}), 413
|
||||
return jsonify({"error": f"la solicitud excede {limit_mb} MB"}), 413
|
||||
|
||||
app.register_blueprint(cacu_bp, url_prefix="/cacu")
|
||||
app.register_blueprint(cama_bp, url_prefix="/cama")
|
||||
|
||||
@@ -1,41 +1,7 @@
|
||||
from flask import Blueprint, jsonify, request
|
||||
from flask import Blueprint
|
||||
|
||||
from models.cacu import CaCuModel
|
||||
from models.prediction import ApplicabilityRejected, PredictionService
|
||||
from persistance.cacu import paciente_repository
|
||||
from persistance.db import get_cacu_session
|
||||
from webapi.indicadores import registrar_indicadores
|
||||
|
||||
cacu_bp = Blueprint("cacu", __name__)
|
||||
registrar_indicadores(cacu_bp, "cacu", get_cacu_session)
|
||||
|
||||
|
||||
@cacu_bp.get("/pacientes/<int:pac_id>")
|
||||
def get_paciente(pac_id: int):
|
||||
"""Read one CaCu patient by primary key."""
|
||||
paciente = paciente_repository.get(pac_id)
|
||||
if paciente is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify(paciente.model_dump())
|
||||
|
||||
|
||||
@cacu_bp.post("/predict")
|
||||
def predict():
|
||||
"""Predict and record the result against the active `ModelVersion` (MLD-4/MLD-5).
|
||||
|
||||
Returns 501 while `CaCuModel.predict` is not implemented."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
service = PredictionService(CaCuModel(), domain="cacu", scenario=body.get("scenario", "tamizaje"))
|
||||
try:
|
||||
prediction = service.predict_and_record(
|
||||
body.get("data"),
|
||||
pac_id_hospital=body.get("pac_id_hospital", ""),
|
||||
episodio_id=body.get("episodio_id"),
|
||||
)
|
||||
except NotImplementedError as exc:
|
||||
return jsonify({"error": str(exc)}), 501
|
||||
except ApplicabilityRejected as exc:
|
||||
return jsonify({"error": str(exc)}), 422
|
||||
except RuntimeError as exc:
|
||||
return jsonify({"error": str(exc)}), 503
|
||||
return jsonify(prediction.model_dump())
|
||||
|
||||
@@ -1,38 +1,7 @@
|
||||
from flask import Blueprint, jsonify, request
|
||||
from flask import Blueprint
|
||||
|
||||
from models.cama import CaMaModel
|
||||
from models.prediction import ApplicabilityRejected, PredictionService
|
||||
from persistance.cama import paciente_repository
|
||||
from persistance.db import get_cama_session
|
||||
from webapi.indicadores import registrar_indicadores
|
||||
|
||||
cama_bp = Blueprint("cama", __name__)
|
||||
registrar_indicadores(cama_bp, "cama", get_cama_session)
|
||||
|
||||
|
||||
@cama_bp.get("/pacientes/<int:pac_id>")
|
||||
def get_paciente(pac_id: int):
|
||||
paciente = paciente_repository.get(pac_id)
|
||||
if paciente is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify(paciente.model_dump())
|
||||
|
||||
|
||||
@cama_bp.post("/predict")
|
||||
def predict():
|
||||
"""Predict and record the result against the active `ModelVersion` (MLD-4/MLD-5)."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
service = PredictionService(CaMaModel(), domain="cama", scenario=body.get("scenario", "tamizaje"))
|
||||
try:
|
||||
prediction = service.predict_and_record(
|
||||
body.get("data"),
|
||||
pac_id_hospital=body.get("pac_id_hospital", ""),
|
||||
episodio_id=body.get("episodio_id"),
|
||||
)
|
||||
except NotImplementedError as exc:
|
||||
return jsonify({"error": str(exc)}), 501
|
||||
except ApplicabilityRejected as exc:
|
||||
return jsonify({"error": str(exc)}), 422
|
||||
except RuntimeError as exc:
|
||||
return jsonify({"error": str(exc)}), 503
|
||||
return jsonify(prediction.model_dump())
|
||||
|
||||
@@ -13,12 +13,12 @@ _MAX_PAGE = 500
|
||||
def list_rows(target: str):
|
||||
spec = ENTITY_REGISTRY.get(target)
|
||||
if spec is None:
|
||||
return jsonify({"error": f"unknown target: {target!r}"}), 404
|
||||
return jsonify({"error": f"destino desconocido: {target!r}"}), 404
|
||||
try:
|
||||
limit = min(max(int(request.args.get("limit", 50)), 1), _MAX_PAGE)
|
||||
offset = max(int(request.args.get("offset", 0)), 0)
|
||||
except ValueError:
|
||||
return jsonify({"error": "limit/offset must be integers"}), 400
|
||||
return jsonify({"error": "limit y offset deben ser números enteros"}), 400
|
||||
rows = spec.repository.list(limit=limit, offset=offset)
|
||||
return jsonify(
|
||||
{
|
||||
|
||||
+27
-101
@@ -1,29 +1,19 @@
|
||||
"""Model governance (ML, MLD, EL and VAR requirements): model versions and
|
||||
their promotion, cohorts, predictions, and the OCR extraction jobs with
|
||||
their manual review queue.
|
||||
their promotion, and the OCR extraction jobs with their manual review queue.
|
||||
|
||||
Training, versioning and artifact storage live in MLflow (`models.registry`
|
||||
is a thin layer over it); training runs anywhere, registering the result
|
||||
through `POST /model-versions`. Browsing/downloading a logged artifact goes
|
||||
straight to the MLflow tracking server's own UI/API, not through here.
|
||||
Versions and artifacts live in MLflow (`models.registry`); training runs
|
||||
elsewhere and registers its result through `POST /model-versions`, naming
|
||||
the indicator kit cohort build it was trained on (`cohorte_armado_id`).
|
||||
"""
|
||||
from dataclasses import asdict
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
|
||||
from core.governance.enums import EstatusExtraccion
|
||||
from core.governance.models import ExtractionRun
|
||||
from core.ocr import OcrEstatus
|
||||
from models.cohort import COHORT_BUILDERS, describe_builder
|
||||
from models.ocr import OCR_JOBS, OcrColumnSpec, run_pending_extractions
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from models.ocr import OCR_JOBS, OcrJob, run_pending_extractions
|
||||
from models.registry import REPORT_TAGS, PromotionBlocked, registry
|
||||
from persistance.governance import (
|
||||
cohort_exclusion_count_repository,
|
||||
cohort_exclusion_repository,
|
||||
cohort_version_repository,
|
||||
extraction_run_repository,
|
||||
model_prediction_repository,
|
||||
)
|
||||
from persistance.governance import extraction_run_repository
|
||||
from persistance.repository import Repository
|
||||
|
||||
governance_bp = Blueprint("governance", __name__)
|
||||
@@ -39,9 +29,11 @@ def _bad_request(exc: ValueError):
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
|
||||
def _ocr_job_or_404(domain: str | None, entity: str | None) -> tuple[Repository, OcrColumnSpec] | None:
|
||||
def _ocr_job(domain: str | None, entity: str | None) -> OcrJob:
|
||||
job = OCR_JOBS.get((domain, entity))
|
||||
return (job.repository, job.columns) if job else None
|
||||
if job is None:
|
||||
raise LookupError(f"no hay un trabajo de OCR registrado para (domain={domain!r}, entity={entity!r})")
|
||||
return job
|
||||
|
||||
|
||||
def _pk_name(repository: Repository) -> str:
|
||||
@@ -61,7 +53,7 @@ def list_model_versions():
|
||||
@governance_bp.post("/model-versions")
|
||||
def register_model_version():
|
||||
"""Registers a trained version: `{domain, scenario,
|
||||
environment: DEV|PROD, cohort_version_id?, metrics?, hyperparameters?,
|
||||
environment: DEV|PROD, cohorte_armado_id?, metrics?, hyperparameters?,
|
||||
technical_validation_report_uri?, clinical_validation_report_uri?,
|
||||
interpretability_report_uri?}`."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
@@ -72,7 +64,7 @@ def register_model_version():
|
||||
domain=body["domain"],
|
||||
scenario=body["scenario"],
|
||||
environment=body["environment"],
|
||||
cohort_version_id=body.get("cohort_version_id"),
|
||||
cohorte_armado_id=body.get("cohorte_armado_id"),
|
||||
metrics=body.get("metrics"),
|
||||
hyperparameters=body.get("hyperparameters"),
|
||||
**{k: body[k] for k in REPORT_TAGS if k in body},
|
||||
@@ -80,11 +72,6 @@ def register_model_version():
|
||||
return jsonify(registry.describe(body["domain"], body["scenario"], version)), 201
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>")
|
||||
def get_model_version(domain: str, scenario: str, version: str):
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.patch("/model-versions/<domain>/<scenario>/<version>/reports")
|
||||
def attach_reports(domain: str, scenario: str, version: str):
|
||||
"""MLD-01/01b/03 documents, usually written after training."""
|
||||
@@ -121,19 +108,9 @@ def retire_model_version(domain: str, scenario: str, version: str):
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/compare")
|
||||
def compare_model_versions(domain: str, scenario: str):
|
||||
a, b = request.args.get("a"), request.args.get("b")
|
||||
if not a or not b:
|
||||
return jsonify({"error": "a y b deben ser versiones de MLflow"}), 400
|
||||
return jsonify(registry.compare(domain, scenario, a, b))
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/artifacts")
|
||||
def upload_artifact(domain: str, scenario: str, version: str):
|
||||
"""Multipart: `file`, `kind` (ArtifactKind) — logs it to the version's
|
||||
MLflow run. Browse/download logged artifacts via the MLflow tracking
|
||||
server directly, not through here."""
|
||||
"""Multipart `file` and `kind` (ArtifactKind); logged to the version's MLflow run."""
|
||||
from core.governance.enums import ArtifactKind
|
||||
|
||||
upload = request.files.get("file")
|
||||
@@ -146,48 +123,7 @@ def upload_artifact(domain: str, scenario: str, version: str):
|
||||
return jsonify(registry.describe(domain, scenario, version)), 201
|
||||
|
||||
|
||||
# -- cohorts ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/cohort-scenarios")
|
||||
def list_cohort_scenarios():
|
||||
"""Scenarios with a registered `CohortBuilder` (see models.cohort.register_cohort_builder)."""
|
||||
return jsonify({"scenarios": [describe_builder(cls) for cls in COHORT_BUILDERS.values()]})
|
||||
|
||||
|
||||
@governance_bp.post("/cohort-versions")
|
||||
def build_cohort_version():
|
||||
"""Builds and freezes a new cohort version: `{domain, scenario, description?}`."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
builder = COHORT_BUILDERS.get((body.get("domain"), body.get("scenario")))
|
||||
if builder is None:
|
||||
return jsonify({"error": f"no hay un CohortBuilder registrado para ({body.get('domain')!r}, {body.get('scenario')!r})"}), 404
|
||||
return jsonify(builder().build(description=body.get("description")).model_dump()), 201
|
||||
|
||||
|
||||
@governance_bp.get("/cohort-versions")
|
||||
def list_cohort_versions():
|
||||
filters = {k: v for k, v in request.args.items() if k in {"domain", "scenario"}}
|
||||
versions = cohort_version_repository.list(limit=200, **filters)
|
||||
return jsonify({"cohort_versions": [v.model_dump() for v in versions]})
|
||||
|
||||
|
||||
@governance_bp.get("/cohort-versions/<int:cohort_version_id>/exclusions")
|
||||
def get_cohort_exclusions(cohort_version_id: int):
|
||||
"""EL-05/EL-07: per-criterion counts and the per-episode log behind them."""
|
||||
counts = cohort_exclusion_count_repository.list(limit=1000, cohort_version_id=cohort_version_id)
|
||||
detail = cohort_exclusion_repository.list(limit=1000, cohort_version_id=cohort_version_id)
|
||||
return jsonify({"counts": [c.model_dump() for c in counts], "detail": [d.model_dump() for d in detail]})
|
||||
|
||||
|
||||
# -- predictions and OCR -------------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/predictions")
|
||||
def list_predictions():
|
||||
filters = {k: v for k, v in request.args.items() if k in {"domain", "pac_id_hospital", "mlflow_run_id", "modelo_nombre", "modelo_version"}}
|
||||
predictions = model_prediction_repository.list(limit=200, **filters)
|
||||
return jsonify({"predictions": [p.model_dump() for p in predictions]})
|
||||
# -- OCR ---------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/ocr/jobs")
|
||||
@@ -209,13 +145,9 @@ def list_ocr_jobs():
|
||||
def list_ocr_rows(domain: str, entity: str):
|
||||
"""Rows of an OCR job filtered by `status`: `review` (the default, rows
|
||||
flagged `requiere_revision`), `pending`, `failed`, `done` or `all`.
|
||||
|
||||
Filtering happens in Python because `Repository.list` only supports
|
||||
equality filters; a review queue is small."""
|
||||
job = _ocr_job_or_404(domain, entity)
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
|
||||
repository, spec = job
|
||||
Filtering happens in Python: `Repository.list` only supports equality."""
|
||||
job = _ocr_job(domain, entity)
|
||||
repository, spec = job.repository, job.columns
|
||||
|
||||
status = request.args.get("status", "review")
|
||||
limit = int(request.args.get("limit", 100))
|
||||
@@ -238,7 +170,7 @@ def list_ocr_rows(domain: str, entity: str):
|
||||
return estatus == OcrEstatus.REALIZADO.value
|
||||
return True
|
||||
|
||||
candidates = [row for row in repository.list(limit=2000) if matches(row)]
|
||||
candidates = [row for row in repository.iter_all() if matches(row)]
|
||||
page = candidates[offset : offset + limit]
|
||||
rows = [
|
||||
{
|
||||
@@ -259,13 +191,11 @@ def list_ocr_rows(domain: str, entity: str):
|
||||
@governance_bp.get("/ocr/<domain>/<entity>/<int:pk>/blob")
|
||||
def get_ocr_blob(domain: str, entity: str, pk: int):
|
||||
"""Raw bytes of the row's stored PDF, for the review UI's page viewer."""
|
||||
job = _ocr_job_or_404(domain, entity)
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
|
||||
repository, spec = job
|
||||
job = _ocr_job(domain, entity)
|
||||
repository, spec = job.repository, job.columns
|
||||
row = repository.get(pk)
|
||||
if row is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify({"error": "no se encontró el registro"}), 404
|
||||
blob = getattr(row, spec.blob_field, None)
|
||||
if blob is None:
|
||||
return jsonify({"error": "esta fila no tiene un PDF almacenado"}), 404
|
||||
@@ -277,10 +207,8 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
|
||||
"""Stores values entered by a reviewer for an OCR row. Marks the row
|
||||
done with method "manual" (VAR-03), clears `requiere_revision`, and logs
|
||||
an `ExtractionRun` like an automated run (VAR-07/08)."""
|
||||
job = _ocr_job_or_404(domain, entity)
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
|
||||
repository, spec = job
|
||||
job = _ocr_job(domain, entity)
|
||||
repository, spec = job.repository, job.columns
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
values = body.get("values")
|
||||
@@ -294,7 +222,7 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
|
||||
with repository.open_session() as session:
|
||||
tracked = session.get(repository.model, pk)
|
||||
if tracked is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify({"error": "no se encontró el registro"}), 404
|
||||
for column, value in values.items():
|
||||
setattr(tracked, column, value)
|
||||
setattr(tracked, spec.estatus_field, OcrEstatus.REALIZADO.value)
|
||||
@@ -313,7 +241,7 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
|
||||
entity=entity,
|
||||
entity_pk=str(pk),
|
||||
column_extracted=",".join(sorted(values)),
|
||||
transform_description="Corrección manual vía UI de gobernanza — usuario revisó el PDF y escribió el valor directamente.",
|
||||
transform_description="Corrección manual",
|
||||
estatus=EstatusExtraccion.COMPLETADA,
|
||||
)
|
||||
)
|
||||
@@ -327,9 +255,7 @@ def run_ocr():
|
||||
body = request.get_json(silent=True) or {}
|
||||
domain = body.get("domain")
|
||||
entity = body.get("entity")
|
||||
job = OCR_JOBS.get((domain, entity))
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 400
|
||||
job = _ocr_job(domain, entity)
|
||||
|
||||
try:
|
||||
summary = run_pending_extractions(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""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
|
||||
|
||||
@@ -14,6 +15,7 @@ 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,
|
||||
@@ -28,6 +30,7 @@ from webapi.imports.services.introspection_service import (
|
||||
)
|
||||
|
||||
imports_bp = Blueprint("imports", __name__)
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BadRequest(Exception):
|
||||
@@ -45,20 +48,20 @@ def _bad_request(exc: Exception):
|
||||
def _json_body() -> dict:
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
raise BadRequest("request body must be a JSON object")
|
||||
raise BadRequest("el cuerpo de la solicitud debe ser un objeto JSON")
|
||||
return body
|
||||
|
||||
|
||||
def _require(mapping: dict, key: str):
|
||||
value = mapping.get(key)
|
||||
if value in (None, ""):
|
||||
raise BadRequest(f"missing {key}")
|
||||
raise BadRequest(f"falta {key}")
|
||||
return value
|
||||
|
||||
|
||||
def _uploaded_file() -> tuple[str, bytes]:
|
||||
if "file" not in request.files:
|
||||
raise BadRequest("missing file")
|
||||
raise BadRequest("falta el archivo")
|
||||
upload = request.files["file"]
|
||||
return upload.filename or "", upload.read()
|
||||
|
||||
@@ -67,12 +70,12 @@ def _form_int(key: str, default: int | None = None) -> int:
|
||||
raw = request.form.get(key)
|
||||
if raw is None:
|
||||
if default is None:
|
||||
raise BadRequest(f"missing {key}")
|
||||
raise BadRequest(f"falta {key}")
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError as exc:
|
||||
raise BadRequest(f"{key} must be an integer") from exc
|
||||
raise BadRequest(f"{key} debe ser un número entero") from exc
|
||||
|
||||
|
||||
def _form_json(key: str, default=None):
|
||||
@@ -82,12 +85,12 @@ def _form_json(key: str, default=None):
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise BadRequest(f"{key} must be JSON: {exc}") from exc
|
||||
raise BadRequest(f"{key} debe ser JSON válido: {exc}") from exc
|
||||
|
||||
|
||||
def _outcome(exc: Exception) -> str:
|
||||
"""How an attempt that raised is logged."""
|
||||
if isinstance(exc, ImportRequestError) and str(exc).startswith("the database refused"):
|
||||
if isinstance(exc, DatabaseRefused):
|
||||
return "rechazada_por_la_base"
|
||||
if isinstance(exc, (BadRequest, ConnectorError, ExtractionError, ImportRequestError)):
|
||||
return "solicitud_invalida"
|
||||
@@ -148,7 +151,7 @@ def preview_file():
|
||||
kind = request.form.get("source_kind") or kind_for_filename(name)
|
||||
cls = connector_class(kind)
|
||||
if not issubclass(cls, FileConnector):
|
||||
raise BadRequest(f"{kind!r} is not a file source")
|
||||
raise BadRequest(f"{kind!r} no es una fuente de archivo")
|
||||
options = _form_json("options", {}) or {}
|
||||
if "file_name" in cls.option_names:
|
||||
options.setdefault("file_name", name)
|
||||
@@ -226,7 +229,7 @@ def pdf_table_preview():
|
||||
page_number = _form_int("page_number")
|
||||
bbox = _form_json("bbox")
|
||||
if not isinstance(bbox, list) or len(bbox) != 4:
|
||||
raise BadRequest("missing page_number or bbox")
|
||||
raise BadRequest("falta page_number o bbox")
|
||||
connector = PdfConnector(raw)
|
||||
connector.select_table(page_number, tuple(float(v) for v in bbox))
|
||||
return jsonify(preview_with_suggestions(connector, request.form.get("target")))
|
||||
@@ -253,7 +256,7 @@ def document_extract():
|
||||
body = _json_body()
|
||||
_require(body, "target")
|
||||
if not body.get("files"):
|
||||
raise BadRequest("missing files")
|
||||
raise BadRequest("faltan los archivos")
|
||||
return jsonify(document_report(body))
|
||||
|
||||
|
||||
@@ -269,7 +272,7 @@ def document_page_image():
|
||||
if bbox is None:
|
||||
return Response(reader.render_page(raw, page_number, dpi=dpi), mimetype="image/png")
|
||||
if not isinstance(bbox, list) or len(bbox) != 4:
|
||||
raise BadRequest("bbox must be [x0, y0, x1, y1]")
|
||||
raise BadRequest("bbox debe ser [x0, y0, x1, y1]")
|
||||
return Response(reader.render_region(raw, page_number, BBox(*map(float, bbox)), dpi=dpi), mimetype="image/png")
|
||||
|
||||
|
||||
@@ -317,14 +320,19 @@ def commit():
|
||||
audit.succeed()
|
||||
finally:
|
||||
import_audit.record(audit)
|
||||
written = sum(r.created + r.updated for r in results)
|
||||
if written and audit.domain:
|
||||
ColaDeRecalculo().solicitar(audit.domain)
|
||||
recalculating = False
|
||||
if audit.domain and any(r.created or r.updated for r in results):
|
||||
try:
|
||||
ColaDeRecalculo().solicitar(audit.domain)
|
||||
recalculating = True
|
||||
except OSError:
|
||||
# The rows are already saved; failing here would invite a duplicate retry.
|
||||
log.exception("no se pudo solicitar el recálculo de %s", audit.domain)
|
||||
return jsonify(
|
||||
{
|
||||
"ok": all(r.rejected == 0 for r in results),
|
||||
"audit_id": audit.id,
|
||||
"indicadores_en_recalculo": bool(written and audit.domain),
|
||||
"indicadores_en_recalculo": recalculating,
|
||||
"results": [
|
||||
{
|
||||
"target": r.target,
|
||||
|
||||
@@ -1,40 +1,7 @@
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from models.prediction import ApplicabilityRejected, PredictionService
|
||||
from models.tea import TeaModel
|
||||
from flask import Blueprint
|
||||
from persistance.db import get_tea_session
|
||||
from persistance.tea import pacientes_repository
|
||||
|
||||
from webapi.indicadores import registrar_indicadores
|
||||
|
||||
tea_bp = Blueprint("tea", __name__)
|
||||
registrar_indicadores(tea_bp, "tea", get_tea_session)
|
||||
|
||||
|
||||
@tea_bp.get("/pacientes/<int:pac_id>")
|
||||
def get_paciente(pac_id: int):
|
||||
paciente = pacientes_repository.get(pac_id)
|
||||
if paciente is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify(paciente.model_dump())
|
||||
|
||||
|
||||
@tea_bp.post("/predict")
|
||||
def predict():
|
||||
"""Predict and record the result against the active `ModelVersion` (MLD-4/MLD-5).
|
||||
|
||||
Returns 501 while `TeaModel.predict` is not implemented."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
service = PredictionService(TeaModel(), domain="tea", scenario=body.get("scenario", "tamizaje"))
|
||||
try:
|
||||
prediction = service.predict_and_record(
|
||||
body.get("data"),
|
||||
pac_id_hospital=body.get("pac_id_hospital", ""),
|
||||
episodio_id=body.get("episodio_id"),
|
||||
)
|
||||
except NotImplementedError as exc:
|
||||
return jsonify({"error": str(exc)}), 501
|
||||
except ApplicabilityRejected as exc:
|
||||
return jsonify({"error": str(exc)}), 422
|
||||
except RuntimeError as exc:
|
||||
return jsonify({"error": str(exc)}), 503
|
||||
return jsonify(prediction.model_dump())
|
||||
|
||||
+6
-15
@@ -8,8 +8,8 @@ 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; an `AuditSink`
|
||||
decides where the finished record goes.
|
||||
`ImportAudit` collects the facts while the import runs; `JsonlAuditSink`
|
||||
appends the finished record.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -19,7 +19,6 @@ import os
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from abc import ABC, abstractmethod
|
||||
from collections import Counter, defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
@@ -246,15 +245,7 @@ class ImportAudit:
|
||||
return record
|
||||
|
||||
|
||||
class AuditSink(ABC):
|
||||
@abstractmethod
|
||||
def write(self, record: dict[str, Any]) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
def read(self) -> list[dict[str, Any]]: ...
|
||||
|
||||
|
||||
class JsonlAuditSink(AuditSink):
|
||||
class JsonlAuditSink:
|
||||
"""One JSON object per line; appends are locked so several gunicorn
|
||||
workers can share the file."""
|
||||
|
||||
@@ -287,14 +278,14 @@ class JsonlAuditSink(AuditSink):
|
||||
return records
|
||||
|
||||
|
||||
def default_sink() -> AuditSink:
|
||||
def default_sink() -> JsonlAuditSink:
|
||||
return JsonlAuditSink(report_dir() / "importaciones.jsonl")
|
||||
|
||||
|
||||
def record(audit: ImportAudit, sink: AuditSink | None = None) -> None:
|
||||
def record(audit: ImportAudit) -> None:
|
||||
"""Writes the record; a full disk must not turn a successful import into an error."""
|
||||
try:
|
||||
(sink or default_sink()).write(audit.as_dict())
|
||||
default_sink().write(audit.as_dict())
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
@@ -53,9 +53,6 @@ class Connector(ABC):
|
||||
"""Builds a ready-to-read connector from the JSON a client sends
|
||||
in an import request's `payload`."""
|
||||
|
||||
@abstractmethod
|
||||
def get_columns(self) -> list[SourceColumn]: ...
|
||||
|
||||
@abstractmethod
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult: ...
|
||||
|
||||
@@ -88,6 +85,6 @@ def decode_file(payload: dict[str, Any], key: str = "file_base64") -> bytes:
|
||||
try:
|
||||
return base64.b64decode(payload[key], validate=True)
|
||||
except KeyError as exc:
|
||||
raise ConnectorError(f"missing {key}") from exc
|
||||
raise ConnectorError(f"falta {key}") from exc
|
||||
except (binascii.Error, ValueError, TypeError) as exc:
|
||||
raise ConnectorError(f"{key} is not valid base64: {exc}") from exc
|
||||
raise ConnectorError(f"{key} no es base64 válido: {exc}") from exc
|
||||
|
||||
@@ -30,7 +30,7 @@ class CsvConnector(FileConnector):
|
||||
def __init__(self, raw: bytes, *, delimiter: str | None = None, encoding: str | None = None):
|
||||
self._encoding, text = _decode(raw, encoding)
|
||||
if "\x00" in text:
|
||||
raise ConnectorError("file looks binary, not a delimited text file")
|
||||
raise ConnectorError("el archivo parece binario, no un texto delimitado")
|
||||
self._delimiter = delimiter or _sniff_delimiter(text)
|
||||
try:
|
||||
self._df = pd.read_csv(
|
||||
@@ -42,7 +42,7 @@ class CsvConnector(FileConnector):
|
||||
skipinitialspace=True,
|
||||
)
|
||||
except Exception as exc: # pandas raises a variety of error types
|
||||
raise ConnectorError(f"could not parse CSV: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo leer el CSV: {exc}") from exc
|
||||
self._df.columns = [str(c).strip() for c in self._df.columns]
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
@@ -58,7 +58,7 @@ def _decode(raw: bytes, encoding: str | None) -> tuple[str, str]:
|
||||
return candidate, raw.decode(candidate)
|
||||
except (UnicodeDecodeError, LookupError):
|
||||
continue
|
||||
raise ConnectorError(f"could not decode CSV as {encoding or ' / '.join(_FALLBACK_ENCODINGS)}")
|
||||
raise ConnectorError(f"no se pudo decodificar el CSV como {encoding or ' / '.join(_FALLBACK_ENCODINGS)}")
|
||||
|
||||
|
||||
def _sniff_delimiter(text: str) -> str:
|
||||
|
||||
@@ -82,14 +82,14 @@ class DocumentConnector(DataFrameConnector):
|
||||
overrides: dict[str, dict[str, Any]] | None = None,
|
||||
):
|
||||
if not files:
|
||||
raise ConnectorError("no documents given")
|
||||
raise ConnectorError("no se recibieron documentos")
|
||||
entity = ENTITY_REGISTRY.get(target)
|
||||
if entity is None:
|
||||
raise ConnectorError(f"unknown target: {target!r}")
|
||||
raise ConnectorError(f"destino desconocido: {target!r}")
|
||||
if segmentation not in SEGMENTERS:
|
||||
raise ConnectorError(f"unknown segmentation {segmentation!r} (available: {', '.join(SEGMENTERS)})")
|
||||
raise ConnectorError(f"segmentación desconocida {segmentation!r} (disponibles: {', '.join(SEGMENTERS)})")
|
||||
if ocr_mode not in ("auto", "always", "never"):
|
||||
raise ConnectorError(f"unknown ocr_mode {ocr_mode!r}")
|
||||
raise ConnectorError(f"ocr_mode desconocido {ocr_mode!r}")
|
||||
self.files = files
|
||||
self.target = target
|
||||
self.specs = field_specs_for(entity, key_pattern=key_pattern)
|
||||
@@ -175,12 +175,9 @@ class DocumentConnector(DataFrameConnector):
|
||||
return combine_pages(parts) if parts else None
|
||||
|
||||
def _record_image(self, record: ExtractedRecord) -> bytes | None:
|
||||
"""A PNG of the clearest picture embedded on the record's pages (a
|
||||
mammogram, a lesion photo) — mappable onto a target's own image
|
||||
column (e.g. `mast_dicom_blob`), the same way `documento` maps onto
|
||||
a PDF column. A `scan` is the page itself, not a distinct picture,
|
||||
so a `figure` wins when both are present; with several figures, the
|
||||
first one found is used."""
|
||||
"""A PNG of the first picture embedded on the record's pages (a mammogram,
|
||||
a lesion photo), mappable onto an image column such as `mast_dicom_blob`.
|
||||
A `figure` wins over a `scan`, which is the whole page."""
|
||||
by_name = dict(self.files)
|
||||
candidates = [(document, image) for document, image in record.images if document in by_name]
|
||||
if not candidates:
|
||||
|
||||
@@ -29,19 +29,20 @@ class EdfConnector(FileConnector):
|
||||
extensions = ("edf",)
|
||||
option_names = ("file_name",)
|
||||
|
||||
def __init__(self, raw: bytes, *, file_name: str = "registro.edf"):
|
||||
self.files = [(file_name, raw)]
|
||||
def __init__(self, files: list[tuple[str, bytes]]):
|
||||
self.files = files
|
||||
self._df: pd.DataFrame | None = None
|
||||
|
||||
@classmethod
|
||||
def from_bytes(cls, raw: bytes, options: dict[str, Any] | None = None) -> "EdfConnector":
|
||||
return cls([((options or {}).get("file_name") or "registro.edf", raw)])
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "EdfConnector":
|
||||
"""Accepts one file (`file_base64` + `options.file_name`) or several
|
||||
(`files: [{name, file_base64}]`)."""
|
||||
"""One file (`file_base64` + `options.file_name`) or several (`files: [{name, file_base64}]`)."""
|
||||
if not payload.get("files"):
|
||||
return super().from_payload(payload)
|
||||
connector = cls(b"", file_name="")
|
||||
connector.files = [(f.get("name") or f"registro_{i}.edf", decode_file(f)) for i, f in enumerate(payload["files"], 1)]
|
||||
return connector
|
||||
return cls([(f.get("name") or f"registro_{i}.edf", decode_file(f)) for i, f in enumerate(payload["files"], 1)])
|
||||
|
||||
def metadata(self) -> dict[str, Any]:
|
||||
return {"files": [name for name, _ in self.files]}
|
||||
|
||||
@@ -25,15 +25,15 @@ class ExcelConnector(FileConnector):
|
||||
try:
|
||||
self._workbook = pd.ExcelFile(io.BytesIO(raw), engine="openpyxl")
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not open Excel file: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo abrir el archivo de Excel: {exc}") from exc
|
||||
|
||||
self._sheet = sheet_name if sheet_name not in (None, "") else self._workbook.sheet_names[0]
|
||||
if isinstance(self._sheet, str) and self._sheet not in self._workbook.sheet_names:
|
||||
raise ConnectorError(f"sheet {self._sheet!r} not found — available: {self._workbook.sheet_names}")
|
||||
raise ConnectorError(f"no existe la hoja {self._sheet!r} (disponibles: {self._workbook.sheet_names})")
|
||||
try:
|
||||
self._df = self._workbook.parse(self._sheet, dtype=object)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not read sheet {self._sheet!r}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo leer la hoja {self._sheet!r}: {exc}") from exc
|
||||
self._df.columns = [str(c).strip() for c in self._df.columns]
|
||||
|
||||
def list_sheets(self) -> list[str]:
|
||||
|
||||
@@ -26,19 +26,19 @@ class JsonConnector(FileConnector):
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not parse JSON: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo leer el JSON: {exc}") from exc
|
||||
|
||||
if record_path:
|
||||
try:
|
||||
for key in record_path.split("."):
|
||||
data = data[key]
|
||||
except (KeyError, TypeError, IndexError) as exc:
|
||||
raise ConnectorError(f"record_path {record_path!r} not found: {exc}") from exc
|
||||
raise ConnectorError(f"no se encontró record_path {record_path!r}: {exc}") from exc
|
||||
|
||||
if isinstance(data, dict):
|
||||
data = data.get("data", [data])
|
||||
if not isinstance(data, list) or not all(isinstance(record, dict) for record in data):
|
||||
raise ConnectorError("JSON source must resolve to a list of objects")
|
||||
raise ConnectorError("el JSON debe dar una lista de objetos")
|
||||
|
||||
self._record_path = record_path
|
||||
self._df = pd.DataFrame([_flatten(record) for record in data], dtype=object)
|
||||
|
||||
@@ -54,7 +54,7 @@ class RegionSpec:
|
||||
try:
|
||||
return cls(str(raw["target_field"]), [int(n) for n in raw["page_numbers"]], tuple(float(v) for v in raw["bbox"]))
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise ConnectorError(f"invalid region: {exc}") from exc
|
||||
raise ConnectorError(f"región inválida: {exc}") from exc
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -81,7 +81,7 @@ class PdfConnector(DataFrameConnector):
|
||||
elif mode == "regions":
|
||||
connector.extract_regions([RegionSpec.parse(r) for r in payload["regions"]], dpi=int(payload.get("dpi", _DEFAULT_DPI)))
|
||||
else:
|
||||
raise ConnectorError(f"unknown pdf mode: {mode!r}")
|
||||
raise ConnectorError(f"modo de PDF desconocido: {mode!r}")
|
||||
return connector
|
||||
|
||||
def __init__(self, file_bytes: bytes):
|
||||
@@ -89,7 +89,7 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
self._pdf = pdfplumber.open(io.BytesIO(file_bytes))
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not open PDF: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo abrir el PDF: {exc}") from exc
|
||||
|
||||
self._table_grid: list[list[str | None]] | None = None
|
||||
self._region_rows: dict[str, list[str | None]] | None = None
|
||||
@@ -120,12 +120,12 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
tables = page.find_tables()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not detect tables on page {page.page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron detectar tablas en la página {page.page_number}: {exc}") from exc
|
||||
for table in tables:
|
||||
try:
|
||||
grid = table.extract()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not extract table on page {page.page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo extraer la tabla de la página {page.page_number}: {exc}") from exc
|
||||
if len(grid) < 2:
|
||||
continue # header + >=1 data row required
|
||||
candidates.append(
|
||||
@@ -145,9 +145,9 @@ class PdfConnector(DataFrameConnector):
|
||||
cropped = page.within_bbox(bbox, strict=False)
|
||||
grid = cropped.extract_table()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not extract table at {bbox} on page {page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo extraer la tabla en {bbox} de la página {page_number}: {exc}") from exc
|
||||
if not grid or len(grid) < 2:
|
||||
raise ConnectorError(f"no usable table found at {bbox} on page {page_number}")
|
||||
raise ConnectorError(f"no se encontró una tabla utilizable en {bbox} de la página {page_number}")
|
||||
self._table_grid = grid
|
||||
self._region_rows = None
|
||||
|
||||
@@ -161,14 +161,14 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
image = page.to_image(resolution=dpi).original
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not render page {page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo dibujar la página {page_number}: {exc}") from exc
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
def extract_regions(self, regions: list[RegionSpec], dpi: int = _DEFAULT_DPI) -> dict[str, list[str | None]]:
|
||||
if not regions:
|
||||
raise ConnectorError("no regions given")
|
||||
raise ConnectorError("no se indicaron regiones")
|
||||
_check_dpi(dpi)
|
||||
|
||||
by_page: dict[int, list[RegionSpec]] = {}
|
||||
@@ -183,8 +183,9 @@ class PdfConnector(DataFrameConnector):
|
||||
page = self._page(page_number)
|
||||
lines = self._lines_for_page(page, by_page[page_number], dpi)
|
||||
for row in self._cluster_rows(lines, page_number):
|
||||
for region in by_page[page_number]:
|
||||
result[region.target_field].append(row.get(region.target_field))
|
||||
# Every field gets a cell per row, even regions not drawn on this page.
|
||||
for field_name in result:
|
||||
result[field_name].append(row.get(field_name))
|
||||
|
||||
self._region_rows = result
|
||||
self._table_grid = None
|
||||
@@ -210,7 +211,7 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
region_lines = page.within_bbox(point_bbox, strict=False).extract_text_lines()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not extract text for region {region.target_field!r}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo extraer el texto de la región {region.target_field!r}: {exc}") from exc
|
||||
for line in region_lines:
|
||||
text = (line.get("text") or "").strip()
|
||||
if not text:
|
||||
@@ -228,7 +229,7 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
rendered_image = page.to_image(resolution=dpi).original
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not render page {page.page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo dibujar la página {page.page_number}: {exc}") from exc
|
||||
img_w, img_h = rendered_image.size
|
||||
crop_box = (
|
||||
max(0, round(x0n * img_w)),
|
||||
@@ -242,7 +243,7 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
data = pytesseract.image_to_data(cropped, output_type=Output.DICT, lang=DEFAULT_LANG, config=_OCR_CONFIG)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"OCR failed for region {region.target_field!r}: {exc}") from exc
|
||||
raise ConnectorError(f"falló el OCR de la región {region.target_field!r}: {exc}") from exc
|
||||
for words in group_words(data):
|
||||
text = " ".join(w["text"] for w in words).strip()
|
||||
if not text:
|
||||
@@ -306,7 +307,7 @@ class PdfConnector(DataFrameConnector):
|
||||
self.warnings.append(
|
||||
ExtractionWarning(
|
||||
page_number=page_number,
|
||||
message=f"alignment conflict on field(s) {duplicated}: cluster split at largest internal gap",
|
||||
message=f"conflicto de alineación en {duplicated}: el grupo se dividió en el mayor espacio interno",
|
||||
)
|
||||
)
|
||||
return self._split_conflicts(left, page_number) + self._split_conflicts(right, page_number)
|
||||
@@ -322,13 +323,13 @@ class PdfConnector(DataFrameConnector):
|
||||
return pd.DataFrame(data_rows, columns=columns)
|
||||
if self._region_rows is not None:
|
||||
return pd.DataFrame(self._region_rows)
|
||||
raise ConnectorError("no table or region resolved — call select_table() or extract_regions() first")
|
||||
raise ConnectorError("no hay tabla ni regiones seleccionadas")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _page(self, page_number: int):
|
||||
if not (1 <= page_number <= self.page_count):
|
||||
raise ConnectorError(f"page_number out of range: {page_number}")
|
||||
raise ConnectorError(f"page_number fuera de rango: {page_number}")
|
||||
return self._pdf.pages[page_number - 1]
|
||||
|
||||
@staticmethod
|
||||
@@ -340,7 +341,7 @@ class PdfConnector(DataFrameConnector):
|
||||
|
||||
def _check_dpi(dpi: int) -> None:
|
||||
if not (_MIN_DPI <= dpi <= _MAX_DPI):
|
||||
raise ConnectorError(f"dpi must be between {_MIN_DPI} and {_MAX_DPI}, got {dpi}")
|
||||
raise ConnectorError(f"dpi debe estar entre {_MIN_DPI} y {_MAX_DPI} (se recibió {dpi})")
|
||||
|
||||
|
||||
def _table_confidence(grid: list[list[str | None]]) -> float:
|
||||
|
||||
@@ -16,17 +16,17 @@ def register_connector(cls: type[Connector]) -> type[Connector]:
|
||||
def connector_class(kind: str | None) -> type[Connector]:
|
||||
cls = CONNECTORS.get(kind or "")
|
||||
if cls is None:
|
||||
raise ConnectorError(f"unknown source kind {kind!r} (available: {', '.join(sorted(CONNECTORS))})")
|
||||
raise ConnectorError(f"tipo de fuente desconocido {kind!r} (disponibles: {', '.join(sorted(CONNECTORS))})")
|
||||
return cls
|
||||
|
||||
|
||||
def build_connector(kind: str | None, payload: dict[str, Any]) -> Connector:
|
||||
if not isinstance(payload, dict):
|
||||
raise ConnectorError("payload must be an object")
|
||||
raise ConnectorError("payload debe ser un objeto")
|
||||
try:
|
||||
return connector_class(kind).from_payload(payload)
|
||||
except KeyError as exc:
|
||||
raise ConnectorError(f"missing field in payload: {exc}") from exc
|
||||
raise ConnectorError(f"falta un campo en payload: {exc}") from exc
|
||||
|
||||
|
||||
def kind_for_filename(filename: str) -> str | None:
|
||||
|
||||
@@ -91,21 +91,21 @@ class SqlConnector(Connector):
|
||||
return cls(cls.server_url(payload["server"]))
|
||||
if payload.get("connection_string"):
|
||||
return cls(payload["connection_string"])
|
||||
raise ConnectorError("missing server or connection_string")
|
||||
raise ConnectorError("falta server o connection_string")
|
||||
|
||||
@classmethod
|
||||
def server_url(cls, server: dict[str, Any]) -> sa.engine.URL:
|
||||
engine = cls.ENGINES.get(server.get("engine", ""))
|
||||
if engine is None:
|
||||
raise ConnectorError(f"unknown engine {server.get('engine')!r} (available: {', '.join(cls.ENGINES)})")
|
||||
raise ConnectorError(f"motor desconocido {server.get('engine')!r} (disponibles: {', '.join(cls.ENGINES)})")
|
||||
if not engine.available:
|
||||
raise ConnectorError(f"the {engine.label} driver ({engine.driver_module}) is not installed on the server")
|
||||
raise ConnectorError(f"el controlador de {engine.label} ({engine.driver_module}) no está instalado en el servidor")
|
||||
if not server.get("host") or not server.get("database"):
|
||||
raise ConnectorError("host and database are required")
|
||||
raise ConnectorError("se requieren el servidor (host) y la base de datos")
|
||||
try:
|
||||
port = int(server.get("port") or engine.default_port)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ConnectorError("port must be a number") from exc
|
||||
raise ConnectorError("el puerto debe ser un número") from exc
|
||||
return sa.engine.URL.create(
|
||||
engine.drivername,
|
||||
username=server.get("user") or None,
|
||||
@@ -121,7 +121,7 @@ class SqlConnector(Connector):
|
||||
try:
|
||||
self._engine = sa.create_engine(url, poolclass=NullPool)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"invalid connection string: {exc}") from exc
|
||||
raise ConnectorError(f"cadena de conexión inválida: {exc}") from exc
|
||||
self._table: sa.Table | None = None
|
||||
self._query: str | None = None
|
||||
|
||||
@@ -134,7 +134,7 @@ class SqlConnector(Connector):
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not connect: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo conectar: {exc}") from exc
|
||||
|
||||
def get_dialect(self) -> str:
|
||||
return self._engine.dialect.name
|
||||
@@ -143,27 +143,27 @@ class SqlConnector(Connector):
|
||||
try:
|
||||
return sa.inspect(self._engine).get_schema_names()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not list schemas: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron listar los esquemas: {exc}") from exc
|
||||
|
||||
def list_tables(self, *, schema: str | None = None) -> list[str]:
|
||||
try:
|
||||
inspector = sa.inspect(self._engine)
|
||||
return inspector.get_table_names(schema=schema) + inspector.get_view_names(schema=schema)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not list tables: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron listar las tablas: {exc}") from exc
|
||||
|
||||
def list_columns(self, table_name: str, *, schema: str | None = None) -> list[SourceColumn]:
|
||||
try:
|
||||
columns = sa.inspect(self._engine).get_columns(table_name, schema=schema)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not list columns: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron listar las columnas: {exc}") from exc
|
||||
return [SourceColumn(name=c["name"], inferred_type=_sa_type_to_kind(c["type"])) for c in columns]
|
||||
|
||||
def select_table(self, table_name: str, *, schema: str | None = None) -> "SqlConnector":
|
||||
try:
|
||||
self._table = sa.Table(table_name, sa.MetaData(), schema=schema, autoload_with=self._engine)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not open table {table_name!r}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo abrir la tabla {table_name!r}: {exc}") from exc
|
||||
self._query = None
|
||||
return self
|
||||
|
||||
@@ -173,9 +173,6 @@ class SqlConnector(Connector):
|
||||
|
||||
# -- Connector ----------------------------------------------------------
|
||||
|
||||
def get_columns(self) -> list[SourceColumn]:
|
||||
return self.preview(limit=200).columns
|
||||
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult:
|
||||
statement = self._selectable()
|
||||
try:
|
||||
@@ -187,7 +184,7 @@ class SqlConnector(Connector):
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not read rows: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron leer las filas: {exc}") from exc
|
||||
return PreviewResult(columns=self._columns(names, rows), sample_rows=rows, total_rows=total)
|
||||
|
||||
def read_rows(self, column_mapping: dict[str, str]) -> Iterator[dict[str, Any]]:
|
||||
@@ -200,7 +197,7 @@ class SqlConnector(Connector):
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not read rows: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron leer las filas: {exc}") from exc
|
||||
|
||||
# -- internals ----------------------------------------------------------
|
||||
|
||||
@@ -209,7 +206,7 @@ class SqlConnector(Connector):
|
||||
return sa.select(self._table).subquery("source")
|
||||
if self._query:
|
||||
return _text_subquery(self._query)
|
||||
raise ConnectorError("no table or query selected — call select_table()/select_query() first")
|
||||
raise ConnectorError("no hay tabla ni consulta seleccionada")
|
||||
|
||||
def _columns(self, names: list[str], rows: list[dict[str, Any]]) -> list[SourceColumn]:
|
||||
if self._table is not None:
|
||||
|
||||
@@ -18,7 +18,8 @@ from sqlalchemy.exc import ArgumentError
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
|
||||
_DEFAULT_DIALECTS = "mysql,mariadb,postgresql,mssql,oracle"
|
||||
_DEFAULT_DIALECTS = "mysql,mariadb,postgresql,mssql"
|
||||
_DEFAULT_PORTS = {"mysql": 3306, "mariadb": 3306, "postgresql": 5432, "mssql": 1433}
|
||||
_LEADING_COMMENTS = re.compile(r"^\s*((--[^\n]*\n)|(/\*.*?\*/)|\s)*", re.S)
|
||||
|
||||
|
||||
@@ -40,27 +41,27 @@ class SqlSourcePolicy:
|
||||
try:
|
||||
url = connection if isinstance(connection, URL) else make_url(connection)
|
||||
except ArgumentError as exc:
|
||||
raise ConnectorError(f"invalid connection string: {exc}") from exc
|
||||
raise ConnectorError(f"cadena de conexión inválida: {exc}") from exc
|
||||
dialect = url.get_backend_name()
|
||||
if dialect not in self.allowed_dialects:
|
||||
raise ConnectorError(
|
||||
f"dialect {dialect!r} is not allowed for import sources (allowed: {', '.join(sorted(self.allowed_dialects))})"
|
||||
f"el motor {dialect!r} no está permitido como fuente (permitidos: {', '.join(sorted(self.allowed_dialects))})"
|
||||
)
|
||||
if self.allowed_hosts is not None and (url.host or "").lower() not in self.allowed_hosts:
|
||||
raise ConnectorError(f"host {url.host!r} is not in the allowed import-source hosts")
|
||||
raise ConnectorError(f"el servidor {url.host!r} no está entre los permitidos como fuente")
|
||||
if _same_database(url, _own_database_urls()):
|
||||
raise ConnectorError("this connection points at the application's own database — not a valid import source")
|
||||
raise ConnectorError("esta conexión apunta a una base de datos de la propia aplicación; no puede ser una fuente")
|
||||
return url
|
||||
|
||||
@staticmethod
|
||||
def check_query(query: str) -> str:
|
||||
statement = query.strip().rstrip(";").strip()
|
||||
if ";" in statement:
|
||||
raise ConnectorError("custom SQL must be a single statement")
|
||||
raise ConnectorError("la consulta debe ser una sola instrucción")
|
||||
body = _LEADING_COMMENTS.sub("", statement, count=1)
|
||||
first_word = body.split(None, 1)[0].upper() if body else ""
|
||||
if first_word not in ("SELECT", "WITH"):
|
||||
raise ConnectorError("custom SQL must be a SELECT (or WITH ... SELECT) query")
|
||||
raise ConnectorError("la consulta debe ser un SELECT (o WITH ... SELECT)")
|
||||
return statement
|
||||
|
||||
|
||||
@@ -85,6 +86,8 @@ def _same_database(candidate: URL, own: list[URL]) -> bool:
|
||||
def key(url: URL) -> tuple:
|
||||
if url.get_backend_name() == "sqlite":
|
||||
return ("sqlite", os.path.realpath(url.database or ""))
|
||||
return (url.get_backend_name(), (url.host or "localhost").lower(), url.port, (url.database or "").lower())
|
||||
backend = url.get_backend_name()
|
||||
port = url.port or _DEFAULT_PORTS.get(backend)
|
||||
return (backend, (url.host or "localhost").lower(), port, (url.database or "").lower())
|
||||
|
||||
return key(candidate) in {key(url) for url in own}
|
||||
|
||||
@@ -16,9 +16,6 @@ class DataFrameConnector(Connector):
|
||||
@abstractmethod
|
||||
def _dataframe(self) -> pd.DataFrame: ...
|
||||
|
||||
def get_columns(self) -> list[SourceColumn]:
|
||||
return columns_from_dataframe(self._dataframe())
|
||||
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult:
|
||||
df = self._dataframe()
|
||||
return PreviewResult(
|
||||
|
||||
@@ -11,6 +11,8 @@ SYNONYMS: dict[str, set[str]] = {
|
||||
"pac_id_hospital": {
|
||||
"id_hospital", "hospital_id", "expediente", "num_expediente", "no_expediente", "numero_expediente",
|
||||
"exp", "nss", "id_paciente", "paciente_id", "folio_paciente", "clave_paciente",
|
||||
# A source may name the patient column after the entity.
|
||||
"paciente",
|
||||
},
|
||||
"pac_fecha_nacimiento": {"fecha_nacimiento", "dob", "birth_date", "fecha_nac", "fec_nac", "f_nac", "f_nacimiento", "nacimiento"},
|
||||
"pac_sexo": {"sexo", "genero", "gender", "sex"},
|
||||
@@ -31,15 +33,11 @@ SYNONYMS: dict[str, set[str]] = {
|
||||
"bx_cin_grado": {"grado_cin", "cin", "resultado_histopatologico", "diagnostico_histopatologico"},
|
||||
"bh_fecha": {"fecha", "tomada", "fecha_toma", "fecha_muestra"},
|
||||
}
|
||||
# A source may name the patient column after the entity ("Paciente" holding
|
||||
# the expediente).
|
||||
SYNONYMS["pac_id_hospital"] |= {"paciente", "clave_paciente"}
|
||||
|
||||
# Scores per match kind; the 1:1 assignment takes the best-scoring pairs first.
|
||||
_EXACT, _NORMALIZED, _SYNONYM, _UNPREFIXED = 1.0, 0.9, 0.8, 0.75
|
||||
_WORD_FLOOR, _FUZZY_CAP = 0.5, 0.7
|
||||
# Words that carry no meaning for matching ("Fecha *de* solicitud") and are
|
||||
# too short to be anything but units ("kg", "g/dl").
|
||||
# Words that carry no meaning for matching ("Fecha *de* solicitud").
|
||||
_STOPWORDS = {"de", "del", "la", "el", "los", "las", "en", "por", "para", "con"}
|
||||
_NEAR_WORD = 0.8
|
||||
|
||||
@@ -63,6 +61,7 @@ def _normalize(name: str) -> str:
|
||||
|
||||
|
||||
def _words(normalized: str) -> list[str]:
|
||||
"""Meaningful words; two letters or fewer are units ("kg") or noise."""
|
||||
return [w for w in re.split(r"[^a-z0-9]+", normalized) if len(w) > 2 and w not in _STOPWORDS]
|
||||
|
||||
|
||||
@@ -89,7 +88,7 @@ def _unprefixed(target: str) -> str:
|
||||
return rest if rest else head
|
||||
|
||||
|
||||
class ColumnMatcher:
|
||||
def suggest_mapping(source_columns: list[str], target_fields: list[str]) -> list[MatchSuggestion]:
|
||||
"""Exact name -> normalized (case/accents/separators) -> static synonym
|
||||
table -> name without the table prefix -> word-level similarity -> no
|
||||
match.
|
||||
@@ -97,68 +96,60 @@ class ColumnMatcher:
|
||||
The 1:1 assignment is global: all (source, target) pairs are scored and
|
||||
claimed best-first, so a weak fuzzy match early in the file cannot take
|
||||
a target from an exact match later in it."""
|
||||
candidates: list[tuple[float, int, str, str, str]] = []
|
||||
for position, source in enumerate(source_columns):
|
||||
for target in target_fields:
|
||||
scored = _score(source, target)
|
||||
if scored is not None:
|
||||
score, reason = scored
|
||||
# -position: on equal scores the earlier source column wins.
|
||||
candidates.append((score, -position, source, target, reason))
|
||||
|
||||
def suggest(self, source_columns: list[str], target_fields: list[str]) -> list[MatchSuggestion]:
|
||||
candidates: list[tuple[float, int, str, str, str]] = []
|
||||
for position, source in enumerate(source_columns):
|
||||
for target in target_fields:
|
||||
scored = self._score(source, target)
|
||||
if scored is not None:
|
||||
score, reason = scored
|
||||
# -position: on equal scores the earlier source column wins.
|
||||
candidates.append((score, -position, source, target, reason))
|
||||
claimed_sources: dict[str, MatchSuggestion] = {}
|
||||
claimed_targets: set[str] = set()
|
||||
for score, _, source, target, reason in sorted(candidates, reverse=True):
|
||||
if source in claimed_sources or target in claimed_targets:
|
||||
continue
|
||||
claimed_sources[source] = MatchSuggestion(source, target, round(score, 2), reason)
|
||||
claimed_targets.add(target)
|
||||
|
||||
claimed_sources: dict[str, MatchSuggestion] = {}
|
||||
claimed_targets: set[str] = set()
|
||||
for score, _, source, target, reason in sorted(candidates, reverse=True):
|
||||
if source in claimed_sources or target in claimed_targets:
|
||||
continue
|
||||
claimed_sources[source] = MatchSuggestion(source, target, round(score, 2), reason)
|
||||
claimed_targets.add(target)
|
||||
return [claimed_sources.get(source, MatchSuggestion(source, None, 0.0, "none")) for source in source_columns]
|
||||
|
||||
return [claimed_sources.get(source, MatchSuggestion(source, None, 0.0, "none")) for source in source_columns]
|
||||
|
||||
@classmethod
|
||||
def _score(cls, source: str, target: str) -> tuple[float, str] | None:
|
||||
if source == target:
|
||||
return _EXACT, "exact"
|
||||
# A dotted (flattened JSON) name also matches by its last segment:
|
||||
# "paciente.expediente" is an expediente.
|
||||
variants = [source] + ([source.rsplit(".", 1)[-1]] if "." in source else [])
|
||||
scored = [s for s in (cls._score_one(v, target) for v in variants) if s is not None]
|
||||
return max(scored, key=lambda s: s[0]) if scored else None
|
||||
def _score(source: str, target: str) -> tuple[float, str] | None:
|
||||
if source == target:
|
||||
return _EXACT, "exact"
|
||||
# A dotted (flattened JSON) name also matches by its last segment:
|
||||
# "paciente.expediente" is an expediente.
|
||||
variants = [source] + ([source.rsplit(".", 1)[-1]] if "." in source else [])
|
||||
scored = [s for s in (_score_one(v, target) for v in variants) if s is not None]
|
||||
return max(scored, key=lambda s: s[0]) if scored else None
|
||||
|
||||
@staticmethod
|
||||
def _score_one(source: str, target: str) -> tuple[float, str] | None:
|
||||
normalized_source, normalized_target = _normalize(source), _normalize(target)
|
||||
if normalized_source == normalized_target:
|
||||
return _NORMALIZED, "normalized"
|
||||
if normalized_source in SYNONYMS.get(target, set()):
|
||||
return _SYNONYM, "synonym"
|
||||
unprefixed_target = _unprefixed(normalized_target)
|
||||
if normalized_source == unprefixed_target:
|
||||
return _UNPREFIXED, "unprefixed"
|
||||
# Not every field has a table prefix (`hemoglobina_g_dl`), so words
|
||||
# are compared against both the full and the unprefixed name. When
|
||||
# the target *does* have real content beyond its prefix ("eeg" in
|
||||
# "eeg_estudio"), that prefix is dropped from the full-name words
|
||||
# first: every column in the table shares it, so a source word
|
||||
# matching only that (e.g. "eeg_id" ~ "eeg_estudio", both just
|
||||
# carrying "eeg") is not real evidence of a relationship. When the
|
||||
# target has no content beyond its prefix (it isn't really a
|
||||
# "prefix_field" name, e.g. "hemoglobina_g_dl"), nothing is dropped.
|
||||
unprefixed_target_words = _words(unprefixed_target)
|
||||
prefix_token = normalized_target.split("_", 1)[0]
|
||||
target_words_full = (
|
||||
[w for w in _words(normalized_target) if w != prefix_token]
|
||||
if unprefixed_target_words
|
||||
else _words(normalized_target)
|
||||
)
|
||||
source_words = _words(normalized_source)
|
||||
words = max(_word_score(source_words, target_words_full), _word_score(source_words, unprefixed_target_words))
|
||||
if words >= _WORD_FLOOR:
|
||||
# 0.5..0.7 by word overlap, plus a tiny whole-string tiebreak so
|
||||
# "fecha_reporte" prefers bx_fecha_reporte over another one-word overlap.
|
||||
ratio = difflib.SequenceMatcher(None, normalized_source, unprefixed_target).ratio()
|
||||
return min(0.5 + (words - _WORD_FLOOR) * 0.36 + ratio * 0.02, _FUZZY_CAP), "fuzzy"
|
||||
return None
|
||||
|
||||
def _score_one(source: str, target: str) -> tuple[float, str] | None:
|
||||
normalized_source, normalized_target = _normalize(source), _normalize(target)
|
||||
if normalized_source == normalized_target:
|
||||
return _NORMALIZED, "normalized"
|
||||
if normalized_source in SYNONYMS.get(target, set()):
|
||||
return _SYNONYM, "synonym"
|
||||
unprefixed_target = _unprefixed(normalized_target)
|
||||
if normalized_source == unprefixed_target:
|
||||
return _UNPREFIXED, "unprefixed"
|
||||
# Words are compared against the full and the unprefixed name, since not every
|
||||
# field has a table prefix (`hemoglobina_g_dl`). The prefix itself is shared by
|
||||
# every column of the table ("eeg_id" ~ "eeg_estudio"), so it is not evidence.
|
||||
unprefixed_target_words = _words(unprefixed_target)
|
||||
prefix_token = normalized_target.split("_", 1)[0]
|
||||
target_words_full = (
|
||||
[w for w in _words(normalized_target) if w != prefix_token]
|
||||
if unprefixed_target_words
|
||||
else _words(normalized_target)
|
||||
)
|
||||
source_words = _words(normalized_source)
|
||||
words = max(_word_score(source_words, target_words_full), _word_score(source_words, unprefixed_target_words))
|
||||
if words >= _WORD_FLOOR:
|
||||
# 0.5..0.7 by word overlap, plus a tiny whole-string tiebreak so
|
||||
# "fecha_reporte" prefers bx_fecha_reporte over another one-word overlap.
|
||||
ratio = difflib.SequenceMatcher(None, normalized_source, unprefixed_target).ratio()
|
||||
return min(0.5 + (words - _WORD_FLOOR) * 0.36 + ratio * 0.02, _FUZZY_CAP), "fuzzy"
|
||||
return None
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
"""Import schema for `core.cacu.models.BiometriaHematica` (full blood count panel)."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId
|
||||
|
||||
|
||||
class BiometriaHematicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
bh_fecha: Optional[date] = None
|
||||
bh_fecha: FlexDate = None
|
||||
|
||||
eritrocitos_mill_ul: Optional[float] = None
|
||||
hemoglobina_g_dl: Optional[float] = None
|
||||
@@ -35,13 +32,3 @@ class BiometriaHematicaImportSchema(ImportSchema):
|
||||
|
||||
plaquetas_mil_ul: Optional[float] = None
|
||||
vpm_fl: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("bh_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,34 +1,21 @@
|
||||
"""Import schema for `core.cacu.models.BiopsiaCervical`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import GRADO_CIN_ALIAS, GradoCIN
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_GRADO_CIN_CATALOG = Catalog(GradoCIN, GRADO_CIN_ALIAS)
|
||||
|
||||
|
||||
class BiopsiaCervicalImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
cit_id: Optional[int] = None
|
||||
bx_fecha_solicitud: Optional[date] = None
|
||||
bx_fecha_reporte: Optional[date] = None
|
||||
bx_fecha_solicitud: FlexDate = None
|
||||
bx_fecha_reporte: FlexDate = None
|
||||
bx_observaciones: Optional[str] = None
|
||||
bx_cin_grado: CatalogValue(_GRADO_CIN_CATALOG) = None
|
||||
bx_pdf_blob: Optional[bytes] = None
|
||||
bx_ocr_confianza: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("bx_fecha_solicitud", "bx_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -3,14 +3,11 @@
|
||||
`cit_calidad_especimen` stays a plain string: Core's alias dict for it maps to
|
||||
`bool`, not to a canonical string, so it can't back a catalog.
|
||||
"""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import CELULAS_ESCAMOSAS_ALIAS, CelulasEscamosas, ResultadoVPH
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_CELULAS_ESCAMOSAS_CATALOG = Catalog(CelulasEscamosas, CELULAS_ESCAMOSAS_ALIAS)
|
||||
_RESULTADO_VPH_CATALOG = Catalog(ResultadoVPH)
|
||||
@@ -21,10 +18,10 @@ class CitologiaCervicalImportSchema(ImportSchema):
|
||||
# natural key) still point at this record.
|
||||
cit_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
cit_fecha_toma: Optional[date] = None
|
||||
cit_fecha_reporte: Optional[date] = None
|
||||
cit_fecha_toma: FlexDate = None
|
||||
cit_fecha_reporte: FlexDate = None
|
||||
cit_calidad_especimen: Optional[str] = None
|
||||
cit_pdf_blob: Optional[bytes] = None
|
||||
cit_observaciones: Optional[str] = None
|
||||
@@ -39,13 +36,3 @@ class CitologiaCervicalImportSchema(ImportSchema):
|
||||
cit_vph_resultado: CatalogValue(_RESULTADO_VPH_CATALOG) = None
|
||||
cit_vph_genotipo_16: Optional[int] = None
|
||||
cit_vph_genotipo_18: Optional[int] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("cit_fecha_toma", "cit_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -8,14 +8,11 @@ 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 datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
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, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_TIPO_EPISODIO_CATALOG = Catalog(TipoEpisodio, TIPO_EPISODIO_ALIAS)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
@@ -23,20 +20,10 @@ _ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
|
||||
class EpisodioClinicoImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
tipo_episodio: CatalogValue(_TIPO_EPISODIO_CATALOG) = None
|
||||
cie10_codigo: Optional[str] = None
|
||||
especialidad_medica: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
evento_fecha: Optional[date] = None
|
||||
ventana_inicio: Optional[date] = None
|
||||
ventana_fin: Optional[date] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("evento_fecha", "ventana_inicio", "ventana_fin", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
evento_fecha: FlexDate = None
|
||||
ventana_inicio: FlexDate = None
|
||||
ventana_fin: FlexDate = None
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
"""Import schema for `core.cacu.models.NotaMedica`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import ESPECIALIDAD_ALIAS, Especialidad, TIPO_NOTA_ALIAS, TipoNota
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId, RequiredStr
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
@@ -14,12 +11,12 @@ _TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
nm_id_hospital: str
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
nm_id_hospital: RequiredStr
|
||||
nm_nota_previa_id: Optional[str] = None
|
||||
nm_tipo_nota: CatalogValue(_TIPO_NOTA_CATALOG) = None
|
||||
nm_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
nm_fecha: Optional[date] = None
|
||||
nm_fecha: FlexDate = None
|
||||
nm_medico_tratante: Optional[str] = None
|
||||
nm_motivo_consulta: Optional[str] = None
|
||||
nm_interrogatorio: Optional[str] = None
|
||||
@@ -39,18 +36,3 @@ class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_presion_arterial_sistolica: Optional[int] = None
|
||||
nm_presion_arterial_diastolica: Optional[int] = None
|
||||
nm_temperatura: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("nm_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_nm_id_hospital(cls, v):
|
||||
return required_str(v, field_name="nm_id_hospital")
|
||||
|
||||
@field_validator("nm_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
"""Import schema for `core.cacu.models.OrdenesEstudio` (one order per row, one study type each)."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import TIPO_ESTUDIO_ALIAS, TipoEstudio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
|
||||
@@ -16,24 +13,14 @@ class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# natural key) still point at this record.
|
||||
ord_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: int
|
||||
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None
|
||||
ord_fecha: Optional[date] = None
|
||||
ord_fecha_solicitud: Optional[date] = None
|
||||
ord_fecha_resultado: Optional[date] = None
|
||||
ord_fecha: FlexDate = None
|
||||
ord_fecha_solicitud: FlexDate = None
|
||||
ord_fecha_resultado: FlexDate = None
|
||||
ord_estatus: Optional[str] = None
|
||||
ord_diagnostico: Optional[str] = None
|
||||
ord_observaciones: Optional[str] = None
|
||||
ord_especialidad: Optional[str] = None
|
||||
ord_medico_solicitante: Optional[str] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("ord_fecha", "ord_fecha_solicitud", "ord_fecha_resultado", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"""Import schema for `core.cacu.models.Paciente`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import DEPENDENCIA_ALIAS, Dependencia, PARENTESCO_ALIAS, Parentesco, SEXO_BIOLOGICO_ALIAS, SexoBiologico
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, CodigoPostal, HospitalId, coerce_postal_code, required_date, required_str
|
||||
from webapi.imports.schemas.coercion import (
|
||||
Catalog,
|
||||
CatalogValue,
|
||||
PostalCode,
|
||||
RequiredDate,
|
||||
RequiredHospitalId,
|
||||
)
|
||||
|
||||
# Dependencia/Parentesco: Core marks both catalogs as tentative.
|
||||
_DEPENDENCIA_CATALOG = Catalog(Dependencia, DEPENDENCIA_ALIAS, strict=False)
|
||||
@@ -18,25 +21,10 @@ 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: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
|
||||
# IND-01: required, since age at each event of interest is derived from it.
|
||||
pac_fecha_nacimiento: date
|
||||
pac_codigo_postal: Optional[CodigoPostal] = None
|
||||
pac_fecha_nacimiento: RequiredDate
|
||||
pac_codigo_postal: PostalCode = None
|
||||
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
|
||||
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("pac_fecha_nacimiento", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha_nacimiento(cls, v):
|
||||
return required_date(v, field_name="pac_fecha_nacimiento")
|
||||
|
||||
@field_validator("pac_codigo_postal", mode="before")
|
||||
@classmethod
|
||||
def _coerce_codigo_postal(cls, v):
|
||||
return coerce_postal_code(v)
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
"""Import schema for `core.cama.models.BiometriaHematica` (full blood count panel)."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId
|
||||
|
||||
|
||||
class BiometriaHematicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
bh_fecha: Optional[date] = None
|
||||
bh_fecha: FlexDate = None
|
||||
|
||||
eritrocitos_mill_ul: Optional[float] = None
|
||||
hemoglobina_g_dl: Optional[float] = None
|
||||
@@ -35,13 +32,3 @@ class BiometriaHematicaImportSchema(ImportSchema):
|
||||
|
||||
plaquetas_mil_ul: Optional[float] = None
|
||||
vpm_fl: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("bh_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,34 +1,21 @@
|
||||
"""Import schema for `core.cama.models.BiopsiaMama`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import GradoHistologicoMama
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_GRADO_HISTOLOGICO_MAMA_CATALOG = Catalog(GradoHistologicoMama)
|
||||
|
||||
|
||||
class BiopsiaMamaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_id: Optional[int] = None
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
mast_id: Optional[int] = None
|
||||
bx_fecha_solicitud: Optional[date] = None
|
||||
bx_fecha_reporte: Optional[date] = None
|
||||
bx_fecha_solicitud: FlexDate = None
|
||||
bx_fecha_reporte: FlexDate = None
|
||||
bx_grado_histologico: CatalogValue(_GRADO_HISTOLOGICO_MAMA_CATALOG) = None
|
||||
bx_pdf_blob: Optional[bytes] = None
|
||||
bx_ocr_confianza: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("bx_fecha_solicitud", "bx_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -2,14 +2,11 @@
|
||||
`webapi.imports.schemas.cacu.episodio_clinico.EpisodioClinicoImportSchema`
|
||||
(see its docstring for why `nm_id`/`episodio_anterior_id` are excluded).
|
||||
"""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
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, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_TIPO_EPISODIO_CATALOG = Catalog(TipoEpisodio, TIPO_EPISODIO_ALIAS)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
@@ -17,20 +14,10 @@ _ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
|
||||
class EpisodioClinicoImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
tipo_episodio: CatalogValue(_TIPO_EPISODIO_CATALOG) = None
|
||||
cie10_codigo: Optional[str] = None
|
||||
especialidad_medica: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
evento_fecha: Optional[date] = None
|
||||
ventana_inicio: Optional[date] = None
|
||||
ventana_fin: Optional[date] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("evento_fecha", "ventana_inicio", "ventana_fin", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
evento_fecha: FlexDate = None
|
||||
ventana_inicio: FlexDate = None
|
||||
ventana_fin: FlexDate = None
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
"""Import schema for `core.cama.models.Mastografia`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import BIRADS, BIRADS_ALIAS
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_BIRADS_CATALOG = Catalog(BIRADS, BIRADS_ALIAS)
|
||||
|
||||
@@ -16,22 +13,12 @@ class MastografiaImportSchema(ImportSchema):
|
||||
# natural key) still point at this record.
|
||||
mast_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_id: Optional[int] = None
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
mast_fecha_toma: Optional[date] = None
|
||||
mast_fecha_reporte: Optional[date] = None
|
||||
mast_fecha_toma: FlexDate = None
|
||||
mast_fecha_reporte: FlexDate = None
|
||||
mast_calidad_imagen: Optional[str] = None
|
||||
mast_birads: CatalogValue(_BIRADS_CATALOG) = None
|
||||
mast_dicom_blob: Optional[bytes] = None
|
||||
mast_interpretacion: Optional[str] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("mast_fecha_toma", "mast_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
"""Import schema for `core.cama.models.NotaMedica`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import ESPECIALIDAD_ALIAS, Especialidad, TIPO_NOTA_ALIAS, TipoNota
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId, RequiredStr
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
@@ -14,12 +11,12 @@ _TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
nm_id_hospital: str
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
nm_id_hospital: RequiredStr
|
||||
nm_nota_previa_id: Optional[str] = None
|
||||
nm_tipo_nota: CatalogValue(_TIPO_NOTA_CATALOG) = None
|
||||
nm_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
nm_fecha: Optional[date] = None
|
||||
nm_fecha: FlexDate = None
|
||||
nm_medico_tratante: Optional[str] = None
|
||||
nm_motivo_consulta: Optional[str] = None
|
||||
nm_interrogatorio: Optional[str] = None
|
||||
@@ -39,18 +36,3 @@ class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_presion_arterial_sistolica: Optional[int] = None
|
||||
nm_presion_arterial_diastolica: Optional[int] = None
|
||||
nm_temperatura: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("nm_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_nm_id_hospital(cls, v):
|
||||
return required_str(v, field_name="nm_id_hospital")
|
||||
|
||||
@field_validator("nm_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
"""Import schema for `core.cama.models.OrdenesEstudio` (one order per row, one study type each)."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import TIPO_ESTUDIO_ALIAS, TipoEstudio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
|
||||
@@ -16,24 +13,14 @@ class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# natural key) still point at this record.
|
||||
ord_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: int
|
||||
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None
|
||||
ord_fecha: Optional[date] = None
|
||||
ord_fecha_solicitud: Optional[date] = None
|
||||
ord_fecha_resultado: Optional[date] = None
|
||||
ord_fecha: FlexDate = None
|
||||
ord_fecha_solicitud: FlexDate = None
|
||||
ord_fecha_resultado: FlexDate = None
|
||||
ord_estatus: Optional[str] = None
|
||||
ord_diagnostico: Optional[str] = None
|
||||
ord_observaciones: Optional[str] = None
|
||||
ord_especialidad: Optional[str] = None
|
||||
ord_medico_solicitante: Optional[str] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("ord_fecha", "ord_fecha_solicitud", "ord_fecha_resultado", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"""Import schema for `core.cama.models.Paciente`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import DEPENDENCIA_ALIAS, Dependencia, PARENTESCO_ALIAS, Parentesco, SEXO_BIOLOGICO_ALIAS, SexoBiologico
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, CodigoPostal, HospitalId, coerce_postal_code, required_date, required_str
|
||||
from webapi.imports.schemas.coercion import (
|
||||
Catalog,
|
||||
CatalogValue,
|
||||
PostalCode,
|
||||
RequiredDate,
|
||||
RequiredHospitalId,
|
||||
)
|
||||
|
||||
# Dependencia/Parentesco: Core marks both catalogs as tentative.
|
||||
_DEPENDENCIA_CATALOG = Catalog(Dependencia, DEPENDENCIA_ALIAS, strict=False)
|
||||
@@ -18,25 +21,10 @@ 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: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
|
||||
# IND-01: required, since age at each event of interest is derived from it.
|
||||
pac_fecha_nacimiento: date
|
||||
pac_codigo_postal: Optional[CodigoPostal] = None
|
||||
pac_fecha_nacimiento: RequiredDate
|
||||
pac_codigo_postal: PostalCode = None
|
||||
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
|
||||
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("pac_codigo_postal", mode="before")
|
||||
@classmethod
|
||||
def _coerce_codigo_postal(cls, v):
|
||||
return coerce_postal_code(v)
|
||||
|
||||
@field_validator("pac_fecha_nacimiento", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha_nacimiento(cls, v):
|
||||
return required_date(v, field_name="pac_fecha_nacimiento")
|
||||
|
||||
@@ -7,7 +7,7 @@ from datetime import date, datetime
|
||||
from enum import Enum
|
||||
from typing import Annotated, Any, Optional, Type
|
||||
|
||||
from pydantic import BeforeValidator, StringConstraints
|
||||
from pydantic import BeforeValidator, StringConstraints, ValidationInfo
|
||||
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
from extraction import ExtractionError
|
||||
@@ -18,9 +18,9 @@ from extraction.signals import EegRecording
|
||||
HospitalId = Annotated[str, StringConstraints(max_length=HOSPITAL_ID_LENGTH)]
|
||||
|
||||
|
||||
def required_str(v: Any, *, field_name: str) -> str:
|
||||
def required_str(v: Any, info: ValidationInfo) -> str:
|
||||
if v is None or str(v).strip() == "":
|
||||
raise ValueError(f"{field_name} es requerido")
|
||||
raise ValueError(f"{info.field_name} es requerido")
|
||||
return str(v).strip()
|
||||
|
||||
|
||||
@@ -34,10 +34,10 @@ def optional_str(v: Any) -> Any:
|
||||
_DAY_FIRST_FORMATS = ("%d/%m/%Y", "%d-%m-%Y", "%d.%m.%Y", "%Y/%m/%d")
|
||||
|
||||
|
||||
def required_date(v: Any, *, field_name: str) -> Any:
|
||||
def required_date(v: Any, info: ValidationInfo) -> Any:
|
||||
coerced = coerce_date(v)
|
||||
if coerced is None:
|
||||
raise ValueError(f"{field_name} es requerido")
|
||||
raise ValueError(f"{info.field_name} es requerido")
|
||||
return coerced
|
||||
|
||||
|
||||
@@ -67,16 +67,6 @@ def coerce_date(v: Any) -> Any:
|
||||
return v
|
||||
|
||||
|
||||
def coerce_datetime(v: Any) -> Any:
|
||||
if v is None or (isinstance(v, str) and not v.strip()):
|
||||
return None
|
||||
if isinstance(v, datetime):
|
||||
return v
|
||||
if isinstance(v, str):
|
||||
return datetime.fromisoformat(v.strip())
|
||||
return v
|
||||
|
||||
|
||||
class Catalog:
|
||||
"""A closed set of valid values for one field: an `Enum`'s values plus any
|
||||
aliases for them, matched case-insensitively. Built from the Enum because
|
||||
@@ -132,10 +122,6 @@ def CatalogValue(catalog: Catalog): # noqa: N802 (used in annotations, like a t
|
||||
return Annotated[Optional[str], BeforeValidator(catalog.coerce), catalog]
|
||||
|
||||
|
||||
def coerce_alias(v: Any, catalog: Catalog) -> Any:
|
||||
return catalog.coerce(v)
|
||||
|
||||
|
||||
def coerce_postal_code(v: Any) -> Any:
|
||||
"""Mexican postal codes are 5 digits. A numeric source (Excel cell, SQL
|
||||
INT column) has already dropped the leading zero, so restore it."""
|
||||
@@ -170,3 +156,15 @@ def edf_file(v: Any) -> Any:
|
||||
except ExtractionError as exc:
|
||||
raise ValueError(f"no es un archivo EDF válido: {exc}") from exc
|
||||
return bytes(v)
|
||||
|
||||
|
||||
# Field types. Blank cells become None; required ones say which field is missing.
|
||||
OptionalStr = Annotated[Optional[str], BeforeValidator(optional_str)]
|
||||
# A TEA record's own id as the source sends it (its primary key is String(36)).
|
||||
SourceId = Annotated[Optional[Annotated[str, StringConstraints(max_length=36)]], BeforeValidator(optional_str)]
|
||||
RequiredStr = Annotated[str, BeforeValidator(required_str)]
|
||||
RequiredHospitalId = Annotated[HospitalId, BeforeValidator(required_str)]
|
||||
FlexDate = Annotated[Optional[date], BeforeValidator(coerce_date)]
|
||||
RequiredDate = Annotated[date, BeforeValidator(required_date)]
|
||||
PostalCode = Annotated[Optional[CodigoPostal], BeforeValidator(coerce_postal_code)]
|
||||
EdfFile = Annotated[Optional[bytes], BeforeValidator(edf_file)]
|
||||
|
||||
@@ -6,34 +6,8 @@ Keys are `"<domain>.<ModelName>"`, since some names (`NotaMedica`) repeat
|
||||
across domains.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from typing import Sequence, Type
|
||||
from typing import Sequence
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from core.cacu.models import BiometriaHematica as CacuBiometriaHematica
|
||||
from core.cacu.models import BiopsiaCervical as CacuBiopsiaCervical
|
||||
from core.cacu.models import CitologiaCervical as CacuCitologiaCervical
|
||||
from core.cacu.models import EpisodioClinico as CacuEpisodioClinico
|
||||
from core.cacu.models import NotaMedica as CacuNotaMedica
|
||||
from core.cacu.models import OrdenesEstudio as CacuOrdenesEstudio
|
||||
from core.cacu.models import Paciente as CacuPaciente
|
||||
from core.cama.models import BiometriaHematica as CamaBiometriaHematica
|
||||
from core.cama.models import BiopsiaMama as CamaBiopsiaMama
|
||||
from core.cama.models import EpisodioClinico as CamaEpisodioClinico
|
||||
from core.cama.models import Mastografia as CamaMastografia
|
||||
from core.cama.models import NotaMedica as CamaNotaMedica
|
||||
from core.cama.models import OrdenesEstudio as CamaOrdenesEstudio
|
||||
from core.cama.models import Paciente as CamaPaciente
|
||||
from core.tea.models import AntecedentesMaternosGestacion as TeaAntecedentesMaternosGestacion
|
||||
from core.tea.models import EegEstudio as TeaEegEstudio
|
||||
from core.tea.models import EegSegmento as TeaEegSegmento
|
||||
from core.tea.models import EvaluacionPsicologica as TeaEvaluacionPsicologica
|
||||
from core.tea.models import InstrumentoAplicado as TeaInstrumentoAplicado
|
||||
from core.tea.models import NotaMedica as TeaNotaMedica
|
||||
from core.tea.models import OrdenesEstudio as TeaOrdenesEstudio
|
||||
from core.tea.models import Pacientes as TeaPacientes
|
||||
from core.tea.models import PartoNeonatal as TeaPartoNeonatal
|
||||
from core.tea.models import PotencialesEvocadosAuditivos as TeaPotencialesEvocadosAuditivos
|
||||
from persistance.cacu import biometria_hematica_repository as cacu_biometria_hematica_repository
|
||||
from persistance.cacu import biopsia_cervical_repository as cacu_biopsia_cervical_repository
|
||||
from persistance.cacu import citologia_cervical_repository as cacu_citologia_cervical_repository
|
||||
@@ -49,6 +23,7 @@ from persistance.cama import nota_medica_repository as cama_nota_medica_reposito
|
||||
from persistance.cama import ordenes_estudio_repository as cama_ordenes_estudio_repository
|
||||
from persistance.cama import paciente_repository as cama_paciente_repository
|
||||
from persistance.repository import Repository
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from persistance.tea import antecedentes_maternos_gestacion_repository as tea_antecedentes_maternos_gestacion_repository
|
||||
from persistance.tea import eeg_estudio_repository as tea_eeg_estudio_repository
|
||||
from persistance.tea import eeg_segmento_repository as tea_eeg_segmento_repository
|
||||
@@ -107,59 +82,54 @@ from webapi.imports.schemas.tea.potenciales_evocados_auditivos import (
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EntitySpec:
|
||||
schema: Type[BaseModel]
|
||||
model: type
|
||||
schema: type[ImportSchema]
|
||||
repository: Repository
|
||||
conflict_fields: Sequence[str] | None
|
||||
|
||||
@property
|
||||
def model(self) -> type:
|
||||
return self.repository.model
|
||||
|
||||
|
||||
ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
"cacu.Paciente": EntitySpec(
|
||||
schema=CacuPacienteImportSchema,
|
||||
model=CacuPaciente,
|
||||
repository=cacu_paciente_repository,
|
||||
conflict_fields=("pac_id_hospital",),
|
||||
),
|
||||
"tea.Pacientes": EntitySpec(
|
||||
schema=PacientesImportSchema,
|
||||
model=TeaPacientes,
|
||||
repository=tea_pacientes_repository,
|
||||
# The source's own id; TEA's child tables reference it directly.
|
||||
conflict_fields=("pac_id",),
|
||||
),
|
||||
"cacu.OrdenesEstudio": EntitySpec(
|
||||
schema=CacuOrdenesEstudioImportSchema,
|
||||
model=CacuOrdenesEstudio,
|
||||
repository=cacu_ordenes_estudio_repository,
|
||||
conflict_fields=("ord_numero_hospital",),
|
||||
),
|
||||
"cacu.CitologiaCervical": EntitySpec(
|
||||
schema=CitologiaCervicalImportSchema,
|
||||
model=CacuCitologiaCervical,
|
||||
repository=cacu_citologia_cervical_repository,
|
||||
conflict_fields=("pac_id_hospital", "ord_numero_hospital"),
|
||||
),
|
||||
"cacu.BiopsiaCervical": EntitySpec(
|
||||
schema=BiopsiaCervicalImportSchema,
|
||||
model=CacuBiopsiaCervical,
|
||||
repository=cacu_biopsia_cervical_repository,
|
||||
conflict_fields=("pac_id_hospital", "ord_numero_hospital"),
|
||||
),
|
||||
"cacu.NotaMedica": EntitySpec(
|
||||
schema=CacuNotaMedicaImportSchema,
|
||||
model=CacuNotaMedica,
|
||||
repository=cacu_nota_medica_repository,
|
||||
conflict_fields=("pac_id_hospital", "nm_id_hospital"),
|
||||
),
|
||||
"cacu.BiometriaHematica": EntitySpec(
|
||||
schema=CacuBiometriaHematicaImportSchema,
|
||||
model=CacuBiometriaHematica,
|
||||
repository=cacu_biometria_hematica_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cacu.EpisodioClinico": EntitySpec(
|
||||
schema=CacuEpisodioClinicoImportSchema,
|
||||
model=CacuEpisodioClinico,
|
||||
repository=cacu_episodio_clinico_repository,
|
||||
# No hospital-visible identifier of its own, like EvaluacionPsicologica
|
||||
# or PartoNeonatal; a patient can have several episodes.
|
||||
@@ -167,73 +137,61 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
),
|
||||
"cama.Paciente": EntitySpec(
|
||||
schema=CamaPacienteImportSchema,
|
||||
model=CamaPaciente,
|
||||
repository=cama_paciente_repository,
|
||||
conflict_fields=("pac_id_hospital",),
|
||||
),
|
||||
"cama.OrdenesEstudio": EntitySpec(
|
||||
schema=CamaOrdenesEstudioImportSchema,
|
||||
model=CamaOrdenesEstudio,
|
||||
repository=cama_ordenes_estudio_repository,
|
||||
conflict_fields=("ord_numero_hospital",),
|
||||
),
|
||||
"cama.Mastografia": EntitySpec(
|
||||
schema=MastografiaImportSchema,
|
||||
model=CamaMastografia,
|
||||
repository=cama_mastografia_repository,
|
||||
conflict_fields=("pac_id_hospital", "ord_numero_hospital"),
|
||||
),
|
||||
"cama.BiopsiaMama": EntitySpec(
|
||||
schema=BiopsiaMamaImportSchema,
|
||||
model=CamaBiopsiaMama,
|
||||
repository=cama_biopsia_mama_repository,
|
||||
conflict_fields=("pac_id_hospital", "ord_numero_hospital"),
|
||||
),
|
||||
"cama.NotaMedica": EntitySpec(
|
||||
schema=CamaNotaMedicaImportSchema,
|
||||
model=CamaNotaMedica,
|
||||
repository=cama_nota_medica_repository,
|
||||
conflict_fields=("pac_id_hospital", "nm_id_hospital"),
|
||||
),
|
||||
"cama.BiometriaHematica": EntitySpec(
|
||||
schema=CamaBiometriaHematicaImportSchema,
|
||||
model=CamaBiometriaHematica,
|
||||
repository=cama_biometria_hematica_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cama.EpisodioClinico": EntitySpec(
|
||||
schema=CamaEpisodioClinicoImportSchema,
|
||||
model=CamaEpisodioClinico,
|
||||
repository=cama_episodio_clinico_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.OrdenesEstudio": EntitySpec(
|
||||
schema=TeaOrdenesEstudioImportSchema,
|
||||
model=TeaOrdenesEstudio,
|
||||
repository=tea_ordenes_estudio_repository,
|
||||
conflict_fields=("ord_id_hospital",),
|
||||
),
|
||||
"tea.NotaMedica": EntitySpec(
|
||||
schema=TeaNotaMedicaImportSchema,
|
||||
model=TeaNotaMedica,
|
||||
repository=tea_nota_medica_repository,
|
||||
conflict_fields=("nm_id_hospital",),
|
||||
),
|
||||
"tea.EvaluacionPsicologica": EntitySpec(
|
||||
schema=EvaluacionPsicologicaImportSchema,
|
||||
model=TeaEvaluacionPsicologica,
|
||||
repository=tea_evaluacion_psicologica_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.PotencialesEvocadosAuditivos": EntitySpec(
|
||||
schema=PotencialesEvocadosAuditivosImportSchema,
|
||||
model=TeaPotencialesEvocadosAuditivos,
|
||||
repository=tea_potenciales_evocados_auditivos_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.EegEstudio": EntitySpec(
|
||||
schema=EegEstudioImportSchema,
|
||||
model=TeaEegEstudio,
|
||||
repository=tea_eeg_estudio_repository,
|
||||
# The EDF file and its scanned report describe the same study; both
|
||||
# the `edf` connector (from the file's own admin code) and a
|
||||
@@ -243,25 +201,21 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
),
|
||||
"tea.EegSegmento": EntitySpec(
|
||||
schema=EegSegmentoImportSchema,
|
||||
model=TeaEegSegmento,
|
||||
repository=tea_eeg_segmento_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.InstrumentoAplicado": EntitySpec(
|
||||
schema=InstrumentoAplicadoImportSchema,
|
||||
model=TeaInstrumentoAplicado,
|
||||
repository=tea_instrumento_aplicado_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.AntecedentesMaternosGestacion": EntitySpec(
|
||||
schema=AntecedentesMaternosGestacionImportSchema,
|
||||
model=TeaAntecedentesMaternosGestacion,
|
||||
repository=tea_antecedentes_maternos_gestacion_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.PartoNeonatal": EntitySpec(
|
||||
schema=PartoNeonatalImportSchema,
|
||||
model=TeaPartoNeonatal,
|
||||
repository=tea_parto_neonatal_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
optional, like TEA's Core; system-managed `amg_created_at`/`amg_updated_at`/`amg_fuente_sistema` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import (
|
||||
CategoriaPesoMaterno,
|
||||
FuenteAntecedenteMaterno,
|
||||
@@ -12,7 +10,7 @@ from core.tea.enums import (
|
||||
VolumenLiquidoAmniotico,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr
|
||||
|
||||
_FUENTE_ANTECEDENTE_MATERNO_CATALOG = Catalog(FuenteAntecedenteMaterno)
|
||||
_CATEGORIA_PESO_MATERNO_CATALOG = Catalog(CategoriaPesoMaterno)
|
||||
@@ -23,7 +21,7 @@ _VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG = Catalog(VolumenLiquidoAmniotico)
|
||||
|
||||
class AntecedentesMaternosGestacionImportSchema(ImportSchema):
|
||||
amg_pac_id: Optional[int] = None
|
||||
amg_id_madre_seudonimo: Optional[str] = None
|
||||
amg_id_madre_seudonimo: OptionalStr = None
|
||||
amg_fuente_antecedente: CatalogValue(_FUENTE_ANTECEDENTE_MATERNO_CATALOG) = None
|
||||
amg_flag_vinculo_verificado: Optional[int] = None
|
||||
amg_imc_pregestacional: Optional[float] = None
|
||||
@@ -34,7 +32,7 @@ class AntecedentesMaternosGestacionImportSchema(ImportSchema):
|
||||
amg_antecedente_aborto: Optional[int] = None
|
||||
amg_embarazo_multiple: CatalogValue(_TIPO_EMBARAZO_CATALOG) = None
|
||||
amg_infeccion_gestacion: Optional[int] = None
|
||||
amg_infeccion_tipo: Optional[str] = None
|
||||
amg_infeccion_tipo: OptionalStr = None
|
||||
amg_infeccion_hospitalizacion: Optional[int] = None
|
||||
amg_diabetes_gestacional: Optional[int] = None
|
||||
amg_hipertension_preeclampsia: CatalogValue(_TRASTORNO_HIPERTENSIVO_GESTACION_CATALOG) = None
|
||||
@@ -50,17 +48,8 @@ class AntecedentesMaternosGestacionImportSchema(ImportSchema):
|
||||
amg_estres_agudo: Optional[int] = None
|
||||
amg_trastorno_neurologico: Optional[int] = None
|
||||
amg_liquido_amniotico: CatalogValue(_VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG) = None
|
||||
amg_medicamentos_gestacion: Optional[str] = None
|
||||
amg_medicamentos_gestacion: OptionalStr = None
|
||||
amg_farmaco_riesgo_neurodesarrollo: Optional[int] = None
|
||||
amg_observaciones: Optional[str] = None
|
||||
amg_observaciones: OptionalStr = None
|
||||
amg_ocr_confianza: Optional[float] = None
|
||||
amg_nlp_version: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"amg_id_madre_seudonimo", "amg_infeccion_tipo",
|
||||
"amg_medicamentos_gestacion", "amg_observaciones", "amg_nlp_version",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
amg_nlp_version: OptionalStr = None
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
"""Import schema for `core.tea.models.EegEstudio`. All fields optional, like TEA's
|
||||
Core; system-managed `eeg_created_at`/`eeg_updated_at` are excluded."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import (
|
||||
CalidadTecnicaEeg,
|
||||
ConclusionEeg,
|
||||
@@ -17,7 +14,7 @@ from core.tea.enums import (
|
||||
TipoGrafoelemento,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import edf_file, Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, EdfFile, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_FUENTE_INTERPRETACION_EEG_CATALOG = Catalog(FuenteInterpretacionEeg)
|
||||
_ESTADO_REGISTRO_EEG_CATALOG = Catalog(EstadoRegistroEeg)
|
||||
@@ -31,23 +28,25 @@ _CONCLUSION_EEG_CATALOG = Catalog(ConclusionEeg)
|
||||
|
||||
|
||||
class EegEstudioImportSchema(ImportSchema):
|
||||
eeg_ord_id: Optional[str] = None
|
||||
# The source's own id, kept so rows that reference it by id still point at this record.
|
||||
eeg_id: SourceId = None
|
||||
eeg_ord_id: OptionalStr = None
|
||||
eeg_pac_id: Optional[int] = None
|
||||
eeg_reporte_disponible: Optional[int] = None
|
||||
eeg_fuente_interpretacion: CatalogValue(_FUENTE_INTERPRETACION_EEG_CATALOG) = None
|
||||
eeg_fecha_nacimiento_archivo: Optional[date] = None
|
||||
eeg_fecha_nacimiento_archivo: FlexDate = None
|
||||
eeg_edad_meses: Optional[float] = None
|
||||
eeg_fecha_estudio: Optional[date] = None
|
||||
eeg_fecha_reporte: Optional[date] = None
|
||||
eeg_fecha_estudio: FlexDate = None
|
||||
eeg_fecha_reporte: FlexDate = None
|
||||
eeg_dias_respuesta: Optional[int] = None
|
||||
eeg_medico_interpreta: Optional[str] = None
|
||||
eeg_medico_interpreta: OptionalStr = None
|
||||
eeg_estado_registro: CatalogValue(_ESTADO_REGISTRO_EEG_CATALOG) = None
|
||||
eeg_privacion_sueno: Optional[int] = None
|
||||
eeg_sedacion: Optional[int] = None
|
||||
eeg_sedacion_farmaco: Optional[str] = None
|
||||
eeg_sedacion_farmaco: OptionalStr = None
|
||||
eeg_duracion_min: Optional[float] = None
|
||||
eeg_calidad_tecnica: CatalogValue(_CALIDAD_TECNICA_EEG_CATALOG) = None
|
||||
eeg_descripcion_senal: Optional[str] = None
|
||||
eeg_descripcion_senal: OptionalStr = None
|
||||
eeg_ritmo_base_frecuencia: Optional[float] = None
|
||||
eeg_ritmo_base_amplitud: Optional[int] = None
|
||||
eeg_simetria: CatalogValue(_SIMETRIA_CATALOG) = None
|
||||
@@ -55,36 +54,16 @@ class EegEstudioImportSchema(ImportSchema):
|
||||
eeg_actividad_epileptiforme: Optional[int] = None
|
||||
eeg_tipo_grafoelemento: CatalogValue(_TIPO_GRAFOELEMENTO_CATALOG) = None
|
||||
eeg_distribucion_anormalidad: CatalogValue(_DISTRIBUCION_ANORMALIDAD_CATALOG) = None
|
||||
eeg_localizacion: Optional[str] = None
|
||||
eeg_localizacion: OptionalStr = None
|
||||
eeg_activacion_sueno: Optional[int] = None
|
||||
eeg_lentificacion: CatalogValue(_LENTIFICACION_CATALOG) = None
|
||||
eeg_crisis_registradas: Optional[int] = None
|
||||
eeg_respuesta_fotoestimulacion: CatalogValue(_RESPUESTA_FOTOESTIMULACION_CATALOG) = None
|
||||
eeg_conclusion_texto: Optional[str] = None
|
||||
eeg_conclusion_texto: OptionalStr = None
|
||||
eeg_conclusion_categoria: CatalogValue(_CONCLUSION_EEG_CATALOG) = None
|
||||
eeg_id_registro_laboratorio: Optional[str] = None
|
||||
eeg_pdf_ruta: Optional[str] = None
|
||||
eeg_id_registro_laboratorio: OptionalStr = None
|
||||
eeg_pdf_ruta: OptionalStr = None
|
||||
eeg_ocr_confianza: Optional[float] = None
|
||||
eeg_nlp_version: Optional[str] = None
|
||||
eeg_nlp_version: OptionalStr = None
|
||||
eeg_utilizable: Optional[int] = None
|
||||
eeg_estudio: Optional[bytes] = None
|
||||
|
||||
@field_validator(
|
||||
"eeg_ord_id", "eeg_medico_interpreta", "eeg_sedacion_farmaco",
|
||||
"eeg_descripcion_senal", "eeg_localizacion", "eeg_conclusion_texto",
|
||||
"eeg_id_registro_laboratorio", "eeg_pdf_ruta", "eeg_nlp_version",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("eeg_fecha_nacimiento_archivo", "eeg_fecha_estudio", "eeg_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@field_validator("eeg_estudio", mode="before")
|
||||
@classmethod
|
||||
def _valid_edf(cls, v):
|
||||
return edf_file(v)
|
||||
eeg_estudio: EdfFile = None
|
||||
|
||||
@@ -2,27 +2,20 @@
|
||||
TEA's Core."""
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import optional_str
|
||||
from webapi.imports.schemas.coercion import OptionalStr
|
||||
|
||||
|
||||
class EegSegmentoImportSchema(ImportSchema):
|
||||
seg_eeg_id: Optional[str] = None
|
||||
seg_estado: Optional[str] = None
|
||||
seg_eeg_id: OptionalStr = None
|
||||
seg_estado: OptionalStr = None
|
||||
seg_inicio_s: Optional[float] = None
|
||||
seg_fin_s: Optional[float] = None
|
||||
seg_duracion_s: Optional[float] = None
|
||||
seg_fuente: Optional[str] = None
|
||||
seg_fuente: OptionalStr = None
|
||||
seg_frecuencia_flash_hz: Optional[float] = None
|
||||
seg_n_destellos: Optional[int] = None
|
||||
seg_cobertura: Optional[float] = None
|
||||
seg_rms_uv: Optional[float] = None
|
||||
seg_emg: Optional[float] = None
|
||||
seg_p2p_max_uv: Optional[float] = None
|
||||
|
||||
@field_validator("seg_eeg_id", "seg_estado", "seg_fuente", mode="before")
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
"""Import schema for `core.tea.models.EvaluacionPsicologica`, including the 28
|
||||
ADOS-2 item columns. All fields optional, like TEA's Core; system-managed `psi_created_at`/`psi_updated_at` are excluded."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import (
|
||||
ClasificacionAdos2,
|
||||
InstrumentoTamizaje,
|
||||
@@ -13,7 +10,7 @@ from core.tea.enums import (
|
||||
VentanaMadurativa,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
_INSTRUMENTO_TAMIZAJE_CATALOG = Catalog(InstrumentoTamizaje)
|
||||
@@ -23,12 +20,14 @@ _CLASIFICACION_ADOS2_CATALOG = Catalog(ClasificacionAdos2)
|
||||
|
||||
|
||||
class EvaluacionPsicologicaImportSchema(ImportSchema):
|
||||
psi_ord_id: Optional[str] = None
|
||||
# The source's own id, kept so rows that reference it by id still point at this record.
|
||||
psi_id: SourceId = None
|
||||
psi_ord_id: OptionalStr = None
|
||||
psi_pac_id: Optional[int] = None
|
||||
psi_fecha_entrevista_inicial: Optional[date] = None
|
||||
psi_fecha_ados2: Optional[date] = None
|
||||
psi_fecha_evaluacion: Optional[date] = None
|
||||
psi_psicologo: Optional[str] = None
|
||||
psi_fecha_entrevista_inicial: FlexDate = None
|
||||
psi_fecha_ados2: FlexDate = None
|
||||
psi_fecha_evaluacion: FlexDate = None
|
||||
psi_psicologo: OptionalStr = None
|
||||
psi_edad_meses: Optional[float] = None
|
||||
psi_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
psi_instrumento_tamizaje: CatalogValue(_INSTRUMENTO_TAMIZAJE_CATALOG) = None
|
||||
@@ -80,22 +79,8 @@ class EvaluacionPsicologicaImportSchema(ImportSchema):
|
||||
psi_css_umbral_aplicado: Optional[int] = None
|
||||
psi_caso_confirmado: Optional[int] = None
|
||||
psi_cars_total: Optional[float] = None
|
||||
psi_otros_instrumentos: Optional[str] = None
|
||||
psi_otros_instrumentos: OptionalStr = None
|
||||
psi_regresion_desarrollo: Optional[int] = None
|
||||
psi_diagnostico_texto: Optional[str] = None
|
||||
psi_diagnostico_texto: OptionalStr = None
|
||||
psi_ocr_confianza: Optional[float] = None
|
||||
psi_nlp_version: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"psi_ord_id", "psi_psicologo", "psi_otros_instrumentos",
|
||||
"psi_diagnostico_texto", "psi_nlp_version",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("psi_fecha_entrevista_inicial", "psi_fecha_ados2", "psi_fecha_evaluacion", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
psi_nlp_version: OptionalStr = None
|
||||
|
||||
@@ -1,24 +1,13 @@
|
||||
"""Import schema for `core.tea.models.InstrumentoAplicado`. All fields
|
||||
optional, like TEA's Core."""
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import optional_str
|
||||
from webapi.imports.schemas.coercion import OptionalStr
|
||||
|
||||
|
||||
class InstrumentoAplicadoImportSchema(ImportSchema):
|
||||
ins_psi_id: Optional[str] = None
|
||||
ins_instrumento: Optional[str] = None
|
||||
ins_informante: Optional[str] = None
|
||||
ins_area: Optional[str] = None
|
||||
ins_interpretacion: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"ins_psi_id", "ins_instrumento", "ins_informante", "ins_area", "ins_interpretacion",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
ins_psi_id: OptionalStr = None
|
||||
ins_instrumento: OptionalStr = None
|
||||
ins_informante: OptionalStr = None
|
||||
ins_area: OptionalStr = None
|
||||
ins_interpretacion: OptionalStr = None
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
"""Import schema for `core.tea.models.NotaMedica`. All fields optional, like TEA's
|
||||
Core; system-managed `nm_created_at`/`nm_updated_at`/`nm_fuente_sistema` are excluded."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import Especialidad, Pronostico, TipoNota, VentanaMadurativa
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad)
|
||||
@@ -17,27 +14,27 @@ _PRONOSTICO_CATALOG = Catalog(Pronostico)
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_pac_id: Optional[int] = None
|
||||
nm_id_hospital: Optional[str] = None
|
||||
nm_nota_previa_id: Optional[str] = None
|
||||
nm_id_hospital: OptionalStr = None
|
||||
nm_nota_previa_id: OptionalStr = None
|
||||
nm_tipo_nota: CatalogValue(_TIPO_NOTA_CATALOG) = None
|
||||
nm_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
nm_fecha: Optional[date] = None
|
||||
nm_fecha: FlexDate = None
|
||||
nm_edad_meses: Optional[float] = None
|
||||
nm_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
nm_medico_tratante: Optional[str] = None
|
||||
nm_motivo_consulta: Optional[str] = None
|
||||
nm_interrogatorio: Optional[str] = None
|
||||
nm_medico_tratante: OptionalStr = None
|
||||
nm_motivo_consulta: OptionalStr = None
|
||||
nm_interrogatorio: OptionalStr = None
|
||||
nm_regresion_referida: Optional[int] = None
|
||||
nm_antecedente_familiar_tea: Optional[int] = None
|
||||
nm_perimetro_cefalico: Optional[float] = None
|
||||
nm_diagnostico_texto: Optional[str] = None
|
||||
nm_cie_codigo: Optional[str] = None
|
||||
nm_cie_descripcion: Optional[str] = None
|
||||
nm_tratamiento_texto: Optional[str] = None
|
||||
nm_receta: Optional[str] = None
|
||||
nm_plan_estudios: Optional[str] = None
|
||||
nm_diagnostico_texto: OptionalStr = None
|
||||
nm_cie_codigo: OptionalStr = None
|
||||
nm_cie_descripcion: OptionalStr = None
|
||||
nm_tratamiento_texto: OptionalStr = None
|
||||
nm_receta: OptionalStr = None
|
||||
nm_plan_estudios: OptionalStr = None
|
||||
nm_pronostico: CatalogValue(_PRONOSTICO_CATALOG) = None
|
||||
nm_observaciones: Optional[str] = None
|
||||
nm_observaciones: OptionalStr = None
|
||||
nm_masa_corporal: Optional[float] = None
|
||||
nm_talla: Optional[float] = None
|
||||
nm_imc_visita: Optional[float] = None
|
||||
@@ -46,20 +43,4 @@ class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_presion_arterial_sistolica: Optional[int] = None
|
||||
nm_presion_arterial_diastolica: Optional[int] = None
|
||||
nm_temperatura: Optional[float] = None
|
||||
nm_pdf_ruta: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"nm_id_hospital", "nm_nota_previa_id", "nm_medico_tratante",
|
||||
"nm_motivo_consulta", "nm_interrogatorio", "nm_diagnostico_texto", "nm_cie_codigo",
|
||||
"nm_cie_descripcion", "nm_tratamiento_texto", "nm_receta", "nm_plan_estudios",
|
||||
"nm_observaciones", "nm_pdf_ruta",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("nm_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
nm_pdf_ruta: OptionalStr = None
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
"""Import schema for `core.tea.models.OrdenesEstudio`. All fields optional, like
|
||||
TEA's Core; system-managed `ord_*_created_at`/`ord_updated_at`/`ord_fuente_sistema` are excluded."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import TIPO_ESTUDIO_ALIAS, Especialidad, EstatusEstudio, TipoEstudio, VentanaMadurativa
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad)
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
@@ -16,38 +13,25 @@ _VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
|
||||
|
||||
class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id still point at this record.
|
||||
ord_id: SourceId = None
|
||||
ord_pac_id: Optional[int] = None
|
||||
ord_nota_medica_id: Optional[str] = None
|
||||
ord_id_hospital: Optional[str] = None
|
||||
ord_fecha: Optional[date] = None
|
||||
ord_medico_solicitante: Optional[str] = None
|
||||
ord_nota_medica_id: OptionalStr = None
|
||||
ord_id_hospital: OptionalStr = None
|
||||
ord_fecha: FlexDate = None
|
||||
ord_medico_solicitante: OptionalStr = None
|
||||
ord_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
ord_diagnostico_asignado: Optional[str] = None
|
||||
ord_cie_asignado: Optional[str] = None
|
||||
ord_diagnostico_asignado: OptionalStr = None
|
||||
ord_cie_asignado: OptionalStr = None
|
||||
ord_dias_vigencia: Optional[int] = None
|
||||
ord_fecha_vencimiento: Optional[date] = None
|
||||
ord_fecha_vencimiento: FlexDate = None
|
||||
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None
|
||||
ord_estatus: CatalogValue(_ESTATUS_ESTUDIO_CATALOG) = None
|
||||
ord_fecha_realizacion: Optional[date] = None
|
||||
ord_fecha_resultado: Optional[date] = None
|
||||
ord_fecha_realizacion: FlexDate = None
|
||||
ord_fecha_resultado: FlexDate = None
|
||||
ord_dias_espera: Optional[int] = None
|
||||
ord_proveedor: Optional[str] = None
|
||||
ord_proveedor: OptionalStr = None
|
||||
ord_edad_meses: Optional[float] = None
|
||||
ord_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
ord_pdf_ruta: Optional[str] = None
|
||||
ord_observaciones: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"ord_nota_medica_id", "ord_id_hospital", "ord_medico_solicitante",
|
||||
"ord_diagnostico_asignado", "ord_cie_asignado", "ord_proveedor", "ord_pdf_ruta",
|
||||
"ord_observaciones",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("ord_fecha", "ord_fecha_vencimiento", "ord_fecha_realizacion", "ord_fecha_resultado", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
ord_pdf_ruta: OptionalStr = None
|
||||
ord_observaciones: OptionalStr = None
|
||||
|
||||
@@ -3,14 +3,11 @@ Core; system-managed `pac_created_at`/`pac_updated_at`/`pac_fuente_sistema` are
|
||||
|
||||
`pac_id` is importable: every other TEA table references the patient by the
|
||||
source system's integer id, so it has to be kept, not renumbered."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import Parentesco, SexoBiologico
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_SEXO_CATALOG = Catalog(SexoBiologico)
|
||||
_PARENTESCO_CATALOG = Catalog(Parentesco)
|
||||
@@ -18,20 +15,10 @@ _PARENTESCO_CATALOG = Catalog(Parentesco)
|
||||
|
||||
class PacientesImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: Optional[str] = None
|
||||
pac_id_titular: Optional[str] = None
|
||||
pac_id_hospital: OptionalStr = None
|
||||
pac_id_titular: OptionalStr = None
|
||||
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
|
||||
pac_fecha_nacimiento: Optional[date] = None
|
||||
pac_fecha_nacimiento: FlexDate = None
|
||||
pac_sexo: CatalogValue(_SEXO_CATALOG) = None
|
||||
pac_codigo_postal_vigente: Optional[str] = None
|
||||
pac_dependencia: Optional[str] = None
|
||||
|
||||
@field_validator("pac_id_hospital", "pac_id_titular", "pac_codigo_postal_vigente", "pac_dependencia", mode="before")
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("pac_fecha_nacimiento", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha_nacimiento(cls, v):
|
||||
return coerce_date(v)
|
||||
pac_codigo_postal_vigente: OptionalStr = None
|
||||
pac_dependencia: OptionalStr = None
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
TEA's Core; system-managed `pnn_created_at`/`pnn_updated_at`/`pnn_fuente_sistema` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import (
|
||||
ClasificacionEdadGestacional,
|
||||
ComplicacionIntraparto,
|
||||
@@ -12,7 +10,7 @@ from core.tea.enums import (
|
||||
TipoParto,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr
|
||||
|
||||
_FUENTE_ANTECEDENTE_NEONATAL_CATALOG = Catalog(FuenteAntecedenteNeonatal)
|
||||
_TIPO_PARTO_CATALOG = Catalog(TipoParto)
|
||||
@@ -45,16 +43,8 @@ class PartoNeonatalImportSchema(ImportSchema):
|
||||
pnn_hipoglucemia_neonatal: Optional[int] = None
|
||||
pnn_anoxia: Optional[int] = None
|
||||
pnn_sindrome_congenito: Optional[int] = None
|
||||
pnn_sindrome_congenito_desc: Optional[str] = None
|
||||
pnn_sindrome_congenito_desc: OptionalStr = None
|
||||
pnn_flag_riesgo_neonatal: Optional[int] = None
|
||||
pnn_observaciones: Optional[str] = None
|
||||
pnn_observaciones: OptionalStr = None
|
||||
pnn_ocr_confianza: Optional[float] = None
|
||||
pnn_nlp_version: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"pnn_sindrome_congenito_desc", "pnn_observaciones", "pnn_nlp_version",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
pnn_nlp_version: OptionalStr = None
|
||||
|
||||
@@ -1,22 +1,19 @@
|
||||
"""Import schema for `core.tea.models.PotencialesEvocadosAuditivos`. All fields
|
||||
optional, like TEA's Core; system-managed `pea_created_at`/`pea_updated_at` are excluded."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import GradoHipoacusia
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_GRADO_HIPOACUSIA_CATALOG = Catalog(GradoHipoacusia)
|
||||
|
||||
|
||||
class PotencialesEvocadosAuditivosImportSchema(ImportSchema):
|
||||
pea_ord_id: Optional[str] = None
|
||||
pea_ord_id: OptionalStr = None
|
||||
pea_pac_id: Optional[int] = None
|
||||
pea_fecha_estudio: Optional[date] = None
|
||||
pea_medico_interpreta: Optional[str] = None
|
||||
pea_fecha_estudio: FlexDate = None
|
||||
pea_medico_interpreta: OptionalStr = None
|
||||
pea_umbral_od: Optional[int] = None
|
||||
pea_umbral_oi: Optional[int] = None
|
||||
pea_latencia_v_od: Optional[float] = None
|
||||
@@ -24,19 +21,6 @@ class PotencialesEvocadosAuditivosImportSchema(ImportSchema):
|
||||
pea_interpico_i_v_od: Optional[float] = None
|
||||
pea_interpico_i_v_oi: Optional[float] = None
|
||||
pea_grado_hipoacusia: CatalogValue(_GRADO_HIPOACUSIA_CATALOG) = None
|
||||
pea_conclusion_texto: Optional[str] = None
|
||||
pea_conclusion_texto: OptionalStr = None
|
||||
pea_flag_diferencial_auditivo: Optional[int] = None
|
||||
pea_ocr_confianza: Optional[float] = None
|
||||
|
||||
@field_validator(
|
||||
"pea_ord_id", "pea_medico_interpreta", "pea_conclusion_texto",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("pea_fecha_estudio", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -25,6 +25,10 @@ class ImportRequestError(Exception):
|
||||
bad connection string or an invalid on_conflict. Mapped to HTTP 400."""
|
||||
|
||||
|
||||
class DatabaseRefused(ImportRequestError):
|
||||
"""The database rejected the batch at write time; nothing was written."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ImportSource:
|
||||
"""One parsed and structurally validated entry of a request's `sources`."""
|
||||
@@ -40,32 +44,32 @@ class ImportSource:
|
||||
@classmethod
|
||||
def parse(cls, raw: Any) -> "ImportSource":
|
||||
if not isinstance(raw, dict):
|
||||
raise ImportRequestError("each source must be an object")
|
||||
raise ImportRequestError("cada fuente debe ser un objeto")
|
||||
target = raw.get("target")
|
||||
if not target:
|
||||
raise ImportRequestError("source is missing 'target'")
|
||||
raise ImportRequestError("a la fuente le falta 'target'")
|
||||
spec = ENTITY_REGISTRY.get(target)
|
||||
if spec is None:
|
||||
raise ImportRequestError(f"unknown target: {target!r}")
|
||||
raise ImportRequestError(f"destino desconocido: {target!r}")
|
||||
|
||||
fields = set(spec.schema.model_fields)
|
||||
mapping = raw.get("column_mapping") or {}
|
||||
defaults = raw.get("defaults") or {}
|
||||
if not isinstance(mapping, dict) or not isinstance(defaults, dict):
|
||||
raise ImportRequestError("'column_mapping' and 'defaults' must be objects")
|
||||
raise ImportRequestError("'column_mapping' y 'defaults' deben ser objetos")
|
||||
unknown = sorted((set(mapping.values()) | set(defaults)) - fields)
|
||||
if unknown:
|
||||
raise ImportRequestError(f"{target} has no field(s) {unknown}")
|
||||
raise ImportRequestError(f"{target} no tiene los campos {unknown}")
|
||||
targets = list(mapping.values())
|
||||
duplicated = sorted({t for t in targets if targets.count(t) > 1})
|
||||
if duplicated:
|
||||
raise ImportRequestError(f"more than one source column mapped to {duplicated}")
|
||||
raise ImportRequestError(f"más de una columna de origen asignada a {duplicated}")
|
||||
if not mapping and not defaults:
|
||||
raise ImportRequestError(f"source for {target} maps no columns")
|
||||
raise ImportRequestError(f"la fuente de {target} no asigna ninguna columna")
|
||||
|
||||
payload = raw.get("payload")
|
||||
if not isinstance(payload, dict):
|
||||
raise ImportRequestError("source is missing 'payload'")
|
||||
raise ImportRequestError("a la fuente le falta 'payload'")
|
||||
return cls(
|
||||
source_type=raw.get("source_type", ""),
|
||||
target=target,
|
||||
@@ -159,12 +163,12 @@ class SourceCommitResult:
|
||||
|
||||
def _parse_batch(raw_sources: Any) -> list[ImportSource]:
|
||||
if not isinstance(raw_sources, list) or not raw_sources:
|
||||
raise ImportRequestError("'sources' must be a non-empty list")
|
||||
raise ImportRequestError("'sources' debe ser una lista no vacía")
|
||||
sources = [ImportSource.parse(raw) for raw in raw_sources]
|
||||
domains = sorted({source.domain for source in sources})
|
||||
if len(domains) > 1:
|
||||
raise ImportRequestError(
|
||||
f"a batch cannot mix domains — got {domains}, every source must target the same one"
|
||||
f"un lote no puede mezclar dominios ({', '.join(domains)}): todas las fuentes deben ir al mismo"
|
||||
)
|
||||
return sources
|
||||
|
||||
@@ -214,11 +218,8 @@ def merge_duplicates(sources: list[ImportSource], rows: list[list[dict[str, Any]
|
||||
|
||||
|
||||
def _key_part(value: Any) -> Any:
|
||||
"""Normalized for comparison across sources: a CSV's natural key is
|
||||
always a string ("5001"), while a typed source (the document extractor,
|
||||
a SQL column) can hand back an int or a date for the very same value.
|
||||
Stringifying both sides is what lets rows that describe the same record
|
||||
actually match, instead of silently landing as two separate ones."""
|
||||
"""Normalized for comparison across sources: a CSV key is the string "5001"
|
||||
where a typed source gives the int 5001."""
|
||||
if _is_blank(value):
|
||||
return None
|
||||
return str(value).strip().upper()
|
||||
@@ -232,14 +233,14 @@ def commit_sources(
|
||||
try:
|
||||
policy = ConflictPolicy(on_conflict)
|
||||
except ValueError as exc:
|
||||
raise ImportRequestError(f"invalid on_conflict: {on_conflict!r}") from exc
|
||||
raise ImportRequestError(f"on_conflict inválido: {on_conflict!r}") from exc
|
||||
|
||||
sources = _parse_batch(raw_sources)
|
||||
tracked = [audit.source(source) for source in sources] if audit else []
|
||||
if policy is ConflictPolicy.UPSERT:
|
||||
keyless = sorted({s.target for s in sources if not s.spec.conflict_fields})
|
||||
if keyless:
|
||||
raise ImportRequestError(f"{', '.join(keyless)} has no natural key — on_conflict=upsert is not valid for it")
|
||||
raise ImportRequestError(f"{', '.join(keyless)} no tiene llave natural: on_conflict=upsert no aplica")
|
||||
|
||||
# Read + validate everything before opening the write transaction, so a
|
||||
# slow source (OCR, a remote SQL table) never holds database locks.
|
||||
@@ -274,7 +275,7 @@ def commit_sources(
|
||||
"row_index": validation.accepted_rows[outcome.index].row_index,
|
||||
"field": ",".join(source.spec.conflict_fields or ()),
|
||||
"category": "conflict",
|
||||
"message": outcome.error or "conflict",
|
||||
"message": outcome.error or "conflicto",
|
||||
"raw_value": _jsonable(
|
||||
validation.accepted_rows[outcome.index].data.get((source.spec.conflict_fields or ("",))[0])
|
||||
),
|
||||
@@ -303,7 +304,10 @@ def commit_sources(
|
||||
session.commit()
|
||||
except SQLAlchemyError as exc:
|
||||
session.rollback()
|
||||
raise ImportRequestError(f"the database refused the batch, nothing was written: {exc.__class__.__name__}: {exc.orig if hasattr(exc, 'orig') else exc}") from exc
|
||||
detail = exc.orig if hasattr(exc, "orig") else exc
|
||||
raise DatabaseRefused(
|
||||
f"la base de datos rechazó el lote y no se escribió nada: {exc.__class__.__name__}: {detail}"
|
||||
) from exc
|
||||
finally:
|
||||
session.close()
|
||||
return [results[i] for i in range(len(validated))]
|
||||
|
||||
@@ -9,7 +9,7 @@ from webapi.imports.connectors import Connector, ConnectorError
|
||||
from webapi.imports.connectors.document import DocumentConnector
|
||||
from webapi.imports.connectors.pdf import PdfConnector, RegionSpec
|
||||
from webapi.imports.connectors.tabular import columns_from_dataframe, rows_from_dataframe
|
||||
from webapi.imports.mapping.column_matcher import ColumnMatcher
|
||||
from webapi.imports.mapping import column_matcher
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
|
||||
@@ -18,8 +18,8 @@ def suggest_mapping(source_columns: list[str], target_key: str | None) -> list[d
|
||||
return []
|
||||
spec = ENTITY_REGISTRY.get(target_key)
|
||||
if spec is None:
|
||||
raise ConnectorError(f"unknown target: {target_key!r}")
|
||||
matches = ColumnMatcher().suggest(source_columns, list(spec.schema.model_fields.keys()))
|
||||
raise ConnectorError(f"destino desconocido: {target_key!r}")
|
||||
matches = column_matcher.suggest_mapping(source_columns, list(spec.schema.model_fields.keys()))
|
||||
return [
|
||||
{"source_column": m.source_column, "target_field": m.target_field, "confidence": m.confidence, "reason": m.reason}
|
||||
for m in matches
|
||||
|
||||
@@ -5,8 +5,8 @@ same batch.
|
||||
|
||||
Links are derived from Core's columns: an entity with both `pac_id` and
|
||||
`pac_id_hospital` links to its domain's `Paciente`, and one with both
|
||||
`ord_id` and `ord_numero_hospital` links to its `OrdenesEstudio`. TEA uses
|
||||
UUID keys without such pairs, so it gets no links.
|
||||
`ord_id` and `ord_numero_hospital` links to its `OrdenesEstudio`. TEA's child
|
||||
tables carry the source's patient id itself (`*_pac_id`), so it needs none.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from functools import cache
|
||||
|
||||
+12
-22
@@ -3,8 +3,8 @@
|
||||
A successful import asks for a recomputation (`ColaDeRecalculo.solicitar`),
|
||||
which only drops a marker file. A separate process (`python -m
|
||||
webapi.indicadores_vivos`, the `indicadores` compose service) picks the
|
||||
markers up and runs that domain's pipeline with Hamilton (`webapi.pipeline`):
|
||||
catalogs -> staging to facts -> views -> registry -> definitions -> reports.
|
||||
markers up and runs that domain's cycle (`orquestacion.correr`): catalogs ->
|
||||
staging to facts -> views -> registry -> definitions -> reports.
|
||||
Requests that arrive while a domain is running are folded into one more run.
|
||||
|
||||
State lives in files under `INDICADORES_DIR`: `pendiente/<dominio>` markers
|
||||
@@ -18,6 +18,7 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
@@ -97,10 +98,7 @@ class ColaDeRecalculo:
|
||||
|
||||
def correr(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
|
||||
"""Runs the domain's graph (without `migrar`: the API migrates on startup)."""
|
||||
from orquestacion import Contexto
|
||||
from orquestacion.aristas import aristas_de
|
||||
|
||||
from webapi.pipeline import correr
|
||||
from orquestacion import Contexto, correr, pasos_de
|
||||
|
||||
desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5))
|
||||
hasta = hasta or int(os.environ.get("INDICADORES_HASTA", date.today().year))
|
||||
@@ -110,11 +108,10 @@ class ColaDeRecalculo:
|
||||
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
|
||||
try:
|
||||
ctx = Contexto(dominio, desde, hasta, permitir_sin_definir=True)
|
||||
nombres = [a.nombre for a in aristas_de(dominio) if a.nombre != "migrar"]
|
||||
pasos = correr(ctx, solo=nombres)
|
||||
pasos = correr(ctx, solo=[p for p in pasos_de(dominio) if p != "migrar"])
|
||||
entrada.update(
|
||||
estado="ok",
|
||||
pasos=[{"arista": p.arista, "segundos": round(p.segundos, 2), "resumen": _short(p.resumen)} for p in pasos],
|
||||
pasos=[{"paso": p.nombre, "segundos": round(p.segundos, 2), "resumen": _short(p.resumen)} for p in pasos],
|
||||
)
|
||||
except Exception as exc: # the worker must survive a failing domain
|
||||
log.exception("recálculo de %s falló", dominio)
|
||||
@@ -144,22 +141,15 @@ def main() -> None:
|
||||
if os.environ.get("INDICADORES_AL_INICIAR", "1") == "1":
|
||||
for dominio in DOMINIOS:
|
||||
cola.solicitar(dominio)
|
||||
stopping = False
|
||||
|
||||
def _stop(*_):
|
||||
nonlocal stopping
|
||||
stopping = True
|
||||
|
||||
signal.signal(signal.SIGTERM, _stop)
|
||||
signal.signal(signal.SIGINT, _stop)
|
||||
stop = threading.Event()
|
||||
signal.signal(signal.SIGTERM, lambda *_: stop.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: stop.set())
|
||||
log.info("indicadores en vivo: revisando cada %.0f s en %s", interval, cola.base)
|
||||
while not stopping:
|
||||
while True:
|
||||
for dominio in cola.atender():
|
||||
log.info("%s: %s", dominio, cola.estado()[dominio].get("estado"))
|
||||
for _ in range(int(interval * 10)):
|
||||
if stopping:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
if stop.wait(interval):
|
||||
break
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
"""Runs a domain's indicator pipeline with Hamilton.
|
||||
|
||||
The steps are the kit's own transformations as Orquestacion declares them
|
||||
(`orquestacion.aristas.aristas_de`): each one names the table groups it reads
|
||||
and writes, and moves data only through the database. Here every step becomes
|
||||
a Hamilton node whose inputs are the steps that write what it reads, so
|
||||
Hamilton orders and runs the graph; nothing of Orquestacion's own executor is
|
||||
used. Steps left out of `solo` are given as overrides and don't run.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from types import ModuleType
|
||||
from typing import Any, Callable, Sequence
|
||||
|
||||
from hamilton import ad_hoc_utils, driver
|
||||
from orquestacion.arista import Arista, Contexto
|
||||
from orquestacion.aristas import aristas_de
|
||||
from orquestacion.repositorios import repositorios_de
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Paso:
|
||||
"""What a step left: its short summary and how long it took. `None` summary: not run."""
|
||||
|
||||
arista: str
|
||||
resumen: Any
|
||||
segundos: float
|
||||
|
||||
|
||||
def _node(arista: Arista, ctx: Contexto, inputs: Sequence[str]) -> Callable[..., Paso]:
|
||||
def run(**_upstream: Paso) -> Paso:
|
||||
started = time.monotonic()
|
||||
return Paso(arista.nombre, arista.correr(ctx), time.monotonic() - started)
|
||||
|
||||
run.__name__ = arista.nombre
|
||||
run.__doc__ = arista.descripcion
|
||||
run.__annotations__ = {name: Paso for name in inputs} | {"return": Paso}
|
||||
run.__signature__ = inspect.Signature(
|
||||
[inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, annotation=Paso) for name in inputs],
|
||||
return_annotation=Paso,
|
||||
)
|
||||
return run
|
||||
|
||||
|
||||
def modulo(ctx: Contexto, aristas: Sequence[Arista]) -> ModuleType:
|
||||
"""The Hamilton module of a domain: one function per step."""
|
||||
writer = {vertex: arista.nombre for arista in aristas for vertex in arista.escribe}
|
||||
nodes = []
|
||||
for arista in aristas:
|
||||
inputs = sorted({writer[v] for v in arista.lee if v in writer and writer[v] != arista.nombre})
|
||||
nodes.append(_node(arista, ctx, inputs))
|
||||
return ad_hoc_utils.create_temporary_module(*nodes)
|
||||
|
||||
|
||||
def correr(ctx: Contexto, *, solo: Sequence[str] | None = None) -> list[Paso]:
|
||||
"""Runs the domain's steps (all, or only `solo`) in dependency order."""
|
||||
if ctx.repos is None:
|
||||
ctx = Contexto(ctx.proyecto, ctx.anio_inicio, ctx.anio_fin, ctx.corte, ctx.permitir_sin_definir,
|
||||
ctx.parametros, repos=repositorios_de(ctx.proyecto))
|
||||
aristas = aristas_de(ctx.proyecto)
|
||||
nombres = [a.nombre for a in aristas]
|
||||
wanted = [n for n in nombres if solo is None or n in solo]
|
||||
skipped = {n: Paso(n, None, 0.0) for n in nombres if n not in wanted}
|
||||
dr = driver.Builder().with_modules(modulo(ctx, aristas)).build()
|
||||
results = dr.execute(wanted, overrides=skipped)
|
||||
return [results[n] for n in _order(dr, wanted)]
|
||||
|
||||
|
||||
def _order(dr: driver.Driver, wanted: Sequence[str]) -> list[str]:
|
||||
"""Topological order of the requested steps, for reporting."""
|
||||
graph = dr.graph
|
||||
order: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def visit(name: str) -> None:
|
||||
if name in seen:
|
||||
return
|
||||
seen.add(name)
|
||||
for dependency in graph.nodes[name].dependencies:
|
||||
visit(dependency.name)
|
||||
if name in wanted:
|
||||
order.append(name)
|
||||
|
||||
for name in wanted:
|
||||
visit(name)
|
||||
return order
|
||||
Reference in New Issue
Block a user