OCRia-1 / tests /test_public_interfaces.py
suryatmodulus's picture ajimeno's picture
Duplicate from llamaindex/OCRia-1
400c03b
Raw History Blame Contribute Delete
6.21 kB
# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.
# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).
# This is not open-source software: see the license for permitted uses.
"""Exercise public dispatch, serialization, CLI, and HTTP with CPU attention fixtures."""
import base64
import http.client
import importlib.util
import io
import json
from pathlib import Path
import runpy
import sys
import threading
import numpy as np
from PIL import Image
import pytest
import ocria_grounding
from ocria_grounding import ground_layout, load_fast_layout, to_layout_items_page
from parse_rl_utils.ocria_attention_grounding.api import FastLayout
ROOT = Path(__file__).resolve().parents[1]
ANSWER = "# Heading\n\nOne two three four five six seven eight."
class Capture:
def unit_maps(
self, image: Image.Image, answer: str, units: list[tuple[int, int]]
) -> tuple[np.ndarray, tuple[int, int], np.ndarray]:
maps = np.zeros((len(units), 12, 16), dtype=np.float32)
for i in range(len(units)):
maps[i, 3 + i // 5, 2 + i % 5] = 1
return maps, (12, 16), np.ones(len(units), dtype=bool)
@pytest.fixture(scope="module")
def backend() -> FastLayout:
return load_fast_layout()
def test_fast_dispatch_rejects_detector_and_unknown_method(backend: FastLayout) -> None:
image = Image.new("RGB", (320, 240), "white")
with pytest.raises(ValueError, match="attention only"):
ground_layout(
Capture(),
image,
ANSWER,
method="fast-layout",
fast_backend=backend,
detector=object(),
)
with pytest.raises(ValueError, match="Unknown layout method"):
ground_layout(None, image, ANSWER, method="typo")
def test_serializer_preserves_split_segments_and_text_offsets() -> None:
segments = [
{
"x": 10.0,
"y": 20.0,
"w": 30.0,
"h": 40.0,
"label": "text",
"start_index": 0,
"end_index": 4,
},
{
"x": 60.0,
"y": 5.0,
"w": 20.0,
"h": 15.0,
"label": "text",
"start_index": 5,
"end_index": 9,
},
]
page = {
"width": 100,
"height": 100,
"items": [
{
"type": "Text",
"label": "text",
"md": "alpha beta",
"box": [10.0, 5.0, 80.0, 60.0],
"layout_segments": segments,
}
],
}
result = to_layout_items_page(page, scale=0.5)["items"][0]
assert result["layout_segments"] == [
{**s, **{k: s[k] * 0.5 for k in ("x", "y", "w", "h")}} for s in segments
]
assert page["items"][0]["layout_segments"] == segments
def test_cli_fast_mode_skips_detector_and_writes_boxes(tmp_path, monkeypatch, backend):
source = tmp_path / "page.png"
Image.new("RGB", (320, 240), "white").save(source)
monkeypatch.setattr(ocria_grounding, "load", lambda *args: Capture())
monkeypatch.setattr(ocria_grounding, "transcribe", lambda *args: ANSWER)
monkeypatch.setattr(ocria_grounding, "load_fast_layout", lambda: backend)
def fail_detector() -> None:
raise AssertionError("CLI loaded detector in fast mode")
monkeypatch.setattr(ocria_grounding, "load_detector", fail_detector)
monkeypatch.setattr(
sys, "argv", ["boxes.py", str(source), "--layout", "fast-layout"]
)
runpy.run_path(str(ROOT / "examples/boxes.py"), run_name="__main__")
result = json.loads(source.with_suffix(".boxes.json").read_text())
assert result["items"] and result["attention_source"] == "teacher-forced"
assert Image.open(source.with_suffix(".boxes.png")).size == (320, 240)
def test_http_fast_mode_serializes_real_backend_result_and_rejects_bad_input(
backend: FastLayout,
) -> None:
spec = importlib.util.spec_from_file_location(
"serve_boxes", ROOT / "examples/serve_boxes.py"
)
server_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(server_module)
server_module.STATE.update(
g=Capture(), det=None, method="fast-layout", fast=backend
)
server = server_module.ThreadingHTTPServer(("127.0.0.1", 0), server_module.Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
image = io.BytesIO()
Image.new("RGB", (320, 240), "white").save(image, format="PNG")
request = {
"image_png_b64": base64.b64encode(image.getvalue()).decode(),
"answer": ANSWER,
}
try:
connection = http.client.HTTPConnection(
"127.0.0.1", server.server_port, timeout=10
)
connection.request(
"POST", "/ground", json.dumps(request), {"Content-Type": "application/json"}
)
response = connection.getresponse()
body = json.loads(response.read())
assert response.status == 200 and body["items"]
assert body["attention_source"] == "teacher-forced"
connection.request(
"POST", "/ground", "{}", {"Content-Type": "application/json"}
)
response = connection.getresponse()
response.read()
assert response.status == 400
connection.close()
finally:
server.shutdown()
server.server_close()
thread.join(timeout=5)
def test_live_fast_dispatch_never_constructs_pixel_geometry(
backend: FastLayout, monkeypatch: pytest.MonkeyPatch
) -> None:
import ocria_grounding.ground as original_ground
import ocria_grounding.layout as original_layout
def reject_pixels(*args: object, **kwargs: object) -> None:
raise AssertionError("Fast dispatch constructed raster geometry")
monkeypatch.setattr(original_ground, "Page", reject_pixels)
monkeypatch.setattr(original_layout, "Page", reject_pixels)
result = ground_layout(
Capture(),
Image.new("RGB", (320, 240)),
ANSWER,
method="fast-layout",
fast_backend=backend,
)
assert result["items"] and result["attention_source"] == "teacher-forced"