diff --git a/models/definitions.py b/models/definitions.py index 9a461df..aedd85e 100644 --- a/models/definitions.py +++ b/models/definitions.py @@ -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]) diff --git a/models/graph.py b/models/graph.py new file mode 100644 index 0000000..cfa420e --- /dev/null +++ b/models/graph.py @@ -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") diff --git a/models/unpack.py b/models/unpack.py deleted file mode 100644 index d4bfca2..0000000 --- a/models/unpack.py +++ /dev/null @@ -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)} diff --git a/tests/test_ingest.py b/tests/test_ingest.py index 1af7043..ad3dc01 100644 --- a/tests/test_ingest.py +++ b/tests/test_ingest.py @@ -15,36 +15,44 @@ from sqlalchemy import create_engine, make_url, text from synthetic.site import build FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "hospital" -SQL = "dlt.sources.sql_database:sql_database" -FILES = "dlt.sources.filesystem:filesystem" -def pipeline(tmp: Path) -> dict: - def sql(name, path): - return {"name": name, "source": SQL, "args": {"credentials": f"sqlite:///{path}"}} +def graph(tmp: Path, hospital_tables: dict[str, list[str]]) -> dict: + """What an operator would draw for this site: one Source per table or set of files, and + a Read on each column that holds documents.""" - def files(name, glob, **extra): + def table(node_id, db, name): + args = {"credentials": f"sqlite:///{db}", "table": name} + return {"id": node_id, "kind": "source", "source": SQL_TABLE, "args": args} + + def files(node_id, glob, **extra): args = {"bucket_url": str(tmp / "site" / "files"), "file_glob": glob} - return {"name": name, "source": FILES, "args": args, **extra} + return {"id": node_id, "kind": "source", "source": FILES, "args": args, **extra} + nodes = [ + table(f"{name}_{t}", tmp / f"hospital_{name}.db", t) + for name, tables in hospital_tables.items() + for t in tables + ] return { - "sources": [ - sql("cacu", tmp / "hospital_cacu.db"), - sql("cama", tmp / "hospital_cama.db"), - sql("site", tmp / "site" / "site.db"), - files( - "notes", "*.csv", source="dlt.sources.filesystem:readers", resources=["read_csv"] - ), + "nodes": nodes + + [ + table("his_patients", tmp / "site" / "site.db", "pacientes_his"), + table("archivos", tmp / "site" / "site.db", "ArchivosUni"), + files("notes", "*.csv", source=READERS, resource="read_csv"), files("altas", "*.xlsx", then="persistance.readers:read_excel"), files("pdfs", "*.pdf", then="persistance.readers:read_bytes"), - ], - "rules": [ - {"source": "site", "table": "ArchivosUni", "llm": ["Archivo"]}, - {"source": "pdfs", "table": "filesystem", "llm": ["content"]}, - ], + {"id": "archivos_text", "kind": "read", "inputs": ["archivos"], "column": "archivo"}, + {"id": "pdfs_text", "kind": "read", "inputs": ["pdfs"], "column": "content"}, + ] } +SQL_TABLE = "dlt.sources.sql_database:sql_table" +FILES = "dlt.sources.filesystem:filesystem" +READERS = "dlt.sources.filesystem:readers" + + @pytest.fixture(params=["sqlite", "postgres"]) def platform(request, tmp_path): """Env for a fresh platform on each backend, and a SQL connection to read it back.""" @@ -86,74 +94,67 @@ def run(env, *args): subprocess.run(args, env=env, check=True) -OPS = {"collect_job": "collect_sources", "unpack_job": "unpack_items"} +def ingest(env): + config = Path(env["ISSSTELEON_DATA"]) / "run.json" + config.write_text(json.dumps({"ops": {"run_pipeline": {"config": {"pipeline": "site"}}}})) + run(env, "dagster", "job", "execute", "-m", "models.definitions", "-j", "ingest", + "--config", str(config)) # fmt: skip -def job(env, name): - config = Path(env["ISSSTELEON_DATA"]) / f"{name}.json" - config.write_text(json.dumps({"ops": {OPS[name]: {"config": {"pipeline": "site"}}}})) - run( - env, - "dagster", - "job", - "execute", - "-m", - "models.definitions", - "-j", - name, - "--config", - str(config), - ) - - -def test_collect_and_unpack(platform, tmp_path): +def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_path): env, count, query = platform - for db in ("hospital_cacu.db", "hospital_cama.db"): - shutil.copy(FIXTURES / db, tmp_path / db) + tables = {} + for name in ("cacu", "cama"): + shutil.copy(FIXTURES / f"hospital_{name}.db", tmp_path / f"hospital_{name}.db") + with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con: + found = con.execute("select name from sqlite_master where type = 'table'") + tables[name] = [t for (t,) in found] truth = build(FIXTURES / "hospital_cacu.db", tmp_path / "site")["records"] - (tmp_path / "pipeline.json").write_text(json.dumps(pipeline(tmp_path))) + (tmp_path / "pipeline.json").write_text(json.dumps(graph(tmp_path, tables))) run(env, "python", "-m", "persistance.config_log", "site", str(tmp_path / "pipeline.json")) - expected = {"raw__site__archivos_uni": 53, "raw__pdfs__filesystem": 8} - for name in ("cacu", "cama"): - with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con: - tables = con.execute("select name from sqlite_master where type = 'table'") - for (table,) in tables.fetchall(): - rows = con.execute(f"select count(*) from {table}").fetchone()[0] - expected[f"raw__{name}__{table}"] = rows by_place = {} for r in truth: by_place.setdefault(r["where"].split(":")[0].split("/")[0], []).append(r) - expected |= { - "raw__site__pacientes_his": len(by_place["pacientes_his"]), - "raw__altas__filesystem": len(by_place["altas.xlsx"]), - "raw__notes__read_csv": len(by_place["consultas.csv"]), + expected = { + "his_patients": len(by_place["pacientes_his"]), + "altas": len(by_place["altas.xlsx"]), + "notes": len(by_place["consultas.csv"]), + "archivos": len(by_place["ArchivosUni"]), + "pdfs": len(by_place["files"]), + "archivos_text": len(by_place["ArchivosUni"]), + "pdfs_text": len(by_place["files"]), } + for name, names in tables.items(): + with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con: + for t in names: + expected[f"{name}_{t}"] = con.execute(f"select count(*) from {t}").fetchone()[0] - for _ in range(2): # a rerun changes nothing - job(env, "collect_job") - assert {t: count(t) for t in expected} == expected + def counts(): + return {node: count(f"n__site__{node}") for node in expected} - with sqlite3.connect(tmp_path / "hospital_cacu.db") as con: # a changed row updates + for _ in range(2): # loading the same site again changes nothing + ingest(env) + assert counts() == expected + read_once = query("select sha256, _dlt_load_id from bronze.read_cache order by sha256") + assert len(read_once) == expected["archivos"] + expected["pdfs"] # each file read once + + with sqlite3.connect(tmp_path / "hospital_cacu.db") as con: # a corrected record updates con.execute("update paciente set pac_codigo_postal = '64000' where pac_id = 1") - job(env, "collect_job") - assert count("raw__cacu__paciente") == expected["raw__cacu__paciente"] - changed = query("select pac_codigo_postal from bronze.raw__cacu__paciente where pac_id = 1") - assert changed == [("64000",)] + ingest(env) + assert counts() == expected + corrected = "select pac_codigo_postal from bronze.n__site__cacu_paciente where pac_id = 1" + assert query(corrected) == [("64000",)] - job(env, "unpack_job") - items = query( - "select i.text, i.ocr, i.error, r.raw_table, r.row_ref from bronze.items i " - "join bronze.item_refs r on r.sha256 = i.sha256" - ) - assert len(items) == 53 + 8 and all(error is None for _, _, error, _, _ in items) + read = query("select id, text, ocr, error from bronze.n__site__archivos_text") + assert all(error is None for *_, error in read) space = re.compile(r"\s+") - found = {(t, json.loads(ref)[0]): (space.sub(" ", txt), ocr) for txt, ocr, _, t, ref in items} + by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read} for r in by_place["ArchivosUni"]: - txt, ocr = found[("raw__site__archivos_uni", int(r["where"].split(":")[1]))] - assert bool(ocr) == r["scanned"] - if "record_number" in r["identity"]: # OCR included: the identifier reads back exactly + txt, ocr = by_id[int(r["where"].split(":")[1])] + assert bool(ocr) == r["scanned"] # OCR runs on scans, and only on scans + if "record_number" in r["identity"]: # even scanned, the identifier reads back exactly assert r["identity"]["record_number"] in txt, (r["where"], txt) - before = query("select sha256, _dlt_load_id from bronze.items order by sha256") - job(env, "unpack_job") # nothing new to read: no item is read or written again - assert query("select sha256, _dlt_load_id from bronze.items order by sha256") == before + assert query("select sha256, _dlt_load_id from bronze.read_cache order by sha256") == ( + read_once + ) # reruns never read a file again