# 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. """Transcript spans, sparse attention decoding, and layout serialization.""" import re import numpy as np from .blocks import Block, split_blocks from .words import word_spans _FURN_TAG = re.compile(r"") _HEADING_PREFIX = re.compile(r"^#{1,6}\s+") def merge_duplicate_text(items: list[dict]) -> list[dict]: """Merge identical text predictions occupying the same page region. Formatting markers and whitespace do not distinguish duplicate text; punctuation, numbers and element types do. Keep the first occurrence's content with the tighter of two boxes whose intersection-over-union exceeds one half. Distinct locations remain separate occurrences. """ kept: list[dict] = [] seen: dict[tuple[str, str], list[int]] = {} for item in items: typ = item["type"] if typ not in {"Text", "Section-header", "Page-header", "Page-footer"}: kept.append(item) continue text = _HEADING_PREFIX.sub("", item["md"].strip()) text = text.replace("**", "").replace("__", "").strip("*`_ \n") key = (typ, " ".join(text.casefold().split())) if len(key[1]) < 12: kept.append(item) continue box = item["bbox"] area = box["w"] * box["h"] for index in seen.get(key, []): old = kept[index] other = old["bbox"] other_area = other["w"] * other["h"] intersection = max( 0, min(box["x"] + box["w"], other["x"] + other["w"]) - max(box["x"], other["x"]), ) * max( 0, min(box["y"] + box["h"], other["y"] + other["h"]) - max(box["y"], other["y"]), ) if intersection / max(1e-12, area + other_area - intersection) <= 0.5: continue if area < other_area: kept[index] = { **old, "bbox": box, "layout_segments": item["layout_segments"], } break else: seen.setdefault(key, []).append(len(kept)) kept.append(item) return kept def element_text(answer: str, start: int, end: int) -> str: """Return scored element text while retaining raw spans for attention lookup.""" return _FURN_TAG.sub("", answer[start:end]).strip() 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 dense_maps(sparse: dict, grid: tuple[int, int]) -> 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) class SparseWordMaps: """Sparse float32 maps with one borrowed grid, valid until the next lookup.""" def __init__(self, sparse: dict, grid: tuple[int, int]) -> None: self._scratch = np.zeros(grid, dtype=np.float32) self._last = np.empty(0, dtype=np.intp) self.indices = [] self.values = [] self.peaks = np.zeros(len(sparse["idx"]), dtype=np.intp) self.maxima = np.zeros(len(sparse["idx"]), dtype=np.float32) for u, (indices, values) in enumerate(zip(sparse["idx"], sparse["val"])): # Dense scatter keeps the last occurrence of a repeated cell. if len(set(indices)) != len(indices): cells = dict(zip(indices, values)) indices, values = list(cells), list(cells.values()) ix = np.asarray(indices, dtype=np.intp) mass = np.asarray(values, dtype=np.float32) self.indices.append(ix) self.values.append(mass) lengths = np.asarray([len(v) for v in self.values], dtype=np.intp) valid = np.flatnonzero(lengths) if len(valid): mass = np.concatenate(self.values) indices = np.concatenate(self.indices) starts = np.r_[0, np.cumsum(lengths[valid][:-1])] maxima = np.maximum.reduceat(mass, starts) if not np.isfinite(maxima).all(): raise ValueError("Sparse word attention must have a finite maximum") # Resolve float32 ties by the first cell in dense grid order. candidates = np.where( mass == np.repeat(maxima, lengths[valid]), indices, grid[0] * grid[1] ) peaks = np.minimum.reduceat(candidates, starts) positive = maxima > 0 self.maxima[valid[positive]] = maxima[positive] self.peaks[valid[positive]] = peaks[positive] def __getitem__(self, unit: int) -> np.ndarray: self._scratch.flat[self._last] = 0 self._scratch.flat[self.indices[unit]] = self.values[unit] self._last = self.indices[unit] return self._scratch _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: """llamacloud-bench / 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 = element_text(answer, el["start"], el["end"]) if el.get("close_table"): md += "" 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, } def join_paragraph_segments(answer: str, items: list[dict]) -> list[dict]: """Keep transcript paragraphs as logical items with indexed spatial segments. Adjacent text fragments must exactly reconstruct one original paragraph. Segment indices are inclusive offsets in the reconstructed Markdown, while boxes retain the page coordinate frame supplied by the caller. """ paragraphs = {} for block in split_blocks(answer): if block.type == "text": markdown = element_text(answer, block.start, block.end) paragraphs["".join(markdown.split())] = markdown texts = ["".join(item["md"].split()) for item in items] result = [] index = 0 while index < len(items): item = items[index] stop = None if item["type"] == "Text" and texts[index] not in paragraphs: joined = [] # Bound the search for a paragraph crossing several columns. for end in range(index, min(index + 8, len(items))): if ( items[end]["type"] != "Text" or len(items[end]["layout_segments"]) != 1 ): break joined.append(texts[end]) if end > index and "".join(joined) in paragraphs: stop = end + 1 break if stop is None: result.append(item) index += 1 continue markdown = paragraphs["".join(texts[index:stop])] # Map the whitespace-free match back to the untouched source Markdown. # Column cuts can fall beside formatting markers, not just spaces. offsets = [offset for offset, char in enumerate(markdown) if not char.isspace()] segments = [] position = 0 for piece, text in zip(items[index:stop], texts[index:stop]): segments.append( { **piece["layout_segments"][0], "start_index": offsets[position], "end_index": offsets[position + len(text) - 1], } ) position += len(text) x = min(segment["x"] for segment in segments) y = min(segment["y"] for segment in segments) x1 = max(segment["x"] + segment["w"] for segment in segments) y1 = max(segment["y"] + segment["h"] for segment in segments) result.append( { **item, "md": markdown, "value": markdown, "bbox": {**item["bbox"], "x": x, "y": y, "w": x1 - x, "h": y1 - y}, "layout_segments": segments, } ) index = stop return result