Files

712 lines
29 KiB
Python

"""Model governance (ML, MLD, EL and VAR requirements): model versions and
their training and promotion, notebooks run on a cohort build, and the OCR
extraction jobs with their manual review queue.
Versions and artifacts live in MLflow (`models.io.registry`). Training can
either run elsewhere and register its result through `POST /model-versions`
(naming the indicator kit cohort build it was trained on,
`cohorte_armado_id`), or be triggered in place through `POST
/model-versions/<domain>/<scenario>/train`, for a deployment with no
command-line access to run the `entrenar` compose profile by hand.
Notebooks (`models.reports.experiment`) run in the background on the build's
file alone and are kept as MLflow runs.
"""
import contextlib
import io
import json
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
from core.governance.models import ExtractionRun
from core.ocr import OcrEstatus
from flask import Blueprint, Response, jsonify, request
from models.io.lineage import DOMAINS
from models.io.registry import REPORT_TAGS, PromotionBlocked, registry
from models.io.storage import build_file, cohorts_root, exported_builds
from models.ocr import OCR_JOBS, OcrJob, run_pending_extractions
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__)
@governance_bp.errorhandler(LookupError)
def _not_found(exc: LookupError):
return jsonify({"error": str(exc)}), 404
@governance_bp.errorhandler(ValueError)
def _bad_request(exc: ValueError):
return jsonify({"error": str(exc)}), 400
def _ocr_job(domain: str | None, entity: str | None) -> OcrJob:
job = OCR_JOBS.get((domain, entity))
if job is None:
raise LookupError(f"no hay un trabajo de OCR registrado para (domain={domain!r}, entity={entity!r})")
return job
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
@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 ----------------------------------------------------------------
@governance_bp.get("/model-versions")
def list_model_versions():
"""`?domain=` alone matches every scenario of that domain; `?domain=&scenario=`
matches one; neither matches everything."""
return jsonify({"model_versions": registry.versions(request.args.get("domain"), request.args.get("scenario"))})
@governance_bp.post("/model-versions")
def register_model_version():
"""Registers a trained version: `{domain, scenario,
environment: DEV|PROD, cohorte_armado_id?, metrics?, hyperparameters?,
technical_validation_report_uri?, clinical_validation_report_uri?,
interpretability_report_uri?}`."""
body = request.get_json(silent=True) or {}
missing = [k for k in ("domain", "scenario", "environment") if not body.get(k)]
if missing:
return jsonify({"error": f"faltan campos: {missing}"}), 400
version = registry.register(
domain=body["domain"],
scenario=body["scenario"],
environment=body["environment"],
cohorte_armado_id=body.get("cohorte_armado_id"),
metrics=body.get("metrics"),
hyperparameters=body.get("hyperparameters"),
**{k: body[k] for k in REPORT_TAGS if k in body},
)
return jsonify(registry.describe(body["domain"], body["scenario"], version)), 201
@governance_bp.post("/model-versions/<domain>/<scenario>/train")
def train_model_version(domain: str, scenario: str):
"""Exports the scenario's latest dbt cohort build, trains a PROD version on it unless one from the same file,
code and environment already exists, and tries to promote it: the same one-shot pipeline the `entrenar`
compose profile runs (`models run <domain> <scenario> --export --source dbt --environment prod --train
--promote`), over HTTP instead of a shell. 503 with no dbt manifest configured; 404 for a domain/scenario with
no trainer or whose cohort isn't exportable yet; 409 with the training's own version trained but not promoted
(it's missing its validation reports: attach them, then `/promote`)."""
from models.__main__ import main as models_main
manifest = os.environ.get("DBT_MANIFEST")
if not manifest:
return jsonify({"error": "No hay un manifest de dbt configurado."}), 503
argv = ["run", domain, scenario, "--export", "--source", "dbt", "--manifest", manifest, "--environment", "prod",
"--train", "--promote"]
out, err = io.StringIO(), io.StringIO()
try:
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = models_main(argv)
except SystemExit as exit:
code = exit.code if isinstance(exit.code, int) else 1
output, error = out.getvalue().strip(), err.getvalue().strip()
if code == 0:
return jsonify({"output": output})
status = 404 if "no such model" in error else 409 if "not promoted, missing" in error else 503
return jsonify({"error": error or "No se pudo entrenar el modelo.", "output": output}), status
@governance_bp.get("/scenarios")
def trainable_scenarios():
"""The scenarios that can be trained from here, each with its production version if it has one."""
from webapi import training_jobs
result = []
for entry in training_jobs.catalog():
try:
production = str(registry.resolve(entry["domain"], entry["scenario"]).version)
except LookupError:
production = None
result.append({**entry, "produccion": production})
return jsonify({"scenarios": result})
@governance_bp.post("/model-versions/<domain>/<scenario>/train-jobs")
def start_training_job(domain: str, scenario: str):
"""Starts the scenario's training in the background and answers 202 with the job; a job of that scenario that is
still running is answered 409 with it. 404 for a scenario that cannot be trained, 503 with no dbt manifest."""
from webapi import training_jobs
if training_jobs.running(domain, scenario) is not None:
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
@governance_bp.get("/training-jobs")
def list_training_jobs():
from webapi import training_jobs
return jsonify({"jobs": training_jobs.jobs()})
@governance_bp.get("/training-jobs/<job_id>")
def training_job(job_id: str):
from webapi import training_jobs
return jsonify({"job": training_jobs.get(job_id)})
@governance_bp.patch("/model-versions/<domain>/<scenario>/<version>/reports")
def attach_reports(domain: str, scenario: str, version: str):
"""MLD-01/01b/03 documents, usually written after training."""
body = request.get_json(silent=True) or {}
registry.attach_reports(domain, scenario, version, **body)
return jsonify(registry.describe(domain, scenario, version))
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>/lineage")
def model_version_lineage(domain: str, scenario: str, version: str):
return jsonify(registry.lineage(domain, scenario, version))
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>/checks")
def model_version_checks(domain: str, scenario: str, version: str):
checks = registry.checks(domain, scenario, version)
return jsonify({"ready": all(c.passed for c in checks), "checks": [asdict(c) for c in checks]})
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/promote")
def promote_model_version(domain: str, scenario: str, version: str):
"""Puts the version in production, tagging the previous one of its
scenario `retirada_en`. 409 with the failing checks when it isn't ready."""
try:
registry.promote(domain, scenario, version)
except PromotionBlocked as blocked:
return jsonify({"error": str(blocked), "checks": [asdict(c) for c in blocked.checks]}), 409
return jsonify(registry.describe(domain, scenario, version))
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/retire")
def retire_model_version(domain: str, scenario: str, version: str):
registry.retire(domain, scenario, version)
return jsonify(registry.describe(domain, scenario, version))
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>/artifacts/<path:path>")
def download_artifact(domain: str, scenario: str, version: str, path: str):
"""ML-01b: one file the version's training run stored; a folder (the saved model) as a zip."""
name, data = registry.artifact(domain, scenario, version, path)
return _download(name, data)
# -- notebooks -------------------------------------------------------------------------
def submit(job, *args):
"""Runs a notebook in the background, one at a time per worker by default (`WEBAPI_NOTEBOOK_WORKERS`)."""
return _notebooks.submit(job, *args)
_notebooks = ThreadPoolExecutor(max_workers=int(os.environ.get("WEBAPI_NOTEBOOK_WORKERS", "1")), thread_name_prefix="notebook")
def _cohorts_root(domain: str) -> Path:
if domain not in DOMAINS:
raise ValueError(f"dominio desconocido: {domain!r}")
return cohorts_root(getattr(settings, f"{domain}_database_url"))
@governance_bp.get("/cohort-files")
def list_cohort_files():
"""`?domain=`: the domain's cohort builds that have their file, the data a notebook can run on."""
domain = request.args.get("domain", "")
return jsonify({"builds": exported_builds(_cohorts_root(domain), domain)})
@governance_bp.get("/notebook-templates")
def list_notebook_templates():
"""`?domain=`: the notebooks kept in the code (`models/<domain>/<scenario>/notebooks/`), with the scenarios each can
run for; `POST /experiments` runs one by its `id` as `template`."""
from models.reports.templates import notebook_templates
return jsonify({"templates": notebook_templates(request.args.get("domain") or None)})
@governance_bp.get("/experiments")
def list_experiments():
"""Notebook runs, newest first; `?domain=` and `?domain=&scenario=` narrow them."""
return jsonify({"experiments": experiment.experiments(request.args.get("domain") or None,
request.args.get("scenario") or None)})
@governance_bp.post("/experiments")
def run_experiment():
"""Multipart `file` (a .ipynb) or `template` (the id of a notebook kept in the code, `/notebook-templates`), `domain`,
`scenario`, `url`, `source` (kit|dbt), `build` and optionally `version`: runs the notebook on that build's file in
the background and answers 202 with the run, still `en_curso`. A template is read from the code, never from the
request, and must be of the domain and serve the scenario."""
upload = request.files.get("file")
form = request.form
template = form.get("template") or None
missing = [k for k in ("domain", "scenario", "url", "source", "build") if not form.get(k)]
if (upload is None and template is None) or missing:
return jsonify({"error": f"faltan campos: {(['file o template'] if upload is None and template is None else []) + missing}"}), 400
if upload is not None and template is not None:
return jsonify({"error": "elige un archivo o una plantilla, no ambos"}), 400
domain, scenario, version = form["domain"], form["scenario"], form.get("version") or None
url = form["url"]
if url.split("/", 1)[0] != domain:
return jsonify({"error": f"la cohorte {url!r} no es del dominio {domain!r}"}), 400
if not form["build"].isdigit():
return jsonify({"error": "build debe ser un número"}), 400
path = build_file(_cohorts_root(domain), url, form["source"], int(form["build"]))
if template is not None:
from models.reports.templates import notebook_templates, template_notebook
name, notebook = template_notebook(template)
found = {t["id"]: t for t in notebook_templates(domain)}.get(template)
if found is None or scenario not in found["scenarios"]:
return jsonify({"error": f"la plantilla {template!r} no corre para {domain}/{scenario}"}), 400
else:
try:
notebook = experiment.check_notebook(json.loads(upload.read()))
except (UnicodeDecodeError, json.JSONDecodeError):
return jsonify({"error": "el archivo no es un notebook de Jupyter (.ipynb)"}), 400
name = experiment.notebook_name(upload.filename or "notebook")
if version:
registry.get(domain, scenario, version)
run_id = experiment.start(notebook, name, path, domain, scenario, version)
submit(experiment.execute, run_id, notebook, name, path, domain, scenario, version)
return jsonify(experiment.describe(run_id)), 202
@governance_bp.get("/experiments/<run_id>")
def get_experiment(run_id: str):
return jsonify(experiment.describe(run_id))
@governance_bp.get("/experiments/<run_id>/page")
def experiment_page(run_id: str):
"""The notebook's rendered page. It's served sandboxed, as an origin of its own, since its scripts are the
notebook's."""
page = experiment.page(run_id)
if page is None:
return jsonify({"error": "el notebook todavía no tiene página"}), 404
response = Response(page, mimetype="text/html")
response.headers["Content-Security-Policy"] = "sandbox allow-scripts allow-popups"
response.headers["X-Content-Type-Options"] = "nosniff"
return response
@governance_bp.get("/experiments/<run_id>/artifacts/<path:path>")
def download_experiment_artifact(run_id: str, path: str):
name, data = experiment.artifact(run_id, path)
return _download(name, data)
def _download(name: str, data: bytes):
response = Response(data, mimetype="application/octet-stream")
response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{quote(name)}"
response.headers["X-Content-Type-Options"] = "nosniff"
return response
# -- OCR ---------------------------------------------------------------------------------
@governance_bp.get("/ocr/jobs")
def list_ocr_jobs():
"""The configured OCR jobs, with the result columns each one fills."""
jobs = [
{
"domain": job.domain,
"entity": job.entity,
"label": job.label,
"result_fields": list(job.columns.result_field_map.values()),
}
for job in OCR_JOBS.values()
]
return jsonify({"jobs": jobs})
@governance_bp.get("/ocr/<domain>/<entity>/rows")
def list_ocr_rows(domain: str, entity: str):
"""Rows of an OCR job filtered by `status`: `review` (the default, rows
flagged `requiere_revision`), `pending`, `failed`, `done` or `all`.
Filtering happens in Python: `Repository.list` only supports equality."""
job = _ocr_job(domain, entity)
repository, spec = job.repository, job.columns
status = request.args.get("status", "review")
limit = int(request.args.get("limit", 100))
offset = int(request.args.get("offset", 0))
pk_name = _pk_name(repository)
def matches(row) -> bool:
if getattr(row, spec.blob_field, None) is None:
return False
estatus = getattr(row, spec.estatus_field, None)
if status == "all":
return True
if status == "review":
return bool(getattr(row, spec.requiere_revision_field, None))
if status == "pending":
return estatus in (None, OcrEstatus.PENDIENTE.value)
if status == "failed":
return estatus == OcrEstatus.FALLIDO.value
if status == "done":
return estatus == OcrEstatus.REALIZADO.value
return True
candidates = [row for row in repository.iter_all() if matches(row)]
page = candidates[offset : offset + limit]
rows = [
{
"id": getattr(row, pk_name),
"pac_id_hospital": getattr(row, "pac_id_hospital", None),
"values": {column: getattr(row, column, None) for column in spec.result_field_map.values()},
"confianza": getattr(row, spec.confianza_field, None),
"estatus": getattr(row, spec.estatus_field, None),
"requiere_revision": getattr(row, spec.requiere_revision_field, None),
"metodo_principal": getattr(row, spec.metodo_principal_field, None),
"metodo_alternativo": getattr(row, spec.metodo_alternativo_field, None),
}
for row in page
]
return jsonify({"rows": rows, "total": len(candidates)})
@governance_bp.get("/ocr/<domain>/<entity>/<int:pk>/blob")
def get_ocr_blob(domain: str, entity: str, pk: int):
"""Raw bytes of the row's stored PDF, for the review UI's page viewer."""
job = _ocr_job(domain, entity)
repository, spec = job.repository, job.columns
row = repository.get(pk)
if row is None:
return jsonify({"error": "no se encontró el registro"}), 404
blob = getattr(row, spec.blob_field, None)
if blob is None:
return jsonify({"error": "esta fila no tiene un PDF almacenado"}), 404
return Response(blob, mimetype="application/pdf")
@governance_bp.post("/ocr/<domain>/<entity>/<int:pk>/correct")
def correct_ocr_row(domain: str, entity: str, pk: int):
"""Stores values entered by a reviewer for an OCR row. Marks the row
done with method "manual" (VAR-03), clears `requiere_revision`, and logs
an `ExtractionRun` like an automated run (VAR-07/08)."""
job = _ocr_job(domain, entity)
repository, spec = job.repository, job.columns
body = request.get_json(silent=True) or {}
values = body.get("values")
if not isinstance(values, dict) or not values:
return jsonify({"error": "'values' es requerido y debe tener al menos un campo"}), 400
allowed = set(spec.result_field_map.values())
unknown = set(values) - allowed
if unknown:
return jsonify({"error": f"columnas no permitidas para esta entidad: {sorted(unknown)}"}), 400
with repository.open_session() as session:
tracked = session.get(repository.model, pk)
if tracked is None:
return jsonify({"error": "no se encontró el registro"}), 404
for column, value in values.items():
setattr(tracked, column, value)
setattr(tracked, spec.estatus_field, OcrEstatus.REALIZADO.value)
setattr(tracked, spec.requiere_revision_field, False)
setattr(tracked, spec.metodo_principal_field, "manual")
setattr(tracked, spec.metodo_alternativo_field, None)
setattr(tracked, spec.confianza_field, float(body["confianza"]) if "confianza" in body else 1.0)
session.add(tracked)
session.commit()
session.refresh(tracked)
updated = tracked.model_dump()
extraction_run_repository.create(
ExtractionRun(
domain=domain,
entity=entity,
entity_pk=str(pk),
column_extracted=",".join(sorted(values)),
transform_description="Corrección manual",
estatus=EstatusExtraccion.COMPLETADA,
)
)
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
`limit` EEGs (5 by default), or every EEG with an EDF again with `all`. Larger batches are the indicator cycle's
or `python -m models tea analyze`'s. Rows already analysed with the current plan, modules and baselines are
skipped, so repeated calls are safe (VAR-09)."""
from models.eeg_analysis import analyze_pending
from webapi.orchestration.eeg import CLUSTERS, cluster as configured_cluster
body = request.get_json(silent=True) or {}
try:
limit = int(body.get("limit", 5))
except (TypeError, ValueError):
return jsonify({"error": "limit must be a whole number"}), 400
if limit < 1:
return jsonify({"error": "limit must be at least 1"}), 400
cluster = body.get("cluster") or configured_cluster()
if cluster not in CLUSTERS:
return jsonify({"error": f"cluster must be one of {', '.join(CLUSTERS)}"}), 400
summary = analyze_pending(everything=bool(body.get("all")), limit=limit, cluster=cluster)
return jsonify(asdict(summary))
@governance_bp.post("/ocr/run")
def run_ocr():
"""Runs an OCR job over pending rows. Rows already `REALIZADO` are
skipped, so repeated calls are safe (VAR-09)."""
body = request.get_json(silent=True) or {}
domain = body.get("domain")
entity = body.get("entity")
job = _ocr_job(domain, entity)
try:
summary = run_pending_extractions(
job.repository,
job.columns,
job.extractor(),
domain=domain,
entity=entity,
governance_repository=extraction_run_repository,
source_description=body.get("source_description"),
limit=int(body.get("limit", 500)),
)
except NotImplementedError as exc:
return jsonify({"error": str(exc)}), 501
return jsonify(
{
"processed": summary.processed,
"skipped_already_done": summary.skipped_already_done,
"failed": summary.failed,
"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())