# 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. """Separate prose that continues into another column without a Markdown break.""" import numpy as np from .blocks import Block from .io import units_for _COLUMN_WINDOW = 12 _COLUMN_TAIL_MIN = 6 _COLUMN_JUMP = 0.15 def split_column_blocks(answer: str, capture: dict, blocks: list[Block]) -> list[Block]: """Split at sustained rightward/upward transitions in cached word peaks. Offsets stay in the original transcript and attention-grid coordinates. Twelve preceding words must support a disjoint horizontal band. A tail can have six words if they form coherent rows beyond that band. The upward jump must exceed three typical line steps, allowing short columns while excluding ordinary left-to-right line wraps. Only prose is eligible, preserving image/table attention-unit contracts. """ units, per_block = units_for(answer, blocks) sparse = capture["sparse_maps"] gh, gw = capture["grid"] result = [] for block, indices in zip(blocks, per_block): if block.type != "text" or len(indices) < 2 * _COLUMN_WINDOW: result.append(block) continue valid, points = [], [] for unit in indices: if sparse["val"][unit]: cell = sparse["idx"][unit][int(np.argmax(sparse["val"][unit]))] valid.append(unit) points.append([cell % gw + 0.5, cell // gw + 0.5]) positions = np.asarray(points) # Estimate line spacing in attention-grid cells. Small positive steps # capture wraps; larger jumps can belong to a different region. deltas = np.diff(positions[:, 1]) if len(positions) else np.array([]) line_steps = deltas[(deltas > 0) & (deltas <= max(2, gh * 0.03))] vertical_jump = ( max(2.0, 3 * float(np.median(line_steps))) if len(line_steps) else _COLUMN_JUMP * gh ) cuts = [] last = -_COLUMN_WINDOW for index in range(_COLUMN_WINDOW, len(valid) - _COLUMN_TAIL_MIN + 1): if ( index - last < _COLUMN_WINDOW or positions[index, 1] - positions[index - 1, 1] >= -vertical_jump ): continue before = positions[index - _COLUMN_WINDOW : index] after = positions[index : index + _COLUMN_WINDOW] if len(after) < _COLUMN_WINDOW: # Short tails need multiple coherent rows and every word to # clear the preceding column's right edge (grid coordinates). dy = np.diff(after[:, 1]) if ( np.ptp(after[:, 1]) < 1 or np.any(dy < -1) or after[:, 0].min() <= np.quantile(before[:, 0], 0.9) ): continue if ( np.quantile(after[:, 0], 0.1) > np.quantile(before[:, 0], 0.9) and np.median(after[:, 1]) - np.median(before[:, 1]) < -vertical_jump ): cuts.append(units[valid[index]][0]) last = index boundaries = [block.start, *cuts, block.end] result.extend( Block(block.type, start, end) for start, end in zip(boundaries, boundaries[1:]) ) return _split_short_openings(answer, capture, result) def _split_short_openings( answer: str, capture: dict, blocks: list[Block] ) -> list[Block]: """Recover 4–11 opening words stranded at the foot of a previous column. Twelve following words must support a disjoint column above the opening. Both windows follow row order; all coordinates are attention-grid cells. Splits preserve transcript offsets and therefore cached attention indices. """ units, per_block = units_for(answer, blocks) sparse = capture["sparse_maps"] grid_width = capture["grid"][1] result = [] for block, indices in zip(blocks, per_block): cut = None if block.type == "text" and len(indices) >= 17: points = [] for unit in indices[:23]: values = sparse["val"][unit] if not values: break cell = sparse["idx"][unit][int(np.argmax(values))] points.append([cell % grid_width, cell // grid_width]) # All candidate cuts lie within the first 23 words. Reject ordinary # same-column prose before reading the rest of its attention maps. if len(points) == min(23, len(indices)): horizontal = [point[0] for point in points] if not any( min(horizontal[index : index + 12]) > max(horizontal[:index]) for index in range(4, min(12, len(indices) - 11)) ): result.append(block) continue for unit in indices[23:]: values = sparse["val"][unit] if not values: break cell = sparse["idx"][unit][int(np.argmax(values))] points.append([cell % grid_width, cell // grid_width]) if len(points) == len(indices): positions = np.asarray(points) steps = np.diff(positions[:, 1]) steps = steps[(steps > 0) & (steps <= 3)] jump = max(3, 3 * float(np.median(steps))) if len(steps) else 3 for index in range(4, min(12, len(indices) - 11)): before, after = positions[:index], positions[index : index + 12] if ( after[:, 0].min() <= before[:, 0].max() or np.median(before[:, 1]) - np.median(after[:, 1]) <= jump or any(np.any(np.diff(p[:, 1]) < -1) for p in (before, after)) or any(np.ptp(p[:, 1]) > jump for p in (before, after)) or any( np.any(np.diff(p[:, 0])[np.diff(p[:, 1]) == 0] <= 0) for p in (before, after) ) ): continue cut = units[indices[index]][0] break if cut is None: result.append(block) else: result.extend( [Block(block.type, block.start, cut), Block(block.type, cut, block.end)] ) return result