Files
WebApi/webapi/models.py
T
alberto c326f4901d C1a: code only, no comments, no Markdown
Remove 64 Python docstrings and 39 comments, and trim prose from three noqa pragmas. The submodule had zero tracked Markdown files.

Move published route descriptions into decorator arguments and the Correction schema description into ConfigDict. Drop internal docstrings, including the OAuth callback excluded from OpenAPI. Published route descriptions are unchanged in the before-and-after comparison of the nine application routers. The full application OpenAPI check requires fastapi-users, which is missing from the shared environment.
2026-12-01 16:55:32 -06:00

290 lines
10 KiB
Python

import mimetypes
import zipfile
from datetime import date
from typing import Annotated, Any, Literal
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.domains import Domain
from core.models import title
from persistance import bundle, cluster, registry
from persistance.cluster import Execution, TrainingSource
from webapi.runs import dagster, execution_config, submit
router = APIRouter(prefix="/models", tags=["models"])
class Version(BaseModel):
version: int
created: int
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,
description=(
"A version's report: the generated ones as JSON (what the "
'governance page draws), the\n'
'clinical validation as the file the clinical team uploaded.'
),
) # fmt: skip
def read_report(domain: Domain, name: str, version: int, report: str) -> Response:
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",
description=(
"The clinical team's validation of a version: the third report, "
"which promotion needs\n"
"unless the site left it out of PROMOTION_REPORTS."
),
)
def add_clinical_validation(domain: Domain, name: str, version: int, file: UploadFile) -> dict:
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",
description=(
"The version risk batches come from from now on; refused (409) "
"without the reports\n"
"the site requires (PROMOTION_REPORTS; default: technical "
"validation, interpretability\n"
"and clinical validation)."
),
)
def promote(domain: Domain, name: str, version: int) -> dict:
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
@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
source: TrainingSource | None = Field(None, title="Datos de entrenamiento")
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["source"] = {"kind": "site"}
else:
del json_schema["properties"]["source"]
for definition in ("TrainingSource", "SiteTrainingSource", "FolderTrainingSource"):
del json_schema["$defs"][definition]
return TrainingConfig(
domain=domain.value, name=name, json_schema=json_schema, defaults=defaults
)
class Analyze(BaseModel):
execution: Execution | None = None
@router.post(
"/{domain}/train",
description="Starts training a new version of every model of the domain; follow it at /runs.",
)
def train(domain: Domain, request: Training,
client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip
if request.source is not None and domain != Domain.TEA:
raise HTTPException(422, f"{domain.value} models take no training source")
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.source is not None:
config["source"] = request.source.model_dump()
return submit(client, "train", "train_models", config, domain=domain.value)
@router.post(
"/{domain}/analyze",
description=(
"Starts analysing the studies the domain's models read whole "
"(TEA: its EEGs); follow\n"
"it at /runs."
),
)
def analyze(
domain: Domain,
request: Analyze = Analyze(), # noqa: B008
client: DagsterGraphQLClient = Depends(dagster),
) -> dict[str, str]:
config = {"domain": domain.value, "execution": execution_config(request.execution)}
return submit(client, "analyze", "analyze_studies", config, domain=domain.value)
@router.post(
"/{domain}/score",
description="Starts a risk batch from each model's champion; follow it at /runs.",
)
def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
return submit(client, "score", "score_models", {"domain": domain.value}, domain=domain.value)