File size: 2,325 Bytes
400c03b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# 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.
"""Capture adapter regressions: raster isolation, coordinate frames, and top-k retention."""

from typing import Any

import numpy as np
import pytest

from parse_rl_utils.ocria_attention_grounding.hf_adapter import ground_fast_layout


class DimensionsOnly:
    size = (600, 300)

    def convert(self, *_args: Any) -> None:
        raise AssertionError("Cached grounding must not read raster pixels")


class RecordingBackend:
    def __init__(self) -> None:
        self.capture: dict = {}

    def __call__(self, *, answer: str, attention: dict) -> dict:
        self.capture = attention
        return {"timings_ms": {}, "items": []}


def test_cached_attention_skips_gpu_and_raster_and_rejects_wrong_frame() -> None:
    backend = RecordingBackend()
    capture = {"width": 600, "height": 300}
    page = ground_fast_layout(
        None, DimensionsOnly(), "word", backend=backend, attention=capture
    )
    assert page["attention_source"] == "precomputed"
    assert page["timings_ms"]["attention_capture"] == 0
    with pytest.raises(ValueError, match="coordinate frame"):
        ground_fast_layout(
            None,
            DimensionsOnly(),
            "word",
            backend=backend,
            attention={"width": 300, "height": 600},
        )


def test_live_capture_keeps_512_cells_and_missing_unit_alignment() -> None:
    class Grounder:
        def unit_maps(self, image: Any, answer: str, units: list) -> tuple:
            assert [answer[start:end] for start, end in units] == ["first", "second"]
            return (
                np.arange(1200, dtype=np.float32).reshape(2, 20, 30),
                (20, 30),
                [True, False],
            )

    backend = RecordingBackend()
    page = ground_fast_layout(
        Grounder(), DimensionsOnly(), "first second", backend=backend
    )
    sparse = backend.capture["sparse_maps"]
    assert set(sparse["idx"][0]) == set(range(88, 600))
    assert sparse["idx"][1] == []
    assert sparse["val"][1] == []
    assert sparse["has"] == [True, False]
    assert page["attention_source"] == "teacher-forced"