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())