# 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. """Typography, shared-line profiles, and sparse support beyond the local patch.""" from .rust import get_rust import numpy as np from .blocks import Block from .native import get_native _BLOCK_TYPES = ( "text", "list", "heading", "header", "footer", "page_number", "table", "image", "code", "formula", ) def extended_features( answer: str, units: list[tuple[int, int]], blocks: list[Block], per_block: list[list[int]], features: np.ndarray, valid: list[int], peaks: np.ndarray, sparse: dict, grid: tuple[int, int], ) -> np.ndarray: """Append 51 features to the 53-feature context representation. Nearby word profiles share the current word's grid-row frame. Full-support quantiles and threshold extents retain evidence beyond the local 5x5 patch. All offsets use grid cells; no annotation or page-image input is accepted. """ gh, gw = grid owners = {u: k for k, indices in enumerate(per_block) for u in indices} lookup = {u: j for j, u in enumerate(valid)} positions = np.full((len(units), 2), np.nan) positions[valid] = peaks # Each word profile is shared by up to 24 neighbors; normalize it once. profiles = features[:, 9:34].reshape(-1, 5, 5).sum(2) profiles /= np.maximum(profiles.sum(1), 1e-12)[:, None] native = get_native() pooled_profiles = ( native.pool_profiles(positions, owners, valid, profiles) if native is not None else None ) rust = get_rust() stats, packed = ( rust.context_bounds(sparse, valid, peaks, gw) if rust is not None else (None, None) ) mass_stats = None if packed: masses = np.concatenate([row[2] for row in packed]) starts = np.r_[ 0, np.cumsum([len(row[2]) for row in packed[:-1]], dtype=np.intp) ] mass_stats = np.column_stack( [ np.maximum.reduceat(masses, starts), -np.add.reduceat(masses * np.log(np.maximum(masses, 1e-12)), starts), ] ) block_types = [ [float(block.type == kind) for kind in _BLOCK_TYPES] for block in blocks ] typography: dict[str, list[float]] = {} extras = [] for row, u in enumerate(valid): owner = owners[u] word = answer[units[u][0] : units[u][1]] glyphs = typography.get(word) if glyphs is None: length = max(1, len(word)) glyphs = [ sum(c.isupper() for c in word) / length, sum(c.isdigit() for c in word) / length, sum( "\u2e80" <= c <= "\u9fff" or "\uac00" <= c <= "\ud7af" for c in word ) / length, sum(c in "iljtf1" for c in word) / length, sum(c.lower() in "mw" for c in word) / length, ] typography[word] = glyphs px, py = peaks[row] values = block_types[owner] + glyphs values.extend( [ px / gw, py / gh, len(per_block[owner]), (u - per_block[owner][0]) / max(1, len(per_block[owner]) - 1), ] ) if pooled_profiles is not None: values.extend(pooled_profiles[row].tolist()) else: pooled = np.zeros(7) count = 0 for neighbor in range(max(0, u - 12), min(len(units), u + 13)): if ( neighbor == u or owners.get(neighbor) != owner or neighbor not in lookup or abs(positions[neighbor, 1] - py) > 1 ): continue profile = profiles[lookup[neighbor]] offset = int(round(positions[neighbor, 1] - py)) pooled[1 + offset : 6 + offset] += profile count += 1 if count: pooled /= count values.extend([*pooled.tolist(), count]) if stats is not None: _, attention, mass = packed[row] values.extend(stats[row].tolist()) else: indices = np.asarray(sparse["idx"][u]) attention = np.asarray(sparse["val"][u]) mass = attention / attention.sum() xx, yy = indices % gw + 0.5, indices // gw + 0.5 for coords, peak in ((xx, px), (yy, py)): order = np.argsort(coords) cdf = np.cumsum(mass[order]) quantiles = np.searchsorted(cdf, (0.05, 0.25, 0.5, 0.75, 0.95)) np.minimum(quantiles, len(order) - 1, out=quantiles) values.extend((coords[order[quantiles]] - peak).tolist()) for threshold in (0.1, 0.3, 0.6): keep = attention >= threshold * attention.max() values.extend( [ float(xx[keep].min() - 0.5 - px), float(yy[keep].min() - 0.5 - py), float(xx[keep].max() + 0.5 - px), float(yy[keep].max() + 0.5 - py), ] ) if mass_stats is not None: values.extend(mass_stats[row].tolist()) else: values.extend( [ float(mass.max()), float(-(mass * np.log(np.maximum(mass, 1e-12))).sum()), ] ) extras.append(values) extra_array = np.asarray(extras).reshape(len(valid), 51) # Quantile and threshold offsets share the same grid-cell clipping bounds. np.clip(extra_array[:, 27:49], -20, 20, out=extra_array[:, 27:49]) return np.column_stack([features, extra_array])