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 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import random
4
+
5
+ import cv2
6
+ import einops
7
+ import numpy as np
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import torchvision.transforms as T
11
+ from blendmodes.blend import BlendType, blendLayers
12
+ from PIL import Image
13
+ from pytorch_lightning import seed_everything
14
+ from safetensors.torch import load_file
15
+ from skimage import exposure
16
+
17
+ import src.import_util # noqa: F401
18
+ from deps.ControlNet.annotator.canny import CannyDetector
19
+ from deps.ControlNet.annotator.hed import HEDdetector
20
+ from deps.ControlNet.annotator.util import HWC3
21
+ from deps.ControlNet.cldm.cldm import ControlLDM
22
+ from deps.ControlNet.cldm.model import create_model, load_state_dict
23
+ from deps.gmflow.gmflow.gmflow import GMFlow
24
+ from flow.flow_utils import get_warped_and_mask
25
+ from src.config import RerenderConfig
26
+ from src.controller import AttentionControl
27
+ from src.ddim_v_hacked import DDIMVSampler
28
+ from src.freeu import freeu_forward
29
+ from src.img_util import find_flat_region, numpy2tensor
30
+ from src.video_util import frame_to_video, get_fps, prepare_frames
31
+
32
+ blur = T.GaussianBlur(kernel_size=(9, 9), sigma=(18, 18))
33
+ totensor = T.PILToTensor()
34
+
35
+
36
+ def setup_color_correction(image):
37
+ correction_target = cv2.cvtColor(np.asarray(image.copy()),
38
+ cv2.COLOR_RGB2LAB)
39
+ return correction_target
40
+
41
+
42
+ def apply_color_correction(correction, original_image):
43
+ image = Image.fromarray(
44
+ cv2.cvtColor(
45
+ exposure.match_histograms(cv2.cvtColor(np.asarray(original_image),
46
+ cv2.COLOR_RGB2LAB),
47
+ correction,
48
+ channel_axis=2),
49
+ cv2.COLOR_LAB2RGB).astype('uint8'))
50
+
51
+ image = blendLayers(image, original_image, BlendType.LUMINOSITY)
52
+
53
+ return image
54
+
55
+
56
+ def rerender(cfg: RerenderConfig, first_img_only: bool, key_video_path: str):
57
+
58
+ # Preprocess input
59
+ prepare_frames(cfg.input_path, cfg.input_dir, cfg.image_resolution,
60
+ cfg.crop)
61
+
62
+ # Load models
63
+ if cfg.control_type == 'HED':
64
+ detector = HEDdetector()
65
+ elif cfg.control_type == 'canny':
66
+ canny_detector = CannyDetector()
67
+ low_threshold = cfg.canny_low
68
+ high_threshold = cfg.canny_high
69
+
70
+ def apply_canny(x):
71
+ return canny_detector(x, low_threshold, high_threshold)
72
+
73
+ detector = apply_canny
74
+
75
+ model: ControlLDM = create_model(
76
+ './deps/ControlNet/models/cldm_v15.yaml').cpu()
77
+ if cfg.control_type == 'HED':
78
+ model.load_state_dict(
79
+ load_state_dict('./models/control_sd15_hed.pth', location='cuda'))
80
+ elif cfg.control_type == 'canny':
81
+ model.load_state_dict(
82
+ load_state_dict('./models/control_sd15_canny.pth',
83
+ location='cuda'))
84
+ model = model.cuda()
85
+ model.control_scales = [cfg.control_strength] * 13
86
+
87
+ if cfg.sd_model is not None:
88
+ model_ext = os.path.splitext(cfg.sd_model)[1]
89
+ if model_ext == '.safetensors':
90
+ model.load_state_dict(load_file(cfg.sd_model), strict=False)
91
+ elif model_ext == '.ckpt' or model_ext == '.pth':
92
+ model.load_state_dict(torch.load(cfg.sd_model)['state_dict'],
93
+ strict=False)
94
+
95
+ try:
96
+ model.first_stage_model.load_state_dict(torch.load(
97
+ './models/vae-ft-mse-840000-ema-pruned.ckpt')['state_dict'],
98
+ strict=False)
99
+ except Exception:
100
+ print('Warning: We suggest you download the fine-tuned VAE',
101
+ 'otherwise the generation quality will be degraded')
102
+
103
+ model.model.diffusion_model.forward = \
104
+ freeu_forward(model.model.diffusion_model, *cfg.freeu_args)
105
+ ddim_v_sampler = DDIMVSampler(model)
106
+
107
+ flow_model = GMFlow(
108
+ feature_channels=128,
109
+ num_scales=1,
110
+ upsample_factor=8,
111
+ num_head=1,
112
+ attention_type='swin',
113
+ ffn_dim_expansion=4,
114
+ num_transformer_layers=6,
115
+ ).to('cuda')
116
+
117
+ checkpoint = torch.load('models/gmflow_sintel-0c07dcb3.pth',
118
+ map_location=lambda storage, loc: storage)
119
+ weights = checkpoint['model'] if 'model' in checkpoint else checkpoint
120
+ flow_model.load_state_dict(weights, strict=False)
121
+ flow_model.eval()
122
+
123
+ num_samples = 1
124
+ ddim_steps = 20
125
+ scale = 7.5
126
+
127
+ seed = cfg.seed
128
+ if seed == -1:
129
+ seed = random.randint(0, 65535)
130
+ eta = 0.0
131
+
132
+ prompt = cfg.prompt
133
+ a_prompt = cfg.a_prompt
134
+ n_prompt = cfg.n_prompt
135
+ prompt = prompt + ', ' + a_prompt
136
+
137
+ style_update_freq = cfg.style_update_freq
138
+ pixelfusion = True
139
+ color_preserve = cfg.color_preserve
140
+
141
+ x0_strength = 1 - cfg.x0_strength
142
+ mask_period = cfg.mask_period
143
+ firstx0 = True
144
+ controller = AttentionControl(cfg.inner_strength, cfg.mask_period,
145
+ cfg.cross_period, cfg.ada_period,
146
+ cfg.warp_period, cfg.loose_cfattn)
147
+
148
+ imgs = sorted(os.listdir(cfg.input_dir))
149
+ imgs = [os.path.join(cfg.input_dir, img) for img in imgs]
150
+ if cfg.frame_count >= 0:
151
+ imgs = imgs[:cfg.frame_count]
152
+
153
+ with torch.no_grad():
154
+ frame = cv2.imread(imgs[0])
155
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
156
+ img = HWC3(frame)
157
+ H, W, C = img.shape
158
+
159
+ img_ = numpy2tensor(img)
160
+ # if color_preserve:
161
+ # img_ = numpy2tensor(img)
162
+ # else:
163
+ # img_ = apply_color_correction(color_corrections,
164
+ # Image.fromarray(img))
165
+ # img_ = totensor(img_).unsqueeze(0)[:, :3] / 127.5 - 1
166
+ encoder_posterior = model.encode_first_stage(img_.cuda())
167
+ x0 = model.get_first_stage_encoding(encoder_posterior).detach()
168
+
169
+ detected_map = detector(img)
170
+ detected_map = HWC3(detected_map)
171
+ # For visualization
172
+ detected_img = 255 - detected_map
173
+
174
+ control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
175
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
176
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
177
+ cond = {
178
+ 'c_concat': [control],
179
+ 'c_crossattn':
180
+ [model.get_learned_conditioning([prompt] * num_samples)]
181
+ }
182
+ un_cond = {
183
+ 'c_concat': [control],
184
+ 'c_crossattn':
185
+ [model.get_learned_conditioning([n_prompt] * num_samples)]
186
+ }
187
+ shape = (4, H // 8, W // 8)
188
+
189
+ controller.set_task('initfirst')
190
+ seed_everything(seed)
191
+ samples, _ = ddim_v_sampler.sample(ddim_steps,
192
+ num_samples,
193
+ shape,
194
+ cond,
195
+ verbose=False,
196
+ eta=eta,
197
+ unconditional_guidance_scale=scale,
198
+ unconditional_conditioning=un_cond,
199
+ controller=controller,
200
+ x0=x0,
201
+ strength=x0_strength)
202
+ x_samples = model.decode_first_stage(samples)
203
+ pre_result = x_samples
204
+ pre_img = img
205
+ first_result = pre_result
206
+ first_img = pre_img
207
+
208
+ x_samples = (
209
+ einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 +
210
+ 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
211
+ color_corrections = setup_color_correction(Image.fromarray(x_samples[0]))
212
+ Image.fromarray(x_samples[0]).save(os.path.join(cfg.first_dir,
213
+ 'first.jpg'))
214
+ cv2.imwrite(os.path.join(cfg.first_dir, 'first_edge.jpg'), detected_img)
215
+
216
+ if first_img_only:
217
+ exit(0)
218
+
219
+ for i in range(0, min(len(imgs), cfg.frame_count) - 1, cfg.interval):
220
+ cid = i + 1
221
+ print(cid)
222
+ if cid <= (len(imgs) - 1):
223
+ frame = cv2.imread(imgs[cid])
224
+ else:
225
+ frame = cv2.imread(imgs[len(imgs) - 1])
226
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
227
+ img = HWC3(frame)
228
+
229
+ if color_preserve:
230
+ img_ = numpy2tensor(img)
231
+ else:
232
+ img_ = apply_color_correction(color_corrections,
233
+ Image.fromarray(img))
234
+ img_ = totensor(img_).unsqueeze(0)[:, :3] / 127.5 - 1
235
+ encoder_posterior = model.encode_first_stage(img_.cuda())
236
+ x0 = model.get_first_stage_encoding(encoder_posterior).detach()
237
+
238
+ detected_map = detector(img)
239
+ detected_map = HWC3(detected_map)
240
+
241
+ control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
242
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
243
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
244
+ cond['c_concat'] = [control]
245
+ un_cond['c_concat'] = [control]
246
+
247
+ image1 = torch.from_numpy(pre_img).permute(2, 0, 1).float()
248
+ image2 = torch.from_numpy(img).permute(2, 0, 1).float()
249
+ warped_pre, bwd_occ_pre, bwd_flow_pre = get_warped_and_mask(
250
+ flow_model, image1, image2, pre_result, False)
251
+ blend_mask_pre = blur(
252
+ F.max_pool2d(bwd_occ_pre, kernel_size=9, stride=1, padding=4))
253
+ blend_mask_pre = torch.clamp(blend_mask_pre + bwd_occ_pre, 0, 1)
254
+
255
+ image1 = torch.from_numpy(first_img).permute(2, 0, 1).float()
256
+ warped_0, bwd_occ_0, bwd_flow_0 = get_warped_and_mask(
257
+ flow_model, image1, image2, first_result, False)
258
+ blend_mask_0 = blur(
259
+ F.max_pool2d(bwd_occ_0, kernel_size=9, stride=1, padding=4))
260
+ blend_mask_0 = torch.clamp(blend_mask_0 + bwd_occ_0, 0, 1)
261
+
262
+ if firstx0:
263
+ mask = 1 - F.max_pool2d(blend_mask_0, kernel_size=8)
264
+ controller.set_warp(
265
+ F.interpolate(bwd_flow_0 / 8.0,
266
+ scale_factor=1. / 8,
267
+ mode='bilinear'), mask)
268
+ else:
269
+ mask = 1 - F.max_pool2d(blend_mask_pre, kernel_size=8)
270
+ controller.set_warp(
271
+ F.interpolate(bwd_flow_pre / 8.0,
272
+ scale_factor=1. / 8,
273
+ mode='bilinear'), mask)
274
+
275
+ controller.set_task('keepx0, keepstyle')
276
+ seed_everything(seed)
277
+ samples, intermediates = ddim_v_sampler.sample(
278
+ ddim_steps,
279
+ num_samples,
280
+ shape,
281
+ cond,
282
+ verbose=False,
283
+ eta=eta,
284
+ unconditional_guidance_scale=scale,
285
+ unconditional_conditioning=un_cond,
286
+ controller=controller,
287
+ x0=x0,
288
+ strength=x0_strength)
289
+ direct_result = model.decode_first_stage(samples)
290
+
291
+ if not pixelfusion:
292
+ pre_result = direct_result
293
+ pre_img = img
294
+ viz = (
295
+ einops.rearrange(direct_result, 'b c h w -> b h w c') * 127.5 +
296
+ 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
297
+
298
+ else:
299
+
300
+ blend_results = (1 - blend_mask_pre
301
+ ) * warped_pre + blend_mask_pre * direct_result
302
+ blend_results = (
303
+ 1 - blend_mask_0) * warped_0 + blend_mask_0 * blend_results
304
+
305
+ bwd_occ = 1 - torch.clamp(1 - bwd_occ_pre + 1 - bwd_occ_0, 0, 1)
306
+ blend_mask = blur(
307
+ F.max_pool2d(bwd_occ, kernel_size=9, stride=1, padding=4))
308
+ blend_mask = 1 - torch.clamp(blend_mask + bwd_occ, 0, 1)
309
+
310
+ encoder_posterior = model.encode_first_stage(blend_results)
311
+ xtrg = model.get_first_stage_encoding(
312
+ encoder_posterior).detach() # * mask
313
+ blend_results_rec = model.decode_first_stage(xtrg)
314
+ encoder_posterior = model.encode_first_stage(blend_results_rec)
315
+ xtrg_rec = model.get_first_stage_encoding(
316
+ encoder_posterior).detach()
317
+ xtrg_ = (xtrg + 1 * (xtrg - xtrg_rec)) # * mask
318
+ blend_results_rec_new = model.decode_first_stage(xtrg_)
319
+ tmp = (abs(blend_results_rec_new - blend_results).mean(
320
+ dim=1, keepdims=True) > 0.25).float()
321
+ mask_x = F.max_pool2d((F.interpolate(
322
+ tmp, scale_factor=1 / 8., mode='bilinear') > 0).float(),
323
+ kernel_size=3,
324
+ stride=1,
325
+ padding=1)
326
+
327
+ mask = (1 - F.max_pool2d(1 - blend_mask, kernel_size=8)
328
+ ) # * (1-mask_x)
329
+
330
+ if cfg.smooth_boundary:
331
+ noise_rescale = find_flat_region(mask)
332
+ else:
333
+ noise_rescale = torch.ones_like(mask)
334
+ masks = []
335
+ for i in range(ddim_steps):
336
+ if i <= ddim_steps * mask_period[
337
+ 0] or i >= ddim_steps * mask_period[1]:
338
+ masks += [None]
339
+ else:
340
+ masks += [mask * cfg.mask_strength]
341
+
342
+ # mask 3
343
+ # xtrg = ((1-mask_x) *
344
+ # (xtrg + xtrg - xtrg_rec) + mask_x * samples) * mask
345
+ # mask 2
346
+ # xtrg = (xtrg + 1 * (xtrg - xtrg_rec)) * mask
347
+ xtrg = (xtrg + (1 - mask_x) * (xtrg - xtrg_rec)) * mask # mask 1
348
+
349
+ tasks = 'keepstyle, keepx0'
350
+ if not firstx0:
351
+ tasks += ', updatex0'
352
+ if i % style_update_freq == 0:
353
+ tasks += ', updatestyle'
354
+ controller.set_task(tasks, 1.0)
355
+
356
+ seed_everything(seed)
357
+ samples, _ = ddim_v_sampler.sample(
358
+ ddim_steps,
359
+ num_samples,
360
+ shape,
361
+ cond,
362
+ verbose=False,
363
+ eta=eta,
364
+ unconditional_guidance_scale=scale,
365
+ unconditional_conditioning=un_cond,
366
+ controller=controller,
367
+ x0=x0,
368
+ strength=x0_strength,
369
+ xtrg=xtrg,
370
+ mask=masks,
371
+ noise_rescale=noise_rescale)
372
+ x_samples = model.decode_first_stage(samples)
373
+ pre_result = x_samples
374
+ pre_img = img
375
+
376
+ viz = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 +
377
+ 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
378
+
379
+ Image.fromarray(viz[0]).save(
380
+ os.path.join(cfg.key_dir, f'{cid:04d}.png'))
381
+ if key_video_path is not None:
382
+ fps = get_fps(cfg.input_path)
383
+ fps //= cfg.interval
384
+ frame_to_video(key_video_path, cfg.key_dir, fps, False)
385
+
386
+
387
+ def postprocess(cfg: RerenderConfig, ne: bool, max_process: int, tmp: bool,
388
+ ps: bool):
389
+ video_base_dir = cfg.work_dir
390
+ o_video = cfg.output_path
391
+ fps = get_fps(cfg.input_path)
392
+
393
+ end_frame = cfg.frame_count - 1
394
+ interval = cfg.interval
395
+ key_dir = os.path.split(cfg.key_dir)[-1]
396
+ use_e = '-ne' if ne else ''
397
+ use_tmp = '-tmp' if tmp else ''
398
+ use_ps = '-ps' if ps else ''
399
+ o_video_cmd = f'--output {o_video}'
400
+
401
+ cmd = (
402
+ f'python video_blend.py {video_base_dir} --beg 1 --end {end_frame} '
403
+ f'--itv {interval} --key {key_dir} {use_e} {o_video_cmd} --fps {fps} '
404
+ f'--n_proc {max_process} {use_tmp} {use_ps}')
405
+ print(cmd)
406
+ os.system(cmd)
407
+
408
+
409
+ if __name__ == '__main__':
410
+ parser = argparse.ArgumentParser()
411
+ parser.add_argument('--cfg', type=str, default=None)
412
+ parser.add_argument('--input',
413
+ type=str,
414
+ default=None,
415
+ help='The input path to video.')
416
+ parser.add_argument('--output', type=str, default=None)
417
+ parser.add_argument('--prompt', type=str, default=None)
418
+ parser.add_argument('--key_video_path', type=str, default=None)
419
+ parser.add_argument('-one',
420
+ action='store_true',
421
+ help='Run the first frame with ControlNet only')
422
+ parser.add_argument('-nr',
423
+ action='store_true',
424
+ help='Do not run rerender and do postprocessing only')
425
+ parser.add_argument('-nb',
426
+ action='store_true',
427
+ help='Do not run postprocessing and run rerender only')
428
+ parser.add_argument(
429
+ '-ne',
430
+ action='store_true',
431
+ help='Do not run ebsynth (use previous ebsynth temporary output)')
432
+ parser.add_argument('-nps',
433
+ action='store_true',
434
+ help='Do not run poisson gradient blending')
435
+ parser.add_argument('--n_proc',
436
+ type=int,
437
+ default=4,
438
+ help='The max process count')
439
+ parser.add_argument('--tmp',
440
+ action='store_true',
441
+ help='Keep ebsynth temporary output')
442
+
443
+ args = parser.parse_args()
444
+
445
+ cfg = RerenderConfig()
446
+ if args.cfg is not None:
447
+ cfg.create_from_path(args.cfg)
448
+ if args.input is not None:
449
+ print('Config has been loaded. --input is ignored.')
450
+ if args.output is not None:
451
+ print('Config has been loaded. --output is ignored.')
452
+ if args.prompt is not None:
453
+ print('Config has been loaded. --prompt is ignored.')
454
+ else:
455
+ if args.input is None:
456
+ print('Config not found. --input is required.')
457
+ exit(0)
458
+ if args.output is None:
459
+ print('Config not found. --output is required.')
460
+ exit(0)
461
+ if args.prompt is None:
462
+ print('Config not found. --prompt is required.')
463
+ exit(0)
464
+ cfg.create_from_parameters(args.input, args.output, args.prompt)
465
+
466
+ if not args.nr:
467
+ rerender(cfg, args.one, args.key_video_path)
468
+ torch.cuda.empty_cache()
469
+ if not args.nb:
470
+ postprocess(cfg, args.ne, args.n_proc, args.tmp, not args.nps)