# 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. """Select a word attention mode using sparse support and transcript neighbors.""" from typing import Protocol from .predict import predict from .rust import get_rust import numpy as np from .blocks import Block PEAK_FEATURE_VERSION = "word-peaks-v1" PEAK_FEATURE_COUNT = 22 PEAK_SELECTION_MARGIN = 0.1 class PeakPredictor(Protocol): def predict(self, features: np.ndarray) -> np.ndarray: ... def peak_candidates( context: np.ndarray, peak: np.ndarray, indices: list[int], values: list[float], grid_width: int, ) -> tuple[list[int], list[list[float]]]: """Return sparse-array positions and features for four separated modes. Positions index the original sparse arrays, not sorted ranks or grid cells. Geometry uses grid-cell units. Neighbor offsets come from the existing 53-column word context representation; reference boxes are not inputs. """ ix, attention = np.asarray(indices), np.asarray(values) points = np.column_stack([ix % grid_width + 0.5, ix // grid_width + 0.5]) remaining = np.argsort(-attention) retained = [] while len(remaining) and len(retained) < 4: index = int(remaining[0]) retained.append(index) # Squared distance preserves the 1.5-cell separation without square roots. distance = points[remaining] - points[index] remaining = remaining[distance[:, 0] ** 2 + distance[:, 1] ** 2 >= 2.25] selected = points[retained] delta = selected - peak nearby = (abs(points[None, :, 0] - selected[:, None, 0]) <= 1) & ( abs(points[None, :, 1] - selected[:, None, 1]) <= 1 ) rows = np.empty((len(retained), PEAK_FEATURE_COUNT)) rows[:, 0] = np.arange(len(retained)) rows[:, 1] = attention[retained] / attention.max() total = attention.sum() rows[:, 2] = [attention[mask].sum() / total for mask in nearby] rows[:, 3] = np.log1p(context[0]) rows[:, 4:6] = delta neighbors = context[34:50].reshape(4, 4) offsets = np.clip(neighbors[None, :, :2] - delta[:, None, :], -30, 30) offsets = np.where(neighbors[None, :, 3:4] != 0, offsets, 0) tail = rows[:, 6:].reshape(-1, 4, 4) tail[:, :, :2] = offsets tail[:, :, 2] = np.log1p(neighbors[:, 2]) tail[:, :, 3] = neighbors[:, 3] return retained, rows.tolist() def select_word_peaks( context: np.ndarray, valid: list[int], peaks: np.ndarray, sparse: dict, grid: tuple[int, int], blocks: list[Block], per_block: list[list[int]], model: PeakPredictor, ) -> dict[int, int]: """Map original text-unit indices to selected sparse-array positions. Batch candidate scoring across the page. Preserve the primary mode unless an alternative clears the quality margin; image and table maps are skipped. """ eligible = { u for block, units in zip(blocks, per_block) if block.type in {"text", "list", "heading", "header", "footer"} for u in units } rust = get_rust() if rust is not None: rows, records = rust.peak_features( context, valid, peaks, sparse, grid, eligible ) else: rows, records = [], [] for j, u in enumerate(valid): if u not in eligible: continue retained, features = peak_candidates( context[j], peaks[j], sparse["idx"][u], sparse["val"][u], grid[1] ) records.append((u, len(rows), retained)) rows.extend(features) if not len(rows): return {} quality = predict(model, np.asarray(rows)) choices = {} for u, start, retained in records: scores = quality[start : start + len(retained)] best = int(scores.argmax()) if best and scores[best] > scores[0] + PEAK_SELECTION_MARGIN: choices[u] = retained[best] _repair_bracketed_peaks(choices, valid, peaks, sparse, grid, blocks, per_block) return choices def _repair_bracketed_peaks( choices: dict[int, int], valid: list[int], peaks: np.ndarray, sparse: dict, grid: tuple[int, int], blocks: list[Block], per_block: list[list[int]], ) -> None: """Repair isolated vertical outliers bracketed by same-line transcript words. Coordinates and tolerances use attention cells. Snapshot ranked peaks before repairs so changes do not propagate into subsequent repair decisions. Choices retain original sparse-array positions, including gaps from missing attention. """ grid_width = grid[1] lookup = {unit: row for row, unit in enumerate(valid)} positions = peaks.copy() for unit, index in choices.items(): cell = sparse["idx"][unit][index] positions[lookup[unit]] = [cell % grid_width + 0.5, cell // grid_width + 0.5] for block, units in zip(blocks, per_block): if block.type not in {"text", "list"}: continue rows = [lookup[unit] for unit in units if unit in lookup] if len(rows) < 8: continue for index in range(1, len(rows) - 1): row = rows[index] before, after = positions[rows[index - 1]], positions[rows[index + 1]] if abs(before[1] - after[1]) > 1 or after[0] < before[0]: continue neighbors = rows[max(0, index - 3) : index] + rows[index + 1 : index + 4] nearby = positions[neighbors] ys = nearby[:, 1] low, high = ys.min(), ys.max() # A point inside a one-cell band cannot be 1.5 cells from its median. # Reject these common cases before computing the median. if high - low > 1 or low <= positions[row, 1] <= high: continue line_y = float(np.median(ys)) if abs(positions[row, 1] - line_y) <= 1.5: continue unit = valid[row] cells = np.asarray(sparse["idx"][unit]) values = np.asarray(sparse["val"][unit]) x, y = cells % grid_width + 0.5, cells // grid_width + 0.5 # Require a strong alternative between immediate neighbors. Endpoints # and line resets lack this evidence and retain the ranked choice. eligible = ( (abs(y - line_y) <= 0.5) & (x >= before[0] - 0.5) & (x <= after[0] + 0.5) & (values >= 0.25 * values.max()) ) if eligible.any(): indices = np.flatnonzero(eligible) choices[unit] = int(indices[values[indices].argmax()])