# 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. """Attention maps -> boxes on the page image (CPU only: numpy, scipy, PIL). Word boxes (82% of words at IoU >= 0.5 against exact PDF word boxes on held-out pages): the page ink is closed along the line into word blobs, and each word takes the blob near its attention peak that has the most attention times a width prior from its character count, grown along the line toward that width. An element's box is the envelope of its words' boxes, after dropping words that sit apart from the element's main cluster (a stray token attending somewhere else must not stretch the box across the page). An image reference has no words on the page, so its box comes from the attention of its own tokens, snapped to the graphic under the peak. """ from __future__ import annotations import statistics import numpy as np from PIL import Image from scipy import ndimage from .tune import FLAGS BIG_FONT = 2.0 # blob height / body glyph height above which a word is set in a larger font MAX_FONT = 5.0 # taller blobs are frames, rules or graphics, never one line of text def _u8(a): return a.view(np.uint8) if a.dtype == bool else a.astype(np.uint8) def dilate(a, shape): """binary_dilation by an all-ones (h, w) rectangle, as two 1D max filters (same output, linear time).""" h, w = shape out = _u8(a) if h > 1: out = ndimage.maximum_filter1d(out, h, axis=0, mode="constant", cval=0, origin=-1 if h % 2 == 0 else 0) if w > 1: out = ndimage.maximum_filter1d(out, w, axis=1, mode="constant", cval=0, origin=-1 if w % 2 == 0 else 0) return out.astype(bool) def erode(a, shape): """binary_erosion by an all-ones (h, w) rectangle (border counts as background), as two 1D min filters.""" h, w = shape out = _u8(a) if h > 1: out = ndimage.minimum_filter1d(out, h, axis=0, mode="constant", cval=0) if w > 1: out = ndimage.minimum_filter1d(out, w, axis=1, mode="constant", cval=0) return out.astype(bool) def close(a, shape): """binary_closing by an all-ones (h, w) rectangle.""" return erode(dilate(a, shape), shape) class Page: """Ink analysis of one rendered page, computed once and shared by every word on it.""" def __init__(self, rgb: np.ndarray, grid: tuple[int, int]): self.h, self.w = rgb.shape[:2] self.gh, self.gw = grid self.cell = (self.w / self.gw, self.h / self.gh) gray = np.asarray(Image.fromarray(rgb).convert("L"), dtype=np.float32) # PIL luma self.ink = gray < min(160.0, float(gray.mean()) - 40.0) if "contrast_ink" in FLAGS: # also light text on a dark local background (white on a coloured panel) k = 8 small = gray[::k, ::k] bg_small = ndimage.median_filter(small, size=int(FLAGS.get("bg_size", "9"))) bg = np.kron(bg_small, np.ones((k, k), np.float32))[:self.h, :self.w] dark_bg = bg < float(FLAGS.get("dark_bg", "120")) self.ink = (self.ink & ~dark_bg) | (dark_bg & (gray > bg + float(FLAGS.get("light_delta", "60")))) # any non-background mark, light colours included: photos, chart fills, shaded boxes sat = rgb.max(-1).astype(np.float32) - rgb.min(-1).astype(np.float32) self.fg = (gray < 235.0) | (sat > 40.0) lab, _ = ndimage.label(self.ink) hs = [s[0].stop - s[0].start for s in ndimage.find_objects(lab) if s is not None] self.line_h = float(statistics.median([x for x in hs if x >= 4] or [10])) closed = close(self.ink, (1, max(3, int(0.45 * self.line_h)))) | self.ink self.lab, n = ndimage.label(closed) self.blobs = [[s[1].start, s[0].start, s[1].stop, s[0].stop] for s in ndimage.find_objects(self.lab)] tall = sorted(b[3] - b[1] for b in self.blobs if b[3] - b[1] >= 4) self.med_h = float(tall[len(tall) // 2] if tall else 10) # long thin or large ink pieces (table rulings, frames, rules): what a table box snaps out to raw = [[s[1].start, s[0].start, s[1].stop, s[0].stop] for s in ndimage.find_objects(lab) if s is not None] big = 4 * self.line_h self.structures = [b for b in raw if b[2] - b[0] > big or b[3] - b[1] > big] self.blob_arr = np.array(self.blobs, dtype=np.float64).reshape(-1, 4) self._fg_lab = None def fg_components(self): """Labels and slices of the foreground closed by one body line: the graphics an image reference snaps to (computed once per page; every image reference on it reads the same).""" if self._fg_lab is None: k = int(self.line_h) | 1 # a k x k closing fg = close(self.fg, (k, k)) lab, _ = ndimage.label(fg) self._fg_lab = (lab, ndimage.find_objects(lab)) return self._fg_lab def snap_word(self, m: np.ndarray, n_chars: int) -> list[float] | None: """Box of one word from its attention map (gh x gw): see the module docstring. None when there is no ink around the attention peak: the peak sits on blank paper (often an edge column of the image grid), which says nothing about where the word is, and a cell box there would stretch the element's box to the margin.""" gh, gw = m.shape cw, ch = self.cell py, px = np.unravel_index(int(m.argmax()), m.shape) y0, y1 = int(max(0, (py - 1) * ch)), int(min(self.h, (py + 2) * ch)) x0, x1 = int(max(0, (px - 1) * cw)), int(min(self.w, (px + 2) * cw)) ids = np.unique(self.lab[y0:y1, x0:x1]) ids = ids[ids > 0] n = max(n_chars, 1) def fit(b): # expected width = characters x half the body glyph height; on a blob clearly taller than body text (a # large heading) its own height, else the heading looks like several short words. Measuring every blob's # own height instead cost 2.3 points of word IoU>=0.5 on the dev pages (ascenders, brackets). bh = float(b[3] - b[1]) ew = n * 0.5 * (bh if BIG_FONT * self.med_h < bh <= MAX_FONT * self.med_h else self.med_h) return abs(np.log(max(b[2] - b[0], 1) / ew)) best, best_s = None, -1.0 for i in ids: b = self.blobs[i - 1] ty0, ty1 = int(b[1] // ch), int(min(gh - 1, (b[3] - 1) // ch)) tx0, tx1 = int(b[0] // cw), int(min(gw - 1, (b[2] - 1) // cw)) s = float(m[ty0:ty1 + 1, tx0:tx1 + 1].sum()) * float(np.exp(-fit(b))) if s > best_s: best, best_s = b, s if best is None: return None b = list(best) A = self.blob_arr while True: # grow along the line while the width gets closer to the expected width h, nxt = b[3] - b[1], None vo = np.minimum(b[3], A[:, 3]) - np.maximum(b[1], A[:, 1]) gap = np.maximum(A[:, 0] - b[2], b[0] - A[:, 2]) for k in np.nonzero((vo >= 0.5 * np.minimum(h, A[:, 3] - A[:, 1])) & (gap >= 0) & (gap <= 0.8 * h))[0]: o = self.blobs[k] nb = [min(b[0], o[0]), min(b[1], o[1]), max(b[2], o[2]), max(b[3], o[3])] if fit(nb) < fit(b) - 1e-6 and (nxt is None or gap[k] < nxt[0]): nxt = (gap[k], nb) if nxt is None: return [float(v) for v in b] b = nxt[1] def graphic_around(self, box: list[float], max_frac: float = 0.6) -> list[float] | None: """The union of `box` with the graphic it sits on (a chart ocria read as a table: the words are its values and labels, the figure is larger), or None. The graphic is the closed-foreground component that overlaps the box most; it must be larger than the box, under `max_frac` of the page, and filled like a figure (not text).""" lab, sl = self.fg_components() x0, y0, x1, y1 = (int(v) for v in box) ids, counts = np.unique(lab[max(0, y0):y1, max(0, x0):x1], return_counts=True) keep = ids > 0 if not keep.any(): return None i = int(ids[keep][np.argmax(counts[keep])]) s = sl[i - 1] g = [s[1].start, s[0].start, s[1].stop, s[0].stop] ga, ba = (g[2] - g[0]) * (g[3] - g[1]), max((x1 - x0) * (y1 - y0), 1) if ga <= 1.2 * ba or ga > max_frac * self.w * self.h: return None if float(self.fg[s].mean()) < float(FLAGS.get("chart_fill", "0.15")) or float(self.ink[s].mean()) > 0.5: return None return [float(min(box[0], g[0])), float(min(box[1], g[1])), float(max(box[2], g[2])), float(max(box[3], g[3]))] def image_hot_box(self, m: np.ndarray) -> list[float]: """The attention hot area of an image reference (cells >= 30% of its peak), without snapping to graphics.""" cw, ch = self.cell ys, xs = np.nonzero(m >= 0.3 * float(m.max())) return [float(xs.min() * cw), float(ys.min() * ch), float((xs.max() + 1) * cw), float((ys.max() + 1) * ch)] def image_box(self, m: np.ndarray) -> list[float]: """Box of an image reference: the graphic (foreground component) under its strongest attention.""" cw, ch = self.cell hot = m >= 0.3 * float(m.max()) ys, xs = np.nonzero(hot) tok = [xs.min() * cw, ys.min() * ch, (xs.max() + 1) * cw, (ys.max() + 1) * ch] lab, sl = self.fg_components() if "exact_image_grid" in FLAGS: # Map pixels back to their cells; rounding cell widths before repeating # accumulates drift toward the bottom/right of non-divisible images. iy = np.arange(self.h) * self.gh // self.h ix = np.arange(self.w) * self.gw // self.w up = hot[iy[:, None], ix[None, :]] else: up = np.kron(hot, np.ones((int(np.ceil(ch)), int(np.ceil(cw))), dtype=bool))[:self.h, :self.w] ids = np.unique(lab[:up.shape[0], :up.shape[1]][up]) ids = ids[ids > 0] if not len(ids): return [float(v) for v in tok] boxes = [[sl[i - 1][1].start, sl[i - 1][0].start, sl[i - 1][1].stop, sl[i - 1][0].stop] for i in ids] # the component that holds most of the attention, plus any other big one inside the hot area mass = [float(m[int(b[1] // ch):int(np.ceil(b[3] / ch)), int(b[0] // cw):int(np.ceil(b[2] / cw))].sum()) for b in boxes] b = boxes[int(np.argmax(mass))] if (b[2] - b[0]) * (b[3] - b[1]) > 0.9 * self.w * self.h: # the closing merged the whole page return [float(v) for v in tok] return [float(v) for v in b] def snap_table(page: Page, env: list[float]) -> list[float]: """A table box reaches its ruling: the envelope of its words grows to the ruling pieces that touch it and either stay within a few lines of it, or are the table's own grid (covers most of the envelope, at most twice its area). A page-wide rule above a heading or a form's page frame is neither.""" m = 3 * page.line_h lim = [env[0] - m, env[1] - m, env[2] + m, env[3] + m] area = max((env[2] - env[0]) * (env[3] - env[1]), 1.0) box = list(env) for s in page.structures: touches = s[0] < env[2] and s[2] > env[0] and s[1] < env[3] and s[3] > env[1] inside = s[0] >= lim[0] and s[1] >= lim[1] and s[2] <= lim[2] and s[3] <= lim[3] inter = max(0, min(s[2], env[2]) - max(s[0], env[0])) * max(0, min(s[3], env[3]) - max(s[1], env[1])) grid = inter >= 0.6 * area and (s[2] - s[0]) * (s[3] - s[1]) <= 2.0 * area if touches and (inside or grid): box = [min(box[0], s[0]), min(box[1], s[1]), max(box[2], s[2]), max(box[3], s[3])] return [float(v) for v in box] def _overlap(a0: float, a1: float, b0: float, b1: float) -> float: return max(0.0, min(a1, b1) - max(a0, b0)) def absorb_uncovered_ink(page: Page, boxes: list, can_grow: list[bool], passes: int = 0, line_only: list[bool] | None = None) -> list: """Every word blob on the page that no element box covers joins the nearest element on its line (the label of a form row whose value sits far to the right, a time printed left of an entry, a closing "2)") or on the line just above or below it (the rest of a heading or paragraph), provided no other element's box lies between them. The attention places most words of an element, but the words it misses or that the cluster drops as strays are still the element's ink, and a box that leaves them out cuts the element's content. Only text-sized blobs count (rulings, frames and graphics are not words). `can_grow[i]` False keeps box i as it is (pictures: their box is the graphic). Returns new boxes; None stays None.""" passes = passes or int(FLAGS.get("absorb_passes", "3")) out = [None if b is None else list(map(float, b)) for b in boxes] lo, hi = 0.4 * page.med_h, MAX_FONT * page.med_h words = [b for b in page.blobs if lo <= b[3] - b[1] <= hi and b[2] - b[0] <= 0.6 * page.w] def covered(b) -> bool: area = max((b[2] - b[0]) * (b[3] - b[1]), 1) return any(e is not None and _overlap(b[0], b[2], e[0], e[2]) * _overlap(b[1], b[3], e[1], e[3]) >= 0.5 * area for e in ref) def blocked(i: int, region: list[float]) -> bool: return any(j != i and e is not None and _overlap(region[0], region[2], e[0], e[2]) > 0 and _overlap(region[1], region[3], e[1], e[3]) > 0 for j, e in enumerate(ref)) # absorb_frozen: every blob is matched against the attention boxes as they came in and all growth is applied at # once, so a box that took one line cannot reach the next one through it (a cascade down a column, across a page) frozen = "absorb_frozen" in FLAGS ref = [None if b is None else list(b) for b in out] if frozen else out if frozen: passes = 1 for _ in range(passes): changed = False for b in words: if covered(b): continue h = b[3] - b[1] best, best_gap = None, None for i, e in enumerate(ref): if e is None or not can_grow[i]: continue if _overlap(b[1], b[3], e[1], e[3]) >= 0.5 * h: # same line: gap along x gap = max(e[0] - b[2], b[0] - e[2], 0.0) if "absorb_gap" in FLAGS and gap > float(FLAGS["absorb_gap"]) * page.med_h: continue region = [min(b[2], e[2]), b[1], max(b[0], e[0]), b[3]] elif line_only and line_only[i]: # a heading or furniture band does not take the lines around it continue elif _overlap(b[0], b[2], e[0], e[2]) >= 0.5 * (b[2] - b[0]): # line above or below: gap along y gap = max(e[1] - b[3], b[1] - e[3], 0.0) if gap > float(FLAGS.get("absorb_vgap", "1.0")) * page.med_h: continue region = [max(b[0], e[0]), min(b[3], e[3]), min(b[2], e[2]), max(b[1], e[1])] else: continue if region[2] > region[0] and region[3] > region[1] and blocked(i, region): continue if best_gap is None or gap < best_gap: best, best_gap = i, gap if best is not None: e = out[best] out[best] = [min(e[0], b[0]), min(e[1], b[1]), max(e[2], b[2]), max(e[3], b[3])] changed = True if not changed: break return out def envelope(boxes: list[list[float]]) -> list[float]: return [min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes)] def main_cluster(boxes: list[list[float]], line_h: float, wide: bool = False) -> list[list[float]]: """The largest group of word boxes chained by proximity (vertical gap <= 1.5 lines; horizontal gap <= 4 lines, or any for a table, whose columns sit far apart). Words outside it are attention strays.""" n = len(boxes) if n <= 2: return boxes dy_max, dx_max = 1.5 * line_h, (float("inf") if wide else 4.0 * line_h) parent = list(range(n)) def find(i): while parent[i] != i: parent[i] = parent[parent[i]] i = parent[i] return i order = sorted(range(n), key=lambda i: boxes[i][1]) for a_i, a in enumerate(order): for b in order[a_i + 1:]: if boxes[b][1] - boxes[a][3] > dy_max: break p, q = boxes[a], boxes[b] dy = max(0.0, max(p[1], q[1]) - min(p[3], q[3])) dx = max(0.0, max(p[0], q[0]) - min(p[2], q[2])) if dy <= dy_max and dx <= dx_max: parent[find(a)] = find(b) groups: dict[int, list[int]] = {} for i in range(n): groups.setdefault(find(i), []).append(i) best = max(groups.values(), key=len) return [boxes[i] for i in best] def unclaimed_graphics(page: Page, boxes: list, min_side: float = 2.0, max_frac: float = 0.4) -> list[list[float]]: """Graphics on the page that no element covers (icons, logos, photos the answer does not mention): foreground components that are filled or coloured like a picture (not thin text strokes), between `min_side` body-glyph heights square and `max_frac` of the page, and less than 30% covered by element boxes.""" rgb_sat = None fg = close(page.fg, (int(page.line_h) | 1, int(page.line_h) | 1)) lab, _ = ndimage.label(fg) out = [] side = min_side * page.med_h for sl in ndimage.find_objects(lab): if sl is None: continue y0, y1, x0, x1 = sl[0].start, sl[0].stop, sl[1].start, sl[1].stop w, h = x1 - x0, y1 - y0 if w < side or h < side or w * h > max_frac * page.w * page.h or max(w / h, h / w) > 6: continue b = [float(x0), float(y0), float(x1), float(y1)] area = w * h cov = sum(_overlap(b[0], b[2], e[0], e[2]) * _overlap(b[1], b[3], e[1], e[3]) for e in boxes if e is not None) if cov >= 0.3 * area: continue fill = float(page.fg[y0:y1, x0:x1].mean()) if fill < float(FLAGS.get("pic_fill", "0.35")): # thin strokes: text or line art the answer left out continue out.append(b) return out def fill_tables(page: Page, boxes: list, is_table: list[bool], max_gap: float = 2.5) -> list: """A table box grows up and down through the ink lines inside its horizontal range, line by line, while the gap to the next line stays under `max_gap` body lines and the line touches no other element's box. ocria's attention collapses a long table's later rows onto its first ones, so the words alone stop short of the table's end.""" out = [None if b is None else list(map(float, b)) for b in boxes] gap_px = max_gap * page.line_h for i, b in enumerate(out): if b is None or not is_table[i]: continue x0, x1 = int(max(0, b[0])), int(min(page.w, b[2])) prof = page.ink[:, x0:x1].sum(1) > max(2, 0.002 * (x1 - x0)) others = [o for j, o in enumerate(out) if j != i and o is not None and _overlap(o[0], o[2], b[0], b[2]) > 0] def hits(y0: float, y1: float) -> bool: return any(_overlap(y0, y1, o[1], o[3]) > 0 for o in others) for step in (1, -1): # down, then up edge = int(b[3]) if step == 1 else int(b[1]) - 1 while True: y, gap = edge + step, 0 while 0 <= y < page.h and not prof[y] and gap <= gap_px: y += step gap += 1 if not (0 <= y < page.h) or gap > gap_px: break y_end = y while 0 <= y_end + step < page.h and prof[y_end + step]: y_end += step lo, hi = sorted((y, y_end)) if hits(lo, hi + 1) or hi - lo > 6 * page.line_h: # another element, or a graphic / frame break edge = y_end if step == 1: b[3] = float(hi + 1) else: b[1] = float(lo) return out