# 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. """Reusable pixel-free layout extraction from precomputed word attention. Frozen predictors are loaded once per instance. Capture coordinates and output boxes use the original image pixel frame; PDF frame conversion belongs to the caller. """ from pathlib import Path import time from numbers import Integral import numpy as np import joblib from .navigation import constrain_sidebar_icons from .headings import ( expand_table_to_embedded_heading, merge_bold_heading_continuations, merge_heading_lines, merge_numeric_callouts, trim_paragraph_heading_overlap, ) from .pictures import ( merge_figure_tables, trim_picture_text_overlap, trim_picture_table_overlap, ) from .io import join_paragraph_segments, merge_duplicate_text, to_layout_page from .learned import ground_cached def finalize_layout(answer: str, page: dict) -> dict: """Apply the retained checkpoint's geometry rules in their evaluation order.""" page["items"] = merge_duplicate_text(merge_heading_lines(page["items"])) trim_picture_text_overlap(page["items"]) page["items"] = merge_numeric_callouts(page["items"]) trim_paragraph_heading_overlap(page["items"]) page["items"] = join_paragraph_segments(answer, page["items"]) page["items"] = merge_figure_tables(page["items"]) page["items"] = merge_bold_heading_continuations(answer, page["items"]) page["items"] = constrain_sidebar_icons( page["items"], page["width"], page["height"] ) trim_picture_table_overlap(page["items"]) expand_table_to_embedded_heading(page["items"]) return page def validate_capture(attention: dict) -> None: """Check external sparse coordinates before indexing arrays or native buffers.""" dimensions = np.asarray([attention["width"], attention["height"]], dtype=float) if not np.isfinite(dimensions).all() or (dimensions <= 0).any(): raise ValueError("Page dimensions must be finite and positive") grid = attention["grid"] if len(grid) != 2 or any( not isinstance(n, Integral) or isinstance(n, bool) or n <= 0 for n in grid ): raise ValueError("Attention grid must contain two positive integers") sparse = attention["sparse_maps"] if not len(sparse["idx"]) == len(sparse["val"]) == len(sparse["has"]): raise ValueError("Sparse indices, values, and validity rows must align") flags = np.asarray(sparse["has"]) if flags.ndim != 1 or (len(flags) and flags.dtype.kind != "b"): raise ValueError("Attention validity flags must be boolean") cells = int(grid[0]) * int(grid[1]) for indices, values in zip(sparse["idx"], sparse["val"], strict=True): if len(indices) != len(values): raise ValueError("Each sparse index must have one attention value") if not len(indices): continue indices = np.asarray(indices) values = np.asarray(values, dtype=np.float32) if ( indices.ndim != 1 or indices.dtype.kind not in "iu" or (indices < 0).any() or (indices >= cells).any() ): raise ValueError( "Sparse indices must be integers inside the attention grid" ) if values.ndim != 1 or not np.isfinite(values).all() or (values < 0).any(): raise ValueError("Sparse attention values must be finite and nonnegative") class FastLayout: """A reusable backend with explicit, trusted frozen predictor artifacts.""" def __init__( self, *, words: Path, pictures: Path, regions: Path, tables: Path, peaks: Path ) -> None: self.words = joblib.load(words) self.pictures = joblib.load(pictures) self.regions = joblib.load(regions) self.tables = joblib.load(tables) self.peaks = joblib.load(peaks) def layout_page(self, *, answer: str, attention: dict) -> dict: """Return a ParseBench page in pixels, including spatial text segments. Attention uses the existing cache contract: width, height, grid [h,w], sparse_maps {idx, val, has}, one row per transcript attention unit. This method performs no image, PDF, network, or model-inference I/O. """ validate_capture(attention) result = ground_cached( answer, attention, self.words, picture_model=self.pictures, with_extended_context=True, region_models=self.regions, table_model=self.tables, with_region_context=True, peak_model=self.peaks, ) page = to_layout_page( answer, result["elements"], attention["width"], attention["height"] ) return finalize_layout(answer, page) def __call__(self, *, answer: str, attention: dict) -> dict: """Return the public OCRia item schema, retaining detailed text segments.""" started = time.perf_counter() page = self.layout_page(answer=answer, attention=attention) items = [] for item in page["items"]: box = item["bbox"] items.append( { "type": item["type"], "label": box["label"], "md": item["md"], "box": [ box["x"], box["y"], box["x"] + box["w"], box["y"] + box["h"], ], "layout_segments": item["layout_segments"], } ) return { "width": page["width"], "height": page["height"], "items": items, "attention_source": "precomputed", "timings_ms": { "attention_capture": 0.0, "layout_postprocessing": (time.perf_counter() - started) * 1000, }, }