OCR only on the pages without text; otherwise routes; batches on Dask through its own API

This commit is contained in:
Roberto Treviño
2026-11-27 19:17:49 -06:00
parent 385cc5b80b
commit 0c78f8cf7d
5 changed files with 82 additions and 45 deletions
+30 -17
View File
@@ -1,16 +1,15 @@
"""Where long batches run (the EEG analysis, measuring a reference cohort). Where Dask is """Where long batches run (the EEG analysis, measuring a reference cohort). Where Dask is
installed (the `dask` extra, for testing on a cluster) they run on the scheduler at installed (the `dask` extra, for testing on a cluster) they run on the scheduler at
DASK_SCHEDULER_ADDRESS, or on a Dask cluster of this machine's cores, through joblib's own DASK_SCHEDULER_ADDRESS, or on a Dask cluster of this machine's cores. Without it (the
Dask backend. Without it (the product) joblib runs them on local processes. BATCH_JOBS caps product) joblib runs them on local processes. BATCH_JOBS caps how many run at once: each
how many run at once (each task carries its recording: a cap paces a slow link).""" task carries its data (a recording), so a cap paces a slow link."""
import os import os
from collections.abc import Iterator from collections.abc import Callable, Iterable
from contextlib import contextmanager
from importlib.util import find_spec from importlib.util import find_spec
from typing import Any
from joblib import parallel_config from joblib import Parallel, delayed
from joblib.externals.loky import get_reusable_executor
def jobs() -> int: def jobs() -> int:
@@ -18,22 +17,36 @@ def jobs() -> int:
return int(os.environ.get("BATCH_JOBS", "-1")) return int(os.environ.get("BATCH_JOBS", "-1"))
@contextmanager def run(task: Callable, arguments: Iterable[tuple]) -> list[Any]:
def batch() -> Iterator[None]: """`task(*a)` for each tuple of `arguments`, results in their order. The arguments are
drawn as tasks start, so at most `jobs()` of them are held at once."""
if find_spec("distributed") is None: if find_spec("distributed") is None:
try: return Parallel(n_jobs=jobs())(delayed(task)(*a) for a in arguments)
yield from distributed import Client, LocalCluster, as_completed
finally: # the local workers go when the batch is done
get_reusable_executor().shutdown(wait=True)
return
from distributed import Client, LocalCluster
address = os.environ.get("DASK_SCHEDULER_ADDRESS") address = os.environ.get("DASK_SCHEDULER_ADDRESS")
# one process per core, no dashboard port to collide with (8787 is often taken) # one process per core, no dashboard port to collide with (8787 is often taken)
where = address or LocalCluster(threads_per_worker=1, dashboard_address=None) where = address or LocalCluster(threads_per_worker=1, dashboard_address=None)
try: try:
with Client(where), parallel_config(backend="dask"): with Client(where) as client:
yield limit = jobs() if jobs() > 0 else sum(client.nthreads().values())
pending = iter(enumerate(arguments))
results: dict[int, Any] = {}
order: dict[Any, int] = {}
def submit() -> Any | None:
if (item := next(pending, None)) is None:
return None
future = client.submit(task, *item[1], pure=False)
order[future] = item[0]
return future
running = as_completed([f for f in (submit() for _ in range(limit)) if f])
for done in running:
results[order.pop(done)] = done.result()
if (future := submit()) is not None:
running.add(future)
return [results[i] for i in range(len(results))]
finally: finally:
if not address: if not address:
where.close() where.close()
+46 -19
View File
@@ -13,6 +13,7 @@ from functools import cache
import ocrmypdf import ocrmypdf
import pandas as pd import pandas as pd
import pdfplumber import pdfplumber
import pikepdf
import splink.comparison_library as cl import splink.comparison_library as cl
from markitdown import MarkItDown from markitdown import MarkItDown
from openai import OpenAI, OpenAIError from openai import OpenAI, OpenAIError
@@ -45,7 +46,7 @@ from core.pipeline import (
) )
from persistance import config_log, files, nodes, silver from persistance import config_log, files, nodes, silver
MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer MIN_WORDS = 5 # fewer than this from a PDF page means it has no text layer
READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error` READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error`
"text": {"data_type": "text", "nullable": True}, "text": {"data_type": "text", "nullable": True},
"ocr": {"data_type": "bool"}, "ocr": {"data_type": "bool"},
@@ -77,14 +78,34 @@ def _lines(text: str) -> str:
def _text(content: bytes) -> str: def _text(content: bytes) -> str:
"""PDFs through pdfplumber's layout mode, which keeps a table's rows on one line each """Files other than PDFs, through MarkItDown."""
(spacing within a line collapsed); every other format through MarkItDown."""
if content.startswith(b"%PDF"):
with pdfplumber.open(io.BytesIO(content)) as pdf:
return _lines("\n".join(page.extract_text(layout=True) or "" for page in pdf.pages))
return _reader().convert_stream(io.BytesIO(content)).text_content return _reader().convert_stream(io.BytesIO(content)).text_content
def _pdf_pages(content: bytes) -> list[str]:
"""Each page's text layer, through pdfplumber's layout mode, which keeps a table's rows
on one line each (spacing within a line collapsed)."""
with pdfplumber.open(io.BytesIO(content)) as pdf:
return [_lines(page.extract_text(layout=True) or "") for page in pdf.pages]
def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]:
"""Tesseract's text (OCRmyPDF's sidecar, from the deskewed page) of these pages only,
copied into a PDF of their own: a typed page keeps its own text layer."""
source, scans = pikepdf.open(io.BytesIO(content)), pikepdf.new()
for n in numbers:
scans.pages.append(source.pages[n])
pages, sidecar = io.BytesIO(), io.BytesIO()
scans.save(pages)
pages.seek(0)
ocrmypdf.ocr(
pages, io.BytesIO(), language="spa", force_ocr=True, output_type="pdf", optimize=0,
progress_bar=False, jobs=1, deskew=True, sidecar=sidecar,
) # fmt: skip
found = sidecar.getvalue().decode().split("\f")
return [_lines(found[i]) if i < len(found) else "" for i in range(len(numbers))]
def read_file(content: bytes) -> dict: def read_file(content: bytes) -> dict:
"""Text of one file, its format, and whether OCR was needed. An unreadable file keeps """Text of one file, its format, and whether OCR was needed. An unreadable file keeps
its error; a signal recording (EDF) has no text to read.""" its error; a signal recording (EDF) has no text to read."""
@@ -95,18 +116,17 @@ def read_file(content: bytes) -> dict:
def _read_text(content: bytes) -> dict: def _read_text(content: bytes) -> dict:
"""The file's text; a PDF page by page, OCR only on the pages without a text layer (a
typed form whose second page is a scan, say)."""
try: try:
found = _text(content) if not content.startswith(b"%PDF"):
ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS return {"text": _text(content), "ocr": False, "error": None}
if ocr: # Tesseract's own text (OCRmyPDF's sidecar), from the deskewed page pages = _pdf_pages(content)
text = io.BytesIO() scanned = [i for i, page in enumerate(pages) if len(page.split()) < MIN_WORDS]
ocrmypdf.ocr( if scanned:
io.BytesIO(content), io.BytesIO(), language="spa", skip_text=True, for i, page in zip(scanned, _ocr_pages(content, scanned), strict=True):
output_type="pdf", optimize=0, progress_bar=False, jobs=1, deskew=True, pages[i] = page
sidecar=text, return {"text": "\n".join(p for p in pages if p), "ocr": bool(scanned), "error": None}
) # fmt: skip
found = _lines(text.getvalue().decode())
return {"text": found, "ocr": ocr, "error": None}
except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"} return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
@@ -136,8 +156,11 @@ def run_read(p: str, node: Read):
return nodes.write(p, node.id, rows, READ_COLUMNS) return nodes.write(p, node.id, rows, READ_COLUMNS)
def run_route(p: str, node: Route): def run_route(p: str, node: Route, others: list[Route] = ()):
return nodes.write(p, node.id, [r for r in nodes.rows(p, node.inputs[0]) if matches(node, r)]) """The input's rows the route takes; an `otherwise` route, those `others` don't."""
rows = nodes.rows(p, node.inputs[0])
taken = [r for r in rows if matches(node, r) and not any(matches(o, r) for o in others)]
return nodes.write(p, node.id, taken)
def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]: def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]:
@@ -468,6 +491,10 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
for node in pipeline.order(): for node in pipeline.order():
if node.kind == "target": if node.kind == "target":
run_target(pipeline_id, node, kinds) run_target(pipeline_id, node, kinds)
elif node.kind == "route" and node.otherwise:
others = [n for n in pipeline.nodes if n.kind == "route" and n.id != node.id
and n.inputs == node.inputs and not n.otherwise] # fmt: skip
run_route(pipeline_id, node, others)
else: else:
RUNNERS[node.kind](pipeline_id, node) RUNNERS[node.kind](pipeline_id, node)
log(f"{node.id} ({node.kind}) done") log(f"{node.id} ({node.kind}) done")
+2 -4
View File
@@ -11,7 +11,6 @@ from the valid studies.
from pathlib import Path from pathlib import Path
import pandas as pd import pandas as pd
from joblib import Parallel, delayed
from models import cluster from models import cluster
from models.tea.eeg.analysis import analyze from models.tea.eeg.analysis import analyze
@@ -48,9 +47,8 @@ def _one(key: str, edf: bytes, age: float) -> dict:
def measure(studies) -> list[dict]: def measure(studies) -> list[dict]:
"""Each study's verdict and features, in listing order, each a task on the cluster """Each study's verdict and features, in listing order, each a task on the cluster
(models.cluster).""" (models.cluster)."""
with cluster.batch(): # each task carries its recording: workers see no local folder # each task carries its recording: workers see no local folder
return Parallel(n_jobs=cluster.jobs())(delayed(_one)(key, Path(path).read_bytes(), age) return cluster.run(_one, ((key, Path(path).read_bytes(), age) for key, path, age in studies))
for key, path, age in studies) # fmt: skip
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]: def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
+3 -5
View File
@@ -15,7 +15,6 @@ from pathlib import Path
import mlflow.pyfunc import mlflow.pyfunc
import pandas as pd import pandas as pd
from joblib import Parallel, delayed
from models import cluster from models import cluster
from models.tea.eeg import analysis, curves, reference from models.tea.eeg import analysis, curves, reference
@@ -43,10 +42,9 @@ class Baseline(mlflow.pyfunc.PythonModel):
def analyze() -> int: def analyze() -> int:
"""Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt.""" """Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt."""
pending = eeg.pending() pending = eeg.pending()
with cluster.batch(): # one task per EEG, carrying its recording (models.cluster) done = cluster.run(
tasks = (delayed(analysis.analyze)(eeg.signal(r["edf"]), r["birth_date"]) analysis.analyze, ((eeg.signal(r["edf"]), r["birth_date"]) for r in pending)
for r in pending) # fmt: skip ) # one task per EEG
done = Parallel(n_jobs=cluster.jobs())(tasks)
found = dict(zip((r["edf"] for r in pending), done, strict=True)) found = dict(zip((r["edf"] for r in pending), done, strict=True))
eeg.save_analyses(found) eeg.save_analyses(found)
silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"]) silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"])
+1
View File
@@ -13,6 +13,7 @@ dependencies = [
"splink>=5.0.0", "splink>=5.0.0",
"markitdown[docx,xlsx]>=0.1.9", "markitdown[docx,xlsx]>=0.1.9",
"ocrmypdf>=17.14.2", "ocrmypdf>=17.14.2",
"pikepdf>=10.0",
"pdfplumber>=0.11.11", "pdfplumber>=0.11.11",
"scikit-learn>=1.9.1", "scikit-learn>=1.9.1",
"scipy>=1.18.1", "scipy>=1.18.1",