Doubiiu/DynamiCrafter_interp_loop
165
1import spaces2import gradio as gr3import os4import sys5import time6from omegaconf import OmegaConf7import torch8from pytorch_lightning import seed_everything9from huggingface_hub import hf_hub_download10from einops import repeat11import torchvision.transforms as transforms12from utils.utils import instantiate_from_config13sys.path.insert(0, "scripts/evaluation")14from funcs import (15 batch_ddim_sampling,16 load_model_checkpoint,17 get_latent_z,18 save_videos19)20 21def download_model():22 REPO_ID = 'Doubiiu/DynamiCrafter_512_Interp'23 filename_list = ['model.ckpt']24 if not os.path.exists('./checkpoints/dynamicrafter_512_interp_v1/'):25 os.makedirs('./checkpoints/dynamicrafter_512_interp_v1/')26 for filename in filename_list:27 local_file = os.path.join('./checkpoints/dynamicrafter_512_interp_v1/', filename)28 if not os.path.exists(local_file):29 hf_hub_download(repo_id=REPO_ID, filename=filename, local_dir='./checkpoints/dynamicrafter_512_interp_v1/', force_download=True)30 31 32 33download_model()34ckpt_path='checkpoints/dynamicrafter_512_interp_v1/model.ckpt'35config_file='configs/inference_512_v1.0.yaml'36config = OmegaConf.load(config_file)37model_config = config.pop("model", OmegaConf.create())38model_config['params']['unet_config']['params']['use_checkpoint']=False 39model = instantiate_from_config(model_config)40assert os.path.exists(ckpt_path), "Error: checkpoint Not Found!"41model = load_model_checkpoint(model, ckpt_path)42model.eval()43model = model.cuda()44 45 46 47@spaces.GPU(duration=300)48def infer(image, prompt, steps=50, cfg_scale=7.5, eta=1.0, fs=3, seed=123, image2=None):49 resolution = (320, 512)50 save_fps = 851 seed_everything(seed)52 transform = transforms.Compose([53 transforms.Resize(min(resolution)),54 transforms.CenterCrop(resolution),55 ])56 torch.cuda.empty_cache()57 print('start:', prompt, time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))58 start = time.time()59 if steps > 60:60 steps = 60 61 62 batch_size=163 channels = model.model.diffusion_model.out_channels64 frames = model.temporal_length65 h, w = resolution[0] // 8, resolution[1] // 866 noise_shape = [batch_size, channels, frames, h, w]67 68 # text cond69 with torch.no_grad(), torch.cuda.amp.autocast():70 text_emb = model.get_learned_conditioning([prompt])71 72 # img cond73 img_tensor = torch.from_numpy(image).permute(2, 0, 1).float().to(model.device)74 img_tensor = (img_tensor / 255. - 0.5) * 275 76 image_tensor_resized = transform(img_tensor) #3,256,25677 videos = image_tensor_resized.unsqueeze(0) # bchw78 79 z = get_latent_z(model, videos.unsqueeze(2)) #bc,1,hw80 81 if image2 is not None:82 img_tensor2 = torch.from_numpy(image2).permute(2, 0, 1).float().to(model.device)83 img_tensor2 = (img_tensor2 / 255. - 0.5) * 284 85 image_tensor_resized2 = transform(img_tensor2) #3,h,w86 videos2 = image_tensor_resized2.unsqueeze(0) # bchw87 88 z2 = get_latent_z(model, videos2.unsqueeze(2)) #bc,1,hw89 90 91 92 img_tensor_repeat = repeat(z, 'b c t h w -> b c (repeat t) h w', repeat=frames)93 94 img_tensor_repeat = torch.zeros_like(img_tensor_repeat)95 96 ## old97 img_tensor_repeat[:,:,:1,:,:] = z98 if image2 is not None:99 img_tensor_repeat[:,:,-1:,:,:] = z2100 else:101 img_tensor_repeat[:,:,-1:,:,:] = z102 103 cond_images = model.embedder(img_tensor.unsqueeze(0)) ## blc104 img_emb = model.image_proj_model(cond_images)105 106 imtext_cond = torch.cat([text_emb, img_emb], dim=1)107 108 fs = torch.tensor([fs], dtype=torch.long, device=model.device)109 cond = {"c_crossattn": [imtext_cond], "fs": fs, "c_concat": [img_tensor_repeat]}110 111 ## inference112 batch_samples = batch_ddim_sampling(model, cond, noise_shape, n_samples=1, ddim_steps=steps, ddim_eta=eta, cfg_scale=cfg_scale)113 ## b,samples,c,t,h,w114 ## remove the last frame for looping video115 if image2 is None:116 batch_samples = batch_samples[:,:,:,:-1,...]117 video_path = './output.mp4'118 save_videos(batch_samples, './', filenames=['output'], fps=save_fps)119 return video_path120 121 122i2v_examples_interp_512 = [123 ['prompts/512_interp/smile_01.png', 'a smiling girl', 50, 7.5, 1.0, 5, 12306, 'prompts/512_interp/smile_02.png'],124 ['prompts/512_interp/stone01_01.png', 'rotating view', 50, 7.5, 1.0, 5, 123, 'prompts/512_interp/stone01_02.png'],125 ['prompts/512_interp/walk_01.png', 'man walking', 50, 7.5, 1.0, 5, 345, 'prompts/512_interp/walk_02.png'],126]127i2v_examples_loop_512 = [128 ['prompts/512_loop/24.png', 'a beach with waves and clouds at sunset', 50, 7.5, 1.0, 5, 234],129 ['prompts/512_loop/36.png', 'clothes swaying in the wind', 50, 7.5, 1.0, 5, 123],130 ['prompts/512_loop/40.png', 'flowers swaying in the wind', 50, 7.5, 1.0, 5, 234],131]132 133 134 135 136css = """#input_img {max-width: 512px !important} #input_img2 {max-width: 512px !important} #output_vid {max-width: 512px; max-height: 320px} """137 138with gr.Blocks(analytics_enabled=False, css=css) as dynamicrafter_iface:139 gr.Markdown("<div align='center'> <h1> DynamiCrafter: Animating Open-domain Images with Video Diffusion Priors </span> </h1> \140 <h2 style='font-weight: 450; font-size: 1rem; margin: 0rem'>\141 <a href='https://doubiiu.github.io/'>Jinbo Xing</a>, \142 <a href='https://menghanxia.github.io/'>Menghan Xia</a>, <a href='https://yzhang2016.github.io/'>Yong Zhang</a>, \143 <a href=''>Haoxin Chen</a>, <a href=''> Wangbo Yu</a>,\144 <a href='https://github.com/hyliu'>Hanyuan Liu</a>, <a href='https://xinntao.github.io/'>Xintao Wang</a>,\145 <a href='https://www.cse.cuhk.edu.hk/~ttwong/myself.html'>Tien-Tsin Wong</a>,\146 <a href='https://scholar.google.com/citations?user=4oXBp9UAAAAJ&hl=zh-CN'>Ying Shan</a>\147 </h2> \148 <a style='font-size:18px;color: #000000'>If DynamiCrafter is useful, please help star the </a>\149 <a style='font-size:18px;color: #000000' href='https://github.com/Doubiiu/DynamiCrafter'>[Github Repo]</a>\150 <a style='font-size:18px;color: #000000'>, which is important to Open-Source projects. Thanks!</a>\151 <a style='font-size:18px;color: #000000' href='https://arxiv.org/abs/2310.12190'> [ArXiv] </a>\152 <a style='font-size:18px;color: #000000' href='https://doubiiu.github.io/projects/DynamiCrafter/'> [Project Page] </a> </div>")153 154 #######generative frame interpolation and looping video generation######155 with gr.Tab(label='Generative Frame Interpolation_320x512'):156 with gr.Column():157 with gr.Row():158 with gr.Column():159 with gr.Row():160 i2v_input_image = gr.Image(label="Input Image1",elem_id="input_img")161 with gr.Row():162 i2v_input_text = gr.Text(label='Prompts')163 with gr.Row():164 i2v_seed = gr.Slider(label='Random Seed', minimum=0, maximum=50000, step=1, value=123)165 i2v_eta = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, label='ETA', value=1.0, elem_id="i2v_eta")166 i2v_cfg_scale = gr.Slider(minimum=1.0, maximum=15.0, step=0.5, label='CFG Scale', value=7.5, elem_id="i2v_cfg_scale")167 with gr.Row():168 i2v_steps = gr.Slider(minimum=1, maximum=50, step=1, elem_id="i2v_steps", label="Sampling steps", value=50)169 i2v_motion = gr.Slider(minimum=5, maximum=30, step=1, elem_id="i2v_motion", label="FPS", value=10)170 i2v_end_btn = gr.Button("Generate")171 with gr.Column():172 with gr.Row():173 i2v_input_image2 = gr.Image(label="Input Image2",elem_id="input_img2")174 with gr.Row():175 i2v_output_video = gr.Video(label="Generated Video",elem_id="output_vid",autoplay=True,show_share_button=True)176 177 gr.Examples(examples=i2v_examples_interp_512,178 inputs=[i2v_input_image, i2v_input_text, i2v_steps, i2v_cfg_scale, i2v_eta, i2v_motion, i2v_seed, i2v_input_image2],179 outputs=[i2v_output_video],180 fn = infer,181 cache_examples=True,182 )183 i2v_end_btn.click(inputs=[i2v_input_image, i2v_input_text, i2v_steps, i2v_cfg_scale, i2v_eta, i2v_motion, i2v_seed, i2v_input_image2],184 outputs=[i2v_output_video],185 fn = infer186 )187 #######generative frame interpolation and looping video generation######188 with gr.Tab(label='Looping Video Generation_320x512'):189 with gr.Column():190 with gr.Row():191 with gr.Column():192 with gr.Row():193 i2v_input_image = gr.Image(label="Input Image",elem_id="input_img")194 with gr.Row():195 i2v_input_text = gr.Text(label='Prompts')196 with gr.Row():197 i2v_seed = gr.Slider(label='Random Seed', minimum=0, maximum=50000, step=1, value=123)198 i2v_eta = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, label='ETA', value=1.0, elem_id="i2v_eta")199 i2v_cfg_scale = gr.Slider(minimum=1.0, maximum=15.0, step=0.5, label='CFG Scale', value=7.5, elem_id="i2v_cfg_scale")200 with gr.Row():201 i2v_steps = gr.Slider(minimum=1, maximum=50, step=1, elem_id="i2v_steps", label="Sampling steps", value=50)202 i2v_motion = gr.Slider(minimum=5, maximum=30, step=1, elem_id="i2v_motion", label="FPS", value=5)203 i2v_end_btn = gr.Button("Generate")204 # with gr.Tab(label='Result'):205 with gr.Row():206 i2v_output_video = gr.Video(label="Generated Video",elem_id="output_vid",autoplay=True,show_share_button=True)207 208 gr.Examples(examples=i2v_examples_loop_512,209 inputs=[i2v_input_image, i2v_input_text, i2v_steps, i2v_cfg_scale, i2v_eta, i2v_motion, i2v_seed],210 outputs=[i2v_output_video],211 fn = infer,212 cache_examples=True,213 )214 i2v_end_btn.click(inputs=[i2v_input_image, i2v_input_text, i2v_steps, i2v_cfg_scale, i2v_eta, i2v_motion, i2v_seed],215 outputs=[i2v_output_video],216 fn = infer217 )218 219dynamicrafter_iface.queue(max_size=12).launch(show_api=True)