sumoOCR-tiny / tests /test_sumoocr.py
bikramdocsumo
Initial release: SumoOCR tiny v0.1.0
10469c8
Raw History Blame Contribute Delete
2.03 kB
import os
from collections import Counter
import cv2
import numpy as np
import pytest
from sumoocr import Line, SumoOCR
from sumoocr.cli import main
HERE = os.path.dirname(os.path.abspath(__file__))
PAGE = os.path.join(HERE, "..", "examples", "invoice.png")
@pytest.fixture(scope="module")
def ocr():
return SumoOCR(threads=1)
def test_page(ocr):
lines = ocr(PAGE)
assert lines and all(isinstance(ln, Line) for ln in lines)
text = "\n".join(ln.text for ln in lines)
for s in ("Brightwater Analytics LLP", "INVOICE", "GB179116235", "15/05/2026"):
assert s in text
ln = lines[0]
assert 0.85 <= ln.conf <= 1.0 and len(ln.box) == 4
def test_inputs_agree(ocr):
bgr = cv2.imread(PAGE)
a = [ln.text for ln in ocr(PAGE)]
assert [ln.text for ln in ocr(bgr)] == a
assert [ln.text for ln in ocr(cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY))] # grayscale works
@pytest.mark.parametrize("turn", [cv2.ROTATE_90_CLOCKWISE, cv2.ROTATE_180, cv2.ROTATE_90_COUNTERCLOCKWISE])
def test_turned_pages(ocr, turn):
bgr = cv2.imread(PAGE)
upright = [ln.text for ln in ocr(bgr)]
img = cv2.rotate(bgr, turn)
turned = ocr(img)
assert [ln.text for ln in turned[:2]] == upright[:2] # read upright, in the upright page's reading order
common = sum((Counter(upright) & Counter(ln.text for ln in turned)).values())
assert common >= 0.9 * len(upright)
h, w = img.shape[:2] # boxes in the turned image's pixels
assert all(-1 <= x <= w + 1 and -1 <= y <= h + 1 for ln in turned for x, y in ln.box)
def test_read_line(ocr):
bgr = cv2.imread(PAGE)
line = next(ln for ln in ocr(bgr) if ln.text == "VAT Reg. No.: GB179116235")
q = np.array(line.box)
x0, y0 = q.min(0).astype(int)
x1, y1 = q.max(0).astype(int)
text, conf = ocr.read_line(bgr[y0:y1 + 1, x0:x1 + 1])
assert text == line.text and conf > 0.9
def test_cli(capsys):
assert main([PAGE, "--threads", "1"]) == 0
assert "Brightwater Analytics LLP" in capsys.readouterr().out