React / docs /curation_pipeline.md
yxma's picture
docs/curation_pipeline.md: point at MultimodalData/twm/scripts/ now that one-shot scripts have been migrated out of /tmp/ into a versioned home.
fd26b94 verified

React data curation pipeline

Note (2026-05-18 update): The one-shot scripts referenced below have been moved out of /tmp/ and into a versioned home at MultimodalData/twm/scripts/. All references in this document have been updated. The previous /tmp/ copies are stale.

The procedure below is what runs between a fresh recording session and a HF push. Follow it in order; each stage produces a checkable artifact, so a bad stage doesn't silently propagate downstream.

Source files referenced. The first five live in the recording-machine MultimodalData/twm/ checkout. The rest are the curation scripts produced for this dataset; they currently live in MultimodalData/twm/scripts/ (development scratchpad) and should be moved into MultimodalData/twm/twm/scripts/ so they're versioned alongside the rest of the codebase.

Script Current location Notes
viz.py MultimodalData/twm/ Single source of truth for visualization. Owns the 1280×480 panel builder (left → middle → right cam ordering), projection overlay, OptiTrack helpers, calibration loading, adaptive-shrink GIF encoder. Every other visualization script in the repo imports from here.
data_collection.py MultimodalData/twm/ Recording loop. make_preview is now a re-export of twm.viz.build_preview_panel.
compress_h5.py MultimodalData/twm/ BLOSC → GZIP+shuffle.
visualize.py MultimodalData/twm/ Interactive replay viewer / MP4 export. Projection overlay on by default, --no_projection to disable. Delegates panel + overlay to twm.viz.
twm.contact_index MultimodalData/twm/twm/ Tactile contact metrics → .pt files.
make_episode_gifs_v3.py MultimodalData/twm/scripts/ Per-episode HF preview GIFs (canonical viewer layout).
freeze_diagnose.py MultimodalData/twm/scripts/ Augmented freeze detector: cross-modal motion + frame-duplicate + OT-gap + rotation/translation teleport. Classifies each freeze into pipeline_stall / ot_dropout / ot_teleport / real_still.
inspect_freezes_v3.py MultimodalData/twm/scripts/ Helper layer used by freeze_diagnose.py — schedules clips per freeze event, renders them via twm.viz.
freeze_cut_report.py MultimodalData/twm/scripts/ Per-threshold tally of frozen-pose frames (no clip rendering).

The pipeline assumes the standard layout:

/media/yxma/Disk1/twm/
├── data/<task>/<date>/episode_*.h5             # raw H5 (BLOSC)
├── processed/<mode>/<task>/<date>/episode_*.pt # contact-indexed .pt
└── figures/
    ├── dataset_figures/                        # summary plots + JSONs
    └── episode_previews/<task>/<date>/         # one GIF per episode

<date> is YYYY-MM-DD; <task> is e.g. motherboard.


Stage 0 — Recording

Use data_collection.py. Confirm before you stop the run:

  • All three RealSense cams are streaming (preview window shows three rows).
  • Both GelSight feeds are alive.
  • All three OptiTrack rigid bodies (left, right, work-piece) are tracked for the whole take. If a body's pose stops updating mid-run, the recorder will silently hold the last sample → this is the failure mode detected in Stage 5C. Re-aim the cameras or re-seat the markers before starting a long take.
  • Audible buffer-drop warnings are zero in the last 30 s of the session.

Output: data/<task>/<date>/episode_*.h5 (BLOSC-compressed).


Stage 1 — Integrity check

For every new H5, confirm it opens and that frame counts agree across modalities. The fast version:

python - <<'PY'
import h5py, hdf5plugin, sys
from pathlib import Path
ROOT = Path("/media/yxma/Disk1/twm/data/motherboard/<date>")
for p in sorted(ROOT.glob("episode_*.h5")):
    try:
        f = h5py.File(p, "r")
        T = f["realsense/cam0/color"].shape[0]
        for k in ("realsense/cam1/color", "realsense/cam2/color",
                 "gelsight/left/frames", "gelsight/right/frames"):
            assert f[k].shape[0] == T, (p, k, f[k].shape[0], T)
        f.close()
        print(f"OK   {p.name}  T={T}")
    except Exception as e:
        print(f"BAD  {p.name}  {e}")
        p.rename(p.with_suffix(p.suffix + ".corrupt"))
