Forrest Wargo commited on
Commit
eb3bdf4
·
1 Parent(s): 5dca6b2
Files changed (1) hide show
  1. handler.py +47 -155
handler.py CHANGED
@@ -21,29 +21,19 @@ def _b64_to_pil(data_url: str) -> Image.Image:
21
 
22
 
23
  class EndpointHandler:
24
- """HF Inference Endpoint handler for Moondream3 Preview.
25
 
26
- Input contract (OpenAI-style):
27
  {
28
- "messages": [
29
- {
30
- "role": "user",
31
- "content": [
32
- { "type": "image_url", "image_url": { "url": "data:<mime>;base64,<...>" } },
33
- { "type": "text", "text": "<object or question>" }
34
- ]
35
- }
36
- ],
37
- "task": "point" | "detect" | "query" // optional, default "point"
38
- "max_objects": <int> // optional for detect
39
- "reasoning": <bool> // optional for query
40
  }
41
 
42
- Output:
43
- - task=="point": { points: [{x, y}], width, height }
44
- - task=="detect": { objects: [{x_min, y_min, x_max, y_max}], width, height }
45
- - task=="query": { answer: "...", width?, height? }
46
- Coordinates are normalized (0-1). width/height echo source image dims for convenience.
47
  """
48
 
49
  def __init__(self, path: str = "") -> None:
@@ -105,33 +95,16 @@ class EndpointHandler:
105
  except Exception:
106
  pass
107
 
108
- messages = data.get("messages")
109
- task = str(data.get("task", "point")).lower()
110
- reasoning = bool(data.get("reasoning", True))
111
- max_objects = data.get("max_objects")
112
  prioritize_accuracy = bool(data.get("prioritize_accuracy", True))
113
 
114
- if not messages:
115
- return {"error": "Provide 'messages' with user image and text"}
116
-
117
- # Extract first user image and text
118
- image_data_url: Optional[str] = None
119
- text_piece: Optional[str] = None
120
- for msg in messages:
121
- if msg.get("role") != "user":
122
- return {"error": "Only user messages are supported."}
123
- for part in msg.get("content", []):
124
- if part.get("type") == "image_url" and image_data_url is None:
125
- image_data_url = part.get("image_url", {}).get("url")
126
- elif part.get("type") == "text" and text_piece is None:
127
- text_piece = part.get("text")
128
- if image_data_url and text_piece:
129
- break
130
-
131
- if not image_data_url or not isinstance(image_data_url, str) or not image_data_url.startswith("data:"):
132
- return {"error": "image_url.url must be a data URL (data:...)"}
133
  if not text_piece:
134
- return {"error": "Content must include text."}
135
 
136
  # Decode for dimensions and pass PIL to model
137
  try:
@@ -147,44 +120,32 @@ class EndpointHandler:
147
  except Exception:
148
  pass
149
 
150
- # Run selected skill
151
  try:
152
- if task == "point":
153
- if prioritize_accuracy:
154
- flipped = pil.transpose(Image.FLIP_LEFT_RIGHT)
155
- res_orig = self.model.point(pil, text_piece)
156
- res_flip = self.model.point(flipped, text_piece)
157
- points = self._tta_points(res_orig.get("points", []), res_flip.get("points", []))
158
- out: Dict[str, Any] = {"points": points}
159
- else:
160
- result = self.model.point(pil, text_piece)
161
- out = {"points": result.get("points", [])}
162
- elif task == "detect":
163
- settings = {"max_objects": int(max_objects)} if max_objects else None
164
- if prioritize_accuracy:
165
- flipped = pil.transpose(Image.FLIP_LEFT_RIGHT)
166
- res_orig = self.model.detect(pil, text_piece, settings=settings)
167
- res_flip = self.model.detect(flipped, text_piece, settings=settings)
168
- objects = self._tta_boxes(res_orig.get("objects", []), res_flip.get("objects", []))
169
- out = {"objects": objects}
170
- else:
171
- result = self.model.detect(pil, text_piece, settings=settings)
172
- out = {"objects": result.get("objects", [])}
173
- elif task == "query":
174
- result = self.model.query(pil, question=text_piece, reasoning=reasoning, stream=False)
175
- out = {"answer": result.get("answer", "")}
176
  else:
177
- return {"error": f"Unsupported task '{task}'. Use 'point', 'detect', or 'query'."}
 
178
  except Exception as e:
179
  return {"error": f"Model inference failed: {e}"}
180
 
