# 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. """Optional bridge from the public Transformers capture to the pixel-free backend.""" import time from typing import Any, Protocol import numpy as np from .blocks import split_blocks from .io import units_for class LayoutBackend(Protocol): def __call__(self, *, answer: str, attention: dict) -> dict: ... def ground_fast_layout( grounder: Any, image: Any, answer: str, *, backend: LayoutBackend, attention: dict | None = None, ) -> dict: """Capture with public OCRia when needed; cached calls only inspect image.size. Use this backend's token spans, not the public package's block parser: sparse row indices must follow exactly the transcript units consumed by ground_cached. Retain 512 cells per unit, matching our replay cache, rounded to six decimals. """ capture_ms = 0.0 source = "precomputed" if attention is None: started = time.perf_counter() units, _ = units_for(answer, split_blocks(answer)) width, height = image.size if units: maps, grid, has = grounder.unit_maps(image, answer, units) flat = maps.reshape(len(units), -1) indices, values = [], [] for row, valid in zip(flat, has, strict=True): count = min(512, len(row)) top = ( np.argpartition(-row, count - 1)[:count] if valid else np.empty(0, dtype=np.int64) ) indices.append(top.tolist()) values.append(np.round(row[top].astype(np.float32), 6).tolist()) else: grid, has, indices, values = (1, 1), [], [], [] attention = { "width": width, "height": height, "grid": list(grid), "sparse_maps": {"idx": indices, "val": values, "has": list(has)}, } capture_ms = (time.perf_counter() - started) * 1000 source = "teacher-forced" elif tuple(image.size) != (attention["width"], attention["height"]): raise ValueError("Image dimensions differ from the attention coordinate frame") page = backend(answer=answer, attention=attention) page["attention_source"] = source page["timings_ms"]["attention_capture"] = capture_ms return page