"""Batch depth for coaf_dataset_24_25 — input is 25-frame rgb_align/.""" import json import os import sys import time from pathlib import Path import imageio import numpy as np import torch VDA_ROOT = Path( "/project/llmsvgen/sunkai/minghao/week7/week7-video_depth_anything/Video-Depth-Anything" ) sys.path.insert(0, str(VDA_ROOT)) os.chdir(str(VDA_ROOT)) from utils.dc_utils import read_video_frames, save_video from video_depth_anything.video_depth import VideoDepthAnything DATASET_ROOT = Path("/project/llmsvgen/sunkai/robomaster_3d/Casual_CoAF/coaf_dataset_24_25") RAW_ROOT = DATASET_ROOT / "raw" OUTPUT_ROOT = DATASET_ROOT / "modalities" / "depth" TMP_DIR = Path("/tmp/depth_tmp_videos_24_25") RGB_ALIGN_FRAMES = 25 ENCODER = "vitl" INPUT_SIZE = 518 MAX_RES = 1280 FPS = 8 def build_model(encoder, device): model_configs = { "vits": {"encoder": "vits", "features": 64, "out_channels": [48, 96, 192, 384]}, "vitb": {"encoder": "vitb", "features": 128, "out_channels": [96, 192, 384, 768]}, "vitl": {"encoder": "vitl", "features": 256, "out_channels": [256, 512, 1024, 1024]}, } checkpoint_path = f"./checkpoints/video_depth_anything_{encoder}.pth" if not os.path.isfile(checkpoint_path): raise FileNotFoundError(f"Checkpoint not found: {checkpoint_path}") model = VideoDepthAnything(**model_configs[encoder], metric=False) state_dict = torch.load(checkpoint_path, map_location="cpu") model.load_state_dict(state_dict, strict=True) return model.to(device).eval() def frames_to_tmp_video(rgb_dir, tmp_path, num_frames=RGB_ALIGN_FRAMES, fps=8): frames = [] for i in range(1, num_frames + 1): path = rgb_dir / f"frame_{i:04d}.png" if not path.exists(): break frames.append(imageio.imread(str(path))) if len(frames) != num_frames: raise ValueError(f"Expected {num_frames} frames in {rgb_dir}, got {len(frames)}") imageio.mimsave(str(tmp_path), frames, fps=fps, codec="libx264", macro_block_size=1) return len(frames) def main(): import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--start", type=int, default=0, help="First episode index (inclusive)") parser.add_argument("--stop", type=int, default=5000, help="Last episode index (exclusive)") parser.add_argument("--skip-existing", action="store_true", default=True) parser.add_argument("--no-skip-existing", dest="skip_existing", action="store_false") args = parser.parse_args() if not torch.cuda.is_available(): raise RuntimeError( "CUDA GPU required for Video Depth Anything (xformers attention). " "Run via sbatch on a GPU node, not the login node." ) device = "cuda" print(f"Device: {device} ({torch.cuda.get_device_name(0)})") model = build_model(ENCODER, device) TMP_DIR.mkdir(parents=True, exist_ok=True) OUTPUT_ROOT.mkdir(parents=True, exist_ok=True) episodes = sorted(RAW_ROOT.glob("episode_*")) episodes = [ ep for ep in episodes if args.start <= int(ep.name.split("_")[-1]) < args.stop ] print( f"Processing {len(episodes)} episodes idx [{args.start}, {args.stop}) " f"(rgb_align -> depth, {RGB_ALIGN_FRAMES} frames)" ) start_time = time.time() processed = 0 failed = [] for ep_dir in episodes: ep_name = ep_dir.name out_dir = OUTPUT_ROOT / ep_name if args.skip_existing and (out_dir / "depth.mp4").exists(): processed += 1 continue rgb_dir = ep_dir / "rgb_align" if not rgb_dir.exists(): failed.append({"episode": ep_name, "error": "rgb_align dir not found"}) continue tmp_video = TMP_DIR / f"{ep_name}.mp4" try: frames_to_tmp_video(rgb_dir, tmp_video, num_frames=RGB_ALIGN_FRAMES, fps=FPS) frames, target_fps = read_video_frames(str(tmp_video), -1, -1, MAX_RES) depths, fps = model.infer_video_depth( frames, target_fps, input_size=INPUT_SIZE, device=device, fp32=False ) out_dir.mkdir(parents=True, exist_ok=True) save_video(depths, str(out_dir / "depth.mp4"), fps=fps, is_depths=True, grayscale=False) processed += 1 if processed % 200 == 0: elapsed = time.time() - start_time eps = processed / elapsed remaining = (len(episodes) - processed) / max(eps, 0.01) print(f" [{processed}/{len(episodes)}] ~{remaining:.0f}s remaining") except Exception as e: failed.append({"episode": ep_name, "error": str(e)}) finally: if tmp_video.exists(): tmp_video.unlink() print(f"\nDone! {processed}/{len(episodes)}, {len(failed)} failed") if failed: (OUTPUT_ROOT / "depth_failures.json").write_text(json.dumps(failed, indent=2) + "\n") if __name__ == "__main__": main()