clh / scripts /vae_demo.py
LiuhanChen's picture
Add files using upload-large-folder tool
a71d323 verified
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)