forked from pixray/pixray
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pixray.py
executable file
·2063 lines (1757 loc) · 81.4 KB
/
pixray.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
import argparse
import json
import math
import logging
from urllib.request import urlopen
import sys
import os
import subprocess
import json
import yaml
import glob
from braceexpand import braceexpand
from types import SimpleNamespace
import os.path
from omegaconf import OmegaConf
import hashlib
import time
import torch
from torch import nn, optim
from torch.nn import functional as F
from torchvision import transforms
from torchvision.transforms import functional as TF
from torchvision.utils import save_image
torch.backends.cudnn.benchmark = False # NR: True is a bit faster, but can lead to OOM. False is more deterministic.
#torch.use_deterministic_algorithms(True) # NR: grid_sampler_2d_backward_cuda does not have a deterministic implementation
from torch_optimizer import DiffGrad, AdamP
from perlin_numpy import generate_fractal_noise_2d
from util import str2bool, get_file_path, emit_filename
from slip import get_clip_perceptor
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
# installed by doing `pip install git+https://github.com/openai/CLIP`
from clip import clip
import kornia
import kornia.augmentation as K
import numpy as np
import imageio
import re
import random
from einops import rearrange
from filters.colorlookup import ColorLookup
from filters.wallpaper import WallpaperFilter
from filters.tiler import TilerFilter
filters_class_table = {
"lookup": ColorLookup,
"tiler": TilerFilter,
"wallpaper": WallpaperFilter,
}
from PIL import ImageFile, Image, PngImagePlugin
ImageFile.LOAD_TRUNCATED_IMAGES = True
# or 'border'
global_padding_mode = 'reflection'
global_aspect_width = 1
global_spot_file = None
from util import map_number, palette_from_string, real_glob
from vqgan import VqganDrawer
from vdiff import VdiffDrawer
class_table = {
"vqgan": VqganDrawer,
"vdiff": VdiffDrawer,
}
try:
from super_resolution import SuperResolutionDrawer
class_table.update({"super_resolution": SuperResolutionDrawer})
except ImportError as e:
print("--> Super resolution drawer not supported", e)
pass
try:
from fftdrawer import FftDrawer
# update class_table if these import OK
class_table.update({"fft": FftDrawer})
except ImportError as e:
print("--> Not running with fft support", e)
pass
try:
from clipdrawer import ClipDrawer
from pixeldrawer import PixelDrawer
from linedrawer import LineDrawer
# update class_table if these import OK
class_table.update({
"line_sketch": LineDrawer,
"pixel": PixelDrawer,
"clipdraw": ClipDrawer
})
except ImportError as e:
print("--> Not running with pydiffvg drawer support ", e)
pass
try:
import matplotlib.colors
except ImportError:
# only needed for palette stuff
pass
from Losses.LossInterface import LossInterface
from Losses.PaletteLoss import PaletteLoss
from Losses.SaturationLoss import SaturationLoss
from Losses.SymmetryLoss import SymmetryLoss
from Losses.SmoothnessLoss import SmoothnessLoss
from Losses.EdgeLoss import EdgeLoss
from Losses.StyleLoss import StyleLoss
from Losses.ResmemLoss import ResmemLoss
from Losses.AestheticLoss import AestheticLoss
loss_class_table = {
"palette": PaletteLoss,
"saturation": SaturationLoss,
"symmetry": SymmetryLoss,
"smoothness": SmoothnessLoss,
"edge": EdgeLoss,
"style": StyleLoss,
"resmem": ResmemLoss,
"aesthetic": AestheticLoss,
}
# this is enabled when not in the master branch
# print("warning: running unreleased future version")
# https://stackoverflow.com/a/39662359
def isnotebook():
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'Shell':
return True # Seems to be what co-lab does
elif shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
else:
return False # Other type (?)
except NameError:
return False # Probably standard Python interpreter
IS_NOTEBOOK = isnotebook()
if IS_NOTEBOOK:
from IPython import display
from tqdm.notebook import tqdm
from IPython.display import clear_output
else:
from tqdm import tqdm
# Functions and classes
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]
# NR: Testing with different intital images
def old_random_noise_image(w,h):
random_image = Image.fromarray(np.random.randint(0,255,(w,h,3),dtype=np.dtype('uint8')))
return random_image
def NormalizeData(data):
return (data - np.min(data)) / (np.max(data) - np.min(data))
# https://stats.stackexchange.com/a/289477
def contrast_noise(n):
n = 0.9998 * n + 0.0001
n1 = (n / (1-n))
n2 = np.power(n1, -2)
n3 = 1 / (1 + n2)
return n3
def random_noise_image(w,h):
# scale up roughly as power of 2
if (w>1024 or h>1024):
side, octp = 2048, 6
elif (w>512 or h>512):
side, octp = 1024, 5
elif (w>256 or h>256):
side, octp = 512, 4
else:
side, octp = 256, 3
nr = NormalizeData(generate_fractal_noise_2d((side, side), (32, 32), octp))
ng = NormalizeData(generate_fractal_noise_2d((side, side), (32, 32), octp))
nb = NormalizeData(generate_fractal_noise_2d((side, side), (32, 32), octp))
stack = np.dstack((contrast_noise(nr),contrast_noise(ng),contrast_noise(nb)))
substack = stack[:h, :w, :]
im = Image.fromarray((255.999 * substack).astype('uint8'))
return im
# testing
def gradient_2d(start, stop, width, height, is_horizontal):
if is_horizontal:
return np.tile(np.linspace(start, stop, width), (height, 1))
else:
return np.tile(np.linspace(start, stop, height), (width, 1)).T
def gradient_3d(width, height, start_list, stop_list, is_horizontal_list):
result = np.zeros((height, width, len(start_list)), dtype=float)
for i, (start, stop, is_horizontal) in enumerate(zip(start_list, stop_list, is_horizontal_list)):
result[:, :, i] = gradient_2d(start, stop, width, height, is_horizontal)
return result
def random_gradient_image(w,h):
array = gradient_3d(w, h, (0, 0, np.random.randint(0,255)), (np.random.randint(1,255), np.random.randint(2,255), np.random.randint(3,128)), (True, False, False))
random_image = Image.fromarray(np.uint8(array))
return random_image
class ReplaceGrad(torch.autograd.Function):
@staticmethod
def forward(ctx, x_forward, x_backward):
ctx.shape = x_backward.shape
return x_forward
@staticmethod
def backward(ctx, grad_in):
return None, grad_in.sum_to_size(ctx.shape)
replace_grad = ReplaceGrad.apply
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)
class Prompt(nn.Module):
def __init__(self, embed, weight=1., stop=float('-inf')):
super().__init__()
self.register_buffer('embed', embed)
self.register_buffer('weight', torch.as_tensor(weight))
self.register_buffer('stop', torch.as_tensor(stop))
def forward(self, input):
input_normed = F.normalize(input.unsqueeze(1), dim=2)
embed_normed = F.normalize(self.embed.unsqueeze(0), dim=2)
dists = input_normed.sub(embed_normed).norm(dim=2).div(2).arcsin().pow(2).mul(2)
dists = dists * self.weight.sign()
return self.weight.abs() * replace_grad(dists, torch.maximum(dists, self.stop)).mean()
# https://stackoverflow.com/q/354038
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def parse_prompt(prompt):
"""Prompts can either just be text, be a text:weight pair, or a text:weight:stop triple"""
# defaults
textPrompt = prompt
weight = 1
stop = float('-inf')
# try to parse numbers from the right but stop as soon as that fails
extra_numbers = []
keep_going = True
while len(extra_numbers) < 2 and keep_going:
vals = textPrompt.rsplit(':', 1)
if len(vals) > 1 and is_number(vals[1]):
extra_numbers.append(float(vals[1]))
textPrompt = vals[0]
else:
keep_going = False
# print(f"parsed nums is {textPrompt}, {extra_numbers}")
# if there is only 1 number, that becomes the weight
if len(extra_numbers) == 1:
weight = extra_numbers[0]
# if there are two numbers it is weight and stop (stored backwards)
elif len(extra_numbers) == 2:
weight = extra_numbers[1]
stop = extra_numbers[0]
# print(f"parsed vals is {textPrompt}, {weight}, {stop}")
return textPrompt, weight, stop
from typing import cast, Dict, List, Optional, Tuple, Union
# override class to get padding_mode
class MyRandomPerspective(K.RandomPerspective):
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
_, _, height, width = input.shape
transform = cast(torch.Tensor, transform)
return kornia.geometry.transform.warp_perspective(
input, transform, (height, width), mode=self.flags["resample"].name.lower(),
align_corners=self.flags["align_corners"], padding_mode=global_padding_mode
)
global_fill_color=None;
# override class to get fill color
class MyRandomAffine(K.RandomAffine):
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
_, _, height, width = input.shape
transform = cast(torch.Tensor, transform)
return kornia.geometry.transform.warp_affine(
input,
transform[:, :2, :],
(height, width),
self.flags["resample"].name.lower(),
align_corners=self.flags["align_corners"],
padding_mode="fill",
fill_value=global_fill_color
)
class MyRandomPerspectivePadded(K.RandomPerspective):
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
_, _, height, width = input.shape
transform = cast(torch.Tensor, transform)
return kornia.geometry.transform.warp_perspective(
input, transform, (height, width), mode=self.flags["resample"].name.lower(),
align_corners=self.flags["align_corners"],
padding_mode="fill",
fill_value=global_fill_color
)
cached_spot_indexes = {}
def fetch_spot_indexes(sideX, sideY):
global global_spot_file
# make sure image is loaded if we need it
cache_key = (sideX, sideY)
if cache_key not in cached_spot_indexes:
if global_spot_file is not None:
mask_image = Image.open(global_spot_file)
elif global_aspect_width != 1:
mask_image = Image.open("inputs/spot_wide.png")
else:
mask_image = Image.open("inputs/spot_square.png")
# this is a one channel mask
mask_image = mask_image.convert('RGB')
mask_image = mask_image.resize((sideX, sideY), Image.LANCZOS)
mask_image_tensor = TF.to_tensor(mask_image)
# print("ONE CHANNEL ", mask_image_tensor.shape)
mask_indexes = mask_image_tensor.ge(0.5).to(device)
# print("GE ", mask_indexes.shape)
# sys.exit(0)
mask_indexes_off = mask_image_tensor.lt(0.5).to(device)
cached_spot_indexes[cache_key] = [mask_indexes, mask_indexes_off]
return cached_spot_indexes[cache_key]
# n = torch.ones((3,5,5))
# f = generate.fetch_spot_indexes(5, 5)
# f[0].shape = [60,3]
class MakeCutouts(nn.Module):
def __init__(self, cut_size, cutn, cut_pow=1.):
global global_aspect_width
super().__init__()
self.cut_size = cut_size
self.cutn = cutn
self.cutn_zoom = int(0.6*cutn)
self.cut_pow = cut_pow
self.transforms = None
augmentations = []
# if global_aspect_width != 1:
# augmentations.append(K.RandomCrop(size=(self.cut_size,self.cut_size), p=1.0, cropping_mode="resample", return_transform=True))
augmentations.append(MyRandomPerspective(distortion_scale=0.40, p=0.7, return_transform=True))
augmentations.append(K.RandomResizedCrop(size=(self.cut_size,self.cut_size), scale=(0.25,0.95), ratio=(0.85,1.2), cropping_mode='resample', p=1.0, return_transform=True))
augmentations.append(K.ColorJitter(hue=0.1, saturation=0.1, p=0.8, return_transform=True))
self.augs_zoom = nn.Sequential(*augmentations)
augmentations = []
if global_aspect_width == 1:
n_s = 0.95
n_t = (1-n_s)/2
augmentations.append(MyRandomAffine(degrees=0, translate=(n_t, n_t), scale=(n_s, n_s), p=1.0, return_transform=True))
elif global_aspect_width > 1:
n_s = 1/global_aspect_width
n_t = (1-n_s)/2
augmentations.append(MyRandomAffine(degrees=0, translate=(0, n_t), scale=(0.9*n_s, n_s), p=1.0, return_transform=True))
else:
n_s = global_aspect_width
n_t = (1-n_s)/2
augmentations.append(MyRandomAffine(degrees=0, translate=(n_t, 0), scale=(0.9*n_s, n_s), p=1.0, return_transform=True))
# augmentations.append(K.CenterCrop(size=(self.cut_size,self.cut_size), p=1.0, cropping_mode="resample", return_transform=True))
augmentations.append(K.CenterCrop(size=self.cut_size, cropping_mode='resample', p=1.0, return_transform=True))
augmentations.append(MyRandomPerspectivePadded(distortion_scale=0.20, p=0.7, return_transform=True))
augmentations.append(K.ColorJitter(hue=0.1, saturation=0.1, p=0.8, return_transform=True))
self.augs_wide = nn.Sequential(*augmentations)
self.noise_fac = 0.1
# Pooling
self.av_pool = nn.AdaptiveAvgPool2d((self.cut_size, self.cut_size))
self.max_pool = nn.AdaptiveMaxPool2d((self.cut_size, self.cut_size))
def forward(self, input, spot=None):
global global_aspect_width, cur_iteration
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
cutouts = []
mask_indexes = None
if spot is not None:
spot_indexes = fetch_spot_indexes(self.cut_size, self.cut_size)
if spot == 0:
mask_indexes = spot_indexes[1]
else:
mask_indexes = spot_indexes[0]
# print("Mask indexes ", mask_indexes)
for _ in range(self.cutn):
# Pooling
cutout = (self.av_pool(input) + self.max_pool(input))/2
if mask_indexes is not None:
cutout[0][mask_indexes] = 0.0 # 0.5
if global_aspect_width != 1:
if global_aspect_width > 1:
cutout = kornia.geometry.transform.rescale(cutout, (1, global_aspect_width))
else:
cutout = kornia.geometry.transform.rescale(cutout, (1/global_aspect_width, 1))
# if cur_iteration % 50 == 0 and _ == 0:
# print(cutout.shape)
# TF.to_pil_image(cutout[0].cpu()).save(f"cutout_im_{cur_iteration:02d}_{spot}.png")
cutouts.append(cutout)
if self.transforms is not None:
# print("Cached transforms available")
batch1 = kornia.geometry.transform.warp_perspective(torch.cat(cutouts[:self.cutn_zoom], dim=0), self.transforms[:self.cutn_zoom],
(self.cut_size, self.cut_size), padding_mode=global_padding_mode)
batch2 = kornia.geometry.transform.warp_perspective(torch.cat(cutouts[self.cutn_zoom:], dim=0), self.transforms[self.cutn_zoom:],
(self.cut_size, self.cut_size), padding_mode="fill", fill_value=global_fill_color)
batch = torch.cat([batch1, batch2])
# if cur_iteration < 2:
# for j in range(4):
# TF.to_pil_image(batch[j].cpu()).save(f"cached_im_{cur_iteration:02d}_{j:02d}_{spot}.png")
# j_wide = j + self.cutn_zoom
# TF.to_pil_image(batch[j_wide].cpu()).save(f"cached_im_{cur_iteration:02d}_{j_wide:02d}_{spot}.png")
else:
batch1, transforms1 = self.augs_zoom(torch.cat(cutouts[:self.cutn_zoom], dim=0))
batch2, transforms2 = self.augs_wide(torch.cat(cutouts[self.cutn_zoom:], dim=0))
# print(batch1.shape, batch2.shape)
batch = torch.cat([batch1, batch2])
# print(batch.shape)
self.transforms = torch.cat([transforms1, transforms2])
## batch, self.transforms = self.augs(torch.cat(cutouts, dim=0))
# if cur_iteration < 4:
# for j in range(4):
# TF.to_pil_image(batch[j].cpu()).save(f"live_im_{cur_iteration:02d}_{j:02d}_{spot}.png")
# j_wide = j + self.cutn_zoom
# TF.to_pil_image(batch[j_wide].cpu()).save(f"live_im_{cur_iteration:02d}_{j_wide:02d}_{spot}.png")
# print(batch.shape, self.transforms.shape)
if self.noise_fac:
facs = batch.new_empty([self.cutn, 1, 1, 1]).uniform_(0, self.noise_fac)
batch = batch + facs * torch.randn_like(batch)
return batch
def resize_image(image, out_size):
ratio = image.size[0] / image.size[1]
area = min(image.size[0] * image.size[1], out_size[0] * out_size[1])
size = round((area * ratio)**0.5), round((area / ratio)**0.5)
return image.resize(size, Image.LANCZOS)
def rebuild_optimisers(args):
global best_loss, best_iter, best_z, num_loss_drop, max_loss_drops, iter_drop_delay
global drawer, filters
drop_divisor = 10 ** num_loss_drop
new_opts = drawer.get_opts(drop_divisor)
if new_opts == None:
# legacy
dropped_learning_rate = args.learning_rate/drop_divisor;
# print(f"Optimizing with {args.optimiser} set to {dropped_learning_rate}")
#temporary hack
if args.init_image and args.drawer=="vdiff":
dropped_learning_rate = 0.01/drop_divisor
# Set the optimiser
to_optimize = [ drawer.get_z() ]
if args.optimiser == "Adam":
opt = optim.Adam(to_optimize, lr=dropped_learning_rate) # LR=0.1
elif args.optimiser == "AdamW":
opt = optim.AdamW(to_optimize, lr=dropped_learning_rate) # LR=0.2
elif args.optimiser == "Adagrad":
opt = optim.Adagrad(to_optimize, lr=dropped_learning_rate) # LR=0.5+
elif args.optimiser == "Adamax":
opt = optim.Adamax(to_optimize, lr=dropped_learning_rate) # LR=0.5+?
elif args.optimiser == "DiffGrad":
opt = DiffGrad(to_optimize, lr=dropped_learning_rate) # LR=2+?
elif args.optimiser == "AdamP":
opt = AdamP(to_optimize, lr=dropped_learning_rate) # LR=2+?
# elif args.optimiser == "RAdam":
# opt = RAdam(to_optimize, lr=dropped_learning_rate) # LR=2+?
new_opts = [opt]
return new_opts
# used for target image
def fetch_images(preprocess, image_files):
images = []
for filename in image_files:
image = preprocess(Image.open(filename).convert("RGB"))
images.append(image)
return images
def do_image_features(model, images, image_mean, image_std):
image_input = torch.tensor(np.stack(images)).cuda()
image_input -= image_mean[:, None, None]
image_input /= image_std[:, None, None]
with torch.no_grad():
image_features = model.encode_image(image_input).float()
return image_features
# note: this should probably be split into a setup and a session init
def do_init(args):
global opts, perceptors, normalize, cutoutsTable, cutoutSizeTable
global z_orig, im_targets, z_labels, init_image_tensor, target_image_tensor
global gside_X, gside_Y, overlay_image_rgba, overlay_image_rgba_list, init_image_rgba_list
global pmsTable, pmsImageTable, pmsTargetTable, pImages, device, spotPmsTable, spotOffPmsTable
global drawer, filters
global lossGlobals, global_cached_png_info, global_seed_used
reset_session_globals()
# do seed first!
if args.seed is None:
seed = torch.seed()
elif isinstance(args.seed, int):
seed = args.seed
elif isinstance(args.seed, str) and args.seed.isdigit():
seed = int(args.seed)
else:
# deterministic 32 bit int from string
# https://stackoverflow.com/a/44556106/1010653
e_str = args.seed.encode()
hash_digest = hashlib.sha512(e_str).digest()
seed = int.from_bytes(hash_digest, 'big') % 0x100000000
int_seed = int(seed)%(2**30)
print('Using seed:', seed)
global_seed_used = seed
torch.manual_seed(seed)
np.random.seed(int_seed)
random.seed(int_seed)
# set device only once
if device is None:
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
drawer = class_table[args.drawer](args)
drawer.load_model(args, device)
num_resolutions = drawer.get_num_resolutions()
# print("-----------> NUMR ", num_resolutions)
#as of torch 1.8, jit produces errors. The below code no longer works with 1.10
#jit = True if float(torch.__version__[:3]) < 1.8 else False
jit = False
if num_resolutions!=None:
f = 2**(num_resolutions - 1)
toksX, toksY = args.size[0] // f, args.size[1] // f
sideX, sideY = toksX * f, toksY * f
else:
sideX, sideY = args.size[0], args.size[1]
# save sideX, sideY in globals (need if using overlay)
gside_X = sideX
gside_Y = sideY
# model loading optimization: if all models are loaded keep things as they are
if set(args.clip_models) <= set(perceptors.keys()):
print("All CLIP models already loaded: ", args.clip_models)
else:
# TODO: unload models?
perceptors = {}
for clip_model in args.clip_models:
perceptor = get_clip_perceptor(clip_model, device)
perceptors[clip_model] = perceptor
# now separately setup cuts
for clip_model in args.clip_models:
perceptor = perceptors[clip_model]
cut_size = perceptor.input_resolution
cutoutSizeTable[clip_model] = cut_size
if not cut_size in cutoutsTable:
make_cutouts = MakeCutouts(cut_size, args.num_cuts, cut_pow=args.cut_pow)
cutoutsTable[cut_size] = make_cutouts
filters = None
if args.filters is not None:
filter_names = args.filters.split(",")
filter_names = [f.strip() for f in filter_names]
filterClasses = []
for filt in filter_names:
filt_name, weight, stop = parse_prompt(filt)
if filt_name not in filters_class_table:
raise ValueError(f"Requested filter not found, aborting: {filt_name}")
filtClass = filters_class_table[filt_name]
# do special initializations here
try:
filtInstance = filtClass(args, device=device)
filterClasses.append({"filter":filtInstance, "weight": weight})
except TypeError as e:
print(f'error in initializing {filtClass} - this message is to provide information')
raise TypeError(e)
filters = filterClasses
init_image_tensor = None
target_image_tensor = None
# Image initialisation
if args.init_image or args.init_noise:
# setup init image wih pil
# first - always start with noise or blank
if args.init_noise == 'pixels':
img = random_noise_image(args.size[0], args.size[1])
elif args.init_noise == 'gradient':
img = random_gradient_image(args.size[0], args.size[1])
elif args.init_noise == 'snow':
img = old_random_noise_image(args.size[0], args.size[1])
else:
img = Image.new(mode="RGB", size=(args.size[0], args.size[1]), color=(255, 255, 255))
starting_image = img.convert('RGB')
starting_image = starting_image.resize((sideX, sideY), Image.LANCZOS)
if args.init_image:
# now we might overlay an init image
filelist = None
if 'http' in args.init_image:
init_images = [Image.open(urlopen(args.init_image))]
else:
filelist = real_glob(args.init_image)
init_images = [Image.open(f) for f in filelist]
init_image_rgba_list = []
for init_image in init_images:
# this version is needed potentially for the loss function
init_image_rgb = init_image.convert('RGB')
init_image_rgb = init_image_rgb.resize((sideX, sideY), Image.LANCZOS)
init_image_tensor = TF.to_tensor(init_image_rgb)
init_image_tensor = init_image_tensor.to(device).unsqueeze(0)
# this version gets overlaid on the background (noise)
init_image_rgba = init_image.convert('RGBA')
init_image_rgba = init_image_rgba.resize((sideX, sideY), Image.LANCZOS)
top_image = init_image_rgba.copy()
if args.init_image_alpha and args.init_image_alpha >= 0:
top_image.putalpha(args.init_image_alpha)
cur_start_image = starting_image.copy()
cur_start_image.paste(top_image, (0, 0), top_image)
init_image_rgba_list.append(cur_start_image)
starting_image = init_image_rgba_list[0]
save_image(init_image_tensor,"init_image_tensor.png")
drawer.init_from_tensor(init_image_tensor * 2 - 1)
z_orig = drawer.get_z_copy()
else:
starting_image.save("starting_image.png")
starting_tensor = TF.to_tensor(starting_image)
init_tensor = starting_tensor.to(device).unsqueeze(0)
drawer.init_from_tensor(init_tensor * 2 - 1)
else:
drawer.init_from_tensor(init_tensor=None)
# this is the old vqgan version [need to patch vqgan to do this?]
# drawer.rand_init(toksX, toksY)
if args.overlay_image is not None:
# todo: maybe split this up on pipes and whatnot
overlay_image_rgba_list = []
if 'http' in args.overlay_image:
overlay_images = [Image.open(urlopen(args.overlay_image))]
else:
filelist = real_glob(args.overlay_image)
overlay_images = [Image.open(f) for f in filelist]
for overlay_image in overlay_images:
overlay_image_rgba = overlay_image.convert('RGBA')
overlay_image_rgba = overlay_image_rgba.resize((sideX, sideY), Image.LANCZOS)
if args.overlay_alpha:
overlay_image_rgba.putalpha(args.overlay_alpha)
overlay_image_rgba_list.append(overlay_image_rgba)
overlay_image_rgba_list[0].save('overlay_image0.png')
global_cached_png_info = None
pmsTable = {}
pmsImageTable = {}
pmsTargetTable = {}
spotPmsTable = {}
spotOffPmsTable = {}
for clip_model in args.clip_models:
pmsTable[clip_model] = []
pmsImageTable[clip_model] = []
pmsTargetTable[clip_model] = []
spotPmsTable[clip_model] = []
spotOffPmsTable[clip_model] = []
drawer_clip_target = None
if hasattr(drawer, 'clip_model') and drawer.clip_model is not None:
print(f"drawer {drawer} needs {drawer.clip_model}")
drawer_clip_target = drawer.clip_model
# NR: Weights / blending
allpromptembeds = []
allweights = []
if args.target_images is not None:
if args.animation_dir is not None:
for clip_model in args.clip_models:
pmsTarget = pmsTargetTable[clip_model]
perceptor = perceptors[clip_model]
input_resolution = perceptor.input_resolution
# print(f"Running {clip_model} at {input_resolution}")
preprocess = Compose([
Resize(input_resolution, interpolation=Image.BICUBIC),
CenterCrop(input_resolution),
ToTensor()
])
image_mean = torch.tensor([0.48145466, 0.4578275, 0.40821073]).cuda()
image_std = torch.tensor([0.26862954, 0.26130258, 0.27577711]).cuda()
input_files = []
for target_image in args.target_images:
f1, weight, stop = parse_prompt(target_image)
infiles = real_glob(f1)
input_files.extend(infiles)
for path in input_files:
images = fetch_images(preprocess, [path])
features = do_image_features(perceptor, images, image_mean, image_std)
pmsTarget.append(Prompt(features, weight, stop).to(device))
else:
for clip_model in args.clip_models:
pMs = pmsTable[clip_model]
perceptor = perceptors[clip_model]
input_resolution = perceptor.input_resolution
# print(f"Running {clip_model} at {input_resolution}")
preprocess = Compose([
Resize(input_resolution, interpolation=Image.BICUBIC),
CenterCrop(input_resolution),
ToTensor()
])
image_mean = torch.tensor([0.48145466, 0.4578275, 0.40821073]).cuda()
image_std = torch.tensor([0.26862954, 0.26130258, 0.27577711]).cuda()
input_files = []
for target_image in args.target_images:
f1, weight, stop = parse_prompt(target_image)
# print("Target parse ", target_image, "to", f1)
if 'http' in f1:
# note: this is currently untested...
infile = urlopen(f1)
input_files.append(infile)
else:
infiles = real_glob(f1)
input_files.extend(infiles)
print(input_files)
images = fetch_images(preprocess, input_files);
features = do_image_features(perceptor, images, image_mean, image_std)
if clip_model == drawer_clip_target:
allpromptembeds.append(features)
allweights.append(weight)
pMs.append(Prompt(features, weight, stop).to(device))
if args.image_labels is not None:
z_labels = []
filelist = real_glob(args.image_labels)
cur_labels = []
for image_label in filelist:
image_label = Image.open(image_label)
image_label_rgb = image_label.convert('RGB')
image_label_rgb = image_label_rgb.resize((sideX, sideY), Image.LANCZOS)
image_label_rgb_tensor = TF.to_tensor(image_label_rgb)
image_label_rgb_tensor = image_label_rgb_tensor.to(device).unsqueeze(0) * 2 - 1
z_label = drawer.get_z_from_tensor(image_label_rgb_tensor)
cur_labels.append(z_label)
image_embeddings = torch.stack(cur_labels)
print("Processing labels: ", image_embeddings.shape)
image_embeddings /= image_embeddings.norm(dim=-1, keepdim=True)
image_embeddings = image_embeddings.mean(dim=0)
image_embeddings /= image_embeddings.norm()
z_labels.append(image_embeddings.unsqueeze(0))
if z_orig is not None:
z_orig = drawer.get_z_copy()
# normalize = transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],
# std=[0.26862954, 0.26130258, 0.27577711])
# CLIP tokenize/encode
for prompt in args.prompts:
for clip_model in args.clip_models:
pMs = pmsTable[clip_model]
perceptor = perceptors[clip_model]
txt, weight, stop = parse_prompt(prompt)
if txt[0] == '=':
# hack for now to test pseudo encode shim
txt = txt[1:]
print(f"--> {clip_model} encoding {txt} with stops")
actual_tokens = clip.tokenize(txt).to(device)
stops = actual_tokens.argmax(dim=-1) - 1
embed = perceptor.encode_text(actual_tokens, stops).float()
else:
# print(f"--> {clip_model} normal encoding {txt}")
embed = perceptor.encode_text(txt).float()
if clip_model == drawer_clip_target:
allpromptembeds.append(embed)
allweights.append(weight)
pMs.append(Prompt(embed, weight, stop).to(device))
if drawer_clip_target is not None:
if args.drawer=="vdiff" and args.vdiff_model[:7] == "cc12m_1":
target_embeds = torch.cat(allpromptembeds)
allweights = torch.tensor(allweights, dtype=torch.float, device=device)
clip_embed = F.normalize(target_embeds.mul(allweights[:, None]).sum(0, keepdim=True), dim=-1)
print(f"clip_embed for drawer {drawer} is {clip_embed.shape}")
drawer.sample_state[3] = {"clip_embed":clip_embed}
for vect_prompt in args.vector_prompts:
f1, weight, stop = parse_prompt(vect_prompt)
# vect_promts are by nature tuned to 10% of a normal prompt
weight = 0.1 * weight
if 'http' in f1:
# note: this is currently untested...
infile = None
infile_handle = urlopen(f1)
elif 'json' in f1:
infile = f1
else:
infile = f"vectors/{f1}.json"
if not os.path.exists(infile):
infile = f"pixray/vectors/{f1}.json"
if infile:
with open(infile) as f_in:
vect_table = json.load(f_in)
else:
vect_table = json.load(infile_handle)
for clip_model in args.clip_models:
if clip_model not in vect_table:
print(f"WARNING: no vector for {clip_model} in {f1}!")
print("Continuing without this vector... (BUT THIS RESULT MIGHT NOT BE WHAT YOU WANT 😬)")
# time.sleep(3)
continue
pMs = pmsTable[clip_model]
v = np.array(vect_table[clip_model])
embed = torch.FloatTensor(v).to(device).float()
pMs.append(Prompt(embed, weight, stop).to(device))
for prompt in args.spot_prompts:
for clip_model in args.clip_models:
pMs = spotPmsTable[clip_model]
perceptor = perceptors[clip_model]
txt, weight, stop = parse_prompt(prompt)
embed = perceptor.encode_text(txt).float()
pMs.append(Prompt(embed, weight, stop).to(device))
for prompt in args.spot_prompts_off:
for clip_model in args.clip_models:
pMs = spotOffPmsTable[clip_model]
perceptor = perceptors[clip_model]
txt, weight, stop = parse_prompt(prompt)
embed = perceptor.encode_text(txt).float()
pMs.append(Prompt(embed, weight, stop).to(device))
for label in args.labels:
for clip_model in args.clip_models:
pMs = pmsTable[clip_model]
perceptor = perceptors[clip_model]
txt, weight, stop = parse_prompt(label)
texts = [template.format(txt) for template in imagenet_templates] #format with class
# print(f"Tokenizing all of {texts}")
# texts = clip.tokenize(texts).to(device) #tokenize
class_embeddings = perceptor.encode_text(texts) #embed with text encoder
class_embeddings /= class_embeddings.norm(dim=-1, keepdim=True)
class_embedding = class_embeddings.mean(dim=0)
class_embedding /= class_embedding.norm()
pMs.append(Prompt(class_embedding.unsqueeze(0), weight, stop).to(device))
for clip_model in args.clip_models:
pImages = pmsImageTable[clip_model]
for path in args.image_prompts:
img = Image.open(path)
pil_image = img.convert('RGB')
img = resize_image(pil_image, (sideX, sideY))
pImages.append(TF.to_tensor(img).unsqueeze(0).to(device))
for seed, weight in zip(args.noise_prompt_seeds, args.noise_prompt_weights):
gen = torch.Generator().manual_seed(seed)
embed = torch.empty([1, perceptor.output_dim]).normal_(generator=gen)
pMs.append(Prompt(embed, weight).to(device))
#custom loss
if args.custom_loss is not None:
custom_losses = args.custom_loss.split(",")
custom_losses = [loss.strip() for loss in custom_losses]
custom_loss_names = args.custom_loss
lossClasses = []
for loss_chunk in custom_losses:
# check for special delimiter
if loss_chunk.find('->') > 0:
parts = loss_chunk.split('->')
loss = parts[0]
instance_args = parts[1:]
else:
loss = loss_chunk
instance_args = []
loss_name, weight, stop = parse_prompt(loss)
lossClass = loss_class_table[loss_name]
# do special initializations here
try:
lossInstance = lossClass(device=device)
lossInstance.instance_settings(instance_args)
lossClasses.append({"loss":lossInstance, "weight": weight})
except TypeError as e:
print(f'error in initializing {lossClass} - this message is to provide information')
raise TypeError(e)
args.custom_loss = lossClasses
#Loss args parse
if args.custom_loss:
for t in args.custom_loss:
args = t["loss"].parse_settings(args)
#adding globals for loss
if args.custom_loss is not None and len(args.custom_loss)>0:
for t in args.custom_loss:
lossGlobals.update(t["loss"].add_globals(args))
opts = rebuild_optimisers(args)
# Output for the user
print('Using device:', device)
print('Optimising using:', args.optimiser)
if args.prompts:
print('Using text prompts:', args.prompts)
if args.spot_prompts:
print('Using spot prompts:', args.spot_prompts)