Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 55da6cd28b | |||
| 9b631928ad | |||
| c326f4901d | |||
| 37c456c5ef | |||
| edd3093d5d | |||
| 323240dd30 | |||
| 326502f90c | |||
| 2c5568f5d1 | |||
| 87a0893ee4 | |||
| 82f7a18a9f | |||
| b4db5f9b2c | |||
| 06f1cadc4b | |||
| b61a4863d1 |
@@ -1,37 +0,0 @@
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException, UploadFile
|
||||
|
||||
from core.domains import Domain
|
||||
from webapi.models import training_inputs, upload_training_inputs
|
||||
|
||||
|
||||
def test_training_inputs(tmp_path, monkeypatch):
|
||||
root = tmp_path / "reference"
|
||||
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(root))
|
||||
assert training_inputs(Domain.TEA, "curve_x")["sets"] == []
|
||||
with pytest.raises(HTTPException) as undefined:
|
||||
training_inputs(Domain.TEA, "ados2_association")
|
||||
assert undefined.value.status_code == 404
|
||||
|
||||
def upload(name, files):
|
||||
return upload_training_inputs(
|
||||
Domain.TEA,
|
||||
"curve_x",
|
||||
name,
|
||||
[UploadFile(BytesIO(content), filename=filename) for filename, content in files],
|
||||
)
|
||||
|
||||
expected = {"name": "cohort", "edf_files": 1, "has_ages": True, "bytes": 7}
|
||||
assert upload("cohort", [("one.EDF", b"edf"), ("edades.csv", b"ages")]) == expected
|
||||
assert training_inputs(Domain.TEA, "curve_x")["sets"] == [expected]
|
||||
|
||||
for invalid in ("bad.txt", "../x"):
|
||||
with pytest.raises(HTTPException) as rejected:
|
||||
upload("cohort", [("two.edf", b"edf"), (invalid, b"bad")])
|
||||
assert rejected.value.status_code == 422
|
||||
with pytest.raises(HTTPException) as rejected:
|
||||
upload("bad set", [("one.edf", b"edf")])
|
||||
assert rejected.value.status_code == 422
|
||||
assert {path.name for path in (root / "cohort").iterdir()} == {"one.EDF", "edades.csv"}
|
||||
@@ -1,6 +1,3 @@
|
||||
"""The Conectar dialog's API: an operator who knows nothing of dlt picks a kind of source,
|
||||
answers its questions, and "Probar conexión" says in plain words what it found."""
|
||||
|
||||
import sqlite3
|
||||
|
||||
import pytest
|
||||
@@ -87,13 +84,13 @@ def test_a_sign_in_button_without_an_app_registration_says_who_must_register_one
|
||||
def test_signing_in_hands_the_account_to_the_dialog(client, monkeypatch, tmp_path):
|
||||
from authlib.integrations.httpx_client import OAuth2Client, oauth2_client
|
||||
|
||||
httpx = oauth2_client.httpx2 # the HTTP library this authlib is built on
|
||||
httpx = oauth2_client.httpx2
|
||||
|
||||
monkeypatch.setenv("MICROSOFT_CLIENT_ID", "app")
|
||||
monkeypatch.setenv("MICROSOFT_CLIENT_SECRET", "app-secret")
|
||||
exchanged = {}
|
||||
|
||||
def provider(request: httpx.Request) -> httpx.Response: # the token endpoint
|
||||
def provider(request: httpx.Request) -> httpx.Response:
|
||||
exchanged["body"] = request.content.decode()
|
||||
return httpx.Response(200, json={"access_token": "at", "refresh_token": "rt",
|
||||
"token_type": "Bearer", "expires_in": 3600}) # fmt: skip
|
||||
@@ -104,7 +101,7 @@ def test_signing_in_hands_the_account_to_the_dialog(client, monkeypatch, tmp_pat
|
||||
transport=httpx.MockTransport(provider)) # fmt: skip
|
||||
|
||||
monkeypatch.setattr(sources, "_client", client_for)
|
||||
monkeypatch.setattr(sources, "PENDING", tmp_path / "pending") # any worker's callback
|
||||
monkeypatch.setattr(sources, "PENDING", tmp_path / "pending")
|
||||
monkeypatch.setattr(sources, "account", lambda p, token, env: {
|
||||
"user": "ana@hospital.mx", "drive_id": "d1",
|
||||
"oauth2_client_params": {"client_id": env["client_id"], "token": token}}) # fmt: skip
|
||||
@@ -119,7 +116,7 @@ def test_signing_in_hands_the_account_to_the_dialog(client, monkeypatch, tmp_pat
|
||||
assert "code_verifier=" in exchanged["body"] and "code=c0de" in exchanged["body"]
|
||||
again = client.get("/ingest/sources/oauth/microsoft/callback",
|
||||
params={"state": start["state"], "code": "c0de"}) # fmt: skip
|
||||
assert again.status_code == 400 # a sign-in is used once
|
||||
assert again.status_code == 400
|
||||
|
||||
|
||||
def test_a_saved_account_shows_who_but_never_its_tokens():
|
||||
|
||||
@@ -3,6 +3,8 @@ from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
|
||||
from core.domains import Domain
|
||||
from persistance.cluster import FolderTrainingSource
|
||||
from webapi import models
|
||||
from webapi.models import Training, train, training_config
|
||||
|
||||
|
||||
@@ -18,19 +20,41 @@ def test_tea_training_config_schema():
|
||||
assert schema["title"] == "TrainingForm"
|
||||
assert set(schema["properties"]) == {"as_of", "execution", "source"}
|
||||
assert schema["properties"]["as_of"]["title"] == "Datos hasta"
|
||||
assert set(schema["$defs"]) == {"Execution", "TrainingSource"}
|
||||
assert set(schema["$defs"]) == {
|
||||
"Execution",
|
||||
"TrainingSource",
|
||||
"SiteTrainingSource",
|
||||
"FolderTrainingSource",
|
||||
}
|
||||
execution = schema["$defs"]["Execution"]
|
||||
assert execution["title"] == "Ejecución"
|
||||
assert execution["properties"]["mode"]["title"] == "Modo"
|
||||
assert execution["properties"]["scheduler"]["title"] == "Planificador Dask"
|
||||
source = schema["$defs"]["TrainingSource"]
|
||||
assert source["title"] == "Datos de entrenamiento"
|
||||
assert source["properties"]["kind"]["enum"] == ["site", "folder"]
|
||||
assert source["properties"]["folder"]["title"] == "Carpeta"
|
||||
assert source["properties"]["line_hz"]["enum"] == [50, 60]
|
||||
assert source["discriminator"] == {
|
||||
"propertyName": "kind",
|
||||
"mapping": {
|
||||
"site": "#/$defs/SiteTrainingSource",
|
||||
"folder": "#/$defs/FolderTrainingSource",
|
||||
},
|
||||
}
|
||||
assert source["oneOf"] == [
|
||||
{"$ref": "#/$defs/SiteTrainingSource"},
|
||||
{"$ref": "#/$defs/FolderTrainingSource"},
|
||||
]
|
||||
site = schema["$defs"]["SiteTrainingSource"]
|
||||
assert set(site["properties"]) == {"kind"}
|
||||
folder = schema["$defs"]["FolderTrainingSource"]
|
||||
assert folder["properties"]["folder"]["title"] == "Carpeta"
|
||||
assert folder["properties"]["line_hz"]["enum"] == [50, 60]
|
||||
assert (site["title"], folder["title"]) == (
|
||||
"Niños del sitio sin el diagnóstico",
|
||||
"Carpeta de EDF con edades",
|
||||
)
|
||||
assert schema["properties"]["source"]["title"] == "Datos de entrenamiento"
|
||||
assert config["defaults"] == {
|
||||
"execution": {"mode": "sync", "scheduler": None},
|
||||
"source": {"kind": "site", "line_hz": 50},
|
||||
"source": {"kind": "site"},
|
||||
}
|
||||
|
||||
|
||||
@@ -54,8 +78,33 @@ def test_train_validates_the_training_source():
|
||||
{"kind": "folder"},
|
||||
{"kind": "folder", "folder": "../x"},
|
||||
{"kind": "folder", "folder": "hel", "line_hz": 55},
|
||||
{"kind": "site", "folder": "hel"},
|
||||
{"kind": "site", "line_hz": 60},
|
||||
{"kind": "other"},
|
||||
):
|
||||
with pytest.raises(ValidationError):
|
||||
Training(source=source)
|
||||
assert Training(source={"kind": "folder", "folder": "hel"}).source.line_hz == 50
|
||||
assert Training(source={"kind": "site"}).model_dump()["source"] == {"kind": "site"}
|
||||
folder = Training(source={"kind": "folder", "folder": "hel"}).source
|
||||
assert isinstance(folder, FolderTrainingSource)
|
||||
assert folder.line_hz == 50
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"source",
|
||||
[
|
||||
{"kind": "site"},
|
||||
{"kind": "folder", "folder": "hel", "line_hz": 60},
|
||||
],
|
||||
)
|
||||
def test_train_submits_the_selected_source(monkeypatch, source):
|
||||
client = object()
|
||||
|
||||
def submit(actual_client, job, op, config, *, domain):
|
||||
assert actual_client is client
|
||||
assert (job, op, domain) == ("train", "train_models", "tea")
|
||||
assert config["source"] == source
|
||||
return {"run_id": "training"}
|
||||
|
||||
monkeypatch.setattr(models, "submit", submit)
|
||||
assert train(Domain.TEA, Training(source=source), client) == {"run_id": "training"}
|
||||
|
||||
+3
-7
@@ -1,6 +1,3 @@
|
||||
"""Sign-in for the web app: an administrator from the environment, users who see some
|
||||
domains, a session cookie, and an API that answers everyone as before."""
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
@@ -32,11 +29,10 @@ def test_the_first_administrator_signs_in_and_adds_a_team(client):
|
||||
assert login(client, "cacu@isssteleon.mx", "equipo-cacu").status_code == 204
|
||||
assert client.get("/users/me").json()["domains"] == ["cacu"]
|
||||
other = {"email": "x@isssteleon.mx", "password": "otra-clave"}
|
||||
assert client.post("/users/register", json=other).status_code == 403 # not an admin
|
||||
assert client.post("/users/register", json=other).status_code == 403
|
||||
|
||||
|
||||
def test_the_api_answers_without_a_session(client):
|
||||
# routes that read no platform data (the in-process app's database is the default one)
|
||||
for path in ("/health", "/domains", "/ingest/schema", "/ingest/sources/types"):
|
||||
assert client.get(path).status_code == 200, path
|
||||
|
||||
@@ -44,7 +40,7 @@ def test_the_api_answers_without_a_session(client):
|
||||
def test_a_restart_keeps_the_administrator_once_and_the_session_secret(client, own_platform):
|
||||
assert login(client, "admin@isssteleon.mx", "una-clave-larga").status_code == 204
|
||||
secret = (own_platform / "auth_secret").read_text()
|
||||
with TestClient(app): # the app starts again on the same data
|
||||
with TestClient(app):
|
||||
pass
|
||||
assert (own_platform / "auth_secret").read_text() == secret
|
||||
assert client.get("/users/me").status_code == 200 # the session still holds
|
||||
assert client.get("/users/me").status_code == 200
|
||||
|
||||
@@ -11,6 +11,7 @@ from pathlib import Path
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from models.tea.jobs import ASSOCIATION, MODELS
|
||||
from synthetic import tea
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
@@ -57,6 +58,45 @@ def _sensor_run(api: httpx.Client, seconds: int = 300) -> str:
|
||||
return runs[0]["id"]
|
||||
|
||||
|
||||
def _train_tea(api: httpx.Client) -> None:
|
||||
_wait(api, _ok(api.post("/models/tea/analyze", json={}))["run_id"])
|
||||
for names in (list(MODELS), [ASSOCIATION]):
|
||||
training = _ok(
|
||||
api.post(
|
||||
"/models/tea/train",
|
||||
json={
|
||||
"models": names,
|
||||
"source": {"kind": "site"},
|
||||
},
|
||||
)
|
||||
)
|
||||
_wait(api, training["run_id"])
|
||||
for name in names:
|
||||
versions = f"/models/tea/{name}/versions"
|
||||
version = _ok(api.get(versions))[-1]["version"]
|
||||
path = f"{versions}/{version}"
|
||||
_ok(
|
||||
api.post(
|
||||
f"{path}/reports/clinical_validation",
|
||||
files={
|
||||
"file": ("synthetic-validation.txt", b"Synthetic hospital test fixture")
|
||||
},
|
||||
)
|
||||
)
|
||||
_ok(api.post(f"{path}/promote"))
|
||||
assert any(
|
||||
v["version"] == version and v["status"] == "champion"
|
||||
for v in _ok(api.get(versions))
|
||||
), name
|
||||
_wait(api, _ok(api.post("/models/tea/score"))["run_id"])
|
||||
risks = _ok(
|
||||
api.get(
|
||||
"/tea/fhir/Patient", params={"_revinclude": "RiskAssessment:subject", "_count": 200}
|
||||
)
|
||||
)
|
||||
assert any(e["resource"]["resourceType"] == "RiskAssessment" for e in risks["entry"])
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _platform(data: Path):
|
||||
from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore
|
||||
@@ -137,6 +177,7 @@ def test_the_tea_pages_load_from_the_synthetic_hospital(tmp_path):
|
||||
_ok(api.put("/ingest/pipelines/tea", json=pipeline))
|
||||
_wait(api, _ok(api.post("/ingest/pipelines/tea/runs", json={}))["run_id"])
|
||||
_wait(api, _sensor_run(api))
|
||||
_train_tea(api)
|
||||
subprocess.run(
|
||||
["npx", "playwright", "test"], cwd=ROOT / "WebApp", check=True,
|
||||
env={**os.environ, **files, "API_URL": str(api.base_url).rstrip("/")},
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""The one dependency every route goes through. Open for now; this is where auth will go."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
|
||||
+1
-4
@@ -1,6 +1,3 @@
|
||||
"""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
|
||||
@@ -15,7 +12,7 @@ router = APIRouter(prefix="/tea/eegs", tags=["eeg"])
|
||||
|
||||
|
||||
class Study(BaseModel):
|
||||
id: str # person and study date
|
||||
id: str
|
||||
person_id: str
|
||||
study_date: str
|
||||
lab_record_id: str | None
|
||||
|
||||
+80
-53
@@ -1,8 +1,3 @@
|
||||
"""The FHIR R4B API, one base per domain (`/{domain}/fhir`): read, the searches the WebApp
|
||||
uses, paging, and a CapabilityStatement built from these routes themselves. Resources are
|
||||
built by Core's mappers from the rows Persistance reads; nothing is computed here beyond
|
||||
counting a few thousand rows (measures) and ordering the follow-up list."""
|
||||
|
||||
import unicodedata
|
||||
from collections import defaultdict
|
||||
from datetime import date, datetime
|
||||
@@ -52,14 +47,12 @@ def outcome(status: int, text: str) -> Response:
|
||||
|
||||
|
||||
def _clinical(domain: Domain):
|
||||
"""The domain's follow-up module: a domain serves clinical resources once it has one."""
|
||||
if (found := part(domain, "follow_up")) is None:
|
||||
raise HTTPException(404, f"no clinical resources for {domain.value} yet")
|
||||
return found
|
||||
|
||||
|
||||
def _cutoff(domain: Domain, asked: date | None) -> date:
|
||||
"""The day asked for, or by default the last day with data in the domain (up to today)."""
|
||||
if asked is not None:
|
||||
return asked
|
||||
return reads.last_data_day(domain.value) or date.today()
|
||||
@@ -74,8 +67,6 @@ def _page(count: int | None, offset: int) -> tuple[int, int]:
|
||||
|
||||
def bundle(request: Request, matches: list[Resource], total: int, count: int, offset: int,
|
||||
included: list[Resource] = (), applied: dict | None = None) -> Response: # fmt: skip
|
||||
"""A searchset page of `matches`, with links to its neighbours. The links carry the
|
||||
parameters as applied (`applied`: defaults the server chose)."""
|
||||
base = str(request.base_url).rstrip("/") + request.url.path.rsplit("/", 1)[0]
|
||||
|
||||
def link(relation: str, at: int) -> dict:
|
||||
@@ -100,9 +91,6 @@ def _sliced(found: list, count: int, offset: int) -> list:
|
||||
return found[offset:offset + count] # fmt: skip
|
||||
|
||||
|
||||
# --- Patient ---------------------------------------------------------------------------------
|
||||
|
||||
|
||||
_WINDOW = Query(
|
||||
None,
|
||||
alias="follow-up-window",
|
||||
@@ -169,7 +157,6 @@ def read_patient(domain: Domain, id: str) -> Response:
|
||||
|
||||
|
||||
def _with_identity(domain: Domain, rows: list[dict]) -> list[dict]:
|
||||
"""Persons with their names, identifiers and the ids they replaced."""
|
||||
persons = [r["person_id"] for r in rows]
|
||||
names, ids, replaces = {}, {}, {}
|
||||
for r in reads.rows(domain.value, "names", persons=persons):
|
||||
@@ -313,8 +300,9 @@ def _patient_rows(
|
||||
applied = {"follow-up-cutoff": at.isoformat(), **filters}
|
||||
else:
|
||||
rows = [{**r, "status": fu.status(r, at)} for r in persons]
|
||||
if _id:
|
||||
rows = [r for r in rows if r["person_id"] in _id.split(",")]
|
||||
if _id and (not listed or domain == Domain.TEA):
|
||||
ids = set(_id.split(","))
|
||||
rows = [r for r in rows if r["person_id"] in ids]
|
||||
if status:
|
||||
rows = [r for r in rows if r["status"] in status.split(",")]
|
||||
if filters:
|
||||
@@ -353,9 +341,6 @@ def _revincludes(domain: Domain) -> tuple[str, ...]:
|
||||
return (*REVINCLUDES, "Condition:subject") if domain == Domain.TEA else REVINCLUDES
|
||||
|
||||
|
||||
# --- clinical searches: by subject ----------------------------------------------------------
|
||||
|
||||
|
||||
def _subjects(subject: str | None) -> list[str]:
|
||||
if not subject:
|
||||
raise HTTPException(422, "subject is required (Patient/<id>, comma-separated)")
|
||||
@@ -363,8 +348,6 @@ def _subjects(subject: str | None) -> list[str]:
|
||||
|
||||
|
||||
def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]:
|
||||
"""Every instance of the domain's studies (the catalog's) for these persons, as known
|
||||
by `at`: its DiagnosticReport (or Encounter) and Observations, in date order."""
|
||||
found: list[Resource] = []
|
||||
report_facts = _clinical(domain).REPORT_FACTS
|
||||
if domain == Domain.TEA:
|
||||
@@ -453,13 +436,20 @@ def _clinical_search(kind: str, build, request, domain, subject, count, offset):
|
||||
SUBJECT = "Patient/<id>, comma-separated"
|
||||
|
||||
|
||||
@router.get("/DiagnosticReport", responses=_OK, response_class=Response)
|
||||
@router.get(
|
||||
"/DiagnosticReport",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description=(
|
||||
"The domain's reports (each study of the catalog with a report), "
|
||||
"as known by the last\n"
|
||||
"day with data."
|
||||
),
|
||||
)
|
||||
def search_diagnostic_report(request: Request, domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||
"""The domain's reports (each study of the catalog with a report), as known by the last
|
||||
day with data."""
|
||||
return _study_search("DiagnosticReport", request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
@@ -471,30 +461,42 @@ def _study_search(kind: str, request, domain, subject, count, offset) -> Respons
|
||||
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
||||
|
||||
|
||||
@router.get("/Encounter", responses=_OK, response_class=Response)
|
||||
@router.get(
|
||||
"/Encounter",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="Consultations: each study of the catalog without a report, as an encounter.",
|
||||
)
|
||||
def search_encounter(request: Request, domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||
"""Consultations: each study of the catalog without a report, as an encounter."""
|
||||
return _study_search("Encounter", request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
@router.get("/Observation", responses=_OK, response_class=Response)
|
||||
@router.get(
|
||||
"/Observation",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="Every result of the domain's reports, one per field of the catalog.",
|
||||
)
|
||||
def search_observation(request: Request, domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||
"""Every result of the domain's reports, one per field of the catalog."""
|
||||
return _study_search("Observation", request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
@router.get("/Condition", responses=_OK, response_class=Response)
|
||||
@router.get(
|
||||
"/Condition",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="What clinical notes diagnosed (CaMa: and each recurrence).",
|
||||
)
|
||||
def search_condition(request: Request, domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||
"""What clinical notes diagnosed (CaMa: and each recurrence)."""
|
||||
|
||||
def build(rows):
|
||||
return [f.condition(r) for r in rows]
|
||||
@@ -502,13 +504,20 @@ def search_condition(request: Request, domain: Domain,
|
||||
return _clinical_search("condition", build, request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
@router.get("/Procedure", responses=_OK, response_class=Response)
|
||||
@router.get(
|
||||
"/Procedure",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description=(
|
||||
"The procedures the domain's timeline infers (CaCu: colposcopies "
|
||||
"and treatments;\n"
|
||||
"CaMa: each treatment, by its kind)."
|
||||
),
|
||||
)
|
||||
def search_procedure(request: Request, domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||
"""The procedures the domain's timeline infers (CaCu: colposcopies and treatments;
|
||||
CaMa: each treatment, by its kind)."""
|
||||
|
||||
def build(rows):
|
||||
return [f.procedure(r, domain.value) for r in rows]
|
||||
@@ -516,18 +525,19 @@ def search_procedure(request: Request, domain: Domain,
|
||||
return _clinical_search("procedure", build, request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
@router.get("/RiskAssessment", responses=_OK, response_class=Response)
|
||||
@router.get(
|
||||
"/RiskAssessment",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="The champion models' risks, one per model and index date.",
|
||||
)
|
||||
def search_risk_assessment(request: Request, domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||
"""The champion models' risks, one per model and index date."""
|
||||
return _clinical_search("risk", _risk_assessments, request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
# --- Measure and MeasureReport ----------------------------------------------------------------
|
||||
|
||||
|
||||
def _measure(domain: Domain, key: str) -> m.Measure:
|
||||
found = measures(domain)
|
||||
for code, measure in found.items():
|
||||
@@ -541,16 +551,25 @@ def read_measure(domain: Domain, id: str) -> Response:
|
||||
return fhir(f.measure(_measure(domain, id), domain.value))
|
||||
|
||||
|
||||
@router.get("/Measure", responses=_OK, response_class=Response)
|
||||
@router.get(
|
||||
"/Measure",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="Every measure of the domain (none for a domain without them yet).",
|
||||
)
|
||||
def search_measure(request: Request, domain: Domain, _count: int | None = Query(None),
|
||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||
"""Every measure of the domain (none for a domain without them yet)."""
|
||||
count, offset = _page(_count, _offset)
|
||||
found = [f.measure(x, domain.value) for x in measures(domain).values()]
|
||||
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
||||
|
||||
|
||||
@router.get("/MeasureReport", responses=_OK, response_class=Response)
|
||||
@router.get(
|
||||
"/MeasureReport",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="The measure's summary report for each period asked for, evaluated over gold.",
|
||||
)
|
||||
def search_measure_report(
|
||||
request: Request,
|
||||
domain: Domain,
|
||||
@@ -568,7 +587,6 @@ def search_measure_report(
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0),
|
||||
) -> Response:
|
||||
"""The measure's summary report for each period asked for, evaluated over gold."""
|
||||
found = _measure(domain, measure.split("|")[0])
|
||||
count, offset = _page(_count, _offset)
|
||||
try:
|
||||
@@ -586,10 +604,18 @@ def search_measure_report(
|
||||
return bundle(request, reports, len(asked), count, offset)
|
||||
|
||||
|
||||
# --- the FHIR door: what a standard hospital sends -----------------------------------------
|
||||
|
||||
|
||||
@router.post("", responses=_OK, response_class=Response, status_code=202)
|
||||
@router.post(
|
||||
"",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
status_code=202,
|
||||
description=(
|
||||
"A standard hospital's Bundle: checked as FHIR, kept as sent in "
|
||||
"the sender's inbox,\n"
|
||||
"and placed by the sender's pipeline (a run starts; follow it at "
|
||||
"the Location)."
|
||||
),
|
||||
)
|
||||
def post_bundle(
|
||||
domain: Domain,
|
||||
bundle: Annotated[dict[str, Any], Body(description="a FHIR R4 batch or transaction Bundle")],
|
||||
@@ -600,8 +626,6 @@ def post_bundle(
|
||||
),
|
||||
client: DagsterGraphQLClient = Depends(dagster),
|
||||
) -> Response:
|
||||
"""A standard hospital's Bundle: checked as FHIR, kept as sent in the sender's inbox,
|
||||
and placed by the sender's pipeline (a run starts; follow it at the Location)."""
|
||||
try:
|
||||
parsed = Bundle.model_validate(bundle)
|
||||
except ValueError as e:
|
||||
@@ -622,19 +646,22 @@ def post_bundle(
|
||||
return found
|
||||
|
||||
|
||||
# --- CapabilityStatement ----------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/metadata", responses=_OK, response_class=Response)
|
||||
@router.get(
|
||||
"/metadata",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description=(
|
||||
"What this base serves: built from the routes above, so it cannot drift from them."
|
||||
),
|
||||
)
|
||||
def metadata(request: Request, domain: Domain) -> Response:
|
||||
"""What this base serves: built from the routes above, so it cannot drift from them."""
|
||||
resources: dict[str, dict] = {}
|
||||
system: list[dict] = []
|
||||
fu = part(domain, "follow_up")
|
||||
clinical = fu is not None
|
||||
for route in router.routes:
|
||||
path = route.path.removeprefix(router.prefix)
|
||||
if not path: # the base itself: the FHIR door
|
||||
if not path:
|
||||
if clinical:
|
||||
system = [{"code": "batch"}, {"code": "transaction"}]
|
||||
continue
|
||||
|
||||
+44
-41
@@ -1,5 +1,3 @@
|
||||
"""/conectar: look into a site's sources, draw and save pipelines, run them, inspect nodes."""
|
||||
|
||||
from typing import Annotated, Any
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||
@@ -8,7 +6,7 @@ from fhir.resources.R4B.conceptmap import ConceptMap
|
||||
from pydantic import BaseModel
|
||||
|
||||
from core import concept_map
|
||||
from core.pipeline import ID_PATTERN, ImportPath, Pipeline, Source, redacted, restored
|
||||
from core.pipeline import ID_PATTERN, Pipeline, Source, redacted, restored
|
||||
from core.schema import ENTITIES
|
||||
from persistance import config_log, nodes
|
||||
from webapi.runs import dagster
|
||||
@@ -22,33 +20,26 @@ Rows = list[dict[str, Any]]
|
||||
def _from_source(call, *args):
|
||||
try:
|
||||
return call(*args)
|
||||
except Exception as e: # noqa: BLE001 - the operator needs the source's own message
|
||||
except Exception as e: # noqa: BLE001
|
||||
raise HTTPException(422, detail=f"{type(e).__name__}: {e}") from e
|
||||
|
||||
|
||||
@router.get("/schema")
|
||||
@router.get(
|
||||
"/schema",
|
||||
description="What the canvas draws with: every node kind's form, and the platform entities.",
|
||||
)
|
||||
def schema() -> dict[str, Any]:
|
||||
"""What the canvas draws with: every node kind's form, and the platform entities."""
|
||||
return {
|
||||
"pipeline": Pipeline.model_json_schema(),
|
||||
"entities": {name: model.model_json_schema() for name, model in ENTITIES.items()},
|
||||
}
|
||||
|
||||
|
||||
class SourceRef(BaseModel):
|
||||
source: ImportPath
|
||||
args: dict[str, Any] = {}
|
||||
|
||||
|
||||
@router.post("/sources/resources")
|
||||
def source_resources(ref: SourceRef) -> list[str]:
|
||||
"""What a source offers (a database's tables...): also tests that it can be reached."""
|
||||
return _from_source(nodes.resources, ref.source, ref.args)
|
||||
|
||||
|
||||
@router.post("/sources/preview")
|
||||
@router.post(
|
||||
"/sources/preview",
|
||||
description="The first rows a source node would load.",
|
||||
)
|
||||
def source_preview(node: Source, limit: Annotated[int, Query(ge=1, le=200)] = 20) -> Rows:
|
||||
"""The first rows a source node would load."""
|
||||
return [nodes.shown(r) for r in _from_source(nodes.preview, node, limit)]
|
||||
|
||||
|
||||
@@ -62,19 +53,26 @@ class SavedPipeline(BaseModel):
|
||||
pipeline: Pipeline
|
||||
|
||||
|
||||
@router.get("/pipelines/{pipeline_id}")
|
||||
@router.get(
|
||||
"/pipelines/{pipeline_id}",
|
||||
description="A saved pipeline (latest by default), with its secrets masked.",
|
||||
)
|
||||
def pipeline(pipeline_id: PipelineId, version: int | None = None) -> SavedPipeline:
|
||||
"""A saved pipeline (latest by default), with its secrets masked."""
|
||||
if not config_log.latest_version(pipeline_id):
|
||||
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
||||
found, saved = config_log.get(pipeline_id, version)
|
||||
return SavedPipeline(version=found, pipeline=redacted(saved))
|
||||
|
||||
|
||||
@router.put("/pipelines/{pipeline_id}")
|
||||
@router.put(
|
||||
"/pipelines/{pipeline_id}",
|
||||
description=(
|
||||
"Saves a new version. Masked secrets sent back are kept as they "
|
||||
"were saved; every\n"
|
||||
"ConceptMap a node names must exist."
|
||||
),
|
||||
)
|
||||
def save_pipeline(pipeline_id: PipelineId, drawn: Pipeline) -> dict[str, int]:
|
||||
"""Saves a new version. Masked secrets sent back are kept as they were saved; every
|
||||
ConceptMap a node names must exist."""
|
||||
named = {n.concept_map for n in drawn.nodes if getattr(n, "concept_map", None)}
|
||||
if missing := sorted(m for m in named if not config_log.latest_version(m, "concept_maps")):
|
||||
raise HTTPException(422, detail=f"no concept maps {missing}")
|
||||
@@ -86,24 +84,26 @@ def save_pipeline(pipeline_id: PipelineId, drawn: Pipeline) -> dict[str, int]:
|
||||
return {"version": config_log.save(pipeline_id, complete)}
|
||||
|
||||
|
||||
@router.get("/concept-maps")
|
||||
def concept_maps() -> Rows:
|
||||
"""Every ConceptMap a site saved: its id, latest version and when."""
|
||||
return config_log.listing("concept_maps")
|
||||
|
||||
|
||||
@router.get("/concept-maps/{map_id}")
|
||||
@router.get(
|
||||
"/concept-maps/{map_id}",
|
||||
description="A site's codes in platform terms (FHIR R4B ConceptMap), latest version.",
|
||||
)
|
||||
def get_concept_map(map_id: PipelineId) -> dict[str, Any]:
|
||||
"""A site's codes in platform terms (FHIR R4B ConceptMap), latest version."""
|
||||
if not config_log.latest_version(map_id, "concept_maps"):
|
||||
raise HTTPException(404, detail=f"no concept map {map_id}")
|
||||
return config_log.concept_map(map_id).model_dump(mode="json", exclude_none=True)
|
||||
|
||||
|
||||
@router.put("/concept-maps/{map_id}")
|
||||
@router.put(
|
||||
"/concept-maps/{map_id}",
|
||||
description=(
|
||||
"Saves a new version of a ConceptMap. Its groups target the "
|
||||
"systems platform fields\n"
|
||||
"take codes from, and only codes those fields allow "
|
||||
"(core.concept_map)."
|
||||
),
|
||||
)
|
||||
def save_concept_map(map_id: PipelineId, doc: dict[str, Any]) -> dict[str, int]:
|
||||
"""Saves a new version of a ConceptMap. Its groups target the systems platform fields
|
||||
take codes from, and only codes those fields allow (core.concept_map)."""
|
||||
try:
|
||||
found = ConceptMap.model_validate({**doc, "resourceType": "ConceptMap"})
|
||||
except ValueError as e:
|
||||
@@ -114,23 +114,24 @@ def save_concept_map(map_id: PipelineId, doc: dict[str, Any]) -> dict[str, int]:
|
||||
|
||||
|
||||
class RunRequest(BaseModel):
|
||||
version: int | None = None # default: the latest saved
|
||||
version: int | None = None
|
||||
|
||||
|
||||
@router.post("/pipelines/{pipeline_id}/runs")
|
||||
@router.post(
|
||||
"/pipelines/{pipeline_id}/runs",
|
||||
description="Starts the `ingest` job for this pipeline; follow it at /runs/{run_id}.",
|
||||
)
|
||||
def start_run(
|
||||
pipeline_id: PipelineId,
|
||||
request: RunRequest,
|
||||
client: DagsterGraphQLClient = Depends(dagster),
|
||||
) -> dict[str, str]:
|
||||
"""Starts the `ingest` job for this pipeline; follow it at /runs/{run_id}."""
|
||||
if not config_log.latest_version(pipeline_id):
|
||||
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
||||
return {"run_id": submit(client, pipeline_id, request.version)}
|
||||
|
||||
|
||||
def submit(client: DagsterGraphQLClient, pipeline_id: str, version: int | None = None) -> str:
|
||||
"""Starts the `ingest` job for a saved pipeline (the latest version by default)."""
|
||||
config = {"pipeline": pipeline_id, "version": version}
|
||||
try:
|
||||
return client.submit_job_execution(
|
||||
@@ -140,13 +141,15 @@ def submit(client: DagsterGraphQLClient, pipeline_id: str, version: int | None =
|
||||
raise HTTPException(502, detail=str(e)) from e
|
||||
|
||||
|
||||
@router.get("/pipelines/{pipeline_id}/nodes/{node_id}/rows")
|
||||
@router.get(
|
||||
"/pipelines/{pipeline_id}/nodes/{node_id}/rows",
|
||||
description="What a node produced in the last run (empty if it produced nothing yet).",
|
||||
)
|
||||
def node_rows(
|
||||
pipeline_id: PipelineId,
|
||||
node_id: NodeId,
|
||||
limit: Annotated[int, Query(ge=1, le=500)] = 50,
|
||||
) -> Rows:
|
||||
"""What a node produced in the last run (empty if it produced nothing yet)."""
|
||||
out = []
|
||||
for row in nodes.rows(pipeline_id, node_id):
|
||||
out.append(nodes.shown(row))
|
||||
|
||||
+3
-4
@@ -9,8 +9,8 @@ from webapi.auth import caller
|
||||
app = FastAPI(
|
||||
title="ISSSTELEON",
|
||||
version="0.0.0",
|
||||
dependencies=[Depends(caller)], # every route; where authentication will go
|
||||
generate_unique_id_function=lambda route: route.name, # clean names in the generated client
|
||||
dependencies=[Depends(caller)],
|
||||
generate_unique_id_function=lambda route: route.name,
|
||||
lifespan=users.lifespan,
|
||||
)
|
||||
app.include_router(ingest.router)
|
||||
@@ -22,12 +22,11 @@ app.include_router(models.router)
|
||||
app.include_router(eeg.router)
|
||||
app.include_router(preview.router)
|
||||
app.include_router(fhir.router)
|
||||
app.include_router(users.router) # sign-in for the web app; no route requires it
|
||||
app.include_router(users.router)
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def errors(request: Request, error: HTTPException):
|
||||
"""FHIR routes answer errors as an OperationOutcome."""
|
||||
if "/fhir/" in request.url.path or request.url.path.endswith("/fhir"):
|
||||
return fhir.outcome(error.status_code, str(error.detail))
|
||||
return await http_exception_handler(request, error)
|
||||
|
||||
+50
-64
@@ -1,21 +1,16 @@
|
||||
"""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 import APIRouter, Depends, HTTPException, Query, UploadFile
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel, Field, WithJsonSchema
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from core import tea
|
||||
from core.domains import Domain, InputSpec
|
||||
from core.domains import Domain
|
||||
from core.models import title
|
||||
from persistance import bundle, cluster, inputs, registry
|
||||
from persistance import bundle, cluster, registry
|
||||
from persistance.cluster import Execution, TrainingSource
|
||||
from webapi.runs import dagster, execution_config, submit
|
||||
|
||||
@@ -24,7 +19,7 @@ router = APIRouter(prefix="/models", tags=["models"])
|
||||
|
||||
class Version(BaseModel):
|
||||
version: int
|
||||
created: int # ms since the epoch
|
||||
created: int
|
||||
aliases: list[str]
|
||||
metrics: dict[str, float]
|
||||
params: dict[str, str]
|
||||
@@ -112,10 +107,14 @@ def versions(domain: Domain, name: str) -> list[Version]:
|
||||
@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
|
||||
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:
|
||||
"""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}")
|
||||
@@ -125,20 +124,31 @@ def read_report(domain: Domain, name: str, version: int, report: str) -> Respons
|
||||
headers={"Content-Disposition": f'inline; filename="{filename}"'}) # fmt: skip
|
||||
|
||||
|
||||
@router.post("/{domain}/{name}/versions/{version}/reports/clinical_validation")
|
||||
@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:
|
||||
"""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")
|
||||
@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:
|
||||
"""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:
|
||||
@@ -183,40 +193,6 @@ def lineage(domain: Domain, name: str, version: int) -> dict:
|
||||
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:
|
||||
@@ -237,7 +213,7 @@ class TrainingForm(BaseModel):
|
||||
None, title="Datos hasta", description="Fecha de corte de los datos (por omisión, hoy)"
|
||||
)
|
||||
execution: Execution | None = None
|
||||
source: TrainingSource | None = None
|
||||
source: TrainingSource | None = Field(None, title="Datos de entrenamiento")
|
||||
|
||||
|
||||
class Training(TrainingForm):
|
||||
@@ -256,10 +232,11 @@ 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", "line_hz": 50}
|
||||
defaults["source"] = {"kind": "site"}
|
||||
else:
|
||||
del json_schema["properties"]["source"]
|
||||
del json_schema["$defs"]["TrainingSource"]
|
||||
for definition in ("TrainingSource", "SiteTrainingSource", "FolderTrainingSource"):
|
||||
del json_schema["$defs"][definition]
|
||||
return TrainingConfig(
|
||||
domain=domain.value, name=name, json_schema=json_schema, defaults=defaults
|
||||
)
|
||||
@@ -269,10 +246,12 @@ class Analyze(BaseModel):
|
||||
execution: Execution | None = None
|
||||
|
||||
|
||||
@router.post("/{domain}/train")
|
||||
@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
|
||||
"""Starts training a new version of every model of the domain; follow it at /runs."""
|
||||
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)}
|
||||
@@ -285,19 +264,26 @@ def train(domain: Domain, request: Training,
|
||||
return submit(client, "train", "train_models", config, domain=domain.value)
|
||||
|
||||
|
||||
@router.post("/{domain}/analyze")
|
||||
@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]:
|
||||
"""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")
|
||||
@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]:
|
||||
"""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)
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Print the OpenAPI document; the WebApp generates its client from it."""
|
||||
|
||||
import json
|
||||
|
||||
from webapi.main import app
|
||||
|
||||
+56
-23
@@ -1,9 +1,7 @@
|
||||
"""What waits for a person, and their decisions (append-only; the next run applies them)."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, model_validator
|
||||
from pydantic import BaseModel, ConfigDict, model_validator
|
||||
|
||||
from core.pipeline import EntityName, Id, validate
|
||||
from core.schema import ENTITIES
|
||||
@@ -14,29 +12,44 @@ router = APIRouter(prefix="/review", tags=["review"])
|
||||
Rows = list[dict[str, Any]]
|
||||
|
||||
|
||||
@router.get("/held")
|
||||
@router.get(
|
||||
"/held",
|
||||
description="Rows a rule held, with the reasons and the values as they came.",
|
||||
)
|
||||
def held(entity: EntityName) -> Rows:
|
||||
"""Rows a rule held, with the reasons and the values as they came."""
|
||||
return review.held(entity)
|
||||
|
||||
|
||||
@router.get("/conflicts")
|
||||
@router.get(
|
||||
"/conflicts",
|
||||
description="Rows of one person and date that disagree; reject the wrong ones.",
|
||||
)
|
||||
def conflicts(entity: EntityName) -> Rows:
|
||||
"""Rows of one person and date that disagree; reject the wrong ones."""
|
||||
return review.conflicts(entity)
|
||||
|
||||
|
||||
@router.get("/unrecognised")
|
||||
@router.get(
|
||||
"/unrecognised",
|
||||
description=(
|
||||
"Documents a pipeline's routes don't recognise (what its "
|
||||
"`otherwise` routes took):\n"
|
||||
"a new layout, a study the platform doesn't know, a scan nothing "
|
||||
"could read."
|
||||
),
|
||||
)
|
||||
def unrecognised(pipeline: Id) -> Rows:
|
||||
"""Documents a pipeline's routes don't recognise (what its `otherwise` routes took):
|
||||
a new layout, a study the platform doesn't know, a scan nothing could read."""
|
||||
return review.unrecognised(pipeline)
|
||||
|
||||
|
||||
@router.get("/persons")
|
||||
@router.get(
|
||||
"/persons",
|
||||
description=(
|
||||
"Persons to settle (with their possible owners), torn persons "
|
||||
"and persons nothing\n"
|
||||
"names (with their records) left by a pipeline's link node."
|
||||
),
|
||||
)
|
||||
def persons(pipeline: Id, node: Id) -> dict[str, Rows]:
|
||||
"""Persons to settle (with their possible owners), torn persons and persons nothing
|
||||
names (with their records) left by a pipeline's link node."""
|
||||
return review.persons(pipeline, node)
|
||||
|
||||
|
||||
@@ -46,16 +59,27 @@ class PersonDecision(BaseModel):
|
||||
same: bool
|
||||
|
||||
|
||||
@router.post("/persons", status_code=201)
|
||||
@router.post(
|
||||
"/persons",
|
||||
status_code=201,
|
||||
description="Whether a person and a possible owner are one patient; applied on the next run.",
|
||||
)
|
||||
def decide_persons(decision: PersonDecision, who: Caller = Depends(caller)) -> dict[str, str]:
|
||||
"""Whether a person and a possible owner are one patient; applied on the next run."""
|
||||
nodes.decide_persons(decision.person, decision.candidate, decision.same, who.id)
|
||||
return {"person": decision.person}
|
||||
|
||||
|
||||
class Correction(BaseModel):
|
||||
"""One field of one record as a reviewer read it in the source document: an identity
|
||||
field (a mistyped record number) or a study's (a stage the scan made unreadable)."""
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"One field of one record as a reviewer read it in the source "
|
||||
"document: an identity\n"
|
||||
"field (a mistyped record number) or a study's (a stage the scan "
|
||||
"made unreadable)."
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
entity: EntityName = "identity"
|
||||
record: str
|
||||
@@ -66,7 +90,6 @@ class Correction(BaseModel):
|
||||
def _a_valid_value(self):
|
||||
if self.field not in ENTITIES[self.entity].model_fields:
|
||||
raise ValueError(f"{self.entity} has no field {self.field}")
|
||||
# only this field's own problems (a study's other required fields aren't given here)
|
||||
reasons = [r for r in validate(self.entity, {self.field: self.value})
|
||||
if r.split(":")[0] == self.field] # fmt: skip
|
||||
if reasons:
|
||||
@@ -74,10 +97,17 @@ class Correction(BaseModel):
|
||||
return self
|
||||
|
||||
|
||||
@router.post("/corrections", status_code=201)
|
||||
@router.post(
|
||||
"/corrections",
|
||||
status_code=201,
|
||||
description=(
|
||||
"A corrected field of one record; the next run uses it (linking "
|
||||
"for identity fields,\n"
|
||||
"the study's target for the others). Fixing the source too is "
|
||||
"still worth it."
|
||||
),
|
||||
)
|
||||
def correct(fix: Correction, who: Caller = Depends(caller)) -> dict[str, str]:
|
||||
"""A corrected field of one record; the next run uses it (linking for identity fields,
|
||||
the study's target for the others). Fixing the source too is still worth it."""
|
||||
nodes.correct(fix.record, fix.field, fix.value, who.id, fix.entity)
|
||||
return {"record": fix.record}
|
||||
|
||||
@@ -88,8 +118,11 @@ class Rejection(BaseModel):
|
||||
reason: str
|
||||
|
||||
|
||||
@router.post("/rejections", status_code=201)
|
||||
@router.post(
|
||||
"/rejections",
|
||||
status_code=201,
|
||||
description="This record's row must not reach silver; applied on the next run.",
|
||||
)
|
||||
def reject(decision: Rejection, who: Caller = Depends(caller)) -> dict[str, str]:
|
||||
"""This record's row must not reach silver; applied on the next run."""
|
||||
nodes.reject(decision.entity, decision.record, decision.reason, who.id)
|
||||
return {"record": decision.record}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Runs live in Dagster: the API starts them and reads their state, never computes."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
+52
-44
@@ -1,6 +1,3 @@
|
||||
"""The Conectar dialog: the kinds of source an operator can pick, "Probar conexión", the
|
||||
server folders they may browse, and the files they upload. Open like the rest of the API."""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
@@ -20,28 +17,29 @@ router = APIRouter(prefix="/ingest", tags=["ingest"])
|
||||
UPLOADS = "uploads"
|
||||
|
||||
|
||||
@router.get("/sources/types")
|
||||
@router.get(
|
||||
"/sources/types",
|
||||
description="Every kind of source the dialog offers, grouped, with the fields each one asks.",
|
||||
)
|
||||
def source_types() -> sources.Catalog:
|
||||
"""Every kind of source the dialog offers, grouped, with the fields each one asks."""
|
||||
return sources.catalog()
|
||||
|
||||
|
||||
class Answers(BaseModel):
|
||||
type: str
|
||||
answers: dict[str, Any] = {}
|
||||
pipeline: str | None = None # editing a saved source: its secrets come back masked
|
||||
pipeline: str | None = None
|
||||
node: str | None = None
|
||||
|
||||
|
||||
class Tested(BaseModel):
|
||||
ok: bool
|
||||
message: str # in plain words, for the operator
|
||||
detail: str | None = None # the source's own words, for whoever helps them
|
||||
message: str
|
||||
detail: str | None = None
|
||||
tables: list[str] = []
|
||||
rows: list[dict[str, Any]] = []
|
||||
|
||||
|
||||
# What a source's own error means, in words an operator can act on (first match wins).
|
||||
PLAIN = [
|
||||
(
|
||||
r"login failed|password authentication failed|access denied|authentication|"
|
||||
@@ -92,11 +90,18 @@ def _with_saved_secrets(asked: Answers) -> dict[str, Any]:
|
||||
return found.guided.answers
|
||||
|
||||
|
||||
@router.post("/sources/test")
|
||||
@router.post(
|
||||
"/sources/test",
|
||||
description=(
|
||||
'"Probar conexión": reaches the source with the answers given. A '
|
||||
"database lists its\n"
|
||||
"tables (until one is picked; then its first rows); files and "
|
||||
"records show their first\n"
|
||||
"rows. Never a server error: what went wrong comes back in plain "
|
||||
"words."
|
||||
),
|
||||
)
|
||||
def test_source(asked: Answers, limit: Annotated[int, Query(ge=1, le=100)] = 20) -> Tested:
|
||||
""" "Probar conexión": reaches the source with the answers given. A database lists its
|
||||
tables (until one is picked; then its first rows); files and records show their first
|
||||
rows. Never a server error: what went wrong comes back in plain words."""
|
||||
if asked.type not in sources.catalog().types:
|
||||
raise HTTPException(404, detail=f"no source type {asked.type}")
|
||||
answers = _with_saved_secrets(asked)
|
||||
@@ -110,9 +115,9 @@ def test_source(asked: Answers, limit: Annotated[int, Query(ge=1, le=100)] = 20)
|
||||
tables=tables) # fmt: skip
|
||||
node = Source(id="probe", guided={"type": asked.type, "answers": answers})
|
||||
rows = [nodes.shown(r) for r in nodes.preview(node, limit)]
|
||||
except (sources.MissingAnswer, ValidationError) as e: # an answer missing: plain words
|
||||
except (sources.MissingAnswer, ValidationError) as e:
|
||||
return Tested(ok=False, message=_missing(e))
|
||||
except Exception as e: # noqa: BLE001 - whatever the source says goes back to the operator
|
||||
except Exception as e: # noqa: BLE001
|
||||
return Tested(ok=False, message=plain(e), detail=f"{type(e).__name__}: {e}"[:2000])
|
||||
found = (
|
||||
"Conexión correcta."
|
||||
@@ -125,7 +130,7 @@ def test_source(asked: Answers, limit: Annotated[int, Query(ge=1, le=100)] = 20)
|
||||
|
||||
|
||||
def _missing(e: Exception) -> str:
|
||||
if isinstance(e, ValidationError): # raised while the node is made from the answers
|
||||
if isinstance(e, ValidationError):
|
||||
return next((str(err["ctx"]["error"]) for err in e.errors()
|
||||
if isinstance(err.get("ctx", {}).get("error"), sources.MissingAnswer)),
|
||||
str(e)) # fmt: skip
|
||||
@@ -133,8 +138,6 @@ def _missing(e: Exception) -> str:
|
||||
|
||||
|
||||
def roots() -> dict[str, Path]:
|
||||
"""The folders the operator mounted for sources (SOURCE_ROOTS, separated by ":"), by
|
||||
name; uploads always."""
|
||||
found = {"Subidos": (DATA_DIR / UPLOADS).resolve()}
|
||||
for raw in filter(None, os.environ.get("SOURCE_ROOTS", "").split(os.pathsep)):
|
||||
path = Path(raw).resolve()
|
||||
@@ -144,21 +147,26 @@ def roots() -> dict[str, Path]:
|
||||
|
||||
class Entry(BaseModel):
|
||||
name: str
|
||||
path: str # what a folder field takes
|
||||
path: str
|
||||
kind: Literal["folder", "file"]
|
||||
size: int | None = None
|
||||
|
||||
|
||||
class Browsed(BaseModel):
|
||||
path: str | None # None: the list of roots
|
||||
path: str | None
|
||||
parent: str | None
|
||||
entries: list[Entry]
|
||||
|
||||
|
||||
@router.get("/sources/browse")
|
||||
@router.get(
|
||||
"/sources/browse",
|
||||
description=(
|
||||
"The server folders a source may read: the roots, or what one "
|
||||
"folder under them\n"
|
||||
"holds. Nothing outside the roots is shown."
|
||||
),
|
||||
)
|
||||
def browse(path: str | None = None) -> Browsed:
|
||||
"""The server folders a source may read: the roots, or what one folder under them
|
||||
holds. Nothing outside the roots is shown."""
|
||||
allowed = roots()
|
||||
if path is None:
|
||||
return Browsed(path=None, parent=None, entries=[
|
||||
@@ -178,24 +186,28 @@ def browse(path: str | None = None) -> Browsed:
|
||||
|
||||
|
||||
class Uploaded(BaseModel):
|
||||
bucket_url: str # the folder: what an upload field and a filesystem source take
|
||||
bucket_url: str
|
||||
files: list[str]
|
||||
|
||||
|
||||
def _relative(name: str) -> PurePosixPath:
|
||||
"""A file's name as the browser sent it (a folder upload keeps its subfolders), never
|
||||
reaching outside its folder."""
|
||||
parts = [p for p in PurePosixPath(name.replace("\\", "/")).parts if p not in ("", ".", "..")]
|
||||
if not parts:
|
||||
raise HTTPException(422, detail="the file needs a name")
|
||||
return PurePosixPath(*parts)
|
||||
|
||||
|
||||
@router.post("/uploads")
|
||||
@router.post(
|
||||
"/uploads",
|
||||
description=(
|
||||
"Files from the operator's computer (one, many, or a whole "
|
||||
"folder), kept on the\n"
|
||||
"server for a `filesystem` source; streamed to disk, so large "
|
||||
"recordings fit. Send\n"
|
||||
"`folder` from a previous answer to add to the same set."
|
||||
),
|
||||
)
|
||||
def upload(files: list[UploadFile], folder: Annotated[str | None, Form()] = None) -> Uploaded:
|
||||
"""Files from the operator's computer (one, many, or a whole folder), kept on the
|
||||
server for a `filesystem` source; streamed to disk, so large recordings fit. Send
|
||||
`folder` from a previous answer to add to the same set."""
|
||||
base = (DATA_DIR / UPLOADS).resolve()
|
||||
target = Path(folder).resolve() if folder else base / uuid.uuid4().hex[:12]
|
||||
if target.parent != base:
|
||||
@@ -211,10 +223,6 @@ def upload(files: list[UploadFile], folder: Annotated[str | None, Form()] = None
|
||||
return Uploaded(bucket_url=str(target), files=kept)
|
||||
|
||||
|
||||
# Sign-in buttons: OAuth 2.0 authorization code flow with PKCE (authlib). The dialog opens
|
||||
# `start`'s address in a window; the provider sends the user back to `callback`, which
|
||||
# hands the account to the dialog (window.opener) and closes. A pending sign-in is a file
|
||||
# in the data folder for ten minutes, so whichever API worker gets the callback finds it.
|
||||
PENDING = DATA_DIR / "oauth_pending"
|
||||
PENDING_SECONDS = 600
|
||||
STATE = re.compile(r"[A-Za-z0-9_-]{8,128}")
|
||||
@@ -234,7 +242,6 @@ def _pend(state: str, pending: dict[str, Any]) -> None:
|
||||
|
||||
|
||||
def _claimed(state: str) -> dict[str, Any] | None:
|
||||
"""The pending sign-in of `state`, taken once (by an atomic rename), if still fresh."""
|
||||
import json
|
||||
import time
|
||||
|
||||
@@ -278,14 +285,19 @@ def _client(provider: sources.Provider, env: dict[str, str], redirect_uri: str):
|
||||
|
||||
|
||||
class SignIn(BaseModel):
|
||||
url: str # where the dialog's window goes
|
||||
url: str
|
||||
state: str
|
||||
|
||||
|
||||
@router.get("/sources/oauth/{provider}/start")
|
||||
@router.get(
|
||||
"/sources/oauth/{provider}/start",
|
||||
description=(
|
||||
"The provider's sign-in address. `origin` is the web app's "
|
||||
"(where the user returns:\n"
|
||||
"`{origin}/api/…/callback`, the address IT registered)."
|
||||
),
|
||||
)
|
||||
def oauth_start(provider: str, origin: str) -> SignIn:
|
||||
"""The provider's sign-in address. `origin` is the web app's (where the user returns:
|
||||
`{origin}/api/…/callback`, the address IT registered)."""
|
||||
import secrets
|
||||
|
||||
found, env = _registration(provider)
|
||||
@@ -300,9 +312,6 @@ def oauth_start(provider: str, origin: str) -> SignIn:
|
||||
|
||||
|
||||
def account(provider: str, token: dict[str, Any], env: dict[str, str]) -> dict[str, Any]:
|
||||
"""What a source needs to read as the signed-in user, and who they are (shown in the
|
||||
dialog). Microsoft: msgraphfs's OAuth client parameters and the user's own drive;
|
||||
Google: dlt's OAuth credentials for Drive."""
|
||||
import httpx
|
||||
|
||||
found = sources.catalog().providers[provider]
|
||||
@@ -330,7 +339,6 @@ def account(provider: str, token: dict[str, Any], env: dict[str, str]) -> dict[s
|
||||
|
||||
@router.get("/sources/oauth/{provider}/callback", include_in_schema=False)
|
||||
def oauth_callback(provider: str, state: str, code: str | None = None, error: str | None = None):
|
||||
"""Where the provider returns the user: the account goes to the dialog that asked."""
|
||||
import json
|
||||
|
||||
from fastapi.responses import HTMLResponse
|
||||
@@ -349,7 +357,7 @@ def oauth_callback(provider: str, state: str, code: str | None = None, error: st
|
||||
_endpoint(found.token_url, env), code=code, code_verifier=pending["verifier"]
|
||||
)
|
||||
message["account"] = account(provider, dict(token), env)
|
||||
except Exception as e: # noqa: BLE001 - shown to the person signing in
|
||||
except Exception as e: # noqa: BLE001
|
||||
message["error"] = f"No se pudo iniciar sesión: {e}"
|
||||
payload = json.dumps(message).replace("</", "<\\/")
|
||||
target = json.dumps(pending["origin"])
|
||||
|
||||
+8
-24
@@ -1,12 +1,3 @@
|
||||
"""Sign-in for the web app (fastapi-users): users, the domains each may see, and a session
|
||||
cookie. It decides only what the web app shows; no API route requires a session, so
|
||||
pipelines, the FHIR door and scripts answer as before.
|
||||
|
||||
Users live in the platform database (`config.users`). The first administrator comes from
|
||||
AUTH_ADMIN_EMAIL and AUTH_ADMIN_PASSWORD at startup; AUTH_SECRET signs the sessions (without
|
||||
it, one is made and kept in the data folder).
|
||||
"""
|
||||
|
||||
import os
|
||||
import secrets
|
||||
import uuid
|
||||
@@ -38,7 +29,6 @@ class User(SQLAlchemyBaseUserTableUUID, Base):
|
||||
__tablename__ = "users"
|
||||
__table_args__ = {"schema": SCHEMA}
|
||||
name: Mapped[str] = mapped_column(String(120), default="")
|
||||
# the domains the web app shows this user (an administrator sees every one)
|
||||
domains: Mapped[list[str]] = mapped_column(JSON, default=list)
|
||||
|
||||
|
||||
@@ -52,14 +42,8 @@ class UserCreate(schemas.BaseUserCreate):
|
||||
domains: list[Domain] = []
|
||||
|
||||
|
||||
class UserUpdate(schemas.BaseUserUpdate):
|
||||
name: str | None = None
|
||||
domains: list[Domain] | None = None
|
||||
|
||||
|
||||
@cache
|
||||
def _engine():
|
||||
"""The platform database, opened asynchronously (SQLite: its `config` file attached)."""
|
||||
url = make_url(platform_url())
|
||||
if url.drivername.startswith("sqlite"):
|
||||
engine = create_async_engine(url.set(drivername="sqlite+aiosqlite"))
|
||||
@@ -113,19 +97,22 @@ backend = AuthenticationBackend(
|
||||
transport=CookieTransport(
|
||||
cookie_name="isssteleon_session",
|
||||
cookie_max_age=SESSION_HOURS * 3600,
|
||||
cookie_secure=os.environ.get("AUTH_COOKIE_SECURE", "") == "1", # behind HTTPS
|
||||
cookie_secure=os.environ.get("AUTH_COOKIE_SECURE", "") == "1",
|
||||
cookie_samesite="lax",
|
||||
),
|
||||
get_strategy=lambda: JWTStrategy(secret=_secret(), lifetime_seconds=SESSION_HOURS * 3600),
|
||||
)
|
||||
users = FastAPIUsers[User, uuid.UUID](_manager, [backend])
|
||||
current_user = users.current_user(active=True)
|
||||
|
||||
router = APIRouter()
|
||||
router.include_router(users.get_auth_router(backend), prefix="/auth", tags=["auth"])
|
||||
router.include_router(users.get_users_router(UserRead, UserUpdate), prefix="/users", tags=["users"])
|
||||
user_routes = users.get_users_router(UserRead, schemas.BaseUserUpdate)
|
||||
user_routes.routes[:] = [
|
||||
route for route in user_routes.routes if route.name == "users:current_user"
|
||||
]
|
||||
router.include_router(user_routes, prefix="/users", tags=["users"])
|
||||
admins_only = [Depends(users.current_user(active=True, superuser=True))]
|
||||
router.include_router( # an administrator adds users
|
||||
router.include_router(
|
||||
users.get_register_router(UserRead, UserCreate),
|
||||
prefix="/users",
|
||||
tags=["users"],
|
||||
@@ -134,9 +121,8 @@ router.include_router( # an administrator adds users
|
||||
|
||||
|
||||
async def first_admin() -> None:
|
||||
"""The users table, and the administrator AUTH_ADMIN_EMAIL names (once)."""
|
||||
async with _engine().begin() as connection:
|
||||
if connection.dialect.name != "sqlite": # SQLite: the attached file is the schema
|
||||
if connection.dialect.name != "sqlite":
|
||||
await connection.execute(text(f"create schema if not exists {SCHEMA}"))
|
||||
await connection.run_sync(Base.metadata.create_all)
|
||||
email, password = os.environ.get("AUTH_ADMIN_EMAIL"), os.environ.get("AUTH_ADMIN_PASSWORD")
|
||||
@@ -154,8 +140,6 @@ async def first_admin() -> None:
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
||||
"""Each API worker starts here; one at a time (a lock in the data folder), so the
|
||||
users table, the first administrator and the session secret are made once."""
|
||||
import fcntl
|
||||
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
Reference in New Issue
Block a user