# 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. """Detector-free boxes from attention cells, without reading page pixels.""" import statistics import numpy as np from scipy import ndimage from .blocks import Block, resolve_page_numbers from .boxes import envelope, main_cluster from .geometry import paragraph_paths from .words import norm from .io import SparseWordMaps def attention_boxes( size: tuple[int, int], blocks: list[Block], units: list[tuple[int, int]], per_block: list[list[int]], maps: np.ndarray | SparseWordMaps, grid: tuple[int, int], has: np.ndarray, support: bool = False, answer: str = "", infer_words: bool = False, support_boxes: dict[int, tuple[int, int, int, int]] | None = None, peak_indices: np.ndarray | None = None, ) -> dict: """Use peak cells for words and connected attention support for pictures. Coordinates are projected directly from the attention grid to image pixels. Consecutive words sharing a cell collapse for path selection, while their original text spans remain intact. No ink, rendering, or pixel masks are used. Optional support boxes are per-unit cell bounds for the same 0.3-threshold, eight-connected peak component; omitted entries use the normal calculation. """ width, height = size gh, gw = grid cw, ch = width / gw, height / gh if peak_indices is None and isinstance(maps, SparseWordMaps): peaks = maps.peaks elif peak_indices is None: peaks = ( np.argmax(maps.reshape(len(maps), -1), axis=1) if len(maps) else np.array([], dtype=int) ) else: peaks = peak_indices lengths = [max(1, len(norm(answer[s:e]))) for s, e in units] if infer_words else [] advances: dict[int, list[float]] = {} if infer_words: # Adjacent word centres constrain character advance without a font or # pixel detector. Ignore reversed/different-line pairs and large gaps. for k, (block, indices) in enumerate(zip(blocks, per_block)): if block.type == "image": continue estimates = [] for a, b in zip(indices, indices[1:]): ya, xa = divmod(int(peaks[a]), gw) yb, xb = divmod(int(peaks[b]), gw) advance = (xb - xa) * cw / ((lengths[a] + lengths[b]) / 2 + 1) if has[a] and has[b] and ya == yb and 0.1 * cw <= advance <= 1.5 * cw: estimates.append(advance) advances[k] = estimates global_advance = statistics.median( [a for values in advances.values() for a in values] or [0.5 * ch] ) pieces: list[Block] = [] boxes: list[list[float] | None] = [] for block_index, (block, indices) in enumerate(zip(blocks, per_block)): estimates = advances.get(block_index, []) advance = ( statistics.median(estimates) if len(estimates) >= 3 else global_advance ) located: list[tuple[int, list[float]]] = [] for u in indices: if not has[u]: continue y, x = divmod(int(peaks[u]), gw) maximum = ( maps.maxima[u] if isinstance(maps, SparseWordMaps) else maps[u, y, x] ) if maximum <= 0: continue x0, y0, x1, y1 = int(x), int(y), int(x) + 1, int(y) + 1 if support and support_boxes is not None and u in support_boxes: x0, y0, x1, y1 = support_boxes[u] elif support or block.type == "image": m = maps[u] labels, _ = ndimage.label( m >= 0.3 * float(m[y, x]), structure=np.ones((3, 3)) ) yy, xx = np.nonzero(labels == labels[y, x]) x0, y0, x1, y1 = ( int(xx.min()), int(yy.min()), int(xx.max()) + 1, int(yy.max()) + 1, ) box = [x0 * cw, y0 * ch, x1 * cw, y1 * ch] if infer_words and block.type != "image": cx, cy = (x + 0.5) * cw, (y + 0.5) * ch half_width, half_height = ( max(cw / 2, lengths[u] * advance / 2), 0.85 * advance, ) box = [ max(0.0, cx - half_width), max(0.0, cy - half_height), min(float(width), cx + half_width), min(float(height), cy + half_height), ] if not located or box != located[-1][1]: located.append((u, box)) if not located: pieces.append(Block(block.type, block.start, block.end)) boxes.append(None) continue words = [box for _, box in located] paths = ( paragraph_paths(words) if block.type in ("text", "list", "heading") else None ) if infer_words and block.type == "heading" and paths: # A heading can have wide spaces; its supported runs share one box. paths = [[i for path in paths for i in path]] if paths: for k, path in enumerate(paths): start = block.start if k == 0 else units[located[path[0]][0]][0] end = ( block.end if k + 1 == len(paths) else units[located[paths[k + 1][0]][0]][0] ) pieces.append(Block(block.type, start, end)) boxes.append(envelope([words[i] for i in path])) else: pieces.append(Block(block.type, block.start, block.end)) boxes.append(envelope(main_cluster(words, ch, wide=block.type == "table"))) resolve_page_numbers(pieces, boxes, height) return { "width": width, "height": height, "grid": list(grid), "elements": [ { "type": b.type, "start": b.start, "end": b.end, "box": None if box is None else [round(v, 1) for v in box], } for b, box in zip(pieces, boxes) ], }