Files
models/models/graph.py
T

428 lines
18 KiB
Python

"""Runs a pipeline graph: each node, after its inputs, writes its output table; then dbt
places what the targets staged into silver."""
import hashlib
import io
import json
import os
import unicodedata
from collections.abc import Callable
from concurrent.futures import ProcessPoolExecutor
from functools import cache
import ocrmypdf
import pandas as pd
import pdfplumber
import splink.comparison_library as cl
from markitdown import MarkItDown
from openai import OpenAI, OpenAIError
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.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 persistance import config_log, nodes, silver
MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer
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},
}
@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:
"""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:
return _lines("\n".join(page.extract_text(layout=True) or "" for page in pdf.pages))
return _reader().convert_stream(io.BytesIO(content)).text_content
def read_file(content: bytes) -> dict:
"""Text of one file, and whether OCR was needed. An unreadable file keeps its error."""
try:
found = _text(content)
ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS
if ocr: # Tesseract's own text (OCRmyPDF's sidecar), from the deskewed page
text = io.BytesIO()
ocrmypdf.ocr(
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 = _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}"}
def run_read(p: str, node: Read):
"""The input's rows with the file column replaced by its text; each file read once."""
rows = list(nodes.rows(p, node.inputs[0]))
keys = {}
for row in rows:
content = row.pop(node.column)
row["key"] = hashlib.sha256(content).hexdigest() if content else None
keys[row["key"]] = content
found = nodes.cached("read_cache", set(keys) - {None})
new = {k: c for k, c in keys.items() if k and k not in found}
with ProcessPoolExecutor() as pool:
read = dict(zip(new, pool.map(read_file, new.values()), strict=True))
nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()], READ_COLUMNS)
found |= read
for row in rows:
result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"})
row |= {k: result[k] for k in READ_COLUMNS}
return nodes.write(p, node.id, rows, READ_COLUMNS)
def run_route(p: str, node: Route):
return nodes.write(p, node.id, [r for r in nodes.rows(p, node.inputs[0]) if matches(node, r)])
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]))
@cache
def _llm() -> tuple[OpenAI, str] | None:
"""The configured OpenAI-compatible endpoint, if it answers; None otherwise."""
if not (url := os.environ.get("LLM_URL")):
return None
client = OpenAI(base_url=url, api_key=os.environ.get("LLM_API_KEY", "none"), timeout=600)
try:
client.models.list()
except OpenAIError:
return None
return client, os.environ["LLM_MODEL"]
PROMPT = (
"Extract every {entity} record stated in the document. For each field give its value "
"in the schema's terms and `quote`: the exact text of the document it was read from, "
"copied character by character. Leave out fields the document does not state.{hints}"
)
def _ask_llm(node: Extract, text: str) -> dict:
client, model = _llm()
system = PROMPT.format(entity=node.entity, hints=f"\n{node.hints}" if node.hints else "")
key = hashlib.sha256(json.dumps([model, system, text]).encode()).hexdigest()
if found := nodes.cached("llm_cache", {key}):
return json.loads(found[key]["answer"])
reply = client.chat.completions.create(
model=model, temperature=0, seed=7,
messages=[{"role": "system", "content": system}, {"role": "user", "content": text}],
response_format={"type": "json_schema", "json_schema": {
"name": "answer", "schema": answer_schema(node.entity), "strict": True}},
) # fmt: skip
answer = reply.choices[0].message.content
nodes.remember("llm_cache", [{"key": key, "answer": answer, "model": model}], {})
return json.loads(answer)
def run_extract(p: str, node: Extract):
use_llm = node.method == "llm" or (node.method == "auto" and _llm() is not None)
codes = _codes(node, node.patterns)
out = []
for row in nodes.rows(p, node.inputs[0]):
text = row.get(node.column) or ""
if use_llm:
found = ground(_ask_llm(node, text), text)
elif node.patterns:
found = apply_patterns(node, text, codes)
else:
found = [({}, {}, ["no LLM answering and no patterns set"])]
for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]):
out.append({**values, 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]]:
"""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)."""
skip, fixed = nodes.rejected("identity"), nodes.corrections()
records: dict[str, dict] = {}
sources: dict[str, str] = {}
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])
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
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."""
records, sources = _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]
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, "_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: held if r.cluster_id in torn else None,
**{f: getattr(r, f) for f in fields}}
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()
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]):
"""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]
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}
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)
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)}")