# 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. """Place attention-grounded elements on layout-detector regions (element-first placement). The attention says WHICH words belong to an element and roughly where they are; a detector region says where a block of the page starts and ends. Each element takes the region(s) holding most of its words: - one region, owned by this element alone -> the region's box - one region shared with other elements -> the region's width, over this element's own words (vertically) - several regions each holding >= 25% of words -> their union (a paragraph that continues in the next column) - a table -> the Table region holding most of its words (union with its words) - an image reference -> the Picture/Table region under its attention box (IoU or holding) - no region holding any of its words -> its attention box, unchanged Picture regions no element claims become picture elements of their own (graphics the answer does not mention). Region boxes are pixels of the page image, like the element boxes. """ from __future__ import annotations PICTURE = {"picture", "chart", "figure"} TABLE = {"table"} SKIP = {"checkbox_selected", "checkbox_unselected"} def _norm(label: str) -> str: """Detector label in one spelling: Docling's "Picture" / "picture", "Checkbox-Selected" / "checkbox_selected".""" return label.lower().replace("-", "_").replace(" ", "_") def _inter(a, b) -> float: return 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])) def _area(a) -> float: return max(0.0, a[2] - a[0]) * max(0.0, a[3] - a[1]) def _holds(r, w, pad: float) -> bool: cx, cy = (w[0] + w[2]) / 2, (w[1] + w[3]) / 2 return r[0] - pad <= cx <= r[2] + pad and r[1] - pad <= cy <= r[3] + pad def clean_regions(dets: list[dict], min_score: float = 0.35) -> list[dict]: """Detections above `min_score`, minus a box mostly (>= 80%) inside a higher-scoring box of the same kind.""" keep: list[dict] = [] dets = [{**d, "label": _norm(d["label"])} for d in dets] for d in sorted((d for d in dets if d["score"] >= min_score and d["label"] not in SKIP), key=lambda d: -d["score"]): b = d["box"] if any(k["label"] == d["label"] and _inter(b, k["box"]) >= 0.8 * max(_area(b), 1e-9) for k in keep): continue keep.append(d) return keep def place_on_regions(types: list[str], words: list[list], boxes: list, regions: list[dict], line_h: float, add_unclaimed_pictures: bool = True, text_too: bool = True) -> tuple[list, list[list[float]]]: """(new boxes per element, extra picture boxes). `types[i]` is element i's block type, `words[i]` its snapped word boxes (after stray filtering), `boxes[i]` its attention box (None allowed).""" pad = 0.3 * line_h R = [r["box"] for r in regions] counts = [[sum(_holds(r, w, pad) for w in ws) for r in R] for ws in words] # region -> elements that hold words in it users: dict[int, list[int]] = {} for i, c in enumerate(counts): for j, n in enumerate(c): if n and types[i] not in ("image",): users.setdefault(j, []).append(i) out = list(boxes) claimed: set[int] = set() for i, t in enumerate(types): if t == "image": b = boxes[i] if b is None: continue cand = [(j, _inter(b, R[j]) / max(min(_area(b), _area(R[j])), 1e-9)) for j, r in enumerate(regions) if r["label"] in PICTURE | TABLE] cand = [(j, v) for j, v in cand if v >= 0.5] if cand: j = max(cand, key=lambda x: x[1])[0] out[i] = list(R[j]) claimed.add(j) continue ws, c = words[i], counts[i] n = len(ws) if not n or not any(c): continue if t == "table": tj = [j for j in range(len(R)) if regions[j]["label"] in TABLE | PICTURE and c[j]] if tj: j = max(tj, key=lambda j: c[j]) if c[j] >= 0.3 * n: r = R[j] b = boxes[i] or r out[i] = [min(r[0], b[0]), min(r[1], b[1]), max(r[2], b[2]), max(r[3], b[3])] \ if _inter(b, r) >= 0.5 * _area(b) else list(r) claimed.add(j) continue if not text_too: # visual-only mode: text keeps its attention box continue main = [j for j in range(len(R)) if c[j] >= 0.25 * n and regions[j]["label"] not in PICTURE] if not main: continue for j in main: claimed.add(j) if len(main) == 1 and len(users.get(main[0], [])) == 1: out[i] = list(R[main[0]]) continue if len(main) > 1 and all(len(users.get(j, [])) == 1 for j in main): out[i] = [min(R[j][0] for j in main), min(R[j][1] for j in main), max(R[j][2] for j in main), max(R[j][3] for j in main)] continue # shared region(s): the region's horizontal extent, the element's own words vertically inside = [w for w in ws if any(_holds(R[j], w, pad) for j in main)] if not inside: continue x0 = min(R[j][0] for j in main) x1 = max(R[j][2] for j in main) y0 = max(min(w[1] for w in inside), min(R[j][1] for j in main)) y1 = min(max(w[3] for w in inside), max(R[j][3] for j in main)) if y1 > y0: out[i] = [x0, y0, x1, y1] extra = [] if add_unclaimed_pictures: for j, r in enumerate(regions): if j in claimed or r["label"] not in PICTURE: continue if any(b is not None and _inter(b, R[j]) >= 0.5 * _area(R[j]) for b in out): continue extra.append(list(R[j])) return out, extra def ink_regions(page, kv: float = 1.0, kh: float = 1.5) -> list[dict]: """Detector-free regions from the page image alone: text blocks are the ink closed across word gaps (kh x body glyph height) and line spacing (kv x), so a paragraph is one block and a column gutter stays open; pictures are filled foreground components (the graphics an image reference snaps to). Same shape as detector output.""" import numpy as np from scipy import ndimage h = page.med_h row, col = np.ones((1, max(3, int(kh * h)) | 1), bool), np.ones((max(3, int(kv * h)) | 1, 1), bool) closed = ndimage.binary_erosion(ndimage.binary_erosion( ndimage.binary_dilation(ndimage.binary_dilation(page.ink, row), col), row), col) lab, _ = ndimage.label(closed | page.ink) out = [] for s in ndimage.find_objects(lab): if s is None: continue y0, y1, x0, x1 = s[0].start, s[0].stop, s[1].start, s[1].stop if (y1 - y0) < 0.5 * h or (x1 - x0) < h: continue out.append({"label": "text", "score": 1.0, "box": [float(x0), float(y0), float(x1), float(y1)]}) flab, fsl = page.fg_components() for s in fsl: if s is None: continue y0, y1, x0, x1 = s[0].start, s[0].stop, s[1].start, s[1].stop w_, h_ = x1 - x0, y1 - y0 if w_ < 3 * h or h_ < 3 * h or w_ * h_ > 0.6 * page.w * page.h: continue if float(page.fg[s].mean()) < 0.35 or float(page.ink[s].mean()) > 0.5: continue out.append({"label": "picture", "score": 1.0, "box": [float(x0), float(y0), float(x1), float(y1)]}) return out