abreza commited on
Commit
e05bac0
·
1 Parent(s): ae7b7e0

add wan ttm

Browse files
Files changed (1) hide show
  1. app.py +163 -497
app.py CHANGED
@@ -19,6 +19,14 @@ from concurrent.futures import ThreadPoolExecutor
19
  import atexit
20
  import uuid
21
  import decord
 
 
 
 
 
 
 
 
22
 
23
  from models.SpaTrackV2.models.vggt4track.models.vggt_moe import VGGT4Track
24
  from models.SpaTrackV2.models.vggt4track.utils.load_fn import preprocess_image
@@ -30,548 +38,206 @@ logging.basicConfig(level=logging.INFO)
30
  logger = logging.getLogger(__name__)
31
 
32
  # Constants
33
- MAX_FRAMES = 80
34
- OUTPUT_FPS = 24
35
- RENDER_WIDTH = 512
36
- RENDER_HEIGHT = 384
37
-
38
- # Camera movement types
39
- CAMERA_MOVEMENTS = [
40
- "static",
41
- "move_forward",
42
- "move_backward",
43
- "move_left",
44
- "move_right",
45
- "move_up",
46
- "move_down"
47
- ]
48
-
49
- # Thread pool for delayed deletion
50
- thread_pool_executor = ThreadPoolExecutor(max_workers=2)
51
-
52
- def delete_later(path: Union[str, os.PathLike], delay: int = 600):
53
- """Delete file or directory after specified delay"""
54
- def _delete():
55
- try:
56
- if os.path.isfile(path):
57
- os.remove(path)
58
- elif os.path.isdir(path):
59
- shutil.rmtree(path)
60
- except Exception as e:
61
- logger.warning(f"Failed to delete {path}: {e}")
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  def _wait_and_delete():
64
  time.sleep(delay)
65
- _delete()
66
-
67
- thread_pool_executor.submit(_wait_and_delete)
68
- atexit.register(_delete)
 
69
 
70
  def create_user_temp_dir():
71
- """Create a unique temporary directory for each user session"""
72
  session_id = str(uuid.uuid4())[:8]
73
  temp_dir = os.path.join("temp_local", f"session_{session_id}")
74
  os.makedirs(temp_dir, exist_ok=True)
75
- delete_later(temp_dir, delay=600)
76
  return temp_dir
77
 
78
- # Global model initialization
79
- print("🚀 Initializing models...")
80
- vggt4track_model = VGGT4Track.from_pretrained("Yuxihenry/SpatialTrackerV2_Front")
81
- vggt4track_model.eval()
82
- vggt4track_model = vggt4track_model.to("cuda")
83
-
84
- tracker_model = Predictor.from_pretrained("Yuxihenry/SpatialTrackerV2-Offline")
85
- tracker_model.eval()
86
- print("✅ Models loaded successfully!")
87
-
88
- gr.set_static_paths(paths=[Path.cwd().absolute()/"_viz"])
89
-
90
-
91
- def generate_camera_trajectory(num_frames: int, movement_type: str,
92
- base_intrinsics: np.ndarray,
93
- scene_scale: float = 1.0) -> tuple:
94
- """
95
- Generate camera extrinsics for different movement types.
96
-
97
- Returns:
98
- extrinsics: (T, 4, 4) camera-to-world matrices
99
- """
100
- # Movement speed (adjust based on scene scale)
101
  speed = scene_scale * 0.02
102
-
103
  extrinsics = np.zeros((num_frames, 4, 4), dtype=np.float32)
104
-
105
  for t in range(num_frames):
106
- # Start with identity matrix
107
  ext = np.eye(4, dtype=np.float32)
108
-
109
- progress = t / max(num_frames - 1, 1)
110
-
111
- if movement_type == "static":
112
- pass # Keep identity
113
- elif movement_type == "move_forward":
114
- ext[2, 3] = -speed * t # Move along -Z (forward in OpenGL convention)
115
- elif movement_type == "move_backward":
116
- ext[2, 3] = speed * t # Move along +Z
117
- elif movement_type == "move_left":
118
- ext[0, 3] = -speed * t # Move along -X
119
- elif movement_type == "move_right":
120
- ext[0, 3] = speed * t # Move along +X
121
- elif movement_type == "move_up":
122
- ext[1, 3] = -speed * t # Move along -Y (up in OpenGL)
123
- elif movement_type == "move_down":
124
- ext[1, 3] = speed * t # Move along +Y
125
-
126
  extrinsics[t] = ext
127
-
128
  return extrinsics
129
 
