# 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. """Candidate table/chart extents from transcript structure and sparse attention.""" from bisect import bisect_left, bisect_right import re from typing import Protocol from .predict import predict import numpy as np from .blocks import Block from .rectangles import mass_box, mass_boxes from .pictures import ious TABLE_FEATURE_VERSION = "table-candidates-v1" TABLE_FEATURE_COUNT = 41 TABLE_SELECTION_MARGIN = 0.05 class TablePredictor(Protocol): def predict(self, features: np.ndarray) -> np.ndarray: ... _HINTS = ( "figure", "chart", "graph", "plot", "series", "axis", "reference line", "table", ) def table_candidates( answer: str, blocks: list[Block], per: list[list[int]], units: list[tuple[int, int]], capture: dict, block_index: int, original: list[float], ) -> tuple[list[list[float]], list[list[float]]]: """Propose grid-cell rectangles using table words, cell alignment, and neighbors. The first candidate preserves the original box. Chart-like transcripts can place numeric cells throughout a plot; their pooled attention and adjacent captions provide broader extents than a connected-word component alone. """ gh, gw = capture["grid"] sp = capture["sparse_maps"] block = blocks[block_index] us = [ u for u in per[block_index] if sp["has"][u] and sp["val"][u] and max(sp["val"][u]) > 0 ] if not us: return [], [] peak_by = {} density = np.zeros((gh, gw)) sharp = np.zeros_like(density) for u in us: ix = np.asarray(sp["idx"][u]) v = np.asarray(sp["val"][u]) p = ix[v.argmax()] peak_by[u] = (p % gw + 0.5, p // gw + 0.5) density.flat[ix] += v / v.sum() keep = v >= 0.3 * v.max() sharp.flat[ix[keep]] += v[keep] / v[keep].sum() density /= density.sum() sharp /= sharp.sum() peaks = np.array([peak_by[u] for u in us]) boxes = [original] kinds = [0] def add(b: np.ndarray | list[float], kind: int) -> None: b = np.clip(b, 0, [gw, gh, gw, gh]).tolist() if b[2] > b[0] and b[3] > b[1] and b not in boxes: boxes.append(b) kinds.append(kind) for kind, m in [(1, density), (2, sharp)]: for box in mass_boxes(m, [0, 0.01, 0.025, 0.05, 0.1, 0.2]): add(box, kind) quantiles = np.array([0, 0.01, 0.025, 0.05, 0.1]) low, high = np.quantile(peaks, [quantiles, 1 - quantiles], axis=0) for lower, upper in zip(low, high): bb = np.r_[lower - 0.5, upper + 0.5] for pad in [0, 0.5, 1, 2]: add(bb + np.array([-pad, -pad, pad, pad]), 3) # The generated heading often represents axis/legend text of a chart. if block_index and blocks[block_index - 1].type == "heading": heading = [] for u in per[block_index - 1]: if sp["has"][u] and sp["val"][u] and max(sp["val"][u]) > 0: p = sp["idx"][u][int(np.argmax(sp["val"][u]))] heading.append([p % gw + 0.5, p // gw + 0.5]) if heading: joint = np.vstack([peaks, heading]) add( np.r_[ np.quantile(joint, 0.01, axis=0) - 0.5, np.quantile(joint, 0.99, axis=0) + 0.5, ], 4, ) anchors = [] for direction in [-1, 1]: anchor = None for k in range( block_index + direction, -1 if direction < 0 else len(blocks), direction ): if blocks[k].type in ("image", "table"): break pts = [] for u in per[k]: if sp["has"][u] and sp["val"][u] and max(sp["val"][u]) > 0: p = sp["idx"][u][int(np.argmax(sp["val"][u]))] pts.append([p % gw + 0.5, p // gw + 0.5]) if pts: pts = np.array(pts) anchor = np.r_[ np.quantile(pts, 0.05, axis=0) - 0.5, np.quantile(pts, 0.95, axis=0) + 0.5, ] break anchors.append(anchor) seed = np.array(mass_box(sharp, 0.025)) prev, nxt = anchors top = prev[3] if prev is not None and prev[3] < seed[1] else seed[1] bottom = nxt[1] if nxt is not None and nxt[1] > seed[3] else seed[3] for fraction in [0.25, 0.5, 0.75, 1.0]: b = seed.copy() b[1] += fraction * (top - b[1]) b[3] += fraction * (bottom - b[3]) add(b, 5) available = [a for a in anchors if a is not None] if available: b[0] = min(b[0], min(a[0] for a in available)) b[2] = max(b[2], max(a[2] for a in available)) add(b, 6) # Cell alignment distinguishes a printed grid from values read off a plot. cells = [] word_starts = [units[u][0] for u in us] for row, tr in enumerate( re.finditer( r"]*>(.*?)", answer[block.start : block.end], re.I | re.S ) ): for col, cell in enumerate( re.finditer(r"]*>(.*?)", tr.group(1), re.I | re.S) ): start = block.start + tr.start(1) + cell.start(1) end = block.start + tr.start(1) + cell.end(1) first = bisect_left(word_starts, start) last = bisect_right(word_starts, end) ps = [peak_by[u] for u in us[first:last] if units[u][1] <= end] if ps: cells.append([row, col, *np.median(ps, axis=0)]) structure = [0.0] * 8 if cells: c = np.array(cells) rows = np.unique(c[:, 0]) cols = np.unique(c[:, 1]) sx = max(1.0, np.std(c[:, 2])) sy = max(1.0, np.std(c[:, 3])) row_scatter = np.mean([np.std(c[c[:, 0] == r, 3]) for r in rows]) / sy col_scatter = np.mean([np.std(c[c[:, 1] == r, 2]) for r in cols]) / sx def corr(a: np.ndarray, b: np.ndarray) -> float: a = a - a.mean() b = b - b.mean() return float( (a * b).sum() / max(1e-9, np.sqrt((a * a).sum() * (b * b).sum())) ) structure = [ len(rows), len(cols), len(cells), row_scatter, col_scatter, corr(c[:, 0], c[:, 3]), corr(c[:, 1], c[:, 2]), sx / sy, ] nearby = ( answer[max(0, block.start - 400) : block.start].lower() + " " + answer[block.end : block.end + 250].lower() ) hints = [float(h in nearby) for h in _HINTS] numeric_fraction = sum( answer[units[u][0] : units[u][1]].replace(".", "").replace("-", "").isdigit() for u in us ) / len(us) features = [] for b, kind in zip(boxes, kinds): x0, y0, x1, y1 = b inside = ( (peaks[:, 0] >= x0) & (peaks[:, 0] <= x1) & (peaks[:, 1] >= y0) & (peaks[:, 1] <= y1) ) patch = density[int(y0) : int(np.ceil(y1)), int(x0) : int(np.ceil(x1))] area = (x1 - x0) * (y1 - y0) mass = float(patch.sum()) f = [ kind, x0 / gw, y0 / gh, x1 / gw, y1 / gh, (x1 - x0) / gw, (y1 - y0) / gh, area / (gw * gh), mass, float(inside.mean()), np.log1p(len(us)), float(numeric_fraction), gh, gw, ] f += ( structure + hints + ious(np.array([b]), np.array([original])).ravel().tolist() + ((np.array(b) - original) / [gw, gh, gw, gh]).tolist() ) for anchor in anchors: f.extend( [0.0, 0.0, 0.0] if anchor is None else [1.0, (y0 - anchor[3]) / gh, (y1 - anchor[1]) / gh] ) features.append(f) return boxes, features def refine_tables( capture: dict, answer: str, blocks: list[Block], per_block: list[list[int]], units: list[tuple[int, int]], result: dict, model: TablePredictor, ) -> None: """Replace a table box only when predicted quality clears the baseline margin. Transcript spans and table types are preserved, including charts transcribed as HTML tables. Features use cached attention and text, with no page pixels. """ gh, gw = capture["grid"] scale = np.array([capture["width"] / gw, capture["height"] / gh] * 2) elements = { (element["start"], element["end"]): element for element in result["elements"] if element["type"] == "table" and element["box"] is not None } for block_index, block in enumerate(blocks): if block.type != "table": continue element = elements.get((block.start, block.end)) if element is None: continue original = (np.asarray(element["box"]) / scale).tolist() boxes, features = table_candidates( answer, blocks, per_block, units, capture, block_index, original ) if not boxes: continue quality = predict(model, np.asarray(features)) selected = int(quality.argmax()) if quality[selected] > quality[0] + TABLE_SELECTION_MARGIN: element["box"] = (np.asarray(boxes[selected]) * scale).tolist() _TABLE_CELL = re.compile(r"]*>(.*?)", re.S | re.I) def coherent_table_words( selected: list[int], cells: list[list[int]], boxes: np.ndarray, peaks: np.ndarray, ) -> list[int]: """Drop isolated word bands while preserving support in every table cell. Coordinates and predicted word heights use attention-grid cells. Each axis needs a band containing 90% of the words; sparse genuine rows or columns survive when any cell depends on them. """ for axis in (0, 1): if len(selected) < 12: break ordered = sorted(selected, key=lambda j: peaks[j, axis]) gap = max(3.0, 3 * float(np.median(boxes[selected, 3] - boxes[selected, 1]))) bands: list[list[int]] = [[]] for j in ordered: if bands[-1] and peaks[j, axis] - peaks[bands[-1][-1], axis] > gap: bands.append([]) bands[-1].append(j) main = max(bands, key=len) members = set(main) if len(main) >= 0.9 * len(selected) and all( members.intersection(cell) for cell in cells ): selected = main return selected def _refine_supported_table_words( answer: str, elements: list[dict], units: list[tuple[int, int]], valid: list[int], boxes: np.ndarray, peaks: np.ndarray, scale: np.ndarray, ) -> None: """Refine whole-table extents from supported cell words, preserving one region. Word boxes and peaks use grid cells; element boxes and the result use pixels. Every cell with available word predictions must have support inside the old table bounds plus one grid cell. A cell whose predictions all lie outside that guard preserves the old table box. """ starts = [units[u][0] for u in valid] for element in elements: if element["type"] != "table" or element["box"] is None: continue bounds = np.asarray(element["box"]) / scale selected: list[int] = [] cell_groups: list[list[int]] = [] complete = True for cell in _TABLE_CELL.finditer(answer, element["start"], element["end"]): first = bisect_left(starts, cell.start(1)) last = bisect_right(starts, cell.end(1)) rows = [j for j in range(first, last) if units[valid[j]][1] <= cell.end(1)] if not rows: continue supported = [ j for j in rows if bounds[0] - 1 <= peaks[j, 0] <= bounds[2] + 1 and bounds[1] - 1 <= peaks[j, 1] <= bounds[3] + 1 ] if not supported: complete = False break selected.extend(supported) cell_groups.append(supported) if complete and len(cell_groups) >= 2: selected = coherent_table_words(selected, cell_groups, boxes, peaks) words = boxes[selected] element["box"] = ( np.r_[words[:, :2].min(0), words[:, 2:].max(0)] * scale ).tolist() # Text glyphs stop short of the table's vertical cell padding. padding = 0.25 * float(np.median(words[:, 3] - words[:, 1])) * scale[1] element["box"][1] -= padding element["box"][3] += padding _TABLE_ROW = re.compile(r"]*>(.*?)", re.S | re.I) def refine_table_word_boxes( answer: str, elements: list[dict], units: list[tuple[int, int]], valid: list[int], boxes: np.ndarray, peaks: np.ndarray, scale: np.ndarray, ) -> None: """Recover vertically truncated tables from ordered, multi-column cell rows. Peaks and word boxes use grid cells; element boxes use pixels. Two HTML rows must independently agree outside the coarse bounds before those bounds expand. The expanded guard still requires support from every available table cell. """ snapshots = [ (e, list(e["box"])) for e in elements if e["type"] == "table" and e["box"] is not None ] _refine_supported_table_words(answer, elements, units, valid, boxes, peaks, scale) starts = [units[u][0] for u in valid] for element, old in snapshots: bounds = np.array(old) / scale votes: list[list[tuple[list[int], float]]] = [[], []] for row in _TABLE_ROW.finditer(answer, element["start"], element["end"]): cells: list[list[list[int]]] = [[], []] for cell in _TABLE_CELL.finditer(answer, row.start(1), row.end(1)): first = bisect_left(starts, cell.start(1)) last = bisect_right(starts, cell.end(1)) indices = [ j for j in range(first, last) if units[valid[j]][1] <= cell.end(1) ] if not indices: continue supported = [ j for j in indices if bounds[0] - 1 <= peaks[j, 0] <= bounds[2] + 1 ] if len(supported) < 0.9 * len(indices): continue for direction in (0, 1): outside = [ j for j in supported if ( peaks[j, 1] < bounds[1] - 1 if direction == 0 else peaks[j, 1] > bounds[3] + 1 ) ] if len(outside) >= 0.8 * len(supported): cells[direction].append(outside) for direction in (0, 1): row_cells = cells[direction] if len(row_cells) < 2: continue # Separate columns must agree on a row band, allowing multiline cells. centers = np.array( [ np.median(peaks[word_indices], axis=0) for word_indices in row_cells ] ) heights = [np.ptp(peaks[word_indices, 1]) for word_indices in row_cells] if np.ptp(centers[:, 0]) < 2 or np.ptp(centers[:, 1]) > max( 2, float(np.median(heights)) ): continue votes[direction].append( ( [j for word_indices in row_cells for j in word_indices], float(np.median(centers[:, 1])), ) ) expanded = bounds.copy() for direction in (0, 1): ordered_rows = votes[direction] if len(ordered_rows) < 2 or any( b[1] <= a[1] for a, b in zip(ordered_rows, ordered_rows[1:]) ): continue indices = [j for word_indices, _ in ordered_rows for j in word_indices] if direction == 0: expanded[1] = min(expanded[1], float(peaks[indices, 1].min())) else: expanded[3] = max(expanded[3], float(peaks[indices, 1].max())) if np.array_equal(expanded, bounds): continue guard = (expanded * scale).tolist() candidate = {**element, "box": guard.copy()} _refine_supported_table_words( answer, [candidate], units, valid, boxes, peaks, scale ) # A cell without support leaves the guard untouched; preserve the prior result. if candidate["box"] != guard: element["box"] = candidate["box"] expand_chart_category_axis(answer, elements, units, valid, peaks, scale) def expand_chart_category_axis( answer: str, elements: list[dict], units: list[tuple[int, int]], valid: list[int], peaks: np.ndarray, scale: np.ndarray, ) -> None: """Extend categorical chart bounds by half the category spacing at each end. HTML data rows can describe bars rather than physical table rows. Require three evenly spaced horizontal labels with aligned values above them. Peaks use grid cells; element boxes and the updated bounds use pixels. """ starts = [units[u][0] for u in valid] for element in elements: if element["type"] != "table" or element["box"] is None: continue rows = list(_TABLE_ROW.finditer(answer, element["start"], element["end"])) labels = [] values = [] for row in rows[1:]: cells = list(_TABLE_CELL.finditer(answer, row.start(1), row.end(1))) if len(cells) != 2: break centers = [] for cell in cells: first = bisect_left(starts, cell.start(1)) last = bisect_right(starts, cell.end(1)) indices = [ j for j in range(first, last) if units[valid[j]][1] <= cell.end(1) ] if not indices: break centers.append(np.median(peaks[indices], axis=0)) if len(centers) != 2: break labels.append(centers[0]) values.append(centers[1]) if len(labels) < 3 or len(labels) != len(rows) - 1: continue category_points = np.asarray(labels) value_points = np.asarray(values) steps = np.diff(category_points[:, 0]) if ( np.ptp(category_points[:, 1]) > 1 or np.any(steps < 2) or steps.max() > 1.5 * steps.min() or np.any(abs(value_points[:, 0] - category_points[:, 0]) > 2) or np.sum(value_points[:, 1] < category_points[:, 1] - 2) < 0.75 * len(labels) ): continue bounds = np.asarray(element["box"]) / scale half_step = float(np.median(steps)) / 2 bounds[0] = min(bounds[0], category_points[0, 0] - half_step) bounds[2] = max(bounds[2], category_points[-1, 0] + half_step) element["box"] = (bounds * scale).tolist()