-
Notifications
You must be signed in to change notification settings - Fork 0
/
ModernSlideShower.py
3443 lines (2923 loc) · 150 KB
/
ModernSlideShower.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 argparse
import collections
import datetime
import io
import math
import multiprocessing
import os
import random
import shutil
import tomllib
import moderngl
import moderngl_window as mglw
import moderngl_window.context.base
import moderngl_window.context.pyglet.keys
import moderngl_window.meta
import moderngl_window.timers.clock
import mpmath
import numpy as np
import rawpy
import tomli_w
from PIL import Image, ImageDraw, ImageOps
from moderngl_window.integrations.imgui import ModernglWindowRenderer
from moderngl_window.opengl import program, vao
from mpmath import mp
from natsort import natsorted
from scipy.ndimage import gaussian_filter
from StaticData import *
Point = collections.namedtuple('Point', ['x', 'y'])
ORIENTATION_DB = dict([
(2, [Image.Transpose.FLIP_LEFT_RIGHT, Image.Transpose.FLIP_TOP_BOTTOM]),
(3, [Image.Transpose.ROTATE_180, Image.Transpose.FLIP_TOP_BOTTOM]),
(4, [Image.Transpose.FLIP_TOP_BOTTOM, Image.Transpose.FLIP_TOP_BOTTOM]),
(5, [Image.Transpose.ROTATE_90]),
(6, [Image.Transpose.ROTATE_270, Image.Transpose.FLIP_TOP_BOTTOM]),
(7, [Image.Transpose.ROTATE_270]),
(8, [Image.Transpose.ROTATE_90, Image.Transpose.FLIP_TOP_BOTTOM])
])
def sigmoid(x, mi, mx):
return mi + (mx - mi) * (lambda t: (1 + 200 ** (-t + 0.5)) ** (-1))((x - mi) / (mx - mi))
def smootherstep_ease(x):
# average between smoothstep and smootherstep
if x <= 0:
return 0
elif x >= 1:
return 1
else:
return x * x * (x * (x * (x * 6 - 15) + 8) + 3) / 2
def mix(a, b, amount=.5):
return a * (1 - amount) + b * amount
def restrict(val, min_val, max_val):
if val < min_val: return min_val
if val > max_val: return max_val
return val
def split_complex(in_value):
out_real, out_imaginary = [], []
current_value = in_value
for _ in range(4):
with mp.workprec(52):
t = current_value
c_hi = t - (t - current_value)
out_real.append(float(c_hi.real))
out_imaginary.append(float(c_hi.imag))
current_value -= c_hi
return out_real, out_imaginary
def split_complex_32(in_value):
out_real, out_imaginary = [], []
current_value = in_value
for _ in range(4):
with mp.workprec(26):
t = current_value
c_hi = t - (t - current_value)
out_real.append(float(c_hi.real))
out_imaginary.append(float(c_hi.imag))
current_value -= c_hi
return out_real, out_imaginary
def format_bytes_3(size):
power = 2 ** 10 # 2**10 = 1024
n = 0
power_labels = {0: 'B', 1: 'KB', 2: 'MB', 3: 'GB', 4: 'TB'}
f_size = size
while f_size > power:
f_size /= power
n += 1
digits = 3 - math.ceil(math.log10(f_size)) if f_size < 1000 else 0
formatted_string = f'{f_size:.{digits:d}f} {power_labels[n]} ({size:,d} B)'
formatted_string = formatted_string.replace(",", " ")
return formatted_string
def reorient_image(im):
image_orientation = 0
try:
im_exif = im.getexif()
image_orientation = im_exif.get(274, 0)
except (KeyError, AttributeError, TypeError, IndexError):
# print(KeyError)
pass
set_of_operations = ORIENTATION_DB.get(image_orientation, [Image.Transpose.FLIP_TOP_BOTTOM])
for operation in set_of_operations:
im = im.transpose(operation)
return im
# def load_settings():
# if os.path.isfile("settings.json"):
# with open("settings.json", 'r') as f:
# return json.load(f)
def load_image(path_target, do_thumb=False):
def draw_dummy():
im_object = Image.new("RGB", (256, 256), (20, 50, 80))
d = ImageDraw.Draw(im_object)
d.ellipse((10, 10, 200, 200))
d.ellipse((100, 100, 255, 255))
return im_object.tobytes()
try:
if not do_thumb and any((path_target.lower().endswith(ex) for ex in RAW_FILE_TYPES)):
with open(path_target, 'rb', buffering=0) as f: # This is a workaround for opening non-latin file names
thumb = rawpy.imread(f).extract_thumb()
path_target = io.BytesIO(thumb.data)
with Image.open(path_target) as im_object:
im_exif = im_object.info.get("exif", b'')
if im_object.mode == "RGB":
im_object = reorient_image(im_object)
else:
im_object = reorient_image(im_object).convert(mode="RGB")
if do_thumb:
im_object.thumbnail((256, 256))
im_object = ImageOps.pad(im_object, (256, 256))
return im_object.tobytes(), Point(im_object.width, im_object.height), im_exif
except Exception as e:
if do_thumb:
return draw_dummy(), Point(0, 0), b''
else:
return None, e, b''
def image_loader_process(in_queue: multiprocessing.Queue, out_queue: multiprocessing.Queue, do_thumb):
out_queue.put("Started")
while True:
task_data = in_queue.get()
if task_data is None:
print("Exit loader")
return
pic_data = load_image(task_data[1], do_thumb=do_thumb)
try:
out_queue.put((task_data, *pic_data), timeout=2)
except Exception:
pass
def init_image_loader(do_thumb=False):
thumb_queue_tasks = multiprocessing.Queue()
thumb_queue_data = multiprocessing.Queue()
thumb_queue_tasks.cancel_join_thread()
thumb_queue_data.cancel_join_thread()
thumb_loader = multiprocessing.Process(target=image_loader_process,
args=(thumb_queue_tasks, thumb_queue_data, do_thumb))
thumb_loader.start()
thumb_queue_data.get()
return thumb_queue_tasks, thumb_queue_data, thumb_loader
class Configs(Enum):
HIDE_BORDERS = "hide_borders"
TRANSITION_DURATION = "transition_duration"
INTER_BLUR = "transition_blur"
STARTING_ZOOM_FACTOR = "initial_zoom"
PIXEL_SIZE = "pixel_squareness"
FULL_SCREEN_ID = "full_screen_monitor_id"
Values = (HIDE_BORDERS,
TRANSITION_DURATION,
INTER_BLUR,
STARTING_ZOOM_FACTOR,
PIXEL_SIZE,
FULL_SCREEN_ID,
)
DESCRIPTIONS = {
HIDE_BORDERS: "Hide image borders",
TRANSITION_DURATION: "Duration of transition between images",
INTER_BLUR: "Blur during transition",
STARTING_ZOOM_FACTOR: "Zoom of newly shown image",
PIXEL_SIZE: "Pixel shape in case of extreme zoom",
FULL_SCREEN_ID: "ID of the full screen monitor",
}
FORMATS = {
HIDE_BORDERS: (0, 1000, '%.1f', 0),
TRANSITION_DURATION: (0.01, 10, '%.3f', 0),
INTER_BLUR: (0, 1000, '%.1f', 0),
STARTING_ZOOM_FACTOR: (0, 5, '%.3f', 0),
PIXEL_SIZE: (0, 100, '%.2f', 32),
FULL_SCREEN_ID: (0, 3, '%.0f', 0),
}
class Config:
def __init__(self, config_file='settings.toml'):
self.config_file = config_file
self.defaults = {
Configs.HIDE_BORDERS.value: 100,
Configs.TRANSITION_DURATION.value: 0.75,
Configs.INTER_BLUR.value: 30.0,
Configs.STARTING_ZOOM_FACTOR.value: 0.98,
Configs.PIXEL_SIZE.value: 0,
Configs.FULL_SCREEN_ID.value: 1,
}
self.settings = self.defaults.copy()
self.load_settings()
def load_settings(self):
if os.path.isfile(self.config_file):
with open(self.config_file, 'rb') as f:
loaded_settings = tomllib.load(f)
for key, value in loaded_settings.items():
if key in self.defaults:
self.settings[key] = self.validate_setting(key, value)
def save_settings(self):
with open(self.config_file, 'wb') as f:
tomli_w.dump(self.settings, f)
def validate_setting(self, key, value):
min_val, max_val, _, _ = Configs.FORMATS.value[key]
if isinstance(value, (int, float)):
if value < min_val:
return min_val
elif value > max_val:
return max_val
else:
return value
else:
return self.defaults[key]
def get(self, key):
return self.settings.get(key.value, self.defaults.get(key.value))
def set(self, key, value):
if key.value in self.defaults:
self.settings[key.value] = self.validate_setting(key.value, value)
class ModernSlideShower(mglw.WindowConfig):
gl_version = (3, 3)
title = "ModernSlideShower"
aspect_ratio = None
clear_color = (0.0, 0.0, 0.0, 0.0)
wnd = mglw.context.base.BaseWindow
screens = []
use_screen_id = 0
start_with_random_image = False
average_frame_time = 0
last_image_load_time = 0
previous_image_duration = 0
init_end_time = 0
picture_vao = moderngl.VertexArray
round_vao = moderngl.VertexArray
file_operation_vao = moderngl.VertexArray
ret_vertex_buffer = moderngl.Buffer
jpegtran_exe = os.path.join(JPEGTRAN_EXE_PATH, JPEGTRAN_EXE_FILE)
image_count = 0
dir_count = 0
image_index = 0
new_image_index = 0
previous_image_index = 0
dir_list = []
file_list = []
dir_to_file = []
file_to_dir = []
image_ratings = []
image_categories = []
tinder_stats_d = {-1: 0, 0: 0, 1: 0}
tinder_last_choice = 0
small_zoom = False
move_sensitivity = 0.
pic_square = 1
thumbs_list = {}
thumb_id = 0
thumb_spacing = 5 # how many percent of space between thumbnails
thumb_period = 1 + thumb_spacing / 100
thumb_loader = multiprocessing.Process
image_loader = multiprocessing.Process
thumb_queue_tasks = multiprocessing.SimpleQueue
thumb_queue_data = multiprocessing.SimpleQueue
image_queue_tasks = multiprocessing.SimpleQueue
image_queue_data = multiprocessing.SimpleQueue
thumbs_for_image_requested = -1
preloads_for_image_requested = -1
image_cache = {}
# random_folder_mode = False
# exclude_plus_minus = False
seen_images = np.zeros(0)
current_image_is_unseen = True
all_images_seen_times = -1
imgui_io = imgui.get_io
imgui_style = imgui.get_style
image_original_size = Point(0, 0)
im_exif = b''
common_path = ""
parent_path = "" # all path lower than parent is considered as subfolders.
pic_pos_current = mp.mpc()
pic_pos_future = mp.mpc()
pic_move_speed = mp.mpc()
pic_pos_fading = mp.mpc()
pic_zoom = .5
pic_zoom_future = .2
pic_zoom_null = .2
pic_angle = 0.
pic_angle_future = 0.
big_zoom = False
gl_program_pic = [moderngl.Program] * 2
gl_program_borders = moderngl.Program
gl_program_round = moderngl.Program
gl_program_mandel = [moderngl.Program] * 3
gl_program_crop = moderngl.Program
gl_program_browse_squares = moderngl.Program
gl_program_browse_pic = moderngl.Program
gl_program_compare = moderngl.Program
use_old_gl = False
mandel_id = 0
program_id = 0
image_texture = moderngl.Texture
thumb_textures = moderngl.TextureArray
THUMBS_ROW_MAX = 7
thumb_rows = 0
thumb_row_elements = 0
thumbs_backward_max = 100
thumbs_forward_max = 200
thumbs_count = thumbs_forward_max + thumbs_backward_max
thumbs_backward = 0
thumbs_forward = 1
thumbs_shown = 1
thumbs_displacement = mp.mpc()
thumb_central_index = 0
current_texture = moderngl.Texture
current_texture_old = moderngl.Texture
histo_texture = moderngl.Texture
histo_texture_empty = moderngl.Buffer
mandel_stat_empty = moderngl.Buffer
histogram_array = np.empty
max_keyboard_flip_speed = .3
mouse_move_atangent = 0.
mouse_move_atangent_delta = 0.
mouse_move_cumulative = 0.
mouse_unflipping_speed = 1.
last_image_folder = None
transition_center = (.4, .4)
reset_frame_timer = True
interface_mode = InterfaceMode.GENERAL
switch_mode = SWITCH_MODE_CIRCLES
# scan_all_files = False
split_line = 0
right_click_start = 0
left_click_start = 0
next_message_top = 0
menu_top = 0
menu_bottom = 1
menu_clicked_last_time = 0
current_frame_start_time = 0
last_frame_duration = 0
mandel_stat_buffer = moderngl.Buffer
mandel_stat_texture_id = 0
mandel_stat_texture_swapped = False
mandel_zones_mask = np.empty
mandel_stat_pull_time = 0
mandel_good_zones = np.empty((32, 32))
mandel_look_for_good_zones = False
mandel_chosen_zone = (0, 0)
mandel_pos_future = mp.mpc()
mandel_move_acceleration = mp.mpc()
mandel_auto_travel_mode = 0
mandel_auto_travel_limit = 0
mandel_auto_travel_speed = 1
mandel_zones_hg = np.empty
mandel_show_debug = False
mandel_auto_complexity = 0.
mandel_auto_complexity_speed = 0.
mandel_auto_complexity_target = 0.
mandel_auto_complexity_fill_target = 620
# configs = {
# Configs.HIDE_BORDERS: 100,
# Configs.TRANSITION_DURATION: .75,
# Configs.INTER_BLUR: 30.,
# Configs.STARTING_ZOOM_FACTOR: .98,
# Configs.PIXEL_SIZE: 0
# }
# config_descriptions = {
# Configs.HIDE_BORDERS: "Hide image borders",
# Configs.TRANSITION_DURATION: "Duration of transition between images",
# Configs.INTER_BLUR: "Blur during transition",
# Configs.STARTING_ZOOM_FACTOR: "Zoom of newly shown image",
# Configs.PIXEL_SIZE: "Pixel shape in case of extreme zoom",
# }
# config_formats = {
# Configs.HIDE_BORDERS: (0, 1000, '%.1f', 2),
# Configs.TRANSITION_DURATION: (0.01, 10, '%.3f', 2),
# Configs.INTER_BLUR: (0, 1000, '%.1f', 4),
# Configs.STARTING_ZOOM_FACTOR: (0, 5, '%.3f', 4),
# Configs.PIXEL_SIZE: (0, 100, '%.1f', 4),
# }
last_key_press_time = 0
setting_active = 0
autoflip_speed = 0.
run_reduce_flipping_speed = 0.
run_key_flipping = 0
key_flipping_next_time = 0.
run_flip_once = 0
pressed_mouse = 0
pop_db = []
# levels_borders = [[0.] * 4, [1.] * 4, [1.] * 4, [0.] * 4, [1.] * 4, [1.] * 4]
levels_borders = [[1. if i % 3 else 0.] * 4 for i in range(6)]
levels_borders_previous = []
levels_enabled = True
levels_edit_band = 3
levels_edit_parameter = 0
levels_edit_group = 0
gesture_mode_timeout = 0
key_picture_movement = [False] * 8
transform_mode = 2
crop_borders_active = 0
pic_screen_borders = np.array([0.] * 4)
crop_borders = np.array([0.] * 4)
resize_xy = 1
resize_x = 1
resize_y = 1
transition_stage = 1.
mouse_buffer = np.array([0., 0.])
show_image_info = 0
show_rapid_menu = False
selected_rapid_action = -1
current_image_file_size = 0
central_message_showing = False
# parser = argparse.ArgumentParser(description="ModernSlideShower", allow_abbrev=False)
# program_args = dict
entered_digits = ""
digit_flop_time = 0
def __init__(self, **kwargs):
super().__init__(**kwargs)
imgui.create_context()
self.imgui = ModernglWindowRenderer(self.wnd)
self.init_program()
def init_program(self):
self.ret_vertex_buffer = self.ctx.buffer(reserve=16)
mp.prec = 120
self.imgui_io = imgui.get_io()
self.imgui_style = imgui.get_style()
self.imgui_io.ini_file_name = np.empty(0).tobytes()
x = np.arange(0, 32)
y = x[:, np.newaxis]
self.mandel_zones_mask = np.exp(-((x - 16) ** 2 + (y - 16) ** 2) / 50).astype(float, order='F')
self.picture_vao = mglw.opengl.vao.VAO("main_image", mode=moderngl.POINTS)
Image.MAX_IMAGE_PIXELS = 10000 * 10000 * 3
random.seed()
# parser.add_argument("--folder_name", help="Specify the folder name")
# self.program_args, unknown_args = parser.parse_known_args()
def sub_program(program_name: str):
return mglw.opengl.program.ShaderSource(program_name.upper(), program_name.lower(),
picture_program_text).source
def get_program_text(filename, program_text=""):
if os.path.isfile(filename):
with open(filename, 'r') as fd:
program_text = fd.read()
return program_text
if program_args.old_gl:
self.use_old_gl = True
else:
try:
# test fot newer version compatibility
picture_program_text = DUMMY_420_SHADER
self.ctx.program(vertex_shader=sub_program("picture_vertex"))
except moderngl.error.Error:
self.use_old_gl = True
prog_suffix = "_simple" if self.use_old_gl else ""
picture_program_text = get_program_text("picture" + prog_suffix + ".glsl")
mandel_program_text = get_program_text("mandelbrot" + prog_suffix + ".glsl")
def compile_program(vertex_name, geometry_name, fragment_name):
if geometry_name:
geometry_name = sub_program(geometry_name)
return self.ctx.program(vertex_shader=sub_program(vertex_name),
geometry_shader=geometry_name,
fragment_shader=sub_program(fragment_name))
self.gl_program_pic = []
for _ in (0, 0):
self.gl_program_pic.append(compile_program("picture_vertex", "picture_geometry", "picture_fragment"))
self.gl_program_pic[-1]['texture_image'] = 5
self.gl_program_crop = compile_program("picture_vertex", "crop_geometry", "crop_fragment")
self.gl_program_browse_squares = compile_program("picture_vertex", "browse_geometry", "browse_fragment")
self.gl_program_browse_pic = compile_program("picture_vertex", "browse_pic_geometry", "browse_pic_fragment")
self.gl_program_compare = compile_program("compare_vertex", "compare_geometry", "compare_fragment")
self.gl_program_round = compile_program("round_vertex", None, "round_fragment")
self.gl_program_borders = self.ctx.program(vertex_shader=sub_program("picture_vertex"),
varyings=['crop_borders'])
self.gl_program_browse_pic['texture_thumb'] = 8
self.gl_program_borders['texture_image'] = 5
p_d = moderngl_window.meta.ProgramDescription
program_single = mglw.opengl.program.ProgramShaders.from_single
self.gl_program_mandel = []
self.gl_program_mandel.append(program_single(p_d(defines={"definition": 0}), mandel_program_text).create())
self.gl_program_mandel.append(program_single(p_d(defines={"definition": 1}), mandel_program_text).create())
self.gl_program_mandel.append(program_single(p_d(defines={"definition": 2}), mandel_program_text).create())
self.mandel_stat_buffer = self.ctx.texture((32, 64), 1, dtype='u4')
self.mandel_stat_buffer.bind_to_image(4, read=True, write=True)
self.mandel_stat_empty = self.ctx.buffer(reserve=(32 * 64 * 4))
self.histo_texture = self.ctx.texture((256, 5), 1, dtype='u4')
self.histo_texture.bind_to_image(7, read=True, write=True)
self.histo_texture_empty = self.ctx.buffer(reserve=(256 * 5 * 4))
self.histogram_array = np.zeros((5, 256), dtype=np.float32)
self.generate_round_geometry()
self.empty_level_borders()
self.empty_level_borders()
self.find_jpegtran()
# self.load_settings()
# loaded_settings = load_settings()
# if loaded_settings:
# self.configs = load_settings()
def post_init(self):
self.window_size = self.wnd.size
if program_args.random_image:
self.start_with_random_image = Actions.IMAGE_RANDOM_FILE
if program_args.random_dir:
self.start_with_random_image = Actions.IMAGE_RANDOM_DIR_FIRST_FILE
# if "-r" in sys.argv or "-F5" in sys.argv:
# self.start_with_random_image = Actions.IMAGE_RANDOM_FILE
# if "-F6" in sys.argv:
# self.start_with_random_image = Actions.IMAGE_RANDOM_IN_CURRENT_DIR
# if "-F7" in sys.argv:
# self.start_with_random_image = Actions.IMAGE_RANDOM_DIR_FIRST_FILE
# if "-F8" in sys.argv:
# self.start_with_random_image = Actions.IMAGE_RANDOM_DIR_RANDOM_FILE
self.get_images()
if self.wnd.is_closing:
return
if self.image_count == 0:
self.central_message_showing = 2
self.switch_interface_mode(InterfaceMode.MANDELBROT)
self.init_end_time = self.timer.time
return
self.image_categories = np.zeros(self.image_count, dtype=int)
self.seen_images = np.zeros(self.image_count, dtype=bool)
self.tinder_stats_d[0] = self.image_count
self.find_common_path()
if self.start_with_random_image:
if self.start_with_random_image is True:
self.start_with_random_image = Actions.IMAGE_RANDOM_FILE
self.random_image(self.start_with_random_image)
else:
self.load_image()
self.unschedule_pop_message(7)
self.unschedule_pop_message(8)
self.transition_stage = 1
if program_args.tinder_mode:
self.switch_swithing_mode(SWITCH_MODE_TINDER)
# --- Temp part. Fill thumbs base
new_image = Image.new("RGB", (256, 256), (25, 50, 80))
d = ImageDraw.Draw(new_image)
d.ellipse((10, 10, 200, 200))
d.ellipse((100, 100, 255, 255))
thumb_texture = self.ctx.texture_array((256, 256, self.thumbs_count), 3)
for i in range(self.thumbs_count):
d.ellipse(tuple(np.random.randint(0, 128, 2).tolist() + np.random.randint(128, 256, 2).tolist()))
thumb_texture.write(new_image.tobytes(), (0, 0, i, 256, 256, 1))
self.thumb_textures = thumb_texture
self.gl_program_browse_pic['thumbs_count'] = self.thumbs_count
self.gl_program_browse_squares['thumb_period'] = self.thumb_period
self.gl_program_browse_pic['thumb_period'] = self.thumb_period
self.thumbs_list = [''] * self.thumbs_count
self.init_end_time = self.timer.time
self.thumb_textures.use(location=8)
def previous_level_borders(self):
self.levels_borders = self.levels_borders_previous
self.update_levels()
def empty_level_borders(self):
self.levels_borders_previous = self.levels_borders
self.levels_borders = [[0.] * 4, [1.] * 4, [1.] * 4, [0.] * 4, [1.] * 4, [1.] * 4]
self.update_levels()
def generate_round_geometry(self):
points_count = 50
def generate_points(points_array_x, points_array_y, scale, move):
points_array = np.empty((100,), dtype=points_array_x.dtype)
points_array[0::2] = points_array_x
points_array[1::2] = points_array_y
points_array *= scale
points_array += move
return points_array
points_array = generate_points(
np.sin(np.linspace(0., math.tau, points_count, endpoint=False)),
np.cos(np.linspace(0., math.tau, points_count, endpoint=False)),
40, 70
)
self.round_vao = mglw.opengl.vao.VAO("round", mode=moderngl.POINTS)
self.round_vao.buffer(points_array.astype('f4'), '2f', ['in_position'])
points_array = generate_points(
(np.linspace(2, 0, points_count, endpoint=False)),
(np.linspace(6, 0, points_count, endpoint=False) % 3),
30, 20
)
self.file_operation_vao = mglw.opengl.vao.VAO("round", mode=moderngl.POINTS)
self.file_operation_vao.buffer(points_array.astype('f4'), '2f', ['in_position'])
def update_levels(self, edit_parameter=None):
if edit_parameter is None:
for i in range(6):
self.update_levels(i)
return
border_name = LEVEL_BORDER_NAMES[edit_parameter]
self.gl_program_pic[self.program_id][border_name] = tuple(self.levels_borders[edit_parameter])
def find_jpegtran(self):
if not os.path.isfile(self.jpegtran_exe):
if os.path.isfile(JPEGTRAN_EXE_FILE):
self.jpegtran_exe = os.path.abspath(JPEGTRAN_EXE_FILE)
else:
self.jpegtran_exe = None
def get_images(self):
file_arguments = []
dir_arguments = []
if program_args.path:
for argument in program_args.path:
if os.path.isdir(argument.rstrip('\\"')):
dir_arguments.append(os.path.abspath(argument.rstrip('\\"')))
if os.path.isfile(argument):
file_arguments.append(os.path.abspath(argument))
if len(dir_arguments):
[self.scan_directory(directory) for directory in dir_arguments]
if len(file_arguments):
if len(dir_arguments) == 0 and len(file_arguments) == 1:
if file_arguments[0].lower().endswith(ALL_FILE_TYPES) or program_args.ignore_extention:
self.scan_directory(os.path.dirname(file_arguments[0]), file_arguments[0])
else:
self.scan_file(file_arguments[0])
else:
[self.scan_file(file) for file in file_arguments]
else:
self.scan_directory(os.path.abspath('.\\'))
print(self.image_count, "total images found")
def find_common_path(self):
# todo: resolve situation when paths are on different drives
if len(self.dir_list) == 0:
return
if len(self.dir_list) > 10000:
self.common_path = os.path.commonpath(self.dir_list[::len(self.dir_list) // 1000] + self.dir_list[-3:])
else:
self.common_path = os.path.commonpath(self.dir_list)
parent_path = self.dir_list[0]
if self.common_path == parent_path:
self.common_path = os.path.dirname(self.common_path)
if program_args.base_folder_name:
search_folder = os.path.sep + program_args.base_folder_name + os.path.sep
found_match = self.common_path.find(search_folder)
if found_match >= 0:
self.parent_path = self.common_path[:found_match + len(search_folder)]
if not self.parent_path:
self.parent_path = os.path.dirname(self.common_path)
print(f"Common path: {self.common_path}")
print(f"Parent path: {self.parent_path}")
def scan_directory(self, dirname, look_for_file=None):
print("Searching for images in", dirname)
def adjust_step():
if self.image_count > 15000:
return 1000
elif self.image_count > 5000:
return 500
return 100
report_step = adjust_step()
for root, dirs, files in os.walk(dirname):
file_count = 0
this_dir_file_list = []
first_file = self.image_count
if program_args.exclude_sorted:
if "\\++" in root or "\\--" in root:
continue
for f in files:
if self.wnd.is_closing:
return
if f.lower().endswith(ALL_FILE_TYPES) or program_args.ignore_extention:
img_path = os.path.join(root, f)
self.image_count += 1
file_count += 1
this_dir_file_list.append(f)
self.file_to_dir.append(self.dir_count)
if not self.image_count % report_step:
print(self.image_count, "images found", end="\r")
self.render()
report_step = adjust_step()
if look_for_file:
if img_path == look_for_file:
self.new_image_index = self.image_count - 1
if file_count:
self.dir_list.append(root)
self.dir_to_file.append([first_file, file_count])
self.dir_count += 1
self.file_list += natsorted(this_dir_file_list)
def scan_file(self, filename):
if filename.lower().endswith(ALL_FILE_TYPES) or program_args.ignore_extention:
file_dir = os.path.dirname(filename)
if self.dir_list and file_dir == self.dir_list[-1]:
self.file_to_dir.append(self.dir_count - 1)
self.dir_to_file[-1][1] += 1
else:
self.dir_list.append(file_dir)
self.dir_to_file.append([self.image_count, 1])
self.file_to_dir.append(self.dir_count)
self.dir_count += 1
self.file_list.append(os.path.basename(filename))
self.image_count += 1
elif filename.lower().endswith(LIST_FILE_TYPE):
self.load_list_file(filename)
if "_r." in os.path.basename(filename):
self.start_with_random_image = self.start_with_random_image or True
elif filename.lower().endswith(PLAIN_LIST_FILE_TYPE):
self.load_plain_list_file(filename)
if "_r." in os.path.basename(filename):
self.start_with_random_image = self.start_with_random_image or True
def load_plain_list_file(self, filename):
print("Opening plain list", filename)
with open(filename, 'r', encoding='utf-8') as file_handle:
if program_args.skip_load:
def skip_lines(lines):
for _ in range(lines):
next(file_handle, False)
return next(file_handle, False)
loaded_list = []
last_line = 0
skip_step = 2 ** program_args.skip_load
sp = (-skip_step // 50 - 1, skip_step // 30 + 1, skip_step // 2 + 1)
skip_lines(random.randint(0, skip_step))
while last_line := skip_lines(skip_step if last_line else 0):
loaded_list.append(last_line.rstrip())
skip_step = max(skip_step + random.randint(*sp[:2]), sp[2])
else:
loaded_list = [line.rstrip() for line in file_handle.readlines()]
last_dir_index = 0
for line in loaded_list:
if not line.lower().endswith(ALL_FILE_TYPES):
continue
line_split = line.split(":::")
image_rating = line_split[0] if len(line_split) > 1 else 0
file_dir = os.path.dirname(line_split[-1])
self.file_list.append(os.path.basename(line_split[-1]))
if self.dir_list and file_dir == self.dir_list[last_dir_index]:
self.dir_to_file[last_dir_index][1] += 1
elif file_dir in self.dir_list:
last_dir_index = self.dir_list.index(file_dir)
self.dir_to_file[last_dir_index][1] += 1
else:
last_dir_index = self.dir_count
self.dir_list.append(file_dir)
self.dir_to_file.append([self.image_count, 1])
self.dir_count += 1
self.file_to_dir.append(last_dir_index)
self.image_ratings.append(image_rating)
self.image_count += 1
def load_list_file(self, filename):
print("Opening list", filename)
with open(filename, 'r', encoding='utf-8') as file_handle:
loaded_list = [line.rstrip() for line in file_handle.readlines()]
print("Image list decompression")
current_dir = ""
current_dir_index = self.dir_count
current_dir_file_count = 0
current_dir_file_start = self.image_count
previous_line = ""
for line in loaded_list:
if line[-1] == "\\":
if current_dir_file_count:
self.dir_to_file.append([current_dir_file_start, current_dir_file_count])
self.dir_list.append(current_dir)
self.dir_count += 1
current_dir_file_count = 0
current_dir = line[:-1]
current_dir_index = self.dir_count
current_dir_file_start = self.image_count
else:
if line[0] == ":":
length_end = 2 if line[2] == " " or line[2] == ":" else 3
full_line = previous_line[:int(line[1:length_end])] + line[length_end + 1:]
if line[length_end] == ":":
full_line += previous_line[len(full_line):]
else:
full_line = line
previous_line = full_line
self.file_list.append(full_line)
self.file_to_dir.append(current_dir_index)
current_dir_file_count += 1
self.image_count += 1
self.dir_to_file.append([current_dir_file_start, current_dir_file_count])
self.dir_list.append(current_dir)
self.dir_count += 1
def save_list_file(self, compress=True):
if not os.path.isdir(SAVE_FOLDER):
try:
os.makedirs(SAVE_FOLDER)
except Exception as e:
print("Could not create folder ", e)
new_list_file_name = os.path.basename(self.common_path) + '_' + \
datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S") + '.' + LIST_FILE_TYPE
new_list_file_name = os.path.join(os.path.dirname(self.common_path), new_list_file_name)
with open(new_list_file_name, 'w', encoding='utf-8') as file_handle:
for dir_num, dir_name in enumerate(self.dir_list):
first, count = self.dir_to_file[dir_num]
file_handle.write("{}\\\n".format(dir_name))
if not compress:
file_handle.writelines("{}\n".format(name) for name in self.file_list[first:first + count])
else:
previous_file_name = ""
for file_name in self.file_list[first:first + count]:
common_start = 0
start_increment = 1
common_end = 0
for pair in zip(previous_file_name, file_name):
if pair[0] == pair[1]:
common_start += start_increment
common_end -= 1
else:
start_increment = 0
common_end = 0
if 4 < common_start - common_end and common_start < 99:
if len(previous_file_name) != len(file_name) or common_end == 0:
common_end = 1000
separator = ' '
else:
separator = ':'
short_name = f":{common_start:d}{separator}{file_name[common_start:common_end]}\n"
else:
short_name = file_name + "\n"
file_handle.write(short_name)
previous_file_name = file_name
def get_file_path(self, index=None):
if index is None:
index = min(self.new_image_index, self.image_count - 1)
if self.image_count == 0:
dir_index = - 1
else:
dir_index = self.file_to_dir[index]
if dir_index == -1:
return EMPTY_IMAGE_LIST
dir_name = self.dir_list[dir_index]
file_name = self.file_list[index]
img_path = os.path.join(dir_name, file_name)
if os.path.isfile(img_path):
return img_path
else:
return EMPTY_IMAGE_LIST
def release_texture(self, texture):
if self.image_texture == texture:
return
if type(texture) is moderngl.Texture:
try:
texture.release()
except Exception:
pass
def prepare_to_mandelbrot(self):
self.image_original_size = Point(self.wnd.width, self.wnd.height)
self.show_image_info = 1
self.wnd.title = "ModernSlideShower: Mandelbrot mode"
self.pic_angle_future = -30
self.mandel_auto_complexity = 2
self.pic_zoom = 1e-3
self.pic_zoom_future = .2
self.discrete_actions(Actions.SWITCH_MODE_CIRCLES)
self.unschedule_pop_message(21)
def load_next_existing_image(self):
start_number = self.new_image_index
half_count = self.image_count // 2
image_jump = (self.new_image_index - self.image_index + half_count) % self.image_count - half_count
increment = -1 if image_jump < 0 else 1
while True:
self.new_image_index = (self.new_image_index + increment) % self.image_count
if start_number == self.new_image_index:
self.file_list[self.new_image_index] = EMPTY_IMAGE_LIST
self.central_message_showing = 3
self.switch_interface_mode(InterfaceMode.MANDELBROT)
break
if os.path.exists(self.get_file_path()):
if not self.load_image(subloader=True):
break
def load_image(self, subloader=False):
def load_failed():
if subloader:
return 1
else: