OCR only on the pages without text; otherwise routes; batches on Dask through its own API
This commit is contained in:
+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")
|
||||
|
||||
Reference in New Issue
Block a user