Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9c260ed3f5 | |||
| ddb2f3f958 | |||
| af054460b5 | |||
| 6452e43cad | |||
| b0b797ac15 | |||
| 0e6494f053 |
@@ -0,0 +1,9 @@
|
|||||||
|
# Acceso a fecha de nacimiento de CaCu
|
||||||
|
|
||||||
|
`GET /cacu/seguimiento/pacientes/<pac_id>/demografia` consulta la persona en la base CaCu configurada y devuelve únicamente `pac_id` y `fecha_nacimiento` (fecha ISO o `null`). Un identificador inexistente responde 404.
|
||||||
|
|
||||||
|
El endpoint no implementa autenticación ni autorización propias y expone información demográfica individual a quien pueda acceder a WebApi. La protección de acceso, si se requiere, debe aplicarse en la instalación que lo publique.
|
||||||
|
|
||||||
|
La ruta individual de tamizaje API-02 utiliza la persistencia configurada. El equipo responsable deberá establecer los controles de acceso individual apropiados antes de utilizar datos personales reales; no se ha implementado autenticación específica de endpoints en esta intervención.
|
||||||
|
|
||||||
|
Actualmente el contrato de seguimiento emite `simulado: true` de manera incondicional, incluso cuando consulta la persistencia configurada. Esta marca no permite identificar la procedencia real de cada registro; no se modifica su valor aquí.
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
"""Cover the bundle HTTP contract with an app client and two temporary registries.
|
||||||
|
|
||||||
|
Fails if export loses ZIP metadata, import misreports registry versions or malformed uploads succeed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import zipfile
|
||||||
|
from dataclasses import replace
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
import mlflow
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
from flask import Flask
|
||||||
|
from models.io.registry import PRODUCTION_ALIAS
|
||||||
|
from models.tea.eeg import bundle, train
|
||||||
|
from models.tea.eeg.analyze import ReferenceStudy, pipeline
|
||||||
|
from models.tea.eeg.settings import settings
|
||||||
|
|
||||||
|
from webapi.blueprints.governance import governance_bp
|
||||||
|
from webapi.tea import baselines
|
||||||
|
|
||||||
|
BASELINES = "/governance/tea/baselines"
|
||||||
|
SCENARIO = "eeg-posterior-rhythm"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client():
|
||||||
|
"""Mount the governance routes so changes to route registration or error handling surface in HTTP."""
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.config.update(TESTING=True)
|
||||||
|
app.register_blueprint(governance_bp, url_prefix="/governance")
|
||||||
|
return app.test_client()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def trained_registries(tmp_path, monkeypatch):
|
||||||
|
"""Train one synthetic baseline in SQLite and provide an empty destination to expose failed transfers."""
|
||||||
|
config = settings()
|
||||||
|
metric = next(metric for metric in config.metrics if metric.scenario == SCENARIO)
|
||||||
|
config = replace(config, metrics=(metric,))
|
||||||
|
monkeypatch.setattr(baselines, "settings", lambda: config)
|
||||||
|
monkeypatch.chdir(tmp_path)
|
||||||
|
previous_uri = mlflow.get_tracking_uri()
|
||||||
|
|
||||||
|
def use_store(name):
|
||||||
|
uri = f"sqlite:///{tmp_path / f'{name}.db'}"
|
||||||
|
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
|
||||||
|
mlflow.set_tracking_uri(uri)
|
||||||
|
|
||||||
|
try:
|
||||||
|
use_store("source")
|
||||||
|
biomarker, phase = config.scenarios[SCENARIO]
|
||||||
|
features = pipeline(config).module(biomarker).features
|
||||||
|
rng = np.random.default_rng(0)
|
||||||
|
ages = np.linspace(16, 36, 100)
|
||||||
|
found = train.Listing.of("source", [(f"/synthetic/{k}.edf", float(age)) for k, age in enumerate(ages)])
|
||||||
|
studies = [
|
||||||
|
ReferenceStudy(key, age, 1, {
|
||||||
|
(biomarker, phase): {feature: float(1 + 0.02 * age + rng.normal(0, 0.1)) for feature in features},
|
||||||
|
})
|
||||||
|
for key, _, age in found.studies
|
||||||
|
]
|
||||||
|
train.train_all(config, "PROD", found=found, studies=studies)
|
||||||
|
yield use_store
|
||||||
|
finally:
|
||||||
|
mlflow.set_tracking_uri(previous_uri)
|
||||||
|
|
||||||
|
|
||||||
|
def test_export_and_import_baselines(client, trained_registries, monkeypatch):
|
||||||
|
"""Pin ZIP headers, cleanup and registry transfer. Fail if repeats register another version."""
|
||||||
|
real_export = bundle.export
|
||||||
|
export_paths = []
|
||||||
|
|
||||||
|
def capture_export(config, path, **kwargs):
|
||||||
|
export_paths.append(path)
|
||||||
|
return real_export(config, path, **kwargs)
|
||||||
|
|
||||||
|
monkeypatch.setattr(bundle, "export", capture_export)
|
||||||
|
with client.get(f"{BASELINES}/export?environment=prod&production=0") as response:
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.mimetype == "application/zip"
|
||||||
|
assert response.headers["Content-Disposition"] == "attachment; filename=baselines.zip"
|
||||||
|
assert response.headers["X-Baselines-Versions"] == "1"
|
||||||
|
assert export_paths[0].is_file()
|
||||||
|
archive = response.data
|
||||||
|
sha256 = hashlib.sha256(archive).hexdigest()
|
||||||
|
assert response.headers["X-Baselines-Sha256"] == sha256
|
||||||
|
assert not export_paths[0].exists()
|
||||||
|
with zipfile.ZipFile(BytesIO(archive)) as exported:
|
||||||
|
manifest = json.loads(exported.read(bundle.MANIFEST))
|
||||||
|
assert list(manifest["escenarios"]) == [SCENARIO]
|
||||||
|
|
||||||
|
model = train.latest(SCENARIO, "PROD")
|
||||||
|
mlflow.MlflowClient().set_registered_model_alias(model.name, PRODUCTION_ALIAS, model.version)
|
||||||
|
with client.get(f"{BASELINES}/export?environment=dev&production=1") as response:
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.data == archive
|
||||||
|
assert not export_paths[1].exists()
|
||||||
|
|
||||||
|
trained_registries("destination")
|
||||||
|
response = client.post(f"{BASELINES}/import", data={"file": (BytesIO(archive), "baselines.zip")})
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json == {"sha256": sha256, "imported": [{"scenario": SCENARIO, "version": 1}]}
|
||||||
|
assert train.latest(SCENARIO, "PROD").tags[bundle.BUNDLE_TAG] == sha256
|
||||||
|
|
||||||
|
duplicate = client.post(f"{BASELINES}/import", data={"file": (BytesIO(archive), "baselines.zip")})
|
||||||
|
assert duplicate.status_code == 409
|
||||||
|
assert duplicate.json["error"]
|
||||||
|
versions = mlflow.MlflowClient().search_model_versions(f"name = '{model.name}'")
|
||||||
|
assert [int(version.version) for version in versions] == [1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_rejects_garbage(client):
|
||||||
|
"""Pin a JSON 400 for non-ZIP bytes. Fail if the ZIP exception becomes a server error."""
|
||||||
|
response = client.post(f"{BASELINES}/import", data={"file": (BytesIO(b"garbage"), "baselines.zip")})
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json["error"]
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""Cover the cluster route with cluster_client and monkeypatched network probes.
|
||||||
|
|
||||||
|
Fails if an unapproved scheduler is probed or health results use the wrong HTTP status.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
import distributed
|
||||||
|
import pytest
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
from tea.pipeline import cluster_status
|
||||||
|
from webapi.blueprints.governance import governance_bp
|
||||||
|
|
||||||
|
CLUSTER_URL = "/governance/tea/cluster"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def cluster_client(monkeypatch):
|
||||||
|
"""Mount the governance blueprint with clean config so machine defaults cannot affect routing."""
|
||||||
|
for variable in ("DASK_SCHEDULER_ADDRESS", "TEA_DASK_SCHEDULERS"):
|
||||||
|
monkeypatch.delenv(variable, raising=False)
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.register_blueprint(governance_bp, url_prefix="/governance")
|
||||||
|
return app.test_client()
|
||||||
|
|
||||||
|
|
||||||
|
def test_rejects_scheduler_outside_allow_list(cluster_client, monkeypatch):
|
||||||
|
"""Pin allow-list enforcement. Fail if an arbitrary scheduler reaches a network probe."""
|
||||||
|
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://default:8786")
|
||||||
|
monkeypatch.setenv("TEA_DASK_SCHEDULERS", "tcp://backup:8786")
|
||||||
|
probe = Mock()
|
||||||
|
monkeypatch.setattr(cluster_status.ClusterStatus, "check", probe)
|
||||||
|
|
||||||
|
response = cluster_client.get(CLUSTER_URL, query_string={"scheduler": "tcp://other:8786"})
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json["error"]
|
||||||
|
probe.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", ["invalid", "remote"])
|
||||||
|
def test_rejects_invalid_cluster_choice(cluster_client, mode):
|
||||||
|
"""Pin validation errors. Fail if an unknown mode or addressless remote request succeeds."""
|
||||||
|
response = cluster_client.get(CLUSTER_URL, query_string={"mode": mode})
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json["error"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_local_mode_reports_reachable(cluster_client):
|
||||||
|
"""Pin local status serialization. Fail if local checks start reporting remote details."""
|
||||||
|
response = cluster_client.get(CLUSTER_URL, query_string={"mode": "local"})
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json["mode"] == "local"
|
||||||
|
assert response.json["reachable"] is True
|
||||||
|
assert response.json["scheduler"] is None
|
||||||
|
assert response.json["workers"] is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("scheduler", ["tcp://backup:8786", "tcp://default:8786"])
|
||||||
|
def test_unreachable_approved_scheduler_returns_health(cluster_client, monkeypatch, scheduler):
|
||||||
|
"""Pin HTTP 200 on connection failure. Fail if either approval source rejects its address."""
|
||||||
|
connect = Mock(side_effect=OSError("connection refused"))
|
||||||
|
monkeypatch.setattr(distributed, "Client", connect)
|
||||||
|
monkeypatch.setattr(cluster_status, "urlopen", Mock(side_effect=OSError))
|
||||||
|
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://default:8786")
|
||||||
|
monkeypatch.setenv("TEA_DASK_SCHEDULERS", "tcp://first:8786, tcp://backup:8786 ")
|
||||||
|
|
||||||
|
response = cluster_client.get(CLUSTER_URL, query_string={"scheduler": scheduler})
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json["mode"] == "remote"
|
||||||
|
assert response.json["scheduler"] == scheduler
|
||||||
|
assert response.json["reachable"] is False
|
||||||
|
assert response.json["error"] == "connection refused"
|
||||||
|
connect.assert_called_once_with(scheduler, timeout=5)
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
"""Cover cohort metadata, uploads and request errors using a temporary root and the app client.
|
||||||
|
|
||||||
|
Fails if the API accepts unsafe files, bypasses the upload limit or loses stored metadata.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from webapi import create_app
|
||||||
|
|
||||||
|
COHORTS = "/governance/tea/reference-cohorts"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def cohort_client(tmp_path, monkeypatch):
|
||||||
|
"""Wire the app to a temporary root so escaped writes and metadata errors are observable."""
|
||||||
|
root = tmp_path / "reference"
|
||||||
|
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(root))
|
||||||
|
app = create_app()
|
||||||
|
app.config.update(TESTING=True)
|
||||||
|
return app.test_client(), root
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_reference_cohorts(cohort_client):
|
||||||
|
"""Pin nested EDF counts and age-table metadata. Fail if either is omitted."""
|
||||||
|
client, root = cohort_client
|
||||||
|
cohort = root / "reference-1"
|
||||||
|
nested = cohort / "2026"
|
||||||
|
nested.mkdir(parents=True)
|
||||||
|
(root / "empty").mkdir()
|
||||||
|
(root / "loose.edf").write_bytes(b"loose")
|
||||||
|
(cohort / "study.edf").write_bytes(b"edf")
|
||||||
|
(nested / "second.EDF").write_bytes(b"second")
|
||||||
|
(cohort / "edades.csv").write_bytes(b"ages")
|
||||||
|
|
||||||
|
response = client.get(COHORTS)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json == [
|
||||||
|
{"name": "empty", "edfs": 0, "size_bytes": 0, "has_ages": False, "path": str(root / "empty")},
|
||||||
|
{"name": "reference-1", "edfs": 2, "size_bytes": 13, "has_ages": True, "path": str(cohort)},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("filename", ["study.edf", "edades.csv"])
|
||||||
|
def test_upload_reference_file(cohort_client, filename):
|
||||||
|
"""Pin each permitted upload and the stored bytes. Fail if the upload leaves a staging file."""
|
||||||
|
client, root = cohort_client
|
||||||
|
payload = b"reference data"
|
||||||
|
response = client.post(f"{COHORTS}/sample-1/files", data={"file": (BytesIO(payload), filename)})
|
||||||
|
|
||||||
|
assert response.status_code == 201
|
||||||
|
assert response.json == {"name": "sample-1", "file": filename, "size_bytes": len(payload)}
|
||||||
|
folder = root / "sample-1"
|
||||||
|
assert list(folder.iterdir()) == [folder / filename]
|
||||||
|
assert (folder / filename).read_bytes() == payload
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(("name", "filename"), [
|
||||||
|
("sample", "other.csv"),
|
||||||
|
("sample", "../study.edf"),
|
||||||
|
("sample", r"..\study.edf"),
|
||||||
|
("sample", "nested/study.edf"),
|
||||||
|
("sample", r"nested\study.edf"),
|
||||||
|
("sample/other", "study.edf"),
|
||||||
|
("..", "study.edf"),
|
||||||
|
("sample..other", "study.edf"),
|
||||||
|
("bad%20name", "study.edf"),
|
||||||
|
("a" * 65, "study.edf"),
|
||||||
|
])
|
||||||
|
def test_reject_invalid_paths_and_extensions(cohort_client, name, filename):
|
||||||
|
"""Pin validation before writes. Fail if an unsafe component or unsupported extension is accepted."""
|
||||||
|
client, root = cohort_client
|
||||||
|
response = client.post(f"{COHORTS}/{name}/files", data={"file": (BytesIO(b"edf"), filename)})
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json["error"]
|
||||||
|
assert not root.exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_reject_a_cohort_symlink(cohort_client, tmp_path):
|
||||||
|
"""Pin root confinement. Fail if a cohort symlink allows an upload outside the root."""
|
||||||
|
client, root = cohort_client
|
||||||
|
outside = tmp_path / "outside"
|
||||||
|
outside.mkdir()
|
||||||
|
root.mkdir()
|
||||||
|
(root / "linked").symlink_to(outside, target_is_directory=True)
|
||||||
|
|
||||||
|
response = client.post(f"{COHORTS}/linked/files", data={"file": (BytesIO(b"edf"), "study.edf")})
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert not list(outside.iterdir())
|
||||||
|
assert client.get(COHORTS).json == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_root_configuration(cohort_client, monkeypatch):
|
||||||
|
"""Pin a 503 on both endpoints. Fail if either silently falls back to a different root."""
|
||||||
|
client, _ = cohort_client
|
||||||
|
monkeypatch.delenv("TEA_REFERENCE_ROOT")
|
||||||
|
|
||||||
|
for response in (client.get(COHORTS), client.post(f"{COHORTS}/sample/files")):
|
||||||
|
assert response.status_code == 503
|
||||||
|
assert response.json["error"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_upload_uses_app_size_limit(cohort_client):
|
||||||
|
"""Pin the existing JSON 413. Fail if multipart parsing bypasses the configured size limit."""
|
||||||
|
client, root = cohort_client
|
||||||
|
client.application.config["MAX_CONTENT_LENGTH"] = 1024
|
||||||
|
response = client.post(f"{COHORTS}/sample/files", data={"file": (BytesIO(b"x" * 1024), "study.edf")})
|
||||||
|
|
||||||
|
assert response.status_code == 413
|
||||||
|
assert response.json["error"]
|
||||||
|
assert not root.exists()
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
"""Cover governance EEG reads with SQLite recordings and a stub baseline registry.
|
||||||
|
|
||||||
|
Fails if the routes misreport analysis outcomes, FHIR counts or drawable metrics.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import pytest
|
||||||
|
from core.tea.models import Eeg, EegMetrica
|
||||||
|
from flask import Flask
|
||||||
|
from persistance import tea
|
||||||
|
from persistance.repository import Repository
|
||||||
|
from sqlalchemy import create_engine, event
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
from webapi.blueprints.governance import governance_bp
|
||||||
|
from webapi.fhir.eeg_curves import BaselineCurves
|
||||||
|
from webapi.tea import eeg_queries
|
||||||
|
|
||||||
|
EEG_URL = "/governance/tea/eeg"
|
||||||
|
BASELINE_URL = "/governance/tea/baselines/eeg-posterior-rhythm/3"
|
||||||
|
UUID = "a62321cf-515e-4883-b1b3-48e4202f790c"
|
||||||
|
CURVE = {"edad_meses": [16.0, 24.0], "p5": [4.0, 5.0], "p25": [5.0, 6.0],
|
||||||
|
"mediana": [6.0, 7.0], "p75": [7.0, 8.0], "p95": [8.0, 9.0]}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client():
|
||||||
|
"""Mount the governance routes so incorrect paths or response handling fail requests."""
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.config["TESTING"] = True
|
||||||
|
app.register_blueprint(governance_bp, url_prefix="/governance")
|
||||||
|
return app.test_client()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def database(monkeypatch):
|
||||||
|
"""Seed pending, failed, valid and invalid EEGs with scored and unscored metrics to expose miscounts."""
|
||||||
|
engine = create_engine("sqlite://")
|
||||||
|
Eeg.__table__.create(engine)
|
||||||
|
EegMetrica.__table__.create(engine)
|
||||||
|
with Session(engine) as session:
|
||||||
|
session.add_all([
|
||||||
|
Eeg(eeg_id="1", eeg_estudio=b"EDF"),
|
||||||
|
Eeg(eeg_id="2", eeg_valido=0),
|
||||||
|
Eeg(eeg_id="10", eeg_error="read failed"),
|
||||||
|
Eeg(eeg_id=UUID, eeg_valido=1, eeg_nivel="completo", eeg_edad_meses=23.5,
|
||||||
|
eeg_id_registro_laboratorio="LAB-4", eeg_pac_id=12, eeg_fecha_estudio=date(2025, 4, 3)),
|
||||||
|
EegMetrica(met_eeg_id=UUID, met_codigo="RITMO_POSTERIOR", met_valor=8.1, met_z=2.5,
|
||||||
|
met_fuera=1, met_modelo="tea-eeg-posterior-rhythm/3"),
|
||||||
|
EegMetrica(met_eeg_id=UUID, met_codigo="HUSOS_SUENO_N2", met_valor=0.4),
|
||||||
|
EegMetrica(met_eeg_id="2", met_codigo="RITMO_POSTERIOR", met_valor=3.1, met_z=-2.5, met_fuera=-1),
|
||||||
|
EegMetrica(met_eeg_id="2", met_codigo="HUSOS_SUENO_N2"),
|
||||||
|
])
|
||||||
|
session.commit()
|
||||||
|
monkeypatch.setattr(tea, "eeg_repository", Repository(lambda: Session(engine), Eeg))
|
||||||
|
yield engine
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def registry(monkeypatch):
|
||||||
|
"""Resolve one concrete version with one feature curve, so incorrect labels or feature lookups fail."""
|
||||||
|
expected = ("tea", "eeg-posterior-rhythm", "3")
|
||||||
|
registry = Mock()
|
||||||
|
registry.resolve.side_effect = lambda *args: {expected: SimpleNamespace(model_uri="models:/posterior/3")}[args]
|
||||||
|
module = SimpleNamespace(baselines={"posterior_rhythm_hz": SimpleNamespace(curva=pd.DataFrame(CURVE))})
|
||||||
|
curves = BaselineCurves(registry=registry, loader=lambda uri: {"models:/posterior/3": module}[uri])
|
||||||
|
monkeypatch.setattr(eeg_queries, "baseline_curves", lambda: curves)
|
||||||
|
return registry
|
||||||
|
|
||||||
|
|
||||||
|
def test_recordings_page_without_edf_bytes(client, database):
|
||||||
|
"""Pin descending IDs, pagination and analysis flags. Fail if the query projects EDF bytes or counts errors as pending."""
|
||||||
|
statements = []
|
||||||
|
|
||||||
|
@event.listens_for(database, "before_cursor_execute")
|
||||||
|
def capture_sql(connection, cursor, statement, parameters, context, executemany):
|
||||||
|
statements.append(statement)
|
||||||
|
|
||||||
|
response = client.get(EEG_URL)
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json == [
|
||||||
|
{"id": UUID, "lab_id": "LAB-4", "patient_id": 12, "study_date": "2025-04-03", "valid": True,
|
||||||
|
"analysed": True},
|
||||||
|
{"id": 10, "lab_id": None, "patient_id": None, "study_date": None, "valid": None, "analysed": True},
|
||||||
|
{"id": 2, "lab_id": None, "patient_id": None, "study_date": None, "valid": False, "analysed": True},
|
||||||
|
{"id": 1, "lab_id": None, "patient_id": None, "study_date": None, "valid": None, "analysed": False},
|
||||||
|
]
|
||||||
|
assert client.get(EEG_URL, query_string={"limit": 2, "offset": 1}).json == response.json[1:3]
|
||||||
|
assert all("eeg_estudio" not in statement for statement in statements)
|
||||||
|
|
||||||
|
|
||||||
|
def test_recording_page_size(client, database):
|
||||||
|
"""Pin the default and maximum page sizes. Fail if oversized requests return more than 500 rows."""
|
||||||
|
with Session(database) as session:
|
||||||
|
session.add_all(Eeg(eeg_id=str(key)) for key in range(1000, 1501))
|
||||||
|
session.commit()
|
||||||
|
assert len(client.get(EEG_URL).json) == 200
|
||||||
|
assert len(client.get(EEG_URL, query_string={"limit": 1000}).json) == 500
|
||||||
|
|
||||||
|
|
||||||
|
def test_recording_metrics(client, database):
|
||||||
|
"""Pin metric values and EEG metadata. Fail if UUIDs, null scores or the pinned model label are lost."""
|
||||||
|
response = client.get(f"{EEG_URL}/{UUID}/metrics")
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json == {
|
||||||
|
"eeg_id": UUID, "valid": True, "level": "completo", "age_months": 23.5,
|
||||||
|
"metrics": [
|
||||||
|
{"name": "husos_sueno_n2", "value": 0.4, "z": None, "outside": None, "model": None},
|
||||||
|
{"name": "ritmo_posterior", "value": 8.1, "z": 2.5, "outside": 1, "model": "tea-eeg-posterior-rhythm/3"},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
assert client.get(f"{EEG_URL}/2/metrics").json == {
|
||||||
|
"eeg_id": 2, "valid": False, "level": None, "age_months": None,
|
||||||
|
"metrics": [{"name": "ritmo_posterior", "value": 3.1, "z": -2.5, "outside": -1, "model": None}],
|
||||||
|
}
|
||||||
|
missing = client.get(f"{EEG_URL}/999/metrics")
|
||||||
|
assert missing.status_code == 404 and missing.json["error"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_summary(client, database):
|
||||||
|
"""Pin stored and FHIR counts. Fail if one missing view hides the other or pending EEGs count as analysed."""
|
||||||
|
expected = {"eegs": 4, "analysed": 3, "valid": 1, "not_valid": 1, "failed": 1, "metrics": 4,
|
||||||
|
"metrics_with_z": 2, "high": 1, "low": 1, "fhir_eegs": 0, "fhir_metrics": 0}
|
||||||
|
assert client.get(f"{EEG_URL}/summary").json == expected
|
||||||
|
with database.begin() as connection:
|
||||||
|
connection.exec_driver_sql("CREATE VIEW tea_paciente_eegs AS SELECT eeg_id FROM eeg WHERE eeg_valido = 1")
|
||||||
|
assert client.get(f"{EEG_URL}/summary").json == {**expected, "fhir_eegs": 1}
|
||||||
|
with database.begin() as connection:
|
||||||
|
connection.exec_driver_sql("CREATE VIEW tea_paciente_eeg_metricas AS SELECT met_id FROM eeg_metrica")
|
||||||
|
assert client.get(f"{EEG_URL}/summary").json == {**expected, "fhir_eegs": 1, "fhir_metrics": 4}
|
||||||
|
|
||||||
|
|
||||||
|
def test_baseline_metrics_and_curve(client, registry):
|
||||||
|
"""Pin drawable names and the pinned version's series. Fail if routes include missing features or lose metadata."""
|
||||||
|
assert client.get(f"{BASELINE_URL}/metrics").json == ["ritmo_posterior"]
|
||||||
|
response = client.get(f"{BASELINE_URL}/curve", query_string={"metric": "ritmo_posterior"})
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json == {"scenario": "eeg-posterior-rhythm", "version": 3, "metric": "ritmo_posterior", **CURVE}
|
||||||
|
registry.resolve.assert_called_once_with("tea", "eeg-posterior-rhythm", "3")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(("scenario", "version", "metric"), [
|
||||||
|
("eeg-unknown", 3, "ritmo_posterior"),
|
||||||
|
("eeg-posterior-rhythm", 9, "ritmo_posterior"),
|
||||||
|
("eeg-posterior-rhythm", 3, "unknown"),
|
||||||
|
])
|
||||||
|
def test_missing_curve(client, registry, scenario, version, metric):
|
||||||
|
"""Pin missing curve responses. Fail if unknown scenarios, versions or metrics return a successful curve."""
|
||||||
|
response = client.get(f"/governance/tea/baselines/{scenario}/{version}/curve", query_string={"metric": metric})
|
||||||
|
assert response.status_code == 404 and response.json["error"]
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
"""What this module covers: `POST /governance/tea/eeg/preview`, which analyses one EDF (and an ADOS-2 report) in memory and
|
||||||
|
answers a patient-summary bundle without writing to any database, and the `EegPreview` class behind it.
|
||||||
|
|
||||||
|
Fixtures: `app_client`, the real app over an empty migrated TEA database, with its engine so the tests can count rows;
|
||||||
|
`edf`, a synthetic two-minute EDF from `models/tests/tea/synth_edf.py` (too short to be a valid study, so only its
|
||||||
|
quality part is answered); `ados2_pdf`, a one-page report with a Module 2 score table drawn with reportlab.
|
||||||
|
"""
|
||||||
|
import importlib.util
|
||||||
|
import io
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
SYNTH = Path(__file__).resolve().parents[2] / "models" / "tests" / "tea" / "synth_edf.py"
|
||||||
|
URL = "/governance/tea/eeg/preview"
|
||||||
|
ROWS = [("Señalar", "1"), ("Gestos descriptivos, convencionales, instrumentales o informativos", "0"),
|
||||||
|
("Contacto visual inusual", "2"), ("Expresiones faciales dirigidas a otros", "1"),
|
||||||
|
("Disfrute compartido durante la interacción", "0"), ("Mostrar", "2"),
|
||||||
|
("Iniciación espontánea de la atención conjunta", "1"), ("Características de las iniciaciones sociales", "1"),
|
||||||
|
("Calidad general de la relación", "2"), ("Uso estereotipado o idiosincrásico de palabras o frases", "1"),
|
||||||
|
("Manierismos de manos y dedos y otros manierismos complejos", "2"),
|
||||||
|
("Intereses inusualmente repetitivos o comportamientos estereotipados", "1")]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def edf() -> bytes:
|
||||||
|
"""A synthetic two-minute EDF, the same file for every test."""
|
||||||
|
spec = importlib.util.spec_from_file_location("synth_edf", SYNTH)
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
return module.edf_bytes(minutes=2)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def ados2_pdf() -> bytes:
|
||||||
|
"""A report whose Module 2 table lists twelve items with their algorithm scores."""
|
||||||
|
from reportlab.pdfgen.canvas import Canvas
|
||||||
|
|
||||||
|
buffer = io.BytesIO()
|
||||||
|
pdf = Canvas(buffer, pagesize=(612, 792))
|
||||||
|
pdf.setFont("Helvetica", 10)
|
||||||
|
y = 720
|
||||||
|
for caption, score in [("Afectación Social (AS)", None), *ROWS[:8], ("TOTAL DE AFECTACIÓN SOCIAL", "7"),
|
||||||
|
("Comportamiento restringido y repetitivo (CRR)", None), *ROWS[8:],
|
||||||
|
("PUNTAJE TOTAL DE COMPORTAMIENTO RESTRINGIDO Y REPETITIVO (CRR)", "6"),
|
||||||
|
("PUNTUACIÓN TOTAL GLOBAL (AS + CRR)", "13")]:
|
||||||
|
pdf.drawString(76, y, caption)
|
||||||
|
if score is not None:
|
||||||
|
pdf.drawCentredString(512, y, score)
|
||||||
|
y -= 20
|
||||||
|
pdf.showPage()
|
||||||
|
pdf.save()
|
||||||
|
return buffer.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def app_client(tmp_path):
|
||||||
|
"""The real app over an empty migrated TEA database; yields (client, engine)."""
|
||||||
|
from conftest import base_de
|
||||||
|
|
||||||
|
from webapi import create_app
|
||||||
|
|
||||||
|
base = base_de("tea", tmp_path, datos=lambda session: None)
|
||||||
|
app = create_app()
|
||||||
|
app.config.update(TESTING=True)
|
||||||
|
try:
|
||||||
|
with app.test_client() as client:
|
||||||
|
yield client, base.motor
|
||||||
|
finally:
|
||||||
|
base.motor.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def _post(client, **files):
|
||||||
|
return client.post(URL, data={k: (io.BytesIO(v), name) for k, (name, v) in files.items()},
|
||||||
|
content_type="multipart/form-data")
|
||||||
|
|
||||||
|
|
||||||
|
def _types(response):
|
||||||
|
return [e["resource"]["resourceType"] for e in response.json["bundle"]["entry"]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_edf_is_analysed_and_nothing_is_stored(app_client, edf, monkeypatch):
|
||||||
|
"""Pins the summary bundle (report with its quality observations) and zero rows written to `eeg`, `eeg_criterio`
|
||||||
|
and `eeg_metrica`. Fails if the route stores the recording, or answers without the EEG's report."""
|
||||||
|
client, engine = app_client
|
||||||
|
monkeypatch.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False)
|
||||||
|
response = _post(client, edf=("estudio.edf", edf))
|
||||||
|
assert response.status_code == 200, response.json
|
||||||
|
assert "DiagnosticReport" in _types(response) and "Procedure" in _types(response)
|
||||||
|
assert "Observation" in _types(response)
|
||||||
|
with engine.connect() as connection:
|
||||||
|
for table in ("eeg", "eeg_criterio", "eeg_metrica"):
|
||||||
|
assert connection.execute(text(f"select count(*) from {table}")).scalar() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_file_that_is_not_an_edf_is_refused(app_client):
|
||||||
|
"""Pins 400 for a recording MNE cannot open and for a missing field. Fails if either answers 200 or 500."""
|
||||||
|
client, _ = app_client
|
||||||
|
assert _post(client, edf=("estudio.edf", b"no es un edf")).status_code == 400
|
||||||
|
assert client.post(URL, data={}, content_type="multipart/form-data").status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_without_a_report_the_bundle_has_no_ados2(app_client, edf):
|
||||||
|
"""Pins that the ADOS-2 observation appears only with a readable report. Fails if one is invented."""
|
||||||
|
client, _ = app_client
|
||||||
|
response = _post(client, edf=("estudio.edf", edf))
|
||||||
|
assert [e for e in response.json["bundle"]["entry"] if e["resource"]["id"].startswith("ados2-")] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_unreadable_report_gives_a_notice_not_an_error(app_client, edf):
|
||||||
|
"""Pins 200 plus a Spanish notice when the attached PDF has no ADOS-2 table. Fails if the route answers 500, drops
|
||||||
|
the EEG, or says nothing about the report."""
|
||||||
|
client, _ = app_client
|
||||||
|
from reportlab.pdfgen.canvas import Canvas
|
||||||
|
|
||||||
|
buffer = io.BytesIO()
|
||||||
|
pdf = Canvas(buffer)
|
||||||
|
pdf.drawString(72, 700, "Nota clinica sin tabla")
|
||||||
|
pdf.showPage()
|
||||||
|
pdf.save()
|
||||||
|
response = _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", buffer.getvalue()))
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert any("ADOS-2" in aviso for aviso in response.json["avisos"])
|
||||||
|
assert "DiagnosticReport" in _types(response)
|
||||||
|
|
||||||
|
|
||||||
|
def test_without_an_age_the_css_is_not_invented(app_client, edf, ados2_pdf):
|
||||||
|
"""Pins the notice when the report gives no CSS and the EDF no age. Fails if a CSS is made up or the notice is lost."""
|
||||||
|
client, _ = app_client
|
||||||
|
response = _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", ados2_pdf))
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert any("CSS" in aviso for aviso in response.json["avisos"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_report_that_is_not_a_pdf_is_refused(app_client, edf):
|
||||||
|
"""Pins 400 for an ADOS-2 file that is not a PDF. Fails if text is handed to the document extraction."""
|
||||||
|
client, _ = app_client
|
||||||
|
assert _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", b"texto")).status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_ados2_report_is_read_and_scored(app_client, edf, ados2_pdf, monkeypatch):
|
||||||
|
"""Pins that the table's items and module reach the bundle's ADOS-2 observation, scored by the platform's scorer at
|
||||||
|
the age the analysis used. Fails if the report is ignored, or its items are lost, or nothing is scored."""
|
||||||
|
import dataclasses
|
||||||
|
|
||||||
|
from models.tea.eeg import analyze
|
||||||
|
|
||||||
|
real = analyze.measure
|
||||||
|
monkeypatch.setattr(analyze, "measure", lambda *args: dataclasses.replace(real(*args), age_months=30.0))
|
||||||
|
client, engine = app_client
|
||||||
|
response = _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", ados2_pdf))
|
||||||
|
assert response.status_code == 200, response.json
|
||||||
|
ados2 = [e["resource"] for e in response.json["bundle"]["entry"] if e["resource"]["id"].startswith("ados2-")]
|
||||||
|
assert len(ados2) == 1 and len(ados2[0]["component"]) > 10, response.json["avisos"]
|
||||||
|
with engine.connect() as connection:
|
||||||
|
assert connection.execute(text("select count(*) from ados2")).scalar() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_alterations_are_listed_although_the_validation_flag_is_off(monkeypatch):
|
||||||
|
"""Pins `show_alterations=True` over the environment gate in the FHIR builder. Fails if a preview of a valid EEG
|
||||||
|
hides its metrics because `TEA_ALTERACIONES_VALIDADAS` is unset."""
|
||||||
|
from webapi.fhir import tea
|
||||||
|
|
||||||
|
monkeypatch.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False)
|
||||||
|
eeg = {"procedimiento_id": "p", "fecha_eeg": "2026-01-01", "calidad": "BUENO", "valido": 1, "nivel": None,
|
||||||
|
"duracion_min": 5, "edad_meses": 24.0, "canales": 19}
|
||||||
|
metric = {"procedimiento_id": "p", "metrica": "ritmo_posterior", "valor": 7.0, "grupo_edad_eeg": "24 meses",
|
||||||
|
"ref_min": 6.0, "ref_mediana": 7.5, "ref_max": 9.0, "modelo": None, "valor_z": -0.4, "estado": "normal"}
|
||||||
|
hidden = tea.eeg_resources(eeg, "x", [metric], [], True)
|
||||||
|
shown = tea.eeg_resources(eeg, "x", [metric], [], True, show_alterations=True)
|
||||||
|
assert len(shown) == len(hidden) + 1
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""Cover progress lookup with a Flask client and temporary training and analysis folders.
|
||||||
|
|
||||||
|
Fails if the route selects the wrong directory or changes the progress response status or shape.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
from webapi.blueprints.governance import governance_bp
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def progress_client(tmp_path, monkeypatch):
|
||||||
|
"""Set up isolated job folders so reading the configured indicator root is required."""
|
||||||
|
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.register_blueprint(governance_bp, url_prefix="/governance")
|
||||||
|
return app.test_client()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(("kind", "base"), [("train", "entrenamientos"), ("analyze", "analisis_eeg")])
|
||||||
|
def test_progress_snapshot(progress_client, tmp_path, kind, base):
|
||||||
|
"""Pin progress lookup for both job kinds. Fail if missing files succeed or the snapshot is wrapped."""
|
||||||
|
url = f"/governance/tea/jobs/{kind}/example/progress"
|
||||||
|
response = progress_client.get(url)
|
||||||
|
assert response.status_code == 404 and set(response.json) == {"error"}
|
||||||
|
|
||||||
|
folder = tmp_path / base / "example"
|
||||||
|
folder.mkdir(parents=True)
|
||||||
|
(folder / "job.json").write_text("{}", encoding="utf-8")
|
||||||
|
response = progress_client.get(url)
|
||||||
|
assert response.status_code == 404 and set(response.json) == {"error"}
|
||||||
|
|
||||||
|
snapshot = {"updated_at": "2026-01-01T00:00:00+00:00", "phase": "midiendo", "done": 2, "total": 10,
|
||||||
|
"elapsed_s": 1, "eta_s": None, "tasks": None, "cluster": None, "history": []}
|
||||||
|
(folder / "progress.json").write_text(json.dumps(snapshot), encoding="utf-8")
|
||||||
|
response = progress_client.get(url)
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json == snapshot
|
||||||
|
|
||||||
|
response = progress_client.get(f"/governance/tea/jobs/{kind}/nested%2F..%2Fexample/progress")
|
||||||
|
assert response.status_code == 404 and set(response.json) == {"error"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_kind(progress_client):
|
||||||
|
"""Pin invalid kind handling. Fail if an unsupported job kind becomes a missing job."""
|
||||||
|
response = progress_client.get("/governance/tea/jobs/other/example/progress")
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert set(response.json) == {"error"}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
"""What this module covers: `POST /governance/tea/eeg/upload`, which registers one EDF as an EEG through the import
|
||||||
|
pipeline (`tea.Eeg`, upsert on the laboratory id).
|
||||||
|
|
||||||
|
Fixtures: `app_client`, a migrated empty TEA database (`base_de`) behind the real app; `edf`, a synthetic EDF of two
|
||||||
|
minutes from `models/tests/tea/synth_edf.py` (nothing comes from a patient).
|
||||||
|
"""
|
||||||
|
import importlib.util
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
SYNTH = Path(__file__).resolve().parents[2] / "models" / "tests" / "tea" / "synth_edf.py"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def edf() -> bytes:
|
||||||
|
"""A synthetic two-minute EDF, the same file for every test."""
|
||||||
|
spec = importlib.util.spec_from_file_location("synth_edf", SYNTH)
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
return module.edf_bytes(minutes=2)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def app_client(tmp_path):
|
||||||
|
"""The real app over an empty migrated TEA database; yields (client, engine)."""
|
||||||
|
from conftest import base_de
|
||||||
|
|
||||||
|
from webapi import create_app
|
||||||
|
|
||||||
|
base = base_de("tea", tmp_path, datos=lambda session: None)
|
||||||
|
app = create_app()
|
||||||
|
app.config.update(TESTING=True)
|
||||||
|
try:
|
||||||
|
with app.test_client() as client:
|
||||||
|
yield client, base.motor
|
||||||
|
finally:
|
||||||
|
base.motor.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def _post(client, edf, name="estudio-1.edf", **form):
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
return client.post("/governance/tea/eeg/upload", data={"file": (BytesIO(edf), name), **form},
|
||||||
|
content_type="multipart/form-data")
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_uploaded_edf_becomes_an_eeg_row(app_client, edf):
|
||||||
|
"""Pins down: a valid EDF is stored in `eeg` with its file, and the answer carries the new id and the lab id.
|
||||||
|
|
||||||
|
Fails if the route stops going through the `tea.Eeg` import (no row, no bytes, or no id in the answer).
|
||||||
|
"""
|
||||||
|
client, engine = app_client
|
||||||
|
response = _post(client, edf)
|
||||||
|
assert response.status_code == 201, response.get_json()
|
||||||
|
body = response.get_json()
|
||||||
|
assert body["created"] is True and body["eeg_id"] is not None and body["lab_id"]
|
||||||
|
with engine.connect() as connection:
|
||||||
|
stored = connection.execute(text("select length(eeg_estudio), eeg_pac_id from eeg")).one()
|
||||||
|
assert stored[0] == len(edf) and stored[1] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_uploading_the_same_study_twice_updates_it(app_client, edf):
|
||||||
|
"""Pins down: the laboratory id is the natural key, so a second upload updates the row and does not add one.
|
||||||
|
|
||||||
|
Fails if the upsert policy is lost and the study is duplicated or rejected.
|
||||||
|
"""
|
||||||
|
client, engine = app_client
|
||||||
|
first = _post(client, edf).get_json()
|
||||||
|
second = _post(client, edf)
|
||||||
|
assert second.status_code == 201
|
||||||
|
assert second.get_json()["created"] is False and second.get_json()["eeg_id"] == first["eeg_id"]
|
||||||
|
with engine.connect() as connection:
|
||||||
|
assert connection.execute(text("select count(*) from eeg")).scalar() == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_file_that_is_not_an_edf_is_refused(app_client):
|
||||||
|
"""Pins down: bytes MNE cannot open answer 400 with a message and write nothing.
|
||||||
|
|
||||||
|
Fails if the connector's validation is bypassed and garbage reaches the table.
|
||||||
|
"""
|
||||||
|
client, engine = app_client
|
||||||
|
response = _post(client, b"not an edf at all")
|
||||||
|
assert response.status_code == 400 and response.get_json()["error"]
|
||||||
|
with engine.connect() as connection:
|
||||||
|
assert connection.execute(text("select count(*) from eeg")).scalar() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_request_needs_a_file_and_a_numeric_patient(app_client, edf):
|
||||||
|
"""Pins down: a missing `file` and a non-numeric `patient_id` are 400s before any import runs.
|
||||||
|
|
||||||
|
Fails if the form is read without checking, which would turn bad input into a 500.
|
||||||
|
"""
|
||||||
|
client, _ = app_client
|
||||||
|
assert client.post("/governance/tea/eeg/upload", data={}).status_code == 400
|
||||||
|
assert _post(client, edf, patient_id="abc").status_code == 400
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"""What this module covers: the cluster choice of an indicator recomputation: how `POST /reportes/indicadores/<d>/recalcular`
|
||||||
|
validates it, how the queue carries it in the pending marker, and how the worker applies it to one run only.
|
||||||
|
|
||||||
|
Fixtures: `queue`, a `RecomputationQueue` over a temporary folder.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
from webapi.blueprints.reports import reports_bp
|
||||||
|
from webapi.recomputation import RecomputationQueue, _cluster_override
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def queue(tmp_path, monkeypatch):
|
||||||
|
"""A queue over an empty temporary folder, which the route also uses through INDICADORES_DIR."""
|
||||||
|
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
|
||||||
|
return RecomputationQueue(tmp_path)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(queue):
|
||||||
|
"""The reports blueprint alone, over the same folder as `queue`."""
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.register_blueprint(reports_bp, url_prefix="/reportes")
|
||||||
|
return app.test_client()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_request_carries_its_cluster_choice_to_the_worker(queue):
|
||||||
|
"""Pins down: the marker keeps the choice, `requested_cluster` reads it back, and a plain request has none.
|
||||||
|
|
||||||
|
Fails if `request_run` drops the choice or the marker stops being readable after a plain request.
|
||||||
|
"""
|
||||||
|
queue.request_run("tea", {"mode": "local"})
|
||||||
|
assert queue.requested_cluster("tea") == {"mode": "local"}
|
||||||
|
queue.request_run("tea")
|
||||||
|
assert queue.requested_cluster("tea") is None
|
||||||
|
assert queue.requested_cluster("cacu") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_marker_written_as_plain_text_still_counts_as_pending(queue):
|
||||||
|
"""Pins down: a marker left by an older version (a bare timestamp) is pending and has no cluster choice.
|
||||||
|
|
||||||
|
Fails if the worker starts to crash on, or ignore, markers that are not JSON.
|
||||||
|
"""
|
||||||
|
queue._pending.mkdir(parents=True)
|
||||||
|
(queue._pending / "tea").write_text("2026-01-01T00:00:00+00:00", encoding="utf-8")
|
||||||
|
assert queue.pending() == ["tea"] and queue.requested_cluster("tea") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_route_validates_and_queues_the_choice(client, queue):
|
||||||
|
"""Pins down: a valid choice is queued (202), a bad mode, a non-object body and `remote` without a scheduler are
|
||||||
|
400s that queue nothing, and no body keeps working.
|
||||||
|
|
||||||
|
Fails if the route queues unchecked input, or stops accepting the body-less call the UI used before.
|
||||||
|
"""
|
||||||
|
ok = client.post("/reportes/indicadores/tea/recalcular", json={"cluster": {"mode": "local"}})
|
||||||
|
assert ok.status_code == 202 and queue.requested_cluster("tea") == {"mode": "local"}
|
||||||
|
for bad in ({"cluster": {"mode": "nope"}}, ["x"]):
|
||||||
|
assert client.post("/reportes/indicadores/tea/recalcular", json=bad).status_code == 400
|
||||||
|
os.environ.pop("DASK_SCHEDULER_ADDRESS", None)
|
||||||
|
assert client.post("/reportes/indicadores/tea/recalcular", json={"cluster": {"mode": "remote"}}).status_code == 400
|
||||||
|
assert client.post("/reportes/indicadores/tea/recalcular").status_code == 202
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_run_applies_the_choice_and_then_restores_the_environment(monkeypatch):
|
||||||
|
"""Pins down: during the run the choice is in the environment (`local` drops the scheduler), and afterwards the
|
||||||
|
process environment is exactly as before, even when the run fails.
|
||||||
|
|
||||||
|
Fails if one run's choice leaks into the next runs of the worker.
|
||||||
|
"""
|
||||||
|
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://scheduler:1")
|
||||||
|
monkeypatch.delenv("EEG_ANALYSIS_CLUSTER", raising=False)
|
||||||
|
before = dict(os.environ)
|
||||||
|
with _cluster_override({"mode": "local"}):
|
||||||
|
assert os.environ["EEG_ANALYSIS_CLUSTER"] == "local" and "DASK_SCHEDULER_ADDRESS" not in os.environ
|
||||||
|
assert dict(os.environ) == before
|
||||||
|
with pytest.raises(RuntimeError):
|
||||||
|
with _cluster_override({"mode": "remote", "scheduler": "tcp://other:2"}):
|
||||||
|
assert os.environ["DASK_SCHEDULER_ADDRESS"] == "tcp://other:2"
|
||||||
|
raise RuntimeError("boom")
|
||||||
|
assert dict(os.environ) == before
|
||||||
|
with _cluster_override(None):
|
||||||
|
assert dict(os.environ) == before
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""Relaciones y tiempos individuales sobre procedimientos y observaciones sintéticos."""
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from sqlalchemy import event
|
||||||
|
from sqlmodel import Session, create_engine
|
||||||
|
|
||||||
|
from webapi.follow_up.screening import rutas_de
|
||||||
|
from webapi.orchestration.tables.cacu import TABLAS
|
||||||
|
|
||||||
|
|
||||||
|
def test_rutas_en_un_query_con_vinculos_repeticiones_y_corte():
|
||||||
|
motor = create_engine("sqlite://")
|
||||||
|
procedimiento = TABLAS.Procedimiento.__table__
|
||||||
|
observacion = TABLAS.Observacion.__table__
|
||||||
|
procedimiento.create(motor)
|
||||||
|
observacion.create(motor)
|
||||||
|
fechas = {i: date(2025, 3, i) for i in range(1, 11)}
|
||||||
|
|
||||||
|
def acto(id_, estudio, clase, dia, padre=None, pac=1):
|
||||||
|
return dict(procedimiento_id=id_, estudio_id=estudio, clase=clase, fecha=fechas.get(dia),
|
||||||
|
padre_id=padre, pac_id=pac, carga_id=1, fuente_tabla="fixture", fuente_id=str(id_))
|
||||||
|
|
||||||
|
with motor.begin() as conexion:
|
||||||
|
conexion.execute(procedimiento.insert(), [
|
||||||
|
acto(1, "citologia", "toma", 1),
|
||||||
|
acto(2, "citologia", "toma", 2),
|
||||||
|
acto(3, "citologia", "reporte", 1, 1), # Mismo día que la toma.
|
||||||
|
acto(4, "citologia", "reporte", 2, 1),
|
||||||
|
acto(5, "citologia", "reporte", 4, 1),
|
||||||
|
acto(6, "biopsia", "orden", 3, 1),
|
||||||
|
acto(7, "biopsia", "reporte", 4, 6),
|
||||||
|
acto(8, "biopsia", "reporte", 9, 6), # Posterior al corte.
|
||||||
|
acto(9, "biopsia", "orden", 4, 2),
|
||||||
|
acto(10, "biopsia", "reporte", 9, 9), # Pendiente al corte para la segunda toma.
|
||||||
|
acto(11, "biopsia", "orden", 3), # Otro episodio de la misma paciente.
|
||||||
|
acto(12, "biopsia", "reporte", 3, 11),
|
||||||
|
acto(13, "biopsia", "orden", 3, 2, pac=2), # Cadena inconsistente entre pacientes.
|
||||||
|
acto(14, "biopsia", "reporte", 3, 13, pac=2),
|
||||||
|
acto(15, "nota_medica", "encuentro", 3),
|
||||||
|
acto(16, "citologia", "reporte", 9, 2),
|
||||||
|
acto(17, "citologia", "toma", 2, pac=2),
|
||||||
|
acto(18, "citologia", "reporte", 6, 17), # Reporte sin resultado Bethesda.
|
||||||
|
acto(19, "citologia", "reporte", None, 17),
|
||||||
|
])
|
||||||
|
conexion.execute(observacion.insert(), [
|
||||||
|
dict(procedimiento_id=p, carga_id=1, pac_id=pac, resultado_id="citologia.bethesda", valor_fuente="NEG")
|
||||||
|
for p, pac in [(3, 1), (4, 1), (5, 1), (16, 1), (19, 2)]
|
||||||
|
])
|
||||||
|
|
||||||
|
consultas = []
|
||||||
|
event.listen(motor, "before_cursor_execute", lambda *args: consultas.append(args[2]))
|
||||||
|
with Session(motor) as sesion:
|
||||||
|
rutas = rutas_de(sesion, {1: (1, fechas[1]), 2: (1, fechas[2]), 17: (2, fechas[2])}, fechas[6], detalle=True)
|
||||||
|
assert rutas_de(sesion, {}, fechas[6]) == {}
|
||||||
|
assert len(consultas) == 1
|
||||||
|
|
||||||
|
primera = rutas[1]
|
||||||
|
citologia, colposcopia, biopsia, diagnostico = primera["etapas"]
|
||||||
|
assert citologia["estado"] == "registrada"
|
||||||
|
assert citologia["dias_desde_toma"] == citologia["dias_desde_anterior"] == 0
|
||||||
|
assert [e["fecha"] for e in citologia["eventos"]] == ["2025-03-01", "2025-03-02", "2025-03-04"]
|
||||||
|
assert citologia["evento_ref"] == citologia["eventos"][0]["ref"]
|
||||||
|
assert biopsia["estado"] == "registrada" and biopsia["fecha"] == "2025-03-04"
|
||||||
|
assert len(biopsia["eventos"]) == len(biopsia["ordenes"]) == 1
|
||||||
|
assert biopsia["dias_desde_toma"] == 3 and biopsia["dias_desde_anterior"] is None
|
||||||
|
assert primera["dias_desde_ultimo_evento"] == 2
|
||||||
|
for etapa in (colposcopia, diagnostico):
|
||||||
|
assert etapa["estado"] == "desconocida" and etapa["fecha"] is None and etapa["eventos"] == []
|
||||||
|
|
||||||
|
segunda = rutas[2]
|
||||||
|
assert segunda["id"] != primera["id"]
|
||||||
|
assert segunda["etapas"][0]["estado"] == "desconocida"
|
||||||
|
assert segunda["etapas"][2]["estado"] == "pendiente" and segunda["etapas"][2]["fecha"] is None
|
||||||
|
assert segunda["etapas"][2]["dias_desde_toma"] is None
|
||||||
|
assert len(segunda["etapas"][2]["ordenes"]) == 1
|
||||||
|
assert segunda["dias_desde_ultimo_evento"] == 4 # La orden no reinicia el reloj.
|
||||||
|
assert all(e["estado"] == "desconocida" for e in rutas[17]["etapas"])
|
||||||
+129
-2
@@ -10,10 +10,38 @@ from conftest import cliente_de
|
|||||||
|
|
||||||
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "horizontes_disponibles", "reglas",
|
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "horizontes_disponibles", "reglas",
|
||||||
"paginacion", "items"}
|
"paginacion", "items"}
|
||||||
LLAVES_DEL_ITEM = {"pac_id", "id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
|
LLAVES_DEL_ITEM = {"pac_id", "id_seudonimo", "grupo_edad", "edad_al_corte", "estatus", "ultima_citologia", "ultimo_vph",
|
||||||
"dias_toma_diagnostico", "ultima_biopsia", "probabilidades", "prioridad"} # fmt: skip
|
"dias_toma_diagnostico", "ultima_biopsia", "probabilidades", "prioridad"} # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("fecha", ["1980-01-01", None])
|
||||||
|
def test_demografia_consulta_persona_y_distingue_nulo(monkeypatch, fecha):
|
||||||
|
from datetime import date
|
||||||
|
from flask import Flask
|
||||||
|
from webapi.follow_up import routes
|
||||||
|
|
||||||
|
class Resultado:
|
||||||
|
def first(self):
|
||||||
|
return (date.fromisoformat(fecha) if fecha else None,)
|
||||||
|
|
||||||
|
class Sesion:
|
||||||
|
def execute(self, consulta):
|
||||||
|
assert consulta.compile().params == {"pac_id_1": 42}
|
||||||
|
return Resultado()
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.register_blueprint(routes.follow_up_blueprint(Sesion), url_prefix="/cacu")
|
||||||
|
respuesta = app.test_client().get('/cacu/seguimiento/pacientes/42/demografia')
|
||||||
|
assert respuesta.status_code == 200
|
||||||
|
assert respuesta.json == {"pac_id": "42", "fecha_nacimiento": fecha}
|
||||||
|
|
||||||
|
|
||||||
|
def test_demografia_rechaza_identificador_fuera_de_rango(client):
|
||||||
|
assert client.get('/cacu/seguimiento/pacientes/9223372036854775808/demografia').status_code == 404
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
def client(tmp_path_factory):
|
def client(tmp_path_factory):
|
||||||
"""La app sobre la base de demostración de CaCu, sin `DEV_REVISION` en el entorno."""
|
"""La app sobre la base de demostración de CaCu, sin `DEV_REVISION` en el entorno."""
|
||||||
@@ -42,7 +70,8 @@ def test_el_pedido_se_respeta(client):
|
|||||||
|
|
||||||
assert cuerpo["ventana"]["meses"] == 6 and cuerpo["paginacion"]["page_size"] == 2
|
assert cuerpo["ventana"]["meses"] == 6 and cuerpo["paginacion"]["page_size"] == 2
|
||||||
assert len(cuerpo["items"]) <= 2 and all(i["estatus"]["codigo"] == "PRE_COLPOSCOPIA" for i in cuerpo["items"])
|
assert len(cuerpo["items"]) <= 2 and all(i["estatus"]["codigo"] == "PRE_COLPOSCOPIA" for i in cuerpo["items"])
|
||||||
assert cuerpo["filtros"] == {"estatus": "PRE_COLPOSCOPIA", "orden": "reciente", "horizonte": 5.0}
|
assert cuerpo["filtros"] == {"estatus": "PRE_COLPOSCOPIA", "orden": "reciente", "horizonte": 5.0,
|
||||||
|
"q": None, "edad_min": None, "edad_max": None}
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
@@ -72,6 +101,66 @@ def test_in_dev_esta_obsoleta():
|
|||||||
in_dev()
|
in_dev()
|
||||||
|
|
||||||
|
|
||||||
|
def test_edades_cumplidas_al_corte_y_desconocidas(monkeypatch):
|
||||||
|
from datetime import date
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from webapi.follow_up import listing
|
||||||
|
|
||||||
|
monkeypatch.setattr(listing, "grupos_de_cortes", lambda *a, **kw: [SimpleNamespace(edad_min=0, edad_max=130, etiqueta="grupo")])
|
||||||
|
class Session:
|
||||||
|
def execute(self, query):
|
||||||
|
return [(1, date(2000, 12, 31)), (2, date(2000, 1, 1)), (3, None),
|
||||||
|
(4, "inválida"), (5, date(2026, 1, 1)), (6, date(2000, 2, 29))]
|
||||||
|
fechas = listing._edades(Session(), date(2025, 12, 30), [], listing.TABLAS)
|
||||||
|
assert fechas[1] == (24, "grupo") and fechas[2] == (25, "grupo")
|
||||||
|
assert not ({3, 4, 5} & fechas.keys())
|
||||||
|
cumple = listing._edades(Session(), date(2025, 12, 31), [], listing.TABLAS)
|
||||||
|
assert cumple[1][0] == 25
|
||||||
|
historica = listing._edades(Session(), date(2021, 2, 28), [], listing.TABLAS)
|
||||||
|
assert historica[6][0] == 20 # La convención existente cumple el 1 de marzo en años no bisiestos.
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("query", ["edad_min=-1", "edad_max=1.5", "edad_min=", "edad_max=abc",
|
||||||
|
"edad_min=9&edad_max=8", "q=" + "x" * 101])
|
||||||
|
def test_filtros_nuevos_invalidos(client, query):
|
||||||
|
assert client.get(f"/cacu/seguimiento?{query}").status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_busqueda_edad_y_paginacion_sobre_cohorte_completa(client, monkeypatch):
|
||||||
|
from webapi.follow_up import listing
|
||||||
|
original = listing._items
|
||||||
|
|
||||||
|
def items_controlados(*args):
|
||||||
|
filas = original(*args)
|
||||||
|
assert len(filas) >= 3
|
||||||
|
for n, fila in enumerate(filas):
|
||||||
|
fila["id_seudonimo"] = f"Prueba-{n:02}"
|
||||||
|
fila["edad_al_corte"] = [30, 60, None][n % 3]
|
||||||
|
return filas
|
||||||
|
|
||||||
|
monkeypatch.setattr(listing, "_items", items_controlados)
|
||||||
|
base = "/cacu/seguimiento?corte=2025-12-31&meses=12"
|
||||||
|
todas = client.get(base + "&page_size=200").get_json()["items"]
|
||||||
|
assert len(todas) >= 3
|
||||||
|
segunda = client.get(base + "&page_size=1&page=2").get_json()["items"][0]
|
||||||
|
buscada = client.get(base + "&q=%20%20pRuEbA-01%20&page_size=1").get_json()
|
||||||
|
assert buscada["paginacion"]["total_items"] == 1 and buscada["items"][0]["pac_id"] == segunda["pac_id"]
|
||||||
|
assert buscada["filtros"]["q"] == "prueba-01"
|
||||||
|
por_id = client.get(base + "&q=" + segunda["pac_id"]).get_json()
|
||||||
|
assert segunda["pac_id"] in [i["pac_id"] for i in por_id["items"]]
|
||||||
|
vacio = client.get(base + "&q=no-existe&horizonte=999").get_json()
|
||||||
|
assert vacio["items"] == [] and vacio["paginacion"]["total_items"] == 0
|
||||||
|
for filtro, esperado in [("edad_min=30&edad_max=60", {30, 60}), ("edad_min=60", {60}), ("edad_max=30", {30})]:
|
||||||
|
cuerpo = client.get(base + "&" + filtro + "&page_size=200").get_json()
|
||||||
|
assert {i["edad_al_corte"] for i in cuerpo["items"]} == esperado
|
||||||
|
estatus = segunda["estatus"]["codigo"]
|
||||||
|
combinado = client.get(base + f"&q=prueba&edad_min=60&edad_max=60&estatus={estatus}&orden=reciente&page_size=1").get_json()
|
||||||
|
esperadas = [i for i in todas if i["edad_al_corte"] == 60 and i["estatus"]["codigo"] == estatus]
|
||||||
|
assert combinado["paginacion"]["total_items"] == len(esperadas)
|
||||||
|
assert (combinado["filtros"]["q"], combinado["filtros"]["edad_min"], combinado["filtros"]["edad_max"]) == ("prueba", 60, 60)
|
||||||
|
assert combinado["items"] == esperadas[:1]
|
||||||
|
|
||||||
|
|
||||||
def test_la_lista_se_ordena_por_la_probabilidad_de_lieag_al_horizonte_pedido(client):
|
def test_la_lista_se_ordena_por_la_probabilidad_de_lieag_al_horizonte_pedido(client):
|
||||||
"""Fija: con un lote de CIN2+ confirmado, cada fila trae sus probabilidades por horizonte y `orden=lieag` pone
|
"""Fija: con un lote de CIN2+ confirmado, cada fila trae sus probabilidades por horizonte y `orden=lieag` pone
|
||||||
primero a la de mayor probabilidad al `horizonte` pedido, y al final a quien el modelo no evalúa; un horizonte que
|
primero a la de mayor probabilidad al `horizonte` pedido, y al final a quien el modelo no evalúa; un horizonte que
|
||||||
@@ -110,6 +199,13 @@ def test_la_lista_se_ordena_por_la_probabilidad_de_lieag_al_horizonte_pedido(cli
|
|||||||
"ic_bajo": 0.22, "ic_alto": 0.40}
|
"ic_bajo": 0.22, "ic_alto": 0.40}
|
||||||
assert all(i["probabilidades"] is None for i in cuerpo["items"][2:])
|
assert all(i["probabilidades"] is None for i in cuerpo["items"][2:])
|
||||||
assert client.get("/cacu/seguimiento?corte=2025-12-31&orden=lieag&horizonte=3").status_code == 400
|
assert client.get("/cacu/seguimiento?corte=2025-12-31&orden=lieag&horizonte=3").status_code == 400
|
||||||
|
primera = cuerpo["items"][0]
|
||||||
|
edad = primera["edad_al_corte"]
|
||||||
|
assert edad is not None
|
||||||
|
combinado = client.get(f"/cacu/seguimiento?corte=2025-12-31&meses=12&orden=lieag&horizonte=1"
|
||||||
|
f"&q={alta}&edad_min={edad}&edad_max={edad}&estatus={primera['estatus']['codigo']}").get_json()
|
||||||
|
assert combinado["paginacion"]["total_items"] == 1
|
||||||
|
assert combinado["items"][0]["pac_id"] == str(alta)
|
||||||
|
|
||||||
|
|
||||||
def test_un_caso_tiene_su_estatus_y_su_probabilidad_de_supervivencia(client):
|
def test_un_caso_tiene_su_estatus_y_su_probabilidad_de_supervivencia(client):
|
||||||
@@ -188,3 +284,34 @@ def test_un_caso_es_un_carcinoma_invasor_o_in_situ():
|
|||||||
|
|
||||||
parametros = tomllib.loads((Path(referencia.__file__).parent / "parametros.toml").read_text(encoding="utf-8"))
|
parametros = tomllib.loads((Path(referencia.__file__).parent / "parametros.toml").read_text(encoding="utf-8"))
|
||||||
assert parametros["cacu"]["seguimiento"]["caso"]["grados"]["valor"] == ["CIS", "CARCINOMA"]
|
assert parametros["cacu"]["seguimiento"]["caso"]["grados"]["valor"] == ["CIS", "CARCINOMA"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_ruta_es_optativa_y_se_proyecta_solo_para_la_pagina(client, monkeypatch):
|
||||||
|
from webapi.follow_up import listing
|
||||||
|
|
||||||
|
base = "/cacu/seguimiento?corte=2025-12-31&meses=12&q=%20&page_size=2&page=2"
|
||||||
|
normal = client.get(base).get_json()
|
||||||
|
assert normal["items"] and "ruta_tamizaje" not in normal["items"][0]
|
||||||
|
assert client.get(base + "&incluir=otra").status_code == 400
|
||||||
|
|
||||||
|
llamadas = []
|
||||||
|
proyectar = listing.rutas_de
|
||||||
|
|
||||||
|
def en_bloque(sesion, tomas, corte, tablas):
|
||||||
|
llamadas.append({pac_id for pac_id, _ in tomas.values()})
|
||||||
|
return proyectar(sesion, tomas, corte, tablas)
|
||||||
|
|
||||||
|
monkeypatch.setattr(listing, "rutas_de", en_bloque)
|
||||||
|
respuesta = client.get(base + "&incluir=ruta_tamizaje")
|
||||||
|
assert respuesta.status_code == 200
|
||||||
|
cuerpo = respuesta.get_json()
|
||||||
|
assert llamadas == [{int(i["pac_id"]) for i in normal["items"]}]
|
||||||
|
for fila in cuerpo["items"]:
|
||||||
|
ruta = fila.pop("ruta_tamizaje")
|
||||||
|
assert ruta["corte"] == cuerpo["corte"]
|
||||||
|
detalle = client.get(ruta["detalle_url"])
|
||||||
|
assert detalle.status_code == 200 and detalle.get_json()["id"] == ruta["id"]
|
||||||
|
assert client.get(ruta["detalle_url"].split("?")[0]).status_code == 400
|
||||||
|
assert client.get(ruta["detalle_url"].replace("corte=" + ruta["corte"], "corte=2026-12-31")).status_code == 404
|
||||||
|
assert client.get(ruta["detalle_url"].replace(f"/rutas/{fila['pac_id']}/", "/rutas/999999/")).status_code == 404
|
||||||
|
assert cuerpo == normal
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
"""Cover the analysis job routes with captured launches and saved job files.
|
||||||
|
|
||||||
|
Fixtures: analysis_client supplies the Flask routes, a temporary job directory and EEG rows.
|
||||||
|
Fails if scope or cluster options are lost, or persisted jobs change their API shape or order.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from flask import Flask
|
||||||
|
from sqlalchemy.pool import StaticPool
|
||||||
|
from sqlmodel import Session, create_engine
|
||||||
|
|
||||||
|
from core.tea.models import Eeg
|
||||||
|
from persistance.tea import eeg_repository
|
||||||
|
from webapi import detached_jobs
|
||||||
|
from webapi.blueprints.governance import governance_bp
|
||||||
|
|
||||||
|
URL = "/governance/tea/eeg/analyze-jobs"
|
||||||
|
SUMMARY = {"pending": 3, "valid": 1, "not_valid": 1, "failed": 1}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def analysis_client(tmp_path, monkeypatch):
|
||||||
|
"""Supply EEG IDs 1 and 2 (numeric) and two UUID ids, and capture child launches to detect invalid launches and lost options."""
|
||||||
|
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
|
||||||
|
monkeypatch.delenv("DASK_SCHEDULER_ADDRESS", raising=False)
|
||||||
|
monkeypatch.delenv("EEG_ANALYSIS_CLUSTER", raising=False)
|
||||||
|
launches = []
|
||||||
|
engine = create_engine("sqlite://", poolclass=StaticPool)
|
||||||
|
Eeg.__table__.create(engine)
|
||||||
|
with Session(engine) as session:
|
||||||
|
session.add_all([Eeg(eeg_id="1", eeg_estudio=b"edf"), Eeg(eeg_id="2"),
|
||||||
|
Eeg(eeg_id="ed257fbd-61d5-4c9c-bb72-00c4ec550961", eeg_estudio=b"edf"),
|
||||||
|
Eeg(eeg_id="a735a43f-376a-403a-b19f-13670130152a", eeg_estudio=b"edf")])
|
||||||
|
session.commit()
|
||||||
|
|
||||||
|
def popen(argv, **kwargs):
|
||||||
|
launches.append((argv[4:], kwargs["env"]))
|
||||||
|
return SimpleNamespace(pid=os.getpid())
|
||||||
|
|
||||||
|
monkeypatch.setattr(detached_jobs.subprocess, "Popen", popen)
|
||||||
|
monkeypatch.setattr(eeg_repository, "open_session", lambda: Session(engine))
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.register_blueprint(governance_bp, url_prefix="/governance")
|
||||||
|
yield app.test_client(), launches
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("body,flags", [
|
||||||
|
({}, []),
|
||||||
|
({"all": False}, []),
|
||||||
|
({"all": True}, ["--all"]),
|
||||||
|
({"limit": 4}, ["--limit", "4"]),
|
||||||
|
({"ids": [1, 2]}, ["--ids", "1,2"]),
|
||||||
|
({"ids": ["ed257fbd-61d5-4c9c-bb72-00c4ec550961", "a735a43f-376a-403a-b19f-13670130152a"]},
|
||||||
|
["--ids", "ed257fbd-61d5-4c9c-bb72-00c4ec550961,a735a43f-376a-403a-b19f-13670130152a"]),
|
||||||
|
])
|
||||||
|
def test_launch_scope(analysis_client, tmp_path, body, flags):
|
||||||
|
"""Pin scope flags, response fields and the progress directory. Fail if launch wiring changes."""
|
||||||
|
client, launches = analysis_client
|
||||||
|
response = client.post(URL, json=body)
|
||||||
|
|
||||||
|
assert response.status_code == 202
|
||||||
|
assert launches[0][0] == [sys.executable, "-m", "models", "tea", "analyze", *flags, "--cluster", "auto"]
|
||||||
|
assert response.json.keys() == {"id", "iniciado", "estado", "codigo", "salida", "error", "cluster", "ids", "summary"}
|
||||||
|
folder = tmp_path / "analisis_eeg" / response.json["id"]
|
||||||
|
assert launches[0][1]["RUN_PROGRESS_DIR"] == str(folder)
|
||||||
|
assert response.json["ids"] == ([str(i) for i in body["ids"]] if "ids" in body else None)
|
||||||
|
assert response.json["cluster"] is response.json["summary"] is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("choice,mode,scheduler", [
|
||||||
|
({"mode": "auto"}, "remote", "tcp://inherited:8786"),
|
||||||
|
({"mode": "local"}, "local", None),
|
||||||
|
({"mode": "sync"}, "sync", "tcp://inherited:8786"),
|
||||||
|
({"mode": "remote"}, "remote", "tcp://inherited:8786"),
|
||||||
|
({"mode": "remote", "scheduler": "tcp://chosen:8786"}, "remote", "tcp://chosen:8786"),
|
||||||
|
])
|
||||||
|
def test_cluster_choice(analysis_client, monkeypatch, choice, mode, scheduler):
|
||||||
|
"""Pin the cluster flag and training-style child environment. Fail if either loses the requested choice."""
|
||||||
|
client, launches = analysis_client
|
||||||
|
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "remote")
|
||||||
|
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://inherited:8786")
|
||||||
|
|
||||||
|
response = client.post(URL, json={"cluster": choice})
|
||||||
|
|
||||||
|
assert response.status_code == 202
|
||||||
|
argv, env = launches[0]
|
||||||
|
assert argv[-2:] == ["--cluster", choice["mode"]]
|
||||||
|
assert env["EEG_ANALYSIS_CLUSTER"] == mode
|
||||||
|
assert env.get("DASK_SCHEDULER_ADDRESS") == scheduler
|
||||||
|
assert response.json["cluster"] == (dict(choice, scheduler=scheduler) if mode == choice["mode"] == "remote" else choice)
|
||||||
|
assert os.environ["DASK_SCHEDULER_ADDRESS"] == "tcp://inherited:8786"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("body", [
|
||||||
|
[], {"all": 1}, {"limit": 0}, {"limit": True}, {"ids": []}, {"ids": [True]}, {"ids": None}, {"ids": ["a,b"]}, {"ids": [" "]}, {"ids": ["x" * 65]},
|
||||||
|
{"ids": [1], "all": True}, {"ids": [1], "limit": 2}, {"all": True, "limit": 2},
|
||||||
|
{"cluster": {"mode": "remote"}}, {"cluster": {"mode": "invalid"}},
|
||||||
|
])
|
||||||
|
def test_invalid_options(analysis_client, body):
|
||||||
|
"""Pin 400 for invalid options. Fail if malformed scopes or cluster choices launch a child."""
|
||||||
|
client, launches = analysis_client
|
||||||
|
assert client.post(URL, json=body).status_code == 400
|
||||||
|
assert not launches
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_eeg_ids(analysis_client):
|
||||||
|
"""Pin 404 and the missing IDs. Fail if an unknown EEG reaches the child."""
|
||||||
|
client, launches = analysis_client
|
||||||
|
response = client.post(URL, json={"ids": [1, 99, 98]})
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert "98, 99" in response.json["error"]
|
||||||
|
assert not launches
|
||||||
|
|
||||||
|
|
||||||
|
def test_refuses_second_analysis(analysis_client):
|
||||||
|
"""Pin the running-job conflict. Fail if a blank request can launch a concurrent analysis."""
|
||||||
|
client, launches = analysis_client
|
||||||
|
assert client.post(URL).status_code == 202
|
||||||
|
assert client.post(URL).status_code == 409
|
||||||
|
assert len(launches) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_saved_jobs_report_summary_and_list_newest_first(analysis_client, tmp_path):
|
||||||
|
"""Pin summary parsing after exit and descending job order. Fail if a running job exposes counts."""
|
||||||
|
client, _ = analysis_client
|
||||||
|
older, newer = "20260101T000000-aaaaaa", "20260102T000000-bbbbbb"
|
||||||
|
for job_id in (newer, older):
|
||||||
|
folder = tmp_path / "analisis_eeg" / job_id
|
||||||
|
folder.mkdir(parents=True)
|
||||||
|
(folder / "job.json").write_text(json.dumps({"id": job_id, "pid": os.getpid(), "iniciado": job_id}))
|
||||||
|
(folder / "stdout.log").write_text(f"analysis output\nsummary: {json.dumps(SUMMARY)}\n")
|
||||||
|
if job_id == older:
|
||||||
|
(folder / "exit").write_text("1\n")
|
||||||
|
|
||||||
|
jobs = client.get(URL).json
|
||||||
|
assert [job["id"] for job in jobs] == [newer, older]
|
||||||
|
assert jobs[0]["estado"] == "en_curso" and jobs[0]["summary"] is None
|
||||||
|
assert jobs[1]["estado"] == "fallido" and jobs[1]["summary"] == SUMMARY
|
||||||
|
assert client.get(f"{URL}/{older}").json == jobs[1]
|
||||||
|
assert client.get(f"{URL}/unknown").status_code == 404
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
"""Cover TEA training options and compatibility through the governance route.
|
||||||
|
|
||||||
|
Fixtures: training_client uses a temporary job directory and captures subprocess launches.
|
||||||
|
Fails if request options stop controlling argv, the child environment, or persisted state.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
from webapi import training_jobs
|
||||||
|
from webapi.blueprints.governance import governance_bp
|
||||||
|
|
||||||
|
TRAIN_URL = "/governance/model-versions/tea/eeg/train-jobs"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def training_client(tmp_path, monkeypatch):
|
||||||
|
"""Capture training launches. Real subprocesses would bypass the captured argv and environment."""
|
||||||
|
for variable in (*training_jobs.REFERENCE_ENV.values(), "TEA_REFERENCE_ROOT",
|
||||||
|
"DASK_SCHEDULER_ADDRESS", "EEG_ANALYSIS_CLUSTER"):
|
||||||
|
monkeypatch.delenv(variable, raising=False)
|
||||||
|
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
|
||||||
|
launches = []
|
||||||
|
|
||||||
|
def popen(argv, **kwargs):
|
||||||
|
launches.append((argv[4:], kwargs["env"]))
|
||||||
|
return SimpleNamespace(pid=os.getpid())
|
||||||
|
|
||||||
|
monkeypatch.setattr(training_jobs.subprocess, "Popen", popen)
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.register_blueprint(governance_bp, url_prefix="/governance")
|
||||||
|
return app.test_client(), launches
|
||||||
|
|
||||||
|
|
||||||
|
def test_body_overrides_reference_environment(training_client, monkeypatch, tmp_path):
|
||||||
|
"""Pin body precedence and persisted choices. Fail if an override or flag is lost."""
|
||||||
|
client, launches = training_client
|
||||||
|
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
|
||||||
|
monkeypatch.setenv("TEA_REFERENCE_NAME", "fallback")
|
||||||
|
monkeypatch.setenv("TEA_REFERENCE_DIR", str(tmp_path / "fallback"))
|
||||||
|
monkeypatch.setenv("TEA_REFERENCE_AGES", str(tmp_path / "fallback.csv"))
|
||||||
|
monkeypatch.setenv("TEA_REFERENCE_LINE_HZ", "60")
|
||||||
|
body = {
|
||||||
|
"reference_name": "cohort-1",
|
||||||
|
"reference_dir": str(tmp_path / "cohort"),
|
||||||
|
"reference_ages": str(tmp_path / "ages.csv"),
|
||||||
|
"line_hz": 50,
|
||||||
|
"promote": False,
|
||||||
|
"cluster": {"mode": "local"},
|
||||||
|
}
|
||||||
|
|
||||||
|
response = client.post(TRAIN_URL, json=body)
|
||||||
|
|
||||||
|
assert response.status_code == 202
|
||||||
|
job = response.json["job"]
|
||||||
|
assert job["cluster"] == body["cluster"]
|
||||||
|
argv, _ = launches[0]
|
||||||
|
assert argv == [
|
||||||
|
sys.executable, "-m", "models", "run", "tea", "eeg", "--environment", "prod", "--train",
|
||||||
|
"--reference-dir", body["reference_dir"], "--reference-ages", body["reference_ages"],
|
||||||
|
"--line-hz", "50", "--reference-name", "cohort-1",
|
||||||
|
]
|
||||||
|
folder = tmp_path / "entrenamientos" / job["id"]
|
||||||
|
saved = json.loads((folder / "job.json").read_text())
|
||||||
|
assert saved["parameters"] == {key: value for key, value in body.items() if key != "cluster"}
|
||||||
|
assert saved["cluster"] == body["cluster"]
|
||||||
|
assert client.get(f"/governance/training-jobs/{job['id']}").json["job"]["cluster"] == body["cluster"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_reference_name_can_be_passed_without_a_directory(training_client):
|
||||||
|
"""Pin a name-only request. Fail if the flag becomes conditional on a reference directory."""
|
||||||
|
client, launches = training_client
|
||||||
|
|
||||||
|
response = client.post(TRAIN_URL, json={"reference_name": "cohort-1", "promote": True})
|
||||||
|
|
||||||
|
assert response.status_code == 202
|
||||||
|
argv, _ = launches[0]
|
||||||
|
assert argv[-2:] == ["--reference-name", "cohort-1"]
|
||||||
|
assert "--reference-dir" not in argv
|
||||||
|
assert "--promote" in argv
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cluster,mode,scheduler", [
|
||||||
|
(None, "remote", "tcp://inherited:8786"),
|
||||||
|
({"mode": "auto"}, "remote", "tcp://inherited:8786"),
|
||||||
|
({"mode": "local"}, "local", None),
|
||||||
|
({"mode": "sync"}, "sync", "tcp://inherited:8786"),
|
||||||
|
({"mode": "remote"}, "remote", "tcp://inherited:8786"),
|
||||||
|
({"mode": "remote", "scheduler": "tcp://chosen:8786"}, "remote", "tcp://chosen:8786"),
|
||||||
|
])
|
||||||
|
def test_cluster_changes_only_the_child_environment(training_client, monkeypatch, cluster, mode, scheduler):
|
||||||
|
"""Pin cluster variables and scheduler fallback. Fail if mode leaks into argv or the parent."""
|
||||||
|
client, launches = training_client
|
||||||
|
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "remote")
|
||||||
|
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://inherited:8786")
|
||||||
|
|
||||||
|
response = client.post(TRAIN_URL, json={"cluster": cluster} if cluster else {})
|
||||||
|
|
||||||
|
assert response.status_code == 202
|
||||||
|
choice = {"mode": "remote", "scheduler": scheduler} if cluster == {"mode": "remote"} else cluster
|
||||||
|
assert response.json["job"]["cluster"] == choice
|
||||||
|
argv, env = launches[0]
|
||||||
|
assert argv == [sys.executable, "-m", "models", "run", "tea", "eeg", "--environment", "prod", "--train", "--promote"]
|
||||||
|
assert env["EEG_ANALYSIS_CLUSTER"] == mode
|
||||||
|
assert env.get("DASK_SCHEDULER_ADDRESS") == scheduler
|
||||||
|
assert os.environ["EEG_ANALYSIS_CLUSTER"] == "remote"
|
||||||
|
assert os.environ["DASK_SCHEDULER_ADDRESS"] == "tcp://inherited:8786"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("field", ["reference_dir", "reference_ages"])
|
||||||
|
def test_reference_paths_must_resolve_inside_root(training_client, monkeypatch, tmp_path, field):
|
||||||
|
"""Pin containment after symlink resolution. Fail if a local path can escape the root."""
|
||||||
|
client, launches = training_client
|
||||||
|
root = tmp_path / "reference"
|
||||||
|
root.mkdir()
|
||||||
|
(root / "escape").symlink_to(tmp_path, target_is_directory=True)
|
||||||
|
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(root))
|
||||||
|
|
||||||
|
response = client.post(TRAIN_URL, json={field: str(root / "escape")})
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert field in response.json["error"]
|
||||||
|
assert not launches
|
||||||
|
|
||||||
|
|
||||||
|
def test_remote_reference_can_be_outside_root(training_client, monkeypatch, tmp_path):
|
||||||
|
"""Pin the remote path exemption. Fail if worker paths are rejected by the API root check."""
|
||||||
|
client, launches = training_client
|
||||||
|
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
|
||||||
|
|
||||||
|
response = client.post(TRAIN_URL, json={
|
||||||
|
"reference_dir": "/worker/reference",
|
||||||
|
"cluster": {"mode": "remote", "scheduler": "tcp://chosen:8786"},
|
||||||
|
})
|
||||||
|
|
||||||
|
assert response.status_code == 202
|
||||||
|
assert "/worker/reference" in launches[0][0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_remote_requires_a_scheduler(training_client):
|
||||||
|
"""Pin the missing-scheduler response. Fail if an unconfigured remote job starts."""
|
||||||
|
client, launches = training_client
|
||||||
|
|
||||||
|
response = client.post(TRAIN_URL, json={"cluster": {"mode": "remote"}})
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert "DASK_SCHEDULER_ADDRESS" in response.json["error"]
|
||||||
|
assert not launches
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("request_options", [{}, {"json": {}}])
|
||||||
|
def test_empty_body_keeps_environment_defaults(training_client, monkeypatch, tmp_path, request_options):
|
||||||
|
"""Pin launch defaults and the progress folder. Fail if either is lost for an empty request."""
|
||||||
|
client, launches = training_client
|
||||||
|
monkeypatch.setenv("TEA_REFERENCE_DIR", "/reference")
|
||||||
|
monkeypatch.setenv("TEA_REFERENCE_AGES", "/reference/ages.csv")
|
||||||
|
monkeypatch.setenv("TEA_REFERENCE_LINE_HZ", "50")
|
||||||
|
|
||||||
|
response = client.post(TRAIN_URL, **request_options)
|
||||||
|
|
||||||
|
assert response.status_code == 202
|
||||||
|
assert response.json["job"]["cluster"] is None
|
||||||
|
argv, env = launches[0]
|
||||||
|
folder = tmp_path / "entrenamientos" / response.json["job"]["id"]
|
||||||
|
assert env == {**os.environ, "RUN_PROGRESS_DIR": str(folder)}
|
||||||
|
assert argv == [
|
||||||
|
sys.executable, "-m", "models", "run", "tea", "eeg", "--environment", "prod", "--train", "--promote",
|
||||||
|
"--reference-dir", "/reference", "--reference-ages", "/reference/ages.csv", "--line-hz", "50",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("body", [
|
||||||
|
{"reference_name": "nested/cohort"},
|
||||||
|
{"reference_name": "a" * 65},
|
||||||
|
{"reference_dir": "relative"},
|
||||||
|
{"line_hz": 55},
|
||||||
|
{"promote": "false"},
|
||||||
|
{"cluster": {"mode": "unknown"}},
|
||||||
|
[],
|
||||||
|
])
|
||||||
|
def test_invalid_body_options_are_rejected(training_client, body):
|
||||||
|
"""Pin JSON and option validation. Fail if an invalid value reaches the subprocess."""
|
||||||
|
client, launches = training_client
|
||||||
|
|
||||||
|
response = client.post(TRAIN_URL, json=body)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json["error"]
|
||||||
|
assert not launches
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_named_cohort_is_trained_from_its_folder_and_ages(training_client, monkeypatch, tmp_path):
|
||||||
|
"""Pin that a cohort name with a folder under `TEA_REFERENCE_ROOT` launches with that folder, its `edades.csv`
|
||||||
|
and the chosen line frequency. Fail if the name stays a bare label, which the child rejects without a directory."""
|
||||||
|
client, launches = training_client
|
||||||
|
cohort = tmp_path / "tiny"
|
||||||
|
cohort.mkdir()
|
||||||
|
(cohort / "edades.csv").write_text("archivo,edad_meses\na.edf,20\n")
|
||||||
|
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
|
||||||
|
|
||||||
|
response = client.post(TRAIN_URL, json={"reference_name": "tiny", "line_hz": 50, "promote": False})
|
||||||
|
|
||||||
|
assert response.status_code == 202
|
||||||
|
argv, _ = launches[0]
|
||||||
|
assert argv[argv.index("--reference-dir") + 1] == str(cohort.resolve())
|
||||||
|
assert argv[argv.index("--reference-ages") + 1] == str((cohort / "edades.csv").resolve())
|
||||||
|
assert argv[argv.index("--line-hz") + 1] == "50"
|
||||||
|
assert argv[argv.index("--reference-name") + 1] == "tiny"
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_explicit_directory_wins_over_the_cohort_folder(training_client, monkeypatch, tmp_path):
|
||||||
|
"""Pin that a request giving `reference_dir` is never redirected to the cohort named beside it.
|
||||||
|
Fail if resolving a name overrides a directory the caller chose."""
|
||||||
|
client, launches = training_client
|
||||||
|
(tmp_path / "tiny").mkdir()
|
||||||
|
(tmp_path / "other").mkdir()
|
||||||
|
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
|
||||||
|
|
||||||
|
client.post(TRAIN_URL, json={"reference_name": "tiny", "reference_dir": str(tmp_path / "other")})
|
||||||
|
|
||||||
|
argv, _ = launches[0]
|
||||||
|
assert argv[argv.index("--reference-dir") + 1] == str((tmp_path / "other").resolve())
|
||||||
|
assert "--reference-ages" not in argv
|
||||||
@@ -18,6 +18,7 @@ import os
|
|||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from dataclasses import asdict
|
from dataclasses import asdict
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from tempfile import NamedTemporaryFile
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
|
|
||||||
from core.governance.enums import EstatusExtraccion
|
from core.governance.enums import EstatusExtraccion
|
||||||
@@ -32,6 +33,10 @@ from models.reports import experiment
|
|||||||
from persistance.governance import extraction_run_repository
|
from persistance.governance import extraction_run_repository
|
||||||
from persistance.repository import Repository
|
from persistance.repository import Repository
|
||||||
from persistance.settings import settings
|
from persistance.settings import settings
|
||||||
|
from werkzeug.wsgi import wrap_file
|
||||||
|
|
||||||
|
from webapi.tea.analyze_jobs import AnalysisRunning, AnalyzeJobs
|
||||||
|
from webapi.tea.reference_cohorts import ReferenceCohortStore
|
||||||
|
|
||||||
governance_bp = Blueprint("governance", __name__)
|
governance_bp = Blueprint("governance", __name__)
|
||||||
|
|
||||||
@@ -57,6 +62,123 @@ def _pk_name(repository: Repository) -> str:
|
|||||||
return next(iter(repository.model.__table__.primary_key.columns)).name
|
return next(iter(repository.model.__table__.primary_key.columns)).name
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.get("/tea/cluster")
|
||||||
|
def tea_cluster_status():
|
||||||
|
"""Report health for a configured TEA cluster."""
|
||||||
|
from tea.pipeline.cluster_status import ClusterStatus
|
||||||
|
|
||||||
|
scheduler = request.args.get("scheduler")
|
||||||
|
if scheduler is not None:
|
||||||
|
allowed = {
|
||||||
|
address.strip()
|
||||||
|
for address in os.environ.get("TEA_DASK_SCHEDULERS", "").split(",")
|
||||||
|
if address.strip()
|
||||||
|
}
|
||||||
|
if not scheduler or (
|
||||||
|
scheduler != os.environ.get("DASK_SCHEDULER_ADDRESS") and scheduler not in allowed
|
||||||
|
):
|
||||||
|
raise ValueError("El planificador Dask no está autorizado.")
|
||||||
|
|
||||||
|
return jsonify(ClusterStatus().check(
|
||||||
|
mode=request.args.get("mode", "auto"),
|
||||||
|
scheduler=scheduler,
|
||||||
|
reference_name=request.args.get("reference"),
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.get("/tea/reference-cohorts")
|
||||||
|
def list_reference_cohorts():
|
||||||
|
"""List the stored TEA reference cohorts."""
|
||||||
|
root = os.environ.get("TEA_REFERENCE_ROOT")
|
||||||
|
if not root:
|
||||||
|
return jsonify({"error": "TEA_REFERENCE_ROOT no está configurado."}), 503
|
||||||
|
return jsonify(ReferenceCohortStore(root).list_cohorts())
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.post("/tea/reference-cohorts/<path:name>/files")
|
||||||
|
def upload_reference_cohort_file(name: str):
|
||||||
|
"""Add an EDF or an age table to a reference cohort."""
|
||||||
|
root = os.environ.get("TEA_REFERENCE_ROOT")
|
||||||
|
if not root:
|
||||||
|
return jsonify({"error": "TEA_REFERENCE_ROOT no está configurado."}), 503
|
||||||
|
upload = request.files.get("file")
|
||||||
|
if upload is None or not upload.filename:
|
||||||
|
return jsonify({"error": "Se requiere el campo file."}), 400
|
||||||
|
return jsonify(ReferenceCohortStore(root).save_file(name, upload.filename, upload.stream)), 201
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.get("/tea/baselines/export")
|
||||||
|
def export_baselines():
|
||||||
|
"""Download trained EEG baselines as a ZIP."""
|
||||||
|
from webapi.tea.baselines import BaselineBundles
|
||||||
|
|
||||||
|
production = request.args.get("production", "0")
|
||||||
|
if production not in ("0", "1"):
|
||||||
|
return jsonify({"error": "production debe ser 0 o 1."}), 400
|
||||||
|
|
||||||
|
archive = NamedTemporaryFile(suffix=".zip")
|
||||||
|
try:
|
||||||
|
exported = BaselineBundles().export(
|
||||||
|
Path(archive.name), environment=request.args.get("environment", "prod"), production=production == "1"
|
||||||
|
)
|
||||||
|
response = Response(wrap_file(request.environ, archive), mimetype="application/zip")
|
||||||
|
response.headers["Content-Disposition"] = "attachment; filename=baselines.zip"
|
||||||
|
response.headers["X-Baselines-Sha256"] = exported.sha256
|
||||||
|
response.headers["X-Baselines-Versions"] = str(len(exported.versions))
|
||||||
|
return response
|
||||||
|
except BaseException:
|
||||||
|
archive.close()
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.post("/tea/baselines/import")
|
||||||
|
def import_baselines():
|
||||||
|
"""Register trained EEG baselines from an uploaded ZIP."""
|
||||||
|
from webapi.tea.baselines import BaselineBundles, BaselineConflict
|
||||||
|
|
||||||
|
upload = request.files.get("file")
|
||||||
|
if upload is None or not upload.filename:
|
||||||
|
return jsonify({"error": "Se requiere el campo file."}), 400
|
||||||
|
try:
|
||||||
|
return jsonify(BaselineBundles().import_(upload.stream))
|
||||||
|
except BaselineConflict as error:
|
||||||
|
return jsonify({"error": str(error)}), 409
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.post("/tea/eeg/upload")
|
||||||
|
def upload_eeg():
|
||||||
|
"""Register one EDF file as an EEG through the import pipeline."""
|
||||||
|
from webapi.imports.services.import_service import ImportRequestError
|
||||||
|
from webapi.tea.edf_intake import EdfIntake
|
||||||
|
|
||||||
|
upload = request.files.get("file")
|
||||||
|
if upload is None or not upload.filename:
|
||||||
|
return jsonify({"error": "Se requiere el campo file."}), 400
|
||||||
|
patient = request.form.get("patient_id", "").strip()
|
||||||
|
if patient and not patient.isdigit():
|
||||||
|
return jsonify({"error": "patient_id debe ser un entero."}), 400
|
||||||
|
try:
|
||||||
|
added = EdfIntake().add(upload.filename, upload.read(), int(patient) if patient else None)
|
||||||
|
except (ImportRequestError, ValueError) as error:
|
||||||
|
return jsonify({"error": str(error)}), 400
|
||||||
|
return jsonify(added), 201
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.post("/tea/eeg/preview")
|
||||||
|
def preview_eeg():
|
||||||
|
"""Analyse one EDF, and the child's ADOS-2 report if given, without storing either: the summary bundle."""
|
||||||
|
from webapi.tea.eeg_preview import EegPreview, PreviewError
|
||||||
|
|
||||||
|
edf = request.files.get("edf")
|
||||||
|
if edf is None or not edf.filename:
|
||||||
|
return jsonify({"error": "Se requiere el campo edf."}), 400
|
||||||
|
report = request.files.get("ados2")
|
||||||
|
try:
|
||||||
|
return jsonify(EegPreview().run(edf.read(), report.read() if report is not None and report.filename else None))
|
||||||
|
except PreviewError as error:
|
||||||
|
return jsonify({"error": str(error)}), 400
|
||||||
|
|
||||||
|
|
||||||
# -- model versions ----------------------------------------------------------------
|
# -- model versions ----------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
@@ -142,6 +264,11 @@ def start_training_job(domain: str, scenario: str):
|
|||||||
return jsonify({"error": "Ya hay un entrenamiento en curso para este modelo.",
|
return jsonify({"error": "Ya hay un entrenamiento en curso para este modelo.",
|
||||||
"job": training_jobs.running(domain, scenario)}), 409
|
"job": training_jobs.running(domain, scenario)}), 409
|
||||||
try:
|
try:
|
||||||
|
if domain == "tea" and request.get_data():
|
||||||
|
body = request.get_json(silent=True)
|
||||||
|
if not isinstance(body, dict):
|
||||||
|
raise ValueError("El cuerpo debe ser un objeto JSON.")
|
||||||
|
return jsonify({"job": training_jobs.start(domain, scenario, body)}), 202
|
||||||
return jsonify({"job": training_jobs.start(domain, scenario)}), 202
|
return jsonify({"job": training_jobs.start(domain, scenario)}), 202
|
||||||
except RuntimeError as error:
|
except RuntimeError as error:
|
||||||
return jsonify({"error": str(error)}), 503
|
return jsonify({"error": str(error)}), 503
|
||||||
@@ -441,6 +568,49 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
|
|||||||
return jsonify(updated)
|
return jsonify(updated)
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.post("/tea/eeg/analyze-jobs")
|
||||||
|
def start_analyze_job():
|
||||||
|
"""Start a detached EEG analysis."""
|
||||||
|
body = request.get_json(silent=True) if request.get_data() else {}
|
||||||
|
try:
|
||||||
|
return jsonify(AnalyzeJobs().start(body)), 202
|
||||||
|
except AnalysisRunning as error:
|
||||||
|
return jsonify({"error": str(error)}), 409
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.get("/tea/eeg/analyze-jobs")
|
||||||
|
def list_analyze_jobs():
|
||||||
|
"""List detached EEG analyses."""
|
||||||
|
return jsonify(AnalyzeJobs().jobs())
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.get("/tea/eeg/analyze-jobs/<job_id>")
|
||||||
|
def analyze_job(job_id: str):
|
||||||
|
"""Read a detached EEG analysis."""
|
||||||
|
return jsonify(AnalyzeJobs().get(job_id))
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.get("/tea/jobs/<kind>/<path:job_id>/progress")
|
||||||
|
def tea_job_progress(kind: str, job_id: str):
|
||||||
|
"""Read the latest progress snapshot for a detached TEA job."""
|
||||||
|
from webapi import training_jobs
|
||||||
|
|
||||||
|
if kind == "train":
|
||||||
|
base = training_jobs._base()
|
||||||
|
elif kind == "analyze":
|
||||||
|
base = AnalyzeJobs().base
|
||||||
|
else:
|
||||||
|
raise ValueError("Tipo de trabajo TEA no válido.")
|
||||||
|
|
||||||
|
folder = base / job_id
|
||||||
|
if "/" not in job_id and job_id not in {".", ".."} and (folder / "job.json").is_file():
|
||||||
|
try:
|
||||||
|
return jsonify(json.loads((folder / "progress.json").read_text(encoding="utf-8")))
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
|
raise LookupError(f"No se encontró el progreso del trabajo {job_id}.")
|
||||||
|
|
||||||
|
|
||||||
@governance_bp.post("/eeg/run")
|
@governance_bp.post("/eeg/run")
|
||||||
def run_eeg_analysis():
|
def run_eeg_analysis():
|
||||||
"""Runs TEA's EEG analysis on the stored EDFs that need it (`models.eeg_analysis`), in this request: at most
|
"""Runs TEA's EEG analysis on the stored EDFs that need it (`models.eeg_analysis`), in this request: at most
|
||||||
@@ -495,3 +665,47 @@ def run_ocr():
|
|||||||
"needs_review": summary.needs_review,
|
"needs_review": summary.needs_review,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.get("/tea/baselines/<scenario>/<int:version>/metrics")
|
||||||
|
def tea_baseline_metrics(scenario: str, version: int):
|
||||||
|
"""List the metrics with a curve in the baseline version."""
|
||||||
|
from webapi.tea.eeg_queries import BaselineQueries
|
||||||
|
|
||||||
|
return jsonify(BaselineQueries(scenario, version).metrics())
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.get("/tea/baselines/<scenario>/<int:version>/curve")
|
||||||
|
def tea_baseline_curve(scenario: str, version: int):
|
||||||
|
"""Read a metric's curve from the baseline version."""
|
||||||
|
from webapi.tea.eeg_queries import BaselineQueries
|
||||||
|
|
||||||
|
return jsonify(BaselineQueries(scenario, version).curve(request.args.get("metric", "").lower()))
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.get("/tea/eeg")
|
||||||
|
def tea_eeg_recordings():
|
||||||
|
"""List EEG recordings with their analysis status."""
|
||||||
|
from webapi.tea.eeg_queries import EegQueries
|
||||||
|
|
||||||
|
limit = int(request.args.get("limit", 200))
|
||||||
|
offset = int(request.args.get("offset", 0))
|
||||||
|
if limit < 0 or offset < 0:
|
||||||
|
raise ValueError("El límite y el desplazamiento deben ser mayores o iguales a cero.")
|
||||||
|
return jsonify(EegQueries().recordings(limit, offset))
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.get("/tea/eeg/<eeg_id>/metrics")
|
||||||
|
def tea_eeg_metrics(eeg_id: str):
|
||||||
|
"""Read one EEG's verdict and metric values."""
|
||||||
|
from webapi.tea.eeg_queries import EegQueries
|
||||||
|
|
||||||
|
return jsonify(EegQueries().metrics(eeg_id))
|
||||||
|
|
||||||
|
|
||||||
|
@governance_bp.get("/tea/eeg/summary")
|
||||||
|
def tea_eeg_summary():
|
||||||
|
"""Count EEG analysis outcomes and FHIR view rows."""
|
||||||
|
from webapi.tea.eeg_queries import EegQueries
|
||||||
|
|
||||||
|
return jsonify(EegQueries().summary())
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
"""Aggregate reports: the log of import attempts and the state of the live
|
"""Aggregate reports: the log of import attempts and the state of the live
|
||||||
indicator recomputation. Nothing here returns row-level data."""
|
indicator recomputation. Nothing here returns row-level data."""
|
||||||
|
import os
|
||||||
|
|
||||||
from flask import Blueprint, Response, jsonify, request
|
from flask import Blueprint, Response, jsonify, request
|
||||||
|
|
||||||
|
from webapi.detached_jobs import cluster_environment
|
||||||
from webapi.imports import audit as import_audit
|
from webapi.imports import audit as import_audit
|
||||||
from webapi.recomputation import DOMAINS, RecomputationQueue
|
from webapi.recomputation import DOMAINS, RecomputationQueue
|
||||||
|
|
||||||
@@ -45,5 +48,12 @@ def recomputation_status():
|
|||||||
def recompute(dominio: str):
|
def recompute(dominio: str):
|
||||||
if dominio not in DOMAINS:
|
if dominio not in DOMAINS:
|
||||||
return jsonify({"error": f"dominio desconocido: {dominio}"}), 404
|
return jsonify({"error": f"dominio desconocido: {dominio}"}), 404
|
||||||
RecomputationQueue().request_run(dominio)
|
body = request.get_json(silent=True) if request.get_data() else {}
|
||||||
|
if not isinstance(body, dict):
|
||||||
|
return jsonify({"error": "El cuerpo debe ser un objeto JSON."}), 400
|
||||||
|
try:
|
||||||
|
cluster = cluster_environment(body, dict(os.environ))
|
||||||
|
except ValueError as error:
|
||||||
|
return jsonify({"error": str(error)}), 400
|
||||||
|
RecomputationQueue().request_run(dominio, cluster)
|
||||||
return jsonify({"pendiente": True}), 202
|
return jsonify({"pendiente": True}), 202
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
"""File-backed state and launch support for detached jobs."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
TAIL_CHARS = 4000
|
||||||
|
|
||||||
|
|
||||||
|
def cluster_environment(body: dict, env: dict[str, str]) -> dict | None:
|
||||||
|
"""Apply a cluster choice to the child environment."""
|
||||||
|
if "cluster" not in body:
|
||||||
|
return None
|
||||||
|
cluster = body["cluster"]
|
||||||
|
if not isinstance(cluster, dict) or cluster.get("mode") not in ("auto", "local", "remote", "sync"):
|
||||||
|
raise ValueError("cluster.mode debe ser auto, local, remote o sync.")
|
||||||
|
mode = cluster["mode"]
|
||||||
|
scheduler = cluster.get("scheduler")
|
||||||
|
if "scheduler" in cluster and (not isinstance(scheduler, str) or not scheduler.strip() or "\0" in scheduler):
|
||||||
|
raise ValueError("cluster.scheduler debe ser texto no vacío.")
|
||||||
|
if mode == "auto":
|
||||||
|
return {"mode": mode}
|
||||||
|
env["EEG_ANALYSIS_CLUSTER"] = mode
|
||||||
|
if mode == "local":
|
||||||
|
env.pop("DASK_SCHEDULER_ADDRESS", None)
|
||||||
|
if mode == "remote":
|
||||||
|
scheduler = scheduler or env.get("DASK_SCHEDULER_ADDRESS")
|
||||||
|
if not scheduler:
|
||||||
|
raise ValueError("El modo remote requiere cluster.scheduler o DASK_SCHEDULER_ADDRESS.")
|
||||||
|
env["DASK_SCHEDULER_ADDRESS"] = scheduler
|
||||||
|
return {"mode": mode, "scheduler": scheduler}
|
||||||
|
return {"mode": mode}
|
||||||
|
|
||||||
|
|
||||||
|
def _alive(pid: int) -> bool:
|
||||||
|
try:
|
||||||
|
os.kill(pid, 0)
|
||||||
|
except ProcessLookupError:
|
||||||
|
return False
|
||||||
|
except PermissionError:
|
||||||
|
return True
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _tail(path: Path) -> str:
|
||||||
|
return path.read_text(encoding="utf-8", errors="replace")[-TAIL_CHARS:].strip() if path.exists() else ""
|
||||||
|
|
||||||
|
|
||||||
|
def state(folder: Path) -> dict:
|
||||||
|
"""Read job metadata, logs, and process state."""
|
||||||
|
job = json.loads((folder / "job.json").read_text(encoding="utf-8"))
|
||||||
|
exit_file = folder / "exit"
|
||||||
|
code = int(exit_file.read_text().strip() or 1) if exit_file.exists() else None
|
||||||
|
out, err = _tail(folder / "stdout.log"), _tail(folder / "stderr.log")
|
||||||
|
if code == 0:
|
||||||
|
status = "completado"
|
||||||
|
elif code is not None:
|
||||||
|
status = "fallido"
|
||||||
|
else:
|
||||||
|
status = "en_curso" if _alive(job["pid"]) else "interrumpido"
|
||||||
|
return {**job, "estado": status, "codigo": code, "salida": out, "error": err}
|
||||||
|
|
||||||
|
|
||||||
|
def launch(base: Path, argv: list[str], env: dict[str, str], metadata: dict, *,
|
||||||
|
precise_id: bool = False, cwd: Path | None = None) -> Path:
|
||||||
|
"""Start a detached command and publish its job metadata."""
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
timestamp = now.strftime("%Y%m%dT%H%M%S%f" if precise_id else "%Y%m%dT%H%M%S")
|
||||||
|
job_id = f"{timestamp}-{uuid.uuid4().hex[:6]}"
|
||||||
|
folder = base / job_id
|
||||||
|
folder.mkdir(parents=True)
|
||||||
|
shell = '{ "$@" > "$0/stdout.log" 2> "$0/stderr.log"; echo $? > "$0/exit.tmp"; mv "$0/exit.tmp" "$0/exit"; }'
|
||||||
|
process = subprocess.Popen(["sh", "-c", shell, str(folder.resolve()), *argv],
|
||||||
|
cwd=cwd or folder, env={**env, "RUN_PROGRESS_DIR": str(folder.resolve())},
|
||||||
|
start_new_session=True,
|
||||||
|
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||||
|
job = {**metadata, "id": job_id, "pid": process.pid,
|
||||||
|
"iniciado": datetime.now(timezone.utc).isoformat(timespec="seconds")}
|
||||||
|
temporary = folder / "job.json.tmp"
|
||||||
|
temporary.write_text(json.dumps(job), encoding="utf-8")
|
||||||
|
temporary.replace(folder / "job.json")
|
||||||
|
return folder
|
||||||
|
|
||||||
|
|
||||||
|
def folders(base: Path) -> list[Path]:
|
||||||
|
"""List published jobs newest first by their timestamped IDs."""
|
||||||
|
return sorted((path for path in base.glob("*") if (path / "job.json").exists()), reverse=True)
|
||||||
+10
-8
@@ -273,7 +273,7 @@ def quality_observations(eeg: dict, checks: list[dict], pseudonym: str, simulate
|
|||||||
return observations
|
return observations
|
||||||
|
|
||||||
|
|
||||||
def curve_extension(label: str, curve: dict) -> dict:
|
def curve_extension(label: str, curve: dict, validated: bool | None = None) -> dict:
|
||||||
"""The reference curve as one nested extension on the metric observation. `fuente` is the baseline's registered
|
"""The reference curve as one nested extension on the metric observation. `fuente` is the baseline's registered
|
||||||
label and `estado` the alterations validation gate (`TEA_ALTERACIONES_VALIDADAS`); each series is a run of
|
label and `estado` the alterations validation gate (`TEA_ALTERACIONES_VALIDADAS`); each series is a run of
|
||||||
sub-extensions, one per point, read back in order (`edad-meses`, then the five percentiles), because a FHIR
|
sub-extensions, one per point, read back in order (`edad-meses`, then the five percentiles), because a FHIR
|
||||||
@@ -281,12 +281,12 @@ def curve_extension(label: str, curve: dict) -> dict:
|
|||||||
series = (("edad-meses", curve["edad_meses"]), *((p, curve[p]) for p in PERCENTILES))
|
series = (("edad-meses", curve["edad_meses"]), *((p, curve[p]) for p in PERCENTILES))
|
||||||
return {"url": CURVE, "extension": [
|
return {"url": CURVE, "extension": [
|
||||||
{"url": f"{CURVE}/fuente", "valueString": label},
|
{"url": f"{CURVE}/fuente", "valueString": label},
|
||||||
{"url": f"{CURVE}/estado", "valueString": "validada" if alterations_validated() else "pendiente"},
|
{"url": f"{CURVE}/estado", "valueString": "validada" if (alterations_validated() if validated is None else validated) else "pendiente"},
|
||||||
*({"url": f"{CURVE}/{name}", "valueDecimal": float(value)} for name, values in series for value in values)]}
|
*({"url": f"{CURVE}/{name}", "valueDecimal": float(value)} for name, values in series for value in values)]}
|
||||||
|
|
||||||
|
|
||||||
def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], pseudonym: str,
|
def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], pseudonym: str,
|
||||||
simulated: bool, curves=None) -> list[dict]:
|
simulated: bool, curves=None, validated: bool | None = None) -> list[dict]:
|
||||||
"""One `Observation` per metric and one per metric with each electrode's z-score as a component. A metric's
|
"""One `Observation` per metric and one per metric with each electrode's z-score as a component. A metric's
|
||||||
observation has its value, or `not-performed` without one; with a z, also its age baseline's p5-p95 at the EEG
|
observation has its value, or `not-performed` without one; with a z, also its age baseline's p5-p95 at the EEG
|
||||||
as the reference, H/L/N, and the z and the baseline's median as components. With the baseline's label
|
as the reference, H/L/N, and the z and the baseline's median as components. With the baseline's label
|
||||||
@@ -322,7 +322,7 @@ def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict],
|
|||||||
if curves is not None and m.get("modelo"):
|
if curves is not None and m.get("modelo"):
|
||||||
curve = curves.curve(m["modelo"], m["metrica"])
|
curve = curves.curve(m["modelo"], m["metrica"])
|
||||||
if curve is not None:
|
if curve is not None:
|
||||||
resource.setdefault("extension", []).append(curve_extension(m["modelo"], curve))
|
resource.setdefault("extension", []).append(curve_extension(m["modelo"], curve, validated))
|
||||||
observations.append(tagged(resource, simulated))
|
observations.append(tagged(resource, simulated))
|
||||||
at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"]
|
at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"]
|
||||||
and x["valor_z"] is not None]
|
and x["valor_z"] is not None]
|
||||||
@@ -338,14 +338,16 @@ def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict],
|
|||||||
|
|
||||||
|
|
||||||
def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool,
|
def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool,
|
||||||
checks: list[dict] = (), curves=None) -> list[dict]:
|
checks: list[dict] = (), curves=None, show_alterations: bool | None = None) -> list[dict]:
|
||||||
"""The recording as a `Procedure` and its result as a `DiagnosticReport` with its observations; a bad EEG has
|
"""The recording as a `Procedure` and its result as a `DiagnosticReport` with its observations; a bad EEG has
|
||||||
no result beyond its quality, and the alterations stay out until validated. The report carries the recording's
|
no result beyond its quality, and the alterations stay out until validated. The report carries the recording's
|
||||||
duration, channel count and the age the analysis compared the references at as extensions, and each metric
|
duration, channel count and the age the analysis compared the references at as extensions, and each metric
|
||||||
observation the baseline's full centile curve when its label resolves (`curves`)."""
|
observation the baseline's full centile curve when its label resolves (`curves`). `show_alterations` overrides
|
||||||
|
the validation gate for an analysis the caller shows without storing it; None follows the gate."""
|
||||||
quality = quality_observations(eeg, list(checks), pseudonym, simulated)
|
quality = quality_observations(eeg, list(checks), pseudonym, simulated)
|
||||||
altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated, curves)
|
shown = alterations_validated() if show_alterations is None else show_alterations
|
||||||
if eeg["valido"] == 1 and alterations_validated() else [])
|
altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated, curves, validated=shown)
|
||||||
|
if eeg["valido"] == 1 and shown else [])
|
||||||
procedure = tagged({"resourceType": "Procedure", "id": f"eeg-{eeg['procedimiento_id']}", "status": "completed",
|
procedure = tagged({"resourceType": "Procedure", "id": f"eeg-{eeg['procedimiento_id']}", "status": "completed",
|
||||||
"code": concept(CATALOG, "eeg", "Electroencefalograma"),
|
"code": concept(CATALOG, "eeg", "Electroencefalograma"),
|
||||||
"subject": {"reference": f"Patient/{pseudonym}"},
|
"subject": {"reference": f"Patient/{pseudonym}"},
|
||||||
|
|||||||
+48
-11
@@ -28,6 +28,7 @@ from types import SimpleNamespace
|
|||||||
from sqlalchemy import func, select
|
from sqlalchemy import func, select
|
||||||
from sqlmodel import Session
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
from webapi.follow_up.screening import rutas_de
|
||||||
from webapi.follow_up.silver import biopsias, citologias, notas
|
from webapi.follow_up.silver import biopsias, citologias, notas
|
||||||
from webapi.follow_up.status import ESTATUS, estatus_al, exigir_opcion, exigir_opciones, reglas_de
|
from webapi.follow_up.status import ESTATUS, estatus_al, exigir_opcion, exigir_opciones, reglas_de
|
||||||
from webapi.orchestration.tables.cacu import TABLAS
|
from webapi.orchestration.tables.cacu import TABLAS
|
||||||
@@ -99,6 +100,10 @@ def seguimiento_de(
|
|||||||
estatus: str | None = None,
|
estatus: str | None = None,
|
||||||
orden: str = "reciente",
|
orden: str = "reciente",
|
||||||
horizonte: float | None = None,
|
horizonte: float | None = None,
|
||||||
|
q: str | None = None,
|
||||||
|
edad_min: int | None = None,
|
||||||
|
edad_max: int | None = None,
|
||||||
|
incluir_ruta: bool = False,
|
||||||
page: int = 1,
|
page: int = 1,
|
||||||
page_size: int = 50,
|
page_size: int = 50,
|
||||||
hoy: date | None = None,
|
hoy: date | None = None,
|
||||||
@@ -127,6 +132,14 @@ def seguimiento_de(
|
|||||||
raise PedidoInvalido(f"orden desconocido {orden!r}; hay {list(ORDENES)}.")
|
raise PedidoInvalido(f"orden desconocido {orden!r}; hay {list(ORDENES)}.")
|
||||||
if page < 1 or not 1 <= page_size <= PAGINA_MAXIMA:
|
if page < 1 or not 1 <= page_size <= PAGINA_MAXIMA:
|
||||||
raise PedidoInvalido(f"page empieza en 1 y page_size va de 1 a {PAGINA_MAXIMA}.")
|
raise PedidoInvalido(f"page empieza en 1 y page_size va de 1 a {PAGINA_MAXIMA}.")
|
||||||
|
if any(v is not None and (isinstance(v, bool) or not isinstance(v, int) or v < 0) for v in (edad_min, edad_max)):
|
||||||
|
raise PedidoInvalido("Los límites de edad deben ser enteros no negativos.")
|
||||||
|
if edad_min is not None and edad_max is not None and edad_min > edad_max:
|
||||||
|
raise PedidoInvalido("edad_min no puede superar edad_max.")
|
||||||
|
if q is not None:
|
||||||
|
q = " ".join(q.split()).casefold()
|
||||||
|
if len(q) > 100:
|
||||||
|
raise PedidoInvalido("q admite hasta 100 caracteres.")
|
||||||
|
|
||||||
corte = _acotado(sesion, corte or hoy or date.today(), tablas)
|
corte = _acotado(sesion, corte or hoy or date.today(), tablas)
|
||||||
desde = _meses_antes(corte, meses) + timedelta(days=1)
|
desde = _meses_antes(corte, meses) + timedelta(days=1)
|
||||||
@@ -134,6 +147,13 @@ def seguimiento_de(
|
|||||||
items = _items(sesion, corte, desde, lista, estatus_de, tablas)
|
items = _items(sesion, corte, desde, lista, estatus_de, tablas)
|
||||||
if estatus is not None:
|
if estatus is not None:
|
||||||
items = [i for i in items if i["estatus"]["codigo"] == estatus]
|
items = [i for i in items if i["estatus"]["codigo"] == estatus]
|
||||||
|
if q:
|
||||||
|
items = [i for i in items if any(q in " ".join(str(i[k] or "").split()).casefold()
|
||||||
|
for k in ("pac_id", "id_seudonimo"))]
|
||||||
|
if edad_min is not None or edad_max is not None:
|
||||||
|
items = [i for i in items if i["edad_al_corte"] is not None
|
||||||
|
and (edad_min is None or i["edad_al_corte"] >= edad_min)
|
||||||
|
and (edad_max is None or i["edad_al_corte"] <= edad_max)]
|
||||||
horizontes = sorted({h["horizonte_anios"] for i in items for p in (i["probabilidades"] or {}).values() for h in p})
|
horizontes = sorted({h["horizonte_anios"] for i in items for p in (i["probabilidades"] or {}).values() for h in p})
|
||||||
horizonte = HORIZONTE_POR_OMISION if horizonte is None else float(horizonte)
|
horizonte = HORIZONTE_POR_OMISION if horizonte is None else float(horizonte)
|
||||||
if horizontes and horizonte not in horizontes:
|
if horizontes and horizonte not in horizontes:
|
||||||
@@ -147,16 +167,25 @@ def seguimiento_de(
|
|||||||
if total and page > paginas:
|
if total and page > paginas:
|
||||||
raise PaginaFuera(f"page {page} pasa de la última ({paginas}).")
|
raise PaginaFuera(f"page {page} pasa de la última ({paginas}).")
|
||||||
etiquetas = _etiquetas_de_estatus()
|
etiquetas = _etiquetas_de_estatus()
|
||||||
|
pagina = items[(page - 1) * page_size : page * page_size]
|
||||||
|
anclas = [i.pop("_toma_ruta", None) for i in pagina]
|
||||||
|
if incluir_ruta:
|
||||||
|
tomas = {ancla[0]: (int(item["pac_id"]), ancla[1])
|
||||||
|
for item, ancla in zip(pagina, anclas) if ancla is not None}
|
||||||
|
rutas = rutas_de(sesion, tomas, corte, tablas)
|
||||||
|
for item, ancla in zip(pagina, anclas):
|
||||||
|
item["ruta_tamizaje"] = rutas[ancla[0]] if ancla is not None else None
|
||||||
return {
|
return {
|
||||||
"simulado": True,
|
"simulado": True,
|
||||||
"corte": corte.isoformat(),
|
"corte": corte.isoformat(),
|
||||||
"ventana": {"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()},
|
"ventana": {"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()},
|
||||||
"filtros": {"estatus": estatus, "orden": orden, "horizonte": horizonte},
|
"filtros": {"estatus": estatus, "orden": orden, "horizonte": horizonte,
|
||||||
|
"q": q or None, "edad_min": edad_min, "edad_max": edad_max},
|
||||||
"horizontes_disponibles": horizontes,
|
"horizontes_disponibles": horizontes,
|
||||||
"estatus_disponibles": [{"codigo": c, "etiqueta": e} for c, e in etiquetas.items()],
|
"estatus_disponibles": [{"codigo": c, "etiqueta": e} for c, e in etiquetas.items()],
|
||||||
"reglas": _reglas_usadas(sesion, [*PARAMETROS_DE_LA_LISTA.values(), *del_estatus.values()], tablas),
|
"reglas": _reglas_usadas(sesion, [*PARAMETROS_DE_LA_LISTA.values(), *del_estatus.values()], tablas),
|
||||||
"paginacion": {"page": page, "page_size": page_size, "total_items": total, "total_pages": paginas},
|
"paginacion": {"page": page, "page_size": page_size, "total_items": total, "total_pages": paginas},
|
||||||
"items": items[(page - 1) * page_size : page * page_size],
|
"items": pagina,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -198,7 +227,7 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
|
|||||||
gravedad = {c["clave"]: i for i, c in enumerate(lista["catalogo"])}
|
gravedad = {c["clave"]: i for i, c in enumerate(lista["catalogo"])}
|
||||||
biopsia_de = _ultima_biopsia(sesion, corte, tablas)
|
biopsia_de = _ultima_biopsia(sesion, corte, tablas)
|
||||||
riesgos = _probabilidades_por_paciente()
|
riesgos = _probabilidades_por_paciente()
|
||||||
edades = _grupo_de_edad(sesion, corte, lista["grupos_edad"], tablas)
|
edades = _edades(sesion, corte, lista["grupos_edad"], tablas)
|
||||||
notas_de = _notas_por_paciente(sesion, corte)
|
notas_de = _notas_por_paciente(sesion, corte)
|
||||||
items = []
|
items = []
|
||||||
for pac_id, de_la_paciente in en_ventana.items():
|
for pac_id, de_la_paciente in en_ventana.items():
|
||||||
@@ -211,7 +240,8 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
|
|||||||
items.append({
|
items.append({
|
||||||
"pac_id": identificador(pac_id),
|
"pac_id": identificador(pac_id),
|
||||||
"id_seudonimo": identificador(pac_id),
|
"id_seudonimo": identificador(pac_id),
|
||||||
"grupo_edad": edades.get(pac_id, SIN_DATO),
|
"grupo_edad": edades.get(pac_id, (None, SIN_DATO))[1],
|
||||||
|
"edad_al_corte": edades.get(pac_id, (None, SIN_DATO))[0],
|
||||||
"estatus": {"codigo": estatus, "etiqueta": _etiquetas_de_estatus()[estatus]},
|
"estatus": {"codigo": estatus, "etiqueta": _etiquetas_de_estatus()[estatus]},
|
||||||
"ultima_citologia": None if cito is None else {
|
"ultima_citologia": None if cito is None else {
|
||||||
"fecha": cito["fecha"].isoformat(), "bethesda": cito["resultado"], "calidad": cito["calidad"],
|
"fecha": cito["fecha"].isoformat(), "bethesda": cito["resultado"], "calidad": cito["calidad"],
|
||||||
@@ -224,6 +254,7 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
|
|||||||
"ultima_biopsia": biopsia_de.get(pac_id),
|
"ultima_biopsia": biopsia_de.get(pac_id),
|
||||||
"probabilidades": {k: v[pac_id] for k, v in riesgos.items() if pac_id in v} or None,
|
"probabilidades": {k: v[pac_id] for k, v in riesgos.items() if pac_id in v} or None,
|
||||||
"prioridad": None,
|
"prioridad": None,
|
||||||
|
"_toma_ruta": None if cito is None else (cito["toma_id"], cito["toma"]),
|
||||||
"_orden": mas_reciente,
|
"_orden": mas_reciente,
|
||||||
})
|
})
|
||||||
items.sort(key=lambda i: int(i["pac_id"]))
|
items.sort(key=lambda i: int(i["pac_id"]))
|
||||||
@@ -283,17 +314,18 @@ def _estudios(sesion: Session, corte: date, fecha_estudio: str) -> list[dict]:
|
|||||||
"""Cada toma de citología hasta el corte, con lo que ya se sabía al corte (un resultado posterior no existe)."""
|
"""Cada toma de citología hasta el corte, con lo que ya se sabía al corte (un resultado posterior no existe)."""
|
||||||
c = citologias()
|
c = citologias()
|
||||||
filas = sesion.execute(select(
|
filas = sesion.execute(select(
|
||||||
c.c.pac_id, c.c.fecha_toma, c.c.fecha_reporte, c.c.calidad_muestra, c.c.resultado, c.c.vph, c.c.genotipo_16_18,
|
c.c.procedimiento_id, c.c.pac_id, c.c.fecha_toma, c.c.fecha_reporte, c.c.calidad_muestra,
|
||||||
|
c.c.resultado, c.c.vph, c.c.genotipo_16_18,
|
||||||
)).all()
|
)).all()
|
||||||
estudios = []
|
estudios = []
|
||||||
for pac_id, toma, reporte, calidad, resultado, vph, genotipo in filas:
|
for toma_id, pac_id, toma, reporte, calidad, resultado, vph, genotipo in filas:
|
||||||
toma, reporte = _fecha(toma), None if reporte is None else _fecha(reporte)
|
toma, reporte = _fecha(toma), None if reporte is None else _fecha(reporte)
|
||||||
conocido = reporte is not None and reporte <= corte
|
conocido = reporte is not None and reporte <= corte
|
||||||
fecha = toma if fecha_estudio == "toma" else reporte
|
fecha = toma if fecha_estudio == "toma" else reporte
|
||||||
if fecha is None or toma > corte or (fecha_estudio == "reporte" and not conocido):
|
if fecha is None or toma > corte or (fecha_estudio == "reporte" and not conocido):
|
||||||
continue
|
continue
|
||||||
estudios.append({
|
estudios.append({
|
||||||
"pac_id": pac_id, "fecha": fecha, "toma": toma, "calidad": calidad,
|
"pac_id": pac_id, "fecha": fecha, "toma": toma, "toma_id": toma_id, "calidad": calidad,
|
||||||
"resultado": resultado if conocido else None,
|
"resultado": resultado if conocido else None,
|
||||||
"vph": vph if conocido else None, "genotipo_16_18": genotipo if conocido else None,
|
"vph": vph if conocido else None, "genotipo_16_18": genotipo if conocido else None,
|
||||||
})
|
})
|
||||||
@@ -308,16 +340,21 @@ def _mostrada(citologias_: list[dict], resultado_mostrado: str, gravedad: dict[s
|
|||||||
return max(citologias_, key=lambda e: (gravedad.get(e["resultado"], -1), e["fecha"]))
|
return max(citologias_, key=lambda e: (gravedad.get(e["resultado"], -1), e["fecha"]))
|
||||||
|
|
||||||
|
|
||||||
def _grupo_de_edad(sesion: Session, corte: date, cortes, tablas: TablasKit) -> dict[int, str]:
|
def _edades(sesion: Session, corte: date, cortes, tablas: TablasKit) -> dict[int, tuple[int | None, str]]:
|
||||||
"""El grupo de edad de cada paciente con fecha de nacimiento, con la edad cumplida al corte."""
|
"""Edad cumplida y grupo al corte; una fecha inválida o futura no determina edad."""
|
||||||
grupos = grupos_de_cortes(cortes, tablas=tablas)
|
grupos = grupos_de_cortes(cortes, tablas=tablas)
|
||||||
edades = {}
|
edades = {}
|
||||||
for pac_id, nacimiento in sesion.execute(select(tablas.Persona.pac_id, tablas.Persona.fecha_nacimiento)):
|
for pac_id, nacimiento in sesion.execute(select(tablas.Persona.pac_id, tablas.Persona.fecha_nacimiento)):
|
||||||
if nacimiento is None:
|
if nacimiento is None:
|
||||||
continue
|
continue
|
||||||
nacimiento = _fecha(nacimiento)
|
try:
|
||||||
|
nacimiento = _fecha(nacimiento)
|
||||||
|
except (TypeError, ValueError, OverflowError):
|
||||||
|
continue
|
||||||
|
if nacimiento > corte:
|
||||||
|
continue
|
||||||
edad = corte.year - nacimiento.year - ((corte.month, corte.day) < (nacimiento.month, nacimiento.day))
|
edad = corte.year - nacimiento.year - ((corte.month, corte.day) < (nacimiento.month, nacimiento.day))
|
||||||
edades[pac_id] = next((g.etiqueta for g in grupos if g.edad_min <= edad <= g.edad_max), SIN_DATO)
|
edades[pac_id] = (edad, next((g.etiqueta for g in grupos if g.edad_min <= edad <= g.edad_max), SIN_DATO))
|
||||||
return edades
|
return edades
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -17,9 +17,12 @@ from datetime import date
|
|||||||
|
|
||||||
from flask import Blueprint, Response, jsonify, request
|
from flask import Blueprint, Response, jsonify, request
|
||||||
from webapi.follow_up.listing import PaginaFuera, PedidoInvalido, seguimiento_de
|
from webapi.follow_up.listing import PaginaFuera, PedidoInvalido, seguimiento_de
|
||||||
from sqlmodel import Session
|
from webapi.follow_up.screening import detalle_de
|
||||||
|
from sqlmodel import Session, select
|
||||||
|
from webapi.orchestration.tables.cacu import TABLAS
|
||||||
|
|
||||||
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
|
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
|
||||||
|
RUTA_ID = re.compile(r"[0-9a-f]{64}")
|
||||||
|
|
||||||
|
|
||||||
def in_dev() -> bool:
|
def in_dev() -> bool:
|
||||||
@@ -49,12 +52,52 @@ def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
|
|||||||
sesion.close()
|
sesion.close()
|
||||||
return Response(json.dumps(cuerpo, ensure_ascii=False), mimetype="application/json")
|
return Response(json.dumps(cuerpo, ensure_ascii=False), mimetype="application/json")
|
||||||
|
|
||||||
|
@blueprint.get("/seguimiento/pacientes/<int:pac_id>/demografia")
|
||||||
|
def get_demografia(pac_id: int):
|
||||||
|
no_disponible = {"error": "Información demográfica no disponible"}
|
||||||
|
if pac_id > 2**63 - 1:
|
||||||
|
return jsonify(no_disponible), 404
|
||||||
|
sesion = get_session()
|
||||||
|
try:
|
||||||
|
fila = sesion.execute(select(TABLAS.Persona.fecha_nacimiento).where(TABLAS.Persona.pac_id == pac_id)).first()
|
||||||
|
if fila is None:
|
||||||
|
return jsonify(no_disponible), 404
|
||||||
|
nacimiento = fila[0]
|
||||||
|
return jsonify({"pac_id": str(pac_id), "fecha_nacimiento": nacimiento.isoformat() if nacimiento is not None else None})
|
||||||
|
finally:
|
||||||
|
sesion.close()
|
||||||
|
|
||||||
|
@blueprint.get("/seguimiento/rutas/<int:pac_id>/<ruta_id>")
|
||||||
|
def get_ruta(pac_id: int, ruta_id: str):
|
||||||
|
no_disponible = {"error": "Ruta de tamizaje no disponible"}
|
||||||
|
if not RUTA_ID.fullmatch(ruta_id) or pac_id > 2**63 - 1:
|
||||||
|
return jsonify(no_disponible), 404
|
||||||
|
sesion = get_session()
|
||||||
|
try:
|
||||||
|
texto = request.args.get("corte", "")
|
||||||
|
try:
|
||||||
|
if not FECHA.fullmatch(texto):
|
||||||
|
raise ValueError
|
||||||
|
corte = date.fromisoformat(texto)
|
||||||
|
except ValueError:
|
||||||
|
return jsonify({"error": "corte debe ser una fecha válida AAAA-MM-DD"}), 400
|
||||||
|
ruta = detalle_de(sesion, pac_id, ruta_id, corte)
|
||||||
|
if ruta is None:
|
||||||
|
return jsonify(no_disponible), 404
|
||||||
|
return jsonify(ruta)
|
||||||
|
finally:
|
||||||
|
sesion.close()
|
||||||
|
|
||||||
return blueprint
|
return blueprint
|
||||||
|
|
||||||
|
|
||||||
def _requested(args) -> dict:
|
def _requested(args) -> dict:
|
||||||
"""Los parámetros de la consulta, con su tipo. `ValueError` si uno viene mal escrito."""
|
"""Los parámetros de la consulta, con su tipo. `ValueError` si uno viene mal escrito."""
|
||||||
pedido = {}
|
pedido = {}
|
||||||
|
if "incluir" in args:
|
||||||
|
if args.getlist("incluir") != ["ruta_tamizaje"]:
|
||||||
|
raise ValueError("incluir admite ruta_tamizaje")
|
||||||
|
pedido["incluir_ruta"] = True
|
||||||
if corte := args.get("corte"):
|
if corte := args.get("corte"):
|
||||||
if not FECHA.fullmatch(corte):
|
if not FECHA.fullmatch(corte):
|
||||||
raise ValueError(f"corte mal escrito {corte!r}; use AAAA-MM-DD")
|
raise ValueError(f"corte mal escrito {corte!r}; use AAAA-MM-DD")
|
||||||
@@ -64,6 +107,19 @@ def _requested(args) -> dict:
|
|||||||
if not texto.isdigit():
|
if not texto.isdigit():
|
||||||
raise ValueError(f"{nombre} debe ser un entero; llegó {texto!r}")
|
raise ValueError(f"{nombre} debe ser un entero; llegó {texto!r}")
|
||||||
pedido[nombre] = int(texto)
|
pedido[nombre] = int(texto)
|
||||||
|
for nombre in ("edad_min", "edad_max"):
|
||||||
|
if nombre in args:
|
||||||
|
texto = args.get(nombre, "")
|
||||||
|
if not texto.isascii() or not texto.isdigit():
|
||||||
|
raise ValueError(f"{nombre} debe ser un entero no negativo")
|
||||||
|
pedido[nombre] = int(texto)
|
||||||
|
if "q" in args:
|
||||||
|
texto = args.get("q", "")
|
||||||
|
if len(texto) > 100:
|
||||||
|
raise ValueError("q admite hasta 100 caracteres")
|
||||||
|
q = " ".join(texto.split())
|
||||||
|
if q:
|
||||||
|
pedido["q"] = q
|
||||||
if estatus := args.get("estatus"):
|
if estatus := args.get("estatus"):
|
||||||
pedido["estatus"] = estatus
|
pedido["estatus"] = estatus
|
||||||
if orden := args.get("orden"):
|
if orden := args.get("orden"):
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
"""Ruta individual acreditada por los vínculos de la plata de CaCu."""
|
||||||
|
|
||||||
|
from collections import defaultdict
|
||||||
|
from datetime import date
|
||||||
|
from hmac import compare_digest, digest
|
||||||
|
from secrets import token_bytes
|
||||||
|
|
||||||
|
from sqlalchemy import and_, literal, or_, select, union_all
|
||||||
|
|
||||||
|
from webapi.follow_up.pivot import hijos_de, pivote
|
||||||
|
from webapi.orchestration.tables.cacu import TABLAS
|
||||||
|
|
||||||
|
ETAPAS = ("citologia", "colposcopia", "biopsia", "diagnostico")
|
||||||
|
_CLAVE = token_bytes(32)
|
||||||
|
|
||||||
|
|
||||||
|
def _ref(tipo, *partes):
|
||||||
|
mensaje = ":".join(map(str, (tipo, *partes))).encode()
|
||||||
|
return digest(_CLAVE, mensaje, "sha256").hex()
|
||||||
|
|
||||||
|
|
||||||
|
def _eventos(sesion, tomas, corte, tablas):
|
||||||
|
"""Una consulta por página. Solo sigue padres del mismo paciente."""
|
||||||
|
toma = pivote(tablas, "citologia", "toma", nombre="ruta_toma")
|
||||||
|
cito = pivote(tablas, "citologia", "reporte", nombre="ruta_citologia")
|
||||||
|
orden = pivote(tablas, "biopsia", "orden", nombre="ruta_orden_biopsia")
|
||||||
|
biopsia = pivote(tablas, "biopsia", "reporte", nombre="ruta_reporte_biopsia")
|
||||||
|
observacion = tablas.Observacion.__table__
|
||||||
|
|
||||||
|
def hijo(padre, evento):
|
||||||
|
return and_(hijos_de(padre, evento), padre.c.pac_id == evento.c.pac_id)
|
||||||
|
|
||||||
|
desde_toma = toma.c.procedimiento_id.in_(tomas)
|
||||||
|
hasta_corte = corte.isoformat()
|
||||||
|
con_resultado = select(observacion.c.procedimiento_id).where(
|
||||||
|
observacion.c.procedimiento_id == cito.c.procedimiento_id,
|
||||||
|
observacion.c.pac_id == cito.c.pac_id,
|
||||||
|
observacion.c.resultado_id == "citologia.bethesda",
|
||||||
|
or_(observacion.c.valor_id.is_not(None), observacion.c.valor_fuente.is_not(None)),
|
||||||
|
).exists()
|
||||||
|
reportes_cito = (
|
||||||
|
select(toma.c.procedimiento_id, literal("citologia"), cito.c.procedimiento_id, cito.c.fecha)
|
||||||
|
.select_from(toma.join(cito, hijo(toma, cito)))
|
||||||
|
.where(desde_toma, cito.c.fecha >= toma.c.fecha, cito.c.fecha <= hasta_corte, con_resultado)
|
||||||
|
)
|
||||||
|
ordenes = toma.join(orden, hijo(toma, orden))
|
||||||
|
ordenes_biopsia = (
|
||||||
|
select(toma.c.procedimiento_id, literal("orden"), orden.c.procedimiento_id, orden.c.fecha)
|
||||||
|
.select_from(ordenes)
|
||||||
|
.where(desde_toma, orden.c.fecha >= toma.c.fecha, orden.c.fecha <= hasta_corte)
|
||||||
|
)
|
||||||
|
reportes_biopsia = (
|
||||||
|
select(toma.c.procedimiento_id, literal("biopsia"), biopsia.c.procedimiento_id, biopsia.c.fecha)
|
||||||
|
.select_from(ordenes.join(biopsia, hijo(orden, biopsia)))
|
||||||
|
.where(desde_toma, biopsia.c.fecha >= toma.c.fecha, biopsia.c.fecha <= hasta_corte,
|
||||||
|
or_(orden.c.fecha.is_(None),
|
||||||
|
and_(orden.c.fecha >= toma.c.fecha, biopsia.c.fecha >= orden.c.fecha)))
|
||||||
|
)
|
||||||
|
por_toma = defaultdict(lambda: defaultdict(list))
|
||||||
|
for toma_id, tipo, evento_id, fecha in sesion.execute(union_all(reportes_cito, ordenes_biopsia, reportes_biopsia)):
|
||||||
|
fecha = date.fromisoformat(str(fecha)[:10])
|
||||||
|
por_toma[toma_id][tipo].append((fecha, evento_id))
|
||||||
|
return por_toma
|
||||||
|
|
||||||
|
|
||||||
|
def rutas_de(sesion, tomas, corte, tablas=TABLAS, *, detalle=False):
|
||||||
|
"""Proyecta tomas seleccionadas {id: (pac_id, fecha)} sin leer otras filas."""
|
||||||
|
if not tomas:
|
||||||
|
return {}
|
||||||
|
eventos = _eventos(sesion, tomas, corte, tablas)
|
||||||
|
return {
|
||||||
|
toma_id: _ruta(toma_id, pac_id, toma, corte, eventos[toma_id], detalle)
|
||||||
|
for toma_id, (pac_id, toma) in tomas.items()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _ruta(toma_id, pac_id, toma, corte, eventos, detalle):
|
||||||
|
ruta_id = _ref("ruta", pac_id, toma_id, corte)
|
||||||
|
ultimo = anterior = toma
|
||||||
|
etapas = []
|
||||||
|
for codigo in ETAPAS:
|
||||||
|
registros = sorted(eventos[codigo])
|
||||||
|
fecha, evento_id = registros[0] if registros else (None, None)
|
||||||
|
pendiente = codigo == "biopsia" and bool(eventos["orden"])
|
||||||
|
estado = "registrada" if fecha else "pendiente" if pendiente else "desconocida"
|
||||||
|
etapa = {"codigo": codigo, "estado": estado, "fecha": fecha.isoformat() if fecha else None}
|
||||||
|
if detalle:
|
||||||
|
etapa.update(
|
||||||
|
dias_desde_toma=(fecha - toma).days if fecha else None,
|
||||||
|
dias_desde_anterior=(fecha - anterior).days if fecha and anterior and fecha >= anterior else None,
|
||||||
|
evento_ref=_ref("evento", ruta_id, evento_id) if evento_id is not None else None,
|
||||||
|
eventos=[{"ref": _ref("evento", ruta_id, eid), "fecha": f.isoformat()} for f, eid in registros],
|
||||||
|
)
|
||||||
|
if codigo == "biopsia":
|
||||||
|
etapa["ordenes"] = [
|
||||||
|
{"ref": _ref("evento", ruta_id, eid), "fecha": f.isoformat()}
|
||||||
|
for f, eid in sorted(eventos["orden"])
|
||||||
|
]
|
||||||
|
etapas.append(etapa)
|
||||||
|
anterior = fecha
|
||||||
|
if fecha is not None:
|
||||||
|
ultimo = max(ultimo, fecha)
|
||||||
|
|
||||||
|
ruta = {"id": ruta_id, "corte": corte.isoformat(), "toma": toma.isoformat(),
|
||||||
|
"etapas": etapas, "dias_desde_ultimo_evento": (corte - ultimo).days}
|
||||||
|
if detalle:
|
||||||
|
ruta["toma_ref"] = _ref("evento", ruta_id, toma_id)
|
||||||
|
else:
|
||||||
|
ruta["detalle_url"] = f"/cacu/seguimiento/rutas/{pac_id}/{ruta_id}?corte={corte.isoformat()}"
|
||||||
|
return ruta
|
||||||
|
|
||||||
|
|
||||||
|
def detalle_de(sesion, pac_id, ruta_id, corte, tablas=TABLAS):
|
||||||
|
toma = tablas.Procedimiento.__table__
|
||||||
|
candidatas = select(toma.c.procedimiento_id, toma.c.fecha).where(
|
||||||
|
toma.c.pac_id == pac_id, toma.c.estudio_id == "citologia", toma.c.clase == "toma", toma.c.fecha <= corte,
|
||||||
|
)
|
||||||
|
for toma_id, fecha in sesion.execute(candidatas):
|
||||||
|
if compare_digest(_ref("ruta", pac_id, toma_id, corte), ruta_id):
|
||||||
|
return rutas_de(sesion, {toma_id: (pac_id, fecha)}, corte, tablas, detalle=True)[toma_id]
|
||||||
|
return None
|
||||||
+36
-35
@@ -24,6 +24,7 @@ import os
|
|||||||
import signal
|
import signal
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
from contextlib import contextmanager
|
||||||
from datetime import date, datetime, timezone
|
from datetime import date, datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
@@ -48,34 +49,21 @@ def _short(value: Any) -> str:
|
|||||||
return text if len(text) <= _SUMMARY_MAX else text[:_SUMMARY_MAX] + "…"
|
return text if len(text) <= _SUMMARY_MAX else text[:_SUMMARY_MAX] + "…"
|
||||||
|
|
||||||
|
|
||||||
def _warm_models(dominio: str) -> dict[str, Any]:
|
@contextmanager
|
||||||
"""Leaves the members of the domain's live models labelled over the new build, so the API reads them instead of the build,
|
def _cluster_override(cluster: dict | None):
|
||||||
and their scenario points computed by the pipeline over those members."""
|
"""Applies a cluster choice to this process's environment while a run lasts, then restores it."""
|
||||||
from webapi.model_analysis import refresh_subgroups, warm
|
if not cluster:
|
||||||
|
yield
|
||||||
|
return
|
||||||
|
from webapi.detached_jobs import cluster_environment
|
||||||
|
|
||||||
started = time.monotonic()
|
saved = dict(os.environ)
|
||||||
try:
|
try:
|
||||||
resumen = {"cargados": warm(dominio), "escenarios_recalculados": refresh_subgroups(dominio)}
|
cluster_environment({"cluster": cluster}, os.environ)
|
||||||
except Exception as exc: # the indicators are already saved
|
yield
|
||||||
log.exception("no se pudieron preparar los modelos de %s", dominio)
|
finally:
|
||||||
resumen = f"error: {type(exc).__name__}"
|
os.environ.clear()
|
||||||
return {"paso": "modelos", "segundos": round(time.monotonic() - started, 2), "resumen": _short(resumen)}
|
os.environ.update(saved)
|
||||||
|
|
||||||
|
|
||||||
def _answer_measures(dominio: str) -> dict[str, Any]:
|
|
||||||
"""Leaves each measure's latest periods answered with what this run loaded (`webapi.kpis.answer_latest`)."""
|
|
||||||
from importlib import import_module
|
|
||||||
|
|
||||||
from webapi.kpis import answer_latest
|
|
||||||
|
|
||||||
started = time.monotonic()
|
|
||||||
manifest = os.environ.get("DBT_MANIFEST")
|
|
||||||
try:
|
|
||||||
resumen = answer_latest(dominio, import_module(f"persistance.{dominio}"), Path(manifest)) if manifest else "sin DBT_MANIFEST"
|
|
||||||
except Exception as exc: # the indicators are already saved
|
|
||||||
log.exception("no se pudieron responder los indicadores de %s", dominio)
|
|
||||||
resumen = f"error: {type(exc).__name__}"
|
|
||||||
return {"paso": "respuestas", "segundos": round(time.monotonic() - started, 2), "resumen": _short(resumen)}
|
|
||||||
|
|
||||||
|
|
||||||
class RecomputationQueue:
|
class RecomputationQueue:
|
||||||
@@ -92,11 +80,20 @@ class RecomputationQueue:
|
|||||||
def _status_path(self) -> Path:
|
def _status_path(self) -> Path:
|
||||||
return self.base / "estado.json"
|
return self.base / "estado.json"
|
||||||
|
|
||||||
def request_run(self, dominio: str) -> None:
|
def request_run(self, dominio: str, cluster: dict | None = None) -> None:
|
||||||
|
"""Queues a run; `cluster` (`{mode, scheduler?}`) picks where the EEG analysis of that run executes."""
|
||||||
if dominio not in DOMAINS:
|
if dominio not in DOMAINS:
|
||||||
raise ValueError(f"dominio desconocido: {dominio!r}")
|
raise ValueError(f"dominio desconocido: {dominio!r}")
|
||||||
self._pending.mkdir(parents=True, exist_ok=True)
|
self._pending.mkdir(parents=True, exist_ok=True)
|
||||||
(self._pending / dominio).write_text(_now(), encoding="utf-8")
|
(self._pending / dominio).write_text(json.dumps({"at": _now(), "cluster": cluster}), encoding="utf-8")
|
||||||
|
|
||||||
|
def requested_cluster(self, dominio: str) -> dict | None:
|
||||||
|
"""The cluster choice of the queued request, or none for a plain one."""
|
||||||
|
try:
|
||||||
|
marker = json.loads((self._pending / dominio).read_text(encoding="utf-8"))
|
||||||
|
except (FileNotFoundError, json.JSONDecodeError):
|
||||||
|
return None
|
||||||
|
return marker.get("cluster") if isinstance(marker, dict) else None
|
||||||
|
|
||||||
def pending(self) -> list[str]:
|
def pending(self) -> list[str]:
|
||||||
if not self._pending.exists():
|
if not self._pending.exists():
|
||||||
@@ -133,8 +130,10 @@ class RecomputationQueue:
|
|||||||
tmp.write_text(json.dumps(status, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
|
tmp.write_text(json.dumps(status, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
|
||||||
tmp.replace(self._status_path)
|
tmp.replace(self._status_path)
|
||||||
|
|
||||||
def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
|
def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None,
|
||||||
"""Runs the domain's graph (without `migrate`: the API migrates on startup)."""
|
cluster: dict | None = None) -> dict[str, Any]:
|
||||||
|
"""Runs the domain's graph (without `migrate`: the API migrates on startup). `cluster` overrides where the
|
||||||
|
EEG analysis runs, for this run only."""
|
||||||
from webapi.orchestration import Context, run, steps_of
|
from webapi.orchestration import Context, run, steps_of
|
||||||
from webapi.orchestration.eeg import live_ados2_relation, live_ados2_scoring, live_eeg_analysis
|
from webapi.orchestration.eeg import live_ados2_relation, live_ados2_scoring, live_eeg_analysis
|
||||||
from webapi.orchestration.estimators import live_estimators
|
from webapi.orchestration.estimators import live_estimators
|
||||||
@@ -146,10 +145,11 @@ class RecomputationQueue:
|
|||||||
self._save_status(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]})
|
self._save_status(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]})
|
||||||
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
|
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
|
||||||
try:
|
try:
|
||||||
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio),
|
with _cluster_override(cluster):
|
||||||
eeg_analysis=live_eeg_analysis(dominio), ados2_relation=live_ados2_relation(dominio),
|
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio),
|
||||||
ados2_scoring=live_ados2_scoring(dominio))
|
eeg_analysis=live_eeg_analysis(dominio), ados2_relation=live_ados2_relation(dominio),
|
||||||
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
|
ados2_scoring=live_ados2_scoring(dominio))
|
||||||
|
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
|
||||||
entrada.update(
|
entrada.update(
|
||||||
estado="ok",
|
estado="ok",
|
||||||
pasos=[{"paso": p.name, "segundos": round(p.seconds, 2), "resumen": _short(p.summary)} for p in pasos],
|
pasos=[{"paso": p.name, "segundos": round(p.seconds, 2), "resumen": _short(p.summary)} for p in pasos],
|
||||||
@@ -171,8 +171,9 @@ class RecomputationQueue:
|
|||||||
"""Runs every pending domain once; returns the ones it ran."""
|
"""Runs every pending domain once; returns the ones it ran."""
|
||||||
ran = []
|
ran = []
|
||||||
for dominio in self.pending():
|
for dominio in self.pending():
|
||||||
|
choice = self.requested_cluster(dominio)
|
||||||
if self.take(dominio):
|
if self.take(dominio):
|
||||||
self.run(dominio)
|
self.run(dominio, cluster=choice)
|
||||||
ran.append(dominio)
|
ran.append(dominio)
|
||||||
return ran
|
return ran
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
"""TEA governance storage services."""
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
"""Detached analysis jobs for stored TEA EEGs."""
|
||||||
|
|
||||||
|
import fcntl
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from webapi import detached_jobs
|
||||||
|
|
||||||
|
SUMMARY_FIELDS = {"pending", "valid", "not_valid", "failed"}
|
||||||
|
|
||||||
|
|
||||||
|
class AnalysisRunning(RuntimeError):
|
||||||
|
"""An EEG analysis job is already running."""
|
||||||
|
|
||||||
|
|
||||||
|
class AnalyzeJobs:
|
||||||
|
"""Launch and read EEG analysis jobs from the indicator directory."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.base = Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "analisis_eeg"
|
||||||
|
|
||||||
|
def start(self, body: dict) -> dict:
|
||||||
|
"""Validate analysis options and launch one job at a time."""
|
||||||
|
if not isinstance(body, dict) or body.keys() - {"all", "limit", "ids", "cluster"}:
|
||||||
|
raise ValueError("El cuerpo debe ser un objeto JSON con opciones de análisis válidas.")
|
||||||
|
|
||||||
|
everything = body.get("all", False)
|
||||||
|
limit = body.get("limit")
|
||||||
|
ids = body.get("ids")
|
||||||
|
if type(everything) is not bool:
|
||||||
|
raise ValueError("all debe ser un valor booleano.")
|
||||||
|
if "limit" in body and (type(limit) is not int or limit < 1):
|
||||||
|
raise ValueError("limit debe ser un entero positivo.")
|
||||||
|
if "ids" in body:
|
||||||
|
if (not isinstance(ids, list) or not ids
|
||||||
|
or any(type(value) not in (int, str) or not str(value).strip() or len(str(value)) > 64
|
||||||
|
or any(mark in str(value) for mark in ",\0") for value in ids)):
|
||||||
|
raise ValueError("ids debe ser una lista no vacía de identificadores de EEG.")
|
||||||
|
ids = [str(value).strip() for value in ids]
|
||||||
|
if sum((everything, limit is not None, ids is not None)) > 1:
|
||||||
|
raise ValueError("Elija solo una opción entre all, limit e ids.")
|
||||||
|
|
||||||
|
env = os.environ.copy()
|
||||||
|
cluster = detached_jobs.cluster_environment(body, env)
|
||||||
|
argv = [sys.executable, "-m", "models", "tea", "analyze"]
|
||||||
|
if everything:
|
||||||
|
argv.append("--all")
|
||||||
|
elif limit is not None:
|
||||||
|
argv.extend(("--limit", str(limit)))
|
||||||
|
elif ids is not None:
|
||||||
|
argv.extend(("--ids", ",".join(map(str, ids))))
|
||||||
|
argv.extend(("--cluster", cluster["mode"] if cluster else "auto"))
|
||||||
|
|
||||||
|
self.base.mkdir(parents=True, exist_ok=True)
|
||||||
|
with (self.base / ".start.lock").open("a") as lock:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||||
|
if any(self._state(folder)["estado"] == "en_curso" for folder in detached_jobs.folders(self.base)):
|
||||||
|
raise AnalysisRunning("Ya hay un análisis de EEG en curso.")
|
||||||
|
if ids is not None:
|
||||||
|
from models.eeg_analysis import selected_ids
|
||||||
|
from persistance.tea import eeg_repository
|
||||||
|
|
||||||
|
with eeg_repository.open_session() as session:
|
||||||
|
selected_ids(session, ids)
|
||||||
|
folder = detached_jobs.launch(self.base, argv, env, {"cluster": cluster, "ids": ids},
|
||||||
|
precise_id=True, cwd=Path.cwd())
|
||||||
|
return self._state(folder)
|
||||||
|
|
||||||
|
def get(self, job_id: str) -> dict:
|
||||||
|
"""Read one analysis job by ID."""
|
||||||
|
folder = self.base / job_id
|
||||||
|
if "/" in job_id or not (folder / "job.json").is_file():
|
||||||
|
raise LookupError(f"No se encontró el análisis de EEG {job_id}.")
|
||||||
|
return self._state(folder)
|
||||||
|
|
||||||
|
def jobs(self) -> list[dict]:
|
||||||
|
"""List analysis jobs newest first."""
|
||||||
|
return [self._state(folder) for folder in detached_jobs.folders(self.base)]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _state(folder: Path) -> dict:
|
||||||
|
job = detached_jobs.state(folder)
|
||||||
|
job.pop("pid", None)
|
||||||
|
job.setdefault("cluster", None)
|
||||||
|
job.setdefault("ids", None)
|
||||||
|
job["summary"] = None
|
||||||
|
if job["codigo"] is not None:
|
||||||
|
for line in reversed(job["salida"].splitlines()):
|
||||||
|
if line.startswith("summary:"):
|
||||||
|
try:
|
||||||
|
summary = json.loads(line.removeprefix("summary:"))
|
||||||
|
except ValueError:
|
||||||
|
break
|
||||||
|
if (isinstance(summary, dict) and summary.keys() == SUMMARY_FIELDS
|
||||||
|
and all(type(value) is int and value >= 0 for value in summary.values())):
|
||||||
|
job["summary"] = summary
|
||||||
|
break
|
||||||
|
return job
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Transfer trained EEG baselines between registries."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import shutil
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import NamedTemporaryFile
|
||||||
|
from typing import BinaryIO
|
||||||
|
from zipfile import BadZipFile
|
||||||
|
|
||||||
|
from models.tea.eeg import bundle
|
||||||
|
from models.tea.eeg.bundle import BundleError
|
||||||
|
from models.tea.eeg.settings import settings
|
||||||
|
|
||||||
|
|
||||||
|
class BaselineConflict(BundleError):
|
||||||
|
"""Every baseline in the bundle already exists in the registry."""
|
||||||
|
|
||||||
|
|
||||||
|
class BaselineBundles:
|
||||||
|
"""Export and register bundles using the configured EEG scenarios."""
|
||||||
|
|
||||||
|
def export(self, path: Path, *, environment: str, production: bool) -> bundle.Exported:
|
||||||
|
return bundle.export(settings(), path, environment=environment.upper(), production=production)
|
||||||
|
|
||||||
|
def import_(self, stream: BinaryIO) -> dict:
|
||||||
|
config = settings()
|
||||||
|
with NamedTemporaryFile(suffix=".zip") as upload:
|
||||||
|
shutil.copyfileobj(stream, upload, length=1024 * 1024)
|
||||||
|
upload.flush()
|
||||||
|
upload.seek(0)
|
||||||
|
sha256 = hashlib.file_digest(upload, "sha256").hexdigest()
|
||||||
|
try:
|
||||||
|
versions = bundle.import_(config, upload.name)
|
||||||
|
except (BadZipFile, KeyError, TypeError, AttributeError, FileNotFoundError) as error:
|
||||||
|
raise BundleError(f"Paquete de baselines inválido: {error}") from error
|
||||||
|
|
||||||
|
imported = [
|
||||||
|
{"scenario": scenario, "version": int(version)}
|
||||||
|
for scenario, (version, new) in versions.items() if new
|
||||||
|
]
|
||||||
|
if versions and not imported:
|
||||||
|
existing = ", ".join(f"{scenario}: {version}" for scenario, (version, _) in versions.items())
|
||||||
|
raise BaselineConflict(f"Las versiones ya están registradas: {existing}")
|
||||||
|
return {"sha256": sha256, "imported": imported}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""Add an EEG recording to TEA through the import pipeline.
|
||||||
|
|
||||||
|
The recording goes through the `edf` connector and the `tea.Eeg` target, the same path an import takes, so the
|
||||||
|
validation, the natural key (`eeg_id_registro_laboratorio`) and the audit trail are the import's own.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from persistance.tea import eeg_repository
|
||||||
|
from webapi.imports import audit as import_audit
|
||||||
|
from webapi.imports.services.import_service import ImportRequestError, ImportSource, commit_sources
|
||||||
|
|
||||||
|
TARGET = "tea.Eeg"
|
||||||
|
COLUMNS = {
|
||||||
|
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||||
|
"fecha_estudio": "eeg_fecha_estudio",
|
||||||
|
"canales": "eeg_canales",
|
||||||
|
"duracion_min": "eeg_duracion_min",
|
||||||
|
"estudio": "eeg_estudio",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class EdfIntake:
|
||||||
|
"""Registers one EDF file as an EEG, optionally linked to a patient."""
|
||||||
|
|
||||||
|
def add(self, filename: str, raw: bytes, patient_id: int | None = None) -> dict:
|
||||||
|
"""`ImportRequestError` for a file that is not a readable EDF or that the import rejects."""
|
||||||
|
source = {
|
||||||
|
"source_type": "edf",
|
||||||
|
"target": TARGET,
|
||||||
|
"payload": {"file_base64": base64.b64encode(raw).decode("ascii"), "options": {"file_name": filename}},
|
||||||
|
"column_mapping": COLUMNS,
|
||||||
|
"defaults": {} if patient_id is None else {"eeg_pac_id": patient_id},
|
||||||
|
"label": filename,
|
||||||
|
}
|
||||||
|
lab_id = self._lab_id(source)
|
||||||
|
audit = import_audit.ImportAudit("carga", {"on_conflict": "upsert", "merge_duplicates": False})
|
||||||
|
try:
|
||||||
|
(result,) = commit_sources([source], on_conflict="upsert", audit=audit)
|
||||||
|
except Exception as exc:
|
||||||
|
audit.fail(exc, "solicitud_invalida" if isinstance(exc, ImportRequestError) else "fallida")
|
||||||
|
raise
|
||||||
|
else:
|
||||||
|
audit.succeed()
|
||||||
|
finally:
|
||||||
|
import_audit.record(audit)
|
||||||
|
if result.rejected:
|
||||||
|
raise ImportRequestError("; ".join(error["message"] for error in result.errors) or "el EEG fue rechazado")
|
||||||
|
return {"eeg_id": self._eeg_id(lab_id), "lab_id": lab_id, "created": bool(result.created)}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _lab_id(source: dict) -> str | None:
|
||||||
|
(row,) = ImportSource.parse(source).rows()
|
||||||
|
return row.get("eeg_id_registro_laboratorio")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _eeg_id(lab_id: str | None):
|
||||||
|
if lab_id is None:
|
||||||
|
return None
|
||||||
|
model = eeg_repository.model
|
||||||
|
session = eeg_repository.open_session()
|
||||||
|
try:
|
||||||
|
found = session.execute(
|
||||||
|
select(model.eeg_id).where(model.eeg_id_registro_laboratorio == lab_id)
|
||||||
|
).scalars().first()
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
return found
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
"""Analyse one EDF, and read its ADOS-2 report, in memory: the answer is a patient summary bundle and nothing is stored.
|
||||||
|
|
||||||
|
The recording goes through the same measurement and baselines as a stored EEG, and its rows are turned into the
|
||||||
|
dicts the FHIR summary builders take, so the web app draws it with the view it uses for a patient. No session is
|
||||||
|
opened, no row is added and no registry entry is written; the uploaded bytes live in this call only.
|
||||||
|
"""
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from webapi.fhir import tea as fhir
|
||||||
|
from webapi.fhir.eeg_curves import baseline_curves
|
||||||
|
|
||||||
|
PSEUDONYM = "vista-previa"
|
||||||
|
EEG_ID = "vista-previa"
|
||||||
|
ADOS2_ID = "vista-previa"
|
||||||
|
|
||||||
|
|
||||||
|
class PreviewError(ValueError):
|
||||||
|
"""The file cannot be analysed at all (the EDF cannot be read, or the report is not a PDF)."""
|
||||||
|
|
||||||
|
|
||||||
|
def _item_labels() -> dict[str, str]:
|
||||||
|
"""Each item's printed caption, from the score-table vocabulary the extraction reads reports with."""
|
||||||
|
from extraction.nlp.vocabulary import SCORE_TABLES
|
||||||
|
|
||||||
|
labels: dict[str, str] = {}
|
||||||
|
for captions in SCORE_TABLES["ados2"]["variants"].values():
|
||||||
|
for caption, field in captions.items():
|
||||||
|
labels.setdefault(field.removeprefix("ado_"), caption)
|
||||||
|
return labels
|
||||||
|
|
||||||
|
|
||||||
|
def _recording_date(edf: bytes) -> date:
|
||||||
|
from extraction import ExtractionError
|
||||||
|
from extraction.signals import EegRecording
|
||||||
|
|
||||||
|
try:
|
||||||
|
start = EegRecording.read(edf).start
|
||||||
|
except ExtractionError as error:
|
||||||
|
raise PreviewError(f"El archivo no es un EDF legible: {error}") from error
|
||||||
|
return start.date() if start else date.today()
|
||||||
|
|
||||||
|
|
||||||
|
class EegPreview:
|
||||||
|
"""Builds the summary of one EDF and, optionally, of the child's ADOS-2 report."""
|
||||||
|
|
||||||
|
def __init__(self, settings=None, baselines=None, measure_fn=None, curves=None):
|
||||||
|
self._settings, self._baselines, self._measure, self._curves = settings, baselines, measure_fn, curves
|
||||||
|
|
||||||
|
def run(self, edf: bytes, ados2: bytes | None = None) -> dict:
|
||||||
|
from models.eeg_analysis import checked_settings, rows
|
||||||
|
from models.tea.eeg.analyze import measure
|
||||||
|
from models.tea.eeg.baselines import Baselines
|
||||||
|
|
||||||
|
settings = self._settings or checked_settings()
|
||||||
|
baselines = self._baselines or Baselines(settings.domain)
|
||||||
|
taken = _recording_date(edf)
|
||||||
|
measured = (self._measure or measure)(EEG_ID, edf, None, settings)
|
||||||
|
if measured.error and measured.valid is None and not measured.checks:
|
||||||
|
raise PreviewError(f"No se pudo analizar el EDF: {measured.error}")
|
||||||
|
result = rows(measured, settings, baselines)
|
||||||
|
avisos: list[str] = []
|
||||||
|
resources = []
|
||||||
|
if ados2 is not None:
|
||||||
|
observation = self._ados2(ados2, measured.age_months, taken, avisos)
|
||||||
|
if observation is not None:
|
||||||
|
resources.append(observation)
|
||||||
|
if measured.error:
|
||||||
|
avisos.append(f"El análisis del EEG terminó con un error: {measured.error}")
|
||||||
|
resources += self._eeg(measured, result, taken)
|
||||||
|
return {"bundle": {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]},
|
||||||
|
"avisos": avisos}
|
||||||
|
|
||||||
|
def _eeg(self, m, result, taken: date) -> list[dict]:
|
||||||
|
valid = result.eeg.get("eeg_valido")
|
||||||
|
quality = "SIN_ANALIZAR" if valid is None else "BUENO" if valid == 1 else "MALO"
|
||||||
|
eeg = {"procedimiento_id": EEG_ID, "fecha_eeg": taken, "calidad": quality, "valido": valid,
|
||||||
|
"nivel": result.eeg.get("eeg_nivel"), "duracion_min": result.eeg.get("eeg_duracion_min"),
|
||||||
|
"edad_meses": result.eeg.get("eeg_edad_meses"), "canales": result.eeg.get("eeg_canales")}
|
||||||
|
age_group = f"{round(m.age_months)} meses" if m.age_months is not None else "sin dato"
|
||||||
|
codes = {metric.met_id: metric.met_codigo for metric in result.metrics}
|
||||||
|
metrics = [{"procedimiento_id": EEG_ID, "metrica": x.met_codigo, "valor": x.met_valor, "grupo_edad_eeg": age_group,
|
||||||
|
"ref_min": x.met_p5, "ref_mediana": x.met_mediana, "ref_max": x.met_p95, "modelo": x.met_modelo,
|
||||||
|
"valor_z": x.met_z,
|
||||||
|
"estado": "no_evaluable" if x.met_z is None else
|
||||||
|
"aumentado" if x.met_fuera == 1 else "disminuido" if x.met_fuera == -1 else "normal"}
|
||||||
|
for x in result.metrics]
|
||||||
|
electrodes = [{"procedimiento_id": EEG_ID, "metrica": codes[x.mel_met_id], "electrodo": x.mel_electrodo,
|
||||||
|
"valor": x.mel_valor, "valor_z": x.mel_z} for x in result.electrodes]
|
||||||
|
checks = [{"procedimiento_id": EEG_ID, "criterio": c.cri_codigo, "electrodo": c.cri_electrodo,
|
||||||
|
"valor": c.cri_valor, "valor_texto": c.cri_valor_texto, "bajo": c.cri_bajo, "alto": c.cri_alto,
|
||||||
|
"anormal": c.cri_anormal, "decisivo": c.cri_decisivo, "etiqueta": c.cri_codigo,
|
||||||
|
"unidad": c.cri_unidad} for c in result.criteria]
|
||||||
|
return fhir.eeg_resources(eeg, PSEUDONYM, metrics, electrodes, True, checks,
|
||||||
|
curves=self._curves or baseline_curves(), show_alterations=True)
|
||||||
|
|
||||||
|
def _ados2(self, raw: bytes, age_months: float | None, taken: date, avisos: list[str]) -> dict | None:
|
||||||
|
try:
|
||||||
|
row = self._report_row(raw)
|
||||||
|
items, module, algorithm = self._items(row), row.get("ado_modulo"), row.get("ado_algoritmo")
|
||||||
|
score = self._score(module, items, age_months, algorithm)
|
||||||
|
except PreviewError:
|
||||||
|
raise
|
||||||
|
except Exception as error: # noqa: BLE001
|
||||||
|
avisos.append(f"No se pudo leer el ADOS-2 del PDF: {error}")
|
||||||
|
return None
|
||||||
|
css = row.get("ado_css") or (score.css if score else None)
|
||||||
|
classification = row.get("ado_clasificacion") or (score.classification if score else None)
|
||||||
|
if not items or not module:
|
||||||
|
avisos.append("No se pudo leer el ADOS-2 del PDF: faltan el módulo o los puntajes de los reactivos.")
|
||||||
|
return None
|
||||||
|
if css is None:
|
||||||
|
avisos.append("No se pudo calcular el CSS del ADOS-2: el informe no lo trae y el EDF no da la edad del niño.")
|
||||||
|
return None
|
||||||
|
labels = _item_labels()
|
||||||
|
lines = [{"procedimiento_id": ADOS2_ID, "fecha_ados2": _date(row.get("ado_fecha")) or taken,
|
||||||
|
"modulo": module, "algoritmo": algorithm, "css": int(css), "clasificacion": classification,
|
||||||
|
"dominio": "SA" if code.startswith("sa_") else "RRB", "reactivo": f"ados2.{code}",
|
||||||
|
"etiqueta": labels.get(code, code.replace("_", " ").upper()), "puntaje": value,
|
||||||
|
"puntaje_algoritmo": 2 if value == 3 else 0 if value in (7, 8, 9) else value}
|
||||||
|
for code, value in items.items()]
|
||||||
|
return fhir.ados2_observation(lines, PSEUDONYM, True)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _report_row(raw: bytes) -> dict:
|
||||||
|
if not raw.lstrip()[:5].startswith(b"%PDF"):
|
||||||
|
raise PreviewError("El informe del ADOS-2 debe ser un PDF.")
|
||||||
|
from webapi.imports.connectors.document import DocumentConnector
|
||||||
|
|
||||||
|
records, _ = DocumentConnector([("ados2.pdf", raw)], target="tea.Ados2")._extract()
|
||||||
|
if not records:
|
||||||
|
raise ValueError("el PDF no contiene una evaluación ADOS-2")
|
||||||
|
row = records[0].row()
|
||||||
|
return {k: (None if v in ("", None) else v) for k, v in row.items()}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _items(row: dict) -> dict[str, int]:
|
||||||
|
from core.tea.models import ADOS2_ITEMS
|
||||||
|
|
||||||
|
out = {}
|
||||||
|
for code in ADOS2_ITEMS:
|
||||||
|
value = row.get(f"ado_{code}")
|
||||||
|
if value is not None:
|
||||||
|
out[code] = int(float(value))
|
||||||
|
return out
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _score(module, items, age_months, algorithm):
|
||||||
|
from tea.scoring import score
|
||||||
|
|
||||||
|
return score(module, items, age_months=age_months, algorithm=algorithm) if module and items else None
|
||||||
|
|
||||||
|
|
||||||
|
def _date(value) -> date | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if isinstance(value, date):
|
||||||
|
return value
|
||||||
|
try:
|
||||||
|
return date.fromisoformat(str(value)[:10])
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
"""Read EEG analysis results and registered baseline curves for governance."""
|
||||||
|
|
||||||
|
from core.tea.models import Eeg, EegMetrica
|
||||||
|
from sqlalchemy import case, func, inspect, or_, select
|
||||||
|
|
||||||
|
from webapi.fhir.eeg_curves import baseline_curves
|
||||||
|
from webapi.fhir.tea import EEGS, METRICS
|
||||||
|
|
||||||
|
|
||||||
|
class BaselineQueries:
|
||||||
|
"""Use the analysis metric catalog to find drawable curves."""
|
||||||
|
|
||||||
|
def __init__(self, scenario: str, version: int):
|
||||||
|
self.scenario = scenario
|
||||||
|
self.version = version
|
||||||
|
self.label = f"tea-{scenario}/{version}"
|
||||||
|
self.curves = baseline_curves()
|
||||||
|
|
||||||
|
def metrics(self) -> list[str]:
|
||||||
|
from models.tea.eeg.settings import settings
|
||||||
|
|
||||||
|
candidates = {metric.code.lower() for metric in settings().metrics if metric.scenario == self.scenario}
|
||||||
|
return [name for name in sorted(candidates) if self.curves.curve(self.label, name) is not None]
|
||||||
|
|
||||||
|
def curve(self, metric: str) -> dict:
|
||||||
|
curve = self.curves.curve(self.label, metric)
|
||||||
|
if curve is None:
|
||||||
|
raise LookupError("No se encontró una curva para la métrica y la versión solicitadas.")
|
||||||
|
return {"scenario": self.scenario, "version": self.version, "metric": metric, **curve}
|
||||||
|
|
||||||
|
|
||||||
|
def _public_id(key: str) -> int | str:
|
||||||
|
if key.isascii() and key.isdecimal() and str(int(key)) == key:
|
||||||
|
return int(key)
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
def _valid(value: int | None) -> bool | None:
|
||||||
|
return None if value is None else value == 1
|
||||||
|
|
||||||
|
|
||||||
|
def _count_where(condition):
|
||||||
|
return func.count(case((condition, 1)))
|
||||||
|
|
||||||
|
|
||||||
|
class EegQueries:
|
||||||
|
"""Read projected EEG fields and aggregate counts from the TEA database."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
from persistance.tea import eeg_repository
|
||||||
|
|
||||||
|
self.repository = eeg_repository
|
||||||
|
|
||||||
|
def recordings(self, limit: int, offset: int) -> list[dict]:
|
||||||
|
query = select(
|
||||||
|
Eeg.eeg_id, Eeg.eeg_id_registro_laboratorio, Eeg.eeg_pac_id, Eeg.eeg_fecha_estudio,
|
||||||
|
Eeg.eeg_valido, case((Eeg.eeg_error.is_not(None), 1), else_=0),
|
||||||
|
).order_by(func.length(Eeg.eeg_id).desc(), Eeg.eeg_id.desc()).limit(min(limit, 500)).offset(offset)
|
||||||
|
with self.repository.open_session() as session:
|
||||||
|
return [
|
||||||
|
{"id": _public_id(key), "lab_id": lab_id, "patient_id": patient_id,
|
||||||
|
"study_date": study_date.isoformat() if study_date is not None else None,
|
||||||
|
"valid": _valid(valid), "analysed": valid is not None or bool(failed)}
|
||||||
|
for key, lab_id, patient_id, study_date, valid, failed in session.execute(query)
|
||||||
|
]
|
||||||
|
|
||||||
|
def metrics(self, eeg_id: str) -> dict:
|
||||||
|
header = select(Eeg.eeg_valido, Eeg.eeg_nivel, Eeg.eeg_edad_meses).where(Eeg.eeg_id == eeg_id)
|
||||||
|
metrics = select(
|
||||||
|
EegMetrica.met_codigo, EegMetrica.met_valor, EegMetrica.met_z, EegMetrica.met_fuera, EegMetrica.met_modelo,
|
||||||
|
).where(
|
||||||
|
EegMetrica.met_eeg_id == eeg_id, EegMetrica.met_codigo.is_not(None), EegMetrica.met_valor.is_not(None),
|
||||||
|
).order_by(EegMetrica.met_codigo, EegMetrica.met_id)
|
||||||
|
with self.repository.open_session() as session:
|
||||||
|
row = session.execute(header).one_or_none()
|
||||||
|
if row is None:
|
||||||
|
raise LookupError(f"No se encontró el EEG {eeg_id}.")
|
||||||
|
valid, level, age_months = row
|
||||||
|
return {
|
||||||
|
"eeg_id": _public_id(eeg_id), "valid": _valid(valid), "level": level, "age_months": age_months,
|
||||||
|
"metrics": [
|
||||||
|
{"name": code.lower(), "value": value, "z": z, "outside": outside, "model": model}
|
||||||
|
for code, value, z, outside, model in session.execute(metrics)
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
def summary(self) -> dict:
|
||||||
|
failed = Eeg.eeg_error.is_not(None)
|
||||||
|
eeg_counts = select(
|
||||||
|
func.count().label("eegs"),
|
||||||
|
_count_where(or_(Eeg.eeg_valido.is_not(None), failed)).label("analysed"),
|
||||||
|
_count_where(Eeg.eeg_valido == 1).label("valid"),
|
||||||
|
_count_where(Eeg.eeg_valido == 0).label("not_valid"),
|
||||||
|
_count_where(failed).label("failed"),
|
||||||
|
).select_from(Eeg)
|
||||||
|
metric_counts = select(
|
||||||
|
func.count().label("metrics"),
|
||||||
|
_count_where(EegMetrica.met_z.is_not(None)).label("metrics_with_z"),
|
||||||
|
_count_where(EegMetrica.met_fuera == 1).label("high"),
|
||||||
|
_count_where(EegMetrica.met_fuera == -1).label("low"),
|
||||||
|
).select_from(EegMetrica)
|
||||||
|
with self.repository.open_session() as session:
|
||||||
|
relations = inspect(session.connection())
|
||||||
|
return {
|
||||||
|
**session.execute(eeg_counts).mappings().one(),
|
||||||
|
**session.execute(metric_counts).mappings().one(),
|
||||||
|
**{
|
||||||
|
name: session.scalar(select(func.count()).select_from(view))
|
||||||
|
if relations.has_table(view.name) else 0
|
||||||
|
for name, view in (("fhir_eegs", EEGS), ("fhir_metrics", METRICS))
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""Store reference cohorts on the local filesystem."""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import NamedTemporaryFile
|
||||||
|
from typing import BinaryIO
|
||||||
|
|
||||||
|
COHORT_NAME = re.compile(r"[A-Za-z0-9._-]{1,64}")
|
||||||
|
AGES_FILE = "edades.csv"
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_component(value: str) -> bool:
|
||||||
|
return bool(value) and value != "." and not any(char in value for char in ("/", "\\", "..", "\0", ":"))
|
||||||
|
|
||||||
|
|
||||||
|
class ReferenceCohortStore:
|
||||||
|
"""List cohorts and atomically publish uploads under a configured root."""
|
||||||
|
|
||||||
|
def __init__(self, root: str | Path):
|
||||||
|
self.root = Path(root).resolve()
|
||||||
|
|
||||||
|
def list_cohorts(self) -> list[dict]:
|
||||||
|
if not self.root.exists():
|
||||||
|
return []
|
||||||
|
|
||||||
|
cohorts = []
|
||||||
|
for folder in sorted(self.root.iterdir()):
|
||||||
|
if (not COHORT_NAME.fullmatch(folder.name) or not _safe_component(folder.name)
|
||||||
|
or folder.is_symlink() or not folder.is_dir()):
|
||||||
|
continue
|
||||||
|
edfs = [
|
||||||
|
path for path in folder.rglob("*")
|
||||||
|
if path.suffix.lower() == ".edf" and not path.is_symlink() and path.is_file()
|
||||||
|
]
|
||||||
|
ages = folder / AGES_FILE
|
||||||
|
has_ages = not ages.is_symlink() and ages.is_file()
|
||||||
|
size = sum(path.stat().st_size for path in edfs)
|
||||||
|
if has_ages:
|
||||||
|
size += ages.stat().st_size
|
||||||
|
cohorts.append({
|
||||||
|
"name": folder.name,
|
||||||
|
"edfs": len(edfs),
|
||||||
|
"size_bytes": size,
|
||||||
|
"has_ages": has_ages,
|
||||||
|
"path": str(folder),
|
||||||
|
})
|
||||||
|
return cohorts
|
||||||
|
|
||||||
|
def save_file(self, name: str, filename: str, stream: BinaryIO) -> dict:
|
||||||
|
if not COHORT_NAME.fullmatch(name) or not _safe_component(name):
|
||||||
|
raise ValueError("Nombre de cohorte inválido.")
|
||||||
|
if not _safe_component(filename):
|
||||||
|
raise ValueError("Nombre de archivo inválido.")
|
||||||
|
if filename != AGES_FILE and Path(filename).suffix.lower() != ".edf":
|
||||||
|
raise ValueError("Solo se admite un archivo EDF o edades.csv.")
|
||||||
|
|
||||||
|
folder = self.root / name
|
||||||
|
target = folder / filename
|
||||||
|
if folder.is_symlink() or target.is_symlink():
|
||||||
|
raise ValueError("Ruta de archivo inválida.")
|
||||||
|
folder.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
temporary = None
|
||||||
|
try:
|
||||||
|
with NamedTemporaryFile(dir=folder, suffix=".tmp", delete=False) as output:
|
||||||
|
temporary = Path(output.name)
|
||||||
|
shutil.copyfileobj(stream, output, length=1024 * 1024)
|
||||||
|
size = output.tell()
|
||||||
|
temporary.replace(target)
|
||||||
|
finally:
|
||||||
|
if temporary is not None:
|
||||||
|
temporary.unlink(missing_ok=True)
|
||||||
|
return {"name": name, "file": filename, "size_bytes": size}
|
||||||
+100
-52
@@ -7,17 +7,23 @@ worker of the server answers for any job and a restart does not lose them. A job
|
|||||||
code is `interrumpido`.
|
code is `interrumpido`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import subprocess
|
import re
|
||||||
|
import subprocess as subprocess
|
||||||
import sys
|
import sys
|
||||||
import tomllib
|
import tomllib
|
||||||
import uuid
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
TAIL_CHARS = 4000
|
from webapi import detached_jobs
|
||||||
# A domain whose scenarios train on a reference cohort and not on a dbt cohort build.
|
from webapi.detached_jobs import cluster_environment as _training_cluster
|
||||||
|
REFERENCE_ENV = {
|
||||||
|
"reference_name": "TEA_REFERENCE_NAME",
|
||||||
|
"reference_dir": "TEA_REFERENCE_DIR",
|
||||||
|
"reference_ages": "TEA_REFERENCE_AGES",
|
||||||
|
"line_hz": "TEA_REFERENCE_LINE_HZ",
|
||||||
|
}
|
||||||
|
# A domain whose scenarios train on a reference cohort and not on a dbt cohort build; a scenario that says `external` in its
|
||||||
|
# `model.toml` does too, whatever its domain.
|
||||||
OWN_STEPS = {"tea": "Entrena con la cohorte de referencia de EEG (el clúster, o la carpeta de `TEA_REFERENCE_DIR`)."}
|
OWN_STEPS = {"tea": "Entrena con la cohorte de referencia de EEG (el clúster, o la carpeta de `TEA_REFERENCE_DIR`)."}
|
||||||
|
|
||||||
|
|
||||||
@@ -50,68 +56,111 @@ def _base() -> Path:
|
|||||||
return Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "entrenamientos"
|
return Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "entrenamientos"
|
||||||
|
|
||||||
|
|
||||||
def _command(domain: str, scenario: str) -> list[str]:
|
def _tea_parameters(body: dict, env: dict[str, str]) -> dict:
|
||||||
argv = [sys.executable, "-m", "models", "run", domain, scenario, "--environment", "prod", "--train", "--promote"]
|
parameters = {key: body.get(key, env.get(variable) or None) for key, variable in REFERENCE_ENV.items()}
|
||||||
|
if not parameters["reference_dir"]:
|
||||||
|
for key in ("reference_ages", "line_hz"):
|
||||||
|
if key not in body:
|
||||||
|
parameters[key] = None
|
||||||
|
|
||||||
|
for key in ("reference_name", "reference_dir", "reference_ages"):
|
||||||
|
if key in body and (not isinstance(body[key], str) or not body[key] or "\0" in body[key]):
|
||||||
|
raise ValueError(f"{key} debe ser texto no vacío.")
|
||||||
|
name = parameters["reference_name"]
|
||||||
|
if name is not None and not re.fullmatch(r"[A-Za-z0-9._-]{1,64}", name):
|
||||||
|
raise ValueError("reference_name debe tener de 1 a 64 caracteres de A-Z, a-z, 0-9, punto, guion o guion bajo.")
|
||||||
|
if "reference_dir" in body and not Path(body["reference_dir"]).is_absolute():
|
||||||
|
raise ValueError("reference_dir debe ser una ruta absoluta.")
|
||||||
|
if "line_hz" in body and (type(body["line_hz"]) not in (int, float) or body["line_hz"] not in (50, 60)):
|
||||||
|
raise ValueError("line_hz debe ser 50 o 60.")
|
||||||
|
promote = body.get("promote", True)
|
||||||
|
if not isinstance(promote, bool):
|
||||||
|
raise ValueError("promote debe ser un valor booleano.")
|
||||||
|
return {**parameters, "promote": promote}
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_cohort(parameters: dict, body: dict, root: str) -> None:
|
||||||
|
"""Point a named cohort at its folder (and ages table) under `root`, when the request gave no directory."""
|
||||||
|
name = parameters["reference_name"]
|
||||||
|
if "reference_dir" in body or not name or not root:
|
||||||
|
return
|
||||||
|
folder = Path(root) / name
|
||||||
|
if not folder.is_dir():
|
||||||
|
return
|
||||||
|
parameters["reference_dir"] = str(folder)
|
||||||
|
ages = folder / "edades.csv"
|
||||||
|
if "reference_ages" not in body and ages.is_file():
|
||||||
|
parameters["reference_ages"] = str(ages)
|
||||||
|
|
||||||
|
|
||||||
|
def _check_reference_paths(parameters: dict, root: str) -> None:
|
||||||
|
for key in ("reference_dir", "reference_ages"):
|
||||||
|
value = parameters[key]
|
||||||
|
if value is None:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
path = Path(value).resolve()
|
||||||
|
inside_root = path.is_relative_to(Path(root).resolve())
|
||||||
|
except (OSError, RuntimeError, ValueError):
|
||||||
|
raise ValueError(f"No se pudo resolver la ruta de {key}.") from None
|
||||||
|
if not inside_root:
|
||||||
|
raise ValueError(f"{key} debe estar dentro de TEA_REFERENCE_ROOT.")
|
||||||
|
parameters[key] = str(path)
|
||||||
|
|
||||||
|
|
||||||
|
def _command(domain: str, scenario: str, parameters: dict | None = None) -> list[str]:
|
||||||
|
argv = [sys.executable, "-m", "models", "run", domain, scenario, "--environment", "prod", "--train"]
|
||||||
|
if domain == "tea" and parameters is None:
|
||||||
|
parameters = _tea_parameters({}, os.environ)
|
||||||
|
if parameters is None or parameters["promote"]:
|
||||||
|
argv.append("--promote")
|
||||||
external = any(e["external"] for e in catalog() if (e["domain"], e["scenario"]) == (domain, scenario))
|
external = any(e["external"] for e in catalog() if (e["domain"], e["scenario"]) == (domain, scenario))
|
||||||
if not external:
|
if not external:
|
||||||
argv += ["--export", "--source", "dbt", "--manifest", os.environ["DBT_MANIFEST"]]
|
argv += ["--export", "--source", "dbt", "--manifest", os.environ["DBT_MANIFEST"]]
|
||||||
elif domain == "tea" and os.environ.get("TEA_REFERENCE_DIR"):
|
elif parameters is not None:
|
||||||
# A reference cohort on this machine's disk, instead of the configured one in the cluster's storage.
|
for key in ("reference_dir", "reference_ages", "line_hz", "reference_name"):
|
||||||
argv += ["--reference-dir", os.environ["TEA_REFERENCE_DIR"]]
|
if parameters[key] is not None:
|
||||||
if os.environ.get("TEA_REFERENCE_AGES"):
|
argv += [f"--{key.replace('_', '-')}", str(parameters[key])]
|
||||||
argv += ["--reference-ages", os.environ["TEA_REFERENCE_AGES"]]
|
|
||||||
if os.environ.get("TEA_REFERENCE_LINE_HZ"):
|
|
||||||
argv += ["--line-hz", os.environ["TEA_REFERENCE_LINE_HZ"]]
|
|
||||||
return argv
|
return argv
|
||||||
|
|
||||||
|
|
||||||
def _alive(pid: int) -> bool:
|
|
||||||
try:
|
|
||||||
os.kill(pid, 0)
|
|
||||||
except ProcessLookupError:
|
|
||||||
return False
|
|
||||||
except PermissionError:
|
|
||||||
return True
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def _tail(path: Path) -> str:
|
|
||||||
return path.read_text(encoding="utf-8", errors="replace")[-TAIL_CHARS:].strip() if path.exists() else ""
|
|
||||||
|
|
||||||
|
|
||||||
def _state(folder: Path) -> dict:
|
def _state(folder: Path) -> dict:
|
||||||
job = json.loads((folder / "job.json").read_text(encoding="utf-8"))
|
job = detached_jobs.state(folder)
|
||||||
out, err = _tail(folder / "stdout.log"), _tail(folder / "stderr.log")
|
if job["estado"] == "fallido" and "not promoted, missing" in job["error"]:
|
||||||
exit_file = folder / "exit"
|
job["estado"] = "entrenado_sin_promover"
|
||||||
if exit_file.exists():
|
job.pop("parameters", None)
|
||||||
code = int(exit_file.read_text().strip() or 1)
|
job.setdefault("cluster", None)
|
||||||
state = ("completado" if code == 0 else "entrenado_sin_promover" if "not promoted, missing" in err else "fallido")
|
return job
|
||||||
elif _alive(job["pid"]):
|
|
||||||
code, state = None, "en_curso"
|
|
||||||
else:
|
|
||||||
code, state = None, "interrumpido"
|
|
||||||
return {**job, "estado": state, "codigo": code, "salida": out, "error": err}
|
|
||||||
|
|
||||||
|
|
||||||
def running(domain: str, scenario: str) -> dict | None:
|
def running(domain: str, scenario: str) -> dict | None:
|
||||||
return next((j for j in jobs() if j["estado"] == "en_curso" and (j["domain"], j["scenario"]) == (domain, scenario)), None)
|
return next((j for j in jobs() if j["estado"] == "en_curso" and (j["domain"], j["scenario"]) == (domain, scenario)), None)
|
||||||
|
|
||||||
|
|
||||||
def start(domain: str, scenario: str) -> dict:
|
def start(domain: str, scenario: str, body: dict | None = None) -> dict:
|
||||||
"""Starts a job. `LookupError` for a scenario that cannot be trained, `RuntimeError` with no dbt manifest."""
|
"""Starts a job. `LookupError` for a scenario that cannot be trained, `RuntimeError` with no dbt manifest."""
|
||||||
if (domain, scenario) not in {(s["domain"], s["scenario"]) for s in catalog()}:
|
if (domain, scenario) not in {(s["domain"], s["scenario"]) for s in catalog()}:
|
||||||
raise LookupError(f"no such model: {domain}/{scenario}")
|
raise LookupError(f"no such model: {domain}/{scenario}")
|
||||||
if not any(e["external"] for e in catalog() if (e["domain"], e["scenario"]) == (domain, scenario)) and not os.environ.get("DBT_MANIFEST"):
|
if not any(e["external"] for e in catalog() if (e["domain"], e["scenario"]) == (domain, scenario)) and not os.environ.get("DBT_MANIFEST"):
|
||||||
raise RuntimeError("No hay un manifest de dbt configurado.")
|
raise RuntimeError("No hay un manifest de dbt configurado.")
|
||||||
job_id = f"{datetime.now(timezone.utc):%Y%m%dT%H%M%S}-{uuid.uuid4().hex[:6]}"
|
env = os.environ.copy()
|
||||||
folder = _base() / job_id
|
cluster = None
|
||||||
folder.mkdir(parents=True)
|
if domain == "tea":
|
||||||
shell = '{ "$@" > stdout.log 2> stderr.log; echo $? > exit; }'
|
body = {} if body is None else body
|
||||||
process = subprocess.Popen(["sh", "-c", shell, "sh", *_command(domain, scenario)], cwd=folder, start_new_session=True,
|
cluster = _training_cluster(body, env)
|
||||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
parameters = _tea_parameters(body, env)
|
||||||
job = {"id": job_id, "domain": domain, "scenario": scenario, "pid": process.pid,
|
if env.get("TEA_REFERENCE_ROOT") and (cluster is None or cluster["mode"] != "remote"):
|
||||||
"iniciado": datetime.now(timezone.utc).isoformat(timespec="seconds")}
|
_resolve_cohort(parameters, body, env["TEA_REFERENCE_ROOT"])
|
||||||
(folder / "job.json").write_text(json.dumps(job), encoding="utf-8")
|
_check_reference_paths(parameters, env["TEA_REFERENCE_ROOT"])
|
||||||
|
argv = _command(domain, scenario, parameters)
|
||||||
|
if parameters["line_hz"] is None and parameters["reference_dir"]:
|
||||||
|
parameters["line_hz"] = 60
|
||||||
|
else:
|
||||||
|
parameters = None
|
||||||
|
argv = _command(domain, scenario)
|
||||||
|
folder = detached_jobs.launch(_base(), argv, env, {
|
||||||
|
"domain": domain, "scenario": scenario, "cluster": cluster, "parameters": parameters,
|
||||||
|
})
|
||||||
return _state(folder)
|
return _state(folder)
|
||||||
|
|
||||||
|
|
||||||
@@ -124,5 +173,4 @@ def get(job_id: str) -> dict:
|
|||||||
|
|
||||||
def jobs(limit: int = 50) -> list[dict]:
|
def jobs(limit: int = 50) -> list[dict]:
|
||||||
"""The latest jobs, newest first."""
|
"""The latest jobs, newest first."""
|
||||||
folders = sorted((p for p in _base().glob("*") if (p / "job.json").exists()), reverse=True) if _base().exists() else []
|
return [_state(folder) for folder in detached_jobs.folders(_base())[:limit]]
|
||||||
return [_state(p) for p in folders[:limit]]
|
|
||||||
|
|||||||
Reference in New Issue
Block a user