130
-
131
- def render_from_pointcloud(rgb_frames: np.ndarray,
132
- depth_frames: np.ndarray,
133
- intrinsics: np.ndarray,
134
- original_extrinsics: np.ndarray,
135
- new_extrinsics: np.ndarray,
136
- output_path: str,
137
- fps: int = 24,
138
- generate_ttm_inputs: bool = False) -> dict:
139
- """
140
- Render video from point cloud with new camera trajectory.
141
-
142
- Args:
143
- rgb_frames: (T, H, W, 3) RGB frames
144
- depth_frames: (T, H, W) depth maps
145
- intrinsics: (T, 3, 3) camera intrinsics
146
- original_extrinsics: (T, 4, 4) original camera extrinsics (world-to-camera)
147
- new_extrinsics: (T, 4, 4) new camera extrinsics for rendering
148
- output_path: path to save rendered video
149
- fps: output video fps
150
- generate_ttm_inputs: if True, also generate motion_signal.mp4 and mask.mp4 for TTM
151
-
152
- Returns:
153
- dict with paths: {'rendered': path, 'motion_signal': path or None, 'mask': path or None}
154
- """
155
  T, H, W, _ = rgb_frames.shape
 
156
 
157
- # Setup video writers
158
- fourcc = cv2.VideoWriter_fourcc(*'mp4v')
159
- out = cv2.VideoWriter(output_path, fourcc, fps, (W, H))
160
-
161
- # TTM outputs: motion_signal (warped with NN inpainting) and mask (valid pixels before inpainting)
162
- motion_signal_path = None
163
- mask_path = None
164
- out_motion_signal = None
165
- out_mask = None
166
 
167
- if generate_ttm_inputs:
168
- base_dir = os.path.dirname(output_path)
169
- motion_signal_path = os.path.join(base_dir, "motion_signal.mp4")
170
- mask_path = os.path.join(base_dir, "mask.mp4")
171
- out_motion_signal = cv2.VideoWriter(motion_signal_path, fourcc, fps, (W, H))
172
- out_mask = cv2.VideoWriter(mask_path, fourcc, fps, (W, H))
173
-
174
- # Create meshgrid for pixel coordinates
175
  u, v = np.meshgrid(np.arange(W), np.arange(H))
176
- ones = np.ones_like(u)
177
-
178
  for t in range(T):
179
- # Get current frame data
180
- rgb = rgb_frames[t]
181
- depth = depth_frames[t]
182
- K = intrinsics[t]
183
-
184
- # Original camera pose (camera-to-world)
185
  orig_c2w = np.linalg.inv(original_extrinsics[t])
186
-
187
- # New camera pose (camera-to-world for the new viewpoint)
188
- # Apply the new extrinsics relative to the first frame
189
- if t == 0:
190
- base_c2w = orig_c2w.copy()
191
-
192
- # New camera is: base_c2w @ new_extrinsics[t]
193
  new_c2w = base_c2w @ new_extrinsics[t]
194
  new_w2c = np.linalg.inv(new_c2w)
195
 
196
- # Unproject pixels to 3D points
197
- K_inv = np.linalg.inv(K)
198
-
199
- # Pixel coordinates to normalized camera coordinates
200
- pixels = np.stack([u, v, ones], axis=-1).reshape(-1, 3) # (H*W, 3)
201
- rays_cam = (K_inv @ pixels.T).T # (H*W, 3)
202
-
203
- # Scale by depth to get 3D points in original camera frame
204
- depth_flat = depth.reshape(-1, 1)
205
- points_cam = rays_cam * depth_flat # (H*W, 3)
206
-
207
- # Transform to world coordinates
208
  points_world = (orig_c2w[:3, :3] @ points_cam.T).T + orig_c2w[:3, 3]
209
-
210
- # Transform to new camera coordinates
211
  points_new_cam = (new_w2c[:3, :3] @ points_world.T).T + new_w2c[:3, 3]
 
212
 
213
- # Project to new image
214
- points_proj = (K @ points_new_cam.T).T
215
-
216
- # Get pixel coordinates
217
- z = points_proj[:, 2:3]
218
- z = np.clip(z, 1e-6, None) # Avoid division by zero
219
- uv_new = points_proj[:, :2] / z
220
-
221
- # Create output image using forward warping with z-buffer
222
  rendered = np.zeros((H, W, 3), dtype=np.uint8)
223
- z_buffer = np.full((H, W), np.inf, dtype=np.float32)
224
-
225
- colors = rgb.reshape(-1, 3)
226
- depths_new = points_new_cam[:, 2]
227
 
228
  for i in range(len(uv_new)):
229
  uu, vv = int(round(uv_new[i, 0])), int(round(uv_new[i, 1]))
230
- if 0 <= uu < W and 0 <= vv < H and depths_new[i] > 0:
231
- if depths_new[i] < z_buffer[vv, uu]:
232
- z_buffer[vv, uu] = depths_new[i]
233
- rendered[vv, uu] = colors[i]
234
 
235
- # Create valid pixel mask BEFORE hole filling (for TTM)
236
- # Valid pixels are those that received projected colors
237
  valid_mask = (rendered.sum(axis=-1) > 0).astype(np.uint8) * 255
