Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cddfc38ab5 | |||
| 5039afcc3f | |||
| fee6a6622d |
@@ -1,67 +0,0 @@
|
|||||||
"""Automático through the API, as the Conectar button uses it: an operator connects
|
|
||||||
ISSSTELEON's test source and nothing else; the site's language model (LLM_URL: at
|
|
||||||
ISSSTELEON, its SGLang) drafts the whole pipeline, which is saved and run. What it places
|
|
||||||
must agree with the pipeline an operator drew, record by record. Real processes and the
|
|
||||||
real endpoint; nothing faked."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
|
|
||||||
from test_conectar import ok, wait_for
|
|
||||||
|
|
||||||
SOURCE = "resultados"
|
|
||||||
# Studies whose every record the operator's drawing places, the draft must place too.
|
|
||||||
DRAWN = ("cervical_cytology", "mammography", "cervical_biopsy", "breast_biopsy")
|
|
||||||
HOURS = 3600 # with a model answering, it reads every document: an hour or more per run
|
|
||||||
|
|
||||||
|
|
||||||
def staged(platform, pipeline: str) -> dict[tuple, object]:
|
|
||||||
"""What a pipeline's targets staged, clean rows only: (study, record, field) -> value."""
|
|
||||||
rows = platform.query(
|
|
||||||
"select study, _record, field, value_text, value_num, value_bool, value_date "
|
|
||||||
f"from bronze.staged__observation where _pipeline = '{pipeline}'"
|
|
||||||
)
|
|
||||||
return {(s, r, f): next((v for v in vs if v is not None), None) for s, r, f, *vs in rows}
|
|
||||||
|
|
||||||
|
|
||||||
def test_automatico_drafts_a_sites_pipeline_and_runs_it(api, platform, site):
|
|
||||||
model = ok(api.get("/ingest/llm"))
|
|
||||||
assert model["available"], model["reason"]
|
|
||||||
|
|
||||||
drawn = json.loads(site.drawn)
|
|
||||||
source = next(n for n in drawn["nodes"] if n["id"] == SOURCE)
|
|
||||||
# Automático starts from the sources alone: a drawing with more is refused.
|
|
||||||
ok(api.put("/ingest/pipelines/half", json={"nodes": drawn["nodes"][:2]}))
|
|
||||||
assert api.post("/ingest/pipelines/half/draft").status_code == 422
|
|
||||||
assert api.post("/ingest/pipelines/nowhere/draft").status_code == 404
|
|
||||||
|
|
||||||
ok(api.put("/ingest/pipelines/auto", json={"nodes": [source]}))
|
|
||||||
wait_for(api, ok(api.post("/ingest/pipelines/auto/draft"))["run_id"], seconds=3 * HOURS)
|
|
||||||
saved = ok(api.get("/ingest/pipelines/auto"))
|
|
||||||
assert saved["version"] == 2
|
|
||||||
kinds = [n["kind"] for n in saved["pipeline"]["nodes"]]
|
|
||||||
assert {"read", "route", "extract", "link", "target"} <= set(kinds)
|
|
||||||
studies = {n["entity"] for n in saved["pipeline"]["nodes"] if n["kind"] == "target"}
|
|
||||||
# One layout may report several studies: pathology by organ, notes by what they record.
|
|
||||||
assert set(DRAWN) | {"breast_treatment", "death"} <= studies, studies
|
|
||||||
# Documents no route claims wait for a reviewer, as with a drawn pipeline.
|
|
||||||
assert any(n.get("otherwise") for n in saved["pipeline"]["nodes"])
|
|
||||||
|
|
||||||
# The operator's own drawing over the same source: where both placed a value, the same.
|
|
||||||
ok(api.put("/ingest/concept-maps/erick_site", json=json.loads(site.concept_map.read_text())))
|
|
||||||
ok(api.put("/ingest/pipelines/site", json=drawn))
|
|
||||||
wait_for(api, ok(api.post("/ingest/pipelines/site/runs", json={}))["run_id"], 2 * HOURS)
|
|
||||||
mine, theirs = staged(platform, "auto"), staged(platform, "site")
|
|
||||||
both = set(mine) & set(theirs)
|
|
||||||
differ = {k: (mine[k], theirs[k]) for k in both if str(mine[k]) != str(theirs[k])}
|
|
||||||
assert both and not differ, differ
|
|
||||||
for study in DRAWN:
|
|
||||||
drawn_records = {r for s, r, _ in theirs if s == study}
|
|
||||||
assert drawn_records <= {r for s, r, _ in mine if s == study}, study
|
|
||||||
|
|
||||||
# Each case review waits on carries the model's reading, and still waits for a person.
|
|
||||||
link = next(n["id"] for n in saved["pipeline"]["nodes"] if n["kind"] == "link")
|
|
||||||
persons = ok(api.get("/review/persons", params={"pipeline": "auto", "node": link}))
|
|
||||||
for entry in persons["to_settle"]:
|
|
||||||
assert all(c["suggestion"]["reason"] for c in entry["candidates"])
|
|
||||||
for entry in persons["torn"]:
|
|
||||||
assert entry["suggestion"]["reason"]
|
|
||||||
+4
-2
@@ -30,6 +30,7 @@ PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cama.json"
|
|||||||
CAPTURED_ON = "2026-11-26" # the day of the capture's load: durations counted to it
|
CAPTURED_ON = "2026-11-26" # the day of the capture's load: durations counted to it
|
||||||
TRAINED_ON = "2026-11-24" # survival's follow-up ended the day the reference was trained
|
TRAINED_ON = "2026-11-24" # survival's follow-up ended the day the reference was trained
|
||||||
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
|
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
|
||||||
|
NEW = {"CAMA_DIAS_RESULTADO_BIOPSIA"} # tests/test_cama_biopsy_time.py
|
||||||
CODES = { # platform code -> the current platform's
|
CODES = { # platform code -> the current platform's
|
||||||
**{c: f"B{c}" for c in ("0", "1", "2", "3", "4", "5", "6")},
|
**{c: f"B{c}" for c in ("0", "1", "2", "3", "4", "5", "6")},
|
||||||
"4A": "B4", "4B": "B4", "4C": "B4",
|
"4A": "B4", "4B": "B4", "4C": "B4",
|
||||||
@@ -128,8 +129,9 @@ def test_cama_from_the_hospital_to_indicators(api, platform, tmp_path):
|
|||||||
# Indicators: every measure, every semester, as the current platform answers them.
|
# Indicators: every measure, every semester, as the current platform answers them.
|
||||||
reference = json.loads((REFERENCE / "indicators.json").read_text())
|
reference = json.loads((REFERENCE / "indicators.json").read_text())
|
||||||
(measures,) = pages(api, "/cama/fhir/Measure")
|
(measures,) = pages(api, "/cama/fhir/Measure")
|
||||||
assert {m["resource"]["name"] for m in measures["entry"]} == set(reference)
|
# A measure the current platform never had (not in its capture) is checked by its own tests.
|
||||||
for measure in [e["resource"] for e in measures["entry"]]:
|
assert {m["resource"]["name"] for m in measures["entry"]} == set(reference) | NEW
|
||||||
|
for measure in [e["resource"] for e in measures["entry"] if e["resource"]["name"] not in NEW]:
|
||||||
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
|
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
|
||||||
"event-cutoff": CAPTURED_ON} # fmt: skip
|
"event-cutoff": CAPTURED_ON} # fmt: skip
|
||||||
found = [e for b in pages(api, "/cama/fhir/MeasureReport", params) for e in b["entry"]]
|
found = [e for b in pages(api, "/cama/fhir/MeasureReport", params) for e in b["entry"]]
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ built by Core's mappers from the rows Persistance reads; nothing is computed her
|
|||||||
counting a few thousand rows (measures) and ordering the follow-up list."""
|
counting a few thousand rows (measures) and ordering the follow-up list."""
|
||||||
|
|
||||||
import operator
|
import operator
|
||||||
|
import os
|
||||||
import unicodedata
|
import unicodedata
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from typing import Annotated, Any
|
from typing import Annotated, Any
|
||||||
@@ -19,6 +20,8 @@ from fhir.resources.R4B.resource import Resource
|
|||||||
from core import catalog
|
from core import catalog
|
||||||
from core import fhir as f
|
from core import fhir as f
|
||||||
from core import measures as m
|
from core import measures as m
|
||||||
|
from core import models
|
||||||
|
from core.cacu import reference_risk as reference
|
||||||
from core.domains import Domain, measures, part
|
from core.domains import Domain, measures, part
|
||||||
from core.follow_up import window_start
|
from core.follow_up import window_start
|
||||||
from core.pipeline import ID_PATTERN
|
from core.pipeline import ID_PATTERN
|
||||||
@@ -111,6 +114,46 @@ def read_patient(domain: Domain, id: str) -> Response:
|
|||||||
return fhir(f.patient(found, fu.STATUS_SYSTEM))
|
return fhir(f.patient(found, fu.STATUS_SYSTEM))
|
||||||
|
|
||||||
|
|
||||||
|
NCI_REFERENCE = "CACU_NCI_REFERENCE" # set to 1 to serve the experimental NCI reference comparison
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/Patient/{id}/$reference-risk", responses=_OK, response_class=Response)
|
||||||
|
def reference_risk(domain: Domain, id: str,
|
||||||
|
cutoff: date | None = Query(None, description="Only what was reported by this day"),
|
||||||
|
sample: date | None = Query(None, description="The cytology's sample day")) -> Response: # fmt: skip
|
||||||
|
"""EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The NCI/ASCCP CIN3+ reference risk of one
|
||||||
|
patient's cytology by a cut-off, how it was resolved and, beside it, the institutional models'
|
||||||
|
risks when they measure the same thing. Research only: not validated, not a recommendation."""
|
||||||
|
if domain != Domain.CACU or os.environ.get(NCI_REFERENCE) != "1":
|
||||||
|
raise HTTPException(404, "the NCI reference comparison is not enabled")
|
||||||
|
(person,) = reads.rows(domain.value, "person", id=id) or [None]
|
||||||
|
if person is None:
|
||||||
|
raise HTTPException(404, f"no Patient/{id}")
|
||||||
|
day = _cutoff(domain, cutoff)
|
||||||
|
one = {"persons": [id]}
|
||||||
|
facts = {
|
||||||
|
"birth_date": person.get("birth_date"),
|
||||||
|
"cytologies": reads.rows(domain.value, "reference_cytologies", **one),
|
||||||
|
"biopsies": reads.rows(domain.value, "reference_biopsies", **one),
|
||||||
|
"events": reads.rows(domain.value, "reference_events", **one),
|
||||||
|
}
|
||||||
|
resolution = reference.resolve(facts, day, sample)
|
||||||
|
latest: dict[str, dict] = {} # each model's latest assessment by the cut-off
|
||||||
|
for r in reads.rows(domain.value, "risk", **one):
|
||||||
|
index = str(r["index_date"])[:10]
|
||||||
|
if index > day.isoformat():
|
||||||
|
continue
|
||||||
|
found = latest.setdefault(r["model"], {"model": r["model"], "index_date": index,
|
||||||
|
"title": models.title(r["model"]), "predictions": []})
|
||||||
|
if index > found["index_date"]:
|
||||||
|
found.update(index_date=index, predictions=[])
|
||||||
|
if index == found["index_date"]:
|
||||||
|
found["predictions"].append({"years": int(r["horizon_years"]), "p": r["probability"],
|
||||||
|
"low": r["ci_low"], "high": r["ci_high"]})
|
||||||
|
comparison = reference.compare(resolution, list(latest.values())) if resolution["horizons"] else []
|
||||||
|
return fhir(f.reference_risk(resolution, comparison, reference.tables()))
|
||||||
|
|
||||||
|
|
||||||
def _with_identity(domain: Domain, rows: list[dict]) -> list[dict]:
|
def _with_identity(domain: Domain, rows: list[dict]) -> list[dict]:
|
||||||
"""Persons with their names, identifiers and the ids they replaced."""
|
"""Persons with their names, identifiers and the ids they replaced."""
|
||||||
persons = [r["person_id"] for r in rows]
|
persons = [r["person_id"] for r in rows]
|
||||||
|
|||||||
+1
-37
@@ -10,7 +10,7 @@ from pydantic import BaseModel
|
|||||||
from core import concept_map
|
from core import concept_map
|
||||||
from core.pipeline import ID_PATTERN, ImportPath, Pipeline, Source, redacted, restored
|
from core.pipeline import ID_PATTERN, ImportPath, Pipeline, Source, redacted, restored
|
||||||
from core.schema import ENTITIES
|
from core.schema import ENTITIES
|
||||||
from persistance import config_log, llm, nodes
|
from persistance import config_log, nodes
|
||||||
from webapi.runs import dagster
|
from webapi.runs import dagster
|
||||||
|
|
||||||
router = APIRouter(prefix="/ingest", tags=["ingest"])
|
router = APIRouter(prefix="/ingest", tags=["ingest"])
|
||||||
@@ -140,42 +140,6 @@ def submit(client: DagsterGraphQLClient, pipeline_id: str, version: int | None =
|
|||||||
raise HTTPException(502, detail=str(e)) from e
|
raise HTTPException(502, detail=str(e)) from e
|
||||||
|
|
||||||
|
|
||||||
class LanguageModel(BaseModel):
|
|
||||||
available: bool
|
|
||||||
model: str | None
|
|
||||||
vision: bool # reads page images (scans), not only their OCR text
|
|
||||||
reason: str | None # why it is not available
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/llm")
|
|
||||||
def language_model() -> LanguageModel:
|
|
||||||
"""The site's language model (LLM_URL): whether it answers, which, and whether it
|
|
||||||
reads images. Automático needs it; extract nodes use their patterns without it."""
|
|
||||||
return LanguageModel(**llm.status())
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/pipelines/{pipeline_id}/draft")
|
|
||||||
def start_draft(
|
|
||||||
pipeline_id: PipelineId, run: bool = True, client: DagsterGraphQLClient = Depends(dagster)
|
|
||||||
) -> dict[str, str]:
|
|
||||||
"""Automático: starts the `draft` job, which draws the whole pipeline from its saved
|
|
||||||
sources (the only nodes it may hold), saves it as a new version and runs it (`run`
|
|
||||||
false: drawn and saved only); follow it at /runs/{run_id}."""
|
|
||||||
if not config_log.latest_version(pipeline_id):
|
|
||||||
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
|
||||||
_, saved = config_log.get(pipeline_id)
|
|
||||||
if not saved.nodes or any(n.kind != "source" for n in saved.nodes):
|
|
||||||
raise HTTPException(422, detail="Automático arma la canalización a partir de sus "
|
|
||||||
"fuentes: guárdela solo con ellas.") # fmt: skip
|
|
||||||
if not (found := llm.status())["available"]:
|
|
||||||
raise HTTPException(503, detail=f"El modelo de lenguaje no responde: {found['reason']}")
|
|
||||||
config = {"ops": {"draft_pipeline": {"config": {"pipeline": pipeline_id, "run": run}}}}
|
|
||||||
try:
|
|
||||||
return {"run_id": client.submit_job_execution("draft", run_config=config)}
|
|
||||||
except DagsterGraphQLClientError as e:
|
|
||||||
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")
|
||||||
def node_rows(
|
def node_rows(
|
||||||
pipeline_id: PipelineId,
|
pipeline_id: PipelineId,
|
||||||
|
|||||||
Reference in New Issue
Block a user