# 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. """Recover a second text instance from translated, sequence-wide attention.""" from bisect import bisect_left, bisect_right from collections import Counter import numpy as np from .words import norm _MIN_RELATIVE_PEAK = 0.15 _MIN_SEQUENCE_SUPPORT = 0.8 def recover_repeated_paragraphs( answer: str, capture: dict, elements: list[dict], units: list[tuple[int, int]], ) -> None: """Append a translated copy only when distinctive and common words support it. Elements use pixel-edge boxes; sparse attention uses flattened grid cells. Units retain the original transcript order and cache indices. Distinctive words propose a translation, then the full sequence must corroborate it. Original elements and their boxes remain intact. """ keys = [norm(answer[start:end]) for start, end in units] counts = Counter(keys) gh, gw = capture["grid"] scale = np.array([capture["width"] / gw, capture["height"] / gh] * 2) sparse = capture["sparse_maps"] starts = [start for start, _ in units] ends = [end for _, end in units] added = [] for element in elements: if element["type"] not in {"text", "list"} or element.get("box") is None: continue indices = range( bisect_left(starts, element["start"]), bisect_right(ends, element["end"]), ) if len(indices) < 40: continue distinctive = [ unit for unit in indices if len(keys[unit]) >= 5 and counts[keys[unit]] == 1 and sparse["val"][unit] ] if len(distinctive) < 8: continue box = np.asarray(element["box"]) / scale deltas = [] for position, unit in enumerate(distinctive): # Even perfect support from the remaining words cannot rescue this # proposal once its required supporting count becomes unreachable. if len(deltas) + len(distinctive) - position < max( 8, _MIN_SEQUENCE_SUPPORT * len(distinctive) ): break mass = np.asarray(sparse["val"][unit]) peak = int(mass.argmax()) maximum = mass[peak] if maximum <= 0: continue primary = sparse["idx"][unit][peak] px, py = primary % gw + 0.5, primary // gw + 0.5 if not (box[0] - 2 <= px <= box[2] + 2 and box[1] - 2 <= py <= box[3] + 2): continue selected = mass >= _MIN_RELATIVE_PEAK * maximum cells = np.asarray(sparse["idx"][unit])[selected] weights = mass[selected] xs, ys = cells % gw + 0.5, cells // gw + 0.5 outside = ( (xs < box[0] - 2) | (xs > box[2] + 2) | (ys < box[1] - 2) | (ys > box[3] + 2) ) if not outside.any(): continue candidates = np.flatnonzero(outside) chosen = candidates[weights[candidates].argmax()] deltas.append([xs[chosen] - px, ys[chosen] - py]) if len(deltas) < 8 or len(deltas) < _MIN_SEQUENCE_SUPPORT * len(distinctive): continue delta = np.median(deltas, axis=0) agreement = np.max(np.abs(np.asarray(deltas) - delta), axis=1) <= 2 if ( agreement.sum() < 8 or agreement.mean() < 0.85 or np.max(np.abs(delta) / [gw, gh]) < 0.15 ): continue shifted = box + np.tile(delta, 2) if np.any(shifted[:2] < 0) or np.any(shifted[2:] > [gw, gh]): continue if ( np.maximum( 0, np.minimum(box[2:], shifted[2:]) - np.maximum(box[:2], shifted[:2]) ).prod() > 0 ): continue # A few distinctive words can share spurious secondary attention. # Require the translated locations to explain the whole word sequence. supported = 0 for unit in indices: if not sparse["val"][unit]: continue mass = np.asarray(sparse["val"][unit]) if mass.max() <= 0: continue cells = np.asarray(sparse["idx"][unit]) points = np.column_stack([cells % gw + 0.5, cells // gw + 0.5]) target = points[mass.argmax()] + delta nearby = np.max(abs(points - target), axis=1) <= 2 supported += bool( nearby.any() and mass[nearby].max() >= _MIN_RELATIVE_PEAK * mass.max() ) if supported >= _MIN_SEQUENCE_SUPPORT * len(indices): added.append({**element, "box": (shifted * scale).tolist()}) elements.extend(added)