Link: reviewer decisions and corrections, orphan candidates by typo-near identifiers; OCR sidecar text

This commit is contained in:
Roberto Treviño
2026-11-24 22:35:13 -06:00
parent 0c4706658b
commit 77fc039586
2 changed files with 206 additions and 92 deletions
+146 -38
View File
@@ -15,11 +15,13 @@ import pdfplumber
import splink.comparison_library as cl
from markitdown import MarkItDown
from openai import OpenAI, OpenAIError
from splink import Linker, SettingsCreator
from splink import Linker, SettingsCreator, block_on
from splink.backends.duckdb import DuckDBAPI
from splink.clustering import cluster_pairwise_predictions_at_threshold
from core.pipeline import (
HELD,
IDENTIFIERS,
QUOTES,
RECORD,
Extract,
@@ -54,13 +56,17 @@ def _reader() -> MarkItDown:
return MarkItDown()
def _lines(text: str) -> str:
"""Non-empty lines, with the spacing inside each collapsed."""
return "\n".join(" ".join(line.split()) for line in text.splitlines() if line.strip())
def _text(content: bytes) -> str:
"""PDFs through pdfplumber's layout mode, which keeps a table's rows on one line each
(spacing within a line collapsed); every other format through MarkItDown."""
if content.startswith(b"%PDF"):
with pdfplumber.open(io.BytesIO(content)) as pdf:
text = "\n".join(page.extract_text(layout=True) or "" for page in pdf.pages)
return "\n".join(" ".join(line.split()) for line in text.splitlines() if line.strip())
return _lines("\n".join(page.extract_text(layout=True) or "" for page in pdf.pages))
return _reader().convert_stream(io.BytesIO(content)).text_content
@@ -69,13 +75,14 @@ def read_file(content: bytes) -> dict:
try:
found = _text(content)
ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS
if ocr:
out = io.BytesIO()
if ocr: # Tesseract's own text (OCRmyPDF's sidecar), from the deskewed page
text = io.BytesIO()
ocrmypdf.ocr(
io.BytesIO(content), out, language="spa", skip_text=True,
io.BytesIO(content), io.BytesIO(), language="spa", skip_text=True,
output_type="pdf", optimize=0, progress_bar=False, jobs=1, deskew=True,
sidecar=text,
) # fmt: skip
found = _text(out.getvalue())
found = _lines(text.getvalue().decode())
return {"text": found, "ocr": ocr, "error": None}
except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
@@ -179,52 +186,153 @@ def _comparison(field: str):
return cl.ExactMatch(field)
def run_link(p: str, node: Link):
"""Persons from the node's rules (Splink deterministic linking and clustering). A person
whose records disagree on birth date or sex is held; pairs Splink scores above
`review` that the rules left apart are queued for review."""
def _plain(identifier: str) -> str:
"""An identifier as compared: letters and digits only, upper case."""
return "".join(ch for ch in identifier if ch.isalnum()).upper()
def _near(identifier: str) -> list[str]:
"""The identifier and every version of it with one character left out: two identifiers
one typo apart (a wrong, missing, extra or swapped character) share one of these."""
return sorted(
{identifier} | {identifier[:i] + identifier[i + 1 :] for i in range(len(identifier))}
)
def _identities(p: str, node: Link) -> pd.DataFrame:
"""One row per record: its identity fields (first value found, reviewers' corrections
applied, identifiers plain); records rejected for identity are left out."""
skip, fixed = nodes.rejected("identity"), nodes.corrections()
records: dict[str, dict] = {}
for i in node.inputs:
for row in nodes.rows(p, i):
if row.get(HELD):
if row.get(HELD) or row[RECORD] in skip:
continue
row = {**row, **fixed.get(row[RECORD], {})} # a reviewer's correction wins
mine = records.setdefault(row[RECORD], {"unique_id": row[RECORD]})
for f in node.fields:
if row.get(f) is not None and mine.get(f) is None:
mine[f] = str(row[f])
value = str(row[f])
mine[f] = _plain(value) if f in IDENTIFIERS else value
frame = pd.DataFrame(list(records.values()))
fields = [f for f in node.fields if f in frame and frame[f].notna().any()]
frame = frame[["unique_id", *fields]]
rules = node.rules or node.default_rules()
rules = [r for r in rules if all(f"l.{f}" not in r or f in fields for f in node.fields)]
settings = SettingsCreator(
link_type="dedupe_only",
comparisons=[_comparison(f) for f in fields],
blocking_rules_to_generate_predictions=rules,
return frame[["unique_id", *(f for f in node.fields if f in frame and frame[f].notna().any())]]
def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.DataFrame:
clusters = cluster_pairwise_predictions_at_threshold(
records[["unique_id"]], edges, db, "unique_id", "unique_id_l", "unique_id_r"
)
linker = Linker(DuckDBAPI().register(frame), settings, log_level=None)
sure = linker.inference.deterministic_link()
clusters = linker.clustering.cluster_pairwise_predictions_at_threshold(sure)
persons = clusters.as_pandas_dataframe()[["unique_id", "cluster_id"]].merge(frame)
return clusters.as_pandas_dataframe()[["unique_id", "cluster_id"]].merge(records)
def run_link(p: str, node: Link):
"""Persons: records the node's rules join (Splink deterministic linking), joined or kept
apart by reviewers' decisions. A person whose records disagree on birth date or sex is
held. Persons that may be one (identifiers one typo apart, or the same birth date) and
don't contradict each other are queued for review, with Splink's probability."""
records = _identities(p, node)
fields = [c for c in records.columns if c != "unique_id"]
rules = [r for r in node.rules or node.default_rules()
if all(f"l.{f}" not in r or f in fields for f in node.fields)] # fmt: skip
comparisons = [_comparison(f) for f in fields]
db = DuckDBAPI()
linker = Linker(
db.register(records),
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
blocking_rules_to_generate_predictions=rules),
log_level=None,
) # fmt: skip
decided = nodes.person_decisions()
sure = linker.inference.deterministic_link().as_pandas_dataframe()
pairs = {frozenset(e) for e in zip(sure.unique_id_l, sure.unique_id_r, strict=True)}
pairs = {e for e in pairs if decided.get(e, True)} | {e for e, same in decided.items() if same}
known = set(records.unique_id)
edges = pd.DataFrame(
[sorted(e) for e in pairs if e <= known], columns=["unique_id_l", "unique_id_r"]
)
persons = _persons(records, edges, db)
facts = [f for f in ("birth_date", "sex") if f in fields]
torn = set()
if facts:
spread = persons.groupby("cluster_id")[facts].nunique()
torn = set(spread[(spread > 1).any(axis=1)].index)
spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame()
torn = set(spread[(spread > 1).any(axis=1)].index) if facts else set()
held = json.dumps(["records of this person disagree on birth date or sex"])
columns = {f: {"data_type": "text", "nullable": True} for f in (HELD, *fields)}
nodes.write(p, node.id, [
{RECORD: r.unique_id, "person_id": r.cluster_id,
HELD: held if r.cluster_id in torn else None}
HELD: held if r.cluster_id in torn else None,
**{f: getattr(r, f) for f in fields}}
for r in persons.itertuples()
], {HELD: {"data_type": "text", "nullable": True}}) # fmt: skip
], columns) # fmt: skip
linker.training.estimate_u_using_random_sampling(max_pairs=1e6)
person = dict(zip(persons.unique_id, persons.cluster_id, strict=True))
maybe = linker.inference.predict(threshold_match_probability=node.review).as_pandas_dataframe()
return nodes.write(p, f"{node.id}__review", [
{"record_l": r.unique_id_l, "record_r": r.unique_id_r, "probability": r.match_probability}
for r in maybe.itertuples() if person[r.unique_id_l] != person[r.unique_id_r]
]) # fmt: skip
# One row per person, so random pairs are different people and Splink's u is honest.
ids = [f for f in IDENTIFIERS if f in fields]
whole = persons.drop(columns="unique_id").groupby("cluster_id").first()
for f in ids:
near = (
persons.dropna(subset=[f])
.groupby("cluster_id")[f]
.agg(lambda values: sorted({n for v in values for n in _near(v)}))
)
whole[f"{f}_near"] = near.reindex(whole.index).apply(
lambda v: v if isinstance(v, list) else []
)
whole = whole.reset_index().rename(columns={"cluster_id": "unique_id"})
blocks = [block_on(f"{f}_near", arrays_to_explode=[f"{f}_near"]) for f in ids]
reasons = [f"{f} one typo apart" for f in ids]
if "birth_date" in fields:
blocks.append(block_on("birth_date"))
reasons.append("same birth date")
model = Linker(
db.register(whole),
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
blocking_rules_to_generate_predictions=blocks),
log_level=None,
) # fmt: skip
model.training.estimate_u_using_random_sampling(max_pairs=1e6)
found = model.inference.predict(warning_mode="never").as_pandas_dataframe()
known = [f for f in ("birth_date", "sex", "postal_code") if f in fields]
orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set()
lone = set() # persons whose identifier is carried by one record only
for f in ids:
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
lone |= {person for (person, _), n in carried.items() if n == 1}
def settle(r) -> tuple[str, str] | None:
"""(the person to settle, a possible owner), or None when the pair is implausible:
they contradict each other, or one typo apart is all they share (with sequential
record numbers every patient has such neighbours) unless one side has no
demographics and the other's identifier stands on a single record."""
a, b = r.unique_id_l, r.unique_id_r
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
if frozenset((a, b)) in decided or any(
pd.notna(x) and pd.notna(y) and x != y for x, y in sides
):
return None
if not reasons[int(r.match_key)].endswith("typo apart"):
return a, b
if a in orphan and b in lone:
return a, b
if b in orphan and a in lone:
return b, a
return None
side = {r.unique_id: r for r in whole.itertuples()}
queue = []
for r in found.itertuples():
if pair := settle(r):
person, owner = pair
queue.append(
{
"person": person,
"candidate": owner,
"probability": r.match_probability,
"reason": reasons[int(r.match_key)],
**{f"person_{f}": getattr(side[person], f) for f in fields},
**{f"candidate_{f}": getattr(side[owner], f) for f in fields},
}
)
return nodes.write(p, f"{node.id}__review", queue)
def run_target(p: str, node: Target, kinds: dict[str, str]):
+60 -54
View File
@@ -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
)