OCR only on the pages without text; otherwise routes; batches on Dask through its own API
This commit is contained in:
+30
-17
@@ -1,16 +1,15 @@
|
||||
"""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
|
||||
DASK_SCHEDULER_ADDRESS, or on a Dask cluster of this machine's cores, through joblib's own
|
||||
Dask backend. Without it (the product) joblib runs them on local processes. BATCH_JOBS caps
|
||||
how many run at once (each task carries its recording: a cap paces a slow link)."""
|
||||
DASK_SCHEDULER_ADDRESS, or on a Dask cluster of this machine's cores. Without it (the
|
||||
product) joblib runs them on local processes. BATCH_JOBS caps how many run at once: each
|
||||
task carries its data (a recording), so a cap paces a slow link."""
|
||||
|
||||
import os
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from collections.abc import Callable, Iterable
|
||||
from importlib.util import find_spec
|
||||
from typing import Any
|
||||
|
||||
from joblib import parallel_config
|
||||
from joblib.externals.loky import get_reusable_executor
|
||||
from joblib import Parallel, delayed
|
||||
|
||||
|
||||
def jobs() -> int:
|
||||
@@ -18,22 +17,36 @@ def jobs() -> int:
|
||||
return int(os.environ.get("BATCH_JOBS", "-1"))
|
||||
|
||||
|
||||
@contextmanager
|
||||
def batch() -> Iterator[None]:
|
||||
def run(task: Callable, arguments: Iterable[tuple]) -> list[Any]:
|
||||
"""`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:
|
||||
try:
|
||||
yield
|
||||
finally: # the local workers go when the batch is done
|
||||
get_reusable_executor().shutdown(wait=True)
|
||||
return
|
||||
from distributed import Client, LocalCluster
|
||||
return Parallel(n_jobs=jobs())(delayed(task)(*a) for a in arguments)
|
||||
from distributed import Client, LocalCluster, as_completed
|
||||
|
||||
address = os.environ.get("DASK_SCHEDULER_ADDRESS")
|
||||
# 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)
|
||||
try:
|
||||
with Client(where), parallel_config(backend="dask"):
|
||||
yield
|
||||
with Client(where) as client:
|
||||
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:
|
||||
if not address:
|
||||
where.close()
|
||||
|
||||
+46
-19
@@ -13,6 +13,7 @@ from functools import cache
|
||||
import ocrmypdf
|
||||
import pandas as pd
|
||||
import pdfplumber
|
||||
import pikepdf
|
||||
import splink.comparison_library as cl
|
||||
from markitdown import MarkItDown
|
||||
from openai import OpenAI, OpenAIError
|
||||
@@ -45,7 +46,7 @@ from core.pipeline import (
|
||||
)
|
||||
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`
|
||||
"text": {"data_type": "text", "nullable": True},
|
||||
"ocr": {"data_type": "bool"},
|
||||
@@ -77,14 +78,34 @@ def _lines(text: str) -> str:
|
||||
|
||||
|
||||
def _text(content: bytes) -> str:
|
||||
"""PDFs through pdfplumber's layout mode, which keeps a table's rows on one line each
|
||||
(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))
|
||||
"""Files other than PDFs, through MarkItDown."""
|
||||
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:
|
||||
"""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."""
|
||||
@@ -95,18 +116,17 @@ def read_file(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:
|
||||
found = _text(content)
|
||||
ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS
|
||||
if ocr: # Tesseract's own text (OCRmyPDF's sidecar), from the deskewed page
|
||||
text = io.BytesIO()
|
||||
ocrmypdf.ocr(
|
||||
io.BytesIO(content), io.BytesIO(), language="spa", skip_text=True,
|
||||
output_type="pdf", optimize=0, progress_bar=False, jobs=1, deskew=True,
|
||||
sidecar=text,
|
||||
) # fmt: skip
|
||||
found = _lines(text.getvalue().decode())
|
||||
return {"text": found, "ocr": ocr, "error": None}
|
||||
if not content.startswith(b"%PDF"):
|
||||
return {"text": _text(content), "ocr": False, "error": None}
|
||||
pages = _pdf_pages(content)
|
||||
scanned = [i for i, page in enumerate(pages) if len(page.split()) < MIN_WORDS]
|
||||
if scanned:
|
||||
for i, page in zip(scanned, _ocr_pages(content, scanned), strict=True):
|
||||
pages[i] = page
|
||||
return {"text": "\n".join(p for p in pages if p), "ocr": bool(scanned), "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}"}
|
||||
|
||||
@@ -136,8 +156,11 @@ def run_read(p: str, node: Read):
|
||||
return nodes.write(p, node.id, rows, READ_COLUMNS)
|
||||
|
||||
|
||||
def run_route(p: str, node: Route):
|
||||
return nodes.write(p, node.id, [r for r in nodes.rows(p, node.inputs[0]) if matches(node, r)])
|
||||
def run_route(p: str, node: Route, others: list[Route] = ()):
|
||||
"""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]]:
|
||||
@@ -468,6 +491,10 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
|
||||
for node in pipeline.order():
|
||||
if node.kind == "target":
|
||||
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:
|
||||
RUNNERS[node.kind](pipeline_id, node)
|
||||
log(f"{node.id} ({node.kind}) done")
|
||||
|
||||
@@ -11,7 +11,6 @@ from the valid studies.
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
from joblib import Parallel, delayed
|
||||
|
||||
from models import cluster
|
||||
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]:
|
||||
"""Each study's verdict and features, in listing order, each a task on the cluster
|
||||
(models.cluster)."""
|
||||
with cluster.batch(): # each task carries its recording: workers see no local folder
|
||||
return Parallel(n_jobs=cluster.jobs())(delayed(_one)(key, Path(path).read_bytes(), age)
|
||||
for key, path, age in studies) # fmt: skip
|
||||
# each task carries its recording: workers see no local folder
|
||||
return cluster.run(_one, ((key, Path(path).read_bytes(), age) for key, path, age in studies))
|
||||
|
||||
|
||||
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
|
||||
|
||||
+3
-5
@@ -15,7 +15,6 @@ from pathlib import Path
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pandas as pd
|
||||
from joblib import Parallel, delayed
|
||||
|
||||
from models import cluster
|
||||
from models.tea.eeg import analysis, curves, reference
|
||||
@@ -43,10 +42,9 @@ class Baseline(mlflow.pyfunc.PythonModel):
|
||||
def analyze() -> int:
|
||||
"""Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt."""
|
||||
pending = eeg.pending()
|
||||
with cluster.batch(): # one task per EEG, carrying its recording (models.cluster)
|
||||
tasks = (delayed(analysis.analyze)(eeg.signal(r["edf"]), r["birth_date"])
|
||||
for r in pending) # fmt: skip
|
||||
done = Parallel(n_jobs=cluster.jobs())(tasks)
|
||||
done = cluster.run(
|
||||
analysis.analyze, ((eeg.signal(r["edf"]), r["birth_date"]) for r in pending)
|
||||
) # one task per EEG
|
||||
found = dict(zip((r["edf"] for r in pending), done, strict=True))
|
||||
eeg.save_analyses(found)
|
||||
silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"])
|
||||
|
||||
@@ -13,6 +13,7 @@ dependencies = [
|
||||
"splink>=5.0.0",
|
||||
"markitdown[docx,xlsx]>=0.1.9",
|
||||
"ocrmypdf>=17.14.2",
|
||||
"pikepdf>=10.0",
|
||||
"pdfplumber>=0.11.11",
|
||||
"scikit-learn>=1.9.1",
|
||||
"scipy>=1.18.1",
|
||||
|
||||
Reference in New Issue
Block a user