Spaces:
Runtime error
Runtime error
Update scripts/gradio/i2v_test_application.py
Browse files- scripts/gradio/i2v_test_application.py +228 -228
scripts/gradio/i2v_test_application.py
CHANGED
@@ -1,229 +1,229 @@
|
|
1 |
-
import os
|
2 |
-
import time
|
3 |
-
from omegaconf import OmegaConf
|
4 |
-
import torch
|
5 |
-
from scripts.evaluation.funcs import load_model_checkpoint, save_videos, batch_ddim_sampling, get_latent_z
|
6 |
-
from utils.utils import instantiate_from_config
|
7 |
-
from huggingface_hub import hf_hub_download
|
8 |
-
from einops import repeat
|
9 |
-
import torchvision.transforms as transforms
|
10 |
-
from pytorch_lightning import seed_everything
|
11 |
-
from einops import rearrange
|
12 |
-
from cldm.model import load_state_dict
|
13 |
-
import cv2
|
14 |
-
|
15 |
-
|
16 |
-
def extract_frames(video_path):
|
17 |
-
# 動画ファイルを読み込む
|
18 |
-
cap = cv2.VideoCapture(video_path)
|
19 |
-
|
20 |
-
frame_list = []
|
21 |
-
frame_num = 0
|
22 |
-
|
23 |
-
while True:
|
24 |
-
# フレームを読み込む
|
25 |
-
ret, frame = cap.read()
|
26 |
-
if not ret:
|
27 |
-
break
|
28 |
-
|
29 |
-
# フレームをリストに追加
|
30 |
-
frame_list.append(frame)
|
31 |
-
frame_num += 1
|
32 |
-
|
33 |
-
# 動画ファイルを閉じる
|
34 |
-
cap.release()
|
35 |
-
|
36 |
-
return frame_list
|
37 |
-
|
38 |
-
class Image2Video():
|
39 |
-
def __init__(self,result_dir='./tmp/',gpu_num=1,resolution='256_256') -> None:
|
40 |
-
self.resolution = (int(resolution.split('_')[0]), int(resolution.split('_')[1])) #hw
|
41 |
-
self.download_model()
|
42 |
-
|
43 |
-
self.result_dir = result_dir
|
44 |
-
if not os.path.exists(self.result_dir):
|
45 |
-
os.mkdir(self.result_dir)
|
46 |
-
|
47 |
-
#ToonCrafterModel
|
48 |
-
ckpt_path='checkpoints/tooncrafter_'+resolution.split('_')[1]+'_interp_v1/model.ckpt'
|
49 |
-
config_file='configs/inference_'+resolution.split('_')[1]+'_v1.0.yaml'
|
50 |
-
config = OmegaConf.load(config_file)
|
51 |
-
model_config = config.pop("model", OmegaConf.create())
|
52 |
-
model_config['params']['unet_config']['params']['use_checkpoint']=False
|
53 |
-
|
54 |
-
#ControlModel
|
55 |
-
cn_ckpt_path = "control_models/sketch_encoder.ckpt"
|
56 |
-
cn_config_file = 'configs/cldm_v21.yaml'
|
57 |
-
cn_config = OmegaConf.load(cn_config_file)
|
58 |
-
cn_model_config = cn_config.pop("control_stage_config", OmegaConf.create())
|
59 |
-
|
60 |
-
|
61 |
-
model_list = []
|
62 |
-
for gpu_id in range(gpu_num):
|
63 |
-
model = instantiate_from_config(model_config)
|
64 |
-
cn_model = instantiate_from_config(cn_model_config)
|
65 |
-
|
66 |
-
# model = model.cuda(gpu_id)
|
67 |
-
assert os.path.exists(ckpt_path), "Error: checkpoint Not Found!"
|
68 |
-
model = load_model_checkpoint(model, ckpt_path)
|
69 |
-
model.eval()
|
70 |
-
|
71 |
-
cn_model.load_state_dict(load_state_dict(cn_ckpt_path, location='
|
72 |
-
cn_model.eval()
|
73 |
-
|
74 |
-
model.control_model = cn_model
|
75 |
-
|
76 |
-
model_list.append(model)
|
77 |
-
self.model_list = model_list
|
78 |
-
self.save_fps = 8
|
79 |
-
|
80 |
-
def get_image(self, image, prompt, steps=50, cfg_scale=7.5, eta=1.0, fs=3, seed=123, image2=None, frame_guides=None,control_scale=0.6):
|
81 |
-
control_frames = extract_frames(frame_guides)
|
82 |
-
seed_everything(seed)
|
83 |
-
transform = transforms.Compose([
|
84 |
-
transforms.Resize(min(self.resolution)),
|
85 |
-
transforms.CenterCrop(self.resolution),
|
86 |
-
])
|
87 |
-
torch.cuda.empty_cache()
|
88 |
-
print('start:', prompt, time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
|
89 |
-
start = time.time()
|
90 |
-
gpu_id=0
|
91 |
-
if steps > 60:
|
92 |
-
steps = 60
|
93 |
-
model = self.model_list[gpu_id]
|
94 |
-
model = model.cuda()
|
95 |
-
batch_size=1
|
96 |
-
channels = model.model.diffusion_model.out_channels
|
97 |
-
frames = model.temporal_length
|
98 |
-
h, w = self.resolution[0] // 8, self.resolution[1] // 8
|
99 |
-
noise_shape = [batch_size, channels, frames, h, w]
|
100 |
-
|
101 |
-
# text cond
|
102 |
-
with torch.no_grad(), torch.cuda.amp.autocast():
|
103 |
-
text_emb = model.get_learned_conditioning([prompt])
|
104 |
-
|
105 |
-
#control cond
|
106 |
-
if frame_guides is not None:
|
107 |
-
cn_videos = []
|
108 |
-
for frame in control_frames:
|
109 |
-
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
110 |
-
frame = cv2.bitwise_not(frame)
|
111 |
-
cn_tensor = torch.from_numpy(frame).unsqueeze(2).permute(2, 0, 1).float().to(model.device)
|
112 |
-
|
113 |
-
#cn_tensor = (cn_tensor / 255. - 0.5) * 2
|
114 |
-
cn_tensor = ( cn_tensor/255.0 )
|
115 |
-
cn_tensor_resized = transform(cn_tensor) #3,h,w
|
116 |
-
|
117 |
-
cn_video = cn_tensor_resized.unsqueeze(0).unsqueeze(2) # bc1hw
|
118 |
-
cn_videos.append(cn_video)
|
119 |
-
|
120 |
-
cn_videos = torch.cat(cn_videos, dim=2)
|
121 |
-
model_list = []
|
122 |
-
for model in self.model_list:
|
123 |
-
model.control_scale = control_scale
|
124 |
-
model_list.append(model)
|
125 |
-
self.model_list = model_list
|
126 |
-
|
127 |
-
else:
|
128 |
-
cn_videos = None
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
# img cond
|
133 |
-
img_tensor = torch.from_numpy(image).permute(2, 0, 1).float().to(model.device)
|
134 |
-
img_tensor = (img_tensor / 255. - 0.5) * 2
|
135 |
-
|
136 |
-
image_tensor_resized = transform(img_tensor) #3,h,w
|
137 |
-
videos = image_tensor_resized.unsqueeze(0).unsqueeze(2) # bc1hw
|
138 |
-
|
139 |
-
# z = get_latent_z(model, videos) #bc,1,hw
|
140 |
-
videos = repeat(videos, 'b c t h w -> b c (repeat t) h w', repeat=frames//2)
|
141 |
-
|
142 |
-
img_tensor2 = torch.from_numpy(image2).permute(2, 0, 1).float().to(model.device)
|
143 |
-
img_tensor2 = (img_tensor2 / 255. - 0.5) * 2
|
144 |
-
image_tensor_resized2 = transform(img_tensor2) #3,h,w
|
145 |
-
videos2 = image_tensor_resized2.unsqueeze(0).unsqueeze(2) # bchw
|
146 |
-
videos2 = repeat(videos2, 'b c t h w -> b c (repeat t) h w', repeat=frames//2)
|
147 |
-
|
148 |
-
|
149 |
-
videos = torch.cat([videos, videos2], dim=2)
|
150 |
-
z, hs = self.get_latent_z_with_hidden_states(model, videos)
|
151 |
-
|
152 |
-
img_tensor_repeat = torch.zeros_like(z)
|
153 |
-
|
154 |
-
img_tensor_repeat[:,:,:1,:,:] = z[:,:,:1,:,:]
|
155 |
-
img_tensor_repeat[:,:,-1:,:,:] = z[:,:,-1:,:,:]
|
156 |
-
|
157 |
-
|
158 |
-
cond_images = model.embedder(img_tensor.unsqueeze(0)) ## blc
|
159 |
-
img_emb = model.image_proj_model(cond_images)
|
160 |
-
|
161 |
-
imtext_cond = torch.cat([text_emb, img_emb], dim=1)
|
162 |
-
|
163 |
-
fs = torch.tensor([fs], dtype=torch.long, device=model.device)
|
164 |
-
cond = {"c_crossattn": [imtext_cond], "fs": fs, "c_concat": [img_tensor_repeat], "control_cond": cn_videos}
|
165 |
-
|
166 |
-
## inference
|
167 |
-
batch_samples = batch_ddim_sampling(model, cond, noise_shape, n_samples=1, ddim_steps=steps, ddim_eta=eta, cfg_scale=cfg_scale, hs=hs)
|
168 |
-
|
169 |
-
## remove the last frame
|
170 |
-
if image2 is None:
|
171 |
-
batch_samples = batch_samples[:,:,:,:-1,...]
|
172 |
-
## b,samples,c,t,h,w
|
173 |
-
prompt_str = prompt.replace("/", "_slash_") if "/" in prompt else prompt
|
174 |
-
prompt_str = prompt_str.replace(" ", "_") if " " in prompt else prompt_str
|
175 |
-
prompt_str=prompt_str[:40]
|
176 |
-
if len(prompt_str) == 0:
|
177 |
-
prompt_str = 'empty_prompt'
|
178 |
-
|
179 |
-
save_videos(batch_samples, self.result_dir, filenames=[prompt_str], fps=self.save_fps)
|
180 |
-
print(f"Saved in {prompt_str}. Time used: {(time.time() - start):.2f} seconds")
|
181 |
-
model = model.cpu()
|
182 |
-
result_dir = os.path.join("/group/40034/gzhiwang/ToonCrafter_with_SketchGuidance", f"{prompt_str}.mp4")
|
183 |
-
print("result saved to:", result_dir)
|
184 |
-
return result_dir
|
185 |
-
|
186 |
-
# import torchvision
|
187 |
-
# batch_tensors = batch_samples
|
188 |
-
# n_samples = batch_tensors.shape[1]
|
189 |
-
# for idx, vid_tensor in enumerate(batch_tensors):
|
190 |
-
# video = vid_tensor.detach().cpu()
|
191 |
-
# video = torch.clamp(video.float(), -1., 1.)
|
192 |
-
# video = video.permute(2, 0, 1, 3, 4) # t,n,c,h,w
|
193 |
-
# frame_grids = [torchvision.utils.make_grid(framesheet, nrow=int(n_samples)) for framesheet in video] #[3, 1*h, n*w]
|
194 |
-
# grid = torch.stack(frame_grids, dim=0) # stack in temporal dim [t, 3, n*h, w]
|
195 |
-
# grid = (grid + 1.0) / 2.0
|
196 |
-
# grid = (grid * 255).to(torch.uint8).permute(0, 2, 3, 1)
|
197 |
-
# # savepath = os.path.join(savedir, f"{filenames[idx]}.mp4")
|
198 |
-
# # torchvision.io.write_video(savepath, grid, fps=fps, video_codec='h264', options={'crf': '10'})
|
199 |
-
# return grid
|
200 |
-
|
201 |
-
def download_model(self):
|
202 |
-
REPO_ID = 'Doubiiu/ToonCrafter'
|
203 |
-
filename_list = ['model.ckpt']
|
204 |
-
if not os.path.exists('./checkpoints/tooncrafter_'+str(self.resolution[1])+'_interp_v1/'):
|
205 |
-
os.makedirs('./checkpoints/tooncrafter_'+str(self.resolution[1])+'_interp_v1/')
|
206 |
-
for filename in filename_list:
|
207 |
-
local_file = os.path.join('./checkpoints/tooncrafter_'+str(self.resolution[1])+'_interp_v1/', filename)
|
208 |
-
if not os.path.exists(local_file):
|
209 |
-
hf_hub_download(repo_id=REPO_ID, filename=filename, local_dir='./checkpoints/tooncrafter_'+str(self.resolution[1])+'_interp_v1/', local_dir_use_symlinks=False)
|
210 |
-
|
211 |
-
def get_latent_z_with_hidden_states(self, model, videos):
|
212 |
-
b, c, t, h, w = videos.shape
|
213 |
-
x = rearrange(videos, 'b c t h w -> (b t) c h w')
|
214 |
-
encoder_posterior, hidden_states = model.first_stage_model.encode(x, return_hidden_states=True)
|
215 |
-
|
216 |
-
hidden_states_first_last = []
|
217 |
-
### use only the first and last hidden states
|
218 |
-
for hid in hidden_states:
|
219 |
-
hid = rearrange(hid, '(b t) c h w -> b c t h w', t=t)
|
220 |
-
hid_new = torch.cat([hid[:, :, 0:1], hid[:, :, -1:]], dim=2)
|
221 |
-
hidden_states_first_last.append(hid_new)
|
222 |
-
|
223 |
-
z = model.get_first_stage_encoding(encoder_posterior).detach()
|
224 |
-
z = rearrange(z, '(b t) c h w -> b c t h w', b=b, t=t)
|
225 |
-
return z, hidden_states_first_last
|
226 |
-
if __name__ == '__main__':
|
227 |
-
i2v = Image2Video()
|
228 |
-
video_path = i2v.get_image('prompts/art.png','man fishing in a boat at sunset')
|
229 |
print('done', video_path)
|
|
|
1 |
+
import os
|
2 |
+
import time
|
3 |
+
from omegaconf import OmegaConf
|
4 |
+
import torch
|
5 |
+
from scripts.evaluation.funcs import load_model_checkpoint, save_videos, batch_ddim_sampling, get_latent_z
|
6 |
+
from utils.utils import instantiate_from_config
|
7 |
+
from huggingface_hub import hf_hub_download
|
8 |
+
from einops import repeat
|
9 |
+
import torchvision.transforms as transforms
|
10 |
+
from pytorch_lightning import seed_everything
|
11 |
+
from einops import rearrange
|
12 |
+
from cldm.model import load_state_dict
|
13 |
+
import cv2
|
14 |
+
|
15 |
+
|
16 |
+
def extract_frames(video_path):
|
17 |
+
# 動画ファイルを読み込む
|
18 |
+
cap = cv2.VideoCapture(video_path)
|
19 |
+
|
20 |
+
frame_list = []
|
21 |
+
frame_num = 0
|
22 |
+
|
23 |
+
while True:
|
24 |
+
# フレームを読み込む
|
25 |
+
ret, frame = cap.read()
|
26 |
+
if not ret:
|
27 |
+
break
|
28 |
+
|
29 |
+
# フレームをリストに追加
|
30 |
+
frame_list.append(frame)
|
31 |
+
frame_num += 1
|
32 |
+
|
33 |
+
# 動画ファイルを閉じる
|
34 |
+
cap.release()
|
35 |
+
|
36 |
+
return frame_list
|
37 |
+
|
38 |
+
class Image2Video():
|
39 |
+
def __init__(self,result_dir='./tmp/',gpu_num=1,resolution='256_256') -> None:
|
40 |
+
self.resolution = (int(resolution.split('_')[0]), int(resolution.split('_')[1])) #hw
|
41 |
+
self.download_model()
|
42 |
+
|
43 |
+
self.result_dir = result_dir
|
44 |
+
if not os.path.exists(self.result_dir):
|
45 |
+
os.mkdir(self.result_dir)
|
46 |
+
|
47 |
+
#ToonCrafterModel
|
48 |
+
ckpt_path='checkpoints/tooncrafter_'+resolution.split('_')[1]+'_interp_v1/model.ckpt'
|
49 |
+
config_file='configs/inference_'+resolution.split('_')[1]+'_v1.0.yaml'
|
50 |
+
config = OmegaConf.load(config_file)
|
51 |
+
model_config = config.pop("model", OmegaConf.create())
|
52 |
+
model_config['params']['unet_config']['params']['use_checkpoint']=False
|
53 |
+
|
54 |
+
#ControlModel
|
55 |
+
cn_ckpt_path = "control_models/sketch_encoder.ckpt"
|
56 |
+
cn_config_file = 'configs/cldm_v21.yaml'
|
57 |
+
cn_config = OmegaConf.load(cn_config_file)
|
58 |
+
cn_model_config = cn_config.pop("control_stage_config", OmegaConf.create())
|
59 |
+
|
60 |
+
|
61 |
+
model_list = []
|
62 |
+
for gpu_id in range(gpu_num):
|
63 |
+
model = instantiate_from_config(model_config)
|
64 |
+
cn_model = instantiate_from_config(cn_model_config)
|
65 |
+
|
66 |
+
# model = model.cuda(gpu_id)
|
67 |
+
assert os.path.exists(ckpt_path), "Error: checkpoint Not Found!"
|
68 |
+
model = load_model_checkpoint(model, ckpt_path)
|
69 |
+
model.eval()
|
70 |
+
|
71 |
+
cn_model.load_state_dict(load_state_dict(cn_ckpt_path, location='cpu'))
|
72 |
+
cn_model.eval()
|
73 |
+
|
74 |
+
model.control_model = cn_model
|
75 |
+
|
76 |
+
model_list.append(model)
|
77 |
+
self.model_list = model_list
|
78 |
+
self.save_fps = 8
|
79 |
+
|
80 |
+
def get_image(self, image, prompt, steps=50, cfg_scale=7.5, eta=1.0, fs=3, seed=123, image2=None, frame_guides=None,control_scale=0.6):
|
81 |
+
control_frames = extract_frames(frame_guides)
|
82 |
+
seed_everything(seed)
|
83 |
+
transform = transforms.Compose([
|
84 |
+
transforms.Resize(min(self.resolution)),
|
85 |
+
transforms.CenterCrop(self.resolution),
|
86 |
+
])
|
87 |
+
torch.cuda.empty_cache()
|
88 |
+
print('start:', prompt, time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
|
89 |
+
start = time.time()
|
90 |
+
gpu_id=0
|
91 |
+
if steps > 60:
|
92 |
+
steps = 60
|
93 |
+
model = self.model_list[gpu_id]
|
94 |
+
model = model.cuda()
|
95 |
+
batch_size=1
|
96 |
+
channels = model.model.diffusion_model.out_channels
|
97 |
+
frames = model.temporal_length
|
98 |
+
h, w = self.resolution[0] // 8, self.resolution[1] // 8
|
99 |
+
noise_shape = [batch_size, channels, frames, h, w]
|
100 |
+
|
101 |
+
# text cond
|
102 |
+
with torch.no_grad(), torch.cuda.amp.autocast():
|
103 |
+
text_emb = model.get_learned_conditioning([prompt])
|
104 |
+
|
105 |
+
#control cond
|
106 |
+
if frame_guides is not None:
|
107 |
+
cn_videos = []
|
108 |
+
for frame in control_frames:
|
109 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
110 |
+
frame = cv2.bitwise_not(frame)
|
111 |
+
cn_tensor = torch.from_numpy(frame).unsqueeze(2).permute(2, 0, 1).float().to(model.device)
|
112 |
+
|
113 |
+
#cn_tensor = (cn_tensor / 255. - 0.5) * 2
|
114 |
+
cn_tensor = ( cn_tensor/255.0 )
|
115 |
+
cn_tensor_resized = transform(cn_tensor) #3,h,w
|
116 |
+
|
117 |
+
cn_video = cn_tensor_resized.unsqueeze(0).unsqueeze(2) # bc1hw
|
118 |
+
cn_videos.append(cn_video)
|
119 |
+
|
120 |
+
cn_videos = torch.cat(cn_videos, dim=2)
|
121 |
+
model_list = []
|
122 |
+
for model in self.model_list:
|
123 |
+
model.control_scale = control_scale
|
124 |
+
model_list.append(model)
|
125 |
+
self.model_list = model_list
|
126 |
+
|
127 |
+
else:
|
128 |
+
cn_videos = None
|
129 |
+
|
130 |
+
|
131 |
+
|
132 |
+
# img cond
|
133 |
+
img_tensor = torch.from_numpy(image).permute(2, 0, 1).float().to(model.device)
|
134 |
+
img_tensor = (img_tensor / 255. - 0.5) * 2
|
135 |
+
|
136 |
+
image_tensor_resized = transform(img_tensor) #3,h,w
|
137 |
+
videos = image_tensor_resized.unsqueeze(0).unsqueeze(2) # bc1hw
|
138 |
+
|
139 |
+
# z = get_latent_z(model, videos) #bc,1,hw
|
140 |
+
videos = repeat(videos, 'b c t h w -> b c (repeat t) h w', repeat=frames//2)
|
141 |
+
|
142 |
+
img_tensor2 = torch.from_numpy(image2).permute(2, 0, 1).float().to(model.device)
|
143 |
+
img_tensor2 = (img_tensor2 / 255. - 0.5) * 2
|
144 |
+
image_tensor_resized2 = transform(img_tensor2) #3,h,w
|
145 |
+
videos2 = image_tensor_resized2.unsqueeze(0).unsqueeze(2) # bchw
|
146 |
+
videos2 = repeat(videos2, 'b c t h w -> b c (repeat t) h w', repeat=frames//2)
|
147 |
+
|
148 |
+
|
149 |
+
videos = torch.cat([videos, videos2], dim=2)
|
150 |
+
z, hs = self.get_latent_z_with_hidden_states(model, videos)
|
151 |
+
|
152 |
+
img_tensor_repeat = torch.zeros_like(z)
|
153 |
+
|
154 |
+
img_tensor_repeat[:,:,:1,:,:] = z[:,:,:1,:,:]
|
155 |
+
img_tensor_repeat[:,:,-1:,:,:] = z[:,:,-1:,:,:]
|
156 |
+
|
157 |
+
|
158 |
+
cond_images = model.embedder(img_tensor.unsqueeze(0)) ## blc
|
159 |
+
img_emb = model.image_proj_model(cond_images)
|
160 |
+
|
161 |
+
imtext_cond = torch.cat([text_emb, img_emb], dim=1)
|
162 |
+
|
163 |
+
fs = torch.tensor([fs], dtype=torch.long, device=model.device)
|
164 |
+
cond = {"c_crossattn": [imtext_cond], "fs": fs, "c_concat": [img_tensor_repeat], "control_cond": cn_videos}
|
165 |
+
|
166 |
+
## inference
|
167 |
+
batch_samples = batch_ddim_sampling(model, cond, noise_shape, n_samples=1, ddim_steps=steps, ddim_eta=eta, cfg_scale=cfg_scale, hs=hs)
|
168 |
+
|
169 |
+
## remove the last frame
|
170 |
+
if image2 is None:
|
171 |
+
batch_samples = batch_samples[:,:,:,:-1,...]
|
172 |
+
## b,samples,c,t,h,w
|
173 |
+
prompt_str = prompt.replace("/", "_slash_") if "/" in prompt else prompt
|
174 |
+
prompt_str = prompt_str.replace(" ", "_") if " " in prompt else prompt_str
|
175 |
+
prompt_str=prompt_str[:40]
|
176 |
+
if len(prompt_str) == 0:
|
177 |
+
prompt_str = 'empty_prompt'
|
178 |
+
|
179 |
+
save_videos(batch_samples, self.result_dir, filenames=[prompt_str], fps=self.save_fps)
|
180 |
+
print(f"Saved in {prompt_str}. Time used: {(time.time() - start):.2f} seconds")
|
181 |
+
model = model.cpu()
|
182 |
+
result_dir = os.path.join("/group/40034/gzhiwang/ToonCrafter_with_SketchGuidance", f"{prompt_str}.mp4")
|
183 |
+
print("result saved to:", result_dir)
|
184 |
+
return result_dir
|
185 |
+
|
186 |
+
# import torchvision
|
187 |
+
# batch_tensors = batch_samples
|
188 |
+
# n_samples = batch_tensors.shape[1]
|
189 |
+
# for idx, vid_tensor in enumerate(batch_tensors):
|
190 |
+
# video = vid_tensor.detach().cpu()
|
191 |
+
# video = torch.clamp(video.float(), -1., 1.)
|
192 |
+
# video = video.permute(2, 0, 1, 3, 4) # t,n,c,h,w
|
193 |
+
# frame_grids = [torchvision.utils.make_grid(framesheet, nrow=int(n_samples)) for framesheet in video] #[3, 1*h, n*w]
|
194 |
+
# grid = torch.stack(frame_grids, dim=0) # stack in temporal dim [t, 3, n*h, w]
|
195 |
+
# grid = (grid + 1.0) / 2.0
|
196 |
+
# grid = (grid * 255).to(torch.uint8).permute(0, 2, 3, 1)
|
197 |
+
# # savepath = os.path.join(savedir, f"{filenames[idx]}.mp4")
|
198 |
+
# # torchvision.io.write_video(savepath, grid, fps=fps, video_codec='h264', options={'crf': '10'})
|
199 |
+
# return grid
|
200 |
+
|
201 |
+
def download_model(self):
|
202 |
+
REPO_ID = 'Doubiiu/ToonCrafter'
|
203 |
+
filename_list = ['model.ckpt']
|
204 |
+
if not os.path.exists('./checkpoints/tooncrafter_'+str(self.resolution[1])+'_interp_v1/'):
|
205 |
+
os.makedirs('./checkpoints/tooncrafter_'+str(self.resolution[1])+'_interp_v1/')
|
206 |
+
for filename in filename_list:
|
207 |
+
local_file = os.path.join('./checkpoints/tooncrafter_'+str(self.resolution[1])+'_interp_v1/', filename)
|
208 |
+
if not os.path.exists(local_file):
|
209 |
+
hf_hub_download(repo_id=REPO_ID, filename=filename, local_dir='./checkpoints/tooncrafter_'+str(self.resolution[1])+'_interp_v1/', local_dir_use_symlinks=False)
|
210 |
+
|
211 |
+
def get_latent_z_with_hidden_states(self, model, videos):
|
212 |
+
b, c, t, h, w = videos.shape
|
213 |
+
x = rearrange(videos, 'b c t h w -> (b t) c h w')
|
214 |
+
encoder_posterior, hidden_states = model.first_stage_model.encode(x, return_hidden_states=True)
|
215 |
+
|
216 |
+
hidden_states_first_last = []
|
217 |
+
### use only the first and last hidden states
|
218 |
+
for hid in hidden_states:
|
219 |
+
hid = rearrange(hid, '(b t) c h w -> b c t h w', t=t)
|
220 |
+
hid_new = torch.cat([hid[:, :, 0:1], hid[:, :, -1:]], dim=2)
|
221 |
+
hidden_states_first_last.append(hid_new)
|
222 |
+
|
223 |
+
z = model.get_first_stage_encoding(encoder_posterior).detach()
|
224 |
+
z = rearrange(z, '(b t) c h w -> b c t h w', b=b, t=t)
|
225 |
+
return z, hidden_states_first_last
|
226 |
+
if __name__ == '__main__':
|
227 |
+
i2v = Image2Video()
|
228 |
+
video_path = i2v.get_image('prompts/art.png','man fishing in a boat at sunset')
|
229 |
print('done', video_path)
|