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,169 @@
1
+ """rollout-diff: A git diff for robot runs.
2
+
3
+ Quick 3-line Python API:
4
+ import rollout_diff as rd
5
+ d = rd.diff("good.mp4", "new.mp4", world_diff=True)
6
+ d.save_html("report.html") # or d.save_video("diff.mp4") / d.save_video("diff.gif")
7
+ """
8
+ import json as _json
9
+ import os as _os
10
+ import warnings as _warnings
11
+ from pathlib import Path as _Path
12
+
13
+ _os.environ.setdefault("USE_TF", "0") # PyTorch only; ignore broken TensorFlow installs
14
+ _os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS_WARNING", "1") # Windows non-Developer-Mode warning spam
15
+ _os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1") # keep CLI output calm; set to 0 to re-enable
16
+ _warnings.filterwarnings("ignore", message=r"Failed to find CUDA\.", category=UserWarning)
17
+ _warnings.filterwarnings("ignore", message=r"xFormers is not available.*", category=UserWarning)
18
+
19
+ __version__ = "1.0.1"
20
+
21
+
22
+ class DiffResult:
23
+ """User-friendly result object returned by `rollout_diff.diff(...)`."""
24
+
25
+ def __init__(self, raw, fa, fb, name_a, name_b, shown, verdict, badge, note="", min_s=1.0, gated=False):
26
+ self.raw = raw
27
+ self.fa = fa
28
+ self.fb = fb
29
+ self.name_a = str(name_a)
30
+ self.name_b = str(name_b)
31
+ self.items = shown
32
+ self.verdict = verdict
33
+ self.badge = badge
34
+ self.note = note
35
+ self.min_s = float(min_s)
36
+ self.gated = bool(gated)
37
+
38
+ fps = float(raw.get("fps", 10))
39
+ (sa, ea), (sb, eb) = raw["trim_a"], raw["trim_b"]
40
+ self.active_a = round((ea - sa) / fps, 2)
41
+ self.active_b = round((eb - sb) / fps, 2)
42
+ self.active_delta_s = round(self.active_b - self.active_a, 2)
43
+ self.start_scene_warning = raw.get("start_scene_warning")
44
+ self.explanation = raw.get("explanation")
45
+
46
+ from .report import INFO_KINDS
47
+ self.n_diffs = sum(1 for it in shown if it["kind"] not in INFO_KINDS)
48
+
49
+ def __repr__(self):
50
+ return (f"DiffResult({self.badge!r}, n_diffs={self.n_diffs}, "
51
+ f"active={self.active_a:.1f}s->{self.active_b:.1f}s ({self.active_delta_s:+.1f}s))")
52
+
53
+ def save_html(self, path):
54
+ """Write the interactive synced HTML report to `path`."""
55
+ from .report import write_html
56
+ p = _Path(path)
57
+ p.parent.mkdir(parents=True, exist_ok=True)
58
+ write_html(self.raw, self.fa, self.fb, str(p), self.name_a, self.name_b,
59
+ min_s=self.min_s, floor_note=self.note, gated=self.gated)
60
+ return p
61
+
62
+ def save_video(self, path, width=400, fps=None, speed=1.0, max_frames=220):
63
+ """Write a synced side-by-side diff `.mp4` video or `.gif` animation to `path`."""
64
+ from .export import write_video
65
+ return write_video(self.raw, self.fa, self.fb, path, name_a=self.name_a, name_b=self.name_b,
66
+ min_s=self.min_s, width=width, fps=fps, speed=speed,
67
+ max_frames=max_frames, gated=self.gated)
68
+
69
+ def to_json(self, path=None):
70
+ """Return a JSON-serializable summary dict (and optionally write it to `path`)."""
71
+ payload = dict(
72
+ a=self.name_a, b=self.name_b, summary=self.badge,
73
+ verdict=self.verdict if self.gated else None,
74
+ fps=self.raw["fps"], fp=self.raw["fp"], alike=self.raw["alike"],
75
+ trim_a=self.raw["trim_a"], trim_b=self.raw["trim_b"],
76
+ active_a=self.active_a, active_b=self.active_b, active_delta_s=self.active_delta_s,
77
+ start_scene_score=self.raw.get("start_scene_score"),
78
+ start_scene_warning=self.start_scene_warning,
79
+ explanation=self.explanation,
80
+ items=self.items,
81
+ )
82
+ if path is not None:
83
+ p = _Path(path)
84
+ p.parent.mkdir(parents=True, exist_ok=True)
85
+ p.write_text(_json.dumps(payload, indent=1, default=float), encoding="utf-8")
86
+ return payload
87
+
88
+ def log_wandb(self, run=None, prefix="rollout_diff", include_html=True):
89
+ """Log diff counts, active-time delta, and (optionally) the interactive HTML report to Weights & Biases."""
90
+ try:
91
+ import wandb
92
+ except ImportError as exc:
93
+ raise ImportError("log_wandb() requires wandb (pip install wandb).") from exc
94
+ import tempfile
95
+ target = run if run is not None else wandb
96
+ metrics = {
97
+ f"{prefix}/n_diffs": self.n_diffs,
98
+ f"{prefix}/active_a_s": self.active_a,
99
+ f"{prefix}/active_b_s": self.active_b,
100
+ f"{prefix}/active_delta_s": self.active_delta_s,
101
+ f"{prefix}/passed": int(self.verdict == "PASS"),
102
+ }
103
+ if include_html:
104
+ with tempfile.TemporaryDirectory() as td:
105
+ hp = self.save_html(_Path(td) / "report.html")
106
+ metrics[f"{prefix}/report"] = wandb.Html(hp.read_text(encoding="utf-8"))
107
+ target.log(metrics)
108
+ return metrics
109
+
110
+
111
+ def diff(a, b, *, cam="side", fps=10, fp="global", world_diff=False, channels=False,
112
+ track=False, arm_diff=False, explain=False, explain_model=None, explain_backend="auto",
113
+ explain_url=None, explain_4bit=False, also=None, min_s=1.0, gated=False, robot=None):
114
+ """Compare two robot runs (`.mp4` files or local/HF Hub `dataset#episode`) in one Python call.
115
+
116
+ Returns a `DiffResult` with `.items`, `.badge`, `.active_delta_s`, `.save_html(...)`,
117
+ `.save_video(...)`, `.to_json(...)`, and `.log_wandb(...)`.
118
+ """
119
+ from .core import compare, load_run
120
+ from .report import diff_badge, summary
121
+
122
+ fa = a if hasattr(a, "ndim") else load_run(a, fps=fps, cam=cam)
123
+ fb = b if hasattr(b, "ndim") else load_run(b, fps=fps, cam=cam)
124
+ name_a = "run_a" if hasattr(a, "ndim") else str(a)
125
+ name_b = "run_b" if hasattr(b, "ndim") else str(b)
126
+ goods = [(g if hasattr(g, "ndim") else load_run(g, fps=fps, cam=cam)) for g in (also or [])]
127
+
128
+ note = ""
129
+ if world_diff:
130
+ from . import world_diff as wd_mod
131
+ res = compare(fa, fb, fps=fps, fp=fp, spatial=False)
132
+ res["spatial"] = wd_mod.spot_world(fa, fb, res, goods=goods, mask_model=robot)
133
+ res["spatial_items"] = res["spatial"]["items"]
134
+ note = "robot-free world-change diff (SAM 2.1 + DINOv2-reg, Apache-2.0)"
135
+ else:
136
+ use_ch = bool(channels or track or arm_diff or robot is not None)
137
+ res = compare(fa, fb, fps=fps, fp=fp, spatial=True, robot=robot, channels=use_ch,
138
+ arm_diff=arm_diff, track=track, spec_a=name_a, spec_b=name_b, goods=goods)
139
+ if use_ch:
140
+ note = "OBJECT DIFF (32x32 plates) + REST DIFF + TIMING" + (" · LocoTrack-S" if track else "")
141
+
142
+ shown, verdict = summary(res, min_s=min_s)
143
+ if explain:
144
+ from .explain import explain_diff
145
+ res["explanation"] = explain_diff(
146
+ res, fa, fb, shown, backend=explain_backend, model=explain_model,
147
+ url=explain_url, load_4bit=explain_4bit,
148
+ )
149
+ note = (note + " · " if note else "") + f"VLM ({res['explanation']['model']})"
150
+ badge, _ = diff_badge(shown, gated=gated, verdict=verdict)
151
+ return DiffResult(res, fa, fb, name_a, name_b, shown, verdict, badge, note=note, min_s=min_s, gated=gated)
152
+
153
+
154
+ def batch(a, b, out_dir, *, episodes=None, max_pairs=None, cam="side", fps=10, fp="global",
155
+ world_diff=False, channels=False, track=False, arm_diff=False, also=None,
156
+ min_s=1.0, gated=False, robot=None, log=print):
157
+ """Compare many video pairs or two checkpoints/datasets and write an interactive `index.html` dashboard."""
158
+ from .batch import resolve_batch_pairs, run_batch
159
+
160
+ pairs = resolve_batch_pairs(a, b, episodes=episodes, max_pairs=max_pairs)
161
+ use_ch = bool((channels or track or arm_diff or robot is not None) and not world_diff)
162
+ return run_batch(
163
+ pairs, out_dir, name_a=str(a), name_b=str(b), fps=fps, cam=cam, fp=fp,
164
+ world_diff_mode=world_diff, channels=use_ch, arm_diff=arm_diff, track=track,
165
+ robot=robot, also=also, min_s=min_s, gated=gated, log=log,
166
+ )
167
+
168
+
169
+ __all__ = ["__version__", "DiffResult", "diff", "batch"]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1 @@
1
+ # Vendored Apache-2.0 PyTorch LocoTrack (Cho et al., ECCV 2024, cvlab-kaist/locotrack)
@@ -0,0 +1,47 @@
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from einops import rearrange
5
+
6
+ from . import utils
7
+
8
+
9
+ class CMDTop(nn.Module):
10
+ def __init__(self, in_channel, out_channels, kernel_shapes, strides):
11
+ super(CMDTop, self).__init__()
12
+ self.in_channels = [in_channel] + list(out_channels[:-1])
13
+ self.out_channels = out_channels
14
+ self.kernel_shapes = kernel_shapes
15
+ self.strides = strides
16
+
17
+ self.conv = nn.ModuleList([
18
+ nn.Sequential(
19
+ utils.Conv2dSamePadding(
20
+ in_channels=self.in_channels[i],
21
+ out_channels=self.out_channels[i],
22
+ kernel_size=self.kernel_shapes[i],
23
+ stride=self.strides[i],
24
+ ),
25
+ nn.GroupNorm(out_channels[i] // 16, out_channels[i]),
26
+ nn.ReLU()
27
+ ) for i in range(len(out_channels))
28
+ ])
29
+
30
+ def forward(self, x):
31
+ """
32
+ x: (b, h, w, i, j)
33
+ """
34
+ out1 = rearrange(x, 'b h w i j -> b (i j) h w')
35
+ out2 = rearrange(x, 'b h w i j -> b (h w) i j')
36
+
37
+ for i in range(len(self.out_channels)):
38
+ out1 = self.conv[i](out1)
39
+
40
+ for i in range(len(self.out_channels)):
41
+ out2 = self.conv[i](out2)
42
+
43
+ out1 = torch.mean(out1, dim=(2, 3)) # (b, out_channels[-1])
44
+ out2 = torch.mean(out2, dim=(2, 3)) # (b, out_channels[-1])
45
+
46
+ return torch.cat([out1, out2], dim=-1) # (b, 2*out_channels[-1])
47
+