|
import os, argparse |
|
import sys |
|
import gradio as gr |
|
|
|
sys.path.insert(1, os.path.join(sys.path[0], 'lvdm')) |
|
import spaces |
|
from lvdm.models.samplers.ddim import DDIMSampler |
|
|
|
import os |
|
import time |
|
from omegaconf import OmegaConf |
|
import torch |
|
from scripts.evaluation.funcs import load_model_checkpoint, save_videos, batch_ddim_sampling, get_latent_z |
|
from utils.utils import instantiate_from_config |
|
from huggingface_hub import hf_hub_download |
|
from einops import repeat |
|
import torchvision.transforms as transforms |
|
from pytorch_lightning import seed_everything |
|
from einops import rearrange |
|
from cldm.model import load_state_dict |
|
import cv2 |
|
|
|
import torch |
|
print("cuda available:", torch.cuda.is_available()) |
|
|
|
|
|
from huggingface_hub import snapshot_download |
|
import os |
|
|
|
|
|
|
|
def download_model(): |
|
REPO_ID = 'fbnnb/TC_sketch' |
|
filename_list = ['tc_sketch.pt'] |
|
tar_dir = './checkpoints/tooncrafter_1024_interp_sketch/' |
|
if not os.path.exists(tar_dir): |
|
os.makedirs(tar_dir) |
|
for filename in filename_list: |
|
local_file = os.path.join(tar_dir, filename) |
|
if not os.path.exists(local_file): |
|
hf_hub_download(repo_id=REPO_ID, filename=filename, local_dir=tar_dir, local_dir_use_symlinks=False) |
|
print("downloaded") |
|
|
|
|
|
def get_latent_z_with_hidden_states(model, videos): |
|
b, c, t, h, w = videos.shape |
|
x = rearrange(videos, 'b c t h w -> (b t) c h w') |
|
encoder_posterior, hidden_states = model.first_stage_model.encode(x, return_hidden_states=True) |
|
|
|
hidden_states_first_last = [] |
|
|
|
for hid in hidden_states: |
|
hid = rearrange(hid, '(b t) c h w -> b c t h w', t=t) |
|
hid_new = torch.cat([hid[:, :, 0:1], hid[:, :, -1:]], dim=2) |
|
hidden_states_first_last.append(hid_new) |
|
|
|
z = model.get_first_stage_encoding(encoder_posterior).detach() |
|
z = rearrange(z, '(b t) c h w -> b c t h w', b=b, t=t) |
|
return z, hidden_states_first_last |
|
|
|
|
|
|
|
def extract_frames(video_path): |
|
|
|
cap = cv2.VideoCapture(video_path) |
|
|
|
frame_list = [] |
|
frame_num = 0 |
|
|
|
while True: |
|
|
|
ret, frame = cap.read() |
|
if not ret: |
|
break |
|
|
|
|
|
frame_list.append(frame) |
|
frame_num += 1 |
|
|
|
print("load video length:", len(frame_list)) |
|
|
|
cap.release() |
|
|
|
return frame_list |
|
|
|
|
|
resolution = '576_1024' |
|
resolution = (576, 1024) |
|
download_model() |
|
print("after download model") |
|
result_dir = "./results/" |
|
if not os.path.exists(result_dir): |
|
os.mkdir(result_dir) |
|
|
|
|
|
ckpt_path='checkpoints/tooncrafter_1024_interp_sketch/tc_sketch.pt' |
|
config_file='configs/inference_1024_v1.0.yaml' |
|
config = OmegaConf.load(config_file) |
|
model_config = config.pop("model", OmegaConf.create()) |
|
model_config['params']['unet_config']['params']['use_checkpoint']=False |
|
|
|
model = instantiate_from_config(model_config).cuda() |
|
assert os.path.exists(ckpt_path), "Error: checkpoint Not Found!" |
|
model = load_model_checkpoint(model, ckpt_path) |
|
model.eval() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
save_fps = 8 |
|
print("resolution:", resolution) |
|
print("init done.") |
|
|
|
|
|
|
|
def transpose_if_needed(tensor): |
|
h = tensor.shape[-2] |
|
w = tensor.shape[-1] |
|
if h > w: |
|
tensor = tensor.permute(0, 2, 1) |
|
return tensor |
|
|
|
def untranspose(tensor): |
|
ndim = tensor.ndim |
|
return tensor.transpose(ndim-1, ndim-2) |
|
|
|
|
|
@spaces.GPU(duration=200) |
|
def get_image(image1, prompt, image2, dim_steps=50, ddim_eta=1., fs=None, seed=123, \ |
|
unconditional_guidance_scale=1.0, cfg_img=None, text_input=False, multiple_cond_cfg=False, \ |
|
loop=False, interp=False, timestep_spacing='uniform', guidance_rescale=0.0, noise_shape=[72, 108], n_samples=1, **kwargs): |
|
|
|
with torch.no_grad(): |
|
seed_everything(seed) |
|
video_size = (576, 1024) |
|
transform = transforms.Compose([ |
|
transforms.Resize(min(video_size)), |
|
transforms.CenterCrop(video_size), |
|
|
|
|
|
]) |
|
|
|
image1 = torch.from_numpy(image1).permute(2, 0, 1).float().cuda() |
|
input_h, input_w = image1.shape[1:] |
|
image1 = (image1 / 255. - 0.5) * 2 |
|
|
|
image2 = torch.from_numpy(image2).permute(2, 0, 1).float().cuda() |
|
input_h, input_w = image2.shape[1:] |
|
image2 = (image2 / 255. - 0.5) * 2 |
|
|
|
|
|
|
|
image_tensor1 = transform(image1).unsqueeze(1) |
|
|
|
image_tensor2 = transform(image2).unsqueeze(1) |
|
frame_tensor1 = repeat(image_tensor1, 'c t h w -> c (repeat t) h w', repeat=8) |
|
frame_tensor2 = repeat(image_tensor2, 'c t h w -> c (repeat t) h w', repeat=8) |
|
videos = torch.cat([frame_tensor1, frame_tensor2], dim=1).unsqueeze(0) |
|
|
|
|
|
|
|
global model |
|
model.cuda() |
|
|
|
ddim_sampler = DDIMSampler(model) if not multiple_cond_cfg else DDIMSampler_multicond(model) |
|
batch_size = 1 |
|
fs = torch.tensor([fs], dtype=torch.long, device=model.device) |
|
|
|
if not text_input: |
|
prompts = [""]*batch_size |
|
|
|
img = videos[:,:,0] |
|
img_emb = model.embedder(img) |
|
img_emb = model.image_proj_model(img_emb) |
|
|
|
cond_emb = model.get_learned_conditioning(prompts) |
|
cond = {"c_crossattn": [torch.cat([cond_emb,img_emb], dim=1)]} |
|
if model.model.conditioning_key == 'hybrid': |
|
z, hs = get_latent_z_with_hidden_states(model, videos) |
|
if loop or interp: |
|
img_cat_cond = torch.zeros_like(z) |
|
img_cat_cond[:,:,0,:,:] = z[:,:,0,:,:] |
|
img_cat_cond[:,:,-1,:,:] = z[:,:,-1,:,:] |
|
else: |
|
img_cat_cond = z[:,:,:1,:,:] |
|
img_cat_cond = repeat(img_cat_cond, 'b c t h w -> b c (repeat t) h w', repeat=z.shape[2]) |
|
cond["c_concat"] = [img_cat_cond] |
|
|
|
if unconditional_guidance_scale != 1.0: |
|
if model.uncond_type == "empty_seq": |
|
prompts = batch_size * [""] |
|
uc_emb = model.get_learned_conditioning(prompts) |
|
elif model.uncond_type == "zero_embed": |
|
uc_emb = torch.zeros_like(cond_emb) |
|
uc_img_emb = model.embedder(torch.zeros_like(img)) |
|
uc_img_emb = model.image_proj_model(uc_img_emb) |
|
uc = {"c_crossattn": [torch.cat([uc_emb,uc_img_emb],dim=1)]} |
|
if model.model.conditioning_key == 'hybrid': |
|
uc["c_concat"] = [img_cat_cond] |
|
else: |
|
uc = None |
|
|
|
|
|
|
|
|
|
additional_decode_kwargs = {'ref_context': hs} |
|
|
|
|
|
|
|
if multiple_cond_cfg and cfg_img != 1.0: |
|
uc_2 = {"c_crossattn": [torch.cat([uc_emb,img_emb],dim=1)]} |
|
if model.model.conditioning_key == 'hybrid': |
|
uc_2["c_concat"] = [img_cat_cond] |
|
kwargs.update({"unconditional_conditioning_img_nonetext": uc_2}) |
|
else: |
|
kwargs.update({"unconditional_conditioning_img_nonetext": None}) |
|
|
|
z0 = None |
|
cond_mask = None |
|
|
|
batch_variants = [] |
|
for _ in range(n_samples): |
|
|
|
if z0 is not None: |
|
cond_z0 = z0.clone() |
|
kwargs.update({"clean_cond": True}) |
|
else: |
|
cond_z0 = None |
|
if ddim_sampler is not None: |
|
|
|
samples, _ = ddim_sampler.sample(S=ddim_steps, |
|
conditioning=cond, |
|
batch_size=batch_size, |
|
shape=noise_shape, |
|
verbose=False, |
|
unconditional_guidance_scale=unconditional_guidance_scale, |
|
unconditional_conditioning=uc, |
|
eta=ddim_eta, |
|
cfg_img=cfg_img, |
|
mask=cond_mask, |
|
x0=cond_z0, |
|
fs=fs, |
|
timestep_spacing=timestep_spacing, |
|
guidance_rescale=guidance_rescale, |
|
**kwargs |
|
) |
|
|
|
|
|
batch_images = model.decode_first_stage(samples, **additional_decode_kwargs) |
|
|
|
index = list(range(samples.shape[2])) |
|
del index[1] |
|
del index[-2] |
|
samples = samples[:,:,index,:,:] |
|
|
|
batch_images_middle = model.decode_first_stage(samples, **additional_decode_kwargs) |
|
batch_images[:,:,batch_images.shape[2]//2-1:batch_images.shape[2]//2+1] = batch_images_middle[:,:,batch_images.shape[2]//2-2:batch_images.shape[2]//2] |
|
|
|
|
|
|
|
batch_variants.append(batch_images) |
|
|
|
batch_variants = torch.stack(batch_variants) |
|
|
|
|
|
prompt_str = prompt.replace("/", "_slash_") if "/" in prompt else prompt |
|
prompt_str = prompt_str.replace(" ", "_") if " " in prompt else prompt_str |
|
prompt_str=prompt_str[:40] |
|
if len(prompt_str) == 0: |
|
prompt_str = 'empty_prompt' |
|
|
|
result_dir = "./tmp/" |
|
save_videos(batch_image, result_dir, filenames=[prompt_str], fps=8) |
|
print(f"Saved in {prompt_str}. Time used: {(time.time() - start):.2f} seconds") |
|
model = model.cpu() |
|
saved_result_dir = os.path.join(result_dir, f"{prompt_str}.mp4") |
|
print("result saved to:", saved_result_dir) |
|
return saved_result_dir |
|
|
|
|
|
|
|
|
|
|
|
|
|
def dynamicrafter_demo(result_dir='./tmp/', res=1024): |
|
if res == 1024: |
|
resolution = '576_1024' |
|
css = """#input_img {max-width: 1024px !important} #output_vid {max-width: 1024px; max-height:576px}""" |
|
elif res == 512: |
|
resolution = '320_512' |
|
css = """#input_img {max-width: 512px !important} #output_vid {max-width: 512px; max-height: 320px} #input_img2 {max-width: 512px !important} #output_vid {max-width: 512px; max-height: 320px}""" |
|
elif res == 256: |
|
resolution = '256_256' |
|
css = """#input_img {max-width: 256px !important} #output_vid {max-width: 256px; max-height: 256px}""" |
|
else: |
|
raise NotImplementedError(f"Unsupported resolution: {res}") |
|
|
|
with gr.Blocks(analytics_enabled=False, css=css) as dynamicrafter_iface: |
|
|
|
|
|
|
|
with gr.Tab(label='ToonCrafter_576x1024'): |
|
with gr.Column(): |
|
with gr.Row(): |
|
with gr.Column(): |
|
with gr.Row(): |
|
i2v_input_image = gr.Image(label="Input Image1",elem_id="input_img") |
|
|
|
with gr.Row(): |
|
i2v_input_text = gr.Text(label='Prompts') |
|
with gr.Row(): |
|
i2v_seed = gr.Slider(label='Random Seed', minimum=0, maximum=50000, step=1, value=123) |
|
i2v_eta = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, label='ETA', value=1.0, elem_id="i2v_eta") |
|
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") |
|
with gr.Row(): |
|
i2v_steps = gr.Slider(minimum=1, maximum=60, step=1, elem_id="i2v_steps", label="Sampling steps", value=50) |
|
i2v_motion = gr.Slider(minimum=5, maximum=30, step=1, elem_id="i2v_motion", label="FPS", value=10) |
|
control_scale = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, elem_id="i2v_ctrl_scale", label="control_scale", value=0.6) |
|
i2v_end_btn = gr.Button("Generate") |
|
with gr.Column(): |
|
with gr.Row(): |
|
i2v_input_image2 = gr.Image(label="Input Image 2",elem_id="input_img2") |
|
with gr.Row(): |
|
i2v_output_video = gr.Video(label="Generated Video",elem_id="output_vid",autoplay=True,show_share_button=True) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
img_size = [72, 108] |
|
|
|
i2v_end_btn.click(inputs=[i2v_input_image, i2v_input_text, i2v_input_image2, i2v_steps, i2v_eta, i2v_motion, i2v_seed], |
|
outputs=[i2v_output_video], |
|
fn = get_image |
|
) |
|
|
|
|
|
return dynamicrafter_iface |
|
|
|
|
|
def get_parser(): |
|
parser = argparse.ArgumentParser() |
|
return parser |
|
|
|
|
|
if __name__ == "__main__": |
|
parser = get_parser() |
|
args = parser.parse_args() |
|
|
|
result_dir = os.path.join('./', 'results') |
|
dynamicrafter_iface = dynamicrafter_demo(result_dir) |
|
dynamicrafter_iface.queue(max_size=12) |
|
print("launching...") |
|
dynamicrafter_iface.launch(max_threads=1, share=True) |
|
|
|
|
|
|
|
|