Extract reads several columns as one document; reviewers' corrections of study fields applied at the target; the site gates on ISSSTELEON's test source

This commit is contained in:
Roberto Treviño
2026-11-27 01:45:16 -06:00
parent 44cb0dc894
commit 02aab07a67
3 changed files with 138 additions and 127 deletions
+33 -39
View File
@@ -1,5 +1,6 @@
"""Phase 1 gate, stages 1-2: everything a site has reaches bronze, once, and every document
the rules point at is read into text (scanned ones through OCR)."""
the rules point at is read into text (scanned ones through OCR). The site: the synthetic
hospitals' tables (SQLite) and ISSSTELEON's test source (SQL Server tables of PDFs)."""
import json
import re
@@ -7,48 +8,42 @@ import shutil
import sqlite3
from pathlib import Path
from synthetic.site import build
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "hospital"
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 graph(tmp: Path, hospital_tables: dict[str, list[str]], site_url: str) -> dict:
"""What an operator would draw for this site: one Source per table, and a Read on each
column that holds documents."""
def table(node_id, db, name):
args = {"credentials": f"sqlite:///{db}", "table": name}
def table(node_id, credentials, name, **args):
args = {"credentials": credentials, "table": name, **args}
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 {"id": node_id, "kind": "source", "source": FILES, "args": args, **extra}
nodes = [
table(f"{name}_{t}", tmp / f"hospital_{name}.db", t)
table(f"{name}_{t}", f"sqlite:///{tmp / f'hospital_{name}.db'}", t)
for name, tables in hospital_tables.items()
for t in tables
]
return {
"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"),
table("archivos", site_url, "ArchivosUni", schema="dbo"),
table("subrogados", site_url, "ResultadosSubrogados", schema="dbo"),
{"id": "archivos_text", "kind": "read", "inputs": ["archivos"], "column": "archivo"},
{"id": "pdfs_text", "kind": "read", "inputs": ["pdfs"], "column": "content"},
{
"id": "subrogados_text",
"kind": "read",
"inputs": ["subrogados"],
"column": "archivo",
},
]
}
SQL_TABLE = "dlt.sources.sql_database:sql_table"
FILES = "dlt.sources.filesystem:filesystem"
READERS = "dlt.sources.filesystem:readers"
def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_path):
def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, site, tmp_path):
count, query = platform.count, platform.query
tables = {}
for name in ("cacu", "cama"):
@@ -56,21 +51,19 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat
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(graph(tmp_path, tables)))
truth = site.truth
(tmp_path / "pipeline.json").write_text(json.dumps(graph(tmp_path, tables, site.url)))
platform.save("pipelines", "site", tmp_path / "pipeline.json")
by_place = {}
for r in truth:
by_place.setdefault(r["where"].split(":")[0].split("/")[0], []).append(r)
by_place.setdefault(r["where"].split(":")[0], []).append(r)
documents = len(by_place["ArchivosUni"]) + len(by_place["ResultadosSubrogados"])
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"]),
"subrogados": len(by_place["ResultadosSubrogados"]),
"archivos_text": len(by_place["ArchivosUni"]),
"pdfs_text": len(by_place["files"]),
"subrogados_text": len(by_place["ResultadosSubrogados"]),
}
for name, names in tables.items():
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
@@ -84,7 +77,7 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat
platform.ingest()
assert counts() == expected
read_once = query("select key, _dlt_load_id from bronze.read_cache order by key")
assert len(read_once) == expected["archivos"] + expected["pdfs"] # each file read once
assert len(read_once) == documents # 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")
@@ -93,15 +86,16 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat
corrected = "select pac_codigo_postal from bronze.n__site__cacu_paciente where pac_id = 1"
assert query(corrected) == [("64000",)]
read = query("select id, text, ocr, error from bronze.n__site__archivos_text")
assert [error for *_, error in read if error is not None] == []
space = re.compile(r"\s+")
by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read}
for r in by_place["ArchivosUni"]:
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)
for table, node in (("ArchivosUni", "archivos"), ("ResultadosSubrogados", "subrogados")):
read = query(f"select id, text, ocr, error from bronze.n__site__{node}_text")
assert [error for *_, error in read if error is not None] == []
by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read}
for r in by_place[table]:
txt, ocr = by_id[int(r["where"].split(":")[1])]
assert bool(ocr) == r.get("scanned", False) # OCR runs on scans, and only on scans
if "record_number" in r["identity"]: # even scanned, the number reads back exactly
assert r["identity"]["record_number"] in txt, (r["where"], txt)
assert query("select key, _dlt_load_id from bronze.read_cache order by key") == (
read_once
) # reruns never read a file again