add import audit trail, live indicator recompute, reportes endpoints; production hardening

This commit is contained in:
Roberto Treviño Cervantes
2026-10-30 11:19:30 -06:00
parent 168edb30f5
commit 2b2c290f58
74 changed files with 4095 additions and 1782 deletions
+27 -101
View File
@@ -1,29 +1,19 @@
"""Model governance (ML, MLD, EL and VAR requirements): model versions and
their promotion, cohorts, predictions, and the OCR extraction jobs with
their manual review queue.
their promotion, and the OCR extraction jobs with their manual review queue.
Training, versioning and artifact storage live in MLflow (`models.registry`
is a thin layer over it); training runs anywhere, registering the result
through `POST /model-versions`. Browsing/downloading a logged artifact goes
straight to the MLflow tracking server's own UI/API, not through here.
Versions and artifacts live in MLflow (`models.registry`); training runs
elsewhere and registers its result through `POST /model-versions`, naming
the indicator kit cohort build it was trained on (`cohorte_armado_id`).
"""
from dataclasses import asdict
from flask import Blueprint, Response, jsonify, request
from core.governance.enums import EstatusExtraccion
from core.governance.models import ExtractionRun
from core.ocr import OcrEstatus
from models.cohort import COHORT_BUILDERS, describe_builder
from models.ocr import OCR_JOBS, OcrColumnSpec, run_pending_extractions
from flask import Blueprint, Response, jsonify, request
from models.ocr import OCR_JOBS, OcrJob, run_pending_extractions
from models.registry import REPORT_TAGS, PromotionBlocked, registry
from persistance.governance import (
cohort_exclusion_count_repository,
cohort_exclusion_repository,
cohort_version_repository,
extraction_run_repository,
model_prediction_repository,
)
from persistance.governance import extraction_run_repository
from persistance.repository import Repository
governance_bp = Blueprint("governance", __name__)
@@ -39,9 +29,11 @@ def _bad_request(exc: ValueError):
return jsonify({"error": str(exc)}), 400
def _ocr_job_or_404(domain: str | None, entity: str | None) -> tuple[Repository, OcrColumnSpec] | None:
def _ocr_job(domain: str | None, entity: str | None) -> OcrJob:
job = OCR_JOBS.get((domain, entity))
return (job.repository, job.columns) if job else None
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:
@@ -61,7 +53,7 @@ def list_model_versions():
@governance_bp.post("/model-versions")
def register_model_version():
"""Registers a trained version: `{domain, scenario,
environment: DEV|PROD, cohort_version_id?, metrics?, hyperparameters?,
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 {}
@@ -72,7 +64,7 @@ def register_model_version():
domain=body["domain"],
scenario=body["scenario"],
environment=body["environment"],
cohort_version_id=body.get("cohort_version_id"),
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},
@@ -80,11 +72,6 @@ def register_model_version():
return jsonify(registry.describe(body["domain"], body["scenario"], version)), 201
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>")
def get_model_version(domain: str, scenario: str, version: str):
return jsonify(registry.describe(domain, scenario, version))
@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."""
@@ -121,19 +108,9 @@ def retire_model_version(domain: str, scenario: str, version: str):
return jsonify(registry.describe(domain, scenario, version))
@governance_bp.get("/model-versions/<domain>/<scenario>/compare")
def compare_model_versions(domain: str, scenario: str):
a, b = request.args.get("a"), request.args.get("b")
if not a or not b:
return jsonify({"error": "a y b deben ser versiones de MLflow"}), 400
return jsonify(registry.compare(domain, scenario, a, b))
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/artifacts")
def upload_artifact(domain: str, scenario: str, version: str):
"""Multipart: `file`, `kind` (ArtifactKind) — logs it to the version's
MLflow run. Browse/download logged artifacts via the MLflow tracking
server directly, not through here."""
"""Multipart `file` and `kind` (ArtifactKind); logged to the version's MLflow run."""
from core.governance.enums import ArtifactKind
upload = request.files.get("file")
@@ -146,48 +123,7 @@ def upload_artifact(domain: str, scenario: str, version: str):
return jsonify(registry.describe(domain, scenario, version)), 201
# -- cohorts ---------------------------------------------------------------------------
@governance_bp.get("/cohort-scenarios")
def list_cohort_scenarios():
"""Scenarios with a registered `CohortBuilder` (see models.cohort.register_cohort_builder)."""
return jsonify({"scenarios": [describe_builder(cls) for cls in COHORT_BUILDERS.values()]})
@governance_bp.post("/cohort-versions")
def build_cohort_version():
"""Builds and freezes a new cohort version: `{domain, scenario, description?}`."""
body = request.get_json(silent=True) or {}
builder = COHORT_BUILDERS.get((body.get("domain"), body.get("scenario")))
if builder is None:
return jsonify({"error": f"no hay un CohortBuilder registrado para ({body.get('domain')!r}, {body.get('scenario')!r})"}), 404
return jsonify(builder().build(description=body.get("description")).model_dump()), 201
@governance_bp.get("/cohort-versions")
def list_cohort_versions():
filters = {k: v for k, v in request.args.items() if k in {"domain", "scenario"}}
versions = cohort_version_repository.list(limit=200, **filters)
return jsonify({"cohort_versions": [v.model_dump() for v in versions]})
@governance_bp.get("/cohort-versions/<int:cohort_version_id>/exclusions")
def get_cohort_exclusions(cohort_version_id: int):
"""EL-05/EL-07: per-criterion counts and the per-episode log behind them."""
counts = cohort_exclusion_count_repository.list(limit=1000, cohort_version_id=cohort_version_id)
detail = cohort_exclusion_repository.list(limit=1000, cohort_version_id=cohort_version_id)
return jsonify({"counts": [c.model_dump() for c in counts], "detail": [d.model_dump() for d in detail]})
# -- predictions and OCR -------------------------------------------------------------------
@governance_bp.get("/predictions")
def list_predictions():
filters = {k: v for k, v in request.args.items() if k in {"domain", "pac_id_hospital", "mlflow_run_id", "modelo_nombre", "modelo_version"}}
predictions = model_prediction_repository.list(limit=200, **filters)
return jsonify({"predictions": [p.model_dump() for p in predictions]})
# -- OCR ---------------------------------------------------------------------------------
@governance_bp.get("/ocr/jobs")
@@ -209,13 +145,9 @@ def list_ocr_jobs():
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 because `Repository.list` only supports
equality filters; a review queue is small."""
job = _ocr_job_or_404(domain, entity)
if job is None:
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
repository, spec = job
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))
@@ -238,7 +170,7 @@ def list_ocr_rows(domain: str, entity: str):
return estatus == OcrEstatus.REALIZADO.value
return True
candidates = [row for row in repository.list(limit=2000) if matches(row)]
candidates = [row for row in repository.iter_all() if matches(row)]
page = candidates[offset : offset + limit]
rows = [
{
@@ -259,13 +191,11 @@ def list_ocr_rows(domain: str, entity: str):
@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_or_404(domain, entity)
if job is None:
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
repository, spec = job
job = _ocr_job(domain, entity)
repository, spec = job.repository, job.columns
row = repository.get(pk)
if row is None:
return jsonify({"error": "not found"}), 404
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
@@ -277,10 +207,8 @@ 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_or_404(domain, entity)
if job is None:
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
repository, spec = job
job = _ocr_job(domain, entity)
repository, spec = job.repository, job.columns
body = request.get_json(silent=True) or {}
values = body.get("values")
@@ -294,7 +222,7 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
with repository.open_session() as session:
tracked = session.get(repository.model, pk)
if tracked is None:
return jsonify({"error": "not found"}), 404
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)
@@ -313,7 +241,7 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
entity=entity,
entity_pk=str(pk),
column_extracted=",".join(sorted(values)),
transform_description="Corrección manual vía UI de gobernanza — usuario revisó el PDF y escribió el valor directamente.",
transform_description="Corrección manual",
estatus=EstatusExtraccion.COMPLETADA,
)
)
@@ -327,9 +255,7 @@ def run_ocr():
body = request.get_json(silent=True) or {}
domain = body.get("domain")
entity = body.get("entity")
job = OCR_JOBS.get((domain, entity))
if job is None:
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 400
job = _ocr_job(domain, entity)
try:
summary = run_pending_extractions(