Files
WebApi/webapi/models.py
T
alberto f26d32a010 Merge origin/rebuild into parity/T1-merge (WebApi)
- main.py: both routers sets (execution, preview from tea/parity; sources, users from
  rebuild).
- runs.py: tea/parity's cancel, history and execution config; rebuild's /terminate is the
  same action and is not kept twice.
- eeg.py: tea/parity's (the record reads per-child FHIR resources, not rebuild's EEG
  detail with zones and relation).
- fhir.py: tea/parity's patient rows with TEA filters, plus rebuild's name/identifier
  search applied to whatever rows the request selects.
- models.py: tea/parity's endpoints; /models/{domain} returns rebuild's name + title.
- tests: P7 deletions kept (test_cacu, test_cama, test_conectar, test_synthea*, test_tea);
  test_webapp keeps tea/parity's runner, now with the first administrator (sign-in).
2026-11-30 23:56:11 -06:00

304 lines
11 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 pathlib import Path
from typing import Annotated, Any, Literal
from dagster_graphql import DagsterGraphQLClient
from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile
from fastapi.responses import Response
from pydantic import BaseModel, Field, WithJsonSchema
from core import tea
from core.domains import Domain, InputSpec
from core.models import title
from persistance import bundle, cluster, inputs, 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]
status: Literal["champion", "retired", "candidate"]
class Model(BaseModel):
name: str
title: str
@router.get("/{domain}")
def models(domain: Domain) -> list[Model]:
prefix = f"{domain.value}."
return [Model(name=n.removeprefix(prefix), title=title(n)) 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, which promotion needs
unless the site left it out of PROMOTION_REPORTS."""
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 the reports
the site requires (PROMOTION_REPORTS; default: technical validation, interpretability
and clinical validation)."""
try:
registry.promote(f"{domain.value}.{name}", version)
except registry.UnknownVersion as e:
raise HTTPException(404, detail=str(e)) from e
except ValueError as e:
raise HTTPException(409, detail=str(e)) from e
return {"champion": version}
@router.get("/{domain}/{name}/versions/{version}/checks")
def version_checks(domain: Domain, name: str, version: int) -> dict:
registered = f"{domain.value}.{name}"
try:
status = registry.status(registered, version)
except registry.UnknownVersion as e:
raise HTTPException(404, detail=str(e)) from e
checks = registry.checks(registered, version)
return {
"version": version,
"status": status,
"checks": checks,
"promotable": status != "retired" and all(check["present"] for check in checks),
}
@router.post("/{domain}/{name}/versions/{version}/retire")
def retire(domain: Domain, name: str, version: int) -> dict[str, str]:
try:
registry.retire(f"{domain.value}.{name}", version)
except registry.UnknownVersion as e:
raise HTTPException(404, detail=str(e)) from e
except ValueError as e:
raise HTTPException(409, detail=str(e)) from e
return {"status": "retired"}
@router.get("/{domain}/{name}/versions/{version}/lineage")
def lineage(domain: Domain, name: str, version: int) -> dict:
try:
return registry.lineage(f"{domain.value}.{name}", version)
except registry.UnknownVersion as e:
raise HTTPException(404, detail=str(e)) from e
def _training_inputs(domain: Domain, name: str) -> tuple[InputSpec, Path]:
declared = tea.TRAINING_INPUTS if domain == Domain.TEA else {}
spec = declared.get(name, declared.get("*"))
if spec is None:
raise HTTPException(404, detail=f"no training inputs for {domain.value}.{name}")
try:
return spec, inputs.root(spec)
except LookupError as e:
raise HTTPException(503, detail=str(e)) from e
@router.get("/{domain}/{name}/inputs")
def training_inputs(domain: Domain, name: str) -> dict:
spec, root = _training_inputs(domain, name)
return {"description": spec.description, "allowed": spec.allowed, "sets": inputs.sets(root)}
@router.post("/{domain}/{name}/inputs/{set}/files")
def upload_training_inputs(
domain: Domain,
name: str,
set: str,
files: Annotated[
list[Annotated[UploadFile, WithJsonSchema({"type": "string", "format": "binary"})]],
File(min_length=1),
],
) -> dict:
spec, root = _training_inputs(domain, name)
try:
return inputs.upload(root, set, spec.allowed, [(f.filename or "", f.file) for f in files])
except ValueError as e:
raise HTTPException(422, detail=str(e)) from e
@router.get("/{domain}/{name}/versions/{version}/curve")
def curve(domain: Domain, name: str, version: int, feature: str = "value") -> list[dict]:
if domain != Domain.TEA:
raise HTTPException(404, detail="no age curve for this model")
try:
model = registry.load(f"{domain.value}.{name}", version).unwrap_python_model()
if not hasattr(model, "curve"):
raise HTTPException(404, detail="no age curve for this model")
return model.curve(feature, range(16, 37))
except KeyError as e:
raise HTTPException(404, detail=f"no curve feature {feature!r}") from e
except LookupError as e:
raise HTTPException(404, detail=str(e)) from e
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] = []
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 domain == Domain.TEA:
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 domain != Domain.TEA:
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)