# 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. """Layout regions from Docling's Heron detector (docling-project/docling-layout-heron, RT-DETRv2, Apache-2.0). Heron is a third-party model: it is downloaded from its own repository and governed by its own license (Apache-2.0), not by this repository's license. det = Detector() # cuda, else mps, else cpu regions = det(image) # [{label, score, box: [x0, y0, x1, y1]}] in pixels of `image` """ from __future__ import annotations DETECTOR = "docling-project/docling-layout-heron" class Detector: def __init__(self, model: str = DETECTOR, device: str | None = None, max_side: int = 1600): import torch from transformers import AutoImageProcessor, AutoModelForObjectDetection if device is None: device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" self.torch, self.device, self.max_side = torch, device, max_side self.proc = AutoImageProcessor.from_pretrained(model) self.model = AutoModelForObjectDetection.from_pretrained(model).to(device).eval() def __call__(self, image, threshold: float = 0.2) -> list[dict]: """Detections in pixels of `image`. The page is downscaled to <= max_side px first (Heron reads 640 x 640).""" from PIL import Image im = image.convert("RGB") w, h = im.size s = min(1.0, self.max_side / max(w, h)) if s < 1: im = im.resize((max(1, int(w * s)), max(1, int(h * s))), Image.LANCZOS) sx, sy = w / im.width, h / im.height with self.torch.no_grad(): out = self.model(**self.proc(images=[im], return_tensors="pt").to(self.device)) r = self.proc.post_process_object_detection(out, target_sizes=[(im.height, im.width)], threshold=threshold)[0] return [{"label": self.model.config.id2label[int(lab)], "score": round(float(sc), 3), "box": [round(float(b[0]) * sx, 1), round(float(b[1]) * sy, 1), round(float(b[2]) * sx, 1), round(float(b[3]) * sy, 1)]} for sc, lab, b in zip(r["scores"], r["labels"], r["boxes"])]