# 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. """Conservative region-edge features from predicted word boxes.""" from dataclasses import dataclass import numpy as np from .predict import Predictor, predict REGION_FEATURE_VERSION = "region-edges-v1" REGION_FEATURE_COUNT = 47 REGION_CONTEXT_VERSION = "region-edges-context-v1" REGION_CONTEXT_COUNT = 86 _REGION_TYPES = ("text", "list", "heading", "header", "footer") @dataclass class HeadingRegionBlend: """Blend shared and heading-specific edge corrections in word-height units.""" base: Predictor specialist: Predictor def predict(self, features: np.ndarray) -> np.ndarray: result = predict(self.base, features).copy() headings = features[:, _REGION_TYPES.index("heading")] == 1 if headings.any(): result[headings] = 0.5 * result[headings] + 0.5 * predict( self.specialist, features[headings] ) return result @dataclass class HeaderRegionOverride: """Use refreshed edge models for headers and retained models for other types.""" base: Predictor refreshed: Predictor def predict(self, features: np.ndarray) -> np.ndarray: headers = features[:, _REGION_TYPES.index("header")] == 1 result = np.empty(len(features)) if headers.any(): result[headers] = predict(self.refreshed, features[headers]) if (~headers).any(): result[~headers] = predict(self.base, features[~headers]) return result @dataclass class HeadingGlyphRegionBlend: """Refine a heading edge with letter-shape features; preserve other types.""" base: Predictor shared: Predictor specialist: Predictor def predict(self, features: np.ndarray) -> np.ndarray: geometry = features[:, :REGION_CONTEXT_COUNT] result = np.empty(len(features)) headings = geometry[:, _REGION_TYPES.index("heading")] == 1 if (~headings).any(): result[~headings] = predict(self.base, geometry[~headings]) if headings.any(): result[headings] = 0.5 * ( predict(self.shared, geometry[headings]) + predict(self.specialist, features[headings]) ) return result def heading_glyph_features(texts: list[str]) -> np.ndarray: """Return ascender/capital and Latin descender fractions among letters. These are text-shape hints, not font measurements. Geometry remains the primary signal, including for scripts without Latin ascender conventions. """ result = np.zeros((len(texts), 2)) for i, text in enumerate(texts): letters = [char for char in text if char.isalpha()] count = max(1, len(letters)) result[i, 0] = ( sum(char in "bdfhklt" or char.isupper() for char in letters) / count ) result[i, 1] = sum(char in "gjpqy" for char in letters) / count return result def contextual_region_features(records: list[dict]) -> np.ndarray: """Append neighboring region geometry to uncorrected region features. Records are in transcript order, with grid-cell anchors and median word heights. All neighbors use their original anchors, so applying corrections later cannot make features depend on the order of model evaluation. """ anchors = [np.asarray(record["anchor"]) for record in records] kinds = [np.argmax(record["features"][:5]) for record in records] rows = [] for i, record in enumerate(records): box = anchors[i] height = record["height"] extra = [] for offset in (-2, -1, 1, 2): j = i + offset if not 0 <= j < len(records): extra.extend([0.0] * 7) continue neighbor = records[j] extra.extend( [ 1.0, *(((anchors[j] - box) / height).clip(-30, 30)).tolist(), neighbor["height"] / height, float(kinds[j] == kinds[i]), ] ) nearby = [ records[j] for j in range(max(0, i - 8), min(len(records), i + 9)) if j != i ] # Edge consensus is local in reading order and within three word heights, # reducing interference from a separate column or an indented list. for edge in (0, 2): aligned = [ (neighbor["anchor"][edge] - box[edge]) / height for neighbor in nearby if abs(neighbor["anchor"][edge] - box[edge]) / height < 3 ] extra.extend( [len(aligned), *np.quantile(aligned, [0.1, 0.5, 0.9]).tolist()] if aligned else [0.0] * 4 ) heights = [neighbor["height"] / height for neighbor in nearby] extra.extend( np.quantile(heights, [0.1, 0.5, 0.9]).tolist() if heights else [0.0] * 3 ) rows.append([*record["features"], *extra]) return np.asarray(rows).reshape(-1, REGION_CONTEXT_COUNT) def region_features( kind: str, text: str, box: np.ndarray, gate: np.ndarray, words: np.ndarray, lengths: np.ndarray, grid: tuple[int, int], ) -> tuple[list[float], float]: """Describe a region's edges in units of its median predicted word height. All input boxes use grid-cell edges. `gate` is the pre-regression attention box, and `words` contains only the words retained by that spatial guard. Returned height converts model residuals back into grid-cell coordinates. """ gh, gw = grid heights = words[:, 3] - words[:, 1] height = max(0.1, float(np.median(heights))) widths = words[:, 2] - words[:, 0] relative = (np.quantile(words, [0, 0.1, 0.5, 0.9, 1], axis=0) - box) / height area = max(0.1, (box[2] - box[0]) * (box[3] - box[1])) features = [float(kind == value) for value in _REGION_TYPES] features.extend( [ np.log1p(len(words)), np.log1p(len(text)), height, (box[2] - box[0]) / height, (box[3] - box[1]) / height, float((widths * heights).sum() / area), float(np.median(widths / np.maximum(1, lengths)) / height), gh, gw, ] ) features.extend((box / [gw, gh, gw, gh]).tolist()) features.extend(((gate - box) / height).tolist()) features.extend(relative.ravel().tolist()) features.extend((np.quantile(heights, [0.1, 0.5, 0.9]) / height).tolist()) features.extend( [ float(np.mean([c.isupper() for c in text])) if text else 0.0, float(np.mean([c.isdigit() for c in text])) if text else 0.0, ] ) return np.asarray(features, dtype=float).tolist(), height