forked from njbbaer/progrockdiffusion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prd.py
3263 lines (2923 loc) · 134 KB
/
prd.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
# -*- coding: utf-8 -*-
"""ProgRock Diffusion
Command line version of Disco Diffusion (v5 Alpha) adapted for command line by Jason Hough (and friends!)
--
Original file is located at
https://colab.research.google.com/drive/1QGCyDlYneIvv1zFXngfOCCoSUKC6j1ZP
Original notebook by Katherine Crowson (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings). It uses either OpenAI's 256x256 unconditional ImageNet or Katherine Crowson's fine-tuned 512x512 diffusion model (https://github.com/openai/guided-diffusion), together with CLIP (https://github.com/openai/CLIP) to connect text prompts with images.
Modified by Daniel Russell (https://github.com/russelldc, https://twitter.com/danielrussruss) to include (hopefully) optimal params for quick generations in 15-100 timesteps rather than 1000, as well as more robust augmentations.
Further improvements from Dango233 and nsheppard helped improve the quality of diffusion in general, and especially so for shorter runs like this notebook aims to achieve.
Vark added code to load in multiple Clip models at once, which all prompts are evaluated against, which may greatly improve accuracy.
The latest zoom, pan, rotation, and keyframes features were taken from Chigozie Nri's VQGAN Zoom Notebook (https://github.com/chigozienri, https://twitter.com/chigozienri)
Advanced DangoCutn Cutout method is also from Dango223.
Somnai (https://twitter.com/Somnai_dreams) added Diffusion Animation techniques, QoL improvements and various implementations of tech and techniques, mostly listed in the changelog below.
Pixel art models by u/Kaliyuga_ai
Comic faces model by alex_spirin
"""
# @title Licensed under the MIT License
# Copyright (c) 2021 Katherine Crowson
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#@title <- View Changelog
import os
from os import path
from pickle import FALSE
import shutil
from attr import has
root_path = os.getcwd()
#Simple create paths taken with modifications from Datamosh's Batch VQGAN+CLIP notebook
def createPath(filepath):
if path.exists(filepath) == False:
os.makedirs(filepath)
print(f'Made {filepath}')
else:
pass
initDirPath = f'{root_path}/init_images'
createPath(initDirPath)
outDirPath = f'{root_path}/images_out'
createPath(outDirPath)
model_path = f'{root_path}/models'
createPath(model_path)
model_256_downloaded = False
model_512_downloaded = False
model_secondary_downloaded = False
python_example = "python3"
import sys
if sys.platform == 'win32':
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
python_example = "python"
#Uncomment the below line if you're getting an error about OMP: Error #15.
#os.environ['KMP_DUPLICATE_LIB_OK']='TRUE'
import subprocess
from dataclasses import dataclass
from functools import partial
import cv2
import pandas as pd
import re
import gc
import io
import math
import timm
from IPython import display
import lpips
from PIL import Image, ImageOps, ImageStat, ImageEnhance
from PIL.PngImagePlugin import PngInfo
import requests
from glob import glob
import json5 as json
from types import SimpleNamespace
import torch
from torch import nn
from torch.nn import functional as F
import torchvision.transforms as T
import torchvision.transforms.functional as TF
from tqdm import tqdm
sys.path.append(f'{root_path}/ResizeRight')
sys.path.append(f'{root_path}/CLIP')
sys.path.append(f'{root_path}/guided-diffusion')
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 numexpr
import matplotlib.pyplot as plt
import random
from ipywidgets import Output
import hashlib
import urllib.request
from os.path import exists
# Setting default values for everything, which can then be overridden by settings files.
batch_name = "Default"
text_prompts = "No prompt in the file, by Sir Digby Chicken Caeser"
image_prompts = {}
clip_guidance_scale = "auto"
tv_scale = 0
range_scale = 150
sat_scale = 0
n_batches = 1
display_rate = 20
cutn_batches = 4
cutn_batches_final = None
max_frames = 10000
interp_spline = "Linear"
init_image = None
init_scale = 1000
skip_steps = 0
skip_steps_ratio = 0.3
frames_scale = 1500
frames_skip_steps = "60%"
perlin_init = False
perlin_mode = "mixed"
skip_augs = False
randomize_class = True
clip_denoised = False
clamp_grad = True
clamp_max = "auto"
set_seed = "random_seed"
fuzzy_prompt = False
rand_mag = 0.05
eta = "auto"
width_height = [832, 512]
width_height_scale = 1
diffusion_model = "512x512_diffusion_uncond_finetune_008100"
use_secondary_model = True
steps = 250
sampling_mode = "ddim"
diffusion_steps = 1000
ViTB32 = True
ViTB16 = True
ViTL14 = False
ViTL14_336 = False
RN101 = False
RN50 = True
RN50x4 = False
RN50x16 = False
RN50x64 = False
cut_overview = "[12]*400+[4]*600"
cut_innercut = "[4]*400+[12]*600"
cut_ic_pow = 1
cut_ic_pow_final = None
cut_icgray_p = "[0.2]*400+[0]*600"
key_frames = True
angle = "0:(0)"
zoom = "0: (1), 10: (1.05)"
translation_x = "0: (0)"
translation_y = "0: (0)"
video_init_path = "/content/training.mp4"
extract_nth_frame = 2
intermediate_saves = 0
add_metadata = True
stop_early = 0
fix_brightness_contrast = True
adjustment_interval = 10
high_contrast_threshold = 80
high_contrast_adjust_amount = 0.85
high_contrast_start = 20
high_contrast_adjust = True
low_contrast_threshold = 20
low_contrast_adjust_amount = 2
low_contrast_start = 20
low_contrast_adjust = True
high_brightness_threshold = 180
high_brightness_adjust_amount = 0.85
high_brightness_start = 0
high_brightness_adjust = True
low_brightness_threshold = 40
low_brightness_adjust_amount = 1.15
low_brightness_start = 0
low_brightness_adjust = True
sharpen_preset = 'Off' #@param ['Off', 'Faster', 'Fast', 'Slow', 'Very Slow']
keep_unsharp = False #@param{type: 'boolean'}
animation_mode = "None" # "Video Input", "2D"
gobig_orientation = "vertical"
gobig_scale = 2
symmetry_loss_v = False
symmetry_loss_h = False
symm_loss_scale = 161803
symm_switch = 45
# Command Line parse
import argparse
example_text = f'''Usage examples:
To simply use the 'Default' output directory and get settings from settings.json:
{python_example} prd.py
To use your own settings.json (note that putting it in quotes can help parse errors):
{python_example} prd.py -s "some_directory/mysettings.json"
Note that multiple settings files are allowed. They're parsed in order. The values present are applied over any previous value:
{python_example} prd.py -s "some_directory/mysettings.json" -s "highres.json"
To use the 'Default' output directory and settings, but override the output name and prompt:
{python_example} prd.py -p "A cool image of the author of this program" -o Coolguy
To use multiple prompts with optional weight values:
{python_example} prd.py -p "A cool image of the author of this program" -p "Pale Blue Sky:.5"
You can ignore the seed coming from a settings file by adding -i, resulting in a new random seed
To force use of the CPU for image generation, add a -c or --cpu with how many threads to use (warning: VERY slow):
{python_example} prd.py -c 16
To generate a checkpoint image at 20% steps, for use as an init image in future runs, add -g or --geninit:
{python_example} prd.py -g
To use a checkpoint image at 20% steps add -u or --useinit:
{python_example} prd.py -u
To specify which CUDA device to use (advanced) by device ID (default is 0):
{python_example} prd.py --cuda 1
To HIDE the settings that get added to your output PNG's metadata, use:
{python_example} prd.py --hidemetadata
To increase resolution 2x by splitting the final image and re-rendering detail in the sections, use:
{python_example} prd.py --gobig
To increase resolution 2x on an existing output, make sure to supply proper settings, then use:
{python_example} prd.py --gobig --gobiginit "some_directory/image.png"
If you already upscaled your gobiginit image, you can skip the resizing process. Provide the scaling factor used:
{python_example} prd.py --gobig --gobiginit "some_directory/image.png" --gobiginit_scaled 2
Alternative scaling method is to use ESRGAN (note: RealESRGAN must be installed and in your path):
{python_example} prd.py --esrgan
More information on instlaling it is here: https://github.com/xinntao/Real-ESRGAN
'''
my_parser = argparse.ArgumentParser(
prog='ProgRockDiffusion',
description='Generate images from text prompts.',
epilog=example_text,
formatter_class=argparse.RawDescriptionHelpFormatter)
my_parser.add_argument('--gui',
action='store_true',
required=False,
help='Use the PyQt5 GUI')
my_parser.add_argument(
'-s',
'--settings',
action='append',
required=False,
default=['settings.json'],
help=
'A settings JSON file to use, best to put in quotes. Multiples are allowed and layered in order.'
)
my_parser.add_argument('-o',
'--output',
action='store',
required=False,
help='What output directory to use within images_out')
my_parser.add_argument('-p',
'--prompt',
action='append',
required=False,
help='Override the prompt')
my_parser.add_argument('-i',
'--ignoreseed',
action='store_true',
required=False,
help='Ignores the random seed in the settings file')
my_parser.add_argument(
'-c',
'--cpu',
type=int,
nargs='?',
action='store',
required=False,
default=False,
const=0,
help='Force use of CPU instead of GPU, and how many threads to run')
my_parser.add_argument(
'-g',
'--geninit',
type=int,
nargs='?',
action='store',
required=False,
default=False,
const=20,
help=
'Save a partial image at the specified percent of steps (1 to 99), for use as later init image'
)
my_parser.add_argument('-u',
'--useinit',
action='store_true',
required=False,
default=False,
help='Use the specified init image')
my_parser.add_argument('--cuda',
action='store',
required=False,
default='0',
help='Which GPU to use. Default is 0.')
my_parser.add_argument(
'--hidemetadata',
action='store_true',
required=False,
help='Will prevent settings from being added to the output PNG file')
my_parser.add_argument(
'--gobig',
action='store_true',
required=False,
help='After generation, the image is split into sections and re-rendered, to double the size.')
my_parser.add_argument(
'--gobiginit',
action='store',
required=False,
help=
'An image to use to kick off GO BIG mode, skipping the initial render.'
)
my_parser.add_argument(
'--gobiginit_scaled',
type=int,
nargs='?',
action='store',
required=False,
default=False,
const=2,
help=
'If you already scaled your gobiginit image, add this option along with the multiplier used (default 2)'
)
my_parser.add_argument(
'--esrgan',
action='store_true',
required=False,
help=
'Resize your output with ESRGAN (realesrgan-ncnn-vulkan must be in your path).'
)
my_parser.add_argument(
'--skip_checks',
action='store_true',
required=False,
default=False,
help=
'Do not check values to make sure they are sensible.'
)
cl_args = my_parser.parse_args()
# Simple check to see if a key is present in the settings file
def is_json_key_present(json, key):
try:
buf = json[key]
except KeyError:
return False
if type(buf) == type(None):
return False
return True
#A simple way to ensure values are in an accceptable range, and also return a random value if desired
def clampval(minval, val, maxval):
if val == "random":
try:
val = random.randint(minval, maxval)
except:
val = random.uniform(minval, maxval)
return val
#Auto is handled later, so we just return it back as is
elif val == "auto":
return val
elif val < minval and not cl_args.skip_checks:
val = minval
return val
elif val > maxval and not cl_args.skip_checks:
val = maxval
return val
else:
return val
print('\nPROG ROCK DIFFUSION')
print('-------------------')
#rolling a d20 to see if I should pester you about supporting PRD.
# Apologies if this offends you. At least it's only on a critical miss, right?
d20 = random.randint(1,20)
if d20 == 1:
print('Please consider supporting my Patreon. Thanks! https://is.gd/rVX6IH')
else:
print('')
# Load the JSON config files
for setting_arg in cl_args.settings:
try:
with open(setting_arg, 'r', encoding="utf-8") as json_file:
print(f'Parsing {setting_arg}')
settings_file = json.load(json_file)
# If any of these are in this settings file they'll be applied, overwriting any previous value.
# Some are passed through clampval first to make sure they are within bounds (or randomized if desired)
if is_json_key_present(settings_file, 'batch_name'):
batch_name = (settings_file['batch_name'])
if is_json_key_present(settings_file, 'text_prompts'):
text_prompts = (settings_file['text_prompts'])
if is_json_key_present(settings_file, 'image_prompts'):
image_prompts = (settings_file['image_prompts'])
if is_json_key_present(settings_file, 'clip_guidance_scale'):
clip_guidance_scale = clampval(
1500, (settings_file['clip_guidance_scale']), 100000)
if is_json_key_present(settings_file, 'tv_scale'):
tv_scale = clampval(0, (settings_file['tv_scale']), 1000)
if is_json_key_present(settings_file, 'range_scale'):
range_scale = clampval(0, (settings_file['range_scale']), 1000)
if is_json_key_present(settings_file, 'sat_scale'):
sat_scale = clampval(0, (settings_file['sat_scale']), 20000)
if is_json_key_present(settings_file, 'n_batches'):
n_batches = (settings_file['n_batches'])
if is_json_key_present(settings_file, 'display_rate'):
display_rate = (settings_file['display_rate'])
if is_json_key_present(settings_file, 'cutn_batches'):
cutn_batches = (settings_file['cutn_batches'])
if is_json_key_present(settings_file, 'cutn_batches_final'):
cutn_batches_final = (settings_file['cutn_batches_final'])
if is_json_key_present(settings_file, 'max_frames'):
max_frames = (settings_file['max_frames'])
if is_json_key_present(settings_file, 'interp_spline'):
interp_spline = (settings_file['interp_spline'])
if is_json_key_present(settings_file, 'init_image'):
init_image = (settings_file['init_image'])
if is_json_key_present(settings_file, 'init_scale'):
init_scale = (settings_file['init_scale'])
if is_json_key_present(settings_file, 'skip_steps'):
skip_steps = (settings_file['skip_steps'])
if is_json_key_present(settings_file, 'skip_steps_ratio'):
skip_steps_ratio = (settings_file['skip_steps_ratio'])
if is_json_key_present(settings_file, 'stop_early'):
stop_early = (settings_file['stop_early'])
if is_json_key_present(settings_file, 'frames_scale'):
frames_scale = (settings_file['frames_scale'])
if is_json_key_present(settings_file, 'frames_skip_steps'):
frames_skip_steps = (settings_file['frames_skip_steps'])
if is_json_key_present(settings_file, 'perlin_init'):
perlin_init = (settings_file['perlin_init'])
if is_json_key_present(settings_file, 'perlin_mode'):
perlin_mode = (settings_file['perlin_mode'])
if is_json_key_present(settings_file, 'skip_augs'):
skip_augs = (settings_file['skip_augs'])
if is_json_key_present(settings_file, 'randomize_class'):
randomize_class = (settings_file['randomize_class'])
if is_json_key_present(settings_file, 'clip_denoised'):
clip_denoised = (settings_file['clip_denoised'])
if is_json_key_present(settings_file, 'clamp_grad'):
clamp_grad = (settings_file['clamp_grad'])
if is_json_key_present(settings_file, 'clamp_max'):
clamp_max = clampval(0.001, (settings_file['clamp_max']), 0.3)
if is_json_key_present(settings_file, 'set_seed'):
set_seed = (settings_file['set_seed'])
if is_json_key_present(settings_file, 'fuzzy_prompt'):
fuzzy_prompt = (settings_file['fuzzy_prompt'])
if is_json_key_present(settings_file, 'rand_mag'):
rand_mag = clampval(0.0, (settings_file['rand_mag']), 0.999)
if is_json_key_present(settings_file, 'eta'):
eta = clampval(0.0, (settings_file['eta']), 0.999)
if is_json_key_present(settings_file, 'width'):
width_height = [(settings_file['width']),
(settings_file['height'])]
if is_json_key_present(settings_file, 'width_height_scale'):
width_height_scale = (settings_file['width_height_scale'])
if is_json_key_present(settings_file, 'diffusion_model'):
diffusion_model = (settings_file['diffusion_model'])
if is_json_key_present(settings_file, 'use_secondary_model'):
use_secondary_model = (settings_file['use_secondary_model'])
if is_json_key_present(settings_file, 'steps'):
steps = (settings_file['steps'])
if is_json_key_present(settings_file, 'sampling_mode'):
sampling_mode = (settings_file['sampling_mode'])
if is_json_key_present(settings_file, 'diffusion_steps'):
diffusion_steps = (settings_file['diffusion_steps'])
if is_json_key_present(settings_file, 'ViTB32'):
ViTB32 = (settings_file['ViTB32'])
if is_json_key_present(settings_file, 'ViTB16'):
ViTB16 = (settings_file['ViTB16'])
if is_json_key_present(settings_file, 'ViTL14'):
ViTL14 = (settings_file['ViTL14'])
if is_json_key_present(settings_file, 'ViTL14_336'):
ViTL14_336 = (settings_file['ViTL14_336'])
if is_json_key_present(settings_file, 'RN101'):
RN101 = (settings_file['RN101'])
if is_json_key_present(settings_file, 'RN50'):
RN50 = (settings_file['RN50'])
if is_json_key_present(settings_file, 'RN50x4'):
RN50x4 = (settings_file['RN50x4'])
if is_json_key_present(settings_file, 'RN50x16'):
RN50x16 = (settings_file['RN50x16'])
if is_json_key_present(settings_file, 'RN50x64'):
RN50x64 = (settings_file['RN50x64'])
if is_json_key_present(settings_file, 'cut_overview'):
cut_overview = (settings_file['cut_overview'])
if is_json_key_present(settings_file, 'cut_innercut'):
cut_innercut = (settings_file['cut_innercut'])
if is_json_key_present(settings_file, 'cut_ic_pow'):
cut_ic_pow = (settings_file['cut_ic_pow'])
if type(cut_ic_pow) != str:
cut_ic_pow = clampval(0.0, cut_ic_pow, 100)
if is_json_key_present(settings_file, 'cut_ic_pow_final'):
cut_ic_pow_final = clampval(0.5, (settings_file['cut_ic_pow_final']), 100)
if is_json_key_present(settings_file, 'cut_icgray_p'):
cut_icgray_p = (settings_file['cut_icgray_p'])
if is_json_key_present(settings_file, 'key_frames'):
key_frames = (settings_file['key_frames'])
if is_json_key_present(settings_file, 'angle'):
angle = (settings_file['angle'])
if is_json_key_present(settings_file, 'zoom'):
zoom = (settings_file['zoom'])
if is_json_key_present(settings_file, 'translation_x'):
translation_x = (settings_file['translation_x'])
if is_json_key_present(settings_file, 'translation_y'):
translation_y = (settings_file['translation_y'])
if is_json_key_present(settings_file, 'video_init_path'):
video_init_path = (settings_file['video_init_path'])
if is_json_key_present(settings_file, 'extract_nth_frame'):
extract_nth_frame = (settings_file['extract_nth_frame'])
if is_json_key_present(settings_file, 'intermediate_saves'):
intermediate_saves = (settings_file['intermediate_saves'])
if is_json_key_present(settings_file, 'fix_brightness_contrast'):
fix_brightness_contrast = (settings_file['fix_brightness_contrast'])
if is_json_key_present(settings_file, 'adjustment_interval'):
adjustment_interval = (settings_file['adjustment_interval'])
if is_json_key_present(settings_file, 'high_contrast_threshold'):
high_contrast_threshold = (
settings_file['high_contrast_threshold'])
if is_json_key_present(settings_file,
'high_contrast_adjust_amount'):
high_contrast_adjust_amount = (
settings_file['high_contrast_adjust_amount'])
if is_json_key_present(settings_file, 'high_contrast_start'):
high_contrast_start = (settings_file['high_contrast_start'])
if is_json_key_present(settings_file, 'high_contrast_adjust'):
high_contrast_adjust = (settings_file['high_contrast_adjust'])
if is_json_key_present(settings_file, 'low_contrast_threshold'):
low_contrast_threshold = (
settings_file['low_contrast_threshold'])
if is_json_key_present(settings_file,
'low_contrast_adjust_amount'):
low_contrast_adjust_amount = (
settings_file['low_contrast_adjust_amount'])
if is_json_key_present(settings_file, 'low_contrast_start'):
low_contrast_start = (settings_file['low_contrast_start'])
if is_json_key_present(settings_file, 'low_contrast_adjust'):
low_contrast_adjust = (settings_file['low_contrast_adjust'])
if is_json_key_present(settings_file, 'high_brightness_threshold'):
high_brightness_threshold = (
settings_file['high_brightness_threshold'])
if is_json_key_present(settings_file,
'high_brightness_adjust_amount'):
high_brightness_adjust_amount = (
settings_file['high_brightness_adjust_amount'])
if is_json_key_present(settings_file, 'high_brightness_start'):
high_brightness_start = (
settings_file['high_brightness_start'])
if is_json_key_present(settings_file, 'high_brightness_adjust'):
high_brightness_adjust = (
settings_file['high_brightness_adjust'])
if is_json_key_present(settings_file, 'low_brightness_threshold'):
low_brightness_threshold = (
settings_file['low_brightness_threshold'])
if is_json_key_present(settings_file,
'low_brightness_adjust_amount'):
low_brightness_adjust_amount = (
settings_file['low_brightness_adjust_amount'])
if is_json_key_present(settings_file, 'low_brightness_start'):
low_brightness_start = (settings_file['low_brightness_start'])
if is_json_key_present(settings_file, 'low_brightness_adjust'):
low_brightness_adjust = (
settings_file['low_brightness_adjust'])
if is_json_key_present(settings_file, 'sharpen_preset'):
sharpen_preset = (settings_file['sharpen_preset'])
if is_json_key_present(settings_file, 'keep_unsharp'):
keep_unsharp = (settings_file['keep_unsharp'])
if is_json_key_present(settings_file, 'animation_mode'):
animation_mode = (settings_file['animation_mode'])
if is_json_key_present(settings_file, 'gobig_orientation'):
gobig_orientation = (settings_file['gobig_orientation'])
if is_json_key_present(settings_file, 'gobig_scale'):
gobig_scale = int(settings_file['gobig_scale'])
if is_json_key_present(settings_file, 'symmetry_loss'):
symmetry_loss_v = (settings_file['symmetry_loss'])
print("symmetry_loss was depracated, please use symmetry_loss_v in the future")
if is_json_key_present(settings_file, 'symmetry_loss_v'):
symmetry_loss_v = (settings_file['symmetry_loss_v'])
if is_json_key_present(settings_file, 'symmetry_loss_h'):
symmetry_loss_h = (settings_file['symmetry_loss_h'])
if is_json_key_present(settings_file, 'symm_loss_scale'):
symm_loss_scale = (settings_file['symm_loss_scale'])
if is_json_key_present(settings_file, 'symm_switch'):
symm_switch = int(clampval(1, (settings_file['symm_switch']), steps))
except Exception as e:
print('Failed to open or parse ' + setting_arg +
' - Check formatting.')
print(e)
quit()
print('')
width_height = [
width_height[0] * width_height_scale, width_height[1] * width_height_scale
]
if symmetry_loss_v or symmetry_loss_h:
symm_switch = 100.*(1. - (symm_switch/steps))
print(f"Symmetry ends at {100-symm_switch}%")
#Now override some depending on command line and maybe a special case
if cl_args.output:
batch_name = cl_args.output
print(f'Setting Output dir to {batch_name}')
if cl_args.ignoreseed:
set_seed = 'random_seed'
print(f'Using a random seed instead of the one provided by the JSON file.')
if cl_args.hidemetadata:
add_metadata = False
print(
f'Hide metadata flag is ON, settings will not be stored in the PNG output.'
)
gui = False
if cl_args.gui:
gui = True
import prdgui
letsgobig = False
gobig_horizontal = False
gobig_vertical = False
if cl_args.gobig:
letsgobig = True
if gobig_orientation == "horizontal": # default is vertical, if the settings file says otherwise, change it
gobig_horizontal = True
else:
gobig_vertical = True
n_batches = 1
print('Going BIG! N-batches automatically set to 1, as only 1 output is supported.')
if cl_args.gobiginit:
init_image = cl_args.gobiginit
print(f'Using {init_image} to kickstart GO BIG. Initial render will be skipped.')
# check to make sure it is a multiple of 64, otherwise resize it and let the user know.
temp_image = Image.open(init_image)
s_width, s_height = temp_image.size
reside_x = (s_width // 64) * 64
reside_y = (s_height// 64) * 64
if reside_x != s_width or reside_y != s_height:
print('ERROR: Your go big init resolution was NOT a multiple of 64.')
print('ERROR: Please resize your image.')
raise Exception("Exiting due to improperly sized go big init.")
side_x, side_y = temp_image.size
width_height[0] = side_x
width_height[1] = side_y
temp_image.close
else:
cl_args.gobiginit = None
if cl_args.gobiginit_scaled != False:
gobig_scale = cl_args.gobiginit_scaled
if cl_args.geninit:
geninit = True
if cl_args.geninit > 0 and cl_args.geninit <= 100:
geninitamount = float(cl_args.geninit /
100) # turn it into a float percent
print(
f'GenInit mode enabled. A checkpoint image will be saved at {cl_args.geninit:.1%} of steps.'
)
else:
geninitamount = 0.2
print(
f'GenInit mode enabled. Provided number was out of bounds, so using {geninitamount:.1%} of steps instead.'
)
else:
geninit = False
if skip_steps == 0 and init_image is not None:
if 0 < skip_steps_ratio <= 1:
skip_steps = (int(steps * skip_steps_ratio))
else:
skip_steps = (int(steps * 0.33))
if cl_args.useinit:
if skip_steps == 0:
skip_steps = (
int(steps * 0.2)
) # don't change skip_steps if the settings file specified one
if path.exists(f'{cl_args.useinit}'):
useinit = True
init_image = cl_args.useinit
print(
f'UseInit mode is using {cl_args.useinit} and starting at {skip_steps}.'
)
else:
init_image = 'geninit.png'
if path.exists(init_image):
print(
f'UseInit mode is using {init_image} and starting at {skip_steps}.'
)
useinit = True
else:
print('No init image found. Uneinit mode canceled.')
useinit = False
else:
useinit = False
#Automatic Eta based on steps
if eta == 'auto':
maxetasteps = 315
minetasteps = 50
maxeta = 1.0
mineta = 0.0
if steps > maxetasteps: eta = maxeta
elif steps < minetasteps: eta = mineta
else:
stepsrange = (maxetasteps - minetasteps)
newrange = (maxeta - mineta)
eta = (((steps - minetasteps) * newrange) / stepsrange) + mineta
eta = round(eta, 2)
print(f'Eta set automatically to: {eta}')
#Automatic clamp_max based on steps
if clamp_max == 'auto':
if steps <= 35: clamp_max = 0.001
elif steps <= 75: clamp_max = 0.0125
elif steps <= 150: clamp_max = 0.02
elif steps <= 225: clamp_max = 0.035
elif steps <= 300: clamp_max = 0.05
elif steps <= 500: clamp_max = 0.075
else: clamp_max = 0.1
print(f'Clamp_max automatically set to {clamp_max}')
#Automatic clip_guidance_scale based on overall resolution
if clip_guidance_scale == 'auto':
res = width_height[0] * width_height[1] # total pixels
maxcgsres = 2000000
mincgsres = 250000
maxcgs = 50000
mincgs = 2500
if res > maxcgsres: clip_guidance_scale = maxcgs
elif res < mincgsres: clip_guidance_scale = mincgs
else:
resrange = (maxcgsres - mincgsres)
newrange = (maxcgs - mincgs)
clip_guidance_scale = ((
(res - mincgsres) * newrange) / resrange) + mincgs
clip_guidance_scale = round(clip_guidance_scale)
print(f'clip_guidance_scale set automatically to: {clip_guidance_scale}')
if cl_args.prompt:
text_prompts["0"] = cl_args.prompt
print(f'Setting prompt to {text_prompts}')
# PROMPT RANDOMIZERS
# If any word in the prompt starts and ends with _, replace it with a random line from the corresponding text file
# For example, _artist_ will replace with a line from artist.txt
# Build a list of randomizers to draw from:
def randomizer(category):
random.seed()
randomizers = []
with open(f'settings/{category}.txt', encoding="utf-8") as f:
for line in f:
randomizers.append(line.strip())
random_item = random.choice(randomizers)
return(random_item)
# Search through the prompt for any _randomizer_ words and replace them accordingly
prompt_change = False
for k, v in text_prompts.items():
if type(v) == list:
newprompts = []
for prompt in v:
if "_" in prompt:
while "_" in prompt:
start = prompt.index('_')
end = prompt.index('_',start+1)
swap = prompt[(start + 1):end]
swapped = randomizer(swap)
prompt = prompt.replace(f'_{swap}_', swapped, 1)
newprompt = prompt
prompt_change = True
else:
newprompt = prompt
newprompts.append(newprompt)
if prompt_change == True:
v = newprompts
else: # to handle if the prompt is actually a multi-prompt.
for kk, vv in v.items():
newprompts = []
for prompt in vv:
if "_" in prompt:
while "_" in prompt:
start = prompt.index('_')
end = prompt.index('_',start+1)
swap = prompt[(start + 1):end]
swapped = randomizer(swap)
prompt = prompt.replace(f'_{swap}_', swapped, 1)
newprompt = prompt
prompt_change = True
else:
newprompt = prompt
newprompts.append(newprompt)
if prompt_change == True:
vv = newprompts
if prompt_change == True:
v = {**v, kk: vv}
if prompt_change == True:
text_prompts = {**text_prompts, k: v}
print(f'Prompt with randomizers: {text_prompts}\n')
# INIT IMAGE RANDOMIZER
# If the setting for init_image is a word between two underscores, we'll pull a random image from that directory,
# and set our size accordingly.
# randomly pick a file name from a directory:
def random_file(directory):
files = []
files = os.listdir(f'{initDirPath}/{directory}')
file = random.choice(files)
return(file)
# Check for init randomizer in settings, and configure a random init if found
init_image_OriginalPath = init_image
if init_image != None:
if init_image.startswith("_") and init_image.endswith("_"):
randominit_dir = (init_image[1:])
randominit_dir = (randominit_dir[:-1]) # parse out the directory name
print(f"Randomly picking an init image from {initDirPath}/{randominit_dir}")
init_image_OriginalPath = init_image = (f'{initDirPath}/{randominit_dir}/{random_file(randominit_dir)}')
print(f"New init image is {init_image}")
# check to see if the image matches the configured size, if not we'll resize it
temp = Image.open(init_image).convert('RGB')
temp_width, temp_height = temp.size
if (temp_width != width_height[0]) or (temp_height != width_height[1]):
print('Randomly chosen init image does not match width and height from settings.')
print('It will be resized as temp_init.png and used as your init.')
temp = temp.resize(width_height, Image.Resampling.LANCZOS)
temp.save('temp_init.png')
init_image = 'temp_init.png'
# Decide if we're using CPU or GPU, with appropriate settings depending...
if cl_args.cpu or not torch.cuda.is_available():
DEVICE = torch.device('cpu')
device = DEVICE
fp16_mode = False
cores = os.cpu_count()
if cl_args.cpu == 0:
print(
f'No thread count specified. Using detected {cores} cores for CPU mode.'
)
elif cl_args.cpu > cores:
print(
f'Too many threads specified. Using detected {cores} cores for CPU mode.'
)
else:
cores = int(cl_args.cpu)
print(f'Using {cores} cores for CPU mode.')
torch.set_num_threads(cores)
else:
DEVICE = torch.device(f'cuda:{cl_args.cuda}')
device = DEVICE
fp16_mode = True
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
print('Using device:', device)
#@title 2.2 Define necessary functions
def ease(num, t):
start = num[0]
end = num[1]
power = num[2]
return start + pow(t, power) * (end - start)
def interp(t):
return 3 * t**2 - 2 * t**3
# return a number between two numbers in a given range
def val_interpolate(x1, y1, x2, y2, x):
"""Perform linear interpolation for x between (x1,y1) and (x2,y2) """
d = [[x1, y1],[x2, y2]]
output = d[0][1] + (x - d[0][0]) * ((d[1][1] - d[0][1])/(d[1][0] - d[0][0]))
return(output)
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)