SPB Git

Repository Public

test_ocr_worker.py 17.0 KB 382 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER — Universal Web Intelligence Engine7# File             : tests/unit/ocr/test_ocr_worker.py8# Module           : Tests9# Repository       : https://git.spboucher.ai/spider10# Project Website  : Not specified11# Created          : 2026-12-0412# Last Modified    : 2026-12-0413#14# Author           : Simon-Pierre Boucher15# Position         : Professor of Finance16# Institution      : Université du Québec en Outaouais (UQO)17# Organization     : SP Boucher18# Website          : https://spboucher.ai19# Git              : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development      : dev@spboucher.ai23# Support          : support@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : ISC33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Real OCR through the native worker. Skipped automatically where `spider-ocr` is unavailable42(not macOS, or binary not built: `services/ocr-worker/build.sh`)."""43from __future__ import annotations4445import hashlib46import json47import os48import signal49import subprocess50from pathlib import Path5152import pytest53from PIL import Image5455from spider.contracts import CaptureRef, Rect56from spider.ocr import (57    OcrError,58    OcrUnavailable,59    OcrWorker,60    available,61    binary_path,62    cer,63    merge_tile_lines,64    similarity,65)66from spider.ocr import client as ocr_client6768SAMPLE = Path(__file__).resolve().parents[2] / "fixtures" / "ocr" / "sample"69GROUND_TRUTH = {rec["file"]: rec for rec in map(json.loads, (SAMPLE / "ground_truth.jsonl").read_text("utf-8").splitlines())}7071def real(test):72    """Marks a test that needs the native worker; skipped where it is not available."""73    skip = pytest.mark.skipif(not available(), reason="spider-ocr (Apple Vision) is not available")74    return pytest.mark.macos(skip(test))757677def reference(name: str) -> str:78    return "\n".join(line["text"] for line in GROUND_TRUTH[name]["lines"])798081@pytest.fixture82async def worker():83    async with OcrWorker(timeout=60) as w:84        yield w858687# ------------------------------------------------------------------ availability (runs everywhere)88def test_unavailable_off_macos(monkeypatch):89    monkeypatch.setattr(ocr_client.sys, "platform", "linux")90    assert ocr_client.available() is False91    with pytest.raises(OcrUnavailable):92        ocr_client.build()939495async def test_missing_binary_raises_unavailable(tmp_path, monkeypatch):96    monkeypatch.setenv("SPIDER_OCR_BIN", str(tmp_path / "nope"))97    monkeypatch.setattr(ocr_client, "WORKER_DIR", tmp_path / "no-worker")98    monkeypatch.setattr(ocr_client.Path, "home", classmethod(lambda cls: tmp_path))99    assert ocr_client.binary_path() is None100    assert ocr_client.available() is False101    w = OcrWorker()102    with pytest.raises(OcrUnavailable):103        await w.start()104    with pytest.raises(OcrUnavailable):105        await w.recognize(SAMPLE / "para-fr-16-0.png")106    with pytest.raises(OcrUnavailable):107        await w.recognize_many([SAMPLE / "para-fr-16-0.png"], return_exceptions=True)108    await w.close()109110111def test_binary_path_prefers_env(tmp_path, monkeypatch):112    fake = tmp_path / "spider-ocr"113    fake.write_text("#!/bin/sh\nexit 0\n")114    fake.chmod(0o755)115    monkeypatch.setenv("SPIDER_OCR_BIN", str(fake))116    assert ocr_client.binary_path() == fake117118119# ------------------------------------------------------------------ real recognition120@pytest.mark.parametrize(("name", "limit"), [("para-fr-16-0.png", 0.02), ("para-en-16-0.png", 0.02),121                                             ("prices-fr-dark.png", 0.02), ("prices-en-light.png", 0.02)])122@real123async def test_recognises_french_and_english_samples(worker, name, limit):124    page = await worker.recognize(SAMPLE / name)125    truth = GROUND_TRUTH[name]126    assert (page.width, page.height) == (truth["width"], truth["height"])127    assert page.orientation == 1 and page.rotation == 0 and not page.banded128    assert page.engine["name"] == "apple-vision" and page.engine["revision"] >= 1129    assert cer(reference(name), page.text) <= limit130    assert len(page.lines) == len(truth["lines"])131    assert all(0 < line.confidence <= 1 for line in page.lines)132133134@real135async def test_french_accents_and_prices_are_read(worker):136    page = await worker.recognize(SAMPLE / "prices-fr-dark.png", languages=["fr-CA", "en-US"])137    assert "Payé le 28 février 2025 : 1 250,00 $" in page.text138    assert "Échéance : 2025-02-17" in page.text139140141@pytest.mark.parametrize("name", ["para-fr-16-0.png", "para-en-24-1.png", "columns-en.png", "page-fr-light.png"])142@real143async def test_pixel_boxes_fall_inside_ground_truth_boxes(worker, name):144    page = await worker.recognize(SAMPLE / name)145    for truth in GROUND_TRUTH[name]["lines"]:146        best = max(page.lines, key=lambda line: similarity(line.text, truth["text"]))147        assert similarity(best.text, truth["text"]) >= 0.9, truth["text"]148        # Vision pads its boxes (ascenders, descenders): allow 0.6 x font size, at least 4 px.149        tol = max(4.0, 0.6 * truth["size"])150        assert best.x >= truth["x"] - tol and best.y >= truth["y"] - tol, (truth, best)151        assert best.x + best.w <= truth["x"] + truth["w"] + tol, (truth, best)152        assert best.y + best.h <= truth["y"] + truth["h"] + tol, (truth, best)153        # and the box really is on the line: it covers the centre of the ground-truth box154        cx, cy = truth["x"] + truth["w"] / 2, truth["y"] + truth["h"] / 2155        assert best.x <= cx <= best.x + best.w and best.y <= cy <= best.y + best.h156        assert len(best.quad) == 4157158159@real160async def test_lines_are_in_reading_order_on_two_columns(worker):161    page = await worker.recognize(SAMPLE / "columns-en.png")162    assert cer(reference("columns-en.png"), page.text) <= 0.02  # ground truth is row-major163164165@real166async def test_alternatives_and_fast_level(worker):167    page = await worker.recognize(SAMPLE / "para-en-24-1.png", alternatives=2)168    assert all(len(line.alternatives) <= 2 for line in page.lines)169    assert any(line.alternatives for line in page.lines)170    assert all(len(line.alternatives) == len(line.alternative_confidences) for line in page.lines)171    none = await worker.recognize(SAMPLE / "para-en-24-1.png", alternatives=0)172    assert all(line.alternatives == [] for line in none.lines)173    fast = await worker.recognize(SAMPLE / "para-en-24-1.png", fast=True)174    assert fast.level == "fast" and cer(reference("para-en-24-1.png"), fast.text) <= 0.05175176177@real178async def test_serve_mode_batches_in_one_process(worker):179    names = sorted(GROUND_TRUTH)180    pid = worker.pid181    pages = await worker.recognize_many([SAMPLE / n for n in names] * 2)182    assert len(pages) == 2 * len(names)183    assert [Path(p.path).name for p in pages] == names * 2          # input order is kept184    assert worker.pid == pid and worker.restarts == 0               # one process served everything185    for name, first, second in zip(names, pages[:len(names)], pages[len(names):], strict=True):186        assert first.text == second.text                             # deterministic187        assert (first.width, first.height) == (GROUND_TRUTH[name]["width"], GROUND_TRUTH[name]["height"])188    info = await worker.ping()189    assert info["op"] == "pong" and info["pid"] == pid190    assert "en-US" in await worker.supported_languages()191192193@real194async def test_corrupt_files_give_structured_errors(worker, tmp_path):195    good = SAMPLE / "para-en-16-0.png"196    truncated = tmp_path / "truncated.png"197    truncated.write_bytes(good.read_bytes()[:4000])198    empty = tmp_path / "empty.png"199    empty.write_bytes(b"")200    text = tmp_path / "not-an-image.png"201    text.write_text("this is not an image")202    missing = tmp_path / "missing.png"203204    for path, code in [(truncated, "corrupt_image"), (empty, "empty_file"), (text, "unreadable_image"),205                       (missing, "not_found"), (tmp_path, "not_a_file")]:206        with pytest.raises(OcrError) as caught:207            await worker.recognize(path)208        assert caught.value.code == code209        assert caught.value.path == str(path.resolve())210211    results = await worker.recognize_many([good, truncated, empty, good], return_exceptions=True)212    assert [type(r).__name__ for r in results] == ["OcrPage", "OcrError", "OcrError", "OcrPage"]213    assert results[0].text == results[3].text and len(results[0].lines) == 8214    with pytest.raises(OcrError):215        await worker.recognize_many([good, truncated])216    assert worker.restarts == 0  # errors never took the worker down217218219@real220async def test_worker_restarts_after_being_killed(worker):221    first = await worker.recognize(SAMPLE / "para-fr-16-0.png")222    old_pid = worker.pid223    os.kill(old_pid, signal.SIGKILL)224    again = await worker.recognize(SAMPLE / "para-fr-16-0.png")225    assert again.text == first.text226    assert worker.restarts == 1 and worker.pid not in (None, old_pid)227    # a second death is survived too, and a batch in flight is replayed228    os.kill(worker.pid, signal.SIGKILL)229    pages = await worker.recognize_many([SAMPLE / "para-fr-16-0.png", SAMPLE / "para-en-16-0.png"])230    assert pages[0].text == first.text and worker.restarts == 2231232233@real234async def test_timeout_restarts_the_worker(worker):235    with pytest.raises(OcrError) as caught:236        await worker.recognize(SAMPLE / "tiles-fr.png", timeout=0.001)237    assert caught.value.code == "timeout"238    page = await worker.recognize(SAMPLE / "para-en-16-0.png")239    assert len(page.lines) == 8 and worker.restarts == 1240241242@real243async def test_restarts_are_bounded():244    w = OcrWorker(binary="/usr/bin/false", max_restarts=3)  # a "worker" that exits at once245    outcomes = []246    for _ in range(6):247        try:248            await w.recognize(SAMPLE / "para-en-16-0.png")249        except OcrError as exc:250            outcomes.append(exc.code)251        except OcrUnavailable as exc:252            outcomes.append("unavailable")253            assert "in a row" in str(exc)254    await w.close()255    assert outcomes[0] == "worker_crashed" and outcomes[-1] == "unavailable"256    assert w.restarts == 3257258259@real260async def test_closed_worker_refuses_requests():261    w = OcrWorker()262    await w.start()263    await w.close()264    with pytest.raises(OcrUnavailable):265        await w.recognize(SAMPLE / "para-en-16-0.png")266267268def tile_capture(source: Image.Image, top: int, bottom: int, dpr: float, out: Path) -> CaptureRef:269    out.parent.mkdir(parents=True, exist_ok=True)270    source.crop((0, top, source.width, bottom)).save(out)271    return CaptureRef(kind="tile", path=str(out), sha256=hashlib.sha256(out.read_bytes()).hexdigest(),272                      mime="image/png", width=source.width, height=bottom - top, dpr=dpr,273                      css=Rect(x=0, y=top / dpr, w=source.width / dpr, h=(bottom - top) / dpr))274275276@real277async def test_overlapping_tiles_are_deduplicated(worker, tmp_path):278    name = "tiles-fr.png"279    truth = GROUND_TRUTH[name]280    source = Image.open(SAMPLE / name)281    dpr = 2.0282    # Two real tile crops of one page, 120 px of overlap; the seams cut through lines of text.283    tiles = [tile_capture(source, 0, 540, dpr, tmp_path / "t0.png"),284             tile_capture(source, 420, source.height, dpr, tmp_path / "t1.png")]285    pages = [(cap, (await worker.recognize_capture(cap)).lines) for cap in tiles]286    assert all(line.capture_sha256 == cap.sha256 for cap, lines in pages for line in lines)287288    naive = sum(len(lines) for _, lines in pages)289    merged = merge_tile_lines(pages)290    assert naive > len(truth["lines"])                    # the overlap really produced duplicates291    assert len(merged) == len(truth["lines"])             # ... and each line survives exactly once292    assert cer(reference(name), "\n".join(m["text"] for m in merged)) <= 0.02293    assert {m["capture_sha256"] for m in merged} == {cap.sha256 for cap in tiles}294    for m, expected in zip(merged, truth["lines"], strict=True):  # document CSS coordinates295        assert abs(m["css"].y - expected["y"] / dpr) <= 0.6 * expected["size"] / dpr296        assert abs(m["css"].x - expected["x"] / dpr) <= 0.6 * expected["size"] / dpr297298299@real300async def test_banding_gives_the_same_text_in_original_coordinates(worker):301    name = "tiles-fr.png"302    whole = await worker.recognize(SAMPLE / name)303    banded = await worker.recognize(SAMPLE / name, max_pixels=150_000)304    assert not whole.banded and banded.banded and banded.bands >= 3305    assert (banded.width, banded.height) == (whole.width, whole.height)306    assert len(banded.lines) == len(GROUND_TRUTH[name]["lines"])307    assert cer(reference(name), banded.text) <= 0.02308    for a, b in zip(whole.lines, banded.lines, strict=True):309        assert abs(a.y - b.y) <= 6 and abs(a.x - b.x) <= 6310311312@real313async def test_rotated_page_is_detected_and_reported_in_original_coordinates(worker):314    name = "rotated-en-90.png"315    truth = GROUND_TRUTH[name]316    page = await worker.recognize(SAMPLE / name, detect_orientation=True)317    assert page.rotation == truth["rotation"] == 90 and page.rotation_detected318    assert (page.width, page.height) == (truth["width"], truth["height"])319    assert cer(reference(name), page.text) <= 0.03320    for line, expected in zip(page.lines, truth["lines"], strict=True):321        assert line.h > line.w                                         # vertical boxes, as in the file322        tol = 0.6 * expected["size"]323        assert abs(line.x - expected["x"]) <= tol and abs(line.y - expected["y"]) <= tol324        assert abs(line.w - expected["w"]) <= 2 * tol and abs(line.h - expected["h"]) <= 2 * tol325    upright = await worker.recognize(SAMPLE / "para-en-16-0.png", detect_orientation=True)326    assert upright.rotation == 0327328329@real330async def test_exif_orientation_is_honoured(worker, tmp_path):331    source = Image.open(SAMPLE / "para-en-16-0.png")332    exif = Image.Exif()333    exif[0x0112] = 8  # stored rotated: the viewer must turn it 90 degrees counter-clockwise334    stored = tmp_path / "exif8.png"335    source.rotate(-90, expand=True).save(stored, exif=exif)  # stored clockwise, displayed upright336    page = await worker.recognize(stored, detect_orientation=True)337    assert page.orientation == 8 and page.rotation == 0338    assert (page.width, page.height) == (source.width, source.height)  # displayed size339    plain = await worker.recognize(SAMPLE / "para-en-16-0.png")340    assert page.text == plain.text341    for a, b in zip(page.lines, plain.lines, strict=True):342        assert abs(a.x - b.x) <= 3 and abs(a.y - b.y) <= 3 and abs(a.w - b.w) <= 4343344345@real346async def test_region_and_language_warnings(worker):347    name = "para-en-16-0.png"348    first = GROUND_TRUTH[name]["lines"][0]349    region = (0, 0, GROUND_TRUTH[name]["width"], first["y"] + first["h"] + 6)350    page = await worker.recognize(SAMPLE / name, region=region, languages=["en-US", "xx-YY"])351    assert [line.text for line in page.lines] == [first["text"]]352    assert abs(page.lines[0].y - first["y"]) <= 0.6 * first["size"]     # still whole-image coordinates353    assert "unsupported_language:xx-YY" in page.warnings and page.languages == ["en-US"]354    with pytest.raises(OcrError) as caught:355        await worker.recognize(SAMPLE / name, region=(5000, 5000, 10, 10))356    assert caught.value.code == "invalid_region"357358359def run(argv: list[str], **kwargs) -> subprocess.CompletedProcess[str]:360    return subprocess.run(argv, check=False, capture_output=True, text=True, **kwargs)361362363@real364def test_one_shot_cli_and_exit_codes(tmp_path):365    binary = str(binary_path())366    empty = tmp_path / "empty.png"367    empty.write_bytes(b"")368    ok = run([binary, str(SAMPLE / "para-fr-16-0.png"), str(empty)])369    rows = [json.loads(line) for line in ok.stdout.splitlines()]370    assert ok.returncode == 0 and [r["ok"] for r in rows] == [True, False]371    assert rows[1]["error"]["code"] == "empty_file" and rows[0]["error"] is None372    assert cer(reference("para-fr-16-0.png"), "\n".join(line["text"] for line in rows[0]["lines"])) <= 0.02373    assert run([binary, str(empty), str(tmp_path / "missing.png")]).returncode == 1374    assert run([binary]).returncode == 2375    assert run([binary, "--level", "bogus", "x.png"]).returncode == 2376    langs = json.loads(run([binary, "--list-languages"]).stdout)377    assert "en-US" in langs["languages"] and langs["engine"]["name"] == "apple-vision"378    served = run([binary, "--serve"], input='{"op":"ping","id":7}\nnot json\n{"id":"x"}\n')379    replies = [json.loads(line) for line in served.stdout.splitlines()]380    assert served.returncode == 0 and replies[0]["op"] == "pong" and replies[0]["id"] == 7381    assert [r["error"]["code"] for r in replies[1:]] == ["bad_json", "bad_request"]382
Files main
Menu

Theme