238
 
239
- # Nearest-neighbor hole filling using dilation
240
- # This is the inpainting method described in TTM: "Missing regions are inpainted by nearest-neighbor color assignment"
241
- motion_signal_frame = rendered.copy()
242
- hole_mask = (motion_signal_frame.sum(axis=-1) == 0).astype(np.uint8)
243
  if hole_mask.sum() > 0:
244
- kernel = np.ones((3, 3), np.uint8)
245
- # Iteratively dilate to fill holes with nearest neighbor colors
246
- max_iterations = max(H, W) # Ensure all holes can be filled
247
- for _ in range(max_iterations):
248
- if hole_mask.sum() == 0:
249
- break
250
- dilated = cv2.dilate(motion_signal_frame, kernel, iterations=1)
251
- motion_signal_frame = np.where(hole_mask[:, :, None] > 0, dilated, motion_signal_frame)
252
- hole_mask = (motion_signal_frame.sum(axis=-1) == 0).astype(np.uint8)
253
-
254
- # Write TTM outputs if enabled
255
- if generate_ttm_inputs:
256
- # Motion signal: warped frame with NN inpainting
257
- motion_signal_bgr = cv2.cvtColor(motion_signal_frame, cv2.COLOR_RGB2BGR)
258
- out_motion_signal.write(motion_signal_bgr)
259
-
260
- # Mask: binary mask of valid (projected) pixels - white where valid, black where holes
261
- mask_frame = np.stack([valid_mask, valid_mask, valid_mask], axis=-1)
262
- out_mask.write(mask_frame)
263
-
264
- # For the rendered output, use the same inpainted result
265
- rendered_bgr = cv2.cvtColor(motion_signal_frame, cv2.COLOR_RGB2BGR)
266
- out.write(rendered_bgr)
267
-
268
- out.release()
269
-
270
- if generate_ttm_inputs:
271
- out_motion_signal.release()
272
- out_mask.release()
273
-
274
- return {
275
- 'rendered': output_path,
276
- 'motion_signal': motion_signal_path,
277
- 'mask': mask_path
278
- }
279
-
280
-
281
- @spaces.GPU
282
- def run_spatial_tracker(video_tensor: torch.Tensor):
283
- """
284
- GPU-intensive spatial tracking function.
285
-
286
- Args:
287
- video_tensor: Preprocessed video tensor (T, C, H, W)
288
-
289
- Returns:
290
- Dictionary containing tracking results
291
- """
292
- # Run VGGT to get depth and camera poses
293
- video_input = preprocess_image(video_tensor)[None].cuda()
294
 
 
 
 
 
 
 
 
 
 
 
 
295
  with torch.no_grad():
296
- with torch.cuda.amp.autocast(dtype=torch.bfloat16):
297
- predictions = vggt4track_model(video_input / 255)
298
- extrinsic = predictions["poses_pred"]
299
- intrinsic = predictions["intrs"]
300
- depth_map = predictions["points_map"][..., 2]
301
- depth_conf = predictions["unc_metric"]
302
-
303
- depth_tensor = depth_map.squeeze().cpu().numpy()
304
- extrs = extrinsic.squeeze().cpu().numpy()
305
- intrs = intrinsic.squeeze().cpu().numpy()
306
- video_tensor_gpu = video_input.squeeze()
307
- unc_metric = depth_conf.squeeze().cpu().numpy() > 0.5
308
-
309
- # Setup tracker
310
- tracker_model.spatrack.track_num = 512
311
  tracker_model.to("cuda")
 
 
312
 
313
- # Get grid points for tracking
314
- frame_H, frame_W = video_tensor_gpu.shape[2:]
315
- grid_pts = get_points_on_a_grid(30, (frame_H, frame_W), device="cpu")
316
- query_xyt = torch.cat([torch.zeros_like(grid_pts[:, :, :1]), grid_pts], dim=2)[0].numpy()
317
-
318
- # Run tracker
319
- with torch.amp.autocast(device_type="cuda", dtype=torch.bfloat16):
320
- (
321
- c2w_traj, intrs_out, point_map, conf_depth,
322
- track3d_pred, track2d_pred, vis_pred, conf_pred, video_out
323
- ) = tracker_model.forward(
324
- video_tensor_gpu, depth=depth_tensor,
325
- intrs=intrs, extrs=extrs,
326
- queries=query_xyt,
327
- fps=1, full_point=False, iters_track=4,
328
- query_no_BA=True, fixed_cam=False, stage=1,
329
- unc_metric=unc_metric,
330
- support_frame=len(video_tensor_gpu)-1, replace_ratio=0.2
331
- )
332
 
333
- # Resize outputs for rendering
334
- max_size = 384
335
- h, w = video_out.shape[2:]
336
- scale = min(max_size / h, max_size / w)
337
- if scale < 1:
338
- new_h, new_w = int(h * scale), int(w * scale)
339
- video_out = T.Resize((new_h, new_w))(video_out)
340
- point_map = T.Resize((new_h, new_w))(point_map)
341
- conf_depth = T.Resize((new_h, new_w))(conf_depth)
342
- intrs_out[:, :2, :] = intrs_out[:, :2, :] * scale
343
-
344
- # Move results to CPU and return
345
- return {
346
- 'video_out': video_out.cpu(),
347
- 'point_map': point_map.cpu(),
348
- 'conf_depth': conf_depth.cpu(),
349
- 'intrs_out': intrs_out.cpu(),
350
- 'c2w_traj': c2w_traj.cpu(),
351
- }
352
-
353
-
354
- def process_video(video_path: str, camera_movement: str, generate_ttm: bool = True, progress=gr.Progress()):
355
- """Main processing function
356
-
357
- Args:
358
- video_path: Path to input video
359
- camera_movement: Type of camera movement
360
- generate_ttm: If True, generate TTM-compatible outputs (motion_signal.mp4, mask.mp4, first_frame.png)
361
- progress: Gradio progress tracker
362
- """
363
- if video_path is None:
364
- return None, None, None, None, "❌ Please upload a video first"
365
-
366
- progress(0, desc="Initializing...")
367
-
368
- # Create temp directory
369
- temp_dir = create_user_temp_dir()
370
- out_dir = os.path.join(temp_dir, "results")
371
- os.makedirs(out_dir, exist_ok=True)
372
-
373
- try:
374
- # Load video
375
- progress(0.1, desc="Loading video...")
376
- video_reader = decord.VideoReader(video_path)
377
- video_tensor = torch.from_numpy(
378
- video_reader.get_batch(range(len(video_reader))).asnumpy()
379
- ).permute(0, 3, 1, 2).float()
380
-
381
- # Subsample frames if too many
382
- fps_skip = max(1, len(video_tensor) // MAX_FRAMES)
383
- video_tensor = video_tensor[::fps_skip][:MAX_FRAMES]
384
-
385
- # Resize to have minimum side 336
386
- h, w = video_tensor.shape[2:]
387
- scale = 336 / min(h, w)
388
- if scale < 1:
389
- new_h, new_w = int(h * scale) // 2 * 2, int(w * scale) // 2 * 2
390
- video_tensor = T.Resize((new_h, new_w))(video_tensor)
391
-
392
- progress(0.2, desc="Estimating depth and camera poses...")
393
-
394
- # Run GPU-intensive spatial tracking
395
- progress(0.4, desc="Running 3D tracking...")
396
- tracking_results = run_spatial_tracker(video_tensor)
397
-
398
- progress(0.6, desc="Preparing point cloud...")
399
-
400
- # Extract results from tracking
401
- video_out = tracking_results['video_out']
402
- point_map = tracking_results['point_map']
403
- conf_depth = tracking_results['conf_depth']
404
- intrs_out = tracking_results['intrs_out']
405
- c2w_traj = tracking_results['c2w_traj']
406
-
407
- # Get RGB frames and depth
408
- rgb_frames = rearrange(video_out.numpy(), "T C H W -> T H W C").astype(np.uint8)
409
- depth_frames = point_map[:, 2].numpy()
410
- depth_conf_np = conf_depth.numpy()
411
-
412
- # Mask out unreliable depth
413
- depth_frames[depth_conf_np < 0.5] = 0
414
-
415
- # Get camera parameters
416
- intrs_np = intrs_out.numpy()
417
- extrs_np = torch.inverse(c2w_traj).numpy() # world-to-camera
418
-
419
- progress(0.7, desc=f"Generating {camera_movement} camera trajectory...")
420
-
421
- # Calculate scene scale from depth
422
- valid_depth = depth_frames[depth_frames > 0]
423
- scene_scale = np.median(valid_depth) if len(valid_depth) > 0 else 1.0
424
-
425
- # Generate new camera trajectory
426
- num_frames = len(rgb_frames)
427
- new_extrinsics = generate_camera_trajectory(
428
- num_frames, camera_movement, intrs_np, scene_scale
429
- )
430
 
431
- progress(0.8, desc="Rendering video from new viewpoint...")
 
432
 
433
- # Render video (CPU-based, no GPU needed)
434
- output_video_path = os.path.join(out_dir, "rendered_video.mp4")
435
- render_results = render_from_pointcloud(
436
- rgb_frames, depth_frames, intrs_np, extrs_np,
437
- new_extrinsics, output_video_path, fps=OUTPUT_FPS,
438
- generate_ttm_inputs=generate_ttm
439
- )
440
 
441
- # Save first frame for TTM
442
- first_frame_path = None
443
- motion_signal_path = None
444
- mask_path = None
445
-
446
- if generate_ttm:
447
- first_frame_path = os.path.join(out_dir, "first_frame.png")
448
- # Save original first frame (before warping) as PNG
449
- first_frame_rgb = rgb_frames[0]
450
- first_frame_bgr = cv2.cvtColor(first_frame_rgb, cv2.COLOR_RGB2BGR)
451
- cv2.imwrite(first_frame_path, first_frame_bgr)
452
-
453
- motion_signal_path = render_results['motion_signal']
454
- mask_path = render_results['mask']
455
-
456
- progress(1.0, desc="Done!")
457
-
458
- status_msg = f"✅ Video rendered successfully with '{camera_movement}' camera movement!"
459
- if generate_ttm:
460
- status_msg += "\n\n📁 **TTM outputs generated:**\n"
461
- status_msg += f"- `first_frame.png`: Input frame for TTM\n"
462
- status_msg += f"- `motion_signal.mp4`: Warped video with NN inpainting\n"
463
- status_msg += f"- `mask.mp4`: Valid pixel mask (white=valid, black=hole)"
464
-
465
- return render_results['rendered'], motion_signal_path, mask_path, first_frame_path, status_msg
466
-
467
- except Exception as e:
468
- logger.error(f"Error processing video: {e}")
469
- import traceback
470
- traceback.print_exc()
471
- return None, None, None, None, f"❌ Error: {str(e)}"
472
-
473
-
474
- # Create Gradio interface
475
- print("🎨 Creating Gradio interface...")
476
-
477
- with gr.Blocks(
478
- theme=gr.themes.Soft(),
479
- title="🎬 Video to Point Cloud Renderer",
480
- css="""
481
- .gradio-container {
482
- max-width: 1200px !important;
483
- margin: auto !important;
484
- }
485
- """
486
- ) as demo:
487
- gr.Markdown("""
488
- # 🎬 Video to Point Cloud Renderer (TTM Compatible)
489
-
490
- Upload a video to generate a 3D point cloud and render it from a new camera perspective.
491
- Generates outputs compatible with **Time-to-Move (TTM)** motion-controlled video generation.
492
-
493
- **How it works:**
494
- 1. Upload a video
495
- 2. Select a camera movement type
496
- 3. Click "Generate" to create the rendered video and TTM inputs
497
-
498
- **TTM Inputs:**
499
- - `first_frame.png`: The first frame of the original video
500
- - `motion_signal.mp4`: Warped video with nearest-neighbor inpainting
501
- - `mask.mp4`: Binary mask showing valid projected pixels (white) vs holes (black)
502
- """)
503
 
504
- with gr.Row():
505
- with gr.Column(scale=1):
506
- gr.Markdown("### 📥 Input")
507
- video_input = gr.Video(
508
- label="Upload Video",
509
- format="mp4",
510
- height=300
511
- )
512
-
513
- camera_movement = gr.Dropdown(
514
- choices=CAMERA_MOVEMENTS,
515
- value="static",
516
- label="🎥 Camera Movement",
517
- info="Select how the camera should move in the rendered video"
518
- )
519
-
520
- generate_ttm = gr.Checkbox(
521
- label="🎯 Generate TTM Inputs",
522
- value=True,
523
- info="Generate motion_signal.mp4 and mask.mp4 for Time-to-Move"
524
- )
525
-
526
- generate_btn = gr.Button("🚀 Generate", variant="primary", size="lg")
527
-
528
- with gr.Column(scale=1):
529
- gr.Markdown("### 📤 Rendered Output")
530
- output_video = gr.Video(
531
- label="Rendered Video",
532
- height=250
533
- )
534
- first_frame_output = gr.Image(
535
- label="First Frame (first_frame.png)",
536
- height=150
537
- )
538
 
539
- with gr.Row():
540
- with gr.Column(scale=1):
541
- gr.Markdown("### 🎯 TTM: Motion Signal")
542
- motion_signal_output = gr.Video(
543
- label="Motion Signal Video (motion_signal.mp4)",
544
- height=250
545
- )
546
- with gr.Column(scale=1):
547
- gr.Markdown("### 🎭 TTM: Mask")
548
- mask_output = gr.Video(
549
- label="Mask Video (mask.mp4)",
550
- height=250
551
- )
552
-
553
- status_text = gr.Markdown("Ready to process...")
554
-
555
- # Event handlers
556
- generate_btn.click(
557
- fn=process_video,
558
- inputs=[video_input, camera_movement, generate_ttm],
559
- outputs=[output_video, motion_signal_output, mask_output, first_frame_output, status_text]
560
- )
561
 
562
- # Examples
563
- gr.Markdown("### 📁 Examples")
564
- if os.path.exists("./examples"):
565
- example_videos = [f for f in os.listdir("./examples") if f.endswith(".mp4")][:4]
566
- if example_videos:
567
- gr.Examples(
568
- examples=[[f"./examples/{v}", "move_forward", True] for v in example_videos],
569
- inputs=[video_input, camera_movement, generate_ttm],
570
- outputs=[output_video, motion_signal_output, mask_output, first_frame_output, status_text],
571
- fn=process_video,
572
- cache_examples=False
573
- )
574
-
575
- # Launch
576
- if __name__ == "__main__":
577
- demo.launch(share=False)
 
 
 
 
 
 
19
  import atexit
20
  import uuid
21
  import decord
22
+ from PIL import Image
23
+
24
+ try:
25
+ from pipelines.wan_pipeline import WanImageToVideoTTMPipeline
26
+ from pipelines.utils import compute_hw_from_area, validate_inputs
27
+ from diffusers.utils import export_to_video, load_image
28
+ except ImportError:
29
+ print("Warning: TTM pipelines not found. Ensure the /pipelines folder is in your path.")
30
 
31
  from models.SpaTrackV2.models.vggt4track.models.vggt_moe import VGGT4Track
32
  from models.SpaTrackV2.models.vggt4track.utils.load_fn import preprocess_image
 
38
  logger = logging.getLogger(__name__)
39
 
40
  # Constants
41
+ MAX_FRAMES = 81
42
+ OUTPUT_FPS = 16
43
+ WAN_MODEL_ID = "Wan-AI/Wan2.2-I2V-A14B-Diffusers"
44
+ DTYPE = torch.bfloat16
45
+
46
+ # --- Global Model Initialization ---
47
+ print("🚀 Initializing models...")
48
+ vggt4track_model = VGGT4Track.from_pretrained("Yuxihenry/SpatialTrackerV2_Front")
49
+ vggt4track_model.eval().to("cuda")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
+ tracker_model = Predictor.from_pretrained("Yuxihenry/SpatialTrackerV2-Offline")
52
+ tracker_model.eval()
53
+
54
+ # Lazy loading for Wan to save VRAM initially
55
+ wan_pipe = None
56
+
57
+ def get_wan_pipeline():
58
+ global wan_pipe
59
+ if wan_pipe is None:
60
+ print("🚀 Initializing Wan 2.2 TTM Pipeline...")
61
+ wan_pipe = WanImageToVideoTTMPipeline.from_pretrained(WAN_MODEL_ID, torch_dtype=DTYPE)
62
+ wan_pipe.vae.enable_tiling()
63
+ wan_pipe.vae.enable_slicing()
64
+ wan_pipe.to("cuda")
65
+ return wan_pipe
66
+
67
+ # --- Utility Functions ---
68
+ def delete_later(path, delay=600):
69
  def _wait_and_delete():
70
  time.sleep(delay)
71
+ try:
72
+ if os.path.isfile(path): os.remove(path)
73
+ elif os.path.isdir(path): shutil.rmtree(path)
74
+ except: pass
75
+ ThreadPoolExecutor(max_workers=1).submit(_wait_and_delete)
76
 
77
  def create_user_temp_dir():
 
78
  session_id = str(uuid.uuid4())[:8]
79
  temp_dir = os.path.join("temp_local", f"session_{session_id}")
80
  os.makedirs(temp_dir, exist_ok=True)
81
+ delete_later(temp_dir)
82
  return temp_dir
83
 
84
+ def generate_camera_trajectory(num_frames, movement_type, base_intrinsics, scene_scale=1.0):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  speed = scene_scale * 0.02
 
86
  extrinsics = np.zeros((num_frames, 4, 4), dtype=np.float32)
 
87
  for t in range(num_frames):
 
88
  ext = np.eye(4, dtype=np.float32)
89
+ if movement_type == "move_forward": ext[2, 3] = -speed * t
90
+ elif movement_type == "move_backward": ext[2, 3] = speed * t
91
+ elif movement_type == "move_left": ext[0, 3] = -speed * t
92
+ elif movement_type == "move_right": ext[0, 3] = speed * t
93
+ elif movement_type == "move_up": ext[1, 3] = -speed * t
94
+ elif movement_type == "move_down": ext[1, 3] = speed * t
 
 
 
 
 
 
 
 
 
 
 
 
95
  extrinsics[t] = ext
 
96
  return extrinsics
97
 
98
+ def render_from_pointcloud(rgb_frames, depth_frames, intrinsics, original_extrinsics, new_extrinsics, output_path, generate_ttm_inputs=True):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  T, H, W, _ = rgb_frames.shape
100
+ out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*'mp4v'), OUTPUT_FPS, (W, H))
101
 
102
+ motion_signal_path = os.path.join(os.path.dirname(output_path), "motion_signal.mp4")
103
+ mask_path = os.path.join(os.path.dirname(output_path), "mask.mp4")
104
+ out_motion = cv2.VideoWriter(motion_signal_path, cv2.VideoWriter_fourcc(*'mp4v'), OUTPUT_FPS, (W, H))
105
+ out_mask = cv2.VideoWriter(mask_path, cv2.VideoWriter_fourcc(*'mp4v'), OUTPUT_FPS, (W, H))
 
 
 
 
 
106
 
 
 
 
 
 
 
 
 
107
  u, v = np.meshgrid(np.arange(W), np.arange(H))
 
 
108
  for t in range(T):
 
 
 
 
 
 
109
  orig_c2w = np.linalg.inv(original_extrinsics[t])
110
+ if t == 0: base_c2w = orig_c2w.copy()
 
 
 
 
 
 
111
  new_c2w = base_c2w @ new_extrinsics[t]
112
  new_w2c = np.linalg.inv(new_c2w)
113
 
114
+ K_inv = np.linalg.inv(intrinsics[t])
115
+ pixels = np.stack([u, v, np.ones_like(u)], axis=-1).reshape(-1, 3)
116
+ rays_cam = (K_inv @ pixels.T).T
117
+ points_cam = rays_cam * depth_frames[t].reshape(-1, 1)
 
 
 
 
 
 
 
 
118
  points_world = (orig_c2w[:3, :3] @ points_cam.T).T + orig_c2w[:3, 3]
 
 
119
  points_new_cam = (new_w2c[:3, :3] @ points_world.T).T + new_w2c[:3, 3]
120
+ points_proj = (intrinsics[t] @ points_new_cam.T).T
121
 
122
+ uv_new = points_proj[:, :2] / np.clip(points_proj[:, 2:3], 1e-6, None)
 
 
 
 
 
 
 
 
123
  rendered = np.zeros((H, W, 3), dtype=np.uint8)
124
+ z_buf = np.full((H, W), np.inf)
 
 
 
125
 
126
  for i in range(len(uv_new)):
127
  uu, vv = int(round(uv_new[i, 0])), int(round(uv_new[i, 1]))
128
+ if 0 <= uu < W and 0 <= vv < H and points_new_cam[i, 2] > 0:
129
+ if points_new_cam[i, 2] < z_buf[vv, uu]:
130
+ z_buf[vv, uu] = points_new_cam[i, 2]
131
+ rendered[vv, uu] = rgb_frames[t].reshape(-1, 3)[i]
132
 
 
 
133
  valid_mask = (rendered.sum(axis=-1) > 0).astype(np.uint8) * 255
134
 
135
+ # Hole filling for motion signal
136
+ motion_frame = rendered.copy()
137
+ hole_mask = (motion_frame.sum(axis=-1) == 0).astype(np.uint8)
 
