fix governance reqs; allow for sandboxed jupyter notebooks for testing
This commit is contained in:
+106
-12
@@ -1,20 +1,32 @@
|
||||
"""Model governance (ML, MLD, EL and VAR requirements): model versions and
|
||||
their promotion, and the OCR extraction jobs with their manual review queue.
|
||||
their 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 runs
|
||||
elsewhere and registers its result through `POST /model-versions`, naming
|
||||
the indicator kit cohort build it was trained on (`cohorte_armado_id`).
|
||||
Notebooks (`models.pipelines.experiment`) run in the background on the build's
|
||||
file alone and are kept as MLflow runs.
|
||||
"""
|
||||
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.pipelines import experiment
|
||||
from persistance.governance import extraction_run_repository
|
||||
from persistance.repository import Repository
|
||||
from persistance.settings import settings
|
||||
|
||||
governance_bp = Blueprint("governance", __name__)
|
||||
|
||||
@@ -108,19 +120,101 @@ def retire_model_version(domain: str, scenario: str, version: str):
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/artifacts")
|
||||
def upload_artifact(domain: str, scenario: str, version: str):
|
||||
"""Multipart `file` and `kind` (ArtifactKind); logged to the version's MLflow run."""
|
||||
from core.governance.enums import ArtifactKind
|
||||
@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("/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")
|
||||
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
|
||||
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/<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 ---------------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user