# 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. """Rectangular block estimates from attention density and transcript geometry.""" from dataclasses import dataclass import statistics import numpy as np from .native import get_native from .io import SparseWordMaps from scipy import ndimage from scipy.signal import find_peaks from .blocks import Block, resolve_page_numbers from .boxes import envelope from .words import norm from .rust import get_rust @dataclass(frozen=True) class RectangleConfig: word_threshold: float = 0.3 text_quantile: float = 0.01 image_quantile: float = 0.05 text_y_scale: float = 1.0 x_padding: float = 0.0 y_offset: float = 0.0 image_padding: float = 0.0 image_whitespace: float = 0.0 fit_lines: bool = False centroid: bool = True anchor_fraction: float = 0.5 font_height: float = 1.7 connected_words: bool = False y_inset: float = 0.0 keep_prose: bool = False keep_tables: bool = False line_density: bool = False line_fill: float = 0.7 density_floor: float = 0.1 compact_image: bool = False adaptive_anchor: bool = False guard_expansion: float = 0.0 heading_x_scale: float = 1.0 heading_y_inset: float = 0.0 heading_y_shift: float = 0.0 furniture_x_scale: float = 1.0 furniture_y_inset: float = 0.0 furniture_y_shift: float = 0.0 text_x_scale: float = 1.0 text_y_inset: float = 0.0 component_centroid: bool = False component_center: bool = False centroid_radius: float = 1.0 glyph_widths: bool = False fit_blend_x: float = 1.0 fit_blend_y: float = 1.0 image_power: float = 1.0 image_component_share: float = 0.0 image_hot_threshold: float = 0.3 image_text_suppression: float = 0.0 def mass_box( density: np.ndarray, quantile: float, compact: bool = False ) -> list[float]: """Axis-wise attention quantiles in cell-edge coordinates, including edge cells.""" bounds = [] for marginal in (density.sum(axis=0), density.sum(axis=1)): cdf = np.cumsum(marginal) total = float(cdf[-1]) lo = int(np.searchsorted(cdf, quantile * total, side="right")) hi = int(np.searchsorted(cdf, (1 - quantile) * total, side="left")) + 1 if compact: prefix = np.concatenate(([0.0], cdf)) target = (1 - 2 * quantile) * total candidates = [ ( start, int(np.searchsorted(prefix, prefix[start] + target, side="left")), ) for start in range(len(marginal)) if prefix[start] + target <= total ] lo, hi = min(candidates, key=lambda pair: pair[1] - pair[0]) bounds.append((lo, min(len(marginal), hi))) return [ float(bounds[0][0]), float(bounds[1][0]), float(bounds[0][1]), float(bounds[1][1]), ] def mass_boxes(density: np.ndarray, quantiles: list[float]) -> list[list[float]]: """Share reductions across attention quantiles when the native backend is enabled.""" native = get_native() if native is not None: return native.mass_boxes(density, quantiles) return [mass_box(density, q) for q in quantiles] def fitted_lines( points: list[tuple[float, float, float]], cw: float, ch: float, config: RectangleConfig, ) -> list[float] | None: """Fit word positions to cumulative character counts within transcript-order lines. A peak may land partway through a word. The anchor fraction models that offset; robust slopes and intercepts recover the line's first and last edge. Coordinates and inferred character advances are in rendered-page pixels. """ groups: list[list[tuple[float, float, float]]] = [] for point in points: if ( not groups or abs(point[1] - statistics.median(p[1] for p in groups[-1])) > 0.8 * ch or point[0] < groups[-1][-1][0] - 1.5 * cw ): groups.append([]) groups[-1].append(point) slopes = [] for group in groups: for a, b in zip(group, group[1:]): chars = ( (1 - config.anchor_fraction) * a[2] + 1 + config.anchor_fraction * b[2] ) advance = (b[0] - a[0]) / chars if 0.1 * cw <= advance <= 1.5 * cw: slopes.append(advance) if not slopes: return None default_advance = statistics.median(slopes) lines = [] for group in groups: local = [] for a, b in zip(group, group[1:]): chars = ( (1 - config.anchor_fraction) * a[2] + 1 + config.anchor_fraction * b[2] ) advance = (b[0] - a[0]) / chars if 0.1 * cw <= advance <= 1.5 * cw: local.append(advance) advance = statistics.median(local) if len(local) >= 2 else default_advance offsets, length = [], 0 for x, _, chars in group: offsets.append(x - advance * (length + config.anchor_fraction * chars)) length += chars + 1 left = statistics.median(offsets) if ( config.adaptive_anchor and len(group) >= 5 and len({p[2] for p in group}) >= 3 ): chars = np.array([p[2] for p in group], dtype=float) preceding = np.concatenate(([0.0], np.cumsum(chars[:-1] + 1))) xs = np.array([p[0] for p in group]) design = np.column_stack((np.ones(len(group)), preceding, chars)) weights = np.ones(len(group)) for _ in range(3): fit = np.linalg.lstsq( design * weights[:, None], xs * weights, rcond=None )[0] residual = np.abs(xs - design @ fit) scale = max(0.35 * cw, 1.5 * float(np.median(residual))) weights = np.sqrt(np.minimum(1.0, scale / np.maximum(residual, 1e-9))) if 0.1 * cw <= fit[1] <= 1.5 * cw and 0 <= fit[2] / fit[1] <= 1: # Separately fitting cumulative characters and word length lets # the observed peaks choose their own within-word anchor. left, advance = float(fit[0]), float(fit[1]) cy = statistics.median(p[1] for p in group) + config.y_offset * ch h = max(0.5 * ch, min(3 * ch, config.font_height * advance)) lines.append([left, cy - h / 2, left + advance * (length - 1), cy + h / 2]) return envelope(lines) def rectangle_boxes( size: tuple[int, int], answer: str, blocks: list[Block], units: list[tuple[int, int]], per_block: list[list[int]], maps: np.ndarray | SparseWordMaps, grid: tuple[int, int], has: np.ndarray, config: RectangleConfig, ) -> dict: """Fit one rectangle per emitted block using only attention and text. Normalize each word's retained attention before pooling so a few confident words cannot dominate the block. Pictures retain their own spatial density. No source pixels, PDF text layer, detector, or ground-truth boxes are read. """ width, height = size gh, gw = grid cw, ch = width / gw, height / gh # Reuse one peak scan for occupancy, word support, and the coarse guard. if isinstance(maps, SparseWordMaps): peaks, maxima = maps.peaks, maps.maxima else: peaks = ( maps.reshape(len(maps), -1).argmax(axis=1) if len(maps) else np.array([], dtype=np.int64) ) maxima = maps.reshape(len(maps), gh * gw)[np.arange(len(maps)), peaks] text_occupancy = np.zeros(grid, dtype=float) if config.image_text_suppression: for block, indices in zip(blocks, per_block): if block.type in ("image", "table"): continue for u in indices: if has[u] and maxima[u] > 0: text_occupancy.flat[int(peaks[u])] = 1 text_occupancy = ndimage.maximum_filter(text_occupancy, size=3) # The coarse guard uses the same 0.3-threshold connected word support. # Cache cell bounds locally so that pass need not relabel each word map. support_boxes: dict[int, tuple[int, int, int, int]] = {} native = get_native() reuse_support = config.connected_words and config.word_threshold == 0.3 rust = get_rust() fused_density = ( rust is not None and reuse_support and ( isinstance(maps, SparseWordMaps) or (maps.dtype == np.float32 and maps.flags.c_contiguous) ) and not config.component_centroid and not config.component_center ) boxes: list[list[float] | None] = [] for block, indices in zip(blocks, per_block): batch = None if ( fused_density and isinstance(maps, SparseWordMaps) and block.type != "image" and config.centroid_radius == 1 ): indices = [u for u in indices if has[u] and maxima[u] > 0] density, batch_bounds, batch_centers = rust.add_components( [maps.indices[u] for u in indices], [maps.values[u] for u in indices], peaks[indices], grid, ) batch = { u: (tuple(int(v) for v in b), c) for u, b, c in zip(indices, batch_bounds, batch_centers) } else: density = np.zeros(grid, dtype=np.float64) points = [] for u in indices: if not has[u] or maxima[u] <= 0: continue m = None if batch is not None else maps[u] if block.type == "image": density += m / m.sum() continue if fused_density: if batch is not None: y, x = divmod(int(peaks[u]), gw) bounds, center = batch[u] else: y, x, bounds, center = rust.add_component(m, density, int(peaks[u])) support_boxes[u] = bounds else: y, x = divmod(int(peaks[u]), gw) mask = m >= config.word_threshold * maxima[u] if config.connected_words: if native is not None and mask[y, x]: mask, bounds = native.peak_component_bounds(mask, y, x) if reuse_support: support_boxes[u] = bounds else: labels, _ = ndimage.label(mask, structure=np.ones((3, 3))) mask = labels == labels[y, x] if reuse_support and u not in support_boxes: yy, xx = np.nonzero(mask) support_boxes[u] = ( int(xx.min()), int(yy.min()), int(xx.max()) + 1, int(yy.max()) + 1, ) selected = np.where(mask, m, 0) total = selected.sum() if u in support_boxes: # Preserve the full-map reduction order, but normalize and add # only the nonzero component's bounding rectangle. bx0, by0, bx1, by1 = support_boxes[u] density[by0:by1, bx0:bx1] += selected[by0:by1, bx0:bx1] / total else: density += selected / total px, py = x + 0.5, y + 0.5 if config.centroid and fused_density and config.centroid_radius == 1: px, py = center elif config.centroid: radius = int(config.centroid_radius) y0, y1, x0, x1 = ( max(0, y - radius), min(gh, y + radius + 1), max(0, x - radius), min(gw, x + radius + 1), ) local = m[y0:y1, x0:x1] px = float(np.dot(local.sum(0), np.arange(x0, x1) + 0.5) / local.sum()) py = float(np.dot(local.sum(1), np.arange(y0, y1) + 0.5) / local.sum()) if config.component_centroid: px = float( np.dot(selected.sum(0), np.arange(gw) + 0.5) / selected.sum() ) py = float( np.dot(selected.sum(1), np.arange(gh) + 0.5) / selected.sum() ) if config.component_center: yy, xx = np.nonzero(selected) px, py = ( (float(xx.min() + xx.max()) + 1) / 2, (float(yy.min() + yy.max()) + 1) / 2, ) start, end = units[u] word = norm(answer[start:end]) chars = ( sum(0.6 if c in "iljtf1" else 1.4 if c in "mw" else 1.0 for c in word) if config.glyph_widths else len(word) ) points.append((px * cw, py * ch, max(1.0, float(chars)))) if not density.any(): boxes.append(None) continue q = config.image_quantile if block.type == "image" else config.text_quantile if block.type == "image": peak = np.unravel_index(int(density.argmax()), grid) labels, _ = ndimage.label( density >= config.image_hot_threshold * density.max(), structure=np.ones((3, 3)), ) core = labels == labels[peak] if config.image_text_suppression: # Preserve the image's strongest connected region; downweight # distant attention that lands on separately emitted text. density = density / ( 1 + config.image_text_suppression * text_occupancy * ~core ) if config.image_power != 1: density = (density / density.max()) ** config.image_power share = float(density[core].sum() / density.sum()) if config.image_component_share and share >= config.image_component_share: density = np.where(core, density, 0) q = 0.0 cell_box = mass_box( density, q, compact=config.compact_image and block.type == "image" ) box = [cell_box[0] * cw, cell_box[1] * ch, cell_box[2] * cw, cell_box[3] * ch] if block.type != "image": if config.fit_lines and block.type != "table": box = fitted_lines(points, cw, ch, config) or box else: cy = (box[1] + box[3]) / 2 + config.y_offset * ch half_height = (box[3] - box[1]) * config.text_y_scale / 2 box[1], box[3] = cy - half_height, cy + half_height if config.line_density and block.type != "table": profile = density.sum(axis=1) peaks, _ = find_peaks( np.pad(profile, (1, 1)), height=config.density_floor * profile.max() ) rows = peaks - 1 rows = rows[(rows >= cell_box[1]) & (rows < cell_box[3])] if len(rows): pitch = float(np.median(np.diff(rows))) if len(rows) > 1 else 2.0 glyph_height = max(0.5, min(3.0, config.line_fill * pitch)) * ch box[1] = (rows[0] + 0.5 + config.y_offset) * ch - glyph_height / 2 box[3] = (rows[-1] + 0.5 + config.y_offset) * ch + glyph_height / 2 box[0] -= config.x_padding * cw box[2] += config.x_padding * cw inset = min(config.y_inset * ch, 0.45 * (box[3] - box[1])) box[1] += inset box[3] -= inset else: box = [ box[0] - config.image_padding * cw, box[1] - config.image_padding * ch, box[2] + config.image_padding * cw, box[3] + config.image_padding * ch, ] boxes.append(box) if config.image_whitespace: # Only text entirely outside the seed rectangle can bound its expansion; # chart labels inside the image must not clip the picture. text_boxes = [ box for b, box in zip(blocks, boxes) if box is not None and b.type in ("text", "heading", "list") ] for block, box in zip(blocks, boxes): if block.type != "image" or box is None: continue x0, y0, x1, y1 = box left, top, right, bottom = 0.0, 0.0, float(width), float(height) for text in text_boxes: if min(x1, text[2]) > max(x0, text[0]): if text[3] <= y0: top = max(top, text[3]) elif text[1] >= y1: bottom = min(bottom, text[1]) if min(y1, text[3]) > max(y0, text[1]): if text[2] <= x0: left = max(left, text[2]) elif text[0] >= x1: right = min(right, text[0]) f = config.image_whitespace box[:] = [ x0 + f * (left - x0), y0 + f * (top - y0), x1 + f * (right - x1), y1 + f * (bottom - y1), ] for i, box in enumerate(boxes): if box is None: continue box[:] = [ float(np.clip(v, 0, width if axis % 2 == 0 else height)) for axis, v in enumerate(box) ] if box[2] <= box[0] or box[3] <= box[1]: boxes[i] = None pieces = [Block(b.type, b.start, b.end) for b in blocks] resolve_page_numbers(pieces, boxes, height) 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) ] if config.keep_prose or config.keep_tables or config.guard_expansion: from .coarse import attention_boxes prose = ( {"text", "list", "table", "code", "formula"} if config.keep_prose else ({"table"} if config.keep_tables else set()) ) guarded = ( {"text", "list", "heading", "header", "footer", "code", "formula"} if config.guard_expansion else set() ) selected = [ (b, indices) for b, indices in zip(blocks, per_block) if b.type in prose | guarded ] coarse = attention_boxes( size, [b for b, _ in selected], units, [indices for _, indices in selected], maps, grid, has, support=True, answer=answer, support_boxes=support_boxes, peak_indices=peaks, ) kept = [] for element in elements: if element["type"] in prose: continue alternatives = [ e for e in coarse["elements"] if e["box"] is not None and e["type"] == element["type"] and e["start"] >= element["start"] and e["end"] <= element["end"] ] if element["type"] in guarded and alternatives: support_box = envelope([e["box"] for e in alternatives]) box = element["box"] replace = box is None or len(alternatives) > 1 if box is not None: sw, sh = ( support_box[2] - support_box[0], support_box[3] - support_box[1], ) overlap = max( 0.0, min(box[2], support_box[2]) - max(box[0], support_box[0]) ) * max( 0.0, min(box[3], support_box[3]) - max(box[1], support_box[1]) ) replace |= ( box[2] - box[0] > config.guard_expansion * sw or box[3] - box[1] > config.guard_expansion * sh or overlap < 0.5 * sw * sh ) # Preserve separately supported columns and reject extrapolation # far beyond the words that the attention-only baseline retained. if replace: kept.extend(alternatives) continue element["box"] = [ round(f * v + (1 - f) * support_box[axis], 1) for axis, v in enumerate(box) for f in [ config.fit_blend_x if axis % 2 == 0 else config.fit_blend_y ] ] kept.append(element) elements = kept + [e for e in coarse["elements"] if e["type"] in prose] elements.sort(key=lambda e: e["start"]) for element in elements: box = element["box"] if box is None: continue if element["type"] == "heading": x_scale, inset, shift = ( config.heading_x_scale, config.heading_y_inset, config.heading_y_shift, ) elif element["type"] in ("header", "footer"): x_scale, inset, shift = ( config.furniture_x_scale, config.furniture_y_inset, config.furniture_y_shift, ) elif element["type"] in ("text", "list"): x_scale, inset, shift = config.text_x_scale, config.text_y_inset, 0.0 else: continue # Correct outer-edge uncertainty in cell units. Fixed edge trimming # preserves the interior line spacing of multi-line paragraphs. cx = (box[0] + box[2]) / 2 half_width = (box[2] - box[0]) * x_scale / 2 trim = min(inset * ch, 0.4 * (box[3] - box[1])) adjusted = [ cx - half_width, box[1] + trim + shift * ch, cx + half_width, box[3] - trim + shift * ch, ] adjusted = [ round(float(np.clip(v, 0, width if axis % 2 == 0 else height)), 1) for axis, v in enumerate(adjusted) ] if adjusted[2] > adjusted[0] and adjusted[3] > adjusted[1]: element["box"] = adjusted return {"width": width, "height": height, "grid": list(grid), "elements": elements}