-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathimage_server.py
3379 lines (2817 loc) · 154 KB
/
image_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
print("Importing libraries. This may take one or more minutes.")
try:
# Import core libraries
import os, re, time, sys, asyncio, ctypes, math, threading, platform, json, sys, contextlib
import torch
import scipy
import numpy as np
from random import randint
from omegaconf import OmegaConf
from PIL import Image, ImageEnhance, ImageFilter
import cv2
from itertools import product
from einops import rearrange
from pytorch_lightning import seed_everything
from transformers import BlipProcessor, BlipForConditionalGeneration, set_seed
from typing import Optional
from safetensors.torch import load_file
from cryptography.fernet import Fernet
# Import built libraries
from ldm.util import instantiate_from_config, max_tile
from optimization.pixelvae import load_pixelvae_model
from optimization.taesd import TAESD
from lora import (
apply_lora,
assign_lora_names_to_compvis_modules,
load_lora,
load_lora_raw,
register_lora_for_inference,
remove_lora_for_inference,
)
from upsample_prompts import load_chat_pipeline, upsample_caption, collect_response
import segmenter
import hitherdither
# Import PyTorch functions
from torch import autocast
from torch import Tensor
from torch.nn import functional as F
from torch.nn.modules.utils import _pair
# Import logging libraries
import traceback, warnings
import logging as pylog
from transformers.utils import logging
# Import websocket tools
import requests
from websockets import serve
from io import BytesIO
import base64
# Import CLDM requirements
from cldm_inference import load_controlnet, sample_cldm, unload_cldm
# Import console management libraries
from rich import print as rprint
with warnings.catch_warnings():
warnings.simplefilter("ignore")
try:
import pygetwindow as gw
except:
pass
from colorama import just_fix_windows_console
import playsound
system = platform.system()
if system == "Windows":
# Fix windows console for color codes
just_fix_windows_console()
# Patch existing console to remove interactivity
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-10), 128)
# Disable all logging for pytorch lightning
log = pylog.getLogger("lightning_fabric")
log.propagate = False
log.setLevel(pylog.ERROR)
logging.set_verbosity(logging.CRITICAL)
except:
import traceback
print(f"ERROR:\n{traceback.format_exc()}")
input("Catastrophic failure, send this error to the developer.\nPress any key to exit.")
exit()
# Global variables
global modelName
modelName = None
global modelSettings
modelSettings = None
# Unet
global model
# Conditioning (clip)
global modelCS
# VAE (Unused, replaced by TAE)
global modelFS
# TAE
global modelTA
# Pixel VAE
global modelPV
# Language model
global modelLM
modelLM = None
# Image classifier
global modelBLIP
modelBLIP = None
global modelType
global running
global loadedDevice
loadedDevice = "cpu"
global modelPath
global system_models
system_models = ["quality", "resfix", "crop", "detail", "brightness", "contrast", "saturation", "outline", "color_cr", "color_mg", "color_yb", "light_bf", "light_du", "light_lr"]
global sounds
sounds = False
expectedVersion = "10.5.0"
global maxSize
# model loading globals
global split_loaded
split_loaded = False
# For testing only, limits memory usage to "maxMemory"
maxSize = 512
maxMemory = 4
if False:
cardMemory = torch.cuda.get_device_properties("cuda").total_memory / 1073741824
usedMemory = cardMemory - (torch.cuda.mem_get_info()[0] / 1073741824)
fractionalMaxMemory = (maxMemory - (usedMemory + 0.3)) / cardMemory
print(usedMemory)
print(cardMemory)
print(maxMemory)
print(cardMemory * fractionalMaxMemory)
torch.cuda.set_per_process_memory_fraction(fractionalMaxMemory)
global timeout
global loaded
loaded = ""
# Clears pytorch and mps cache
def clearCache():
global loadedDevice
torch.cuda.empty_cache()
if torch.backends.mps.is_available() and loadedDevice != "cpu":
try:
torch.mps.empty_cache()
except:
pass
# Play sound file
def audioThread(file):
try:
absoluteFile = os.path.abspath(f"../sounds/{file}")
with warnings.catch_warnings():
warnings.simplefilter("ignore")
playsound.playsound(absoluteFile)
except:
pass
# Async audio manager
def play(file):
global sounds
if sounds:
try:
threading.Thread(target=audioThread, args=(file,), daemon=True).start()
except:
pass
# Calculate precision mode by gpu
def get_precision(device, precision):
fp16_mode = torch.bfloat16
try:
fp8_mode = torch.float8_e4m3fn
except:
if precision == "fp8":
precision = "fp16"
fp8_mode = torch.bfloat16
if device == "cuda" and torch.cuda.is_available():
# If GPU is nvidia 10xx force fp32 precision
gpu_name = torch.cuda.get_device_name(device)
if gpu_name.startswith("NVIDIA GeForce GTX 10"):
if device == "cuda" and (precision == "fp8" or precision == "fp16"):
precision = "fp32"
# If GPU is nvidia 16xx, use float16 and enable benchmark mode
elif torch.cuda.get_device_capability(device) == (7, 5) and gpu_name.startswith("NVIDIA GeForce GTX 16"):
torch.backends.cudnn.benchmark = True
fp16_mode = torch.float16
if device == "cuda" and (precision == "fp8" or precision == "fp16"):
precision = "fp16"
# If GPU is nvidia 20xx disable float8 precision
elif gpu_name.startswith("NVIDIA GeForce GTX 20"):
if device == "cuda" and (precision == "fp8" or precision == "fp16"):
fp16_mode = torch.float16
precision = "fp16"
# If GPU is not nvidia
elif not "NVIDIA" in gpu_name:
fp16_mode = torch.float16
precision = "fp32"
else:
# Fallback to fp32 precision
fp16_mode = torch.float16
precision = "fp32"
return precision, fp16_mode, fp8_mode
# Determine correct autocast mode
def autocast(device, precision, dtype = torch.float16):
if device == "cuda" and torch.cuda.is_available():
gpu_properties = torch.cuda.get_device_properties(device)
gpu_name = gpu_properties.name
if "NVIDIA" in gpu_name:
if re.search(r"1[06]\d{2}", gpu_name):
# Get manual autocast working
return contextlib.nullcontext()
else:
if precision == "fp32":
return contextlib.nullcontext()
else:
return torch.autocast("cuda", dtype=dtype, enabled=True)
else:
# Get manual autocast working
return contextlib.nullcontext()
if device == "cpu" or device == "mps" or precision == "fp32":
return contextlib.nullcontext()
return contextlib.nullcontext()
# Patch the Conv2d class with a custom __init__ method
def patch_conv(**patch):
cls = torch.nn.Conv2d
init = cls.__init__
def __init__(self, *args, **kwargs):
# Call the original init method and apply the patch arguments
return init(self, *args, **kwargs, **patch)
cls.__init__ = __init__
# Patch Conv2d layers in the given model for asymmetric padding
def patch_conv_asymmetric(model, x, y):
for layer in flatten(model):
if type(layer) == torch.nn.Conv2d:
# Set padding mode based on x and y arguments
layer.padding_modeX = "circular" if x else "constant"
layer.padding_modeY = "circular" if y else "constant"
# Compute padding values based on reversed padding repeated twice
layer.paddingX = (layer._reversed_padding_repeated_twice[0], layer._reversed_padding_repeated_twice[1], 0, 0)
layer.paddingY = (0, 0, layer._reversed_padding_repeated_twice[2], layer._reversed_padding_repeated_twice[3])
# Patch the _conv_forward method with a replacement function
layer._conv_forward = __replacementConv2DConvForward.__get__(layer, torch.nn.Conv2d)
# Restore original _conv_forward method for Conv2d layers in the model
def restoreConv2DMethods(model):
for layer in flatten(model):
if type(layer) == torch.nn.Conv2d:
layer._conv_forward = torch.nn.Conv2d._conv_forward.__get__(layer, torch.nn.Conv2d)
# Replacement function for Conv2d's _conv_forward method
def __replacementConv2DConvForward(self, input: Tensor, weight: Tensor, bias: Optional[Tensor]):
working = F.pad(input, self.paddingX, mode=self.padding_modeX)
working = F.pad(working, self.paddingY, mode=self.padding_modeY)
return F.conv2d(working, weight, bias, self.stride, _pair(0), self.dilation, self.groups)
# Patch Conv2d layers in the given models for asymmetric padding
def patch_tiling(tilingX, tilingY, model, modelTA, modelPV):
# Patch for relevant models
patch_conv_asymmetric(model, tilingX, tilingY)
patch_conv_asymmetric(modelTA, tilingX, tilingY)
patch_conv_asymmetric(modelPV.model, tilingX, tilingY)
if tilingX or tilingY:
# Print a message indicating the direction(s) patched for tiling
rprint("[#494b9b]Patched for tiling in the [#48a971]" + "X" * tilingX + "[#494b9b] and [#48a971]" * (tilingX and tilingY) + "Y" * tilingY + "[#494b9b] direction" + "s" * (tilingX and tilingY))
return model, modelTA, modelPV
def remove_repeated_words(string):
# Splitting the string by spaces to preserve original punctuation
parts = string.split()
normalized_parts = []
separators = []
# Normalize parts and remember original separators
for part in parts:
if part.endswith(","):
normalized_parts.append(part[:-1])
separators.append(", ")
else:
normalized_parts.append(part)
separators.append(" ")
# Check for repetitions from the end
if len(normalized_parts) > 1:
i = -2
while -i <= len(normalized_parts) and normalized_parts[-1] == normalized_parts[i]:
i -= 1
if i != -2:
# Keep one instance of the repeated word
final_parts = normalized_parts[:i+2]
else:
final_parts = normalized_parts
else:
final_parts = normalized_parts
# Reconstruct the string using the original separators
reconstructed_string = ""
for i, part in enumerate(final_parts):
if i < len(separators) - 1: # Avoid index out of range
reconstructed_string += part + separators[i]
else:
reconstructed_string += part # Last part, no separator
# Handling trailing separators if the last part was a repetition
if reconstructed_string.endswith(", "):
reconstructed_string = reconstructed_string[:-2]
elif reconstructed_string.endswith(" "):
reconstructed_string = reconstructed_string[:-1]
return reconstructed_string
# Print image in console
def climage(image, alignment, *args):
# Get console bounds with a small margin - better safe than sorry
twidth, theight = (os.get_terminal_size().columns - 1, (os.get_terminal_size().lines - 1) * 2)
# Set up variables
image = image.convert("RGBA")
iwidth, iheight = min(twidth, image.width), min(theight, image.height)
line = []
lines = []
# Alignment stuff
margin = 0
if alignment == "centered":
margin = int((twidth / 2) - (iwidth / 2))
elif alignment == "right":
margin = int(twidth - iwidth)
elif alignment == "manual":
margin = args[0]
# Loop over the height of the image / 2 (because 2 pixels = 1 text character)
for y2 in range(int(iheight / 2)):
# Add default colors to the start of the line
line = [" " * margin]
# Loop over width
for x in range(iwidth):
# Get the color for the upper and lower half of the text character
r, g, b, a = image.getpixel((x, (y2 * 2)))
r2, g2, b2, a2 = image.getpixel((x, (y2 * 2) + 1))
# Set text characters, nothing, full block, half block. Half block + background color = 2 pixels
if a < 200 and a2 < 200:
line.append(f" ")
else:
# Convert to hex colors for Rich to use
rgb, rgb2 = "#{:02x}{:02x}{:02x}".format(r, g, b), "#{:02x}{:02x}{:02x}".format(r2, g2, b2)
# Lookup table because I was bored
colorCodes = [f"{rgb2} on {rgb}", f"{rgb2}", f"{rgb}", "nothing", f"{rgb}"]
# ~It just works~
maping = (int(a < 200) + (int(a2 < 200) * 2) + (int(rgb == rgb2 and a + a2 > 400) * 4))
color = colorCodes[maping]
if rgb == rgb2:
line.append(f"[{color}]█[/]")
else:
if maping == 2:
line.append(f"[{color}]▀[/]")
else:
line.append(f"[{color}]▄[/]")
# Add default colors to the end of the line
lines.append("".join(line) + "\u202F")
return " \n".join(lines)
# Print progress bar in console
def clbar(iterable, name="", printEnd="\r", position="", unit="it", disable=False, prefixwidth=1, suffixwidth=1, total=0):
# Console manipulation stuff
def up(lines=1):
for _ in range(lines):
sys.stdout.write("\x1b[1A")
sys.stdout.flush()
def down(lines=1):
for _ in range(lines):
sys.stdout.write("\n")
sys.stdout.flush()
# Allow the complete disabling of the progress bar
if not disable:
# Positions the bar correctly
down(int(position == "last") * 2)
up(int(position == "first") * 3)
# Set up variables
if total > 0:
# iterable = iterable[0:total]
pass
else:
total = max(1, len(iterable))
name = f"{name}"
speed = f" {total}/{total} at 100.00 {unit}/s "
prediction = f" 00:00 < 00:00 "
prefix = max(len(name), len("100%"), prefixwidth)
suffix = max(len(speed), len(prediction), suffixwidth)
barwidth = os.get_terminal_size().columns - (suffix + prefix + 2)
# Prints the progress bar
def printProgressBar(iteration, delay):
# Define progress bar graphic
line1 = [
"[#494b9b on #3b1725]▄[/#494b9b on #3b1725]",
"[#c4f129 on #494b9b]▄[/#c4f129 on #494b9b]" * int(int(barwidth * min(total, iteration) // total) > 0),
"[#ffffff on #494b9b]▄[/#ffffff on #494b9b]" * max(0, int(barwidth * min(total, iteration) // total) - 2),
"[#c4f129 on #494b9b]▄[/#c4f129 on #494b9b]" * int(int(barwidth * min(total, iteration) // total) > 1),
"[#3b1725 on #494b9b]▄[/#3b1725 on #494b9b]" * max(0, barwidth - int(barwidth * min(total, iteration) // total)),
"[#494b9b on #3b1725]▄[/#494b9b on #3b1725]",
]
line2 = [
"[#3b1725 on #494b9b]▄[/#3b1725 on #494b9b]",
"[#494b9b on #48a971]▄[/#494b9b on #48a971]" * int(int(barwidth * min(total, iteration) // total) > 0),
"[#494b9b on #c4f129]▄[/#494b9b on #c4f129]" * max(0, int(barwidth * min(total, iteration) // total) - 2),
"[#494b9b on #48a971]▄[/#494b9b on #48a971]" * int(int(barwidth * min(total, iteration) // total) > 1),
"[#494b9b on #3b1725]▄[/#494b9b on #3b1725]" * max(0, barwidth - int(barwidth * min(total, iteration) // total)),
"[#3b1725 on #494b9b]▄[/#3b1725 on #494b9b]",
]
percent = ("{0:.0f}").format(100 * (min(total, iteration) / float(total)))
# Avoid predicting speed until there's enough data
if len(delay) >= 1:
delay.append(time.time() - delay[-1])
del delay[-2]
# Fancy color stuff and formating
if iteration == 0:
speedColor = "[#48a971]"
measure = f"... {unit}/s"
passed = f"00:00"
remaining = f"??:??"
else:
if np.mean(delay) <= 1:
measure = f"{round(1/max(0.01, np.mean(delay)), 2)} {unit}/s"
else:
measure = f"{round(np.mean(delay), 2)} s/{unit}"
if np.mean(delay) <= 1:
speedColor = "[#c4f129]"
elif np.mean(delay) <= 10:
speedColor = "[#48a971]"
elif np.mean(delay) <= 30:
speedColor = "[#494b9b]"
else:
speedColor = "[#ab333d]"
passed = "{:02d}:{:02d}".format(math.floor(sum(delay) / 60), round(sum(delay)) % 60)
remaining = "{:02d}:{:02d}".format(math.floor((total * np.mean(delay) - sum(delay)) / 60), round(total * np.mean(delay) - sum(delay)) % 60)
speed = f" {min(total, iteration)}/{total} at {measure} "
prediction = f" {passed} < {remaining} "
# Print single bar across two lines
rprint(f'\r{f"{name}".center(prefix)} {"".join(line1)}{speedColor}{speed.center(suffix-1)}[white]')
rprint(f'[#48a971]{f"{percent}%".center(prefix)}[/#48a971] {"".join(line2)}[#494b9b]{prediction.center(suffix-1)}', end=printEnd)
delay.append(time.time())
return delay
# Print at 0 progress
delay = []
delay = printProgressBar(0, delay)
down(int(position == "first") * 2)
# Update the progress bar
for i, item in enumerate(iterable):
yield item
up(int(position == "first") * 2 + 1)
delay = printProgressBar(i + 1, delay)
down(int(position == "first") * 2)
down(int(position != "first"))
else:
for i, item in enumerate(iterable):
yield item
# Encode pil image bytes as base64 string
def encodeImage(image, format):
if format == "png":
buffer = BytesIO()
image.save(buffer, format="PNG")
image_bytes = buffer.getvalue()
return base64.b64encode(image_bytes).decode("utf-8")
else:
return base64.b64encode(image.convert("RGBA").tobytes()).decode("utf-8")
# Decode base64 string to pil image
def decodeImage(imageString):
try:
if imageString["format"] == "png":
return Image.open(BytesIO(base64.b64decode(imageString["image"]))).convert("RGB")
else:
return Image.frombytes(format, (imageString["width"], imageString["height"]), base64.b64decode(imageString["image"])).convert("RGB")
except:
rprint(f"\n[#ab333d]ERROR: Image cannot be decoded from bytes. It may have been corrupted.")
print(imageString)
return None
# Open the image and convert it to a tensor with values with range -1, 1
def load_img(image, h0, w0):
image.convert("RGB")
w, h = image.size
# Override the image size if h0 and w0 are provided
if h0 is not None and w0 is not None:
h, w = h0, w0
# Adjust the width and height to be divisible by 8 and resize the image using bicubic resampling
w, h = map(lambda x: x - x % 8, (w, h))
image = image.resize((w, h), resample=Image.Resampling.BICUBIC)
# Color adjustments to account for Tiny Autoencoder
contrast = ImageEnhance.Contrast(image)
image_contrast = contrast.enhance(0.78)
saturation = ImageEnhance.Color(image_contrast)
image_saturation = saturation.enhance(0.833)
# Convert the image to a numpy array of float32 values in the range [0, 1], transpose it, and convert it to a PyTorch tensor
image = np.array(image_saturation).astype(np.float32) / 255
image = rearrange(image, "h w c -> c h w")
image = torch.from_numpy(image).unsqueeze(0)
# Apply a normalization by scaling the values in the range [-1, 1]
return image
# Run blip captioning for each image in a set with optional starting prompts
def caption_images(blip, images, prompt=None):
processor = blip["processor"]
model = blip["model"]
outputs = []
for image in images:
if prompt is not None:
inputs = processor(image, prompt, return_tensors="pt")
else:
inputs = processor(image, return_tensors="pt")
outputs.append(processor.decode(model.generate(**inputs, max_new_tokens=30)[0], skip_special_tokens=True))
return outputs
# Flatten a model into its layers
def flatten(el):
# Flatten nested elements by recursively traversing through children
flattened = [flatten(children) for children in el.children()]
res = [el]
for c in flattened:
res += c
return res
# Gamma adjustment
def adjust_gamma(image, gamma=1.0):
# Create a lookup table for the gamma function
gamma_map = [255 * ((i / 255.0) ** (1.0 / gamma)) for i in range(256)]
gamma_table = bytes([(int(x / 255.0 * 65535.0) >> 8) for x in gamma_map] * 3)
# Apply the gamma correction using the lookup table
return image.point(gamma_table)
# Load blip image captioning model
def load_blip(path):
timer = time.time()
print("\nLoading vision model")
try:
processor = BlipProcessor.from_pretrained(path)
model = BlipForConditionalGeneration.from_pretrained(path)
play("iteration.wav")
rprint(f"[#c4f129]Loaded in [#48a971]{round(time.time()-timer, 2)} [#c4f129]seconds")
return {"processor": processor, "model": model}
except Exception as e:
rprint(f"[#ab333d]{traceback.format_exc()}\n\nBLIP could not be loaded, this may indicate a model has not been downloaded fully, or you have run out of RAM.")
return None
# Helper for loading model files
def load_model_from_config(model, verbose=False):
# Load the model's state dictionary from the specified file
try:
# First try to load as a Safetensor, then as a pickletensor
try:
pl_sd = load_file(model, device="cpu")
except:
rprint(f"[#ab333d]Model is not a Safetensor. Please consider using Safetensors format for better security.")
pl_sd = torch.load(model, map_location="cpu")
sd = pl_sd
# If "state_dict" is found in the loaded dictionary, assign it to sd
if "state_dict" in sd:
sd = pl_sd["state_dict"]
return sd
except Exception as e:
rprint(f"[#ab333d]{traceback.format_exc()}\n\nThis may indicate a model has not been downloaded fully, or is corrupted.")
# Load stable diffusion 1.5 format model
def load_model(modelFileString, config, device, precision, optimized, split = True):
global modelName
global modelSettings
modelParams = {"file": modelFileString, "device": device, "precision": precision, "optimized": optimized, "split": split}
if modelSettings != modelParams:
timer = time.time()
global split_loaded
if not split_loaded:
unload_cldm()
if device == "cuda" and not torch.cuda.is_available():
if torch.backends.mps.is_available():
device = "mps"
else:
device = "cpu"
rprint(f"\n[#ab333d]GPU is not responding, loading model in CPU mode")
global loadedDevice
global modelType
global modelPath
modelPath, modelFile = os.path.split(modelFileString)
loadedDevice = device
# Check the modelFile and print corresponding loading message
print()
modelType = "pixel"
if modelFile == "model.pxlm":
print(f"Loading primary model")
elif modelFile == "modelmicro.pxlm":
print(f"Loading micro model")
elif modelFile == "modelmini.pxlm":
print(f"Loading mini model")
elif modelFile == "modelmega.pxlm":
print(f"Loading mega model")
elif modelFile == "paletteGen.pxlm":
modelType = "palette"
print(f"Loading PaletteGen model")
else:
modelType = "general"
rprint(f"Loading custom model from [#48a971]{modelFile}")
# Determine if turbo mode is enabled
turbo = True
if optimized and device == "cuda":
turbo = False
# Load the model's state dictionary from the specified file
sd = load_model_from_config(f"{os.path.join(modelPath, modelFile)}")
# Separate the input and output blocks from the state dictionary
if split:
li, lo = [], []
for key, value in sd.items():
sp = key.split(".")
if (sp[0]) == "model":
if "input_blocks" in sp:
li.append(key)
elif "middle_block" in sp:
li.append(key)
elif "time_embed" in sp:
li.append(key)
else:
lo.append(key)
# Reorganize the state dictionary keys to match the model structure
for key in li:
sd["model1." + key[6:]] = sd.pop(key)
for key in lo:
sd["model2." + key[6:]] = sd.pop(key)
# Load the model configuration
config = OmegaConf.load(f"{config}")
global modelPV
# Ignore an annoying userwaring
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Load the pixelvae
decoder_path = os.path.abspath("models/decoder/decoder.px")
modelPV = load_pixelvae_model(decoder_path, device, "eVWtlIBjTRr0-gyZB0smWSwxCiF8l4PVJcNJOIFLFqE=")
# Instantiate and load the main model
if split:
global model
model = instantiate_from_config(config.model_unet)
_, _ = model.load_state_dict(sd, strict=False)
model.eval()
model.unet_bs = 1
model.cdevice = device
model.turbo = turbo
# Instantiate and load the conditional stage model
global modelCS
modelCS = instantiate_from_config(config.model_cond_stage)
_, _ = modelCS.load_state_dict(sd, strict=False)
modelCS.eval()
modelCS.cond_stage_model.device = device
# Instantiate and load the first stage model
global modelTA
modelTA = TAESD().to(device)
# Set precision and device settings
precision, fp16_mode, fp8_mode = get_precision(device, precision)
if device == "cuda" and precision == "fp16":
if split:
model.to(fp16_mode)
modelCS.to(fp16_mode)
modelTA.to(fp16_mode)
precision = fp16_mode
elif device == "cuda" and precision == "fp8":
if split:
model.to(fp8_mode)
for layer in flatten(modelCS):
if isinstance(layer, torch.nn.Linear):
layer.to(fp8_mode)
modelTA.to(fp16_mode)
precision = fp8_mode
rprint(f"Applied [#48a971]torch.fp8[/] to model")
else:
precision = torch.float32
if split:
model.to(precision)
modelCS.to(precision)
modelTA.to(precision)
if split:
assign_lora_names_to_compvis_modules(model, modelCS)
modelName = modelFileString
modelSettings = modelParams
# Print loading information
play("iteration.wav")
rprint(f"[#c4f129]Loaded model to [#48a971]{device}[#c4f129] with [#48a971]{precision} precision[#c4f129] in [#48a971]{round(time.time()-timer, 2)} [#c4f129]seconds")
if split:
split_loaded = True
else:
split_loaded = False
return sd, modelFileString
# Apply prompt enhancements, defaults, and language model management
def managePrompts(prompt, negative, W, H, seed, upscale, generations, loras, translate, promptTuning):
timer = time.time()
global modelLM
global loadedDevice
global modelType
global sounds
global modelPath
prompts = [prompt] * generations
if translate:
# Check GPU VRAM to ensure LLM compatibility because users can't be trusted to select settings properly T-T
cardMemory = torch.cuda.get_device_properties("cuda").total_memory / 1073741824
if cardMemory >= 7.6:
if cardMemory <= 10.2:
rprint(f"\n[#494b9b]Memory is less than 10GB, image generation speed may suffer with LLM loaded.")
try:
# Load LLM for prompt upsampling
if modelLM == None:
print("\nLoading prompt translation language model")
modelLM = load_chat_pipeline(os.path.join(modelPath, "LLM"))
play("iteration.wav")
rprint(f"[#c4f129]Loaded in [#48a971]{round(time.time()-timer, 2)} [#c4f129]seconds")
if modelLM is not None:
try:
# Generate responses
rprint(f"\n[#48a971]Translation model [white]generating [#48a971]{generations} [white]enhanced prompts")
upsampled_captions = []
for prompt in clbar(prompts, name="Enhancing", position="", unit="prompt", prefixwidth=12, suffixwidth=28):
# Try to generate a response, if no response is identified after retrys, set upsampled prompt to initial prompt
upsampled_caption = None
retrys = 5
while upsampled_caption == None and retrys > 0:
outputs = upsample_caption(modelLM, prompt, seed)
upsampled_caption = collect_response(outputs)
retrys -= 1
seed += 1
if upsampled_caption == None:
upsampled_caption = prompt
upsampled_captions.append(upsampled_caption)
play("iteration.wav")
prompts = upsampled_captions
del outputs, upsampled_caption
clearCache()
seed = seed - len(prompts)
print()
for i, prompt in enumerate(prompts[:8]):
rprint(f"[#48a971]Seed: [#c4f129]{seed}[#48a971] Prompt: [#494b9b]{prompt}")
seed += 1
if len(prompts) > 8:
rprint(f"[#48a971]Remaining prompts generated but not displayed.")
except:
rprint(f"\n[#494b9b]Prompt enhancement failed unexpectedly. Prompts will not be edited.")
except Exception as e:
if "torch.cuda.OutOfMemoryError" in traceback.format_exc() or "Invalid buffer size" in traceback.format_exc():
rprint(f"\n[#494b9b]Translation model could not be loaded due to insufficient GPU resources.")
elif "GPU is required" in traceback.format_exc():
rprint(f"\n[#494b9b]Translation model requires a GPU to be loaded.")
else:
rprint(f"\n[#ab333d]ERROR:\n{traceback.format_exc()}")
rprint(f"\n[#494b9b]Translation model could not be loaded.")
else:
rprint(f"\n[#494b9b]Translation model requires a GPU with at least 8GB of VRAM. You only have {round(cardMemory)}GB.")
else:
if modelLM is not None:
del modelLM
clearCache()
modelLM = None
# Load lora names
loraNames = [os.path.split(d["file"])[1] for d in loras if "file" in d]
# Deal with prompt modifications
if modelType == "pixel" and promptTuning:
# Defaults
prefix = "pixel art"
suffix = "detailed"
negativeList = [negative, "mutated, noise, nsfw, nude, frame, film reel, snowglobe, deformed, stock image, watermark, text, signature, username"]
# Lora specific modifications
if any(f"{_}.pxlm" in loraNames for _ in [
"topdown",
"isometric",
"neogeo",
"nes",
"snes",
"playstation",
"gameboy",
"gameboyadvance"
]):
prefix = "pixel"
suffix = ""
elif any(f"{_}.pxlm" in loraNames for _ in ["frontfacing", "gameicons", "flatshading"]):
prefix = "pixel"
suffix = "pixel art"
elif any(f"{_}.pxlm" in loraNames for _ in ["nashorkimitems"]):
prefix = "pixel, item"
suffix = ""
negativeList.insert(0, "vibrant, colorful")
elif any(f"{_}.pxlm" in loraNames for _ in ["gamecharacters"]):
prefix = "pixel"
suffix = "blank background"
if any(f"{_}.pxlm" in loraNames for _ in ["1bit"]):
prefix = f"{prefix}, 1-bit"
suffix = f"{suffix}, pixel art, black and white, white background"
negativeList.insert(0, "color, colors")
if any(f"{_}.pxlm" in loraNames for _ in ["tiling", "tiling16", "tiling32"]):
prefix = f"{prefix}, texture"
suffix = f"{suffix}, pixel art"
# Model specific modifications
if math.sqrt(W * H) >= 832 and not upscale:
suffix = f"{suffix}, pjpixdeuc art style"
# Combine all prompt modifications
negatives = [", ".join(negativeList)] * generations
for i, prompt in enumerate(prompts):
prompts[i] = f"{prefix}, {prompt}, {suffix}"
else:
if promptTuning:
negatives = [f"{negative}, pixel art, blurry, mutated, deformed, borders, watermark, text"] * generations
else:
negatives = [f"{negative}, pixel art"] * generations
del loraNames
return prompts, negatives
# K-centroid downscaling alg
def kCentroid(image, width, height, centroids):
image = image.convert("RGB")
# Create an empty array for the downscaled image
downscaled = np.zeros((height, width, 3), dtype=np.uint8)
# Calculate the scaling factors
wFactor = image.width/width
hFactor = image.height/height
# Iterate over each tile in the downscaled image
for x, y in product(range(width), range(height)):
# Crop the tile from the original image
tile = image.crop((x * wFactor, y * hFactor, (x * wFactor) + wFactor, (y * hFactor) + hFactor))
# Quantize the colors of the tile using k-means clustering
tile = tile.quantize(colors=centroids, method=1, kmeans=centroids).convert("RGB")
# Get the color counts and find the most common color
color_counts = tile.getcolors()
most_common_color = max(color_counts, key=lambda x: x[0])[1]
# Assign the most common color to the corresponding pixel in the downscaled image
downscaled[y, x, :] = most_common_color
return Image.fromarray(downscaled, mode="RGB")
# Displays graphics for k-centroid
def kCentroidVerbose(images, width, height, centroids):
timer = time.time()
for i, image in enumerate(images):
images[i] = decodeImage(image)
rprint(f"\n[#48a971]K-Centroid downscaling[white] from [#48a971]{images[0].width}[white]x[#48a971]{images[0].height}[white] to [#48a971]{width}[white]x[#48a971]{height}[white] with [#48a971]{centroids}[white] centroids")
# Perform k-centroid downscaling and save the image
count = 0
output = []
for image in clbar(images, name = "Processed", unit = "image", prefixwidth = 12, suffixwidth = 28):
count += 1
resized_image = kCentroid(image, int(width), int(height), int(centroids))
name = str(hash(str([image, width, height, centroids, count])))
output.append({"name": name, "format": "png", "image": encodeImage(resized_image, "png")})
if image != images[-1]:
play("iteration.wav")
else:
play("batch.wav")
rprint(f"\n[#c4f129]Resized in [#48a971]{round(time.time()-timer, 2)} [#c4f129]seconds")
return output
# Attempts to detect the ideal pixel resolution of a given image
def pixelDetect(image: Image):
# Thanks to https://github.com/paultron for optimizing my garbage code
# I swapped the axis so they accurately reflect the horizontal and vertical scaling factor for images with uneven ratios
# Convert the image to a NumPy array
npim = np.array(image)[..., :3]
# Compute horizontal differences between pixels
hdiff = np.sqrt(np.sum((npim[:, :-1, :] - npim[:, 1:, :]) ** 2, axis=2))
hsum = np.sum(hdiff, 0)
# Compute vertical differences between pixels
vdiff = np.sqrt(np.sum((npim[:-1, :, :] - npim[1:, :, :]) ** 2, axis=2))
vsum = np.sum(vdiff, 1)