Files
models/models/graph.py
T
alberto 24534606f1 C1a: code only, no comments, no Markdown
Remove 212 Python docstrings and 118 comments, and trim prose from three noqa pragmas. The submodule had zero tracked Markdown files.

Preserve the existing executable statements and lint pragmas. Use pass for class bodies that previously consisted of only a docstring.
2026-12-01 16:55:32 -06:00

523 lines
22 KiB
Python

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 duckdb
import ocrmypdf
import pandas as pd
import pdfplumber
import pikepdf
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,
Edf,
Extract,
Fhir,
Join,
Link,
Map,
Pipeline,
Read,
Route,
Target,
answer_schema,
apply_patterns,
ground,
join,
map_row,
matches,
validate,
)
from models.tea.eeg import read
from persistance import config_log, files, nodes, silver
MIN_WORDS = 5
READ_BATCH = 32
READ_COLUMNS = {
"text": {"data_type": "text", "nullable": True},
"ocr": {"data_type": "bool"},
"error": {"data_type": "text", "nullable": True},
"format": {"data_type": "text", "nullable": True},
}
EDF_COLUMNS = {f"edf_{name}": {"data_type": kind, "nullable": True} for name, kind in (
("patient_code", "text"), ("sex", "text"), ("birth_date", "text"), ("study_date", "text"),
("record_code", "text"), ("duration_s", "double"), ("channels", "bigint"), ("error", "text"),
)} # fmt: skip
def file_format(content: bytes) -> str:
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:
return "\n".join(" ".join(line.split()) for line in text.splitlines() if line.strip())
def _text(content: bytes) -> str:
return _reader().convert_stream(io.BytesIO(content)).text_content
def _pdf_pages(content: bytes) -> list[str]:
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]:
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:
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:
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
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
def run_read(p: str, node: Read):
rows = list(nodes.rows(p, node.inputs[0]))
for row in rows:
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]
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:
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:
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_edf(p: str, node: Edf):
rows = list(nodes.rows(p, node.inputs[0]))
empty = dict.fromkeys(EDF_COLUMNS)
found = {None: {**empty, "edf_error": "empty"}}
for key in {row.get(node.column) for row in rows} - {None}:
content = files.content(key)
if content is None:
found[key] = {**empty, "edf_error": "no file"}
continue
try:
h = read.header(content)
except read.FileNotValid as exc:
found[key] = {**empty, "edf_error": str(exc)}
continue
found[key] = {
"edf_patient_code": h.patient_code,
"edf_sex": h.sex,
"edf_birth_date": h.birthdate.isoformat() if h.birthdate else None,
"edf_study_date": h.start_date.isoformat() if h.start_date else None,
"edf_record_code": h.record_code,
"edf_duration_s": h.duration_s,
"edf_channels": h.channels,
"edf_error": None,
}
for row in rows:
row.update(found[row.get(node.column)])
return nodes.write(p, node.id, rows, EDF_COLUMNS)
def run_route(p: str, node: Route, others: list[Route] = ()):
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]]:
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):
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:
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 = node.text(row)
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"])]
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:
return "".join(ch for ch in identifier if ch.isalnum()).upper()
def _name(name: str) -> str:
plain = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()
return " ".join(plain.upper().split())
def _near(identifier: str) -> list[str]:
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]]:
skip, fixed = nodes.rejected("identity"), nodes.corrections()
records: dict[str, dict] = {}
sources: dict[str, str] = {}
written: 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], {})}
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:
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):
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()
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())
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()
undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set()
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()
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:
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"):
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)
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]):
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()
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, "edf": run_edf, "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+"])
log(f"silver and gold, from {', '.join(entities)}")