Run every node kind: route, map, join, extract (LLM or patterns), link (Splink), target

This commit is contained in:
Roberto Treviño
2026-11-24 20:05:29 -06:00
parent 8d874736db
commit 61721a8005
6 changed files with 404 additions and 121 deletions
-8
View File
@@ -1,8 +0,0 @@
"""The dbt project, alone so `dagster-dbt project prepare-and-package` can build its manifest."""
from dagster_dbt import DbtProject
from persistance.config import DBT_DIR
dbt_project = DbtProject(project_dir=DBT_DIR, profiles_dir=DBT_DIR)
dbt_project.prepare_if_dev()
+222 -52
View File
@@ -1,19 +1,45 @@
"""Runs a pipeline graph: each node, after its inputs, writes its output table."""
"""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
from collections.abc import Callable
from concurrent.futures import ProcessPoolExecutor
from functools import cache
import dlt
import ocrmypdf
import pandas as pd
import pdfplumber
import splink.comparison_library as cl
from markitdown import MarkItDown
from sqlalchemy import inspect, text
from openai import OpenAI, OpenAIError
from splink import Linker, SettingsCreator
from splink.backends.duckdb import DuckDBAPI
from core.pipeline import Pipeline, Read
from persistance import nodes
from persistance.destination import engine, platform
from core.pipeline import (
HELD,
QUOTES,
RECORD,
Extract,
Join,
Link,
Map,
Pipeline,
Read,
Route,
Target,
answer_schema,
apply_patterns,
ground,
join,
map_row,
matches,
validate,
)
from core.schema import ENTITIES
from persistance import 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`
@@ -28,75 +54,219 @@ def _reader() -> MarkItDown:
return MarkItDown()
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 _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 = _reader().convert_stream(io.BytesIO(content)).text_content
found = _text(content)
ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS
if ocr:
out = io.BytesIO()
ocrmypdf.ocr(
io.BytesIO(content),
out,
language="spa",
skip_text=True,
output_type="pdf",
optimize=0,
progress_bar=False,
jobs=1,
)
found = _reader().convert_stream(io.BytesIO(out.getvalue())).text_content
io.BytesIO(content), out, language="spa", skip_text=True,
output_type="pdf", optimize=0, progress_bar=False, jobs=1, deskew=True,
) # fmt: skip
found = _text(out.getvalue())
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 _cached(shas: set[str]) -> dict[str, dict]:
"""Files already read, by content hash, in any node of any pipeline."""
with engine().connect() as con:
if not inspect(con).has_table("read_cache", schema="bronze"):
return {}
rows = con.execute(text("select sha256, text, ocr, error from bronze.read_cache"))
return {r.sha256: dict(r._mapping) for r in rows if r.sha256 in shas}
def run_read(pipeline_id: str, node: Read):
def run_read(p: str, node: Read):
"""The input's rows with the file column replaced by its text; each file read once."""
source = node.inputs[0]
rows = list(nodes.rows(pipeline_id, source))
rows = list(nodes.rows(p, node.inputs[0]))
keys = {}
for row in rows:
content = row.pop(node.column)
row["sha256"] = hashlib.sha256(content).hexdigest() if content else None
row["_content"] = content
found = _cached({r["sha256"] for r in rows if r["sha256"]})
new = {r["sha256"]: r["_content"] for r in rows if r["sha256"] and r["sha256"] not in found}
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))
if read:
cache_rows = [{"sha256": sha, **result} for sha, result in read.items()]
dlt.pipeline("read_cache", destination=platform(), dataset_name="bronze").run(
dlt.resource(
cache_rows,
name="read_cache",
primary_key="sha256",
write_disposition="merge",
columns=READ_COLUMNS,
)
)
nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()], READ_COLUMNS)
found |= read
for row in rows:
row.pop("_content")
result = found.get(row["sha256"], {"text": None, "ocr": False, "error": "empty"})
row.update({k: result[k] for k in READ_COLUMNS})
return nodes.write(pipeline_id, node.id, rows, nodes.key(pipeline_id, source), READ_COLUMNS)
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)
RUNNERS: dict[str, Callable] = {"source": nodes.run_source, "read": run_read}
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 run_map(p: str, node: Map):
return nodes.write(p, node.id, [map_row(node, r) for r in nodes.rows(p, node.inputs[0])])
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)
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)
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 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."""
records: dict[str, dict] = {}
for i in node.inputs:
for row in nodes.rows(p, i):
if row.get(HELD):
continue
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])
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,
)
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)
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)
held = json.dumps(["records of this person disagree on birth date or sex"])
nodes.write(p, node.id, [
{RECORD: r.unique_id, "person_id": r.cluster_id,
HELD: held if r.cluster_id in torn else None}
for r in persons.itertuples()
], {HELD: {"data_type": "text", "nullable": True}}) # 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
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 = ENTITIES[node.entity]
out = []
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 "[]")
staged = {
"person_id": person.get(row[RECORD]), RECORD: row[RECORD],
"_index": row.get("_index", 0), QUOTES: row.get(QUOTES),
HELD: json.dumps(held) if held else None,
"_raw": json.dumps(values, default=str, ensure_ascii=False) if held else None,
} # fmt: skip
if not held:
staged |= model.model_validate(values).model_dump()
out.append(staged)
return nodes.stage(node.entity, p, node.id, out, silver.columns(node.entity))
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,
} # 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 not in RUNNERS:
raise NotImplementedError(f"{node.id}: {node.kind} nodes run from step 4")
RUNNERS[node.kind](pipeline_id, node)
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(entities)
log(f"silver: {', '.join(entities)}")