R4R-Auto-Eval / scripts /build_benchmark.py
cobo2026's picture
Initial R4R Auto Eval progress release v0.1.0 (part 4)
0904fd2 verified
Raw History Blame Contribute Delete
10.8 kB
#!/usr/bin/env python3
"""Build 40 balanced REASSEMBLE cases from two downloaded recordings."""
from __future__ import annotations
import argparse
import hashlib
import json
import random
import subprocess
from pathlib import Path
import polars as pl
FAILURE_SEGMENTS = [
(2, 1), (2, 4), (2, 10), (2, 11), (2, 13),
(2, 15), (2, 25), (2, 31), (2, 35), (2, 37),
(2, 38), (2, 45), (2, 49), (3, 5), (3, 6),
(3, 13), (3, 21), (3, 26), (3, 35), (3, 40),
]
SUCCESS_SEGMENTS = [
(2, 3), (2, 6), (2, 8), (2, 12), (2, 14),
(2, 18), (2, 20), (2, 22), (2, 24), (2, 26),
(2, 32), (2, 39), (2, 47), (2, 50), (2, 52),
(3, 7), (3, 14), (3, 24), (3, 27), (3, 36),
]
CAMERAS = {
"main": "observation.images.hama1",
"wrist": "observation.images.hand",
"external_2": "observation.images.hama2",
}
RECORDINGS = {
2: {"recording": "2025-01-09-17-03-05", "split": "train"},
3: {"recording": "2025-01-09-19-15-33", "split": "train"},
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source-dir", type=Path, default=Path("/tmp"))
parser.add_argument("--data", type=Path, default=Path("/tmp/reassemble_data_000.parquet"))
parser.add_argument("--episodes", type=Path, default=Path("/tmp/reassemble_episodes.parquet"))
parser.add_argument("--tasks", type=Path, default=Path("/tmp/reassemble_tasks.parquet"))
parser.add_argument(
"--output", type=Path, default=Path("gpt6-reassemble40/benchmark")
)
parser.add_argument("--overwrite", action="store_true")
return parser.parse_args()
def run(command: list[str]) -> str:
completed = subprocess.run(command, check=True, text=True, capture_output=True)
return completed.stdout
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for block in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def probe(path: Path) -> dict[str, object]:
raw = run([
"ffprobe", "-v", "error", "-count_frames", "-select_streams", "v:0",
"-show_entries",
"stream=codec_name,width,height,avg_frame_rate,nb_read_frames:format=duration",
"-of", "json", str(path),
])
value = json.loads(raw)
stream = value["streams"][0]
rate_num, rate_den = map(int, stream["avg_frame_rate"].split("/"))
return {
"num_frames": int(stream["nb_read_frames"]),
"fps": rate_num / rate_den,
"duration_s": float(value["format"]["duration"]),
"width": int(stream["width"]),
"height": int(stream["height"]),
"codec": stream["codec_name"],
"sha256": sha256(path),
"size": path.stat().st_size,
"decode_check": "all frames decoded and counted",
"detected_black_seconds": None,
}
def write_json(path: Path, value: object) -> None:
path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
def source_path(source_dir: Path, camera: str, file_index: int) -> Path:
short_name = camera.rsplit(".", 1)[-1]
return source_dir / f"reassemble_{short_name}_{file_index:03d}.mp4"
def main() -> None:
args = parse_args()
if args.output.exists() and not args.overwrite:
raise SystemExit(f"{args.output} already exists; pass --overwrite to rebuild")
data = pl.read_parquet(args.data)
episodes = pl.read_parquet(args.episodes)
tasks = pl.read_parquet(args.tasks)
segments = (
data.group_by(["episode_index", "segment.index"])
.agg(
pl.col("segment.success").first().alias("success"),
pl.col("task_index").first(),
pl.col("frame_index").min().alias("start_frame"),
(pl.col("frame_index").max() + 1).alias("end_frame"),
pl.len().alias("num_frames"),
pl.col("timestamp").min().alias("start_s"),
)
.join(tasks, on="task_index")
)
segment_lookup = {
(row["episode_index"], row["segment.index"]): row
for row in segments.iter_rows(named=True)
}
episode_lookup = {
row["episode_index"]: row for row in episodes.iter_rows(named=True)
}
selected = [(episode, segment, False) for episode, segment in FAILURE_SEGMENTS]
selected += [(episode, segment, True) for episode, segment in SUCCESS_SEGMENTS]
random.Random(20260915).shuffle(selected)
cases_root = args.output / "cases"
truth_root = args.output / "ground_truth"
cases_root.mkdir(parents=True, exist_ok=True)
truth_root.mkdir(parents=True, exist_ok=True)
label_records: list[dict[str, object]] = []
provenance_records: list[dict[str, object]] = []
for offset, (episode_index, segment_index, expected_success) in enumerate(selected):
case_id = f"case_{31 + offset:03d}"
segment = segment_lookup[(episode_index, segment_index)]
if bool(segment["success"]) != expected_success:
raise RuntimeError(f"native label mismatch for episode {episode_index}, segment {segment_index}")
num_frames = int(segment["num_frames"])
local_start = float(segment["start_s"])
duration_s = num_frames / 30.0
instruction = str(segment["task"])
case_dir = cases_root / case_id
case_dir.mkdir(parents=True, exist_ok=True)
(case_dir / "instruction.txt").write_text(instruction + "\n", encoding="utf-8")
episode = episode_lookup[episode_index]
video_metadata: dict[str, object] = {}
view_provenance: list[dict[str, object]] = []
for role, camera in CAMERAS.items():
file_index = int(episode[f"videos/{camera}/file_index"])
episode_offset = float(episode[f"videos/{camera}/from_timestamp"])
absolute_start = episode_offset + local_start
source = source_path(args.source_dir, camera, file_index)
if not source.is_file():
raise FileNotFoundError(source)
destination = case_dir / f"{role}.mp4"
run([
"ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
"-ss", f"{absolute_start:.9f}", "-i", str(source),
"-frames:v", str(num_frames), "-an", "-c:v", "libx264",
"-preset", "medium", "-crf", "23", "-pix_fmt", "yuv420p",
"-movflags", "+faststart", str(destination),
])
details = probe(destination)
if details["num_frames"] != num_frames:
raise RuntimeError(
f"{destination}: expected {num_frames} frames, got {details['num_frames']}"
)
details["source_camera"] = camera
video_metadata[role] = details
view_provenance.append({
"role": role,
"camera": camera,
"asset": f"robot-lev/reassemble/videos/{camera}/chunk-000/file-{file_index:03d}.mp4",
"start_s": absolute_start,
"num_frames": num_frames,
})
fingerprint_input = {
"episode_index": episode_index,
"segment_index": segment_index,
"instruction": instruction,
"videos": {key: value["sha256"] for key, value in video_metadata.items()},
}
build_fingerprint = hashlib.sha256(
json.dumps(fingerprint_input, sort_keys=True).encode("utf-8")
).hexdigest()
metadata = {
"case_id": case_id,
"instruction": instruction,
"goal_image": None,
"videos": video_metadata,
"build_fingerprint": build_fingerprint,
"synchronization": "source mirror clock; same interval and frame count across views",
"format": "RGB H.264/yuv420p MP4; original 30 Hz cadence retained",
}
write_json(case_dir / "metadata.json", metadata)
outcome = "success" if expected_success else "failure"
label_records.append({
"case_id": case_id,
"outcome": outcome,
"success": expected_success,
"native_label": {"segment.success": expected_success},
"label_rule": "constant native segment.success for the entire annotated operation",
"annotation_status": "source_label_only",
"independent_visual_review": "pending",
"progress_annotation": None,
})
provenance_records.append({
"case_id": case_id,
"source": "REASSEMBLE",
"source_repo": "robot-lev/reassemble",
"source_episode": str(episode_index),
"source_task": instruction,
"task": instruction,
"segment_index": segment_index,
"segment_start_frame": int(segment["start_frame"]),
"segment_end_frame_exclusive": int(segment["end_frame"]),
"horizon": "long" if duration_s >= 30 else "short",
"outcome": outcome,
"real_robot": True,
"arms": 1,
"visual_review": "pending",
"views": view_provenance,
"native_label": {"segment.success": expected_success},
"label_rule": "constant native segment.success for the entire annotated operation",
"original_record": RECORDINGS[episode_index],
"temporal_unit": "entire annotated operation segment, not whole multi-operation recording",
"fps": 30,
"num_frames": num_frames,
"duration_s": duration_s,
"license": "CC-BY-4.0",
})
print(f"built {case_id}: ep={episode_index} seg={segment_index} {outcome} {instruction}", flush=True)
labels_path = truth_root / "labels.jsonl"
provenance_path = truth_root / "provenance.jsonl"
labels_path.write_text(
"".join(json.dumps(row, ensure_ascii=False) + "\n" for row in label_records),
encoding="utf-8",
)
provenance_path.write_text(
"".join(json.dumps(row, ensure_ascii=False) + "\n" for row in provenance_records),
encoding="utf-8",
)
summary = {
"case_count": len(selected),
"success_count": sum(row[2] for row in selected),
"failure_count": sum(not row[2] for row in selected),
"source": "REASSEMBLE",
"source_episodes": sorted({row[0] for row in selected}),
"selection_seed": 20260915,
"existing_case_overlap": [],
"recommended_use": "prompt development/calibration hard set",
"warning": "Cases share two source recordings; use a source-disjoint set for final reporting.",
}
write_json(args.output / "selection_summary.json", summary)
if __name__ == "__main__":
main()