Add custom inference handler for docling-layout-heron
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153"""Custom HuggingFace Inference Endpoint handler for docling-project/docling-layout-heron.
Accepts a rendered PDF page image and returns labeled bounding boxes for alldetected layout elements (Table, Picture, Caption, Text, Formula, etc.).
Input: - Binary image (Content-Type: image/png or image/jpeg), OR - JSON: {"inputs": "<base64-encoded image>", "threshold": 0.4}
Output: [ {"score": 0.97, "label": "Table", "box": {"xmin": 88, "ymin": 651, "xmax": 525, "ymax": 721}}, {"score": 0.94, "label": "Picture", "box": {...}}, ... ]
Boxes are in pixel coordinates of the input image.To convert to PDF points: divide by the render scale (e.g. /2 for 144 DPI renders)."""
import ioimport osimport base64from typing import Any, Dict, List
import torchfrom PIL import Imagefrom transformers import RTDetrImageProcessor, RTDetrV2ForObjectDetection
# 17 layout classes — order matches docling-layout-heron label indicesCLASSES = [ "Caption", # 0 "Footnote", # 1 "Formula", # 2 "List-item", # 3 "Page-footer", # 4 "Page-header", # 5 "Picture", # 6 "Section-header", # 7 "Table", # 8 "Text", # 9 "Title", # 10 "Document Index", # 11 "Code", # 12 "Checkbox-Selected", # 13 "Checkbox-Unselected", # 14 "Form", # 15 "Key-Value Region", # 16]
# The layout model to load — loaded from HF hub since this is a handler-only repoMODEL_ID = "docling-project/docling-layout-heron"
class EndpointHandler: def __init__(self, path=""): """ Called once at endpoint startup. Loads the model from the local path if weights exist there, otherwise downloads from docling-project/docling-layout-heron on the Hub. """ # Use local weights if this repo contains them, otherwise pull from hub config_path = os.path.join(path, "config.json") if path else "" model_source = path if (path and os.path.isfile(config_path)) else MODEL_ID
print(f"[handler] Loading model from: {model_source}") self.processor = RTDetrImageProcessor.from_pretrained(model_source) self.model = RTDetrV2ForObjectDetection.from_pretrained( model_source, torch_dtype=torch.float32 ) self.model.eval()
self.device = "cuda" if torch.cuda.is_available() else "cpu" self.model = self.model.to(self.device) print(f"[handler] Model loaded on {self.device}. Ready.")
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]: """ Called on every inference request.
Args: data: dict with keys: - "inputs": PIL.Image | bytes | str (base64) — the page image - "threshold": float (optional, default 0.4) — detection confidence cutoff
Returns: List of dicts: [{"score": float, "label": str, "box": {"xmin","ymin","xmax","ymax"}}] """ inputs = data.pop("inputs", data) threshold = float(data.pop("threshold", 0.4))
# --- Decode image from whatever format arrives --- if isinstance(inputs, Image.Image): image = inputs.convert("RGB")
elif isinstance(inputs, bytes): image = Image.open(io.BytesIO(inputs)).convert("RGB")
elif isinstance(inputs, str): # Base64-encoded image string # Strip data URI prefix if present (e.g. "data:image/png;base64,...") if "," in inputs: inputs = inputs.split(",", 1)[1] image_bytes = base64.b64decode(inputs) image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
else: raise ValueError( f"Unsupported input type: {type(inputs)}. " "Expected PIL.Image, bytes, or base64 string." )
# --- Run inference --- model_inputs = self.processor(images=[image], return_tensors="pt") model_inputs = {k: v.to(self.device) for k, v in model_inputs.items()}
with torch.no_grad(): outputs = self.model(**model_inputs)
# Post-process: convert raw outputs to boxes + labels + scores results = self.processor.post_process_object_detection( outputs, target_sizes=torch.tensor([image.size[::-1]]), # (height, width) threshold=threshold, )[0]
# --- Build response --- detections = [] for score, label_id, box in zip( results["scores"], results["labels"], results["boxes"] ): label_idx = label_id.item() label_name = ( CLASSES[label_idx] if label_idx < len(CLASSES) else f"class_{label_idx}" ) box_vals = [round(v, 2) for v in box.tolist()] detections.append( { "score": round(score.item(), 4), "label": label_name, "box": { "xmin": box_vals[0], "ymin": box_vals[1], "xmax": box_vals[2], "ymax": box_vals[3], }, } )
# Sort by score descending for readability detections.sort(key=lambda x: x["score"], reverse=True) return detectionshandler.pyAdded+153