Run pipeline graphs: one ingest job, Source and Read nodes
This commit is contained in:
+102
@@ -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")
|
||||
Reference in New Issue
Block a user