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
+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}