"""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, )