diffvid 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,538 @@
1
+ """Optional grounded VLM explanation layer (`--explain`, 100% Apache-2.0 compatible).
2
+
3
+ Pure-vision `rollout-diff` stays strictly in charge of DTW time sync, robot masking, spatial/object
4
+ diffing, and exact timestamps. When `--explain` is enabled, this module acts as a visual microscope
5
+ and temporal locator for a local open-weight VLM (Ollama / vLLM / Hugging Face Qwen2.5-VL):
6
+
7
+ 1. Image 1 — Clean Start & End Overview (`A Start | B Start` over `A End | B End`, zero clutter).
8
+ 2. Image 2 — B-Only 6-Frame Anomaly Filmstrip (`B 0.0s`, 4 dense frames right across rollout-diff's
9
+ flagged mid-run divergence / slowdown window, and `B end`) — keeping B visually isolated from A
10
+ so small 7B VLMs never blend A's success into B's failure and actually see drops/knocks unfold.
11
+ 3. Images 3+ — 2x Zoomed Side-by-Side Diff Crops (`A end crop | B end crop`) for each detected
12
+ `OBJECT DIFF` / `END DIFF` box, with ZERO generic `"object 1"` text hints so the VLM must
13
+ actually inspect the pixels to name every object and compare A vs B.
14
+ """
15
+ import base64
16
+ import json
17
+ import os
18
+ import re
19
+ import urllib.error
20
+ import urllib.request
21
+ from pathlib import Path
22
+
23
+ import cv2
24
+ import numpy as np
25
+
26
+ DEFAULT_HF_MODEL = "Qwen/Qwen2.5-VL-7B-Instruct"
27
+ DEFAULT_OLLAMA_MODEL = "qwen2.5vl:7b"
28
+ DEFAULT_OLLAMA_URL = "http://127.0.0.1:11434/v1"
29
+
30
+
31
+ def _default_ollama_url():
32
+ """Respect `OLLAMA_HOST` env var (e.g. `127.0.0.1:11436` or `http://127.0.0.1:11436`)."""
33
+ host = (os.environ.get("OLLAMA_HOST") or "").strip()
34
+ if not host:
35
+ return DEFAULT_OLLAMA_URL
36
+ if not host.startswith(("http://", "https://")):
37
+ host = "http://" + host
38
+ return host.rstrip("/") + "/v1"
39
+
40
+
41
+ def _urlopen(req, timeout=180):
42
+ """Open HTTP request, bypassing system proxies for loopback (127.0.0.1 / localhost)."""
43
+ url = req.full_url if hasattr(req, "full_url") else str(req)
44
+ if any(h in url for h in ("127.0.0.1", "localhost", "[::1]")):
45
+ return urllib.request.build_opener(urllib.request.ProxyHandler({})).open(req, timeout=timeout)
46
+ return urllib.request.urlopen(req, timeout=timeout)
47
+
48
+
49
+ # ------------------------------------------------------------------ 1. Visual Microscope + B-Burst Builder
50
+ def _draw_banner(img_bgr, text, bg=(22, 26, 34), fg=(240, 244, 248), scale=0.50):
51
+ h_bar = 28
52
+ bar = np.full((h_bar, img_bgr.shape[1], 3), bg, dtype=np.uint8)
53
+ safe = text.replace("\u2192", "->").replace("\u00b7", "|").replace("\u2014", "-")
54
+ cv2.putText(bar, safe[:120], (8, 19), cv2.FONT_HERSHEY_SIMPLEX, scale, fg, 1, cv2.LINE_AA)
55
+ return np.vstack([bar, img_bgr])
56
+
57
+
58
+ def _label_corner(img_bgr, text, fg=(255, 255, 255), bg=(18, 22, 28)):
59
+ out = img_bgr.copy()
60
+ (tw, th), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.50, 1)
61
+ cv2.rectangle(out, (4, 4), (tw + 14, th + 12), bg, -1)
62
+ cv2.putText(out, text, (9, th + 8), cv2.FONT_HERSHEY_SIMPLEX, 0.50, fg, 1, cv2.LINE_AA)
63
+ return out
64
+
65
+
66
+ def _build_overview_image(fa, fb, fps, width=384):
67
+ """Image 1: Clean 2x2 overview — top row START (A | B), bottom row END (A | B)."""
68
+ ha, wa = fa[0].shape[:2]
69
+ pw = int(width)
70
+ ph = max(64, int(round(ha * pw / max(wa, 1))))
71
+
72
+ def _tile(im_rgb, lbl, fg):
73
+ bgr = cv2.resize(cv2.cvtColor(im_rgb, cv2.COLOR_RGB2BGR), (pw, ph), interpolation=cv2.INTER_AREA)
74
+ return _label_corner(bgr, lbl, fg=fg)
75
+
76
+ vgap = np.full((ph, 4, 3), (50, 58, 70), dtype=np.uint8)
77
+ row_st = np.hstack([
78
+ _tile(fa[0], "A START (0.0s)", (120, 235, 140)),
79
+ vgap,
80
+ _tile(fb[0], "B START (0.0s)", (110, 195, 255)),
81
+ ])
82
+ row_en = np.hstack([
83
+ _tile(fa[-1], f"A END ({(len(fa) - 1) / fps:.1f}s)", (120, 235, 140)),
84
+ vgap,
85
+ _tile(fb[-1], f"B END ({(len(fb) - 1) / fps:.1f}s)", (110, 195, 255)),
86
+ ])
87
+ hgap = np.full((4, row_st.shape[1], 3), (50, 58, 70), dtype=np.uint8)
88
+ grid = np.vstack([row_st, hgap, row_en])
89
+ panel = _draw_banner(grid, "IMAGE 1: OVERVIEW — TOP: START (A left | B right) | BOTTOM: END (A left | B right)")
90
+ return cv2.cvtColor(panel, cv2.COLOR_BGR2RGB)
91
+
92
+
93
+ def _pick_b_burst_frames(res, fb, shown):
94
+ """Select 6 chronological frame indices of ONLY Video B densely covering the flagged anomaly window."""
95
+ n_b = len(fb)
96
+ if n_b <= 6:
97
+ return list(range(n_b))
98
+ sb, eb = res.get("trim_b", (0, n_b))
99
+ sb = max(0, min(n_b - 1, int(sb)))
100
+ eb = max(sb + 1, min(n_b, int(eb)))
101
+ path = res.get("path") or []
102
+
103
+ # Find the highest-priority mid-run anomaly window in B (MID-RUN DIFF / ARM DIFF / largest MORE TIME / SKIPPED)
104
+ win = None
105
+ best_prio = -1.0
106
+ for it in (shown or []):
107
+ if it.get("info"):
108
+ continue
109
+ k = it.get("kind")
110
+ b_span = it.get("b")
111
+ if not b_span or len(b_span) != 2:
112
+ if path and it.get("step") is not None:
113
+ s0 = max(0, min(len(path) - 1, int(it["step"])))
114
+ s1 = max(s0, min(len(path) - 1, int(it.get("end_step", s0))))
115
+ b_span = [path[s0][1], path[s1][1]]
116
+ else:
117
+ continue
118
+ b0 = max(0, min(n_b - 1, int(b_span[0]) + sb))
119
+ b1 = max(b0, min(n_b - 1, int(b_span[1]) + sb))
120
+ if k in ("MID-RUN DIFF", "ARM DIFF"):
121
+ prio = 3.0 + float(it.get("score", 0.5))
122
+ elif k == "MORE TIME" and float(it.get("seconds", 0.0)) >= 1.5:
123
+ prio = 2.0 + min(2.0, float(it.get("seconds", 0.0)) / 3.0)
124
+ elif k == "SKIPPED":
125
+ prio = 1.5 + min(1.5, float(it.get("seconds", 0.0)) / 3.0)
126
+ elif k in ("OBJECT DIFF", "END DIFF") and b0 < n_b - max(5, n_b // 8):
127
+ # Onset of end-state diff mid-run
128
+ b1 = min(n_b - 1, b0 + max(10, (eb - sb) // 4))
129
+ b0 = max(0, b0 - max(10, (eb - sb) // 6))
130
+ prio = 1.0
131
+ else:
132
+ continue
133
+ if prio > best_prio:
134
+ best_prio = prio
135
+ win = (b0, b1)
136
+
137
+ if win is not None:
138
+ w0, w1 = win
139
+ # Pad slightly so we see just before and just after the anomaly
140
+ pad = max(4, int(0.06 * (eb - sb)))
141
+ w0 = max(1, w0 - pad)
142
+ w1 = min(n_b - 2, max(w0 + 6, w1 + pad))
143
+ mid4 = np.linspace(w0, w1, 4).round().astype(int).tolist()
144
+ idxs = [0] + mid4 + [n_b - 1]
145
+ else:
146
+ idxs = np.linspace(0, n_b - 1, 6).round().astype(int).tolist()
147
+
148
+ # Ensure strictly non-decreasing unique indices when possible
149
+ out = []
150
+ for k in idxs:
151
+ k = max(0, min(n_b - 1, int(k)))
152
+ if out and k <= out[-1] and out[-1] < n_b - 1:
153
+ k = min(n_b - 1, out[-1] + 1)
154
+ out.append(k)
155
+ return out
156
+
157
+
158
+ def _build_b_burst_strip(res, fb, shown, fps, width=320):
159
+ """Image 2: B-ONLY 3x2 chronological filmstrip (6 frames) densely covering the flagged anomaly window."""
160
+ idxs = _pick_b_burst_frames(res, fb, shown)
161
+ hb, wb = fb[0].shape[:2]
162
+ pw = int(width)
163
+ ph = max(64, int(round(hb * pw / max(wb, 1))))
164
+ tiles = []
165
+ for pos, k in enumerate(idxs, start=1):
166
+ bgr = cv2.resize(cv2.cvtColor(fb[k], cv2.COLOR_RGB2BGR), (pw, ph), interpolation=cv2.INTER_AREA)
167
+ tiles.append(_label_corner(bgr, f"[{pos}] B t={k / fps:.1f}s", fg=(0, 230, 255)))
168
+ while len(tiles) < 6:
169
+ tiles.append(np.zeros((ph, pw, 3), dtype=np.uint8))
170
+ vgap = np.full((ph, 4, 3), (50, 58, 70), dtype=np.uint8)
171
+ r1 = np.hstack([tiles[0], vgap, tiles[1], vgap, tiles[2]])
172
+ r2 = np.hstack([tiles[3], vgap, tiles[4], vgap, tiles[5]])
173
+ hgap = np.full((4, r1.shape[1], 3), (50, 58, 70), dtype=np.uint8)
174
+ grid = np.vstack([r1, hgap, r2])
175
+ ts_str = " -> ".join(f"{k / fps:.1f}s" for k in idxs)
176
+ panel = _draw_banner(grid, f"IMAGE 2: RUN B ONLY — CHRONOLOGICAL SEQUENCE ({ts_str})")
177
+ return cv2.cvtColor(panel, cv2.COLOR_BGR2RGB), [round(k / fps, 1) for k in idxs]
178
+
179
+
180
+ def _build_zoomed_crop_pair(fa_end, fb_end, box, idx, crop_size=300):
181
+ """Zoomed 2x side-by-side crop (`A END | B END`) centered on a detected diff box (with 55% context)."""
182
+ h, w = fa_end.shape[:2]
183
+ x0, y0, x1, y1 = box
184
+ bw, bh = max(0.08, x1 - x0), max(0.08, y1 - y0)
185
+ mx, my = max(0.06, 0.55 * bw), max(0.06, 0.55 * bh)
186
+ cx0, cy0 = max(0.0, x0 - mx), max(0.0, y0 - my)
187
+ cx1, cy1 = min(1.0, x1 + mx), min(1.0, y1 + my)
188
+ px0, py0 = int(round(cx0 * w)), int(round(cy0 * h))
189
+ px1, py1 = max(px0 + 8, int(round(cx1 * w))), max(py0 + 8, int(round(cy1 * h)))
190
+
191
+ def _crop(im_rgb, lbl, fg):
192
+ sub = im_rgb[py0:py1, px0:px1]
193
+ bgr = cv2.resize(cv2.cvtColor(sub, cv2.COLOR_RGB2BGR), (crop_size, crop_size), interpolation=cv2.INTER_CUBIC)
194
+ # Draw subtle guide rectangle showing the exact inner diff box inside the padded crop
195
+ ix0 = int(round((x0 - cx0) / max(cx1 - cx0, 1e-5) * crop_size))
196
+ iy0 = int(round((y0 - cy0) / max(cy1 - cy0, 1e-5) * crop_size))
197
+ ix1 = int(round((x1 - cx0) / max(cx1 - cx0, 1e-5) * crop_size))
198
+ iy1 = int(round((y1 - cy0) / max(cy1 - cy0, 1e-5) * crop_size))
199
+ cv2.rectangle(bgr, (ix0, iy0), (ix1, iy1), (0, 220, 220), 2)
200
+ return _label_corner(bgr, lbl, fg=fg)
201
+
202
+ gap = np.full((crop_size, 4, 3), (50, 58, 70), dtype=np.uint8)
203
+ row = np.hstack([
204
+ _crop(fa_end, f"A END - Region #{idx}", (120, 235, 140)),
205
+ gap,
206
+ _crop(fb_end, f"B END - Region #{idx}", (110, 195, 255)),
207
+ ])
208
+ panel = _draw_banner(row, f"ZOOMED CROP #{idx}: END OF A (LEFT) vs END OF B (RIGHT)", scale=0.44)
209
+ return cv2.cvtColor(panel, cv2.COLOR_BGR2RGB)
210
+
211
+
212
+ def build_explain_panels(res, fa, fb, shown, max_panels=5, width=384):
213
+ """Build visual-first VLM input images:
214
+ - Image 1: Clean 2x2 Start & End Overview (A left | B right)
215
+ - Image 2: B-Only 6-Frame Anomaly Filmstrip (isolates B over the exact flagged window!)
216
+ - Images 3..N: 2x Zoomed Side-by-Side Crops (`A end | B end`) for up to `max_panels - 2` diff boxes.
217
+
218
+ Returns `(panels_rgb, panel_captions, boxed_items)`.
219
+ """
220
+ fps = float(res.get("fps", 10))
221
+ boxed_items = [
222
+ it for it in (shown or [])
223
+ if it.get("kind") in ("OBJECT DIFF", "END DIFF", "MISSING OUTCOME", "EXTRA CHANGE", "WRONG PLACE", "OBJECT LOST")
224
+ and it.get("box") and not it.get("info")
225
+ ]
226
+
227
+ panels, captions = [], []
228
+ # Image 1: Clean Start & End Overview
229
+ panels.append(_build_overview_image(fa, fb, fps, width=width))
230
+ captions.append(
231
+ f"IMAGE 1: OVERVIEW — Top: START (A 0.0s | B 0.0s); "
232
+ f"Bottom: END (A {(len(fa) - 1) / fps:.1f}s | B {(len(fb) - 1) / fps:.1f}s)"
233
+ )
234
+
235
+ # Image 2: B-Only 6-Frame Chronological Anomaly Filmstrip
236
+ burst_img, burst_ts = _build_b_burst_strip(res, fb, shown, fps, width=min(320, width))
237
+ panels.append(burst_img)
238
+ captions.append(
239
+ "IMAGE 2: RUN B ONLY — 6 chronological frames (" + " -> ".join(f"[{i+1}] {t:.1f}s" for i, t in enumerate(burst_ts)) + ")"
240
+ )
241
+
242
+ # Images 3+: Zoomed A|B End Crops for each detected diff region (zero text-label hints!)
243
+ max_crops = max(1, int(max_panels) - 2)
244
+ for idx, it in enumerate(boxed_items[:max_crops], start=1):
245
+ panels.append(_build_zoomed_crop_pair(fa[-1], fb[-1], it["box"], idx))
246
+ captions.append(f"IMAGE {len(panels)}: ZOOMED CROP #{idx} — End of A (LEFT) vs End of B (RIGHT) at box {it['box']}")
247
+
248
+ return panels, captions, boxed_items[:max_crops]
249
+
250
+
251
+ def _encode_jpeg_b64(img_rgb, quality=90):
252
+ ok, buf = cv2.imencode(".jpg", cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, quality])
253
+ if not ok:
254
+ raise RuntimeError("Failed to encode keyframe panel as JPEG")
255
+ return base64.b64encode(buf).decode("ascii")
256
+
257
+
258
+ # ------------------------------------------------------------------ 2. Visual-First Anti-Parrot Prompt & Parser
259
+ def build_explain_prompt(res, shown, captions, boxed_items):
260
+ """Build a visual-first prompt that forces the VLM to read the zoomed crops and B-only filmstrip
261
+ WITHOUT handing it generic `"object 1"` text phrases to parrot."""
262
+ fps = float(res.get("fps", 10))
263
+ (sa, ea), (sb, eb) = res.get("trim_a", (0, res.get("len_a", 0))), res.get("trim_b", (0, res.get("len_b", 0)))
264
+ act_a, act_b = (ea - sa) / fps, (eb - sb) / fps
265
+
266
+ lines = [
267
+ "You are a careful robotics visual inspector. Look ONLY at the images provided — never guess or assume success.",
268
+ "",
269
+ "Images provided:",
270
+ *[f"- {c}" for c in captions],
271
+ "",
272
+ "Objective timing measurements from video sync:",
273
+ f"- Active duration: Run A = {act_a:.1f} s, Run B = {act_b:.1f} s (delta {act_b - act_a:+.1f} s).",
274
+ ]
275
+ # Share ONLY objective timing/setup measurements (NO generic 'object 1 was not placed' text that small VLMs parrot!)
276
+ for it in (shown or []):
277
+ k = it.get("kind")
278
+ if k in ("SETUP DIFF", "ENDS EARLY", "SKIPPED", "MORE TIME"):
279
+ lines.append(f"- [{k}] {it['text']}")
280
+ if boxed_items:
281
+ lines.append(
282
+ f"- Visual diff detected {len(boxed_items)} region(s) where the END of Run B visibly differs from "
283
+ "the END of Run A (shown in ZOOMED CROP #1..N with a cyan guide box)."
284
+ )
285
+ else:
286
+ lines.append("- Pure-vision end-state detector flagged 0 boxed end-state regions (still check IMAGE 1 carefully for container/sorting/count differences!).")
287
+
288
+ lines.extend([
289
+ "",
290
+ "Follow these steps IN ORDER using ONLY what you visually see:",
291
+ "Step 1 (START CHECK — IMAGE 1 top): Name the exact object(s) & colors visible at START in A vs B. Do A and B start with the same or different objects?",
292
+ "Step 2 (B ACTION SEQUENCE — IMAGE 2, Run B ONLY): Trace frames [1] -> [2] -> [3] -> [4] -> [5] -> [6] of Run B carefully. "
293
+ "Describe step by step what the robot gripper actually does to the object(s) in Run B: did it grasp cleanly, miss/knock/drop an object off a platform/out of view, leave items unpicked, or put items in the wrong bin?",
294
+ "Step 3 (ZOOMED END CROPS — IMAGES 3+): For EACH Zoomed Crop #k, state literally what exact item & color is inside the cyan box in A (LEFT) vs what is inside B (RIGHT) — e.g. 'blue cube inside black basket' vs 'empty black basket', or 'empty table' vs 'two green plates and green whisk'. NEVER write generic words like 'object 1' or 'an object'!",
295
+ "Step 4 (END OVERVIEW CHECK — IMAGE 1 bottom): Count and compare what ended up in each container/zone in A (bottom-left) vs B (bottom-right).",
296
+ "Step 5 (CONCLUSION): Only AFTER completing Steps 1-4, summarize the true root cause and headline.",
297
+ "",
298
+ "Return ONLY valid JSON with this exact schema (no markdown fences):",
299
+ "{",
300
+ ' "start_comparison": "Exact objects/colors seen at START in A vs B.",',
301
+ ' "b_sequence": "Step-by-step trace of what physically happened across IMAGE 2 frames [1]->[6] in Run B (citing exact timestamps t=...s).",',
302
+ ' "object_diffs": [',
303
+ ' {"box_id": 1, "object": "exact object name & color (NEVER \'object 1\')", "seen_in_a": "what is inside A crop", "seen_in_b": "what is inside B crop", "what_happened": "clear A vs B comparison"}',
304
+ " ],",
305
+ ' "outcome_match": "same | different | uncertain",',
306
+ ' "root_cause": "Concrete physical cause visible in IMAGE 2 / IMAGE 1 (or \'None\' if outcome matches).",',
307
+ ' "headline": "One sharp sentence naming the exact objects and what went wrong in Run B.",',
308
+ ' "observations": ["2-4 concise factual observations with timestamps"]',
309
+ "}",
310
+ ])
311
+ return "\n".join(lines)
312
+
313
+
314
+ def parse_vlm_response(raw_text):
315
+ """Parse structured JSON from a VLM reply, gracefully handling code fences or plain-text fallback."""
316
+ txt = str(raw_text or "").strip()
317
+ if not txt:
318
+ return dict(headline="No explanation returned by model.", outcome_match="uncertain",
319
+ root_cause="", start_comparison="", b_sequence="", object_diffs=[], observations=[], raw="")
320
+ cleaned = re.sub(r"^```(?:json)?\s*", "", txt, flags=re.IGNORECASE)
321
+ cleaned = re.sub(r"\s*```$", "", cleaned).strip()
322
+ m = re.search(r"\{.*\}", cleaned, re.S)
323
+ if m:
324
+ try:
325
+ obj = json.loads(m.group(0))
326
+ if isinstance(obj, dict):
327
+ om = str(obj.get("outcome_match", "uncertain")).strip().lower()
328
+ if om not in ("same", "different", "uncertain"):
329
+ om = "uncertain"
330
+ diffs = obj.get("object_diffs") if isinstance(obj.get("object_diffs"), list) else []
331
+ obs = obj.get("observations") if isinstance(obj.get("observations"), list) else []
332
+ b_seq = str(obj.get("b_sequence") or "").strip()
333
+ st_cmp = str(obj.get("start_comparison") or "").strip()
334
+ clean_obs = [str(o).strip() for o in obs if str(o).strip()]
335
+ if b_seq and not any(b_seq[:30].lower() in o.lower() for o in clean_obs):
336
+ clean_obs.insert(0, f"Run B sequence: {b_seq}")
337
+ if st_cmp and not any(st_cmp[:30].lower() in o.lower() for o in clean_obs):
338
+ clean_obs.insert(0, f"Start setup: {st_cmp}")
339
+ clean_diffs = []
340
+ for d in diffs:
341
+ if not isinstance(d, dict):
342
+ continue
343
+ what = str(d.get("what_happened") or "").strip()
344
+ sa_txt, sb_txt = str(d.get("seen_in_a") or "").strip(), str(d.get("seen_in_b") or "").strip()
345
+ if not what and (sa_txt or sb_txt):
346
+ what = f"A: {sa_txt} | B: {sb_txt}"
347
+ if d.get("object") or what:
348
+ clean_diffs.append(dict(
349
+ box_id=d.get("box_id"),
350
+ object=str(d.get("object") or "").strip(),
351
+ seen_in_a=sa_txt,
352
+ seen_in_b=sb_txt,
353
+ what_happened=what,
354
+ ))
355
+ return dict(
356
+ headline=str(obj.get("headline") or "").strip() or cleaned[:200],
357
+ outcome_match=om,
358
+ root_cause=str(obj.get("root_cause") or "").strip(),
359
+ start_comparison=st_cmp,
360
+ b_sequence=b_seq,
361
+ object_diffs=clean_diffs,
362
+ observations=clean_obs,
363
+ raw=txt,
364
+ )
365
+ except Exception:
366
+ pass
367
+ first_line = next((ln.strip("-* \t") for ln in cleaned.splitlines() if ln.strip()), cleaned[:200])
368
+ return dict(
369
+ headline=first_line,
370
+ outcome_match="uncertain",
371
+ root_cause="",
372
+ start_comparison="",
373
+ b_sequence="",
374
+ object_diffs=[],
375
+ observations=[ln.strip("-* \t") for ln in cleaned.splitlines()[1:] if ln.strip()][:5],
376
+ raw=txt,
377
+ )
378
+
379
+
380
+ # ------------------------------------------------------------------ 3. Backends (OpenAI-compat HTTP + HF local)
381
+ def _probe_openai_endpoint(base_url, timeout=1.5):
382
+ """Quick non-blocking check to see if a local Ollama/vLLM server is already listening."""
383
+ url = base_url.rstrip("/") + "/models"
384
+ req = urllib.request.Request(url, method="GET")
385
+ try:
386
+ with _urlopen(req, timeout=timeout) as resp:
387
+ return resp.status == 200
388
+ except Exception:
389
+ return False
390
+
391
+
392
+ def _call_openai_compat(panels_rgb, prompt, model, base_url, api_key=None, max_tokens=700, timeout=180):
393
+ """Call any OpenAI-compatible vision chat endpoint (Ollama, vLLM, LM Studio, llama.cpp, OpenAI)."""
394
+ content = []
395
+ for im in panels_rgb:
396
+ b64 = _encode_jpeg_b64(im)
397
+ content.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}})
398
+ content.append({"type": "text", "text": prompt})
399
+
400
+ payload = {
401
+ "model": model,
402
+ "messages": [{"role": "user", "content": content}],
403
+ "temperature": 0.1,
404
+ "max_tokens": int(max_tokens),
405
+ }
406
+ url = base_url.rstrip("/") + "/chat/completions"
407
+ headers = {"Content-Type": "application/json"}
408
+ key = api_key or os.environ.get("OPENAI_API_KEY") or os.environ.get("ROLLOUT_DIFF_VLM_KEY")
409
+ if key:
410
+ headers["Authorization"] = f"Bearer {key}"
411
+ elif "127.0.0.1" in base_url or "localhost" in base_url:
412
+ headers["Authorization"] = "Bearer ollama"
413
+
414
+ req = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST")
415
+ try:
416
+ with _urlopen(req, timeout=timeout) as resp:
417
+ data = json.loads(resp.read().decode("utf-8"))
418
+ except urllib.error.HTTPError as exc:
419
+ body = exc.read().decode("utf-8", errors="replace")[:300]
420
+ raise RuntimeError(f"VLM endpoint {url} returned HTTP {exc.code}: {body}") from None
421
+ except urllib.error.URLError as exc:
422
+ raise RuntimeError(
423
+ f"Could not connect to VLM endpoint {url} ({exc.reason}). "
424
+ "Start Ollama (`ollama serve` + `ollama pull qwen2.5vl:7b`) or pass `--explain-backend hf`."
425
+ ) from None
426
+ return data["choices"][0]["message"]["content"]
427
+
428
+
429
+ _HF_CACHE = {}
430
+
431
+
432
+ def _load_hf_vlm(model_id, load_4bit=False):
433
+ """Load & cache a local Hugging Face VLM (e.g. Qwen/Qwen2.5-VL-7B-Instruct, Apache-2.0)."""
434
+ key = (model_id, bool(load_4bit))
435
+ if key in _HF_CACHE:
436
+ return _HF_CACHE[key]
437
+ try:
438
+ import torch
439
+ from transformers import AutoProcessor
440
+ try:
441
+ from transformers import AutoModelForImageTextToText as _VLMCls
442
+ except ImportError:
443
+ from transformers import Qwen2_5_VLForConditionalGeneration as _VLMCls
444
+ except ImportError as exc:
445
+ raise RuntimeError(
446
+ "Local HF VLM requires transformers>=4.49 and torch. "
447
+ "Install with: pip install -U 'transformers>=4.49' accelerate qwen-vl-utils"
448
+ ) from exc
449
+
450
+ use_cuda = torch.cuda.is_available()
451
+ dtype = torch.bfloat16 if (use_cuda and torch.cuda.is_bf16_supported()) else (torch.float16 if use_cuda else torch.float32)
452
+ kwargs = dict(device_map="auto" if use_cuda else None, dtype=dtype)
453
+ if load_4bit:
454
+ try:
455
+ from transformers import BitsAndBytesConfig
456
+ kwargs["quantization_config"] = BitsAndBytesConfig(
457
+ load_in_4bit=True, bnb_4bit_compute_dtype=dtype, bnb_4bit_quant_type="nf4",
458
+ )
459
+ except ImportError as exc:
460
+ raise RuntimeError("4-bit mode (--explain-4bit) requires bitsandbytes: pip install bitsandbytes") from exc
461
+
462
+ processor = AutoProcessor.from_pretrained(model_id)
463
+ model = _VLMCls.from_pretrained(model_id, **kwargs).eval()
464
+ _HF_CACHE[key] = (processor, model)
465
+ return processor, model
466
+
467
+
468
+ def _call_hf_local(panels_rgb, prompt, model_id, load_4bit=False, max_tokens=700):
469
+ """Run local Hugging Face VLM directly in PyTorch on GPU/CPU (zero server needed)."""
470
+ import torch
471
+ from PIL import Image
472
+
473
+ processor, model = _load_hf_vlm(model_id, load_4bit=load_4bit)
474
+ pil_images = [Image.fromarray(im) for im in panels_rgb]
475
+ messages = [{
476
+ "role": "user",
477
+ "content": [{"type": "image", "image": im} for im in pil_images] + [{"type": "text", "text": prompt}],
478
+ }]
479
+ text_prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
480
+ inputs = processor(text=[text_prompt], images=pil_images, padding=True, return_tensors="pt")
481
+ dev = next(model.parameters()).device
482
+ inputs = {k: (v.to(dev) if hasattr(v, "to") else v) for k, v in inputs.items()}
483
+ with torch.no_grad():
484
+ gen_ids = model.generate(**inputs, max_new_tokens=int(max_tokens), do_sample=False)
485
+ in_len = inputs["input_ids"].shape[1]
486
+ trimmed = gen_ids[:, in_len:]
487
+ return processor.batch_decode(trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
488
+
489
+
490
+ # ------------------------------------------------------------------ 4. Public entry point
491
+ def explain_diff(res, fa, fb, shown, *, backend="auto", model=None, url=None, api_key=None,
492
+ load_4bit=False, max_panels=5, max_tokens=700, debug_dir=None, log=None):
493
+ """Generate a grounded VLM explanation using overview + B-only anomaly burst + zoomed diff crops."""
494
+ _log = log or (lambda _m: None)
495
+ panels, captions, boxed_items = build_explain_panels(res, fa, fb, shown, max_panels=max_panels)
496
+ prompt = build_explain_prompt(res, shown, captions, boxed_items)
497
+
498
+ if debug_dir:
499
+ dd = Path(debug_dir)
500
+ dd.mkdir(parents=True, exist_ok=True)
501
+ for i, im in enumerate(panels, start=1):
502
+ cv2.imwrite(str(dd / f"panel_{i}.jpg"), cv2.cvtColor(im, cv2.COLOR_RGB2BGR))
503
+ (dd / "prompt.txt").write_text(prompt, encoding="utf-8")
504
+
505
+ chosen_backend = backend
506
+ chosen_url = url or os.environ.get("ROLLOUT_DIFF_VLM_URL")
507
+ ollama_url = _default_ollama_url()
508
+ if chosen_backend == "auto":
509
+ if chosen_url:
510
+ chosen_backend = "openai"
511
+ elif _probe_openai_endpoint(ollama_url):
512
+ chosen_backend = "openai"
513
+ chosen_url = ollama_url
514
+ else:
515
+ chosen_backend = "hf"
516
+
517
+ if chosen_backend == "openai":
518
+ chosen_url = chosen_url or ollama_url
519
+ chosen_model = model or os.environ.get("ROLLOUT_DIFF_VLM_MODEL") or DEFAULT_OLLAMA_MODEL
520
+ _log(f"Stage: generating VLM explanation via {chosen_url} ({chosen_model}, {len(panels)} focused image(s)) ...")
521
+ raw = _call_openai_compat(panels, prompt, model=chosen_model, base_url=chosen_url,
522
+ api_key=api_key, max_tokens=max_tokens)
523
+ elif chosen_backend == "hf":
524
+ chosen_model = model or os.environ.get("ROLLOUT_DIFF_VLM_MODEL") or DEFAULT_HF_MODEL
525
+ q_note = ", 4-bit" if load_4bit else ""
526
+ _log(f"Stage: generating VLM explanation locally via HF ({chosen_model}{q_note}, {len(panels)} focused image(s)) ...")
527
+ raw = _call_hf_local(panels, prompt, model_id=chosen_model, load_4bit=load_4bit, max_tokens=max_tokens)
528
+ else:
529
+ raise ValueError(f"Unknown explain backend '{backend}' (expected 'auto', 'openai', or 'hf')")
530
+
531
+ if debug_dir:
532
+ (Path(debug_dir) / "answer.txt").write_text(str(raw), encoding="utf-8")
533
+ parsed = parse_vlm_response(raw)
534
+ parsed["model"] = chosen_model
535
+ parsed["backend"] = chosen_backend
536
+ parsed["panels"] = captions
537
+ _log(f" VLM explanation ready (outcome: {parsed['outcome_match']})")
538
+ return parsed