-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwarp.py
12270 lines (10600 loc) · 547 KB
/
warp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
print("hererrererer !!!!!!!!")
#@title Prepare folders & Install
import subprocess, os, sys
###########################################################################################################################################
#cell execution check thanks to #soze
if len(sys.argv) > 4:
user_seed = int(sys.argv[4])
user_prompt = sys.argv[1]
user_width = int(float(sys.argv[2]))
user_height = int(float(sys.argv[3]))
load_settings_param_str = sys.argv[5]
settings_file_name = sys.argv[6]
if load_settings_param_str == "False":
load_settings_param = False
elif load_settings_param_str == "True":
load_settings_param = True
print("Prompt:", user_prompt)
executed_cells = {
'prepare_folders':False,
# 'install_pytorch':False,
# 'install_sd_dependencies':False,
'import_dependencies':False,
# 'basic_settings':False,
# 'animation_settings':False,
'video_input_settings':False,
# 'video_masking':False,
# 'generate_optical_flow':False,
'load_model':False,
# 'tiled_vae':False,
'save_loaded_model':False,
# 'clip_guidance':False,
# 'brightness_adjustment':False,
'content_aware_scheduling':False,
'plot_threshold_vs_frame_difference':False,
'create_schedules':False,
'frame_captioning':False,
'flow_and_turbo_settings':False,
'consistency_maps_mixing':False,
'seed_and_grad_settings':False,
'prompts':False,
'warp_turbo_smooth_settings':False,
'video_mask_settings': False,
'frame_correction':False,
'main_settings':False,
'advanced':False,
'lora':False,
# 'reference_controlnet':False,
'GUI':False,
'do_the_run':False
}
executed_cells_errors = {
'prepare_folders': 'Prepare folders & Install',
# 'install_pytorch':'1.2 Install pytorch',
# 'install_sd_dependencies':'1.3 Install SD Dependencies',
'import_dependencies':'Import dependencies, define functions',
# 'basic_settings':'2.Settings - Basic Settings',
# 'animation_settings': '2.Settings - Animation Settings',
'video_input_settings':'2.Settings - Video Input Settings',
# 'video_masking':'2.Settings - Video Masking',
# 'generate_optical_flow':'Optical map settings - Generate optical flow and consistency maps',
'load_model':'Load up a stable. - define SD + K functions, load model',
# 'tiled_vae':'Extra features - Tiled VAE',
'save_loaded_model':'Extra features - Save loaded model',
# 'clip_guidance':'CLIP guidance - CLIP guidance settings',
# 'brightness_adjustment':'Automatic Brightness Adjustment',
'content_aware_scheduling':'Content-aware scheduing - Content-aware scheduing',
'plot_threshold_vs_frame_difference':'Content-aware scheduing - Plot threshold vs frame difference',
'create_schedules':'Content-aware scheduing - Create schedules from frame difference',
'frame_captioning':'Frame captioning - Generate captions for keyframes',
'flow_and_turbo_settings':'Render settings - Non-gui - Flow and turbo settings',
'consistency_maps_mixing':'Render settings - Non-gui - Consistency map mixing',
'seed_and_grad_settings':'Render settings - Non-gui - Seed and grad Settings',
'prompts':'Render settings - Non-gui - Prompts',
'warp_turbo_smooth_settings':'Render settings - Non-gui - Warp Turbo Smooth Settings',
'video_mask_settings':'Render settings - Non-gui - Video mask settings',
'frame_correction':'Render settings - Non-gui - Frame correction',
'main_settings':'Render settings - Non-gui - Main settings',
'advanced':'Render settings - Non-gui - Advanced',
'lora': 'LORA & embedding paths',
# 'reference_controlnet': 'Reference controlnet (attention injection)',
'GUI':'GUI',
'do_the_run':'Diffuse! - Do the run'
}
def check_execution(cell_name):
for key in executed_cells.keys():
if key == cell_name:
#reached current cell successfully, exit
return
if executed_cells[key] == False:
raise RuntimeError(f'The {executed_cells_errors[key]} cell was not run successfully and must be executed to continue. \
RUN ALL after starting runtime (CTRL-F9)');
cell_name = 'prepare_folders'
# check_execution(cell_name)
def gitclone(url, recursive=False, dest=None, branch=None):
command = ['git', 'clone']
if branch is not None:
command.append(['-b', branch])
command.append(url)
if dest: command.append(dest)
if recursive: command.append('--recursive')
res = subprocess.run(command, stdout=subprocess.PIPE).stdout.decode('utf-8')
print(res)
def pipi(modulestr):
res = subprocess.run(['python','-m','pip', '-q', 'install', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8')
print(res)
def pipie(modulestr):
res = subprocess.run(['git', 'install', '-e', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8')
print(res)
def wget_p(url, outputdir):
res = subprocess.run(['wget', url, '-P', f'{outputdir}'], stdout=subprocess.PIPE).stdout.decode('utf-8')
print(res)
is_colab = False
google_drive = False
save_models_to_google_drive = False
print("Google Colab not detected.")
if is_colab:
if google_drive is True:
drive.mount('/content/drive')
root_path = '/content/drive/MyDrive/AI/StableWarpFusion'
else:
root_path = '/content'
else:
root_path = os.getcwd()
import os
def createPath(filepath):
os.makedirs(filepath, exist_ok=True)
initDirPath = os.path.join(root_path,'init_images')
createPath(initDirPath)
outDirPath = os.path.join(root_path,'images_out')
createPath(outDirPath)
root_dir = os.getcwd()
print("ROOOT DIR", root_dir)
if is_colab:
root_dir = '/content/'
if google_drive and not save_models_to_google_drive or not google_drive:
model_path = '/content/models'
createPath(model_path)
if google_drive and save_models_to_google_drive:
model_path = f'{root_path}/models'
createPath(model_path)
else:
root_dir = root_path
model_path = f'{root_path}/models'
createPath(model_path)
#(c) Alex Spirin 2023
class FrameDataset():
def __init__(self, source_path, outdir_prefix='', videoframes_root=''):
self.frame_paths = None
image_extenstions = ['jpeg', 'jpg', 'png', 'tiff', 'bmp', 'webp']
if "{" in source_path:
source_path_e = eval(source_path)
if isinstance(source_path_e, dict):
self.frame_paths = []
for i in range(max(np.array([int(o) for o in source_path_e.keys()]).max(),1)):
frame = get_sched_from_json(i, source_path_e, blend=False)
assert os.path.exists(frame), f'The source frame {frame} doesn`t exist. Please provide an existing file name.'
self.frame_paths.append(frame)
return
if not os.path.exists(source_path):
if len(glob(source_path))>0:
self.frame_paths = sorted(glob(source_path))
else:
raise Exception(f'Frame source for {outdir_prefix} not found at {source_path}\nPlease specify an existing source path.')
if os.path.exists(source_path):
if os.path.isfile(source_path):
if os.path.splitext(source_path)[1][1:].lower() in image_extenstions:
self.frame_paths = [source_path]
hash = generate_file_hash(source_path)[:10]
out_path = os.path.join(videoframes_root, outdir_prefix+'_'+hash)
extractFrames(source_path, out_path,
nth_frame=1, start_frame=0, end_frame=999999999)
self.frame_paths = glob(os.path.join(out_path, '*.*'))
if len(self.frame_paths)<1:
raise Exception(f'Couldn`t extract frames from {source_path}\nPlease specify an existing source path.')
elif os.path.isdir(source_path):
self.frame_paths = glob(os.path.join(source_path, '*.*'))
if len(self.frame_paths)<1:
raise Exception(f'Found 0 frames in {source_path}\nPlease specify an existing source path.')
extensions = []
if self.frame_paths is not None:
for f in self.frame_paths:
ext = os.path.splitext(f)[1][1:]
if ext not in image_extenstions:
raise Exception(f'Found non-image file extension: {ext} in {source_path}. Please provide a folder with image files of the same extension, or specify a glob pattern.')
if not ext in extensions:
extensions+=[ext]
if len(extensions)>1:
raise Exception(f'Found multiple file extensions: {extensions} in {source_path}. Please provide a folder with image files of the same extension, or specify a glob pattern.')
self.frame_paths = sorted(self.frame_paths)
else: raise Exception(f'Frame source for {outdir_prefix} not found at {source_path}\nPlease specify an existing source path.')
print(f'Found {len(self.frame_paths)} frames at {source_path}')
def __getitem__(self, idx):
idx = min(idx, len(self.frame_paths)-1)
return self.frame_paths[idx]
def __len__(self):
return len(self.frame_paths)
gpu = None
# import requests
# installer_url = 'https://raw.githubusercontent.com/Sxela/WarpTools/main/installersw/warp_installer_032.py'
# r = requests.get(installer_url, allow_redirects=True)
# open('warp_installer.py', 'wb').write(r.content)
# import warp_installer
force_os = 'off'
force_torch_reinstall = False # \ @param {'type':'boolean'}
force_xformers_reinstall = False
use_torch_v2 = True # \ @param {'type':'boolean'}
import subprocess, sys
import os, platform
# if force_torch_reinstall:
# warp_installer.uninstall_pytorch(is_colab)
# if platform.system() != 'Linux' or force_os == 'Windows':
# warp_installer.install_torch_windows(force_torch_reinstall, use_torch_v2)
try:
if os.environ["IS_DOCKER"] == "1":
print('Docker found. Skipping install.')
except:
os.environ["IS_DOCKER"] = "0"
if (is_colab or (platform.system() == 'Linux') or force_os == 'Linux') and os.environ["IS_DOCKER"]=="0":
from subprocess import getoutput
import time
s = getoutput('nvidia-smi')
if 'T4' in s:
gpu = 'T4'
elif 'P100' in s:
gpu = 'P100'
elif 'V100' in s:
gpu = 'V100'
elif 'A100' in s:
gpu = 'A100'
for g in ['A4000','A5000','A6000']:
if g in s:
gpu = 'A100'
for g in ['2080','2070','2060']:
if g in s:
gpu = 'T4'
print(' DONE !')
import shutil, traceback
import pathlib, shutil, os, sys
skip_install = False #@param {'type':'boolean'}
os.makedirs('./embeddings', exist_ok=True)
if os.environ["IS_DOCKER"]=="1":
skip_install = True
print('Docker detected. Skipping install.')
if not is_colab:
os.environ['KMP_DUPLICATE_LIB_OK']='TRUE'
PROJECT_DIR = os.path.abspath(os.getcwd())
USE_ADABINS = False
root_path = os.getcwd()
model_path = f'{root_path}/models'
print("Current directory:", os.getcwd())
print("Listing directories in current path:", os.listdir('.'))
# if skip_install:
# warp_installer.pull_repos(is_colab)
# else:
# warp_installer.install_dependencies_colab(is_colab, root_dir)
sys.path.append(f'{PROJECT_DIR}/BLIP')
executed_cells[cell_name] = True
###########################################################################################################################################
"""# 2. Settings"""
# Commented out IPython magic to ensure Python compatibility.
#@title ### Import dependencies, define functions
cell_name = 'import_dependencies'
# check_execution(cell_name)
user_settings_keys = ['latent_scale_schedule', 'init_scale_schedule', 'steps_schedule', 'style_strength_schedule',
'cfg_scale_schedule', 'flow_blend_schedule', 'image_scale_schedule', 'flow_override_map',
'text_prompts', 'negative_prompts', 'prompt_patterns_sched', 'latent_fixed_mean',
'latent_fixed_std', 'rec_prompts', 'cc_masked_diffusion_schedule', 'mask_paths','user_comment', 'blend_json_schedules', 'VERBOSE', 'use_background_mask', 'invert_mask', 'background',
'background_source', 'mask_clip_low', 'mask_clip_high', 'turbo_mode', 'turbo_steps', 'colormatch_turbo',
'turbo_frame_skips_steps', 'soften_consistency_mask_for_turbo_frames', 'flow_warp', 'apply_mask_after_warp',
'warp_num_k', 'warp_forward', 'warp_strength', 'warp_mode', 'warp_towards_init', 'check_consistency',
'padding_ratio', 'padding_mode', 'match_color_strength',
'mask_result', 'use_patchmatch_inpaiting', 'cond_image_src', 'set_seed', 'clamp_grad', 'clamp_max', 'sat_scale',
'init_grad', 'grad_denoised', 'blend_latent_to_init', 'fixed_code', 'code_randomness', 'dynamic_thresh',
'sampler', 'use_karras_noise', 'inpainting_mask_weight', 'inverse_inpainting_mask', 'inpainting_mask_source',
'normalize_latent', 'normalize_latent_offset', 'latent_norm_4d', 'colormatch_frame', 'color_match_frame_str',
'colormatch_offset', 'colormatch_method', 'colormatch_regrain', 'colormatch_after',
'fixed_seed', 'rec_cfg', 'rec_steps_pct', 'rec_randomness', 'use_predicted_noise', 'overwrite_rec_noise',
'save_controlnet_annotations', 'control_sd15_openpose_hands_face', 'control_sd15_depth_detector',
'control_sd15_softedge_detector', 'control_sd15_seg_detector', 'control_sd15_scribble_detector',
'control_sd15_lineart_coarse', 'control_sd15_inpaint_mask_source', 'control_sd15_shuffle_source',
'control_sd15_shuffle_1st_source', 'controlnet_multimodel', 'controlnet_mode', 'normalize_cn_weights',
'controlnet_preprocess', 'detect_resolution', 'bg_threshold', 'low_threshold', 'high_threshold',
'value_threshold', 'distance_threshold', 'temporalnet_source', 'temporalnet_skip_1st_frame',
'controlnet_multimodel_mode', 'max_faces', 'do_softcap', 'softcap_thresh', 'softcap_q', 'masked_guidance',
'alpha_masked_diffusion', 'invert_alpha_masked_diffusion', 'normalize_prompt_weights', 'sd_batch_size',
'controlnet_low_vram', 'deflicker_scale', 'deflicker_latent_scale', 'pose_detector','apply_freeu_after_control',
'do_freeunet','batch_length','batch_overlap','looped_noise',
'overlap_stylized','context_length','context_overlap','blend_batch_outputs',
'force_flow_generation','use_legacy_cc','flow_threads','num_flow_workers','flow_lq',
'flow_save_img_preview','num_flow_updates','lazy_warp', 'blend_prompts_b4_diffusion',
'clip_skip','qr_cn_mask_clip_high','qr_cn_mask_clip_low','qr_cn_mask_thresh',
'use_manual_splits','scene_split_thresh','scene_splits','qr_cn_mask_invert',
'qr_cn_mask_grayscale','fill_lips','flow_maxsize','use_reference', 'reference_weight',
'reference_source', 'reference_mode',
'missed_consistency_schedule', 'overshoot_consistency_schedule', 'edges_consistency_schedule',
'consistency_blur_schedule','consistency_dilate_schedule','soften_consistency_schedule', 'offload_model',
'use_tiled_vae', 'num_tiles','force_mask_overwrite','mask_source','extract_background_mask',
'enable_adjust_brightness',
'high_brightness_threshold',
'high_brightness_adjust_ratio',
'high_brightness_adjust_fix_amount',
'max_brightness_threshold',
'low_brightness_threshold',
'low_brightness_adjust_ratio',
'low_brightness_adjust_fix_amount',
'min_brightness_threshold','color_video_path','color_extract_nth_frame','b1','b2','s1','s2']
user_settings_eval_keys = ['scene_splits','latent_scale_schedule', 'init_scale_schedule', 'steps_schedule', 'style_strength_schedule',
'cfg_scale_schedule', 'flow_blend_schedule', 'image_scale_schedule', 'flow_override_map',
'text_prompts', 'negative_prompts', 'prompt_patterns_sched', 'latent_fixed_mean',
'latent_fixed_std', 'rec_prompts', 'cc_masked_diffusion_schedule', 'mask_paths',
'missed_consistency_schedule', 'overshoot_consistency_schedule', 'edges_consistency_schedule',
'consistency_blur_schedule','consistency_dilate_schedule','soften_consistency_schedule','num_tiles']
#init settings
user_settings = {} #init empty to check for missing keys
# user_settings = dict([(key,'') for key in user_settings_keys])
image_prompts = {}
import os, random, torch
import numpy as np
animation_mode = 'Video Input'
def seed_everything(seed, deterministic=False):
print(f'Set global seed to {seed}')
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
if deterministic:
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
import torch
from dataclasses import dataclass
from functools import partial
import cv2
import pandas as pd
import gc
import io
import math
# import timm
# from IPython import display
import lpips
# !wget "https://download.pytorch.org/models/vgg16-397923af.pth" -O /root/.cache/torch/hub/checkpoints/vgg16-397923af.pth
from PIL import Image, ImageOps, ImageDraw
import requests
from glob import glob
import json
from types import SimpleNamespace
from torch import nn
from torch.nn import functional as F
import torchvision.transforms as T
import torchvision.transforms.functional as TF
from tqdm.notebook import tqdm
# from CLIP import clip
# from resize_right import resize
# from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
import random
# from ipywidgets import Output
import hashlib
from functools import partial
if is_colab:
os.chdir('/content')
from google.colab import files
else:
os.chdir(f'{PROJECT_DIR}')
# from IPython.display import Image as ipyimg
from numpy import asarray
from einops import rearrange, repeat
import torch, torchvision
import time
from omegaconf import OmegaConf
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
import torch
DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print('Using device:', DEVICE)
device = DEVICE # At least one of the modules expects this name..
if torch.cuda.get_device_capability(DEVICE) == (8,0): ## A100 fix thanks to Emad
print('Disabling CUDNN for A100 gpu', file=sys.stderr)
torch.backends.cudnn.enabled = False
elif torch.cuda.get_device_capability(DEVICE)[0] == 8: ## A100 fix thanks to Emad
print('Disabling CUDNN for Ada gpu', file=sys.stderr)
torch.backends.cudnn.enabled = False
import open_clip
#@title 1.5 Define necessary functions
from typing import Mapping
import mediapipe as mp
import numpy
from PIL import Image
def append_dims(x, n):
return x[(Ellipsis, *(None,) * (n - x.ndim))]
def expand_to_planes(x, shape):
return append_dims(x, len(shape)).repeat([1, 1, *shape[2:]])
def alpha_sigma_to_t(alpha, sigma):
return torch.atan2(sigma, alpha) * 2 / math.pi
def t_to_alpha_sigma(t):
return torch.cos(t * math.pi / 2), torch.sin(t * math.pi / 2)
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_face_detection = mp.solutions.face_detection # Only for counting faces.
mp_face_mesh = mp.solutions.face_mesh
mp_face_connections = mp.solutions.face_mesh_connections.FACEMESH_TESSELATION
mp_hand_connections = mp.solutions.hands_connections.HAND_CONNECTIONS
mp_body_connections = mp.solutions.pose_connections.POSE_CONNECTIONS
DrawingSpec = mp.solutions.drawing_styles.DrawingSpec
PoseLandmark = mp.solutions.drawing_styles.PoseLandmark
f_thick = 2
f_rad = 1
right_iris_draw = DrawingSpec(color=(10, 200, 250), thickness=f_thick, circle_radius=f_rad)
right_eye_draw = DrawingSpec(color=(10, 200, 180), thickness=f_thick, circle_radius=f_rad)
right_eyebrow_draw = DrawingSpec(color=(10, 220, 180), thickness=f_thick, circle_radius=f_rad)
left_iris_draw = DrawingSpec(color=(250, 200, 10), thickness=f_thick, circle_radius=f_rad)
left_eye_draw = DrawingSpec(color=(180, 200, 10), thickness=f_thick, circle_radius=f_rad)
left_eyebrow_draw = DrawingSpec(color=(180, 220, 10), thickness=f_thick, circle_radius=f_rad)
mouth_draw = DrawingSpec(color=(10, 180, 10), thickness=f_thick, circle_radius=f_rad)
head_draw = DrawingSpec(color=(10, 200, 10), thickness=f_thick, circle_radius=f_rad)
# mp_face_mesh.FACEMESH_CONTOURS has all the items we care about.
face_connection_spec = {}
for edge in mp_face_mesh.FACEMESH_FACE_OVAL:
face_connection_spec[edge] = head_draw
for edge in mp_face_mesh.FACEMESH_LEFT_EYE:
face_connection_spec[edge] = left_eye_draw
for edge in mp_face_mesh.FACEMESH_LEFT_EYEBROW:
face_connection_spec[edge] = left_eyebrow_draw
# for edge in mp_face_mesh.FACEMESH_LEFT_IRIS:
# face_connection_spec[edge] = left_iris_draw
for edge in mp_face_mesh.FACEMESH_RIGHT_EYE:
face_connection_spec[edge] = right_eye_draw
for edge in mp_face_mesh.FACEMESH_RIGHT_EYEBROW:
face_connection_spec[edge] = right_eyebrow_draw
# for edge in mp_face_mesh.FACEMESH_RIGHT_IRIS:
# face_connection_spec[edge] = right_iris_draw
for edge in mp_face_mesh.FACEMESH_LIPS:
face_connection_spec[edge] = mouth_draw
iris_landmark_spec = {468: right_iris_draw, 473: left_iris_draw}
def draw_pupils(image, landmark_list, drawing_spec, halfwidth: int = 2):
"""We have a custom function to draw the pupils because the mp.draw_landmarks method requires a parameter for all
landmarks. Until our PR is merged into mediapipe, we need this separate method."""
if len(image.shape) != 3:
raise ValueError("Input image must be H,W,C.")
image_rows, image_cols, image_channels = image.shape
if image_channels != 3: # BGR channels
raise ValueError('Input image must contain three channel bgr data.')
for idx, landmark in enumerate(landmark_list.landmark):
if (
(landmark.HasField('visibility') and landmark.visibility < 0.9) or
(landmark.HasField('presence') and landmark.presence < 0.5)
):
continue
if landmark.x >= 1.0 or landmark.x < 0 or landmark.y >= 1.0 or landmark.y < 0:
continue
image_x = int(image_cols*landmark.x)
image_y = int(image_rows*landmark.y)
draw_color = None
if isinstance(drawing_spec, Mapping):
if drawing_spec.get(idx) is None:
continue
else:
draw_color = drawing_spec[idx].color
elif isinstance(drawing_spec, DrawingSpec):
draw_color = drawing_spec.color
image[image_y-halfwidth:image_y+halfwidth, image_x-halfwidth:image_x+halfwidth, :] = draw_color
def reverse_channels(image):
"""Given a numpy array in RGB form, convert to BGR. Will also convert from BGR to RGB."""
# im[:,:,::-1] is a neat hack to convert BGR to RGB by reversing the indexing order.
# im[:,:,::[2,1,0]] would also work but makes a copy of the data.
return image[:, :, ::-1]
def generate_annotation(
input_image: Image.Image,
max_faces: int,
min_face_size_pixels: int = 0,
return_annotation_data: bool = False
):
"""
Find up to 'max_faces' inside the provided input image.
If min_face_size_pixels is provided and nonzero it will be used to filter faces that occupy less than this many
pixels in the image.
If return_annotation_data is TRUE (default: false) then in addition to returning the 'detected face' image, three
additional parameters will be returned: faces before filtering, faces after filtering, and an annotation image.
The faces_before_filtering return value is the number of faces detected in an image with no filtering.
faces_after_filtering is the number of faces remaining after filtering small faces.
:return:
If 'return_annotation_data==True', returns (numpy array, numpy array, int, int).
If 'return_annotation_data==False' (default), returns a numpy array.
"""
with mp_face_mesh.FaceMesh(
static_image_mode=True,
max_num_faces=max_faces,
refine_landmarks=True,
min_detection_confidence=0.5,
) as facemesh:
img_rgb = numpy.asarray(input_image)
results = facemesh.process(img_rgb).multi_face_landmarks
if results is None:
return None
faces_found_before_filtering = len(results)
# Filter faces that are too small
filtered_landmarks = []
for lm in results:
landmarks = lm.landmark
face_rect = [
landmarks[0].x,
landmarks[0].y,
landmarks[0].x,
landmarks[0].y,
] # Left, up, right, down.
for i in range(len(landmarks)):
face_rect[0] = min(face_rect[0], landmarks[i].x)
face_rect[1] = min(face_rect[1], landmarks[i].y)
face_rect[2] = max(face_rect[2], landmarks[i].x)
face_rect[3] = max(face_rect[3], landmarks[i].y)
if min_face_size_pixels > 0:
face_width = abs(face_rect[2] - face_rect[0])
face_height = abs(face_rect[3] - face_rect[1])
face_width_pixels = face_width * input_image.size[0]
face_height_pixels = face_height * input_image.size[1]
face_size = min(face_width_pixels, face_height_pixels)
if face_size >= min_face_size_pixels:
filtered_landmarks.append(lm)
else:
filtered_landmarks.append(lm)
faces_remaining_after_filtering = len(filtered_landmarks)
# Annotations are drawn in BGR for some reason, but we don't need to flip a zero-filled image at the start.
empty = numpy.zeros_like(img_rgb)
# Draw detected faces:
for face_landmarks in filtered_landmarks:
mp_drawing.draw_landmarks(
empty,
face_landmarks,
connections=face_connection_spec.keys(),
landmark_drawing_spec=None,
connection_drawing_spec=face_connection_spec
)
draw_pupils(empty, face_landmarks, iris_landmark_spec, 2)
# Flip BGR back to RGB.
empty = reverse_channels(empty)
# We might have to generate a composite.
if return_annotation_data:
# Note that we're copying the input image AND flipping the channels so we can draw on top of it.
annotated = reverse_channels(numpy.asarray(input_image)).copy()
for face_landmarks in filtered_landmarks:
mp_drawing.draw_landmarks(
empty,
face_landmarks,
connections=face_connection_spec.keys(),
landmark_drawing_spec=None,
connection_drawing_spec=face_connection_spec
)
draw_pupils(empty, face_landmarks, iris_landmark_spec, 2)
annotated = reverse_channels(annotated)
if not return_annotation_data:
return empty
else:
return empty, annotated, faces_found_before_filtering, faces_remaining_after_filtering
def mask_color_and_add_strokes(image_path, target_color, stroke_color=(0, 0, 255), tolerance=15, stroke_width=3):
"""
Masks a specific color in an image and adds a stroke to the remaining lines.
:param image_path: Path to the image file.
:param target_color: The color to mask as a BGR tuple, e.g., (B, G, R).
:param stroke_color: The color of the stroke as a BGR tuple.
:param tolerance: Tolerance for color masking.
:param stroke_width: Width of the stroke.
:return: Image with color masked and strokes added.
"""
# Load the image
image = image_path
# Convert the target color to numpy array
target_color = np.array(target_color)
# Define the lower and upper bounds for the color to mask
lower_bound = np.clip(target_color - tolerance, 0, 255)
upper_bound = np.clip(target_color + tolerance, 0, 255)
# Create a mask and apply it to the image
mask = cv2.inRange(image, lower_bound, upper_bound)
result = cv2.bitwise_and(image, image, mask=mask)
# Detect edges in the image
edges = cv2.Canny(result, 100, 200)
# Create a stroke effect
kernel = np.ones((stroke_width, stroke_width), np.uint8)
dilated_edges = cv2.dilate(edges, kernel, iterations=1)
# Draw strokes on the image
result[dilated_edges > 0] = stroke_color
return result
# https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869
import PIL
def interp(t):
return 3 * t**2 - 2 * t ** 3
def perlin(width, height, scale=10, device=None):
gx, gy = torch.randn(2, width + 1, height + 1, 1, 1, device=device)
xs = torch.linspace(0, 1, scale + 1)[:-1, None].to(device)
ys = torch.linspace(0, 1, scale + 1)[None, :-1].to(device)
wx = 1 - interp(xs)
wy = 1 - interp(ys)
dots = 0
dots += wx * wy * (gx[:-1, :-1] * xs + gy[:-1, :-1] * ys)
dots += (1 - wx) * wy * (-gx[1:, :-1] * (1 - xs) + gy[1:, :-1] * ys)
dots += wx * (1 - wy) * (gx[:-1, 1:] * xs - gy[:-1, 1:] * (1 - ys))
dots += (1 - wx) * (1 - wy) * (-gx[1:, 1:] * (1 - xs) - gy[1:, 1:] * (1 - ys))
return dots.permute(0, 2, 1, 3).contiguous().view(width * scale, height * scale)
def perlin_ms(octaves, width, height, grayscale, device=device):
out_array = [0.5] if grayscale else [0.5, 0.5, 0.5]
# out_array = [0.0] if grayscale else [0.0, 0.0, 0.0]
for i in range(1 if grayscale else 3):
scale = 2 ** len(octaves)
oct_width = width
oct_height = height
for oct in octaves:
p = perlin(oct_width, oct_height, scale, device)
out_array[i] += p * oct
scale //= 2
oct_width *= 2
oct_height *= 2
return torch.cat(out_array)
def create_perlin_noise(octaves=[1, 1, 1, 1], width=2, height=2, grayscale=True):
out = perlin_ms(octaves, width, height, grayscale)
if grayscale:
out = TF.resize(size=(side_y, side_x), img=out.unsqueeze(0))
out = TF.to_pil_image(out.clamp(0, 1)).convert('RGB')
else:
out = out.reshape(-1, 3, out.shape[0]//3, out.shape[1])
out = TF.resize(size=(side_y, side_x), img=out)
out = TF.to_pil_image(out.clamp(0, 1).squeeze())
out = ImageOps.autocontrast(out)
return out
# def regen_perlin():
# if perlin_mode == 'color':
# init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
# init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False)
# elif perlin_mode == 'gray':
# init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True)
# init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
# else:
# init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
# init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
# init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1)
# del init2
# return init.expand(batch_size, -1, -1, -1)
def fetch(url_or_path):
if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'):
r = requests.get(url_or_path)
r.raise_for_status()
fd = io.BytesIO()
fd.write(r.content)
fd.seek(0)
return fd
return open(url_or_path, 'rb')
def read_image_workaround(path):
"""OpenCV reads images as BGR, Pillow saves them as RGB. Work around
this incompatibility to avoid colour inversions."""
im_tmp = cv2.imread(path)
return cv2.cvtColor(im_tmp, cv2.COLOR_BGR2RGB)
def parse_prompt(prompt):
if prompt.startswith('http://') or prompt.startswith('https://'):
vals = prompt.rsplit(':', 2)
vals = [vals[0] + ':' + vals[1], *vals[2:]]
else:
vals = prompt.rsplit(':', 1)
vals = vals + ['', '1'][len(vals):]
return vals[0], float(vals[1])
def sinc(x):
return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([]))
def lanczos(x, a):
cond = torch.logical_and(-a < x, x < a)
out = torch.where(cond, sinc(x) * sinc(x/a), x.new_zeros([]))
return out / out.sum()
def ramp(ratio, width):
n = math.ceil(width / ratio + 1)
out = torch.empty([n])
cur = 0
for i in range(out.shape[0]):
out[i] = cur
cur += ratio
return torch.cat([-out[1:].flip([0]), out])[1:-1]
def resample(input, size, align_corners=True):
n, c, h, w = input.shape
dh, dw = size
input = input.reshape([n * c, 1, h, w])
if dh < h:
kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype)
pad_h = (kernel_h.shape[0] - 1) // 2
input = F.pad(input, (0, 0, pad_h, pad_h), 'reflect')
input = F.conv2d(input, kernel_h[None, None, :, None])
if dw < w:
kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype)
pad_w = (kernel_w.shape[0] - 1) // 2
input = F.pad(input, (pad_w, pad_w, 0, 0), 'reflect')
input = F.conv2d(input, kernel_w[None, None, None, :])
input = input.reshape([n, c, h, w])
return F.interpolate(input, size, mode='bicubic', align_corners=align_corners)
class MakeCutouts(nn.Module):
def __init__(self, cut_size, cutn, skip_augs=False):
super().__init__()
self.cut_size = cut_size
self.cutn = cutn
self.skip_augs = skip_augs
self.augs = T.Compose([
T.RandomHorizontalFlip(p=0.5),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomAffine(degrees=15, translate=(0.1, 0.1)),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomPerspective(distortion_scale=0.4, p=0.7),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomGrayscale(p=0.15),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
# T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),
])
def forward(self, input):
input = T.Pad(input.shape[2]//4, fill=0)(input)
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
cutouts = []
for ch in range(self.cutn):
if ch > self.cutn - self.cutn//4:
cutout = input.clone()
else:
size = int(max_size * torch.zeros(1,).normal_(mean=.8, std=.3).clip(float(self.cut_size/max_size), 1.))
offsetx = torch.randint(0, abs(sideX - size + 1), ())
offsety = torch.randint(0, abs(sideY - size + 1), ())
cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]
if not self.skip_augs:
cutout = self.augs(cutout)
cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
del cutout
cutouts = torch.cat(cutouts, dim=0)
return cutouts
cutout_debug = False
padargs = {}
class MakeCutoutsDango(nn.Module):
def __init__(self, cut_size,
Overview=4,
InnerCrop = 0, IC_Size_Pow=0.5, IC_Grey_P = 0.2
):
super().__init__()
self.cut_size = cut_size
self.Overview = Overview
self.InnerCrop = InnerCrop
self.IC_Size_Pow = IC_Size_Pow
self.IC_Grey_P = IC_Grey_P
if args.animation_mode == 'None':
self.augs = T.Compose([
T.RandomHorizontalFlip(p=0.5),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomGrayscale(p=0.1),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),
])
elif args.animation_mode == 'Video Input Legacy':
self.augs = T.Compose([
T.RandomHorizontalFlip(p=0.5),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomAffine(degrees=15, translate=(0.1, 0.1)),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomPerspective(distortion_scale=0.4, p=0.7),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomGrayscale(p=0.15),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
# T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),
])
elif args.animation_mode == '2D' or args.animation_mode == 'Video Input':
self.augs = T.Compose([
T.RandomHorizontalFlip(p=0.4),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomGrayscale(p=0.1),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.3),
])
def forward(self, input):
cutouts = []
gray = T.Grayscale(3)
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
l_size = max(sideX, sideY)
output_shape = [1,3,self.cut_size,self.cut_size]
output_shape_2 = [1,3,self.cut_size+2,self.cut_size+2]
pad_input = F.pad(input,((sideY-max_size)//2,(sideY-max_size)//2,(sideX-max_size)//2,(sideX-max_size)//2), **padargs)
cutout = resize(pad_input, out_shape=output_shape)
if self.Overview>0:
if self.Overview<=4:
if self.Overview>=1:
cutouts.append(cutout)
if self.Overview>=2:
cutouts.append(gray(cutout))
if self.Overview>=3:
cutouts.append(TF.hflip(cutout))
if self.Overview==4:
cutouts.append(gray(TF.hflip(cutout)))
else:
cutout = resize(pad_input, out_shape=output_shape)
for _ in range(self.Overview):
cutouts.append(cutout)
if cutout_debug:
if is_colab:
TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("/content/cutout_overview0.jpg",quality=99)
else:
TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("cutout_overview0.jpg",quality=99)
if self.InnerCrop >0:
for i in range(self.InnerCrop):
size = int(torch.rand([])**self.IC_Size_Pow * (max_size - min_size) + min_size)
offsetx = torch.randint(0, sideX - size + 1, ())
offsety = torch.randint(0, sideY - size + 1, ())
cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]
if i <= int(self.IC_Grey_P * self.InnerCrop):
cutout = gray(cutout)
cutout = resize(cutout, out_shape=output_shape)
cutouts.append(cutout)
if cutout_debug:
if is_colab:
TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("/content/cutout_InnerCrop.jpg",quality=99)
else:
TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("cutout_InnerCrop.jpg",quality=99)
cutouts = torch.cat(cutouts)
if skip_augs is not True: cutouts=self.augs(cutouts)
return cutouts
def spherical_dist_loss(x, y):
x = F.normalize(x, dim=-1)
y = F.normalize(y, dim=-1)
return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
def tv_loss(input):
"""L2 total variation loss, as in Mahendran et al."""
input = F.pad(input, (0, 1, 0, 1), 'replicate')
x_diff = input[..., :-1, 1:] - input[..., :-1, :-1]
y_diff = input[..., 1:, :-1] - input[..., :-1, :-1]
return (x_diff**2 + y_diff**2).mean([1, 2, 3])
def get_image_from_lat(lat):
img = sd_model.decode_first_stage(lat.cuda())[0]
return TF.to_pil_image(img.add(1).div(2).clamp(0, 1))
def get_lat_from_pil(frame):
print(frame.shape, 'frame2pil.shape')
frame = np.array(frame)
frame = (frame/255.)[None,...].transpose(0, 3, 1, 2)
frame = 2*torch.from_numpy(frame).float().cuda()-1.
return sd_model.get_first_stage_encoding(sd_model.encode_first_stage(frame))
def range_loss(input):
return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3])
stop_on_next_loop = False # Make sure GPU memory doesn't get corrupted from cancelling the run mid-way through, allow a full frame to complete
TRANSLATION_SCALE = 1.0/200.0
def get_sched_from_json(frame_num, sched_json, blend=False):
frame_num = int(frame_num)
frame_num = max(frame_num, 0)
sched_int = {}
for key in sched_json.keys():
sched_int[int(key)] = sched_json[key]
sched_json = sched_int
keys = sorted(list(sched_json.keys())); #print(keys)
if frame_num<0:
frame_num = max(keys)
try:
frame_num = min(frame_num,max(keys)) #clamp frame num to 0:max(keys) range
except:
pass
# print('clamped frame num ', frame_num)
if frame_num in keys: