File size: 5,462 Bytes
d6c389a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""
Custom HuggingFace Inference Endpoint handler for docling-project/docling-layout-heron.

Accepts a rendered PDF page image and returns labeled bounding boxes for all
detected 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 io
import os
import base64
from typing import Any, Dict, List

import torch
from PIL import Image
from transformers import RTDetrImageProcessor, RTDetrV2ForObjectDetection

# 17 layout classes — order matches docling-layout-heron label indices
CLASSES = [
    "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 repo
MODEL_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 detections