# 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. """Region-first layout: a layout detector's regions are the items, and OCRia-1's answer is distributed into them. Per page: 1. Every word of the answer gets a position: its PDF word box when the page has a text layer (align.py), else the ink blob its attention points at (boxes.Page.snap_word). 2. A word goes to the smallest non-picture region holding its centre; a word with no position, or outside every region, takes the region of the word before it in the same block (else the next one). Each region's text is its words in answer order, one block's words kept together. 3. An image reference goes to the Picture or Table region under its attention box. A table goes to the Table region holding most of its words (else the Picture region); with neither, the table gets its own box around its words. 4. Regions that get no text are dropped, except pictures. Pictures scoring under 0.6 are dropped first, and of a Picture and a Table region with IoU >= 0.5 only the higher-scoring one is kept. 5. Elements none of whose words reach a region keep their attention box. Finally, of two items whose boxes overlap at IoU >= 0.5, the one with less text is dropped, and image references are removed from text items. Boxes are pixels of the page image, like the detector's regions and the word boxes. """ from __future__ import annotations import re import numpy as np from .align import unit_boxes_multi from .blocks import split_blocks from .boxes import Page from .ground import _FURN_TAG, boxes_from_maps, units_for from .regions import PICTURE, TABLE, clean_regions from .words import norm MIN_SCORE = 0.35 # detections below this are ignored PICTURE_MIN_SCORE = 0.6 # pictures need more (most low-score pictures duplicate a table, a chart or an icon) PAIR_IOU = 0.5 # a Picture and a Table region this close are one region TABLE_SHARE = 0.3 # a table goes to the Table/Picture region holding at least this share of its words # detector label -> (item type, segment label), Docling label names TYPE = {"text": "Text", "section_header": "Section-header", "list_item": "List-item", "picture": "Picture", "page_header": "Page-header", "page_footer": "Page-footer", "caption": "Caption", "footnote": "Footnote", "table": "Table", "formula": "Formula", "title": "Title", "code": "Code", "document_index": "Document Index", "form": "Form", "key_value_region": "Key-Value Region"} SEG = {"Section-header": "paragraph_title", "Title": "doc_title", "Picture": "image", "Table": "table", "Page-header": "header", "Page-footer": "footer"} EL_TYPE = {"text": "Text", "heading": "Section-header", "table": "Table", "image": "Picture", "header": "Page-header", "footer": "Page-footer", "list": "List-item", "code": "Code", "page_number": "Page-footer"} _IMAGE_REF = re.compile(r"[ \t]*!\[[^\]]*\](\([^)]*\))?[ \t]*") def _ov(a, b): 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])) aa, ab = max(1e-9, (a[2] - a[0]) * (a[3] - a[1])), max(1e-9, (b[2] - b[0]) * (b[3] - b[1])) return i / (aa + ab - i) def tidy_regions(regs: list[dict]) -> list[dict]: """Of a Picture and a Table region with IoU >= PAIR_IOU keep the higher-scoring one; drop weak pictures.""" drop = set() by_score = sorted(range(len(regs)), key=lambda j: -regs[j]["score"]) for a in by_score: if a in drop: continue la, ba = regs[a]["label"], regs[a]["box"] for b in by_score: if b == a or b in drop: continue lb = regs[b]["label"] if {la, lb} <= PICTURE | TABLE and (la in TABLE) != (lb in TABLE) and _ov(ba, regs[b]["box"]) >= PAIR_IOU: drop.add(b) return [r for j, r in enumerate(regs) if j not in drop and (r["label"] not in PICTURE or r["score"] >= PICTURE_MIN_SCORE)] def _table_region(words, regs, R): ws = [w for w in words if w is not None] if not ws: return None for kinds in (TABLE, PICTURE): cnt = [(sum(R[j][0] <= (w[0] + w[2]) / 2 <= R[j][2] and R[j][1] <= (w[1] + w[3]) / 2 <= R[j][3] for w in ws), j) for j in range(len(R)) if regs[j]["label"] in kinds] if cnt and max(cnt)[0] >= TABLE_SHARE * len(ws): return max(cnt)[1] return None def _dedupe(out_items): """Two items whose boxes overlap at IoU >= 0.5 are one element: the one with more text keeps it.""" order = sorted(range(len(out_items)), key=lambda k: -len(out_items[k][1]["md"])) keep, gone = [], set() for k in order: if any(_ov(out_items[k][1]["box"], out_items[h][1]["box"]) >= 0.5 for h in keep): gone.add(k) else: keep.append(k) return [x for k, x in enumerate(out_items) if k not in gone] def page_words(image, answer, blocks, units, per_block, maps, grid, has, words=None) -> list[dict]: """Per block: its type, span, markdown, attention box, and (for non-image blocks) each word's box and offset.""" page = Page(np.asarray(image.convert("RGB")), grid) base = boxes_from_maps(image, answer, blocks, units, per_block, maps, grid, has, page=page) # attention-only boxes pdfbox = unit_boxes_multi(answer, units, words) if words else {} el_by_span = {(e["start"], e["end"]): e for e in base["elements"]} out = [] for b, idx in zip(blocks, per_block): el = el_by_span.get((b.start, b.end)) f = {"type": b.type, "start": b.start, "end": b.end, "md": _FURN_TAG.sub("", answer[b.start:b.end]).strip(), "box": el["box"] if el else None} if b.type != "image": ws, starts = [], [] for u in idx: w = pdfbox.get(u) if w is None and has[u]: w = page.snap_word(maps[u], len(norm(answer[units[u][0]:units[u][1]]))) ws.append(w) starts.append(units[u][0]) f["words"], f["starts"] = ws, starts out.append(f) return out def place(answer: str, blocks_info: list[dict], detections: list[dict]) -> list[dict]: """Region-first items [{type, label, md, box, start}] from `page_words` output and detector regions.""" regs = tidy_regions(clean_regions(detections, MIN_SCORE)) R = [r["box"] for r in regs] area = [(r[2] - r[0]) * (r[3] - r[1]) for r in R] def region_of(b): cx, cy = (b[0] + b[2]) / 2, (b[1] + b[3]) / 2 hold = [j for j, r in enumerate(R) if r[0] <= cx <= r[2] and r[1] <= cy <= r[3] and regs[j]["label"] not in PICTURE] return min(hold, key=lambda j: area[j]) if hold else None texts = {j: [] for j in range(len(R))} # region -> [(answer offset, md)] leftovers = [] # (element type, md, attention box) for b in blocks_info: md = b["md"] if b["type"] == "image": bx = b["box"] cand = [(j, max(0.0, min(bx[2], R[j][2]) - max(bx[0], R[j][0])) * max(0.0, min(bx[3], R[j][3]) - max(bx[1], R[j][1])) / max(1e-9, min(area[j], (bx[2] - bx[0]) * (bx[3] - bx[1])))) for j in range(len(R)) if regs[j]["label"] in PICTURE | TABLE] if bx else [] cand = [c for c in cand if c[1] >= 0.5] if cand: texts[max(cand, key=lambda c: c[1])[0]].append((b["start"], md)) elif bx: leftovers.append(("image", md, bx)) continue ws = [region_of(w) if w is not None else None for w in b["words"]] last = None for k in range(len(ws)): # words without a region: the previous word's, else the next one's if ws[k] is None: ws[k] = last last = ws[k] nxt = None for k in range(len(ws) - 1, -1, -1): if ws[k] is None: ws[k] = nxt nxt = ws[k] if not ws or all(w is None for w in ws): if b["box"]: leftovers.append((b["type"], md, b["box"])) continue if b["type"] == "table": tj = _table_region(b["words"], regs, R) bw = [w for w in b["words"] if w is not None] if tj is None and bw: # no Table/Picture region: the table's own words give its box h = sorted(w[3] - w[1] for w in bw)[len(bw) // 2] * 0.3 box = [min(w[0] for w in bw) - h, min(w[1] for w in bw) - h, max(w[2] for w in bw) + h, max(w[3] for w in bw) + h] regs.append({"label": "table", "score": 0.0, "box": box}) R.append(box) area.append((box[2] - box[0]) * (box[3] - box[1])) texts[len(R) - 1] = [(b["start"], md)] continue texts[tj if tj is not None else max(set(ws), key=ws.count)].append((b["start"], md)) continue starts = b["starts"] run_start = 0 # contiguous runs of words per region keep their own markdown slice for k in range(1, len(ws) + 1): if k == len(ws) or ws[k] != ws[run_start]: s = starts[run_start] if run_start else b["start"] e = starts[k] if k < len(ws) else b["end"] texts[ws[run_start]].append((s, _FURN_TAG.sub("", answer[s:e]).strip())) run_start = k def item(t, md, bx): if t != "Picture": # an image reference's alt text is not page text md = _IMAGE_REF.sub(" ", md).strip() return {"type": t, "label": SEG.get(t, "text"), "md": md, "box": [round(float(v), 1) for v in bx]} out = [] for j, r in enumerate(regs): t = TYPE.get(r["label"], "Text") parts = [m for _, m in sorted(texts[j]) if m] if not parts and r["label"] not in PICTURE: continue out.append((min((o for o, _ in texts[j]), default=10 ** 9), item(t, "\n\n".join(parts), R[j]))) for t, md, bx in leftovers: out.append((10 ** 9, item(EL_TYPE.get(t, "Text"), md, bx))) out.sort(key=lambda x: x[0]) return [{**it, "start": off if off < 10 ** 9 else None} for off, it in _dedupe(out)] def ground_layout(grounder, image, answer: str, detector=None, words: list[dict] | None = None, detections: list[dict] | None = None, *, method: str = "accurate-layout", fast_backend=None, attention: dict | None = None) -> dict: """{width, height, items: [{type, label, md, box, start}]} for one page; `box` is [x0, y0, x1, y1] in pixels of `image`. `detector` (detector.Detector) or precomputed `detections` give the regions; `words` (pdf.render_pdf_page) give exact word positions on pages with a text layer. With neither detector nor detections the items are the attention-only elements.""" if method == "fast-layout": if fast_backend is None: raise ValueError("fast-layout requires an initialized FastLayout backend") if detector is not None or detections is not None or words is not None: raise ValueError("fast-layout accepts attention only; omit detector, detections, and words") from parse_rl_utils.ocria_attention_grounding.hf_adapter import ground_fast_layout return ground_fast_layout(grounder, image, answer, backend=fast_backend, attention=attention) if method != "accurate-layout": raise ValueError(f"Unknown layout method: {method}") if attention is not None or fast_backend is not None: raise ValueError("attention and fast_backend require method='fast-layout'") w, h = image.size blocks = split_blocks(answer) units, per_block = units_for(answer, blocks) if not units: return {"width": w, "height": h, "items": []} maps, grid, has = grounder.unit_maps(image, answer, units) if detections is None and detector is not None: detections = detector(image) if detections is None: base = boxes_from_maps(image, answer, blocks, units, per_block, maps, grid, has) items = [{"type": EL_TYPE.get(e["type"], "Text"), "label": SEG.get(EL_TYPE.get(e["type"], "Text"), "text"), "md": _FURN_TAG.sub("", answer[e["start"]:e["end"]]).strip(), "box": e["box"], "start": e["start"]} for e in base["elements"] if e["box"] is not None] return {"width": w, "height": h, "items": items} info = page_words(image, answer, blocks, units, per_block, maps, grid, has, words) return {"width": w, "height": h, "items": place(answer, info, detections)} def to_layout_items_page(page: dict, scale: float = 1.0, page_md: str = "") -> dict: """`ground_layout` output as a ParseBench `layout_pages` entry (x, y, w, h boxes in pixels x `scale`; use 72 / DPI for PDF points).""" items = [] for it in page["items"]: x0, y0, x1, y1 = (v * scale for v in it["box"]) if x1 <= x0 or y1 <= y0: continue seg = {"x": x0, "y": y0, "w": x1 - x0, "h": y1 - y0, "label": it["label"]} segments = [seg] if "layout_segments" in it: segments = [{**part, **{key: part[key] * scale for key in ("x", "y", "w", "h")}} for part in it["layout_segments"]] items.append({"type": it["type"], "md": it["md"], "value": it["md"], "bbox": dict(seg), "layout_segments": segments}) return {"page_number": 1, "width": page["width"] * scale, "height": page["height"] * scale, "md": page_md, "items": items}