diff --git a/models/graph.py b/models/graph.py index bdf105c..00b5b2b 100644 --- a/models/graph.py +++ b/models/graph.py @@ -184,7 +184,7 @@ def run_extract(p: str, node: Extract): codes = _codes(node, node.patterns) out = [] for row in nodes.rows(p, node.inputs[0]): - text = row.get(node.column) or "" + text = node.text(row) if use_llm: found = ground(_ask_llm(node, text), text) elif node.patterns: @@ -385,10 +385,13 @@ def run_target(p: str, node: Target, kinds: dict[str, str]): linked = {r[RECORD]: r for r in nodes.rows(p, link)} person = {k: r["person_id"] for k, r in linked.items()} model, study = catalog.model(node.entity), catalog.studies()[node.entity] + fixed = nodes.corrections() # a reviewer's reading of a value wins over the extraction observations, held_rows = [], [] for i in (i for i in node.inputs if i != link): for row in nodes.rows(p, i): values = {f: row.get(f) for f in model.model_fields if row.get(f) is not None} + values |= {f: v for f, v in fixed.get(row[RECORD], {}).items() + if f in model.model_fields} # fmt: skip held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values) if row[RECORD] not in person: held.append("no identity linked to this record") diff --git a/tests/test_ingest.py b/tests/test_ingest.py index 0b674a3..fb4d0fd 100644 --- a/tests/test_ingest.py +++ b/tests/test_ingest.py @@ -1,5 +1,6 @@ """Phase 1 gate, stages 1-2: everything a site has reaches bronze, once, and every document -the rules point at is read into text (scanned ones through OCR).""" +the rules point at is read into text (scanned ones through OCR). The site: the synthetic +hospitals' tables (SQLite) and ISSSTELEON's test source (SQL Server tables of PDFs).""" import json import re @@ -7,48 +8,42 @@ import shutil import sqlite3 from pathlib import Path -from synthetic.site import build - FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "hospital" -def graph(tmp: Path, hospital_tables: dict[str, list[str]]) -> dict: - """What an operator would draw for this site: one Source per table or set of files, and - a Read on each column that holds documents.""" +def graph(tmp: Path, hospital_tables: dict[str, list[str]], site_url: str) -> dict: + """What an operator would draw for this site: one Source per table, and a Read on each + column that holds documents.""" - def table(node_id, db, name): - args = {"credentials": f"sqlite:///{db}", "table": name} + def table(node_id, credentials, name, **args): + args = {"credentials": credentials, "table": name, **args} return {"id": node_id, "kind": "source", "source": SQL_TABLE, "args": args} - def files(node_id, glob, **extra): - args = {"bucket_url": str(tmp / "site" / "files"), "file_glob": glob} - return {"id": node_id, "kind": "source", "source": FILES, "args": args, **extra} - nodes = [ - table(f"{name}_{t}", tmp / f"hospital_{name}.db", t) + table(f"{name}_{t}", f"sqlite:///{tmp / f'hospital_{name}.db'}", t) for name, tables in hospital_tables.items() for t in tables ] return { "nodes": nodes + [ - table("his_patients", tmp / "site" / "site.db", "pacientes_his"), - table("archivos", tmp / "site" / "site.db", "ArchivosUni"), - files("notes", "*.csv", source=READERS, resource="read_csv"), - files("altas", "*.xlsx", then="persistance.readers:read_excel"), - files("pdfs", "*.pdf", then="persistance.readers:read_bytes"), + table("archivos", site_url, "ArchivosUni", schema="dbo"), + table("subrogados", site_url, "ResultadosSubrogados", schema="dbo"), {"id": "archivos_text", "kind": "read", "inputs": ["archivos"], "column": "archivo"}, - {"id": "pdfs_text", "kind": "read", "inputs": ["pdfs"], "column": "content"}, + { + "id": "subrogados_text", + "kind": "read", + "inputs": ["subrogados"], + "column": "archivo", + }, ] } SQL_TABLE = "dlt.sources.sql_database:sql_table" -FILES = "dlt.sources.filesystem:filesystem" -READERS = "dlt.sources.filesystem:readers" -def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_path): +def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, site, tmp_path): count, query = platform.count, platform.query tables = {} for name in ("cacu", "cama"): @@ -56,21 +51,19 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con: found = con.execute("select name from sqlite_master where type = 'table'") tables[name] = [t for (t,) in found] - truth = build(FIXTURES / "hospital_cacu.db", tmp_path / "site")["records"] - (tmp_path / "pipeline.json").write_text(json.dumps(graph(tmp_path, tables))) + truth = site.truth + (tmp_path / "pipeline.json").write_text(json.dumps(graph(tmp_path, tables, site.url))) platform.save("pipelines", "site", tmp_path / "pipeline.json") by_place = {} for r in truth: - by_place.setdefault(r["where"].split(":")[0].split("/")[0], []).append(r) + by_place.setdefault(r["where"].split(":")[0], []).append(r) + documents = len(by_place["ArchivosUni"]) + len(by_place["ResultadosSubrogados"]) expected = { - "his_patients": len(by_place["pacientes_his"]), - "altas": len(by_place["altas.xlsx"]), - "notes": len(by_place["consultas.csv"]), "archivos": len(by_place["ArchivosUni"]), - "pdfs": len(by_place["files"]), + "subrogados": len(by_place["ResultadosSubrogados"]), "archivos_text": len(by_place["ArchivosUni"]), - "pdfs_text": len(by_place["files"]), + "subrogados_text": len(by_place["ResultadosSubrogados"]), } for name, names in tables.items(): with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con: @@ -84,7 +77,7 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat platform.ingest() assert counts() == expected read_once = query("select key, _dlt_load_id from bronze.read_cache order by key") - assert len(read_once) == expected["archivos"] + expected["pdfs"] # each file read once + assert len(read_once) == documents # each file read once with sqlite3.connect(tmp_path / "hospital_cacu.db") as con: # a corrected record updates con.execute("update paciente set pac_codigo_postal = '64000' where pac_id = 1") @@ -93,15 +86,16 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat corrected = "select pac_codigo_postal from bronze.n__site__cacu_paciente where pac_id = 1" assert query(corrected) == [("64000",)] - read = query("select id, text, ocr, error from bronze.n__site__archivos_text") - assert [error for *_, error in read if error is not None] == [] space = re.compile(r"\s+") - by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read} - for r in by_place["ArchivosUni"]: - txt, ocr = by_id[int(r["where"].split(":")[1])] - assert bool(ocr) == r["scanned"] # OCR runs on scans, and only on scans - if "record_number" in r["identity"]: # even scanned, the identifier reads back exactly - assert r["identity"]["record_number"] in txt, (r["where"], txt) + for table, node in (("ArchivosUni", "archivos"), ("ResultadosSubrogados", "subrogados")): + read = query(f"select id, text, ocr, error from bronze.n__site__{node}_text") + assert [error for *_, error in read if error is not None] == [] + by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read} + for r in by_place[table]: + txt, ocr = by_id[int(r["where"].split(":")[1])] + assert bool(ocr) == r.get("scanned", False) # OCR runs on scans, and only on scans + if "record_number" in r["identity"]: # even scanned, the number reads back exactly + assert r["identity"]["record_number"] in txt, (r["where"], txt) assert query("select key, _dlt_load_id from bronze.read_cache order by key") == ( read_once ) # reruns never read a file again diff --git a/tests/test_silver.py b/tests/test_silver.py index 19d4b5a..eec1325 100644 --- a/tests/test_silver.py +++ b/tests/test_silver.py @@ -1,41 +1,62 @@ -"""Phase 1 gate: a messy site, drawn once as a pipeline, becomes silver an analyst can trust, -and everything the platform can't decide alone is put in front of a reviewer. +"""Phase 1 gate: ISSSTELEON's test source, drawn once as a pipeline, becomes silver an analyst +can trust, and everything the platform can't decide alone is put in front of a reviewer. -The site hides its answers the way real ones do: demographics split between a database -and an Excel file with mistyped record numbers (one of them another patient's real number), -reports as BLOBs in three layouts (some scanned), loose PDFs, a CSV of consultations, and -contradicting copies of some reports. +The source hides its answers the way the real one does (synthetic.site): one PDF per study in +two SQL Server tables, the institute's forms and what outsourced labs send back; an HPV result +is a document of its own on its cytology's order; pathology comes scanned, the name surname +first and no birth date; some forms say "MA." for María or misspell the name and leave the +employee number out; some HPV reports were re-issued the other way; two women share a name. """ import json +from collections import Counter from datetime import date +from core import catalog + FIELDS = { - "cervical_cytology": ("sample_date", "adequacy", "result", "hpv"), - "cervical_biopsy": ("request_date", "histology"), -} -BOOLS = {"hpv"} + "cervical_cytology": ("sample_date", "report_date", "adequacy", "result", "hpv", "hpv_16", + "hpv_18"), + "cervical_biopsy": ("request_date", "report_date", "histology"), + "mammography": ("exam_date", "report_date", "adequacy", "birads"), + "breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade", + "er", "pr", "her2", "ki67_pct", "size_mm", "stage"), + "breast_treatment": ("start_date", "kind"), + "clinical_note": ("note_date", "specialty", "icd10"), +} # fmt: skip +BOOLS = {"hpv", "hpv_16", "hpv_18"} +NUMBERS = {"ki67_pct", "size_mm"} -def _value(field, v): +def value(field, v): if v is None: return None if field in BOOLS: - return bool(v) + return bool(v) if not isinstance(v, str) else v == "true" + if field in NUMBERS: + return float(v) return v.isoformat() if isinstance(v, date) else str(v) -def test_a_messy_site_becomes_silver_and_review_gets_the_rest(platform, messy_site, tmp_path): - truth = messy_site.truth - (tmp_path / "pipeline.json").write_text(messy_site.drawn) - platform.save("concept_maps", "messy_site", messy_site.concept_map) +def said(record: dict, entity: str) -> dict | None: + """What a document says of one study (an oncology note: its treatment and the note).""" + if entity == "clinical_note": + return record.get("clinical_note") + return record["values"] if record["entity"] == entity else None + + +def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path): + truth = site.truth + (tmp_path / "pipeline.json").write_text(site.drawn) + platform.save("concept_maps", "erick_site", site.concept_map) platform.save("pipelines", "site", tmp_path / "pipeline.json") platform.ingest() q = platform.query - of = messy_site.patients(q) + of = site.patients(q) - # Persons: nobody is merged with somebody else, except where a record number belongs to - # two patients, and that person is held (torn) until a reviewer corrects the record. + # Persons: nobody is merged with somebody else, except the two women of one name, joined + # by a pathology report (it shows no birth date) and held (torn) until a reviewer says + # whose report it is. members: dict[str, set] = {} held, person_of = set(), {} for record, person, why in q("select _record, person_id, _held from bronze.n__site__persons"): @@ -44,98 +65,91 @@ def test_a_messy_site_becomes_silver_and_review_gets_the_rest(platform, messy_si if why: held.add(person) torn = {p for p, who in members.items() if len(who) > 1} - assert torn and torn == held, (torn, held) + assert len(torn) == 1 and torn == held, (torn, held) + assert members[next(iter(torn))] == set(site.meta["namesakes"]) patient = {p: next(iter(who)) for p, who in members.items() if p not in torn} - # A name reaches silver as the registry wrote it (accents, ñ); linking compared it - # without them, so the reports' plain upper-case names still joined. - torn_patients = {x for p in torn for x in members[p]} - written = {r["values"]["full_name"] for r in truth - if r["entity"] == "identity" and r["person"] not in torn_patients} # fmt: skip - names = {text for (text,) in q("select text from silver.person_name")} - assert any("ñ" in n for n in written) and written <= names - - # Every patient split into several persons is in the review queue, joined by candidates. + # Every woman split into several persons (a misspelled form, say) is in the review + # queue, joined by candidates. parts: dict[str, set] = {} for p, x in patient.items(): parts.setdefault(x, set()).add(p) - # A queued person or candidate is one of its records (decisions are kept by record). queued = { frozenset(person_of[r] for r in pair) for pair in q("select person, candidate from bronze.n__site__persons__review") } - for x, persons in parts.items(): - if len(persons) > 1: - reached, frontier = set(), {next(iter(persons))} - while frontier: - reached |= frontier - frontier = { - b for a in frontier for pair in queued if a in pair for b in pair - } - reached - assert persons <= reached, (x, persons) + split = {x: persons for x, persons in parts.items() if len(persons) > 1} + assert split # the misspelled forms, at least + for x, persons in split.items(): + reached, frontier = set(), {next(iter(persons))} + while frontier: + reached |= frontier + frontier = {b for a in frontier for pair in queued if a in pair for b in pair} + frontier -= reached + assert persons <= reached, (x, persons) - # Every value accepted from a document is what the document says. + # Every value accepted from a document is what the document says; and most of what the + # documents say is read (a scan's columns can come back out of order, and a value its + # pattern doesn't find is left out, never guessed). at = {r["where"]: r for r in truth} place = { r: f"ArchivosUni:{i}" for i, r in q("select id, _record from bronze.n__site__archivos") } - place |= {r: f"files/{n}" for n, r in q("select file_name, _record from bronze.n__site__pdfs")} - for entity, fields in FIELDS.items(): - accepted: dict[str, dict] = {} # each accepted record, from its observations (long) + place |= {r: f"ResultadosSubrogados:{i}" + for i, r in q("select id, _record from bronze.n__site__subrogados")} # fmt: skip + record_of = {w: r for r, w in place.items()} + accepted: dict[str, dict[str, dict]] = {} # study -> record -> fields (from silver's long rows) + for entity in FIELDS: + mine = accepted[entity] = {} for record, field, *values in q( "select _record, field, value_text, value_num, value_bool, value_date " f"from bronze.staged__observation where study = '{entity}'" ): - value = next((v for v in values if v is not None), None) - accepted.setdefault(record, dict.fromkeys(fields))[field] = value - for record, values in accepted.items(): + got = next((v for v in values if v is not None), None) + mine.setdefault(record, {})[field] = value(field, got) + assert mine, entity + stated = read = 0 + missed: Counter = Counter() + for record, got in mine.items(): t = at[place[record]] if not t.get("flipped"): - got = {f: _value(f, values[f]) for f in fields} - assert got == {f: t["values"][f] for f in fields}, (t["where"], got) + truly = {f: v for f, v in said(t, entity).items() if v is not None} + assert got == {f: value(f, truly.get(f)) for f in got}, (t["where"], got) + stated, read = stated + len(truly), read + len(got) + missed.update(set(truly) - set(got)) + assert read >= 0.95 * stated, (entity, read, stated, missed) - # A value a rule held (a scan misread: "LJEBG") is held because it is wrong: it is + # A row a rule held because of a value (a scan misread) is held because it is wrong: # never loaded, and a reviewer sees it. misread = set() - for record, raw in q("select _record, _raw from bronze.staged__held"): + for record, entity, raw in q("select _record, study, _raw from bronze.staged__held"): if record in place and person_of.get(record) not in torn: t, got = at[place[record]], json.loads(raw) - fields = FIELDS[t["entity"]] - assert {f: _value(f, got.get(f)) for f in fields} != { - f: t["values"][f] for f in fields}, t["where"] # fmt: skip - misread.add(place[record]) + truly = said(t, entity) + assert {f: value(f, got.get(f)) for f in truly} != { + f: value(f, v) for f, v in truly.items()}, t["where"] # fmt: skip + misread.add(record) - # Silver: everything except contradicting reports, rows of the torn person and misreads. - out = {place[r] for r, p in person_of.items() if p in torn and r in place} | misread - torn_notes = { - (e, date.fromisoformat("-".join(reversed(f.split("/")))).isoformat()) - for e, f, r in q("select expediente, fecha, _record from bronze.n__site__notes") - if person_of.get(r) in torn - } - - def silver(entity): - fields = FIELDS[entity] + # Silver: each person's studies, the records of one study key merged (a cytology form and + # its HPV report are one cytology), but for the torn person's, the misreads, and a study + # whose reports contradict each other (until review says which is right). + for entity, fields in FIELDS.items(): + key = catalog.studies()[entity].key + merged: dict[tuple, dict] = {} + disputed = set() + for r in truth: + record = record_of[r["where"]] + got = accepted[entity].get(record) + if got is None or person_of[record] in torn or record in misread: + continue + at_key = (person_of[record], *(got.get(k) for k in key)) + merged.setdefault(at_key, {}).update(got) + if r.get("conflict"): + disputed.add(at_key) + expected = {(k[0], *(row.get(f) for f in fields)) + for k, row in merged.items() if k not in disputed} # fmt: skip rows = q(f"select person_id, {', '.join(fields)} from silver.{entity}") - return { - (patient[p], *(_value(f, v) for f, v in zip(fields, values, strict=True))) - for p, *values in rows - } - - def expected(entity, keep): - return { - (r["person"], *(r["values"][f] for f in FIELDS[entity])) - for r in truth - if r["entity"] == entity and r["where"] not in out and keep(r) - } - - assert silver("cervical_cytology") == expected( - "cervical_cytology", lambda r: not r.get("conflict") - ) - assert silver("cervical_biopsy") == expected("cervical_biopsy", lambda r: True) - notes = q("select person_id, note_date, specialty, icd10 from silver.clinical_note") - assert sorted((patient[p], *map(str, n)) for p, *n in notes) == sorted( - (r["person"], r["values"]["note_date"], r["values"]["specialty"], r["values"]["icd10"]) - for r in truth - if r["entity"] == "clinical_note" - and (r["person"], r["values"]["note_date"]) not in torn_notes - ) + got = {(p, *(value(f, v) for f, v in zip(fields, values, strict=True))) + for p, *values in rows if p not in torn} # fmt: skip + assert got == expected, (entity, sorted(got - expected, key=str)[:4], + sorted(expected - got, key=str)[:4]) # fmt: skip