181
- if width and height:
182
- out.update({"width": width, "height": height})
183
- out.update({"task": task})
184
-
185
  # Print prompt, dimensions, and raw output
 
 
 
 
 
 
 
186
  try:
187
- print(f"[moondream-endpoint] Prompt: {text_piece}")
 
 
188
  except Exception:
189
  pass
190
  if width and height:
@@ -197,15 +158,17 @@ class EndpointHandler:
197
  except Exception:
198
  pass
199
 
200
- # Ensure strict shape for point task: include points[] and raw
201
- if task == "point":
202
- # Ensure points array exists
203
- if not isinstance(out.get("points"), list) or not out["points"]:
204
- return {"error": "No points returned"}
205
- # Attach raw for strict client and drop width/height from payload
206
- return {"points": out["points"], "raw": out}
207
-
208
- return out
 
 
209
 
210
  @staticmethod
211
  def _flip_point(p: Dict[str, Any]) -> Dict[str, float]:
@@ -244,77 +207,6 @@ class EndpointHandler:
244
  merged = list(points_a) + unflipped_b
245
  return cls._deduplicate_and_average_points(merged)
246
 
247
- @staticmethod
248
- def _flip_box(b: Dict[str, Any]) -> Dict[str, float]:
249
- xmin = float(b.get("x_min", 0.0))
250
- xmax = float(b.get("x_max", 0.0))
251
- ymin = float(b.get("y_min", 0.0))
252
- ymax = float(b.get("y_max", 0.0))
253
- nxmin = 1.0 - xmax
254
- nxmax = 1.0 - xmin
255
- nxmin, nxmax = max(0.0, min(1.0, nxmin)), max(0.0, min(1.0, nxmax))
256
- ymin, ymax = max(0.0, min(1.0, ymin)), max(0.0, min(1.0, ymax))
257
- if nxmin > nxmax:
258
- nxmin, nxmax = nxmax, nxmin
259
- return {"x_min": nxmin, "y_min": ymin, "x_max": nxmax, "y_max": ymax}
260
-
261
- @staticmethod
262
- def _iou(b1: Dict[str, float], b2: Dict[str, float]) -> float:
263
- x1 = max(b1["x_min"], b2["x_min"])
264
- y1 = max(b1["y_min"], b2["y_min"])
265
- x2 = min(b1["x_max"], b2["x_max"])
266
- y2 = min(b1["y_max"], b2["y_max"])
267
- inter_w = max(0.0, x2 - x1)
268
- inter_h = max(0.0, y2 - y1)
269
- inter = inter_w * inter_h
270
- a1 = max(0.0, b1["x_max"] - b1["x_min"]) * max(0.0, b1["y_max"] - b1["y_min"])
271
- a2 = max(0.0, b2["x_max"] - b2["x_min"]) * max(0.0, b2["y_max"] - b2["y_min"])
272
- denom = a1 + a2 - inter
273
- return inter / denom if denom > 0 else 0.0
274
-
275
- @classmethod
276
- def _merge_boxes_with_nms(cls, boxes: List[Dict[str, float]], iou_threshold: float = 0.5) -> List[Dict[str, float]]:
277
- merged: List[Dict[str, float]] = []
278
- used = [False] * len(boxes)
279
- for i in range(len(boxes)):
280
- if used[i]:
281
- continue
282
- cluster = [boxes[i]]
283
- used[i] = True
284
- for j in range(i + 1, len(boxes)):
285
- if used[j]:
286
- continue
287
- if cls._iou(boxes[i], boxes[j]) >= iou_threshold:
288
- used[j] = True
289
- cluster.append(boxes[j])
290
- # Average cluster
291
- n = float(len(cluster))
292
- avg = {
293
- "x_min": sum(b["x_min"] for b in cluster) / n,
294
- "y_min": sum(b["y_min"] for b in cluster) / n,
295
- "x_max": sum(b["x_max"] for b in cluster) / n,
296
- "y_max": sum(b["y_max"] for b in cluster) / n,
297
- }
298
- # Clamp
299
- avg["x_min"] = max(0.0, min(1.0, avg["x_min"]))
300
- avg["y_min"] = max(0.0, min(1.0, avg["y_min"]))
301
- avg["x_max"] = max(0.0, min(1.0, avg["x_max"]))
302
- avg["y_max"] = max(0.0, min(1.0, avg["y_max"]))
303
- merged.append(avg)
304
- return merged
305
-
306
- @classmethod
307
- def _tta_boxes(cls, boxes_a: List[Dict[str, Any]], boxes_b_flipped: List[Dict[str, Any]]) -> List[Dict[str, float]]:
308
- unflipped_b = [cls._flip_box(b) for b in boxes_b_flipped]
309
- combined = [
310
- {
311
- "x_min": float(b.get("x_min", 0.0)),
312
- "y_min": float(b.get("y_min", 0.0)),
313
- "x_max": float(b.get("x_max", 0.0)),
314
- "y_max": float(b.get("y_max", 0.0)),
315
- }
316
- for b in (list(boxes_a) + unflipped_b)
317
- ]
318
- return cls._merge_boxes_with_nms(combined, iou_threshold=0.5)
319
 
