Link: reviewer decisions and corrections, orphan candidates by typo-near identifiers; OCR sidecar text
This commit is contained in:
+60
-54
@@ -1,18 +1,14 @@
|
||||
"""Phase 1 gate: a messy site, drawn once as a pipeline, becomes silver an analyst can trust.
|
||||
"""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.
|
||||
|
||||
The site hides its answers the way real ones do: demographics split between a database
|
||||
and an Excel file with mistyped record numbers, reports as BLOBs in three layouts (some
|
||||
scanned), loose PDFs, a CSV of consultations, and contradicting copies of some reports.
|
||||
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.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from synthetic.site import build
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital" / "hospital_cacu.db"
|
||||
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "messy_site.json"
|
||||
FIELDS = {
|
||||
"cervical_cytology": ("sample_date", "adequacy", "result", "hpv"),
|
||||
"cervical_biopsy": ("request_date", "histology"),
|
||||
@@ -28,44 +24,67 @@ def _value(field, v):
|
||||
return v.isoformat() if isinstance(v, date) else str(v)
|
||||
|
||||
|
||||
def test_a_messy_site_becomes_silver_with_no_wrong_value(platform, tmp_path):
|
||||
truth = build(HOSPITAL, tmp_path / "site")["records"]
|
||||
at = {r["where"]: r for r in truth}
|
||||
drawn = PIPELINE.read_text().replace("{site}", str(tmp_path / "site"))
|
||||
(tmp_path / "pipeline.json").write_text(drawn)
|
||||
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.run("python", "-m", "persistance.config_log", "site", str(tmp_path / "pipeline.json"))
|
||||
platform.ingest()
|
||||
q = platform.query
|
||||
of = messy_site.patients(q)
|
||||
|
||||
# Which place in the site each record came from (only for checking against the truth).
|
||||
where = {
|
||||
r: f"ArchivosUni:{i}" for i, r in q("select id, _record from bronze.n__site__archivos")
|
||||
}
|
||||
where |= {r: f"files/{n}" for n, r in q("select file_name, _record from bronze.n__site__pdfs")}
|
||||
where |= {
|
||||
r: f"pacientes_his:{n}"
|
||||
for n, r in q("select num, _record from bronze.n__site__his_patients")
|
||||
}
|
||||
# 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.
|
||||
members: dict[str, set] = {}
|
||||
held, person_of = set(), {}
|
||||
for record, person, why in q("select _record, person_id, _held from bronze.n__site__persons"):
|
||||
members.setdefault(person, set()).add(of[record])
|
||||
person_of[record] = person
|
||||
if why:
|
||||
held.add(person)
|
||||
torn = {p for p, who in members.items() if len(who) > 1}
|
||||
assert torn and torn == held, (torn, held)
|
||||
patient = {p: next(iter(who)) for p, who in members.items() if p not in torn}
|
||||
|
||||
# Nobody is merged with somebody else.
|
||||
patients_of: dict[str, set] = {}
|
||||
for record, person in q("select _record, person_id from bronze.n__site__persons"):
|
||||
if record in where:
|
||||
patients_of.setdefault(person, set()).add(at[where[record]]["person"])
|
||||
assert all(len(p) == 1 for p in patients_of.values()), patients_of
|
||||
patient = {person: next(iter(p)) for person, p in patients_of.items()}
|
||||
# Every patient split into several persons is in the review queue, joined by candidates.
|
||||
parts: dict[str, set] = {}
|
||||
for p, x in patient.items():
|
||||
parts.setdefault(x, set()).add(p)
|
||||
queued = {
|
||||
frozenset(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)
|
||||
|
||||
# Every value accepted from a document is what the document says.
|
||||
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():
|
||||
cols = ", ".join(fields)
|
||||
for record, held, *values in q(
|
||||
f"select _record, _held, {cols} from bronze.staged__{entity}"
|
||||
):
|
||||
t = at[where[record]]
|
||||
if held is None and not t.get("flipped"):
|
||||
rows = q(f"select _record, _held, {', '.join(fields)} from bronze.staged__{entity}")
|
||||
for record, why, *values in rows:
|
||||
t = at[place[record]]
|
||||
if why is None and not t.get("flipped"):
|
||||
got = {f: _value(f, v) for f, v in zip(fields, values, strict=True)}
|
||||
assert got == {f: t["values"][f] for f in fields}, (t["where"], got)
|
||||
|
||||
# Silver: everything except contradicting reports and rows of the torn person.
|
||||
out = {place[r] for r, p in person_of.items() if p in torn and r in place}
|
||||
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]
|
||||
rows = q(f"select person_id, {', '.join(fields)} from silver.{entity}")
|
||||
@@ -78,30 +97,17 @@ def test_a_messy_site_becomes_silver_with_no_wrong_value(platform, tmp_path):
|
||||
return {
|
||||
(r["person"], *(r["values"][f] for f in FIELDS[entity]))
|
||||
for r in truth
|
||||
if r["entity"] == entity and keep(r)
|
||||
if r["entity"] == entity and r["where"] not in out and keep(r)
|
||||
}
|
||||
|
||||
# Contradicting reports stay out until a reviewer decides; everything else is in.
|
||||
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 note_date, specialty, icd10 from silver.clinical_note")
|
||||
assert sorted(tuple(map(str, n)) for n in notes) == sorted(
|
||||
(r["values"]["note_date"], r["values"]["specialty"], r["values"]["icd10"])
|
||||
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"
|
||||
)
|
||||
|
||||
# The reviewer rejects each wrong copy; the next run places the right value.
|
||||
wrong = [rec for rec, w in where.items() if at[w].get("flipped")]
|
||||
assert wrong
|
||||
reject = "; ".join(
|
||||
f"nodes.reject('cervical_cytology', {rec!r}, 'contradicts the original report', 'qa')"
|
||||
for rec in wrong
|
||||
)
|
||||
platform.run("python", "-c", f"from persistance import nodes; {reject}")
|
||||
platform.ingest()
|
||||
assert silver("cervical_cytology") == expected(
|
||||
"cervical_cytology", lambda r: not r.get("flipped")
|
||||
and (r["person"], r["values"]["note_date"]) not in torn_notes
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user