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.
- diffvid-1.0.1.dist-info/METADATA +275 -0
- diffvid-1.0.1.dist-info/RECORD +38 -0
- diffvid-1.0.1.dist-info/WHEEL +5 -0
- diffvid-1.0.1.dist-info/entry_points.txt +2 -0
- diffvid-1.0.1.dist-info/licenses/LICENSE +202 -0
- diffvid-1.0.1.dist-info/licenses/NOTICE +5 -0
- diffvid-1.0.1.dist-info/top_level.txt +1 -0
- rollout_diff/__init__.py +169 -0
- rollout_diff/__main__.py +5 -0
- rollout_diff/_locotrack/__init__.py +1 -0
- rollout_diff/_locotrack/cmdtop.py +47 -0
- rollout_diff/_locotrack/locotrack_model.py +1077 -0
- rollout_diff/_locotrack/nets.py +429 -0
- rollout_diff/_locotrack/utils.py +301 -0
- rollout_diff/arm_diff.py +324 -0
- rollout_diff/batch.py +692 -0
- rollout_diff/cli.py +475 -0
- rollout_diff/core.py +879 -0
- rollout_diff/explain.py +538 -0
- rollout_diff/export.py +215 -0
- rollout_diff/hub.py +207 -0
- rollout_diff/object_diff.py +672 -0
- rollout_diff/objects.py +245 -0
- rollout_diff/objlog.py +903 -0
- rollout_diff/point_diff.py +221 -0
- rollout_diff/profile.py +215 -0
- rollout_diff/report.py +758 -0
- rollout_diff/robot_mask.py +238 -0
- rollout_diff/teach.py +1374 -0
- rollout_diff/world/__init__.py +25 -0
- rollout_diff/world/changes.py +154 -0
- rollout_diff/world/compare.py +139 -0
- rollout_diff/world/config.py +28 -0
- rollout_diff/world/match.py +458 -0
- rollout_diff/world/models.py +214 -0
- rollout_diff/world/plates.py +312 -0
- rollout_diff/world/track.py +301 -0
- rollout_diff/world_diff.py +11 -0
rollout_diff/batch.py
ADDED
|
@@ -0,0 +1,692 @@
|
|
|
1
|
+
"""Batch comparison & checkpoint dashboard (`rollout-diff batch`).
|
|
2
|
+
|
|
3
|
+
Compares many video pairs in one run — either:
|
|
4
|
+
1. One reference run vs a folder of evaluation runs (`good.mp4 eval_dir/`)
|
|
5
|
+
2. Two folders of videos paired by filename or order (`ckpt10k/ ckpt20k/`)
|
|
6
|
+
3. Two LeRobot datasets (local or HF Hub, `ds_a ds_b --episodes 0-9`)
|
|
7
|
+
4. One reference run vs a LeRobot dataset (`good.mp4 ds_b --episodes 0-9`)
|
|
8
|
+
|
|
9
|
+
Outputs an interactive `index.html` checkpoint dashboard (worst-first sorting, filters,
|
|
10
|
+
A/B preview thumbnails, active-time delta stats, a plain-words conclusion, and links into each
|
|
11
|
+
episode's full report), plus `summary.md` (PR-ready Markdown table) and `summary.json`.
|
|
12
|
+
`match_starts` re-pairs each B run with the A run that started most alike (`--pair start`).
|
|
13
|
+
"""
|
|
14
|
+
import base64
|
|
15
|
+
import html
|
|
16
|
+
import json
|
|
17
|
+
import re
|
|
18
|
+
import weakref
|
|
19
|
+
from collections import Counter
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
import cv2
|
|
23
|
+
import numpy as np
|
|
24
|
+
|
|
25
|
+
from .core import (START_SCENE_GLOBAL_THR, START_SCENE_MEAN_THR, check_floor, compare, fingerprints,
|
|
26
|
+
load_run, start_scene_score)
|
|
27
|
+
from .hub import _hf_download, is_hub_repo
|
|
28
|
+
from .report import COLORS, INFO_KINDS, diff_badge, summary, write_html
|
|
29
|
+
|
|
30
|
+
VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm"}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _nat_key(text):
|
|
34
|
+
return [int(tok) if tok.isdigit() else tok.lower() for tok in re.split(r"(\d+)", str(text))]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _slugify(text):
|
|
38
|
+
s = re.sub(r"[^A-Za-z0-9._-]+", "_", str(text)).strip("._-")
|
|
39
|
+
return s or "run"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def parse_episodes(spec, total=None, default_limit=20):
|
|
43
|
+
"""Parse episode selection like '0-9', '0,2,5,8-10', or '0..4' into sorted unique ints."""
|
|
44
|
+
if spec is None or str(spec).strip() == "":
|
|
45
|
+
if total is None:
|
|
46
|
+
return []
|
|
47
|
+
return list(range(min(int(total), default_limit)))
|
|
48
|
+
out = []
|
|
49
|
+
for part in str(spec).split(","):
|
|
50
|
+
part = part.strip()
|
|
51
|
+
if not part:
|
|
52
|
+
continue
|
|
53
|
+
m = re.fullmatch(r"(\d+)\s*(?:-|\.\.)\s*(\d+)", part)
|
|
54
|
+
if m:
|
|
55
|
+
a, b = int(m.group(1)), int(m.group(2))
|
|
56
|
+
step = 1 if b >= a else -1
|
|
57
|
+
out.extend(range(a, b + step, step))
|
|
58
|
+
elif part.isdigit():
|
|
59
|
+
out.append(int(part))
|
|
60
|
+
else:
|
|
61
|
+
raise ValueError(f"Invalid --episodes token '{part}' (expected e.g. '0-9' or '0,2,5')")
|
|
62
|
+
seen, uniq = set(), []
|
|
63
|
+
for e in out:
|
|
64
|
+
if e not in seen:
|
|
65
|
+
seen.add(e)
|
|
66
|
+
uniq.append(e)
|
|
67
|
+
return uniq
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _is_single_run(spec):
|
|
71
|
+
s = str(spec)
|
|
72
|
+
if "#" in s:
|
|
73
|
+
return True
|
|
74
|
+
p = Path(s)
|
|
75
|
+
return p.is_file() and p.suffix.lower() in VIDEO_EXTS
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _is_lerobot_dataset(spec):
|
|
79
|
+
s = str(spec)
|
|
80
|
+
if "#" in s:
|
|
81
|
+
return False
|
|
82
|
+
p = Path(s)
|
|
83
|
+
if p.is_dir() and (p / "meta" / "info.json").exists():
|
|
84
|
+
return True
|
|
85
|
+
return is_hub_repo(s)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _lerobot_total_episodes(spec):
|
|
89
|
+
if is_hub_repo(spec):
|
|
90
|
+
info_p = _hf_download(spec, "meta/info.json")
|
|
91
|
+
else:
|
|
92
|
+
info_p = Path(spec) / "meta" / "info.json"
|
|
93
|
+
info = json.loads(info_p.read_text(encoding="utf-8"))
|
|
94
|
+
return int(info.get("total_episodes", 0))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _list_videos(folder):
|
|
98
|
+
p = Path(folder)
|
|
99
|
+
if not p.is_dir():
|
|
100
|
+
return []
|
|
101
|
+
direct = [f for f in p.iterdir() if f.is_file() and f.suffix.lower() in VIDEO_EXTS]
|
|
102
|
+
found = direct if direct else [f for f in p.rglob("*") if f.is_file() and f.suffix.lower() in VIDEO_EXTS]
|
|
103
|
+
return sorted(found, key=lambda f: _nat_key(f.relative_to(p).as_posix()))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def resolve_batch_pairs(src_a, src_b, episodes=None, max_pairs=None):
|
|
107
|
+
"""Resolve `(src_a, src_b)` into a list of `dict(id, label, a, b)` comparison pairs."""
|
|
108
|
+
a_single = _is_single_run(src_a)
|
|
109
|
+
b_single = _is_single_run(src_b)
|
|
110
|
+
a_ds = _is_lerobot_dataset(src_a)
|
|
111
|
+
b_ds = _is_lerobot_dataset(src_b)
|
|
112
|
+
|
|
113
|
+
raw_pairs = []
|
|
114
|
+
if a_single and not b_single:
|
|
115
|
+
if b_ds:
|
|
116
|
+
total = _lerobot_total_episodes(src_b) if not episodes else None
|
|
117
|
+
eps = parse_episodes(episodes, total=total)
|
|
118
|
+
raw_pairs = [(f"ep{e:03d}", str(src_a), f"{src_b}#{e}") for e in eps]
|
|
119
|
+
else:
|
|
120
|
+
vids_b = _list_videos(src_b)
|
|
121
|
+
# Avoid comparing a single reference video against itself if it lives inside src_b
|
|
122
|
+
ref_res = Path(src_a).resolve() if Path(src_a).is_file() else None
|
|
123
|
+
if ref_res is not None:
|
|
124
|
+
vids_b = [v for v in vids_b if v.resolve() != ref_res]
|
|
125
|
+
if episodes:
|
|
126
|
+
idxs = parse_episodes(episodes, total=len(vids_b))
|
|
127
|
+
vids_b = [vids_b[i] for i in idxs if 0 <= i < len(vids_b)]
|
|
128
|
+
raw_pairs = [(v.stem, str(src_a), str(v)) for v in vids_b]
|
|
129
|
+
elif a_ds and b_ds:
|
|
130
|
+
if episodes:
|
|
131
|
+
eps = parse_episodes(episodes)
|
|
132
|
+
else:
|
|
133
|
+
tot = min(_lerobot_total_episodes(src_a), _lerobot_total_episodes(src_b))
|
|
134
|
+
eps = parse_episodes(None, total=tot)
|
|
135
|
+
raw_pairs = [(f"ep{e:03d}", f"{src_a}#{e}", f"{src_b}#{e}") for e in eps]
|
|
136
|
+
elif not a_single and not b_single and not a_ds and not b_ds:
|
|
137
|
+
vids_a = _list_videos(src_a)
|
|
138
|
+
vids_b = _list_videos(src_b)
|
|
139
|
+
map_a = {v.stem: v for v in vids_a}
|
|
140
|
+
map_b = {v.stem: v for v in vids_b}
|
|
141
|
+
common = sorted(set(map_a) & set(map_b), key=_nat_key)
|
|
142
|
+
if common:
|
|
143
|
+
raw_pairs = [(stem, str(map_a[stem]), str(map_b[stem])) for stem in common]
|
|
144
|
+
else:
|
|
145
|
+
n = min(len(vids_a), len(vids_b))
|
|
146
|
+
raw_pairs = [(f"{i + 1:02d}_{vids_b[i].stem}", str(vids_a[i]), str(vids_b[i])) for i in range(n)]
|
|
147
|
+
if episodes:
|
|
148
|
+
idxs = parse_episodes(episodes, total=len(raw_pairs))
|
|
149
|
+
raw_pairs = [raw_pairs[i] for i in idxs if 0 <= i < len(raw_pairs)]
|
|
150
|
+
elif a_single and b_single:
|
|
151
|
+
raw_pairs = [(Path(str(src_b).split("#")[0]).stem, str(src_a), str(src_b))]
|
|
152
|
+
else:
|
|
153
|
+
raise ValueError(
|
|
154
|
+
f"Unsupported batch input combination: A='{src_a}', B='{src_b}'. "
|
|
155
|
+
"Use (ref_video, folder), (folderA, folderB), (datasetA, datasetB), or (ref_video, dataset)."
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
if max_pairs is not None and max_pairs > 0:
|
|
159
|
+
raw_pairs = raw_pairs[:int(max_pairs)]
|
|
160
|
+
|
|
161
|
+
used = set()
|
|
162
|
+
pairs = []
|
|
163
|
+
for label, a_sp, b_sp in raw_pairs:
|
|
164
|
+
base = _slugify(label)
|
|
165
|
+
slug = base
|
|
166
|
+
k = 2
|
|
167
|
+
while slug in used:
|
|
168
|
+
slug = f"{base}_{k}"
|
|
169
|
+
k += 1
|
|
170
|
+
used.add(slug)
|
|
171
|
+
pairs.append(dict(id=slug, label=str(label), a=a_sp, b=b_sp))
|
|
172
|
+
return pairs
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _first_fp(spec, fps=10, cam="side"):
|
|
176
|
+
# ponytail: decodes the whole run to get frame 0; add a first-frame reader if pairing gets slow
|
|
177
|
+
g, p = fingerprints(load_run(spec, fps=fps, cam=cam)[:1])
|
|
178
|
+
return g[0], p[0]
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def start_distance(fp_a, fp_b):
|
|
182
|
+
"""Frame-0 difference in units of the start-scene warning bars: below 1.0 = same start scene."""
|
|
183
|
+
mean, glob = start_scene_score(fp_a[1], fp_b[1], fp_a[0], fp_b[0])
|
|
184
|
+
return max(mean / START_SCENE_MEAN_THR, glob / START_SCENE_GLOBAL_THR)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def match_starts(pairs, fps=10, cam="side", first_fp=None, log=print):
|
|
188
|
+
"""Re-pair every B run with the A run (among the A runs in `pairs`) whose first frame is most alike.
|
|
189
|
+
A B run that no A run starts like (distance >= 1) gets a `skip` reason instead of an unfair comparison."""
|
|
190
|
+
first_fp = first_fp or (lambda s: _first_fp(s, fps, cam))
|
|
191
|
+
cands = list(dict.fromkeys(p["a"] for p in pairs))
|
|
192
|
+
fps_a = {a: first_fp(a) for a in cands}
|
|
193
|
+
out = []
|
|
194
|
+
for p in pairs:
|
|
195
|
+
fp_b = first_fp(p["b"])
|
|
196
|
+
dist = {a: start_distance(fps_a[a], fp_b) for a in cands}
|
|
197
|
+
best = min(cands, key=dist.get)
|
|
198
|
+
q = dict(p, a=best, start_dist=round(dist[best], 2))
|
|
199
|
+
if dist[best] >= 1.0:
|
|
200
|
+
q["skip"] = f"no A run starts like this one (closest: {best}, {dist[best]:.2f}x the same-scene limit)"
|
|
201
|
+
if log:
|
|
202
|
+
log(f" {p['label']}: " + (q.get("skip") or f"A = {best} (start {dist[best]:.2f}x limit)"))
|
|
203
|
+
out.append(q)
|
|
204
|
+
return out
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _thumb_b64(frame_rgb, box=None, color_hex="#e11d48", width=220):
|
|
208
|
+
h, w = frame_rgb.shape[:2]
|
|
209
|
+
im = cv2.resize(frame_rgb, (width, max(1, round(h * width / max(w, 1)))), interpolation=cv2.INTER_AREA)
|
|
210
|
+
bgr = cv2.cvtColor(im, cv2.COLOR_RGB2BGR)
|
|
211
|
+
if box is not None and len(box) == 4:
|
|
212
|
+
hh, ww = bgr.shape[:2]
|
|
213
|
+
x0, y0, x1, y1 = box
|
|
214
|
+
hx = color_hex.lstrip("#")
|
|
215
|
+
rgb = tuple(int(hx[i:i + 2], 16) for i in (0, 2, 4)) if len(hx) == 6 else (225, 29, 72)
|
|
216
|
+
cv2.rectangle(bgr, (int(x0 * ww), int(y0 * hh)), (int(x1 * ww), int(y1 * hh)), (rgb[2], rgb[1], rgb[0]), 2)
|
|
217
|
+
ok, buf = cv2.imencode(".jpg", bgr, [cv2.IMWRITE_JPEG_QUALITY, 72])
|
|
218
|
+
return base64.b64encode(buf).decode() if ok else ""
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _make_pair_thumbs(fa, fb, res, shown):
|
|
222
|
+
path = res.get("path") or []
|
|
223
|
+
sa, sb = res.get("trim_a", (0, len(fa)))[0], res.get("trim_b", (0, len(fb)))[0]
|
|
224
|
+
box, color, step = None, "#e11d48", (len(path) - 1 if path else 0)
|
|
225
|
+
for it in shown:
|
|
226
|
+
if not it.get("info") and it.get("box") and it["kind"] not in INFO_KINDS:
|
|
227
|
+
box = it["box"]
|
|
228
|
+
color = COLORS.get(it["kind"], "#e11d48")
|
|
229
|
+
step = int(it.get("peak_step", it.get("step", step)))
|
|
230
|
+
break
|
|
231
|
+
if path:
|
|
232
|
+
step = max(0, min(len(path) - 1, step))
|
|
233
|
+
ia, jb = path[step]
|
|
234
|
+
fa_f = fa[min(len(fa) - 1, ia + sa)]
|
|
235
|
+
fb_f = fb[min(len(fb) - 1, jb + sb)]
|
|
236
|
+
else:
|
|
237
|
+
fa_f, fb_f = fa[-1], fb[-1]
|
|
238
|
+
return _thumb_b64(fa_f), _thumb_b64(fb_f, box=box, color_hex=color)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def summarize_batch(records):
|
|
242
|
+
"""Aggregate per-episode batch records into checkpoint-level KPIs."""
|
|
243
|
+
total = len(records)
|
|
244
|
+
n_error = sum(1 for r in records if r["status"] == "ERROR")
|
|
245
|
+
n_skipped = sum(1 for r in records if r["status"] == "SKIPPED")
|
|
246
|
+
ok_recs = [r for r in records if r["status"] not in ("ERROR", "SKIPPED")]
|
|
247
|
+
n_diff = sum(1 for r in ok_recs if r["n_diffs"] > 0)
|
|
248
|
+
n_clean = len(ok_recs) - n_diff
|
|
249
|
+
clean_pct = round(100.0 * n_clean / max(len(ok_recs), 1), 1) if ok_recs else 0.0
|
|
250
|
+
|
|
251
|
+
act_a = [r["active_a"] for r in ok_recs if r.get("active_a") is not None]
|
|
252
|
+
act_b = [r["active_b"] for r in ok_recs if r.get("active_b") is not None]
|
|
253
|
+
act_d = [r["active_delta_s"] for r in ok_recs if r.get("active_delta_s") is not None]
|
|
254
|
+
med_a = round(float(np.median(act_a)), 2) if act_a else 0.0
|
|
255
|
+
med_b = round(float(np.median(act_b)), 2) if act_b else 0.0
|
|
256
|
+
med_d = round(float(np.median(act_d)), 2) if act_d else 0.0
|
|
257
|
+
|
|
258
|
+
# whole-run active time only: a run with one slower and one faster step is not counted as both
|
|
259
|
+
n_slower = sum(1 for r in ok_recs if r["active_delta_s"] >= 1.0)
|
|
260
|
+
n_faster = sum(1 for r in ok_recs if r["active_delta_s"] <= -1.0)
|
|
261
|
+
n_start_warn = sum(1 for r in ok_recs if r.get("start_scene_warning"))
|
|
262
|
+
|
|
263
|
+
kc = Counter()
|
|
264
|
+
for r in ok_recs:
|
|
265
|
+
for k, v in (r.get("kinds") or {}).items():
|
|
266
|
+
if k not in INFO_KINDS:
|
|
267
|
+
kc[k] += int(v)
|
|
268
|
+
return dict(
|
|
269
|
+
total=total,
|
|
270
|
+
n_ok=len(ok_recs),
|
|
271
|
+
n_clean=n_clean,
|
|
272
|
+
n_diff=n_diff,
|
|
273
|
+
n_error=n_error,
|
|
274
|
+
n_skipped=n_skipped,
|
|
275
|
+
clean_pct=clean_pct, # share of compared pairs with no difference (not a task success rate)
|
|
276
|
+
median_active_a=med_a,
|
|
277
|
+
median_active_b=med_b,
|
|
278
|
+
median_active_delta_s=med_d,
|
|
279
|
+
n_slower=n_slower,
|
|
280
|
+
n_faster=n_faster,
|
|
281
|
+
n_start_warn=n_start_warn,
|
|
282
|
+
kind_counts=dict(kc.most_common()),
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def conclusion(records, stats):
|
|
287
|
+
"""The batch in a few plain sentences (dashboard, summary.md and summary.json)."""
|
|
288
|
+
ok = [r for r in records if r["status"] not in ("ERROR", "SKIPPED")]
|
|
289
|
+
if not ok:
|
|
290
|
+
return ["No pair could be compared."]
|
|
291
|
+
out = [f"B differs from A in {stats['n_diff']} of {stats['n_ok']} compared episodes "
|
|
292
|
+
f"({stats['n_clean']} show no difference)."]
|
|
293
|
+
d = stats["median_active_delta_s"]
|
|
294
|
+
timing = (f"median active time {stats['median_active_a']:.1f} s → {stats['median_active_b']:.1f} s ({d:+.1f} s); "
|
|
295
|
+
f"{stats['n_slower']} slower, {stats['n_faster']} faster.")
|
|
296
|
+
out.append((f"B is {'slower' if d > 0 else 'faster'}: " if abs(d) >= 1.0 else "Timing is about the same: ") + timing)
|
|
297
|
+
eps = Counter(k for r in ok for k in r["kinds"])
|
|
298
|
+
if eps:
|
|
299
|
+
out.append("Most common: " + ", ".join(f"`{k}` in {v} episode{'s' if v > 1 else ''}"
|
|
300
|
+
for k, v in eps.most_common(3)) + ".")
|
|
301
|
+
worst = max(ok, key=lambda r: (r["n_diffs"], r["active_delta_s"]))
|
|
302
|
+
if worst["n_diffs"]:
|
|
303
|
+
out.append(f"Look first at {worst['label']} ({worst['n_diffs']} differences, {worst['active_delta_s']:+.1f} s).")
|
|
304
|
+
if stats["n_start_warn"]:
|
|
305
|
+
out.append(f"{stats['n_start_warn']} pair(s) started from different scenes: part of their differences may "
|
|
306
|
+
"come from the start, not the policy.")
|
|
307
|
+
if stats["n_skipped"]:
|
|
308
|
+
out.append(f"{stats['n_skipped']} B run(s) skipped: no A run started like them.")
|
|
309
|
+
if stats["n_error"]:
|
|
310
|
+
out.append(f"{stats['n_error']} episode(s) could not be compared (see the table).")
|
|
311
|
+
return out
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def format_markdown(records, stats, name_a, name_b, gated=False, note=""):
|
|
315
|
+
"""Render a clean GitHub-Flavored Markdown summary table (PR-comment ready)."""
|
|
316
|
+
lines = [
|
|
317
|
+
f"## rollout-diff batch summary (`{name_a}` → `{name_b}`)",
|
|
318
|
+
"",
|
|
319
|
+
"**Conclusion:** " + " ".join(conclusion(records, stats)),
|
|
320
|
+
"",
|
|
321
|
+
(f"- **Episodes:** {stats['total']} total · **{stats['n_clean']} clean** · "
|
|
322
|
+
f"**{stats['n_diff']} with diffs** ({stats['clean_pct']:.1f}% clean)"
|
|
323
|
+
+ (f" · **{stats['n_skipped']} skipped**" if stats["n_skipped"] else "")
|
|
324
|
+
+ (f" · **{stats['n_error']} errors**" if stats["n_error"] else "")),
|
|
325
|
+
(f"- **Median active time:** {stats['median_active_a']:.1f} s → {stats['median_active_b']:.1f} s "
|
|
326
|
+
f"(**{stats['median_active_delta_s']:+.1f} s**) · {stats['n_slower']} slower, {stats['n_faster']} faster"),
|
|
327
|
+
]
|
|
328
|
+
if stats["kind_counts"]:
|
|
329
|
+
parts = ", ".join(f"`{k}` ×{v}" for k, v in stats["kind_counts"].items())
|
|
330
|
+
lines.append(f"- **Difference types:** {parts}")
|
|
331
|
+
if stats["n_start_warn"]:
|
|
332
|
+
lines.append(f"- **Start-scene warnings:** {stats['n_start_warn']} pair(s) started from different scenes")
|
|
333
|
+
if note:
|
|
334
|
+
lines.append(f"- **Mode:** {note}")
|
|
335
|
+
lines += [
|
|
336
|
+
"",
|
|
337
|
+
"| Episode | Status | Active Time | Differences | Report |",
|
|
338
|
+
"| :--- | :---: | :---: | :--- | :---: |",
|
|
339
|
+
]
|
|
340
|
+
rank = {"ERROR": 0, "SKIPPED": 2}
|
|
341
|
+
ordered = sorted(records, key=lambda r: (rank.get(r["status"], 1), -r["n_diffs"], -r.get("end_score", 0.0)))
|
|
342
|
+
for r in ordered:
|
|
343
|
+
if r["status"] in rank:
|
|
344
|
+
lines.append(f"| `{r['label']}` | {r['status']} | – | {r['top_text'].replace('|', '/')} | – |")
|
|
345
|
+
continue
|
|
346
|
+
t_str = f"{r['active_a']:.1f} s → {r['active_b']:.1f} s ({r['active_delta_s']:+.1f} s)"
|
|
347
|
+
diff_txt = r["top_text"].replace("|", "/") if r["top_text"] else "no differences"
|
|
348
|
+
href = f"[open]({r['report_href']})" if r.get("report_href") else "–"
|
|
349
|
+
lines.append(f"| `{r['label']}` | **{r['badge']}** | {t_str} | {diff_txt} | {href} |")
|
|
350
|
+
return "\n".join(lines) + "\n"
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def write_dashboard_html(records, stats, out_path, name_a, name_b, gated=False, note=""):
|
|
354
|
+
"""Write a self-contained interactive HTML checkpoint dashboard (`index.html`)."""
|
|
355
|
+
if stats["n_error"] and stats["n_ok"] == 0:
|
|
356
|
+
badge_txt, badge_cls = f"{stats['n_error']} ERRORS", "fail"
|
|
357
|
+
elif stats["n_diff"] == 0:
|
|
358
|
+
badge_txt, badge_cls = ("ALL PASS" if gated else "ALL CLEAN"), "pass"
|
|
359
|
+
else:
|
|
360
|
+
badge_txt = f"{stats['n_diff']} / {stats['n_ok']} " + ("FAILED" if gated else "WITH DIFFS")
|
|
361
|
+
badge_cls = "fail" if gated else "diff"
|
|
362
|
+
|
|
363
|
+
payload = dict(
|
|
364
|
+
records=[{k: v for k, v in r.items() if k != "items"} for r in records],
|
|
365
|
+
stats=stats,
|
|
366
|
+
colors=COLORS,
|
|
367
|
+
info_kinds=sorted(INFO_KINDS),
|
|
368
|
+
)
|
|
369
|
+
meta_parts = [f"A: {html.escape(str(name_a))}", f"B: {html.escape(str(name_b))}"]
|
|
370
|
+
if note:
|
|
371
|
+
meta_parts.append(html.escape(str(note)))
|
|
372
|
+
bold = lambda s: re.sub(r"`([^`]+)`", r"<b>\1</b>", html.escape(s))
|
|
373
|
+
concl = "".join("<li>" + bold(s) + "</li>" for s in conclusion(records, stats))
|
|
374
|
+
page = (
|
|
375
|
+
DASHBOARD_TEMPLATE
|
|
376
|
+
.replace("__DATA__", json.dumps(payload).replace("</", "<\\/")) # names cannot close the <script>
|
|
377
|
+
.replace("__BADGE__", html.escape(badge_txt))
|
|
378
|
+
.replace("__BCLASS__", badge_cls)
|
|
379
|
+
.replace("__META__", " · ".join(meta_parts))
|
|
380
|
+
.replace("__CONCLUSION__", concl)
|
|
381
|
+
)
|
|
382
|
+
Path(out_path).write_text(page, encoding="utf-8")
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _memoize_robot_mask(robot_fn):
|
|
386
|
+
"""Wrap a robot cut-out callable so repeated reference / `--also` videos are masked once per batch."""
|
|
387
|
+
if robot_fn is None:
|
|
388
|
+
return None
|
|
389
|
+
cache = {}
|
|
390
|
+
|
|
391
|
+
def _wrapped(frames, idx, run_motion):
|
|
392
|
+
key = (id(frames), frames.shape, int(idx[0]), int(idx[-1]), len(idx))
|
|
393
|
+
if key not in cache:
|
|
394
|
+
cache[key] = robot_fn(frames, idx, run_motion)
|
|
395
|
+
weakref.finalize(frames, cache.pop, key, None) # run freed: drop its masks (a new run may reuse its id)
|
|
396
|
+
return cache[key]
|
|
397
|
+
|
|
398
|
+
return _wrapped
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _bare_rec(pair, i, status, text):
|
|
402
|
+
"""Table row for a pair that was skipped or could not be compared."""
|
|
403
|
+
return dict(id=pair["id"], index=i, label=pair["label"], spec_a=pair["a"], spec_b=pair["b"], report_href=None,
|
|
404
|
+
status=status, badge=status, badge_cls="fail" if status == "ERROR" else "skip", n_diffs=0, kinds={},
|
|
405
|
+
dur_a=0.0, dur_b=0.0, active_a=None, active_b=None, active_delta_s=None, end_score=0.0,
|
|
406
|
+
start_scene_warning=None, start_dist=pair.get("start_dist"), top_text=text,
|
|
407
|
+
thumb_a="", thumb_b="", items=[])
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def run_batch(pairs, out_dir, name_a="", name_b="", fps=10, cam="side", fp="global",
|
|
411
|
+
alike=None, idle=None, spatial=True, spatial_thr=None, mid_thr=None,
|
|
412
|
+
world_diff_mode=False, channels=False, arm_diff=False, track=False,
|
|
413
|
+
robot=None, change_model=None, match_model=None, also=None,
|
|
414
|
+
min_s=1.0, gated=False, note="", floor=None, reports="all", log=print):
|
|
415
|
+
"""Execute a full batch comparison, writing per-episode HTML reports + `index.html` + `summary.md/json`.
|
|
416
|
+
`floor`: a `rollout-diff calibrate` result; adds its timing check and PASS/FAIL. `reports="diff"`: write
|
|
417
|
+
per-episode reports only for pairs with differences. Pairs with a `skip` reason are listed, not compared."""
|
|
418
|
+
out_p = Path(out_dir)
|
|
419
|
+
out_p.mkdir(parents=True, exist_ok=True)
|
|
420
|
+
frame_cache = {}
|
|
421
|
+
robot_cached = _memoize_robot_mask(robot)
|
|
422
|
+
todo = [p for p in pairs if not p.get("skip")]
|
|
423
|
+
uses = Counter([p["a"] for p in todo] + [p["b"] for p in todo])
|
|
424
|
+
|
|
425
|
+
def _get_frames(spec):
|
|
426
|
+
if spec in frame_cache:
|
|
427
|
+
return frame_cache[spec]
|
|
428
|
+
frames = load_run(spec, fps=fps, cam=cam)
|
|
429
|
+
if uses[spec] > 1: # only runs used again (the reference) stay in RAM; one-off runs are freed
|
|
430
|
+
frame_cache[spec] = frames
|
|
431
|
+
return frames
|
|
432
|
+
|
|
433
|
+
goods_frames = [load_run(g, fps=fps, cam=cam) for g in (also or [])]
|
|
434
|
+
records = []
|
|
435
|
+
for i, pair in enumerate(pairs, start=1):
|
|
436
|
+
label, sp_a, sp_b, slug = pair["label"], pair["a"], pair["b"], pair["id"]
|
|
437
|
+
if pair.get("skip"):
|
|
438
|
+
records.append(_bare_rec(pair, i, "SKIPPED", pair["skip"]))
|
|
439
|
+
if log:
|
|
440
|
+
log(f"[{i}/{len(pairs)}] {label}: SKIPPED ({pair['skip']})")
|
|
441
|
+
continue
|
|
442
|
+
if log:
|
|
443
|
+
log(f"[{i}/{len(pairs)}] {label}: {sp_a} vs {sp_b}")
|
|
444
|
+
try:
|
|
445
|
+
fa = _get_frames(sp_a)
|
|
446
|
+
fb = _get_frames(sp_b)
|
|
447
|
+
kw = dict(fps=fps, fp=fp, alike=alike, idle=idle)
|
|
448
|
+
if world_diff_mode and spatial:
|
|
449
|
+
from . import world_diff
|
|
450
|
+
res = compare(fa, fb, spatial=False, **kw)
|
|
451
|
+
res["spatial"] = world_diff.spot_world(
|
|
452
|
+
fa, fb, res, goods=goods_frames, change_model=change_model,
|
|
453
|
+
mask_model=robot_cached, match_model=match_model,
|
|
454
|
+
)
|
|
455
|
+
res["spatial_items"] = res["spatial"]["items"]
|
|
456
|
+
else:
|
|
457
|
+
ckw = dict(kw, spatial=spatial, robot=robot_cached, channels=channels,
|
|
458
|
+
arm_diff=arm_diff, track=track, spec_a=sp_a, spec_b=sp_b, goods=goods_frames)
|
|
459
|
+
if spatial_thr is not None:
|
|
460
|
+
ckw["spatial_thr"] = spatial_thr
|
|
461
|
+
if mid_thr is not None:
|
|
462
|
+
ckw["mid_thr"] = mid_thr
|
|
463
|
+
res = compare(fa, fb, **ckw)
|
|
464
|
+
|
|
465
|
+
floor_items = check_floor(res, floor) if floor else None
|
|
466
|
+
shown, verdict = summary(res, min_s=min_s, floor_items=floor_items)
|
|
467
|
+
badge, bcls = diff_badge(shown, gated=gated, verdict=verdict)
|
|
468
|
+
non_info = [it for it in shown if it["kind"] not in INFO_KINDS]
|
|
469
|
+
rep_name = f"{slug}.html" if (reports == "all" or non_info or verdict == "FAIL") else None
|
|
470
|
+
if rep_name:
|
|
471
|
+
write_html(res, fa, fb, str(out_p / rep_name), sp_a, sp_b, min_s=min_s, floor_items=floor_items,
|
|
472
|
+
floor_note=note, gated=gated)
|
|
473
|
+
|
|
474
|
+
(sa, ea), (sb, eb) = res["trim_a"], res["trim_b"]
|
|
475
|
+
act_a, act_b = round((ea - sa) / fps, 2), round((eb - sb) / fps, 2)
|
|
476
|
+
kinds = dict(Counter(it["kind"] for it in non_info))
|
|
477
|
+
top_lines = [f"{it['kind']}: {it['text']}" for it in non_info[:2]]
|
|
478
|
+
if len(non_info) > 2:
|
|
479
|
+
top_lines.append(f"+{len(non_info) - 2} more")
|
|
480
|
+
th_a, th_b = _make_pair_thumbs(fa, fb, res, shown)
|
|
481
|
+
sp = res.get("spatial") or {}
|
|
482
|
+
rec = dict(
|
|
483
|
+
id=slug,
|
|
484
|
+
index=i,
|
|
485
|
+
label=label,
|
|
486
|
+
spec_a=sp_a,
|
|
487
|
+
spec_b=sp_b,
|
|
488
|
+
report_href=rep_name,
|
|
489
|
+
status=verdict if gated else ("DIFF" if non_info else "NO DIFF"),
|
|
490
|
+
badge=badge,
|
|
491
|
+
badge_cls=bcls,
|
|
492
|
+
n_diffs=len(non_info),
|
|
493
|
+
kinds=kinds,
|
|
494
|
+
dur_a=round(res["len_a"] / fps, 2),
|
|
495
|
+
dur_b=round(res["len_b"] / fps, 2),
|
|
496
|
+
active_a=act_a,
|
|
497
|
+
active_b=act_b,
|
|
498
|
+
active_delta_s=round(act_b - act_a, 2),
|
|
499
|
+
end_score=round(float(sp.get("end_score", 0.0)), 3),
|
|
500
|
+
start_scene_warning=res.get("start_scene_warning"),
|
|
501
|
+
start_dist=pair.get("start_dist"),
|
|
502
|
+
top_text=" · ".join(top_lines),
|
|
503
|
+
thumb_a=th_a,
|
|
504
|
+
thumb_b=th_b,
|
|
505
|
+
items=shown,
|
|
506
|
+
)
|
|
507
|
+
if log:
|
|
508
|
+
log(f" -> {badge:10s} active {act_a:.1f}s -> {act_b:.1f}s ({act_b - act_a:+.1f}s)"
|
|
509
|
+
+ (f" | {top_lines[0]}" if top_lines else ""))
|
|
510
|
+
except Exception as exc:
|
|
511
|
+
rec = dict(_bare_rec(pair, i, "ERROR", str(exc)), error=str(exc))
|
|
512
|
+
if log:
|
|
513
|
+
log(f" -> ERROR: {exc}")
|
|
514
|
+
records.append(rec)
|
|
515
|
+
|
|
516
|
+
stats = summarize_batch(records)
|
|
517
|
+
na = name_a or (pairs[0]["a"] if pairs else "")
|
|
518
|
+
nb = name_b or (pairs[0]["b"] if pairs else "")
|
|
519
|
+
md_text = format_markdown(records, stats, na, nb, gated=gated, note=note)
|
|
520
|
+
(out_p / "summary.md").write_text(md_text, encoding="utf-8")
|
|
521
|
+
write_dashboard_html(records, stats, out_p / "index.html", na, nb, gated=gated, note=note)
|
|
522
|
+
|
|
523
|
+
json_payload = dict(
|
|
524
|
+
a=na, b=nb, note=note, gated=gated, stats=stats, conclusion=conclusion(records, stats),
|
|
525
|
+
records=[{k: v for k, v in r.items() if k not in ("thumb_a", "thumb_b")} for r in records],
|
|
526
|
+
)
|
|
527
|
+
(out_p / "summary.json").write_text(json.dumps(json_payload, indent=1, default=float), encoding="utf-8")
|
|
528
|
+
return dict(records=records, stats=stats, markdown=md_text, out_dir=str(out_p))
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
DASHBOARD_TEMPLATE = """<!doctype html>
|
|
532
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
533
|
+
<title>rollout-diff batch dashboard</title>
|
|
534
|
+
<style>
|
|
535
|
+
:root { --bg:#f4f6f9; --card:#fff; --ink:#16202a; --muted:#5d6b78; --line:#d5dce3; --accent:#e11d48; --ok:#15803d; --warn:#d97706; }
|
|
536
|
+
@media (prefers-color-scheme: dark) { :root { --bg:#11151b; --card:#1a2029; --ink:#e6ebf0; --muted:#94a3b8; --line:#2b3544; --accent:#fb7185; --ok:#22c55e; --warn:#f59e0b; } }
|
|
537
|
+
* { box-sizing: border-box; }
|
|
538
|
+
body { margin:0; background:var(--bg); color:var(--ink); font:14px/1.45 system-ui, "Segoe UI", sans-serif; }
|
|
539
|
+
main { max-width:1240px; margin:0 auto; padding:20px 16px 48px; display:grid; gap:14px; }
|
|
540
|
+
.card { background:var(--card); border:1px solid var(--line); border-radius:12px; padding:16px 18px; }
|
|
541
|
+
h1 { font-size:21px; margin:0 0 4px; display:flex; flex-wrap:wrap; align-items:center; gap:10px; }
|
|
542
|
+
.muted { color:var(--muted); font-size:12.5px; }
|
|
543
|
+
.badge { display:inline-block; padding:2px 10px; border-radius:6px; font-weight:700; font-size:12.5px; color:#fff; white-space:nowrap; }
|
|
544
|
+
.badge.pass { background:#15803d; } .badge.fail { background:#dc2626; } .badge.diff { background:#ea580c; } .badge.skip { background:#64748b; }
|
|
545
|
+
.concl { margin:0; padding-left:20px; } .concl li { margin:3px 0; }
|
|
546
|
+
.kpis { display:grid; grid-template-columns:repeat(auto-fit, minmax(220px, 1fr)); gap:12px; }
|
|
547
|
+
.kpi { background:var(--card); border:1px solid var(--line); border-radius:12px; padding:14px 16px; }
|
|
548
|
+
.kpi-lbl { font-size:11.5px; text-transform:uppercase; letter-spacing:.05em; color:var(--muted); font-weight:700; }
|
|
549
|
+
.kpi-val { font-size:24px; font-weight:700; margin:4px 0 4px; font-variant-numeric:tabular-nums; }
|
|
550
|
+
.bar { height:7px; border-radius:99px; background:var(--line); overflow:hidden; margin-top:8px; }
|
|
551
|
+
.bar > i { display:block; height:100%; background:#15803d; }
|
|
552
|
+
.pills { display:flex; flex-wrap:wrap; gap:5px; margin-top:6px; }
|
|
553
|
+
.tag { display:inline-block; font-size:11px; font-weight:700; padding:2px 7px; border-radius:4px; color:#fff; letter-spacing:.02em; }
|
|
554
|
+
.toolbar { display:flex; flex-wrap:wrap; gap:8px; align-items:center; margin-bottom:12px; }
|
|
555
|
+
.btn { padding:5px 11px; border-radius:6px; border:1px solid var(--line); background:var(--bg); color:var(--ink); cursor:pointer; font:13px/1.2 system-ui; }
|
|
556
|
+
.btn.active { background:var(--ink); color:var(--card); border-color:var(--ink); }
|
|
557
|
+
.search { padding:5px 10px; border-radius:6px; border:1px solid var(--line); background:var(--bg); color:var(--ink); font:13px system-ui; min-width:190px; }
|
|
558
|
+
.sep { flex:1; }
|
|
559
|
+
table { width:100%; border-collapse:collapse; }
|
|
560
|
+
th, td { text-align:left; padding:10px 8px; border-bottom:1px solid var(--line); vertical-align:middle; }
|
|
561
|
+
th { font-size:11.5px; text-transform:uppercase; letter-spacing:.05em; color:var(--muted); }
|
|
562
|
+
tr.row { cursor:pointer; transition:background .12s ease; }
|
|
563
|
+
tr.row:hover { background:var(--bg); }
|
|
564
|
+
.thumbs { display:flex; gap:4px; min-width:196px; }
|
|
565
|
+
.thumbs img { width:96px; height:64px; object-fit:cover; border-radius:5px; border:1px solid var(--line); background:#000; display:block; }
|
|
566
|
+
.delta { font-weight:700; font-variant-numeric:tabular-nums; }
|
|
567
|
+
.delta.slow { color:#d97706; } .delta.fast { color:#2563eb; } .delta.flat { color:var(--muted); }
|
|
568
|
+
.warn-pill { display:inline-block; font-size:11px; font-weight:700; color:#b45309; background:rgba(245,158,11,.16); border:1px solid #f59e0b; padding:1px 6px; border-radius:4px; margin-left:6px; }
|
|
569
|
+
.open-link { display:inline-block; padding:5px 10px; border-radius:6px; border:1px solid var(--line); text-decoration:none; color:var(--ink); font-weight:600; font-size:12.5px; white-space:nowrap; }
|
|
570
|
+
.open-link:hover { border-color:var(--accent); color:var(--accent); }
|
|
571
|
+
.empty { text-align:center; padding:28px; color:var(--muted); }
|
|
572
|
+
</style></head>
|
|
573
|
+
<body><main>
|
|
574
|
+
<section class="card">
|
|
575
|
+
<h1>rollout-diff batch <span class="badge __BCLASS__">__BADGE__</span></h1>
|
|
576
|
+
<div class="muted">__META__</div>
|
|
577
|
+
</section>
|
|
578
|
+
<section class="card"><div class="kpi-lbl" style="margin-bottom:6px">Conclusion</div><ul class="concl">__CONCLUSION__</ul></section>
|
|
579
|
+
<section class="kpis" id="kpis"></section>
|
|
580
|
+
<section class="card">
|
|
581
|
+
<div class="toolbar">
|
|
582
|
+
<button class="btn active" data-flt="all">All</button>
|
|
583
|
+
<button class="btn" data-flt="diff">Diffs only</button>
|
|
584
|
+
<button class="btn" data-flt="clean">No diff</button>
|
|
585
|
+
<button class="btn" data-flt="slow">Slower</button>
|
|
586
|
+
<span class="sep"></span>
|
|
587
|
+
<input class="search" id="q" type="search" placeholder="Filter episodes or diff text...">
|
|
588
|
+
<select class="btn" id="sort">
|
|
589
|
+
<option value="worst">Sort: Worst first</option>
|
|
590
|
+
<option value="slowest">Sort: Slowest first</option>
|
|
591
|
+
<option value="order">Sort: Episode order</option>
|
|
592
|
+
</select>
|
|
593
|
+
</div>
|
|
594
|
+
<div style="overflow-x:auto">
|
|
595
|
+
<table>
|
|
596
|
+
<thead><tr><th>Preview (A / B)</th><th>Episode</th><th>Status</th><th>Active Time</th><th>Differences</th><th></th></tr></thead>
|
|
597
|
+
<tbody id="tbody"></tbody>
|
|
598
|
+
</table>
|
|
599
|
+
</div>
|
|
600
|
+
</section>
|
|
601
|
+
</main>
|
|
602
|
+
<script>
|
|
603
|
+
const D = __DATA__;
|
|
604
|
+
const S = D.stats;
|
|
605
|
+
const esc = s => String(s || "").replace(/[&<>"]/g, c => ({"&":"&","<":"<",">":">",'"':"""}[c]));
|
|
606
|
+
|
|
607
|
+
// 1. Render KPI cards
|
|
608
|
+
const kpiBox = document.getElementById("kpis");
|
|
609
|
+
const kindPills = Object.entries(S.kind_counts || {}).map(([k, v]) =>
|
|
610
|
+
`<span class="tag" style="background:${D.colors[k] || '#64748b'}">${esc(k)} ×${v}</span>`
|
|
611
|
+
).join("") || `<span class="muted">None</span>`;
|
|
612
|
+
const dSign = S.median_active_delta_s >= 0 ? "+" : "";
|
|
613
|
+
kpiBox.innerHTML = `
|
|
614
|
+
<div class="kpi">
|
|
615
|
+
<div class="kpi-lbl">Clean vs Changed</div>
|
|
616
|
+
<div class="kpi-val">${S.n_clean} / ${S.n_ok} clean</div>
|
|
617
|
+
<div class="muted">${S.clean_pct.toFixed(1)}% clean · ${S.n_diff} with diffs${S.n_skipped ? ` · ${S.n_skipped} skipped` : ""}${S.n_error ? ` · ${S.n_error} errors` : ""}</div>
|
|
618
|
+
<div class="bar"><i style="width:${Math.max(0, Math.min(100, S.clean_pct))}%"></i></div>
|
|
619
|
+
</div>
|
|
620
|
+
<div class="kpi">
|
|
621
|
+
<div class="kpi-lbl">Median Active Time</div>
|
|
622
|
+
<div class="kpi-val">${S.median_active_a.toFixed(1)} s → ${S.median_active_b.toFixed(1)} s</div>
|
|
623
|
+
<div class="muted">median delta <b>${dSign}${S.median_active_delta_s.toFixed(1)} s</b> · ${S.n_slower} slower, ${S.n_faster} faster</div>
|
|
624
|
+
</div>
|
|
625
|
+
<div class="kpi">
|
|
626
|
+
<div class="kpi-lbl">Difference Breakdown</div>
|
|
627
|
+
<div class="pills">${kindPills}</div>
|
|
628
|
+
</div>
|
|
629
|
+
<div class="kpi">
|
|
630
|
+
<div class="kpi-lbl">Scene Health</div>
|
|
631
|
+
<div class="kpi-val">${S.n_start_warn} warnings</div>
|
|
632
|
+
<div class="muted">${S.n_start_warn ? "Start scenes differed on some pairs" : "All pairs matched start scene"} · ${S.total} total episodes</div>
|
|
633
|
+
</div>`;
|
|
634
|
+
|
|
635
|
+
// Update filter counts
|
|
636
|
+
document.querySelector('[data-flt="all"]').textContent = `All (${D.records.length})`;
|
|
637
|
+
document.querySelector('[data-flt="diff"]').textContent = `Diffs only (${S.n_diff + S.n_error})`;
|
|
638
|
+
document.querySelector('[data-flt="clean"]').textContent = `No diff (${S.n_clean})`;
|
|
639
|
+
document.querySelector('[data-flt="slow"]').textContent = `Slower (${S.n_slower})`;
|
|
640
|
+
|
|
641
|
+
let flt = "all", sortBy = "worst", query = "";
|
|
642
|
+
const tbody = document.getElementById("tbody");
|
|
643
|
+
|
|
644
|
+
function render() {
|
|
645
|
+
let rows = D.records.slice();
|
|
646
|
+
if (flt === "diff") rows = rows.filter(r => r.n_diffs > 0 || r.status === "ERROR");
|
|
647
|
+
else if (flt === "clean") rows = rows.filter(r => r.n_diffs === 0 && r.status !== "ERROR");
|
|
648
|
+
else if (flt === "slow") rows = rows.filter(r => r.active_delta_s >= 1.0);
|
|
649
|
+
if (query) {
|
|
650
|
+
const q = query.toLowerCase();
|
|
651
|
+
rows = rows.filter(r => (r.label + " " + r.top_text + " " + Object.keys(r.kinds || {}).join(" ")).toLowerCase().includes(q));
|
|
652
|
+
}
|
|
653
|
+
if (sortBy === "worst") {
|
|
654
|
+
rows.sort((a, b) => (b.status === "ERROR") - (a.status === "ERROR") || b.n_diffs - a.n_diffs || b.end_score - a.end_score || a.index - b.index);
|
|
655
|
+
} else if (sortBy === "slowest") {
|
|
656
|
+
rows.sort((a, b) => (b.active_delta_s ?? -999) - (a.active_delta_s ?? -999));
|
|
657
|
+
} else {
|
|
658
|
+
rows.sort((a, b) => a.index - b.index);
|
|
659
|
+
}
|
|
660
|
+
if (!rows.length) {
|
|
661
|
+
tbody.innerHTML = `<tr><td colspan="6" class="empty">No episodes match the current filter.</td></tr>`;
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
tbody.innerHTML = rows.map(r => {
|
|
665
|
+
const thumbs = r.thumb_a ? `<div class="thumbs"><img src="data:image/jpeg;base64,${r.thumb_a}" alt="A"><img src="data:image/jpeg;base64,${r.thumb_b}" alt="B"></div>` : `<span class="muted">–</span>`;
|
|
666
|
+
const tags = Object.entries(r.kinds || {}).map(([k, v]) =>
|
|
667
|
+
`<span class="tag" style="background:${D.colors[k] || '#64748b'}">${esc(k)}${v > 1 ? ` ×${v}` : ""}</span>`
|
|
668
|
+
).join(" ");
|
|
669
|
+
const dt = r.active_a != null ? `${r.active_a.toFixed(1)} s → ${r.active_b.toFixed(1)} s<br><span class="delta ${r.active_delta_s >= 1 ? "slow" : r.active_delta_s <= -1 ? "fast" : "flat"}">${r.active_delta_s >= 0 ? "+" : ""}${r.active_delta_s.toFixed(1)} s</span>` : "–";
|
|
670
|
+
const warn = r.start_scene_warning ? `<span class="warn-pill" title="${esc(r.start_scene_warning)}">Start differs</span>` : "";
|
|
671
|
+
const link = r.report_href ? `<a class="open-link" href="${esc(r.report_href)}" onclick="event.stopPropagation()">Open report →</a>` : "";
|
|
672
|
+
const click = r.report_href ? `onclick="window.location.href='${esc(r.report_href)}'"` : "";
|
|
673
|
+
return `<tr class="row" ${click}>
|
|
674
|
+
<td>${thumbs}</td>
|
|
675
|
+
<td><b>${esc(r.label)}</b>${warn}<div class="muted" style="max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${esc(r.spec_b)}">${esc(r.spec_b)}</div></td>
|
|
676
|
+
<td><span class="badge ${esc(r.badge_cls)}">${esc(r.badge)}</span></td>
|
|
677
|
+
<td style="white-space:nowrap">${dt}</td>
|
|
678
|
+
<td><div class="pills" style="margin:0 0 4px">${tags}</div><div class="muted">${esc(r.top_text || "No differences spotted above threshold.")}</div></td>
|
|
679
|
+
<td>${link}</td>
|
|
680
|
+
</tr>`;
|
|
681
|
+
}).join("");
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
document.querySelectorAll("[data-flt]").forEach(b => b.onclick = () => {
|
|
685
|
+
document.querySelectorAll("[data-flt]").forEach(x => x.classList.remove("active"));
|
|
686
|
+
b.classList.add("active"); flt = b.dataset.flt; render();
|
|
687
|
+
});
|
|
688
|
+
document.getElementById("sort").onchange = e => { sortBy = e.target.value; render(); };
|
|
689
|
+
document.getElementById("q").oninput = e => { query = e.target.value.trim(); render(); };
|
|
690
|
+
render();
|
|
691
|
+
</script></body></html>
|
|
692
|
+
"""
|