Compare commits
79 Commits
main
..
parity/main
| Author | SHA1 | Date | |
|---|---|---|---|
| c326f4901d | |||
| 37c456c5ef | |||
| edd3093d5d | |||
| 323240dd30 | |||
| 326502f90c | |||
| 2c5568f5d1 | |||
| 87a0893ee4 | |||
| 82f7a18a9f | |||
| b4db5f9b2c | |||
| 06f1cadc4b | |||
| b61a4863d1 | |||
| 6c1d098619 | |||
| 4063a9824b | |||
| f26d32a010 | |||
| b61843b639 | |||
| 80049112aa | |||
| ec5d945f71 | |||
| 54b1995681 | |||
| 52bcf34720 | |||
| d92d1697b8 | |||
| 983680ead3 | |||
| 3300ec3048 | |||
| 8a2ce3bbb4 | |||
| eda8dde354 | |||
| 08f240cde9 | |||
| 80b3d23b75 | |||
| b401f98f19 | |||
| 9e5aa20092 | |||
| 88b22b9491 | |||
| d7624c7e0f | |||
| c9b60b190b | |||
| 4ef38c18e2 | |||
| f830003abd | |||
| 3a18af9516 | |||
| 29186909cc | |||
| c7caf56f83 | |||
| 0a4deea370 | |||
| 25955b80e8 | |||
| 8b0b121aaa | |||
| 11c648ac36 | |||
| ae4638e4dd | |||
| 51bcdbdfe3 | |||
| 4212c4d0b5 | |||
| d59c20432e | |||
| d8d834f308 | |||
| f6e8b09dd0 | |||
| 2131ff60a5 | |||
| a4c3d6c1b0 | |||
| e3e774fca4 | |||
| 09691afc76 | |||
| 70c9506b97 | |||
| 7222cbdb49 | |||
| 7e25dde319 | |||
| 052fb23fab | |||
| b515746406 | |||
| 3438a3135b | |||
| 88bbc6155f | |||
| e434e085fe | |||
| e4967347f5 | |||
| 4793cf01f0 | |||
| 8fa2be8aab | |||
| de4485094f | |||
| 074fdb5305 | |||
| 135f23e898 | |||
| d3f7aeb537 | |||
| 1e878b8942 | |||
| dffd33a7bc | |||
| 9c89c9e10d | |||
| 7dbb4b75fc | |||
| 05980899a2 | |||
| cb9115c435 | |||
| 26cf994d1a | |||
| 806302ee5d | |||
| 0dd5c035bc | |||
| e2ed1e9dfb | |||
| 1c53276b55 | |||
| 326250ffb3 | |||
| cddf91185b | |||
| df921f13cd |
+1
-3
@@ -1,4 +1,2 @@
|
||||
__pycache__/
|
||||
node_modules/
|
||||
dist/
|
||||
.angular/
|
||||
.pytest_cache/
|
||||
|
||||
@@ -12,6 +12,7 @@ dependencies = [
|
||||
"fastapi-users[sqlalchemy]>=15",
|
||||
"aiosqlite>=0.20",
|
||||
"asyncpg>=0.30",
|
||||
"requests",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
from zipfile import ZipFile
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException, UploadFile
|
||||
|
||||
from core.domains import Domain
|
||||
from persistance import config
|
||||
from webapi.models import import_models
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("kind", "status", "detail"),
|
||||
[
|
||||
("wrong_sha", 422, "not the one given"),
|
||||
("non_zip", 422, "not a bundle"),
|
||||
("untrusted", 403, "not trusted on this server"),
|
||||
],
|
||||
)
|
||||
def test_import_rejects_invalid_uploads(tmp_path, monkeypatch, kind, status, detail):
|
||||
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
|
||||
if kind == "non_zip":
|
||||
data = b"hello"
|
||||
else:
|
||||
buffer = BytesIO()
|
||||
with ZipFile(buffer, "w") as archive:
|
||||
archive.writestr("manifest.json", "{}")
|
||||
data = buffer.getvalue()
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
sent = "0" * 64 if kind == "wrong_sha" else digest
|
||||
|
||||
with pytest.raises(HTTPException) as rejected:
|
||||
import_models(Domain.TEA, sent, UploadFile(BytesIO(data), filename="bundle.zip"))
|
||||
assert rejected.value.status_code == status
|
||||
assert detail in rejected.value.detail
|
||||
assert not (tmp_path / "bundles" / f"{digest}.zip").exists()
|
||||
@@ -0,0 +1,161 @@
|
||||
import pytest
|
||||
from dagster import DagsterRunStatus
|
||||
from fastapi import HTTPException
|
||||
|
||||
from persistance.cluster import Progress
|
||||
from webapi.runs import _locked, cancel_run, shape
|
||||
|
||||
PAYLOAD = {
|
||||
"runId": "run",
|
||||
"jobName": "analyze",
|
||||
"status": "SUCCESS",
|
||||
"startTime": 1.0,
|
||||
"endTime": 4.0,
|
||||
"tags": [{"key": "domain", "value": "cacu"}],
|
||||
}
|
||||
|
||||
|
||||
def test_shape_splits_info_and_warnings():
|
||||
def event(level, message, step_key=None, kind="LogMessageEvent"):
|
||||
return {"__typename": kind, "level": level, "message": message, "stepKey": step_key}
|
||||
|
||||
run = shape(
|
||||
PAYLOAD,
|
||||
[
|
||||
event("INFO", "starting"),
|
||||
event("WARNING", "skipped", "analyze_studies"),
|
||||
event("DEBUG", "debug"),
|
||||
event("INFO", "engine", kind="EngineEvent"),
|
||||
event("INFO", "finished", "analyze_studies"),
|
||||
],
|
||||
)
|
||||
assert run.info == ["starting", "analyze_studies: finished"]
|
||||
assert run.warnings == ["analyze_studies: skipped"]
|
||||
assert run.error is None
|
||||
|
||||
warning_only = shape(PAYLOAD, [event("WARNING", "skipped")])
|
||||
assert warning_only.state == "succeeded"
|
||||
assert warning_only.error is None
|
||||
|
||||
steps = [
|
||||
{"stepKey": "waiting", "status": "SKIPPED", "startTime": None, "endTime": None},
|
||||
{"stepKey": "second", "status": "SUCCESS", "startTime": 2, "endTime": 4},
|
||||
{"stepKey": "first", "status": "SUCCESS", "startTime": 0, "endTime": 1},
|
||||
]
|
||||
assert [step.key for step in shape(PAYLOAD | {"stepStats": steps}, []).steps] == [
|
||||
"first", "second", "waiting",
|
||||
] # fmt: skip
|
||||
|
||||
capped = shape(
|
||||
PAYLOAD, [event(level, str(i)) for i in range(201) for level in ("INFO", "WARNING")]
|
||||
)
|
||||
assert capped.info == [str(i) for i in range(1, 201)]
|
||||
assert capped.warnings == [str(i) for i in range(200)]
|
||||
|
||||
|
||||
def test_shape_failure_message_is_the_ops_own_exception():
|
||||
failed = PAYLOAD | {"status": "FAILURE"}
|
||||
step_failure = {
|
||||
"__typename": "ExecutionStepFailureEvent",
|
||||
"error": {
|
||||
"message": "DagsterExecutionStepExecutionError: invocation failed",
|
||||
"causes": [
|
||||
{"message": "intermediate cause"},
|
||||
{"message": " LookupError: no EEG x|2026-01-01\nmore details "},
|
||||
],
|
||||
},
|
||||
}
|
||||
assert shape(failed, [step_failure]).error == "LookupError: no EEG x|2026-01-01"
|
||||
run_failure = {"__typename": "RunFailureEvent", "error": {"message": "x" * 501}}
|
||||
assert shape(failed, [step_failure, run_failure]).error == "x" * 500
|
||||
assert shape(failed, []).error == "the run failed"
|
||||
|
||||
|
||||
def test_shape_progress_tag():
|
||||
progress = Progress(
|
||||
phase="analyzing", done=3, total=6, elapsed_s=4, eta_s=4, mode="sync",
|
||||
scheduler=None, updated_at="2026-01-01T00:00:00Z",
|
||||
) # fmt: skip
|
||||
|
||||
def with_tag(value):
|
||||
return PAYLOAD | {"tags": [{"key": "isssteleon/progress", "value": value}]}
|
||||
|
||||
run = shape(with_tag(progress.model_dump_json()), [])
|
||||
assert run.progress is not None
|
||||
assert run.progress.done == 3
|
||||
assert run.progress.phase == "analyzing"
|
||||
assert shape(with_tag("{bad json"), []).progress is None
|
||||
for status, state in (
|
||||
("QUEUED", "queued"),
|
||||
("STARTING", "running"),
|
||||
("CANCELING", "cancelling"),
|
||||
("CANCELED", "cancelled"),
|
||||
):
|
||||
run = shape(PAYLOAD | {"status": status}, [])
|
||||
assert (run.status, run.state) == (status, state)
|
||||
assert shape(PAYLOAD | {"status": "UNKNOWN"}, []).state == "running"
|
||||
|
||||
|
||||
def test_shape_outputs():
|
||||
events = [
|
||||
{
|
||||
"__typename": "ExecutionStepOutputEvent",
|
||||
"stepKey": "preview_study",
|
||||
"outputName": "result",
|
||||
"metadataEntries": [
|
||||
{"label": "result", "jsonString": '{"eeg": {"valid": false}}'},
|
||||
{"label": "text"},
|
||||
],
|
||||
},
|
||||
]
|
||||
assert shape(PAYLOAD, events, outputs=True).outputs == {
|
||||
"preview_study.result": {"eeg": {"valid": False}}
|
||||
}
|
||||
assert shape(PAYLOAD, events, outputs=False).outputs is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("initial", [DagsterRunStatus.QUEUED, DagsterRunStatus.STARTED])
|
||||
def test_cancel_returns_the_terminal_or_cancelling_state(initial):
|
||||
class Client:
|
||||
status = initial
|
||||
|
||||
def get_run_status(self, run_id):
|
||||
return self.status
|
||||
|
||||
def terminate_run(self, run_id):
|
||||
self.status = {
|
||||
DagsterRunStatus.QUEUED: DagsterRunStatus.CANCELED,
|
||||
DagsterRunStatus.STARTED: DagsterRunStatus.CANCELING,
|
||||
}[self.status]
|
||||
|
||||
result = cancel_run("r1", client=Client())
|
||||
expected = (
|
||||
("CANCELED", "cancelled")
|
||||
if initial == DagsterRunStatus.QUEUED
|
||||
else ("CANCELING", "cancelling")
|
||||
)
|
||||
assert (result.id, result.status, result.state) == ("r1", *expected)
|
||||
|
||||
|
||||
def test_cancel_a_finished_run_is_409():
|
||||
class Client:
|
||||
def get_run_status(self, run_id):
|
||||
return DagsterRunStatus.SUCCESS
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
cancel_run("r1", client=Client())
|
||||
assert error.value.status_code == 409
|
||||
assert error.value.detail == "the run already ended: succeeded"
|
||||
|
||||
|
||||
def test_a_storage_lock_is_distinguished_from_a_run_failure():
|
||||
assert _locked({"errors": [{"message": "OperationalError: database is locked"}]})
|
||||
assert _locked(
|
||||
{"data": {"logsForRun": {"__typename": "PythonError", "message": "database is locked"}}}
|
||||
)
|
||||
assert not _locked(
|
||||
{"data": {"logsForRun": {"__typename": "EventConnection", "message": "database is locked"}}}
|
||||
)
|
||||
assert not _locked(
|
||||
{"data": {"logsForRun": {"__typename": "PythonError", "message": "unknown error"}}}
|
||||
)
|
||||
@@ -0,0 +1,140 @@
|
||||
import sqlite3
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from webapi import sources
|
||||
from webapi.main import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(own_platform, monkeypatch):
|
||||
monkeypatch.setenv("SOURCE_ROOTS", str(own_platform / "shared"))
|
||||
(own_platform / "shared" / "reportes" / "2026").mkdir(parents=True)
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
|
||||
|
||||
def probe(client, kind, **answers):
|
||||
response = client.post("/ingest/sources/test", json={"type": kind, "answers": answers})
|
||||
assert response.status_code == 200, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def test_the_dialog_lists_every_kind_with_its_questions(client):
|
||||
found = client.get("/ingest/sources/types").json()
|
||||
assert {"database", "files", "cloud", "web"} <= set(found["groups"])
|
||||
assert found["types"]["sqlserver"]["fields"]["password"]["type"] == "password"
|
||||
|
||||
|
||||
def test_an_unknown_server_and_a_missing_answer_say_so_plainly(client):
|
||||
gone = probe(client, "sqlserver", host="nowhere.invalid", database="P", user="u",
|
||||
password="p") # fmt: skip
|
||||
assert not gone["ok"] and gone["message"].startswith(("No se encontró", "El servidor no"))
|
||||
assert probe(client, "postgresql", host="h")["message"].startswith("falta «Base de datos»")
|
||||
|
||||
|
||||
def test_a_sqlite_file_lists_its_tables_then_shows_rows(client, own_platform):
|
||||
path = own_platform / "shared" / "hospital.db"
|
||||
with sqlite3.connect(path) as con:
|
||||
con.execute("create table pacientes (id int, nombre text)")
|
||||
con.execute("insert into pacientes values (1, 'Ana')")
|
||||
assert probe(client, "sqlite", path=str(path))["tables"] == ["pacientes"]
|
||||
rows = probe(client, "sqlite", path=str(path), table="pacientes")["rows"]
|
||||
assert rows == [{"id": 1, "nombre": "Ana"}]
|
||||
|
||||
|
||||
def test_server_folders_are_browsed_only_under_the_mounted_roots(client, own_platform):
|
||||
roots = client.get("/ingest/sources/browse").json()["entries"]
|
||||
assert [e["name"] for e in roots] == ["shared"]
|
||||
inside = client.get("/ingest/sources/browse", params={"path": roots[0]["path"]}).json()
|
||||
assert [e["name"] for e in inside["entries"]] == ["reportes"]
|
||||
assert client.get("/ingest/sources/browse", params={"path": "/etc"}).status_code == 404
|
||||
escape = str(own_platform / "shared" / ".." / "data")
|
||||
assert client.get("/ingest/sources/browse", params={"path": escape}).status_code == 404
|
||||
|
||||
|
||||
def test_a_folder_uploaded_from_a_computer_is_read_as_spreadsheets_or_documents(client):
|
||||
sent = [("files", ("informes/enero/a.csv", b"folio,resultado\n1,NEGATIVO\n")),
|
||||
("files", ("informes/b.pdf", b"%PDF-1.4 ..."))] # fmt: skip
|
||||
uploaded = client.post("/ingest/uploads", files=sent).json()
|
||||
assert sorted(uploaded["files"]) == ["informes/b.pdf", "informes/enero/a.csv"]
|
||||
more = client.post("/ingest/uploads", files=[("files", ("../../fuera.csv", b"x\n"))],
|
||||
data={"folder": uploaded["bucket_url"]}).json() # fmt: skip
|
||||
assert more["files"] == ["fuera.csv"] and more["bucket_url"] == uploaded["bucket_url"]
|
||||
other = client.post("/ingest/uploads", files=[("files", ("x", b"x"))], data={"folder": "/"})
|
||||
assert other.status_code == 422
|
||||
rows = probe(client, "upload", folder=uploaded["bucket_url"], pattern="**/*.csv",
|
||||
read_as="dlt.sources.filesystem:read_csv")["rows"] # fmt: skip
|
||||
assert rows == [{"folio": 1, "resultado": "NEGATIVO"}]
|
||||
files = probe(client, "upload", folder=uploaded["bucket_url"], pattern="**/*.pdf")["rows"]
|
||||
assert [f["file_name"] for f in files] == ["b.pdf"]
|
||||
|
||||
|
||||
def test_an_empty_folder_says_what_to_check(client, own_platform):
|
||||
found = probe(client, "server_folder", folder=str(own_platform / "shared" / "reportes"))
|
||||
assert found["ok"] and "Revise la ruta" in found["message"]
|
||||
|
||||
|
||||
def test_a_sign_in_button_without_an_app_registration_says_who_must_register_one(client):
|
||||
found = client.get("/ingest/sources/oauth/google/start", params={"origin": "http://x"})
|
||||
assert found.status_code == 503 and "GOOGLE_CLIENT_ID" in found.json()["detail"]
|
||||
|
||||
|
||||
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
|
||||
|
||||
monkeypatch.setenv("MICROSOFT_CLIENT_ID", "app")
|
||||
monkeypatch.setenv("MICROSOFT_CLIENT_SECRET", "app-secret")
|
||||
exchanged = {}
|
||||
|
||||
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
|
||||
|
||||
def client_for(found, env, redirect_uri):
|
||||
return OAuth2Client(env["client_id"], env["client_secret"], scope=found.scope,
|
||||
redirect_uri=redirect_uri, code_challenge_method="S256",
|
||||
transport=httpx.MockTransport(provider)) # fmt: skip
|
||||
|
||||
monkeypatch.setattr(sources, "_client", client_for)
|
||||
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
|
||||
start = client.get("/ingest/sources/oauth/microsoft/start",
|
||||
params={"origin": "http://10.0.10.41:5710"}).json() # fmt: skip
|
||||
assert start["url"].startswith("https://login.microsoftonline.com/organizations/")
|
||||
assert "code_challenge=" in start["url"] and "client_id=app" in start["url"]
|
||||
back = client.get("/ingest/sources/oauth/microsoft/callback",
|
||||
params={"state": start["state"], "code": "c0de"}) # fmt: skip
|
||||
assert back.status_code == 200
|
||||
assert '"user": "ana@hospital.mx"' in back.text and '"http://10.0.10.41:5710"' in back.text
|
||||
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
|
||||
|
||||
|
||||
def test_a_saved_account_shows_who_but_never_its_tokens():
|
||||
from core.pipeline import MASK, Pipeline, redacted, restored
|
||||
|
||||
params = {"client_id": "app", "client_secret": "app-secret-xyz",
|
||||
"token": {"refresh_token": "refresh-xyz"}} # fmt: skip
|
||||
account = {"user": "ana@hospital.mx", "drive_id": "d1", "oauth2_client_params": params}
|
||||
saved = Pipeline(nodes=[{"id": "s", "kind": "source", "guided": {
|
||||
"type": "onedrive", "answers": {"account": account, "folder": "Reportes"}}}]) # fmt: skip
|
||||
shown = redacted(saved)
|
||||
answer = shown.nodes[0].guided.answers["account"]
|
||||
assert answer["user"] == "ana@hospital.mx"
|
||||
dumped = shown.model_dump_json()
|
||||
assert "refresh-xyz" not in dumped and "app-secret-xyz" not in dumped
|
||||
assert answer["oauth2_client_params"]["client_secret"] == MASK
|
||||
back = restored(Pipeline.model_validate(shown.model_dump()), saved).nodes[0]
|
||||
assert (
|
||||
back.args["storage_options"]["oauth2_client_params"]["token"]["refresh_token"]
|
||||
== "refresh-xyz"
|
||||
)
|
||||
@@ -0,0 +1,110 @@
|
||||
import pytest
|
||||
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
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def sync_execution(monkeypatch):
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
|
||||
|
||||
def test_tea_training_config_schema():
|
||||
config = training_config(Domain.TEA, "example").model_dump()
|
||||
assert (config["domain"], config["name"]) == ("tea", "example")
|
||||
schema = config["json_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",
|
||||
"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["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"},
|
||||
}
|
||||
|
||||
|
||||
def test_other_domains_have_no_training_source():
|
||||
for domain in ("cacu", "cama"):
|
||||
config = training_config(Domain(domain), "example").model_dump()
|
||||
assert (config["domain"], config["name"]) == (domain, "example")
|
||||
schema = config["json_schema"]
|
||||
assert set(schema["properties"]) == {"as_of", "execution"}
|
||||
assert set(schema["$defs"]) == {"Execution"}
|
||||
assert config["defaults"] == {"execution": {"mode": "sync", "scheduler": None}}
|
||||
|
||||
|
||||
def test_train_validates_the_training_source():
|
||||
with pytest.raises(HTTPException) as rejected:
|
||||
train(Domain.CACU, Training(source={"kind": "site"}))
|
||||
assert rejected.value.status_code == 422
|
||||
assert rejected.value.detail == "cacu models take no training source"
|
||||
|
||||
for source in (
|
||||
{"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": "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"}
|
||||
@@ -0,0 +1,46 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from webapi.main import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(own_platform, monkeypatch):
|
||||
monkeypatch.setenv("AUTH_ADMIN_EMAIL", "admin@isssteleon.mx")
|
||||
monkeypatch.setenv("AUTH_ADMIN_PASSWORD", "una-clave-larga")
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
|
||||
|
||||
def login(client, email, password):
|
||||
return client.post("/auth/login", data={"username": email, "password": password})
|
||||
|
||||
|
||||
def test_the_first_administrator_signs_in_and_adds_a_team(client):
|
||||
assert client.get("/users/me").status_code == 401
|
||||
assert login(client, "admin@isssteleon.mx", "mala").status_code == 400
|
||||
assert login(client, "admin@isssteleon.mx", "una-clave-larga").status_code == 204
|
||||
me = client.get("/users/me").json()
|
||||
assert me["is_superuser"] and me["domains"] == ["cacu", "cama", "tea"]
|
||||
team = {"email": "cacu@isssteleon.mx", "password": "equipo-cacu", "name": "Equipo CaCu",
|
||||
"domains": ["cacu"]} # fmt: skip
|
||||
assert client.post("/users/register", json=team).status_code == 201
|
||||
client.post("/auth/logout")
|
||||
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
|
||||
|
||||
|
||||
def test_the_api_answers_without_a_session(client):
|
||||
for path in ("/health", "/domains", "/ingest/schema", "/ingest/sources/types"):
|
||||
assert client.get(path).status_code == 200, path
|
||||
|
||||
|
||||
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):
|
||||
pass
|
||||
assert (own_platform / "auth_secret").read_text() == secret
|
||||
assert client.get("/users/me").status_code == 200
|
||||
@@ -0,0 +1,178 @@
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import time
|
||||
from contextlib import closing, contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from models.tea.jobs import ASSOCIATION, MODELS
|
||||
from synthetic import tea
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
FIXTURES = ROOT / "tests" / "fixtures"
|
||||
|
||||
|
||||
def _ok(response: httpx.Response):
|
||||
assert response.status_code == 200, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def _port() -> int:
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def _until_up(url: str, process: subprocess.Popen, seconds: int = 180) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
assert process.poll() is None, f"{process.args[0]} exited with {process.returncode}"
|
||||
try:
|
||||
if httpx.get(url, timeout=2).status_code == 200:
|
||||
return
|
||||
except httpx.TransportError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise TimeoutError(url)
|
||||
|
||||
|
||||
def _wait(api: httpx.Client, run_id: str, seconds: int = 1800) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while (run := _ok(api.get(f"/runs/{run_id}")))["state"] not in ("succeeded", "failed"):
|
||||
assert time.monotonic() < deadline, f"run {run_id} still {run['state']}"
|
||||
time.sleep(2)
|
||||
assert run["state"] == "succeeded", run.get("error")
|
||||
|
||||
|
||||
def _sensor_run(api: httpx.Client, seconds: int = 300) -> str:
|
||||
deadline = time.monotonic() + seconds
|
||||
while not (runs := _ok(api.get("/runs", params={"job": "tea_eeg", "domain": "tea"}))):
|
||||
assert time.monotonic() < deadline, "the sensor started no tea_eeg run"
|
||||
time.sleep(2)
|
||||
return runs[0]["id"]
|
||||
|
||||
|
||||
def _train_tea(api: httpx.Client) -> None:
|
||||
_wait(api, _ok(api.post("/tea/eegs/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("/tea/eegs/analyze", json={}))["run_id"])
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _platform(data: Path):
|
||||
from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore
|
||||
|
||||
(data / "dagster").mkdir(parents=True)
|
||||
(data / "reference").mkdir()
|
||||
shutil.copy(ROOT / "dagster.yaml", data / "dagster")
|
||||
tracking = f"sqlite:///{data / 'mlflow.db'}"
|
||||
SqlAlchemyStore(tracking, (data / "mlflow").as_uri()).engine.dispose()
|
||||
dagster_port, api_port = _port(), _port()
|
||||
env = {
|
||||
**os.environ,
|
||||
"ISSSTELEON_DATA": str(data),
|
||||
"DLT_DATA_DIR": str(data / "dlt"),
|
||||
"DAGSTER_HOME": str(data / "dagster"),
|
||||
"DAGSTER_HOST": "127.0.0.1",
|
||||
"DAGSTER_PORT": str(dagster_port),
|
||||
"MLFLOW_TRACKING_URI": tracking,
|
||||
"MLFLOW_DISABLE_AGENT_HINT": "1",
|
||||
"EXECUTION_MODE": "sync",
|
||||
"TEA_REFERENCE_ROOT": str(data / "reference"),
|
||||
"AUTH_ADMIN_EMAIL": "admin@isssteleon.mx",
|
||||
"AUTH_ADMIN_PASSWORD": "solo-para-pruebas",
|
||||
}
|
||||
webserver = subprocess.Popen(
|
||||
["dagster-webserver", "-m", "models.definitions", "-h", "127.0.0.1",
|
||||
"-p", str(dagster_port)], env=env, cwd=data,
|
||||
) # fmt: skip
|
||||
server = subprocess.Popen(
|
||||
["fastapi", "run", str(ROOT / "WebApi" / "webapi" / "main.py"), "--host", "127.0.0.1",
|
||||
"--port", str(api_port)], env=env, cwd=data,
|
||||
) # fmt: skip
|
||||
daemon = None
|
||||
try:
|
||||
_until_up(f"http://127.0.0.1:{dagster_port}/server_info", webserver)
|
||||
daemon = subprocess.Popen(
|
||||
["dagster-daemon", "run", "-m", "models.definitions"], env=env, cwd=data
|
||||
)
|
||||
_until_up(f"http://127.0.0.1:{api_port}/health", server)
|
||||
with httpx.Client(base_url=f"http://127.0.0.1:{api_port}", timeout=120) as client:
|
||||
yield client
|
||||
finally:
|
||||
for process in (server, daemon, webserver):
|
||||
if process is not None:
|
||||
process.terminate()
|
||||
process.wait(timeout=30)
|
||||
|
||||
|
||||
def _study_files(db: Path, out: Path) -> dict[str, str]:
|
||||
out.mkdir()
|
||||
with closing(sqlite3.connect(db)) as con:
|
||||
edf, report, birth = con.execute(
|
||||
"SELECT eeg_estudio, ord_pdf_blob, pac_fecha_nacimiento FROM eeg "
|
||||
"JOIN pacientes ON pac_id = eeg_pac_id "
|
||||
"JOIN ados2 ON ado_pac_id = eeg_pac_id "
|
||||
"JOIN ordenes_estudio ON ord_id = ado_ord_id ORDER BY eeg_id LIMIT 1"
|
||||
).fetchone()
|
||||
(out / "study.edf").write_bytes(edf)
|
||||
(out / "ados2.pdf").write_bytes(report)
|
||||
return {
|
||||
"TEA_EDF": str(out / "study.edf"),
|
||||
"TEA_ADOS2": str(out / "ados2.pdf"),
|
||||
"TEA_BIRTH": birth,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.webapp
|
||||
def test_the_tea_pages_load_from_the_synthetic_hospital(tmp_path):
|
||||
hospital = tmp_path / "hospital"
|
||||
hospital.mkdir()
|
||||
tea.build(hospital / "hospital_tea.db")
|
||||
files = _study_files(hospital / "hospital_tea.db", tmp_path / "files")
|
||||
concept_map = json.loads((FIXTURES / "concept_maps" / "hospital_tea.json").read_text())
|
||||
drawn = (FIXTURES / "pipelines" / "hospital_tea.json").read_text()
|
||||
pipeline = json.loads(drawn.replace("{hospital}", str(hospital)))
|
||||
with _platform(tmp_path / "platform") as api:
|
||||
_ok(api.put("/ingest/concept-maps/hospital_tea", json=concept_map))
|
||||
_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("/")},
|
||||
) # fmt: skip
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
|
||||
+28
-32
@@ -1,6 +1,12 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from persistance import eeg
|
||||
from persistance.cluster import Execution
|
||||
from persistance.eeg import Scope
|
||||
from webapi.runs import dagster, execution_config, submit
|
||||
|
||||
router = APIRouter(prefix="/tea/eegs", tags=["eeg"])
|
||||
|
||||
@@ -15,42 +21,12 @@ class Study(BaseModel):
|
||||
level: str | None
|
||||
|
||||
|
||||
class Site(BaseModel):
|
||||
site: str
|
||||
value: float
|
||||
z: float | None
|
||||
|
||||
|
||||
class Metric(BaseModel):
|
||||
code: str
|
||||
value: float
|
||||
z: float | None
|
||||
outside: float | None
|
||||
p5: float | None = None
|
||||
median: float | None = None
|
||||
p95: float | None = None
|
||||
model: str | None
|
||||
zones: list[Site] = []
|
||||
electrodes: list[Site] = []
|
||||
|
||||
|
||||
class Relation(BaseModel):
|
||||
biomarker: str
|
||||
metric: str
|
||||
zone: str
|
||||
outcome_code: str
|
||||
kind: str
|
||||
event: str
|
||||
z: float
|
||||
probability: float
|
||||
reference_probability: float
|
||||
observed: float | None = None
|
||||
odds_ratio: float
|
||||
ci_low: float | None
|
||||
ci_high: float | None
|
||||
q: float | None
|
||||
n: float
|
||||
model: str
|
||||
|
||||
|
||||
class Analysis(BaseModel):
|
||||
@@ -59,7 +35,13 @@ class Analysis(BaseModel):
|
||||
level: str | None
|
||||
age_months: float | None
|
||||
metrics: list[Metric]
|
||||
relation: list[Relation] = []
|
||||
checks: list[dict[str, Any]]
|
||||
regions: list[dict[str, Any]]
|
||||
|
||||
|
||||
class AnalyzeRequest(BaseModel):
|
||||
scope: Scope = Scope()
|
||||
execution: Execution | None = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
@@ -67,6 +49,20 @@ def studies() -> list[Study]:
|
||||
return [Study(**s) for s in eeg.studies()]
|
||||
|
||||
|
||||
@router.post(
|
||||
"/analyze",
|
||||
description="Starts `tea_eeg`: analyse the EEGs in scope, score the curves, rebuild gold.",
|
||||
)
|
||||
def analyze_eegs(request: AnalyzeRequest, client=Depends(dagster)) -> dict[str, str]:
|
||||
config = {"scope": request.scope.model_dump(), "execution": execution_config(request.execution)}
|
||||
return submit(client, "tea_eeg", "tea_analyze_studies", config, domain="tea")
|
||||
|
||||
|
||||
@router.get("/summary")
|
||||
def eeg_studies_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:
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from persistance import cluster
|
||||
from persistance.cluster import Execution, Health, Mode, Options
|
||||
|
||||
router = APIRouter(prefix="/execution", tags=["execution"])
|
||||
|
||||
|
||||
@router.get("/options")
|
||||
def execution_options() -> Options:
|
||||
return cluster.options()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def execution_health(
|
||||
mode: Mode | None = None, scheduler: str | None = None, reference: str | None = None
|
||||
) -> Health:
|
||||
try:
|
||||
return cluster.health(Execution(mode=mode, scheduler=scheduler), reference)
|
||||
except cluster.ExecutionError as e:
|
||||
raise HTTPException(422, detail=str(e)) from e
|
||||
+382
-233
@@ -1,20 +1,26 @@
|
||||
import operator
|
||||
import unicodedata
|
||||
from collections import defaultdict
|
||||
from datetime import date, datetime
|
||||
from typing import Annotated, Any
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import Response
|
||||
from fhir.resources.R4B.bundle import Bundle
|
||||
from fhir.resources.R4B.capabilitystatement import CapabilityStatement
|
||||
from fhir.resources.R4B.operationoutcome import OperationOutcome
|
||||
from fhir.resources.R4B.parameters import Parameters
|
||||
from fhir.resources.R4B.resource import Resource
|
||||
|
||||
from core import catalog
|
||||
from core import fhir as f
|
||||
from core import measures as m
|
||||
from core.domains import Domain, measures, part
|
||||
from core.follow_up import window_start
|
||||
from core.pipeline import ID_PATTERN
|
||||
from core.tea import fhir as tea_fhir
|
||||
from core.tea.follow_up import FILTERS as TEA_FILTERS
|
||||
from persistance import config_log, readers
|
||||
from persistance import fhir as reads
|
||||
from persistance import measures as measure_reads
|
||||
@@ -22,8 +28,9 @@ from webapi.ingest import submit
|
||||
from webapi.runs import dagster
|
||||
|
||||
FHIR_JSON = "application/fhir+json"
|
||||
PAGE, MAX_PAGE = (50, 200)
|
||||
PAGE, MAX_PAGE = 50, 200
|
||||
REVINCLUDES = ("DiagnosticReport:subject", "RiskAssessment:subject", "Observation:subject")
|
||||
|
||||
router = APIRouter(prefix="/{domain}/fhir", tags=["fhir"])
|
||||
_OK = {200: {"content": {FHIR_JSON: {"schema": {"type": "object"}}}, "description": "FHIR"}}
|
||||
|
||||
@@ -33,16 +40,10 @@ def fhir(resource: Resource) -> Response:
|
||||
|
||||
|
||||
def outcome(status: int, text: str) -> Response:
|
||||
issue = {
|
||||
"severity": "error",
|
||||
"code": "not-found" if status == 404 else "invalid",
|
||||
"diagnostics": text,
|
||||
}
|
||||
return Response(
|
||||
OperationOutcome(issue=[issue]).model_dump_json(exclude_none=True),
|
||||
status_code=status,
|
||||
media_type=FHIR_JSON,
|
||||
)
|
||||
issue = {"severity": "error", "code": "not-found" if status == 404 else "invalid",
|
||||
"diagnostics": text} # fmt: skip
|
||||
return Response(OperationOutcome(issue=[issue]).model_dump_json(exclude_none=True),
|
||||
status_code=status, media_type=FHIR_JSON) # fmt: skip
|
||||
|
||||
|
||||
def _clinical(domain: Domain):
|
||||
@@ -61,22 +62,17 @@ def _page(count: int | None, offset: int) -> tuple[int, int]:
|
||||
count = PAGE if count is None else count
|
||||
if not 0 <= count <= MAX_PAGE or offset < 0:
|
||||
raise HTTPException(422, f"_count goes from 0 to {MAX_PAGE}; _offset from 0")
|
||||
return (count, offset)
|
||||
return count, offset
|
||||
|
||||
|
||||
def bundle(
|
||||
request: Request,
|
||||
matches: list[Resource],
|
||||
total: int,
|
||||
count: int,
|
||||
offset: int,
|
||||
included: list[Resource] = (),
|
||||
applied: dict | None = None,
|
||||
) -> Response:
|
||||
def bundle(request: Request, matches: list[Resource], total: int, count: int, offset: int,
|
||||
included: list[Resource] = (), applied: dict | None = None) -> Response: # fmt: skip
|
||||
base = str(request.base_url).rstrip("/") + request.url.path.rsplit("/", 1)[0]
|
||||
|
||||
def link(relation: str, at: int) -> dict:
|
||||
url = request.url.include_query_params(**applied or {}, _offset=at, _count=count)
|
||||
params = {**(applied or {}), "_offset": at, "_count": count}
|
||||
query = [(k, v) for k, v in request.query_params.multi_items() if k not in params]
|
||||
url = request.url.replace(query=urlencode([*query, *params.items()], doseq=True))
|
||||
return {"relation": relation, "url": str(url)}
|
||||
|
||||
links = [link("self", offset)]
|
||||
@@ -85,21 +81,65 @@ def bundle(
|
||||
if offset > 0:
|
||||
links.append(link("previous", max(offset - count, 0)))
|
||||
groups = (("match", matches), ("include", included))
|
||||
entries = [
|
||||
{
|
||||
"fullUrl": f"{base}/{r.get_resource_type()}/{r.id}",
|
||||
"resource": r,
|
||||
"search": {"mode": mode},
|
||||
}
|
||||
for mode, group in groups
|
||||
for r in group
|
||||
]
|
||||
entries = [{"fullUrl": f"{base}/{r.get_resource_type()}/{r.id}", "resource": r,
|
||||
"search": {"mode": mode}} for mode, group in groups for r in group] # fmt: skip
|
||||
found = Bundle(type="searchset", total=total, link=links, entry=entries or None)
|
||||
return fhir(found)
|
||||
|
||||
|
||||
def _sliced(found: list, count: int, offset: int) -> list:
|
||||
return found[offset : offset + count]
|
||||
return found[offset:offset + count] # fmt: skip
|
||||
|
||||
|
||||
_WINDOW = Query(
|
||||
None,
|
||||
alias="follow-up-window",
|
||||
description="months: the domain's follow-up list over that window up to the cut-off",
|
||||
)
|
||||
_START = Query(
|
||||
None,
|
||||
alias="follow-up-start",
|
||||
description="explicit window start that overrides follow-up-window",
|
||||
)
|
||||
_CUTOFF = Query(None, alias="follow-up-cutoff", description="default: the last day with data")
|
||||
_STATUS = Query(None, alias="follow-up-status")
|
||||
|
||||
|
||||
@router.get(
|
||||
"/Patient/$eeg-summary",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="EEG counts for the follow-up list. Without a window or start, "
|
||||
"use the whole history.",
|
||||
)
|
||||
def eeg_summary(
|
||||
request: Request,
|
||||
domain: Domain,
|
||||
window: int | None = _WINDOW,
|
||||
start: date | None = _START,
|
||||
cutoff: date | None = _CUTOFF,
|
||||
status: str | None = _STATUS,
|
||||
) -> Response:
|
||||
fu = _clinical(domain)
|
||||
if not hasattr(fu, "summary"):
|
||||
return outcome(404, f"no EEG summary for {domain.value}")
|
||||
at = _cutoff(domain, cutoff)
|
||||
try:
|
||||
rows, _, _ = _patient_rows(request, domain, fu, at, window, start, cutoff, status,
|
||||
whole_history=True) # fmt: skip
|
||||
except ValueError as exc:
|
||||
return outcome(422, str(exc))
|
||||
counts = fu.summary(rows)
|
||||
parameters = [
|
||||
{"name": name, "valueInteger": counts[name]}
|
||||
for name in ("valid", "not_valid", "normal", "abnormal")
|
||||
]
|
||||
for entry in counts["by_alteration"]:
|
||||
parameters.append({"name": "by_alteration", "part": [
|
||||
{"name": "alteration", "valueCode": entry["alteration"]},
|
||||
{"name": "patients", "valueInteger": entry["patients"]},
|
||||
]}) # fmt: skip
|
||||
return fhir(Parameters(parameter=parameters))
|
||||
|
||||
|
||||
@router.get("/Patient/{id}", responses=_OK, response_class=Response)
|
||||
@@ -118,7 +158,7 @@ def read_patient(domain: Domain, id: str) -> Response:
|
||||
|
||||
def _with_identity(domain: Domain, rows: list[dict]) -> list[dict]:
|
||||
persons = [r["person_id"] for r in rows]
|
||||
names, ids, replaces = ({}, {}, {})
|
||||
names, ids, replaces = {}, {}, {}
|
||||
for r in reads.rows(domain.value, "names", persons=persons):
|
||||
names.setdefault(r["person_id"], []).append(r["text"])
|
||||
for r in reads.rows(domain.value, "identifiers", persons=persons):
|
||||
@@ -126,66 +166,55 @@ def _with_identity(domain: Domain, rows: list[dict]) -> list[dict]:
|
||||
for r in reads.rows(domain.value, "replaces", persons=persons):
|
||||
replaces.setdefault(r["replaced_by"], []).append(r["person_id"])
|
||||
return [
|
||||
{
|
||||
**r,
|
||||
"names": names.get(p, []),
|
||||
"identifiers": ids.get(p, []),
|
||||
"replaces": replaces.get(p, []),
|
||||
}
|
||||
for r in rows
|
||||
if (p := r["person_id"])
|
||||
]
|
||||
{**r, "names": names.get(p, []), "identifiers": ids.get(p, []),
|
||||
"replaces": replaces.get(p, [])}
|
||||
for r in rows if (p := r["person_id"])
|
||||
] # fmt: skip
|
||||
|
||||
|
||||
def _folded(text: str) -> str:
|
||||
return "".join(
|
||||
(c for c in unicodedata.normalize("NFKD", text.casefold()) if not unicodedata.combining(c))
|
||||
)
|
||||
return "".join(c for c in unicodedata.normalize("NFKD", text.casefold())
|
||||
if not unicodedata.combining(c)) # fmt: skip
|
||||
|
||||
|
||||
def _matches(row: dict, name: str | None, identifier: str | None) -> bool:
|
||||
if name:
|
||||
words = _folded(name).split()
|
||||
if not any(
|
||||
(
|
||||
all((any((w.startswith(q) for w in _folded(n).split())) for q in words))
|
||||
for n in row["names"]
|
||||
)
|
||||
):
|
||||
if not any(all(any(w.startswith(q) for w in _folded(n).split()) for q in words)
|
||||
for n in row["names"]): # fmt: skip
|
||||
return False
|
||||
if identifier:
|
||||
system, _, value = identifier.rpartition("|")
|
||||
if not any(
|
||||
(
|
||||
(not system or s == system) and v.casefold() == value.strip().casefold()
|
||||
for s, v in row["identifiers"]
|
||||
)
|
||||
):
|
||||
if not any((not system or s == system) and v.casefold() == value.strip().casefold()
|
||||
for s, v in row["identifiers"]): # fmt: skip
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
@router.get("/Patient", responses=_OK, response_class=Response)
|
||||
@router.get(
|
||||
"/Patient",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description=(
|
||||
"Patients, or the domain's follow-up list selected by window or start.\n\n"
|
||||
"For TEA, a cutoff or a TEA filter also selects the follow-up list. Patients without\n"
|
||||
"follow-up episodes appear only in the plain search."
|
||||
),
|
||||
)
|
||||
def search_patient(
|
||||
request: Request,
|
||||
domain: Domain,
|
||||
_id: str | None = Query(None, alias="_id"),
|
||||
window: int | None = Query(
|
||||
None,
|
||||
alias="follow-up-window",
|
||||
description="months: the domain's follow-up list over that window up to the cut-off",
|
||||
),
|
||||
cutoff: date | None = Query(
|
||||
None, alias="follow-up-cutoff", description="default: the last day with data"
|
||||
),
|
||||
status: str | None = Query(None, alias="follow-up-status"),
|
||||
window: int | None = _WINDOW,
|
||||
start: date | None = _START,
|
||||
cutoff: date | None = _CUTOFF,
|
||||
status: str | None = _STATUS,
|
||||
name: str | None = Query(
|
||||
None, description="each word starts a word of her name (case and accents ignored)"
|
||||
),
|
||||
identifier: str | None = Query(
|
||||
None, description="[system|]value: a CURP or record number (case ignored)"
|
||||
),
|
||||
birthdate: list[str] = Query([], description="gt, ge, lt or le and a day (2000-12-31)"),
|
||||
sort: str = Query("-recent", alias="_sort", description="-recent or -risk-<outcome>"),
|
||||
horizon: float | None = Query(None, alias="risk-horizon", description="years"),
|
||||
revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"),
|
||||
@@ -197,69 +226,94 @@ def search_patient(
|
||||
count, offset = _page(_count, _offset)
|
||||
at = _cutoff(domain, cutoff)
|
||||
horizon = fu.DEFAULT_HORIZON if horizon is None else horizon
|
||||
persons_rows = reads.rows(domain.value, "persons")
|
||||
if window is None:
|
||||
rows = [{**r, "status": fu.status(r, at)} for r in persons_rows]
|
||||
else:
|
||||
if window not in fu.WINDOWS:
|
||||
raise HTTPException(422, f"follow-up-window is one of {fu.WINDOWS}")
|
||||
try:
|
||||
rows, listed, applied = _patient_rows(
|
||||
request, domain, fu, at, window, start, cutoff, status, sort, _id
|
||||
)
|
||||
except ValueError as exc:
|
||||
return outcome(422, str(exc))
|
||||
if name or identifier:
|
||||
found = {r["person_id"] for r in _with_identity(domain, rows)
|
||||
if _matches(r, name, identifier)} # fmt: skip
|
||||
rows = [r for r in rows if r["person_id"] in found]
|
||||
persons = [r["person_id"] for r in rows]
|
||||
risks: dict[str, list[dict]] = {}
|
||||
if domain != Domain.TEA and (listed and sort != "-recent" or
|
||||
"RiskAssessment:subject" in revinclude): # fmt: skip
|
||||
for r in reads.rows(domain.value, "risk", persons=persons):
|
||||
risks.setdefault(r["person_id"], []).append(r)
|
||||
if listed:
|
||||
rows = fu.ordered(rows, sort, risks, horizon)
|
||||
page = _sliced(rows, count, offset)
|
||||
mine = {r["person_id"] for r in page}
|
||||
included = _included(domain, revinclude, include, sorted(mine), at,
|
||||
{p: v for p, v in risks.items() if p in mine}) # fmt: skip
|
||||
patients = [f.patient(r, fu.STATUS_SYSTEM) for r in _with_identity(domain, page)]
|
||||
return bundle(request, patients, len(rows), count, offset, included,
|
||||
applied) # fmt: skip
|
||||
|
||||
|
||||
def _patient_rows(
|
||||
request: Request,
|
||||
domain: Domain,
|
||||
fu,
|
||||
at: date,
|
||||
window: int | None,
|
||||
start: date | None,
|
||||
cutoff: date | None,
|
||||
status: str | None,
|
||||
sort: str = "-recent",
|
||||
_id: str | None = None,
|
||||
*,
|
||||
whole_history: bool = False,
|
||||
) -> tuple[list[dict], bool, dict]:
|
||||
filters = {
|
||||
name: request.query_params.getlist(name)
|
||||
for name in (TEA_FILTERS if domain == Domain.TEA else ())
|
||||
if name in request.query_params
|
||||
}
|
||||
if filters:
|
||||
fu.matches({}, filters)
|
||||
listed = (
|
||||
whole_history
|
||||
or start is not None
|
||||
or window is not None
|
||||
or bool(filters)
|
||||
or (hasattr(fu, "FILTERS") and cutoff is not None)
|
||||
)
|
||||
persons = reads.rows(domain.value, "persons")
|
||||
applied = {}
|
||||
if listed:
|
||||
if sort not in fu.SORTS:
|
||||
raise HTTPException(422, f"_sort is one of {fu.SORTS}")
|
||||
start = window_start(at, window)
|
||||
if start is None and window is not None:
|
||||
if window not in fu.WINDOWS:
|
||||
raise HTTPException(422, f"follow-up-window is one of {fu.WINDOWS}")
|
||||
start = window_start(at, window)
|
||||
start = start or date.min
|
||||
params = {"start": start.isoformat(), "cutoff": at.isoformat()}
|
||||
person = {r["person_id"]: r for r in persons_rows}
|
||||
person = {r["person_id"]: r for r in persons}
|
||||
rows = [
|
||||
{**person[r["person_id"]], **r}
|
||||
for r in fu.listed(reads.rows(domain.value, "follow_up", **params), start, at)
|
||||
]
|
||||
if _id:
|
||||
rows = [r for r in rows if r["person_id"] in _id.split(",")]
|
||||
applied = {"follow-up-cutoff": at.isoformat(), **filters}
|
||||
else:
|
||||
rows = [{**r, "status": fu.status(r, at)} for r in persons]
|
||||
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 birthdate:
|
||||
rows = [r for r in rows if all((_born(r, b) for b in birthdate))]
|
||||
if name or identifier:
|
||||
found = {
|
||||
r["person_id"] for r in _with_identity(domain, rows) if _matches(r, name, identifier)
|
||||
}
|
||||
rows = [r for r in rows if r["person_id"] in found]
|
||||
persons = [r["person_id"] for r in rows]
|
||||
risks: dict[str, list[dict]] = {}
|
||||
if window is not None and sort != "-recent" or "RiskAssessment:subject" in revinclude:
|
||||
for r in reads.rows(domain.value, "risk", persons=persons):
|
||||
risks.setdefault(r["person_id"], []).append(r)
|
||||
if window is not None:
|
||||
rows = fu.ordered(rows, sort, risks, horizon)
|
||||
page = _sliced(rows, count, offset)
|
||||
mine = {r["person_id"] for r in page}
|
||||
included = _included(
|
||||
domain, revinclude, include, sorted(mine), at, {p: v for p, v in risks.items() if p in mine}
|
||||
)
|
||||
applied = {"follow-up-cutoff": at.isoformat()} if window is not None else None
|
||||
patients = [f.patient(r, fu.STATUS_SYSTEM) for r in _with_identity(domain, page)]
|
||||
return bundle(request, patients, len(rows), count, offset, included, applied)
|
||||
if filters:
|
||||
rows = [r for r in rows if fu.matches(r, filters)]
|
||||
return rows, listed, applied
|
||||
|
||||
|
||||
_COMPARE = {"gt": operator.gt, "ge": operator.ge, "lt": operator.lt, "le": operator.le}
|
||||
|
||||
|
||||
def _born(row: dict, asked: str) -> bool:
|
||||
try:
|
||||
compare, day = (_COMPARE[asked[:2]], date.fromisoformat(asked[2:]))
|
||||
except (KeyError, ValueError):
|
||||
raise HTTPException(422, "birthdate is gt, ge, lt or le and a day") from None
|
||||
return row["birth_date"] is not None and compare(str(row["birth_date"])[:10], str(day))
|
||||
|
||||
|
||||
def _included(
|
||||
domain: Domain,
|
||||
revinclude: list[str],
|
||||
include: list[str],
|
||||
persons: list[str],
|
||||
at: date,
|
||||
risks: dict[str, list[dict]],
|
||||
) -> list[Resource]:
|
||||
unknown = set(revinclude) - set(REVINCLUDES) | set(include) - {"DiagnosticReport:result"}
|
||||
def _included(domain: Domain, revinclude: list[str], include: list[str], persons: list[str],
|
||||
at: date, risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip
|
||||
allowed = _revincludes(domain)
|
||||
unknown = set(revinclude) - set(allowed) | set(include) - {"DiagnosticReport:result"}
|
||||
if unknown:
|
||||
raise HTTPException(422, f"cannot include {sorted(unknown)}")
|
||||
found: list[Resource] = []
|
||||
@@ -270,13 +324,23 @@ def _included(
|
||||
if reports or observations:
|
||||
for r in _studies(domain, persons, at.isoformat()):
|
||||
kind = r.get_resource_type()
|
||||
if kind == "DiagnosticReport" and reports or (kind == "Observation" and observations):
|
||||
if (kind == "DiagnosticReport" and reports) or (kind == "Observation" and observations):
|
||||
found.append(r)
|
||||
if "Condition:subject" in revinclude:
|
||||
found += [f.condition(r) for r in reads.rows(domain.value, "condition", persons=persons,
|
||||
cutoff=at.isoformat())] # fmt: skip
|
||||
if "RiskAssessment:subject" in revinclude:
|
||||
found += _risk_assessments([r for p in persons for r in risks.get(p, [])])
|
||||
if domain == Domain.TEA:
|
||||
found += _tea_risks(persons, at.isoformat())
|
||||
else:
|
||||
found += _risk_assessments([r for p in persons for r in risks.get(p, [])])
|
||||
return found
|
||||
|
||||
|
||||
def _revincludes(domain: Domain) -> tuple[str, ...]:
|
||||
return (*REVINCLUDES, "Condition:subject") if domain == Domain.TEA else REVINCLUDES
|
||||
|
||||
|
||||
def _subjects(subject: str | None) -> list[str]:
|
||||
if not subject:
|
||||
raise HTTPException(422, "subject is required (Patient/<id>, comma-separated)")
|
||||
@@ -286,25 +350,71 @@ def _subjects(subject: str | None) -> list[str]:
|
||||
def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]:
|
||||
found: list[Resource] = []
|
||||
report_facts = _clinical(domain).REPORT_FACTS
|
||||
if domain == Domain.TEA:
|
||||
births = {
|
||||
r["person_id"]: date.fromisoformat(f._day(r["birth_date"])) if r["birth_date"] else None
|
||||
for r in reads.rows(domain.value, "births", persons=persons)
|
||||
}
|
||||
for study in catalog.of_domain(domain.value):
|
||||
spec = catalog.studies()[study]
|
||||
facts = {}
|
||||
if kind := report_facts.get(study):
|
||||
found_facts = reads.rows(domain.value, kind, persons=persons, cutoff=at)
|
||||
facts = {(r["person_id"], str(r["sample_date"])[:10]): r for r in found_facts}
|
||||
first = next((e.date for e in spec.events.values() if e.parent is None))
|
||||
facts = {(r["person_id"], str(r["sample_date"])[:10]): r["days"]
|
||||
for r in found_facts} # fmt: skip
|
||||
first = next(e.date for e in spec.events.values() if e.parent is None)
|
||||
for row in reads.instances(study, persons, at):
|
||||
extra = f.report_facts(facts.get((row["person_id"], str(row[first])[:10]), {}))
|
||||
found += f.instance(study, f.known(study, row, at), extra)
|
||||
days = facts.get((row["person_id"], str(row[first])[:10]))
|
||||
extra = [] if days is None else [f.ext("days-to-diagnosis", "integer", int(days))]
|
||||
known = f.known(study, row, at)
|
||||
found += f.instance(study, known, extra)
|
||||
if domain == Domain.TEA and study == "ados2":
|
||||
known["evaluation_date"] = date.fromisoformat(f._day(known["evaluation_date"]))
|
||||
found.append(tea_fhir.ados2_observation(known, births.get(row["person_id"])))
|
||||
if domain == Domain.TEA:
|
||||
found += _tea_eeg_studies(persons, at)
|
||||
return found
|
||||
|
||||
|
||||
def _tea_eeg_studies(persons: list[str], at: str) -> list[Resource]:
|
||||
def rows(kind):
|
||||
return reads.rows("tea", kind, persons=persons, cutoff=at)
|
||||
|
||||
def key(row):
|
||||
return row["person_id"], row["study_date"], row["edf"]
|
||||
|
||||
regions, results = defaultdict(list), defaultdict(list)
|
||||
for row in rows("regions"):
|
||||
regions[(*key(row), row["code"])].append(row)
|
||||
for row in rows("checks"):
|
||||
results[key(row)].append(tea_fhir.eeg_check(row))
|
||||
for row in rows("metrics"):
|
||||
results[key(row)].append(tea_fhir.eeg_metric(row, regions[(*key(row), row["code"])]))
|
||||
found = []
|
||||
for row in rows("eegs"):
|
||||
observations = results[key(row)]
|
||||
found.extend((tea_fhir.eeg_report(row, observations), *observations))
|
||||
return found
|
||||
|
||||
|
||||
def _tea_risks(persons: list[str], at: str) -> list[Resource]:
|
||||
groups = defaultdict(list)
|
||||
for row in reads.rows("tea", "association_scores", persons=persons, cutoff=at):
|
||||
group = groups[row["person_id"]]
|
||||
if (
|
||||
not group
|
||||
or row["edf"] == group[0]["edf"]
|
||||
and row["study_date"] == group[0]["study_date"]
|
||||
):
|
||||
group.append(row)
|
||||
return [tea_fhir.association_risk(group) for group in groups.values()]
|
||||
|
||||
|
||||
def _risk_assessments(rows: list[dict]) -> list[Resource]:
|
||||
groups: dict[tuple, list[dict]] = {}
|
||||
for r in rows:
|
||||
groups.setdefault(
|
||||
(r["model"], r["version"], r["person_id"], str(r["index_date"])), []
|
||||
).append(r)
|
||||
groups.setdefault((r["model"], r["version"], r["person_id"], str(r["index_date"])),
|
||||
[]).append(r) # fmt: skip
|
||||
return [f.risk_assessment(g[0], g) for g in groups.values()]
|
||||
|
||||
|
||||
@@ -316,62 +426,77 @@ def _clinical_search(kind: str, build, request, domain, subject, count, offset):
|
||||
params["cutoff"] = _cutoff(domain, None).isoformat()
|
||||
if kind == "procedure":
|
||||
params["types"] = list(fu.PROCEDURES)
|
||||
found = build(reads.rows(domain.value, kind, **params))
|
||||
if kind == "risk" and domain == Domain.TEA:
|
||||
found = _tea_risks(params["persons"], _cutoff(domain, None).isoformat())
|
||||
else:
|
||||
found = build(reads.rows(domain.value, kind, **params))
|
||||
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
||||
|
||||
|
||||
SUBJECT = "Patient/<id>, comma-separated"
|
||||
|
||||
|
||||
@router.get("/DiagnosticReport", responses=_OK, response_class=Response)
|
||||
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:
|
||||
@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
|
||||
return _study_search("DiagnosticReport", request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
def _study_search(kind: str, request, domain, subject, count, offset) -> Response:
|
||||
_clinical(domain)
|
||||
count, offset = _page(count, offset)
|
||||
persons, at = (_subjects(subject), _cutoff(domain, None).isoformat())
|
||||
persons, at = _subjects(subject), _cutoff(domain, None).isoformat()
|
||||
found = [r for r in _studies(domain, persons, at) if r.get_resource_type() == kind]
|
||||
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
||||
|
||||
|
||||
@router.get("/Encounter", responses=_OK, response_class=Response)
|
||||
def search_encounter(
|
||||
request: Request,
|
||||
domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0),
|
||||
) -> 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
|
||||
return _study_search("Encounter", request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
@router.get("/Observation", responses=_OK, response_class=Response)
|
||||
def search_observation(
|
||||
request: Request,
|
||||
domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0),
|
||||
) -> 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
|
||||
return _study_search("Observation", request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
@router.get("/Condition", responses=_OK, response_class=Response)
|
||||
def search_condition(
|
||||
request: Request,
|
||||
domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0),
|
||||
) -> 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
|
||||
|
||||
def build(rows):
|
||||
return [f.condition(r) for r in rows]
|
||||
@@ -379,14 +504,20 @@ def search_condition(
|
||||
return _clinical_search("condition", build, request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
@router.get("/Procedure", responses=_OK, response_class=Response)
|
||||
def search_procedure(
|
||||
request: Request,
|
||||
domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0),
|
||||
) -> 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
|
||||
|
||||
def build(rows):
|
||||
return [f.procedure(r, domain.value) for r in rows]
|
||||
@@ -394,14 +525,16 @@ def search_procedure(
|
||||
return _clinical_search("procedure", build, request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
@router.get("/RiskAssessment", responses=_OK, response_class=Response)
|
||||
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:
|
||||
@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
|
||||
return _clinical_search("risk", _risk_assessments, request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
@@ -418,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)
|
||||
def search_measure(
|
||||
request: Request, domain: Domain, _count: int | None = Query(None), _offset: int = Query(0)
|
||||
) -> 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
|
||||
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,
|
||||
@@ -462,7 +604,18 @@ def search_measure_report(
|
||||
return bundle(request, reports, len(asked), count, offset)
|
||||
|
||||
|
||||
@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")],
|
||||
@@ -483,16 +636,9 @@ def post_bundle(
|
||||
raise HTTPException(404, f"no pipeline {sender} to place what it sends")
|
||||
readers.receive(sender, bundle)
|
||||
run_id = submit(client, sender)
|
||||
entries = [
|
||||
{
|
||||
"response": {
|
||||
"status": "202 Accepted",
|
||||
"location": f"{e.resource.get_resource_type()}/{e.resource.id}",
|
||||
}
|
||||
}
|
||||
for e in parsed.entry or []
|
||||
if e.resource is not None
|
||||
]
|
||||
entries = [{"response": {"status": "202 Accepted", "location":
|
||||
f"{e.resource.get_resource_type()}/{e.resource.id}"}}
|
||||
for e in parsed.entry or [] if e.resource is not None] # fmt: skip
|
||||
answer = Bundle(type="batch-response", entry=entries or None)
|
||||
found = fhir(answer)
|
||||
found.status_code = 202
|
||||
@@ -500,11 +646,19 @@ def post_bundle(
|
||||
return found
|
||||
|
||||
|
||||
@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:
|
||||
resources: dict[str, dict] = {}
|
||||
system: list[dict] = []
|
||||
clinical = part(domain, "follow_up") is not None
|
||||
fu = part(domain, "follow_up")
|
||||
clinical = fu is not None
|
||||
for route in router.routes:
|
||||
path = route.path.removeprefix(router.prefix)
|
||||
if not path:
|
||||
@@ -512,48 +666,43 @@ def metadata(request: Request, domain: Domain) -> Response:
|
||||
system = [{"code": "batch"}, {"code": "transaction"}]
|
||||
continue
|
||||
_, kind, *rest = path.split("/")
|
||||
if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport" and (not clinical)):
|
||||
if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport"
|
||||
and not clinical): # fmt: skip
|
||||
continue
|
||||
if rest and rest[0].startswith("$"):
|
||||
continue
|
||||
entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []})
|
||||
if kind == "Patient" and (not rest):
|
||||
entry |= {
|
||||
"searchInclude": ["DiagnosticReport:result"],
|
||||
"searchRevInclude": list(REVINCLUDES),
|
||||
}
|
||||
if kind == "Patient" and not rest:
|
||||
entry |= {"searchInclude": ["DiagnosticReport:result"],
|
||||
"searchRevInclude": list(_revincludes(domain))} # fmt: skip
|
||||
if domain == Domain.TEA:
|
||||
entry["searchParam"] += [
|
||||
{"name": name, "type": spec[0]} for name, spec in TEA_FILTERS.items()
|
||||
]
|
||||
entry["interaction"].append({"code": "read" if rest else "search-type"})
|
||||
for param in route.dependant.query_params:
|
||||
name = param.alias
|
||||
if name.startswith("_") and name != "_id":
|
||||
continue
|
||||
declared = f.SEARCH_PARAMETERS.get(name)
|
||||
entry["searchParam"].append(
|
||||
{
|
||||
"name": name,
|
||||
"type": declared[1] if declared else _STANDARD[name],
|
||||
**({"definition": f"{f.BASE}/SearchParameter/{name}"} if declared else {}),
|
||||
}
|
||||
)
|
||||
statement = CapabilityStatement.model_validate(
|
||||
{
|
||||
"resourceType": "CapabilityStatement",
|
||||
"status": "active",
|
||||
"date": date.today().isoformat(),
|
||||
"kind": "instance",
|
||||
"fhirVersion": f.FHIR_VERSION,
|
||||
"format": ["json"],
|
||||
"implementation": {
|
||||
"description": f"ISSSTELEON {domain.value}",
|
||||
"url": str(request.base_url).rstrip("/") + f"/{domain.value}/fhir",
|
||||
},
|
||||
"rest": [
|
||||
{
|
||||
"mode": "server",
|
||||
"resource": [{k: v for k, v in r.items() if v} for r in resources.values()],
|
||||
**({"interaction": system} if system else {}),
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
entry["searchParam"].append({
|
||||
"name": name,
|
||||
"type": declared[1] if declared else _STANDARD[name],
|
||||
**({"definition": f"{f.BASE}/SearchParameter/{name}"} if declared else {}),
|
||||
}) # fmt: skip
|
||||
statement = CapabilityStatement.model_validate({
|
||||
"resourceType": "CapabilityStatement",
|
||||
"status": "active",
|
||||
"date": date.today().isoformat(),
|
||||
"kind": "instance",
|
||||
"fhirVersion": f.FHIR_VERSION,
|
||||
"format": ["json"],
|
||||
"implementation": {"description": f"ISSSTELEON {domain.value}",
|
||||
"url": str(request.base_url).rstrip("/") + f"/{domain.value}/fhir"},
|
||||
"rest": [{"mode": "server",
|
||||
"resource": [{k: v for k, v in r.items() if v} for r in resources.values()],
|
||||
**({"interaction": system} if system else {})}],
|
||||
}) # fmt: skip
|
||||
return fhir(statement)
|
||||
|
||||
|
||||
@@ -561,7 +710,7 @@ _STANDARD = {
|
||||
"_id": "token",
|
||||
"subject": "reference",
|
||||
"measure": "reference",
|
||||
"follow-up-start": "date",
|
||||
"name": "string",
|
||||
"birthdate": "date",
|
||||
"identifier": "token",
|
||||
}
|
||||
|
||||
+52
-28
@@ -1,10 +1,12 @@
|
||||
from typing import Annotated, Any
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||
from fastapi import APIRouter, Depends, HTTPException, Path, Query
|
||||
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
|
||||
@@ -18,11 +20,14 @@ Rows = list[dict[str, Any]]
|
||||
def _from_source(call, *args):
|
||||
try:
|
||||
return call(*args)
|
||||
except Exception as e:
|
||||
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]:
|
||||
return {
|
||||
"pipeline": Pipeline.model_json_schema(),
|
||||
@@ -30,17 +35,10 @@ def schema() -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
class SourceRef(BaseModel):
|
||||
source: ImportPath
|
||||
args: dict[str, Any] = {}
|
||||
|
||||
|
||||
@router.post("/sources/resources")
|
||||
def source_resources(ref: SourceRef) -> list[str]:
|
||||
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:
|
||||
return [nodes.shown(r) for r in _from_source(nodes.preview, node, limit)]
|
||||
|
||||
@@ -55,7 +53,10 @@ 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:
|
||||
if not config_log.latest_version(pipeline_id):
|
||||
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
||||
@@ -63,10 +64,17 @@ def pipeline(pipeline_id: PipelineId, version: int | None = None) -> SavedPipeli
|
||||
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]:
|
||||
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"))):
|
||||
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}")
|
||||
previous = config_log.get(pipeline_id)[1] if config_log.latest_version(pipeline_id) else None
|
||||
try:
|
||||
@@ -76,19 +84,25 @@ 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:
|
||||
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]:
|
||||
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]:
|
||||
try:
|
||||
found = ConceptMap.model_validate({**doc, "resourceType": "ConceptMap"})
|
||||
@@ -103,9 +117,14 @@ class RunRequest(BaseModel):
|
||||
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)
|
||||
pipeline_id: PipelineId,
|
||||
request: RunRequest,
|
||||
client: DagsterGraphQLClient = Depends(dagster),
|
||||
) -> dict[str, str]:
|
||||
if not config_log.latest_version(pipeline_id):
|
||||
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
||||
@@ -122,9 +141,14 @@ 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
|
||||
pipeline_id: PipelineId,
|
||||
node_id: NodeId,
|
||||
limit: Annotated[int, Query(ge=1, le=500)] = 50,
|
||||
) -> Rows:
|
||||
out = []
|
||||
for row in nodes.rows(pipeline_id, node_id):
|
||||
|
||||
+4
-1
@@ -1,8 +1,9 @@
|
||||
from fastapi import Depends, FastAPI, Request
|
||||
from fastapi.exception_handlers import http_exception_handler
|
||||
from starlette.exceptions import HTTPException
|
||||
|
||||
from core.domains import Domain
|
||||
from webapi import eeg, fhir, ingest, models, review, runs, sources, users
|
||||
from webapi import eeg, execution, fhir, ingest, models, preview, review, runs, sources, users
|
||||
from webapi.auth import caller
|
||||
|
||||
app = FastAPI(
|
||||
@@ -16,8 +17,10 @@ app.include_router(ingest.router)
|
||||
app.include_router(sources.router)
|
||||
app.include_router(review.router)
|
||||
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)
|
||||
app.include_router(users.router)
|
||||
|
||||
|
||||
+220
-47
@@ -1,13 +1,18 @@
|
||||
import mimetypes
|
||||
import zipfile
|
||||
from datetime import date
|
||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||
from fastapi import APIRouter, Depends, HTTPException, UploadFile
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from core.domains import Domain
|
||||
from core.models import title
|
||||
from persistance import registry
|
||||
from webapi.runs import dagster
|
||||
from persistance import bundle, cluster, registry
|
||||
from persistance.cluster import Execution, TrainingSource
|
||||
from webapi.runs import dagster, execution_config, submit
|
||||
|
||||
router = APIRouter(prefix="/models", tags=["models"])
|
||||
|
||||
@@ -19,6 +24,7 @@ class Version(BaseModel):
|
||||
metrics: dict[str, float]
|
||||
params: dict[str, str]
|
||||
reports: list[str]
|
||||
status: Literal["champion", "retired", "candidate"]
|
||||
|
||||
|
||||
class Model(BaseModel):
|
||||
@@ -32,6 +38,65 @@ def models(domain: Domain) -> list[Model]:
|
||||
return [Model(name=n.removeprefix(prefix), title=title(n)) for n in registry.names(prefix)]
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{domain}/export",
|
||||
responses={200: {"content": {"application/zip": {}}}},
|
||||
response_class=Response,
|
||||
)
|
||||
def export_models(
|
||||
domain: Domain,
|
||||
names: Annotated[list[str] | None, Query()] = None,
|
||||
versions: bundle.Selection = "champion",
|
||||
) -> Response:
|
||||
try:
|
||||
exported = bundle.export(domain, names, versions)
|
||||
except bundle.Empty as e:
|
||||
raise HTTPException(409, detail=str(e)) from e
|
||||
except bundle.BundleError as e:
|
||||
raise HTTPException(422, detail=str(e)) from e
|
||||
return Response(
|
||||
exported.data,
|
||||
media_type="application/zip",
|
||||
headers={
|
||||
"X-Bundle-Sha256": exported.sha256,
|
||||
"X-Bundle-Versions": ",".join(f"{name}/{v}" for name, v in exported.versions),
|
||||
"Content-Disposition": (
|
||||
f'attachment; filename="{domain}-models-{exported.sha256[:12]}.zip"'
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{domain}/import")
|
||||
def import_models(
|
||||
domain: Domain,
|
||||
sha256: Annotated[str, Query(pattern=r"^[0-9a-fA-F]{64}$")],
|
||||
file: UploadFile,
|
||||
client: DagsterGraphQLClient = Depends(dagster),
|
||||
) -> dict[str, str]:
|
||||
computed, path = bundle.stage(file.file)
|
||||
if computed != sha256.lower():
|
||||
path.unlink(missing_ok=True)
|
||||
raise HTTPException(422, detail=f"the file's SHA-256 is {computed}, not the one given")
|
||||
if not zipfile.is_zipfile(path):
|
||||
path.unlink(missing_ok=True)
|
||||
raise HTTPException(422, detail="not a bundle")
|
||||
if not bundle.trusted(computed):
|
||||
path.unlink(missing_ok=True)
|
||||
raise HTTPException(
|
||||
403,
|
||||
detail=f"bundle {computed} is not trusted on this server: "
|
||||
f"the operator adds its SHA-256 to {bundle.trusted_file()}",
|
||||
)
|
||||
return submit(
|
||||
client,
|
||||
"import_bundle",
|
||||
"import_bundle_files",
|
||||
{"domain": domain.value, "sha256": computed},
|
||||
domain.value,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{domain}/{name}/versions")
|
||||
def versions(domain: Domain, name: str) -> list[Version]:
|
||||
if not (found := registry.versions(f"{domain.value}.{name}")):
|
||||
@@ -39,78 +104,186 @@ def versions(domain: Domain, name: str) -> list[Version]:
|
||||
return [Version(**v) for v in found]
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{domain}/{name}/versions/{version}/reports/{report}",
|
||||
responses={
|
||||
200: {
|
||||
"content": {"application/json": {}, "application/octet-stream": {}},
|
||||
"description": "the report as stored",
|
||||
}
|
||||
},
|
||||
response_class=Response,
|
||||
)
|
||||
@router.get("/{domain}/{name}/versions/{version}/reports/{report}",
|
||||
responses={200: {"content": {"application/json": {}, "application/octet-stream": {}},
|
||||
"description": "the report as stored"}},
|
||||
response_class=Response,
|
||||
description=(
|
||||
"A version's report: the generated ones as JSON (what the "
|
||||
'governance page draws), the\n'
|
||||
'clinical validation as the file the clinical team uploaded.'
|
||||
),
|
||||
) # fmt: skip
|
||||
def read_report(domain: Domain, name: str, version: int, report: str) -> Response:
|
||||
found = registry.report(f"{domain.value}.{name}", version, report)
|
||||
if found is None:
|
||||
raise HTTPException(404, detail=f"{domain.value}.{name} v{version} has no {report}")
|
||||
filename, content = found
|
||||
kind = mimetypes.guess_type(filename)[0] or "application/octet-stream"
|
||||
return Response(
|
||||
content, media_type=kind, headers={"Content-Disposition": f'inline; filename="{filename}"'}
|
||||
)
|
||||
return Response(content, media_type=kind,
|
||||
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:
|
||||
registry.add_report(
|
||||
f"{domain.value}.{name}",
|
||||
version,
|
||||
"clinical_validation",
|
||||
file.filename or "report",
|
||||
file.file.read(),
|
||||
)
|
||||
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:
|
||||
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}
|
||||
|
||||
|
||||
class Training(BaseModel):
|
||||
as_of: date | None = None
|
||||
@router.get("/{domain}/{name}/versions/{version}/checks")
|
||||
def version_checks(domain: Domain, name: str, version: int) -> dict:
|
||||
registered = f"{domain.value}.{name}"
|
||||
try:
|
||||
status = registry.status(registered, version)
|
||||
except registry.UnknownVersion as e:
|
||||
raise HTTPException(404, detail=str(e)) from e
|
||||
checks = registry.checks(registered, version)
|
||||
return {
|
||||
"version": version,
|
||||
"status": status,
|
||||
"checks": checks,
|
||||
"promotable": status != "retired" and all(check["present"] for check in checks),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{domain}/{name}/versions/{version}/retire")
|
||||
def retire(domain: Domain, name: str, version: int) -> dict[str, str]:
|
||||
try:
|
||||
registry.retire(f"{domain.value}.{name}", version)
|
||||
except registry.UnknownVersion as e:
|
||||
raise HTTPException(404, detail=str(e)) from e
|
||||
except ValueError as e:
|
||||
raise HTTPException(409, detail=str(e)) from e
|
||||
return {"status": "retired"}
|
||||
|
||||
|
||||
@router.get("/{domain}/{name}/versions/{version}/lineage")
|
||||
def lineage(domain: Domain, name: str, version: int) -> dict:
|
||||
try:
|
||||
return registry.lineage(f"{domain.value}.{name}", version)
|
||||
except registry.UnknownVersion as e:
|
||||
raise HTTPException(404, detail=str(e)) from e
|
||||
|
||||
|
||||
@router.get("/{domain}/{name}/versions/{version}/curve")
|
||||
def curve(domain: Domain, name: str, version: int, feature: str = "value") -> list[dict]:
|
||||
if domain != Domain.TEA:
|
||||
raise HTTPException(404, detail="no age curve for this model")
|
||||
try:
|
||||
model = registry.load(f"{domain.value}.{name}", version).unwrap_python_model()
|
||||
if not hasattr(model, "curve"):
|
||||
raise HTTPException(404, detail="no age curve for this model")
|
||||
return model.curve(feature, range(16, 37))
|
||||
except KeyError as e:
|
||||
raise HTTPException(404, detail=f"no curve feature {feature!r}") from e
|
||||
except LookupError as e:
|
||||
raise HTTPException(404, detail=str(e)) from e
|
||||
|
||||
|
||||
class TrainingForm(BaseModel):
|
||||
as_of: date | None = Field(
|
||||
None, title="Datos hasta", description="Fecha de corte de los datos (por omisión, hoy)"
|
||||
)
|
||||
execution: Execution | None = None
|
||||
source: TrainingSource | None = Field(None, title="Datos de entrenamiento")
|
||||
|
||||
|
||||
class Training(TrainingForm):
|
||||
models: list[str] = []
|
||||
|
||||
|
||||
def _submit(client: DagsterGraphQLClient, job: str, op: str, config: dict) -> dict[str, str]:
|
||||
try:
|
||||
run_id = client.submit_job_execution(job, run_config={"ops": {op: {"config": config}}})
|
||||
except DagsterGraphQLClientError as e:
|
||||
raise HTTPException(502, detail=str(e)) from e
|
||||
return {"run_id": run_id}
|
||||
class TrainingConfig(BaseModel):
|
||||
domain: str
|
||||
name: str
|
||||
json_schema: dict[str, Any]
|
||||
defaults: dict[str, Any]
|
||||
|
||||
|
||||
@router.post("/{domain}/train")
|
||||
def train(
|
||||
domain: Domain, request: Training, client: DagsterGraphQLClient = Depends(dagster)
|
||||
) -> dict[str, str]:
|
||||
config: dict = {"domain": domain.value}
|
||||
@router.get("/{domain}/{name}/training-config")
|
||||
def training_config(domain: Domain, name: str) -> TrainingConfig:
|
||||
json_schema = TrainingForm.model_json_schema()
|
||||
defaults = {"execution": {"mode": cluster.default_mode(), "scheduler": None}}
|
||||
if domain == Domain.TEA:
|
||||
defaults["source"] = {"kind": "site"}
|
||||
else:
|
||||
del json_schema["properties"]["source"]
|
||||
for definition in ("TrainingSource", "SiteTrainingSource", "FolderTrainingSource"):
|
||||
del json_schema["$defs"][definition]
|
||||
return TrainingConfig(
|
||||
domain=domain.value, name=name, json_schema=json_schema, defaults=defaults
|
||||
)
|
||||
|
||||
|
||||
class Analyze(BaseModel):
|
||||
execution: Execution | None = None
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{domain}/train",
|
||||
description="Starts training a new version of every model of the domain; follow it at /runs.",
|
||||
)
|
||||
def train(domain: Domain, request: Training,
|
||||
client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip
|
||||
if request.source is not None and domain != Domain.TEA:
|
||||
raise HTTPException(422, f"{domain.value} models take no training source")
|
||||
config: dict = {"domain": domain.value, "execution": execution_config(request.execution)}
|
||||
if request.as_of:
|
||||
config["as_of"] = request.as_of.isoformat()
|
||||
if request.models:
|
||||
config["models"] = request.models
|
||||
return _submit(client, "train", "train_models", config)
|
||||
if request.source is not None:
|
||||
config["source"] = request.source.model_dump()
|
||||
return submit(client, "train", "train_models", config, domain=domain.value)
|
||||
|
||||
|
||||
@router.post("/{domain}/analyze")
|
||||
def analyze(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||
return _submit(client, "analyze", "analyze_studies", {"domain": domain.value})
|
||||
@router.post(
|
||||
"/{domain}/analyze",
|
||||
description=(
|
||||
"Starts analysing the studies the domain's models read whole "
|
||||
"(TEA: its EEGs); follow\n"
|
||||
"it at /runs."
|
||||
),
|
||||
)
|
||||
def analyze(
|
||||
domain: Domain,
|
||||
request: Analyze = Analyze(), # noqa: B008
|
||||
client: DagsterGraphQLClient = Depends(dagster),
|
||||
) -> dict[str, str]:
|
||||
config = {"domain": domain.value, "execution": execution_config(request.execution)}
|
||||
return submit(client, "analyze", "analyze_studies", config, domain=domain.value)
|
||||
|
||||
|
||||
@router.post("/{domain}/score")
|
||||
@router.post(
|
||||
"/{domain}/score",
|
||||
description="Starts a risk batch from each model's champion; follow it at /runs.",
|
||||
)
|
||||
def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||
return _submit(client, "score", "score_models", {"domain": domain.value})
|
||||
return submit(client, "score", "score_models", {"domain": domain.value}, domain=domain.value)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
|
||||
from webapi.main import app
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
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,
|
||||
)
|
||||
+61
-13
@@ -1,6 +1,8 @@
|
||||
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
|
||||
from persistance import nodes, review
|
||||
@@ -10,22 +12,43 @@ 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:
|
||||
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:
|
||||
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:
|
||||
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]:
|
||||
return review.persons(pipeline, node)
|
||||
|
||||
@@ -36,13 +59,28 @@ 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]:
|
||||
nodes.decide_persons(decision.person, decision.candidate, decision.same, who.id)
|
||||
return {"person": decision.person}
|
||||
|
||||
|
||||
class Correction(BaseModel):
|
||||
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
|
||||
field: str
|
||||
@@ -52,17 +90,23 @@ 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}")
|
||||
reasons = [
|
||||
r
|
||||
for r in validate(self.entity, {self.field: self.value})
|
||||
if r.split(":")[0] == self.field
|
||||
]
|
||||
reasons = [r for r in validate(self.entity, {self.field: self.value})
|
||||
if r.split(":")[0] == self.field] # fmt: skip
|
||||
if reasons:
|
||||
raise ValueError("; ".join(reasons))
|
||||
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]:
|
||||
nodes.correct(fix.record, fix.field, fix.value, who.id, fix.entity)
|
||||
return {"record": fix.record}
|
||||
@@ -74,7 +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]:
|
||||
nodes.reject(decision.entity, decision.record, decision.reason, who.id)
|
||||
return {"record": decision.record}
|
||||
|
||||
+280
-12
@@ -1,29 +1,297 @@
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Literal
|
||||
|
||||
import requests
|
||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
from core.domains import Domain
|
||||
from persistance import cluster
|
||||
from persistance.cluster import Execution, Progress
|
||||
|
||||
router = APIRouter(prefix="/runs", tags=["runs"])
|
||||
|
||||
State = Literal["queued", "running", "succeeded", "failed", "cancelling", "cancelled"]
|
||||
STATE: dict[str, State] = {
|
||||
"QUEUED": "queued",
|
||||
"NOT_STARTED": "queued",
|
||||
"MANAGED": "queued",
|
||||
"STARTING": "running",
|
||||
"STARTED": "running",
|
||||
"CANCELING": "cancelling",
|
||||
"CANCELED": "cancelled",
|
||||
"SUCCESS": "succeeded",
|
||||
"FAILURE": "failed",
|
||||
}
|
||||
|
||||
RUN_QUERY = """
|
||||
query Run($id: ID!, $outputs: Boolean! = false) {
|
||||
runOrError(runId: $id) {
|
||||
__typename
|
||||
... on Run { runId jobName status startTime endTime tags { key value }
|
||||
stepStats { stepKey status startTime endTime } }
|
||||
... on RunNotFoundError { message }
|
||||
... on PythonError { message }
|
||||
}
|
||||
logsForRun(runId: $id, limit: 5000) {
|
||||
__typename
|
||||
... on EventConnection { events { __typename
|
||||
... on MessageEvent { message level stepKey }
|
||||
... on ExecutionStepOutputEvent @include(if: $outputs) {
|
||||
stepKey outputName metadataEntries { label ... on JsonMetadataEntry { jsonString } }
|
||||
}
|
||||
... on ExecutionStepFailureEvent { error { message causes { message } } }
|
||||
... on RunFailureEvent { error { message causes { message } } } } }
|
||||
... on RunNotFoundError { message }
|
||||
... on PythonError { message }
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
RUNS_QUERY = """
|
||||
query Runs($filter: RunsFilter, $cursor: String, $limit: Int) {
|
||||
runsOrError(filter: $filter, cursor: $cursor, limit: $limit) {
|
||||
__typename
|
||||
... on Runs { results { runId jobName status startTime endTime tags { key value } } }
|
||||
... on InvalidPipelineRunsFilterError { message }
|
||||
... on PythonError { message }
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class RunSummary(BaseModel):
|
||||
id: str
|
||||
job: str
|
||||
domain: str | None
|
||||
status: str
|
||||
state: State
|
||||
started: float | None
|
||||
ended: float | None
|
||||
|
||||
|
||||
class Step(BaseModel):
|
||||
key: str
|
||||
status: str
|
||||
started: float | None
|
||||
ended: float | None
|
||||
|
||||
|
||||
class Run(RunSummary):
|
||||
progress: Progress | None
|
||||
steps: list[Step]
|
||||
info: list[str]
|
||||
warnings: list[str]
|
||||
error: str | None
|
||||
outputs: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class Cancel(BaseModel):
|
||||
id: str
|
||||
status: str
|
||||
state: State
|
||||
|
||||
|
||||
def _dagster_address() -> tuple[str, int]:
|
||||
return os.environ.get("DAGSTER_HOST", "localhost"), int(os.environ.get("DAGSTER_PORT", "3000"))
|
||||
|
||||
|
||||
def dagster() -> DagsterGraphQLClient:
|
||||
return DagsterGraphQLClient(
|
||||
os.environ.get("DAGSTER_HOST", "localhost"),
|
||||
port_number=int(os.environ.get("DAGSTER_PORT", "3000")),
|
||||
host, port = _dagster_address()
|
||||
return DagsterGraphQLClient(host, port_number=port)
|
||||
|
||||
|
||||
LOCKED = "database is locked"
|
||||
LOCK_RETRIES = 5
|
||||
STARTING_WAIT_S = 30
|
||||
|
||||
|
||||
def _locked(payload: dict) -> bool:
|
||||
results = (payload.get("data") or {}).values()
|
||||
return LOCKED in str(payload.get("errors", "")) or any(
|
||||
isinstance(r, dict)
|
||||
and r.get("__typename") == "PythonError"
|
||||
and LOCKED in r.get("message", "")
|
||||
for r in results
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{run_id}")
|
||||
def run_status(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||
def _graphql_response(url: str, query: str, variables: dict) -> dict:
|
||||
try:
|
||||
return {"id": run_id, "status": client.get_run_status(run_id).value}
|
||||
response = requests.post(url, json={"query": query, "variables": variables}, timeout=15)
|
||||
if response.status_code != 200:
|
||||
raise HTTPException(502, detail=response.text)
|
||||
return response.json()
|
||||
except requests.RequestException as e:
|
||||
raise HTTPException(502, detail=str(e)) from e
|
||||
|
||||
|
||||
def graphql(query: str, variables: dict) -> dict:
|
||||
host, port = _dagster_address()
|
||||
url = f"http://{host}:{port}/graphql"
|
||||
payload = _graphql_response(url, query, variables)
|
||||
for attempt in range(LOCK_RETRIES):
|
||||
if not _locked(payload):
|
||||
break
|
||||
time.sleep(0.2 * 2**attempt)
|
||||
payload = _graphql_response(url, query, variables)
|
||||
if _locked(payload):
|
||||
raise HTTPException(
|
||||
503, detail="Dagster's run storage is busy; try again", headers={"Retry-After": "5"}
|
||||
)
|
||||
if "errors" in payload:
|
||||
raise HTTPException(502, detail=str(payload["errors"]))
|
||||
return payload["data"]
|
||||
|
||||
|
||||
def _tags(run: dict) -> dict[str, str]:
|
||||
return {tag["key"]: tag["value"] for tag in run.get("tags", [])}
|
||||
|
||||
|
||||
def _summary(run: dict) -> RunSummary:
|
||||
status = run["status"]
|
||||
return RunSummary(
|
||||
id=run["runId"],
|
||||
job=run["jobName"],
|
||||
domain=_tags(run).get("domain"),
|
||||
status=status,
|
||||
state=STATE.get(status, "running"),
|
||||
started=run.get("startTime"),
|
||||
ended=run.get("endTime"),
|
||||
)
|
||||
|
||||
|
||||
def shape(run: dict, logs: list[dict], outputs: bool = False) -> Run:
|
||||
summary = _summary(run)
|
||||
progress = None
|
||||
if (tag := _tags(run).get("isssteleon/progress")) is not None:
|
||||
try:
|
||||
progress = Progress.model_validate_json(tag)
|
||||
except ValidationError:
|
||||
pass
|
||||
|
||||
steps = [
|
||||
Step(
|
||||
key=step["stepKey"],
|
||||
status=step["status"],
|
||||
started=step.get("startTime"),
|
||||
ended=step.get("endTime"),
|
||||
)
|
||||
for step in run.get("stepStats", [])
|
||||
]
|
||||
steps.sort(key=lambda step: (step.started is None, step.started or 0.0))
|
||||
|
||||
info, warnings = [], []
|
||||
error = None
|
||||
result = {} if outputs else None
|
||||
for event in logs:
|
||||
kind = event["__typename"]
|
||||
if kind == "LogMessageEvent" and event["level"] in ("INFO", "WARNING"):
|
||||
line = event["message"]
|
||||
if step_key := event.get("stepKey"):
|
||||
line = f"{step_key}: {line}"
|
||||
(info if event["level"] == "INFO" else warnings).append(line)
|
||||
if result is not None and kind == "ExecutionStepOutputEvent":
|
||||
for entry in event.get("metadataEntries", ()):
|
||||
if "jsonString" in entry:
|
||||
result[f"{event['stepKey']}.{entry['label']}"] = json.loads(entry["jsonString"])
|
||||
if summary.state == "failed" and kind in ("ExecutionStepFailureEvent", "RunFailureEvent"):
|
||||
failure = event.get("error")
|
||||
error = None
|
||||
if failure:
|
||||
causes = failure.get("causes")
|
||||
message = (causes[-1] if causes else failure)["message"]
|
||||
lines = message.strip().splitlines()
|
||||
error = lines[0][:500] if lines else None
|
||||
|
||||
return Run(
|
||||
**summary.model_dump(),
|
||||
progress=progress,
|
||||
outputs=result,
|
||||
steps=steps,
|
||||
info=info[-200:],
|
||||
warnings=warnings[:200],
|
||||
error=(error or "the run failed") if summary.state == "failed" else None,
|
||||
)
|
||||
|
||||
|
||||
def _result(result: dict, typename: str) -> dict:
|
||||
if result["__typename"] != typename:
|
||||
status = 404 if result["__typename"] == "RunNotFoundError" else 502
|
||||
raise HTTPException(status, detail=result.get("message", result["__typename"]))
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/{run_id}")
|
||||
def run_status(run_id: str, outputs: bool = False) -> Run:
|
||||
data = graphql(RUN_QUERY, {"id": run_id, "outputs": outputs})
|
||||
run = _result(data["runOrError"], "Run")
|
||||
logs = _result(data["logsForRun"], "EventConnection")
|
||||
return shape(run, logs["events"], outputs)
|
||||
|
||||
|
||||
def _status(client: DagsterGraphQLClient, run_id: str) -> str:
|
||||
try:
|
||||
return client.get_run_status(run_id).value
|
||||
except DagsterGraphQLClientError as e:
|
||||
raise HTTPException(404 if "RunNotFound" in str(e) else 502, detail=str(e)) from e
|
||||
raise HTTPException(404 if e.args[0] == "RunNotFoundError" else 502, detail=str(e)) from e
|
||||
|
||||
|
||||
@router.post("/{run_id}/terminate")
|
||||
def terminate_run(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||
@router.post("/{run_id}/cancel")
|
||||
def cancel_run(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> Cancel:
|
||||
status = _status(client, run_id)
|
||||
deadline = time.monotonic() + STARTING_WAIT_S
|
||||
while status == "STARTING" and time.monotonic() < deadline:
|
||||
time.sleep(0.5)
|
||||
status = _status(client, run_id)
|
||||
if status in ("SUCCESS", "FAILURE", "CANCELED"):
|
||||
raise HTTPException(409, detail=f"the run already ended: {STATE[status]}")
|
||||
if status == "STARTING":
|
||||
raise HTTPException(
|
||||
409, detail="the run is still starting; try again", headers={"Retry-After": "5"}
|
||||
)
|
||||
try:
|
||||
client.terminate_run(run_id)
|
||||
return {"id": run_id, "status": client.get_run_status(run_id).value}
|
||||
except DagsterGraphQLClientError as e:
|
||||
raise HTTPException(404 if "RunNotFound" in str(e) else 409, detail=str(e)) from e
|
||||
raise HTTPException(502, detail=str(e)) from e
|
||||
status = _status(client, run_id)
|
||||
return Cancel(id=run_id, status=status, state=STATE.get(status, "running"))
|
||||
|
||||
|
||||
@router.get("")
|
||||
def run_history(
|
||||
job: str | None = None,
|
||||
domain: Domain | None = None,
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
before: str | None = None,
|
||||
) -> list[RunSummary]:
|
||||
filters = {}
|
||||
if job is not None:
|
||||
filters["pipelineName"] = job
|
||||
if domain is not None:
|
||||
filters["tags"] = [{"key": "domain", "value": domain.value}]
|
||||
data = graphql(RUNS_QUERY, {"filter": filters, "cursor": before, "limit": limit})
|
||||
return [_summary(run) for run in _result(data["runsOrError"], "Runs")["results"]]
|
||||
|
||||
|
||||
def submit(
|
||||
client: DagsterGraphQLClient, job: str, op: str, config: dict, domain: str
|
||||
) -> dict[str, str]:
|
||||
try:
|
||||
run_id = client.submit_job_execution(
|
||||
job, run_config={"ops": {op: {"config": config}}}, tags={"domain": domain}
|
||||
)
|
||||
except DagsterGraphQLClientError as e:
|
||||
raise HTTPException(502, detail=str(e)) from e
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
def execution_config(choice: Execution | None) -> dict:
|
||||
try:
|
||||
resolved = cluster.resolve(choice)
|
||||
except cluster.ExecutionError as e:
|
||||
raise HTTPException(422, detail=str(e)) from e
|
||||
return {"mode": resolved.mode, "scheduler": resolved.scheduler}
|
||||
|
||||
+107
-108
@@ -4,8 +4,10 @@ import shutil
|
||||
import uuid
|
||||
from pathlib import Path, PurePosixPath
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from fastapi import APIRouter, Form, HTTPException, Query, UploadFile
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
from core import sources
|
||||
from core.pipeline import MASK, Pipeline, Source, restored
|
||||
from persistance import config_log, nodes
|
||||
@@ -15,7 +17,10 @@ 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:
|
||||
return sources.catalog()
|
||||
|
||||
@@ -37,25 +42,28 @@ class Tested(BaseModel):
|
||||
|
||||
PLAIN = [
|
||||
(
|
||||
"login failed|password authentication failed|access denied|authentication|401|403|permission denied|invalid credentials",
|
||||
r"login failed|password authentication failed|access denied|authentication|"
|
||||
r"401|403|permission denied|invalid credentials",
|
||||
"El usuario o la contraseña no son correctos, o no tiene permiso.",
|
||||
),
|
||||
), # fmt: skip
|
||||
(
|
||||
"name or service not known|could not translate host|nodename nor servname|getaddrinfo|unknown host|no such host|resolve",
|
||||
r"name or service not known|could not translate host|nodename nor servname|"
|
||||
r"getaddrinfo|unknown host|no such host|resolve",
|
||||
"No se encontró el servidor. Revise el nombre o la dirección.",
|
||||
),
|
||||
), # fmt: skip
|
||||
(
|
||||
"timed out|timeout|connection refused|unable to connect|adaptive server is unavailable|could not connect|connection reset",
|
||||
r"timed out|timeout|connection refused|unable to connect|adaptive server is unavailable|"
|
||||
r"could not connect|connection reset",
|
||||
"El servidor no respondió. Revise la dirección, el puerto o si está encendido.",
|
||||
),
|
||||
), # fmt: skip
|
||||
(
|
||||
"database .* does not exist|cannot open database|unknown database",
|
||||
r"database .* does not exist|cannot open database|unknown database",
|
||||
"No existe esa base de datos en el servidor.",
|
||||
),
|
||||
), # fmt: skip
|
||||
(
|
||||
"no such table|invalid object name|does not exist|not found|no such file|404",
|
||||
r"no such table|invalid object name|does not exist|not found|no such file|404",
|
||||
"No se encontró lo que pidió (la tabla, la carpeta o el archivo).",
|
||||
),
|
||||
), # fmt: skip
|
||||
]
|
||||
|
||||
|
||||
@@ -73,12 +81,8 @@ def _with_saved_secrets(asked: Answers) -> dict[str, Any]:
|
||||
if not (asked.pipeline and asked.node and config_log.latest_version(asked.pipeline)):
|
||||
raise HTTPException(422, detail="una contraseña oculta necesita la fuente guardada")
|
||||
saved = config_log.get(asked.pipeline)[1]
|
||||
node = {
|
||||
"id": asked.node,
|
||||
"kind": "source",
|
||||
"source": "core.sources:catalog",
|
||||
"guided": {"type": asked.type, "answers": asked.answers},
|
||||
}
|
||||
node = {"id": asked.node, "kind": "source", "source": "core.sources:catalog",
|
||||
"guided": {"type": asked.type, "answers": asked.answers}} # fmt: skip
|
||||
try:
|
||||
found = restored(Pipeline(nodes=[node]), saved).nodes[0]
|
||||
except ValueError as e:
|
||||
@@ -86,42 +90,50 @@ 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:
|
||||
if asked.type not in sources.catalog().types:
|
||||
raise HTTPException(404, detail=f"no source type {asked.type}")
|
||||
answers = _with_saved_secrets(asked)
|
||||
spec = sources.catalog().types[asked.type]
|
||||
picked = all((answers.get(k) for k, f in spec.fields.items() if f.type == "table"))
|
||||
picked = all(answers.get(k) for k, f in spec.fields.items() if f.type == "table")
|
||||
try:
|
||||
if not picked and (listed := sources.listing(asked.type, answers)):
|
||||
tables = nodes.resources(*listed)
|
||||
count = "1 tabla" if len(tables) == 1 else f"{len(tables)} tablas"
|
||||
return Tested(ok=True, message=f"Conexión correcta: {count}.", tables=tables)
|
||||
return Tested(ok=True, message=f"Conexión correcta: {count}.",
|
||||
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:
|
||||
return Tested(ok=False, message=_missing(e))
|
||||
except Exception as e:
|
||||
except Exception as e: # noqa: BLE001
|
||||
return Tested(ok=False, message=plain(e), detail=f"{type(e).__name__}: {e}"[:2000])
|
||||
found = (
|
||||
"Conexión correcta."
|
||||
if rows
|
||||
else "Se conectó, pero no encontró archivos ni filas. Revise la ruta y qué archivos tomar."
|
||||
else (
|
||||
"Se conectó, pero no encontró archivos ni filas. Revise la ruta y qué archivos tomar."
|
||||
)
|
||||
)
|
||||
return Tested(ok=True, message=found, rows=rows)
|
||||
|
||||
|
||||
def _missing(e: Exception) -> str:
|
||||
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),
|
||||
)
|
||||
return next((str(err["ctx"]["error"]) for err in e.errors()
|
||||
if isinstance(err.get("ctx", {}).get("error"), sources.MissingAnswer)),
|
||||
str(e)) # fmt: skip
|
||||
return str(e)
|
||||
|
||||
|
||||
@@ -146,39 +158,31 @@ class Browsed(BaseModel):
|
||||
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:
|
||||
allowed = roots()
|
||||
if path is None:
|
||||
return Browsed(
|
||||
path=None,
|
||||
parent=None,
|
||||
entries=[
|
||||
Entry(name=name, path=str(root), kind="folder")
|
||||
for name, root in allowed.items()
|
||||
if root.is_dir()
|
||||
],
|
||||
)
|
||||
return Browsed(path=None, parent=None, entries=[
|
||||
Entry(name=name, path=str(root), kind="folder")
|
||||
for name, root in allowed.items() if root.is_dir()]) # fmt: skip
|
||||
folder = Path(path).resolve()
|
||||
root = next((r for r in allowed.values() if folder == r or r in folder.parents), None)
|
||||
if root is None or not folder.is_dir():
|
||||
raise HTTPException(404, detail="esa carpeta no está entre las habilitadas")
|
||||
entries = sorted(
|
||||
(
|
||||
Entry(
|
||||
name=p.name,
|
||||
path=str(p),
|
||||
kind="folder" if p.is_dir() else "file",
|
||||
size=None if p.is_dir() else p.stat().st_size,
|
||||
)
|
||||
for p in folder.iterdir()
|
||||
if not p.name.startswith(".")
|
||||
),
|
||||
key=lambda e: (e.kind != "folder", e.name.lower()),
|
||||
)
|
||||
return Browsed(
|
||||
path=str(folder), parent=None if folder == root else str(folder.parent), entries=entries
|
||||
)
|
||||
(Entry(name=p.name, path=str(p), kind="folder" if p.is_dir() else "file",
|
||||
size=None if p.is_dir() else p.stat().st_size)
|
||||
for p in folder.iterdir() if not p.name.startswith(".")),
|
||||
key=lambda e: (e.kind != "folder", e.name.lower())) # fmt: skip
|
||||
return Browsed(path=str(folder), parent=None if folder == root else str(folder.parent),
|
||||
entries=entries) # fmt: skip
|
||||
|
||||
|
||||
class Uploaded(BaseModel):
|
||||
@@ -193,7 +197,16 @@ def _relative(name: str) -> PurePosixPath:
|
||||
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:
|
||||
base = (DATA_DIR / UPLOADS).resolve()
|
||||
target = Path(folder).resolve() if folder else base / uuid.uuid4().hex[:12]
|
||||
@@ -212,7 +225,7 @@ def upload(files: list[UploadFile], folder: Annotated[str | None, Form()] = None
|
||||
|
||||
PENDING = DATA_DIR / "oauth_pending"
|
||||
PENDING_SECONDS = 600
|
||||
STATE = re.compile("[A-Za-z0-9_-]{8,128}")
|
||||
STATE = re.compile(r"[A-Za-z0-9_-]{8,128}")
|
||||
|
||||
|
||||
def _pend(state: str, pending: dict[str, Any]) -> None:
|
||||
@@ -225,7 +238,7 @@ def _pend(state: str, pending: dict[str, Any]) -> None:
|
||||
old.unlink(missing_ok=True)
|
||||
path = PENDING / f"{state}.json"
|
||||
path.write_text(json.dumps(pending))
|
||||
path.chmod(384)
|
||||
path.chmod(0o600)
|
||||
|
||||
|
||||
def _claimed(state: str) -> dict[str, Any] | None:
|
||||
@@ -250,17 +263,14 @@ def _registration(provider: str) -> tuple[sources.Provider, dict[str, str]]:
|
||||
found = sources.catalog().providers.get(provider)
|
||||
if found is None:
|
||||
raise HTTPException(404, detail=f"no provider {provider}")
|
||||
env = {
|
||||
k: os.environ.get(f"{found.env}_{k.upper()}", "")
|
||||
for k in ("client_id", "client_secret", "tenant_id", "project_id")
|
||||
}
|
||||
env = {k: os.environ.get(f"{found.env}_{k.upper()}", "")
|
||||
for k in ("client_id", "client_secret", "tenant_id", "project_id")} # fmt: skip
|
||||
if not (env["client_id"] and env["client_secret"]):
|
||||
needed = f"{found.env}_CLIENT_ID y {found.env}_CLIENT_SECRET"
|
||||
raise HTTPException(
|
||||
503,
|
||||
detail=f"Para iniciar sesión con {found.title}, el área de sistemas debe registrar la aplicación y darle al servidor {needed}.",
|
||||
)
|
||||
return (found, env)
|
||||
raise HTTPException(503, detail=(
|
||||
f"Para iniciar sesión con {found.title}, el área de sistemas debe registrar la "
|
||||
f"aplicación y darle al servidor {needed}.")) # fmt: skip
|
||||
return found, env
|
||||
|
||||
|
||||
def _endpoint(url: str, env: dict[str, str]) -> str:
|
||||
@@ -270,13 +280,8 @@ def _endpoint(url: str, env: dict[str, str]) -> str:
|
||||
def _client(provider: sources.Provider, env: dict[str, str], redirect_uri: str):
|
||||
from authlib.integrations.httpx_client import OAuth2Client
|
||||
|
||||
return OAuth2Client(
|
||||
env["client_id"],
|
||||
env["client_secret"],
|
||||
scope=provider.scope,
|
||||
redirect_uri=redirect_uri,
|
||||
code_challenge_method="S256",
|
||||
)
|
||||
return OAuth2Client(env["client_id"], env["client_secret"], scope=provider.scope,
|
||||
redirect_uri=redirect_uri, code_challenge_method="S256") # fmt: skip
|
||||
|
||||
|
||||
class SignIn(BaseModel):
|
||||
@@ -284,7 +289,14 @@ class SignIn(BaseModel):
|
||||
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:
|
||||
import secrets
|
||||
|
||||
@@ -294,15 +306,8 @@ def oauth_start(provider: str, origin: str) -> SignIn:
|
||||
url, state = _client(found, env, redirect_uri).create_authorization_url(
|
||||
_endpoint(found.authorize_url, env), code_verifier=verifier, **found.authorize_params
|
||||
)
|
||||
_pend(
|
||||
state,
|
||||
{
|
||||
"provider": provider,
|
||||
"verifier": verifier,
|
||||
"redirect_uri": redirect_uri,
|
||||
"origin": origin.rstrip("/"),
|
||||
},
|
||||
)
|
||||
_pend(state, {"provider": provider, "verifier": verifier, "redirect_uri": redirect_uri,
|
||||
"origin": origin.rstrip("/")}) # fmt: skip
|
||||
return SignIn(url=url, state=state)
|
||||
|
||||
|
||||
@@ -318,39 +323,30 @@ def account(provider: str, token: dict[str, Any], env: dict[str, str]) -> dict[s
|
||||
"user": me.get("mail") or me.get("userPrincipalName") or me.get("displayName"),
|
||||
"drive_id": drive.get("id"),
|
||||
"oauth2_client_params": {
|
||||
"client_id": env["client_id"],
|
||||
"client_secret": env["client_secret"],
|
||||
"token_endpoint": _endpoint(found.token_url, env),
|
||||
"scope": found.scope,
|
||||
"client_id": env["client_id"], "client_secret": env["client_secret"],
|
||||
"token_endpoint": _endpoint(found.token_url, env), "scope": found.scope,
|
||||
"token": token,
|
||||
},
|
||||
}
|
||||
about = httpx.get(
|
||||
"https://www.googleapis.com/drive/v3/about", params={"fields": "user"}, headers=bearer
|
||||
).json()
|
||||
credentials = {
|
||||
"client_id": env["client_id"],
|
||||
"client_secret": env["client_secret"],
|
||||
"refresh_token": token.get("refresh_token"),
|
||||
"project_id": env["project_id"] or None,
|
||||
}
|
||||
return {
|
||||
"user": about.get("user", {}).get("emailAddress"),
|
||||
"credentials": {k: v for k, v in credentials.items() if v},
|
||||
}
|
||||
} # fmt: skip
|
||||
about = httpx.get("https://www.googleapis.com/drive/v3/about", params={"fields": "user"},
|
||||
headers=bearer).json() # fmt: skip
|
||||
credentials = {"client_id": env["client_id"], "client_secret": env["client_secret"],
|
||||
"refresh_token": token.get("refresh_token"),
|
||||
"project_id": env["project_id"] or None} # fmt: skip
|
||||
return {"user": about.get("user", {}).get("emailAddress"),
|
||||
"credentials": {k: v for k, v in credentials.items() if v}} # fmt: skip
|
||||
|
||||
|
||||
@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):
|
||||
import json
|
||||
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
pending = _claimed(state)
|
||||
if pending is None or pending["provider"] != provider:
|
||||
return HTMLResponse(
|
||||
"<p>La solicitud de inicio de sesión venció. Cierre esta ventana e inténtelo de nuevo.</p>",
|
||||
status_code=400,
|
||||
)
|
||||
return HTMLResponse("<p>La solicitud de inicio de sesión venció. Cierre esta ventana "
|
||||
"e inténtelo de nuevo.</p>", status_code=400) # fmt: skip
|
||||
message: dict[str, Any] = {"type": "isssteleon-oauth", "state": state}
|
||||
if error or not code:
|
||||
message["error"] = "No se completó el inicio de sesión."
|
||||
@@ -361,10 +357,13 @@ 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:
|
||||
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"])
|
||||
return HTMLResponse(
|
||||
f"<!doctype html><meta charset=utf-8><title>ISSSTELEON</title><p>Listo. Puede cerrar esta ventana.</p><script>window.opener&&window.opener.postMessage({payload},{target});window.close()</script>"
|
||||
"<!doctype html><meta charset=utf-8><title>ISSSTELEON</title>"
|
||||
"<p>Listo. Puede cerrar esta ventana.</p>"
|
||||
f"<script>window.opener&&window.opener.postMessage({payload},{target});"
|
||||
"window.close()</script>"
|
||||
)
|
||||
|
||||
+14
-18
@@ -4,6 +4,7 @@ import uuid
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from functools import cache
|
||||
|
||||
from fastapi import APIRouter, Depends, FastAPI
|
||||
from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin, schemas
|
||||
from fastapi_users.authentication import AuthenticationBackend, CookieTransport, JWTStrategy
|
||||
@@ -12,6 +13,7 @@ from fastapi_users_db_sqlalchemy import SQLAlchemyBaseUserTableUUID, SQLAlchemyU
|
||||
from sqlalchemy import JSON, String, event, make_url, text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
from core.domains import Domain
|
||||
from persistance.config import DATA_DIR, platform_url
|
||||
|
||||
@@ -40,11 +42,6 @@ class UserCreate(schemas.BaseUserCreate):
|
||||
domains: list[Domain] = []
|
||||
|
||||
|
||||
class UserUpdate(schemas.BaseUserUpdate):
|
||||
name: str | None = None
|
||||
domains: list[Domain] | None = None
|
||||
|
||||
|
||||
@cache
|
||||
def _engine():
|
||||
url = make_url(platform_url())
|
||||
@@ -77,17 +74,17 @@ def _secret() -> str:
|
||||
if not path.exists():
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(secrets.token_urlsafe(48))
|
||||
path.chmod(384)
|
||||
path.chmod(0o600)
|
||||
return path.read_text().strip()
|
||||
|
||||
|
||||
class Manager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
||||
@property
|
||||
def reset_password_token_secret(self) -> str:
|
||||
def reset_password_token_secret(self) -> str: # type: ignore[override]
|
||||
return _secret()
|
||||
|
||||
@property
|
||||
def verification_token_secret(self) -> str:
|
||||
def verification_token_secret(self) -> str: # type: ignore[override]
|
||||
return _secret()
|
||||
|
||||
|
||||
@@ -106,10 +103,14 @@ backend = AuthenticationBackend(
|
||||
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(
|
||||
users.get_register_router(UserRead, UserCreate),
|
||||
@@ -124,19 +125,14 @@ async def first_admin() -> None:
|
||||
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"))
|
||||
email, password = os.environ.get("AUTH_ADMIN_EMAIL"), os.environ.get("AUTH_ADMIN_PASSWORD")
|
||||
if not (email and password):
|
||||
return
|
||||
async with async_sessionmaker(_engine(), expire_on_commit=False)() as session:
|
||||
manager = Manager(SQLAlchemyUserDatabase(session, User))
|
||||
try:
|
||||
admin = UserCreate(
|
||||
email=email,
|
||||
password=password,
|
||||
is_superuser=True,
|
||||
name="Administrador",
|
||||
domains=list(Domain),
|
||||
)
|
||||
admin = UserCreate(email=email, password=password, is_superuser=True,
|
||||
name="Administrador", domains=list(Domain)) # fmt: skip
|
||||
await manager.create(admin)
|
||||
except UserAlreadyExists:
|
||||
pass
|
||||
|
||||
Reference in New Issue
Block a user