| |
| """Append reproducible, timestamped additions from a newer review export.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import collections |
| import concurrent.futures |
| import io |
| import json |
| import os |
| import re |
| import shutil |
| import subprocess |
| from pathlib import Path |
| from typing import Any |
|
|
| from PIL import Image |
|
|
| from prepare_spavobench_release import ( |
| HAN, |
| SOURCE_REPOSITORY, |
| build_manifest, |
| build_source_manifest, |
| imageio_ffmpeg, |
| normalize_english, |
| normalize_scene, |
| parse_timestamp, |
| write_json, |
| write_jsonl, |
| ) |
|
|
|
|
| REVIEW_VERSION = "worldmodelbench-review-2026-08-10.json" |
| TIMESTAMP_AT_END = re.compile(r"\s*[((]\s*(\d{1,4}(?:\.\d+)?)\s*[))]\s*$") |
| NUMBERED_ITEM = re.compile(r"(?m)^\s*(\d+)\s*[.)]\s*") |
|
|
| |
| |
| TRANSLATIONS_BY_SOURCE_INDEX: dict[int, list[str]] = { |
| 6: ["Open the drawer, then close it."], |
| 7: ["Spread the blue bedsheet on the bed."], |
| 9: [ |
| "Take out the blue bottle that the person's hand is touching.", |
| "Rotate the small rectangular wooden block and apply clear glue to its side.", |
| "Fit the small rectangular wooden block into the lower-left corner of the rectangle.", |
| ], |
| 10: ["Exit through the door and walk downstairs."], |
| 13: ["Descend slowly along the rock wall."], |
| 14: ["Rotate the pedal clockwise to turn the wheel.", "Rotate the pedal clockwise to turn the wheel."], |
| 16: ["Exit the door.", "Ride the electric bike out through the door.", "Turn left at the intersection."], |
| 17: [ |
| "Run forward to receive a pass from the teammate in black, then shoot the ball into the goal while a player in white defends.", |
| "Run quickly forward to catch up with the soccer ball.", |
| "Avoid the defender and kick the ball into the goal.", |
| "Receive a forward pass from the teammate in black, break through past the defender and goalkeeper, and shoot.", |
| ], |
| 20: ["Remove the rear wheel from the bicycle."], |
| 21: ["Run forward, catch the ball, jump, and complete a dunk while keeping the camera pointed at the hoop.", "Perform a jump shot."], |
| 22: ["Rotate the camera to the left.", "Rotate the camera to the right."], |
| 25: ["Dribble the ball alternately with the left and right hands. Identify the spatial motion during this basketball activity."], |
| 31: ["Drive along the road until the turn is fully completed."], |
| 34: ["Drive forward around the flower bed."], |
| 45: ["Place the transparent inflatable bag into the cardboard box."], |
| 47: ["Pick up the cup by its handle."], |
| 51: ["Return the top item in the box to the shelf."], |
| 52: ["Sweep the paper ball on the floor from near to far."], |
| 53: ["Sweep the paper ball on the floor from far to near."], |
| 56: ["Drive along the highway."], |
| 60: ["Turn left at the intersection ahead."], |
| 62: ["Drive along the highway."], |
| 63: ["Drive along the road."], |
| 72: ["Make a 180-degree turn, then drive forward."], |
| 75: ["Cut the avocado with a knife and show it to the camera."], |
| 80: ["The traffic light is red; continue driving for the next five seconds."], |
| 137: ["Ride the skateboard from right to left in the U-shaped ramp."], |
| 138: ["Circle around the building once."], |
| 139: ["Roll up the sweet pastry in baking paper, covering the corners securely while it chills in the refrigerator."], |
| 162: [ |
| "Lay the carpet in the room.", |
| "Move the flower bed to the woman's left and remove the original flower bed.", |
| "Finally, put the magazines and remote control into the basket.", |
| ], |
| 163: ["Put the plate on the second rack of the oven and close the oven door."], |
| 165: ["Hold the camera level and circle the dining table once to show the dining room."], |
| 177: ["Skateboard up the steps while keeping the camera following the skateboard."], |
| 179: ["Skateboard onto the handrail."], |
| 208: ["Walk forward among the oncoming crowd."], |
| 213: ["Move toward the camera to show the photo clearly."], |
| 218: ["Walk forward."], |
| 219: ["Rotate the camera to the right to show the other side of the room."], |
| 221: ["Rotate the camera to the left."], |
| 222: ["Rotate the camera to the left."], |
| 224: ["Maintain distance from the vehicle ahead and drive along the road until the turn is fully completed."], |
| 225: ["The man walks upstairs while the camera moves backward to maintain a constant distance from him."], |
| 226: ["Move the camera to the right."], |
| 227: ["Drive along the highway."], |
| 229: ["Walk to the far side of the table while rotating the camera to the right, keeping the table centered in view."], |
| 231: ["Walk to the left side of the table while rotating the camera to the right, keeping the table centered in view."], |
| } |
|
|
| |
| |
| INCOMPLETE_CAPTION_SOURCE_INDICES = {223, 228} |
|
|
|
|
| def source_key(row: dict[str, Any]) -> tuple[str, str]: |
| return str(row.get("sample_id") or ""), str(row.get("video_path") or "") |
|
|
|
|
| def split_caption_with_preamble(caption: str) -> list[dict[str, Any]]: |
| matches = list(NUMBERED_ITEM.finditer(caption)) |
| if not matches: |
| chunks = [(None, caption)] |
| else: |
| chunks: list[tuple[int | None, str]] = [] |
| preamble = caption[: matches[0].start()].strip() |
| if preamble: |
| chunks.append((None, preamble)) |
| for position, match in enumerate(matches): |
| end = matches[position + 1].start() if position + 1 < len(matches) else len(caption) |
| chunks.append((int(match.group(1)), caption[match.end() : end])) |
|
|
| parts: list[dict[str, Any]] = [] |
| for item_number, text in chunks: |
| text = text.strip() |
| timestamp = None |
| found = TIMESTAMP_AT_END.search(text) |
| if found: |
| timestamp = found.group(1) |
| text = text[: found.start()].strip() |
| parts.append({"source_item_number": item_number, "raw_caption": text, "timestamp_raw": timestamp}) |
| return parts |
|
|
|
|
| def translated_caption(source_index: int, segment_index: int, raw_caption: str) -> str: |
| overrides = TRANSLATIONS_BY_SOURCE_INDEX.get(source_index) |
| if overrides is not None: |
| if segment_index > len(overrides): |
| raise ValueError(f"missing translation for source row {source_index}, segment {segment_index}") |
| caption = overrides[segment_index - 1] |
| else: |
| caption = raw_caption |
| caption = normalize_english(caption) |
| if HAN.search(caption): |
| raise ValueError(f"untranslated Chinese remains in source row {source_index}, segment {segment_index}") |
| return caption |
|
|
|
|
| def load_existing_records(release: Path) -> list[dict[str, Any]]: |
| payload = json.loads((release / "data" / "annotations.json").read_text(encoding="utf-8")) |
| return list(payload["annotations"]) |
|
|
|
|
| def select_added_source_rows(old_source: dict[str, Any], new_source: dict[str, Any]) -> list[tuple[int, dict[str, Any]]]: |
| old_keep_keys = {source_key(row) for row in old_source["annotations"] if row.get("decision") == "keep"} |
| return [ |
| (index, row) |
| for index, row in enumerate(new_source["annotations"]) |
| if row.get("decision") == "keep" and source_key(row) not in old_keep_keys |
| ] |
|
|
|
|
| def build_candidates( |
| source_rows: list[tuple[int, dict[str, Any]]], |
| existing: list[dict[str, Any]], |
| ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: |
| known_source_indices = { |
| row.get("source_annotation_index") |
| for row in existing |
| if row.get("source_review_version") == REVIEW_VERSION |
| } |
| candidates: list[dict[str, Any]] = [] |
| audit: list[dict[str, Any]] = [] |
|
|
| for source_index, row in source_rows: |
| if source_index in known_source_indices: |
| continue |
| parts = split_caption_with_preamble(str(row.get("text_caption") or "")) |
| for segment_index, part in enumerate(parts, start=1): |
| raw_caption = part["raw_caption"] |
| if not raw_caption: |
| audit.append({"kind": "empty_caption", "source_annotation_index": source_index, "sample_id": row.get("sample_id")}) |
| continue |
| if source_index in INCOMPLETE_CAPTION_SOURCE_INDICES: |
| audit.append({"kind": "incomplete_caption", "source_annotation_index": source_index, "sample_id": row.get("sample_id")}) |
| continue |
|
|
| timestamp_raw = part["timestamp_raw"] |
| if not timestamp_raw and (len(parts) == 1 or part["source_item_number"] is None): |
| timestamp_raw = str(row.get("timestamp_seconds") or "").strip() |
| timestamp_seconds = parse_timestamp(timestamp_raw) |
| if timestamp_seconds is None: |
| audit.append( |
| { |
| "kind": "missing_timestamp", |
| "source_annotation_index": source_index, |
| "source_caption_segment_index": segment_index, |
| "sample_id": row.get("sample_id"), |
| } |
| ) |
| continue |
|
|
| caption = translated_caption(source_index, segment_index, raw_caption) |
| annotation_id = f"spavobench-20260810-{source_index:04d}-{segment_index:02d}" |
| candidates.append( |
| { |
| "annotation_id": annotation_id, |
| "sample_id": row["sample_id"], |
| "source_annotation_index": source_index, |
| "source_review_version": REVIEW_VERSION, |
| "source_caption_segment_index": segment_index, |
| "source_caption_item_number": part["source_item_number"], |
| "text_caption": caption, |
| "caption_status": "complete", |
| "timestamp_raw": timestamp_raw, |
| "timestamp_seconds": timestamp_seconds, |
| "timestamp_provenance": "caption" if part["timestamp_raw"] else "record", |
| "data_source": row.get("data_source", ""), |
| "annotator": row.get("annotator", ""), |
| "decision": "keep", |
| "track": row.get("track", ""), |
| "scene": normalize_scene(row.get("scene", "")), |
| "spatial_ability": row.get("spatial_ability", ""), |
| "perspective": row.get("perspective", ""), |
| "video_path": row.get("video_path", ""), |
| "source_video_url": row.get("video_url", ""), |
| "source_video_repository": SOURCE_REPOSITORY, |
| "source_video_included": False, |
| "submitted_at": row.get("submitted_at"), |
| "local_saved_at": row.get("local_saved_at"), |
| "updated_at": row.get("updated_at"), |
| "frame_timestamp_seconds": timestamp_seconds, |
| "image_path": f"images/{annotation_id}.jpg", |
| } |
| ) |
| return candidates, audit |
|
|
|
|
| def extract_candidates(candidates: list[dict[str, Any]], output: Path, workers: int, http_proxy: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: |
| ffmpeg = imageio_ffmpeg.get_ffmpeg_exe() |
| image_root = output / "images" |
| audit: list[dict[str, Any]] = [] |
|
|
| def run_frame_job(row: dict[str, Any]) -> tuple[str, str | None]: |
| destination = image_root / f"{row['annotation_id']}.jpg" |
| destination.parent.mkdir(parents=True, exist_ok=True) |
| if destination.exists() and destination.stat().st_size > 0: |
| return row["annotation_id"], None |
| command = [ffmpeg, "-hide_banner", "-loglevel", "error"] |
| if http_proxy: |
| command.extend(["-http_proxy", http_proxy]) |
| command.extend( |
| [ |
| "-ss", |
| f"{row['frame_timestamp_seconds']:.3f}", |
| "-i", |
| row["source_video_url"], |
| "-frames:v", |
| "1", |
| "-vf", |
| "format=yuv420p", |
| "-q:v", |
| "2", |
| str(destination), |
| ] |
| ) |
| try: |
| subprocess.run(command, check=True, timeout=240, capture_output=True) |
| if not destination.exists() or destination.stat().st_size == 0: |
| return row["annotation_id"], "ffmpeg completed without an image" |
| return row["annotation_id"], None |
| except subprocess.TimeoutExpired: |
| return row["annotation_id"], "remote frame extraction timed out after 240 seconds" |
| except subprocess.CalledProcessError as error: |
| fallback = command[:-2] + ["-f", "image2pipe", "-vcodec", "png", "-"] |
| try: |
| decoded = subprocess.run(fallback, check=True, timeout=240, capture_output=True).stdout |
| with Image.open(io.BytesIO(decoded)) as image: |
| image.convert("RGB").save(destination, format="JPEG", quality=95) |
| return row["annotation_id"], None |
| except Exception: |
| return row["annotation_id"], f"remote ffmpeg failed with exit status {error.returncode}" |
|
|
| failures: dict[str, str] = {} |
| with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: |
| for annotation_id, error in pool.map(run_frame_job, candidates): |
| if error: |
| failures[annotation_id] = error |
| for row in candidates: |
| if row["annotation_id"] in failures: |
| audit.append({"kind": "frame", "annotation_id": row["annotation_id"], "error": failures[row["annotation_id"]]}) |
| return [row for row in candidates if row["annotation_id"] not in failures], audit |
|
|
|
|
| def append_release(old_source_path: Path, new_source_path: Path, output: Path, workers: int, http_proxy: str) -> dict[str, Any]: |
| old_source = json.loads(old_source_path.read_text(encoding="utf-8")) |
| new_source = json.loads(new_source_path.read_text(encoding="utf-8")) |
| existing = load_existing_records(output) |
| candidates, audit = build_candidates(select_added_source_rows(old_source, new_source), existing) |
| added, extraction_audit = extract_candidates(candidates, output, workers, http_proxy) |
| audit.extend(extraction_audit) |
| merged = existing + added |
|
|
| manifest = build_manifest(merged, audit) |
| manifest["incremental_update"] = { |
| "review_file": REVIEW_VERSION, |
| "source_keep_rows_added": len(select_added_source_rows(old_source, new_source)), |
| "image_caption_records_added": len(added), |
| "skipped_or_failed_records": len(audit), |
| } |
| write_json(output / "data" / "annotations.json", {"schema_version": "spavobench-v1", "annotations": merged}) |
| write_jsonl(output / "data" / "annotations.jsonl", merged) |
| write_json(output / "data" / "manifest.json", manifest) |
| write_json(output / "data" / "update-2026-08-10.json", {"review_file": REVIEW_VERSION, "added_records": added, "audit": audit}) |
| write_jsonl(output / "data" / "frame_failures.jsonl", audit) |
| write_jsonl(output / "source-videos" / "manifest.jsonl", build_source_manifest(merged)) |
| (output / "scripts").mkdir(exist_ok=True) |
| shutil.copy2(Path(__file__), output / "scripts" / Path(__file__).name) |
| return manifest |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--old-source", type=Path, default=Path("/Users/liusmac/Downloads/worldmodelbench-review-2026-08-08 (6).json")) |
| parser.add_argument("--new-source", type=Path, default=Path("/Users/liusmac/Downloads/worldmodelbench-review-2026-08-10.json")) |
| parser.add_argument("--output", type=Path, default=Path("artifacts/spavobench/v1/release")) |
| parser.add_argument("--download-workers", type=int, default=4) |
| parser.add_argument("--http-proxy", default=os.environ.get("SPAVOBENCH_HTTP_PROXY", "http://127.0.0.1:7897")) |
| args = parser.parse_args() |
| print(json.dumps(append_release(args.old_source, args.new_source, args.output, args.download_workers, args.http_proxy), ensure_ascii=False, indent=2)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|