Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0079f38446 | |||
| 9e92e25813 | |||
| 46c66406df | |||
| a2727f06ad | |||
| b660c77191 | |||
| a15ca94564 | |||
| 6eec071f3a | |||
| 9c0bff0cfe | |||
| 8bc0b06e7b | |||
| 830d978a1b | |||
| b89b630c2e | |||
| fecb0247d1 | |||
| 4c8f3e620e | |||
| 7577c99c62 | |||
| a188bf66e1 | |||
| cca67c837d | |||
| d76cb6cb20 | |||
| 84da0eb5fb | |||
| ceca8a03b5 | |||
| 0355d21d47 | |||
| c1444e2b8d |
@@ -1,2 +1,9 @@
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
.venv/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
|
.coverage
|
||||||
|
*.egg-info/
|
||||||
|
.env
|
||||||
|
uv.lock
|
||||||
|
*.db
|
||||||
|
|||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
# Build context is the ISSSTELEON repo root (see root docker-compose.yml)
|
||||||
|
# so this Dockerfile can COPY its sibling Core/, Persistance/, models/ and indicadores_kit/.
|
||||||
|
FROM python:3.12-slim
|
||||||
|
|
||||||
|
RUN pip install --no-cache-dir uv
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY Core/ Core/
|
||||||
|
COPY Persistance/ Persistance/
|
||||||
|
COPY models/ models/
|
||||||
|
COPY indicadores_kit/ indicadores_kit/
|
||||||
|
COPY WebApi/ WebApi/
|
||||||
|
|
||||||
|
RUN cd Persistance && uv sync --no-dev
|
||||||
|
RUN cd WebApi && uv sync --no-dev
|
||||||
|
|
||||||
|
ENV CACU_DATABASE_URL=sqlite:////data/cacu.db
|
||||||
|
ENV CAMA_DATABASE_URL=sqlite:////data/cama.db
|
||||||
|
ENV TEA_DATABASE_URL=sqlite:////data/tea.db
|
||||||
|
|
||||||
|
RUN chmod +x /app/WebApi/docker-entrypoint.sh
|
||||||
|
|
||||||
|
EXPOSE 5000
|
||||||
|
ENTRYPOINT ["/app/WebApi/docker-entrypoint.sh"]
|
||||||
@@ -0,0 +1,334 @@
|
|||||||
|
# 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`.
|
||||||
|
|
||||||
|
## 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 18 indicadores
|
||||||
|
├── Dockerfile imagen; el contexto es la raíz del repo padre
|
||||||
|
└── docker-entrypoint.sh migra las tres bases y arranca main.py
|
||||||
|
```
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
## Flujo de datos
|
||||||
|
|
||||||
|
Ruta de lectura simple (`/cacu/pacientes/<id>`):
|
||||||
|
|
||||||
|
```
|
||||||
|
request -> blueprint -> repositorio de Persistance -> modelo -> JSON
|
||||||
|
```
|
||||||
|
|
||||||
|
El repositorio abre y cierra su propia sesión.
|
||||||
|
|
||||||
|
Ruta de figura (la misma para `/cacu`, `/cama` y `/tea`):
|
||||||
|
|
||||||
|
```
|
||||||
|
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)
|
||||||
|
│ (indicadores_kit lee measure_report y arma el JSON de Plotly)
|
||||||
|
└─ finally: sesion.close()
|
||||||
|
│
|
||||||
|
v
|
||||||
|
Response(texto, mimetype="application/json")
|
||||||
|
```
|
||||||
|
|
||||||
|
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`.
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd WebApi
|
||||||
|
uv sync
|
||||||
|
uv run pytest
|
||||||
|
```
|
||||||
|
|
||||||
|
`WebApi` depende de `../Persistance`, `../models` y `../indicadores_kit`
|
||||||
|
(rutas editables en `pyproject.toml`). Requiere Python 3.12 o más.
|
||||||
|
|
||||||
|
### 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` |
|
||||||
|
|
||||||
|
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:
|
||||||
|
|
||||||
|
```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
|
||||||
|
```
|
||||||
|
|
||||||
|
### 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, carga el staging sintético y calcula los 18 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.** Con la misma `TEA_DATABASE_URL` en todos los pasos:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd Persistance
|
||||||
|
uv run alembic -c persistance/tea/alembic.ini upgrade head # tablas
|
||||||
|
# ... llene las tablas de staging de TEA (pacientes, evaluacion_psicologica, eeg_estudio, ...)
|
||||||
|
cd ../WebApi
|
||||||
|
uv run python -m indicadores_kit.tea.etl # staging -> hechos del kit
|
||||||
|
uv run python -m indicadores_kit.correr tea K01_evaluacion_3_meses 2025-S1 2025-S2
|
||||||
|
# repita `correr` por cada indicador (ids en /tea/indicadores)
|
||||||
|
uv run python main.py # http://localhost:5000
|
||||||
|
```
|
||||||
|
|
||||||
|
Cada `correr` agrega un reporte; no borra los anteriores.
|
||||||
|
|
||||||
|
**CaCu y CaMa** siguen los mismos pasos con su `alembic.ini`, su variable
|
||||||
|
de entorno y el ETL de su proyecto (`python -m indicadores_kit.cacu.etl`).
|
||||||
|
`correr` solo agrega semestres a `dim_periodo`; para tener también meses,
|
||||||
|
prepare los dos tipos y calcule con los pasos del kit:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv run python -c "
|
||||||
|
from datetime import date
|
||||||
|
from indicadores_kit.pasos import calcular_periodos, preparar_registro
|
||||||
|
from indicadores_kit.registry.measures import leer_measure, ruta_de_measure
|
||||||
|
preparar_registro('cacu', 2025, 2025, tipos=('semestre', 'mes'))
|
||||||
|
medida = leer_measure(ruta_de_measure('cacu', 'cacu_eu8'))
|
||||||
|
for tipo in ('semestre', 'mes'):
|
||||||
|
calcular_periodos('cacu', medida, tipo, date(2025, 1, 1), date(2026, 1, 1), permitir_sin_definir=True)
|
||||||
|
"
|
||||||
|
uv run python main.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Los ids son `cacu_eu8` y `cama_eu8`. En `tests/conftest.py` está la
|
||||||
|
secuencia completa con los fixtures del kit.
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
|
||||||
|
### 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`) |
|
||||||
|
| 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 |
|
||||||
|
|
||||||
|
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/K01_evaluacion_3_meses/figuras/fig_c1_grupos"
|
||||||
|
curl "localhost:5000/tea/indicadores/K01_evaluacion_3_meses/figuras/fig_c1_grupos?periodos=2025-S1,2025-S2&tema=oscuro"
|
||||||
|
curl localhost:5000/tea/indicadores/K01_evaluacion_3_meses/periodos
|
||||||
|
curl "localhost:5000/tea/indicadores/K01_evaluacion_3_meses/datos?periodos=2025-S1,2025-S2"
|
||||||
|
curl localhost:5000/tea/indicadores/K01_evaluacion_3_meses/metadatos
|
||||||
|
curl localhost:5000/cacu/indicadores
|
||||||
|
curl localhost:5000/cacu/indicadores/cacu_eu8/datos
|
||||||
|
curl "localhost:5000/cacu/indicadores/cacu_eu8/figuras/fig_c1_puntos?periodos=2025-01,2025-02,2025-03"
|
||||||
|
```
|
||||||
|
|
||||||
|
`/<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`). Las figuras dependen de la definición: con
|
||||||
|
ficha (TEA) hay una por contrato (`fig_c1_grupos`, `fig_c2_apiladas`,
|
||||||
|
`fig_c3r_caja`); sin ficha (CaCu, CaMa) es `fig_c1_puntos`, un punto por
|
||||||
|
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=` | `filas` (una por periodo y grupo), `grupos` y `categorias` con sus etiquetas, `reportes` con la procedencia de cada periodo |
|
||||||
|
| `/metadatos` | la ficha, la unidad, los estándares y las reglas que usa el indicador, con su estado |
|
||||||
|
|
||||||
|
`periodos` se pide igual que en la figura. `estrato` es uno de los
|
||||||
|
`estratos` del indicador. 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.
|
||||||
|
|
||||||
|
Códigos: 400 si `periodos` está mal formado o `estrato` no es del
|
||||||
|
indicador; 404 si el indicador no existe, no tiene reportes o algún
|
||||||
|
periodo pedido no lo tiene.
|
||||||
|
|
||||||
|
## 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 los 18 indicadores calculados.
|
||||||
|
|
||||||
|
Si cambias la URL después de crear el engine, llama a
|
||||||
|
`get_<dominio>_engine.cache_clear()`.
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
|
||||||
|
mkdir -p /data
|
||||||
|
|
||||||
|
cd /app/Persistance
|
||||||
|
uv run alembic -c persistance/cacu/alembic.ini upgrade head
|
||||||
|
uv run alembic -c persistance/cama/alembic.ini upgrade head
|
||||||
|
uv run alembic -c persistance/tea/alembic.ini upgrade head
|
||||||
|
|
||||||
|
cd /app/WebApi
|
||||||
|
exec uv run python main.py
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
from webapi import create_app
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
app.run(host="0.0.0.0", port=5000)
|
||||||
+20
-19
@@ -1,27 +1,28 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "webapi"
|
name = "webapi"
|
||||||
version = "0.0.0"
|
version = "0.1.0"
|
||||||
description = "FastAPI: FHIR routes, control routes, the auth dependency."
|
description = "Flask REST API fronting Persistance (reads) and models (train/predict) for CaCu, CaMa and TEA."
|
||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"core",
|
"flask>=3.0",
|
||||||
"persistance",
|
"persistance",
|
||||||
"fastapi[standard]",
|
"models",
|
||||||
"dagster-graphql",
|
"indicadores-kit",
|
||||||
"authlib>=1.6",
|
|
||||||
"fastapi-users[sqlalchemy]>=15",
|
|
||||||
"aiosqlite>=0.20",
|
|
||||||
"asyncpg>=0.30",
|
|
||||||
"requests",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[build-system]
|
|
||||||
requires = ["uv_build>=0.12,<0.13"]
|
|
||||||
build-backend = "uv_build"
|
|
||||||
|
|
||||||
[tool.uv.build-backend]
|
|
||||||
module-name = "webapi"
|
|
||||||
module-root = ""
|
|
||||||
[tool.uv.sources]
|
[tool.uv.sources]
|
||||||
core = { workspace = true }
|
persistance = { path = "../Persistance", editable = true }
|
||||||
persistance = { workspace = true }
|
models = { path = "../models", editable = true }
|
||||||
|
indicadores-kit = { path = "../indicadores_kit", editable = true }
|
||||||
|
|
||||||
|
[build-system]
|
||||||
|
requires = ["hatchling"]
|
||||||
|
build-backend = "hatchling.build"
|
||||||
|
|
||||||
|
[tool.hatch.build.targets.wheel]
|
||||||
|
packages = ["webapi"]
|
||||||
|
|
||||||
|
[dependency-groups]
|
||||||
|
dev = [
|
||||||
|
"pytest>=8.0.0",
|
||||||
|
]
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""Lo común de las pruebas de indicadores de CaCu y CaMa."""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
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."""
|
||||||
|
from persistance import db
|
||||||
|
from persistance.settings import settings
|
||||||
|
|
||||||
|
ruta = tmp_path_factory.mktemp(proyecto) / f"{proyecto}.db"
|
||||||
|
obtener_motor = getattr(db, f"get_{proyecto}_engine")
|
||||||
|
with pytest.MonkeyPatch.context() as mp:
|
||||||
|
mp.setattr(settings, f"{proyecto}_database_url", f"sqlite:///{ruta}")
|
||||||
|
obtener_motor.cache_clear()
|
||||||
|
try:
|
||||||
|
sembrar_base(proyecto, obtener_motor())
|
||||||
|
|
||||||
|
from webapi import create_app
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
app.config.update(TESTING=True)
|
||||||
|
with app.test_client() as cliente:
|
||||||
|
yield cliente
|
||||||
|
finally:
|
||||||
|
obtener_motor().dispose()
|
||||||
|
obtener_motor.cache_clear()
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
@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 core.cacu.base import CaCuModel
|
||||||
|
from core.cacu.models import Paciente
|
||||||
|
from persistance.db import get_cacu_engine
|
||||||
|
|
||||||
|
engine = get_cacu_engine()
|
||||||
|
CaCuModel.metadata.create_all(engine)
|
||||||
|
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
with Session(engine) as session:
|
||||||
|
session.add(Paciente(pac_id_hospital="H-1", pac_sexo="Femenino"))
|
||||||
|
session.commit()
|
||||||
|
|
||||||
|
from webapi import create_app
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
app.config.update(TESTING=True)
|
||||||
|
with app.test_client() as client:
|
||||||
|
yield client
|
||||||
|
|
||||||
|
os.unlink(db_path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_health(client):
|
||||||
|
response = client.get("/health")
|
||||||
|
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
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
import hashlib
|
|
||||||
from io import BytesIO
|
|
||||||
from zipfile import ZipFile
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from fastapi import HTTPException, UploadFile
|
|
||||||
|
|
||||||
from core.domains import Domain
|
|
||||||
from persistance import config
|
|
||||||
from webapi.models import import_models
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
("kind", "status", "detail"),
|
|
||||||
[
|
|
||||||
("wrong_sha", 422, "not the one given"),
|
|
||||||
("non_zip", 422, "not a bundle"),
|
|
||||||
("untrusted", 403, "not trusted on this server"),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_import_rejects_invalid_uploads(tmp_path, monkeypatch, kind, status, detail):
|
|
||||||
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
|
|
||||||
if kind == "non_zip":
|
|
||||||
data = b"hello"
|
|
||||||
else:
|
|
||||||
buffer = BytesIO()
|
|
||||||
with ZipFile(buffer, "w") as archive:
|
|
||||||
archive.writestr("manifest.json", "{}")
|
|
||||||
data = buffer.getvalue()
|
|
||||||
digest = hashlib.sha256(data).hexdigest()
|
|
||||||
sent = "0" * 64 if kind == "wrong_sha" else digest
|
|
||||||
|
|
||||||
with pytest.raises(HTTPException) as rejected:
|
|
||||||
import_models(Domain.TEA, sent, UploadFile(BytesIO(data), filename="bundle.zip"))
|
|
||||||
assert rejected.value.status_code == status
|
|
||||||
assert detail in rejected.value.detail
|
|
||||||
assert not (tmp_path / "bundles" / f"{digest}.zip").exists()
|
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
"""Rutas de indicadores de CACU: base SQLite temporal sembrada con los fixtures del kit."""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from conftest import MESES, SEMESTRES, cliente_de
|
||||||
|
from indicadores_kit.registry.measures import measures_de
|
||||||
|
from indicadores_kit.serving.figuras import figuras_de
|
||||||
|
|
||||||
|
PROYECTO = "cacu"
|
||||||
|
INDICADOR = "cacu_eu8"
|
||||||
|
DEFINICIONES = measures_de(PROYECTO)
|
||||||
|
(FIGURA,) = figuras_de(DEFINICIONES[INDICADOR])
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def client(tmp_path_factory):
|
||||||
|
yield from cliente_de(PROYECTO, tmp_path_factory)
|
||||||
|
|
||||||
|
|
||||||
|
def _figura(client, indicador: str = INDICADOR, figura: str = FIGURA, query: str = ""):
|
||||||
|
return client.get(f"/{PROYECTO}/indicadores/{indicador}/figuras/{figura}{query}")
|
||||||
|
|
||||||
|
|
||||||
|
def _x(respuesta) -> list[str]:
|
||||||
|
return [x for trazo in respuesta.get_json()["data"] for x in trazo["x"]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_listar_indicadores(client):
|
||||||
|
response = client.get(f"/{PROYECTO}/indicadores")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
lista = response.get_json()
|
||||||
|
visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto]
|
||||||
|
assert [fila["id"] for fila in lista] == sorted(visibles)
|
||||||
|
for fila in lista:
|
||||||
|
medida = DEFINICIONES[fila["id"]]
|
||||||
|
assert fila["titulo"] == medida.title
|
||||||
|
assert fila["contrato"] == medida.extension.contrato
|
||||||
|
assert fila["figuras"] == figuras_de(medida)
|
||||||
|
assert fila["tipos_periodo"] == ["semestre", "mes"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client):
|
||||||
|
"""Provisional (oct 2026): cacu_eu7_anormal, cacu_eu8 e ind2b no se muestran."""
|
||||||
|
ocultos = {"cacu_eu7_anormal", "cacu_eu8", "ind2b"}
|
||||||
|
ids = {fila["id"] for fila in client.get(f"/{PROYECTO}/indicadores").get_json()}
|
||||||
|
|
||||||
|
assert ids == set(DEFINICIONES) - ocultos
|
||||||
|
for indicador in ocultos:
|
||||||
|
assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_figura_con_semestres(client):
|
||||||
|
response = _figura(client, query=f"?periodos={','.join(SEMESTRES)}&tema=oscuro")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.mimetype == "application/json"
|
||||||
|
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES[INDICADOR].title
|
||||||
|
assert set(_x(response)) == set(SEMESTRES)
|
||||||
|
|
||||||
|
|
||||||
|
def test_figura_sin_periodos_usa_los_semestres_con_reporte(client):
|
||||||
|
response = _figura(client)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert set(_x(response)) == set(SEMESTRES) # el primer tipo que publica; los meses no entran
|
||||||
|
|
||||||
|
|
||||||
|
def test_figura_con_meses(client):
|
||||||
|
response = _figura(client, query=f"?periodos={','.join(MESES)}")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert set(_x(response)) == set(MESES)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"query",
|
||||||
|
[
|
||||||
|
"?tema=rojo",
|
||||||
|
"?periodos=2025-1",
|
||||||
|
"?periodos=2025-S3",
|
||||||
|
"?periodos=2025-13x",
|
||||||
|
"?periodos=2025-S1,",
|
||||||
|
"?periodos=abc",
|
||||||
|
"?periodos=2025-T1", # un tipo que el indicador no publica
|
||||||
|
"?periodos=2025-S1,2025-03", # tipos mezclados
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_figura_con_parametros_mal_formados_da_400(client, query):
|
||||||
|
response = _figura(client, query=query)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert "error" in response.get_json()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("indicador", "figura", "query"),
|
||||||
|
[
|
||||||
|
("CACU_NO_EXISTE", FIGURA, ""),
|
||||||
|
(INDICADOR, "fig_c2_apiladas", ""), # figura de otro contrato
|
||||||
|
(INDICADOR, "fig_no_existe", ""),
|
||||||
|
(INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte
|
||||||
|
(INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"),
|
||||||
|
(INDICADOR, FIGURA, "?periodos=2024-11"), # un mes sin reporte
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
||||||
|
response = _figura(client, indicador, figura, query)
|
||||||
|
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert "error" in response.get_json()
|
||||||
|
|
||||||
|
|
||||||
|
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
||||||
|
from webapi import indicadores
|
||||||
|
|
||||||
|
def falla(*args, **kwargs):
|
||||||
|
raise KeyError("columna")
|
||||||
|
|
||||||
|
monkeypatch.setattr(indicadores, "figura_json", falla)
|
||||||
|
with pytest.raises(KeyError):
|
||||||
|
_figura(client, query="?periodos=2025-S1")
|
||||||
|
|
||||||
|
|
||||||
|
# --- Todos los indicadores del proyecto ---
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||||
|
def test_figura_de_cada_indicador(client, indicador):
|
||||||
|
for figura in figuras_de(DEFINICIONES[indicador]):
|
||||||
|
response = _figura(client, indicador, figura)
|
||||||
|
|
||||||
|
assert response.status_code == 200, (indicador, figura)
|
||||||
|
assert set(response.get_json()) >= {"data", "layout"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_una_distribucion_sin_periodos_es_la_del_semestre_mas_reciente(client):
|
||||||
|
assert figuras_de(DEFINICIONES["cacu_eu7"]) == ["fig_c2_barras", "fig_c2_donas"]
|
||||||
|
|
||||||
|
por_defecto = _figura(client, "cacu_eu7", "fig_c2_donas")
|
||||||
|
del_ultimo = _figura(client, "cacu_eu7", "fig_c2_donas", f"?periodos={SEMESTRES[-1]}")
|
||||||
|
de_todos = _figura(client, "cacu_eu7", "fig_c2_donas", f"?periodos={','.join(SEMESTRES)}")
|
||||||
|
|
||||||
|
assert por_defecto.get_json() == del_ultimo.get_json()
|
||||||
|
assert len(de_todos.get_json()["data"]) == len(SEMESTRES) * len(por_defecto.get_json()["data"])
|
||||||
|
# La que compara periodos ya no se publica para una sola distribución.
|
||||||
|
assert _figura(client, "cacu_eu7", "fig_c2_apiladas").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
# --- El catálogo, los periodos, los datos y los metadatos ---
|
||||||
|
|
||||||
|
CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos"}
|
||||||
|
|
||||||
|
|
||||||
|
def _ruta(client, indicador: str, ruta: str, query: str = ""):
|
||||||
|
return client.get(f"/{PROYECTO}/indicadores/{indicador}/{ruta}{query}")
|
||||||
|
|
||||||
|
|
||||||
|
def test_el_catalogo_trae_lo_necesario_para_pedir_lo_demas(client):
|
||||||
|
lista = client.get(f"/{PROYECTO}/indicadores").get_json()
|
||||||
|
|
||||||
|
assert all(set(fila) == CATALOGO for fila in lista)
|
||||||
|
for fila in lista:
|
||||||
|
medida = DEFINICIONES[fila["id"]]
|
||||||
|
assert (fila["version"], fila["unidad"], fila["sentido"]) == (medida.version, medida.basis, medida.improvementNotation)
|
||||||
|
assert fila["estratos"] == medida.extension.estratos
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||||
|
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
|
||||||
|
medida = DEFINICIONES[indicador]
|
||||||
|
|
||||||
|
periodos = _ruta(client, indicador, "periodos")
|
||||||
|
datos = _ruta(client, indicador, "datos")
|
||||||
|
metadatos = _ruta(client, indicador, "metadatos")
|
||||||
|
|
||||||
|
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
|
||||||
|
assert all(r.mimetype == "application/json" for r in (periodos, datos, metadatos))
|
||||||
|
assert all(r.get_json()["id"] == indicador for r in (periodos, datos, metadatos))
|
||||||
|
de_semestre = [p["periodo"] for p in periodos.get_json()["periodos"] if p["tipo"] == "semestre"]
|
||||||
|
assert de_semestre == SEMESTRES
|
||||||
|
cuerpo = datos.get_json()
|
||||||
|
assert (cuerpo["contrato"], cuerpo["tipo_periodo"], cuerpo["periodos"]) == (medida.extension.contrato, "semestre", SEMESTRES)
|
||||||
|
assert cuerpo["filas"] and all(fila["estrato"] is None for fila in cuerpo["filas"])
|
||||||
|
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
|
||||||
|
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
|
||||||
|
assert metadatos.get_json()["tipo_calculo"] == medida.scoring
|
||||||
|
|
||||||
|
|
||||||
|
def test_datos_con_meses(client):
|
||||||
|
response = _ruta(client, INDICADOR, "datos", f"?periodos={','.join(MESES)}")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.get_json()["tipo_periodo"] == "mes"
|
||||||
|
assert [fila["periodo"] for fila in response.get_json()["filas"]] == MESES
|
||||||
|
|
||||||
|
|
||||||
|
def test_los_datos_dicen_de_que_reporte_salen(client):
|
||||||
|
cuerpo = _ruta(client, INDICADOR, "datos", "?periodos=2025-S1").get_json()
|
||||||
|
periodos = _ruta(client, INDICADOR, "periodos").get_json()["periodos"]
|
||||||
|
|
||||||
|
(reporte,) = cuerpo["reportes"]
|
||||||
|
assert reporte["report_id"] == next(p["report_id"] for p in periodos if p["periodo"] == "2025-S1")
|
||||||
|
assert (reporte["periodo_inicio"], reporte["periodo_fin"]) == ("2025-01-01", "2025-07-01")
|
||||||
|
assert cuerpo["version"] == DEFINICIONES[INDICADOR].version
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("query", ["?periodos=2025-S3", "?periodos=2025-S1,2025-03", "?estrato=no_existe"])
|
||||||
|
def test_datos_con_parametros_mal_formados_da_400(client, query):
|
||||||
|
response = _ruta(client, INDICADOR, "datos", query)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert "error" in response.get_json()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("indicador", "ruta", "query"),
|
||||||
|
[
|
||||||
|
("NO_EXISTE", "datos", ""),
|
||||||
|
("NO_EXISTE", "periodos", ""),
|
||||||
|
("NO_EXISTE", "metadatos", ""),
|
||||||
|
(INDICADOR, "datos", "?periodos=2030-S1"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indicador, ruta, query):
|
||||||
|
response = _ruta(client, indicador, ruta, query)
|
||||||
|
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert "error" in response.get_json()
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
"""Rutas de indicadores de CAMA: base SQLite temporal sembrada con los fixtures del kit."""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from conftest import MESES, SEMESTRES, cliente_de
|
||||||
|
from indicadores_kit.registry.measures import measures_de
|
||||||
|
from indicadores_kit.serving.figuras import figuras_de
|
||||||
|
|
||||||
|
PROYECTO = "cama"
|
||||||
|
INDICADOR = "cama_eu8"
|
||||||
|
DEFINICIONES = measures_de(PROYECTO)
|
||||||
|
(FIGURA,) = figuras_de(DEFINICIONES[INDICADOR])
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def client(tmp_path_factory):
|
||||||
|
yield from cliente_de(PROYECTO, tmp_path_factory)
|
||||||
|
|
||||||
|
|
||||||
|
def _figura(client, indicador: str = INDICADOR, figura: str = FIGURA, query: str = ""):
|
||||||
|
return client.get(f"/{PROYECTO}/indicadores/{indicador}/figuras/{figura}{query}")
|
||||||
|
|
||||||
|
|
||||||
|
def _x(respuesta) -> list[str]:
|
||||||
|
return [x for trazo in respuesta.get_json()["data"] for x in trazo["x"]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_listar_indicadores(client):
|
||||||
|
response = client.get(f"/{PROYECTO}/indicadores")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
lista = response.get_json()
|
||||||
|
visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto]
|
||||||
|
assert [fila["id"] for fila in lista] == sorted(visibles)
|
||||||
|
for fila in lista:
|
||||||
|
medida = DEFINICIONES[fila["id"]]
|
||||||
|
assert fila["titulo"] == medida.title
|
||||||
|
assert fila["contrato"] == medida.extension.contrato
|
||||||
|
assert fila["figuras"] == figuras_de(medida)
|
||||||
|
assert fila["tipos_periodo"] == ["semestre", "mes"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client):
|
||||||
|
"""Provisional (oct 2026): cama_confirmacion_birads45, cama_eu8 y cama_birads no se muestran.
|
||||||
|
|
||||||
|
cama_birads lo sustituyen cama_birads_456_paciente y cama_birads_456_mastografia.
|
||||||
|
"""
|
||||||
|
ocultos = {"cama_confirmacion_birads45", "cama_eu8", "cama_birads"}
|
||||||
|
ids = {fila["id"] for fila in client.get(f"/{PROYECTO}/indicadores").get_json()}
|
||||||
|
|
||||||
|
assert ids == set(DEFINICIONES) - ocultos
|
||||||
|
for indicador in ocultos:
|
||||||
|
assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_figura_con_semestres(client):
|
||||||
|
response = _figura(client, query=f"?periodos={','.join(SEMESTRES)}&tema=oscuro")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.mimetype == "application/json"
|
||||||
|
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES[INDICADOR].title
|
||||||
|
assert set(_x(response)) == set(SEMESTRES)
|
||||||
|
|
||||||
|
|
||||||
|
def test_figura_sin_periodos_usa_los_semestres_con_reporte(client):
|
||||||
|
response = _figura(client)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert set(_x(response)) == set(SEMESTRES) # el primer tipo que publica; los meses no entran
|
||||||
|
|
||||||
|
|
||||||
|
def test_figura_con_meses(client):
|
||||||
|
response = _figura(client, query=f"?periodos={','.join(MESES)}")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert set(_x(response)) == set(MESES)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"query",
|
||||||
|
[
|
||||||
|
"?tema=rojo",
|
||||||
|
"?periodos=2025-1",
|
||||||
|
"?periodos=2025-S3",
|
||||||
|
"?periodos=2025-13x",
|
||||||
|
"?periodos=2025-S1,",
|
||||||
|
"?periodos=abc",
|
||||||
|
"?periodos=2025-T1", # un tipo que el indicador no publica
|
||||||
|
"?periodos=2025-S1,2025-03", # tipos mezclados
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_figura_con_parametros_mal_formados_da_400(client, query):
|
||||||
|
response = _figura(client, query=query)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert "error" in response.get_json()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("indicador", "figura", "query"),
|
||||||
|
[
|
||||||
|
("CAMA_NO_EXISTE", FIGURA, ""),
|
||||||
|
(INDICADOR, "fig_c2_apiladas", ""), # figura de otro contrato
|
||||||
|
(INDICADOR, "fig_no_existe", ""),
|
||||||
|
(INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte
|
||||||
|
(INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"),
|
||||||
|
(INDICADOR, FIGURA, "?periodos=2024-11"), # un mes sin reporte
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
||||||
|
response = _figura(client, indicador, figura, query)
|
||||||
|
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert "error" in response.get_json()
|
||||||
|
|
||||||
|
|
||||||
|
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
||||||
|
from webapi import indicadores
|
||||||
|
|
||||||
|
def falla(*args, **kwargs):
|
||||||
|
raise KeyError("columna")
|
||||||
|
|
||||||
|
monkeypatch.setattr(indicadores, "figura_json", falla)
|
||||||
|
with pytest.raises(KeyError):
|
||||||
|
_figura(client, query="?periodos=2025-S1")
|
||||||
|
|
||||||
|
|
||||||
|
# --- Todos los indicadores del proyecto ---
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||||
|
def test_figura_de_cada_indicador(client, indicador):
|
||||||
|
for figura in figuras_de(DEFINICIONES[indicador]):
|
||||||
|
response = _figura(client, indicador, figura)
|
||||||
|
|
||||||
|
assert response.status_code == 200, (indicador, figura)
|
||||||
|
assert set(response.get_json()) >= {"data", "layout"}
|
||||||
|
|
||||||
|
|
||||||
|
# --- El catálogo, los periodos, los datos y los metadatos ---
|
||||||
|
|
||||||
|
CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos"}
|
||||||
|
|
||||||
|
|
||||||
|
def _ruta(client, indicador: str, ruta: str, query: str = ""):
|
||||||
|
return client.get(f"/{PROYECTO}/indicadores/{indicador}/{ruta}{query}")
|
||||||
|
|
||||||
|
|
||||||
|
def test_el_catalogo_trae_lo_necesario_para_pedir_lo_demas(client):
|
||||||
|
lista = client.get(f"/{PROYECTO}/indicadores").get_json()
|
||||||
|
|
||||||
|
assert all(set(fila) == CATALOGO for fila in lista)
|
||||||
|
for fila in lista:
|
||||||
|
medida = DEFINICIONES[fila["id"]]
|
||||||
|
assert (fila["version"], fila["unidad"], fila["sentido"]) == (medida.version, medida.basis, medida.improvementNotation)
|
||||||
|
assert fila["estratos"] == medida.extension.estratos
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||||
|
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
|
||||||
|
medida = DEFINICIONES[indicador]
|
||||||
|
|
||||||
|
periodos = _ruta(client, indicador, "periodos")
|
||||||
|
datos = _ruta(client, indicador, "datos")
|
||||||
|
metadatos = _ruta(client, indicador, "metadatos")
|
||||||
|
|
||||||
|
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
|
||||||
|
assert all(r.mimetype == "application/json" for r in (periodos, datos, metadatos))
|
||||||
|
assert all(r.get_json()["id"] == indicador for r in (periodos, datos, metadatos))
|
||||||
|
de_semestre = [p["periodo"] for p in periodos.get_json()["periodos"] if p["tipo"] == "semestre"]
|
||||||
|
assert de_semestre == SEMESTRES
|
||||||
|
cuerpo = datos.get_json()
|
||||||
|
assert (cuerpo["contrato"], cuerpo["tipo_periodo"], cuerpo["periodos"]) == (medida.extension.contrato, "semestre", SEMESTRES)
|
||||||
|
assert cuerpo["filas"] and all(fila["estrato"] is None for fila in cuerpo["filas"])
|
||||||
|
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
|
||||||
|
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
|
||||||
|
assert metadatos.get_json()["tipo_calculo"] == medida.scoring
|
||||||
|
|
||||||
|
|
||||||
|
def test_datos_con_meses(client):
|
||||||
|
response = _ruta(client, INDICADOR, "datos", f"?periodos={','.join(MESES)}")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.get_json()["tipo_periodo"] == "mes"
|
||||||
|
assert [fila["periodo"] for fila in response.get_json()["filas"]] == MESES
|
||||||
|
|
||||||
|
|
||||||
|
def test_los_datos_dicen_de_que_reporte_salen(client):
|
||||||
|
cuerpo = _ruta(client, INDICADOR, "datos", "?periodos=2025-S1").get_json()
|
||||||
|
periodos = _ruta(client, INDICADOR, "periodos").get_json()["periodos"]
|
||||||
|
|
||||||
|
(reporte,) = cuerpo["reportes"]
|
||||||
|
assert reporte["report_id"] == next(p["report_id"] for p in periodos if p["periodo"] == "2025-S1")
|
||||||
|
assert (reporte["periodo_inicio"], reporte["periodo_fin"]) == ("2025-01-01", "2025-07-01")
|
||||||
|
assert cuerpo["version"] == DEFINICIONES[INDICADOR].version
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("query", ["?periodos=2025-S3", "?periodos=2025-S1,2025-03", "?estrato=no_existe"])
|
||||||
|
def test_datos_con_parametros_mal_formados_da_400(client, query):
|
||||||
|
response = _ruta(client, INDICADOR, "datos", query)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert "error" in response.get_json()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("indicador", "ruta", "query"),
|
||||||
|
[
|
||||||
|
("NO_EXISTE", "datos", ""),
|
||||||
|
("NO_EXISTE", "periodos", ""),
|
||||||
|
("NO_EXISTE", "metadatos", ""),
|
||||||
|
(INDICADOR, "datos", "?periodos=2030-S1"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indicador, ruta, query):
|
||||||
|
response = _ruta(client, indicador, ruta, query)
|
||||||
|
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert "error" in response.get_json()
|
||||||
@@ -1,161 +0,0 @@
|
|||||||
import pytest
|
|
||||||
from dagster import DagsterRunStatus
|
|
||||||
from fastapi import HTTPException
|
|
||||||
|
|
||||||
from persistance.cluster import Progress
|
|
||||||
from webapi.runs import _locked, cancel_run, shape
|
|
||||||
|
|
||||||
PAYLOAD = {
|
|
||||||
"runId": "run",
|
|
||||||
"jobName": "analyze",
|
|
||||||
"status": "SUCCESS",
|
|
||||||
"startTime": 1.0,
|
|
||||||
"endTime": 4.0,
|
|
||||||
"tags": [{"key": "domain", "value": "cacu"}],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def test_shape_splits_info_and_warnings():
|
|
||||||
def event(level, message, step_key=None, kind="LogMessageEvent"):
|
|
||||||
return {"__typename": kind, "level": level, "message": message, "stepKey": step_key}
|
|
||||||
|
|
||||||
run = shape(
|
|
||||||
PAYLOAD,
|
|
||||||
[
|
|
||||||
event("INFO", "starting"),
|
|
||||||
event("WARNING", "skipped", "analyze_studies"),
|
|
||||||
event("DEBUG", "debug"),
|
|
||||||
event("INFO", "engine", kind="EngineEvent"),
|
|
||||||
event("INFO", "finished", "analyze_studies"),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
assert run.info == ["starting", "analyze_studies: finished"]
|
|
||||||
assert run.warnings == ["analyze_studies: skipped"]
|
|
||||||
assert run.error is None
|
|
||||||
|
|
||||||
warning_only = shape(PAYLOAD, [event("WARNING", "skipped")])
|
|
||||||
assert warning_only.state == "succeeded"
|
|
||||||
assert warning_only.error is None
|
|
||||||
|
|
||||||
steps = [
|
|
||||||
{"stepKey": "waiting", "status": "SKIPPED", "startTime": None, "endTime": None},
|
|
||||||
{"stepKey": "second", "status": "SUCCESS", "startTime": 2, "endTime": 4},
|
|
||||||
{"stepKey": "first", "status": "SUCCESS", "startTime": 0, "endTime": 1},
|
|
||||||
]
|
|
||||||
assert [step.key for step in shape(PAYLOAD | {"stepStats": steps}, []).steps] == [
|
|
||||||
"first", "second", "waiting",
|
|
||||||
] # fmt: skip
|
|
||||||
|
|
||||||
capped = shape(
|
|
||||||
PAYLOAD, [event(level, str(i)) for i in range(201) for level in ("INFO", "WARNING")]
|
|
||||||
)
|
|
||||||
assert capped.info == [str(i) for i in range(1, 201)]
|
|
||||||
assert capped.warnings == [str(i) for i in range(200)]
|
|
||||||
|
|
||||||
|
|
||||||
def test_shape_failure_message_is_the_ops_own_exception():
|
|
||||||
failed = PAYLOAD | {"status": "FAILURE"}
|
|
||||||
step_failure = {
|
|
||||||
"__typename": "ExecutionStepFailureEvent",
|
|
||||||
"error": {
|
|
||||||
"message": "DagsterExecutionStepExecutionError: invocation failed",
|
|
||||||
"causes": [
|
|
||||||
{"message": "intermediate cause"},
|
|
||||||
{"message": " LookupError: no EEG x|2026-01-01\nmore details "},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
}
|
|
||||||
assert shape(failed, [step_failure]).error == "LookupError: no EEG x|2026-01-01"
|
|
||||||
run_failure = {"__typename": "RunFailureEvent", "error": {"message": "x" * 501}}
|
|
||||||
assert shape(failed, [step_failure, run_failure]).error == "x" * 500
|
|
||||||
assert shape(failed, []).error == "the run failed"
|
|
||||||
|
|
||||||
|
|
||||||
def test_shape_progress_tag():
|
|
||||||
progress = Progress(
|
|
||||||
phase="analyzing", done=3, total=6, elapsed_s=4, eta_s=4, mode="sync",
|
|
||||||
scheduler=None, updated_at="2026-01-01T00:00:00Z",
|
|
||||||
) # fmt: skip
|
|
||||||
|
|
||||||
def with_tag(value):
|
|
||||||
return PAYLOAD | {"tags": [{"key": "isssteleon/progress", "value": value}]}
|
|
||||||
|
|
||||||
run = shape(with_tag(progress.model_dump_json()), [])
|
|
||||||
assert run.progress is not None
|
|
||||||
assert run.progress.done == 3
|
|
||||||
assert run.progress.phase == "analyzing"
|
|
||||||
assert shape(with_tag("{bad json"), []).progress is None
|
|
||||||
for status, state in (
|
|
||||||
("QUEUED", "queued"),
|
|
||||||
("STARTING", "running"),
|
|
||||||
("CANCELING", "cancelling"),
|
|
||||||
("CANCELED", "cancelled"),
|
|
||||||
):
|
|
||||||
run = shape(PAYLOAD | {"status": status}, [])
|
|
||||||
assert (run.status, run.state) == (status, state)
|
|
||||||
assert shape(PAYLOAD | {"status": "UNKNOWN"}, []).state == "running"
|
|
||||||
|
|
||||||
|
|
||||||
def test_shape_outputs():
|
|
||||||
events = [
|
|
||||||
{
|
|
||||||
"__typename": "ExecutionStepOutputEvent",
|
|
||||||
"stepKey": "preview_study",
|
|
||||||
"outputName": "result",
|
|
||||||
"metadataEntries": [
|
|
||||||
{"label": "result", "jsonString": '{"eeg": {"valid": false}}'},
|
|
||||||
{"label": "text"},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
]
|
|
||||||
assert shape(PAYLOAD, events, outputs=True).outputs == {
|
|
||||||
"preview_study.result": {"eeg": {"valid": False}}
|
|
||||||
}
|
|
||||||
assert shape(PAYLOAD, events, outputs=False).outputs is None
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("initial", [DagsterRunStatus.QUEUED, DagsterRunStatus.STARTED])
|
|
||||||
def test_cancel_returns_the_terminal_or_cancelling_state(initial):
|
|
||||||
class Client:
|
|
||||||
status = initial
|
|
||||||
|
|
||||||
def get_run_status(self, run_id):
|
|
||||||
return self.status
|
|
||||||
|
|
||||||
def terminate_run(self, run_id):
|
|
||||||
self.status = {
|
|
||||||
DagsterRunStatus.QUEUED: DagsterRunStatus.CANCELED,
|
|
||||||
DagsterRunStatus.STARTED: DagsterRunStatus.CANCELING,
|
|
||||||
}[self.status]
|
|
||||||
|
|
||||||
result = cancel_run("r1", client=Client())
|
|
||||||
expected = (
|
|
||||||
("CANCELED", "cancelled")
|
|
||||||
if initial == DagsterRunStatus.QUEUED
|
|
||||||
else ("CANCELING", "cancelling")
|
|
||||||
)
|
|
||||||
assert (result.id, result.status, result.state) == ("r1", *expected)
|
|
||||||
|
|
||||||
|
|
||||||
def test_cancel_a_finished_run_is_409():
|
|
||||||
class Client:
|
|
||||||
def get_run_status(self, run_id):
|
|
||||||
return DagsterRunStatus.SUCCESS
|
|
||||||
|
|
||||||
with pytest.raises(HTTPException) as error:
|
|
||||||
cancel_run("r1", client=Client())
|
|
||||||
assert error.value.status_code == 409
|
|
||||||
assert error.value.detail == "the run already ended: succeeded"
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_storage_lock_is_distinguished_from_a_run_failure():
|
|
||||||
assert _locked({"errors": [{"message": "OperationalError: database is locked"}]})
|
|
||||||
assert _locked(
|
|
||||||
{"data": {"logsForRun": {"__typename": "PythonError", "message": "database is locked"}}}
|
|
||||||
)
|
|
||||||
assert not _locked(
|
|
||||||
{"data": {"logsForRun": {"__typename": "EventConnection", "message": "database is locked"}}}
|
|
||||||
)
|
|
||||||
assert not _locked(
|
|
||||||
{"data": {"logsForRun": {"__typename": "PythonError", "message": "unknown error"}}}
|
|
||||||
)
|
|
||||||
@@ -1,140 +0,0 @@
|
|||||||
import sqlite3
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from fastapi.testclient import TestClient
|
|
||||||
|
|
||||||
from webapi import sources
|
|
||||||
from webapi.main import app
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def client(own_platform, monkeypatch):
|
|
||||||
monkeypatch.setenv("SOURCE_ROOTS", str(own_platform / "shared"))
|
|
||||||
(own_platform / "shared" / "reportes" / "2026").mkdir(parents=True)
|
|
||||||
with TestClient(app) as c:
|
|
||||||
yield c
|
|
||||||
|
|
||||||
|
|
||||||
def probe(client, kind, **answers):
|
|
||||||
response = client.post("/ingest/sources/test", json={"type": kind, "answers": answers})
|
|
||||||
assert response.status_code == 200, response.text
|
|
||||||
return response.json()
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_dialog_lists_every_kind_with_its_questions(client):
|
|
||||||
found = client.get("/ingest/sources/types").json()
|
|
||||||
assert {"database", "files", "cloud", "web"} <= set(found["groups"])
|
|
||||||
assert found["types"]["sqlserver"]["fields"]["password"]["type"] == "password"
|
|
||||||
|
|
||||||
|
|
||||||
def test_an_unknown_server_and_a_missing_answer_say_so_plainly(client):
|
|
||||||
gone = probe(client, "sqlserver", host="nowhere.invalid", database="P", user="u",
|
|
||||||
password="p") # fmt: skip
|
|
||||||
assert not gone["ok"] and gone["message"].startswith(("No se encontró", "El servidor no"))
|
|
||||||
assert probe(client, "postgresql", host="h")["message"].startswith("falta «Base de datos»")
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_sqlite_file_lists_its_tables_then_shows_rows(client, own_platform):
|
|
||||||
path = own_platform / "shared" / "hospital.db"
|
|
||||||
with sqlite3.connect(path) as con:
|
|
||||||
con.execute("create table pacientes (id int, nombre text)")
|
|
||||||
con.execute("insert into pacientes values (1, 'Ana')")
|
|
||||||
assert probe(client, "sqlite", path=str(path))["tables"] == ["pacientes"]
|
|
||||||
rows = probe(client, "sqlite", path=str(path), table="pacientes")["rows"]
|
|
||||||
assert rows == [{"id": 1, "nombre": "Ana"}]
|
|
||||||
|
|
||||||
|
|
||||||
def test_server_folders_are_browsed_only_under_the_mounted_roots(client, own_platform):
|
|
||||||
roots = client.get("/ingest/sources/browse").json()["entries"]
|
|
||||||
assert [e["name"] for e in roots] == ["shared"]
|
|
||||||
inside = client.get("/ingest/sources/browse", params={"path": roots[0]["path"]}).json()
|
|
||||||
assert [e["name"] for e in inside["entries"]] == ["reportes"]
|
|
||||||
assert client.get("/ingest/sources/browse", params={"path": "/etc"}).status_code == 404
|
|
||||||
escape = str(own_platform / "shared" / ".." / "data")
|
|
||||||
assert client.get("/ingest/sources/browse", params={"path": escape}).status_code == 404
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_folder_uploaded_from_a_computer_is_read_as_spreadsheets_or_documents(client):
|
|
||||||
sent = [("files", ("informes/enero/a.csv", b"folio,resultado\n1,NEGATIVO\n")),
|
|
||||||
("files", ("informes/b.pdf", b"%PDF-1.4 ..."))] # fmt: skip
|
|
||||||
uploaded = client.post("/ingest/uploads", files=sent).json()
|
|
||||||
assert sorted(uploaded["files"]) == ["informes/b.pdf", "informes/enero/a.csv"]
|
|
||||||
more = client.post("/ingest/uploads", files=[("files", ("../../fuera.csv", b"x\n"))],
|
|
||||||
data={"folder": uploaded["bucket_url"]}).json() # fmt: skip
|
|
||||||
assert more["files"] == ["fuera.csv"] and more["bucket_url"] == uploaded["bucket_url"]
|
|
||||||
other = client.post("/ingest/uploads", files=[("files", ("x", b"x"))], data={"folder": "/"})
|
|
||||||
assert other.status_code == 422
|
|
||||||
rows = probe(client, "upload", folder=uploaded["bucket_url"], pattern="**/*.csv",
|
|
||||||
read_as="dlt.sources.filesystem:read_csv")["rows"] # fmt: skip
|
|
||||||
assert rows == [{"folio": 1, "resultado": "NEGATIVO"}]
|
|
||||||
files = probe(client, "upload", folder=uploaded["bucket_url"], pattern="**/*.pdf")["rows"]
|
|
||||||
assert [f["file_name"] for f in files] == ["b.pdf"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_an_empty_folder_says_what_to_check(client, own_platform):
|
|
||||||
found = probe(client, "server_folder", folder=str(own_platform / "shared" / "reportes"))
|
|
||||||
assert found["ok"] and "Revise la ruta" in found["message"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_sign_in_button_without_an_app_registration_says_who_must_register_one(client):
|
|
||||||
found = client.get("/ingest/sources/oauth/google/start", params={"origin": "http://x"})
|
|
||||||
assert found.status_code == 503 and "GOOGLE_CLIENT_ID" in found.json()["detail"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_signing_in_hands_the_account_to_the_dialog(client, monkeypatch, tmp_path):
|
|
||||||
from authlib.integrations.httpx_client import OAuth2Client, oauth2_client
|
|
||||||
|
|
||||||
httpx = oauth2_client.httpx2
|
|
||||||
|
|
||||||
monkeypatch.setenv("MICROSOFT_CLIENT_ID", "app")
|
|
||||||
monkeypatch.setenv("MICROSOFT_CLIENT_SECRET", "app-secret")
|
|
||||||
exchanged = {}
|
|
||||||
|
|
||||||
def provider(request: httpx.Request) -> httpx.Response:
|
|
||||||
exchanged["body"] = request.content.decode()
|
|
||||||
return httpx.Response(200, json={"access_token": "at", "refresh_token": "rt",
|
|
||||||
"token_type": "Bearer", "expires_in": 3600}) # fmt: skip
|
|
||||||
|
|
||||||
def client_for(found, env, redirect_uri):
|
|
||||||
return OAuth2Client(env["client_id"], env["client_secret"], scope=found.scope,
|
|
||||||
redirect_uri=redirect_uri, code_challenge_method="S256",
|
|
||||||
transport=httpx.MockTransport(provider)) # fmt: skip
|
|
||||||
|
|
||||||
monkeypatch.setattr(sources, "_client", client_for)
|
|
||||||
monkeypatch.setattr(sources, "PENDING", tmp_path / "pending")
|
|
||||||
monkeypatch.setattr(sources, "account", lambda p, token, env: {
|
|
||||||
"user": "ana@hospital.mx", "drive_id": "d1",
|
|
||||||
"oauth2_client_params": {"client_id": env["client_id"], "token": token}}) # fmt: skip
|
|
||||||
start = client.get("/ingest/sources/oauth/microsoft/start",
|
|
||||||
params={"origin": "http://10.0.10.41:5710"}).json() # fmt: skip
|
|
||||||
assert start["url"].startswith("https://login.microsoftonline.com/organizations/")
|
|
||||||
assert "code_challenge=" in start["url"] and "client_id=app" in start["url"]
|
|
||||||
back = client.get("/ingest/sources/oauth/microsoft/callback",
|
|
||||||
params={"state": start["state"], "code": "c0de"}) # fmt: skip
|
|
||||||
assert back.status_code == 200
|
|
||||||
assert '"user": "ana@hospital.mx"' in back.text and '"http://10.0.10.41:5710"' in back.text
|
|
||||||
assert "code_verifier=" in exchanged["body"] and "code=c0de" in exchanged["body"]
|
|
||||||
again = client.get("/ingest/sources/oauth/microsoft/callback",
|
|
||||||
params={"state": start["state"], "code": "c0de"}) # fmt: skip
|
|
||||||
assert again.status_code == 400
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_saved_account_shows_who_but_never_its_tokens():
|
|
||||||
from core.pipeline import MASK, Pipeline, redacted, restored
|
|
||||||
|
|
||||||
params = {"client_id": "app", "client_secret": "app-secret-xyz",
|
|
||||||
"token": {"refresh_token": "refresh-xyz"}} # fmt: skip
|
|
||||||
account = {"user": "ana@hospital.mx", "drive_id": "d1", "oauth2_client_params": params}
|
|
||||||
saved = Pipeline(nodes=[{"id": "s", "kind": "source", "guided": {
|
|
||||||
"type": "onedrive", "answers": {"account": account, "folder": "Reportes"}}}]) # fmt: skip
|
|
||||||
shown = redacted(saved)
|
|
||||||
answer = shown.nodes[0].guided.answers["account"]
|
|
||||||
assert answer["user"] == "ana@hospital.mx"
|
|
||||||
dumped = shown.model_dump_json()
|
|
||||||
assert "refresh-xyz" not in dumped and "app-secret-xyz" not in dumped
|
|
||||||
assert answer["oauth2_client_params"]["client_secret"] == MASK
|
|
||||||
back = restored(Pipeline.model_validate(shown.model_dump()), saved).nodes[0]
|
|
||||||
assert (
|
|
||||||
back.args["storage_options"]["oauth2_client_params"]["token"]["refresh_token"]
|
|
||||||
== "refresh-xyz"
|
|
||||||
)
|
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
import pytest
|
||||||
|
from indicadores_kit.registry.measures import measures_de
|
||||||
|
from indicadores_kit.serving.figuras import figuras_de
|
||||||
|
from indicadores_kit.tea import fixtures
|
||||||
|
|
||||||
|
DEFINICIONES = measures_de("tea")
|
||||||
|
PERIODOS = ",".join(fixtures.PERIODOS)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def client(tmp_path_factory):
|
||||||
|
"""Una base de TEA temporal, con los 20 indicadores calculados (16 en el catálogo), por `TEA_DATABASE_URL`."""
|
||||||
|
# Dentro de la fixture: la configuración de Persistance se lee al importarla,
|
||||||
|
# y test_app.py debe alcanzar a fijar CACU_DATABASE_URL antes.
|
||||||
|
from persistance.db import get_tea_engine
|
||||||
|
from persistance.settings import settings
|
||||||
|
|
||||||
|
ruta = tmp_path_factory.mktemp("tea") / "tea.db"
|
||||||
|
with pytest.MonkeyPatch.context() as mp:
|
||||||
|
mp.setattr(settings, "tea_database_url", f"sqlite:///{ruta}")
|
||||||
|
get_tea_engine.cache_clear()
|
||||||
|
try:
|
||||||
|
fixtures.base_de_prueba(get_tea_engine())
|
||||||
|
|
||||||
|
from webapi import create_app
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
app.config.update(TESTING=True)
|
||||||
|
with app.test_client() as cliente:
|
||||||
|
yield cliente
|
||||||
|
finally:
|
||||||
|
get_tea_engine().dispose()
|
||||||
|
get_tea_engine.cache_clear()
|
||||||
|
|
||||||
|
|
||||||
|
def _figura(client, indicador: str, figura: str, query: str = ""):
|
||||||
|
return client.get(f"/tea/indicadores/{indicador}/figuras/{figura}{query}")
|
||||||
|
|
||||||
|
|
||||||
|
def test_listar_indicadores(client):
|
||||||
|
response = client.get("/tea/indicadores")
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
lista = response.get_json()
|
||||||
|
visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto]
|
||||||
|
assert [fila["id"] for fila in lista] == sorted(visibles)
|
||||||
|
for fila in lista:
|
||||||
|
medida = DEFINICIONES[fila["id"]]
|
||||||
|
assert fila["titulo"] == medida.title
|
||||||
|
assert fila["contrato"] == medida.extension.contrato
|
||||||
|
assert fila["figuras"] == figuras_de(medida)
|
||||||
|
|
||||||
|
|
||||||
|
def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client):
|
||||||
|
"""Provisional (oct 2026): solo se muestran M21, M22 y los tres destacados (M23 a M25)."""
|
||||||
|
visibles = {
|
||||||
|
"M21_diagnosticados_con_eeg",
|
||||||
|
"M22_diagnosticados_sin_eeg",
|
||||||
|
"M23_pacientes_evaluados",
|
||||||
|
"M24_confirmacion_diagnostico",
|
||||||
|
"M25_dias_mchat_diagnostico",
|
||||||
|
}
|
||||||
|
ids = {fila["id"] for fila in client.get("/tea/indicadores").get_json()}
|
||||||
|
|
||||||
|
assert ids == visibles
|
||||||
|
for oculto in sorted(set(DEFINICIONES) - visibles):
|
||||||
|
assert client.get(f"/tea/indicadores/{oculto}/metadatos").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||||
|
def test_figura_de_cada_indicador(client, indicador):
|
||||||
|
for figura in figuras_de(DEFINICIONES[indicador]):
|
||||||
|
response = _figura(client, indicador, figura, f"?periodos={PERIODOS}&tema=oscuro")
|
||||||
|
|
||||||
|
assert response.status_code == 200, figura
|
||||||
|
assert response.mimetype == "application/json"
|
||||||
|
assert "data" in response.get_json()
|
||||||
|
|
||||||
|
|
||||||
|
def test_figura_sin_periodos_usa_todos_los_reportes(client):
|
||||||
|
(figura,) = figuras_de(DEFINICIONES["K01_evaluacion_3_meses"])
|
||||||
|
|
||||||
|
response = _figura(client, "K01_evaluacion_3_meses", figura)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES["K01_evaluacion_3_meses"].title
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"query",
|
||||||
|
[
|
||||||
|
"?tema=rojo",
|
||||||
|
"?periodos=2025-1",
|
||||||
|
"?periodos=2025-S1,",
|
||||||
|
"?periodos=abc",
|
||||||
|
"?periodos=,",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_figura_con_parametros_mal_formados_da_400(client, query):
|
||||||
|
response = _figura(client, "K01_evaluacion_3_meses", "fig_c1_grupos", query)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert "error" in response.get_json()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("indicador", "figura", "query"),
|
||||||
|
[
|
||||||
|
("K99_no_existe", "fig_c1_grupos", ""),
|
||||||
|
("K01_evaluacion_3_meses", "fig_c2_apiladas", ""), # figura de otro contrato
|
||||||
|
("K01_evaluacion_3_meses", "fig_no_existe", ""),
|
||||||
|
("K01_evaluacion_3_meses", "fig_c1_grupos", "?periodos=2030-S1"), # sin reporte
|
||||||
|
("K01_evaluacion_3_meses", "fig_c1_grupos", f"?periodos={PERIODOS},2030-S2"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
||||||
|
response = _figura(client, indicador, figura, query)
|
||||||
|
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert "error" in response.get_json()
|
||||||
|
|
||||||
|
|
||||||
|
def test_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
|
||||||
|
|
||||||
|
def falla(*args, **kwargs):
|
||||||
|
raise KeyError("columna")
|
||||||
|
|
||||||
|
monkeypatch.setattr(indicadores, "figura_json", falla)
|
||||||
|
with pytest.raises(KeyError):
|
||||||
|
_figura(client, "K01_evaluacion_3_meses", "fig_c1_grupos", "?periodos=2025-S1")
|
||||||
|
|
||||||
|
|
||||||
|
# --- Los periodos, los datos y los metadatos ---
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||||
|
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
|
||||||
|
medida = DEFINICIONES[indicador]
|
||||||
|
|
||||||
|
periodos = client.get(f"/tea/indicadores/{indicador}/periodos")
|
||||||
|
datos = client.get(f"/tea/indicadores/{indicador}/datos?periodos={PERIODOS}")
|
||||||
|
metadatos = client.get(f"/tea/indicadores/{indicador}/metadatos")
|
||||||
|
|
||||||
|
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
|
||||||
|
assert [p["periodo"] for p in periodos.get_json()["periodos"]] == sorted(fixtures.PERIODOS)
|
||||||
|
cuerpo = datos.get_json()
|
||||||
|
assert (cuerpo["id"], cuerpo["contrato"]) == (indicador, medida.extension.contrato)
|
||||||
|
assert cuerpo["filas"] and {fila["periodo"] for fila in cuerpo["filas"]} == set(fixtures.PERIODOS)
|
||||||
|
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
|
||||||
|
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
|
||||||
|
assert metadatos.get_json()["ficha"]["codigo"] == medida.extension.ficha.codigo
|
||||||
|
|
||||||
|
|
||||||
|
def test_los_grupos_de_los_datos_van_en_el_orden_de_la_ficha(client):
|
||||||
|
response = client.get(f"/tea/indicadores/K01_evaluacion_3_meses/datos?periodos={PERIODOS}")
|
||||||
|
|
||||||
|
grupos = list(response.get_json()["grupos"])
|
||||||
|
assert grupos != sorted(grupos) # el orden de la ficha, no el alfabético
|
||||||
|
assert grupos[-1] == "TOTAL"
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
import pytest
|
|
||||||
from fastapi import HTTPException
|
|
||||||
from pydantic import ValidationError
|
|
||||||
|
|
||||||
from core.domains import Domain
|
|
||||||
from persistance.cluster import FolderTrainingSource
|
|
||||||
from webapi import models
|
|
||||||
from webapi.models import Training, train, training_config
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
|
||||||
def sync_execution(monkeypatch):
|
|
||||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
|
||||||
|
|
||||||
|
|
||||||
def test_tea_training_config_schema():
|
|
||||||
config = training_config(Domain.TEA, "example").model_dump()
|
|
||||||
assert (config["domain"], config["name"]) == ("tea", "example")
|
|
||||||
schema = config["json_schema"]
|
|
||||||
assert schema["title"] == "TrainingForm"
|
|
||||||
assert set(schema["properties"]) == {"as_of", "execution", "source"}
|
|
||||||
assert schema["properties"]["as_of"]["title"] == "Datos hasta"
|
|
||||||
assert set(schema["$defs"]) == {
|
|
||||||
"Execution",
|
|
||||||
"TrainingSource",
|
|
||||||
"SiteTrainingSource",
|
|
||||||
"FolderTrainingSource",
|
|
||||||
}
|
|
||||||
execution = schema["$defs"]["Execution"]
|
|
||||||
assert execution["title"] == "Ejecución"
|
|
||||||
assert execution["properties"]["mode"]["title"] == "Modo"
|
|
||||||
assert execution["properties"]["scheduler"]["title"] == "Planificador Dask"
|
|
||||||
source = schema["$defs"]["TrainingSource"]
|
|
||||||
assert source["discriminator"] == {
|
|
||||||
"propertyName": "kind",
|
|
||||||
"mapping": {
|
|
||||||
"site": "#/$defs/SiteTrainingSource",
|
|
||||||
"folder": "#/$defs/FolderTrainingSource",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
assert source["oneOf"] == [
|
|
||||||
{"$ref": "#/$defs/SiteTrainingSource"},
|
|
||||||
{"$ref": "#/$defs/FolderTrainingSource"},
|
|
||||||
]
|
|
||||||
site = schema["$defs"]["SiteTrainingSource"]
|
|
||||||
assert set(site["properties"]) == {"kind"}
|
|
||||||
folder = schema["$defs"]["FolderTrainingSource"]
|
|
||||||
assert folder["properties"]["folder"]["title"] == "Carpeta"
|
|
||||||
assert folder["properties"]["line_hz"]["enum"] == [50, 60]
|
|
||||||
assert (site["title"], folder["title"]) == (
|
|
||||||
"Niños del sitio sin el diagnóstico",
|
|
||||||
"Carpeta de EDF con edades",
|
|
||||||
)
|
|
||||||
assert schema["properties"]["source"]["title"] == "Datos de entrenamiento"
|
|
||||||
assert config["defaults"] == {
|
|
||||||
"execution": {"mode": "sync", "scheduler": None},
|
|
||||||
"source": {"kind": "site"},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def test_other_domains_have_no_training_source():
|
|
||||||
for domain in ("cacu", "cama"):
|
|
||||||
config = training_config(Domain(domain), "example").model_dump()
|
|
||||||
assert (config["domain"], config["name"]) == (domain, "example")
|
|
||||||
schema = config["json_schema"]
|
|
||||||
assert set(schema["properties"]) == {"as_of", "execution"}
|
|
||||||
assert set(schema["$defs"]) == {"Execution"}
|
|
||||||
assert config["defaults"] == {"execution": {"mode": "sync", "scheduler": None}}
|
|
||||||
|
|
||||||
|
|
||||||
def test_train_validates_the_training_source():
|
|
||||||
with pytest.raises(HTTPException) as rejected:
|
|
||||||
train(Domain.CACU, Training(source={"kind": "site"}))
|
|
||||||
assert rejected.value.status_code == 422
|
|
||||||
assert rejected.value.detail == "cacu models take no training source"
|
|
||||||
|
|
||||||
for source in (
|
|
||||||
{"kind": "folder"},
|
|
||||||
{"kind": "folder", "folder": "../x"},
|
|
||||||
{"kind": "folder", "folder": "hel", "line_hz": 55},
|
|
||||||
{"kind": "site", "folder": "hel"},
|
|
||||||
{"kind": "site", "line_hz": 60},
|
|
||||||
{"kind": "other"},
|
|
||||||
):
|
|
||||||
with pytest.raises(ValidationError):
|
|
||||||
Training(source=source)
|
|
||||||
assert Training(source={"kind": "site"}).model_dump()["source"] == {"kind": "site"}
|
|
||||||
folder = Training(source={"kind": "folder", "folder": "hel"}).source
|
|
||||||
assert isinstance(folder, FolderTrainingSource)
|
|
||||||
assert folder.line_hz == 50
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
"source",
|
|
||||||
[
|
|
||||||
{"kind": "site"},
|
|
||||||
{"kind": "folder", "folder": "hel", "line_hz": 60},
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_train_submits_the_selected_source(monkeypatch, source):
|
|
||||||
client = object()
|
|
||||||
|
|
||||||
def submit(actual_client, job, op, config, *, domain):
|
|
||||||
assert actual_client is client
|
|
||||||
assert (job, op, domain) == ("train", "train_models", "tea")
|
|
||||||
assert config["source"] == source
|
|
||||||
return {"run_id": "training"}
|
|
||||||
|
|
||||||
monkeypatch.setattr(models, "submit", submit)
|
|
||||||
assert train(Domain.TEA, Training(source=source), client) == {"run_id": "training"}
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
import pytest
|
|
||||||
from fastapi.testclient import TestClient
|
|
||||||
|
|
||||||
from webapi.main import app
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def client(own_platform, monkeypatch):
|
|
||||||
monkeypatch.setenv("AUTH_ADMIN_EMAIL", "admin@isssteleon.mx")
|
|
||||||
monkeypatch.setenv("AUTH_ADMIN_PASSWORD", "una-clave-larga")
|
|
||||||
with TestClient(app) as c:
|
|
||||||
yield c
|
|
||||||
|
|
||||||
|
|
||||||
def login(client, email, password):
|
|
||||||
return client.post("/auth/login", data={"username": email, "password": password})
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_first_administrator_signs_in_and_adds_a_team(client):
|
|
||||||
assert client.get("/users/me").status_code == 401
|
|
||||||
assert login(client, "admin@isssteleon.mx", "mala").status_code == 400
|
|
||||||
assert login(client, "admin@isssteleon.mx", "una-clave-larga").status_code == 204
|
|
||||||
me = client.get("/users/me").json()
|
|
||||||
assert me["is_superuser"] and me["domains"] == ["cacu", "cama", "tea"]
|
|
||||||
team = {"email": "cacu@isssteleon.mx", "password": "equipo-cacu", "name": "Equipo CaCu",
|
|
||||||
"domains": ["cacu"]} # fmt: skip
|
|
||||||
assert client.post("/users/register", json=team).status_code == 201
|
|
||||||
client.post("/auth/logout")
|
|
||||||
assert login(client, "cacu@isssteleon.mx", "equipo-cacu").status_code == 204
|
|
||||||
assert client.get("/users/me").json()["domains"] == ["cacu"]
|
|
||||||
other = {"email": "x@isssteleon.mx", "password": "otra-clave"}
|
|
||||||
assert client.post("/users/register", json=other).status_code == 403
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_api_answers_without_a_session(client):
|
|
||||||
for path in ("/health", "/domains", "/ingest/schema", "/ingest/sources/types"):
|
|
||||||
assert client.get(path).status_code == 200, path
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_restart_keeps_the_administrator_once_and_the_session_secret(client, own_platform):
|
|
||||||
assert login(client, "admin@isssteleon.mx", "una-clave-larga").status_code == 204
|
|
||||||
secret = (own_platform / "auth_secret").read_text()
|
|
||||||
with TestClient(app):
|
|
||||||
pass
|
|
||||||
assert (own_platform / "auth_secret").read_text() == secret
|
|
||||||
assert client.get("/users/me").status_code == 200
|
|
||||||
@@ -1,178 +0,0 @@
|
|||||||
import json
|
|
||||||
import os
|
|
||||||
import shutil
|
|
||||||
import socket
|
|
||||||
import sqlite3
|
|
||||||
import subprocess
|
|
||||||
import time
|
|
||||||
from contextlib import closing, contextmanager
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from models.tea.jobs import ASSOCIATION, MODELS
|
|
||||||
from synthetic import tea
|
|
||||||
|
|
||||||
ROOT = Path(__file__).parents[2]
|
|
||||||
FIXTURES = ROOT / "tests" / "fixtures"
|
|
||||||
|
|
||||||
|
|
||||||
def _ok(response: httpx.Response):
|
|
||||||
assert response.status_code == 200, response.text
|
|
||||||
return response.json()
|
|
||||||
|
|
||||||
|
|
||||||
def _port() -> int:
|
|
||||||
with socket.socket() as s:
|
|
||||||
s.bind(("127.0.0.1", 0))
|
|
||||||
return s.getsockname()[1]
|
|
||||||
|
|
||||||
|
|
||||||
def _until_up(url: str, process: subprocess.Popen, seconds: int = 180) -> None:
|
|
||||||
deadline = time.monotonic() + seconds
|
|
||||||
while time.monotonic() < deadline:
|
|
||||||
assert process.poll() is None, f"{process.args[0]} exited with {process.returncode}"
|
|
||||||
try:
|
|
||||||
if httpx.get(url, timeout=2).status_code == 200:
|
|
||||||
return
|
|
||||||
except httpx.TransportError:
|
|
||||||
pass
|
|
||||||
time.sleep(1)
|
|
||||||
raise TimeoutError(url)
|
|
||||||
|
|
||||||
|
|
||||||
def _wait(api: httpx.Client, run_id: str, seconds: int = 1800) -> None:
|
|
||||||
deadline = time.monotonic() + seconds
|
|
||||||
while (run := _ok(api.get(f"/runs/{run_id}")))["state"] not in ("succeeded", "failed"):
|
|
||||||
assert time.monotonic() < deadline, f"run {run_id} still {run['state']}"
|
|
||||||
time.sleep(2)
|
|
||||||
assert run["state"] == "succeeded", run.get("error")
|
|
||||||
|
|
||||||
|
|
||||||
def _sensor_run(api: httpx.Client, seconds: int = 300) -> str:
|
|
||||||
deadline = time.monotonic() + seconds
|
|
||||||
while not (runs := _ok(api.get("/runs", params={"job": "tea_eeg", "domain": "tea"}))):
|
|
||||||
assert time.monotonic() < deadline, "the sensor started no tea_eeg run"
|
|
||||||
time.sleep(2)
|
|
||||||
return runs[0]["id"]
|
|
||||||
|
|
||||||
|
|
||||||
def _train_tea(api: httpx.Client) -> None:
|
|
||||||
_wait(api, _ok(api.post("/tea/eegs/analyze", json={}))["run_id"])
|
|
||||||
for names in (list(MODELS), [ASSOCIATION]):
|
|
||||||
training = _ok(
|
|
||||||
api.post(
|
|
||||||
"/models/tea/train",
|
|
||||||
json={
|
|
||||||
"models": names,
|
|
||||||
"source": {"kind": "site"},
|
|
||||||
},
|
|
||||||
)
|
|
||||||
)
|
|
||||||
_wait(api, training["run_id"])
|
|
||||||
for name in names:
|
|
||||||
versions = f"/models/tea/{name}/versions"
|
|
||||||
version = _ok(api.get(versions))[-1]["version"]
|
|
||||||
path = f"{versions}/{version}"
|
|
||||||
_ok(
|
|
||||||
api.post(
|
|
||||||
f"{path}/reports/clinical_validation",
|
|
||||||
files={
|
|
||||||
"file": ("synthetic-validation.txt", b"Synthetic hospital test fixture")
|
|
||||||
},
|
|
||||||
)
|
|
||||||
)
|
|
||||||
_ok(api.post(f"{path}/promote"))
|
|
||||||
assert any(
|
|
||||||
v["version"] == version and v["status"] == "champion"
|
|
||||||
for v in _ok(api.get(versions))
|
|
||||||
), name
|
|
||||||
_wait(api, _ok(api.post("/tea/eegs/analyze", json={}))["run_id"])
|
|
||||||
|
|
||||||
|
|
||||||
@contextmanager
|
|
||||||
def _platform(data: Path):
|
|
||||||
from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore
|
|
||||||
|
|
||||||
(data / "dagster").mkdir(parents=True)
|
|
||||||
(data / "reference").mkdir()
|
|
||||||
shutil.copy(ROOT / "dagster.yaml", data / "dagster")
|
|
||||||
tracking = f"sqlite:///{data / 'mlflow.db'}"
|
|
||||||
SqlAlchemyStore(tracking, (data / "mlflow").as_uri()).engine.dispose()
|
|
||||||
dagster_port, api_port = _port(), _port()
|
|
||||||
env = {
|
|
||||||
**os.environ,
|
|
||||||
"ISSSTELEON_DATA": str(data),
|
|
||||||
"DLT_DATA_DIR": str(data / "dlt"),
|
|
||||||
"DAGSTER_HOME": str(data / "dagster"),
|
|
||||||
"DAGSTER_HOST": "127.0.0.1",
|
|
||||||
"DAGSTER_PORT": str(dagster_port),
|
|
||||||
"MLFLOW_TRACKING_URI": tracking,
|
|
||||||
"MLFLOW_DISABLE_AGENT_HINT": "1",
|
|
||||||
"EXECUTION_MODE": "sync",
|
|
||||||
"TEA_REFERENCE_ROOT": str(data / "reference"),
|
|
||||||
"AUTH_ADMIN_EMAIL": "admin@isssteleon.mx",
|
|
||||||
"AUTH_ADMIN_PASSWORD": "solo-para-pruebas",
|
|
||||||
}
|
|
||||||
webserver = subprocess.Popen(
|
|
||||||
["dagster-webserver", "-m", "models.definitions", "-h", "127.0.0.1",
|
|
||||||
"-p", str(dagster_port)], env=env, cwd=data,
|
|
||||||
) # fmt: skip
|
|
||||||
server = subprocess.Popen(
|
|
||||||
["fastapi", "run", str(ROOT / "WebApi" / "webapi" / "main.py"), "--host", "127.0.0.1",
|
|
||||||
"--port", str(api_port)], env=env, cwd=data,
|
|
||||||
) # fmt: skip
|
|
||||||
daemon = None
|
|
||||||
try:
|
|
||||||
_until_up(f"http://127.0.0.1:{dagster_port}/server_info", webserver)
|
|
||||||
daemon = subprocess.Popen(
|
|
||||||
["dagster-daemon", "run", "-m", "models.definitions"], env=env, cwd=data
|
|
||||||
)
|
|
||||||
_until_up(f"http://127.0.0.1:{api_port}/health", server)
|
|
||||||
with httpx.Client(base_url=f"http://127.0.0.1:{api_port}", timeout=120) as client:
|
|
||||||
yield client
|
|
||||||
finally:
|
|
||||||
for process in (server, daemon, webserver):
|
|
||||||
if process is not None:
|
|
||||||
process.terminate()
|
|
||||||
process.wait(timeout=30)
|
|
||||||
|
|
||||||
|
|
||||||
def _study_files(db: Path, out: Path) -> dict[str, str]:
|
|
||||||
out.mkdir()
|
|
||||||
with closing(sqlite3.connect(db)) as con:
|
|
||||||
edf, report, birth = con.execute(
|
|
||||||
"SELECT eeg_estudio, ord_pdf_blob, pac_fecha_nacimiento FROM eeg "
|
|
||||||
"JOIN pacientes ON pac_id = eeg_pac_id "
|
|
||||||
"JOIN ados2 ON ado_pac_id = eeg_pac_id "
|
|
||||||
"JOIN ordenes_estudio ON ord_id = ado_ord_id ORDER BY eeg_id LIMIT 1"
|
|
||||||
).fetchone()
|
|
||||||
(out / "study.edf").write_bytes(edf)
|
|
||||||
(out / "ados2.pdf").write_bytes(report)
|
|
||||||
return {
|
|
||||||
"TEA_EDF": str(out / "study.edf"),
|
|
||||||
"TEA_ADOS2": str(out / "ados2.pdf"),
|
|
||||||
"TEA_BIRTH": birth,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.webapp
|
|
||||||
def test_the_tea_pages_load_from_the_synthetic_hospital(tmp_path):
|
|
||||||
hospital = tmp_path / "hospital"
|
|
||||||
hospital.mkdir()
|
|
||||||
tea.build(hospital / "hospital_tea.db")
|
|
||||||
files = _study_files(hospital / "hospital_tea.db", tmp_path / "files")
|
|
||||||
concept_map = json.loads((FIXTURES / "concept_maps" / "hospital_tea.json").read_text())
|
|
||||||
drawn = (FIXTURES / "pipelines" / "hospital_tea.json").read_text()
|
|
||||||
pipeline = json.loads(drawn.replace("{hospital}", str(hospital)))
|
|
||||||
with _platform(tmp_path / "platform") as api:
|
|
||||||
_ok(api.put("/ingest/concept-maps/hospital_tea", json=concept_map))
|
|
||||||
_ok(api.put("/ingest/pipelines/tea", json=pipeline))
|
|
||||||
_wait(api, _ok(api.post("/ingest/pipelines/tea/runs", json={}))["run_id"])
|
|
||||||
_wait(api, _sensor_run(api))
|
|
||||||
_train_tea(api)
|
|
||||||
subprocess.run(
|
|
||||||
["npx", "playwright", "test"], cwd=ROOT / "WebApp", check=True,
|
|
||||||
env={**os.environ, **files, "API_URL": str(api.base_url).rstrip("/")},
|
|
||||||
) # fmt: skip
|
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
from webapi.blueprints.cacu import cacu_bp
|
||||||
|
from webapi.blueprints.cama import cama_bp
|
||||||
|
from webapi.blueprints.tea import tea_bp
|
||||||
|
|
||||||
|
|
||||||
|
def create_app() -> Flask:
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
def health():
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
app.register_blueprint(cacu_bp, url_prefix="/cacu")
|
||||||
|
app.register_blueprint(cama_bp, url_prefix="/cama")
|
||||||
|
app.register_blueprint(tea_bp, url_prefix="/tea")
|
||||||
|
|
||||||
|
return app
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
from dataclasses import dataclass
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class Caller:
|
|
||||||
id: str = "anonymous"
|
|
||||||
|
|
||||||
|
|
||||||
def caller() -> Caller:
|
|
||||||
return Caller()
|
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
from flask import Blueprint, jsonify
|
||||||
|
|
||||||
|
from models.cacu import CaCuModel
|
||||||
|
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):
|
||||||
|
"""Example read route — proves WebApi resolves Persistance's repository API."""
|
||||||
|
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():
|
||||||
|
"""Example predict route — proves WebApi resolves the models package."""
|
||||||
|
model = CaCuModel()
|
||||||
|
try:
|
||||||
|
return jsonify({"prediction": model.predict(data=None)})
|
||||||
|
except NotImplementedError as exc:
|
||||||
|
return jsonify({"error": str(exc)}), 501
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
from flask import Blueprint, jsonify
|
||||||
|
|
||||||
|
from models.cama import CaMaModel
|
||||||
|
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():
|
||||||
|
model = CaMaModel()
|
||||||
|
try:
|
||||||
|
return jsonify({"prediction": model.predict(data=None)})
|
||||||
|
except NotImplementedError as exc:
|
||||||
|
return jsonify({"error": str(exc)}), 501
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
from flask import Blueprint, jsonify
|
||||||
|
|
||||||
|
from models.tea import TeaModel
|
||||||
|
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():
|
||||||
|
model = TeaModel()
|
||||||
|
try:
|
||||||
|
return jsonify({"prediction": model.predict(data=None)})
|
||||||
|
except NotImplementedError as exc:
|
||||||
|
return jsonify({"error": str(exc)}), 501
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
from typing import Any
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
|
||||||
from pydantic import BaseModel
|
|
||||||
|
|
||||||
from persistance import eeg
|
|
||||||
from persistance.cluster import Execution
|
|
||||||
from persistance.eeg import Scope
|
|
||||||
from webapi.runs import dagster, execution_config, submit
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/tea/eegs", tags=["eeg"])
|
|
||||||
|
|
||||||
|
|
||||||
class Study(BaseModel):
|
|
||||||
id: str
|
|
||||||
person_id: str
|
|
||||||
study_date: str
|
|
||||||
lab_record_id: str | None
|
|
||||||
analysed: bool
|
|
||||||
valid: bool | None
|
|
||||||
level: str | None
|
|
||||||
|
|
||||||
|
|
||||||
class Metric(BaseModel):
|
|
||||||
code: str
|
|
||||||
value: float
|
|
||||||
z: float | None
|
|
||||||
outside: float | None
|
|
||||||
model: str | None
|
|
||||||
|
|
||||||
|
|
||||||
class Analysis(BaseModel):
|
|
||||||
id: str
|
|
||||||
valid: bool | None
|
|
||||||
level: str | None
|
|
||||||
age_months: float | None
|
|
||||||
metrics: list[Metric]
|
|
||||||
checks: list[dict[str, Any]]
|
|
||||||
regions: list[dict[str, Any]]
|
|
||||||
|
|
||||||
|
|
||||||
class AnalyzeRequest(BaseModel):
|
|
||||||
scope: Scope = Scope()
|
|
||||||
execution: Execution | None = None
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("")
|
|
||||||
def studies() -> list[Study]:
|
|
||||||
return [Study(**s) for s in eeg.studies()]
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/analyze",
|
|
||||||
description="Starts `tea_eeg`: analyse the EEGs in scope, score the curves, rebuild gold.",
|
|
||||||
)
|
|
||||||
def analyze_eegs(request: AnalyzeRequest, client=Depends(dagster)) -> dict[str, str]:
|
|
||||||
config = {"scope": request.scope.model_dump(), "execution": execution_config(request.execution)}
|
|
||||||
return submit(client, "tea_eeg", "tea_analyze_studies", config, domain="tea")
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/summary")
|
|
||||||
def eeg_studies_summary() -> dict[str, int]:
|
|
||||||
return eeg.summary()
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{eeg_id}")
|
|
||||||
def study(eeg_id: str) -> Analysis:
|
|
||||||
if (found := eeg.study(eeg_id)) is None:
|
|
||||||
raise HTTPException(404, detail=f"no analysed EEG {eeg_id}")
|
|
||||||
return Analysis(**found)
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
from fastapi import APIRouter, HTTPException
|
|
||||||
|
|
||||||
from persistance import cluster
|
|
||||||
from persistance.cluster import Execution, Health, Mode, Options
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/execution", tags=["execution"])
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/options")
|
|
||||||
def execution_options() -> Options:
|
|
||||||
return cluster.options()
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/health")
|
|
||||||
def execution_health(
|
|
||||||
mode: Mode | None = None, scheduler: str | None = None, reference: str | None = None
|
|
||||||
) -> Health:
|
|
||||||
try:
|
|
||||||
return cluster.health(Execution(mode=mode, scheduler=scheduler), reference)
|
|
||||||
except cluster.ExecutionError as e:
|
|
||||||
raise HTTPException(422, detail=str(e)) from e
|
|
||||||
-716
@@ -1,716 +0,0 @@
|
|||||||
import unicodedata
|
|
||||||
from collections import defaultdict
|
|
||||||
from datetime import date, datetime
|
|
||||||
from typing import Annotated, Any
|
|
||||||
from urllib.parse import urlencode
|
|
||||||
|
|
||||||
from dagster_graphql import DagsterGraphQLClient
|
|
||||||
from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request
|
|
||||||
from fastapi.responses import Response
|
|
||||||
from fhir.resources.R4B.bundle import Bundle
|
|
||||||
from fhir.resources.R4B.capabilitystatement import CapabilityStatement
|
|
||||||
from fhir.resources.R4B.operationoutcome import OperationOutcome
|
|
||||||
from fhir.resources.R4B.parameters import Parameters
|
|
||||||
from fhir.resources.R4B.resource import Resource
|
|
||||||
|
|
||||||
from core import catalog
|
|
||||||
from core import fhir as f
|
|
||||||
from core import measures as m
|
|
||||||
from core.domains import Domain, measures, part
|
|
||||||
from core.follow_up import window_start
|
|
||||||
from core.pipeline import ID_PATTERN
|
|
||||||
from core.tea import fhir as tea_fhir
|
|
||||||
from core.tea.follow_up import FILTERS as TEA_FILTERS
|
|
||||||
from persistance import config_log, readers
|
|
||||||
from persistance import fhir as reads
|
|
||||||
from persistance import measures as measure_reads
|
|
||||||
from webapi.ingest import submit
|
|
||||||
from webapi.runs import dagster
|
|
||||||
|
|
||||||
FHIR_JSON = "application/fhir+json"
|
|
||||||
PAGE, MAX_PAGE = 50, 200
|
|
||||||
REVINCLUDES = ("DiagnosticReport:subject", "RiskAssessment:subject", "Observation:subject")
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/{domain}/fhir", tags=["fhir"])
|
|
||||||
_OK = {200: {"content": {FHIR_JSON: {"schema": {"type": "object"}}}, "description": "FHIR"}}
|
|
||||||
|
|
||||||
|
|
||||||
def fhir(resource: Resource) -> Response:
|
|
||||||
return Response(resource.model_dump_json(exclude_none=True), media_type=FHIR_JSON)
|
|
||||||
|
|
||||||
|
|
||||||
def outcome(status: int, text: str) -> Response:
|
|
||||||
issue = {"severity": "error", "code": "not-found" if status == 404 else "invalid",
|
|
||||||
"diagnostics": text} # fmt: skip
|
|
||||||
return Response(OperationOutcome(issue=[issue]).model_dump_json(exclude_none=True),
|
|
||||||
status_code=status, media_type=FHIR_JSON) # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def _clinical(domain: Domain):
|
|
||||||
if (found := part(domain, "follow_up")) is None:
|
|
||||||
raise HTTPException(404, f"no clinical resources for {domain.value} yet")
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
def _cutoff(domain: Domain, asked: date | None) -> date:
|
|
||||||
if asked is not None:
|
|
||||||
return asked
|
|
||||||
return reads.last_data_day(domain.value) or date.today()
|
|
||||||
|
|
||||||
|
|
||||||
def _page(count: int | None, offset: int) -> tuple[int, int]:
|
|
||||||
count = PAGE if count is None else count
|
|
||||||
if not 0 <= count <= MAX_PAGE or offset < 0:
|
|
||||||
raise HTTPException(422, f"_count goes from 0 to {MAX_PAGE}; _offset from 0")
|
|
||||||
return count, offset
|
|
||||||
|
|
||||||
|
|
||||||
def bundle(request: Request, matches: list[Resource], total: int, count: int, offset: int,
|
|
||||||
included: list[Resource] = (), applied: dict | None = None) -> Response: # fmt: skip
|
|
||||||
base = str(request.base_url).rstrip("/") + request.url.path.rsplit("/", 1)[0]
|
|
||||||
|
|
||||||
def link(relation: str, at: int) -> dict:
|
|
||||||
params = {**(applied or {}), "_offset": at, "_count": count}
|
|
||||||
query = [(k, v) for k, v in request.query_params.multi_items() if k not in params]
|
|
||||||
url = request.url.replace(query=urlencode([*query, *params.items()], doseq=True))
|
|
||||||
return {"relation": relation, "url": str(url)}
|
|
||||||
|
|
||||||
links = [link("self", offset)]
|
|
||||||
if offset + count < total:
|
|
||||||
links.append(link("next", offset + count))
|
|
||||||
if offset > 0:
|
|
||||||
links.append(link("previous", max(offset - count, 0)))
|
|
||||||
groups = (("match", matches), ("include", included))
|
|
||||||
entries = [{"fullUrl": f"{base}/{r.get_resource_type()}/{r.id}", "resource": r,
|
|
||||||
"search": {"mode": mode}} for mode, group in groups for r in group] # fmt: skip
|
|
||||||
found = Bundle(type="searchset", total=total, link=links, entry=entries or None)
|
|
||||||
return fhir(found)
|
|
||||||
|
|
||||||
|
|
||||||
def _sliced(found: list, count: int, offset: int) -> list:
|
|
||||||
return found[offset:offset + count] # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
_WINDOW = Query(
|
|
||||||
None,
|
|
||||||
alias="follow-up-window",
|
|
||||||
description="months: the domain's follow-up list over that window up to the cut-off",
|
|
||||||
)
|
|
||||||
_START = Query(
|
|
||||||
None,
|
|
||||||
alias="follow-up-start",
|
|
||||||
description="explicit window start that overrides follow-up-window",
|
|
||||||
)
|
|
||||||
_CUTOFF = Query(None, alias="follow-up-cutoff", description="default: the last day with data")
|
|
||||||
_STATUS = Query(None, alias="follow-up-status")
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/Patient/$eeg-summary",
|
|
||||||
responses=_OK,
|
|
||||||
response_class=Response,
|
|
||||||
description="EEG counts for the follow-up list. Without a window or start, "
|
|
||||||
"use the whole history.",
|
|
||||||
)
|
|
||||||
def eeg_summary(
|
|
||||||
request: Request,
|
|
||||||
domain: Domain,
|
|
||||||
window: int | None = _WINDOW,
|
|
||||||
start: date | None = _START,
|
|
||||||
cutoff: date | None = _CUTOFF,
|
|
||||||
status: str | None = _STATUS,
|
|
||||||
) -> Response:
|
|
||||||
fu = _clinical(domain)
|
|
||||||
if not hasattr(fu, "summary"):
|
|
||||||
return outcome(404, f"no EEG summary for {domain.value}")
|
|
||||||
at = _cutoff(domain, cutoff)
|
|
||||||
try:
|
|
||||||
rows, _, _ = _patient_rows(request, domain, fu, at, window, start, cutoff, status,
|
|
||||||
whole_history=True) # fmt: skip
|
|
||||||
except ValueError as exc:
|
|
||||||
return outcome(422, str(exc))
|
|
||||||
counts = fu.summary(rows)
|
|
||||||
parameters = [
|
|
||||||
{"name": name, "valueInteger": counts[name]}
|
|
||||||
for name in ("valid", "not_valid", "normal", "abnormal")
|
|
||||||
]
|
|
||||||
for entry in counts["by_alteration"]:
|
|
||||||
parameters.append({"name": "by_alteration", "part": [
|
|
||||||
{"name": "alteration", "valueCode": entry["alteration"]},
|
|
||||||
{"name": "patients", "valueInteger": entry["patients"]},
|
|
||||||
]}) # fmt: skip
|
|
||||||
return fhir(Parameters(parameter=parameters))
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/Patient/{id}", responses=_OK, response_class=Response)
|
|
||||||
def read_patient(domain: Domain, id: str) -> Response:
|
|
||||||
fu = _clinical(domain)
|
|
||||||
(row,) = reads.rows(domain.value, "person", id=id) or [None]
|
|
||||||
if row is None:
|
|
||||||
(link,) = reads.rows(domain.value, "replaced", id=id) or [None]
|
|
||||||
if link is None:
|
|
||||||
raise HTTPException(404, f"no Patient/{id}")
|
|
||||||
return fhir(f.replaced_patient(id, link["replaced_by"]))
|
|
||||||
status = fu.status(row, _cutoff(domain, None))
|
|
||||||
(found,) = _with_identity(domain, [{**row, "status": status}])
|
|
||||||
return fhir(f.patient(found, fu.STATUS_SYSTEM))
|
|
||||||
|
|
||||||
|
|
||||||
def _with_identity(domain: Domain, rows: list[dict]) -> list[dict]:
|
|
||||||
persons = [r["person_id"] for r in rows]
|
|
||||||
names, ids, replaces = {}, {}, {}
|
|
||||||
for r in reads.rows(domain.value, "names", persons=persons):
|
|
||||||
names.setdefault(r["person_id"], []).append(r["text"])
|
|
||||||
for r in reads.rows(domain.value, "identifiers", persons=persons):
|
|
||||||
ids.setdefault(r["person_id"], []).append((r["system"], r["value"]))
|
|
||||||
for r in reads.rows(domain.value, "replaces", persons=persons):
|
|
||||||
replaces.setdefault(r["replaced_by"], []).append(r["person_id"])
|
|
||||||
return [
|
|
||||||
{**r, "names": names.get(p, []), "identifiers": ids.get(p, []),
|
|
||||||
"replaces": replaces.get(p, [])}
|
|
||||||
for r in rows if (p := r["person_id"])
|
|
||||||
] # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def _folded(text: str) -> str:
|
|
||||||
return "".join(c for c in unicodedata.normalize("NFKD", text.casefold())
|
|
||||||
if not unicodedata.combining(c)) # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def _matches(row: dict, name: str | None, identifier: str | None) -> bool:
|
|
||||||
if name:
|
|
||||||
words = _folded(name).split()
|
|
||||||
if not any(all(any(w.startswith(q) for w in _folded(n).split()) for q in words)
|
|
||||||
for n in row["names"]): # fmt: skip
|
|
||||||
return False
|
|
||||||
if identifier:
|
|
||||||
system, _, value = identifier.rpartition("|")
|
|
||||||
if not any((not system or s == system) and v.casefold() == value.strip().casefold()
|
|
||||||
for s, v in row["identifiers"]): # fmt: skip
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/Patient",
|
|
||||||
responses=_OK,
|
|
||||||
response_class=Response,
|
|
||||||
description=(
|
|
||||||
"Patients, or the domain's follow-up list selected by window or start.\n\n"
|
|
||||||
"For TEA, a cutoff or a TEA filter also selects the follow-up list. Patients without\n"
|
|
||||||
"follow-up episodes appear only in the plain search."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def search_patient(
|
|
||||||
request: Request,
|
|
||||||
domain: Domain,
|
|
||||||
_id: str | None = Query(None, alias="_id"),
|
|
||||||
window: int | None = _WINDOW,
|
|
||||||
start: date | None = _START,
|
|
||||||
cutoff: date | None = _CUTOFF,
|
|
||||||
status: str | None = _STATUS,
|
|
||||||
name: str | None = Query(
|
|
||||||
None, description="each word starts a word of her name (case and accents ignored)"
|
|
||||||
),
|
|
||||||
identifier: str | None = Query(
|
|
||||||
None, description="[system|]value: a CURP or record number (case ignored)"
|
|
||||||
),
|
|
||||||
sort: str = Query("-recent", alias="_sort", description="-recent or -risk-<outcome>"),
|
|
||||||
horizon: float | None = Query(None, alias="risk-horizon", description="years"),
|
|
||||||
revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"),
|
|
||||||
include: list[str] = Query([], alias="_include:iterate", description="DiagnosticReport:result"),
|
|
||||||
_count: int | None = Query(None),
|
|
||||||
_offset: int = Query(0),
|
|
||||||
) -> Response:
|
|
||||||
fu = _clinical(domain)
|
|
||||||
count, offset = _page(_count, _offset)
|
|
||||||
at = _cutoff(domain, cutoff)
|
|
||||||
horizon = fu.DEFAULT_HORIZON if horizon is None else horizon
|
|
||||||
try:
|
|
||||||
rows, listed, applied = _patient_rows(
|
|
||||||
request, domain, fu, at, window, start, cutoff, status, sort, _id
|
|
||||||
)
|
|
||||||
except ValueError as exc:
|
|
||||||
return outcome(422, str(exc))
|
|
||||||
if name or identifier:
|
|
||||||
found = {r["person_id"] for r in _with_identity(domain, rows)
|
|
||||||
if _matches(r, name, identifier)} # fmt: skip
|
|
||||||
rows = [r for r in rows if r["person_id"] in found]
|
|
||||||
persons = [r["person_id"] for r in rows]
|
|
||||||
risks: dict[str, list[dict]] = {}
|
|
||||||
if domain != Domain.TEA and (listed and sort != "-recent" or
|
|
||||||
"RiskAssessment:subject" in revinclude): # fmt: skip
|
|
||||||
for r in reads.rows(domain.value, "risk", persons=persons):
|
|
||||||
risks.setdefault(r["person_id"], []).append(r)
|
|
||||||
if listed:
|
|
||||||
rows = fu.ordered(rows, sort, risks, horizon)
|
|
||||||
page = _sliced(rows, count, offset)
|
|
||||||
mine = {r["person_id"] for r in page}
|
|
||||||
included = _included(domain, revinclude, include, sorted(mine), at,
|
|
||||||
{p: v for p, v in risks.items() if p in mine}) # fmt: skip
|
|
||||||
patients = [f.patient(r, fu.STATUS_SYSTEM) for r in _with_identity(domain, page)]
|
|
||||||
return bundle(request, patients, len(rows), count, offset, included,
|
|
||||||
applied) # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def _patient_rows(
|
|
||||||
request: Request,
|
|
||||||
domain: Domain,
|
|
||||||
fu,
|
|
||||||
at: date,
|
|
||||||
window: int | None,
|
|
||||||
start: date | None,
|
|
||||||
cutoff: date | None,
|
|
||||||
status: str | None,
|
|
||||||
sort: str = "-recent",
|
|
||||||
_id: str | None = None,
|
|
||||||
*,
|
|
||||||
whole_history: bool = False,
|
|
||||||
) -> tuple[list[dict], bool, dict]:
|
|
||||||
filters = {
|
|
||||||
name: request.query_params.getlist(name)
|
|
||||||
for name in (TEA_FILTERS if domain == Domain.TEA else ())
|
|
||||||
if name in request.query_params
|
|
||||||
}
|
|
||||||
if filters:
|
|
||||||
fu.matches({}, filters)
|
|
||||||
listed = (
|
|
||||||
whole_history
|
|
||||||
or start is not None
|
|
||||||
or window is not None
|
|
||||||
or bool(filters)
|
|
||||||
or (hasattr(fu, "FILTERS") and cutoff is not None)
|
|
||||||
)
|
|
||||||
persons = reads.rows(domain.value, "persons")
|
|
||||||
applied = {}
|
|
||||||
if listed:
|
|
||||||
if sort not in fu.SORTS:
|
|
||||||
raise HTTPException(422, f"_sort is one of {fu.SORTS}")
|
|
||||||
if start is None and window is not None:
|
|
||||||
if window not in fu.WINDOWS:
|
|
||||||
raise HTTPException(422, f"follow-up-window is one of {fu.WINDOWS}")
|
|
||||||
start = window_start(at, window)
|
|
||||||
start = start or date.min
|
|
||||||
params = {"start": start.isoformat(), "cutoff": at.isoformat()}
|
|
||||||
person = {r["person_id"]: r for r in persons}
|
|
||||||
rows = [
|
|
||||||
{**person[r["person_id"]], **r}
|
|
||||||
for r in fu.listed(reads.rows(domain.value, "follow_up", **params), start, at)
|
|
||||||
]
|
|
||||||
applied = {"follow-up-cutoff": at.isoformat(), **filters}
|
|
||||||
else:
|
|
||||||
rows = [{**r, "status": fu.status(r, at)} for r in persons]
|
|
||||||
if _id and (not listed or domain == Domain.TEA):
|
|
||||||
ids = set(_id.split(","))
|
|
||||||
rows = [r for r in rows if r["person_id"] in ids]
|
|
||||||
if status:
|
|
||||||
rows = [r for r in rows if r["status"] in status.split(",")]
|
|
||||||
if filters:
|
|
||||||
rows = [r for r in rows if fu.matches(r, filters)]
|
|
||||||
return rows, listed, applied
|
|
||||||
|
|
||||||
|
|
||||||
def _included(domain: Domain, revinclude: list[str], include: list[str], persons: list[str],
|
|
||||||
at: date, risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip
|
|
||||||
allowed = _revincludes(domain)
|
|
||||||
unknown = set(revinclude) - set(allowed) | set(include) - {"DiagnosticReport:result"}
|
|
||||||
if unknown:
|
|
||||||
raise HTTPException(422, f"cannot include {sorted(unknown)}")
|
|
||||||
found: list[Resource] = []
|
|
||||||
reports = "DiagnosticReport:subject" in revinclude
|
|
||||||
observations = "Observation:subject" in revinclude or (
|
|
||||||
reports and "DiagnosticReport:result" in include
|
|
||||||
)
|
|
||||||
if reports or observations:
|
|
||||||
for r in _studies(domain, persons, at.isoformat()):
|
|
||||||
kind = r.get_resource_type()
|
|
||||||
if (kind == "DiagnosticReport" and reports) or (kind == "Observation" and observations):
|
|
||||||
found.append(r)
|
|
||||||
if "Condition:subject" in revinclude:
|
|
||||||
found += [f.condition(r) for r in reads.rows(domain.value, "condition", persons=persons,
|
|
||||||
cutoff=at.isoformat())] # fmt: skip
|
|
||||||
if "RiskAssessment:subject" in revinclude:
|
|
||||||
if domain == Domain.TEA:
|
|
||||||
found += _tea_risks(persons, at.isoformat())
|
|
||||||
else:
|
|
||||||
found += _risk_assessments([r for p in persons for r in risks.get(p, [])])
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
def _revincludes(domain: Domain) -> tuple[str, ...]:
|
|
||||||
return (*REVINCLUDES, "Condition:subject") if domain == Domain.TEA else REVINCLUDES
|
|
||||||
|
|
||||||
|
|
||||||
def _subjects(subject: str | None) -> list[str]:
|
|
||||||
if not subject:
|
|
||||||
raise HTTPException(422, "subject is required (Patient/<id>, comma-separated)")
|
|
||||||
return [s.removeprefix("Patient/") for s in subject.split(",")]
|
|
||||||
|
|
||||||
|
|
||||||
def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]:
|
|
||||||
found: list[Resource] = []
|
|
||||||
report_facts = _clinical(domain).REPORT_FACTS
|
|
||||||
if domain == Domain.TEA:
|
|
||||||
births = {
|
|
||||||
r["person_id"]: date.fromisoformat(f._day(r["birth_date"])) if r["birth_date"] else None
|
|
||||||
for r in reads.rows(domain.value, "births", persons=persons)
|
|
||||||
}
|
|
||||||
for study in catalog.of_domain(domain.value):
|
|
||||||
spec = catalog.studies()[study]
|
|
||||||
facts = {}
|
|
||||||
if kind := report_facts.get(study):
|
|
||||||
found_facts = reads.rows(domain.value, kind, persons=persons, cutoff=at)
|
|
||||||
facts = {(r["person_id"], str(r["sample_date"])[:10]): r["days"]
|
|
||||||
for r in found_facts} # fmt: skip
|
|
||||||
first = next(e.date for e in spec.events.values() if e.parent is None)
|
|
||||||
for row in reads.instances(study, persons, at):
|
|
||||||
days = facts.get((row["person_id"], str(row[first])[:10]))
|
|
||||||
extra = [] if days is None else [f.ext("days-to-diagnosis", "integer", int(days))]
|
|
||||||
known = f.known(study, row, at)
|
|
||||||
found += f.instance(study, known, extra)
|
|
||||||
if domain == Domain.TEA and study == "ados2":
|
|
||||||
known["evaluation_date"] = date.fromisoformat(f._day(known["evaluation_date"]))
|
|
||||||
found.append(tea_fhir.ados2_observation(known, births.get(row["person_id"])))
|
|
||||||
if domain == Domain.TEA:
|
|
||||||
found += _tea_eeg_studies(persons, at)
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
def _tea_eeg_studies(persons: list[str], at: str) -> list[Resource]:
|
|
||||||
def rows(kind):
|
|
||||||
return reads.rows("tea", kind, persons=persons, cutoff=at)
|
|
||||||
|
|
||||||
def key(row):
|
|
||||||
return row["person_id"], row["study_date"], row["edf"]
|
|
||||||
|
|
||||||
regions, results = defaultdict(list), defaultdict(list)
|
|
||||||
for row in rows("regions"):
|
|
||||||
regions[(*key(row), row["code"])].append(row)
|
|
||||||
for row in rows("checks"):
|
|
||||||
results[key(row)].append(tea_fhir.eeg_check(row))
|
|
||||||
for row in rows("metrics"):
|
|
||||||
results[key(row)].append(tea_fhir.eeg_metric(row, regions[(*key(row), row["code"])]))
|
|
||||||
found = []
|
|
||||||
for row in rows("eegs"):
|
|
||||||
observations = results[key(row)]
|
|
||||||
found.extend((tea_fhir.eeg_report(row, observations), *observations))
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
def _tea_risks(persons: list[str], at: str) -> list[Resource]:
|
|
||||||
groups = defaultdict(list)
|
|
||||||
for row in reads.rows("tea", "association_scores", persons=persons, cutoff=at):
|
|
||||||
group = groups[row["person_id"]]
|
|
||||||
if (
|
|
||||||
not group
|
|
||||||
or row["edf"] == group[0]["edf"]
|
|
||||||
and row["study_date"] == group[0]["study_date"]
|
|
||||||
):
|
|
||||||
group.append(row)
|
|
||||||
return [tea_fhir.association_risk(group) for group in groups.values()]
|
|
||||||
|
|
||||||
|
|
||||||
def _risk_assessments(rows: list[dict]) -> list[Resource]:
|
|
||||||
groups: dict[tuple, list[dict]] = {}
|
|
||||||
for r in rows:
|
|
||||||
groups.setdefault((r["model"], r["version"], r["person_id"], str(r["index_date"])),
|
|
||||||
[]).append(r) # fmt: skip
|
|
||||||
return [f.risk_assessment(g[0], g) for g in groups.values()]
|
|
||||||
|
|
||||||
|
|
||||||
def _clinical_search(kind: str, build, request, domain, subject, count, offset):
|
|
||||||
fu = _clinical(domain)
|
|
||||||
count, offset = _page(count, offset)
|
|
||||||
params: dict = {"persons": _subjects(subject)}
|
|
||||||
if kind != "risk":
|
|
||||||
params["cutoff"] = _cutoff(domain, None).isoformat()
|
|
||||||
if kind == "procedure":
|
|
||||||
params["types"] = list(fu.PROCEDURES)
|
|
||||||
if kind == "risk" and domain == Domain.TEA:
|
|
||||||
found = _tea_risks(params["persons"], _cutoff(domain, None).isoformat())
|
|
||||||
else:
|
|
||||||
found = build(reads.rows(domain.value, kind, **params))
|
|
||||||
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
|
||||||
|
|
||||||
|
|
||||||
SUBJECT = "Patient/<id>, comma-separated"
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/DiagnosticReport",
|
|
||||||
responses=_OK,
|
|
||||||
response_class=Response,
|
|
||||||
description=(
|
|
||||||
"The domain's reports (each study of the catalog with a report), "
|
|
||||||
"as known by the last\n"
|
|
||||||
"day with data."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def search_diagnostic_report(request: Request, domain: Domain,
|
|
||||||
subject: str | None = Query(None, description=SUBJECT),
|
|
||||||
_count: int | None = Query(None),
|
|
||||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
|
||||||
return _study_search("DiagnosticReport", request, domain, subject, _count, _offset)
|
|
||||||
|
|
||||||
|
|
||||||
def _study_search(kind: str, request, domain, subject, count, offset) -> Response:
|
|
||||||
_clinical(domain)
|
|
||||||
count, offset = _page(count, offset)
|
|
||||||
persons, at = _subjects(subject), _cutoff(domain, None).isoformat()
|
|
||||||
found = [r for r in _studies(domain, persons, at) if r.get_resource_type() == kind]
|
|
||||||
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/Encounter",
|
|
||||||
responses=_OK,
|
|
||||||
response_class=Response,
|
|
||||||
description="Consultations: each study of the catalog without a report, as an encounter.",
|
|
||||||
)
|
|
||||||
def search_encounter(request: Request, domain: Domain,
|
|
||||||
subject: str | None = Query(None, description=SUBJECT),
|
|
||||||
_count: int | None = Query(None),
|
|
||||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
|
||||||
return _study_search("Encounter", request, domain, subject, _count, _offset)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/Observation",
|
|
||||||
responses=_OK,
|
|
||||||
response_class=Response,
|
|
||||||
description="Every result of the domain's reports, one per field of the catalog.",
|
|
||||||
)
|
|
||||||
def search_observation(request: Request, domain: Domain,
|
|
||||||
subject: str | None = Query(None, description=SUBJECT),
|
|
||||||
_count: int | None = Query(None),
|
|
||||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
|
||||||
return _study_search("Observation", request, domain, subject, _count, _offset)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/Condition",
|
|
||||||
responses=_OK,
|
|
||||||
response_class=Response,
|
|
||||||
description="What clinical notes diagnosed (CaMa: and each recurrence).",
|
|
||||||
)
|
|
||||||
def search_condition(request: Request, domain: Domain,
|
|
||||||
subject: str | None = Query(None, description=SUBJECT),
|
|
||||||
_count: int | None = Query(None),
|
|
||||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
|
||||||
|
|
||||||
def build(rows):
|
|
||||||
return [f.condition(r) for r in rows]
|
|
||||||
|
|
||||||
return _clinical_search("condition", build, request, domain, subject, _count, _offset)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/Procedure",
|
|
||||||
responses=_OK,
|
|
||||||
response_class=Response,
|
|
||||||
description=(
|
|
||||||
"The procedures the domain's timeline infers (CaCu: colposcopies "
|
|
||||||
"and treatments;\n"
|
|
||||||
"CaMa: each treatment, by its kind)."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def search_procedure(request: Request, domain: Domain,
|
|
||||||
subject: str | None = Query(None, description=SUBJECT),
|
|
||||||
_count: int | None = Query(None),
|
|
||||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
|
||||||
|
|
||||||
def build(rows):
|
|
||||||
return [f.procedure(r, domain.value) for r in rows]
|
|
||||||
|
|
||||||
return _clinical_search("procedure", build, request, domain, subject, _count, _offset)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/RiskAssessment",
|
|
||||||
responses=_OK,
|
|
||||||
response_class=Response,
|
|
||||||
description="The champion models' risks, one per model and index date.",
|
|
||||||
)
|
|
||||||
def search_risk_assessment(request: Request, domain: Domain,
|
|
||||||
subject: str | None = Query(None, description=SUBJECT),
|
|
||||||
_count: int | None = Query(None),
|
|
||||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
|
||||||
return _clinical_search("risk", _risk_assessments, request, domain, subject, _count, _offset)
|
|
||||||
|
|
||||||
|
|
||||||
def _measure(domain: Domain, key: str) -> m.Measure:
|
|
||||||
found = measures(domain)
|
|
||||||
for code, measure in found.items():
|
|
||||||
if key in (code, f.measure_id(code), f.measure_url(code)):
|
|
||||||
return measure
|
|
||||||
raise HTTPException(404, f"no {domain.value} Measure {key}")
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/Measure/{id}", responses=_OK, response_class=Response)
|
|
||||||
def read_measure(domain: Domain, id: str) -> Response:
|
|
||||||
return fhir(f.measure(_measure(domain, id), domain.value))
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/Measure",
|
|
||||||
responses=_OK,
|
|
||||||
response_class=Response,
|
|
||||||
description="Every measure of the domain (none for a domain without them yet).",
|
|
||||||
)
|
|
||||||
def search_measure(request: Request, domain: Domain, _count: int | None = Query(None),
|
|
||||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
|
||||||
count, offset = _page(_count, _offset)
|
|
||||||
found = [f.measure(x, domain.value) for x in measures(domain).values()]
|
|
||||||
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/MeasureReport",
|
|
||||||
responses=_OK,
|
|
||||||
response_class=Response,
|
|
||||||
description="The measure's summary report for each period asked for, evaluated over gold.",
|
|
||||||
)
|
|
||||||
def search_measure_report(
|
|
||||||
request: Request,
|
|
||||||
domain: Domain,
|
|
||||||
measure: str = Query(alias="measure", description="the Measure's id or canonical URL"),
|
|
||||||
periods: str = Query(
|
|
||||||
alias="reporting-period",
|
|
||||||
description="semesters (2025-S1) or months (2025-03), comma-separated",
|
|
||||||
),
|
|
||||||
as_of: datetime | None = Query(
|
|
||||||
None, alias="as-of", description="count only what was known by then"
|
|
||||||
),
|
|
||||||
event_cutoff: date | None = Query(
|
|
||||||
None, alias="event-cutoff", description="durations count to this day"
|
|
||||||
),
|
|
||||||
_count: int | None = Query(None),
|
|
||||||
_offset: int = Query(0),
|
|
||||||
) -> Response:
|
|
||||||
found = _measure(domain, measure.split("|")[0])
|
|
||||||
count, offset = _page(_count, _offset)
|
|
||||||
try:
|
|
||||||
asked = [(p.strip(), m.Period.parse(p.strip())) for p in periods.split(",") if p.strip()]
|
|
||||||
except ValueError as e:
|
|
||||||
raise HTTPException(422, f"reporting-period: {e}") from e
|
|
||||||
rows = measure_reads.rows(domain.value, found.rows, **found.params)
|
|
||||||
reports = []
|
|
||||||
page = _sliced(asked, count, offset)
|
|
||||||
results = m.evaluate_periods(found, rows, [p for _, p in page], as_of, event_cutoff)
|
|
||||||
for (text, period), result in zip(page, results, strict=True):
|
|
||||||
report = m.report(found, period, result, as_of)
|
|
||||||
report.id = f"{f.measure_id(found.id)}-{text.lower()}"
|
|
||||||
reports.append(report)
|
|
||||||
return bundle(request, reports, len(asked), count, offset)
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"",
|
|
||||||
responses=_OK,
|
|
||||||
response_class=Response,
|
|
||||||
status_code=202,
|
|
||||||
description=(
|
|
||||||
"A standard hospital's Bundle: checked as FHIR, kept as sent in "
|
|
||||||
"the sender's inbox,\n"
|
|
||||||
"and placed by the sender's pipeline (a run starts; follow it at "
|
|
||||||
"the Location)."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def post_bundle(
|
|
||||||
domain: Domain,
|
|
||||||
bundle: Annotated[dict[str, Any], Body(description="a FHIR R4 batch or transaction Bundle")],
|
|
||||||
sender: str = Query(
|
|
||||||
pattern=ID_PATTERN,
|
|
||||||
max_length=40,
|
|
||||||
description="the sender's pipeline (its fhir nodes read this inbox)",
|
|
||||||
),
|
|
||||||
client: DagsterGraphQLClient = Depends(dagster),
|
|
||||||
) -> Response:
|
|
||||||
try:
|
|
||||||
parsed = Bundle.model_validate(bundle)
|
|
||||||
except ValueError as e:
|
|
||||||
raise HTTPException(422, f"not a valid R4 Bundle: {e}") from e
|
|
||||||
if parsed.type not in ("batch", "transaction", "collection"):
|
|
||||||
raise HTTPException(422, "send a batch, transaction or collection Bundle")
|
|
||||||
if not config_log.latest_version(sender):
|
|
||||||
raise HTTPException(404, f"no pipeline {sender} to place what it sends")
|
|
||||||
readers.receive(sender, bundle)
|
|
||||||
run_id = submit(client, sender)
|
|
||||||
entries = [{"response": {"status": "202 Accepted", "location":
|
|
||||||
f"{e.resource.get_resource_type()}/{e.resource.id}"}}
|
|
||||||
for e in parsed.entry or [] if e.resource is not None] # fmt: skip
|
|
||||||
answer = Bundle(type="batch-response", entry=entries or None)
|
|
||||||
found = fhir(answer)
|
|
||||||
found.status_code = 202
|
|
||||||
found.headers["Location"] = f"/runs/{run_id}"
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/metadata",
|
|
||||||
responses=_OK,
|
|
||||||
response_class=Response,
|
|
||||||
description=(
|
|
||||||
"What this base serves: built from the routes above, so it cannot drift from them."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def metadata(request: Request, domain: Domain) -> Response:
|
|
||||||
resources: dict[str, dict] = {}
|
|
||||||
system: list[dict] = []
|
|
||||||
fu = part(domain, "follow_up")
|
|
||||||
clinical = fu is not None
|
|
||||||
for route in router.routes:
|
|
||||||
path = route.path.removeprefix(router.prefix)
|
|
||||||
if not path:
|
|
||||||
if clinical:
|
|
||||||
system = [{"code": "batch"}, {"code": "transaction"}]
|
|
||||||
continue
|
|
||||||
_, kind, *rest = path.split("/")
|
|
||||||
if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport"
|
|
||||||
and not clinical): # fmt: skip
|
|
||||||
continue
|
|
||||||
if rest and rest[0].startswith("$"):
|
|
||||||
continue
|
|
||||||
entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []})
|
|
||||||
if kind == "Patient" and not rest:
|
|
||||||
entry |= {"searchInclude": ["DiagnosticReport:result"],
|
|
||||||
"searchRevInclude": list(_revincludes(domain))} # fmt: skip
|
|
||||||
if domain == Domain.TEA:
|
|
||||||
entry["searchParam"] += [
|
|
||||||
{"name": name, "type": spec[0]} for name, spec in TEA_FILTERS.items()
|
|
||||||
]
|
|
||||||
entry["interaction"].append({"code": "read" if rest else "search-type"})
|
|
||||||
for param in route.dependant.query_params:
|
|
||||||
name = param.alias
|
|
||||||
if name.startswith("_") and name != "_id":
|
|
||||||
continue
|
|
||||||
declared = f.SEARCH_PARAMETERS.get(name)
|
|
||||||
entry["searchParam"].append({
|
|
||||||
"name": name,
|
|
||||||
"type": declared[1] if declared else _STANDARD[name],
|
|
||||||
**({"definition": f"{f.BASE}/SearchParameter/{name}"} if declared else {}),
|
|
||||||
}) # fmt: skip
|
|
||||||
statement = CapabilityStatement.model_validate({
|
|
||||||
"resourceType": "CapabilityStatement",
|
|
||||||
"status": "active",
|
|
||||||
"date": date.today().isoformat(),
|
|
||||||
"kind": "instance",
|
|
||||||
"fhirVersion": f.FHIR_VERSION,
|
|
||||||
"format": ["json"],
|
|
||||||
"implementation": {"description": f"ISSSTELEON {domain.value}",
|
|
||||||
"url": str(request.base_url).rstrip("/") + f"/{domain.value}/fhir"},
|
|
||||||
"rest": [{"mode": "server",
|
|
||||||
"resource": [{k: v for k, v in r.items() if v} for r in resources.values()],
|
|
||||||
**({"interaction": system} if system else {})}],
|
|
||||||
}) # fmt: skip
|
|
||||||
return fhir(statement)
|
|
||||||
|
|
||||||
|
|
||||||
_STANDARD = {
|
|
||||||
"_id": "token",
|
|
||||||
"subject": "reference",
|
|
||||||
"measure": "reference",
|
|
||||||
"follow-up-start": "date",
|
|
||||||
"name": "string",
|
|
||||||
"identifier": "token",
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
"""Las rutas de indicadores, iguales para cada proyecto (CaCu, CaMa, TEA).
|
||||||
|
|
||||||
|
`registrar_indicadores` agrega a un blueprint:
|
||||||
|
|
||||||
|
GET /indicadores catálogo de indicadores
|
||||||
|
GET /indicadores/<id>/periodos periodos con reporte
|
||||||
|
GET /indicadores/<id>/datos?periodos=&estrato= los números, sin figura
|
||||||
|
GET /indicadores/<id>/metadatos ficha metodológica
|
||||||
|
GET /indicadores/<id>/figuras/<figura>?periodos=&tema=
|
||||||
|
|
||||||
|
Las definiciones salen del kit (`measures_de`), los datos de
|
||||||
|
`indicadores_kit.serving.datos` y las figuras de
|
||||||
|
`indicadores_kit.serving.figuras`; aquí solo se valida, se abre la sesión y
|
||||||
|
se traducen los errores a códigos HTTP. La forma de cada respuesta es un
|
||||||
|
contrato con el frontend: no se quita ni se renombra un campo.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from collections.abc import Callable
|
||||||
|
|
||||||
|
from flask import Blueprint, Response, jsonify, request
|
||||||
|
from indicadores_kit.registry.measures import Measure, measures_de
|
||||||
|
from indicadores_kit.serving.datos import datos_de, metadatos_de, periodos_de, resumen_de
|
||||||
|
from indicadores_kit.serving.figuras import (
|
||||||
|
TEMAS,
|
||||||
|
figura_json,
|
||||||
|
figuras_de,
|
||||||
|
periodos_con_reporte,
|
||||||
|
periodos_por_defecto,
|
||||||
|
)
|
||||||
|
from indicadores_kit.tablas import tablas_de
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
# Cómo se escribe un periodo de cada tipo (`registry/periodos.py`) y un ejemplo para el mensaje.
|
||||||
|
FORMATOS = {
|
||||||
|
"dia": (re.compile(r"\d{4}-\d{2}-\d{2}"), "AAAA-MM-DD"),
|
||||||
|
"semana_epidemiologica": (re.compile(r"\d{4}-SE\d{2}"), "AAAA-SEnn"),
|
||||||
|
"semana_habil": (re.compile(r"\d{4}-SH\d{2}"), "AAAA-SHnn"),
|
||||||
|
"semana_iso": (re.compile(r"\d{4}-W\d{2}"), "AAAA-Wnn"),
|
||||||
|
"mes": (re.compile(r"\d{4}-\d{2}"), "AAAA-MM"),
|
||||||
|
"bimestre": (re.compile(r"\d{4}-B[1-6]"), "AAAA-B1 a AAAA-B6"),
|
||||||
|
"trimestre": (re.compile(r"\d{4}-T[1-4]"), "AAAA-T1 a AAAA-T4"),
|
||||||
|
"semestre": (re.compile(r"\d{4}-S[12]"), "AAAA-S1 o AAAA-S2"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _error(mensaje: str, codigo: int):
|
||||||
|
return jsonify({"error": mensaje}), codigo
|
||||||
|
|
||||||
|
|
||||||
|
def _json(contenido) -> Response:
|
||||||
|
"""Sin `jsonify`, que ordena las llaves: grupos y categorías van en su orden de presentación."""
|
||||||
|
return Response(json.dumps(contenido, ensure_ascii=False), mimetype="application/json")
|
||||||
|
|
||||||
|
|
||||||
|
def _tipo_de(periodo: str, tipos: list[str]) -> str | None:
|
||||||
|
"""El tipo, entre los que publica el indicador, al que pertenece el periodo (o `None`)."""
|
||||||
|
return next((tipo for tipo in tipos if FORMATOS[tipo][0].fullmatch(periodo)), None)
|
||||||
|
|
||||||
|
|
||||||
|
def periodos_pedidos(texto: str | None, medida: Measure) -> tuple[list[str], str | None]:
|
||||||
|
"""Los periodos de `?periodos=` y su tipo. Sin parámetro (o vacío): `([], None)`.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: un periodo mal formado, de un tipo que el indicador no
|
||||||
|
publica (`extension.publicacion.tipos_periodo`), o de tipos mezclados.
|
||||||
|
"""
|
||||||
|
if not texto:
|
||||||
|
return [], None
|
||||||
|
tipos = medida.extension.publicacion.tipos_periodo
|
||||||
|
periodos = list(dict.fromkeys(texto.split(",")))
|
||||||
|
encontrados = {_tipo_de(periodo, tipos) for periodo in periodos}
|
||||||
|
if None in encontrados:
|
||||||
|
formatos = "; ".join(FORMATOS[tipo][1] for tipo in tipos)
|
||||||
|
raise ValueError(f"Periodos mal formados: {texto!r}; este indicador publica {formatos}.")
|
||||||
|
if len(encontrados) > 1:
|
||||||
|
raise ValueError(f"Periodos de tipos distintos: {texto!r}; pida un solo tipo a la vez.")
|
||||||
|
return periodos, encontrados.pop()
|
||||||
|
|
||||||
|
|
||||||
|
def registrar_indicadores(
|
||||||
|
blueprint: Blueprint, proyecto: str, get_session: Callable[[], Session]
|
||||||
|
) -> None:
|
||||||
|
"""Agrega las rutas de indicadores de `proyecto` al blueprint.
|
||||||
|
|
||||||
|
`get_session` es la fábrica de `Persistance` (`get_<proyecto>_session`):
|
||||||
|
se llama en cada petición, no al registrar.
|
||||||
|
"""
|
||||||
|
definiciones = measures_de(proyecto) # fijas: se leen una vez
|
||||||
|
tablas = tablas_de(proyecto)
|
||||||
|
|
||||||
|
def listar_indicadores():
|
||||||
|
# Los marcados `oculto` en su TOML no salen en el catálogo; su id sigue respondiendo.
|
||||||
|
return _json([
|
||||||
|
resumen_de(id_, medida)
|
||||||
|
for id_, medida in definiciones.items()
|
||||||
|
if not medida.extension.publicacion.oculto
|
||||||
|
])
|
||||||
|
|
||||||
|
def _periodos_o_los_que_haya(sesion: Session, medida: Measure, periodos: list[str]) -> list[str]:
|
||||||
|
"""Los pedidos; sin pedir ninguno, los que tienen reporte del primer tipo que publica."""
|
||||||
|
if periodos:
|
||||||
|
return periodos
|
||||||
|
tipo = medida.extension.publicacion.tipos_periodo[0]
|
||||||
|
return periodos_con_reporte(sesion, medida, tablas=tablas, tipo=tipo)
|
||||||
|
|
||||||
|
def get_periodos(indicador: str):
|
||||||
|
medida = definiciones.get(indicador)
|
||||||
|
if medida is None:
|
||||||
|
return _error("indicador desconocido", 404)
|
||||||
|
sesion = get_session()
|
||||||
|
try:
|
||||||
|
periodos = periodos_de(sesion, medida, tablas=tablas)
|
||||||
|
finally:
|
||||||
|
sesion.close()
|
||||||
|
return _json({"id": indicador, "version": medida.version, "periodos": periodos})
|
||||||
|
|
||||||
|
def get_metadatos(indicador: str):
|
||||||
|
medida = definiciones.get(indicador)
|
||||||
|
if medida is None:
|
||||||
|
return _error("indicador desconocido", 404)
|
||||||
|
sesion = get_session()
|
||||||
|
try:
|
||||||
|
metadatos = metadatos_de(sesion, medida, tablas=tablas)
|
||||||
|
finally:
|
||||||
|
sesion.close()
|
||||||
|
return _json({"id": indicador, **metadatos})
|
||||||
|
|
||||||
|
def get_datos(indicador: str):
|
||||||
|
medida = definiciones.get(indicador)
|
||||||
|
if medida is None:
|
||||||
|
return _error("indicador desconocido", 404)
|
||||||
|
estrato = request.args.get("estrato") or None
|
||||||
|
if estrato is not None and estrato not in medida.extension.estratos:
|
||||||
|
return _error(
|
||||||
|
f"estrato desconocido {estrato!r}; este indicador tiene {medida.extension.estratos}",
|
||||||
|
400,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
periodos, _ = periodos_pedidos(request.args.get("periodos"), medida)
|
||||||
|
except ValueError as error:
|
||||||
|
return _error(str(error), 400)
|
||||||
|
|
||||||
|
sesion = get_session()
|
||||||
|
try:
|
||||||
|
periodos = _periodos_o_los_que_haya(sesion, medida, periodos)
|
||||||
|
if not periodos:
|
||||||
|
return _error("el indicador no tiene reportes calculados", 404)
|
||||||
|
datos = datos_de(sesion, medida, periodos, tablas=tablas, estrato=estrato)
|
||||||
|
except KeyError:
|
||||||
|
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||||
|
raise
|
||||||
|
except LookupError as error:
|
||||||
|
return _error(str(error), 404)
|
||||||
|
finally:
|
||||||
|
sesion.close()
|
||||||
|
return _json({"id": indicador, **datos})
|
||||||
|
|
||||||
|
def get_figura(indicador: str, figura: str):
|
||||||
|
medida = definiciones.get(indicador)
|
||||||
|
if medida is None:
|
||||||
|
return _error("indicador desconocido", 404)
|
||||||
|
if figura not in figuras_de(medida):
|
||||||
|
return _error(
|
||||||
|
f"figura {figura!r} no es del contrato {medida.extension.contrato}", 404
|
||||||
|
)
|
||||||
|
|
||||||
|
tema = request.args.get("tema", "claro")
|
||||||
|
if tema not in TEMAS:
|
||||||
|
return _error(f"tema desconocido {tema!r}; use claro u oscuro", 400)
|
||||||
|
try:
|
||||||
|
periodos, tipo = periodos_pedidos(request.args.get("periodos"), medida)
|
||||||
|
except ValueError as error:
|
||||||
|
return _error(str(error), 400)
|
||||||
|
|
||||||
|
sesion = get_session()
|
||||||
|
try:
|
||||||
|
# Sin pedir ninguno: todos, o solo el más reciente si la figura se lee en un periodo.
|
||||||
|
periodos = periodos or periodos_por_defecto(sesion, medida, figura, tablas=tablas)
|
||||||
|
if not periodos:
|
||||||
|
return _error("el indicador no tiene reportes calculados", 404)
|
||||||
|
texto = figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema)
|
||||||
|
except KeyError:
|
||||||
|
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||||
|
raise
|
||||||
|
except LookupError as error:
|
||||||
|
return _error(str(error), 404)
|
||||||
|
finally:
|
||||||
|
sesion.close()
|
||||||
|
return Response(texto, mimetype="application/json")
|
||||||
|
|
||||||
|
blueprint.add_url_rule("/indicadores", "listar_indicadores", listar_indicadores)
|
||||||
|
blueprint.add_url_rule("/indicadores/<indicador>/periodos", "get_periodos", get_periodos)
|
||||||
|
blueprint.add_url_rule("/indicadores/<indicador>/datos", "get_datos", get_datos)
|
||||||
|
blueprint.add_url_rule("/indicadores/<indicador>/metadatos", "get_metadatos", get_metadatos)
|
||||||
|
blueprint.add_url_rule(
|
||||||
|
"/indicadores/<indicador>/figuras/<figura>", "get_figura", get_figura
|
||||||
|
)
|
||||||
@@ -1,158 +0,0 @@
|
|||||||
from typing import Annotated, Any
|
|
||||||
|
|
||||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Path, Query
|
|
||||||
from fhir.resources.R4B.conceptmap import ConceptMap
|
|
||||||
from pydantic import BaseModel
|
|
||||||
|
|
||||||
from core import concept_map
|
|
||||||
from core.pipeline import ID_PATTERN, Pipeline, Source, redacted, restored
|
|
||||||
from core.schema import ENTITIES
|
|
||||||
from persistance import config_log, nodes
|
|
||||||
from webapi.runs import dagster
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/ingest", tags=["ingest"])
|
|
||||||
PipelineId = Annotated[str, Path(pattern=ID_PATTERN, max_length=40)]
|
|
||||||
NodeId = Annotated[str, Path(pattern=ID_PATTERN, max_length=40)]
|
|
||||||
Rows = list[dict[str, Any]]
|
|
||||||
|
|
||||||
|
|
||||||
def _from_source(call, *args):
|
|
||||||
try:
|
|
||||||
return call(*args)
|
|
||||||
except Exception as e: # noqa: BLE001
|
|
||||||
raise HTTPException(422, detail=f"{type(e).__name__}: {e}") from e
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/schema",
|
|
||||||
description="What the canvas draws with: every node kind's form, and the platform entities.",
|
|
||||||
)
|
|
||||||
def schema() -> dict[str, Any]:
|
|
||||||
return {
|
|
||||||
"pipeline": Pipeline.model_json_schema(),
|
|
||||||
"entities": {name: model.model_json_schema() for name, model in ENTITIES.items()},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/sources/preview",
|
|
||||||
description="The first rows a source node would load.",
|
|
||||||
)
|
|
||||||
def source_preview(node: Source, limit: Annotated[int, Query(ge=1, le=200)] = 20) -> Rows:
|
|
||||||
return [nodes.shown(r) for r in _from_source(nodes.preview, node, limit)]
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/pipelines")
|
|
||||||
def pipelines() -> Rows:
|
|
||||||
return config_log.pipelines()
|
|
||||||
|
|
||||||
|
|
||||||
class SavedPipeline(BaseModel):
|
|
||||||
version: int
|
|
||||||
pipeline: Pipeline
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/pipelines/{pipeline_id}",
|
|
||||||
description="A saved pipeline (latest by default), with its secrets masked.",
|
|
||||||
)
|
|
||||||
def pipeline(pipeline_id: PipelineId, version: int | None = None) -> SavedPipeline:
|
|
||||||
if not config_log.latest_version(pipeline_id):
|
|
||||||
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
|
||||||
found, saved = config_log.get(pipeline_id, version)
|
|
||||||
return SavedPipeline(version=found, pipeline=redacted(saved))
|
|
||||||
|
|
||||||
|
|
||||||
@router.put(
|
|
||||||
"/pipelines/{pipeline_id}",
|
|
||||||
description=(
|
|
||||||
"Saves a new version. Masked secrets sent back are kept as they "
|
|
||||||
"were saved; every\n"
|
|
||||||
"ConceptMap a node names must exist."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def save_pipeline(pipeline_id: PipelineId, drawn: Pipeline) -> dict[str, int]:
|
|
||||||
named = {n.concept_map for n in drawn.nodes if getattr(n, "concept_map", None)}
|
|
||||||
if missing := sorted(m for m in named if not config_log.latest_version(m, "concept_maps")):
|
|
||||||
raise HTTPException(422, detail=f"no concept maps {missing}")
|
|
||||||
previous = config_log.get(pipeline_id)[1] if config_log.latest_version(pipeline_id) else None
|
|
||||||
try:
|
|
||||||
complete = restored(drawn, previous)
|
|
||||||
except ValueError as e:
|
|
||||||
raise HTTPException(422, detail=str(e)) from e
|
|
||||||
return {"version": config_log.save(pipeline_id, complete)}
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/concept-maps/{map_id}",
|
|
||||||
description="A site's codes in platform terms (FHIR R4B ConceptMap), latest version.",
|
|
||||||
)
|
|
||||||
def get_concept_map(map_id: PipelineId) -> dict[str, Any]:
|
|
||||||
if not config_log.latest_version(map_id, "concept_maps"):
|
|
||||||
raise HTTPException(404, detail=f"no concept map {map_id}")
|
|
||||||
return config_log.concept_map(map_id).model_dump(mode="json", exclude_none=True)
|
|
||||||
|
|
||||||
|
|
||||||
@router.put(
|
|
||||||
"/concept-maps/{map_id}",
|
|
||||||
description=(
|
|
||||||
"Saves a new version of a ConceptMap. Its groups target the "
|
|
||||||
"systems platform fields\n"
|
|
||||||
"take codes from, and only codes those fields allow "
|
|
||||||
"(core.concept_map)."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def save_concept_map(map_id: PipelineId, doc: dict[str, Any]) -> dict[str, int]:
|
|
||||||
try:
|
|
||||||
found = ConceptMap.model_validate({**doc, "resourceType": "ConceptMap"})
|
|
||||||
except ValueError as e:
|
|
||||||
raise HTTPException(422, detail=str(e)) from e
|
|
||||||
if problems := concept_map.problems(found):
|
|
||||||
raise HTTPException(422, detail=problems)
|
|
||||||
return {"version": config_log.save(map_id, found, "concept_maps")}
|
|
||||||
|
|
||||||
|
|
||||||
class RunRequest(BaseModel):
|
|
||||||
version: int | None = None
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/pipelines/{pipeline_id}/runs",
|
|
||||||
description="Starts the `ingest` job for this pipeline; follow it at /runs/{run_id}.",
|
|
||||||
)
|
|
||||||
def start_run(
|
|
||||||
pipeline_id: PipelineId,
|
|
||||||
request: RunRequest,
|
|
||||||
client: DagsterGraphQLClient = Depends(dagster),
|
|
||||||
) -> dict[str, str]:
|
|
||||||
if not config_log.latest_version(pipeline_id):
|
|
||||||
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
|
||||||
return {"run_id": submit(client, pipeline_id, request.version)}
|
|
||||||
|
|
||||||
|
|
||||||
def submit(client: DagsterGraphQLClient, pipeline_id: str, version: int | None = None) -> str:
|
|
||||||
config = {"pipeline": pipeline_id, "version": version}
|
|
||||||
try:
|
|
||||||
return client.submit_job_execution(
|
|
||||||
"ingest", run_config={"ops": {"run_pipeline": {"config": config}}}
|
|
||||||
)
|
|
||||||
except DagsterGraphQLClientError as e:
|
|
||||||
raise HTTPException(502, detail=str(e)) from e
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/pipelines/{pipeline_id}/nodes/{node_id}/rows",
|
|
||||||
description="What a node produced in the last run (empty if it produced nothing yet).",
|
|
||||||
)
|
|
||||||
def node_rows(
|
|
||||||
pipeline_id: PipelineId,
|
|
||||||
node_id: NodeId,
|
|
||||||
limit: Annotated[int, Query(ge=1, le=500)] = 50,
|
|
||||||
) -> Rows:
|
|
||||||
out = []
|
|
||||||
for row in nodes.rows(pipeline_id, node_id):
|
|
||||||
out.append(nodes.shown(row))
|
|
||||||
if len(out) == limit:
|
|
||||||
break
|
|
||||||
return out
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
from fastapi import Depends, FastAPI, Request
|
|
||||||
from fastapi.exception_handlers import http_exception_handler
|
|
||||||
from starlette.exceptions import HTTPException
|
|
||||||
|
|
||||||
from core.domains import Domain
|
|
||||||
from webapi import eeg, execution, fhir, ingest, models, preview, review, runs, sources, users
|
|
||||||
from webapi.auth import caller
|
|
||||||
|
|
||||||
app = FastAPI(
|
|
||||||
title="ISSSTELEON",
|
|
||||||
version="0.0.0",
|
|
||||||
dependencies=[Depends(caller)],
|
|
||||||
generate_unique_id_function=lambda route: route.name,
|
|
||||||
lifespan=users.lifespan,
|
|
||||||
)
|
|
||||||
app.include_router(ingest.router)
|
|
||||||
app.include_router(sources.router)
|
|
||||||
app.include_router(review.router)
|
|
||||||
app.include_router(runs.router)
|
|
||||||
app.include_router(execution.router)
|
|
||||||
app.include_router(models.router)
|
|
||||||
app.include_router(eeg.router)
|
|
||||||
app.include_router(preview.router)
|
|
||||||
app.include_router(fhir.router)
|
|
||||||
app.include_router(users.router)
|
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(HTTPException)
|
|
||||||
async def errors(request: Request, error: HTTPException):
|
|
||||||
if "/fhir/" in request.url.path or request.url.path.endswith("/fhir"):
|
|
||||||
return fhir.outcome(error.status_code, str(error.detail))
|
|
||||||
return await http_exception_handler(request, error)
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/health")
|
|
||||||
def health() -> dict[str, str]:
|
|
||||||
return {"status": "ok"}
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/domains")
|
|
||||||
def domains() -> list[Domain]:
|
|
||||||
return list(Domain)
|
|
||||||
@@ -1,289 +0,0 @@
|
|||||||
import mimetypes
|
|
||||||
import zipfile
|
|
||||||
from datetime import date
|
|
||||||
from typing import Annotated, Any, Literal
|
|
||||||
|
|
||||||
from dagster_graphql import DagsterGraphQLClient
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile
|
|
||||||
from fastapi.responses import Response
|
|
||||||
from pydantic import BaseModel, Field
|
|
||||||
|
|
||||||
from core.domains import Domain
|
|
||||||
from core.models import title
|
|
||||||
from persistance import bundle, cluster, registry
|
|
||||||
from persistance.cluster import Execution, TrainingSource
|
|
||||||
from webapi.runs import dagster, execution_config, submit
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/models", tags=["models"])
|
|
||||||
|
|
||||||
|
|
||||||
class Version(BaseModel):
|
|
||||||
version: int
|
|
||||||
created: int
|
|
||||||
aliases: list[str]
|
|
||||||
metrics: dict[str, float]
|
|
||||||
params: dict[str, str]
|
|
||||||
reports: list[str]
|
|
||||||
status: Literal["champion", "retired", "candidate"]
|
|
||||||
|
|
||||||
|
|
||||||
class Model(BaseModel):
|
|
||||||
name: str
|
|
||||||
title: str
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{domain}")
|
|
||||||
def models(domain: Domain) -> list[Model]:
|
|
||||||
prefix = f"{domain.value}."
|
|
||||||
return [Model(name=n.removeprefix(prefix), title=title(n)) for n in registry.names(prefix)]
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/{domain}/export",
|
|
||||||
responses={200: {"content": {"application/zip": {}}}},
|
|
||||||
response_class=Response,
|
|
||||||
)
|
|
||||||
def export_models(
|
|
||||||
domain: Domain,
|
|
||||||
names: Annotated[list[str] | None, Query()] = None,
|
|
||||||
versions: bundle.Selection = "champion",
|
|
||||||
) -> Response:
|
|
||||||
try:
|
|
||||||
exported = bundle.export(domain, names, versions)
|
|
||||||
except bundle.Empty as e:
|
|
||||||
raise HTTPException(409, detail=str(e)) from e
|
|
||||||
except bundle.BundleError as e:
|
|
||||||
raise HTTPException(422, detail=str(e)) from e
|
|
||||||
return Response(
|
|
||||||
exported.data,
|
|
||||||
media_type="application/zip",
|
|
||||||
headers={
|
|
||||||
"X-Bundle-Sha256": exported.sha256,
|
|
||||||
"X-Bundle-Versions": ",".join(f"{name}/{v}" for name, v in exported.versions),
|
|
||||||
"Content-Disposition": (
|
|
||||||
f'attachment; filename="{domain}-models-{exported.sha256[:12]}.zip"'
|
|
||||||
),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/{domain}/import")
|
|
||||||
def import_models(
|
|
||||||
domain: Domain,
|
|
||||||
sha256: Annotated[str, Query(pattern=r"^[0-9a-fA-F]{64}$")],
|
|
||||||
file: UploadFile,
|
|
||||||
client: DagsterGraphQLClient = Depends(dagster),
|
|
||||||
) -> dict[str, str]:
|
|
||||||
computed, path = bundle.stage(file.file)
|
|
||||||
if computed != sha256.lower():
|
|
||||||
path.unlink(missing_ok=True)
|
|
||||||
raise HTTPException(422, detail=f"the file's SHA-256 is {computed}, not the one given")
|
|
||||||
if not zipfile.is_zipfile(path):
|
|
||||||
path.unlink(missing_ok=True)
|
|
||||||
raise HTTPException(422, detail="not a bundle")
|
|
||||||
if not bundle.trusted(computed):
|
|
||||||
path.unlink(missing_ok=True)
|
|
||||||
raise HTTPException(
|
|
||||||
403,
|
|
||||||
detail=f"bundle {computed} is not trusted on this server: "
|
|
||||||
f"the operator adds its SHA-256 to {bundle.trusted_file()}",
|
|
||||||
)
|
|
||||||
return submit(
|
|
||||||
client,
|
|
||||||
"import_bundle",
|
|
||||||
"import_bundle_files",
|
|
||||||
{"domain": domain.value, "sha256": computed},
|
|
||||||
domain.value,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{domain}/{name}/versions")
|
|
||||||
def versions(domain: Domain, name: str) -> list[Version]:
|
|
||||||
if not (found := registry.versions(f"{domain.value}.{name}")):
|
|
||||||
raise HTTPException(404, detail=f"no {domain.value} model {name}")
|
|
||||||
return [Version(**v) for v in found]
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{domain}/{name}/versions/{version}/reports/{report}",
|
|
||||||
responses={200: {"content": {"application/json": {}, "application/octet-stream": {}},
|
|
||||||
"description": "the report as stored"}},
|
|
||||||
response_class=Response,
|
|
||||||
description=(
|
|
||||||
"A version's report: the generated ones as JSON (what the "
|
|
||||||
'governance page draws), the\n'
|
|
||||||
'clinical validation as the file the clinical team uploaded.'
|
|
||||||
),
|
|
||||||
) # fmt: skip
|
|
||||||
def read_report(domain: Domain, name: str, version: int, report: str) -> Response:
|
|
||||||
found = registry.report(f"{domain.value}.{name}", version, report)
|
|
||||||
if found is None:
|
|
||||||
raise HTTPException(404, detail=f"{domain.value}.{name} v{version} has no {report}")
|
|
||||||
filename, content = found
|
|
||||||
kind = mimetypes.guess_type(filename)[0] or "application/octet-stream"
|
|
||||||
return Response(content, media_type=kind,
|
|
||||||
headers={"Content-Disposition": f'inline; filename="{filename}"'}) # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/{domain}/{name}/versions/{version}/reports/clinical_validation",
|
|
||||||
description=(
|
|
||||||
"The clinical team's validation of a version: the third report, "
|
|
||||||
"which promotion needs\n"
|
|
||||||
"unless the site left it out of PROMOTION_REPORTS."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def add_clinical_validation(domain: Domain, name: str, version: int, file: UploadFile) -> dict:
|
|
||||||
registry.add_report(f"{domain.value}.{name}", version, "clinical_validation",
|
|
||||||
file.filename or "report", file.file.read()) # fmt: skip
|
|
||||||
return {"reports": sorted(registry.reports(f"{domain.value}.{name}", version))}
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/{domain}/{name}/versions/{version}/promote",
|
|
||||||
description=(
|
|
||||||
"The version risk batches come from from now on; refused (409) "
|
|
||||||
"without the reports\n"
|
|
||||||
"the site requires (PROMOTION_REPORTS; default: technical "
|
|
||||||
"validation, interpretability\n"
|
|
||||||
"and clinical validation)."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def promote(domain: Domain, name: str, version: int) -> dict:
|
|
||||||
try:
|
|
||||||
registry.promote(f"{domain.value}.{name}", version)
|
|
||||||
except registry.UnknownVersion as e:
|
|
||||||
raise HTTPException(404, detail=str(e)) from e
|
|
||||||
except ValueError as e:
|
|
||||||
raise HTTPException(409, detail=str(e)) from e
|
|
||||||
return {"champion": version}
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{domain}/{name}/versions/{version}/checks")
|
|
||||||
def version_checks(domain: Domain, name: str, version: int) -> dict:
|
|
||||||
registered = f"{domain.value}.{name}"
|
|
||||||
try:
|
|
||||||
status = registry.status(registered, version)
|
|
||||||
except registry.UnknownVersion as e:
|
|
||||||
raise HTTPException(404, detail=str(e)) from e
|
|
||||||
checks = registry.checks(registered, version)
|
|
||||||
return {
|
|
||||||
"version": version,
|
|
||||||
"status": status,
|
|
||||||
"checks": checks,
|
|
||||||
"promotable": status != "retired" and all(check["present"] for check in checks),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/{domain}/{name}/versions/{version}/retire")
|
|
||||||
def retire(domain: Domain, name: str, version: int) -> dict[str, str]:
|
|
||||||
try:
|
|
||||||
registry.retire(f"{domain.value}.{name}", version)
|
|
||||||
except registry.UnknownVersion as e:
|
|
||||||
raise HTTPException(404, detail=str(e)) from e
|
|
||||||
except ValueError as e:
|
|
||||||
raise HTTPException(409, detail=str(e)) from e
|
|
||||||
return {"status": "retired"}
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{domain}/{name}/versions/{version}/lineage")
|
|
||||||
def lineage(domain: Domain, name: str, version: int) -> dict:
|
|
||||||
try:
|
|
||||||
return registry.lineage(f"{domain.value}.{name}", version)
|
|
||||||
except registry.UnknownVersion as e:
|
|
||||||
raise HTTPException(404, detail=str(e)) from e
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{domain}/{name}/versions/{version}/curve")
|
|
||||||
def curve(domain: Domain, name: str, version: int, feature: str = "value") -> list[dict]:
|
|
||||||
if domain != Domain.TEA:
|
|
||||||
raise HTTPException(404, detail="no age curve for this model")
|
|
||||||
try:
|
|
||||||
model = registry.load(f"{domain.value}.{name}", version).unwrap_python_model()
|
|
||||||
if not hasattr(model, "curve"):
|
|
||||||
raise HTTPException(404, detail="no age curve for this model")
|
|
||||||
return model.curve(feature, range(16, 37))
|
|
||||||
except KeyError as e:
|
|
||||||
raise HTTPException(404, detail=f"no curve feature {feature!r}") from e
|
|
||||||
except LookupError as e:
|
|
||||||
raise HTTPException(404, detail=str(e)) from e
|
|
||||||
|
|
||||||
|
|
||||||
class TrainingForm(BaseModel):
|
|
||||||
as_of: date | None = Field(
|
|
||||||
None, title="Datos hasta", description="Fecha de corte de los datos (por omisión, hoy)"
|
|
||||||
)
|
|
||||||
execution: Execution | None = None
|
|
||||||
source: TrainingSource | None = Field(None, title="Datos de entrenamiento")
|
|
||||||
|
|
||||||
|
|
||||||
class Training(TrainingForm):
|
|
||||||
models: list[str] = []
|
|
||||||
|
|
||||||
|
|
||||||
class TrainingConfig(BaseModel):
|
|
||||||
domain: str
|
|
||||||
name: str
|
|
||||||
json_schema: dict[str, Any]
|
|
||||||
defaults: dict[str, Any]
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{domain}/{name}/training-config")
|
|
||||||
def training_config(domain: Domain, name: str) -> TrainingConfig:
|
|
||||||
json_schema = TrainingForm.model_json_schema()
|
|
||||||
defaults = {"execution": {"mode": cluster.default_mode(), "scheduler": None}}
|
|
||||||
if domain == Domain.TEA:
|
|
||||||
defaults["source"] = {"kind": "site"}
|
|
||||||
else:
|
|
||||||
del json_schema["properties"]["source"]
|
|
||||||
for definition in ("TrainingSource", "SiteTrainingSource", "FolderTrainingSource"):
|
|
||||||
del json_schema["$defs"][definition]
|
|
||||||
return TrainingConfig(
|
|
||||||
domain=domain.value, name=name, json_schema=json_schema, defaults=defaults
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class Analyze(BaseModel):
|
|
||||||
execution: Execution | None = None
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/{domain}/train",
|
|
||||||
description="Starts training a new version of every model of the domain; follow it at /runs.",
|
|
||||||
)
|
|
||||||
def train(domain: Domain, request: Training,
|
|
||||||
client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip
|
|
||||||
if request.source is not None and domain != Domain.TEA:
|
|
||||||
raise HTTPException(422, f"{domain.value} models take no training source")
|
|
||||||
config: dict = {"domain": domain.value, "execution": execution_config(request.execution)}
|
|
||||||
if request.as_of:
|
|
||||||
config["as_of"] = request.as_of.isoformat()
|
|
||||||
if request.models:
|
|
||||||
config["models"] = request.models
|
|
||||||
if request.source is not None:
|
|
||||||
config["source"] = request.source.model_dump()
|
|
||||||
return submit(client, "train", "train_models", config, domain=domain.value)
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/{domain}/analyze",
|
|
||||||
description=(
|
|
||||||
"Starts analysing the studies the domain's models read whole "
|
|
||||||
"(TEA: its EEGs); follow\n"
|
|
||||||
"it at /runs."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def analyze(
|
|
||||||
domain: Domain,
|
|
||||||
request: Analyze = Analyze(), # noqa: B008
|
|
||||||
client: DagsterGraphQLClient = Depends(dagster),
|
|
||||||
) -> dict[str, str]:
|
|
||||||
config = {"domain": domain.value, "execution": execution_config(request.execution)}
|
|
||||||
return submit(client, "analyze", "analyze_studies", config, domain=domain.value)
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/{domain}/score",
|
|
||||||
description="Starts a risk batch from each model's champion; follow it at /runs.",
|
|
||||||
)
|
|
||||||
def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
|
||||||
return submit(client, "score", "score_models", {"domain": domain.value}, domain=domain.value)
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
import json
|
|
||||||
|
|
||||||
from webapi.main import app
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
print(json.dumps(app.openapi(), indent=1, sort_keys=True))
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
from datetime import date
|
|
||||||
from typing import Annotated
|
|
||||||
|
|
||||||
from dagster_graphql import DagsterGraphQLClient
|
|
||||||
from fastapi import APIRouter, Depends, Form, HTTPException, UploadFile
|
|
||||||
from pydantic import BaseModel, WithJsonSchema
|
|
||||||
|
|
||||||
from persistance import previews
|
|
||||||
from webapi import runs
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/tea/preview", tags=["preview"])
|
|
||||||
_MAX_FILE_BYTES = 200 * 1024 * 1024
|
|
||||||
_BinaryUpload = Annotated[UploadFile, WithJsonSchema({"type": "string", "format": "binary"})]
|
|
||||||
|
|
||||||
|
|
||||||
class PreviewStatus(BaseModel):
|
|
||||||
state: runs.State
|
|
||||||
result: previews.PreviewResult | None
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("")
|
|
||||||
def start_preview(
|
|
||||||
edf: _BinaryUpload,
|
|
||||||
ados2: _BinaryUpload | None = None,
|
|
||||||
birth_date: Annotated[date | None, Form()] = None,
|
|
||||||
pipeline: Annotated[str, Form()] = "tea",
|
|
||||||
client: DagsterGraphQLClient = Depends(runs.dagster),
|
|
||||||
) -> dict[str, str]:
|
|
||||||
for file in (edf, ados2):
|
|
||||||
if file is not None and file.size is not None and file.size > _MAX_FILE_BYTES:
|
|
||||||
raise HTTPException(413, detail="preview files may be at most 200 MiB each")
|
|
||||||
config = {
|
|
||||||
"edf": previews.put(edf.file.read()),
|
|
||||||
"ados2": previews.put(ados2.file.read()) if ados2 is not None else None,
|
|
||||||
"birth_date": birth_date.isoformat() if birth_date else None,
|
|
||||||
"pipeline": pipeline,
|
|
||||||
}
|
|
||||||
return runs.submit(client, "tea_preview", "preview_study", config, domain="tea")
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{run_id}")
|
|
||||||
def preview_status(run_id: str) -> PreviewStatus:
|
|
||||||
run = runs.run_status(run_id, outputs=True)
|
|
||||||
if run.job != "tea_preview":
|
|
||||||
raise HTTPException(404, detail=f"no TEA preview run {run_id}")
|
|
||||||
raw = (run.outputs or {}).get("preview_study.result") if run.state == "succeeded" else None
|
|
||||||
return PreviewStatus(
|
|
||||||
state=run.state,
|
|
||||||
result=previews.PreviewResult.model_validate(raw) if raw is not None else None,
|
|
||||||
)
|
|
||||||
@@ -1,128 +0,0 @@
|
|||||||
from typing import Any
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends
|
|
||||||
from pydantic import BaseModel, ConfigDict, model_validator
|
|
||||||
|
|
||||||
from core.pipeline import EntityName, Id, validate
|
|
||||||
from core.schema import ENTITIES
|
|
||||||
from persistance import nodes, review
|
|
||||||
from webapi.auth import Caller, caller
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/review", tags=["review"])
|
|
||||||
Rows = list[dict[str, Any]]
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/held",
|
|
||||||
description="Rows a rule held, with the reasons and the values as they came.",
|
|
||||||
)
|
|
||||||
def held(entity: EntityName) -> Rows:
|
|
||||||
return review.held(entity)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/conflicts",
|
|
||||||
description="Rows of one person and date that disagree; reject the wrong ones.",
|
|
||||||
)
|
|
||||||
def conflicts(entity: EntityName) -> Rows:
|
|
||||||
return review.conflicts(entity)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/unrecognised",
|
|
||||||
description=(
|
|
||||||
"Documents a pipeline's routes don't recognise (what its "
|
|
||||||
"`otherwise` routes took):\n"
|
|
||||||
"a new layout, a study the platform doesn't know, a scan nothing "
|
|
||||||
"could read."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def unrecognised(pipeline: Id) -> Rows:
|
|
||||||
return review.unrecognised(pipeline)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/persons",
|
|
||||||
description=(
|
|
||||||
"Persons to settle (with their possible owners), torn persons "
|
|
||||||
"and persons nothing\n"
|
|
||||||
"names (with their records) left by a pipeline's link node."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def persons(pipeline: Id, node: Id) -> dict[str, Rows]:
|
|
||||||
return review.persons(pipeline, node)
|
|
||||||
|
|
||||||
|
|
||||||
class PersonDecision(BaseModel):
|
|
||||||
person: str
|
|
||||||
candidate: str
|
|
||||||
same: bool
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/persons",
|
|
||||||
status_code=201,
|
|
||||||
description="Whether a person and a possible owner are one patient; applied on the next run.",
|
|
||||||
)
|
|
||||||
def decide_persons(decision: PersonDecision, who: Caller = Depends(caller)) -> dict[str, str]:
|
|
||||||
nodes.decide_persons(decision.person, decision.candidate, decision.same, who.id)
|
|
||||||
return {"person": decision.person}
|
|
||||||
|
|
||||||
|
|
||||||
class Correction(BaseModel):
|
|
||||||
model_config = ConfigDict(
|
|
||||||
json_schema_extra={
|
|
||||||
"description": (
|
|
||||||
"One field of one record as a reviewer read it in the source "
|
|
||||||
"document: an identity\n"
|
|
||||||
"field (a mistyped record number) or a study's (a stage the scan "
|
|
||||||
"made unreadable)."
|
|
||||||
)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
entity: EntityName = "identity"
|
|
||||||
record: str
|
|
||||||
field: str
|
|
||||||
value: str
|
|
||||||
|
|
||||||
@model_validator(mode="after")
|
|
||||||
def _a_valid_value(self):
|
|
||||||
if self.field not in ENTITIES[self.entity].model_fields:
|
|
||||||
raise ValueError(f"{self.entity} has no field {self.field}")
|
|
||||||
reasons = [r for r in validate(self.entity, {self.field: self.value})
|
|
||||||
if r.split(":")[0] == self.field] # fmt: skip
|
|
||||||
if reasons:
|
|
||||||
raise ValueError("; ".join(reasons))
|
|
||||||
return self
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/corrections",
|
|
||||||
status_code=201,
|
|
||||||
description=(
|
|
||||||
"A corrected field of one record; the next run uses it (linking "
|
|
||||||
"for identity fields,\n"
|
|
||||||
"the study's target for the others). Fixing the source too is "
|
|
||||||
"still worth it."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def correct(fix: Correction, who: Caller = Depends(caller)) -> dict[str, str]:
|
|
||||||
nodes.correct(fix.record, fix.field, fix.value, who.id, fix.entity)
|
|
||||||
return {"record": fix.record}
|
|
||||||
|
|
||||||
|
|
||||||
class Rejection(BaseModel):
|
|
||||||
entity: EntityName
|
|
||||||
record: str
|
|
||||||
reason: str
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/rejections",
|
|
||||||
status_code=201,
|
|
||||||
description="This record's row must not reach silver; applied on the next run.",
|
|
||||||
)
|
|
||||||
def reject(decision: Rejection, who: Caller = Depends(caller)) -> dict[str, str]:
|
|
||||||
nodes.reject(decision.entity, decision.record, decision.reason, who.id)
|
|
||||||
return {"record": decision.record}
|
|
||||||
-297
@@ -1,297 +0,0 @@
|
|||||||
import json
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
from typing import Any, Literal
|
|
||||||
|
|
||||||
import requests
|
|
||||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
||||||
from pydantic import BaseModel, ValidationError
|
|
||||||
|
|
||||||
from core.domains import Domain
|
|
||||||
from persistance import cluster
|
|
||||||
from persistance.cluster import Execution, Progress
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/runs", tags=["runs"])
|
|
||||||
|
|
||||||
State = Literal["queued", "running", "succeeded", "failed", "cancelling", "cancelled"]
|
|
||||||
STATE: dict[str, State] = {
|
|
||||||
"QUEUED": "queued",
|
|
||||||
"NOT_STARTED": "queued",
|
|
||||||
"MANAGED": "queued",
|
|
||||||
"STARTING": "running",
|
|
||||||
"STARTED": "running",
|
|
||||||
"CANCELING": "cancelling",
|
|
||||||
"CANCELED": "cancelled",
|
|
||||||
"SUCCESS": "succeeded",
|
|
||||||
"FAILURE": "failed",
|
|
||||||
}
|
|
||||||
|
|
||||||
RUN_QUERY = """
|
|
||||||
query Run($id: ID!, $outputs: Boolean! = false) {
|
|
||||||
runOrError(runId: $id) {
|
|
||||||
__typename
|
|
||||||
... on Run { runId jobName status startTime endTime tags { key value }
|
|
||||||
stepStats { stepKey status startTime endTime } }
|
|
||||||
... on RunNotFoundError { message }
|
|
||||||
... on PythonError { message }
|
|
||||||
}
|
|
||||||
logsForRun(runId: $id, limit: 5000) {
|
|
||||||
__typename
|
|
||||||
... on EventConnection { events { __typename
|
|
||||||
... on MessageEvent { message level stepKey }
|
|
||||||
... on ExecutionStepOutputEvent @include(if: $outputs) {
|
|
||||||
stepKey outputName metadataEntries { label ... on JsonMetadataEntry { jsonString } }
|
|
||||||
}
|
|
||||||
... on ExecutionStepFailureEvent { error { message causes { message } } }
|
|
||||||
... on RunFailureEvent { error { message causes { message } } } } }
|
|
||||||
... on RunNotFoundError { message }
|
|
||||||
... on PythonError { message }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
|
|
||||||
RUNS_QUERY = """
|
|
||||||
query Runs($filter: RunsFilter, $cursor: String, $limit: Int) {
|
|
||||||
runsOrError(filter: $filter, cursor: $cursor, limit: $limit) {
|
|
||||||
__typename
|
|
||||||
... on Runs { results { runId jobName status startTime endTime tags { key value } } }
|
|
||||||
... on InvalidPipelineRunsFilterError { message }
|
|
||||||
... on PythonError { message }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
class RunSummary(BaseModel):
|
|
||||||
id: str
|
|
||||||
job: str
|
|
||||||
domain: str | None
|
|
||||||
status: str
|
|
||||||
state: State
|
|
||||||
started: float | None
|
|
||||||
ended: float | None
|
|
||||||
|
|
||||||
|
|
||||||
class Step(BaseModel):
|
|
||||||
key: str
|
|
||||||
status: str
|
|
||||||
started: float | None
|
|
||||||
ended: float | None
|
|
||||||
|
|
||||||
|
|
||||||
class Run(RunSummary):
|
|
||||||
progress: Progress | None
|
|
||||||
steps: list[Step]
|
|
||||||
info: list[str]
|
|
||||||
warnings: list[str]
|
|
||||||
error: str | None
|
|
||||||
outputs: dict[str, Any] | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class Cancel(BaseModel):
|
|
||||||
id: str
|
|
||||||
status: str
|
|
||||||
state: State
|
|
||||||
|
|
||||||
|
|
||||||
def _dagster_address() -> tuple[str, int]:
|
|
||||||
return os.environ.get("DAGSTER_HOST", "localhost"), int(os.environ.get("DAGSTER_PORT", "3000"))
|
|
||||||
|
|
||||||
|
|
||||||
def dagster() -> DagsterGraphQLClient:
|
|
||||||
host, port = _dagster_address()
|
|
||||||
return DagsterGraphQLClient(host, port_number=port)
|
|
||||||
|
|
||||||
|
|
||||||
LOCKED = "database is locked"
|
|
||||||
LOCK_RETRIES = 5
|
|
||||||
STARTING_WAIT_S = 30
|
|
||||||
|
|
||||||
|
|
||||||
def _locked(payload: dict) -> bool:
|
|
||||||
results = (payload.get("data") or {}).values()
|
|
||||||
return LOCKED in str(payload.get("errors", "")) or any(
|
|
||||||
isinstance(r, dict)
|
|
||||||
and r.get("__typename") == "PythonError"
|
|
||||||
and LOCKED in r.get("message", "")
|
|
||||||
for r in results
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _graphql_response(url: str, query: str, variables: dict) -> dict:
|
|
||||||
try:
|
|
||||||
response = requests.post(url, json={"query": query, "variables": variables}, timeout=15)
|
|
||||||
if response.status_code != 200:
|
|
||||||
raise HTTPException(502, detail=response.text)
|
|
||||||
return response.json()
|
|
||||||
except requests.RequestException as e:
|
|
||||||
raise HTTPException(502, detail=str(e)) from e
|
|
||||||
|
|
||||||
|
|
||||||
def graphql(query: str, variables: dict) -> dict:
|
|
||||||
host, port = _dagster_address()
|
|
||||||
url = f"http://{host}:{port}/graphql"
|
|
||||||
payload = _graphql_response(url, query, variables)
|
|
||||||
for attempt in range(LOCK_RETRIES):
|
|
||||||
if not _locked(payload):
|
|
||||||
break
|
|
||||||
time.sleep(0.2 * 2**attempt)
|
|
||||||
payload = _graphql_response(url, query, variables)
|
|
||||||
if _locked(payload):
|
|
||||||
raise HTTPException(
|
|
||||||
503, detail="Dagster's run storage is busy; try again", headers={"Retry-After": "5"}
|
|
||||||
)
|
|
||||||
if "errors" in payload:
|
|
||||||
raise HTTPException(502, detail=str(payload["errors"]))
|
|
||||||
return payload["data"]
|
|
||||||
|
|
||||||
|
|
||||||
def _tags(run: dict) -> dict[str, str]:
|
|
||||||
return {tag["key"]: tag["value"] for tag in run.get("tags", [])}
|
|
||||||
|
|
||||||
|
|
||||||
def _summary(run: dict) -> RunSummary:
|
|
||||||
status = run["status"]
|
|
||||||
return RunSummary(
|
|
||||||
id=run["runId"],
|
|
||||||
job=run["jobName"],
|
|
||||||
domain=_tags(run).get("domain"),
|
|
||||||
status=status,
|
|
||||||
state=STATE.get(status, "running"),
|
|
||||||
started=run.get("startTime"),
|
|
||||||
ended=run.get("endTime"),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def shape(run: dict, logs: list[dict], outputs: bool = False) -> Run:
|
|
||||||
summary = _summary(run)
|
|
||||||
progress = None
|
|
||||||
if (tag := _tags(run).get("isssteleon/progress")) is not None:
|
|
||||||
try:
|
|
||||||
progress = Progress.model_validate_json(tag)
|
|
||||||
except ValidationError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
steps = [
|
|
||||||
Step(
|
|
||||||
key=step["stepKey"],
|
|
||||||
status=step["status"],
|
|
||||||
started=step.get("startTime"),
|
|
||||||
ended=step.get("endTime"),
|
|
||||||
)
|
|
||||||
for step in run.get("stepStats", [])
|
|
||||||
]
|
|
||||||
steps.sort(key=lambda step: (step.started is None, step.started or 0.0))
|
|
||||||
|
|
||||||
info, warnings = [], []
|
|
||||||
error = None
|
|
||||||
result = {} if outputs else None
|
|
||||||
for event in logs:
|
|
||||||
kind = event["__typename"]
|
|
||||||
if kind == "LogMessageEvent" and event["level"] in ("INFO", "WARNING"):
|
|
||||||
line = event["message"]
|
|
||||||
if step_key := event.get("stepKey"):
|
|
||||||
line = f"{step_key}: {line}"
|
|
||||||
(info if event["level"] == "INFO" else warnings).append(line)
|
|
||||||
if result is not None and kind == "ExecutionStepOutputEvent":
|
|
||||||
for entry in event.get("metadataEntries", ()):
|
|
||||||
if "jsonString" in entry:
|
|
||||||
result[f"{event['stepKey']}.{entry['label']}"] = json.loads(entry["jsonString"])
|
|
||||||
if summary.state == "failed" and kind in ("ExecutionStepFailureEvent", "RunFailureEvent"):
|
|
||||||
failure = event.get("error")
|
|
||||||
error = None
|
|
||||||
if failure:
|
|
||||||
causes = failure.get("causes")
|
|
||||||
message = (causes[-1] if causes else failure)["message"]
|
|
||||||
lines = message.strip().splitlines()
|
|
||||||
error = lines[0][:500] if lines else None
|
|
||||||
|
|
||||||
return Run(
|
|
||||||
**summary.model_dump(),
|
|
||||||
progress=progress,
|
|
||||||
outputs=result,
|
|
||||||
steps=steps,
|
|
||||||
info=info[-200:],
|
|
||||||
warnings=warnings[:200],
|
|
||||||
error=(error or "the run failed") if summary.state == "failed" else None,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _result(result: dict, typename: str) -> dict:
|
|
||||||
if result["__typename"] != typename:
|
|
||||||
status = 404 if result["__typename"] == "RunNotFoundError" else 502
|
|
||||||
raise HTTPException(status, detail=result.get("message", result["__typename"]))
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{run_id}")
|
|
||||||
def run_status(run_id: str, outputs: bool = False) -> Run:
|
|
||||||
data = graphql(RUN_QUERY, {"id": run_id, "outputs": outputs})
|
|
||||||
run = _result(data["runOrError"], "Run")
|
|
||||||
logs = _result(data["logsForRun"], "EventConnection")
|
|
||||||
return shape(run, logs["events"], outputs)
|
|
||||||
|
|
||||||
|
|
||||||
def _status(client: DagsterGraphQLClient, run_id: str) -> str:
|
|
||||||
try:
|
|
||||||
return client.get_run_status(run_id).value
|
|
||||||
except DagsterGraphQLClientError as e:
|
|
||||||
raise HTTPException(404 if e.args[0] == "RunNotFoundError" else 502, detail=str(e)) from e
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/{run_id}/cancel")
|
|
||||||
def cancel_run(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> Cancel:
|
|
||||||
status = _status(client, run_id)
|
|
||||||
deadline = time.monotonic() + STARTING_WAIT_S
|
|
||||||
while status == "STARTING" and time.monotonic() < deadline:
|
|
||||||
time.sleep(0.5)
|
|
||||||
status = _status(client, run_id)
|
|
||||||
if status in ("SUCCESS", "FAILURE", "CANCELED"):
|
|
||||||
raise HTTPException(409, detail=f"the run already ended: {STATE[status]}")
|
|
||||||
if status == "STARTING":
|
|
||||||
raise HTTPException(
|
|
||||||
409, detail="the run is still starting; try again", headers={"Retry-After": "5"}
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
client.terminate_run(run_id)
|
|
||||||
except DagsterGraphQLClientError as e:
|
|
||||||
raise HTTPException(502, detail=str(e)) from e
|
|
||||||
status = _status(client, run_id)
|
|
||||||
return Cancel(id=run_id, status=status, state=STATE.get(status, "running"))
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("")
|
|
||||||
def run_history(
|
|
||||||
job: str | None = None,
|
|
||||||
domain: Domain | None = None,
|
|
||||||
limit: int = Query(50, ge=1, le=200),
|
|
||||||
before: str | None = None,
|
|
||||||
) -> list[RunSummary]:
|
|
||||||
filters = {}
|
|
||||||
if job is not None:
|
|
||||||
filters["pipelineName"] = job
|
|
||||||
if domain is not None:
|
|
||||||
filters["tags"] = [{"key": "domain", "value": domain.value}]
|
|
||||||
data = graphql(RUNS_QUERY, {"filter": filters, "cursor": before, "limit": limit})
|
|
||||||
return [_summary(run) for run in _result(data["runsOrError"], "Runs")["results"]]
|
|
||||||
|
|
||||||
|
|
||||||
def submit(
|
|
||||||
client: DagsterGraphQLClient, job: str, op: str, config: dict, domain: str
|
|
||||||
) -> dict[str, str]:
|
|
||||||
try:
|
|
||||||
run_id = client.submit_job_execution(
|
|
||||||
job, run_config={"ops": {op: {"config": config}}}, tags={"domain": domain}
|
|
||||||
)
|
|
||||||
except DagsterGraphQLClientError as e:
|
|
||||||
raise HTTPException(502, detail=str(e)) from e
|
|
||||||
return {"run_id": run_id}
|
|
||||||
|
|
||||||
|
|
||||||
def execution_config(choice: Execution | None) -> dict:
|
|
||||||
try:
|
|
||||||
resolved = cluster.resolve(choice)
|
|
||||||
except cluster.ExecutionError as e:
|
|
||||||
raise HTTPException(422, detail=str(e)) from e
|
|
||||||
return {"mode": resolved.mode, "scheduler": resolved.scheduler}
|
|
||||||
@@ -1,369 +0,0 @@
|
|||||||
import os
|
|
||||||
import re
|
|
||||||
import shutil
|
|
||||||
import uuid
|
|
||||||
from pathlib import Path, PurePosixPath
|
|
||||||
from typing import Annotated, Any, Literal
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Form, HTTPException, Query, UploadFile
|
|
||||||
from pydantic import BaseModel, ValidationError
|
|
||||||
|
|
||||||
from core import sources
|
|
||||||
from core.pipeline import MASK, Pipeline, Source, restored
|
|
||||||
from persistance import config_log, nodes
|
|
||||||
from persistance.config import DATA_DIR
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/ingest", tags=["ingest"])
|
|
||||||
UPLOADS = "uploads"
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/sources/types",
|
|
||||||
description="Every kind of source the dialog offers, grouped, with the fields each one asks.",
|
|
||||||
)
|
|
||||||
def source_types() -> sources.Catalog:
|
|
||||||
return sources.catalog()
|
|
||||||
|
|
||||||
|
|
||||||
class Answers(BaseModel):
|
|
||||||
type: str
|
|
||||||
answers: dict[str, Any] = {}
|
|
||||||
pipeline: str | None = None
|
|
||||||
node: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class Tested(BaseModel):
|
|
||||||
ok: bool
|
|
||||||
message: str
|
|
||||||
detail: str | None = None
|
|
||||||
tables: list[str] = []
|
|
||||||
rows: list[dict[str, Any]] = []
|
|
||||||
|
|
||||||
|
|
||||||
PLAIN = [
|
|
||||||
(
|
|
||||||
r"login failed|password authentication failed|access denied|authentication|"
|
|
||||||
r"401|403|permission denied|invalid credentials",
|
|
||||||
"El usuario o la contraseña no son correctos, o no tiene permiso.",
|
|
||||||
), # fmt: skip
|
|
||||||
(
|
|
||||||
r"name or service not known|could not translate host|nodename nor servname|"
|
|
||||||
r"getaddrinfo|unknown host|no such host|resolve",
|
|
||||||
"No se encontró el servidor. Revise el nombre o la dirección.",
|
|
||||||
), # fmt: skip
|
|
||||||
(
|
|
||||||
r"timed out|timeout|connection refused|unable to connect|adaptive server is unavailable|"
|
|
||||||
r"could not connect|connection reset",
|
|
||||||
"El servidor no respondió. Revise la dirección, el puerto o si está encendido.",
|
|
||||||
), # fmt: skip
|
|
||||||
(
|
|
||||||
r"database .* does not exist|cannot open database|unknown database",
|
|
||||||
"No existe esa base de datos en el servidor.",
|
|
||||||
), # fmt: skip
|
|
||||||
(
|
|
||||||
r"no such table|invalid object name|does not exist|not found|no such file|404",
|
|
||||||
"No se encontró lo que pidió (la tabla, la carpeta o el archivo).",
|
|
||||||
), # fmt: skip
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def plain(error: BaseException) -> str:
|
|
||||||
said = f"{type(error).__name__}: {error}"
|
|
||||||
for pattern, message in PLAIN:
|
|
||||||
if re.search(pattern, said, re.IGNORECASE):
|
|
||||||
return message
|
|
||||||
return "No se pudo conectar. Abajo está lo que respondió el sistema."
|
|
||||||
|
|
||||||
|
|
||||||
def _with_saved_secrets(asked: Answers) -> dict[str, Any]:
|
|
||||||
if MASK not in repr(asked.answers):
|
|
||||||
return asked.answers
|
|
||||||
if not (asked.pipeline and asked.node and config_log.latest_version(asked.pipeline)):
|
|
||||||
raise HTTPException(422, detail="una contraseña oculta necesita la fuente guardada")
|
|
||||||
saved = config_log.get(asked.pipeline)[1]
|
|
||||||
node = {"id": asked.node, "kind": "source", "source": "core.sources:catalog",
|
|
||||||
"guided": {"type": asked.type, "answers": asked.answers}} # fmt: skip
|
|
||||||
try:
|
|
||||||
found = restored(Pipeline(nodes=[node]), saved).nodes[0]
|
|
||||||
except ValueError as e:
|
|
||||||
raise HTTPException(422, detail=str(e)) from e
|
|
||||||
return found.guided.answers
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/sources/test",
|
|
||||||
description=(
|
|
||||||
'"Probar conexión": reaches the source with the answers given. A '
|
|
||||||
"database lists its\n"
|
|
||||||
"tables (until one is picked; then its first rows); files and "
|
|
||||||
"records show their first\n"
|
|
||||||
"rows. Never a server error: what went wrong comes back in plain "
|
|
||||||
"words."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def test_source(asked: Answers, limit: Annotated[int, Query(ge=1, le=100)] = 20) -> Tested:
|
|
||||||
if asked.type not in sources.catalog().types:
|
|
||||||
raise HTTPException(404, detail=f"no source type {asked.type}")
|
|
||||||
answers = _with_saved_secrets(asked)
|
|
||||||
spec = sources.catalog().types[asked.type]
|
|
||||||
picked = all(answers.get(k) for k, f in spec.fields.items() if f.type == "table")
|
|
||||||
try:
|
|
||||||
if not picked and (listed := sources.listing(asked.type, answers)):
|
|
||||||
tables = nodes.resources(*listed)
|
|
||||||
count = "1 tabla" if len(tables) == 1 else f"{len(tables)} tablas"
|
|
||||||
return Tested(ok=True, message=f"Conexión correcta: {count}.",
|
|
||||||
tables=tables) # fmt: skip
|
|
||||||
node = Source(id="probe", guided={"type": asked.type, "answers": answers})
|
|
||||||
rows = [nodes.shown(r) for r in nodes.preview(node, limit)]
|
|
||||||
except (sources.MissingAnswer, ValidationError) as e:
|
|
||||||
return Tested(ok=False, message=_missing(e))
|
|
||||||
except Exception as e: # noqa: BLE001
|
|
||||||
return Tested(ok=False, message=plain(e), detail=f"{type(e).__name__}: {e}"[:2000])
|
|
||||||
found = (
|
|
||||||
"Conexión correcta."
|
|
||||||
if rows
|
|
||||||
else (
|
|
||||||
"Se conectó, pero no encontró archivos ni filas. Revise la ruta y qué archivos tomar."
|
|
||||||
)
|
|
||||||
)
|
|
||||||
return Tested(ok=True, message=found, rows=rows)
|
|
||||||
|
|
||||||
|
|
||||||
def _missing(e: Exception) -> str:
|
|
||||||
if isinstance(e, ValidationError):
|
|
||||||
return next((str(err["ctx"]["error"]) for err in e.errors()
|
|
||||||
if isinstance(err.get("ctx", {}).get("error"), sources.MissingAnswer)),
|
|
||||||
str(e)) # fmt: skip
|
|
||||||
return str(e)
|
|
||||||
|
|
||||||
|
|
||||||
def roots() -> dict[str, Path]:
|
|
||||||
found = {"Subidos": (DATA_DIR / UPLOADS).resolve()}
|
|
||||||
for raw in filter(None, os.environ.get("SOURCE_ROOTS", "").split(os.pathsep)):
|
|
||||||
path = Path(raw).resolve()
|
|
||||||
found[path.name or str(path)] = path
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
class Entry(BaseModel):
|
|
||||||
name: str
|
|
||||||
path: str
|
|
||||||
kind: Literal["folder", "file"]
|
|
||||||
size: int | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class Browsed(BaseModel):
|
|
||||||
path: str | None
|
|
||||||
parent: str | None
|
|
||||||
entries: list[Entry]
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/sources/browse",
|
|
||||||
description=(
|
|
||||||
"The server folders a source may read: the roots, or what one "
|
|
||||||
"folder under them\n"
|
|
||||||
"holds. Nothing outside the roots is shown."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def browse(path: str | None = None) -> Browsed:
|
|
||||||
allowed = roots()
|
|
||||||
if path is None:
|
|
||||||
return Browsed(path=None, parent=None, entries=[
|
|
||||||
Entry(name=name, path=str(root), kind="folder")
|
|
||||||
for name, root in allowed.items() if root.is_dir()]) # fmt: skip
|
|
||||||
folder = Path(path).resolve()
|
|
||||||
root = next((r for r in allowed.values() if folder == r or r in folder.parents), None)
|
|
||||||
if root is None or not folder.is_dir():
|
|
||||||
raise HTTPException(404, detail="esa carpeta no está entre las habilitadas")
|
|
||||||
entries = sorted(
|
|
||||||
(Entry(name=p.name, path=str(p), kind="folder" if p.is_dir() else "file",
|
|
||||||
size=None if p.is_dir() else p.stat().st_size)
|
|
||||||
for p in folder.iterdir() if not p.name.startswith(".")),
|
|
||||||
key=lambda e: (e.kind != "folder", e.name.lower())) # fmt: skip
|
|
||||||
return Browsed(path=str(folder), parent=None if folder == root else str(folder.parent),
|
|
||||||
entries=entries) # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
class Uploaded(BaseModel):
|
|
||||||
bucket_url: str
|
|
||||||
files: list[str]
|
|
||||||
|
|
||||||
|
|
||||||
def _relative(name: str) -> PurePosixPath:
|
|
||||||
parts = [p for p in PurePosixPath(name.replace("\\", "/")).parts if p not in ("", ".", "..")]
|
|
||||||
if not parts:
|
|
||||||
raise HTTPException(422, detail="the file needs a name")
|
|
||||||
return PurePosixPath(*parts)
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/uploads",
|
|
||||||
description=(
|
|
||||||
"Files from the operator's computer (one, many, or a whole "
|
|
||||||
"folder), kept on the\n"
|
|
||||||
"server for a `filesystem` source; streamed to disk, so large "
|
|
||||||
"recordings fit. Send\n"
|
|
||||||
"`folder` from a previous answer to add to the same set."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def upload(files: list[UploadFile], folder: Annotated[str | None, Form()] = None) -> Uploaded:
|
|
||||||
base = (DATA_DIR / UPLOADS).resolve()
|
|
||||||
target = Path(folder).resolve() if folder else base / uuid.uuid4().hex[:12]
|
|
||||||
if target.parent != base:
|
|
||||||
raise HTTPException(422, detail="folder is not an upload set")
|
|
||||||
kept = []
|
|
||||||
for file in files:
|
|
||||||
relative = _relative(file.filename or "")
|
|
||||||
destination = target / relative
|
|
||||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
with destination.open("wb") as out:
|
|
||||||
shutil.copyfileobj(file.file, out, length=1 << 20)
|
|
||||||
kept.append(str(relative))
|
|
||||||
return Uploaded(bucket_url=str(target), files=kept)
|
|
||||||
|
|
||||||
|
|
||||||
PENDING = DATA_DIR / "oauth_pending"
|
|
||||||
PENDING_SECONDS = 600
|
|
||||||
STATE = re.compile(r"[A-Za-z0-9_-]{8,128}")
|
|
||||||
|
|
||||||
|
|
||||||
def _pend(state: str, pending: dict[str, Any]) -> None:
|
|
||||||
import json
|
|
||||||
import time
|
|
||||||
|
|
||||||
PENDING.mkdir(parents=True, exist_ok=True)
|
|
||||||
for old in PENDING.glob("*.json"):
|
|
||||||
if time.time() - old.stat().st_mtime > PENDING_SECONDS:
|
|
||||||
old.unlink(missing_ok=True)
|
|
||||||
path = PENDING / f"{state}.json"
|
|
||||||
path.write_text(json.dumps(pending))
|
|
||||||
path.chmod(0o600)
|
|
||||||
|
|
||||||
|
|
||||||
def _claimed(state: str) -> dict[str, Any] | None:
|
|
||||||
import json
|
|
||||||
import time
|
|
||||||
|
|
||||||
if not STATE.fullmatch(state):
|
|
||||||
return None
|
|
||||||
taken = PENDING / f"{state}.{uuid.uuid4().hex}.taken"
|
|
||||||
try:
|
|
||||||
(PENDING / f"{state}.json").rename(taken)
|
|
||||||
except FileNotFoundError:
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
fresh = time.time() - taken.stat().st_mtime <= PENDING_SECONDS
|
|
||||||
return json.loads(taken.read_text()) if fresh else None
|
|
||||||
finally:
|
|
||||||
taken.unlink(missing_ok=True)
|
|
||||||
|
|
||||||
|
|
||||||
def _registration(provider: str) -> tuple[sources.Provider, dict[str, str]]:
|
|
||||||
found = sources.catalog().providers.get(provider)
|
|
||||||
if found is None:
|
|
||||||
raise HTTPException(404, detail=f"no provider {provider}")
|
|
||||||
env = {k: os.environ.get(f"{found.env}_{k.upper()}", "")
|
|
||||||
for k in ("client_id", "client_secret", "tenant_id", "project_id")} # fmt: skip
|
|
||||||
if not (env["client_id"] and env["client_secret"]):
|
|
||||||
needed = f"{found.env}_CLIENT_ID y {found.env}_CLIENT_SECRET"
|
|
||||||
raise HTTPException(503, detail=(
|
|
||||||
f"Para iniciar sesión con {found.title}, el área de sistemas debe registrar la "
|
|
||||||
f"aplicación y darle al servidor {needed}.")) # fmt: skip
|
|
||||||
return found, env
|
|
||||||
|
|
||||||
|
|
||||||
def _endpoint(url: str, env: dict[str, str]) -> str:
|
|
||||||
return url.format(tenant=env["tenant_id"] or "organizations")
|
|
||||||
|
|
||||||
|
|
||||||
def _client(provider: sources.Provider, env: dict[str, str], redirect_uri: str):
|
|
||||||
from authlib.integrations.httpx_client import OAuth2Client
|
|
||||||
|
|
||||||
return OAuth2Client(env["client_id"], env["client_secret"], scope=provider.scope,
|
|
||||||
redirect_uri=redirect_uri, code_challenge_method="S256") # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
class SignIn(BaseModel):
|
|
||||||
url: str
|
|
||||||
state: str
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/sources/oauth/{provider}/start",
|
|
||||||
description=(
|
|
||||||
"The provider's sign-in address. `origin` is the web app's "
|
|
||||||
"(where the user returns:\n"
|
|
||||||
"`{origin}/api/…/callback`, the address IT registered)."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
def oauth_start(provider: str, origin: str) -> SignIn:
|
|
||||||
import secrets
|
|
||||||
|
|
||||||
found, env = _registration(provider)
|
|
||||||
redirect_uri = f"{origin.rstrip('/')}/api/ingest/sources/oauth/{provider}/callback"
|
|
||||||
verifier = secrets.token_urlsafe(48)
|
|
||||||
url, state = _client(found, env, redirect_uri).create_authorization_url(
|
|
||||||
_endpoint(found.authorize_url, env), code_verifier=verifier, **found.authorize_params
|
|
||||||
)
|
|
||||||
_pend(state, {"provider": provider, "verifier": verifier, "redirect_uri": redirect_uri,
|
|
||||||
"origin": origin.rstrip("/")}) # fmt: skip
|
|
||||||
return SignIn(url=url, state=state)
|
|
||||||
|
|
||||||
|
|
||||||
def account(provider: str, token: dict[str, Any], env: dict[str, str]) -> dict[str, Any]:
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
found = sources.catalog().providers[provider]
|
|
||||||
bearer = {"Authorization": f"Bearer {token['access_token']}"}
|
|
||||||
if provider == "microsoft":
|
|
||||||
me = httpx.get("https://graph.microsoft.com/v1.0/me", headers=bearer).json()
|
|
||||||
drive = httpx.get("https://graph.microsoft.com/v1.0/me/drive", headers=bearer).json()
|
|
||||||
return {
|
|
||||||
"user": me.get("mail") or me.get("userPrincipalName") or me.get("displayName"),
|
|
||||||
"drive_id": drive.get("id"),
|
|
||||||
"oauth2_client_params": {
|
|
||||||
"client_id": env["client_id"], "client_secret": env["client_secret"],
|
|
||||||
"token_endpoint": _endpoint(found.token_url, env), "scope": found.scope,
|
|
||||||
"token": token,
|
|
||||||
},
|
|
||||||
} # fmt: skip
|
|
||||||
about = httpx.get("https://www.googleapis.com/drive/v3/about", params={"fields": "user"},
|
|
||||||
headers=bearer).json() # fmt: skip
|
|
||||||
credentials = {"client_id": env["client_id"], "client_secret": env["client_secret"],
|
|
||||||
"refresh_token": token.get("refresh_token"),
|
|
||||||
"project_id": env["project_id"] or None} # fmt: skip
|
|
||||||
return {"user": about.get("user", {}).get("emailAddress"),
|
|
||||||
"credentials": {k: v for k, v in credentials.items() if v}} # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/sources/oauth/{provider}/callback", include_in_schema=False)
|
|
||||||
def oauth_callback(provider: str, state: str, code: str | None = None, error: str | None = None):
|
|
||||||
import json
|
|
||||||
|
|
||||||
from fastapi.responses import HTMLResponse
|
|
||||||
|
|
||||||
pending = _claimed(state)
|
|
||||||
if pending is None or pending["provider"] != provider:
|
|
||||||
return HTMLResponse("<p>La solicitud de inicio de sesión venció. Cierre esta ventana "
|
|
||||||
"e inténtelo de nuevo.</p>", status_code=400) # fmt: skip
|
|
||||||
message: dict[str, Any] = {"type": "isssteleon-oauth", "state": state}
|
|
||||||
if error or not code:
|
|
||||||
message["error"] = "No se completó el inicio de sesión."
|
|
||||||
else:
|
|
||||||
found, env = _registration(provider)
|
|
||||||
try:
|
|
||||||
token = _client(found, env, pending["redirect_uri"]).fetch_token(
|
|
||||||
_endpoint(found.token_url, env), code=code, code_verifier=pending["verifier"]
|
|
||||||
)
|
|
||||||
message["account"] = account(provider, dict(token), env)
|
|
||||||
except Exception as e: # noqa: BLE001
|
|
||||||
message["error"] = f"No se pudo iniciar sesión: {e}"
|
|
||||||
payload = json.dumps(message).replace("</", "<\\/")
|
|
||||||
target = json.dumps(pending["origin"])
|
|
||||||
return HTMLResponse(
|
|
||||||
"<!doctype html><meta charset=utf-8><title>ISSSTELEON</title>"
|
|
||||||
"<p>Listo. Puede cerrar esta ventana.</p>"
|
|
||||||
f"<script>window.opener&&window.opener.postMessage({payload},{target});"
|
|
||||||
"window.close()</script>"
|
|
||||||
)
|
|
||||||
-153
@@ -1,153 +0,0 @@
|
|||||||
import os
|
|
||||||
import secrets
|
|
||||||
import uuid
|
|
||||||
from collections.abc import AsyncIterator
|
|
||||||
from contextlib import asynccontextmanager
|
|
||||||
from functools import cache
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, FastAPI
|
|
||||||
from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin, schemas
|
|
||||||
from fastapi_users.authentication import AuthenticationBackend, CookieTransport, JWTStrategy
|
|
||||||
from fastapi_users.exceptions import UserAlreadyExists
|
|
||||||
from fastapi_users_db_sqlalchemy import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
|
|
||||||
from sqlalchemy import JSON, String, event, make_url, text
|
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
|
||||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
|
||||||
|
|
||||||
from core.domains import Domain
|
|
||||||
from persistance.config import DATA_DIR, platform_url
|
|
||||||
|
|
||||||
SESSION_HOURS = 10
|
|
||||||
SCHEMA = "config"
|
|
||||||
|
|
||||||
|
|
||||||
class Base(DeclarativeBase):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class User(SQLAlchemyBaseUserTableUUID, Base):
|
|
||||||
__tablename__ = "users"
|
|
||||||
__table_args__ = {"schema": SCHEMA}
|
|
||||||
name: Mapped[str] = mapped_column(String(120), default="")
|
|
||||||
domains: Mapped[list[str]] = mapped_column(JSON, default=list)
|
|
||||||
|
|
||||||
|
|
||||||
class UserRead(schemas.BaseUser[uuid.UUID]):
|
|
||||||
name: str = ""
|
|
||||||
domains: list[Domain] = []
|
|
||||||
|
|
||||||
|
|
||||||
class UserCreate(schemas.BaseUserCreate):
|
|
||||||
name: str = ""
|
|
||||||
domains: list[Domain] = []
|
|
||||||
|
|
||||||
|
|
||||||
@cache
|
|
||||||
def _engine():
|
|
||||||
url = make_url(platform_url())
|
|
||||||
if url.drivername.startswith("sqlite"):
|
|
||||||
engine = create_async_engine(url.set(drivername="sqlite+aiosqlite"))
|
|
||||||
|
|
||||||
@event.listens_for(engine.sync_engine, "connect")
|
|
||||||
def _attach(connection, _record):
|
|
||||||
path = DATA_DIR / f"platform__{SCHEMA}.db"
|
|
||||||
connection.execute(f"ATTACH DATABASE '{path}' AS {SCHEMA}")
|
|
||||||
|
|
||||||
return engine
|
|
||||||
return create_async_engine(url.set(drivername="postgresql+asyncpg"))
|
|
||||||
|
|
||||||
|
|
||||||
async def _session() -> AsyncIterator[AsyncSession]:
|
|
||||||
async with async_sessionmaker(_engine(), expire_on_commit=False)() as session:
|
|
||||||
yield session
|
|
||||||
|
|
||||||
|
|
||||||
async def _users(session: AsyncSession = Depends(_session)):
|
|
||||||
yield SQLAlchemyUserDatabase(session, User)
|
|
||||||
|
|
||||||
|
|
||||||
@cache
|
|
||||||
def _secret() -> str:
|
|
||||||
if found := os.environ.get("AUTH_SECRET"):
|
|
||||||
return found
|
|
||||||
path = DATA_DIR / "auth_secret"
|
|
||||||
if not path.exists():
|
|
||||||
path.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
path.write_text(secrets.token_urlsafe(48))
|
|
||||||
path.chmod(0o600)
|
|
||||||
return path.read_text().strip()
|
|
||||||
|
|
||||||
|
|
||||||
class Manager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
|
||||||
@property
|
|
||||||
def reset_password_token_secret(self) -> str: # type: ignore[override]
|
|
||||||
return _secret()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def verification_token_secret(self) -> str: # type: ignore[override]
|
|
||||||
return _secret()
|
|
||||||
|
|
||||||
|
|
||||||
async def _manager(users=Depends(_users)):
|
|
||||||
yield Manager(users)
|
|
||||||
|
|
||||||
|
|
||||||
backend = AuthenticationBackend(
|
|
||||||
name="cookie",
|
|
||||||
transport=CookieTransport(
|
|
||||||
cookie_name="isssteleon_session",
|
|
||||||
cookie_max_age=SESSION_HOURS * 3600,
|
|
||||||
cookie_secure=os.environ.get("AUTH_COOKIE_SECURE", "") == "1",
|
|
||||||
cookie_samesite="lax",
|
|
||||||
),
|
|
||||||
get_strategy=lambda: JWTStrategy(secret=_secret(), lifetime_seconds=SESSION_HOURS * 3600),
|
|
||||||
)
|
|
||||||
users = FastAPIUsers[User, uuid.UUID](_manager, [backend])
|
|
||||||
|
|
||||||
router = APIRouter()
|
|
||||||
router.include_router(users.get_auth_router(backend), prefix="/auth", tags=["auth"])
|
|
||||||
user_routes = users.get_users_router(UserRead, schemas.BaseUserUpdate)
|
|
||||||
user_routes.routes[:] = [
|
|
||||||
route for route in user_routes.routes if route.name == "users:current_user"
|
|
||||||
]
|
|
||||||
router.include_router(user_routes, prefix="/users", tags=["users"])
|
|
||||||
admins_only = [Depends(users.current_user(active=True, superuser=True))]
|
|
||||||
router.include_router(
|
|
||||||
users.get_register_router(UserRead, UserCreate),
|
|
||||||
prefix="/users",
|
|
||||||
tags=["users"],
|
|
||||||
dependencies=admins_only,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def first_admin() -> None:
|
|
||||||
async with _engine().begin() as connection:
|
|
||||||
if connection.dialect.name != "sqlite":
|
|
||||||
await connection.execute(text(f"create schema if not exists {SCHEMA}"))
|
|
||||||
await connection.run_sync(Base.metadata.create_all)
|
|
||||||
email, password = os.environ.get("AUTH_ADMIN_EMAIL"), os.environ.get("AUTH_ADMIN_PASSWORD")
|
|
||||||
if not (email and password):
|
|
||||||
return
|
|
||||||
async with async_sessionmaker(_engine(), expire_on_commit=False)() as session:
|
|
||||||
manager = Manager(SQLAlchemyUserDatabase(session, User))
|
|
||||||
try:
|
|
||||||
admin = UserCreate(email=email, password=password, is_superuser=True,
|
|
||||||
name="Administrador", domains=list(Domain)) # fmt: skip
|
|
||||||
await manager.create(admin)
|
|
||||||
except UserAlreadyExists:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
|
||||||
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
|
||||||
import fcntl
|
|
||||||
|
|
||||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
|
||||||
with open(DATA_DIR / "startup.lock", "w") as lock:
|
|
||||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
||||||
try:
|
|
||||||
_secret()
|
|
||||||
await first_admin()
|
|
||||||
finally:
|
|
||||||
fcntl.flock(lock, fcntl.LOCK_UN)
|
|
||||||
yield
|
|
||||||
Reference in New Issue
Block a user