forked from Djdefrag/QualityScaler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QualityScaler.py
2658 lines (2125 loc) · 93.3 KB
/
QualityScaler.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
# Standard library imports
import sys
from functools import cache
from time import sleep
from webbrowser import open as open_browser
from subprocess import run as subprocess_run
from shutil import rmtree as remove_directory
from timeit import default_timer as timer
from typing import Callable
from threading import Thread
from itertools import repeat
from multiprocessing.pool import ThreadPool
from multiprocessing import (
Process,
Queue as multiprocessing_Queue,
freeze_support as multiprocessing_freeze_support
)
from json import (
load as json_load,
dumps as json_dumps
)
from os import (
sep as os_separator,
devnull as os_devnull,
environ as os_environ,
cpu_count as os_cpu_count,
makedirs as os_makedirs,
listdir as os_listdir,
remove as os_remove
)
from os.path import (
basename as os_path_basename,
dirname as os_path_dirname,
abspath as os_path_abspath,
join as os_path_join,
exists as os_path_exists,
splitext as os_path_splitext,
expanduser as os_path_expanduser
)
# Third-party library imports
from natsort import natsorted
from moviepy.video.io import ImageSequenceClip
from onnxruntime import InferenceSession as onnxruntime_inferenceSession
from PIL.Image import (
open as pillow_image_open,
fromarray as pillow_image_fromarray
)
from cv2 import (
CAP_PROP_FPS,
CAP_PROP_FRAME_COUNT,
CAP_PROP_FRAME_HEIGHT,
CAP_PROP_FRAME_WIDTH,
COLOR_BGR2RGB,
COLOR_GRAY2RGB,
COLOR_BGR2RGBA,
COLOR_RGB2GRAY,
IMREAD_UNCHANGED,
INTER_LINEAR,
INTER_AREA,
VideoCapture as opencv_VideoCapture,
cvtColor as opencv_cvtColor,
imdecode as opencv_imdecode,
imencode as opencv_imencode,
addWeighted as opencv_addWeighted,
cvtColor as opencv_cvtColor,
resize as opencv_resize,
)
from numpy import (
ndarray as numpy_ndarray,
frombuffer as numpy_frombuffer,
concatenate as numpy_concatenate,
transpose as numpy_transpose,
full as numpy_full,
zeros as numpy_zeros,
expand_dims as numpy_expand_dims,
squeeze as numpy_squeeze,
clip as numpy_clip,
mean as numpy_mean,
repeat as numpy_repeat,
max as numpy_max,
float32,
uint8
)
# GUI imports
from tkinter import StringVar
from tkinter import DISABLED
from customtkinter import (
CTk,
CTkButton,
CTkEntry,
CTkFont,
CTkImage,
CTkLabel,
CTkOptionMenu,
CTkScrollableFrame,
CTkToplevel,
filedialog,
set_appearance_mode,
set_default_color_theme
)
if sys.stdout is None: sys.stdout = open(os_devnull, "w")
if sys.stderr is None: sys.stderr = open(os_devnull, "w")
def find_by_relative_path(relative_path: str) -> str:
base_path = getattr(sys, '_MEIPASS', os_path_dirname(os_path_abspath(__file__)))
return os_path_join(base_path, relative_path)
app_name = "QualityScaler"
version = "3.10"
githubme = "https://github.com/Djdefrag/QualityScaler"
telegramme = "https://linktr.ee/j3ngystudio"
app_name_color = "#DA70D6"
dark_color = "#080808"
very_low_VRAM = 4
low_VRAM = 3
medium_VRAM = 2.2
very_high_VRAM = 0.6
AI_LIST_SEPARATOR = [ "----" ]
IRCNN_models_list = [ "IRCNN_Mx1", "IRCNN_Lx1" ]
SRVGGNetCompact_models_list = [ "RealESR_Gx4", "RealSRx4_Anime" ]
RRDB_models_list = [ "BSRGANx4", "BSRGANx2", "RealESRGANx4" ]
AI_models_list = ( SRVGGNetCompact_models_list + AI_LIST_SEPARATOR + RRDB_models_list + AI_LIST_SEPARATOR + IRCNN_models_list )
gpus_list = [ "GPU 1", "GPU 2", "GPU 3", "GPU 4" ]
image_extension_list = [ ".png", ".jpg", ".bmp", ".tiff" ]
video_extension_list = [ ".mp4 (x264)", ".mp4 (x265)", ".avi" ]
interpolation_list = [ "Low", "Medium", "High", "Disabled" ]
AI_multithreading_list = [ "1 threads", "2 threads", "3 threads", "4 threads", "5 threads", "6 threads"]
OUTPUT_PATH_CODED = "Same path as input files"
DOCUMENT_PATH = os_path_join(os_path_expanduser('~'), 'Documents')
USER_PREFERENCE_PATH = find_by_relative_path(f"{DOCUMENT_PATH}{os_separator}{app_name}_UserPreference.json")
FFMPEG_EXE_PATH = find_by_relative_path(f"Assets{os_separator}ffmpeg.exe")
EXIFTOOL_EXE_PATH = find_by_relative_path(f"Assets{os_separator}exiftool.exe")
FRAMES_FOR_CPU = 30
if os_path_exists(FFMPEG_EXE_PATH):
print(f"[{app_name}] External ffmpeg.exe file found")
os_environ["IMAGEIO_FFMPEG_EXE"] = FFMPEG_EXE_PATH
if os_path_exists(USER_PREFERENCE_PATH):
print(f"[{app_name}] Preference file exist")
with open(USER_PREFERENCE_PATH, "r") as json_file:
json_data = json_load(json_file)
default_AI_model = json_data["default_AI_model"]
default_AI_multithreading = json_data["default_AI_multithreading"]
default_gpu = json_data["default_gpu"]
default_image_extension = json_data["default_image_extension"]
default_video_extension = json_data["default_video_extension"]
default_interpolation = json_data["default_interpolation"]
default_output_path = json_data["default_output_path"]
default_resize_factor = json_data["default_resize_factor"]
default_VRAM_limiter = json_data["default_VRAM_limiter"]
default_cpu_number = json_data["default_cpu_number"]
else:
print(f"[{app_name}] Preference file does not exist, using default coded value")
default_AI_model = AI_models_list[0]
default_AI_multithreading = AI_multithreading_list[0]
default_gpu = gpus_list[0]
default_image_extension = image_extension_list[0]
default_video_extension = video_extension_list[0]
default_interpolation = interpolation_list[0]
default_output_path = OUTPUT_PATH_CODED
default_resize_factor = str(50)
default_VRAM_limiter = str(4)
default_cpu_number = str(int(os_cpu_count()/2))
COMPLETED_STATUS = "Completed"
ERROR_STATUS = "Error"
STOP_STATUS = "Stop"
offset_y_options = 0.105
row0_y = 0.52
row1_y = row0_y + offset_y_options
row2_y = row1_y + offset_y_options
row3_y = row2_y + offset_y_options
row4_y = row3_y + offset_y_options
offset_x_options = 0.28
column1_x = 0.5
column0_x = column1_x - offset_x_options
column2_x = column1_x + offset_x_options
column1_5_x = column1_x + offset_x_options/2
supported_file_extensions = [
'.heic', '.jpg', '.jpeg', '.JPG', '.JPEG', '.png',
'.PNG', '.webp', '.WEBP', '.bmp', '.BMP', '.tif',
'.tiff', '.TIF', '.TIFF', '.mp4', '.MP4', '.webm',
'.WEBM', '.mkv', '.MKV', '.flv', '.FLV', '.gif',
'.GIF', '.m4v', ',M4V', '.avi', '.AVI', '.mov',
'.MOV', '.qt', '.3gp', '.mpg', '.mpeg', ".vob"
]
supported_video_extensions = [
'.mp4', '.MP4', '.webm', '.WEBM', '.mkv', '.MKV',
'.flv', '.FLV', '.gif', '.GIF', '.m4v', ',M4V',
'.avi', '.AVI', '.mov', '.MOV', '.qt', '.3gp',
'.mpg', '.mpeg', ".vob"
]
# AI -------------------
class AI:
# CLASS INIT FUNCTIONS
def __init__(
self,
AI_model_name: str,
directml_gpu: str,
resize_factor: int,
max_resolution: int
):
# Passed variables
self.AI_model_name = AI_model_name
self.directml_gpu = directml_gpu
self.resize_factor = resize_factor
self.max_resolution = max_resolution
# Calculated variables
self.AI_model_path = find_by_relative_path(f"AI-onnx{os_separator}{self.AI_model_name}_fp16.onnx")
self.inferenceSession = self._load_inferenceSession()
self.upscale_factor = self._get_upscale_factor()
def _get_upscale_factor(self) -> int:
if "x1" in self.AI_model_name: return 1
elif "x2" in self.AI_model_name: return 2
elif "x4" in self.AI_model_name: return 4
def _load_inferenceSession(self) -> onnxruntime_inferenceSession:
match self.directml_gpu:
case 'GPU 1': directml_backend = [('DmlExecutionProvider', {"device_id": "0"})]
case 'GPU 2': directml_backend = [('DmlExecutionProvider', {"device_id": "1"})]
case 'GPU 3': directml_backend = [('DmlExecutionProvider', {"device_id": "2"})]
case 'GPU 4': directml_backend = [('DmlExecutionProvider', {"device_id": "3"})]
case 'CPU': directml_backend = ['CPUExecutionProvider']
inference_session = onnxruntime_inferenceSession(path_or_bytes = self.AI_model_path, providers = directml_backend)
return inference_session
# INTERNAL CLASS FUNCTIONS
def get_image_mode(self, image: numpy_ndarray) -> str:
match image.shape:
case (rows, cols):
return "Grayscale"
case (rows, cols, channels) if channels == 3:
return "RGB"
case (rows, cols, channels) if channels == 4:
return "RGBA"
def get_image_resolution(self, image: numpy_ndarray) -> tuple:
height = image.shape[0]
width = image.shape[1]
return height, width
def calculate_target_resolution(self, image: numpy_ndarray) -> tuple:
height, width = self.get_image_resolution(image)
target_height = height * self.upscale_factor
target_width = width * self.upscale_factor
return target_height, target_width
def resize_image_with_resize_factor(self, image: numpy_ndarray) -> numpy_ndarray:
old_height, old_width = self.get_image_resolution(image)
new_width = int(old_width * self.resize_factor)
new_height = int(old_height * self.resize_factor)
match self.resize_factor:
case factor if factor > 1:
return opencv_resize(image, (new_width, new_height), interpolation = INTER_LINEAR)
case factor if factor < 1:
return opencv_resize(image, (new_width, new_height), interpolation = INTER_AREA)
case _:
return image
def resize_image_with_target_resolution(
self,
image: numpy_ndarray,
t_height: int,
t_width: int
) -> numpy_ndarray:
old_height, old_width = self.get_image_resolution(image)
old_resolution = old_height + old_width
new_resolution = t_height + t_width
if new_resolution > old_resolution:
return opencv_resize(image, (t_width, t_height), interpolation = INTER_LINEAR)
else:
return opencv_resize(image, (t_width, t_height), interpolation = INTER_AREA)
# VIDEO CLASS FUNCTIONS
def calculate_multiframes_supported_by_gpu(self, video_frame_path: str) -> int:
resized_video_frame = self.resize_image_with_resize_factor(image_read(video_frame_path))
height, width = self.get_image_resolution(resized_video_frame)
image_pixels = height * width
max_supported_pixels = self.max_resolution * self.max_resolution
frames_simultaneously = max_supported_pixels // image_pixels
print(f" Frames supported simultaneously by GPU: {frames_simultaneously}")
return frames_simultaneously
# TILLING FUNCTIONS
def video_need_tilling(self, video_frame_path: str) -> bool:
resized_video_frame = self.resize_image_with_resize_factor(image_read(video_frame_path))
height, width = self.get_image_resolution(resized_video_frame)
image_pixels = height * width
max_supported_pixels = self.max_resolution * self.max_resolution
if image_pixels > max_supported_pixels:
return True
else:
return False
def image_need_tilling(self, image: numpy_ndarray) -> bool:
height, width = self.get_image_resolution(image)
image_pixels = height * width
max_supported_pixels = self.max_resolution * self.max_resolution
if image_pixels > max_supported_pixels:
return True
else:
return False
def add_alpha_channel(self, image: numpy_ndarray) -> numpy_ndarray:
if image.shape[2] == 3:
alpha = numpy_full((image.shape[0], image.shape[1], 1), 255, dtype = uint8)
image = numpy_concatenate((image, alpha), axis = 2)
return image
def calculate_tiles_number(
self,
image: numpy_ndarray,
) -> tuple:
height, width = self.get_image_resolution(image)
tiles_x = (width + self.max_resolution - 1) // self.max_resolution
tiles_y = (height + self.max_resolution - 1) // self.max_resolution
return tiles_x, tiles_y
def split_image_into_tiles(
self,
image: numpy_ndarray,
tiles_x: int,
tiles_y: int
) -> list[numpy_ndarray]:
img_height, img_width = self.get_image_resolution(image)
tile_width = img_width // tiles_x
tile_height = img_height // tiles_y
tiles = []
for y in range(tiles_y):
y_start = y * tile_height
y_end = (y + 1) * tile_height
for x in range(tiles_x):
x_start = x * tile_width
x_end = (x + 1) * tile_width
tile = image[y_start:y_end, x_start:x_end]
tiles.append(tile)
return tiles
def combine_tiles_into_image(
self,
image: numpy_ndarray,
tiles: list[numpy_ndarray],
t_height: int,
t_width: int,
num_tiles_x: int,
) -> numpy_ndarray:
match self.get_image_mode(image):
case "Grayscale": tiled_image = numpy_zeros((t_height, t_width, 3), dtype = uint8)
case "RGB": tiled_image = numpy_zeros((t_height, t_width, 3), dtype = uint8)
case "RGBA": tiled_image = numpy_zeros((t_height, t_width, 4), dtype = uint8)
for tile_index in range(len(tiles)):
actual_tile = tiles[tile_index]
tile_height, tile_width = self.get_image_resolution(actual_tile)
row = tile_index // num_tiles_x
col = tile_index % num_tiles_x
y_start = row * tile_height
y_end = y_start + tile_height
x_start = col * tile_width
x_end = x_start + tile_width
match self.get_image_mode(image):
case "Grayscale": tiled_image[y_start:y_end, x_start:x_end] = actual_tile
case "RGB": tiled_image[y_start:y_end, x_start:x_end] = actual_tile
case "RGBA": tiled_image[y_start:y_end, x_start:x_end] = self.add_alpha_channel(actual_tile)
return tiled_image
# AI CLASS FUNCTIONS
def normalize_image(self, image: numpy_ndarray) -> tuple:
range = 255
if numpy_max(image) > 256: range = 65535
normalized_image = image / range
return normalized_image, range
def preprocess_image(self, image: numpy_ndarray) -> numpy_ndarray:
image = numpy_transpose(image, (2, 0, 1))
image = numpy_expand_dims(image, axis=0)
return image
def onnxruntime_inference(self, image: numpy_ndarray) -> numpy_ndarray:
# IO BINDING
# io_binding = self.inferenceSession.io_binding()
# io_binding.bind_cpu_input(self.inferenceSession.get_inputs()[0].name, image)
# io_binding.bind_output(self.inferenceSession.get_outputs()[0].name, element_type = float32)
# self.inferenceSession.run_with_iobinding(io_binding)
# onnx_output = io_binding.copy_outputs_to_cpu()[0]
onnx_input = {self.inferenceSession.get_inputs()[0].name: image}
onnx_output = self.inferenceSession.run(None, onnx_input)[0]
return onnx_output
def postprocess_output(self, onnx_output: numpy_ndarray) -> numpy_ndarray:
onnx_output = numpy_squeeze(onnx_output, axis=0)
onnx_output = numpy_clip(onnx_output, 0, 1)
onnx_output = numpy_transpose(onnx_output, (1, 2, 0))
return onnx_output.astype(float32)
def de_normalize_image(self, onnx_output: numpy_ndarray, max_range: int) -> numpy_ndarray:
match max_range:
case 255: return (onnx_output * max_range).astype(uint8)
case 65535: return (onnx_output * max_range).round().astype(float32)
def AI_upscale(self, image: numpy_ndarray) -> numpy_ndarray:
image_mode = self.get_image_mode(image)
image, range = self.normalize_image(image)
image = image.astype(float32)
match image_mode:
case "RGB":
image = self.preprocess_image(image)
onnx_output = self.onnxruntime_inference(image)
onnx_output = self.postprocess_output(onnx_output)
output_image = self.de_normalize_image(onnx_output, range)
return output_image
case "RGBA":
alpha = image[:, :, 3]
image = image[:, :, :3]
image = opencv_cvtColor(image, COLOR_BGR2RGB)
image = image.astype(float32)
alpha = alpha.astype(float32)
# Image
image = self.preprocess_image(image)
onnx_output_image = self.onnxruntime_inference(image)
onnx_output_image = self.postprocess_output(onnx_output_image)
onnx_output_image = opencv_cvtColor(onnx_output_image, COLOR_BGR2RGBA)
# Alpha
alpha = numpy_expand_dims(alpha, axis=-1)
alpha = numpy_repeat(alpha, 3, axis=-1)
alpha = self.preprocess_image(alpha)
onnx_output_alpha = self.onnxruntime_inference(alpha)
onnx_output_alpha = self.postprocess_output(onnx_output_alpha)
onnx_output_alpha = opencv_cvtColor(onnx_output_alpha, COLOR_RGB2GRAY)
# Fusion Image + Alpha
onnx_output_image[:, :, 3] = onnx_output_alpha
output_image = self.de_normalize_image(onnx_output_image, range)
return output_image
case "Grayscale":
image = opencv_cvtColor(image, COLOR_GRAY2RGB)
image = self.preprocess_image(image)
onnx_output = self.onnxruntime_inference(image)
onnx_output = self.postprocess_output(onnx_output)
output_image = opencv_cvtColor(onnx_output, COLOR_RGB2GRAY)
output_image = self.de_normalize_image(onnx_output, range)
return output_image
def AI_upscale_with_tilling(self, image: numpy_ndarray) -> numpy_ndarray:
t_height, t_width = self.calculate_target_resolution(image)
tiles_x, tiles_y = self.calculate_tiles_number(image)
tiles_list = self.split_image_into_tiles(image, tiles_x, tiles_y)
tiles_list = [self.AI_upscale(tile) for tile in tiles_list]
return self.combine_tiles_into_image(image, tiles_list, t_height, t_width, tiles_x)
# EXTERNAL FUNCTION
def AI_orchestration(self, image: numpy_ndarray) -> numpy_ndarray:
resized_image = self.resize_image_with_resize_factor(image)
if self.image_need_tilling(resized_image):
return self.AI_upscale_with_tilling(resized_image)
else:
return self.AI_upscale(resized_image)
# GUI utils ---------------------------
class MessageBox(CTkToplevel):
def __init__(
self,
messageType: str,
title: str,
subtitle: str,
default_value: str,
option_list: list,
) -> None:
super().__init__()
self._running: bool = False
self._messageType = messageType
self._title = title
self._subtitle = subtitle
self._default_value = default_value
self._option_list = option_list
self._ctkwidgets_index = 0
self.title('')
self.lift() # lift window on top
self.attributes("-topmost", True) # stay on top
self.protocol("WM_DELETE_WINDOW", self._on_closing)
self.after(10, self._create_widgets) # create widgets with slight delay, to avoid white flickering of background
self.resizable(False, False)
self.grab_set() # make other windows not clickable
def _ok_event(
self,
event = None
) -> None:
self.grab_release()
self.destroy()
def _on_closing(
self
) -> None:
self.grab_release()
self.destroy()
def createEmptyLabel(
self
) -> CTkLabel:
return CTkLabel(master = self,
fg_color = "transparent",
width = 500,
height = 17,
text = '')
def placeInfoMessageTitleSubtitle(
self,
) -> None:
spacingLabel1 = self.createEmptyLabel()
spacingLabel2 = self.createEmptyLabel()
if self._messageType == "info":
title_subtitle_text_color = "#3399FF"
elif self._messageType == "error":
title_subtitle_text_color = "#FF3131"
titleLabel = CTkLabel(
master = self,
width = 500,
anchor = 'w',
justify = "left",
fg_color = "transparent",
text_color = title_subtitle_text_color,
font = bold22,
text = self._title
)
if self._default_value != None:
defaultLabel = CTkLabel(
master = self,
width = 500,
anchor = 'w',
justify = "left",
fg_color = "transparent",
text_color = "#3399FF",
font = bold17,
text = f"Default: {self._default_value}"
)
subtitleLabel = CTkLabel(
master = self,
width = 500,
anchor = 'w',
justify = "left",
fg_color = "transparent",
text_color = title_subtitle_text_color,
font = bold14,
text = self._subtitle
)
spacingLabel1.grid(row = self._ctkwidgets_index, column = 0, columnspan = 2, padx = 0, pady = 0, sticky = "ew")
self._ctkwidgets_index += 1
titleLabel.grid(row = self._ctkwidgets_index, column = 0, columnspan = 2, padx = 25, pady = 0, sticky = "ew")
if self._default_value != None:
self._ctkwidgets_index += 1
defaultLabel.grid(row = self._ctkwidgets_index, column = 0, columnspan = 2, padx = 25, pady = 0, sticky = "ew")
self._ctkwidgets_index += 1
subtitleLabel.grid(row = self._ctkwidgets_index, column = 0, columnspan = 2, padx = 25, pady = 0, sticky = "ew")
self._ctkwidgets_index += 1
spacingLabel2.grid(row = self._ctkwidgets_index, column = 0, columnspan = 2, padx = 0, pady = 0, sticky = "ew")
def placeInfoMessageOptionsText(
self,
) -> None:
for option_text in self._option_list:
optionLabel = CTkLabel(master = self,
width = 600,
height = 45,
corner_radius = 6,
anchor = 'w',
justify = "left",
text_color = "#C0C0C0",
fg_color = "#282828",
bg_color = "transparent",
font = bold12,
text = option_text)
self._ctkwidgets_index += 1
optionLabel.grid(row = self._ctkwidgets_index, column = 0, columnspan = 2, padx = 25, pady = 4, sticky = "ew")
spacingLabel3 = self.createEmptyLabel()
self._ctkwidgets_index += 1
spacingLabel3.grid(row = self._ctkwidgets_index, column = 0, columnspan = 2, padx = 0, pady = 0, sticky = "ew")
def placeInfoMessageOkButton(
self
) -> None:
ok_button = CTkButton(
master = self,
command = self._ok_event,
text = 'OK',
width = 125,
font = bold11,
border_width = 1,
fg_color = "#282828",
text_color = "#E0E0E0",
border_color = "#0096FF"
)
self._ctkwidgets_index += 1
ok_button.grid(row = self._ctkwidgets_index, column = 1, columnspan = 1, padx = (10, 20), pady = (10, 20), sticky = "e")
def _create_widgets(
self
) -> None:
self.grid_columnconfigure((0, 1), weight=1)
self.rowconfigure(0, weight=1)
self.placeInfoMessageTitleSubtitle()
self.placeInfoMessageOptionsText()
self.placeInfoMessageOkButton()
class FileWidget(CTkScrollableFrame):
def __init__(
self,
master,
selected_file_list,
resize_factor = 0,
upscale_factor = 1,
**kwargs
) -> None:
super().__init__(master, **kwargs)
self.grid_columnconfigure(0, weight = 1)
self.file_list = selected_file_list
self.resize_factor = resize_factor
self.upscale_factor = upscale_factor
self.label_list = []
self._create_widgets()
def _destroy_(self) -> None:
self.file_list = []
self.destroy()
place_loadFile_section()
def _create_widgets(self) -> None:
self.add_clean_button()
index_row = 1
for file_path in self.file_list:
label = self.add_file_information(file_path, index_row)
self.label_list.append(label)
index_row +=1
def add_file_information(self, file_path, index_row) -> CTkLabel:
infos, icon = self.extract_file_info(file_path)
label = CTkLabel(
self,
text = infos,
image = icon,
font = bold12,
text_color = "#C0C0C0",
compound = "left",
anchor = "w",
padx = 10,
pady = 5,
justify = "left",
)
label.grid(
row = index_row,
column = 0,
pady = (3, 3),
padx = (3, 3),
sticky = "w")
return label
def add_clean_button(self) -> None:
button = CTkButton(
self,
image = clear_icon,
font = bold11,
text = "CLEAN",
compound = "left",
width = 100,
height = 28,
border_width = 1,
fg_color = "#282828",
text_color = "#E0E0E0",
border_color = "#0096FF"
)
button.configure(command=lambda: self._destroy_())
button.grid(row = 0, column=2, pady=(7, 7), padx = (0, 7))
@cache
def extract_file_icon(self, file_path) -> CTkImage:
max_size = 50
if check_if_file_is_video(file_path):
video_cap = opencv_VideoCapture(file_path)
_, frame = video_cap.read()
source_icon = opencv_cvtColor(frame, COLOR_BGR2RGB)
video_cap.release()
else:
source_icon = opencv_cvtColor(image_read(file_path), COLOR_BGR2RGB)
ratio = min(max_size / source_icon.shape[0], max_size / source_icon.shape[1])
new_width = int(source_icon.shape[1] * ratio)
new_height = int(source_icon.shape[0] * ratio)
source_icon = opencv_resize(source_icon,(new_width, new_height))
ctk_icon = CTkImage(pillow_image_fromarray(source_icon, mode="RGB"), size = (new_width, new_height))
return ctk_icon
def extract_file_info(self, file_path) -> tuple:
if check_if_file_is_video(file_path):
cap = opencv_VideoCapture(file_path)
width = round(cap.get(CAP_PROP_FRAME_WIDTH))
height = round(cap.get(CAP_PROP_FRAME_HEIGHT))
num_frames = int(cap.get(CAP_PROP_FRAME_COUNT))
frame_rate = cap.get(CAP_PROP_FPS)
duration = num_frames/frame_rate
minutes = int(duration/60)
seconds = duration % 60
cap.release()
video_name = str(file_path.split("/")[-1])
file_icon = self.extract_file_icon(file_path)
file_infos = (f"{video_name}\n"
f"Resolution {width}x{height} • {minutes}m:{round(seconds)}s • {num_frames}frames\n")
if self.resize_factor != 0 and self.upscale_factor != 0:
resized_height = int(height * (self.resize_factor/100))
resized_width = int(width * (self.resize_factor/100))
upscaled_height = int(resized_height * self.upscale_factor)
upscaled_width = int(resized_width * self.upscale_factor)
file_infos += (f"AI input {self.resize_factor}% ➜ {resized_width}x{resized_height} \n"
f"AI output x{self.upscale_factor} ➜ {upscaled_width}x{upscaled_height}")
else:
image_name = str(file_path.split("/")[-1])
height, width = get_image_resolution(image_read(file_path))
file_icon = self.extract_file_icon(file_path)
file_infos = (f"{image_name}\n"
f"Resolution {width}x{height}\n")
if self.resize_factor != 0 and self.upscale_factor != 0:
resized_height = int(height * (self.resize_factor/100))
resized_width = int(width * (self.resize_factor/100))
upscaled_height = int(resized_height * self.upscale_factor)
upscaled_width = int(resized_width * self.upscale_factor)
file_infos += (f"AI input {self.resize_factor}% ➜ {resized_width}x{resized_height} \n"
f"AI output x{self.upscale_factor} ➜ {upscaled_width}x{upscaled_height}")
return file_infos, file_icon
# EXTERNAL FUNCTIONS
def clean_file_list(self) -> None:
for label in self.label_list:
label.grid_forget()
def get_selected_file_list(self) -> list:
return self.file_list
def set_upscale_factor(self, upscale_factor) -> None:
self.upscale_factor = upscale_factor
def set_resize_factor(self, resize_factor) -> None:
self.resize_factor = resize_factor
def update_file_widget(a, b, c) -> None:
try:
global file_widget
file_widget
except:
return
upscale_factor = get_upscale_factor()
try:
resize_factor = int(float(str(selected_resize_factor.get())))
except:
resize_factor = 0
file_widget.clean_file_list()
file_widget.set_resize_factor(resize_factor)
file_widget.set_upscale_factor(upscale_factor)
file_widget._create_widgets()
def create_info_button(
command: Callable,
text: str,
width: int = 150
) -> CTkButton:
return CTkButton(
master = window,
command = command,
text = text,
fg_color = "transparent",
hover_color = "#181818",
text_color = "#C0C0C0",
anchor = "w",
corner_radius = 10,
height = 22,
width = width,
font = bold12,
image = info_icon
)
def create_option_menu(
command: Callable,
values: list,
default_value: str
) -> CTkOptionMenu:
option_menu = CTkOptionMenu(
master = window,
command = command,
values = values,
width = 150,
height = 30,
corner_radius = 5,
dropdown_font = bold11,
font = bold11,
anchor = "center",
text_color = "#C0C0C0",
fg_color = "#000000",
button_color = "#000000",
button_hover_color = "#000000",
dropdown_fg_color = "#000000"
)
option_menu.set(default_value)
return option_menu
def create_text_box(textvariable: StringVar) -> CTkEntry:
return CTkEntry(
master = window,
textvariable = textvariable,
corner_radius = 5,
width = 150,
height = 30,
font = bold11,
justify = "center",
text_color = "#C0C0C0",
fg_color = "#000000",
border_width = 1,
border_color = "#404040",
)
def create_text_box_output_path(textvariable: StringVar) -> CTkEntry:
return CTkEntry(
master = window,
textvariable = textvariable,
border_width = 1,
corner_radius = 5,
width = 300,
height = 30,
font = bold11,
justify = "center",
text_color = "#C0C0C0",
fg_color = "#000000",
border_color = "#404040",
state = DISABLED
)
def create_active_button(
command: Callable,
text: str,
icon: CTkImage = None,
width: int = 140,
height: int = 30,
border_color: str = "#0096FF"
) -> CTkButton:
return CTkButton(
master = window,
command = command,
text = text,
image = icon,