Files
WebApi/webapi/models.py
T

210 lines
7.9 KiB
Python

"""Model governance: versions and their reports (MLflow), promotion, and the training and
scoring runs (Dagster). The API starts runs and reads the registry; it never trains."""
import mimetypes
import zipfile
from datetime import date
from typing import Annotated, Any
from dagster_graphql import DagsterGraphQLClient
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile
from fastapi.responses import Response
from pydantic import BaseModel, Field
from core import domains
from core.domains import Domain
from persistance import bundle, cluster, registry
from persistance.cluster import Execution, Reference
from webapi.runs import dagster, execution_config, submit
router = APIRouter(prefix="/models", tags=["models"])
class Version(BaseModel):
version: int
created: int # ms since the epoch
aliases: list[str]
metrics: dict[str, float]
params: dict[str, str]
reports: list[str]
@router.get("/{domain}")
def models(domain: Domain) -> list[str]:
prefix = f"{domain.value}."
return [n.removeprefix(prefix) for n in registry.names(prefix)]
@router.get(
"/{domain}/export",
responses={200: {"content": {"application/zip": {}}}},
response_class=Response,
)
def export_models(
domain: Domain,
names: Annotated[list[str] | None, Query()] = None,
versions: bundle.Selection = "champion",
) -> Response:
try:
exported = bundle.export(domain, names, versions)
except bundle.Empty as e:
raise HTTPException(409, detail=str(e)) from e
except bundle.BundleError as e:
raise HTTPException(422, detail=str(e)) from e
return Response(
exported.data,
media_type="application/zip",
headers={
"X-Bundle-Sha256": exported.sha256,
"X-Bundle-Versions": ",".join(f"{name}/{v}" for name, v in exported.versions),
"Content-Disposition": (
f'attachment; filename="{domain}-models-{exported.sha256[:12]}.zip"'
),
},
)
@router.post("/{domain}/import")
def import_models(
domain: Domain,
sha256: Annotated[str, Query(pattern=r"^[0-9a-fA-F]{64}$")],
file: UploadFile,
client: DagsterGraphQLClient = Depends(dagster),
) -> dict[str, str]:
computed, path = bundle.stage(file.file)
if computed != sha256.lower():
path.unlink(missing_ok=True)
raise HTTPException(422, detail=f"the file's SHA-256 is {computed}, not the one given")
if not zipfile.is_zipfile(path):
path.unlink(missing_ok=True)
raise HTTPException(422, detail="not a bundle")
if not bundle.trusted(computed):
path.unlink(missing_ok=True)
raise HTTPException(
403,
detail=f"bundle {computed} is not trusted on this server: "
f"the operator adds its SHA-256 to {bundle.trusted_file()}",
)
return submit(
client,
"import_bundle",
"import_bundle_files",
{"domain": domain.value, "sha256": computed},
domain.value,
)
@router.get("/{domain}/{name}/versions")
def versions(domain: Domain, name: str) -> list[Version]:
if not (found := registry.versions(f"{domain.value}.{name}")):
raise HTTPException(404, detail=f"no {domain.value} model {name}")
return [Version(**v) for v in found]
@router.get("/{domain}/{name}/versions/{version}/reports/{report}",
responses={200: {"content": {"application/json": {}, "application/octet-stream": {}},
"description": "the report as stored"}},
response_class=Response) # fmt: skip
def read_report(domain: Domain, name: str, version: int, report: str) -> Response:
"""A version's report: the generated ones as JSON (what the governance page draws), the
clinical validation as the file the clinical team uploaded."""
found = registry.report(f"{domain.value}.{name}", version, report)
if found is None:
raise HTTPException(404, detail=f"{domain.value}.{name} v{version} has no {report}")
filename, content = found
kind = mimetypes.guess_type(filename)[0] or "application/octet-stream"
return Response(content, media_type=kind,
headers={"Content-Disposition": f'inline; filename="{filename}"'}) # fmt: skip
@router.post("/{domain}/{name}/versions/{version}/reports/clinical_validation")
def add_clinical_validation(domain: Domain, name: str, version: int, file: UploadFile) -> dict:
"""The clinical team's validation of a version: the third report promotion needs."""
registry.add_report(f"{domain.value}.{name}", version, "clinical_validation",
file.filename or "report", file.file.read()) # fmt: skip
return {"reports": sorted(registry.reports(f"{domain.value}.{name}", version))}
@router.post("/{domain}/{name}/versions/{version}/promote")
def promote(domain: Domain, name: str, version: int) -> dict:
"""The version risk batches come from from now on; refused (409) without its three
reports: technical validation, interpretability and clinical validation."""
try:
registry.promote(f"{domain.value}.{name}", version)
except registry.MissingReports as e:
raise HTTPException(409, detail=str(e)) from e
return {"champion": version}
class TrainingForm(BaseModel):
as_of: date | None = Field(
None, title="Datos hasta", description="Fecha de corte de los datos (por omisión, hoy)"
)
execution: Execution | None = None
reference: Reference | None = None
class Training(TrainingForm):
models: list[str] = [] # which (default: all but the slow ones, like CaMa's recurrence)
class TrainingConfig(BaseModel):
domain: str
name: str
json_schema: dict[str, Any]
defaults: dict[str, Any]
@router.get("/{domain}/{name}/training-config")
def training_config(domain: Domain, name: str) -> TrainingConfig:
json_schema = TrainingForm.model_json_schema()
defaults = {"execution": {"mode": cluster.default_mode(), "scheduler": None}}
if "reference" in getattr(domains.part(domain), "TRAINING_OPTIONS", ()):
defaults["reference"] = {"line_hz": 50}
else:
del json_schema["properties"]["reference"]
del json_schema["$defs"]["Reference"]
return TrainingConfig(
domain=domain.value, name=name, json_schema=json_schema, defaults=defaults
)
class Analyze(BaseModel):
execution: Execution | None = None
@router.post("/{domain}/train")
def train(domain: Domain, request: Training,
client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip
"""Starts training a new version of every model of the domain; follow it at /runs."""
if request.reference is not None and "reference" not in getattr(
domains.part(domain), "TRAINING_OPTIONS", ()
):
raise HTTPException(422, f"{domain.value} models take no reference cohort")
config: dict = {"domain": domain.value, "execution": execution_config(request.execution)}
if request.as_of:
config["as_of"] = request.as_of.isoformat()
if request.models:
config["models"] = request.models
if request.reference is not None:
config["reference"] = request.reference.model_dump()
return submit(client, "train", "train_models", config, domain=domain.value)
@router.post("/{domain}/analyze")
def analyze(
domain: Domain,
request: Analyze = Analyze(), # noqa: B008
client: DagsterGraphQLClient = Depends(dagster),
) -> dict[str, str]:
"""Starts analysing the studies the domain's models read whole (TEA: its EEGs); follow
it at /runs."""
config = {"domain": domain.value, "execution": execution_config(request.execution)}
return submit(client, "analyze", "analyze_studies", config, domain=domain.value)
@router.post("/{domain}/score")
def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
"""Starts a risk batch from each model's champion; follow it at /runs."""
return submit(client, "score", "score_models", {"domain": domain.value}, domain=domain.value)