"""Runs a pipeline graph: each node, after its inputs, writes its output table; then dbt places what the targets staged into silver.""" import io import json import unicodedata from collections.abc import Callable from concurrent.futures import ProcessPoolExecutor from functools import cache import duckdb import ocrmypdf import pandas as pd import pdfplumber import pikepdf import splink.comparison_library as cl from markitdown import MarkItDown from splink import Linker, SettingsCreator, block_on from splink.backends.duckdb import DuckDBAPI from splink.clustering import cluster_pairwise_predictions_at_threshold from core import catalog, concept_map, fhir_in from core.drafting import extract_prompt from core.pipeline import ( HELD, IDENTIFIERS, QUOTES, RECORD, Extract, Fhir, Join, Link, Map, Pipeline, Read, Route, Target, answer_schema, apply_patterns, ground, join, map_row, matches, validate, ) from models import suggest from persistance import config_log, files, llm, nodes, silver MIN_WORDS = 5 # fewer than this from a PDF page means it has no text layer READ_BATCH = 32 # files read at a time (a read is kept as soon as its batch is done) FILE = "_file" # the read file's key (persistance.files): its pages, for a model that sees READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error` "text": {"data_type": "text", "nullable": True}, "ocr": {"data_type": "bool"}, "error": {"data_type": "text", "nullable": True}, "format": {"data_type": "text", "nullable": True}, } ROW_COLUMNS = {**READ_COLUMNS, FILE: {"data_type": "text", "nullable": True}} def file_format(content: bytes) -> str: """What kind of file this is, from its first bytes, so a route can tell a PDF from an EEG recording in the same column: pdf, edf (EDF and EDF+: a fixed ASCII header whose version is "0"), or other (whatever MarkItDown reads).""" if content.startswith(b"%PDF"): return "pdf" head = content[:256] if len(head) == 256 and head[:8] == b"0 " and head[184:192].strip().isdigit(): return "edf" return "other" @cache 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: """Files other than PDFs, through MarkItDown.""" return _reader().convert_stream(io.BytesIO(content)).text_content def _pdf_pages(content: bytes) -> list[str]: """Each page's text layer, through pdfplumber's layout mode, which keeps a table's rows on one line each (spacing within a line collapsed).""" with pdfplumber.open(io.BytesIO(content)) as pdf: return [_lines(page.extract_text(layout=True) or "") for page in pdf.pages] def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]: """Tesseract's text (OCRmyPDF's sidecar, from the deskewed page) of these pages only, copied into a PDF of their own: a typed page keeps its own text layer.""" source, scans = pikepdf.open(io.BytesIO(content)), pikepdf.new() for n in numbers: scans.pages.append(source.pages[n]) pages, sidecar = io.BytesIO(), io.BytesIO() scans.save(pages) pages.seek(0) ocrmypdf.ocr( pages, io.BytesIO(), language="spa", force_ocr=True, output_type="pdf", optimize=0, progress_bar=False, jobs=1, deskew=True, sidecar=sidecar, ) # fmt: skip found = sidecar.getvalue().decode().split("\f") return [_lines(found[i]) if i < len(found) else "" for i in range(len(numbers))] def read_file(content: bytes) -> dict: """Text of one file, its format, and whether OCR was needed. An unreadable file keeps its error; a signal recording (EDF) has no text to read.""" kind = file_format(content) if kind == "edf": return {"text": None, "ocr": False, "error": None, "format": kind} return {**_read_text(content), "format": kind} def _read_text(content: bytes) -> dict: """The file's text; a PDF page by page, OCR only on the pages without a text layer (a typed form whose second page is a scan, say).""" try: if not content.startswith(b"%PDF"): return {"text": _text(content), "ocr": False, "error": None} pages = _pdf_pages(content) scanned = [i for i, page in enumerate(pages) if len(page.split()) < MIN_WORDS] if scanned: for i, page in zip(scanned, _ocr_pages(content, scanned), strict=True): pages[i] = page return {"text": "\n".join(p for p in pages if p), "ocr": bool(scanned), "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}"} def run_read(p: str, node: Read): """The input's rows with their file's text and format beside the file column (which keeps the file, for a study that takes the file itself: an EEG's recording); each file read once.""" rows = list(nodes.rows(p, node.inputs[0])) for row in rows: # the source kept the file; the row carries its hash row["key"] = row.get(node.column) or None keys = {r["key"] for r in rows} - {None} found = nodes.cached("read_cache", keys) legacy = [k for k, r in found.items() if r.get("format") is None] # read before formats for k in legacy: found[k]["format"] = file_format(files.content(k) or b"") nodes.remember("read_cache", [{"key": k, **{c: found[k][c] for c in READ_COLUMNS}} for k in legacy], READ_COLUMNS) # fmt: skip new = sorted(keys - set(found)) with ProcessPoolExecutor() as pool: # a batch of files in memory at a time, each kept for start in range(0, len(new), READ_BATCH): batch = new[start : start + READ_BATCH] read = dict(zip(batch, pool.map(read_file, (files.content(k) for k in batch)), strict=True)) # fmt: skip nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()], READ_COLUMNS) # fmt: skip found |= read for row in rows: row[FILE] = row.pop("key") result = found.get(row[FILE], {"text": None, "ocr": False, "error": "empty"}) row |= {k: result[k] for k in READ_COLUMNS} return nodes.write(p, node.id, rows, ROW_COLUMNS) def run_route(p: str, node: Route, others: list[Route] = ()): """The input's rows the route takes; an `otherwise` route, those `others` don't.""" rows = nodes.rows(p, node.inputs[0]) taken = [r for r in rows if matches(node, r) and not any(matches(o, r) for o in others)] return nodes.write(p, node.id, taken) def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]: """The node's ConceptMap as a translation table per field (none without one).""" if node.concept_map is None: return {} found = config_log.concept_map(node.concept_map) return {f: concept_map.table([found], f) for f in fields} def run_map(p: str, node: Map): codes = _codes(node, node.fields) rows = [map_row(node, r, codes) for r in nodes.rows(p, node.inputs[0])] return nodes.write(p, node.id, rows) def run_fhir(p: str, node: Fhir): """Each Bundle's rows of the node's entity; a resource sent again is its latest.""" maps = [config_log.concept_map(node.concept_map)] if node.concept_map else [] found: dict[str, dict] = {} for row in nodes.rows(p, node.inputs[0]): bundle = json.loads(row[node.column]) for r in fhir_in.rows(bundle, node.entity, p, maps): found[r[RECORD]] = r return nodes.write(p, node.id, list(found.values())) def run_join(p: str, node: Join): left, right = (list(nodes.rows(p, i)) for i in node.inputs) return nodes.write(p, node.id, join(node, left, right, node.inputs[1])) def page_images(content: bytes, pages: int = 2) -> list[bytes]: """The first pages of a PDF as PNG pictures, for a model that reads images (a scan's OCR text misses what the picture still shows).""" out = [] with pdfplumber.open(io.BytesIO(content)) as pdf: for page in pdf.pages[:pages]: picture = io.BytesIO() page.to_image(resolution=110).original.save(picture, format="PNG") out.append(picture.getvalue()) return out def images(row: dict) -> list[bytes]: """A scanned document's pages as pictures, when the model reads them.""" if not (row.get("ocr") and row.get(FILE) and llm.vision()): return [] content = files.content(row[FILE]) return page_images(content) if content and file_format(content) == "pdf" else [] def answer(entity: str, text: str, hints: str = "", pictures: list[bytes] = ()) -> dict: """The model's records of `entity` in `text`, each value with the text it was read from (the same question for the same document is asked once).""" return llm.ask(extract_prompt(entity, hints), text, answer_schema(entity), pictures) def run_extract(p: str, node: Extract): use_llm = node.method == "llm" or (node.method == "auto" and llm.available()) codes = _codes(node, node.patterns) out = [] for row in nodes.rows(p, node.inputs[0]): text = node.text(row) if use_llm: try: found = ground(answer(node.entity, text, node.hints, images(row)), text) except llm.Unreadable as e: # this document waits for a reviewer, not the run found = [({}, {}, [f"the model's answer could not be read: {e}"])] elif node.patterns: found = apply_patterns(node, text, codes) else: found = [({}, {}, ["no LLM answering and no patterns set"])] taken = {f: row[c] for f, c in node.columns.items() if row.get(c) is not None} for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]): out.append({**values, **taken, RECORD: row[RECORD], "_index": index, QUOTES: json.dumps(quotes, ensure_ascii=False), HELD: json.dumps(held) if held else None}) # fmt: skip return nodes.write(p, node.id, out) def _comparison(field: str): if field == "birth_date": return cl.DateOfBirthComparison(field, input_is_string=True) if field == "full_name": return cl.NameComparison(field) if field in ("record_number", "curp", "nss"): return cl.LevenshteinAtThresholds(field, [1, 2]) return cl.ExactMatch(field) 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 _name(name: str) -> str: """A name as compared: upper case, without accents, single spaces.""" plain = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode() return " ".join(plain.upper().split()) 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) -> tuple[pd.DataFrame, dict[str, str], dict[str, str]]: """One row per record: its identity fields (first value found, reviewers' corrections applied, identifiers plain); records rejected for identity are left out. And the input each record came through (its record number's system), and its name as written.""" skip, fixed = nodes.rejected("identity"), nodes.corrections() records: dict[str, dict] = {} sources: dict[str, str] = {} written: dict[str, str] = {} # each record's name as it came (compared normalised) for i in node.inputs: for row in nodes.rows(p, i): 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]}) sources.setdefault(row[RECORD], i) for f in node.fields: if row.get(f) is not None and mine.get(f) is None: value = str(row[f]) if f == "full_name": written[row[RECORD]] = " ".join(value.split()) mine[f] = ( _plain(value) if f in IDENTIFIERS else _name(value) if f == "full_name" else value ) # fmt: skip frame = pd.DataFrame(list(records.values())) present = [f for f in node.fields if f in frame and frame[f].notna().any()] return frame[["unique_id", *present]], sources, written def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.Series: """Each record's stand-in: one record per identity that the rules join to itself (a patient's 24 reports carrying one record number are one row to compare, not 24² pairs). A record a reviewer judged stands for itself, and so does one the rules would not join to an identical record (nothing compared was read, say).""" fields = [c for c in records.columns if c != "unique_id"] key = records[fields].astype(object).where(records[fields].notna(), None) same = pd.Series(list(key.itertuples(index=False, name=None)), index=records.index) stand_in = records.groupby(same, sort=False)["unique_id"].transform("first") stand_in = stand_in.where(~records["unique_id"].isin(judged), records["unique_id"]) joined = set() if rules: con = duckdb.connect() con.register("candidates", records[records["unique_id"].isin(set(stand_in))]) joins = " or ".join(f"({r})" for r in rules) joined = set(con.sql( f"select l.unique_id from candidates l join candidates r" f" on l.unique_id = r.unique_id where {joins}" ).df()["unique_id"]) # fmt: skip return stand_in.where(stand_in.isin(joined), records["unique_id"]) 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" ) 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. A person with nothing that names her (no name, birth date or record number read) is held too.""" records, sources, written = _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] decided = nodes.person_decisions() stand_in = _distinct(records, rules, set().union(*decided)) distinct = records[records["unique_id"].isin(set(stand_in))] db = DuckDBAPI() linker = Linker( db.register(distinct), SettingsCreator(link_type="dedupe_only", comparisons=comparisons, blocking_rules_to_generate_predictions=rules), log_level=None, ) # fmt: skip 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(distinct.unique_id) edges = pd.DataFrame( [sorted(e) for e in pairs if e <= known], columns=["unique_id_l", "unique_id_r"] ) cluster = _persons(distinct, edges, db).set_index("unique_id")["cluster_id"] persons = records.assign(cluster_id=stand_in.map(cluster).to_numpy()) facts = [f for f in ("birth_date", "sex") if f in fields] 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() # Nothing that names her was read (a scan's name line misread, say): nobody to join. read = persons.groupby("cluster_id")[[f for f in fields if f != "sex"]].count().sum(axis=1) nameless = set(read[read == 0].index) why = {c: "records of this person disagree on birth date or sex" for c in torn} why |= {c: "no name, birth date or record number was read" for c in nameless - torn} columns = {f: {"data_type": "text", "nullable": True} for f in (HELD, "_source", *fields)} stable = nodes.stable_persons(persons.groupby("cluster_id")["unique_id"].apply(list).to_dict()) linked = [ {RECORD: r.unique_id, "person_id": stable[r.cluster_id], "_source": sources[r.unique_id], HELD: json.dumps([why[r.cluster_id]]) if r.cluster_id in why else None, **{f: getattr(r, f) for f in fields}, **({"full_name": written[r.unique_id]} if r.unique_id in written else {})} for r in persons.itertuples() ] # fmt: skip nodes.write(p, node.id, linked, columns) nodes.stage("identity", p, node.id, linked, silver.identity_columns()) # silver.person # 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") if f in fields] orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set() # no birth date to tell her apart (a pathology scan: a name, misread or not, and a sex) undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set() # Answers are kept by record; a person is known by any of hers, whatever joined since. whose = persons.set_index("unique_id")["cluster_id"].to_dict() answered = {frozenset(whose.get(r, r) for r in e) for e in decided} 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. Names one typo apart are rare: an undated side (a misread pathology scan) is always queued; so is the very same identifier on a record that says nothing else (a scan read only in part).""" 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 answered or any( pd.notna(x) and pd.notna(y) and x != y for x, y in sides ): return None reason = reasons[int(r.match_key)] if not reason.endswith("typo apart"): return a, b field = reason.removesuffix(" one typo apart") if getattr(r, f"{field}_l") == getattr(r, f"{field}_r"): # the very same identifier return (a, b) if a in undated or b not in undated else (b, a) if field == "full_name" and (a in undated) != (b in undated): return (a, b) if a in undated else (b, a) # names are rarely one typo apart 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]): """Rows of one study into silver's staging, each given its person by the link node: a clean row becomes one observation per field it has (long), keyed by its study instance (the study's key values); a row a rule held waits for review, whole.""" link = next(i for i in node.inputs if kinds[i] == "link") 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") else: held += json.loads(linked[row[RECORD]].get(HELD) or "[]") base = {"study": node.entity, "person_id": person.get(row[RECORD]), RECORD: row[RECORD], "_index": row.get("_index", 0), QUOTES: row.get(QUOTES)} # fmt: skip if held: raw = json.dumps(values, default=str, ensure_ascii=False) held_rows.append({**base, HELD: json.dumps(held), "_raw": raw}) continue clean = model.model_validate(values) instance = json.dumps([str(getattr(clean, k)) for k in model.key]) for name, field in study.fields.items(): if (value := getattr(clean, name)) is not None: observations.append({**base, "instance": instance, "field": name, catalog.value_column(field): value}) # fmt: skip nodes.stage("observation", p, node.id, observations, silver.OBSERVATION) return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS) RUNNERS: dict[str, Callable] = { "source": nodes.run_source, "read": run_read, "route": run_route, "map": run_map, "join": run_join, "extract": run_extract, "link": run_link, "fhir": run_fhir, } # fmt: skip def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print) -> None: kinds = {n.id: n.kind for n in pipeline.nodes} for node in pipeline.order(): if node.kind == "target": run_target(pipeline_id, node, kinds) elif node.kind == "route" and node.otherwise: others = [n for n in pipeline.nodes if n.kind == "route" and n.id != node.id and n.inputs == node.inputs and not n.otherwise] # fmt: skip run_route(pipeline_id, node, others) else: RUNNERS[node.kind](pipeline_id, node) log(f"{node.id} ({node.kind}) done") if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}): silver.build(["silver+"]) # every entity (empty if never staged) and what derives log(f"silver and gold, from {', '.join(entities)}") links = [n.id for n in pipeline.nodes if n.kind == "link"] if links and llm.available(): # the model's reading beside what waits for reviewers for link in links: suggest.persons(pipeline_id, link) log(f"suggestions for review: {', '.join(links)}")