From fbf06741896fac650f936738162f9554b82fc594 Mon Sep 17 00:00:00 2001 From: "James R. Barlow" Date: Sun, 15 Oct 2023 00:49:58 -0700 Subject: [PATCH] hocr_to_ocr_pdf: handle missing hocr json file --- src/ocrmypdf/_pipelines/hocr_to_ocr_pdf.py | 6 +++++- tests/test_api.py | 12 +++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/ocrmypdf/_pipelines/hocr_to_ocr_pdf.py b/src/ocrmypdf/_pipelines/hocr_to_ocr_pdf.py index f3b5d47a..c13097dc 100644 --- a/src/ocrmypdf/_pipelines/hocr_to_ocr_pdf.py +++ b/src/ocrmypdf/_pipelines/hocr_to_ocr_pdf.py @@ -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 ) diff --git a/tests/test_api.py b/tests/test_api.py index d7a0a200..4e92c719 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -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