File size: 13,365 Bytes
a71d323 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 |
import random
import argparse
import cv2
from tqdm import tqdm
import numpy as np
import numpy.typing as npt
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler, Subset
from decord import VideoReader, cpu
from torch.nn import functional as F
from pytorchvideo.transforms import ShortSideScale
from torchvision.transforms import Lambda, Compose
from torchvision.transforms._transforms_video import CenterCropVideo
import sys
from torch.utils.data import Dataset, DataLoader, Subset
import os
import glob
sys.path.append(".")
from causalvideovae.model import CausalVAEModel
from diffusers.models import AutoencoderKL
from diffusers.models import AutoencoderKLTemporalDecoder
from CV_VAE.models.modeling_vae import CVVAEModel
from opensora.registry import MODELS, build_module
from opensora.utils.config_utils import parse_configs
from opensora.registry import MODELS, build_module
from opensora.utils.config_utils import parse_configs
import gradio as gr
from functools import partial
from einops import rearrange
import torchvision.transforms as transforms
from PIL import Image
import time
import imageio
# 创建一个transform,用于中心裁剪图像到指定的大小
transform = transforms.Compose([
transforms.CenterCrop(512),
])
def array_to_video(
image_array: npt.NDArray, fps: float = 30.0, output_file: str = "output_video.mp4"
) -> None:
height, width, channels = image_array[0].shape
imageio.mimwrite(output_file, image_array, fps=fps, quality=6,)
"""
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
video_writer = cv2.VideoWriter(output_file, fourcc, float(fps), (width, height))
for image in image_array:
image_rgb = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
video_writer.write(image_rgb)
video_writer.release()
"""
def custom_to_video(
x: torch.Tensor, fps: float = 2.0, output_file: str = "output_video.mp4"
) -> None:
x = x.detach().cpu()
x = torch.clamp(x, -1, 1)
x = (x + 1) / 2
x = x.permute(1, 2, 3, 0).float().numpy()
x = (255 * x).astype(np.uint8)
array_to_video(x, fps=fps, output_file=output_file)
return
def _format_video_shape(video, time_compress=4, spatial_compress=8):
time = video.shape[1]
height = video.shape[2]
width = video.shape[3]
new_time = (
(time - (time - 1) % time_compress)
if (time - 1) % time_compress != 0
else time
)
new_height = (
(height - (height) % spatial_compress)
if height % spatial_compress != 0
else height
)
new_width = (
(width - (width) % spatial_compress) if width % spatial_compress != 0 else width
)
return video[:, :new_time, :new_height, :new_width]
@torch.no_grad()
def rec_nusvae(input_file):
nus_vae_path = '/storage/clh/Causal-Video-VAE/gradio/nus_vae_temp/video.mp4'
if input_file.endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp')):
#处理图像
image = cv2.imread(input_file, cv2.IMREAD_COLOR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
fps=10
total_frames = 1
video_data = torch.from_numpy(image)
video_data = video_data.unsqueeze(0)
video_data = video_data.permute(3, 0, 1, 2)
video_data = (video_data / 255.0) * 2 - 1
video_data = _format_video_shape(video_data)
video_data = video_data.unsqueeze(0)
video_data = video_data.to(dtype=data_type) # b c t h w
elif input_file.endswith(('.mp4', '.avi', '.mov', '.wmv')):
# 处理视频
decord_vr = VideoReader(input_file, ctx=cpu(0))
total_frames = len(decord_vr)
video = cv2.VideoCapture(input_file)
fps = video.get(cv2.CAP_PROP_FPS)
frame_id_list = np.linspace(0, total_frames-1, total_frames, dtype=int)
video_data = decord_vr.get_batch(frame_id_list).asnumpy()
video_data = torch.from_numpy(video_data)
video_data = video_data.permute(3, 0, 1, 2)
video_data = (video_data / 255.0) * 2 - 1
video_data = _format_video_shape(video_data)
video_data = video_data.unsqueeze(0)
video_data = video_data.to(dtype=data_type) # b c t h w
video_data = video_data.to(device4)
latents, posterior, x_z = nus_vae.encode(video_data)
video_recon, x_z_rec = nus_vae.decode(latents, num_frames=video_data.size(2))
custom_to_video(video_recon[0], fps=fps, output_file=nus_vae_path)
time.sleep(15)
return nus_vae_path
@torch.no_grad()
def rec_cvvae(input_file):
cv_vae_path = '/storage/clh/Causal-Video-VAE/gradio/cv_vae_temp/video.mp4'
if input_file.endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp')):
#处理图像
image = cv2.imread(input_file, cv2.IMREAD_COLOR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
fps=10
total_frames = 1
video_data = torch.from_numpy(image)
video_data = video_data.unsqueeze(0)
video_data = video_data.permute(3, 0, 1, 2)
video_data = (video_data / 255.0) * 2 - 1
video_data = _format_video_shape(video_data)
video_data = video_data.unsqueeze(0)
video_data = video_data.to(dtype=data_type) # b c t h w
elif input_file.endswith(('.mp4', '.avi', '.mov', '.wmv')):
# 处理视频
decord_vr = VideoReader(input_file, ctx=cpu(0))
total_frames = len(decord_vr)
video = cv2.VideoCapture(input_file)
fps = video.get(cv2.CAP_PROP_FPS)
frame_id_list = np.linspace(0, total_frames-1, total_frames, dtype=int)
video_data = decord_vr.get_batch(frame_id_list).asnumpy()
video_data = torch.from_numpy(video_data)
video_data = video_data.permute(3, 0, 1, 2)
video_data = (video_data / 255.0) * 2 - 1
video_data = _format_video_shape(video_data)
video_data = video_data.unsqueeze(0)
video_data = video_data.to(dtype=data_type) # b c t h w
video_data = video_data.to(device3)
latent = cvvae.encode(video_data).latent_dist.sample()
video_recon = cvvae.decode(latent).sample
custom_to_video(video_recon[0], fps=fps, output_file=cv_vae_path)
time.sleep(10)
return cv_vae_path
@torch.no_grad()
def rec_our12(input_file):
our_vae_path = '/storage/clh/Causal-Video-VAE/gradio/our_temp/video.mp4'
if input_file.endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp')):
#处理图像
image = cv2.imread(input_file, cv2.IMREAD_COLOR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
fps=10
total_frames = 1
video_data = torch.from_numpy(image)
video_data = video_data.unsqueeze(0)
video_data = video_data.permute(3, 0, 1, 2)
video_data = (video_data / 255.0) * 2 - 1
video_data = _format_video_shape(video_data)
video_data = video_data.unsqueeze(0)
video_data = video_data.to(dtype=data_type) # b c t h w
elif input_file.endswith(('.mp4', '.avi', '.mov', '.wmv')):
# 处理视频
decord_vr = VideoReader(input_file, ctx=cpu(0))
total_frames = len(decord_vr)
video = cv2.VideoCapture(input_file)
fps = video.get(cv2.CAP_PROP_FPS)
frame_id_list = np.linspace(0, total_frames-1, total_frames, dtype=int)
video_data = decord_vr.get_batch(frame_id_list).asnumpy()
video_data = torch.from_numpy(video_data)
video_data = video_data.permute(3, 0, 1, 2)
video_data = (video_data / 255.0) * 2 - 1
video_data = _format_video_shape(video_data)
video_data = video_data.unsqueeze(0)
video_data = video_data.to(dtype=data_type) # b c t h w
##我们的VAE的输出
input_data = video_data.clone()
input_data = input_data.to(device0)
latents = vqvae.encode(input_data).sample().to(data_type)
video_recon = vqvae.decode(latents)
custom_to_video(video_recon[0], fps=fps, output_file=our_vae_path)
return our_vae_path
@torch.no_grad()
def rec_new(input_file):
our_vae_path = '/storage/clh/Causal-Video-VAE/gradio/new_temp/video.mp4'
if input_file.endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp')):
#处理图像
image = cv2.imread(input_file, cv2.IMREAD_COLOR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
fps=10
total_frames = 1
video_data = torch.from_numpy(image)
video_data = video_data.unsqueeze(0)
video_data = video_data.permute(3, 0, 1, 2)
video_data = (video_data / 255.0) * 2 - 1
video_data = _format_video_shape(video_data)
video_data = video_data.unsqueeze(0)
video_data = video_data.to(dtype=data_type) # b c t h w
elif input_file.endswith(('.mp4', '.avi', '.mov', '.wmv')):
# 处理视频
decord_vr = VideoReader(input_file, ctx=cpu(0))
total_frames = len(decord_vr)
video = cv2.VideoCapture(input_file)
fps = video.get(cv2.CAP_PROP_FPS)
frame_id_list = np.linspace(0, total_frames-1, total_frames, dtype=int)
video_data = decord_vr.get_batch(frame_id_list).asnumpy()
video_data = torch.from_numpy(video_data)
video_data = video_data.permute(3, 0, 1, 2)
video_data = (video_data / 255.0) * 2 - 1
video_data = _format_video_shape(video_data)
video_data = video_data.unsqueeze(0)
video_data = video_data.to(dtype=data_type) # b c t h w
##我们的VAE的输出
input_data = video_data.clone()
input_data = input_data.to(device0)
latents = newvae.encode(input_data).sample().to(data_type)
video_recon = newvae.decode(latents)
custom_to_video(video_recon[0], fps=fps, output_file=our_vae_path)
return our_vae_path
@torch.no_grad()
def show_origin(input_file):
return input_file
@torch.no_grad()
def main(args: argparse.Namespace):
# 创建输出界面
with gr.Blocks() as demo:
with gr.Row():
input_interface = gr.components.File(label="上传文件(图片或视频)")
with gr.Row():
output_video1 = gr.Video(label="原始视频或图片")
output_video2 = gr.Video(label="我们的3D VAE输出视频或图片")
with gr.Row():
show_origin_button = gr.components.Button("展示原始视频或图片")
show_origin_button.click(fn=show_origin, inputs=input_interface, outputs=output_video1)
our12_button = gr.components.Button("用我们的3D VAE重建视频或图片")
our12_button.click(fn=rec_our12, inputs=input_interface, outputs=output_video2)
with gr.Row():
output_video3 = gr.Video(label="CV-VAE VAE输出视频或图片")
output_video4 = gr.Video(label="Open-Sora VAE输出视频或图片")
with gr.Row():
cvvae_button = gr.components.Button("用CV VAE重建视频或图片")
cvvae_button.click(fn=rec_cvvae, inputs=input_interface, outputs=output_video3)
nusvae_button = gr.components.Button("用Open-Sora VAE重建视频或图片")
nusvae_button.click(fn=rec_nusvae, inputs=input_interface, outputs=output_video4)
"""
with gr.Row():
output_video5 = gr.Video(label="我们最新内部版本VAE")
with gr.Row():
new_button = gr.components.Button("用新VAE重建视频或图片")
new_button.click(fn=rec_new, inputs=input_interface, outputs=output_video5)
"""
demo.launch(server_name="0.0.0.0", server_port=11904)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--ckpt", type=str, default="")
parser.add_argument("--sample_fps", type=int, default=30)
parser.add_argument("--tile_overlap_factor", type=float, default=0.125)
parser.add_argument('--enable_tiling', action='store_true')
parser.add_argument("--device", type=str, default="cuda")
parser.add_argument("--config", type=str, default="cuda")
args = parser.parse_args()
device = args.device
data_type = torch.bfloat16
device0 = torch.device('cuda:2')
ckpt = '/storage/clh/models/488dim8_layernorm_nearst'
vqvae = CausalVAEModel.from_pretrained(ckpt)
if args.enable_tiling:
vqvae.enable_tiling()
vqvae.tile_overlap_factor = args.tile_overlap_factor
vqvae = vqvae.to(data_type).to(device0)
vqvae.eval()
device3 = torch.device('cuda:3')
ckpt = '/storage/clh/CV-VAE/vae3d'
cvvae = CVVAEModel.from_pretrained(ckpt)
cvvae = cvvae.to(device3).to(data_type)
cvvae.eval()
device4 = torch.device('cuda:4')
cfg = parse_configs(args, training=False)
nus_vae = build_module(cfg.model, MODELS)
nus_vae = nus_vae.to(device4).to(data_type)
nus_vae.eval()
"""
device5 = torch.device('cuda:5')
ckpt = '/storage/clh/models/488dim8'
newvae = CausalVAEModel.from_pretrained(ckpt)
if args.enable_tiling:
newvae.enable_tiling()
newvae.tile_overlap_factor = args.tile_overlap_factor
newvae = vqvae.to(data_type).to(device0)
newvae.eval()
"""
main(args)
|