Spaces:
Paused
Paused
Upload 3 files
Browse files- LICENSE +21 -0
- app.py +436 -0
- requirements.txt +13 -0
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2025 Kuaishou Visual Generation and Interaction Center
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
app.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import os
|
| 5 |
+
import tempfile
|
| 6 |
+
import shutil
|
| 7 |
+
import imageio
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import numpy as np
|
| 10 |
+
from diffsynth import ModelManager, WanVideoReCamMasterPipeline, save_video
|
| 11 |
+
import json
|
| 12 |
+
from torchvision.transforms import v2
|
| 13 |
+
from einops import rearrange
|
| 14 |
+
import torchvision
|
| 15 |
+
from PIL import Image
|
| 16 |
+
import logging
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from huggingface_hub import hf_hub_download
|
| 19 |
+
|
| 20 |
+
logging.basicConfig(level=logging.INFO)
|
| 21 |
+
logger = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
# Camera transformation types
|
| 24 |
+
CAMERA_TRANSFORMATIONS = {
|
| 25 |
+
"1": "Pan Right",
|
| 26 |
+
"2": "Pan Left",
|
| 27 |
+
"3": "Tilt Up",
|
| 28 |
+
"4": "Tilt Down",
|
| 29 |
+
"5": "Zoom In",
|
| 30 |
+
"6": "Zoom Out",
|
| 31 |
+
"7": "Translate Up (with rotation)",
|
| 32 |
+
"8": "Translate Down (with rotation)",
|
| 33 |
+
"9": "Arc Left (with rotation)",
|
| 34 |
+
"10": "Arc Right (with rotation)"
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
# Global variables for model
|
| 38 |
+
model_manager = None
|
| 39 |
+
pipe = None
|
| 40 |
+
is_model_loaded = False
|
| 41 |
+
|
| 42 |
+
def download_recammaster_checkpoint():
|
| 43 |
+
"""Download ReCamMaster checkpoint from HuggingFace using huggingface_hub"""
|
| 44 |
+
# Define paths
|
| 45 |
+
repo_id = "KwaiVGI/ReCamMaster-Wan2.1"
|
| 46 |
+
filename = "step20000.ckpt"
|
| 47 |
+
checkpoint_dir = Path("models/ReCamMaster/checkpoints")
|
| 48 |
+
checkpoint_path = checkpoint_dir / filename
|
| 49 |
+
|
| 50 |
+
# Check if already exists
|
| 51 |
+
if checkpoint_path.exists():
|
| 52 |
+
logger.info(f"✓ ReCamMaster checkpoint already exists at {checkpoint_path}")
|
| 53 |
+
return checkpoint_path
|
| 54 |
+
|
| 55 |
+
# Create directory if it doesn't exist
|
| 56 |
+
checkpoint_dir.mkdir(parents=True, exist_ok=True)
|
| 57 |
+
|
| 58 |
+
# Download the checkpoint
|
| 59 |
+
logger.info("Downloading ReCamMaster checkpoint from HuggingFace...")
|
| 60 |
+
logger.info(f"Repository: {repo_id}")
|
| 61 |
+
logger.info(f"File: {filename}")
|
| 62 |
+
logger.info(f"Destination: {checkpoint_path}")
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
# Download using huggingface_hub
|
| 66 |
+
downloaded_path = hf_hub_download(
|
| 67 |
+
repo_id=repo_id,
|
| 68 |
+
filename=filename,
|
| 69 |
+
local_dir=checkpoint_dir,
|
| 70 |
+
local_dir_use_symlinks=False
|
| 71 |
+
)
|
| 72 |
+
logger.info(f"✓ Successfully downloaded ReCamMaster checkpoint to {downloaded_path}!")
|
| 73 |
+
return downloaded_path
|
| 74 |
+
except Exception as e:
|
| 75 |
+
logger.error(f"✗ Error downloading checkpoint: {e}")
|
| 76 |
+
raise
|
| 77 |
+
|
| 78 |
+
class Camera(object):
|
| 79 |
+
def __init__(self, c2w):
|
| 80 |
+
c2w_mat = np.array(c2w).reshape(4, 4)
|
| 81 |
+
self.c2w_mat = c2w_mat
|
| 82 |
+
self.w2c_mat = np.linalg.inv(c2w_mat)
|
| 83 |
+
|
| 84 |
+
def parse_matrix(matrix_str):
|
| 85 |
+
"""Parse camera matrix string from JSON format"""
|
| 86 |
+
rows = matrix_str.strip().split('] [')
|
| 87 |
+
matrix = []
|
| 88 |
+
for row in rows:
|
| 89 |
+
row = row.replace('[', '').replace(']', '')
|
| 90 |
+
matrix.append(list(map(float, row.split())))
|
| 91 |
+
return np.array(matrix)
|
| 92 |
+
|
| 93 |
+
def get_relative_pose(cam_params):
|
| 94 |
+
"""Calculate relative camera poses"""
|
| 95 |
+
abs_w2cs = [cam_param.w2c_mat for cam_param in cam_params]
|
| 96 |
+
abs_c2ws = [cam_param.c2w_mat for cam_param in cam_params]
|
| 97 |
+
|
| 98 |
+
cam_to_origin = 0
|
| 99 |
+
target_cam_c2w = np.array([
|
| 100 |
+
[1, 0, 0, 0],
|
| 101 |
+
[0, 1, 0, -cam_to_origin],
|
| 102 |
+
[0, 0, 1, 0],
|
| 103 |
+
[0, 0, 0, 1]
|
| 104 |
+
])
|
| 105 |
+
abs2rel = target_cam_c2w @ abs_w2cs[0]
|
| 106 |
+
ret_poses = [target_cam_c2w, ] + [abs2rel @ abs_c2w for abs_c2w in abs_c2ws[1:]]
|
| 107 |
+
ret_poses = np.array(ret_poses, dtype=np.float32)
|
| 108 |
+
return ret_poses
|
| 109 |
+
|
| 110 |
+
def load_models(progress_callback=None):
|
| 111 |
+
"""Load the ReCamMaster models"""
|
| 112 |
+
global model_manager, pipe, is_model_loaded
|
| 113 |
+
|
| 114 |
+
if is_model_loaded:
|
| 115 |
+
return "Models already loaded!"
|
| 116 |
+
|
| 117 |
+
try:
|
| 118 |
+
logger.info("Starting model loading...")
|
| 119 |
+
|
| 120 |
+
# First ensure the checkpoint is downloaded
|
| 121 |
+
if progress_callback:
|
| 122 |
+
progress_callback(0.05, desc="Checking for ReCamMaster checkpoint...")
|
| 123 |
+
|
| 124 |
+
try:
|
| 125 |
+
ckpt_path = download_recammaster_checkpoint()
|
| 126 |
+
logger.info(f"Using checkpoint at {ckpt_path}")
|
| 127 |
+
except Exception as e:
|
| 128 |
+
error_msg = f"Error downloading ReCamMaster checkpoint: {str(e)}"
|
| 129 |
+
logger.error(error_msg)
|
| 130 |
+
return error_msg
|
| 131 |
+
|
| 132 |
+
if progress_callback:
|
| 133 |
+
progress_callback(0.1, desc="Loading model manager...")
|
| 134 |
+
|
| 135 |
+
# Load Wan2.1 pre-trained models
|
| 136 |
+
model_manager = ModelManager(torch_dtype=torch.bfloat16, device="cpu")
|
| 137 |
+
|
| 138 |
+
if progress_callback:
|
| 139 |
+
progress_callback(0.3, desc="Loading Wan2.1 models...")
|
| 140 |
+
|
| 141 |
+
model_manager.load_models([
|
| 142 |
+
"models/Wan-AI/Wan2.1-T2V-1.3B/diffusion_pytorch_model.safetensors",
|
| 143 |
+
"models/Wan-AI/Wan2.1-T2V-1.3B/models_t5_umt5-xxl-enc-bf16.pth",
|
| 144 |
+
"models/Wan-AI/Wan2.1-T2V-1.3B/Wan2.1_VAE.pth",
|
| 145 |
+
])
|
| 146 |
+
|
| 147 |
+
if progress_callback:
|
| 148 |
+
progress_callback(0.5, desc="Creating pipeline...")
|
| 149 |
+
|
| 150 |
+
pipe = WanVideoReCamMasterPipeline.from_model_manager(model_manager, device="cuda")
|
| 151 |
+
|
| 152 |
+
if progress_callback:
|
| 153 |
+
progress_callback(0.7, desc="Initializing ReCamMaster modules...")
|
| 154 |
+
|
| 155 |
+
# Initialize additional modules introduced in ReCamMaster
|
| 156 |
+
dim = pipe.dit.blocks[0].self_attn.q.weight.shape[0]
|
| 157 |
+
for block in pipe.dit.blocks:
|
| 158 |
+
block.cam_encoder = nn.Linear(12, dim)
|
| 159 |
+
block.projector = nn.Linear(dim, dim)
|
| 160 |
+
block.cam_encoder.weight.data.zero_()
|
| 161 |
+
block.cam_encoder.bias.data.zero_()
|
| 162 |
+
block.projector.weight = nn.Parameter(torch.eye(dim))
|
| 163 |
+
block.projector.bias = nn.Parameter(torch.zeros(dim))
|
| 164 |
+
|
| 165 |
+
if progress_callback:
|
| 166 |
+
progress_callback(0.9, desc="Loading ReCamMaster checkpoint...")
|
| 167 |
+
|
| 168 |
+
# Load ReCamMaster checkpoint
|
| 169 |
+
if not os.path.exists(ckpt_path):
|
| 170 |
+
error_msg = f"Error: ReCamMaster checkpoint not found at {ckpt_path} even after download attempt."
|
| 171 |
+
logger.error(error_msg)
|
| 172 |
+
return error_msg
|
| 173 |
+
|
| 174 |
+
state_dict = torch.load(ckpt_path, map_location="cpu")
|
| 175 |
+
pipe.dit.load_state_dict(state_dict, strict=True)
|
| 176 |
+
pipe.to("cuda")
|
| 177 |
+
pipe.to(dtype=torch.bfloat16)
|
| 178 |
+
|
| 179 |
+
is_model_loaded = True
|
| 180 |
+
|
| 181 |
+
if progress_callback:
|
| 182 |
+
progress_callback(1.0, desc="Models loaded successfully!")
|
| 183 |
+
|
| 184 |
+
logger.info("Models loaded successfully!")
|
| 185 |
+
return "Models loaded successfully!"
|
| 186 |
+
|
| 187 |
+
except Exception as e:
|
| 188 |
+
logger.error(f"Error loading models: {str(e)}")
|
| 189 |
+
return f"Error loading models: {str(e)}"
|
| 190 |
+
|
| 191 |
+
def extract_frames_from_video(video_path, output_dir, max_frames=81):
|
| 192 |
+
"""Extract frames from video and ensure we have at least 81 frames"""
|
| 193 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 194 |
+
|
| 195 |
+
reader = imageio.get_reader(video_path)
|
| 196 |
+
fps = reader.get_meta_data()['fps']
|
| 197 |
+
total_frames = reader.count_frames()
|
| 198 |
+
|
| 199 |
+
frames = []
|
| 200 |
+
for i, frame in enumerate(reader):
|
| 201 |
+
frames.append(frame)
|
| 202 |
+
reader.close()
|
| 203 |
+
|
| 204 |
+
# If we have fewer than required frames, repeat the last frame
|
| 205 |
+
if len(frames) < max_frames:
|
| 206 |
+
logger.info(f"Video has {len(frames)} frames, padding to {max_frames} frames")
|
| 207 |
+
last_frame = frames[-1]
|
| 208 |
+
while len(frames) < max_frames:
|
| 209 |
+
frames.append(last_frame)
|
| 210 |
+
|
| 211 |
+
# Save frames
|
| 212 |
+
for i, frame in enumerate(frames[:max_frames]):
|
| 213 |
+
frame_path = os.path.join(output_dir, f"frame_{i:04d}.png")
|
| 214 |
+
imageio.imwrite(frame_path, frame)
|
| 215 |
+
|
| 216 |
+
return len(frames[:max_frames]), fps
|
| 217 |
+
|
| 218 |
+
def process_video_for_recammaster(video_path, text_prompt, cam_type, height=480, width=832):
|
| 219 |
+
"""Process video through ReCamMaster model"""
|
| 220 |
+
global pipe
|
| 221 |
+
|
| 222 |
+
# Create frame processor
|
| 223 |
+
frame_process = v2.Compose([
|
| 224 |
+
v2.CenterCrop(size=(height, width)),
|
| 225 |
+
v2.Resize(size=(height, width), antialias=True),
|
| 226 |
+
v2.ToTensor(),
|
| 227 |
+
v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
|
| 228 |
+
])
|
| 229 |
+
|
| 230 |
+
def crop_and_resize(image):
|
| 231 |
+
width_img, height_img = image.size
|
| 232 |
+
scale = max(width / width_img, height / height_img)
|
| 233 |
+
image = torchvision.transforms.functional.resize(
|
| 234 |
+
image,
|
| 235 |
+
(round(height_img*scale), round(width_img*scale)),
|
| 236 |
+
interpolation=torchvision.transforms.InterpolationMode.BILINEAR
|
| 237 |
+
)
|
| 238 |
+
return image
|
| 239 |
+
|
| 240 |
+
# Load video frames
|
| 241 |
+
reader = imageio.get_reader(video_path)
|
| 242 |
+
frames = []
|
| 243 |
+
|
| 244 |
+
for i in range(81): # ReCamMaster needs exactly 81 frames
|
| 245 |
+
try:
|
| 246 |
+
frame = reader.get_data(i)
|
| 247 |
+
frame = Image.fromarray(frame)
|
| 248 |
+
frame = crop_and_resize(frame)
|
| 249 |
+
frame = frame_process(frame)
|
| 250 |
+
frames.append(frame)
|
| 251 |
+
except:
|
| 252 |
+
# If we run out of frames, repeat the last one
|
| 253 |
+
if frames:
|
| 254 |
+
frames.append(frames[-1])
|
| 255 |
+
else:
|
| 256 |
+
raise ValueError("Video is too short!")
|
| 257 |
+
|
| 258 |
+
reader.close()
|
| 259 |
+
|
| 260 |
+
frames = torch.stack(frames, dim=0)
|
| 261 |
+
frames = rearrange(frames, "T C H W -> C T H W")
|
| 262 |
+
video_tensor = frames.unsqueeze(0) # Add batch dimension
|
| 263 |
+
|
| 264 |
+
# Load camera trajectory
|
| 265 |
+
tgt_camera_path = "./example_test_data/cameras/camera_extrinsics.json"
|
| 266 |
+
with open(tgt_camera_path, 'r') as file:
|
| 267 |
+
cam_data = json.load(file)
|
| 268 |
+
|
| 269 |
+
# Get camera trajectory for selected type
|
| 270 |
+
cam_idx = list(range(81))[::4] # Sample every 4 frames
|
| 271 |
+
traj = [parse_matrix(cam_data[f"frame{idx}"][f"cam{int(cam_type):02d}"]) for idx in cam_idx]
|
| 272 |
+
traj = np.stack(traj).transpose(0, 2, 1)
|
| 273 |
+
|
| 274 |
+
c2ws = []
|
| 275 |
+
for c2w in traj:
|
| 276 |
+
c2w = c2w[:, [1, 2, 0, 3]]
|
| 277 |
+
c2w[:3, 1] *= -1.
|
| 278 |
+
c2w[:3, 3] /= 100
|
| 279 |
+
c2ws.append(c2w)
|
| 280 |
+
|
| 281 |
+
tgt_cam_params = [Camera(cam_param) for cam_param in c2ws]
|
| 282 |
+
relative_poses = []
|
| 283 |
+
for i in range(len(tgt_cam_params)):
|
| 284 |
+
relative_pose = get_relative_pose([tgt_cam_params[0], tgt_cam_params[i]])
|
| 285 |
+
relative_poses.append(torch.as_tensor(relative_pose)[:,:3,:][1])
|
| 286 |
+
|
| 287 |
+
pose_embedding = torch.stack(relative_poses, dim=0) # 21x3x4
|
| 288 |
+
pose_embedding = rearrange(pose_embedding, 'b c d -> b (c d)')
|
| 289 |
+
camera_tensor = pose_embedding.to(torch.bfloat16).unsqueeze(0) # Add batch dimension
|
| 290 |
+
|
| 291 |
+
# Generate video with ReCamMaster
|
| 292 |
+
video = pipe(
|
| 293 |
+
prompt=[text_prompt],
|
| 294 |
+
negative_prompt=["worst quality, low quality, blurry, jittery, distorted"],
|
| 295 |
+
source_video=video_tensor,
|
| 296 |
+
target_camera=camera_tensor,
|
| 297 |
+
cfg_scale=5.0,
|
| 298 |
+
num_inference_steps=50,
|
| 299 |
+
seed=0,
|
| 300 |
+
tiled=True
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
return video
|
| 304 |
+
|
| 305 |
+
def generate_recammaster_video(
|
| 306 |
+
video_file,
|
| 307 |
+
text_prompt,
|
| 308 |
+
camera_type,
|
| 309 |
+
progress=gr.Progress()
|
| 310 |
+
):
|
| 311 |
+
"""Main function to generate video with ReCamMaster"""
|
| 312 |
+
global pipe, is_model_loaded
|
| 313 |
+
|
| 314 |
+
if not is_model_loaded:
|
| 315 |
+
return None, "Error: Models not loaded! Please load models first."
|
| 316 |
+
|
| 317 |
+
if video_file is None:
|
| 318 |
+
return None, "Please upload a video file."
|
| 319 |
+
|
| 320 |
+
try:
|
| 321 |
+
# Create temporary directory for processing
|
| 322 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 323 |
+
progress(0.1, desc="Processing input video...")
|
| 324 |
+
|
| 325 |
+
# Copy uploaded video to temp directory
|
| 326 |
+
input_video_path = os.path.join(temp_dir, "input.mp4")
|
| 327 |
+
shutil.copy(video_file.name, input_video_path)
|
| 328 |
+
|
| 329 |
+
# Extract frames
|
| 330 |
+
progress(0.2, desc="Extracting video frames...")
|
| 331 |
+
num_frames, fps = extract_frames_from_video(input_video_path, os.path.join(temp_dir, "frames"))
|
| 332 |
+
logger.info(f"Extracted {num_frames} frames at {fps} fps")
|
| 333 |
+
|
| 334 |
+
# Process with ReCamMaster
|
| 335 |
+
progress(0.3, desc="Processing with ReCamMaster...")
|
| 336 |
+
output_video = process_video_for_recammaster(
|
| 337 |
+
input_video_path,
|
| 338 |
+
text_prompt,
|
| 339 |
+
camera_type
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
# Save output video
|
| 343 |
+
progress(0.9, desc="Saving output video...")
|
| 344 |
+
output_path = os.path.join(temp_dir, "output.mp4")
|
| 345 |
+
save_video(output_video, output_path, fps=30, quality=5)
|
| 346 |
+
|
| 347 |
+
# Copy to persistent location
|
| 348 |
+
final_output_path = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False).name
|
| 349 |
+
shutil.copy(output_path, final_output_path)
|
| 350 |
+
|
| 351 |
+
progress(1.0, desc="Done!")
|
| 352 |
+
|
| 353 |
+
transformation_name = CAMERA_TRANSFORMATIONS.get(str(camera_type), "Unknown")
|
| 354 |
+
status_msg = f"Successfully generated video with '{transformation_name}' camera movement!"
|
| 355 |
+
|
| 356 |
+
return final_output_path, status_msg
|
| 357 |
+
|
| 358 |
+
except Exception as e:
|
| 359 |
+
logger.error(f"Error generating video: {str(e)}")
|
| 360 |
+
return None, f"Error: {str(e)}"
|
| 361 |
+
|
| 362 |
+
# Create Gradio interface
|
| 363 |
+
with gr.Blocks(title="ReCamMaster Demo") as demo:
|
| 364 |
+
# Show loading status
|
| 365 |
+
loading_status = gr.Textbox(
|
| 366 |
+
label="Model Loading Status",
|
| 367 |
+
value="Loading models, please wait...",
|
| 368 |
+
interactive=False,
|
| 369 |
+
visible=True
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
gr.Markdown("""
|
| 373 |
+
# 🎥 ReCamMaster Demo
|
| 374 |
+
|
| 375 |
+
ReCamMaster allows you to re-capture videos with novel camera trajectories.
|
| 376 |
+
Upload a video and select a camera transformation to see the magic!
|
| 377 |
+
|
| 378 |
+
**Note:** The ReCamMaster checkpoint will be automatically downloaded from HuggingFace when you start the app.
|
| 379 |
+
You still need to download Wan2.1 models using `python download_wan2.1.py` before running this demo.
|
| 380 |
+
""")
|
| 381 |
+
|
| 382 |
+
with gr.Row():
|
| 383 |
+
with gr.Column():
|
| 384 |
+
# Video input section
|
| 385 |
+
with gr.Group():
|
| 386 |
+
gr.Markdown("### Step 1: Upload Video")
|
| 387 |
+
video_input = gr.Video(label="Input Video")
|
| 388 |
+
text_prompt = gr.Textbox(
|
| 389 |
+
label="Text Prompt (describe your video)",
|
| 390 |
+
placeholder="A person walking in the street",
|
| 391 |
+
value="A dynamic scene"
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
# Camera selection
|
| 395 |
+
with gr.Group():
|
| 396 |
+
gr.Markdown("### Step 2: Select Camera Movement")
|
| 397 |
+
camera_type = gr.Radio(
|
| 398 |
+
choices=[(v, k) for k, v in CAMERA_TRANSFORMATIONS.items()],
|
| 399 |
+
label="Camera Transformation",
|
| 400 |
+
value="1"
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
# Generate button
|
| 404 |
+
generate_btn = gr.Button("Generate Video", variant="primary")
|
| 405 |
+
|
| 406 |
+
with gr.Column():
|
| 407 |
+
# Output section
|
| 408 |
+
output_video = gr.Video(label="Output Video")
|
| 409 |
+
status_output = gr.Textbox(label="Generation Status", interactive=False)
|
| 410 |
+
|
| 411 |
+
# Example videos
|
| 412 |
+
gr.Markdown("### Example Videos")
|
| 413 |
+
gr.Examples(
|
| 414 |
+
examples=[
|
| 415 |
+
["example_test_data/videos/case0.mp4", "A person dancing", "1"],
|
| 416 |
+
["example_test_data/videos/case1.mp4", "A scenic view", "5"],
|
| 417 |
+
],
|
| 418 |
+
inputs=[video_input, text_prompt, camera_type],
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
# Load models automatically when the interface loads
|
| 422 |
+
def on_load():
|
| 423 |
+
status = load_models()
|
| 424 |
+
return gr.update(value=status, visible=True if "Error" in status else False)
|
| 425 |
+
|
| 426 |
+
demo.load(on_load, outputs=[loading_status])
|
| 427 |
+
|
| 428 |
+
# Event handlers
|
| 429 |
+
generate_btn.click(
|
| 430 |
+
fn=generate_recammaster_video,
|
| 431 |
+
inputs=[video_input, text_prompt, camera_type],
|
| 432 |
+
outputs=[output_video, status_output]
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
if __name__ == "__main__":
|
| 436 |
+
demo.launch(share=True)
|
requirements.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.0.0
|
| 2 |
+
torchvision
|
| 3 |
+
cupy-cuda12x
|
| 4 |
+
transformers==4.46.2
|
| 5 |
+
controlnet-aux==0.0.7
|
| 6 |
+
imageio
|
| 7 |
+
imageio[ffmpeg]
|
| 8 |
+
safetensors
|
| 9 |
+
einops
|
| 10 |
+
sentencepiece
|
| 11 |
+
protobuf
|
| 12 |
+
modelscope
|
| 13 |
+
ftfy
|