"""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