PY

Anything that fails to open is renamed *.h5.corrupt and excluded from the rest of the pipeline.


Stage 2 — Compression

BLOSC LZ4 is fast for recording but needs hdf5plugin at read time. Convert to GZIP+shuffle for portability and ~30–50 % size savings:

python -m twm.compress_h5 \
    --in_dir  /media/yxma/Disk1/twm/data/motherboard/<date> \
    --in_place

The script clamps chunk shapes when datasets are shorter than the default chunk (relevant for short test recordings). Re-run integrity check after.


Stage 3 — Visual QA preview MP4 (per episode)

# Projection overlay is on by default; the default --cam_calib list already
# includes all three cameras.
python -m twm.visualize \
    /media/yxma/Disk1/twm/data/motherboard/<date> \
    --save_videos

# Same but no overlay (faster, useful for raw-stream sanity checks):
python -m twm.visualize \
    /media/yxma/Disk1/twm/data/motherboard/<date> \
    --save_videos --no_projection

These MP4s are for the operator only — scrub each one and flag:

  • partial occlusions or out-of-frame moments,
  • visible OT dropouts (the projection dot stays still while the hand moves),
  • color/exposure problems,
  • per-date "active sensors" (i.e. did you only use one side?).

Write findings into tasks.json:per_date_notes.<date>.


Stage 4 — Contact indexing → .pt

Re-run for the new date:

python -m twm.contact_index \
    --in_root  /media/yxma/Disk1/twm/data/motherboard/<date> \
    --out_root /media/yxma/Disk1/twm/processed/mode1_v1/motherboard/<date>

This downsamples cam0 to 128×128, builds the three contact metrics per side (intensity / area / mixed), and stores reference-frame metadata in _contact_meta. Reference strategy is p01 (the 1st-percentile of intensity over the whole episode), which is robust against early-frame calibration drift.

Sanity check:

python - <<'PY'
import torch
p = "/media/yxma/Disk1/twm/processed/mode1_v1/motherboard/<date>/episode_006.pt"
ep = torch.load(p, weights_only=False)
print(list(ep.keys()))
print("T:", ep["view"].shape[0])
print("ref drift L/R:", ep["_contact_meta"]["drift_left"], ep["_contact_meta"]["drift_right"])
PY

If either drift > 5.0 the gel surface moved significantly between the reference frame and the rest of the episode — flag the episode.


Stage 5 — Automated failure-mode detection

Three failure modes are detected from the new .pt files and logged to figures/dataset_figures/bad_frames.json + summarised in data_quality_breakdown.json.

5A. Tactile intensity spikes (LED flicker)

A frame whose tactile intensity exceeds p999 + 30 (uint8) is treated as a momentary LED dropout. Stored as intensity_spikes: [[a, b], ...] per episode, with a 3-frame buffer on each side.

5B. Pose teleports

Per-frame OT velocity > 5 m/s → impossible motion → marker swap or brief solver glitch. Stored as pose_teleports_L / pose_teleports_R.

5C. Pose freezes — disambiguated by cross-modal motion

A sensor whose 7-vec pose is bitwise-identical across consecutive frames for ≥ 0.25 s on an active sensor is a freeze candidate. Each candidate is then diagnosed by combining:

  • max translation velocity in the OT stream within ±1 s
  • max angular velocity in the same window (catches solver flips that the old 5 m/s translation-only check missed)
  • max OT timestamp gap during the interval
  • per-stream consecutive-frame duplicate fraction (cam0/1/2 + affected GS)

Each event is then labelled:

  • ot_loss — the OptiTrack solver lost the rigid body. Signaled by any of: OT timestamp gap ≥ 100 ms, translation velocity ≥ 5 m/s near the event, or angular velocity ≥ 15 rad/s near the event (solver flip on re-acquire). A bitwise-frozen pose with no contradicting evidence also defaults to this class. GelSight is unaffected — the gel pad just isn't deforming during the freeze (sensor moved in air or set down), which mimics a frozen stream but isn't one.
  • pipeline_stall — ALL three RealSense streams duplicate ≥ 30 % of frames in the window. Indicates the recorder itself stalled. Not observed in the current React dataset.
  • real_still — no OT-loss signals and cross-modal motion at noise floor. Operator deliberately paused.
  • ambiguous — none of the above.

