# 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"\s*]*colspan=[\"']?\d+[\"']?[^>]*>" r"(Source:(?:(?!\s*\s*\s*$", re.I | re.S, ) def separate_table_sources( answer: str, elements: list[dict], units: list[tuple[int, int]], lookup: dict[int, int], peaks: np.ndarray, grid_boxes: np.ndarray, word_boxes: np.ndarray, ) -> list[dict]: """Ground explicit final source rows using existing word predictions. Spans remain offsets into the original transcript and boxes use capture pixels. Table geometry is already refined and stays unchanged. A marker tells serialization to restore the closing tag after removing the row. """ rebuilt: list[dict] = [] for element in elements: match = ( _SOURCE_FOOTER.search(answer, element["start"], element["end"]) if element["type"] == "table" else None ) if match: start, end = match.span(1) selected = [ lookup[u] for u, (s, e) in enumerate(units) if start <= s and e <= end and u in lookup ] selected = coherent_paragraph_words(selected, peaks, grid_boxes) if selected: boxes = word_boxes[selected] bounds = np.r_[boxes[:, :2].min(0), boxes[:, 2:].max(0)] rebuilt.append({**element, "end": match.start(), "close_table": True}) rebuilt.append( { "type": "text", "start": start, "end": end, "box": np.round(bounds, 1).tolist(), } ) continue rebuilt.append(element) return rebuilt def ground_cached( answer: str, capture: dict, models: list[Predictor] | None = None, with_context: bool = False, picture_model: PicturePredictor | None = None, with_extended_context: bool = False, region_models: list[Predictor] | None = None, collect_region_features: bool = False, table_model: TablePredictor | None = None, with_region_context: bool = False, peak_model: PeakPredictor | None = None, *, _rotated_spans: set[tuple[int, int]] | None = None, ) -> dict: """Reconstruct pixel-coordinate boxes from dimensions and cached attention. Models predict center dx/dy and log width/height in attention-grid cells. The caller owns model loading; this function performs no file or image I/O. Without models, return the deterministic rectangle baseline. Region models adjust outer edges in local word-height units. Feature collection returns each region's element index, feature row, grid-cell anchor, and word height for offline training-label construction. """ if (region_models is not None or collect_region_features) and models is None: raise ValueError("Region refinement requires word boundary models") if region_models is not None and len(region_models) != 4: raise ValueError("Expected four region edge predictors") width, height = capture["width"], capture["height"] gh, gw = capture["grid"] cw, ch = width / gw, height / gh blocks = split_column_blocks(answer, capture, split_blocks(answer)) blocks = split_bullet_tables(answer, blocks) blocks = split_navigation_headers(answer, capture, blocks) units, per_block = units_for(answer, blocks) sparse = capture["sparse_maps"] if len(units) != len(sparse["idx"]): raise ValueError("Cached attention units do not match the transcript") if get_rust() is not None: maps, has = ( SparseWordMaps(sparse, (gh, gw)), np.asarray(sparse["has"], dtype=bool), ) else: maps, has = dense_maps(sparse, (gh, gw)) base = rectangle_boxes( (width, height), answer, blocks, units, per_block, maps, (gh, gw), has, BASE_CONFIG, ) if picture_model is not None: refine_pictures(capture, blocks, per_block, base, picture_model, answer=answer) if table_model is not None: refine_tables(capture, answer, blocks, per_block, units, base, table_model) if models is None: return base if len(models) != 4: raise ValueError( "Expected center-x, center-y, log-width, and log-height predictors" ) features, valid, peaks = attention_features(answer, units, sparse, (gh, gw)) if not len(valid): if collect_region_features: base["region_features"] = [] return base if peak_model is not None: context = contextual_features(answer, units, per_block, features, valid, peaks) anchors = select_word_peaks( context, valid, peaks, sparse, (gh, gw), blocks, per_block, peak_model ) if anchors: # Local attention features depend only on the changed word's map. # Recompute those rows; contextual features below still see every peak. changed = [u for u in valid if u in anchors] changed_sparse = { key: [values[u] for u in changed] for key, values in sparse.items() } changed_features, _, changed_peaks = attention_features( answer, [units[u] for u in changed], changed_sparse, (gh, gw), {i: anchors[u] for i, u in enumerate(changed)}, ) lookup = {u: row for row, u in enumerate(valid)} rows = [lookup[u] for u in changed] features[rows] = changed_features peaks[rows] = changed_peaks if with_context or with_extended_context: if peak_model is not None and not anchors: features = context else: features = contextual_features( answer, units, per_block, features, valid, peaks ) if with_extended_context: features = extended_features( answer, units, blocks, per_block, features, valid, peaks, sparse, (gh, gw) ) predicted = np.column_stack([predict(model, features) for model in models]) centers, sizes = peaks + predicted[:, :2], np.exp(predicted[:, 2:]) grid_boxes = np.column_stack([centers - sizes / 2, centers + sizes / 2]) word_boxes = grid_boxes * [ cw, ch, cw, ch, ] lookup = {u: j for j, u in enumerate(valid)} valid_starts = [units[u][0] for u in valid] # Descriptions inside image references are not printed text. Keep their # cached indices intact, but exclude them from text-region boundaries. image_units = set() for match in _INLINE_IMAGE_REFERENCE.finditer(answer): first = bisect_left(valid_starts, match.start()) last = bisect_left(valid_starts, match.end()) image_units.update(u for u in valid[first:last] if units[u][1] <= match.end()) region_records = [] cell_scale = np.array([cw, ch, cw, ch]) refine_table_word_boxes( answer, base["elements"], units, valid, grid_boxes, peaks, cell_scale ) # Snapshot pixel-coordinate paragraph edges before any word-based updates. # Three agreeing right edges provide a candidate width for the same left column. column_evidence = [ list(e["box"]) for e in base["elements"] if e["box"] is not None and e["type"] in {"text", "list"} and e["end"] - e["start"] >= 80 and e["box"][3] - e["box"][1] >= 2 * ch ] for element_index, element in enumerate(base["elements"]): box = element["box"] if box is None or element["type"] not in _TEXT_TYPES: continue # Units are in transcript order; only this element's span can contribute. first = bisect_left(valid_starts, element["start"]) last = bisect_right(valid_starts, element["end"]) element_units = [ (u, units[u]) for u in valid[first:last] if u not in image_units ] column_right = box[2] if element["type"] in {"text", "list"}: rights = np.array( [ b[2] for b in column_evidence if abs(b[0] - box[0]) <= 2 * cw and b[2] > box[2] + cw ] ) if len(rights) >= 3: groups = [rights[abs(rights - r) <= cw] for r in rights] support = max(groups, key=len) if len(support) >= 3: column_right = float(np.median(support)) # Require two consecutive valid words in the added band to advance along # one attention row. This guards against isolated peaks in adjacent blocks. # Peak distances are grid cells; the original vertical band stays fixed. if column_right > box[2]: outer = [ lookup[u] for u, (start, end) in element_units if u in lookup and element["start"] <= start and end <= element["end"] and box[2] + cw < peaks[lookup[u], 0] * cw <= column_right + cw and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch ] coherent = any( b == a + 1 and abs(peaks[a, 1] - peaks[b, 1]) <= 1 and 0 <= peaks[b, 0] - peaks[a, 0] <= 3 for a, b in zip(outer, outer[1:]) ) if not coherent: column_right = box[2] selected = [ lookup[u] for u, (start, end) in element_units if u in lookup and element["start"] <= start and end <= element["end"] and ( element["type"] in {"heading", "header", "footer"} or (element["start"], element["end"]) in (_rotated_spans or ()) or box[0] - cw <= peaks[lookup[u], 0] * cw <= column_right + cw ) and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch ] # Extend paragraph and list lines through nearby transcript neighbors. Cell # distances keep the rule independent of render resolution; the original # vertical guard keeps recovery within the existing vertical band. if selected and element["type"] in {"text", "list"}: candidates = { lookup[u] for u, (start, end) in element_units if u in lookup and element["start"] <= start and end <= element["end"] and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch } accepted = set(selected) changed = True while changed: changed = False for j in sorted(candidates - accepted): for neighbor in (j - 1, j + 1): if ( neighbor not in accepted or abs(peaks[j, 1] - peaks[neighbor, 1]) > 1 ): continue gap = max( 0, grid_boxes[j, 0] - grid_boxes[neighbor, 2], grid_boxes[neighbor, 0] - grid_boxes[j, 2], ) if gap <= 1: accepted.add(j) changed = True break selected = recover_line_tails(accepted, candidates, peaks) selected = recover_short_line_tails(selected, candidates, peaks, grid_boxes) if selected and element["type"] in {"text", "list"} and _rotated_spans is None: selected = coherent_paragraph_words(selected, peaks, grid_boxes) # Short key/value blocks can have distant right-aligned values. # Require overlapping word extents on distinct rows; one isolated # numeric peak cannot expand the paragraph's horizontal boundary. if 4 <= len(element_units) <= 16: numeric = [ lookup[u] for u, (start, end) in element_units if u in lookup and lookup[u] not in selected and _NUMERIC_WORD.fullmatch(answer[start:end]) and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch and peaks[lookup[u], 0] * cw > box[2] + cw ] supported = [ j for j in numeric if any( k != j and max(grid_boxes[j, 0], grid_boxes[k, 0]) <= min(grid_boxes[j, 2], grid_boxes[k, 2]) and abs(peaks[j, 1] - peaks[k, 1]) >= 2 for k in numeric ) ] selected = sorted(set(selected) | set(supported)) if element["type"] in {"text", "list"}: selected = recover_paragraph_opening( selected, element_units, lookup, peaks, grid_boxes ) if selected and (element["start"], element["end"]) in (_rotated_spans or ()): selected = coherent_rotated_words(selected, peaks) if selected and element["type"] in {"text", "list", "heading"}: align_word_boxes_to_neighbor_row( selected, element_units, lookup, peaks, grid_boxes, word_boxes, ch ) align_word_boxes_to_reading_order( selected, element_units, lookup, peaks, grid_boxes, word_boxes, cw ) if selected: boxes = word_boxes[selected] bounds = np.r_[boxes[:, :2].min(0), boxes[:, 2:].max(0)] bounds = np.clip(bounds, 0, [width, height, width, height]) if bounds[2] > bounds[0] and bounds[3] > bounds[1]: element["box"] = np.round(bounds, 1).tolist() if region_models is not None or collect_region_features: anchor = np.asarray(element["box"]) / cell_scale row, word_height = region_features( element["type"], answer[element["start"] : element["end"]], anchor, np.asarray(box) / cell_scale, grid_boxes[selected], features[selected, 0], (gh, gw), ) region_records.append( { "element_index": element_index, "text": element_text( answer, element["start"], element["end"] ), "features": row, "anchor": anchor.tolist(), "height": word_height, } ) if with_region_context and region_records: for record, row in zip( region_records, contextual_region_features(region_records) ): record["features"] = row.tolist() if region_models is not None and region_records: rows = np.asarray([record["features"] for record in region_records]) glyph_rows = None if any(isinstance(model, HeadingGlyphRegionBlend) for model in region_models): glyph_rows = np.column_stack( [ rows, heading_glyph_features( [record["text"] for record in region_records] ), ] ) residuals = np.column_stack( [ predict( model, glyph_rows if isinstance(model, HeadingGlyphRegionBlend) else rows, ) for model in region_models ] ) for record, residual in zip(region_records, residuals): # Limit extrapolation to two local word heights on each edge. bounds = np.clip( np.asarray(record["anchor"]) + residual.clip(-2, 2) * record["height"], 0, [gw, gh, gw, gh], ) if bounds[2] > bounds[0] and bounds[3] > bounds[1]: base["elements"][record["element_index"]]["box"] = np.round( bounds * cell_scale, 1 ).tolist() base["elements"] = separate_table_sources( answer, base["elements"], units, lookup, peaks, grid_boxes, word_boxes ) if collect_region_features: base["region_features"] = region_records # Region feature records describe the original pre-refinement anchors. # Orientation recovery only replaces final boxes; the private span set # marks the normalized pass and prevents recursively rotating it again. if _rotated_spans is None: spans = vertical_text_spans(answer, capture) if spans: rotated = ground_cached( answer, rotate_attention_clockwise(capture), models, with_context=with_context, picture_model=picture_model, with_extended_context=with_extended_context, region_models=region_models, table_model=table_model, with_region_context=with_region_context, peak_model=peak_model, _rotated_spans=spans, ) lookup_boxes = { (element["start"], element["end"]): element["box"] for element in rotated["elements"] } for element in base["elements"]: key = (element["start"], element["end"]) rotated_box = lookup_boxes.get(key) if key in spans and rotated_box is not None: x0, y0, x1, y1 = rotated_box element["box"] = [y0, height - x1, y1, height - x0] if _rotated_spans is None: recover_repeated_paragraphs(answer, capture, base["elements"], units) return base