Run pipeline graphs: one ingest job, Source and Read nodes

This commit is contained in:
Roberto Treviño
2026-11-24 18:20:26 -06:00
parent 79a55a7a62
commit 8d874736db
4 changed files with 187 additions and 197 deletions
+11 -26
View File
@@ -1,45 +1,30 @@
"""Dagster code location: every heavy step of the platform is a job defined here.
Ingestion jobs take the pipeline to run (and optionally its config version) as run config.
"""
"""Dagster code location: every heavy step of the platform is a job defined here."""
import dagster as dg
from models import unpack
from persistance import collect, config_log
from models import graph
from persistance import config_log
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
class PipelineRun(dg.Config):
pipeline: str
version: int | None = None
version: int | None = None # default: the latest saved
@dg.op
def collect_sources(context: dg.OpExecutionContext, config: PipelineRun) -> int:
def run_pipeline(context: dg.OpExecutionContext, config: PipelineRun) -> int:
"""Every node of the pipeline graph, inputs first. Returns the config version run."""
version, pipeline = config_log.get(config.pipeline, config.version)
for source in pipeline.sources:
info = collect.run(source)
context.log.info(f"{source.name}: {info}")
return version
@dg.op
def unpack_items(context: dg.OpExecutionContext, config: PipelineRun) -> int:
version, pipeline = config_log.get(config.pipeline, config.version)
context.log.info(str(unpack.run(pipeline)))
context.log.info(f"{config.pipeline} v{version}: {len(pipeline.nodes)} nodes")
graph.run(config.pipeline, pipeline, log=context.log.info)
return version
@dg.job(tags=WRITES)
def collect_job():
collect_sources()
def ingest():
run_pipeline()
@dg.job(tags=WRITES)
def unpack_job():
unpack_items()
defs = dg.Definitions(jobs=[collect_job, unpack_job])
defs = dg.Definitions(jobs=[ingest])
+102
View File
@@ -0,0 +1,102 @@
"""Runs a pipeline graph: each node, after its inputs, writes its output table."""
import hashlib
import io
from collections.abc import Callable
from concurrent.futures import ProcessPoolExecutor
from functools import cache
import dlt
import ocrmypdf
from markitdown import MarkItDown
from sqlalchemy import inspect, text
from core.pipeline import Pipeline, Read
from persistance import nodes
from persistance.destination import engine, platform
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 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
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
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):
"""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))
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}
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,
)
)
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)
RUNNERS: dict[str, Callable] = {"source": nodes.run_source, "read": run_read}
def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print) -> None:
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)
log(f"{node.id} ({node.kind}) done")
-98
View File
@@ -1,98 +0,0 @@
"""Stage 2: read the columns the rules point the LLM at, into text.
MarkItDown reads every format it has a converter (or an installed plugin) for; a PDF with
no text layer is OCRed first with OCRmyPDF. Items are stored once per content hash, so the
same file in two places, or on a rerun, is read once.
"""
import hashlib
import io
import json
from concurrent.futures import ProcessPoolExecutor
from functools import cache
import dlt
import ocrmypdf
from markitdown import MarkItDown
from sqlalchemy import inspect, text
from core.pipeline import Pipeline
from persistance.destination import engine, platform
MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer
ITEM_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 read(content: bytes) -> dict:
"""Text of one file, and whether OCR was needed. Unreadable files keep their error."""
try:
found = _reader().convert_stream(io.BytesIO(content)).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,
) # fmt: skip
found = _reader().convert_stream(io.BytesIO(out.getvalue())).text_content
return {"text": found, "ocr": ocr, "error": None}
except Exception as e: # noqa: BLE001 - any unreadable file is recorded, not fatal
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
def _refs(pipeline: Pipeline):
"""(raw table, column, row reference, content) for every cell an llm rule reads."""
with engine().connect() as con:
for rule in pipeline.rules:
if not rule.llm:
continue
collected = dlt.attach(f"collect_{rule.source}")
naming = collected.default_schema.naming
table = f"raw__{rule.source}__{naming.normalize_table_identifier(rule.table)}"
columns = collected.default_schema.get_table(table)["columns"]
key = [c for c, v in columns.items() if v.get("primary_key")] or ["_dlt_id"]
for column in map(naming.normalize_identifier, rule.llm):
rows = con.execute(text(f"select {', '.join(key)}, {column} from bronze.{table}"))
for *row_key, content in rows:
if content is not None:
yield table, column, json.dumps(row_key, default=str), bytes(content)
def run(pipeline: Pipeline, workers: int | None = None) -> dict:
refs, contents = [], {}
for table, column, row_ref, content in _refs(pipeline):
sha = hashlib.sha256(content).hexdigest()
refs.append({"raw_table": table, "column": column, "row_ref": row_ref, "sha256": sha})
contents[sha] = content
with engine().connect() as con:
if inspect(con).has_table("items", schema="bronze"):
for (sha,) in con.execute(text("select sha256 from bronze.items")):
contents.pop(sha, None)
with ProcessPoolExecutor(workers) as pool:
read_items = [
{"sha256": sha, **found}
for sha, found in zip(contents, pool.map(read, contents.values()), strict=True)
]
out = dlt.pipeline("unpack", destination=platform(), dataset_name="bronze")
out.run(
[
dlt.resource(
read_items, name="items", primary_key="sha256", write_disposition="merge",
columns=ITEM_COLUMNS,
),
dlt.resource(
refs, name="item_refs", write_disposition="merge",
primary_key=["raw_table", "column", "row_ref"],
),
]
) # fmt: skip
return {"refs": len(refs), "read": len(read_items)}