Files

356 lines
15 KiB
Python

"""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.
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.
"""
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 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.repository import Repository
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_or_404(domain: str | None, entity: str | None) -> tuple[Repository, OcrColumnSpec] | None:
job = OCR_JOBS.get((domain, entity))
return (job.repository, job.columns) if job else None
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, cohort_version_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"],
cohort_version_id=body.get("cohort_version_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.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."""
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>/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."""
from core.governance.enums import ArtifactKind
upload = request.files.get("file")
if upload is None:
return jsonify({"error": "falta file"}), 400
kinds = [k.value for k in ArtifactKind]
if request.form.get("kind") not in kinds:
return jsonify({"error": f"kind debe ser uno de {kinds}"}), 400
registry.add_artifact(domain, scenario, version, kind=ArtifactKind(request.form["kind"]), filename=upload.filename or "artefacto", data=upload.read())
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]})
@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 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
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.list(limit=2000) 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_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
row = repository.get(pk)
if row is None:
return jsonify({"error": "not found"}), 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_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
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": "not found"}), 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 vía UI de gobernanza — usuario revisó el PDF y escribió el valor directamente.",
estatus=EstatusExtraccion.COMPLETADA,
)
)
return jsonify(updated)
@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_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
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,
}
)