# 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. """Sub-cell word boundaries from attention, composed with conservative block grouping.""" from bisect import bisect_left, bisect_right from typing import Protocol import re from .predict import predict import numpy as np from .headers import split_navigation_headers from .columns import split_column_blocks from .native import get_native from .blocks import split_blocks from .bullet_tables import split_bullet_tables from .context import extended_features from .io import SparseWordMaps, dense_maps, element_text, units_for from .orientation import ( coherent_rotated_words, rotate_attention_clockwise, vertical_text_spans, ) from .rectangles import RectangleConfig, rectangle_boxes from .pictures import PicturePredictor, refine_pictures from .rust import get_rust from .words import norm from .regions import ( HeadingGlyphRegionBlend, contextual_region_features, heading_glyph_features, region_features, ) from .tables import TablePredictor, refine_tables, refine_table_word_boxes from .repeated import recover_repeated_paragraphs from .peaks import PeakPredictor, select_word_peaks _INLINE_IMAGE_REFERENCE = re.compile(r"!\[[^\]\n]+\]") _NUMERIC_WORD = re.compile(r"[\s*$€£+\d.,%−-]+") BASE_CONFIG = RectangleConfig( keep_tables=True, fit_lines=True, font_height=2.2, anchor_fraction=0.25, connected_words=True, image_quantile=0.15, y_offset=0.125, guard_expansion=1.5, heading_x_scale=1.05, text_x_scale=1.025, furniture_y_inset=0.125, furniture_x_scale=1.1, fit_blend_x=0.75, fit_blend_y=0.75, image_text_suppression=16, ) _TEXT_TYPES = {"text", "list", "heading", "header", "footer"} class Predictor(Protocol): def predict(self, features: np.ndarray) -> np.ndarray: ... def attention_features( answer: str, units: list[tuple[int, int]], sparse: dict, grid: tuple[int, int], anchors: dict[int, int] | None = None, ) -> tuple[np.ndarray, list[int], np.ndarray]: """Return features, retained unit indices, and peak centers in grid-cell units. The 5x5 patch is normalized by the strongest cached cell. Optional anchors select a sparse-array position without modifying weights. Relative moments are clipped to five cells so a weak distant hotspot cannot dominate a word's features. Preserve this feature order when fitting or loading boundary regressors. """ rust = get_rust() if rust is not None: return rust.local_features(answer, units, sparse, grid, anchors) gh, gw = grid features, valid, peaks = [], [], [] for u, (start, end) in enumerate(units): indices = np.asarray(sparse["idx"][u]) values = np.asarray(sparse["val"][u]) if not len(indices) or not sparse["has"][u]: continue maximum = values.max() if not maximum: continue order = np.argsort(-values) if anchors and u in anchors: chosen = anchors[u] order = np.r_[chosen, order[order != chosen]] indices, values = indices[order], values[order] yy, xx = indices // gw, indices % gw dx, dy = (xx - xx[0]).astype(float), (yy - yy[0]).astype(float) patch = np.zeros((5, 5)) local = (abs(dx) <= 2) & (abs(dy) <= 2) patch[(dy[local] + 2).astype(int), (dx[local] + 2).astype(int)] = ( values[local] / maximum ) total = values.sum() mass = values / total clipped_x, clipped_y = dx.clip(-5, 5), dy.clip(-5, 5) features.append( [ len(norm(answer[start:end])), gh, gw, float(maximum), float(total), float((mass * clipped_x).sum()), float((mass * clipped_y).sum()), float((mass * clipped_x**2).sum()), float((mass * clipped_y**2).sum()), *patch.ravel().tolist(), ] ) valid.append(u) peaks.append((xx[0] + 0.5, yy[0] + 0.5)) return ( np.asarray(features, dtype=float).reshape(-1, 34), valid, np.asarray(peaks, dtype=float).reshape(-1, 2), ) def contextual_features( answer: str, units: list[tuple[int, int]], per_block: list[list[int]], features: np.ndarray, valid: list[int], peaks: np.ndarray, ) -> np.ndarray: """Append transcript-neighbor and local line-spacing evidence in grid cells. Only words in the same emitted block contribute. Missing attention keeps its original unit index, so a missing word cannot shift the neighborhood. A local 25-word window bounds work independently of document length. """ positions = np.full((len(units), 2), np.nan) positions[valid] = peaks # Python scalar access avoids repeated NumPy indexing in fixed-size windows. coordinates = positions.tolist() present = np.isfinite(positions[:, 0]).tolist() lengths = [len(norm(answer[start:end])) for start, end in units] owners = {u: k for k, indices in enumerate(per_block) for u in indices} native = get_native() if native is not None: return np.column_stack( [features, native.neighborhood(positions, lengths, owners, valid)] ) context = [] for u in valid: px, py = coordinates[u] row = [] for offset in (-2, -1, 1, 2): neighbor = u + offset if ( 0 <= neighbor < len(units) and owners.get(neighbor) == owners.get(u) and present[neighbor] ): nx, ny = coordinates[neighbor] row.extend( [ float(nx - px), float(ny - py), lengths[neighbor], 1.0, ] ) else: row.extend([0.0, 0.0, 0.0, 0.0]) nearby = [ j for j in range(max(0, u - 12), min(len(units), u + 13)) if owners.get(j) == owners.get(u) and present[j] and abs(coordinates[j][1] - py) <= 1 ] advances = [] for first, second in zip(nearby, nearby[1:]): delta = coordinates[second][0] - coordinates[first][0] chars = 0.75 * lengths[first] + 1 + 0.25 * lengths[second] if 0.1 <= delta / max(chars, 1) <= 1.5: advances.append(delta / chars) row.extend( [ len(nearby), float(np.median(advances)) if advances else 0.0, float(np.median(positions[nearby, 1])) - py if nearby else 0.0, ] ) context.append(row) context_array = np.asarray(context).reshape(-1, 19) # Batch neighbor-offset clipping instead of dispatching eight scalar ufuncs. context_array[:, 0:16:4] = np.clip(context_array[:, 0:16:4], -20, 20) context_array[:, 1:16:4] = np.clip(context_array[:, 1:16:4], -10, 10) return np.column_stack([features, context_array]) def recover_line_tails( accepted: set[int], candidates: set[int], peaks: np.ndarray ) -> list[int]: """Recover omitted word runs bracketed by a line continuation and a wrap. Indices follow transcript order; coordinates are attention-grid cells. Candidates already satisfy the paragraph's vertical guard. A misplaced word may interrupt the line. A quantized row tie requires earlier downward progression and a short horizontal gap relative to local word spacing. """ accepted = set(accepted) runs: list[list[int]] = [] for j in sorted(candidates - accepted): if not runs or j != runs[-1][-1] + 1: runs.append([j]) else: runs[-1].append(j) for run in runs: if len(run) < 3: continue first, last = run[0], run[-1] before = next((j for j in (first - 1, first - 2) if j in accepted), None) after = last + 1 if before is None or after not in accepted: continue positions = peaks[run] low, high = positions.min(0), positions.max(0) prior, following = peaks[before], peaks[after] if high[1] - low[1] > 1 or np.mean(np.diff(positions[:, 0]) >= -1) < 0.8: continue if ( prior[0] < low[0] and following[0] < low[0] and low[1] - 1 <= prior[1] <= high[1] + 1 and ( high[1] < following[1] <= high[1] + 3 or ( following[1] == high[1] and prior[1] < high[1] and low[0] - prior[0] <= max( 3, 3 * float(np.median(np.maximum(0, np.diff(positions[:, 0])))) ) ) ) ): accepted.update(run) return sorted(accepted) def recover_short_line_tails( selected: list[int], candidates: set[int], peaks: np.ndarray, boxes: np.ndarray ) -> list[int]: """Recover one or two omitted words at a supported line end. All coordinates use attention-grid cells. Neighboring word boxes must be separated by at most two median word heights, with a left/down wrap after the omitted run. This bounds gaps without assuming a page-wide font size. """ accepted = set(selected) runs: list[list[int]] = [] for j in sorted(candidates - accepted): if not runs or j != runs[-1][-1] + 1: runs.append([j]) else: runs[-1].append(j) for run in runs: before, after = run[0] - 1, run[-1] + 1 if len(run) > 2 or before not in accepted or after not in accepted: continue sequence = [before, *run] positions = peaks[sequence] height = float(np.median(boxes[sequence, 3] - boxes[sequence, 1])) gaps = boxes[sequence[1:], 0] - boxes[sequence[:-1], 2] if ( np.ptp(positions[:, 1]) <= 1 and np.all(np.diff(positions[:, 0]) > 0) and np.all((gaps >= -height) & (gaps <= 2 * height)) and peaks[after, 0] < peaks[before, 0] and 0 < peaks[after, 1] - positions[:, 1].max() <= 3 ): accepted.update(run) return sorted(accepted) def recover_paragraph_opening( selected: list[int], element_units: list[tuple[int, tuple[int, int]]], lookup: dict[int, int], peaks: np.ndarray, boxes: np.ndarray, ) -> list[int]: """Recover one or two opening words continuous with an accepted first line. Peaks and word boxes use grid cells. Require increasing horizontal positions on one attention row and gaps of at most two local word heights. A substantial accepted body anchors the paragraph before relaxing its coarse boundary. """ if len(selected) < 8: return selected ordered = [lookup[u] for u, _ in element_units if u in lookup] if not ordered: return selected accepted = set(selected) prefix = [] for index in ordered: if index in accepted: break prefix.append(index) if not 1 <= len(prefix) <= 2 or len(prefix) == len(ordered): return selected sequence = prefix + [ordered[len(prefix)]] positions = peaks[sequence] height = float(np.median(boxes[sequence, 3] - boxes[sequence, 1])) gaps = boxes[sequence[1:], 0] - boxes[sequence[:-1], 2] if ( np.ptp(positions[:, 1]) <= 1 and np.all(np.diff(positions[:, 0]) > 0) and np.all((gaps >= -height) & (gaps <= 2 * height)) ): return sorted(accepted | set(prefix)) return selected def align_word_boxes_to_neighbor_row( selected: list[int], element_units: list[tuple[int, tuple[int, int]]], lookup: dict[int, int], peaks: np.ndarray, grid_boxes: np.ndarray, word_boxes: np.ndarray, cell_height: float, ) -> None: """Repair displaced word boxes when consecutive peaks agree on one line. Update grid-cell and capture-pixel boxes together, preserving word heights. Both neighbors must agree vertically and all three peaks must advance left to right on one row; a line wrap or isolated peak cannot trigger correction. """ ordered = [lookup[u] for u, _ in element_units if u in lookup] accepted = set(selected) for k in range(1, len(ordered) - 1): left, mid, right = ordered[k - 1 : k + 2] if not {left, mid, right} <= accepted: continue ax, ay = peaks[left] bx, by = peaks[mid] cx, cy = peaks[right] if max(ay, by, cy) - min(ay, by, cy) > 1 or not ax < bx < cx: continue ltop, lbottom = grid_boxes[left, 1], grid_boxes[left, 3] rtop, rbottom = grid_boxes[right, 1], grid_boxes[right, 3] height = float((lbottom - ltop + rbottom - rtop) / 2) lcenter, rcenter = (ltop + lbottom) / 2, (rtop + rbottom) / 2 target = float((lcenter + rcenter) / 2) center = float((grid_boxes[mid, 1] + grid_boxes[mid, 3]) / 2) if abs(lcenter - rcenter) <= height and abs(center - target) > max( 2, 2 * height ): delta = target - center grid_boxes[mid, [1, 3]] += delta word_boxes[mid, [1, 3]] += delta * cell_height def align_word_boxes_to_reading_order( selected: list[int], element_units: list[tuple[int, tuple[int, int]]], lookup: dict[int, int], peaks: np.ndarray, grid_boxes: np.ndarray, word_boxes: np.ndarray, cell_width: float, ) -> None: """Place an isolated reversed word between agreeing same-row neighbors. Require both its peak and box center to violate the neighbors' reading order. The positive inter-word gap is bounded by word width and height; preserve box width while updating grid-cell and capture-pixel coordinates. """ ordered = [lookup[u] for u, _ in element_units if u in lookup] accepted = set(selected) for k in range(1, len(ordered) - 1): left, mid, right = ordered[k - 1 : k + 2] if not {left, mid, right} <= accepted: continue ax, ay = peaks[left] bx, by = peaks[mid] cx, cy = peaks[right] if max(ay, by, cy) - min(ay, by, cy) > 1 or not ax < cx or ax <= bx <= cx: continue height = ( grid_boxes[left, 3] - grid_boxes[left, 1] + grid_boxes[right, 3] - grid_boxes[right, 1] ) / 2 lo, hi = grid_boxes[left, 2], grid_boxes[right, 0] width = grid_boxes[mid, 2] - grid_boxes[mid, 0] center = (grid_boxes[mid, 0] + grid_boxes[mid, 2]) / 2 if 0 < hi - lo <= 2 * width + 2 * height and (center < ax or center > cx): delta = (lo + hi) / 2 - center grid_boxes[mid, [0, 2]] += delta word_boxes[mid, [0, 2]] += delta * cell_width def coherent_paragraph_words( selected: list[int], peaks: np.ndarray, boxes: np.ndarray ) -> list[int]: """Check attention peaks and predicted box centers for isolated internal words. A word regressor can shift a box away from an otherwise coherent peak band. Both passes preserve transcript endpoints and retain at least 90% of words. """ selected = _coherent_vertical_words(selected, peaks[:, 1], boxes) if len(selected) < 12: return selected centers = (boxes[:, 1] + boxes[:, 3]) / 2 return _coherent_vertical_words(selected, centers, boxes) def _coherent_vertical_words( selected: list[int], vertical: np.ndarray, boxes: np.ndarray ) -> list[int]: """Remove up to two internal word positions detached from a dominant text band. Coordinates are grid cells. The gap scales with median word height; at least 90% of selected words must stay connected vertically. Transcript endpoints remain intact because short opening or closing lines may be widely spaced. """ if len(selected) < 12: return selected ordered = sorted(selected, key=lambda j: vertical[j]) height = float(np.median(boxes[selected, 3] - boxes[selected, 1])) gap = max(2, 2 * height) bands: list[list[int]] = [[]] for j in ordered: if bands[-1] and vertical[j] - vertical[bands[-1][-1]] > gap: bands.append([]) bands[-1].append(j) largest = max(bands, key=len) if ( len(largest) == len(selected) or len(largest) < 0.9 * len(selected) or len(selected) - len(largest) > 2 ): return selected removed = set(selected) - set(largest) if min(selected) in removed or max(selected) in removed: return selected return sorted(largest) _SOURCE_FOOTER = re.compile( r"