Compare commits
3 Commits
b61a4863d1
...
rebuild
| Author | SHA1 | Date | |
|---|---|---|---|
| 05d0e4c278 | |||
| 70c88c54dd | |||
| bd06a31d52 |
@@ -0,0 +1,67 @@
|
|||||||
|
"""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"]
|
||||||
+5
-1
@@ -54,6 +54,7 @@ CODES = { # platform code -> the current platform's
|
|||||||
} # fmt: skip
|
} # fmt: skip
|
||||||
STRATA = {"age_group": "grupo_edad", "follow_up_status": "estatus_seguimiento",
|
STRATA = {"age_group": "grupo_edad", "follow_up_status": "estatus_seguimiento",
|
||||||
"result": "citologia_alto_grado"} # fmt: skip
|
"result": "citologia_alto_grado"} # fmt: skip
|
||||||
|
NEW_STRATA = {"round"} # CACU_EU7, Phase 6
|
||||||
CATEGORY = {"CACU_EU7": "resultado", "CACU_CONFIRMACION_CITOLOGIA": "biopsia_grado"}
|
CATEGORY = {"CACU_EU7": "resultado", "CACU_CONFIRMACION_CITOLOGIA": "biopsia_grado"}
|
||||||
|
|
||||||
|
|
||||||
@@ -110,6 +111,8 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
|
|||||||
reference = json.loads((REFERENCE / "indicators.json").read_text())
|
reference = json.loads((REFERENCE / "indicators.json").read_text())
|
||||||
(measures,) = pages(api, "/cacu/fhir/Measure")
|
(measures,) = pages(api, "/cacu/fhir/Measure")
|
||||||
for measure in [e["resource"] for e in measures["entry"]]:
|
for measure in [e["resource"] for e in measures["entry"]]:
|
||||||
|
if measure["name"] not in reference: # Phase 6's (tests/test_cacu_new_measures.py)
|
||||||
|
continue
|
||||||
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, "/cacu/fhir/MeasureReport", params) for e in b["entry"]]
|
found = [e for b in pages(api, "/cacu/fhir/MeasureReport", params) for e in b["entry"]]
|
||||||
@@ -118,7 +121,8 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
|
|||||||
for ours, theirs in zip(found, reference[name]["body"]["entry"], strict=True):
|
for ours, theirs in zip(found, reference[name]["body"]["entry"], strict=True):
|
||||||
a, b = _report(ours, name), _report(theirs, name)
|
a, b = _report(ours, name), _report(theirs, name)
|
||||||
where = (name, ours["resource"]["period"]["start"])
|
where = (name, ours["resource"]["period"]["start"])
|
||||||
assert a[0] == b[0] and a[3] == b[3], where
|
old = {k: v for k, v in a[3].items() if k not in NEW_STRATA}
|
||||||
|
assert a[0] == b[0] and old == b[3], where
|
||||||
if cohort: # scores its count; the current platform gave none
|
if cohort: # scores its count; the current platform gave none
|
||||||
assert b[1] is None and a[1] == a[0]["initial-population"], where
|
assert b[1] is None and a[1] == a[0]["initial-population"], where
|
||||||
continue
|
continue
|
||||||
|
|||||||
+19
-4
@@ -3,6 +3,7 @@ uses, paging, and a CapabilityStatement built from these routes themselves. Reso
|
|||||||
built by Core's mappers from the rows Persistance reads; nothing is computed here beyond
|
built by Core's mappers from the rows Persistance reads; nothing is computed here beyond
|
||||||
counting a few thousand rows (measures) and ordering the follow-up list."""
|
counting a few thousand rows (measures) and ordering the follow-up list."""
|
||||||
|
|
||||||
|
import operator
|
||||||
import unicodedata
|
import unicodedata
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from typing import Annotated, Any
|
from typing import Annotated, Any
|
||||||
@@ -169,6 +170,7 @@ def search_patient(
|
|||||||
identifier: str | None = Query(
|
identifier: str | None = Query(
|
||||||
None, description="[system|]value: a CURP or record number (case ignored)"
|
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>"),
|
sort: str = Query("-recent", alias="_sort", description="-recent or -risk-<outcome>"),
|
||||||
horizon: float | None = Query(None, alias="risk-horizon", description="years"),
|
horizon: float | None = Query(None, alias="risk-horizon", description="years"),
|
||||||
revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"),
|
revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"),
|
||||||
@@ -202,6 +204,8 @@ def search_patient(
|
|||||||
rows = [r for r in rows if r["person_id"] in _id.split(",")]
|
rows = [r for r in rows if r["person_id"] in _id.split(",")]
|
||||||
if status:
|
if status:
|
||||||
rows = [r for r in rows if r["status"] in status.split(",")]
|
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:
|
if name or identifier:
|
||||||
found = {r["person_id"] for r in _with_identity(domain, rows)
|
found = {r["person_id"] for r in _with_identity(domain, rows)
|
||||||
if _matches(r, name, identifier)} # fmt: skip
|
if _matches(r, name, identifier)} # fmt: skip
|
||||||
@@ -223,6 +227,18 @@ def search_patient(
|
|||||||
applied) # fmt: skip
|
applied) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
_COMPARE = {"gt": operator.gt, "ge": operator.ge, "lt": operator.lt, "le": operator.le}
|
||||||
|
|
||||||
|
|
||||||
|
def _born(row: dict, asked: str) -> bool:
|
||||||
|
"""FHIR's `birthdate` (date: a prefix and a day); a patient without one never matches."""
|
||||||
|
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],
|
def _included(domain: Domain, revinclude: list[str], include: list[str], persons: list[str],
|
||||||
at: date, risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip
|
at: date, risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip
|
||||||
unknown = set(revinclude) - set(REVINCLUDES) | set(include) - {"DiagnosticReport:result"}
|
unknown = set(revinclude) - set(REVINCLUDES) | set(include) - {"DiagnosticReport:result"}
|
||||||
@@ -262,12 +278,10 @@ def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]:
|
|||||||
facts = {}
|
facts = {}
|
||||||
if kind := report_facts.get(study):
|
if kind := report_facts.get(study):
|
||||||
found_facts = reads.rows(domain.value, kind, persons=persons, cutoff=at)
|
found_facts = reads.rows(domain.value, kind, persons=persons, cutoff=at)
|
||||||
facts = {(r["person_id"], str(r["sample_date"])[:10]): r["days"]
|
facts = {(r["person_id"], str(r["sample_date"])[:10]): r for r in found_facts}
|
||||||
for r in found_facts} # fmt: skip
|
|
||||||
first = next(e.date for e in spec.events.values() if e.parent is None)
|
first = next(e.date for e in spec.events.values() if e.parent is None)
|
||||||
for row in reads.instances(study, persons, at):
|
for row in reads.instances(study, persons, at):
|
||||||
days = facts.get((row["person_id"], str(row[first])[:10]))
|
extra = f.report_facts(facts.get((row["person_id"], str(row[first])[:10]), {}))
|
||||||
extra = [] if days is None else [f.ext("days-to-diagnosis", "integer", int(days))]
|
|
||||||
found += f.instance(study, f.known(study, row, at), extra)
|
found += f.instance(study, f.known(study, row, at), extra)
|
||||||
return found
|
return found
|
||||||
|
|
||||||
@@ -519,5 +533,6 @@ _STANDARD = {
|
|||||||
"subject": "reference",
|
"subject": "reference",
|
||||||
"measure": "reference",
|
"measure": "reference",
|
||||||
"name": "string",
|
"name": "string",
|
||||||
|
"birthdate": "date",
|
||||||
"identifier": "token",
|
"identifier": "token",
|
||||||
} # FHIR's own search parameters, by their types
|
} # FHIR's own search parameters, by their types
|
||||||
|
|||||||
+37
-1
@@ -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, nodes
|
from persistance import config_log, llm, nodes
|
||||||
from webapi.runs import dagster
|
from webapi.runs import dagster
|
||||||
|
|
||||||
router = APIRouter(prefix="/ingest", tags=["ingest"])
|
router = APIRouter(prefix="/ingest", tags=["ingest"])
|
||||||
@@ -140,6 +140,42 @@ 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