Governance TEA EEG: reference cohorts, baselines export and import, cluster health, training and analysis jobs with progress, EDF upload, EEG queries

This commit is contained in:
ulises
2026-11-23 09:29:31 -06:00
parent 5831fcd9d9
commit 0e6494f053
20 changed files with 1914 additions and 88 deletions
+199
View File
@@ -18,6 +18,7 @@ import os
from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict
from pathlib import Path
from tempfile import NamedTemporaryFile
from urllib.parse import quote
from core.governance.enums import EstatusExtraccion
@@ -32,6 +33,10 @@ from models.reports import experiment
from persistance.governance import extraction_run_repository
from persistance.repository import Repository
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__)
@@ -57,6 +62,108 @@ def _pk_name(repository: Repository) -> str:
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
# -- model versions ----------------------------------------------------------------
@@ -142,6 +249,11 @@ def start_training_job(domain: str, scenario: str):
return jsonify({"error": "Ya hay un entrenamiento en curso para este modelo.",
"job": training_jobs.running(domain, scenario)}), 409
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
except RuntimeError as error:
return jsonify({"error": str(error)}), 503
@@ -441,6 +553,49 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
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")
def run_eeg_analysis():
"""Runs TEA's EEG analysis on the stored EDFs that need it (`models.eeg_analysis`), in this request: at most
@@ -495,3 +650,47 @@ def run_ocr():
"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())
+11 -1
View File
@@ -1,7 +1,10 @@
"""Aggregate reports: the log of import attempts and the state of the live
indicator recomputation. Nothing here returns row-level data."""
import os
from flask import Blueprint, Response, jsonify, request
from webapi.detached_jobs import cluster_environment
from webapi.imports import audit as import_audit
from webapi.recomputation import DOMAINS, RecomputationQueue
@@ -45,5 +48,12 @@ def recomputation_status():
def recompute(dominio: str):
if dominio not in DOMAINS:
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
+90
View File
@@ -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)
+36 -35
View File
@@ -24,6 +24,7 @@ import os
import signal
import threading
import time
from contextlib import contextmanager
from datetime import date, datetime, timezone
from pathlib import Path
from typing import Any
@@ -48,34 +49,21 @@ def _short(value: Any) -> str:
return text if len(text) <= _SUMMARY_MAX else text[:_SUMMARY_MAX] + "…"
def _warm_models(dominio: str) -> dict[str, Any]:
"""Leaves the members of the domain's live models labelled over the new build, so the API reads them instead of the build,
and their scenario points computed by the pipeline over those members."""
from webapi.model_analysis import refresh_subgroups, warm
@contextmanager
def _cluster_override(cluster: dict | None):
"""Applies a cluster choice to this process's environment while a run lasts, then restores it."""
if not cluster:
yield
return
from webapi.detached_jobs import cluster_environment
started = time.monotonic()
saved = dict(os.environ)
try:
resumen = {"cargados": warm(dominio), "escenarios_recalculados": refresh_subgroups(dominio)}
except Exception as exc: # the indicators are already saved
log.exception("no se pudieron preparar los modelos de %s", dominio)
resumen = f"error: {type(exc).__name__}"
return {"paso": "modelos", "segundos": round(time.monotonic() - started, 2), "resumen": _short(resumen)}
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)}
cluster_environment({"cluster": cluster}, os.environ)
yield
finally:
os.environ.clear()
os.environ.update(saved)
class RecomputationQueue:
@@ -92,11 +80,20 @@ class RecomputationQueue:
def _status_path(self) -> Path:
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:
raise ValueError(f"dominio desconocido: {dominio!r}")
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]:
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.replace(self._status_path)
def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
"""Runs the domain's graph (without `migrate`: the API migrates on startup)."""
def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None,
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.eeg import live_ados2_relation, live_ados2_scoring, live_eeg_analysis
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]})
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
try:
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio),
eeg_analysis=live_eeg_analysis(dominio), ados2_relation=live_ados2_relation(dominio),
ados2_scoring=live_ados2_scoring(dominio))
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
with _cluster_override(cluster):
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio),
eeg_analysis=live_eeg_analysis(dominio), ados2_relation=live_ados2_relation(dominio),
ados2_scoring=live_ados2_scoring(dominio))
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
entrada.update(
estado="ok",
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."""
ran = []
for dominio in self.pending():
choice = self.requested_cluster(dominio)
if self.take(dominio):
self.run(dominio)
self.run(dominio, cluster=choice)
ran.append(dominio)
return ran
+1
View File
@@ -0,0 +1 @@
"""TEA governance storage services."""
+100
View File
@@ -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
+44
View File
@@ -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}
+70
View File
@@ -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
+112
View File
@@ -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))
},
}
+74
View File
@@ -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
View File
@@ -7,17 +7,23 @@ worker of the server answers for any job and a restart does not lose them. A job
code is `interrumpido`.
"""
import json
import os
import subprocess
import re
import subprocess as subprocess
import sys
import tomllib
import uuid
from datetime import datetime, timezone
from pathlib import Path
TAIL_CHARS = 4000
# A domain whose scenarios train on a reference cohort and not on a dbt cohort build.
from webapi import detached_jobs
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`)."}
@@ -50,68 +56,111 @@ def _base() -> Path:
return Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "entrenamientos"
def _command(domain: str, scenario: str) -> list[str]:
argv = [sys.executable, "-m", "models", "run", domain, scenario, "--environment", "prod", "--train", "--promote"]
def _tea_parameters(body: dict, env: dict[str, str]) -> dict:
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))
if not external:
argv += ["--export", "--source", "dbt", "--manifest", os.environ["DBT_MANIFEST"]]
elif domain == "tea" and os.environ.get("TEA_REFERENCE_DIR"):
# A reference cohort on this machine's disk, instead of the configured one in the cluster's storage.
argv += ["--reference-dir", os.environ["TEA_REFERENCE_DIR"]]
if os.environ.get("TEA_REFERENCE_AGES"):
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"]]
elif parameters is not None:
for key in ("reference_dir", "reference_ages", "line_hz", "reference_name"):
if parameters[key] is not None:
argv += [f"--{key.replace('_', '-')}", str(parameters[key])]
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:
job = json.loads((folder / "job.json").read_text(encoding="utf-8"))
out, err = _tail(folder / "stdout.log"), _tail(folder / "stderr.log")
exit_file = folder / "exit"
if exit_file.exists():
code = int(exit_file.read_text().strip() or 1)
state = ("completado" if code == 0 else "entrenado_sin_promover" if "not promoted, missing" in err else "fallido")
elif _alive(job["pid"]):
code, state = None, "en_curso"
else:
code, state = None, "interrumpido"
return {**job, "estado": state, "codigo": code, "salida": out, "error": err}
job = detached_jobs.state(folder)
if job["estado"] == "fallido" and "not promoted, missing" in job["error"]:
job["estado"] = "entrenado_sin_promover"
job.pop("parameters", None)
job.setdefault("cluster", None)
return job
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)
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."""
if (domain, scenario) not in {(s["domain"], s["scenario"]) for s in catalog()}:
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"):
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]}"
folder = _base() / job_id
folder.mkdir(parents=True)
shell = '{ "$@" > stdout.log 2> stderr.log; echo $? > exit; }'
process = subprocess.Popen(["sh", "-c", shell, "sh", *_command(domain, scenario)], cwd=folder, start_new_session=True,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
job = {"id": job_id, "domain": domain, "scenario": scenario, "pid": process.pid,
"iniciado": datetime.now(timezone.utc).isoformat(timespec="seconds")}
(folder / "job.json").write_text(json.dumps(job), encoding="utf-8")
env = os.environ.copy()
cluster = None
if domain == "tea":
body = {} if body is None else body
cluster = _training_cluster(body, env)
parameters = _tea_parameters(body, env)
if env.get("TEA_REFERENCE_ROOT") and (cluster is None or cluster["mode"] != "remote"):
_resolve_cohort(parameters, body, env["TEA_REFERENCE_ROOT"])
_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)
@@ -124,5 +173,4 @@ def get(job_id: str) -> dict:
def jobs(limit: int = 50) -> list[dict]:
"""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(p) for p in folders[:limit]]
return [_state(folder) for folder in detached_jobs.folders(_base())[:limit]]