Empirically across the bimanual set, every freeze event in React classifies as ot_loss — the OptiTrack rig is the bottleneck, not the camera/GelSight capture stack. The right cut is "drop any window overlapping an ot_loss interval"; this is materially different from a benign "operator at rest" interpretation. Fixing it requires improving mocap coverage (camera placement, marker count on each rigid body), not changes to the recorder.

Current scripts:

  • intensity spikes + pose teleports: the original detector that produced the current bad_frames.json (translation-velocity only; rotation teleports are now caught in 5C via freeze_diagnose.py's angular velocity check but should be folded into the main bad_frames.json pipeline.)
  • pose freezes: MultimodalData/twm/scripts/freeze_diagnose.py (cross-modal classifier; outputs per-event verdicts + per-class sample clips). Also see MultimodalData/twm/scripts/freeze_cut_report.py for per-threshold totals across the task.

To do — consolidation. These detectors should be merged into a single scripts/detect_failures.py that:

  1. iterates .pt files under a --pt_root,
  2. applies all three detectors (with rotation-aware teleport check),
  3. writes the union to bad_frames.json and a richer per-mode breakdown to freeze_intervals.json and data_quality_breakdown.json,
  4. emits the per-episode data_quality_report.csv.

Until that exists, the procedure is: re-run each current script in turn and merge their outputs by hand into bad_frames.json.


Stage 6 — Visual QA gallery GIFs (for HF)

python /home/yxma/MultimodalData/twm/scripts/make_episode_gifs_v3.py \
    --data_root /media/yxma/Disk1/twm/data/motherboard \
    --pt_root   /media/yxma/Disk1/twm/processed/mode1_v1/motherboard \
    --out_root  /media/yxma/Disk1/twm/figures/episode_previews/motherboard \
    --tasks_json yxma_React/tasks.json

Settings (all configurable but the defaults are vetted):

  • 60 frames evenly across [2 %, 98 %] of the episode
  • 3 cameras shown left|middle|right with sensor projection overlay
  • 256-color palette (preserves tactile gradients)
  • ≤ 4 MB hard cap; on overflow the script first shrinks the spatial resolution, then drops palette down to 128 colours, never below
  • Output: one GIF per episode under figures/episode_previews/<task>/<date>/episode_*.gif

These GIFs are uploaded to HF and rendered inline on the dataset card.


Stage 7 — Per-event QA clips for borderline failures

Run only when Stage 5 flags something subtle (short freezes, weak intensity spikes, single-frame teleports):

python /home/yxma/MultimodalData/twm/scripts/inspect_short_freezes.py \
    --thr_min_s 1 --thr_max_s 5 \
    --out_dir /media/yxma/Disk1/twm/figures/dataset_figures/freeze_check_short

Each event becomes one short GIF (~60 frames) with the affected sensor circled red. The operator scans these and decides per-event whether to keep, cut, or merge intervals. Final calls live in freeze_intervals.json under a manual_verdict: {"keep"|"cut"|"merge"} field.


Stage 8 — Update metadata

Touch three files before pushing to HF:

  1. tasks.json

    • Add the new date to tasks.<task>.dates.
    • Add a per_date_notes.<date> block:
      {
        "kind": "session",
        "active_sensors": ["left", "right"],
        "note": "human-readable summary, e.g. 'bimanual; one OT freeze in ep_017'"
      }
      
    • Update n_episode_files.
  2. bad_frames.json — automatically refreshed by Stage 5.

  3. data_quality_breakdown.json — automatically refreshed by Stage 5.


Stage 9 — Docs refresh

If the new session adds material the dataset card or supporting docs don't already describe, update:

  • README.md "At a glance" counters (episodes, frames, duration).
  • docs/quality.md if a new failure mode appeared, or percentages changed by > 0.5 %.
  • docs/recording.md if hardware / capture rate / sensor lineup changed.
  • docs/caveats.md for any operator-noted anomaly.

Stage 10 — Push to HF

Pre-flight check — these must all be true:

  • every episode_*.h5 has a matching episode_*.pt
  • every episode_*.pt has been touched by twm.contact_index after the most recent recording (timestamps, file size)
  • tasks.json:per_date_notes.<date> exists
  • bad_frames.json:episodes.<date>/<ep> exists for every episode
  • every episode has a preview GIF under figures/episode_previews/<task>/<date>/
  • data_quality_breakdown.json reflects the new totals

Then upload:

python - <<'PY'
from huggingface_hub import upload_folder
upload_folder(
    repo_id="yxma/React",
    repo_type="dataset",
    folder_path=".",
    path_in_repo=".",
    commit_message="Add <date> session + curation pipeline outputs",
)
PY

(Set HF_HUB_ENABLE_HF_TRANSFER=1 for fast LFS uploads.)


Channel-order gotcha (read before adding any new visualiser)

The three video streams use different byte orders inside the H5 files. Get this wrong and your previews come out with R/B swapped:

Stream H5 byte order Why
realsense/cam{0,1,2}/color BGR pyrealsense2 enabled with rs.format.bgr8 in camera_stream/realsense_stream.py
gelsight/{left,right}/frames RGB Converted in camera_stream/usb_video_stream.py (cv2.cvtColor(BGR2RGB)) before writing
view in processed/.../*.pt BGR Carved out of cam0 by twm.contact_index with no further conversion
tactile_{left,right} in .pt RGB Carved out of gelsight frames, same as above

Rules of thumb:

  • cv2.imshow and cv2.VideoWriter expect BGR — RealSense streams + the recording UI are end-to-end consistent (and incidentally hide the fact that the GelSight thumbnails in twm.visualize are technically rendered with their R/B swapped).
  • PIL.Image.fromarray and the GIF encoder interpret bytes as RGB. Anything PIL-bound (gallery previews, dataloader sample GIFs) must convert RealSense BGR → RGB once. The cheapest way is arr[..., ::-1].
  • When reusing twm.data_collection.make_preview as the panel builder for a GIF, feed the H5 streams in as-is so the panel matches the live viewer pixel-for-pixel, then cv2.cvtColor(panel, cv2.COLOR_BGR2RGB) once at the end before saving with PIL.

If you're writing a new visualiser:

import cv2, h5py, hdf5plugin  # noqa: F401
with h5py.File(path, "r") as f:
    cam_rgb = f["realsense/cam0/color"][i][..., ::-1].copy()  # BGR → RGB
    gs_rgb  = f["gelsight/left/frames"][i]                    # already RGB

Failure-mode reference table

Mode Detector Threshold Where logged
LED intensity spike tactile_<side>_intensity[t] - p999 > 30 uint8 scale bad_frames.json:intensity_spikes
Pose teleport inter-frame velocity > 5 m/s bad_frames.json:pose_teleports_{L,R}
OT freeze pose bitwise-identical for ≥ N frames ≥ 1 s (≈30 fr.) bad_frames.json + freeze_intervals.json
Contact-ref drift _contact_meta.drift_{side} > 5.0 _contact_meta (per-episode .pt)
Color shift / hue (manual; from Stage 3 MP4 review) tasks.json:per_date_notes.<date>.note
Occlusion (manual; from Stage 3 MP4 review) same
Audio-buffer drops (recorder logs at capture time) recording-machine log

Quick "I'm adding one new date" runbook

DATE=2026-06-01
TASK=motherboard

# 1. integrity
python scripts/integrity_check.py data/$TASK/$DATE

# 2. compress
python -m twm.compress_h5 --in_dir data/$TASK/$DATE --in_place

# 3. preview MP4 (operator scrub)
python -m twm.visualize_projection data/$TASK/$DATE --save_videos

# 4. contact index → .pt
python -m twm.contact_index \
    --in_root  data/$TASK/$DATE \
    --out_root processed/mode1_v1/$TASK/$DATE

# 5. detect failure modes
python scripts/detect_failures.py --date $DATE

# 6. gallery GIFs
python scripts/make_episode_gifs_v3.py --only_date $DATE

# 7. per-event clips (only if Stage 5 flagged subtle stuff)
python scripts/inspect_short_freezes.py --only_date $DATE

# 8/9. edit tasks.json + README + docs/* by hand

# 10. push
HF_HUB_ENABLE_HF_TRANSFER=1 python scripts/push_hf.py

If any stage produces an unexpected count or a new failure mode, stop the pipeline and write it up in docs/caveats.md before pushing.