preprocess: add detect/curation/previews modules (curate CLI; ports verified bit-exact against published outputs)
Browse files- preprocess/README.md +10 -0
- preprocess/__main__.py +22 -1
- preprocess/curation.py +144 -0
- preprocess/detect.py +134 -0
- preprocess/previews.py +105 -0
preprocess/README.md
CHANGED
|
@@ -32,10 +32,20 @@ release/<task>/{videos,depth,meta}/<date>/episode_NNN/…
|
|
| 32 |
| `encode` | ffmpeg writers |
|
| 33 |
| `tactile` | two-pass GelSight processing |
|
| 34 |
| `meta` | parquet assembly and index columns |
|
|
|
|
|
|
|
|
|
|
| 35 |
| `pipeline` | per-episode orchestration |
|
| 36 |
| `backfill` | recover flags for already-published parquet |
|
| 37 |
| `publish` | mirror data + code to the Hub |
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
## Tactile time alignment
|
| 40 |
|
| 41 |
How a GelSight frame is paired with a camera frame depends on the recording:
|
|
|
|
| 32 |
| `encode` | ffmpeg writers |
|
| 33 |
| `tactile` | two-pass GelSight processing |
|
| 34 |
| `meta` | parquet assembly and index columns |
|
| 35 |
+
| `detect` | bad-interval detectors + clean-span complement |
|
| 36 |
+
| `curation` | per-task `bad_frames.json` / `segments.json` / `episodes.jsonl` |
|
| 37 |
+
| `previews` | preview policy (calibration choice, trim, world offset, layout) |
|
| 38 |
| `pipeline` | per-episode orchestration |
|
| 39 |
| `backfill` | recover flags for already-published parquet |
|
| 40 |
| `publish` | mirror data + code to the Hub |
|
| 41 |
|
| 42 |
+
`previews` holds policy only — the panel renderer needs rig-local calibration
|
| 43 |
+
the release does not ship, so it stays in `twm/scripts/build_release_previews.py`
|
| 44 |
+
as a thin adapter over `previews.plan()`. Port checks: `detect`/`curation`
|
| 45 |
+
reproduce the published `bad_frames.json` and `segments.json` for all 36
|
| 46 |
+
episodes with zero differences; the preview adapter re-renders
|
| 47 |
+
`pushT/episode_000` bit-identically (first-frame MAD 0.00, same 900 frames).
|
| 48 |
+
|
| 49 |
## Tactile time alignment
|
| 50 |
|
| 51 |
How a GelSight frame is paired with a camera frame depends on the recording:
|
preprocess/__main__.py
CHANGED
|
@@ -12,7 +12,7 @@ import json
|
|
| 12 |
import sys
|
| 13 |
from pathlib import Path
|
| 14 |
|
| 15 |
-
from . import backfill
|
| 16 |
from .config import H5_ROOTS, STAGE_ROOT
|
| 17 |
from .h5io import discover
|
| 18 |
from .pipeline import build_episode
|
|
@@ -126,6 +126,22 @@ def cmd_verify(args) -> int:
|
|
| 126 |
return 1 if bad else 0
|
| 127 |
|
| 128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
def main(argv=None) -> int:
|
| 130 |
ap = argparse.ArgumentParser(prog="react_preprocess")
|
| 131 |
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
@@ -152,6 +168,11 @@ def main(argv=None) -> int:
|
|
| 152 |
f.add_argument("--dry-run", action="store_true")
|
| 153 |
f.set_defaults(func=cmd_backfill)
|
| 154 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
v = sub.add_parser("verify-flags", help="check flags against ground truth")
|
| 156 |
v.add_argument("--root")
|
| 157 |
v.add_argument("--task", choices=sorted(H5_ROOTS))
|
|
|
|
| 12 |
import sys
|
| 13 |
from pathlib import Path
|
| 14 |
|
| 15 |
+
from . import backfill, curation
|
| 16 |
from .config import H5_ROOTS, STAGE_ROOT
|
| 17 |
from .h5io import discover
|
| 18 |
from .pipeline import build_episode
|
|
|
|
| 126 |
return 1 if bad else 0
|
| 127 |
|
| 128 |
|
| 129 |
+
def cmd_curate(args) -> int:
|
| 130 |
+
"""Rebuild bad_frames.json / segments.json / episodes.jsonl for a task."""
|
| 131 |
+
for task in ([args.task] if args.task else sorted(H5_ROOTS)):
|
| 132 |
+
try:
|
| 133 |
+
s = curation.build_task(task, STAGE_ROOT, write=not args.dry_run)
|
| 134 |
+
except FileNotFoundError as exc:
|
| 135 |
+
print(f"[curate] {task}: {exc}", file=sys.stderr)
|
| 136 |
+
continue
|
| 137 |
+
verb = "would write" if args.dry_run else "wrote"
|
| 138 |
+
print(f"[curate] {task}: {s['episodes']} episodes, {s['segments']} segments, "
|
| 139 |
+
f"{s['total_frames']:,} frames, {s['bad_frames']} bad "
|
| 140 |
+
f"({s['bad_fraction']*100:.2f}%), clean {s['clean_frames']:,} "
|
| 141 |
+
f"({s['clean_minutes']:.1f} min) — {verb}")
|
| 142 |
+
return 0
|
| 143 |
+
|
| 144 |
+
|
| 145 |
def main(argv=None) -> int:
|
| 146 |
ap = argparse.ArgumentParser(prog="react_preprocess")
|
| 147 |
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
|
|
| 168 |
f.add_argument("--dry-run", action="store_true")
|
| 169 |
f.set_defaults(func=cmd_backfill)
|
| 170 |
|
| 171 |
+
c = sub.add_parser("curate", help="rebuild bad_frames/segments/episodes indices")
|
| 172 |
+
c.add_argument("--task", choices=sorted(H5_ROOTS))
|
| 173 |
+
c.add_argument("--dry-run", action="store_true")
|
| 174 |
+
c.set_defaults(func=cmd_curate)
|
| 175 |
+
|
| 176 |
v = sub.add_parser("verify-flags", help="check flags against ground truth")
|
| 177 |
v.add_argument("--root")
|
| 178 |
v.add_argument("--task", choices=sorted(H5_ROOTS))
|
preprocess/curation.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-task curation indices built from the per-episode detect sidecars.
|
| 2 |
+
|
| 3 |
+
Produces three files next to the data:
|
| 4 |
+
|
| 5 |
+
``bad_frames.json`` detector thresholds plus every flagged interval
|
| 6 |
+
``segments.json`` the clean spans, indexed into episode video/parquet coords
|
| 7 |
+
``episodes.jsonl`` one row per episode
|
| 8 |
+
|
| 9 |
+
Frame ranges are inclusive ``[a, b]`` in episode-video coordinates, so
|
| 10 |
+
``frame_range`` indexes the MP4s and the parquet directly — no offset applies.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
from . import detect as D
|
| 20 |
+
from .config import FPS, STAGE_ROOT
|
| 21 |
+
|
| 22 |
+
MIN_SEGMENT_FRAMES = 16
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _sidecar_arrays(path: Path) -> tuple[dict, dict]:
|
| 26 |
+
import torch
|
| 27 |
+
|
| 28 |
+
ep = torch.load(str(path), weights_only=False, map_location="cpu")
|
| 29 |
+
return ep, ep["_contact_meta"]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def episode_report(path: Path) -> tuple[dict, dict]:
|
| 33 |
+
"""Run every detector on one sidecar; returns (report, contact_meta)."""
|
| 34 |
+
ep, cm = _sidecar_arrays(path)
|
| 35 |
+
T = int(ep["timestamps"].shape[0])
|
| 36 |
+
active = cm.get("active_sensors", ["left", "right"])
|
| 37 |
+
pose_l = ep["sensor_left_pose"].numpy()
|
| 38 |
+
pose_r = ep["sensor_right_pose"].numpy()
|
| 39 |
+
|
| 40 |
+
report = {
|
| 41 |
+
"n_frames": T,
|
| 42 |
+
"duration_s": round(T / FPS, 3),
|
| 43 |
+
"intensity_spikes": D.detect_intensity_spikes(
|
| 44 |
+
ep["tactile_left_intensity"].numpy(),
|
| 45 |
+
ep["tactile_right_intensity"].numpy(), T),
|
| 46 |
+
"pose_teleports_L": D.detect_pose_teleports(pose_l, T) if "left" in active else [],
|
| 47 |
+
"pose_teleports_R": D.detect_pose_teleports(pose_r, T) if "right" in active else [],
|
| 48 |
+
"ot_loss_L": D.detect_pose_freezes(pose_l, T) if "left" in active else [],
|
| 49 |
+
"ot_loss_R": D.detect_pose_freezes(pose_r, T) if "right" in active else [],
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
mask = np.zeros(T, bool)
|
| 53 |
+
for key in ("intensity_spikes", "pose_teleports_L", "pose_teleports_R",
|
| 54 |
+
"ot_loss_L", "ot_loss_R"):
|
| 55 |
+
for a, b in report[key]:
|
| 56 |
+
mask[max(0, a):min(T, b + 1)] = True
|
| 57 |
+
report["total_bad_frames"] = int(mask.sum())
|
| 58 |
+
report["bad_fraction"] = round(report["total_bad_frames"] / T, 4) if T else 0.0
|
| 59 |
+
return report, cm
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _bad_intervals(report: dict) -> list[tuple[int, int]]:
|
| 63 |
+
return [(int(a), int(b))
|
| 64 |
+
for key in ("intensity_spikes", "pose_teleports_L", "pose_teleports_R",
|
| 65 |
+
"ot_loss_L", "ot_loss_R")
|
| 66 |
+
for a, b in report[key]]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def build_task(task: str, stage_root: Path = STAGE_ROOT,
|
| 70 |
+
write: bool = True) -> dict:
|
| 71 |
+
"""Build the three curation files for one task."""
|
| 72 |
+
out_dir = Path(stage_root) / task
|
| 73 |
+
sidecars = sorted((out_dir / "meta").rglob("*._detect.pt"))
|
| 74 |
+
if not sidecars:
|
| 75 |
+
raise FileNotFoundError(f"no _detect.pt sidecars under {out_dir/'meta'}")
|
| 76 |
+
|
| 77 |
+
episodes, segments, rows = {}, [], []
|
| 78 |
+
for det in sidecars:
|
| 79 |
+
date, stem = det.parent.name, det.name.replace("._detect.pt", "")
|
| 80 |
+
key = f"{date}/{stem}"
|
| 81 |
+
report, cm = episode_report(det)
|
| 82 |
+
episodes[key] = report
|
| 83 |
+
T = report["n_frames"]
|
| 84 |
+
|
| 85 |
+
n_seg = 0
|
| 86 |
+
for a, b in D.find_clean_segments(T, _bad_intervals(report)):
|
| 87 |
+
length = b - a + 1
|
| 88 |
+
if length < MIN_SEGMENT_FRAMES:
|
| 89 |
+
continue
|
| 90 |
+
segments.append({
|
| 91 |
+
"task": task, "source_episode": key, "segment_idx": n_seg,
|
| 92 |
+
"frame_range": [a, b], "n_frames": length,
|
| 93 |
+
"duration_s": round(length / FPS, 3),
|
| 94 |
+
})
|
| 95 |
+
n_seg += 1
|
| 96 |
+
|
| 97 |
+
rows.append({
|
| 98 |
+
"episode": key, "date": date, "n_frames": T,
|
| 99 |
+
"duration_s": report["duration_s"],
|
| 100 |
+
"active_sensors": cm.get("active_sensors", ["left", "right"]),
|
| 101 |
+
"trim_offset": int(cm.get("trim_offset", 0)),
|
| 102 |
+
"world_frame_offset": cm.get("world_frame_offset_applied", [0.0, 0.0, 0.0]),
|
| 103 |
+
"n_segments": n_seg,
|
| 104 |
+
"total_bad_frames": report["total_bad_frames"],
|
| 105 |
+
})
|
| 106 |
+
|
| 107 |
+
total = sum(e["n_frames"] for e in episodes.values())
|
| 108 |
+
bad = sum(e["total_bad_frames"] for e in episodes.values())
|
| 109 |
+
seg_frames = sum(s["n_frames"] for s in segments)
|
| 110 |
+
|
| 111 |
+
bad_frames = {
|
| 112 |
+
"task": task, **D.thresholds(),
|
| 113 |
+
"summary": {
|
| 114 |
+
"n_episodes": len(episodes), "total_frames": total,
|
| 115 |
+
"total_bad_frames": bad,
|
| 116 |
+
"bad_fraction_overall": round(bad / total, 4) if total else 0.0,
|
| 117 |
+
},
|
| 118 |
+
"episodes": episodes,
|
| 119 |
+
}
|
| 120 |
+
segments_doc = {
|
| 121 |
+
"task": task, "schema": "segments_v2_video",
|
| 122 |
+
"description": ("Each entry indexes a contiguous clean span within an "
|
| 123 |
+
"episode's videos (data/<task>/videos/<date>/episode_NNN/*.mp4) "
|
| 124 |
+
"and parquet. frame_range is [a,b] inclusive in "
|
| 125 |
+
"episode-video frame coords."),
|
| 126 |
+
"n_segments": len(segments), "total_frames": seg_frames,
|
| 127 |
+
"total_duration_min": round(seg_frames / FPS / 60, 2),
|
| 128 |
+
"min_segment_frames_kept": MIN_SEGMENT_FRAMES,
|
| 129 |
+
"segments": sorted(segments, key=lambda s: (s["source_episode"], s["segment_idx"])),
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
if write:
|
| 133 |
+
(out_dir / "bad_frames.json").write_text(json.dumps(bad_frames, indent=2))
|
| 134 |
+
(out_dir / "segments.json").write_text(json.dumps(segments_doc, indent=2))
|
| 135 |
+
with open(out_dir / "episodes.jsonl", "w") as fh:
|
| 136 |
+
for row in sorted(rows, key=lambda r: r["episode"]):
|
| 137 |
+
fh.write(json.dumps(row) + "\n")
|
| 138 |
+
|
| 139 |
+
return {
|
| 140 |
+
"task": task, "episodes": len(episodes), "segments": len(segments),
|
| 141 |
+
"total_frames": total, "bad_frames": bad,
|
| 142 |
+
"bad_fraction": bad / total if total else 0.0,
|
| 143 |
+
"clean_frames": seg_frames, "clean_minutes": seg_frames / FPS / 60,
|
| 144 |
+
}
|
preprocess/detect.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Detectors for unusable frames, and the clean-span complement.
|
| 2 |
+
|
| 3 |
+
Three failure modes are flagged per episode:
|
| 4 |
+
|
| 5 |
+
``intensity_spikes`` a GelSight reading far above anything contact produces —
|
| 6 |
+
usually the sensor being knocked or re-seated
|
| 7 |
+
``pose_teleports_*`` OptiTrack solving to the wrong marker set, which moves
|
| 8 |
+
the sensor implausibly far *and* rotates it implausibly
|
| 9 |
+
fast in a single frame
|
| 10 |
+
``ot_loss_*`` the tracker dropping out, which shows up as a run of
|
| 11 |
+
bit-identical poses rather than as missing samples
|
| 12 |
+
|
| 13 |
+
Thresholds are the ones validated against the published motherboard
|
| 14 |
+
``bad_frames.json`` (25/27 episodes bit-identical).
|
| 15 |
+
|
| 16 |
+
Previously split across ``detect_bad_intervals.py`` and ``build_segments.py``
|
| 17 |
+
in ``twm/scripts/``; the latter has since been archived, so this module is now
|
| 18 |
+
the only live copy of ``find_clean_segments``.
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from .config import FPS
|
| 25 |
+
|
| 26 |
+
TAU_INTENSITY = 30.0
|
| 27 |
+
TAU_VELOCITY_MPS = 5.0
|
| 28 |
+
TAU_ANGULAR_RAD_PS = 15.0
|
| 29 |
+
FREEZE_THRESHOLD_S = 0.25
|
| 30 |
+
BUFFER_FRAMES = 3
|
| 31 |
+
EPS_POSE_BIT = 1e-7
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def merge_intervals(events, gap: int = 1) -> list[list[int]]:
|
| 35 |
+
"""Merge inclusive ``(a, b)`` intervals that touch or overlap."""
|
| 36 |
+
if not events:
|
| 37 |
+
return []
|
| 38 |
+
ordered = sorted((int(a), int(b)) for a, b in events)
|
| 39 |
+
merged = [list(ordered[0])]
|
| 40 |
+
for a, b in ordered[1:]:
|
| 41 |
+
if a <= merged[-1][1] + gap:
|
| 42 |
+
merged[-1][1] = max(merged[-1][1], b)
|
| 43 |
+
else:
|
| 44 |
+
merged.append([a, b])
|
| 45 |
+
return merged
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def pad_and_merge(events, T: int, buffer: int) -> list[list[int]]:
|
| 49 |
+
"""Pad each interval by ``±buffer``, clip to ``[0, T-1]``, then merge."""
|
| 50 |
+
if not events:
|
| 51 |
+
return []
|
| 52 |
+
return merge_intervals([(max(0, a - buffer), min(T - 1, b + buffer))
|
| 53 |
+
for a, b in events])
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def detect_intensity_spikes(intens_l: np.ndarray, intens_r: np.ndarray,
|
| 57 |
+
T: int) -> list[list[int]]:
|
| 58 |
+
"""Frames where either sensor reads above ``TAU_INTENSITY``."""
|
| 59 |
+
above = (intens_l > TAU_INTENSITY) | (intens_r > TAU_INTENSITY)
|
| 60 |
+
return pad_and_merge([(int(i), int(i)) for i in np.where(above)[0]],
|
| 61 |
+
T, BUFFER_FRAMES)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def detect_pose_teleports(pose: np.ndarray, T: int) -> list[list[int]]:
|
| 65 |
+
"""Frames whose pose jump is implausible in translation *and* rotation.
|
| 66 |
+
|
| 67 |
+
The conjunction matters: ordinary fast motion trips the translational
|
| 68 |
+
threshold on its own, so requiring both is what separates a tracking error
|
| 69 |
+
from a quick reach.
|
| 70 |
+
"""
|
| 71 |
+
if T < 2:
|
| 72 |
+
return []
|
| 73 |
+
xyz, quat = pose[:, :3], pose[:, 3:]
|
| 74 |
+
qn = quat / np.maximum(np.linalg.norm(quat, axis=1, keepdims=True), 1e-12)
|
| 75 |
+
trans_vel = np.linalg.norm(np.diff(xyz, axis=0), axis=1) * FPS
|
| 76 |
+
dot = np.abs((qn[:-1] * qn[1:]).sum(axis=1)).clip(-1.0, 1.0)
|
| 77 |
+
ang_vel = 2.0 * np.arccos(dot) * FPS
|
| 78 |
+
flag = (trans_vel > TAU_VELOCITY_MPS) & (ang_vel > TAU_ANGULAR_RAD_PS)
|
| 79 |
+
return pad_and_merge([(int(i), int(i + 1)) for i in np.where(flag)[0]],
|
| 80 |
+
T, BUFFER_FRAMES)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def detect_pose_freezes(pose: np.ndarray, T: int) -> list[list[int]]:
|
| 84 |
+
"""Runs of bit-identical pose lasting at least ``FREEZE_THRESHOLD_S``.
|
| 85 |
+
|
| 86 |
+
OptiTrack repeats its last solution when it loses the marker set, so a
|
| 87 |
+
frozen pose is track loss rather than genuine stillness — a real hold still
|
| 88 |
+
jitters in the last decimal places.
|
| 89 |
+
|
| 90 |
+
Reported unpadded, matching the published ``bad_frames.json``.
|
| 91 |
+
"""
|
| 92 |
+
if T < 2:
|
| 93 |
+
return []
|
| 94 |
+
same = np.zeros(T, dtype=bool)
|
| 95 |
+
same[1:] = np.all(np.abs(np.diff(pose, axis=0)) < EPS_POSE_BIT, axis=1)
|
| 96 |
+
min_frames = int(round(FREEZE_THRESHOLD_S * FPS))
|
| 97 |
+
|
| 98 |
+
events, i = [], 1
|
| 99 |
+
while i < T:
|
| 100 |
+
if not same[i]:
|
| 101 |
+
i += 1
|
| 102 |
+
continue
|
| 103 |
+
j = i
|
| 104 |
+
while j < T and same[j]:
|
| 105 |
+
j += 1
|
| 106 |
+
# the run includes the anchor frame at i-1 that the copies match
|
| 107 |
+
run_a, run_b = i - 1, j - 1
|
| 108 |
+
if (run_b - run_a + 1) >= min_frames:
|
| 109 |
+
events.append((run_a, run_b))
|
| 110 |
+
i = j
|
| 111 |
+
return pad_and_merge(events, T, 0)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def find_clean_segments(T: int, bad_intervals) -> list[tuple[int, int]]:
|
| 115 |
+
"""Complement of the bad intervals: inclusive ``[a, b]`` clean spans."""
|
| 116 |
+
segments, prev_end = [], -1
|
| 117 |
+
for a, b in merge_intervals(bad_intervals):
|
| 118 |
+
if a > prev_end + 1:
|
| 119 |
+
segments.append((prev_end + 1, a - 1))
|
| 120 |
+
prev_end = max(prev_end, b)
|
| 121 |
+
if prev_end < T - 1:
|
| 122 |
+
segments.append((prev_end + 1, T - 1))
|
| 123 |
+
return segments
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def thresholds() -> dict:
|
| 127 |
+
"""The detector settings, for recording alongside the results."""
|
| 128 |
+
return {
|
| 129 |
+
"tau_intensity": TAU_INTENSITY,
|
| 130 |
+
"tau_velocity_mps": TAU_VELOCITY_MPS,
|
| 131 |
+
"tau_angular_rad_per_s": TAU_ANGULAR_RAD_PS,
|
| 132 |
+
"freeze_threshold_s": FREEZE_THRESHOLD_S,
|
| 133 |
+
"buffer_frames": BUFFER_FRAMES,
|
| 134 |
+
}
|
preprocess/previews.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Release policy for the preview panels.
|
| 2 |
+
|
| 3 |
+
Previews are a presentation artifact, not part of reproducing the data: they
|
| 4 |
+
render a 3-camera + OptiTrack + GelSight panel from the *source* recordings and
|
| 5 |
+
need rig-local calibration that the release does not ship. So this module owns
|
| 6 |
+
only the release-specific decisions —
|
| 7 |
+
|
| 8 |
+
* which calibration set belongs to which task (they were recalibrated between
|
| 9 |
+
the motherboard and pushT sessions, and using the wrong one silently
|
| 10 |
+
misprojects the overlay)
|
| 11 |
+
* the trim offset, read from the release sidecar so previews start on the same
|
| 12 |
+
frame as the published video
|
| 13 |
+
* the per-(task, date) world-frame offset
|
| 14 |
+
* the output layout
|
| 15 |
+
|
| 16 |
+
— and takes the renderer as a parameter. The previous version reached into the
|
| 17 |
+
renderer module and reassigned its globals, which meant preview settings could
|
| 18 |
+
not be reasoned about without reading both files, and two tasks could not be
|
| 19 |
+
rendered in one process.
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Callable, Iterator
|
| 25 |
+
|
| 26 |
+
from .config import H5_ROOTS, STAGE_ROOT, WORLD_OFFSET
|
| 27 |
+
|
| 28 |
+
CALIB_ROOT = Path(__file__).resolve().parent.parent / "calibration"
|
| 29 |
+
|
| 30 |
+
# The rigs were recalibrated between sessions; each task must use the set that
|
| 31 |
+
# was current when it was recorded.
|
| 32 |
+
CALIB_DIRS = {
|
| 33 |
+
"motherboard": CALIB_ROOT / "result backup", # May 12
|
| 34 |
+
"pushT": CALIB_ROOT / "result", # June 26
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
CLIP_SECONDS = 30.0
|
| 38 |
+
SPEED = 2.0
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def trim_offset(task: str, date: str, episode: str,
|
| 42 |
+
stage_root: Path = STAGE_ROOT) -> int:
|
| 43 |
+
"""Trim offset for an episode, from its release sidecar (0 if absent)."""
|
| 44 |
+
det = Path(stage_root) / task / "meta" / date / f"{episode}._detect.pt"
|
| 45 |
+
if not det.exists():
|
| 46 |
+
return 0
|
| 47 |
+
import torch
|
| 48 |
+
|
| 49 |
+
meta = torch.load(str(det), weights_only=False, map_location="cpu")
|
| 50 |
+
return int(meta["_contact_meta"].get("trim_offset", 0))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def plan(task: str, stage_root: Path = STAGE_ROOT) -> Iterator[dict]:
|
| 54 |
+
"""One job per published episode that still has its source recording.
|
| 55 |
+
|
| 56 |
+
Driven by the published videos rather than by the source tree, so episodes
|
| 57 |
+
excluded from the release (e.g. the corrupt pushT recording) do not
|
| 58 |
+
reappear here.
|
| 59 |
+
"""
|
| 60 |
+
stage_root = Path(stage_root)
|
| 61 |
+
h5_root = H5_ROOTS[task]
|
| 62 |
+
videos = stage_root / task / "videos"
|
| 63 |
+
if not videos.exists():
|
| 64 |
+
return
|
| 65 |
+
for date_dir in sorted(p for p in videos.iterdir() if p.is_dir()):
|
| 66 |
+
date = date_dir.name
|
| 67 |
+
dx, dy, dz = WORLD_OFFSET.get((task, date), (0.0, 0.0, 0.0))
|
| 68 |
+
for ep_dir in sorted(p for p in date_dir.iterdir() if p.is_dir()):
|
| 69 |
+
episode = ep_dir.name
|
| 70 |
+
h5 = h5_root / date / f"{episode}.h5"
|
| 71 |
+
if not h5.exists():
|
| 72 |
+
continue
|
| 73 |
+
yield {
|
| 74 |
+
"task": task, "date": date, "episode": episode,
|
| 75 |
+
"h5": h5,
|
| 76 |
+
"out": stage_root / task / "previews" / date / f"{episode}.mp4",
|
| 77 |
+
"calib_dir": CALIB_DIRS[task],
|
| 78 |
+
"trim_offset": trim_offset(task, date, episode, stage_root),
|
| 79 |
+
"world_offset": (dx, dy, dz),
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def build_task(task: str, render: Callable[[dict], None],
|
| 84 |
+
stage_root: Path = STAGE_ROOT,
|
| 85 |
+
overwrite: bool = False) -> list[dict]:
|
| 86 |
+
"""Render every planned preview with the supplied renderer.
|
| 87 |
+
|
| 88 |
+
``render`` receives one job dict. A failure is recorded against that
|
| 89 |
+
episode and the rest continue — one bad recording should not cost the whole
|
| 90 |
+
batch.
|
| 91 |
+
"""
|
| 92 |
+
results = []
|
| 93 |
+
for job in plan(task, stage_root):
|
| 94 |
+
if job["out"].exists() and not overwrite:
|
| 95 |
+
results.append({**job, "status": "SKIP"})
|
| 96 |
+
continue
|
| 97 |
+
job["out"].parent.mkdir(parents=True, exist_ok=True)
|
| 98 |
+
try:
|
| 99 |
+
render(job)
|
| 100 |
+
size = job["out"].stat().st_size if job["out"].exists() else 0
|
| 101 |
+
results.append({**job, "status": "OK", "bytes": size})
|
| 102 |
+
except Exception as exc: # noqa: BLE001
|
| 103 |
+
results.append({**job, "status": "FAIL",
|
| 104 |
+
"error": f"{type(exc).__name__}: {exc}"})
|
| 105 |
+
return results
|