Merge P4.3 into P4.1 for one combined gate
This commit is contained in:
@@ -0,0 +1,109 @@
|
|||||||
|
import hashlib
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from test_bundles import NAME, _post, _register, _run, _trust
|
||||||
|
|
||||||
|
from models.tea.jobs import Baseline
|
||||||
|
from persistance import registry
|
||||||
|
|
||||||
|
VERSIONS = "/models/tea/curve_x/versions"
|
||||||
|
|
||||||
|
|
||||||
|
def test_version_lifecycle(api, platform, monkeypatch):
|
||||||
|
monkeypatch.setenv("MLFLOW_TRACKING_URI", platform.env["MLFLOW_TRACKING_URI"])
|
||||||
|
monkeypatch.chdir(platform.env["ISSSTELEON_DATA"])
|
||||||
|
for version in (1, 2):
|
||||||
|
assert registry.register(NAME, Baseline("x", {"value": {}}), {}, {}, {}) == version
|
||||||
|
path = f"{VERSIONS}/1"
|
||||||
|
response = api.get(f"{path}/checks")
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
assert response.json() == {
|
||||||
|
"version": 1,
|
||||||
|
"status": "candidate",
|
||||||
|
"checks": [{"report": report, "present": False} for report in registry.REPORTS],
|
||||||
|
"promotable": False,
|
||||||
|
}
|
||||||
|
assert api.get(f"{VERSIONS}/99/checks").status_code == 404
|
||||||
|
for version in (1, 2):
|
||||||
|
for report in registry.REPORTS:
|
||||||
|
registry.add_report(NAME, version, report, "report.json", b"{}")
|
||||||
|
assert api.get(f"{path}/checks").json()["promotable"]
|
||||||
|
assert api.post(f"{path}/promote").json() == {"champion": 1}
|
||||||
|
assert api.get(f"{path}/checks").json()["status"] == "champion"
|
||||||
|
refused = api.post(f"{path}/retire")
|
||||||
|
assert refused.status_code == 409
|
||||||
|
assert (
|
||||||
|
refused.json()["detail"] == "the champion cannot be retired; promote another version first"
|
||||||
|
)
|
||||||
|
assert api.post(f"{VERSIONS}/2/promote").json() == {"champion": 2}
|
||||||
|
assert api.get(f"{path}/checks").json()["status"] == "candidate"
|
||||||
|
assert api.post(f"{path}/retire").json() == {"status": "retired"}
|
||||||
|
assert api.post(f"{path}/promote").status_code == 409
|
||||||
|
checks = api.get(f"{path}/checks").json()
|
||||||
|
assert checks["status"] == "retired" and not checks["promotable"]
|
||||||
|
assert [v["status"] for v in api.get(VERSIONS).json()] == ["retired", "champion"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_imported_lineage(api, platform, fresh_api, fresh_platform, monkeypatch):
|
||||||
|
_register(platform, monkeypatch)
|
||||||
|
bundle_exported = api.get("/models/tea/export")
|
||||||
|
assert bundle_exported.status_code == 200, bundle_exported.text
|
||||||
|
sha = hashlib.sha256(bundle_exported.content).hexdigest()
|
||||||
|
_trust(fresh_platform, sha, monkeypatch)
|
||||||
|
run = _run(fresh_api, _post(fresh_api, bundle_exported.content, sha))
|
||||||
|
assert run["state"] == "succeeded", run
|
||||||
|
response = fresh_api.get(f"{VERSIONS}/1/lineage")
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
lineage = response.json()
|
||||||
|
assert lineage["version"] == 1 and lineage["created"] > 0 and lineage["run_id"]
|
||||||
|
assert lineage["params"] == {}
|
||||||
|
assert lineage["metrics"] == {"n_reference": 10}
|
||||||
|
assert all(not tag.startswith("mlflow.") for tag in lineage["tags"])
|
||||||
|
assert lineage["imported"] == {"sha256": sha, "source_name": NAME, "source_version": "1"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def platform(platform):
|
||||||
|
platform.env["TEA_REFERENCE_ROOT"] = str(Path(platform.env["ISSSTELEON_DATA"]) / "references")
|
||||||
|
return platform
|
||||||
|
|
||||||
|
|
||||||
|
def test_training_inputs(api, platform):
|
||||||
|
root = Path(platform.env["TEA_REFERENCE_ROOT"])
|
||||||
|
path = "/models/tea/curve_x/inputs"
|
||||||
|
assert api.get(path).json()["sets"] == []
|
||||||
|
assert api.get("/models/tea/ados2_association/inputs").status_code == 404
|
||||||
|
response = api.post(
|
||||||
|
f"{path}/cohort/files",
|
||||||
|
files=[("files", ("one.EDF", b"edf")), ("files", ("edades.csv", b"ages"))],
|
||||||
|
)
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
cohort = {"name": "cohort", "edf_files": 1, "has_ages": True, "bytes": 7}
|
||||||
|
assert response.json() == cohort
|
||||||
|
assert api.get(path).json()["sets"] == [cohort]
|
||||||
|
for filename in ("bad.txt", "../x"):
|
||||||
|
response = api.post(
|
||||||
|
f"{path}/cohort/files",
|
||||||
|
files=[("files", ("two.edf", b"edf")), ("files", (filename, b"bad"))],
|
||||||
|
)
|
||||||
|
assert response.status_code == 422, response.text
|
||||||
|
assert (
|
||||||
|
api.post(f"{path}/bad%20set/files", files={"files": ("one.edf", b"edf")}).status_code == 422
|
||||||
|
)
|
||||||
|
assert {p.name for p in (root / "cohort").iterdir()} == {"one.EDF", "edades.csv"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_preview(api, tmp_path, monkeypatch):
|
||||||
|
monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2] / "models" / "tests"))
|
||||||
|
from edf_files import small_edf
|
||||||
|
|
||||||
|
signal = small_edf(tmp_path / "small.edf")
|
||||||
|
run = _run(api, api.post("/tea/preview", files={"edf": ("small.edf", signal)}))
|
||||||
|
assert run["state"] == "succeeded", run
|
||||||
|
response = api.get(f"/tea/preview/{run['id']}")
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
preview = response.json()
|
||||||
|
assert preview["state"] == "succeeded"
|
||||||
|
outputs = api.get(f"/runs/{run['id']}", params={"outputs": "true"}).json()["outputs"]
|
||||||
|
assert preview["result"] == outputs["preview_study.result"]
|
||||||
@@ -415,11 +415,19 @@ def test_tea_from_the_hospital_to_indicators(api, scored_hospital, monkeypatch):
|
|||||||
expected = summary["body"]
|
expected = summary["body"]
|
||||||
assert (len(listed), sum(e["analysed"] for e in listed), sum(bool(e["valid"]) for e in listed)
|
assert (len(listed), sum(e["analysed"] for e in listed), sum(bool(e["valid"]) for e in listed)
|
||||||
) == (expected["eegs"], expected["analysed"], expected["valid"]) # fmt: skip
|
) == (expected["eegs"], expected["analysed"], expected["valid"]) # fmt: skip
|
||||||
|
actual_summary = ok(api.get("/tea/eegs/summary"))
|
||||||
|
assert actual_summary == {
|
||||||
|
key: count for key, count in expected.items() if key not in ("fhir_eegs", "fhir_metrics")
|
||||||
|
}
|
||||||
one = next(e for e in listed if e["valid"])
|
one = next(e for e in listed if e["valid"])
|
||||||
shown = ok(api.get(f"/tea/eegs/{one['id']}"))
|
shown = ok(api.get(f"/tea/eegs/{one['id']}"))
|
||||||
assert shown["valid"] and shown["metrics"] and all(m["value"] is not None
|
assert shown["valid"] and shown["metrics"] and all(m["value"] is not None
|
||||||
for m in shown["metrics"]) # fmt: skip
|
for m in shown["metrics"]) # fmt: skip
|
||||||
|
|
||||||
|
assert shown["checks"] and shown["regions"]
|
||||||
|
curve = ok(api.get("/models/tea/eeg-posterior-rhythm/versions/1/curve"))
|
||||||
|
assert [row["age_months"] for row in curve] == list(range(16, 37))
|
||||||
|
|
||||||
_preview_matches_the_analysis_and_leaves_bronze_unchanged(scored_hospital, monkeypatch)
|
_preview_matches_the_analysis_and_leaves_bronze_unchanged(scored_hospital, monkeypatch)
|
||||||
_reanalysis_by_id_in_local_mode_matches_sync(api, scored_hospital)
|
_reanalysis_by_id_in_local_mode_matches_sync(api, scored_hospital)
|
||||||
_cancel_during_analysis_leaves_bronze_and_gold_untouched(api, scored_hospital)
|
_cancel_during_analysis_leaves_bronze_and_gold_untouched(api, scored_hospital)
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
"""TEA's EEGs for model governance: every study with its analysis verdict, and one study's
|
"""TEA's EEGs for model governance: every study with its analysis verdict, and one study's
|
||||||
metrics with their age curves' scores."""
|
metrics with their age curves' scores."""
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
@@ -36,6 +38,8 @@ class Analysis(BaseModel):
|
|||||||
level: str | None
|
level: str | None
|
||||||
age_months: float | None
|
age_months: float | None
|
||||||
metrics: list[Metric]
|
metrics: list[Metric]
|
||||||
|
checks: list[dict[str, Any]]
|
||||||
|
regions: list[dict[str, Any]]
|
||||||
|
|
||||||
|
|
||||||
class AnalyzeRequest(BaseModel):
|
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")
|
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}")
|
@router.get("/{eeg_id}")
|
||||||
def study(eeg_id: str) -> Analysis:
|
def study(eeg_id: str) -> Analysis:
|
||||||
if (found := eeg.study(eeg_id)) is None:
|
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 starlette.exceptions import HTTPException
|
||||||
|
|
||||||
from core.domains import Domain
|
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
|
from webapi.auth import caller
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
@@ -18,6 +18,7 @@ app.include_router(runs.router)
|
|||||||
app.include_router(execution.router)
|
app.include_router(execution.router)
|
||||||
app.include_router(models.router)
|
app.include_router(models.router)
|
||||||
app.include_router(eeg.router)
|
app.include_router(eeg.router)
|
||||||
|
app.include_router(preview.router)
|
||||||
app.include_router(fhir.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 mimetypes
|
||||||
import zipfile
|
import zipfile
|
||||||
from datetime import date
|
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 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 fastapi.responses import Response
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field, WithJsonSchema
|
||||||
|
|
||||||
from core import domains
|
from core import domains
|
||||||
from core.domains import Domain
|
from core.domains import Domain, InputSpec
|
||||||
from persistance import bundle, cluster, registry
|
from persistance import bundle, cluster, inputs, registry
|
||||||
from persistance.cluster import Execution, Reference
|
from persistance.cluster import Execution, Reference
|
||||||
from webapi.runs import dagster, execution_config, submit
|
from webapi.runs import dagster, execution_config, submit
|
||||||
|
|
||||||
@@ -27,6 +28,7 @@ class Version(BaseModel):
|
|||||||
metrics: dict[str, float]
|
metrics: dict[str, float]
|
||||||
params: dict[str, str]
|
params: dict[str, str]
|
||||||
reports: list[str]
|
reports: list[str]
|
||||||
|
status: Literal["champion", "retired", "candidate"]
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{domain}")
|
@router.get("/{domain}")
|
||||||
@@ -131,11 +133,97 @@ def promote(domain: Domain, name: str, version: int) -> dict:
|
|||||||
reports: technical validation, interpretability and clinical validation."""
|
reports: technical validation, interpretability and clinical validation."""
|
||||||
try:
|
try:
|
||||||
registry.promote(f"{domain.value}.{name}", version)
|
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
|
raise HTTPException(409, detail=str(e)) from e
|
||||||
return {"champion": version}
|
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):
|
class TrainingForm(BaseModel):
|
||||||
as_of: date | None = Field(
|
as_of: date | None = Field(
|
||||||
None, title="Datos hasta", description="Fecha de corte de los datos (por omisión, hoy)"
|
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