hocr_to_ocr_pdf: handle missing hocr json file

This commit is contained in:
James R. Barlow
2023-10-24 00:54:31 -07:00
parent 62c4f65fc3
commit fbf0674189
2 changed files with 14 additions and 4 deletions
+5 -1
View File
@@ -39,7 +39,11 @@ log = logging.getLogger(__name__)
def exec_hocrtransform_sync(page_context: PageContext) -> HOCRResult:
hocr_result = HOCRResult.from_json(page_context.get_path('hocr.json').read_text())
hocr_json = page_context.get_path('hocr.json')
if not hocr_json.exists():
# No hOCR file, so no OCR was performed on this page.
return HOCRResult(pageno=page_context.pageno)
hocr_result = HOCRResult.from_json(hocr_json.read_text())
hocr_result.textpdf = render_hocr_page(
page_context.get_path('ocr_hocr.hocr'), page_context
)
+9 -3
View File
@@ -7,6 +7,7 @@ from io import BytesIO
from pathlib import Path
import pytest
from pdfminer.high_level import extract_text
import ocrmypdf
@@ -27,7 +28,7 @@ def test_stream_api(resources: Path):
assert b'%PDF' in out.read(1024)
def test_hocr_api(resources: Path, outdir: Path):
def test_hocr_api_multipage(resources: Path, outdir: Path, outpdf: Path):
ocrmypdf.pdf_to_hocr(
resources / 'multipage.pdf',
outdir,
@@ -37,9 +38,11 @@ def test_hocr_api(resources: Path, outdir: Path):
)
assert (outdir / '000001_ocr_hocr.hocr').exists()
assert (outdir / '000006_ocr_hocr.hocr').exists()
assert not (outdir / '000004_ocr_hocr.hocr').exists()
ocrmypdf.hocr_to_ocr_pdf(outdir, outpdf)
assert outpdf.exists()
def test_hocr_to_pdf_api(resources: Path, outdir: Path, outpdf: Path):
ocrmypdf.pdf_to_hocr(
@@ -54,4 +57,7 @@ def test_hocr_to_pdf_api(resources: Path, outdir: Path, outpdf: Path):
mangled = hocr.replace('the', 'hocr')
(outdir / '000001_ocr_hocr.hocr').write_text(mangled, encoding='utf-8')
ocrmypdf.hocr_to_ocr_pdf(outdir, outpdf)
ocrmypdf.hocr_to_ocr_pdf(outdir, outpdf, optimize=0)
text = extract_text(outpdf)
assert 'hocr' in text and 'the' not in text