"""Wrapper that runs build_3pointr_dataset.py with multiple fallback prompts. For each input video: try prompts[0]; if SAM3 detects 0 objects, try prompts[1], etc. First prompt that detects gets the episode written. Skips an episode if all fail. Usage: python build_3pointr_dataset_fallback.py \ --videos \ --prompts "a bottle can on the table" "the soda can" "a black can" "the can held by the right gripper" \ --out_root --n_points 512 --start_idx 1 """ import argparse, os, json, glob, traceback from pathlib import Path import numpy as np import cv2 import torch import imageio # Re-use helpers from build_3pointr_dataset.py import importlib.util spec = importlib.util.spec_from_file_location( "_build_mod", "/home/hongyi/PWM/external/build_3pointr_dataset.py") _b = importlib.util.module_from_spec(spec); spec.loader.exec_module(_b) def main(): ap = argparse.ArgumentParser() ap.add_argument("--videos", nargs="+", required=True) ap.add_argument("--prompts", nargs="+", required=True, help="prompts tried in order; first hit wins") ap.add_argument("--out_root", required=True) ap.add_argument("--n_points", type=int, default=512) ap.add_argument("--max_frames", type=int, default=0) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--start_idx", type=int, default=1) args = ap.parse_args() paths = [] for v in args.videos: if os.path.exists(v): paths.append(v) else: paths.extend(sorted(glob.glob(v))) paths = sorted(set(paths)) print(f"[main] {len(paths)} videos, prompts={args.prompts}") import sam3.model_builder as _mb from sam3.model_builder import build_sam3_video_predictor bpe = str(Path(_mb.__file__).parent / "assets" / "bpe_simple_vocab_16e6.txt.gz") print("[main] loading SAM3 ...") predictor = build_sam3_video_predictor( bpe_path=bpe, gpus_to_use=[0], apply_temporal_disambiguation=False) print("[main] loading CoTracker3 (offline) ...") from cotracker.predictor import CoTrackerPredictor cot = CoTrackerPredictor( checkpoint="/home/hongyi/PWM/external/co-tracker/checkpoints/scaled_offline.pth" ).cuda() print("[main] loading MoGe2 ...") from moge.model.v2 import MoGeModel moge = MoGeModel.from_pretrained("Ruicheng/moge-2-vitl-normal").cuda().eval() rng = np.random.default_rng(args.seed) summary = [] os.makedirs(args.out_root, exist_ok=True) for ep_offset, vp in enumerate(paths): ep_id = args.start_idx + ep_offset out_dir = os.path.join(args.out_root, f"{ep_id:04d}") if os.path.exists(os.path.join(out_dir, "metadata.json")): print(f"[{ep_id:04d}] already exists, skipping ({vp})") continue print(f"\n[{ep_id:04d}] === {os.path.basename(vp)} ===", flush=True) try: frames = _b.load_video(vp, args.max_frames or None) T = len(frames); H, W, _ = frames[0].shape print(f" {T} frames, {H}x{W}") if args.max_frames and len(frames) >= args.max_frames: tmp_video = os.path.join(args.out_root, f"_tmp_{ep_id:04d}.mp4") imageio.mimwrite(tmp_video, frames, fps=15, macro_block_size=1) video_for_sam3 = tmp_video else: tmp_video = None video_for_sam3 = vp chosen_prompt = None masks_dict = None; n_obj = 0 for prompt in args.prompts: masks_dict, n_obj = _b.sam3_propagate(predictor, video_for_sam3, prompt) if masks_dict is not None and masks_dict[0].any(): chosen_prompt = prompt print(f" prompt='{prompt}' -> {n_obj} obj") break else: print(f" prompt='{prompt}' -> 0 obj") if tmp_video and os.path.exists(tmp_video): os.remove(tmp_video) if chosen_prompt is None: print(f" ALL prompts failed; skipping") summary.append({"ep": ep_id, "video": vp, "status": "all_prompts_failed"}) continue masks_arr = np.stack([masks_dict[i] for i in range(T)], axis=0) queries_xy = _b.sample_queries_in_mask(masks_arr[0], args.n_points, rng) tracks2d, vis = _b.run_cotracker(cot, frames, queries_xy, init_frame_idx=0) print(f" CoTracker3: {tracks2d.shape}, vis frame0={int(vis[0].sum())}, " f"vis frame-1={int(vis[-1].sum())}") depths, K = _b.run_moge(moge, frames) print(f" MoGe2: depth [{np.nanmin(depths):.2f},{np.nanmax(depths):.2f}] m") pts_3d = _b.lift_points(tracks2d, depths, K) depth_invalid = (pts_3d[..., 2] <= 1e-3) vis = vis.astype(bool) & (~depth_invalid) print(f" 3D pos[0] z [{pts_3d[0,:,2].min():.3f}, {pts_3d[0,:,2].max():.3f}] m, " f"max |cum_flow| {np.abs(pts_3d - pts_3d[0:1]).max():.3f} m") meta = { "ep_id": ep_id, "source_video": os.path.abspath(vp), "prompt": chosen_prompt, "T": int(T), "N": int(args.n_points), "H": int(H), "W": int(W), "intrinsics": {"camera": { "fx": float(K[0,0]), "fy": float(K[1,1]), "cx": float(K[0,2]), "cy": float(K[1,2]), "width": int(W), "height": int(H), }}, "depth_model": "Ruicheng/moge-2-vitl-normal", "depth_units": "metric meters (MoGe2)", "tracker": "cotracker3-offline (scaled_offline.pth)", "n_obj_sam3": int(n_obj), "vis_frame0": int(vis[0].sum()), "vis_frame_last": int(vis[-1].sum()), "convention": "timestep_k corresponds to frame index k-1; timestep_1 has cum_flow == 0", } _b.write_episode(out_dir, frames, masks_arr, pts_3d, vis, meta) summary.append({"ep": ep_id, "video": vp, "status": "ok", "prompt": chosen_prompt, "T": T, "N": args.n_points, "vis_first": int(vis[0].sum()), "vis_last": int(vis[-1].sum())}) print(f" wrote {out_dir}") except Exception as e: print(f" FAILED: {e}") traceback.print_exc() summary.append({"ep": ep_id, "video": vp, "status": "exception", "error": str(e)}) summary_path = os.path.join(args.out_root, "_build_fallback_summary.json") with open(summary_path, "w") as f: json.dump(summary, f, indent=2) print(f"\n[main] summary -> {summary_path}") if __name__ == "__main__": main()