Add governance and TEA preview REST endpoints
Use the models router for curves and training inputs, the EEG router for summary, and a separate preview router. Keep the preview result typed with the existing persistence model and declare multipart binary schemas for generated Blob parameters.
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
"""TEA's EEGs for model governance: every study with its analysis verdict, and one study's
|
||||
metrics with their age curves' scores."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -36,6 +38,8 @@ class Analysis(BaseModel):
|
||||
level: str | None
|
||||
age_months: float | None
|
||||
metrics: list[Metric]
|
||||
checks: list[dict[str, Any]]
|
||||
regions: list[dict[str, Any]]
|
||||
|
||||
|
||||
class AnalyzeRequest(BaseModel):
|
||||
@@ -55,6 +59,11 @@ def analyze_eegs(request: AnalyzeRequest, client=Depends(dagster)) -> dict[str,
|
||||
return submit(client, "tea_eeg", "tea_analyze_studies", config, domain="tea")
|
||||
|
||||
|
||||
@router.get("/summary")
|
||||
def eeg_summary() -> dict[str, int]:
|
||||
return eeg.summary()
|
||||
|
||||
|
||||
@router.get("/{eeg_id}")
|
||||
def study(eeg_id: str) -> Analysis:
|
||||
if (found := eeg.study(eeg_id)) is None:
|
||||
|
||||
+2
-1
@@ -3,7 +3,7 @@ from fastapi.exception_handlers import http_exception_handler
|
||||
from starlette.exceptions import HTTPException
|
||||
|
||||
from core.domains import Domain
|
||||
from webapi import eeg, execution, fhir, ingest, models, review, runs
|
||||
from webapi import eeg, execution, fhir, ingest, models, preview, review, runs
|
||||
from webapi.auth import caller
|
||||
|
||||
app = FastAPI(
|
||||
@@ -18,6 +18,7 @@ app.include_router(runs.router)
|
||||
app.include_router(execution.router)
|
||||
app.include_router(models.router)
|
||||
app.include_router(eeg.router)
|
||||
app.include_router(preview.router)
|
||||
app.include_router(fhir.router)
|
||||
|
||||
|
||||
|
||||
+94
-6
@@ -4,16 +4,17 @@ scoring runs (Dagster). The API starts runs and reads the registry; it never tra
|
||||
import mimetypes
|
||||
import zipfile
|
||||
from datetime import date
|
||||
from typing import Annotated, Any
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, WithJsonSchema
|
||||
|
||||
from core import domains
|
||||
from core.domains import Domain
|
||||
from persistance import bundle, cluster, registry
|
||||
from core.domains import Domain, InputSpec
|
||||
from persistance import bundle, cluster, inputs, registry
|
||||
from persistance.cluster import Execution, Reference
|
||||
from webapi.runs import dagster, execution_config, submit
|
||||
|
||||
@@ -27,6 +28,7 @@ class Version(BaseModel):
|
||||
metrics: dict[str, float]
|
||||
params: dict[str, str]
|
||||
reports: list[str]
|
||||
status: Literal["champion", "retired", "candidate"]
|
||||
|
||||
|
||||
@router.get("/{domain}")
|
||||
@@ -131,11 +133,97 @@ def promote(domain: Domain, name: str, version: int) -> dict:
|
||||
reports: technical validation, interpretability and clinical validation."""
|
||||
try:
|
||||
registry.promote(f"{domain.value}.{name}", version)
|
||||
except registry.MissingReports as e:
|
||||
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 = getattr(domains.part(domain), "TRAINING_INPUTS", {})
|
||||
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)"
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Upload temporary study files and follow their TEA preview run."""
|
||||
|
||||
from datetime import date
|
||||
from typing import Annotated
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, UploadFile
|
||||
from pydantic import BaseModel, WithJsonSchema
|
||||
|
||||
from persistance import previews
|
||||
from webapi import runs
|
||||
|
||||
router = APIRouter(prefix="/tea/preview", tags=["preview"])
|
||||
_MAX_FILE_BYTES = 200 * 1024 * 1024
|
||||
_BinaryUpload = Annotated[UploadFile, WithJsonSchema({"type": "string", "format": "binary"})]
|
||||
|
||||
|
||||
class PreviewStatus(BaseModel):
|
||||
state: runs.State
|
||||
result: previews.PreviewResult | None
|
||||
|
||||
|
||||
@router.post("")
|
||||
def start_preview(
|
||||
edf: _BinaryUpload,
|
||||
ados2: _BinaryUpload | None = None,
|
||||
birth_date: Annotated[date | None, Form()] = None,
|
||||
pipeline: Annotated[str, Form()] = "tea",
|
||||
client: DagsterGraphQLClient = Depends(runs.dagster),
|
||||
) -> dict[str, str]:
|
||||
for file in (edf, ados2):
|
||||
if file is not None and file.size is not None and file.size > _MAX_FILE_BYTES:
|
||||
raise HTTPException(413, detail="preview files may be at most 200 MiB each")
|
||||
config = {
|
||||
"edf": previews.put(edf.file.read()),
|
||||
"ados2": previews.put(ados2.file.read()) if ados2 is not None else None,
|
||||
"birth_date": birth_date.isoformat() if birth_date else None,
|
||||
"pipeline": pipeline,
|
||||
}
|
||||
return runs.submit(client, "tea_preview", "preview_study", config, domain="tea")
|
||||
|
||||
|
||||
@router.get("/{run_id}")
|
||||
def preview_status(run_id: str) -> PreviewStatus:
|
||||
run = runs.run_status(run_id, outputs=True)
|
||||
if run.job != "tea_preview":
|
||||
raise HTTPException(404, detail=f"no TEA preview run {run_id}")
|
||||
raw = (run.outputs or {}).get("preview_study.result") if run.state == "succeeded" else None
|
||||
return PreviewStatus(
|
||||
state=run.state,
|
||||
result=previews.PreviewResult.model_validate(raw) if raw is not None else None,
|
||||
)
|
||||
Reference in New Issue
Block a user