Fix: convert crops PNG cannot store before handing them to tesseract

This commit is contained in:
stumpylog committed 2026-11-20 11:24:06 -08:00
1 parent ad5a7b365e
commit a2c18123fa
2 files changed
+51

No files matched your search

+48
View File
@@ -38,6 +38,7 @@ from documents.zone_ocr import _crop_zone
from documents.zone_ocr import _date_rules
from documents.zone_ocr import _extract_zone
from documents.zone_ocr import _number_locale
from documents.zone_ocr import _ocr_text
from documents.zone_ocr import _parse_date
from documents.zone_ocr import _parse_monetary
from documents.zone_ocr import _parse_number
@@ -315,6 +316,53 @@ class TestZoneExtraction:
assert mock_zone_ocr_run.call_args.args[0][-4:] == ["-l", "eng", "--psm", "6"]
assert mock_zone_ocr_run.call_args.kwargs["timeout"] == 30
@pytest.mark.parametrize(
("mode", "expected_mode"),
[
pytest.param("CMYK", "RGB", id="cmyk-is-converted"),
pytest.param("I;16", "I;16", id="16-bit-is-kept"),
],
)
def test_ocr_accepts_crops_png_cannot_store_directly(
self,
zone: OcrTemplateZone,
tmp_path: Path,
mock_zone_ocr_run: MagicMock,
mode: str,
expected_mode: str,
) -> None:
"""
GIVEN:
- A cropped zone image in a mode and a reader returning text
WHEN:
- The crop is OCRed
THEN:
- The reader's text is returned instead of an exception being raised
- The file handed to the reader is a readable PNG, converted to RGB only
when PNG cannot store the mode
"""
def read_crop(
args: list[str],
**kwargs: Any,
) -> subprocess.CompletedProcess[str]:
with Image.open(args[1]) as crop:
assert crop.format == "PNG"
assert crop.size == (40, 20)
assert crop.mode == expected_mode
crop.load()
return subprocess.CompletedProcess(
args=[],
returncode=0,
stdout="ACCOUNT 123\n",
stderr="",
)
mock_zone_ocr_run.side_effect = read_crop
with Image.new(mode, (40, 20)) as cropped:
assert _ocr_text(cropped, zone, tmp_path) == "ACCOUNT 123"
mock_zone_ocr_run.assert_called_once()
def test_no_text_returns_no_value(
self,
page: Path,
+3
View File
@@ -801,6 +801,9 @@ def _read_barcode(cropped: Image.Image, zone_name: str) -> str | None:
def _ocr_text(cropped: Image.Image, zone: OcrTemplateZone, tmp_dir: Path) -> str | None:
"""OCR a cropped image with Tesseract."""
crop_path = tmp_dir / f"zone_{zone.pk}.png"
# PNG cannot store every mode (e.g. CMYK from a CMYK JPEG or TIFF), so convert the others to RGB.
if cropped.mode not in ("1", "L", "LA", "P", "RGB", "RGBA", "I;16", "I;16B"):
cropped = cropped.convert("RGB")
cropped.save(crop_path)
try: