Enderfga commited on
Commit
da1f1ba
·
verified ·
1 Parent(s): 69bb49c

Upload latent2video.py

Browse files
Files changed (1) hide show
  1. latent2video.py +154 -0
latent2video.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from pathlib import Path
3
+ from typing import Union, List
4
+ from PIL import Image
5
+ import os
6
+ import torch
7
+ import torch.nn as nn
8
+ from diffusers import AutoencoderKLWan
9
+ from diffusers.video_processor import VideoProcessor
10
+ from diffusers.utils import export_to_video
11
+
12
+ def save_images_as_gif(images: List[Image.Image], save_path: str, fps=8) -> None:
13
+
14
+ images[0].save(
15
+ save_path,
16
+ save_all=True,
17
+ append_images=images[1:],
18
+ loop=0,
19
+ duration=int(1000 / fps),
20
+ )
21
+
22
+ def save_video_to_dir(video_frames, save_dir, save_suffix, save_type='frame', fps=8):
23
+ os.makedirs(save_dir, exist_ok=True)
24
+
25
+ save_type_list = save_type.split('_')
26
+
27
+ # save frame
28
+ if 'frame' in save_type_list:
29
+ frame_save_dir = os.path.join(save_dir, 'frames')
30
+ os.makedirs(frame_save_dir, exist_ok=True)
31
+ for idx, img in enumerate(video_frames):
32
+ img.save(os.path.join(frame_save_dir, f'{idx:05d}_{save_suffix}.jpg'))
33
+
34
+ # save to gif
35
+ if 'gif' in save_type_list:
36
+ gif_save_path = os.path.join(save_dir, f'{save_suffix}.gif')
37
+ save_images_as_gif(video_frames, gif_save_path, fps=fps)
38
+
39
+ # save to video
40
+ if 'mp4' in save_type_list:
41
+ video_save_path = os.path.join(save_dir, f'{save_suffix}.mp4')
42
+ export_to_video(video_frames, video_save_path, fps=fps)
43
+
44
+ def setup_vae(model_path: str, device: torch.device) -> AutoencoderKLWan:
45
+ """
46
+ Initialize and setup the VAE model.
47
+
48
+ Args:
49
+ model_path: Path to the VAE model
50
+ device: Target device for model execution
51
+
52
+ Returns:
53
+ Initialized VAE model
54
+ """
55
+ vae = AutoencoderKLWan.from_pretrained(
56
+ model_path,
57
+ subfolder="vae",
58
+ torch_dtype=torch.float32
59
+ ).eval().to(device)
60
+
61
+ # Ensure all parameters are float32
62
+ for param in vae.parameters():
63
+ param.data = param.data.to(torch.float32)
64
+
65
+ return vae
66
+
67
+
68
+ def process_latents(latents: torch.Tensor, vae: nn.Module, device: torch.device) -> torch.Tensor:
69
+ """
70
+ Process and denormalize latent vectors if necessary.
71
+
72
+ Args:
73
+ latents: Input latent vectors
74
+ vae: VAE model containing normalization parameters
75
+ device: Target device for processing
76
+
77
+ Returns:
78
+ Processed latent vectors
79
+ """
80
+ # Ensure latents are in correct shape [B, C, T, H, W]
81
+ if len(latents.shape) == 4:
82
+ latents = latents.unsqueeze(0)
83
+
84
+ # Apply denormalization if mean/std are available
85
+ if hasattr(vae.config, 'latents_mean') and hasattr(vae.config, 'latents_std'):
86
+ latents_mean = torch.tensor(vae.config.latents_mean, device=device, dtype=torch.float32).view(1, -1, 1, 1, 1)
87
+ latents_std = 1.0 / torch.tensor(vae.config.latents_std, device=device, dtype=torch.float32).view(1, -1, 1, 1, 1)
88
+ return latents / latents_std + latents_mean
89
+
90
+ return latents
91
+
92
+
93
+ def latent_to_video(latent_path: Union[str, Path], output_path: Union[str, Path]) -> None:
94
+ """
95
+ Convert latent vectors to video frames and save as MP4.
96
+
97
+ Args:
98
+ latent_path: Path to the latent file (.pth)
99
+ output_path: Path to save the output video (.mp4)
100
+ """
101
+ # Setup device and paths
102
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
103
+ latent_path = Path(latent_path)
104
+ output_path = Path(output_path)
105
+
106
+ # Initialize VAE model
107
+ vae = setup_vae("Wan-AI/Wan2.1-T2V-1.3B-Diffusers", device)
108
+
109
+ # Load and process latents
110
+ latent_dict = torch.load(latent_path, map_location=device)
111
+ latents = latent_dict['latents'].to(torch.float32)
112
+ processed_latents = process_latents(latents, vae, device)
113
+
114
+ # Setup video processor
115
+ vae_scale_factor = 2 ** len(vae.temperal_downsample) if getattr(vae, "vae", None) else 8
116
+ video_processor = VideoProcessor(vae_scale_factor=vae_scale_factor)
117
+
118
+ # Generate video frames
119
+ with torch.no_grad():
120
+ video_frames = vae.decode(processed_latents, return_dict=False)[0]
121
+
122
+ # Post-process and save video
123
+ video_frames = video_processor.postprocess_video(video_frames, output_type="np")
124
+ save_video_to_dir(
125
+ video_frames[0],
126
+ save_dir=str(output_path.parent),
127
+ save_suffix=output_path.stem,
128
+ save_type='mp4',
129
+ fps=16
130
+ )
131
+
132
+
133
+ def main():
134
+ """Parse command line arguments and run the conversion."""
135
+ parser = argparse.ArgumentParser(description="Convert latent vectors to video")
136
+ parser.add_argument('--latent', type=str, required=True, help='Path to the .pth latent file')
137
+ parser.add_argument('--output', type=str, required=True, help='Path to save the output .mp4 video')
138
+ args = parser.parse_args()
139
+
140
+ latent_path = Path(args.latent)
141
+ output_path = Path(args.output)
142
+
143
+ # Validate input/output formats
144
+ assert latent_path.suffix == '.pth', "Latent file must be a .pth file"
145
+ assert output_path.suffix == '.mp4', "Output file must be a .mp4 file"
146
+
147
+ # Ensure output directory exists
148
+ output_path.parent.mkdir(parents=True, exist_ok=True)
149
+
150
+ latent_to_video(latent_path, output_path)
151
+
152
+
153
+ if __name__ == '__main__':
154
+ main()