# 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. """One page: raw ocria answer + page image -> layout elements with boxes, in the two forms the benches read. elements = ground_page(grounder, image, answer) # GPU pass + CPU snapping md = to_box_markdown(answer, elements, w, h) # box-mode markers (0-1000 grid) page = to_layout_page(answer, elements, w, h, scale) # a ParseBench layout page Pure functions below `ground_page` need no GPU and are what the tests exercise. """ from __future__ import annotations import re import numpy as np from .blocks import Block, body_span, resolve_page_numbers, split_blocks from .boxes import Page, absorb_uncovered_ink, envelope, fill_tables, main_cluster, snap_table, unclaimed_graphics from .geometry import paragraph_paths from .tune import FLAGS from .words import norm, word_spans _PAGE_NO = re.compile(r"(?:^|\s)(?:page\s*)?\d{1,4}(?:\s*(?:of|/)\s*\d{1,4})?\s*$", re.I) _FURN_TAG = re.compile(r"") def units_for(answer: str, blocks: list[Block]) -> tuple[list[tuple[int, int]], list[list[int]]]: """Attention units and, per block, the indices of its units: every content word inside the block; an image block is one unit (its whole reference), because the picture it points at has no words to snap to.""" spans = word_spans(answer) units: list[tuple[int, int]] = [] per_block: list[list[int]] = [] k = 0 for b in blocks: mine: list[int] = [] if b.type == "image": mine.append(len(units)) units.append((b.start, b.end)) per_block.append(mine) continue while k < len(spans) and spans[k][0] < b.start: k += 1 j = k while j < len(spans) and spans[j][1] <= b.end: mine.append(len(units)) units.append((spans[j][0], spans[j][1])) j += 1 per_block.append(mine) return units, per_block def element_boxes(page: Page, answer: str, blocks: list[Block], units, per_block, maps, has) -> list: """Pixel box [x0, y0, x1, y1] per block (None when none of its units reached a token).""" return [bx for _, bx in element_pieces(page, answer, blocks, units, per_block, maps, has, split=False)] def element_pieces(page: Page, answer: str, blocks: list[Block], units, per_block, maps, has, split: bool = True, words_out: dict | None = None, geometry_spans: set[tuple[int, int]] | None = None) -> list[tuple[Block, list | None]]: """(block, box) per element. With `split` (tuning flag split_gaps), a text element whose words fall into clusters separated by whitespace gaps becomes one element per cluster when the clusters follow each other in the text (vertical gap > 1.4, horizontal > 2.0 line heights).""" out = [] W, H = page.w, page.h snaps = {} # unit -> word box, for every text unit on the page (image units excluded) for b, idx in zip(blocks, per_block): if b.type != "image": for u in idx: if has[u]: snaps[u] = page.snap_word(maps[u], len(norm(answer[units[u][0]:units[u][1]]))) if "drop_big_words" in FLAGS: # not inside tables: a table word on its ruling gives the table its extent table_units = {u for b, idx in zip(blocks, per_block) if b.type == "table" for u in idx} dropped = _drop_oversized(snaps) snaps = {u: (w if u in table_units else dropped[u]) for u, w in snaps.items()} for b, idx in zip(blocks, per_block): idx = [u for u in idx if has[u]] if not idx: out.append((b, None)) continue if b.type == "image": bx = page.image_box(maps[idx[0]]) if "pic_cap" in FLAGS and (bx[2] - bx[0]) * (bx[3] - bx[1]) > float(FLAGS["pic_cap"]) * W * H: bx = page.image_hot_box(maps[idx[0]]) if (bx[2] - bx[0]) * (bx[3] - bx[1]) > float(FLAGS["pic_cap"]) * W * H: bx = None out.append((b, bx)) continue snapped = [(u, snaps.get(u)) for u in idx] snapped = [(u, w) for u, w in snapped if w is not None] if not snapped: out.append((b, None)) continue words = [w for _, w in snapped] if "paragraph_geometry" in FLAGS and b.type in ("text", "list"): paths = paragraph_paths(words) if paths and (split or len(paths) == 1): for k, path in enumerate(paths): start = b.start if k == 0 else units[snapped[path[0]][0]][0] end = b.end if k + 1 == len(paths) else units[snapped[paths[k + 1][0]][0]][0] piece = Block(b.type, start, end) core = [words[i] for i in path] if words_out is not None: words_out[id(piece)] = core if geometry_spans is not None: geometry_spans.add((start, end)) out.append((piece, envelope(core))) continue if "seq_filter" in FLAGS and b.type != "table" and len(words) >= 3: words = _reading_order_core(words, page.med_h) or words core = main_cluster(words, page.line_h, wide=b.type == "table") if words_out is not None: words_out[id(b)] = core env = envelope(core) if b.type == "table": bx = snap_table(page, env) if "chart_tables" in FLAGS and bx == [float(v) for v in env]: bx = page.graphic_around(bx) or bx out.append((b, bx)) continue pieces = _split_at_gaps(page, b, snapped, units, env) if split and "split_gaps" in FLAGS else None if pieces: out.extend(pieces) else: out.append((b, env)) return out def _follows(a, b, h: float) -> bool: """Word box b can be the word written after a: further right on the same line, or the start of a line below.""" ha, hb = a[3] - a[1], b[3] - b[1] same_line = min(a[3], b[3]) - max(a[1], b[1]) >= 0.5 * min(ha, hb) if same_line: return -0.5 * h <= b[0] - a[2] <= float(FLAGS.get("seq_dx", "4")) * h return b[1] > a[1] + 0.3 * h and b[1] - a[3] <= float(FLAGS.get("seq_dy", "2.5")) * h and b[0] < a[2] def _reading_order_core(words: list, h: float) -> list | None: """The words that sit where the text order says they should: runs of consecutive words in which each follows the previous one on the page (`_follows`, one missing word allowed), keeping runs of >= 2 words; None when no run.""" n = len(words) parent = list(range(n)) def find(i): while parent[i] != i: parent[i] = parent[parent[i]] i = parent[i] return i for i in range(n - 1): if _follows(words[i], words[i + 1], h): parent[find(i + 1)] = find(i) elif i + 2 < n and _follows(words[i], words[i + 2], h): parent[find(i + 2)] = find(i) groups: dict[int, list[int]] = {} for i in range(n): groups.setdefault(find(i), []).append(i) keep = sorted(i for g in groups.values() if len(g) >= 2 for i in g) return [words[i] for i in keep] if keep else None def _iou(a, b) -> float: i = max(0.0, min(a[2], b[2]) - max(a[0], b[0])) * max(0.0, min(a[3], b[3]) - max(a[1], b[1])) u = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - i return i / u if u > 0 else 0.0 def _drop_duplicate_boxes(answer: str, blocks, boxes) -> list: """Of two elements whose boxes overlap at IoU >= 0.5, the one with fewer letters loses its box (two elements placed on the same block: one of them is misplaced, and the longer text is more likely to own the block).""" letters = [sum(c.isalnum() for c in answer[b.start:b.end]) for b in blocks] out = list(boxes) for i in range(len(out)): for j in range(i + 1, len(out)): if out[i] is None or out[j] is None or _iou(out[i], out[j]) < 0.5: continue if letters[i] >= letters[j]: out[j] = None else: out[i] = None return out def _drop_nested_text_boxes(blocks, boxes) -> list: """A text box >= 90% inside another element's text box at least 1.5x its area is a misplaced fragment of that block.""" text = [b.type not in ("image", "table") for b in blocks] area = [0.0 if bx is None else (bx[2] - bx[0]) * (bx[3] - bx[1]) for bx in boxes] out = list(boxes) for i, r in enumerate(boxes): if r is None or not text[i] or area[i] <= 0: continue for j, host in enumerate(boxes): if j == i or host is None or not text[j] or area[j] <= 1.5 * area[i]: continue inter = max(0.0, min(r[2], host[2]) - max(r[0], host[0])) * max(0.0, min(r[3], host[3]) - max(r[1], host[1])) if inter / area[i] >= 0.9: out[i] = None break return out def _drop_oversized(snaps: dict) -> dict: """A word whose box is taller than 4x the page's median word height or larger than 50x its median word area snapped to a frame, a rule or a graphic, not to a word, and one such box stretches its element across the page. Such words get no box (pages with >= 10 words).""" boxes = [w for w in snaps.values() if w is not None] if len(boxes) < 10: return snaps hs = sorted(w[3] - w[1] for w in boxes) areas = sorted((w[2] - w[0]) * (w[3] - w[1]) for w in boxes) mh, ma = hs[len(hs) // 2], areas[len(areas) // 2] return {u: (None if w is None or w[3] - w[1] > 4 * mh or (w[2] - w[0]) * (w[3] - w[1]) > 50 * ma else w) for u, w in snaps.items()} def _split_at_gaps(page: Page, b: Block, snapped, units, env): """Pieces of one element split at whitespace gaps, or None. Only for big elements (>= 4% of the page, >= 6 words), and only when each cluster is one run of consecutive words (else the text cannot be cut).""" W, H = page.w, page.h if len(snapped) < int(FLAGS.get("sg_min_words", "6")) or \ (env[2] - env[0]) * (env[3] - env[1]) < float(FLAGS.get("sg_min_area", "0.04")) * W * H: return None vg, hg = float(FLAGS.get("sg_v", "1.4")) * page.line_h, float(FLAGS.get("sg_h", "2.0")) * page.line_h n = len(snapped) parent = list(range(n)) def find(i): while parent[i] != i: parent[i] = parent[parent[i]] i = parent[i] return i for i in range(n): p = snapped[i][1] for j in range(i + 1, n): q = snapped[j][1] 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 <= vg and dx <= hg: parent[find(i)] = find(j) lab = [find(i) for i in range(n)] runs = [] # consecutive words with the same cluster for i, l in enumerate(lab): if runs and runs[-1][0] == l: runs[-1][1].append(i) else: runs.append((l, [i])) # a single stray word between two runs of one cluster joins its neighbours merged = [] for l, ws in runs: if merged and (merged[-1][0] == l or len(ws) == 1): merged[-1][1].extend(ws) else: merged.append((l, ws)) if len(merged) < 2 or len({l for l, _ in merged}) != len(merged): return None pieces = [] for k, (_, ws) in enumerate(merged): start = b.start if k == 0 else units[snapped[ws[0]][0]][0] end = b.end if k == len(merged) - 1 else units[snapped[merged[k + 1][1][0]][0]][0] pieces.append((Block(b.type, start, end), envelope([snapped[i][1] for i in ws]))) return pieces def ground_page(grounder, image, answer: str, keep_maps: bool = False) -> dict: """{width, height, elements: [{type, start, end, box}]} for one page (box in pixels of `image`, or None). `keep_maps` also returns the sparse attention maps (`sparse_maps`) so the CPU step can be re-run offline.""" blocks = split_blocks(answer) units, per_block = units_for(answer, blocks) w, h = image.size if not units: return {"width": w, "height": h, "elements": []} maps, grid, has = grounder.unit_maps(image, answer, units) out = boxes_from_maps(image, answer, blocks, units, per_block, maps, grid, has) if keep_maps: out["sparse_maps"] = sparsify(maps, has, [b.type == "image" for b in blocks], per_block) return out def boxes_from_maps(image, answer: str, blocks, units, per_block, maps, grid, has, regions: list | None = None, page: Page | None = None) -> dict: """The CPU half of `ground_page`: attention maps -> element boxes. With `regions` (layout-detector detections, [{label, score, box}] in image pixels) elements are placed on the regions (regions.place_on_regions).""" w, h = image.size page = page or Page(np.asarray(image.convert("RGB")), grid) words_of: dict = {} geometry_spans: set[tuple[int, int]] = set() pieces = element_pieces(page, answer, blocks, units, per_block, maps, has, words_out=words_of, geometry_spans=geometry_spans) piece_words = [words_of.get(id(pb), []) for pb, _ in pieces] blocks = [Block(pb.type, pb.start, pb.end) for pb, _ in pieces] boxes = [bx for _, bx in pieces] if regions is None and "ink_regions" in FLAGS: from .regions import ink_regions regions = ink_regions(page, float(FLAGS.get("ink_kv", "1.0")), float(FLAGS.get("ink_kh", "1.5"))) if regions is not None: from .regions import clean_regions, place_on_regions boxes, extra_pics = place_on_regions([b.type for b in blocks], piece_words, boxes, clean_regions(regions, float(FLAGS.get("region_score", "0.35"))), page.line_h, add_unclaimed_pictures="no_region_pics" not in FLAGS, text_too=FLAGS.get("region_kinds", "all") != "visual") if "region_absorb" not in FLAGS and FLAGS.get("region_kinds", "all") != "visual": # regions cover blocks FLAGS_NO_ABSORB = True else: FLAGS_NO_ABSORB = False else: extra_pics, FLAGS_NO_ABSORB = [], False if "no_absorb" not in FLAGS and not FLAGS_NO_ABSORB: # Unconstrained ink absorption can reattach a rejected outlier or bridge # the gutter. Keep accepted geometry paths at their supported extent. boxes = absorb_uncovered_ink(page, boxes, [b.type != "image" and (b.start, b.end) not in geometry_spans for b in blocks], line_only=[b.type in ("heading", "header", "footer", "page_number") for b in blocks] if "absorb_head_line" in FLAGS else None) if "table_fill" in FLAGS: boxes = fill_tables(page, boxes, [b.type == "table" for b in blocks], float(FLAGS.get("table_gap", "2.5"))) if "pad" in FLAGS: # ink-tight boxes vs annotated boxes with a margin: grow text-like boxes by pad x body glyph height m = float(FLAGS["pad"]) * page.med_h boxes = [bx if bx is None or b.type == "image" else [max(0.0, bx[0] - m), max(0.0, bx[1] - m), min(float(w), bx[2] + m), min(float(h), bx[3] + m)] for b, bx in zip(blocks, boxes)] if "dedupe" in FLAGS: boxes = _drop_duplicate_boxes(answer, blocks, boxes) if "drop_nested" in FLAGS: boxes = _drop_nested_text_boxes(blocks, boxes) resolve_page_numbers(blocks, boxes, h) if "furniture_bands" in FLAGS: # detector-free furniture labels by position for b, bx in zip(blocks, boxes): if bx is None or b.type not in ("text", "heading"): continue if bx[3] <= 0.09 * h: b.type = "header" elif bx[1] >= 0.93 * h or (bx[1] >= 0.88 * h and _PAGE_NO.search(answer[b.start:b.end])): b.type = "footer" elements = [{"type": b.type, "start": b.start, "end": b.end, "box": None if bx is None else [round(float(v), 1) for v in bx]} for b, bx in zip(blocks, boxes)] if extra_pics: # detector pictures the answer does not mention end = body_span(answer)[1] elements += [{"type": "image", "start": end, "end": end, "box": [round(float(v), 1) for v in bx]} for bx in extra_pics] elif "add_pictures" in FLAGS: # graphics the answer does not mention: picture boxes with no text, at the end end = body_span(answer)[1] elements += [{"type": "image", "start": end, "end": end, "box": [round(v, 1) for v in bx]} for bx in unclaimed_graphics(page, boxes)] return {"width": w, "height": h, "grid": list(grid), "elements": elements} def sparsify(maps, has, is_image_block, per_block, k_word: int = 64, k_image: int = 512) -> dict: """Top-k cells per unit (indices into the flattened grid, fp16 values): enough to re-run snapping offline at a fraction of the size of the dense maps. Image units keep more cells (their hot area is large).""" img_units = {u for blk, idx in zip(is_image_block, per_block) if blk for u in idx} flat = maps.reshape(maps.shape[0], -1) idx, val = [], [] for u in range(flat.shape[0]): k = min(flat.shape[1], k_image if u in img_units else k_word) top = np.argpartition(-flat[u], k - 1)[:k] if has[u] else np.zeros(0, dtype=np.int64) idx.append(top.astype(np.int32).tolist()) val.append(np.round(flat[u][top].astype(np.float32), 6).tolist()) return {"idx": idx, "val": val, "has": [bool(x) for x in has]} def dense_maps(sparse: dict, grid) -> tuple[np.ndarray, np.ndarray]: """Inverse of `sparsify` (cells outside the kept top-k are 0).""" gh, gw = grid maps = np.zeros((len(sparse["idx"]), gh * gw), np.float32) for u, (i, v) in enumerate(zip(sparse["idx"], sparse["val"])): if i: maps[u, i] = v return maps.reshape(-1, gh, gw), np.array(sparse["has"], bool) def to_box_markdown(answer: str, elements: list[dict], width: float, height: float) -> str: """The answer with a box-mode marker `` (0-1000 grid) opening each boxed element, i.e. what a box-mode model would have written; `layout_score.box_markers_to_attribution` reads it unchanged.""" out, pos = [], 0 for el in sorted(elements, key=lambda e: e["start"]): if el["box"] is None: continue x0, y0, x1, y1 = el["box"] g = [int(round(1000 * x0 / width)), int(round(1000 * y0 / height)), int(round(1000 * x1 / width)), int(round(1000 * y1 / height))] g = [max(0, min(1000, v)) for v in g] if g[2] <= g[0] or g[3] <= g[1]: continue out.append(answer[pos:el["start"]]) out.append(f"\n") pos = el["start"] out.append(answer[pos:]) return "".join(out) # (item type, segment label). The v2 detection metrics resolve a box's class from Canonical17 names only, so a raw # "heading"/"header"/"footer"/"image" type is dropped from localization/classification; segment labels keep the # raw LlamaParse layout names ("heading" itself is excluded by ParseBench's label mapper). _V2_TYPE = {"text": ("Text", "text"), "heading": ("Section-header", "paragraph_title"), "table": ("Table", "table"), "image": ("Picture", "image"), "header": ("Page-header", "header"), "footer": ("Page-footer", "footer")} def to_layout_page(answer: str, elements: list[dict], width: float, height: float, scale: float = 1.0, page_md: str = "") -> dict: """A ParseBench `layout_pages` entry. Boxes are x, y, w, h in the page's own units (pixels x `scale`; use 72 / DPI for PDF points), each item with one `layout_segments` entry equal to its box, because the v2 layout scorer ignores items without layout-aware segments.""" items = [] for el in elements: if el["box"] is None: continue x0, y0, x1, y1 = (v * scale for v in el["box"]) if x1 <= x0 or y1 <= y0: continue md = _FURN_TAG.sub("", answer[el["start"]:el["end"]]).strip() typ, label = _V2_TYPE.get(el["type"], _V2_TYPE["text"]) seg = {"x": x0, "y": y0, "w": x1 - x0, "h": y1 - y0, "label": label} items.append({"type": typ, "md": md, "value": md, "bbox": dict(seg), "layout_segments": [seg]}) return {"page_number": 1, "width": width * scale, "height": height * scale, "md": page_md, "items": items}