-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
dream-factory.py
3343 lines (2921 loc) · 166 KB
/
dream-factory.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
# Copyright 2021 - 2024, Bill Kennedy (https://github.com/rbbrdckybk/dream-factory)
# SPDX-License-Identifier: MIT
import threading
import time
import datetime
import shlex
import subprocess
import sys
import unicodedata
import re
import random
import os
import platform
import signal
import webbrowser
import argparse
import shutil
import base64
import json
import copy
import math
from PIL import Image
from io import BytesIO
import scripts.utils as utils
import scripts.metadata as metadata
import scripts.civitai as civitai
from os.path import exists
from datetime import datetime as dt
from datetime import date
from pathlib import Path
from collections import deque
from PIL.PngImagePlugin import PngImageFile, PngInfo
from torch.cuda import get_device_name, device_count
from scripts.server import ArtServer
from scripts.sdi import SDI
# environment setup
cwd = os.getcwd()
python_path = ""
env_paths = [ \
os.path.join(cwd, 'taming-transformers'),
os.path.join(cwd, 'CLIP')
]
for path in env_paths:
python_path += os.pathsep + path
#os.environ['PYTHONPATH'] = python_path
# Prevent threads from printing at same time.
print_lock = threading.Lock()
# worker thread executes specified shell command
class Worker(threading.Thread):
def __init__(self, command, callback=lambda: None, *args):
threading.Thread.__init__(self)
self.command = command
self.callback = callback
# grab the worker info from the args
self.worker = args[0]
# grab the output buffer
self.output_buffer = None
if len(args) > 1:
self.output_buffer = args[1]
def run(self):
command = ''
original_filename = ''
original_exif = {}
original_iptc = {}
original_command = {}
process_mode = False
if not int(self.command.get('seed')) > 0:
self.command['seed'] = -1
else:
# increment seed if we've finished one or more complete loops
if control.models != []:
# multiple models in queue, only increment for each time we use all of them
complete = math.floor(control.loops / len(control.models))
seed = int(self.command.get('seed')) + complete
self.command['seed'] = seed
else:
seed = int(self.command.get('seed')) + control.loops
self.command['seed'] = seed
# check for ADetailer params
use_adetailer = False
if control.sdi_adetailer_available and self.command.get('adetailer_use') and self.command.get('adetailer_model') != '':
use_adetailer = True
if '<prompt>' in self.command.get('adetailer_prompt'):
self.command['adetailer_prompt'] = self.command.get('adetailer_prompt').replace('<prompt>', self.command.get('prompt'))
# if this is a process-mode prompt, skip past image generation stuff
if self.command.get('mode') != 'process':
# handle IPTC metadata history stuff
if self.command['iptc_title_history']:
for key in self.command['iptc_title_history']:
self.command['iptc_title'] += self.command['iptc_title_history'][key][-1]
if self.command['iptc_description_history']:
for key in self.command['iptc_description_history']:
self.command['iptc_description'] += self.command['iptc_description_history'][key][-1]
if self.command['iptc_keywords_history']:
for key in self.command['iptc_keywords_history']:
for k in self.command['iptc_keywords_history'][key][-1]:
if k not in self.command['iptc_keywords']:
self.command['iptc_keywords'].append(k)
# if this is a random prompt, settle on random values
if self.command.get('mode') == 'random':
if float(self.command.get('min_scale')) > 0 and float(self.command.get('max_scale')) > 0:
self.command['scale'] = round(random.uniform(float(self.command.get('min_scale')), float(self.command.get('max_scale'))), 1)
if float(self.command.get('min_strength')) > 0 and float(self.command.get('max_strength')) > 0:
self.command['strength'] = round(random.uniform(float(self.command.get('min_strength')), float(self.command.get('max_strength'))), 2)
if self.command.get('random_input_image_dir') != "":
self.command['input_image'] = utils.InputManager(self.command.get('random_input_image_dir')).pick_random()
# settle on random values for ranges specified in scale directive
if '-' in str(self.command['scale']):
try:
values = str(self.command['scale']).split('-', 1)
first = float(values[0].strip())
second = float(values[1].strip())
if second >= first:
self.command['scale'] = round(random.uniform(first, second), 1)
else:
self.command['scale'] = round(random.uniform(second, first), 1)
except:
pass
# settle on random values for ranges specified in strength directive
if '-' in str(self.command['strength']):
try:
values = str(self.command['strength']).split('-', 1)
first = float(values[0].strip())
second = float(values[1].strip())
if second >= first:
self.command['strength'] = round(random.uniform(first, second), 2)
else:
self.command['strength'] = round(random.uniform(second, first), 2)
except:
pass
# settle on random values for ranges specified in steps directive
if '-' in str(self.command['steps']):
try:
values = str(self.command['steps']).split('-', 1)
first = int(values[0].strip())
second = int(values[1].strip())
if second >= first:
self.command['steps'] = random.randint(first, second)
else:
self.command['steps'] = random.randint(second, first)
except:
pass
# settle of random styles if necessary
if len(self.command['styles']) > 0:
if self.command['styles'][0].startswith('random'):
num = 1
styles = []
temp = self.command['styles'][0].split(' ')
if len(temp) > 1:
num = int(temp[1])
# pick random styles
if control.sdi_styles != None and control.sdi_styles != []:
if len(control.sdi_styles) > num:
work = copy.deepcopy(control.sdi_styles)
while num > 0:
pick = random.randint(0, len(work)-1)
styles.append(work[pick]['name'])
work.pop(pick)
num = num - 1
else:
# user asked for more random styles than exist; use all of them
for s in control.sdi_styles:
styles.append(s)
# update command with random styles
self.command['styles'] = styles
# check if a model change is needed
if self.command.get('ckpt_file') != '' and (self.command.get('ckpt_file') != self.worker['sdi_instance'].model_loaded):
self.worker['sdi_instance'].load_model(self.command.get('ckpt_file'))
while self.worker['sdi_instance'].options_change_in_progress:
# wait for model change to complete
time.sleep(0.25)
elif self.command.get('ckpt_file') == '':
# revert to default config.txt model if necessary
if control.config.get('ckpt_file') != '' and control.default_model_validated and (control.config.get('ckpt_file') != self.worker['sdi_instance'].model_loaded):
self.worker['sdi_instance'].load_model(control.config.get('ckpt_file'))
while self.worker['sdi_instance'].options_change_in_progress:
# wait for model change to complete
time.sleep(0.25)
if self.command.get('prompt').strip() == '.':
self.command['prompt'] = ''
else:
# clean up potentially dangerous prompt content:
while '--' in self.command.get('prompt'):
self.command['prompt'] = self.command.get('prompt').replace('--', '-')
# check for auto-insertion of model trigger word
if (control.model_trigger_words != None) and (self.command.get('auto_insert_model_trigger') != 'off'):
# check to see if the model we're using has an associated trigger
if control.model_trigger_words.get(self.command.get('ckpt_file')) != None:
trigger = control.model_trigger_words.get(self.command.get('ckpt_file'))
p = self.command.get('prompt')
if trigger not in p:
# trigger word isn't in prompt, we need to add it
if self.command.get('auto_insert_model_trigger') == 'first_comma':
if ',' in p:
self.command['prompt'] = p.split(',', 1)[0] + ', ' + trigger + ',' + p.split(',', 1)[1]
else:
self.command['prompt'] = p + ', ' + trigger
elif self.command.get('auto_insert_model_trigger') == 'end':
self.command['prompt'] = p + ', ' + trigger
elif self.command.get('auto_insert_model_trigger') == 'start':
self.command['prompt'] = trigger + ', ' + p
elif 'keyword:' in self.command.get('auto_insert_model_trigger'):
keyword = self.command.get('auto_insert_model_trigger')
keyword = keyword.split('keyword:', 1)[1].strip()
if keyword in p:
# the keyword we need to replace with the trigger is in the prompt, replace it
self.command['prompt'] = p.replace(keyword, trigger)
# check to see if the hi-res model we're using has an associated trigger if necessary
# BK 2023-10-29
if self.command.get('highres_ckpt_file') != '':
if control.model_trigger_words.get(self.command.get('highres_ckpt_file')) != None:
trigger = control.model_trigger_words.get(self.command.get('highres_ckpt_file'))
p = self.command.get('highres_prompt')
if p.strip() == '':
p = self.command.get('prompt')
if trigger not in p:
# trigger word isn't in highres prompt, we need to add it
if self.command.get('auto_insert_model_trigger') == 'first_comma':
if ',' in p:
self.command['highres_prompt'] = p.split(',', 1)[0] + ', ' + trigger + ',' + p.split(',', 1)[1]
else:
self.command['highres_prompt'] = p + ', ' + trigger
elif self.command.get('auto_insert_model_trigger') == 'end':
self.command['highres_prompt'] = p + ', ' + trigger
elif self.command.get('auto_insert_model_trigger') == 'start':
self.command['highres_prompt'] = trigger + ', ' + p
elif 'keyword:' in self.command.get('auto_insert_model_trigger'):
keyword = self.command.get('auto_insert_model_trigger')
keyword = keyword.split('keyword:', 1)[1].strip()
if keyword in p:
# the keyword we need to replace with the trigger is in the prompt, replace it
self.command['highres_prompt'] = p.replace(keyword, trigger)
# check for wildcard replacements
p = self.command.get('prompt')
#print('before wildcard replace: ' + self.command['prompt'])
for k, v in control.wildcards.items():
key = '__' + k.lower() + '__'
if key in p.lower():
vcopy = v.copy()
# check if any of the values are wildcard keys themselves
key_replacements = 1
while key_replacements > 0:
key_replacements = 0
for v in vcopy:
#print('Checking ' + v)
check_key = v[2:][:-2].lower()
if check_key in control.wildcards.keys():
key_replacements += 1
#print('\n\nFound nested wildcard: ' + v)
#print('\nList before replacement: ' + str(vcopy))
vcopy.extend(control.wildcards[check_key])
vcopy.remove(v)
#print('\nList after replacement: ' + str(vcopy) + '\n\n')
# this will handle multiple replacements of the same key
while key in p.lower():
replace_all = False
if len(vcopy) > 0:
# pick a random value & remove it from the copied list
x = random.randint(0, len(vcopy)-1)
replace = vcopy.pop(x)
else:
# not enough values to make all replacements, sub '' instead
replace_all = True
replace = ''
# make the replacement(s)
p = utils.wildcard_replace(p, key, replace, replace_all)
# check IPTC metadata and make the same replacement if necessary
self.command['iptc_title'] = utils.wildcard_replace(self.command.get('iptc_title'), key, replace, replace_all)
self.command['iptc_description'] = utils.wildcard_replace(self.command.get('iptc_description'), key, replace, replace_all)
self.command['iptc_keywords'] = utils.wildcard_replace_list(self.command.get('iptc_keywords'), key, replace, replace_all)
self.command['iptc_copyright'] = utils.wildcard_replace(self.command.get('iptc_copyright'), key, replace, replace_all)
# handle special hard-coded prompt directive wildcards
if '__!iptc_title__' in p.lower():
p = utils.wildcard_replace(p, '__!iptc_title__', self.command.get('iptc_title'), True)
if '__!iptc_description__' in p.lower():
p = utils.wildcard_replace(p, '__!iptc_description__', self.command.get('iptc_description'), True)
if '__!iptc_keywords__' in p.lower():
p = utils.wildcard_replace_list(p, '__!iptc_keywords__', self.command.get('iptc_keywords'), True)
self.command['prompt'] = p
#print('after wildcard replace: ' + self.command['prompt'])
# check for auto-dimensions
orig_size = [self.command.get('width'), self.command.get('height')]
if self.command.get('auto_size') == 'match_controlnet_image_size':
if self.command.get('controlnet_input_image') != '':
new_size = utils.get_image_size(self.command.get('controlnet_input_image'))
if new_size != []:
self.command['width'] = new_size[0]
self.command['height'] = new_size[1]
elif self.command.get('auto_size') == 'match_input_image_size':
if self.command.get('input_image') != '':
new_size = utils.get_image_size(self.command.get('input_image'))
if new_size != []:
self.command['width'] = new_size[0]
self.command['height'] = new_size[1]
elif self.command.get('auto_size') == 'match_controlnet_image_aspect_ratio':
if self.command.get('controlnet_input_image') != '':
new_size = utils.match_image_aspect_ratio(self.command.get('controlnet_input_image'), orig_size)
if new_size != []:
self.command['width'] = new_size[0]
self.command['height'] = new_size[1]
elif self.command.get('auto_size') == 'match_input_image_aspect_ratio':
if self.command.get('input_image') != '':
new_size = utils.match_image_aspect_ratio(self.command.get('input_image'), orig_size)
if new_size != []:
self.command['width'] = new_size[0]
self.command['height'] = new_size[1]
elif "resize_longest_dimension:" in self.command.get('auto_size'):
new_long_dim = self.command.get('auto_size').split(':', 1)[1].strip()
new_size = utils.resize_based_on_longest_dimension(new_long_dim, orig_size)
if new_size != []:
self.command['width'] = new_size[0]
self.command['height'] = new_size[1]
# check for ControlNet params
use_controlnet = False
scribble_mode = False
cn_params = [64, 64, 64]
img2img = False
if control.sdi_controlnet_available and self.command.get('controlnet_input_image') != '' and (self.command.get('controlnet_model') != '' or 'reference' in self.command.get('controlnet_pre')):
use_controlnet = True
if self.command.get('input_image') != '':
img2img = True
# encode CN image
encoded = base64.b64encode(open(self.command.get('controlnet_input_image'), "rb").read())
encodedString = str(encoded, encoding='utf-8')
cn_img_payload = 'data:image/png;base64,' + encodedString
# get preprocessor params
if len(self.command.get('controlnet_pre')) >= 3:
found = False
for p in control.sdi_controlnet_preprocessors:
#if self.command.get('controlnet_pre').lower() == p[0]:
# self.command['controlnet_pre'] = p[0]
# cn_params = p[1]
# break
if self.command.get('controlnet_pre').lower() == p.lower():
self.command['controlnet_pre'] = p
# these are the openpose defaults; not sure if these are needed
# TODO: investigate
cn_params = [512, 64, 64]
found = True
break
if not found:
self.command['controlnet_pre'] = 'none'
else:
self.command['controlnet_pre'] = 'none'
# check for auto-model from filename
auto = self.command.get('controlnet_model').lower().strip()
if auto.startswith('auto'):
cn_img = self.command.get('controlnet_input_image')
cn_img = utils.filename_from_abspath(cn_img)
auto_model = ''
# attempt to extract controlnet model from cn input file
if '-' in cn_img:
auto_model = cn_img.split('-', 1)[0]
validated = False
if len(auto_model) >= 3 and control.sdi_controlnet_models != None:
for m in control.sdi_controlnet_models:
if auto_model.lower() in m.lower():
auto_model = m
validated = True
break
if not validated:
auto_model = ''
else:
auto_model = ''
if auto_model == '':
# couldn't get model from filename, check for default
if ',' in auto:
auto_model = auto.rsplit(',', 1)[1].strip()
validated = False
if len(auto_model) >= 3 and control.sdi_controlnet_models != None:
for m in control.sdi_controlnet_models:
if auto_model.lower() in m.lower():
auto_model = m
validated = True
break
if not validated:
auto_model = ''
else:
auto_model = ''
if auto_model == '':
# failed to get model or default, disable CN
use_controlnet = False
self.print('WARNING: automatic ControlNet model specified, but unable to determine valid CN model from input image filename: ' + cn_img + '; disabling ControlNet!')
else:
# we have a valid model, use it
self.command['controlnet_model'] = auto_model
# parameters to pass to SD instance
payload = {}
if self.command.get('input_image') != '':
#img2img
encoded = base64.b64encode(open(self.command.get('input_image'), "rb").read())
encodedString = str(encoded, encoding='utf-8')
img_payload = 'data:image/png;base64,' + encodedString
payload = {
"init_images": [img_payload],
"sampler_index": str(self.command.get('sampler')),
#"scheduler": control.sdi_schedulers.get(str(self.command.get('scheduler'))),
"scheduler": str(self.command.get('scheduler')),
#"resize_mode": 0,
"denoising_strength": self.command.get('strength'),
"prompt": str(self.command.get('prompt')),
"seed": self.command.get('seed'),
"batch_size": self.command.get('batch_size'), # gpu makes this many at once
"n_iter": self.command.get('samples'), # number of iterations to run
"steps": self.command.get('steps'),
"cfg_scale": self.command.get('scale'),
"width": self.command.get('width'),
"height": self.command.get('height'),
#"restore_faces": False,
"tiling": self.command.get('tiling'),
"negative_prompt": str(self.command.get('neg_prompt')),
"alwayson_scripts": {}
}
else:
# txt2img
payload = {
"enable_hr": self.command.get('highres_fix'),
"denoising_strength": self.command.get('strength'),
"sampler_index": str(self.command.get('sampler')),
#"scheduler": control.sdi_schedulers.get(str(self.command.get('scheduler'))),
"scheduler": str(self.command.get('scheduler')),
"prompt": str(self.command.get('prompt')),
"seed": self.command.get('seed'),
"batch_size": self.command.get('batch_size'), # gpu makes this many at once
"n_iter": self.command.get('samples'), # number of iterations to run
"steps": self.command.get('steps'),
"cfg_scale": self.command.get('scale'),
"width": self.command.get('width'),
"height": self.command.get('height'),
#"restore_faces": False,
"tiling": self.command.get('tiling'),
"negative_prompt": str(self.command.get('neg_prompt')),
"alwayson_scripts": {}
}
if self.command['highres_fix'] == 'yes':
if self.command.get('highres_upscaler') != '':
payload["hr_upscaler"] = str(self.command.get('highres_upscaler'))
if self.command.get('highres_ckpt_file') != '':
payload["hr_checkpoint_name"] = str(self.command.get('highres_ckpt_file'))
if self.command.get('highres_sampler') != '':
payload["hr_sampler_name"] = str(self.command.get('highres_sampler'))
if self.command.get('highres_scheduler') != '':
#payload["hr_scheduler"] = control.sdi_schedulers.get(str(self.command.get('highres_scheduler')))
payload["hr_scheduler"] = str(self.command.get('highres_scheduler'))
if self.command.get('highres_prompt') != '':
if self.command.get('highres_prompt').lower().strip() == '<remove loras>':
# use the main prompt with loras/hypernets stripped out
mp = str(self.command.get('prompt'))
while '<lora:' in mp and '>' in mp:
p = mp
before = p.split('<lora:', 1)[0]
after = p.split('<lora:', 1)[1]
if '>' in after:
after = after.split('>', 1)[1]
mp = (before + after).strip()
else:
mp = before.strip()
while '<hypernet:' in mp and '>' in mp:
p = mp
before = p.split('<hypernet:', 1)[0]
after = p.split('<hypernet:', 1)[1]
if '>' in after:
after = after.split('>', 1)[1]
mp = (before + after).strip()
else:
mp = before.strip()
payload["hr_prompt"] = str(mp)
else:
if '<prompt>' in self.command.get('highres_prompt'):
self.command['highres_prompt'] = self.command.get('highres_prompt').replace('<prompt>', self.command.get('prompt'))
payload["hr_prompt"] = str(self.command.get('highres_prompt'))
if self.command.get('highres_neg_prompt') != '':
if '<neg_prompt>' in self.command.get('highres_neg_prompt'):
self.command['highres_neg_prompt'] = self.command.get('highres_neg_prompt').replace('<neg_prompt>', self.command.get('neg_prompt'))
payload["hr_negative_prompt"] = str(self.command.get('highres_neg_prompt'))
if self.command.get('highres_steps') != '':
payload["hr_second_pass_steps"] = self.command.get('highres_steps')
# add upscaling factor if necessary
if control.config.get('hires_fix_mode') == 'advanced':
if self.command.get('highres_scale_factor') == '':
# set default so we'll have it in metadata
self.command['highres_scale_factor'] = 2.0
payload["hr_scale"] = self.command.get('highres_scale_factor')
else:
# remove these so they don't go into metadata when HR fix is disabled
self.command['highres_scale_factor'] = ''
self.command['highres_upscaler'] = ''
self.command['highres_ckpt_file'] = ''
self.command['highres_sampler'] = ''
self.command['highres_scheduler'] = ''
self.command['highres_steps'] = ''
self.command['highres_prompt'] = ''
self.command['highres_neg_prompt'] = ''
# add styles to payload if present
if self.command.get('styles') != None and len(self.command.get('styles')) > 0:
payload["styles"] = self.command.get('styles')
# add refiner to payload if present
if self.command.get('refiner_ckpt_file') != '':
payload["refiner_checkpoint"] = str(self.command.get('refiner_ckpt_file'))
if self.command.get('refiner_switch') != '':
payload["refiner_switch_at"] = self.command.get('refiner_switch')
# add CN params to existing payload if ControlNet is enabled
# https://github.com/Mikubill/sd-webui-controlnet/wiki/API
if use_controlnet:
cn_payload = {
"ControlNet": {
"args": [{
"input_image": cn_img_payload,
"mask": "",
"module": str(self.command.get('controlnet_pre')),
"model": str(self.command.get('controlnet_model')),
"weight": float(self.command.get('controlnet_weight')),
#"resize_mode": "Scale to Fit (Inner Fit)",
"lowvram": self.command.get('controlnet_lowvram'),
#"processor_res": cn_params[0],
#"threshold_a": cn_params[1],
#"threshold_b": cn_params[2],
"guidance_start": 0,
"guidance_end": 1,
"control_mode": str(self.command.get('controlnet_controlmode')),
"pixel_perfect": self.command.get('controlnet_pixelperfect')
#"guessmode": self.command.get('controlnet_guessmode') # removed in CN extension v 1.1.09
}]
}
}
#payload["alwayson_scripts"] = cn_payload
payload["alwayson_scripts"].update(cn_payload)
# add ADetailer params to existing payload if ADetailer is enabled
# https://github.com/Bing-su/adetailer/wiki/API
if use_adetailer:
ad_payload = utils.build_adetailer_payload(self.command, True)
if self.command.get('input_image') != '':
ad_payload = utils.build_adetailer_payload(self.command, False)
payload["alwayson_scripts"].update(ad_payload)
# handle override settings here: clip_skip, vae, etc
override_settings = {}
if self.command.get('clip_skip') != '':
override_settings["CLIP_stop_at_last_layers"] = int(self.command.get('clip_skip'))
if self.command.get('input_image') == '' and self.command['highres_fix'] == 'yes' and self.command.get('highres_vae') != '':
# BK 2023-09-26 revert, no separate Auto1111 VAE API setting
#override_settings["sd_vae"] = str(self.command.get('highres_vae'))
pass
else:
if self.command.get('vae') != '':
override_settings["sd_vae"] = self.command.get('vae')
self.command['highres_vae'] = ''
if override_settings != {}:
payload["override_settings"] = override_settings
else:
# !MODE=process -specific stuff here
process_mode = True
original_exif = metadata.read_exif(self.command.get('input_image'))
original_iptc = metadata.read_iptc(self.command.get('input_image'))
if self.command['use_upscale'] == 'yes' and (self.command['upscale_model'] == 'sd' or self.command['upscale_model'] == 'ultimate'):
# get original image parameters if we're doing a SD upscale
original_details = ''
if original_exif != None:
try:
original_details = original_exif[0x9c9c].decode('utf16')
except KeyError as e:
pass
else:
original_command = utils.extract_params_from_command(original_details)
original_filename = utils.filename_from_abspath(self.command.get('input_image')).lower().strip()
# remove extension
original_filename = original_filename[:-4]
# check for !OUTPUT_DIR, create if necessary
if self.command.get('output_dir') != '':
if not os.path.exists(self.command.get('output_dir')):
try:
# attempt to create output directory
Path(self.command.get('output_dir')).mkdir(parents=True, exist_ok=True)
except:
# error creating specified output_dir, fallback to default
self.print("Specified OUTPUT_DIR could not be created: " + self.command.get('output_dir'))
self.print("Using default output directory instead...")
self.command['output_dir'] = ''
# !MODE = process enters here:
command = utils.create_command(self.command, self.command.get('prompt_file'), self.worker['id'])
if not process_mode:
self.print("starting job #" + str(self.worker['jobs_done']+1) + ": " + command)
else:
self.print("starting job #" + str(self.worker['jobs_done']+1) + ": batch processing...")
start_time = time.time()
self.worker['job_start_time'] = start_time
self.worker['job_prompt_info'] = self.command
output_dir = command.split(" --outdir ",1)[1].strip('\"')
#output_dir = output_dir.replace("../","")
if "cuda:" in self.worker['id']:
gpu_id = self.worker['id'].replace('cuda:', '')
else:
gpu_id = self.worker['id']
#samples_dir = os.path.join(output_dir, "gpu_" + str(gpu_id))
samples_dir = output_dir + '/' + "gpu_" + str(gpu_id)
#self.worker['sdi_instance'].last_job_success = True
if control.config.get('debug_test_mode') and not process_mode:
# simulate SD work
work_time = round(random.uniform(2, 6), 2)
time.sleep(work_time)
else:
# invoke SD
if not process_mode:
if self.command.get('input_image') != '':
if use_controlnet:
#self.worker['sdi_instance'].do_controlnet_img2img(payload, samples_dir)
self.worker['sdi_instance'].do_img2img(payload, samples_dir)
else:
self.worker['sdi_instance'].do_img2img(payload, samples_dir)
else:
if use_controlnet:
#self.worker['sdi_instance'].do_controlnet_txt2img(payload, samples_dir)
self.worker['sdi_instance'].do_txt2img(payload, samples_dir)
else:
self.worker['sdi_instance'].do_txt2img(payload, samples_dir)
while self.worker['sdi_instance'].busy and self.worker['sdi_instance'].isRunning:
time.sleep(0.25)
# upscale here if requested
if (self.worker['sdi_instance'].last_job_success or process_mode) and self.worker['sdi_instance'].isRunning:
# only if we're not shutting down
use_upscale = False
if self.command['use_upscale'] == 'yes':
use_upscale = True
if use_upscale or use_adetailer:
if use_upscale:
self.worker['work_state'] = 'upscaling'
elif use_adetailer:
self.worker['work_state'] = 'adetailer'
else:
self.worker['work_state'] = 'processing'
gpu_id = self.worker['id'].replace("cuda:", "")
if control.config.get('debug_test_mode'):
# simulate upscaling work
work_time = round(random.uniform(0.5, 2), 2)
time.sleep(work_time)
else:
new_files = []
if not process_mode:
# upscale all newly-generated images for non-process mode
new_files = os.listdir(samples_dir)
else:
# if process mode, upscale the designated image
new_files.append(self.command.get('input_image'))
if len(new_files) > 0:
# invoke ESRGAN on entire directory
#utils.upscale(self.command['upscale_amount'], samples_dir, self.command['upscale_face_enh'], gpu_id)
# upscale each image
if not process_mode:
self.worker['sdi_instance'].log('upscaling images...')
else:
if use_upscale:
self.worker['sdi_instance'].log('upscaling ' + self.command.get('input_image') + '...')
elif use_adetailer:
self.worker['sdi_instance'].log('adetailer: ' + self.command.get('input_image') + '...')
else:
self.worker['sdi_instance'].log('processing ' + self.command.get('input_image') + '...')
for file in new_files:
encoded = None
if not process_mode:
encoded = base64.b64encode(open(os.path.join(samples_dir, file), "rb").read())
else:
# this whole process_mode thread is pretty hacky...
encoded = base64.b64encode(open(self.command.get('input_image'), "rb").read())
encodedString = str(encoded, encoding='utf-8')
img_payload = 'data:image/png;base64,' + encodedString
if use_upscale:
if self.command['upscale_model'] != 'sd' and self.command['upscale_model'] != 'ultimate':
# normal upscale
payload = {
#"resize_mode": 0,
#"show_extras_results": true,
"gfpgan_visibility": self.command['upscale_gfpgan_amount'],
"codeformer_visibility": self.command['upscale_codeformer_amount'],
#"codeformer_weight": 0,
"upscaling_resize": self.command['upscale_amount'],
#"upscaling_resize_w": 512,
#"upscaling_resize_h": 512,
#"upscaling_crop": true,
"upscaler_1": self.command['upscale_model'],
#"upscaler_2": "None",
#"extras_upscaler_2_visibility": 0,
#"upscale_first": false,
"image": img_payload
}
self.worker['sdi_instance'].do_upscale(payload, samples_dir)
else:
# SD upscale uses img2img
# use whatever params we can find in original image
sd_sampler = str(self.command.get('sampler'))
if "sampler" in original_command:
sd_sampler = original_command['sampler']
# validate sampler in case we're upscaling very old images
if control.prompt_manager != None:
# TODO: should instantiate new prompt_manager if we don't have one yet
sd_sampler = control.prompt_manager.validate_sampler(sd_sampler, True)
sd_vae = str(self.command.get('vae'))
if "vae" in original_command:
sd_vae = original_command['vae']
sd_prompt = str(self.command.get('prompt'))
if "prompt" in original_command:
sd_prompt = original_command['prompt']
sd_neg_prompt = str(self.command.get('neg_prompt'))
if "neg_prompt" in original_command:
sd_neg_prompt = original_command['neg_prompt']
sd_seed = str(self.command.get('seed'))
if "seed" in original_command:
try:
sd_seed = int(original_command['seed'])
except:
pass
sd_steps = self.command.get('steps')
if "steps" in original_command:
try:
sd_steps = int(original_command['steps'])
except:
pass
sd_scale = self.command.get('scale')
if "scale" in original_command:
try:
sd_scale = float(original_command['scale'])
except:
pass
sd_tiling = self.command.get('tiling')
if "tiling" in original_command:
if original_command['tiling'] == 'yes':
sd_tiling = True
else:
sd_tiling = False
# grab styles from original command and put into list
styles = []
if "styles" in original_command:
if original_command['styles'] != '':
temp = original_command['styles'].split(',')
for t in temp:
styles.append(t.strip())
# calculate max output size for sd_upscale
orig_width = 0
orig_height = 0
sd_width = 512
sd_height = 512
if self.command['upscale_model'] == 'sd':
with Image.open(self.command.get('input_image')) as img:
orig_width, orig_height = img.size
set_max_output_size = control.config.get('max_output_size')
# check for overrides in process mode directives
if self.command.get('override_max_output_size') != 0:
set_max_output_size = int(self.command.get('override_max_output_size'))
new_dimensions = utils.get_largest_possible_image_size([orig_width, orig_height], set_max_output_size, True)
if new_dimensions != []:
sd_width = new_dimensions[0]
sd_height = new_dimensions[1]
self.command['width'] = sd_width
self.command['height'] = sd_height
else:
control.print('Error: SD upscale unable to find appropriate upscale size under MAX_OUTPUT_SIZE for ' + str(self.command.get('input_image')) + '!')
if self.command.get('override_steps') != 0:
sd_steps = self.command.get('override_steps')
if self.command.get('override_sampler') != '':
sd_sampler = self.command.get('override_sampler')
# check if a model change is needed before upscaling
override_model = ''
sd_model = str(self.command.get('ckpt_file'))
if "ckpt_file" in original_command:
sd_model = original_command['ckpt_file']
sd_model = control.validate_model(sd_model)
# check if we're overriding the model for upscaling
if self.command.get('override_ckpt_file') != '':
override_model = control.validate_model(self.command.get('override_ckpt_file'))
if override_model != '':
sd_model = override_model
# check if a refiner model is available if necessary
if override_model == '':
if control.config.get('auto_use_refiner'):
refiner_model = original_command['ckpt_file'].replace('.safetensors', '').replace('.ckpt', '')
if '[' in refiner_model:
refiner_model = refiner_model.split('[', 1)[0].strip()
refiner_model = refiner_model + '_refiner'
refiner_model = control.validate_model(refiner_model)
if refiner_model != '':
sd_model = refiner_model
if sd_model != '' and (sd_model != self.worker['sdi_instance'].model_loaded):
self.worker['sdi_instance'].load_model(sd_model)
while self.worker['sdi_instance'].options_change_in_progress:
# wait for model change to complete
time.sleep(0.25)
payload = {
"init_images": [img_payload],
"sampler_index": str(sd_sampler),
#"resize_mode": 0,
"denoising_strength": self.command.get('upscale_sd_strength'),
"prompt": str(sd_prompt),
"seed": str(sd_seed),
"batch_size": 1,
"n_iter": 1,
"steps": sd_steps,
"cfg_scale": sd_scale,
"width": sd_width,
"height": sd_height,
#"restore_faces": False,
"tiling": sd_tiling,
"negative_prompt": sd_neg_prompt,
"alwayson_scripts": {}
}
# add styles to payload if present
if styles != []:
payload["styles"] = styles
override_settings = {}
if self.command.get('clip_skip') != '':
override_settings["CLIP_stop_at_last_layers"] = int(self.command.get('clip_skip'))
if self.command.get('override_vae') != '':
override_settings["sd_vae"] = self.command.get('override_vae')
else:
if override_model == '':
if sd_vae != '':
override_settings["sd_vae"] = sd_vae
if override_settings != {}:
payload["override_settings"] = override_settings
# add additional sd_ultimate_upscale params if necessary
if self.command['upscale_model'] == 'ultimate':
up_index = control.get_upscale_model_index(self.command['upscale_ult_model'])
if up_index == -1:
up_index = control.get_upscale_model_index('ESRGAN_4x')
if up_index == -1:
up_index = 0
custom_scale = 2.0
if 'upscale_amount' in self.command and float(self.command['upscale_amount']) > 1.0:
custom_scale = self.command['upscale_amount']
custom_scale = float(custom_scale)
# docs: https://github.com/Coyote-A/ultimate-upscale-for-automatic1111
payload["script_name"] = "ultimate sd upscale"
payload["script_args"] = [
"", # (not used)
512, # tile_width
512, # tile_height
8, # mask_blur
32, # padding
64, # seams_fix_width
0.35, # seams_fix_denoise
32, # seams_fix_padding
up_index, # upscaler_index
True, # save_upscaled_image a.k.a Upscaled
0, # redraw_mode
False, # save_seams_fix_image a.k.a Seams fix
8, # seams_fix_mask_blur
0, # seams_fix_type
2, # target_size_type (0 = From img2img2 settings, 1 = Custom size, 2 = Scale from image size)
2048, # custom_width
2048, # custom_height
custom_scale # custom_scale
]
# add adetailer if specified
if use_adetailer:
ad_payload = utils.build_adetailer_payload(self.command, True)
payload["alwayson_scripts"].update(ad_payload)
self.worker['sdi_instance'].do_img2img(payload, samples_dir)
else:
# We're just doing ADetailer; no upscale...
payload = {
"init_images": [img_payload],
"alwayson_scripts": {}
}
ad_payload = utils.build_adetailer_payload(self.command, True)
payload["alwayson_scripts"].update(ad_payload)
self.worker['sdi_instance'].do_img2img(payload, samples_dir)
while self.worker['sdi_instance'].busy and self.worker['sdi_instance'].isRunning:
time.sleep(0.25)
# remove originals if upscaled version present
if not process_mode:
new_files = os.listdir(samples_dir)
for f in new_files:
if (".png" in f):
basef = f.replace(".png", "")
if basef[-2:] == "_u":
# this is an upscaled image, delete the original
# or save it in /original if desired
if exists(samples_dir + "/" + basef[:-2] + ".png"):
if self.command['upscale_keep_org'] == 'yes':
# move the original to /original
orig_dir = output_dir + "/original"
Path(orig_dir).mkdir(parents=True, exist_ok=True)
os.replace(samples_dir + "/" + basef[:-2] + ".png", \
orig_dir + "/" + basef[:-2] + ".png")
else:
os.remove(samples_dir + "/" + basef[:-2] + ".png")
# find the new image(s) that SD created: re-name, process, and move them
if self.worker['sdi_instance'].last_job_success and self.worker['sdi_instance'].isRunning:
# only if we're not shutting down
self.worker['work_state'] = "+exif data"
if control.config.get('debug_test_mode'):
# simulate metadata work
work_time = round(random.uniform(1, 2), 2)
time.sleep(work_time)
else:
new_files = []
if exists(samples_dir):
new_files = os.listdir(samples_dir)
nf_count = 0
for f in new_files:
if (".png" in f):
# save just the essential prompt params to metadata