| |
| """Run ReCamMaster on ONE (clip, target_view) pair. |
| |
| ReCamMaster wants: |
| source_video : (T,3,H,W) in [-1,1] -- 41 frames from front.mp4 |
| target_camera: (1, num_anchors, 12) bf16 -- per-anchor (3x4) flattened |
| prompt + negative_prompt |
| num_frames=41, stride=4 -> 11 anchors == our T_anchor_front[11,4,4] |
| |
| The 11 anchors of T_anchor_front are world_from_front_cam (world = front_cam_0). |
| We re-express each target view's anchor pose RELATIVE to source_first_pose |
| (= T_anchor_front[0] = identity), which is: |
| rel[t] = inv(T_anchor_front[0]) @ T_world_from_view_anchor[t] |
| = T_world_from_view_anchor[t] (since T_anchor_front[0] = I) |
| |
| Output: 41-frame mp4 at 832x480, 16fps, in evalWM/results/recammaster/... |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import sys |
| import time |
| from pathlib import Path |
|
|
| import imageio.v3 as iio |
| import numpy as np |
| import torch |
| import torch.nn.functional as F |
|
|
| EVALWM_ROOT = Path("/scratch/project/prj-02-phai-lab/lulin/longtail/evalWM") |
| RECAM_ROOT = Path("/scratch/project/prj-02-phai-lab/lulin/longtail/ReCamMaster") |
| sys.path.insert(0, str(EVALWM_ROOT / "run_baselines")) |
| sys.path.insert(0, str(RECAM_ROOT)) |
|
|
| from io_utils import OUTPUT_FPS, OUTPUT_HEIGHT, OUTPUT_WIDTH, N_OUTPUT_FRAMES |
| from trajectory import SENSOR_FROM_TAG, load_clip_geometry, ANCHOR_INDICES_41 |
|
|
| DEFAULT_NEGATIVE_PROMPT = ( |
| "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰," |
| "最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部," |
| "画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面," |
| "杂乱的背景,三条腿,背景人很多,倒着走" |
| ) |
|
|
|
|
| def build_target_pose_embedding(geo: dict, view: str, num_anchors: int = 11) -> torch.Tensor: |
| """Construct (1, num_anchors, 12) pose embedding for `view`. |
| |
| Base case (num_anchors=11) uses the 11 GT anchors at frame indices [0,4,..,40]. |
| If num_anchors > 11, the extra anchors are padded with the last GT anchor (= frozen |
| camera at t=40). This pairs with last-frame video padding so the scene is "frozen" |
| in the padded tail rather than getting an extrapolated pose. |
| """ |
| sensor = SENSOR_FROM_TAG[view] |
| T_view_41 = geo["T_world_from_cam_41_by_sensor"][sensor] |
| T_front_anchor0 = geo["T_anchor_front_11"][0] |
| inv0 = np.linalg.inv(T_front_anchor0) |
| anchor_poses = T_view_41[ANCHOR_INDICES_41] |
| rel = inv0[None] @ anchor_poses |
| if num_anchors > 11: |
| pad = np.repeat(rel[-1:], num_anchors - 11, axis=0) |
| rel = np.concatenate([rel, pad], axis=0) |
| elif num_anchors < 11: |
| rel = rel[:num_anchors] |
| rel_3x4 = rel[:, :3, :].astype(np.float32) |
| rel_flat = rel_3x4.reshape(num_anchors, 12) |
| return torch.from_numpy(rel_flat).unsqueeze(0).to(torch.bfloat16) |
|
|
|
|
| def load_source_video(front_mp4: str, target_h: int, target_w: int, |
| num_frames: int = N_OUTPUT_FRAMES) -> torch.Tensor: |
| """Returns (T,3,H,W) float32 in [-1,1]. Pads with last frame if source is shorter.""" |
| arr = iio.imread(front_mp4) |
| arr = arr[:num_frames] |
| if arr.shape[0] < num_frames: |
| pad = np.repeat(arr[-1:], num_frames - arr.shape[0], axis=0) |
| arr = np.concatenate([arr, pad], axis=0) |
| t = torch.from_numpy(arr).permute(0, 3, 1, 2).float() / 255.0 |
| if t.shape[2] != target_h or t.shape[3] != target_w: |
| t = F.interpolate(t, size=(target_h, target_w), mode="bilinear", align_corners=False) |
| return (t * 2.0 - 1.0) |
|
|
|
|
| def run_one(args): |
| from diffsynth import ModelManager, WanVideoReCamMasterPipeline, save_video |
|
|
| device = "cuda" |
| row = json.loads(Path(args.clip_json).read_text()) |
| geo = load_clip_geometry(row) |
| pose_embed = build_target_pose_embedding(geo, args.view).to(device) |
| source_video = load_source_video(row["front_mp4"], args.height, args.width).to(device) |
|
|
| |
| if row.get("text_emb_pt"): |
| prompt = torch.load(row["text_emb_pt"], map_location="cpu", weights_only=False).get("prompt", "") |
| else: |
| prompt = "A driving scene viewed from a vehicle-mounted camera." |
|
|
| |
| model_manager = ModelManager(torch_dtype=torch.bfloat16, device="cpu") |
| model_manager.load_models([ |
| str(RECAM_ROOT / "models" / "Wan-AI" / "Wan2.1-T2V-1.3B" / "diffusion_pytorch_model.safetensors"), |
| str(RECAM_ROOT / "models" / "Wan-AI" / "Wan2.1-T2V-1.3B" / "models_t5_umt5-xxl-enc-bf16.pth"), |
| str(RECAM_ROOT / "models" / "Wan-AI" / "Wan2.1-T2V-1.3B" / "Wan2.1_VAE.pth"), |
| ]) |
| pipe = WanVideoReCamMasterPipeline.from_model_manager(model_manager, device=device) |
| |
| dim = pipe.dit.blocks[0].self_attn.q.weight.shape[0] |
| for block in pipe.dit.blocks: |
| block.cam_encoder = torch.nn.Linear(12, dim).to(device).to(torch.bfloat16) |
| block.projector = torch.nn.Linear(dim, dim).to(device).to(torch.bfloat16) |
| block.cam_encoder.weight.data.zero_() |
| block.cam_encoder.bias.data.zero_() |
| block.projector.weight = torch.nn.Parameter(torch.eye(dim).to(device).to(torch.bfloat16)) |
| block.projector.bias = torch.nn.Parameter(torch.zeros(dim).to(device).to(torch.bfloat16)) |
| state_dict = torch.load( |
| RECAM_ROOT / "models" / "ReCamMaster" / "checkpoints" / "step20000.ckpt", |
| map_location="cpu", weights_only=False, |
| ) |
| if "state_dict" in state_dict: |
| state_dict = state_dict["state_dict"] |
| |
| missing, unexpected = pipe.dit.load_state_dict(state_dict, strict=False) |
| print(f"[recam] loaded ckpt: missing={len(missing)} unexpected={len(unexpected)}") |
|
|
| video = pipe( |
| prompt=prompt, |
| negative_prompt=DEFAULT_NEGATIVE_PROMPT, |
| source_video=source_video, |
| target_camera=pose_embed, |
| cfg_scale=args.cfg_scale, |
| num_inference_steps=args.num_steps, |
| seed=args.seed, |
| height=args.height, |
| width=args.width, |
| num_frames=N_OUTPUT_FRAMES, |
| tiled=True, |
| ) |
| |
| out_path = Path(args.output_mp4) |
| out_path.parent.mkdir(parents=True, exist_ok=True) |
| tmp = out_path.with_suffix(".tmp.mp4") |
| save_video(video, str(tmp), fps=OUTPUT_FPS, quality=5) |
| tmp.rename(out_path) |
| print(f"[recammaster_one] wrote {out_path}") |
|
|
|
|
| def parse_args(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--clip-json", required=True) |
| ap.add_argument("--view", required=True, choices=["cross_left", "cross_right", "rear_left", "rear_right", "rear_tele"]) |
| ap.add_argument("--output-mp4", required=True) |
| ap.add_argument("--num-steps", type=int, default=50) |
| ap.add_argument("--cfg-scale", type=float, default=5.0) |
| ap.add_argument("--guidance", type=float, default=1.0) |
| ap.add_argument("--height", type=int, default=480) |
| ap.add_argument("--width", type=int, default=832) |
| ap.add_argument("--seed", type=int, default=0) |
| return ap.parse_args() |
|
|
|
|
| def main(): |
| t0 = time.time() |
| run_one(parse_args()) |
| print(f"[recammaster_one] elapsed {time.time()-t0:.1f}s") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|