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.
rollout_diff/export.py ADDED
@@ -0,0 +1,215 @@
1
+ """Export a synced side-by-side diff video (.mp4) or animated GIF (.gif) with boxes, arrows, and timeline.
2
+
3
+ Uses OpenCV (`cv2.VideoWriter`) for `.mp4` and Pillow (`PIL.Image`) for `.gif` — zero external ffmpeg
4
+ binaries needed, ready to paste straight into GitHub PRs, Slack, Discord, X, or papers.
5
+ """
6
+ from pathlib import Path
7
+
8
+ import cv2
9
+ import numpy as np
10
+
11
+ from .report import COLORS, INFO_KINDS, _steps, diff_badge, summary
12
+
13
+
14
+ def _hex_bgr(hex_str, default=(72, 29, 225)):
15
+ h = str(hex_str or "").lstrip("#")
16
+ if len(h) != 6:
17
+ return default
18
+ r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
19
+ return (b, g, r)
20
+
21
+
22
+ def _draw_pill(img, text, x, y, bg_bgr, fg_bgr=(255, 255, 255), scale=0.48, thick=1):
23
+ (tw, th), bl = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, scale, thick)
24
+ pad_x, pad_y = 7, 4
25
+ x = max(2, min(img.shape[1] - tw - 2 * pad_x - 2, x))
26
+ y = max(2, min(img.shape[0] - th - 2 * pad_y - 2, y))
27
+ x1 = min(img.shape[1] - 2, x + tw + 2 * pad_x)
28
+ y1 = min(img.shape[0] - 2, y + th + 2 * pad_y)
29
+ cv2.rectangle(img, (x, y), (x1, y1), bg_bgr, -1)
30
+ cv2.putText(img, text, (x + pad_x, y + pad_y + th - 1), cv2.FONT_HERSHEY_SIMPLEX,
31
+ scale, fg_bgr, thick, cv2.LINE_AA)
32
+ return x1 - x
33
+
34
+
35
+ def _draw_dashed_rect(img, p0, p1, color, thick=2, dash=7, gap=5):
36
+ x0, y0 = p0
37
+ x1, y1 = p1
38
+ for a, b in (((x0, y0), (x1, y0)), ((x1, y0), (x1, y1)), ((x1, y1), (x0, y1)), ((x0, y1), (x0, y0))):
39
+ dist = float(np.hypot(b[0] - a[0], b[1] - a[1]))
40
+ if dist < 1:
41
+ continue
42
+ dx, dy = (b[0] - a[0]) / dist, (b[1] - a[1]) / dist
43
+ pos = 0.0
44
+ while pos < dist:
45
+ e = min(dist, pos + dash)
46
+ cv2.line(img, (int(round(a[0] + dx * pos)), int(round(a[1] + dy * pos))),
47
+ (int(round(a[0] + dx * e)), int(round(a[1] + dy * e))), color, thick, cv2.LINE_AA)
48
+ pos += dash + gap
49
+
50
+
51
+ def _draw_dashed_poly(img, pts, color, thick=2, dash=6, gap=5):
52
+ for i in range(1, len(pts)):
53
+ a, b = pts[i - 1], pts[i]
54
+ dist = float(np.hypot(b[0] - a[0], b[1] - a[1]))
55
+ if dist < 1:
56
+ continue
57
+ dx, dy = (b[0] - a[0]) / dist, (b[1] - a[1]) / dist
58
+ pos = 0.0
59
+ while pos < dist:
60
+ e = min(dist, pos + dash)
61
+ cv2.line(img, (int(round(a[0] + dx * pos)), int(round(a[1] + dy * pos))),
62
+ (int(round(a[0] + dx * e)), int(round(a[1] + dy * e))), color, thick, cv2.LINE_AA)
63
+ pos += dash + gap
64
+
65
+
66
+ def render_diff_frames(res, fa, fb, name_a="A", name_b="B", min_s=1.0, floor_items=None,
67
+ obj_items=None, width=400, max_frames=220, gated=False):
68
+ """Render RGB frames of a synced side-by-side diff clip (header + A|B panels + boxes + timeline)."""
69
+ shown, verdict = summary(res, min_s=min_s, floor_items=floor_items, obj_items=obj_items)
70
+ badge_txt, badge_cls = diff_badge(shown, gated=gated, verdict=verdict)
71
+ path = res.get("path") or [(0, 0)]
72
+ fps = float(res.get("fps", 10))
73
+ (sa, ea), (sb, eb) = res.get("trim_a", (0, len(fa))), res.get("trim_b", (0, len(fb)))
74
+ act_a, act_b = (ea - sa) / fps, (eb - sb) / fps
75
+ act_d = act_b - act_a
76
+
77
+ # Precompute path step spans for every non-info item
78
+ active_items = []
79
+ for it in shown:
80
+ if it.get("info") or it["kind"] in INFO_KINDS:
81
+ continue
82
+ s0, s1 = _steps(it, path, sa, sb)
83
+ active_items.append(dict(it, _s0=int(s0), _s1=int(s1), _bgr=_hex_bgr(COLORS.get(it["kind"]))))
84
+
85
+ # Panel geometry
86
+ h0, w0 = fa[0].shape[:2]
87
+ pw = int(width)
88
+ ph = max(64, int(round(h0 * pw / max(w0, 1))) & ~1)
89
+ hdr_h, bar_h, gap = 36, 36, 4
90
+ total_w = pw * 2 + gap
91
+ total_h = hdr_h + ph + bar_h
92
+ badge_bgr = (61, 128, 21) if badge_cls == "pass" else (38, 38, 220) if badge_cls == "fail" else (12, 88, 234)
93
+
94
+ S = len(path)
95
+ stride = max(1, int(np.ceil(S / max(1, int(max_frames)))))
96
+ step_indices = list(range(0, S, stride))
97
+ if step_indices[-1] != S - 1:
98
+ step_indices.append(S - 1)
99
+
100
+ frames_out = []
101
+ for s in step_indices:
102
+ ia, jb = path[s]
103
+ fa_i = min(len(fa) - 1, ia + sa)
104
+ fb_i = min(len(fb) - 1, jb + sb)
105
+ img_a = cv2.resize(cv2.cvtColor(fa[fa_i], cv2.COLOR_RGB2BGR), (pw, ph), interpolation=cv2.INTER_AREA)
106
+ img_b = cv2.resize(cv2.cvtColor(fb[fb_i], cv2.COLOR_RGB2BGR), (pw, ph), interpolation=cv2.INTER_AREA)
107
+
108
+ # Draw active boxes, trajectories, and timing pills on B
109
+ live_texts = []
110
+ tim_y = 8
111
+ for it in active_items:
112
+ if not (it["_s0"] <= s <= it["_s1"]):
113
+ continue
114
+ live_texts.append(f"{it['kind']}: {it['text']}")
115
+ box = it.get("box")
116
+ if box and len(box) == 4:
117
+ x0, y0, x1, y1 = box
118
+ p0 = (int(x0 * pw), int(y0 * ph))
119
+ p1 = (int(x1 * pw), int(y1 * ph))
120
+ is_missing = ("not placed" in it["text"] or "removed / missing" in it["text"])
121
+ tag = it.get("object_name") or it["kind"]
122
+ pill_y = p0[1] - 18 if p0[1] >= 22 else (p0[1] + 28 if p0[0] < 95 else p0[1] + 4)
123
+ if is_missing:
124
+ _draw_dashed_rect(img_b, p0, p1, it["_bgr"], thick=2)
125
+ _draw_pill(img_b, tag, p0[0], pill_y, it["_bgr"], scale=0.38, thick=1)
126
+ else:
127
+ cv2.rectangle(img_b, p0, p1, it["_bgr"], 2)
128
+ _draw_pill(img_b, tag, p0[0], pill_y, it["_bgr"], scale=0.38, thick=1)
129
+ tr = it.get("track")
130
+ if tr and len(tr) >= 2:
131
+ pts = np.array([[int(x * pw), int(y * ph)] for x, y in tr], np.int32)
132
+ cv2.polylines(img_b, [pts], False, (21, 204, 250), 2, cv2.LINE_AA)
133
+ cv2.circle(img_b, tuple(pts[0]), 3, (94, 197, 34), -1)
134
+ cv2.arrowedLine(img_b, tuple(pts[-2]), tuple(pts[-1]), (21, 204, 250), 2, tipLength=0.45)
135
+ elif it["kind"] in ("MORE TIME", "LESS TIME", "SKIPPED", "ENDS EARLY"):
136
+ short_t = it["text"].split(":")[0][:36]
137
+ _draw_pill(img_b, f"{it['kind']} {short_t}", max(8, pw - 235), tim_y, it["_bgr"], scale=0.40, thick=1)
138
+ tim_y += 24
139
+
140
+ _draw_pill(img_a, f"A {fa_i / fps:.1f}s", 8, 8, (42, 23, 15), scale=0.46, thick=1)
141
+ _draw_pill(img_b, f"B {fb_i / fps:.1f}s", 8, 8, (42, 23, 15), scale=0.46, thick=1)
142
+
143
+ canvas = np.full((total_h, total_w, 3), (27, 21, 17), dtype=np.uint8)
144
+ # Header bar
145
+ cv2.putText(canvas, "rollout-diff", (10, 24), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (240, 244, 248), 2, cv2.LINE_AA)
146
+ bw = _draw_pill(canvas, badge_txt, 128, 7, badge_bgr, scale=0.46, thick=1)
147
+ act_str = f"active {act_a:.1f}s -> {act_b:.1f}s ({act_d:+.1f}s)"
148
+ cv2.putText(canvas, act_str, (138 + bw, 23), cv2.FONT_HERSHEY_SIMPLEX, 0.46, (184, 163, 148), 1, cv2.LINE_AA)
149
+
150
+ # Panels
151
+ canvas[hdr_h:hdr_h + ph, 0:pw] = img_a
152
+ canvas[hdr_h:hdr_h + ph, pw + gap:total_w] = img_b
153
+
154
+ # Timeline bar
155
+ ty0 = hdr_h + ph + 6
156
+ ty1 = ty0 + 10
157
+ tx0, tx1 = 10, total_w - 10
158
+ cv2.rectangle(canvas, (tx0, ty0), (tx1, ty1), (68, 53, 43), -1)
159
+ span_w = max(1, tx1 - tx0)
160
+ denom = max(1, S - 1)
161
+ for it in active_items:
162
+ sx0 = tx0 + int(round(it["_s0"] / denom * span_w))
163
+ sx1 = max(sx0 + 3, tx0 + int(round(it["_s1"] / denom * span_w)))
164
+ cv2.rectangle(canvas, (sx0, ty0), (min(tx1, sx1), ty1), it["_bgr"], -1)
165
+ cx = tx0 + int(round(s / denom * span_w))
166
+ cv2.line(canvas, (cx, ty0 - 2), (cx, ty1 + 2), (255, 255, 255), 2)
167
+
168
+ cap = live_texts[0] if live_texts else f"{Path(str(name_a)).name} vs {Path(str(name_b)).name}"
169
+ cap = cap.replace("\u2192", "->").replace("\u00b7", "|").replace("\u2014", "-")
170
+ if len(cap) > 95:
171
+ cap = cap[:92] + "..."
172
+ cv2.putText(canvas, cap, (10, total_h - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.40, (226, 232, 240), 1, cv2.LINE_AA)
173
+ frames_out.append(cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB))
174
+
175
+ eff_fps = max(1.0, (fps / stride))
176
+ return frames_out, eff_fps
177
+
178
+
179
+ def write_video(res, fa, fb, out_path, name_a="A", name_b="B", min_s=1.0, floor_items=None,
180
+ obj_items=None, width=400, fps=None, speed=1.0, max_frames=220, gated=False):
181
+ """Write a shareable synced side-by-side diff `.mp4` video or `.gif` animation."""
182
+ out_p = Path(out_path)
183
+ out_p.parent.mkdir(parents=True, exist_ok=True)
184
+ ext = out_p.suffix.lower()
185
+ cap_frames = min(max_frames, 120) if ext == ".gif" else max_frames
186
+ frames, eff_fps = render_diff_frames(
187
+ res, fa, fb, name_a=name_a, name_b=name_b, min_s=min_s, floor_items=floor_items,
188
+ obj_items=obj_items, width=width, max_frames=cap_frames, gated=gated,
189
+ )
190
+ play_fps = float(fps) if fps else max(2.0, eff_fps * float(speed))
191
+
192
+ if ext == ".gif":
193
+ try:
194
+ from PIL import Image
195
+ except ImportError as exc:
196
+ raise ImportError("Exporting .gif needs Pillow (pip install pillow) or use .mp4 instead.") from exc
197
+ pil_frames = [Image.fromarray(f).quantize(colors=160, method=Image.Quantize.FASTOCTREE) for f in frames]
198
+ dur_ms = max(40, int(round(1000.0 / play_fps)))
199
+ pil_frames[0].save(
200
+ str(out_p), save_all=True, append_images=pil_frames[1:],
201
+ duration=dur_ms, loop=0, optimize=True,
202
+ )
203
+ return out_p
204
+
205
+ h, w = frames[0].shape[:2]
206
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
207
+ vw = cv2.VideoWriter(str(out_p), fourcc, play_fps, (w, h))
208
+ if not vw.isOpened():
209
+ raise RuntimeError(f"Could not open video writer for {out_p}")
210
+ try:
211
+ for f in frames:
212
+ vw.write(cv2.cvtColor(f, cv2.COLOR_RGB2BGR))
213
+ finally:
214
+ vw.release()
215
+ return out_p
rollout_diff/hub.py ADDED
@@ -0,0 +1,207 @@
1
+ """Load individual episodes from local or Hugging Face Hub LeRobot datasets (v2.0/v2.1 and v3.0).
2
+
3
+ Syntax matches local folders:
4
+ rollout-diff lerobot/svla_so101_pickplace#0 lerobot/svla_so101_pickplace#12 --cam side
5
+
6
+ Downloads ONLY `meta/info.json`, the single metadata parquet shard (v3.0), and the 1 video file
7
+ containing the requested episode — never the whole dataset.
8
+ """
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+
13
+ import pandas as pd
14
+
15
+ os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS_WARNING", "1")
16
+ os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
17
+
18
+ _CAM_NOTED = set()
19
+ _LAST_CAM = {}
20
+
21
+
22
+ def _short_cam(key):
23
+ return str(key).removeprefix("observation.images.")
24
+
25
+
26
+ def _camera_keys(info):
27
+ """All video/image camera keys in a LeRobot info.json (supports observation.images.* and singular image keys)."""
28
+ feats = info.get("features") or {}
29
+ keys = []
30
+ for k, v in feats.items():
31
+ is_img_prefix = k.startswith("observation.images.") and (
32
+ not isinstance(v, dict) or v.get("dtype") in (None, "video", "image")
33
+ )
34
+ is_vid_dtype = isinstance(v, dict) and v.get("dtype") in ("video", "image")
35
+ if is_img_prefix or is_vid_dtype:
36
+ keys.append(k)
37
+ return keys
38
+
39
+
40
+ def list_cameras(root_or_repo):
41
+ """Return short camera names advertised by a local or Hugging Face Hub LeRobot dataset."""
42
+ hub = is_hub_repo(root_or_repo)
43
+ info_path = _hf_download(root_or_repo, "meta/info.json") if hub else Path(root_or_repo) / "meta/info.json"
44
+ info = json.loads(info_path.read_text(encoding="utf-8"))
45
+ return [_short_cam(k) for k in _camera_keys(info)]
46
+
47
+
48
+ def last_resolved_cam(root_or_repo):
49
+ """Short camera name most recently resolved for `root_or_repo`, or None."""
50
+ return _LAST_CAM.get(str(root_or_repo))
51
+
52
+
53
+ def is_hub_repo(spec_root):
54
+ """True if `spec_root` looks like a Hugging Face Hub repo id (`owner/dataset`) rather than a local path."""
55
+ s = str(spec_root).strip()
56
+ if not s or Path(s).exists():
57
+ return False
58
+ if "\\" in s or ":" in s or s.startswith((".", "/", "~")):
59
+ return False
60
+ parts = s.split("/")
61
+ return len(parts) == 2 and all(bool(p) and p not in (".", "..") for p in parts)
62
+
63
+
64
+ def _hf_download(repo_id, filename):
65
+ try:
66
+ from huggingface_hub import hf_hub_download
67
+ except ImportError as exc:
68
+ raise ImportError(
69
+ "Loading Hugging Face Hub datasets needs 'huggingface-hub' (pip install huggingface-hub)."
70
+ ) from exc
71
+ return Path(hf_hub_download(repo_id=repo_id, filename=filename, repo_type="dataset"))
72
+
73
+
74
+ def _hf_list_files(repo_id):
75
+ try:
76
+ from huggingface_hub import list_repo_files
77
+ except ImportError as exc:
78
+ raise ImportError(
79
+ "Loading Hugging Face Hub datasets needs 'huggingface-hub' (pip install huggingface-hub)."
80
+ ) from exc
81
+ return list(list_repo_files(repo_id=repo_id, repo_type="dataset"))
82
+
83
+
84
+ def _resolve_cam_key(info, cam, log=print, *, source=None):
85
+ """Resolve `--cam` to a LeRobot camera feature key, auto-picking the best fixed camera when omitted or missing."""
86
+ feats = info.get("features") or {}
87
+ auto = cam is None or str(cam).strip() in ("", "auto")
88
+ exact = ""
89
+ if not auto:
90
+ cam_s = str(cam).strip()
91
+ if cam_s in feats:
92
+ return cam_s
93
+ exact = cam_s if cam_s.startswith("observation.images.") else f"observation.images.{cam_s}"
94
+ if exact in feats:
95
+ return exact
96
+ vid_keys = _camera_keys(info)
97
+ if not vid_keys:
98
+ return exact
99
+ # Prefer non-wrist fixed cameras when auto-selecting
100
+ non_wrist = [k for k in vid_keys if not any(w in k.lower() for w in ("wrist", "hand", "gripper"))]
101
+ picked = (non_wrist or vid_keys)[0]
102
+ short = _short_cam(picked)
103
+ if log:
104
+ note_key = None if source is None else (str(source), None if auto else str(cam), picked)
105
+ if note_key is None or note_key not in _CAM_NOTED:
106
+ if note_key is not None:
107
+ _CAM_NOTED.add(note_key)
108
+ avail = ", ".join(_short_cam(k) for k in vid_keys)
109
+ if auto:
110
+ log(f"note: using camera '{short}' (available: {avail}; pass --cam <name> to switch)")
111
+ else:
112
+ log(f"note: camera '{cam}' not in dataset (available: {avail}); using '{short}' (pass --cam <name> to switch)")
113
+ return picked
114
+
115
+
116
+ def _is_v3(info):
117
+ ver = str(info.get("codebase_version", "")).lower()
118
+ if ver.startswith("v3"):
119
+ return True
120
+ if ver.startswith("v2"):
121
+ return False
122
+ vp = str(info.get("video_path", ""))
123
+ return "file_index" in vp or "chunk_index" in vp
124
+
125
+
126
+ def _find_v3_episode_row(root_or_repo, ep, is_hub):
127
+ """Locate episode `ep` across LeRobot v3 `meta/episodes/chunk-*/file-*.parquet` shards."""
128
+ first_rel = "meta/episodes/chunk-000/file-000.parquet"
129
+ checked = set()
130
+
131
+ def _try_parquet(path):
132
+ df = pd.read_parquet(path)
133
+ if "episode_index" in df.columns:
134
+ m = df[df["episode_index"] == ep]
135
+ if len(m):
136
+ return m.iloc[0]
137
+ return None
138
+
139
+ # Fast path: single-shard / early episode in chunk-000/file-000.parquet
140
+ try:
141
+ p0 = _hf_download(root_or_repo, first_rel) if is_hub else Path(root_or_repo) / first_rel
142
+ checked.add(first_rel)
143
+ if p0.exists():
144
+ row = _try_parquet(p0)
145
+ if row is not None:
146
+ return row
147
+ except Exception:
148
+ pass
149
+
150
+ # Multi-shard fallback for larger v3 datasets
151
+ if is_hub:
152
+ rels = sorted(f for f in _hf_list_files(root_or_repo)
153
+ if f.startswith("meta/episodes/") and f.endswith(".parquet") and f not in checked)
154
+ for rel in rels:
155
+ row = _try_parquet(_hf_download(root_or_repo, rel))
156
+ if row is not None:
157
+ return row
158
+ else:
159
+ base = Path(root_or_repo) / "meta/episodes"
160
+ if base.exists():
161
+ for p in sorted(base.rglob("*.parquet")):
162
+ rel = p.relative_to(Path(root_or_repo)).as_posix()
163
+ if rel in checked:
164
+ continue
165
+ row = _try_parquet(p)
166
+ if row is not None:
167
+ return row
168
+ raise KeyError(f"Episode {ep} not found in {root_or_repo} meta/episodes/*.parquet")
169
+
170
+
171
+ def resolve_lerobot_episode(root_or_repo, ep, cam=None, log=print):
172
+ """Resolve one LeRobot episode (local folder or HF Hub repo id, v2.x or v3.0) to a local video slice.
173
+
174
+ Returns dict(video_path: Path, first_frame: int, length: int | None, src_fps: float, key: str, version: str).
175
+ """
176
+ ep = int(ep)
177
+ hub = is_hub_repo(root_or_repo)
178
+ if hub:
179
+ info_path = _hf_download(root_or_repo, "meta/info.json")
180
+ else:
181
+ info_path = Path(root_or_repo) / "meta/info.json"
182
+ if not info_path.exists():
183
+ raise FileNotFoundError(f"Not a LeRobot dataset folder (missing meta/info.json): {root_or_repo}")
184
+ info = json.loads(info_path.read_text(encoding="utf-8"))
185
+ src_fps = float(info.get("fps", 30))
186
+ key = _resolve_cam_key(info, cam, log=log, source=root_or_repo)
187
+ if key:
188
+ _LAST_CAM[str(root_or_repo)] = _short_cam(key)
189
+
190
+ if _is_v3(info):
191
+ row = _find_v3_episode_row(root_or_repo, ep, hub)
192
+ chunk_idx = int(row[f"videos/{key}/chunk_index"])
193
+ file_idx = int(row[f"videos/{key}/file_index"])
194
+ tmpl = info.get("video_path") or "videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4"
195
+ rel_video = tmpl.format(video_key=key, chunk_index=chunk_idx, file_index=file_idx)
196
+ vid_path = _hf_download(root_or_repo, rel_video) if hub else Path(root_or_repo) / rel_video
197
+ first_frame = round(float(row[f"videos/{key}/from_timestamp"]) * src_fps)
198
+ length = int(row["length"])
199
+ return dict(video_path=vid_path, first_frame=first_frame, length=length, src_fps=src_fps, key=key, version="v3")
200
+
201
+ # LeRobot v2.0 / v2.1: one MP4 per episode
202
+ chunks_size = int(info.get("chunks_size", 1000))
203
+ ep_chunk = ep // max(1, chunks_size)
204
+ tmpl = info.get("video_path") or "videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4"
205
+ rel_video = tmpl.format(episode_chunk=ep_chunk, video_key=key, episode_index=ep)
206
+ vid_path = _hf_download(root_or_repo, rel_video) if hub else Path(root_or_repo) / rel_video
207
+ return dict(video_path=vid_path, first_frame=0, length=None, src_fps=src_fps, key=key, version="v2")