138
  if hole_mask.sum() > 0:
139
+ for _ in range(10): # Iterative dilation for NN inpainting
140
+ dilated = cv2.dilate(motion_frame, np.ones((3,3), np.uint8))
141
+ motion_frame = np.where(hole_mask[:, :, None] > 0, dilated, motion_frame)
142
+ hole_mask = (motion_frame.sum(axis=-1) == 0).astype(np.uint8)
143
+ if hole_mask.sum() == 0: break
144
+
145
+ out_motion.write(cv2.cvtColor(motion_frame, cv2.COLOR_RGB2BGR))
146
+ out_mask.write(cv2.merge([valid_mask, valid_mask, valid_mask]))
147
+ out.write(cv2.cvtColor(motion_frame, cv2.COLOR_RGB2BGR))
148
+
149
+ out.release(); out_motion.release(); out_mask.release()
150
+ return {'rendered': output_path, 'motion_signal': motion_signal_path, 'mask': mask_path}
151
+
152
+ # --- Main Processing Logic ---
153
+ def run_ttm_wan_inference(image_path, motion_path, mask_path, prompt, tweak_idx, tstrong_idx, guidance_scale, seed=0):
154
+ pipe = get_wan_pipeline()
155
+ image = load_image(image_path)
156
+ max_area = 480 * 832
157
+ mod_val = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
158
+ h, w = compute_hw_from_area(image.height, image.width, max_area, mod_val)
159
+ image = image.resize((w, h))
160
+
161
+ generator = torch.Generator(device="cuda").manual_seed(seed)
162
+ with torch.inference_mode():
163
+ result = pipe(
164
+ image=image, prompt=prompt, height=h, width=w, num_frames=81,
165
+ guidance_scale=guidance_scale, num_inference_steps=50, generator=generator,
166
+ motion_signal_video_path=motion_path, motion_signal_mask_path=mask_path,
167
+ tweak_index=tweak_idx, tstrong_index=tstrong_idx, negative_prompt="blurry, static, low quality"
168
+ )
169
+ return result.frames[0]
170
+
171
+ def process_video_full_pipeline(video_path, camera_movement, prompt, tweak_idx, tstrong_idx, guidance_scale, progress=gr.Progress()):
172
+ if not video_path or not prompt: return [None]*5 + ["❌ Missing video or prompt"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
 
174
+ temp_dir = create_user_temp_dir()
175
+ res_dir = os.path.join(temp_dir, "results"); os.makedirs(res_dir, exist_ok=True)
176
+
177
+ # 1. Spatial Tracking
178
+ progress(0.1, desc="3D Analysis...")
179
+ vr = decord.VideoReader(video_path)
180
+ vt = torch.from_numpy(vr.get_batch(range(len(vr))).asnumpy()).permute(0,3,1,2).float()
181
+ vt = vt[::max(1, len(vt)//MAX_FRAMES)][:MAX_FRAMES]
182
+
183
+ # Preprocess for VGGT
184
+ v_in = preprocess_image(vt)[None].cuda()
185
  with torch.no_grad():
186
+ preds = vggt4track_model(v_in / 255)
187
+
188
+ # Tracker
 
 
 
 
 
 
 
 
 
 
 
 
189
  tracker_model.to("cuda")
190
+ grid = get_points_on_a_grid(30, v_in.shape[3:], device="cpu")
191
+ queries = torch.cat([torch.zeros_like(grid[:,:,:1]), grid], dim=2)[0].numpy()
192
 
193
+ c2w, intrs, p_map, c_depth, _, _, _, _, v_out = tracker_model.forward(
194
+ v_in.squeeze(), depth=preds["points_map"][...,2].squeeze().cpu().numpy(),
195
+ intrs=preds["intrs"].squeeze().cpu().numpy(), extrs=preds["poses_pred"].squeeze().cpu().numpy(),
196
+ queries=queries, fps=1, iters_track=4, fixed_cam=False
197
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
+ # 2. Rendering
200
+ progress(0.6, desc="Rendering Point Cloud...")
201
+ rgb = rearrange(v_out.cpu().numpy(), "T C H W -> T H W C").astype(np.uint8)
202
+ depth = p_map[0, 2].cpu().numpy() # Simplified for single view context
203
+ new_ext = generate_camera_trajectory(len(rgb), camera_movement, intrs.cpu().numpy(), np.median(depth[depth>0]))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
 
205
+ rend_path = os.path.join(res_dir, "warp.mp4")
206
+ rend_res = render_from_pointcloud(rgb, p_map[:,2].cpu().numpy(), intrs.cpu().numpy(), torch.inverse(c2w).cpu().numpy(), new_ext, rend_path)
207
 
208
+ first_frame_path = os.path.join(res_dir, "first.png")
209
+ cv2.imwrite(first_frame_path, cv2.cvtColor(rgb[0], cv2.COLOR_RGB2BGR))
 
 
 
 
 
210
 
211
+ # 3. Wan TTM Inference
212
+ progress(0.8, desc="Wan 2.2 Realistic Generation...")
213
+ wan_video_path = os.path.join(res_dir, "final_wan.mp4")
214
+ wan_frames = run_ttm_wan_inference(first_frame_path, rend_res['motion_signal'], rend_res['mask'], prompt, tweak_idx, tstrong_idx, guidance_scale)
215
+ export_to_video(wan_frames, wan_video_path, fps=16)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
 
217
+ return rend_path, wan_video_path, rend_res['motion_signal'], rend_res['mask'], first_frame_path, "✅ Generated successfully!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
 
219
+ # --- Gradio UI ---
220
+ with gr.Blocks(theme=gr.themes.Soft(), title="Wan 2.2 TTM Video Generator") as demo:
221
+ gr.Markdown("# 🎬 Time-to-Move (TTM) with Wan 2.2")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
 
223
+ with gr.Row():
224
+ with gr.Column():
225
+ v_in = gr.Video(label="Source Video")
226
+ p_in = gr.Textbox(label="Prompt", placeholder="Describe the action...")
227
+ c_in = gr.Dropdown(choices=["move_forward", "move_backward", "move_left", "move_right", "move_up", "move_down", "static"], value="move_forward", label="Camera Movement")
228
+ with gr.Accordion("TTM Settings", open=False):
229
+ twk = gr.Slider(0, 15, value=3, label="Tweak Index")
230
+ strng = gr.Slider(0, 20, value=7, label="Tstrong Index")
231
+ cfg = gr.Slider(1, 10, value=5.0, label="CFG Scale")
232
+ btn = gr.Button("Generate Realistic Video", variant="primary")
233
+
234
+ with gr.Column():
235
+ v_final = gr.Video(label="Final Realistic Result")
236
+ v_warp = gr.Video(label="Point Cloud Warp (Guide)")
237
+ with gr.Row():
238
+ v_msig = gr.Video(label="Motion Signal")
239
+ v_mask = gr.Video(label="Mask")
240
+
241
+ btn.click(process_video_full_pipeline, [v_in, c_in, p_in, twk, strng, cfg], [v_warp, v_final, v_msig, v_mask, gr.Image(visible=False), gr.Markdown()])
242
+
243
+ demo.launch()