"""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///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 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 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 # -- 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///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 --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///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: 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/") def training_job(job_id: str): from webapi import training_jobs return jsonify({"job": training_jobs.get(job_id)}) @governance_bp.patch("/model-versions////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////lineage") def model_version_lineage(domain: str, scenario: str, version: str): return jsonify(registry.lineage(domain, scenario, version)) @governance_bp.get("/model-versions////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////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////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////artifacts/") 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("/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), `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`.""" upload = request.files.get("file") form = request.form missing = [k for k in ("domain", "scenario", "url", "source", "build") if not form.get(k)] if upload is None or missing: return jsonify({"error": f"faltan campos: {(['file'] if upload is None else []) + missing}"}), 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"])) 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 if version: registry.get(domain, scenario, version) name = experiment.notebook_name(upload.filename or "notebook") 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/") def get_experiment(run_id: str): return jsonify(experiment.describe(run_id)) @governance_bp.get("/experiments//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//artifacts/") 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///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////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////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("/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, } )