vace-aug / vace_object_insert_batch.py
mlnha's picture
every external path now an env var; render script vendored and default to it
0d1fc62 verified
Raw History Blame Contribute Delete
44.6 kB
#!/usr/bin/env python3
"""Build and run a RoboCasa -> VACE object-insertion batch.
The target mesh is the object to insert. The source video is sampled from a
same-category target-object episode across the PickPlace target datasets.
"""
from __future__ import annotations
import argparse
import gzip
import json
import os
import re
import shutil
import subprocess
import sys
import time
import xml.etree.ElementTree as ET
from concurrent.futures import ProcessPoolExecutor, as_completed
from collections import Counter, defaultdict
from pathlib import Path
os.environ.setdefault("MUJOCO_GL", "egl")
os.environ.setdefault("PYOPENGL_PLATFORM", "egl")
import cv2
import mujoco
import numpy as np
import robocasa
import robosuite
from robosuite.utils.binding_utils import MjSim
from robosuite.utils.mjcf_utils import array_to_string, find_elements
TARGET_MESHES = [
"onion/onion_8",
"fish/fish_7",
"ladle/ladle_4",
"eggplant/eggplant_3",
"carrot/carrot_7",
"tomato/tomato_7",
"eggplant/eggplant_4",
"pear/pear_18",
"lemon/lemon_3",
"pear/pear_8",
"orange/orange_3",
"orange/orange_5",
"tangerine/tangerine_4",
"steak/steak_6",
"steak/steak_8",
"egg/egg_6",
"measuring_cup/MeasuringCup009",
"orange/orange_8",
"wooden_spoon/WoodenSpoon012",
]
CAMS = [
"robot0_agentview_left",
"robot0_agentview_right",
"robot0_eye_in_hand",
]
_HERE = Path(__file__).resolve().parent
# The mesh reference-view renderer needs trimesh + pyrender, which the driver's own
# interpreter already has -- so by default reuse it and the vendored copy of the script,
# and this tree needs nothing from outside it.
RENDER_PYTHON = Path(os.environ.get("VACE_RENDER_PYTHON", sys.executable))
RENDER_SCRIPT_DIR = Path(os.environ.get(
"VACE_RENDER_SCRIPT_DIR", _HERE / "aug32" / "vendor"))
ROBOCASA_ROOT = Path(os.environ.get(
"VACE_ROBOCASA_ROOT", "/home/nvidia/jonghoon/robocasa_full/pickplace_target_human"))
# env override so a regenerated / relocated mask tree can be used without editing this file
AUG_MATERIALS_ROOT = Path(os.environ.get(
"VACE_AUG_MATERIALS", "/home/nvidia/jonghoon/robocasa_full/aug_materials/robocasa"))
# where the target meshes live; ":"-separated override, e.g.
# VACE_ASSET_ROOTS=$PWD/data/lightwheel:$PWD/data/objaverse
_DEFAULT_ASSET_ROOTS = (
"/lp-dev/jonghoon/robocasa_calib/repos/robocasa/robocasa/models/assets/objects/lightwheel:"
"/lp-dev/jonghoon/robocasa_calib/repos/robocasa/robocasa/models/assets/objects/objaverse"
)
ASSET_ROOTS = [Path(p) for p in
os.environ.get("VACE_ASSET_ROOTS", _DEFAULT_ASSET_ROOTS).split(":") if p]
def sanitize(value: str) -> str:
value = value.strip().replace("/", "_")
value = re.sub(r"[^A-Za-z0-9_.-]+", "_", value)
value = re.sub(r"_+", "_", value)
return value.strip("_") or "x"
def read_json(path: Path) -> dict:
return json.loads(path.read_text())
def target_obj_info(ep_dir: Path) -> dict | None:
meta = ep_dir / "ep_meta.json"
if not meta.exists():
return None
data = read_json(meta)
obj = next((cfg for cfg in data.get("object_cfgs", []) if cfg.get("name") == "obj"), None)
if obj is None:
return None
info = obj.get("info") or {}
mjcf = info.get("mjcf_path") or ""
return {
"category": info.get("cat"),
"model": Path(mjcf).parent.name if mjcf else None,
"mjcf_path": mjcf,
"lang": data.get("lang"),
}
def scan_sources(dataset_root: Path, categories: set[str]) -> dict[str, list[dict]]:
sources: dict[str, list[dict]] = defaultdict(list)
for task_dir in sorted(p for p in dataset_root.iterdir() if p.is_dir()):
extras = task_dir / "extras"
if not extras.exists():
continue
for ep_dir in sorted(extras.glob("episode_*")):
try:
episode = int(ep_dir.name.split("_")[-1])
except ValueError:
continue
info = target_obj_info(ep_dir)
if not info or info["category"] not in categories:
continue
videos = {
cam: task_dir / "videos/chunk-000" / f"observation.images.{cam}" / f"episode_{episode:06d}.mp4"
for cam in CAMS
}
if not all(path.exists() for path in videos.values()):
continue
sources[info["category"]].append({
"task": task_dir.name,
"episode": episode,
"source_mesh": f"{info['category']}/{info['model']}",
"source_model": info["model"],
"source_category": info["category"],
"lang": info["lang"],
"extras_dir": str(ep_dir),
"videos": {cam: str(path) for cam, path in videos.items()},
})
return sources
def visibility_check_source(job: tuple[str, dict, str, int]) -> tuple[dict, dict | None]:
category, row, out_root_text, min_mask_area = job
out_root = Path(out_root_text)
ep_dir = Path(row["extras_dir"])
cam_stats = {}
ok = True
for cam in CAMS:
seed_dir = (
out_root
/ "visibility_seed_masks"
/ sanitize(row["task"])
/ f"episode_{row['episode']:06d}"
)
try:
stats = render_target_mask(
ep_dir,
cam,
seed_dir / f"{cam}.png",
seed_dir / f"{cam}.json",
)
cam_stats[cam] = stats
if stats["area"] <= min_mask_area:
ok = False
except Exception as exc:
ok = False
cam_stats[cam] = {"error": repr(exc), "area": 0, "bbox_xyxy": None}
vis_row = {
"task": row["task"],
"episode": row["episode"],
"source_mesh": row["source_mesh"],
"category": category,
"visible_all_cams": ok,
"camera_stats": cam_stats,
}
return vis_row, row if ok else None
def round_robin_sources(candidates: list[dict], n: int) -> list[dict]:
by_task: dict[str, list[dict]] = defaultdict(list)
for row in candidates:
by_task[row["task"]].append(row)
task_names = sorted(by_task)
cursors = {task: 0 for task in task_names}
out: list[dict] = []
while len(out) < n:
progressed = False
for task in task_names:
rows = by_task[task]
if not rows:
continue
out.append(rows[cursors[task] % len(rows)])
cursors[task] += 1
progressed = True
if len(out) >= n:
break
if not progressed:
break
return out
def build_assignments(args: argparse.Namespace) -> None:
targets = [line.strip() for line in (args.targets or TARGET_MESHES) if line.strip()]
cats = {t.split("/", 1)[0] for t in targets}
sources = scan_sources(args.dataset_root, cats)
args.out_root.mkdir(parents=True, exist_ok=True)
visibility_rows: list[dict] = []
if args.require_visible_all_cams:
filtered: dict[str, list[dict]] = defaultdict(list)
jobs = [
(category, row, str(args.out_root), args.min_mask_area)
for category, rows in sorted(sources.items())
for row in rows
]
print(json.dumps({
"visibility_prefilter_jobs": len(jobs),
"visibility_workers": args.visibility_workers,
}), flush=True)
sources = filtered
with (args.out_root / "visibility_filter.jsonl").open("w", encoding="utf-8") as f:
if args.visibility_workers <= 1:
iterator = map(visibility_check_source, jobs)
for idx, (vis_row, kept_row) in enumerate(iterator, start=1):
visibility_rows.append(vis_row)
if kept_row is not None:
filtered[vis_row["category"]].append(kept_row)
f.write(json.dumps(vis_row, ensure_ascii=False) + "\n")
f.flush()
if idx % 25 == 0:
print(json.dumps({"visibility_done": idx, "total": len(jobs)}), flush=True)
else:
done = 0
with ProcessPoolExecutor(max_workers=args.visibility_workers) as ex:
future_map = {ex.submit(visibility_check_source, job): job for job in jobs}
for fut in as_completed(future_map):
vis_row, kept_row = fut.result()
visibility_rows.append(vis_row)
if kept_row is not None:
filtered[vis_row["category"]].append(kept_row)
f.write(json.dumps(vis_row, ensure_ascii=False) + "\n")
f.flush()
done += 1
if done % 25 == 0 or done == len(jobs):
print(json.dumps({"visibility_done": done, "total": len(jobs)}), flush=True)
sources = filtered
assignments: list[dict] = []
summary: dict[str, object] = {
"created_at": time.strftime("%Y-%m-%d %H:%M:%S %Z"),
"dataset_root": str(args.dataset_root),
"out_root": str(args.out_root),
"per_mesh": args.per_mesh,
"require_visible_all_cams": bool(args.require_visible_all_cams),
"min_mask_area": args.min_mask_area,
"targets": targets,
"source_counts": {},
"target_counts": {},
}
assignment_idx = 0
for target_mesh in targets:
category, target_model = target_mesh.split("/", 1)
candidates = [
row for row in sources.get(category, [])
if row.get("source_model") != target_model
]
selected = round_robin_sources(candidates, args.per_mesh)
if len(selected) < args.per_mesh:
raise SystemExit(
f"Only {len(selected)} usable same-category sources for {target_mesh}; "
f"requested {args.per_mesh}"
)
task_counts = Counter(row["task"] for row in selected)
mesh_counts = Counter(row["source_mesh"] for row in selected)
summary["target_counts"][target_mesh] = {
"candidate_count_excluding_same_mesh": len(candidates),
"selected_count": len(selected),
"selected_by_task": dict(sorted(task_counts.items())),
"selected_by_source_mesh": dict(sorted(mesh_counts.items())),
}
for sample_idx, src in enumerate(selected):
run_name = (
f"assignment_{assignment_idx:06d}_"
f"{sanitize(src['task'])}_ep{src['episode']:06d}_"
f"{sanitize(target_model)}_from_{sanitize(src['source_model'])}"
)
case_dir = args.out_root / run_name
assignments.append({
"assignment_idx": assignment_idx,
"sample_idx_for_target": sample_idx,
"target_mesh": target_mesh,
"target_category": category,
"target_model": target_model,
"source": src,
"case_dir": str(case_dir),
"run_name": run_name,
})
assignment_idx += 1
for cat, rows in sorted(sources.items()):
summary["source_counts"][cat] = {
"total": len(rows),
"by_task": dict(sorted(Counter(row["task"] for row in rows).items())),
"by_source_mesh": dict(sorted(Counter(row["source_mesh"] for row in rows).items())),
}
with (args.out_root / "assignments.jsonl").open("w", encoding="utf-8") as f:
for row in assignments:
f.write(json.dumps(row, ensure_ascii=False) + "\n")
(args.out_root / "source_summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False))
print(json.dumps({
"assignments": len(assignments),
"view_jobs": len(assignments) * len(CAMS),
"out_root": str(args.out_root),
"assignment_file": str(args.out_root / "assignments.jsonl"),
}, indent=2))
def patch_xml_for_local_assets(xml: str) -> str:
local_rs = os.path.dirname(robosuite.__file__)
local_rc = os.path.dirname(robocasa.__file__)
xml = re.sub(r'/[^"\'\s]*?/robosuite(?=/models/)', local_rs, xml)
xml = re.sub(r'/[^"\'\s]*?/robocasa(?=/models/)', local_rc, xml)
return xml
def sim_from_episode(ep_dir: Path) -> tuple[MjSim, np.ndarray]:
xml = patch_xml_for_local_assets(gzip.open(ep_dir / "model.xml.gz", "rt").read())
root = ET.fromstring(xml)
wb = root.find("worldbody")
existing_cam_names = {c.get("name") for c in root.iter("camera") if c.get("name")}
ep_meta = read_json(ep_dir / "ep_meta.json")
for cn, cfg in ep_meta.get("cam_configs", {}).items():
if cn in existing_cam_names:
continue
parent = find_elements(root=wb, tags="body", attribs={"name": cfg["parent_body"]})
if parent is None:
continue
cam = ET.SubElement(parent, "camera")
cam.set("mode", "fixed")
cam.set("name", cn)
cam.set("pos", array_to_string(cfg["pos"]))
cam.set("quat", array_to_string(cfg["quat"]))
for key, value in (cfg.get("camera_attribs") or {}).items():
cam.set(key, str(value))
sim = MjSim.from_xml_string(ET.tostring(root, encoding="unicode"))
states = np.load(ep_dir / "states.npz")["states"]
return sim, states
def render_target_mask(ep_dir: Path, cam: str, out_path: Path, stats_path: Path) -> dict:
if out_path.exists() and stats_path.exists():
return read_json(stats_path)
sim, states = sim_from_episode(ep_dir)
sim.set_state_from_flattened(states[0])
sim.forward()
model = sim.model._model
data = sim.data._data
target_geom_ids = {
gid for gid in range(model.ngeom)
if (mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_GEOM, gid) or "").startswith("obj_")
}
if not target_geom_ids:
raise RuntimeError(f"No target geoms with obj_ prefix in {ep_dir}")
cam_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_CAMERA, cam)
if cam_id < 0:
raise RuntimeError(f"Camera not found: {cam} in {ep_dir}")
renderer = mujoco.Renderer(model, height=256, width=256)
renderer.enable_segmentation_rendering()
scene_option = mujoco.MjvOption()
scene_option.sitegroup[:] = 0
try:
renderer.update_scene(data, camera=cam_id, scene_option=scene_option)
seg = render_segmentation_safe(renderer)
finally:
renderer.close()
mask = np.isin(seg[..., 0], list(target_geom_ids)).astype(np.uint8) * 255
ys, xs = np.where(mask > 127)
stats = {
"episode_dir": str(ep_dir),
"camera": cam,
"area": int(len(xs)),
"bbox_xyxy": [int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())] if len(xs) else None,
}
out_path.parent.mkdir(parents=True, exist_ok=True)
cv2.imwrite(str(out_path), mask)
stats_path.write_text(json.dumps(stats, indent=2))
return stats
def render_segmentation_safe(renderer: mujoco.Renderer) -> np.ndarray:
"""Render segmentation without MuJoCo's small segid remap allocation bug."""
original_flags = renderer._scene.flags.copy()
renderer._scene.flags[mujoco.mjtRndFlag.mjRND_SEGMENT] = True
renderer._scene.flags[mujoco.mjtRndFlag.mjRND_IDCOLOR] = True
if renderer._gl_context:
renderer._gl_context.make_current()
rgb = np.empty((renderer.height, renderer.width, 3), dtype=np.uint8)
mujoco.mjr_render(renderer._rect, renderer._scene, renderer._mjr_context)
mujoco.mjr_readPixels(rgb, None, renderer._rect, renderer._mjr_context)
image3 = rgb.astype(np.uint32)
segimage = image3[:, :, 0] + image3[:, :, 1] * (2**8) + image3[:, :, 2] * (2**16)
max_segid = int(segimage.max(initial=0))
ngeoms = int(renderer._scene.ngeom)
segid2output = np.full((max(max_segid, ngeoms) + 1, 2), fill_value=-1, dtype=np.int32)
for geom in renderer._scene.geoms[:ngeoms]:
if geom.segid == -1:
continue
segid = int(geom.segid) + 1
if segid < segid2output.shape[0]:
segid2output[segid, 0] = int(geom.objid)
segid2output[segid, 1] = int(geom.objtype)
seg = segid2output[segimage]
np.copyto(renderer._scene.flags, original_flags)
return np.flipud(seg)
def load_assignments(path: Path) -> list[dict]:
return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
def is_archived_path(path: Path) -> bool:
return any(part.startswith("_archive_") for part in path.parts)
def run_cmd(cmd: list[str], log_path: Path) -> int:
log_path.parent.mkdir(parents=True, exist_ok=True)
with log_path.open("a", encoding="utf-8") as log:
log.write("$ " + " ".join(map(str, cmd)) + "\n")
log.flush()
proc = subprocess.run(cmd, stdout=log, stderr=subprocess.STDOUT, text=True)
log.write(f"[exit_code] {proc.returncode}\n")
return proc.returncode
def ffprobe_video(video: Path) -> dict:
proc = subprocess.run(
[
"ffprobe",
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=width,height,r_frame_rate,avg_frame_rate,nb_frames,duration",
"-of",
"json",
str(video),
],
check=True,
capture_output=True,
text=True,
)
streams = json.loads(proc.stdout).get("streams") or []
if not streams:
raise RuntimeError(f"No video stream found in {video}")
return streams[0]
def parse_rate(rate: str | None) -> float:
if not rate:
return 20.0
if "/" in rate:
num, den = rate.split("/", 1)
den_f = float(den)
return float(num) / den_f if den_f else 20.0
return float(rate)
def video_frame_count(video: Path) -> int:
info = ffprobe_video(video)
nb_frames = info.get("nb_frames")
if str(nb_frames).isdigit():
return int(nb_frames)
cap = cv2.VideoCapture(str(video))
try:
count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
finally:
cap.release()
if count <= 0:
raise RuntimeError(f"Could not determine frame count for {video}")
return count
def video_fps(video: Path) -> float:
info = ffprobe_video(video)
return parse_rate(info.get("avg_frame_rate") or info.get("r_frame_rate"))
def video_max_mask_area(video: Path, *, threshold: int = 16) -> int:
cap = cv2.VideoCapture(str(video))
if not cap.isOpened():
raise RuntimeError(f"Could not open mask video: {video}")
max_area = 0
try:
while True:
ok, frame = cap.read()
if not ok:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if frame.ndim == 3 else frame
max_area = max(max_area, int((gray > threshold).sum()))
finally:
cap.release()
return max_area
def segment_starts(total_frames: int, frame_num: int) -> list[int]:
if total_frames <= 0:
raise ValueError(f"total_frames must be positive, got {total_frames}")
if frame_num <= 1:
return [0]
stride = frame_num - 1
starts = [0]
while starts[-1] + frame_num < total_frames:
starts.append(starts[-1] + stride)
return starts
def vace_segment_frame_num(remaining_frames: int, max_frame_num: int) -> int:
"""Use a dynamic tail segment, keeping VACE's preferred 4n+1 length."""
if remaining_frames >= max_frame_num:
return max_frame_num
if remaining_frames <= 1:
return min(max_frame_num, 9)
remainder = remaining_frames % 4
adjusted = remaining_frames if remainder == 1 else remaining_frames + ((1 - remainder) % 4)
return min(max_frame_num, max(9, adjusted))
def write_video_segment(src: Path, dst: Path, start: int, frame_num: int, fps: float) -> dict:
if dst.exists():
try:
existing_count = video_frame_count(dst)
if existing_count == frame_num:
return {
"path": str(dst),
"start": start,
"frame_num": frame_num,
"reused": True,
}
except Exception:
pass
cap = cv2.VideoCapture(str(src))
if not cap.isOpened():
raise RuntimeError(f"Could not open video: {src}")
cap.set(cv2.CAP_PROP_POS_FRAMES, start)
frames = []
try:
for _ in range(frame_num):
ok, frame = cap.read()
if not ok:
break
frames.append(frame)
finally:
cap.release()
if not frames:
raise RuntimeError(f"No frames read from {src} at start={start}")
real_frames = len(frames)
while len(frames) < frame_num:
frames.append(frames[-1].copy())
dst.parent.mkdir(parents=True, exist_ok=True)
h, w = frames[0].shape[:2]
writer = cv2.VideoWriter(str(dst), cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
if not writer.isOpened():
raise RuntimeError(f"Could not open writer for {dst}")
try:
for frame in frames:
writer.write(frame)
finally:
writer.release()
return {
"path": str(dst),
"start": start,
"frame_num": frame_num,
"real_frames": real_frames,
"padded_frames": frame_num - real_frames,
"reused": False,
}
def write_copy_through_manifest(row: dict, cam: str, work_dir: Path, stats: dict) -> Path:
"""Make a complete view output for cameras where the source object is not visible."""
work_dir.mkdir(parents=True, exist_ok=True)
target_tag = sanitize(row["target_model"]).replace("_", "")
inference_dir = work_dir / f"inference_copythrough_{target_tag}"
inference_dir.mkdir(parents=True, exist_ok=True)
src_video = Path(row["source"]["videos"][cam])
out_video = inference_dir / "out_video.mp4"
if out_video.exists() or out_video.is_symlink():
out_video.unlink()
try:
out_video.symlink_to(src_video)
except OSError:
shutil.copy2(src_video, out_video)
manifest = {
"copy_through": True,
"copy_through_reason": stats.get(
"copy_through_reason",
"target-object GT mask is empty or too small for this camera",
),
"video": str(src_video),
"video_info": ffprobe_video(src_video),
"target": row["target_mesh"],
"target_meaning": "new object reference to insert",
"target_model": row["target_model"],
"out_dir": str(work_dir),
"seed_mask_stats": stats,
"mask_source": stats.get("mask_source"),
"preprocess": None,
"inference_save_dir": str(inference_dir),
"out_video": str(out_video),
}
manifest_path = work_dir / "manifest.json"
manifest_path.write_text(json.dumps(manifest, indent=2, ensure_ascii=False))
return manifest_path
def gt_mask_video_path(task: str, episode: int, cam: str, granularity: str = "target_object") -> Path:
ep_dir = AUG_MATERIALS_ROOT / task / f"ep{episode:06d}"
direct = ep_dir / f"mask_gt_{granularity}_{cam}.mp4"
if direct.exists():
return direct
encoded = ep_dir / "encoded_videos" / f"mask_gt_{granularity}_{cam}.mp4"
if encoded.exists():
return encoded
return direct
def mask_video_stats(mask_video: Path, *, threshold: int = 16) -> dict:
cap = cv2.VideoCapture(str(mask_video))
if not cap.isOpened():
raise RuntimeError(f"Could not open GT mask video: {mask_video}")
frame_idx = 0
first_nonzero = None
last_nonzero = None
max_area = 0
nonzero_frames = 0
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or None
try:
while True:
ok, frame = cap.read()
if not ok:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if frame.ndim == 3 else frame
area = int((gray > threshold).sum())
if area > 0:
nonzero_frames += 1
if first_nonzero is None:
first_nonzero = frame_idx
last_nonzero = frame_idx
max_area = max(max_area, area)
frame_idx += 1
finally:
cap.release()
return {
"mask_video": str(mask_video),
"frame_count": frame_count or frame_idx,
"decoded_frames": frame_idx,
"nonzero_frames": nonzero_frames,
"first_nonzero_frame": first_nonzero,
"last_nonzero_frame": last_nonzero,
"max_area": max_area,
"threshold": threshold,
}
def write_gtmask_manifest(row: dict, cam: str, work_dir: Path, stats: dict, ref_images: list[Path]) -> Path:
work_dir.mkdir(parents=True, exist_ok=True)
target_tag = sanitize(row["target_model"]).replace("_", "")
inference_dir = work_dir / f"inference_gtmask_{target_tag}"
inference_dir.mkdir(parents=True, exist_ok=True)
src_video = Path(row["source"]["videos"][cam])
src_mask = Path(stats["mask_video"])
ref_csv = ",".join(str(path) for path in ref_images)
manifest = {
"copy_through": False,
"video": str(src_video),
"video_info": ffprobe_video(src_video),
"target": row["target_mesh"],
"target_meaning": "new object reference to insert",
"target_model": row["target_model"],
"out_dir": str(work_dir),
"mask_source": "gt_mujoco_aug_materials",
"gt_mask_stats": stats,
"reference_images": [str(path) for path in ref_images],
"reference_views": row.get("reference_views"),
"reference_view_variant": row.get("reference_view_variant"),
"preprocess": {
"src_video": str(src_video),
"src_mask": str(src_mask),
"src_ref_images": ref_csv,
},
"inference_save_dir": str(inference_dir),
}
manifest_path = work_dir / "manifest.json"
manifest_path.write_text(json.dumps(manifest, indent=2, ensure_ascii=False))
return manifest_path
def find_asset_dir(target_mesh: str) -> Path:
category, model = target_mesh.split("/", 1)
checked: list[Path] = []
for root in ASSET_ROOTS:
checked.extend([root / category / model, root / model])
for path in checked:
if (path / "visual").is_dir() and any((path / "visual").glob("*.obj")):
return path
raise FileNotFoundError(f"Could not find visual asset for {target_mesh}; checked {checked}")
def ensure_reference_images(target_mesh: str, out_root: Path, gpu: int, views: list[str] | None = None) -> list[Path]:
category, model = target_mesh.split("/", 1)
ref_dir = out_root / "reference_images" / f"{sanitize(category)}__{sanitize(model)}"
requested_views = tuple(views or ("front", "left", "right"))
refs = [ref_dir / f"{view}.png" for view in requested_views]
if all(path.exists() for path in refs):
return refs
lock_root = out_root / "reference_images" / ".locks"
lock_root.mkdir(parents=True, exist_ok=True)
lock_dir = lock_root / f"{sanitize(category)}__{sanitize(model)}.lock"
while True:
try:
lock_dir.mkdir()
break
except FileExistsError:
if all(path.exists() for path in refs):
return refs
time.sleep(2.0)
try:
if all(path.exists() for path in refs):
return refs
asset_dir = find_asset_dir(target_mesh)
ref_dir.mkdir(parents=True, exist_ok=True)
code = f"""
import os, sys
os.environ.setdefault("PYOPENGL_PLATFORM", "egl")
sys.path.insert(0, {str(RENDER_SCRIPT_DIR)!r})
from render_mesh_views_side import render_views
ok = render_views({str(asset_dir)!r}, {str(ref_dir)!r}, resolution=512, min_distance=0.0)
if not ok:
raise SystemExit("render_views failed")
"""
env = os.environ.copy()
env["CUDA_VISIBLE_DEVICES"] = str(gpu)
env.setdefault("PYOPENGL_PLATFORM", "egl")
log_path = out_root / "logs" / "reference_render" / f"{sanitize(category)}__{sanitize(model)}.log"
log_path.parent.mkdir(parents=True, exist_ok=True)
with log_path.open("a", encoding="utf-8") as log:
log.write(f"$ render target={target_mesh} asset={asset_dir} out={ref_dir}\n")
proc = subprocess.run(
[str(RENDER_PYTHON), "-c", code],
stdout=log,
stderr=subprocess.STDOUT,
text=True,
env=env,
)
log.write(f"[exit_code] {proc.returncode}\n")
if proc.returncode != 0:
raise RuntimeError(f"reference render failed for {target_mesh}; see {log_path}")
missing = [path for path in refs if not path.exists()]
if missing:
raise FileNotFoundError(f"reference render missing outputs for {target_mesh}: {missing}")
return refs
finally:
try:
lock_dir.rmdir()
except OSError:
pass
def prep_worker(args: argparse.Namespace) -> None:
rows = load_assignments(args.assignments)
todo = rows[args.worker_id :: args.num_workers]
status_path = args.out_root / "logs" / f"prep_worker_{args.worker_id:02d}_gpu{args.gpu}.jsonl"
status_path.parent.mkdir(parents=True, exist_ok=True)
for row in todo:
ep_dir = Path(row["source"]["extras_dir"])
for cam in CAMS:
case_dir = Path(row["case_dir"])
work_dir = case_dir / f"work_{cam}"
manifest_path = work_dir / "manifest.json"
if manifest_path.exists() and not args.force:
status = {"status": "skipped_existing", "assignment_idx": row["assignment_idx"], "camera": cam}
with status_path.open("a", encoding="utf-8") as f:
f.write(json.dumps(status) + "\n")
continue
try:
mask_video = gt_mask_video_path(row["source"]["task"], int(row["source"]["episode"]), cam, "target_object")
if not mask_video.exists():
raise FileNotFoundError(
f"Missing GT target-object mask video for "
f"{row['source']['task']} ep{int(row['source']['episode']):06d} {cam}: {mask_video}"
)
stats = mask_video_stats(mask_video)
stats["mask_source"] = "gt_mujoco_aug_materials"
if int(stats["max_area"]) <= args.min_mask_area:
stats["copy_through_reason"] = "GT target-object mask is empty or too small across the whole video"
manifest_path = write_copy_through_manifest(row, cam, work_dir, stats)
status = {
"status": "copy_through_invisible",
"assignment_idx": row["assignment_idx"],
"camera": cam,
"target_mesh": row["target_mesh"],
"source_mesh": row["source"]["source_mesh"],
"source_task": row["source"]["task"],
"source_episode": row["source"]["episode"],
"mask_stats": stats,
"manifest": str(manifest_path),
}
with status_path.open("a", encoding="utf-8") as f:
f.write(json.dumps(status, ensure_ascii=False) + "\n")
print(json.dumps(status), flush=True)
continue
ref_images = ensure_reference_images(
row["target_mesh"],
args.out_root,
args.gpu,
row.get("reference_views"),
)
manifest_path = write_gtmask_manifest(row, cam, work_dir, stats, ref_images)
status = {
"status": "ok",
"returncode": 0,
"assignment_idx": row["assignment_idx"],
"camera": cam,
"target_mesh": row["target_mesh"],
"source_mesh": row["source"]["source_mesh"],
"source_task": row["source"]["task"],
"source_episode": row["source"]["episode"],
"mask_stats": stats,
"manifest": str(manifest_path),
"prep_mode": "gt_mask_no_sam2",
}
except Exception as exc:
status = {
"status": "failed",
"assignment_idx": row["assignment_idx"],
"camera": cam,
"target_mesh": row["target_mesh"],
"source_mesh": row["source"]["source_mesh"],
"source_task": row["source"]["task"],
"source_episode": row["source"]["episode"],
"error": repr(exc),
}
with status_path.open("a", encoding="utf-8") as f:
f.write(json.dumps(status, ensure_ascii=False) + "\n")
print(json.dumps(status), flush=True)
def split_batch_manifests(args: argparse.Namespace) -> None:
if args.assignments is not None:
assignment_rows = load_assignments(args.assignments)
manifests = []
for row in assignment_rows:
case_dir = Path(row["case_dir"])
for cam in CAMS:
manifest = case_dir / f"work_{cam}" / "manifest.json"
if manifest.exists():
manifests.append(manifest)
else:
manifests = sorted(
path for path in args.out_root.rglob("assignment_*/work_*/manifest.json")
if not is_archived_path(path.relative_to(args.out_root))
)
jobs: list[dict] = []
for manifest in manifests:
data = read_json(manifest)
if data.get("copy_through"):
continue
preprocess = data["preprocess"]
match = re.search(r"assignment_(\d+)_", str(manifest))
assignment_idx = int(match.group(1)) if match else 0
src_video = Path(preprocess["src_video"])
src_mask = Path(preprocess["src_mask"])
total_frames = min(video_frame_count(src_video), video_frame_count(src_mask))
fps = video_fps(src_video)
starts = segment_starts(total_frames, args.frame_num)
segment_rows = []
segment_root = Path(data["inference_save_dir"]) / "segments"
for segment_idx, start in enumerate(starts):
remaining_frames = max(1, total_frames - start)
segment_frame_num = vace_segment_frame_num(remaining_frames, args.frame_num)
segment_dir = segment_root / f"seg_{segment_idx:03d}_f{start:06d}"
seg_src_video = segment_dir / "src_video_segment.mp4"
seg_src_mask = segment_dir / "src_mask_segment.mp4"
video_info = write_video_segment(src_video, seg_src_video, start, segment_frame_num, fps)
mask_info = write_video_segment(src_mask, seg_src_mask, start, segment_frame_num, fps)
real_frames = max(0, min(segment_frame_num, total_frames - start))
segment_max_mask_area = video_max_mask_area(seg_src_mask)
segment_out_video = segment_dir / "out_video.mp4"
segment_copy_through = segment_max_mask_area <= args.min_mask_area
if segment_copy_through:
if segment_out_video.exists() or segment_out_video.is_symlink():
segment_out_video.unlink()
try:
segment_out_video.symlink_to(seg_src_video)
except OSError:
shutil.copy2(seg_src_video, segment_out_video)
segment_rows.append({
"segment_idx": segment_idx,
"start_frame": start,
"frame_num": segment_frame_num,
"real_frames": real_frames,
"padded_frames": segment_frame_num - real_frames,
"copy_through_zero_mask": segment_copy_through,
"segment_max_mask_area": segment_max_mask_area,
"src_video_segment": str(seg_src_video),
"src_mask_segment": str(seg_src_mask),
"save_dir": str(segment_dir),
"video_segment_info": video_info,
"mask_segment_info": mask_info,
})
if not segment_copy_through:
jobs.append({
"name": f"{manifest.parent.relative_to(args.out_root)}/seg_{segment_idx:03d}_f{start:06d}",
"src_video": str(seg_src_video),
"src_mask": str(seg_src_mask),
"src_ref_images": preprocess["src_ref_images"],
"save_dir": str(segment_dir),
"prompt": "",
"base_seed": args.base_seed + assignment_idx * 1000 + segment_idx,
"frame_num": segment_frame_num,
})
segment_manifest = {
"manifest": str(manifest),
"inference_save_dir": data["inference_save_dir"],
"total_frames": total_frames,
"fps": fps,
"max_frame_num": args.frame_num,
"stride": args.frame_num - 1,
"segments": segment_rows,
"final_out_video": str(Path(data["inference_save_dir"]) / "out_video.mp4"),
}
(Path(data["inference_save_dir"]) / "segments_manifest.json").write_text(
json.dumps(segment_manifest, indent=2, ensure_ascii=False)
)
split_dir = args.split_dir or (args.out_root / "batch_manifests")
split_dir.mkdir(parents=True, exist_ok=True)
for worker_id in range(args.num_workers):
out = split_dir / f"wan_worker_{worker_id:02d}.jsonl"
with out.open("w", encoding="utf-8") as f:
for job in jobs[worker_id :: args.num_workers]:
f.write(json.dumps(job, ensure_ascii=False) + "\n")
print(json.dumps({
"prepared_view_manifests": len(manifests),
"wan_jobs": len(jobs),
"num_workers": args.num_workers,
"split_dir": str(split_dir),
}, indent=2))
def stitch_one_segments_manifest(path: Path, force: bool = False) -> dict:
data = read_json(path)
out_video = Path(data["final_out_video"])
if out_video.exists() and not force:
return {"status": "skipped_existing", "segments_manifest": str(path), "out_video": str(out_video)}
total_frames = int(data["total_frames"])
fps = float(data.get("fps") or 20.0)
frames_written = 0
writer = None
out_video.parent.mkdir(parents=True, exist_ok=True)
try:
for segment in data["segments"]:
seg_video = Path(segment["save_dir"]) / "out_video.mp4"
if not seg_video.exists():
return {
"status": "missing_segment",
"segments_manifest": str(path),
"missing": str(seg_video),
}
cap = cv2.VideoCapture(str(seg_video))
if not cap.isOpened():
return {
"status": "bad_segment",
"segments_manifest": str(path),
"bad": str(seg_video),
}
frame_idx = 0
try:
while frames_written < total_frames:
ok, frame = cap.read()
if not ok:
break
if int(segment["segment_idx"]) > 0 and frame_idx == 0:
frame_idx += 1
continue
if writer is None:
h, w = frame.shape[:2]
writer = cv2.VideoWriter(
str(out_video),
cv2.VideoWriter_fourcc(*"mp4v"),
fps,
(w, h),
)
if not writer.isOpened():
raise RuntimeError(f"Could not open writer for {out_video}")
writer.write(frame)
frames_written += 1
frame_idx += 1
if frames_written >= total_frames:
break
finally:
cap.release()
finally:
if writer is not None:
writer.release()
if frames_written != total_frames:
return {
"status": "incomplete",
"segments_manifest": str(path),
"out_video": str(out_video),
"frames_written": frames_written,
"expected_frames": total_frames,
}
return {
"status": "ok",
"segments_manifest": str(path),
"out_video": str(out_video),
"frames_written": frames_written,
}
def stitch_segments(args: argparse.Namespace) -> None:
if args.assignments is not None:
assignment_rows = load_assignments(args.assignments)
paths = []
for row in assignment_rows:
case_dir = Path(row["case_dir"])
for cam in CAMS:
manifest = case_dir / f"work_{cam}" / "manifest.json"
if not manifest.exists():
continue
data = read_json(manifest)
seg_manifest = Path(data["inference_save_dir"]) / "segments_manifest.json"
if seg_manifest.exists():
paths.append(seg_manifest)
paths = sorted(paths)
else:
paths = sorted(
path for path in args.out_root.rglob("segments_manifest.json")
if not is_archived_path(path.relative_to(args.out_root))
)
rows = [stitch_one_segments_manifest(path, force=args.force) for path in paths]
out_path = args.out_root / "stitch_segments_summary.jsonl"
with out_path.open("w", encoding="utf-8") as f:
for row in rows:
f.write(json.dumps(row, ensure_ascii=False) + "\n")
counts = Counter(row["status"] for row in rows)
print(json.dumps({
"segments_manifests": len(paths),
"status_counts": dict(sorted(counts.items())),
"summary": str(out_path),
}, indent=2))
bad = {k: v for k, v in counts.items() if k not in {"ok", "skipped_existing"}}
if bad:
raise SystemExit(2)
def make_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser()
sub = p.add_subparsers(dest="cmd", required=True)
b = sub.add_parser("build")
b.add_argument("--dataset-root", type=Path, default=ROBOCASA_ROOT)
b.add_argument("--out-root", type=Path, required=True)
b.add_argument("--per-mesh", type=int, default=40)
b.add_argument("--targets", nargs="*")
b.add_argument("--require-visible-all-cams", action="store_true")
b.add_argument("--min-mask-area", type=int, default=8)
b.add_argument("--visibility-workers", type=int, default=24)
w = sub.add_parser("prep-worker")
w.add_argument("--assignments", type=Path, required=True)
w.add_argument("--out-root", type=Path, required=True)
w.add_argument("--worker-id", type=int, required=True)
w.add_argument("--num-workers", type=int, required=True)
w.add_argument("--gpu", type=int, required=True)
w.add_argument("--base-seed", type=int, default=2025)
w.add_argument("--min-mask-area", type=int, default=8)
w.add_argument("--force", action="store_true")
s = sub.add_parser("split-wan")
s.add_argument("--out-root", type=Path, required=True)
s.add_argument("--assignments", type=Path)
s.add_argument("--split-dir", type=Path)
s.add_argument("--num-workers", type=int, required=True)
s.add_argument("--base-seed", type=int, default=2025)
s.add_argument("--frame-num", type=int, default=81)
s.add_argument("--min-mask-area", type=int, default=8)
st = sub.add_parser("stitch-segments")
st.add_argument("--out-root", type=Path, required=True)
st.add_argument("--assignments", type=Path)
st.add_argument("--force", action="store_true")
return p
def main() -> int:
args = make_parser().parse_args()
if args.cmd == "build":
build_assignments(args)
elif args.cmd == "prep-worker":
prep_worker(args)
elif args.cmd == "split-wan":
split_batch_manifests(args)
elif args.cmd == "stitch-segments":
stitch_segments(args)
return 0
if __name__ == "__main__":
raise SystemExit(main())