320
 
 
21
 
22
 
23
  class EndpointHandler:
24
+ """HF Inference Endpoint handler for Moondream3 Preview (point only).
25
 
26
+ Input contract (OpenAI-style, simplified):
27
  {
28
+ "system": "<system prompt>",
29
+ "user": "<user prompt>",
30
+ "image": "data:<mime>;base64,<...>",
31
+ "prioritize_accuracy": true | false // optional (default true)
 
 
 
 
 
 
 
 
32
  }
33
 
34
+ Output (point only):
35
+ { points: [{x, y}], raw: <debug payload> }
36
+ Coordinates are normalized [0,1].
 
 
37
  """
38
 
39
  def __init__(self, path: str = "") -> None:
 
95
  except Exception:
96
  pass
97
 
98
+ # New input contract: expect 'system', 'user', 'image' (point task only)
 
 
 
99
  prioritize_accuracy = bool(data.get("prioritize_accuracy", True))
100
 
101
+ system_prompt: Optional[str] = data.get("system")
102
+ text_piece: Optional[str] = data.get("user")
103
+ image_data_url: Optional[str] = data.get("image")
104
+ if not isinstance(image_data_url, str) or not image_data_url.startswith("data:"):
105
+ return {"error": "image must be a data URL (data:...)"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  if not text_piece:
107
+ return {"error": "user text must be provided"}
108
 
109
  # Decode for dimensions and pass PIL to model
110
  try:
 
120
  except Exception:
121
  pass
122
 
123
+ # Point-only inference
124
  try:
125
+ if prioritize_accuracy:
126
+ flipped = pil.transpose(Image.FLIP_LEFT_RIGHT)
127
+ res_orig = self.model.point(pil, text_piece)
128
+ res_flip = self.model.point(flipped, text_piece)
129
+ points = self._tta_points(res_orig.get("points", []), res_flip.get("points", []))
130
+ out: Dict[str, Any] = {"points": points}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  else:
132
+ result = self.model.point(pil, text_piece)
133
+ out = {"points": result.get("points", [])}
134
  except Exception as e:
135
  return {"error": f"Model inference failed: {e}"}
136
 
 
 
 
 
137
  # Print prompt, dimensions, and raw output
138
+ # Log prompts and timings
139
+ def _se(s: Optional[str], n: int = 120):
140
+ if not s:
141
+ return ("", "")
142
+ return (s[:n], s[-n:] if len(s) > n else s)
143
+ sys_start, sys_end = _se(system_prompt)
144
+ usr_start, usr_end = _se(text_piece)
145
  try:
146
+ print(f"[moondream-endpoint] System prompt (start): {sys_start}")
147
+ print(f"[moondream-endpoint] System prompt (end): {sys_end}")
148
+ print(f"[moondream-endpoint] User prompt (full): {text_piece}")
149
  except Exception:
150
  pass
151
  if width and height:
 
158
  except Exception:
159
  pass
160
 
161
+ # Ensure points array exists and normalized [0,1]
162
+ if not isinstance(out.get("points"), list) or not out["points"]:
163
+ return {"error": "No points returned"}
164
+ def _to_01(p):
165
+ x = float(p.get("x", 0.0))
166
+ y = float(p.get("y", 0.0))
167
+ if x > 1.0 or y > 1.0:
168
+ return {"x": x / 1000.0, "y": y / 1000.0}
169
+ return {"x": x, "y": y}
170
+ points_01 = [_to_01(p) for p in out["points"]]
171
+ return {"points": points_01, "raw": out}
172
 
173
  @staticmethod
174
  def _flip_point(p: Dict[str, Any]) -> Dict[str, float]:
 
207
  merged = list(points_a) + unflipped_b
208
  return cls._deduplicate_and_average_points(merged)
209
 
210
+ # Box-related utilities removed (endpoint is point-only)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
 
212