Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 510000658b |
+3
-8
@@ -1,9 +1,4 @@
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
node_modules/
|
||||||
.venv/
|
dist/
|
||||||
.pytest_cache/
|
.angular/
|
||||||
.coverage
|
|
||||||
*.egg-info/
|
|
||||||
.env
|
|
||||||
uv.lock
|
|
||||||
*.db
|
|
||||||
|
|||||||
-24
@@ -1,24 +0,0 @@
|
|||||||
# 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"]
|
|
||||||
@@ -1,334 +0,0 @@
|
|||||||
# 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()`.
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
#!/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
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
from webapi import create_app
|
|
||||||
|
|
||||||
app = create_app()
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
app.run(host="0.0.0.0", port=5000)
|
|
||||||
+17
-19
@@ -1,28 +1,26 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "webapi"
|
name = "webapi"
|
||||||
version = "0.1.0"
|
version = "0.0.0"
|
||||||
description = "Flask REST API fronting Persistance (reads) and models (train/predict) for CaCu, CaMa and TEA."
|
description = "FastAPI: FHIR routes, control routes, the auth dependency."
|
||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"flask>=3.0",
|
"core",
|
||||||
"persistance",
|
"persistance",
|
||||||
"models",
|
"fastapi[standard]",
|
||||||
"indicadores-kit",
|
"dagster-graphql",
|
||||||
|
"authlib>=1.6",
|
||||||
|
"fastapi-users[sqlalchemy]>=15",
|
||||||
|
"aiosqlite>=0.20",
|
||||||
|
"asyncpg>=0.30",
|
||||||
]
|
]
|
||||||
|
|
||||||
[tool.uv.sources]
|
|
||||||
persistance = { path = "../Persistance", editable = true }
|
|
||||||
models = { path = "../models", editable = true }
|
|
||||||
indicadores-kit = { path = "../indicadores_kit", editable = true }
|
|
||||||
|
|
||||||
[build-system]
|
[build-system]
|
||||||
requires = ["hatchling"]
|
requires = ["uv_build>=0.12,<0.13"]
|
||||||
build-backend = "hatchling.build"
|
build-backend = "uv_build"
|
||||||
|
|
||||||
[tool.hatch.build.targets.wheel]
|
[tool.uv.build-backend]
|
||||||
packages = ["webapi"]
|
module-name = "webapi"
|
||||||
|
module-root = ""
|
||||||
[dependency-groups]
|
[tool.uv.sources]
|
||||||
dev = [
|
core = { workspace = true }
|
||||||
"pytest>=8.0.0",
|
persistance = { workspace = true }
|
||||||
]
|
|
||||||
|
|||||||
@@ -1,43 +0,0 @@
|
|||||||
"""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()
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
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,228 +0,0 @@
|
|||||||
"""Rutas de indicadores de CACU: base SQLite temporal sembrada con los fixtures del kit."""
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from conftest import MESES, SEMESTRES, cliente_de
|
|
||||||
from indicadores_kit.registry.measures import 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()
|
|
||||||
@@ -1,215 +0,0 @@
|
|||||||
"""Rutas de indicadores de CAMA: base SQLite temporal sembrada con los fixtures del kit."""
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from conftest import MESES, SEMESTRES, cliente_de
|
|
||||||
from indicadores_kit.registry.measures import 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 y cama_eu8 no se muestran."""
|
|
||||||
ocultos = {"cama_confirmacion_birads45", "cama_eu8"}
|
|
||||||
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,163 +0,0 @@
|
|||||||
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): K01, K08, M04 y M15 no se muestran; quedan 16 en el catálogo."""
|
|
||||||
ocultos = {"K01_evaluacion_3_meses", "K08_eeg_sueno", "M04_dias_entrevista_ados2", "M15_grado_hipoacusia"}
|
|
||||||
ids = {fila["id"] for fila in client.get("/tea/indicadores").get_json()}
|
|
||||||
|
|
||||||
assert len(ids) == 16
|
|
||||||
assert not ids & ocultos
|
|
||||||
assert {"M21_diagnosticados_con_eeg", "M22_diagnosticados_sin_eeg"} <= ids
|
|
||||||
assert client.get("/tea/indicadores/K01_evaluacion_3_meses/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,19 +1 @@
|
|||||||
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
|
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Caller:
|
||||||
|
id: str = "anonymous"
|
||||||
|
|
||||||
|
|
||||||
|
def caller() -> Caller:
|
||||||
|
return Caller()
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
from fastapi import APIRouter, HTTPException
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from persistance import eeg
|
||||||
|
|
||||||
|
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 Site(BaseModel):
|
||||||
|
site: str
|
||||||
|
value: float
|
||||||
|
z: float | None
|
||||||
|
|
||||||
|
|
||||||
|
class Metric(BaseModel):
|
||||||
|
code: str
|
||||||
|
value: float
|
||||||
|
z: float | None
|
||||||
|
outside: float | None
|
||||||
|
p5: float | None = None
|
||||||
|
median: float | None = None
|
||||||
|
p95: float | None = None
|
||||||
|
model: str | None
|
||||||
|
zones: list[Site] = []
|
||||||
|
electrodes: list[Site] = []
|
||||||
|
|
||||||
|
|
||||||
|
class Relation(BaseModel):
|
||||||
|
biomarker: str
|
||||||
|
metric: str
|
||||||
|
zone: str
|
||||||
|
outcome_code: str
|
||||||
|
kind: str
|
||||||
|
event: str
|
||||||
|
z: float
|
||||||
|
probability: float
|
||||||
|
reference_probability: float
|
||||||
|
observed: float | None = None
|
||||||
|
odds_ratio: float
|
||||||
|
ci_low: float | None
|
||||||
|
ci_high: float | None
|
||||||
|
q: float | None
|
||||||
|
n: float
|
||||||
|
model: str
|
||||||
|
|
||||||
|
|
||||||
|
class Analysis(BaseModel):
|
||||||
|
id: str
|
||||||
|
valid: bool | None
|
||||||
|
level: str | None
|
||||||
|
age_months: float | None
|
||||||
|
metrics: list[Metric]
|
||||||
|
relation: list[Relation] = []
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def studies() -> list[Study]:
|
||||||
|
return [Study(**s) for s in eeg.studies()]
|
||||||
|
|
||||||
|
|
||||||
|
@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)
|
||||||
+552
@@ -0,0 +1,552 @@
|
|||||||
|
import unicodedata
|
||||||
|
from datetime import date, datetime
|
||||||
|
from typing import Annotated, Any
|
||||||
|
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.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 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,
|
||||||
|
}
|
||||||
|
return Response(
|
||||||
|
OperationOutcome(issue=[issue]).model_dump_json(exclude_none=True),
|
||||||
|
status_code=status,
|
||||||
|
media_type=FHIR_JSON,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
base = str(request.base_url).rstrip("/") + request.url.path.rsplit("/", 1)[0]
|
||||||
|
|
||||||
|
def link(relation: str, at: int) -> dict:
|
||||||
|
url = request.url.include_query_params(**applied or {}, _offset=at, _count=count)
|
||||||
|
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
|
||||||
|
]
|
||||||
|
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]
|
||||||
|
|
||||||
|
|
||||||
|
@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"])
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _folded(text: str) -> str:
|
||||||
|
return "".join(
|
||||||
|
(c for c in unicodedata.normalize("NFKD", text.casefold()) if not unicodedata.combining(c))
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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"]
|
||||||
|
)
|
||||||
|
):
|
||||||
|
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"]
|
||||||
|
)
|
||||||
|
):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/Patient", responses=_OK, response_class=Response)
|
||||||
|
def search_patient(
|
||||||
|
request: Request,
|
||||||
|
domain: Domain,
|
||||||
|
_id: str | None = Query(None, alias="_id"),
|
||||||
|
window: int | None = Query(
|
||||||
|
None,
|
||||||
|
alias="follow-up-window",
|
||||||
|
description="months: the domain's follow-up list over that window up to the cut-off",
|
||||||
|
),
|
||||||
|
cutoff: date | None = Query(
|
||||||
|
None, alias="follow-up-cutoff", description="default: the last day with data"
|
||||||
|
),
|
||||||
|
status: str | None = Query(None, alias="follow-up-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
|
||||||
|
persons_rows = reads.rows(domain.value, "persons")
|
||||||
|
if window is None:
|
||||||
|
rows = [{**r, "status": fu.status(r, at)} for r in persons_rows]
|
||||||
|
else:
|
||||||
|
if window not in fu.WINDOWS:
|
||||||
|
raise HTTPException(422, f"follow-up-window is one of {fu.WINDOWS}")
|
||||||
|
if sort not in fu.SORTS:
|
||||||
|
raise HTTPException(422, f"_sort is one of {fu.SORTS}")
|
||||||
|
start = window_start(at, window)
|
||||||
|
params = {"start": start.isoformat(), "cutoff": at.isoformat()}
|
||||||
|
person = {r["person_id"]: r for r in persons_rows}
|
||||||
|
rows = [
|
||||||
|
{**person[r["person_id"]], **r}
|
||||||
|
for r in fu.listed(reads.rows(domain.value, "follow_up", **params), start, at)
|
||||||
|
]
|
||||||
|
if _id:
|
||||||
|
rows = [r for r in rows if r["person_id"] in _id.split(",")]
|
||||||
|
if status:
|
||||||
|
rows = [r for r in rows if r["status"] in status.split(",")]
|
||||||
|
if name or identifier:
|
||||||
|
found = {
|
||||||
|
r["person_id"] for r in _with_identity(domain, rows) if _matches(r, name, identifier)
|
||||||
|
}
|
||||||
|
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 window is not None and sort != "-recent" or "RiskAssessment:subject" in revinclude:
|
||||||
|
for r in reads.rows(domain.value, "risk", persons=persons):
|
||||||
|
risks.setdefault(r["person_id"], []).append(r)
|
||||||
|
if window is not None:
|
||||||
|
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}
|
||||||
|
)
|
||||||
|
applied = {"follow-up-cutoff": at.isoformat()} if window is not None else None
|
||||||
|
patients = [f.patient(r, fu.STATUS_SYSTEM) for r in _with_identity(domain, page)]
|
||||||
|
return bundle(request, patients, len(rows), count, offset, included, applied)
|
||||||
|
|
||||||
|
|
||||||
|
def _included(
|
||||||
|
domain: Domain,
|
||||||
|
revinclude: list[str],
|
||||||
|
include: list[str],
|
||||||
|
persons: list[str],
|
||||||
|
at: date,
|
||||||
|
risks: dict[str, list[dict]],
|
||||||
|
) -> list[Resource]:
|
||||||
|
unknown = set(revinclude) - set(REVINCLUDES) | 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 "RiskAssessment:subject" in revinclude:
|
||||||
|
found += _risk_assessments([r for p in persons for r in risks.get(p, [])])
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
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}
|
||||||
|
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))]
|
||||||
|
found += f.instance(study, f.known(study, row, at), extra)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
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:
|
||||||
|
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)
|
||||||
|
def search_encounter(
|
||||||
|
request: Request,
|
||||||
|
domain: Domain,
|
||||||
|
subject: str | None = Query(None, description=SUBJECT),
|
||||||
|
_count: int | None = Query(None),
|
||||||
|
_offset: int = Query(0),
|
||||||
|
) -> Response:
|
||||||
|
return _study_search("Encounter", request, domain, subject, _count, _offset)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/Observation", responses=_OK, response_class=Response)
|
||||||
|
def search_observation(
|
||||||
|
request: Request,
|
||||||
|
domain: Domain,
|
||||||
|
subject: str | None = Query(None, description=SUBJECT),
|
||||||
|
_count: int | None = Query(None),
|
||||||
|
_offset: int = Query(0),
|
||||||
|
) -> Response:
|
||||||
|
return _study_search("Observation", request, domain, subject, _count, _offset)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/Condition", responses=_OK, response_class=Response)
|
||||||
|
def search_condition(
|
||||||
|
request: Request,
|
||||||
|
domain: Domain,
|
||||||
|
subject: str | None = Query(None, description=SUBJECT),
|
||||||
|
_count: int | None = Query(None),
|
||||||
|
_offset: int = Query(0),
|
||||||
|
) -> Response:
|
||||||
|
|
||||||
|
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)
|
||||||
|
def search_procedure(
|
||||||
|
request: Request,
|
||||||
|
domain: Domain,
|
||||||
|
subject: str | None = Query(None, description=SUBJECT),
|
||||||
|
_count: int | None = Query(None),
|
||||||
|
_offset: int = Query(0),
|
||||||
|
) -> Response:
|
||||||
|
|
||||||
|
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)
|
||||||
|
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:
|
||||||
|
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)
|
||||||
|
def search_measure(
|
||||||
|
request: Request, domain: Domain, _count: int | None = Query(None), _offset: int = Query(0)
|
||||||
|
) -> Response:
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
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
|
||||||
|
]
|
||||||
|
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)
|
||||||
|
def metadata(request: Request, domain: Domain) -> Response:
|
||||||
|
resources: dict[str, dict] = {}
|
||||||
|
system: list[dict] = []
|
||||||
|
clinical = part(domain, "follow_up") 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)):
|
||||||
|
continue
|
||||||
|
entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []})
|
||||||
|
if kind == "Patient" and (not rest):
|
||||||
|
entry |= {
|
||||||
|
"searchInclude": ["DiagnosticReport:result"],
|
||||||
|
"searchRevInclude": list(REVINCLUDES),
|
||||||
|
}
|
||||||
|
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 {}),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
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 {}),
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return fhir(statement)
|
||||||
|
|
||||||
|
|
||||||
|
_STANDARD = {
|
||||||
|
"_id": "token",
|
||||||
|
"subject": "reference",
|
||||||
|
"measure": "reference",
|
||||||
|
"name": "string",
|
||||||
|
"identifier": "token",
|
||||||
|
}
|
||||||
@@ -1,199 +0,0 @@
|
|||||||
"""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
|
|
||||||
)
|
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
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, ImportPath, 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:
|
||||||
|
raise HTTPException(422, detail=f"{type(e).__name__}: {e}") from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/schema")
|
||||||
|
def schema() -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"pipeline": Pipeline.model_json_schema(),
|
||||||
|
"entities": {name: model.model_json_schema() for name, model in ENTITIES.items()},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class SourceRef(BaseModel):
|
||||||
|
source: ImportPath
|
||||||
|
args: dict[str, Any] = {}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/sources/resources")
|
||||||
|
def source_resources(ref: SourceRef) -> list[str]:
|
||||||
|
return _from_source(nodes.resources, ref.source, ref.args)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/sources/preview")
|
||||||
|
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}")
|
||||||
|
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}")
|
||||||
|
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")
|
||||||
|
def concept_maps() -> Rows:
|
||||||
|
return config_log.listing("concept_maps")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/concept-maps/{map_id}")
|
||||||
|
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}")
|
||||||
|
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")
|
||||||
|
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")
|
||||||
|
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
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
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, fhir, ingest, models, 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(models.router)
|
||||||
|
app.include_router(eeg.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)
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import mimetypes
|
||||||
|
from datetime import date
|
||||||
|
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, UploadFile
|
||||||
|
from fastapi.responses import Response
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from core.domains import Domain
|
||||||
|
from core.models import title
|
||||||
|
from persistance import registry
|
||||||
|
from webapi.runs import dagster
|
||||||
|
|
||||||
|
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]
|
||||||
|
|
||||||
|
|
||||||
|
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}/{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,
|
||||||
|
)
|
||||||
|
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}"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{domain}/{name}/versions/{version}/reports/clinical_validation")
|
||||||
|
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(),
|
||||||
|
)
|
||||||
|
return {"reports": sorted(registry.reports(f"{domain.value}.{name}", version))}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{domain}/{name}/versions/{version}/promote")
|
||||||
|
def promote(domain: Domain, name: str, version: int) -> dict:
|
||||||
|
try:
|
||||||
|
registry.promote(f"{domain.value}.{name}", version)
|
||||||
|
except registry.MissingReports as e:
|
||||||
|
raise HTTPException(409, detail=str(e)) from e
|
||||||
|
return {"champion": version}
|
||||||
|
|
||||||
|
|
||||||
|
class Training(BaseModel):
|
||||||
|
as_of: date | None = None
|
||||||
|
models: list[str] = []
|
||||||
|
|
||||||
|
|
||||||
|
def _submit(client: DagsterGraphQLClient, job: str, op: str, config: dict) -> dict[str, str]:
|
||||||
|
try:
|
||||||
|
run_id = client.submit_job_execution(job, run_config={"ops": {op: {"config": config}}})
|
||||||
|
except DagsterGraphQLClientError as e:
|
||||||
|
raise HTTPException(502, detail=str(e)) from e
|
||||||
|
return {"run_id": run_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{domain}/train")
|
||||||
|
def train(
|
||||||
|
domain: Domain, request: Training, client: DagsterGraphQLClient = Depends(dagster)
|
||||||
|
) -> dict[str, str]:
|
||||||
|
config: dict = {"domain": domain.value}
|
||||||
|
if request.as_of:
|
||||||
|
config["as_of"] = request.as_of.isoformat()
|
||||||
|
if request.models:
|
||||||
|
config["models"] = request.models
|
||||||
|
return _submit(client, "train", "train_models", config)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{domain}/analyze")
|
||||||
|
def analyze(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||||
|
return _submit(client, "analyze", "analyze_studies", {"domain": domain.value})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{domain}/score")
|
||||||
|
def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||||
|
return _submit(client, "score", "score_models", {"domain": domain.value})
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import json
|
||||||
|
from webapi.main import app
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print(json.dumps(app.openapi(), indent=1, sort_keys=True))
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
from typing import Any
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
from pydantic import BaseModel, 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")
|
||||||
|
def held(entity: EntityName) -> Rows:
|
||||||
|
return review.held(entity)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/conflicts")
|
||||||
|
def conflicts(entity: EntityName) -> Rows:
|
||||||
|
return review.conflicts(entity)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/unrecognised")
|
||||||
|
def unrecognised(pipeline: Id) -> Rows:
|
||||||
|
return review.unrecognised(pipeline)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/persons")
|
||||||
|
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)
|
||||||
|
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):
|
||||||
|
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
|
||||||
|
]
|
||||||
|
if reasons:
|
||||||
|
raise ValueError("; ".join(reasons))
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/corrections", status_code=201)
|
||||||
|
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)
|
||||||
|
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}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import os
|
||||||
|
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/runs", tags=["runs"])
|
||||||
|
|
||||||
|
|
||||||
|
def dagster() -> DagsterGraphQLClient:
|
||||||
|
return DagsterGraphQLClient(
|
||||||
|
os.environ.get("DAGSTER_HOST", "localhost"),
|
||||||
|
port_number=int(os.environ.get("DAGSTER_PORT", "3000")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{run_id}")
|
||||||
|
def run_status(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||||
|
try:
|
||||||
|
return {"id": run_id, "status": client.get_run_status(run_id).value}
|
||||||
|
except DagsterGraphQLClientError as e:
|
||||||
|
raise HTTPException(404 if "RunNotFound" in str(e) else 502, detail=str(e)) from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{run_id}/terminate")
|
||||||
|
def terminate_run(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||||
|
try:
|
||||||
|
client.terminate_run(run_id)
|
||||||
|
return {"id": run_id, "status": client.get_run_status(run_id).value}
|
||||||
|
except DagsterGraphQLClientError as e:
|
||||||
|
raise HTTPException(404 if "RunNotFound" in str(e) else 409, detail=str(e)) from e
|
||||||
@@ -0,0 +1,370 @@
|
|||||||
|
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")
|
||||||
|
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 = [
|
||||||
|
(
|
||||||
|
"login failed|password authentication failed|access denied|authentication|401|403|permission denied|invalid credentials",
|
||||||
|
"El usuario o la contraseña no son correctos, o no tiene permiso.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"name or service not known|could not translate host|nodename nor servname|getaddrinfo|unknown host|no such host|resolve",
|
||||||
|
"No se encontró el servidor. Revise el nombre o la dirección.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"timed out|timeout|connection refused|unable to connect|adaptive server is unavailable|could not connect|connection reset",
|
||||||
|
"El servidor no respondió. Revise la dirección, el puerto o si está encendido.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"database .* does not exist|cannot open database|unknown database",
|
||||||
|
"No existe esa base de datos en el servidor.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"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).",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
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},
|
||||||
|
}
|
||||||
|
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")
|
||||||
|
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)
|
||||||
|
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:
|
||||||
|
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),
|
||||||
|
)
|
||||||
|
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")
|
||||||
|
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()
|
||||||
|
],
|
||||||
|
)
|
||||||
|
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()),
|
||||||
|
)
|
||||||
|
return Browsed(
|
||||||
|
path=str(folder), parent=None if folder == root else str(folder.parent), entries=entries
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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")
|
||||||
|
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("[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(384)
|
||||||
|
|
||||||
|
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
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 aplicación y darle al servidor {needed}.",
|
||||||
|
)
|
||||||
|
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",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class SignIn(BaseModel):
|
||||||
|
url: str
|
||||||
|
state: str
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/sources/oauth/{provider}/start")
|
||||||
|
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("/"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
about = httpx.get(
|
||||||
|
"https://www.googleapis.com/drive/v3/about", params={"fields": "user"}, headers=bearer
|
||||||
|
).json()
|
||||||
|
credentials = {
|
||||||
|
"client_id": env["client_id"],
|
||||||
|
"client_secret": env["client_secret"],
|
||||||
|
"refresh_token": token.get("refresh_token"),
|
||||||
|
"project_id": env["project_id"] or None,
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
"user": about.get("user", {}).get("emailAddress"),
|
||||||
|
"credentials": {k: v for k, v in credentials.items() if v},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@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,
|
||||||
|
)
|
||||||
|
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:
|
||||||
|
message["error"] = f"No se pudo iniciar sesión: {e}"
|
||||||
|
payload = json.dumps(message).replace("</", "<\\/")
|
||||||
|
target = json.dumps(pending["origin"])
|
||||||
|
return HTMLResponse(
|
||||||
|
f"<!doctype html><meta charset=utf-8><title>ISSSTELEON</title><p>Listo. Puede cerrar esta ventana.</p><script>window.opener&&window.opener.postMessage({payload},{target});window.close()</script>"
|
||||||
|
)
|
||||||
+157
@@ -0,0 +1,157 @@
|
|||||||
|
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] = []
|
||||||
|
|
||||||
|
|
||||||
|
class UserUpdate(schemas.BaseUserUpdate):
|
||||||
|
name: str | None = None
|
||||||
|
domains: list[Domain] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@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(384)
|
||||||
|
return path.read_text().strip()
|
||||||
|
|
||||||
|
|
||||||
|
class Manager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
||||||
|
@property
|
||||||
|
def reset_password_token_secret(self) -> str:
|
||||||
|
return _secret()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def verification_token_secret(self) -> str:
|
||||||
|
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])
|
||||||
|
current_user = users.current_user(active=True)
|
||||||
|
router = APIRouter()
|
||||||
|
router.include_router(users.get_auth_router(backend), prefix="/auth", tags=["auth"])
|
||||||
|
router.include_router(users.get_users_router(UserRead, UserUpdate), 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),
|
||||||
|
)
|
||||||
|
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