-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSDx4_MainV2.py
1629 lines (1262 loc) · 79.4 KB
/
SDx4_MainV2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
from json import load as json_load
from json import dump as json_dump
import requests
import numpy as np
from PyQt6 import uic
from matplotlib.pyplot import subplots as plt_subplots
from shutil import move as shutil_move
from matplotlib.pyplot import cm as plt_cm
from PyQt6.QtSvg import QSvgRenderer
from PyQt6.QtXml import QDomDocument
from PIL import Image, ImageDraw, ImageFont
from PyQt6.QtGui import QIcon, QPixmap, QPainter, QColor
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from PyQt6.QtCore import QPropertyAnimation, QEasingCurve, QThread, pyqtSignal, Qt
from PyQt6.QtWidgets import QApplication, QMainWindow, QFileDialog, QVBoxLayout, QColorDialog, QDialog, QLabel
from PyQt6.QtGui import QPixmap, QResizeEvent
from PIL.ImageQt import ImageQt
#import appdirs
# trye to take the signals directly from file_processing_thread.upscaler to the gui clss without going through the file_processing_thread classs, aslo then can xsperate the image complete proress signal freom the other two and put image complete after the image is porcessed in file_processing_thread
import urllib3
## - As building a exe file with no console, transformers library will suffer from an error where sys.stdout and sys.stderr are None
# Below four lines fix this issue by redirecting stdout and stderr to os.devnull as suggested here: https://github.com/huggingface/transformers/issues/24047#issuecomment-1635532509
if sys.stdout is None:
sys.stdout = open(os.devnull, "w")
if sys.stderr is None:
sys.stderr = open(os.devnull, "w")
import diffusers # this must come after the above fix otherwise will cause the error discussed
from SDx4_Upscaler_Class import SDx4Upscaler
import resources_rc
# Gui classes
from clickablewidget import ClickableWidget
class ImageWidget(QLabel):
def __init__(self, parent=None):
super().__init__(parent)
self.setScaledContents(True)
def setPixmap(self, pixmap):
if pixmap:
self.setScaledContents(True)
self.aspect_ratio = pixmap.width() / pixmap.height()
super().setPixmap(pixmap)
self.resizeEvent(QResizeEvent(self.size(), self.size()))
else:
super().setPixmap(QPixmap())
def resizeEvent(self, event):
print("resize event")
scaled_height = (self.parent().width()) / self.aspect_ratio
scaled_width = (self.parent().height()) * self.aspect_ratio
#if scaled_height > self.parent().height():
self.setFixedHeight(int(scaled_height))
#if scaled_width > self.parent().width():
# self.setFixedWidth(int(scaled_width))
#%% Helper Functions
def resource_path(relative_path):
""" Get the absolute path to a resource, works for dev and for PyInstaller """
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, relative_path)
#%% - Backend Program Threads
class ModelDownloadthread(QThread):
# create a signal to downlaod failed signal
download_failed_signal = pyqtSignal()
def __init__(self, model_folder=resource_path("App_Data\\model\\")):
super().__init__()
self.model_folder = model_folder
def run(self):
try:
original_model_path = diffusers.DiffusionPipeline.download("stabilityai/stable-diffusion-x4-upscaler")
original_model_path = str(original_model_path)
model_path = original_model_path.split("snapshots")[0]
model_destination_path = model_path.split("hub\\")[1]
# Move the 'model_path' folder and all its contents to the 'model_destination_path'
shutil_move(model_path, self.model_folder + model_destination_path)
except:
self.download_failed_signal.emit()
return
class FileHandlingThread(QThread):
def __init__(self, temp_folder, previous_processing_file_list=None):
super().__init__()
self.temp_folder = temp_folder
self.processing_file_list = [] if previous_processing_file_list is None else previous_processing_file_list
def add_files(self, file_paths):
for file_path in file_paths:
self.add_to_processing_list(file_path)
def add_folder(self, folder_path): # update to add mulit folder at once
for file in os.listdir(folder_path): # add full file paths to the processing file list
self.add_to_processing_list(os.path.join(folder_path, file))
def remove_file(self, selected_item):
self.processing_file_list.pop(selected_item)
def add_to_processing_list(self, file_path):
# check file size on disk
file_size = os.path.getsize(file_path)
# convert file size from bytes to KB or MB depending on size
if file_size > 1000000:
file_size = str(round(file_size / 1000000, 2)) + " MB"
else:
file_size = str(round(file_size / 1000, 2)) + " KB"
# load the image file
image = Image.open(file_path).convert("RGB")
# Create preview image
preview_image = image.copy()
preview_image = preview_image.resize((image.width * 4, image.height * 4), Image.NEAREST)
preview_image = preview_image.convert("RGBA") # convert to RGBA so that the image is loadable into the Qimage and can be displayed in the GUI
# Detemine image resoloutions
input_res = (image.width, image.height) # determine the input resoloution
output_res = (preview_image.width, preview_image.height) # determine the output resoloution (same as preview, 4x input res)
# add to the processing file list
file_info_dict = {}
file_info_dict["input_file"] = image
file_info_dict["input_file_path"] = file_path
file_info_dict["preview_file"] = preview_image
file_info_dict["input_res"] = input_res
file_info_dict["output_res"] = output_res
file_info_dict["file_size"] = file_size
self.processing_file_list.append(file_info_dict)
def get_file_images(self, file_number):
input_image = self.processing_file_list[file_number]["input_file"]
preview_image = self.processing_file_list[file_number]["preview_file"]
return input_image, preview_image
def get_file_info(self, file_number):
file_size = self.processing_file_list[file_number]["file_size"]
input_res = self.processing_file_list[file_number]["input_res"]
output_res = self.processing_file_list[file_number]["output_res"]
return file_size, input_res, output_res
# File processing thread
class FileProcessingThread(QThread):
processing_position_signal = pyqtSignal(int, int, int, int, int, int) # Emits (current image, current tile, current iteration) during the upscaling process for gui progress bars
patch_preview = pyqtSignal(object, int, int) # Signal for previewing patches
tile_complete_signal = pyqtSignal(object, int, int) # Signal for tile complete image retrival
finished = pyqtSignal()
stopped = pyqtSignal()
def __init__(self):
super().__init__()
def send_patch_preview(self, img_patch, patch_num):
self.patch_preview.emit(img_patch, patch_num, self.current_image_num)
def send_tile_complete(self, tile_complete_image, tile_num):
self.tile_complete_signal.emit(tile_complete_image, tile_num, self.current_image_num)
def send_progress_update(self, current_tile, total_tiles, current_iteration, total_iterations):
self.processing_position_signal.emit(self.current_image, self.number_of_images, current_tile, total_tiles, current_iteration, total_iterations)
def run(self):
for current_image_num, local_image_path in enumerate(self.local_image_paths):
self.current_image_num = current_image_num
self.current_image = current_image_num + 1
### missing params i.e blend mode!!!
upscaled_image = self.upscaler.upscale(local_image_path,
self.patch_size,
self.padding_size,
self.num_inference_steps,
self.guidance_scale,
self.prompt,
self.negative_prompt,
self.boost_face_quality,
self.blending,
self.callback_steps,
self.show_patches,
self.dummy_upscale)
# get input image name
image_name = os.path.basename(local_image_path)
image_name = os.path.splitext(image_name)[0] # remove file extension
# copy input image to output location
low_res_img = Image.open(local_image_path).convert("RGB")
low_res_img.save(os.path.join(self.output_dir, image_name + "_Original.png"))
upscaled_image.save(os.path.join(self.output_dir, image_name + "_Upscaled.png"))
# CLENA UP IMAGES FROM THE TEMP FOLDER HERE TOO OR COPULD KEEP THEM FOR A COMPARISON VIEWER PAGE OR SOMTHING?????
# Emit the finished signal when processing is done
self.finished.emit()
def initialize_upscale_job(self, processing_file_list, output_dir, patch_size, padding_size, num_inference_steps, guidance_scale, prompt, negative_prompt, boost_face_quality, blending, blend_mode, callback_steps, show_patches, dummy_upscale, xformers, cpu_offload, attention_slicing, seed, safety_checker, local_model_path):
self.local_image_paths = [file_info["input_file_path"] for file_info in processing_file_list]
self.number_of_images = len(self.local_image_paths)
self.upscaler = SDx4Upscaler(xformers, cpu_offload, attention_slicing, seed, safety_checker, local_model_path)
self.upscaler.callback_signal.connect(self.send_patch_preview)
self.upscaler.tile_complete_signal.connect(self.send_tile_complete)
self.upscaler.processing_position_signal.connect(self.send_progress_update)
os.makedirs(output_dir, exist_ok=True)
self.output_dir = output_dir
self.patch_size = patch_size
self.padding_size = padding_size
self.num_inference_steps = num_inference_steps
self.guidance_scale = guidance_scale
self.prompt = prompt
self.negative_prompt = negative_prompt
self.boost_face_quality = boost_face_quality
self.blending = blending
self.callback_steps = callback_steps
self.show_patches = show_patches
self.dummy_upscale = dummy_upscale
# Upscale preview thread
class UpscalePreviewThread(QThread):
preview_update_signal = pyqtSignal(object) # Emits (current image, current tile, current iteration) during the upscaling process for gui progress bars
#request_file_from_filehandler_signal = pyqtSignal(int) # Signal for image retrival
def __init__(self, file_handling_thread):
super().__init__()
self.file_handling_thread = file_handling_thread
def calculate_dynamic_overlap(self, x, window_size, patch_size):
blocks = int(np.ceil(x / patch_size))
hangover = (patch_size * blocks) - x
num_of_overlaps = blocks - 1
overlap = hangover / num_of_overlaps # length hanging over = total length of blocks end to end - length of x number of overlaps = number of blocks * 2 - 2 as there are 2 overlaps for every block except the first and last which only have 1. if there is only 1 block then there is no overlap
# round down overlap
overlap = np.floor(overlap)
all_but_one_ol = overlap * (num_of_overlaps - 1)
last_ol = hangover - all_but_one_ol # to make sure all are ints and there is no remainder
overlap = overlap + (window_size - patch_size)
last_ol = last_ol + (window_size - patch_size)
return overlap, last_ol, blocks
def visualize_patches(self, image):
draw = ImageDraw.Draw(image)
font = ImageFont.load_default()
window_size = 128 * 4
min_padding_size = 8 * 4 # Pixels of padding on right and bottom sides of the patches
patch_size = window_size - min_padding_size # Size of the patches to be extracted from the image in pixels
input_image_width, input_image_height = image.size
#input_image_height = input_image_height * 4
#input_image_width = input_image_width * 4
x_overlap, x_last_overlap, number_of_windows_in_row = self.calculate_dynamic_overlap(input_image_width, window_size, patch_size)
y_overlap, y_last_overlap, number_of_windows_in_col = self.calculate_dynamic_overlap(input_image_height, window_size, patch_size)
for c in range(0, number_of_windows_in_col):
for r in range(0, number_of_windows_in_row):
if r == number_of_windows_in_row - 1:
x_start_point = (r * window_size) - (r * x_last_overlap)
else:
x_start_point = (r * window_size) - (r * x_overlap)
if c == number_of_windows_in_col - 1:
y_start_point = (c * window_size) - (c * y_last_overlap)
else:
y_start_point = (c * window_size) - (c * y_overlap)
# Draw a border around the patchwith the colour genrated from the patch number
patch_number = c * number_of_windows_in_row + r
colour = plt_cm.jet(patch_number / (number_of_windows_in_col * number_of_windows_in_row))
# Convert the float values to integers for the color tuple
colour_int = tuple(int(x * 255) for x in colour[:-1])
draw.rectangle([x_start_point, y_start_point, x_start_point + window_size, y_start_point + window_size], outline=colour_int)
# Get the center coordinates of the patch
center_x = x_start_point + window_size // 2
center_y = y_start_point + window_size // 2
# Draw the patch number in large text at the center of the patch
draw.text((center_x, center_y), str(patch_number), font=font, fill=colour_int, anchor="mm")
return image
def update_preview_tile(self, patch_image, patch_number, file_list_item_number):
self.preview_image = self.file_handling_thread.processing_file_list[file_list_item_number]["preview_file"] # Set the preview image to the image in the file handling thread
input_image_width, input_image_height = self.file_handling_thread.processing_file_list[file_list_item_number]["input_res"] # Get the input image resoloution from the file handling thread
self.preview_image = self.visualize_patches(self.preview_image)
input_image_height = input_image_height * 4
input_image_width = input_image_width * 4
window_size = 128 * 4 # Size of the window to be extracted from the image in pixels
min_padding_size = 8 * 4 # Pixels of padding on right and bottom sides of the patches
patch_size = window_size - min_padding_size # Size of the patches to be extracted from the image in pixels
x_overlap, x_last_overlap, number_of_windows_in_row = self.calculate_dynamic_overlap(input_image_width, window_size, patch_size)
y_overlap, y_last_overlap, number_of_windows_in_col = self.calculate_dynamic_overlap(input_image_height, window_size, patch_size)
r = patch_number % number_of_windows_in_row
c = patch_number // number_of_windows_in_row
if r == number_of_windows_in_row - 1:
x_start_point = (r * window_size) - (r * x_last_overlap)
else:
x_start_point = (r * window_size) - (r * x_overlap)
if c == number_of_windows_in_col - 1:
y_start_point = (c * window_size) - (c * y_last_overlap)
else:
y_start_point = (c * window_size) - (c * y_overlap)
# add the patch image to the preview image in the correct location
self.preview_image.paste(patch_image, (int(x_start_point), int(y_start_point)))
# Draw a border around the patchwith the colour genrated from the patch number
colour = plt_cm.jet(patch_number / (number_of_windows_in_col * number_of_windows_in_row))
# Convert the float values to integers for the color tuple
colour_int = tuple(int(x * 255) for x in colour[:-1])
draw = ImageDraw.Draw(self.preview_image)
draw.rectangle([x_start_point, y_start_point, x_start_point + window_size, y_start_point + window_size], width=10, outline=colour_int)
# update the preview image in the file handling thread
#self.file_handling_thread.processing_file_list[file_list_item_number]["preview_file"] = self.preview_image
# send signal to update the preview image
self.preview_update_signal.emit(self.preview_image)
#%% - Load the UI file
Form, Window = uic.loadUiType(r"GUI\SDx4_interface.ui")
app = QApplication([])
# Secondary UI files
class ThemeDesigner(QDialog):
update_ui_preview_signal = pyqtSignal(dict)
add_new_theme_signal = pyqtSignal(str)
def __init__(self, current_ui_theme, current_ui_mode, avalible_themes, parent=None):
super().__init__(parent)
ThemeDesignerForm, ThemeDesignerWindow = uic.loadUiType(resource_path(r'App_Data\IntegratedThemeDesignerInterface.ui'))
self.original_ui_theme = current_ui_theme
self.original_ui_mode = current_ui_mode
self.current_ui_theme = current_ui_theme
self.current_ui_mode = current_ui_mode
self.avalible_themes = avalible_themes
self.ui = ThemeDesignerForm()
self.ui.setupUi(self)
self.setWindowTitle("SDx4 Theme Designer")
self.setWindowIcon(QIcon(resource_path(r'App_Data\icons\SDx4_Icon.ico')))
self.init_css_theme()
self.init_signals()
self.load_theme(self.current_ui_theme)
# add the themes to the themes list selector
self.ui.basethemesListSelector.addItems(self.avalible_themes)
# Create list of false locks for each color group
self.light_mode_locks = [False] * len(self.lighttheme_groups)
self.dark_mode_locks = [False] * len(self.darktheme_groups)
def init_css_theme(self):
self.color_pick_buttons = {}
self.color_pick_buttons["lightMainWidget"] = self.ui.lightMainWidget
self.color_pick_buttons["lightSecondaryWidget"] = self.ui.lightSecondaryWidget
self.color_pick_buttons["lightAccent1Widget"] = self.ui.lightAccent1Widget
self.color_pick_buttons["lightAccent2Widget"] = self.ui.lightAccent2Widget
self.color_pick_buttons["lightAccent3Widget"] = self.ui.lightAccent3Widget
self.color_pick_buttons["lightAccent4Widget"] = self.ui.lightAccent4Widget
self.color_pick_buttons["lightAccent5Widget"] = self.ui.lightAccent5Widget
self.color_pick_buttons["lightText1Widget"] = self.ui.lightText1Widget
self.color_pick_buttons["lightText2Widget"] = self.ui.lightText2Widget
self.color_pick_buttons["lightIconsWidget"] = self.ui.lightIconsWidget
self.color_pick_buttons["darkMainWidget"] = self.ui.darkMainWidget
self.color_pick_buttons["darkSecondaryWidget"] = self.ui.darkSecondaryWidget
self.color_pick_buttons["darkAccent1Widget"] = self.ui.darkAccent1Widget
self.color_pick_buttons["darkAccent2Widget"] = self.ui.darkAccent2Widget
self.color_pick_buttons["darkAccent3Widget"] = self.ui.darkAccent3Widget
self.color_pick_buttons["darkAccent4Widget"] = self.ui.darkAccent4Widget
self.color_pick_buttons["darkAccent5Widget"] = self.ui.darkAccent5Widget
self.color_pick_buttons["darkText1Widget"] = self.ui.darkText1Widget
self.color_pick_buttons["darkText2Widget"] = self.ui.darkText2Widget
self.color_pick_buttons["darkIconsWidget"] = self.ui.darkIconsWidget
self.color_pick_labels = {}
self.color_pick_labels["lightMainWidget"] = self.ui.lightMainLabel
self.color_pick_labels["lightSecondaryWidget"] = self.ui.lightSecondaryLabel
self.color_pick_labels["lightAccent1Widget"] = self.ui.lightAccent1Label
self.color_pick_labels["lightAccent2Widget"] = self.ui.lightAccent2Label
self.color_pick_labels["lightAccent3Widget"] = self.ui.lightAccent3Label
self.color_pick_labels["lightAccent4Widget"] = self.ui.lightAccent4Label
self.color_pick_labels["lightAccent5Widget"] = self.ui.lightAccent5Label
self.color_pick_labels["lightText1Widget"] = self.ui.lightText1Label
self.color_pick_labels["lightText2Widget"] = self.ui.lightText2Label
self.color_pick_labels["lightIconsWidget"] = self.ui.lightIconsLabel
self.color_pick_labels["darkMainWidget"] = self.ui.darkMainLabel
self.color_pick_labels["darkSecondaryWidget"] = self.ui.darkSecondaryLabel
self.color_pick_labels["darkAccent1Widget"] = self.ui.darkAccent1Label
self.color_pick_labels["darkAccent2Widget"] = self.ui.darkAccent2Label
self.color_pick_labels["darkAccent3Widget"] = self.ui.darkAccent3Label
self.color_pick_labels["darkAccent4Widget"] = self.ui.darkAccent4Label
self.color_pick_labels["darkAccent5Widget"] = self.ui.darkAccent5Label
self.color_pick_labels["darkText1Widget"] = self.ui.darkText1Label
self.color_pick_labels["darkText2Widget"] = self.ui.darkText2Label
self.color_pick_labels["darkIconsWidget"] = self.ui.darkIconsLabel
self.lighttheme_groups = ["lightMainWidget",
"lightSecondaryWidget",
"lightAccent1Widget",
"lightAccent2Widget",
"lightAccent3Widget",
"lightAccent4Widget",
"lightAccent5Widget",
"lightText1Widget",
"lightText2Widget",
"lightIconsWidget"]
self.darktheme_groups = ["darkMainWidget",
"darkSecondaryWidget",
"darkAccent1Widget",
"darkAccent2Widget",
"darkAccent3Widget",
"darkAccent4Widget",
"darkAccent5Widget",
"darkText1Widget",
"darkText2Widget",
"darkIconsWidget"]
def init_color_picker_button_colors(self):
# load all the values from the theme color dictionaries into the lists
self.dark_mode_colors = list(self.dark_theme_dictionary.values())
self.light_mode_colors = list(self.light_theme_dictionary.values())
# make a new list that is light theme colors + dark theme colors
all_colors = self.light_mode_colors + self.dark_mode_colors
for color_pick_button, color_pick_label, color in zip(self.color_pick_buttons.values(), self.color_pick_labels.values(), all_colors):
color_pick_button.setStyleSheet(f'background-color: {color};')
color_pick_label.setText(color)
def init_signals(self):
self.ui.saveThemeBtn.clicked.connect(self.save_theme)
self.ui.toggleEditModeBtn.clicked.connect(self.toggle_ui_mode)
self.ui.randomAllUnlockedColorsBtn.clicked.connect(self.randomise_all_unlocked_colors)
self.ui.basethemesListSelector.currentTextChanged.connect(self.select_base_theme)
self.ui.colorMatchMethodListSelector.currentTextChanged.connect(self.set_color_match_method)
self.ui.lightMainClickWidget.clicked.connect(self.color_picker)
self.ui.lightSecondaryClickWidget.clicked.connect(self.color_picker)
self.ui.lightAccent1ClickWidget.clicked.connect(self.color_picker)
self.ui.lightAccent2ClickWidget.clicked.connect(self.color_picker)
self.ui.lightAccent3ClickWidget.clicked.connect(self.color_picker)
self.ui.lightAccent4ClickWidget.clicked.connect(self.color_picker)
self.ui.lightAccent5ClickWidget.clicked.connect(self.color_picker)
self.ui.lightText1ClickWidget.clicked.connect(self.color_picker)
self.ui.lightText2ClickWidget.clicked.connect(self.color_picker)
self.ui.lightIconsClickWidget.clicked.connect(self.color_picker)
self.ui.darkMainClickWidget.clicked.connect(self.color_picker)
self.ui.darkSecondaryClickWidget.clicked.connect(self.color_picker)
self.ui.darkAccent1ClickWidget.clicked.connect(self.color_picker)
self.ui.darkAccent2ClickWidget.clicked.connect(self.color_picker)
self.ui.darkAccent3ClickWidget.clicked.connect(self.color_picker)
self.ui.darkAccent4ClickWidget.clicked.connect(self.color_picker)
self.ui.darkAccent5ClickWidget.clicked.connect(self.color_picker)
self.ui.darkText1ClickWidget.clicked.connect(self.color_picker)
self.ui.darkText2ClickWidget.clicked.connect(self.color_picker)
self.ui.darkIconsClickWidget.clicked.connect(self.color_picker)
self.ui.lightMainLockBtn.clicked.connect(self.lock_color)
self.ui.lightSecondaryLockBtn.clicked.connect(self.lock_color)
self.ui.lightAccent1LockBtn.clicked.connect(self.lock_color)
self.ui.lightAccent2LockBtn.clicked.connect(self.lock_color)
self.ui.lightAccent3LockBtn.clicked.connect(self.lock_color)
self.ui.lightAccent4LockBtn.clicked.connect(self.lock_color)
self.ui.lightAccent5LockBtn.clicked.connect(self.lock_color)
self.ui.lightText1LockBtn.clicked.connect(self.lock_color)
self.ui.lightText2LockBtn.clicked.connect(self.lock_color)
self.ui.lightIconsLockBtn.clicked.connect(self.lock_color)
self.ui.darkMainLockBtn.clicked.connect(self.lock_color)
self.ui.darkSecondaryLockBtn.clicked.connect(self.lock_color)
self.ui.darkAccent1LockBtn.clicked.connect(self.lock_color)
self.ui.darkAccent2LockBtn.clicked.connect(self.lock_color)
self.ui.darkAccent3LockBtn.clicked.connect(self.lock_color)
self.ui.darkAccent4LockBtn.clicked.connect(self.lock_color)
self.ui.darkAccent5LockBtn.clicked.connect(self.lock_color)
self.ui.darkText1LockBtn.clicked.connect(self.lock_color)
self.ui.darkText2LockBtn.clicked.connect(self.lock_color)
self.ui.darkIconsLockBtn.clicked.connect(self.lock_color)
self.ui.lightMainRandomBtn.clicked.connect(self.randomise_single_color)
self.ui.lightSecondaryRandomBtn.clicked.connect(self.randomise_single_color)
self.ui.lightAccent1RandomBtn.clicked.connect(self.randomise_single_color)
self.ui.lightAccent2RandomBtn.clicked.connect(self.randomise_single_color)
self.ui.lightAccent3RandomBtn.clicked.connect(self.randomise_single_color)
self.ui.lightAccent4RandomBtn.clicked.connect(self.randomise_single_color)
self.ui.lightAccent5RandomBtn.clicked.connect(self.randomise_single_color)
self.ui.lightText1RandomBtn.clicked.connect(self.randomise_single_color)
self.ui.lightText2RandomBtn.clicked.connect(self.randomise_single_color)
self.ui.lightIconsRandomBtn.clicked.connect(self.randomise_single_color)
self.ui.darkMainRandomBtn.clicked.connect(self.randomise_single_color)
self.ui.darkSecondaryRandomBtn.clicked.connect(self.randomise_single_color)
self.ui.darkAccent1RandomBtn.clicked.connect(self.randomise_single_color)
self.ui.darkAccent2RandomBtn.clicked.connect(self.randomise_single_color)
self.ui.darkAccent3RandomBtn.clicked.connect(self.randomise_single_color)
self.ui.darkAccent4RandomBtn.clicked.connect(self.randomise_single_color)
self.ui.darkAccent5RandomBtn.clicked.connect(self.randomise_single_color)
self.ui.darkText1RandomBtn.clicked.connect(self.randomise_single_color)
self.ui.darkText2RandomBtn.clicked.connect(self.randomise_single_color)
self.ui.darkIconsRandomBtn.clicked.connect(self.randomise_single_color)
def select_base_theme(self):
theme = self.ui.basethemesListSelector.currentText()
# load the theme css into the strings
self.load_theme(theme)
def load_theme(self, theme):
self.current_ui_theme = theme
# load the css files into the strings
with open(resource_path(f'App_Data/themes/{theme}/{theme}_dark_theme_dictionary.json'), 'r') as file:
self.dark_theme_dictionary = json_load(file)
with open(resource_path(f'App_Data/themes/{theme}/{theme}_light_theme_dictionary.json'), 'r') as file:
self.light_theme_dictionary = json_load(file)
# load all the values from the theme color dictionaries into the lists
self.dark_mode_colors = list(self.dark_theme_dictionary.values())
self.light_mode_colors = list(self.light_theme_dictionary.values())
# update the ui preview with the new theme
self.init_color_picker_button_colors()
if self.current_ui_mode == "dark":
self.update_ui_preview_signal.emit(self.dark_theme_dictionary)
else:
self.update_ui_preview_signal.emit(self.light_theme_dictionary)
def lock_color(self):
original_sender_name = self.sender().objectName()
sender_name = original_sender_name
sender_name = sender_name.replace("LockBtn", "")
# Check sender name for light or dark and remove it and flag which one was found
if "light" in sender_name:
sender_name = sender_name.replace("light", "")
for i, key in enumerate(self.lighttheme_groups):
if sender_name.lower() in key.lower():
break
# check if original sender Qpushbutton is checked or unchecked
if self.sender().isChecked():
self.light_mode_locks[i] = True
else:
self.light_mode_locks[i] = False
else:
sender_name = sender_name.replace("dark", "")
for i , key in enumerate(self.darktheme_groups):
if sender_name.lower() in key.lower():
break
if self.sender().isChecked():
self.dark_mode_locks[i] = True
else:
self.dark_mode_locks[i] = False
def generate_random_color(self):
# generate a random color hex code
color = '#{:02x}{:02x}{:02x}'.format(*np.random.choice(range(256), size=3))
return color
def randomise_single_color(self):
original_sender_name = self.sender().objectName()
sender_name = original_sender_name
sender_name = sender_name.replace("RandomBtn", "")
# turn the keys of the dictionaries into lists
self.light_theme_dictionary_keys = list(self.light_theme_dictionary.keys())
self.dark_theme_dictionary_keys = list(self.dark_theme_dictionary.keys())
# Check sender name for light or dark and remove it and flag which one was found
if "light" in sender_name:
sender_name = sender_name.replace("light", "")
for lock, key in zip(self.light_mode_locks, self.light_theme_dictionary_keys):
if sender_name.lower() in key.lower():
if lock == False:
print("Unlocked")
self.light_theme_dictionary[key] = self.generate_random_color()
break
else:
sender_name = sender_name.replace("dark", "")
for lock, key in zip(self.dark_mode_locks, self.dark_theme_dictionary_keys):
if sender_name.lower() in key.lower():
if lock == False:
print("Unlocked")
self.dark_theme_dictionary[key] = self.generate_random_color()
break
self.init_color_picker_button_colors()
def randomise_all_unlocked_colors(self):
# turn the keys of the dictionaries into lists
self.light_theme_dictionary_keys = list(self.light_theme_dictionary.keys())
self.dark_theme_dictionary_keys = list(self.dark_theme_dictionary.keys())
for lock, key in zip(self.light_mode_locks, self.light_theme_dictionary_keys):
if lock == False:
print("Unlocked")
self.light_theme_dictionary[key] = self.generate_random_color()
for lock, key in zip(self.dark_mode_locks, self.dark_theme_dictionary_keys):
if lock == False:
print("Unlocked")
self.dark_theme_dictionary[key] = self.generate_random_color()
self.init_color_picker_button_colors()
if self.current_ui_mode == "dark":
self.update_ui_preview_signal.emit(self.dark_theme_dictionary)
else:
self.update_ui_preview_signal.emit(self.light_theme_dictionary)
def color_picker(self):
color_dialog = QColorDialog(self)
color_dialog.setWindowTitle('Choose Color')
original_sender_name = self.sender().objectName()
sender_name = original_sender_name
sender_name = sender_name.replace("Click", "")
sender_name = sender_name.replace("Widget", "")
# Check sender name for light or dark and remove it and flag which one was found
if "light" in sender_name:
update = "light"
sender_name = sender_name.replace("light", "")
for key, value in self.light_theme_dictionary.items():
if sender_name.lower() in key.lower():
break
initial_color = QColor(self.light_theme_dictionary[key])
else:
update = "dark"
sender_name = sender_name.replace("dark", "")
# find the key in the dictionary that contains the entire sender name, check should be performed entirely in lower case
for key, value in self.dark_theme_dictionary.items():
if sender_name.lower() in key.lower():
break
initial_color = QColor(self.dark_theme_dictionary[key])
if initial_color.isValid():
color_dialog.setCurrentColor(initial_color)
if color_dialog.exec() == QColorDialog.DialogCode.Accepted:
color = color_dialog.selectedColor()
else:
return
if update == "light":
self.light_theme_dictionary[key] = color.name()
self.update_ui_preview_signal.emit(self.light_theme_dictionary)
else:
self.dark_theme_dictionary[key] = color.name()
self.update_ui_preview_signal.emit(self.dark_theme_dictionary)
self.init_color_picker_button_colors()
# update the color of the button
#original_sender_name.setStyleSheet(f'background-color: {color.name()};')
# Update the hex readout of the button to the color set
#original_sender_name.setText(color.name())
def toggle_ui_mode(self):
if self.current_ui_mode == "dark":
self.current_ui_mode = "light"
#self.ui_preview.setStyleSheet(self.light_mode_css_content)
# send ui mode change signal to main window
self.update_ui_preview_signal.emit(self.light_theme_dictionary)
else:
self.current_ui_mode = "dark"
#self.ui_preview.setStyleSheet(self.dark_mode_css_content)
# send ui mode change signal to main window
self.update_ui_preview_signal.emit(self.dark_theme_dictionary)
def save_theme(self):
self.ui.themeNameInput.setPlaceholderText("")
# check if text has been enteres into the theme name box
if self.ui.themeNameInput.text() == "":
self.ui.themeNameInput.setPlaceholderText("A name is required to save!")
return
# get the theme name from the text box
theme_name = self.ui.themeNameInput.text()
# create a new folder in the themes folder with the name of the theme if the folder doesn't already exist
os.makedirs(resource_path(f'App_Data/themes/{theme_name}'), exist_ok=True)
# save the dictionary to a file so it can be loaded later as a dictionary easily
with open(resource_path(f'App_Data/themes/{theme_name}/{theme_name}_dark_theme_dictionary.json'), 'w') as f:
json_dump(self.dark_theme_dictionary, f)
# save the dictionary to a file so it can be loaded later as a dictionary easily
with open(resource_path(f'App_Data/themes/{theme_name}/{theme_name}_light_theme_dictionary.json'), 'w') as f:
json_dump(self.light_theme_dictionary, f)
# add the theme to the avalible themes list
#self.avalible_themes.append(theme_name)
self.ui.basethemesListSelector.addItems([theme_name])
self.add_new_theme_signal.emit(theme_name)
self.original_ui_theme = theme_name # update the original theme name to the new theme name
def set_color_match_method(self):
self.color_match_method = self.ui.colorMatchMethodListSelector.currentText()
#FINISH!!!
class ExitDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
exitDialogForm, exitDialogWindow = uic.loadUiType(resource_path(r'App_Data\exitDialogInterface.ui'))
self.ui = exitDialogForm()
self.ui.setupUi(self)
self.setWindowTitle("Exit")
def accept(self):
self.accepted = True
super().accept()
sys.exit()
def reject(self):
self.accepted = False
super().reject()
class CancelUpscaleDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
cancelUpscaleDialogForm, cancelUpscaleDialogWindow = uic.loadUiType(resource_path(r'App_Data\cancelUpscaleDialogInterface.ui'))
self.ui = cancelUpscaleDialogForm()
self.ui.setupUi(self)
self.setWindowTitle("Cancel Upscale")
def accept(self):
self.accepted = True
super().accept()
def reject(self):
self.accepted = False
super().reject()
class ModelDownloadPopup(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
modelDownloadPopupForm, modelDownloadPopupWindow = uic.loadUiType(resource_path(r'App_Data\modelDownloadPopupInterface.ui'))
self.ui = modelDownloadPopupForm()
self.ui.setupUi(self)
self.setWindowTitle("Model Download")
self.ui.cancelModelDownloadBtn.clicked.connect(self.cancel_download)
self.download_model_thread = ModelDownloadthread()
self.download_model_thread.finished.connect(self.finished_model_download)
self.download_model_thread.download_failed_signal.connect(self.download_failed)
self.download_model_thread.start()
def finished_model_download(self):
self.accepted = True
super().accept()
def download_failed(self):
# display error message
#self.ui.downloadStatusLabel.setText("Download Failed")
self.accepted = False
super().reject()
def cancel_download(self):
self.accepted = False
# kill the download thread
self.download_model_thread.terminate()
super().reject()
## MAIN WINDOW CLASS
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Form()
self.ui.setupUi(self)
self.setWindowTitle("SDx4 Upscaler")
self.setWindowIcon(QIcon(resource_path(r'App_Data\icons\SDx4_Icon.ico')))
# Simple Customisation Settings
self.online_version_file_link = "https://github.com/Adillwma/SDx4_ImageUpscaler/raw/main/config.json"
self.update_download_link = "https://github.com/Adillwma/SDx4_ImageUpscaler/raw/main/SDx4_Upscaler.exe"
# Get the path to the application data directory
#app_data_dir = appdirs.user_data_dir(appname='SDx4 Upscaler', appauthor=False)
self.config_file = resource_path(r'App_Data\config.json')
self.help_text_path = resource_path(r"App_Data\copy\help_text.txt")
self.info_text_path = resource_path(r"App_Data\copy\info_text.txt")
self.temp_folder = resource_path(r"App_Data\temp_data")
self.main_css_path = resource_path(r"App_Data\mainStylesheet.css")
self.local_model_path = resource_path(r"App_Data\model\models--stabilityai--stable-diffusion-x4-upscaler\snapshots\572c99286543a273bfd17fac263db5a77be12c4c")
### Initialise UI Elements
self.check_preferences() # Checks the user preferences file to load the correct settings
self.init_icons() # Load the icons for the buttons
self.init_modularUI() # Modular Unified Ui
self.init_programUI() # Main Program Ui elements
self.initalise_settings() # User Settings
self.initialise_avalible_theme_list()
# Begin program threads
self.file_handling_thread = FileHandlingThread(self.temp_folder)
self.is_upscale_running = False
# Initialise Backend
self.file_processing_thread = FileProcessingThread()
# Connect signals from the file processing thread to gui
self.file_processing_thread.finished.connect(self.file_processing_finished)
self.file_processing_thread.stopped.connect(self.file_processing_stopped)
self.file_processing_thread.processing_position_signal.connect(self.update_progress_bars)
# Initialise the upscale preview thread
self.upscale_preview_thread = UpscalePreviewThread(self.file_handling_thread)
self.upscale_preview_thread.preview_update_signal.connect(self.refresh_plot_data)
self.file_processing_thread.patch_preview.connect(self.upscale_preview_thread.update_preview_tile)
self.file_processing_thread.tile_complete_signal.connect(self.upscale_preview_thread.update_preview_tile)
#self.file_handling_thread.start()
self.upscale_preview_thread.start()
#%% - Initialise UI
def check_preferences(self): # Checks the user preferences file to load the correct settings
# Load data from the config file
with open(self.config_file, 'r') as file:
self.config_data = json_load(file)
# check if the program has been run before if not run wizard for user to set preferences
if self.config_data["First Run"] == True:
self.config_data = self.show_setup_wizard() # show the setup wizard
# Program Settings
self.version_number = self.config_data["Version"] # set the version number for checking for updates
# UI Visual Settings
self.current_theme = self.config_data["Theme"] # set the theme to user preference
self.ui.themesListSelector.setCurrentText(self.current_theme)
#self.current_ui_mode = self.config_data["UI"] # set the ui to user preference dark/light mode
#self.
# Directory Paths
self.output_dir = self.config_data["output_dir"] # set the output folder path to user preference
# Main Processor States
self.blending = self.config_data["blending"] # set the verify checksum state to user preference
self.blend_mode = self.config_data["blend_mode"] # set the checksum type to user preference
self.num_inference_steps = self.config_data["num_inference_steps"] # set the target bit depth to user preference
self.guidance_scale = self.config_data["guidance_scale"] # set the target bit depth to user preference
self.boost_face_quality = self.config_data["boost_face_quality"] # set the target bit depth to user preference
# Pipeline Settings
self.cpu_offload = self.config_data["cpu_offload"] # set the normalise up only state to user preference
self.attention_slicing = self.config_data["attention_slicing"] # set the target sample rate to user preference
self.xformers = self.config_data["xformers"] # set the target bit depth to user preference
def init_modularUI(self):
# Left Menu
self.left_menu_animation = QPropertyAnimation(self.ui.leftMenuContainer, b"maximumWidth")
self.left_menu_animation.setEasingCurve(QEasingCurve.Type.InOutQuart)
self.left_menu_animation.setDuration(1000) # Animation duration in milliseconds
self.ui.leftMenuBtn_UiBtnType.clicked.connect(self.expandorshrink_left_menu)
self.ui.leftMenuContainer.setMaximumWidth(50)
self.ui.settingsBtn_UiBtnType.clicked.connect(lambda: self.handle_centre_menu(page=self.ui.settingsCenterMenuPage))
self.ui.infoBtn_UiBtnType.clicked.connect(lambda: self.handle_centre_menu(page=self.ui.infoCenterMenuPage))
self.ui.helpBtn_UiBtnType.clicked.connect(lambda: self.handle_centre_menu(page=self.ui.helpCenterMenuPage))
# Center Menu
self.center_menu_animation = QPropertyAnimation(self.ui.centerMenuContainer, b"maximumWidth")
self.center_menu_animation.setEasingCurve(QEasingCurve.Type.InOutQuart)
self.center_menu_animation.setDuration(1000) # Animation duration in milliseconds
self.ui.centerMenuCloseBtn_UiBtnType.clicked.connect(lambda: self.run_animation(self.center_menu_animation, start=250, end=5))
self.ui.centerMenuContainer.setMaximumWidth(5) # Set centre menu to start hidden (with max width of 0)
# Notification Container
self.notification_animation = QPropertyAnimation(self.ui.popupNotificationContainer, b"maximumHeight")
self.notification_animation.setEasingCurve(QEasingCurve.Type.InOutQuart)
self.notification_animation.setDuration(1000)
self.ui.notificationCloseBtn_UiBtnType.clicked.connect(lambda: self.run_animation(self.notification_animation, start=100, end=0))
self.ui.popupNotificationContainer.setMaximumHeight(0) # Remove notification container once new donload update methods are applied
# ui theme dark / light
self.dark_mode_path = resource_path(fr"App_Data\themes\{self.current_theme}\dark_mode.css")
self.light_mode_path = resource_path(fr"App_Data\themes\{self.current_theme}\light_mode.css")
self.current_ui_mode = "dark"
self.highlight_theme_color = "background-color: #1f232a;" # remove as now dealt with in the css main file
self.ui.uiThemeBtn_UiBtnType.clicked.connect(self.switch_ui_mode)
self.set_icons_color("#FFFFFF") #CHANGE COLOUR TO COME FROM STYLE SHEET PROGRAMATICALLY!!!!
self.set_theme()
### SETTINGS PAGE
self.ui.themesListSelector.currentTextChanged.connect(self.set_theme)
self.ui.checkForUpdates_ProgramBtnType.clicked.connect(self.check_online_for_updates)
self.ui.downloadUpdateBtn_ProgramBtnType.clicked.connect(self.download_latest_version)
self.ui.runThemeDesigner_ProgramBtnType.clicked.connect(self.open_theme_designer_dialog)
### HELP & INFO PAGES
self.set_helpandinfo_copy(self.help_text_path, self.info_text_path)
def init_programUI(self):
self.upscale_settings_animation = QPropertyAnimation(self.ui.upscaleSettingsWidget, b"maximumWidth")
self.upscale_settings_animation.setEasingCurve(QEasingCurve.Type.InOutQuart)
self.upscale_settings_animation.setDuration(1000) # Animation duration in milliseconds
self.ui.advancedmodeBtn_ProgramBtnType.clicked.connect(self.toggle_advanced_mode)
#self.ui.upscaleSettingsWidget.setMaximumWidth(0) # Set upscale settings widget to start hidden (with max width of 0)
self.ui.iterationsSlider.valueChanged.connect(self.update_iterations_setting)
self.ui.guidanceSlider.valueChanged.connect(self.update_guidance_settings)
self.ui.blendingCheckbox.clicked.connect(self.toggle_blending)
self.ui.blendTypeSelector.currentTextChanged.connect(self.toggle_blending_mode)
self.ui.boostfaceQualityCheckbox.clicked.connect(self.toggle_boostface_quality)
self.ui.cpuoffloadCheckbox.clicked.connect(self.toggle_cpu_offload)
self.ui.attentionSlicingCheckbox.clicked.connect(self.toggle_attentionslicing)
self.ui.xformersCheckbox.clicked.connect(self.toggle_xformers)
self.ui.outputLocationBrowseBtn_ProgramBtnType.clicked.connect(self.browse_output_location)
self.ui.addFilesBtn_ProgramBtnType.clicked.connect(self.browse_input_files)
self.ui.addfoldersBtn_ProgramBtnType.clicked.connect(self.browse_input_folders)
self.ui.removeListItemBtn_ProgramBtnType.clicked.connect(self.remove_selected_list_item)
self.ui.runUpscaleBtn_ProgramBtnType.clicked.connect(self.upscale_btn_clicked)
# if a user has selcted an item in the list connect the itemClicked signal to the display image function
self.ui.inputFilesListDisplay.itemClicked.connect(self.file_selected_in_list)
# Create a Matplotlib figure and canvas
self.figure, self.ax = plt_subplots()
self.canvas = FigureCanvas(self.figure)