forked from yfszzx/stable-diffusion-webui-images-browser
-
Notifications
You must be signed in to change notification settings - Fork 111
/
image_browser.py
1929 lines (1744 loc) · 94 KB
/
image_browser.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 gradio as gr
import codecs
import csv
import importlib
import json
import logging
import math
import os
import platform
import random
import re
import shutil
import stat
import subprocess as sp
import sys
import tempfile
import time
import torch
import traceback
import hashlib
import modules.extras
import modules.images
import modules.ui
from datetime import datetime
from modules import paths, shared, script_callbacks, scripts, images
from modules.shared import opts, cmd_opts
from modules.ui_common import plaintext_to_html
from modules.ui_components import ToolButton, DropdownMulti
from PIL import Image, ImageOps, UnidentifiedImageError, ImageDraw
from packaging import version
from pathlib import Path
from typing import List, Tuple
from itertools import chain
from io import StringIO
try:
from scripts.wib import wib_db
except ModuleNotFoundError:
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "scripts")))
from wib import wib_db
try:
from send2trash import send2trash
send2trash_installed = True
except ImportError:
print("Image Browser: send2trash is not installed. Recycle bin cannot be used.")
send2trash_installed = False
try:
import cv2
opencv_installed = True
except ImportError:
print("Image Browser: opencv is not installed. Video related actions cannot be performed.")
opencv_installed = False
try:
from modules import generation_parameters_copypaste as sendto
except ImportError:
from modules import infotext_utils as sendto
try:
from modules_forge import forge_version
forge = True
except ImportError:
forge = False
# Force reload wib_db, as it doesn't get reloaded otherwise, if an extension update is started from webui
importlib.reload(wib_db)
yappi_do = False
components_list = ["Sort by", "Filename keyword search", "EXIF keyword search", "Ranking Filter", "Aesthestic Score", "Generation Info", "File Name", "File Time", "Open Folder", "Send to buttons", "Copy to directory", "Gallery Controls Bar", "Ranking Bar", "Delete Bar", "Additional Generation Info"]
num_of_imgs_per_page = 0
loads_files_num = 0
image_ext_list = [".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp", ".svg"]
video_ext_list = [".mp4", ".mov", ".avi", ".wmv", ".flv", ".mkv", ".webm", ".mpeg", ".mpg", ".3gp", ".ogv", ".m4v"]
if not opencv_installed:
video_ext_list = []
exif_cache = {}
aes_cache = {}
none_select = "Nothing selected"
refresh_symbol = '\U0001f504' # 🔄
up_symbol = '\U000025b2' # ▲
down_symbol = '\U000025bc' # ▼
caution_symbol = '\U000026a0' # ⚠
folder_symbol = '\U0001f4c2' # 📂
play_symbol = '\U000023f5' # ⏵
current_depth = 0
init = True
copy_move = ["Move", "Copy"]
copied_moved = ["Moved", "Copied"]
np = "negative_prompt: "
openoutpaint = False
controlnet = False
js_dummy_return = None
log_file = os.path.join(scripts.basedir(), "image_browser.log")
optimized_cache = None
show_progress_setting = True
gradio_min = "3.23.0"
gradio3_new_gallery_syntax = "3.39.0"
gradio4 = "4.0.0"
gradio4_new_gallery_syntax = "4.16.0"
temp_temp = os.path.join(scripts.basedir(), "temp")
db_version = wib_db.check()
favorite_tab_name = "Favorites"
default_tab_options = ["txt2img", "img2img", "txt2img-grids", "img2img-grids", "Extras", favorite_tab_name, "Others", "All", "Maintenance"]
def check_image_browser_active_tabs():
last_default_tab = wib_db.get_last_default_tab()
if last_default_tab[0] == "Others":
# New tabs don't exist yet in image_browser_active_tabs, add them
with wib_db.transaction() as cursor:
wib_db.update_db_data(cursor, "last_default_tab", "Maintenance")
if hasattr(opts, "image_browser_active_tabs"):
active_and_new_tabs = f"{opts.image_browser_active_tabs}, All, Maintenance"
shared.opts.__setattr__("image_browser_active_tabs", active_and_new_tabs)
shared.opts.save(shared.config_filename)
check_image_browser_active_tabs()
tabs_list = [tab.strip() for tab in chain.from_iterable(csv.reader(StringIO(opts.image_browser_active_tabs))) if tab] if hasattr(opts, "image_browser_active_tabs") and opts.image_browser_active_tabs != "" else default_tab_options
path_maps = {
"txt2img": opts.outdir_samples or opts.outdir_txt2img_samples,
"img2img": opts.outdir_samples or opts.outdir_img2img_samples,
"txt2img-grids": opts.outdir_grids or opts.outdir_txt2img_grids,
"img2img-grids": opts.outdir_grids or opts.outdir_img2img_grids,
"Extras": opts.outdir_samples or opts.outdir_extras_samples,
favorite_tab_name: opts.outdir_save
}
class ImageBrowserTab():
seen_base_tags = set()
def __init__(self, name: str):
self.name: str = os.path.basename(name) if os.path.isdir(name) else name
self.path: str = os.path.realpath(path_maps.get(name, name))
self.base_tag: str = f"image_browser_tab_{self.get_unique_base_tag(self.remove_invalid_html_tag_chars(self.name).lower())}"
def remove_invalid_html_tag_chars(self, tag: str) -> str:
# Removes any character that is not a letter, a digit, a hyphen, or an underscore
removed = re.sub(r'[^a-zA-Z0-9\-_]', '', tag)
return removed
def get_unique_base_tag(self, base_tag: str) -> str:
counter = 1
while base_tag in self.seen_base_tags:
match = re.search(r'_(\d+)$', base_tag)
if match:
counter = int(match.group(1)) + 1
base_tag = re.sub(r'_(\d+)$', f"_{counter}", base_tag)
else:
base_tag = f"{base_tag}_{counter}"
counter += 1
self.seen_base_tags.add(base_tag)
return base_tag
def __str__(self):
return f"Name: {self.name} / Path: {self.path} / Base tag: {self.base_tag} / Seen base tags: {self.seen_base_tags}"
tabs_list = [ImageBrowserTab(tab) for tab in tabs_list]
# Set temp_dir from webui settings, so gradio uses it
if shared.opts.temp_dir != "":
tempfile.tempdir = shared.opts.temp_dir
if forge:
# Workaround for forge: Its ui_tempdir seems to not use the temp_dir configuration
# The following makes sure, that onchange triggers after setting temp_dir
shared.opts.temp_dir = temp_temp
shared.opts.temp_dir = tempfile.tempdir
debug_level_types = ["none", "warning log", "debug log", "javascript log", "capture logs to file"]
debug_levels_list = []
for i in range(len(debug_level_types)):
level = debug_level_types[i].split(" ")[0]
text = str(i) + " - " + debug_level_types[i]
debug_levels_list.append((level, text))
def debug_levels(arg_value=None, arg_level=None, arg_text=None):
if arg_value is not None:
return arg_value, debug_levels_list[arg_value]
elif arg_level is not None:
for i, (level, text) in enumerate(debug_levels_list):
if level == arg_level:
return i, debug_levels_list[i]
elif arg_text is not None:
for i, (level, text) in enumerate(debug_levels_list):
if text == arg_text:
return i, debug_levels_list[i]
# Logging
logger = None
logger_mode = None
def setup_file_handler():
handler_active = False
handlers = logger.handlers
for handler in handlers:
if isinstance(handler, logging.FileHandler):
if os.path.basename(handler.baseFilename) == os.path.basename(log_file):
handler_active = True
break
if not handler_active:
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(logger_mode)
formatter = logging.Formatter(f'%(asctime)s image_browser.py: %(message)s', datefmt='%Y-%m-%d-%H:%M:%S')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
def setup_debug():
global logger, logger_mode
try:
common_logger = True
logger = shared.log
except AttributeError:
common_logger = False
logger = logging.getLogger(__name__)
logger.disabled = False
logger_mode = logging.ERROR
level_value = 0
capture_level_value = 99
if hasattr(opts, "image_browser_debug_level"):
warning_level_value, (warning_level, warning_level_text) = debug_levels(arg_level="warning")
debug_level_value, (debug_level, debug_level_text) = debug_levels(arg_level="debug")
capture_level_value, (capture_level, capture_level_text) = debug_levels(arg_level="capture")
level_value, (level, level_text) = debug_levels(arg_text=opts.image_browser_debug_level)
if level_value >= debug_level_value:
logger_mode = logging.DEBUG
elif level_value >= warning_level_value:
logger_mode = logging.WARNING
logger.setLevel(logger_mode)
if not common_logger:
console_handler = logging.StreamHandler()
console_handler.setLevel(logger_mode)
formatter = logging.Formatter(f'%(asctime)s image_browser.py: %(message)s', datefmt='%Y-%m-%d-%H:%M:%S')
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
if level_value >= capture_level_value:
try:
os.unlink(log_file)
except FileNotFoundError:
pass
setup_file_handler()
logger.warning(f"debug_level: {level_value}")
# Debug logging
if logger.getEffectiveLevel() == logging.DEBUG:
logger.debug(f"{sys.executable} {sys.version}")
logger.debug(f"{platform.system()} {platform.version()}")
try:
git = os.environ.get('GIT', "git")
webui_commit_hash = os.popen(f"{git} rev-parse HEAD").read().strip()
sm_hashes = os.popen(f"{git} submodule").read()
sm_hashes_lines = sm_hashes.splitlines()
image_browser_commit_hash = f"image_browser_commit_hash not found: {sm_hashes}"
for sm_hashes_line in sm_hashes_lines:
if "images-browser" in sm_hashes_line.lower():
image_browser_commit_hash = sm_hashes_line[1:41]
break
except Exception as e:
webui_commit_hash = e
image_browser_commit_hash = e
logger.debug(f"Webui {webui_commit_hash}")
logger.debug(f"Image Browser {image_browser_commit_hash}")
logger.debug(f"Gradio {gr.__version__}")
logger.debug(f"{paths.script_path}")
with open(cmd_opts.ui_config_file, "r", encoding="utf-8") as f:
logger.debug(f.read())
with open(cmd_opts.ui_settings_file, "r", encoding="utf-8") as f:
logger.debug(f.read())
logger.debug(os.path.realpath(__file__))
logger.debug([str(tab) for tab in tabs_list])
logger.debug(f"db_version: {db_version}")
setup_debug()
def delete_recycle(filename):
if opts.image_browser_delete_recycle and send2trash_installed:
send2trash(filename)
else:
file = Path(filename)
file.unlink()
return
def img_path_subdirs_get(img_path):
subdirs = []
subdirs.append(none_select)
for item in os.listdir(img_path):
item_path = os.path.join(img_path, item)
if os.path.isdir(item_path):
subdirs.append(item_path)
return gr.update(choices=subdirs)
def img_path_add_remove(img_dir, path_recorder, add_remove, img_path_depth):
img_dir = os.path.realpath(img_dir)
if add_remove == "add" or (add_remove == "remove" and img_dir in path_recorder):
if add_remove == "add":
path_recorder[img_dir] = {
"depth": int(img_path_depth),
"path_display": f"{img_dir} [{int(img_path_depth)}]"
}
wib_db.update_path_recorder(img_dir, path_recorder[img_dir]["depth"], path_recorder[img_dir]["path_display"])
else:
del path_recorder[img_dir]
wib_db.delete_path_recorder(img_dir)
path_recorder_formatted = [value.get("path_display") for key, value in path_recorder.items()]
path_recorder_formatted = sorted(path_recorder_formatted, key=lambda x: natural_keys(x.lower()))
if add_remove == "remove":
selected = path_recorder[list(path_recorder.keys())[0]]["path_display"]
else:
selected = path_recorder[img_dir]["path_display"]
return path_recorder, gr.update(choices=path_recorder_formatted, value=selected)
def sort_order_flip(turn_page_switch, sort_order):
if sort_order == up_symbol:
sort_order = down_symbol
else:
sort_order = up_symbol
return 1, turn_page_switch + 1, sort_order
def read_path_recorder():
path_recorder = wib_db.load_path_recorder()
path_recorder_formatted = [value.get("path_display") for key, value in path_recorder.items()]
path_recorder_formatted = sorted(path_recorder_formatted, key=lambda x: natural_keys(x.lower()))
path_recorder_unformatted = list(path_recorder.keys())
path_recorder_unformatted = sorted(path_recorder_unformatted, key=lambda x: natural_keys(x.lower()))
return path_recorder, path_recorder_formatted, path_recorder_unformatted
def pure_path(path):
if path == []:
return path, 0
match = re.search(r" \[(\d+)\]$", path)
if match:
path = path[:match.start()]
depth = int(match.group(1))
else:
depth = 0
path = os.path.realpath(path)
return path, depth
def browser2path(img_path_browser):
img_path, _ = pure_path(img_path_browser)
return img_path
def totxt(file):
base, _ = os.path.splitext(file)
file_txt = base + '.txt'
return file_txt
def tab_select():
path_recorder, path_recorder_formatted, path_recorder_unformatted = read_path_recorder()
return path_recorder, gr.update(choices=path_recorder_unformatted)
def js_logs_output(js_log):
logger.debug(f"js_log: {js_log}")
return js_log
def ranking_filter_settings(page_index, turn_page_switch, ranking_filter):
if ranking_filter == "Min-max":
interactive = True
else:
interactive = False
page_index = 1
return page_index, turn_page_switch + 1, gr.update(interactive=interactive), gr.update(interactive=interactive)
def reduplicative_file_move(src, dst):
def same_name_file(basename, path):
name, ext = os.path.splitext(basename)
f_list = os.listdir(path)
max_num = 0
for f in f_list:
if len(f) <= len(basename):
continue
f_ext = f[-len(ext):] if len(ext) > 0 else ""
if f[:len(name)] == name and f_ext == ext:
if f[len(name)] == "(" and f[-len(ext)-1] == ")":
number = f[len(name)+1:-len(ext)-1]
if number.isdigit():
if int(number) > max_num:
max_num = int(number)
return f"{name}({max_num + 1}){ext}"
name = os.path.basename(src)
save_name = os.path.join(dst, name)
src_txt_exists = False
if opts.image_browser_txt_files:
src_txt = totxt(src)
if os.path.exists(src_txt):
src_txt_exists = True
if not os.path.exists(save_name):
if opts.image_browser_copy_image:
shutil.copy2(src, dst)
if opts.image_browser_txt_files and src_txt_exists:
shutil.copy2(src_txt, dst)
else:
shutil.move(src, dst)
if opts.image_browser_txt_files and src_txt_exists:
shutil.move(src_txt, dst)
else:
name = same_name_file(name, dst)
if opts.image_browser_copy_image:
shutil.copy2(src, os.path.join(dst, name))
if opts.image_browser_txt_files and src_txt_exists:
shutil.copy2(src_txt, totxt(os.path.join(dst, name)))
else:
shutil.move(src, os.path.join(dst, name))
if opts.image_browser_txt_files and src_txt_exists:
shutil.move(src_txt, totxt(os.path.join(dst, name)))
def save_image(file_name, filenames, page_index, turn_page_switch, dest_path):
if file_name is not None and os.path.exists(file_name):
reduplicative_file_move(file_name, dest_path)
message = f"<div style='color:#999'>{copied_moved[opts.image_browser_copy_image]} to {dest_path}</div>"
if not opts.image_browser_copy_image:
# Force page refresh with checking filenames
filenames = []
turn_page_switch += 1
else:
message = "<div style='color:#999'>Image not found (may have been already moved)</div>"
return message, filenames, page_index, turn_page_switch
def delete_image(tab_base_tag_box, delete_num, name, filenames, image_index, visible_num, delete_confirm, turn_page_switch, image_page_list):
logger.debug("delete_image")
refresh = False
delete_num = int(delete_num)
image_index = int(image_index)
visible_num = int(visible_num)
image_page_list = json.loads(image_page_list)
new_file_list = []
new_image_page_list = []
if name == "":
refresh = True
else:
try:
index_files = list(filenames).index(name)
index_on_page = image_page_list.index(name)
except ValueError as e:
print(traceback.format_exc(), file=sys.stderr)
# Something went wrong, force a page refresh
refresh = True
if not refresh:
if not delete_confirm:
delete_num = min(visible_num - index_on_page, delete_num)
new_file_list = filenames[:index_files] + filenames[index_files + delete_num:]
new_image_page_list = image_page_list[:index_on_page] + image_page_list[index_on_page + delete_num:]
for i in range(index_files, index_files + delete_num):
if os.path.exists(filenames[i]):
if opts.image_browser_delete_message:
print(f"Deleting file {filenames[i]}")
delete_recycle(filenames[i])
visible_num -= 1
if opts.image_browser_txt_files:
txt_file = totxt(filenames[i])
if os.path.exists(txt_file):
delete_recycle(txt_file)
else:
print(f"File does not exist {filenames[i]}")
# If we reach this point (which we shouldn't), things are messed up, better force a page refresh
refresh = True
if refresh:
turn_page_switch += 1
select_image = False
else:
select_image = True
return new_file_list, 1, turn_page_switch, visible_num, new_image_page_list, select_image, json.dumps(new_image_page_list)
def traverse_all_files(curr_path, image_list, tab_base_tag_box, img_path_depth) -> List[Tuple[str, os.stat_result, str, int]]:
global current_depth
logger.debug(f"curr_path: {curr_path}")
if curr_path == "":
return image_list
f_list = [(os.path.join(curr_path, entry.name), entry.stat()) for entry in os.scandir(curr_path)]
for f_info in f_list:
fname, fstat = f_info
if os.path.splitext(fname)[1] in image_ext_list or os.path.splitext(fname)[1] in video_ext_list:
image_list.append(f_info)
elif stat.S_ISDIR(fstat.st_mode):
if (opts.image_browser_with_subdirs and tab_base_tag_box != "image_browser_tab_others") or (tab_base_tag_box == "image_browser_tab_all") or (tab_base_tag_box == "image_browser_tab_others" and img_path_depth != 0 and (current_depth < img_path_depth or img_path_depth < 0)):
current_depth = current_depth + 1
image_list = traverse_all_files(fname, image_list, tab_base_tag_box, img_path_depth)
current_depth = current_depth - 1
return image_list
def cache_exif(fileinfos):
global exif_cache, aes_cache
if yappi_do:
import yappi
import pandas as pd
yappi.set_clock_type("wall")
yappi.start()
cache_exif_start = time.time()
new_exif = 0
new_aes = 0
with wib_db.transaction() as cursor:
for fi_info in fileinfos:
found_exif = False
found_aes = False
if fi_info[0] in exif_cache:
found_exif = True
if fi_info[0] in aes_cache:
found_aes = True
is_img = os.path.splitext(fi_info[0])[1] in image_ext_list
if not found_exif or not found_aes or not is_img:
exif_cache[fi_info[0]] = "0"
aes_cache[fi_info[0]] = "0"
if not is_img:
allExif = False
else:
try:
image = Image.open(fi_info[0])
(_, allExif, allExif_html) = modules.extras.run_pnginfo(image)
image.close()
except SyntaxError:
allExif = False
logger.warning(f"Extension and content don't match: {fi_info[0]}")
except UnidentifiedImageError as e:
allExif = False
logger.warning(f"UnidentifiedImageError: {e}")
except Image.DecompressionBombError as e:
allExif = False
logger.warning(f"DecompressionBombError: {e}: {fi_info[0]}")
except PermissionError as e:
allExif = False
logger.warning(f"PermissionError: {e}: {fi_info[0]}")
except FileNotFoundError as e:
allExif = False
logger.warning(f"FileNotFoundError: {e}: {fi_info[0]}")
except OSError as e:
if e.errno == 22:
logger.warning(f"Caught OSError with error code 22: {fi_info[0]}")
else:
raise
if allExif:
exif_cache[fi_info[0]] = allExif
wib_db.update_exif_data(cursor, fi_info[0], allExif)
new_exif = new_exif + 1
m = re.search("(?:aesthetic_score:|Score:) (\d+.\d+)", allExif, flags=re.IGNORECASE)
if m:
aes_value = m.group(1)
else:
aes_value = "0"
aes_cache[fi_info[0]] = aes_value
wib_db.update_exif_data_by_key(cursor, fi_info[0], "aesthetic_score", aes_value)
new_aes = new_aes + 1
else:
try:
filename = os.path.splitext(fi_info[0])[0] + ".txt"
geninfo = ""
with open(filename) as f:
for line in f:
geninfo += line
exif_cache[fi_info[0]] = geninfo
wib_db.update_exif_data_by_key(cursor, fi_info[0], geninfo)
new_exif = new_exif + 1
m = re.search("(?:aesthetic_score:|Score:) (\d+.\d+)", geninfo, flags=re.IGNORECASE)
if m:
aes_value = m.group(1)
else:
aes_value = "0"
aes_cache[fi_info[0]] = aes_value
wib_db.update_exif_data_by_key(cursor, fi_info[0], "aesthetic_score", aes_value)
new_aes = new_aes + 1
except Exception:
if is_img:
logger.warning(f"cache_exif: No EXIF in image or txt file for {fi_info[0]}")
# Saved with defaults to not scan it again next time
exif_cache[fi_info[0]] = "0"
allExif = "0"
wib_db.update_exif_data(cursor, fi_info[0], allExif)
new_exif = new_exif + 1
aes_value = "0"
aes_cache[fi_info[0]] = aes_value
wib_db.update_exif_data_by_key(cursor, fi_info[0], "aesthetic_score", aes_value)
new_aes = new_aes + 1
if yappi_do:
yappi.stop()
pd.set_option('display.float_format', lambda x: '%.6f' % x)
yappi_stats = yappi.get_func_stats().strip_dirs()
data = [(s.name, s.ncall, s.tsub, s.ttot, s.ttot/s.ncall) for s in yappi_stats]
df = pd.DataFrame(data, columns=['name', 'ncall', 'tsub', 'ttot', 'tavg'])
print(df.to_string(index=False))
yappi.get_thread_stats().print_all()
cache_exif_end = time.time()
logger.debug(f"cache_exif: {new_exif}/{len(fileinfos)} cache_aes: {new_aes}/{len(fileinfos)} {round(cache_exif_end - cache_exif_start, 1)} seconds")
def exif_rebuild(maint_wait):
global exif_cache, aes_cache
if opts.image_browser_scan_exif:
logger.debug("Rebuild start")
exif_dirs = wib_db.get_exif_dirs()
exif_cache = {}
aes_cache = {}
for key, value in exif_dirs.items():
if os.path.exists(key):
print(f"Rebuilding {key}")
fileinfos = traverse_all_files(key, [], "", 0)
cache_exif(fileinfos)
logger.debug("Rebuild end")
maint_last_msg = "Rebuild finished"
else:
maint_last_msg = "Exif cache not enabled in settings"
return maint_wait, maint_last_msg
def exif_delete_0(maint_wait):
global exif_cache, aes_cache
if opts.image_browser_scan_exif:
with wib_db.transaction() as cursor:
wib_db.delete_exif_0(cursor)
exif_cache = wib_db.load_exif_data(exif_cache)
aes_cache = wib_db.load_aes_data(aes_cache)
maint_last_msg = "Delete finished"
else:
maint_last_msg = "Exif cache not enabled in settings"
return maint_wait, maint_last_msg
def exif_update_dirs(maint_update_dirs_path_recorder, maint_update_dirs_exif_data, maint_update_dirs_ranking, maint_update_dirs_from, maint_update_dirs_to, maint_wait):
global exif_cache, aes_cache
if maint_update_dirs_from == "":
maint_last_msg = "From is empty"
elif maint_update_dirs_to == "":
maint_last_msg = "To is empty"
else:
maint_update_dirs_from = os.path.realpath(maint_update_dirs_from)
maint_update_dirs_to = os.path.realpath(maint_update_dirs_to)
rows = 0
with wib_db.transaction() as cursor:
if maint_update_dirs_path_recorder:
wib_db.update_path_recorder_mult(cursor, maint_update_dirs_from, maint_update_dirs_to)
rows = rows + cursor.rowcount
if maint_update_dirs_exif_data:
wib_db.update_exif_data_mult(cursor, maint_update_dirs_from, maint_update_dirs_to)
rows = rows + cursor.rowcount
if maint_update_dirs_ranking:
wib_db.update_ranking_mult(cursor, maint_update_dirs_from, maint_update_dirs_to)
rows = rows + cursor.rowcount
if rows == 0:
maint_last_msg = "No rows updated"
else:
maint_last_msg = f"{rows} rows updated. Please reload UI!"
return maint_wait, maint_last_msg
def recreate_hash(maint_wait):
version = str(db_version)
with wib_db.transaction() as cursor:
wib_db.migrate_filehash(cursor, version)
maint_last_msg = "Hashes recreated"
return maint_wait, maint_last_msg
def reapply_ranking(path_recorder, maint_wait):
dirs = {}
for tab in tabs_list:
if os.path.exists(tab.path):
dirs[tab.path] = tab.path
for key in path_recorder:
if os.path.exists(key):
dirs[key] = key
with wib_db.transaction() as cursor:
# Traverse all known dirs, check if missing rankings are due to moved files
for key in dirs.keys():
fileinfos = traverse_all_files(key, [], "", 0)
for (file, _) in fileinfos:
# Is there a ranking for this full filepath
ranking_by_file = wib_db.get_ranking_by_file(cursor, file)
if ranking_by_file is None:
name = os.path.basename(file)
(ranking_by_name, alternate_hash) = wib_db.get_ranking_by_name(cursor, name)
# Is there a ranking only for the filename
if ranking_by_name is not None:
hash = wib_db.get_hash(file)
(alternate_file, alternate_ranking) = ranking_by_name
if alternate_ranking is not None and alternate_hash is not None:
(alternate_hash,) = alternate_hash
# Does the found filename's file have no hash or the same hash?
if alternate_hash is None or hash == alternate_hash:
if os.path.exists(alternate_file):
# Insert ranking as a copy of the found filename's ranking
wib_db.insert_ranking(cursor, file, alternate_ranking, hash)
else:
# Replace ranking of the found filename
wib_db.replace_ranking(cursor, file, alternate_file, hash)
maint_last_msg = "Rankings reapplied"
return maint_wait, maint_last_msg
def restart_debug(maint_wait):
setup_file_handler()
maint_last_msg = "Debug restarted"
return maint_wait, maint_last_msg
def atof(text):
try:
retval = float(text)
except ValueError:
retval = text
return retval
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's implementation in the comments)
float regex comes from https://stackoverflow.com/a/12643073/190597
'''
return [ atof(c) for c in re.split(r'[+-]?([0-9]+(?:[.][0-9]*)?|[.][0-9]+)', text) ]
def open_folder(path):
if os.path.exists(path):
# Code from ui_common.py
if not shared.cmd_opts.hide_ui_dir_config:
if platform.system() == "Windows":
os.startfile(path)
elif platform.system() == "Darwin":
sp.Popen(["open", path])
elif "microsoft-standard-WSL2" in platform.uname().release:
sp.Popen(["wsl-open", path])
else:
sp.Popen(["xdg-open", path])
def check_ext(ext):
found = False
scripts_list = scripts.list_scripts("scripts", ".py")
for scriptfile in scripts_list:
if ext in scriptfile.basedir.lower():
found = True
break
return found
def exif_search(needle, haystack, use_regex):
# Convert both haystack and needle to lowercase for case-insensitive search
haystack = haystack.lower()
needle = needle.lower()
if use_regex:
# Set regex flags for dotall (dot matches newline) and ignore case
flags = re.DOTALL | re.IGNORECASE
pattern = re.compile(needle, flags)
return pattern.search(haystack) is not None
else:
# Function to parse and evaluate the logical expression
def parse_expression(expression):
# Split the expression by 'or' to handle OR logic first
or_parts = expression.split(' or ')
for part in or_parts:
# Split each part by 'and' to handle AND logic
and_parts = part.split(' and ')
# Check if all conditions in the AND part are satisfied
if all(
(subpart[4:] not in haystack) if subpart.startswith('not ')
else (subpart in haystack)
for subpart in and_parts
):
return True
# Return False if none of the OR parts evaluate to True
return False
return parse_expression(needle)
def get_all_images(dir_name, sort_by, sort_order, keyword, tab_base_tag_box, img_path_depth, ranking_filter, ranking_filter_min, ranking_filter_max, aes_filter_min, aes_filter_max, exif_keyword, negative_prompt_search, use_regex):
global current_depth
logger.debug("get_all_images")
current_depth = 0
fileinfos = []
if tab_base_tag_box == "image_browser_tab_all":
for path in path_maps.values():
list1 = fileinfos
list2 = traverse_all_files(os.path.realpath(path), [], tab_base_tag_box, img_path_depth)
tmp = dict(list1)
tmp.update(dict(list2))
fileinfos = list(tmp.items())
else:
fileinfos = traverse_all_files(dir_name, [], tab_base_tag_box, img_path_depth)
keyword = keyword.strip(" ")
if opts.image_browser_scan_exif:
cache_exif(fileinfos)
if len(keyword) != 0:
fileinfos = [x for x in fileinfos if keyword.lower() in x[0].lower()]
filenames = [finfo[0] for finfo in fileinfos]
if opts.image_browser_scan_exif:
with wib_db.transaction() as cursor:
if len(exif_keyword) != 0:
if use_regex:
regex_error = False
try:
test_re = re.compile(exif_keyword, re.DOTALL)
except re.error as e:
regex_error = True
print(f"Regex error: {e}")
if (use_regex and not regex_error) or not use_regex:
if negative_prompt_search == "Yes":
fileinfos = [x for x in fileinfos if exif_search(exif_keyword, exif_cache[x[0]], use_regex)]
else:
result = []
for file_info in fileinfos:
file_name = file_info[0]
file_exif = exif_cache[file_name]
file_exif_lc = file_exif.lower()
start_index = file_exif_lc.find(np)
end_index = file_exif.find("\n", start_index)
if negative_prompt_search == "Only":
start_index = start_index + len(np)
sub_string = file_exif[start_index:end_index].strip()
if exif_search(exif_keyword, sub_string, use_regex):
result.append(file_info)
else:
sub_string = file_exif[start_index:end_index].strip()
file_exif = file_exif.replace(sub_string, "")
if exif_search(exif_keyword, file_exif, use_regex):
result.append(file_info)
fileinfos = result
filenames = [finfo[0] for finfo in fileinfos]
wib_db.fill_work_files(cursor, fileinfos)
if len(aes_filter_min) != 0 or len(aes_filter_max) != 0:
try:
aes_filter_min_num = float(aes_filter_min)
except ValueError:
aes_filter_min_num = sys.float_info.min
try:
aes_filter_max_num = float(aes_filter_max)
except ValueError:
aes_filter_max_num = sys.float_info.max
fileinfos = wib_db.filter_aes(cursor, fileinfos, aes_filter_min_num, aes_filter_max_num)
filenames = [finfo[0] for finfo in fileinfos]
if ranking_filter != "All":
ranking_filter_min_num = 1
ranking_filter_max_num = 5
if ranking_filter == "Min-max":
try:
ranking_filter_min_num = int(ranking_filter_min)
except ValueError:
ranking_filter_min_num = 0
try:
ranking_filter_max_num = int(ranking_filter_max)
except ValueError:
ranking_filter_max_num = 0
if ranking_filter_min_num < 1:
ranking_filter_min_num = 1
if ranking_filter_max_num < 1 or ranking_filter_max_num > 5:
ranking_filter_max_num = 5
fileinfos = wib_db.filter_ranking(cursor, fileinfos, ranking_filter, ranking_filter_min_num, ranking_filter_max_num)
filenames = [finfo[0] for finfo in fileinfos]
if sort_by == "date":
if sort_order == up_symbol:
fileinfos = sorted(fileinfos, key=lambda x: x[1].st_mtime)
else:
fileinfos = sorted(fileinfos, key=lambda x: -x[1].st_mtime)
filenames = [finfo[0] for finfo in fileinfos]
elif sort_by == "path name":
if sort_order == up_symbol:
fileinfos = sorted(fileinfos)
else:
fileinfos = sorted(fileinfos, reverse=True)
filenames = [finfo[0] for finfo in fileinfos]
elif sort_by == "random":
random.shuffle(fileinfos)
filenames = [finfo[0] for finfo in fileinfos]
elif sort_by == "ranking":
finfo_ranked = {}
for fi_info in fileinfos:
finfo_ranked[fi_info[0]], _ = get_ranking(fi_info[0])
if sort_order == up_symbol:
fileinfos = dict(sorted(finfo_ranked.items(), key=lambda x: (x[1], x[0])))
else:
fileinfos = dict(reversed(sorted(finfo_ranked.items(), key=lambda x: (x[1], x[0]))))
filenames = [finfo for finfo in fileinfos]
else:
sort_values = {}
exif_info = dict(exif_cache)
if exif_info:
for k, v in exif_info.items():
match = re.search(r'(?<='+ sort_by + ":" ').*?(?=(,|$))', v, flags=re.DOTALL|re.IGNORECASE)
if match:
sort_values[k] = match.group().strip()
else:
sort_values[k] = "0"
if sort_by == "aesthetic_score" or sort_by == "cfg scale":
sort_float = True
else:
sort_float = False
if sort_order == down_symbol:
if sort_float:
fileinfos = [x for x in fileinfos if sort_values[x[0]] != "0"]
fileinfos.sort(key=lambda x: float(sort_values[x[0]]), reverse=True)
fileinfos = dict(fileinfos)
else:
fileinfos = dict(reversed(sorted(fileinfos, key=lambda x: natural_keys(sort_values[x[0]]))))
else:
if sort_float:
fileinfos = [x for x in fileinfos if sort_values[x[0]] != "0"]
fileinfos.sort(key=lambda x: float(sort_values[x[0]]))
fileinfos = dict(fileinfos)
else:
fileinfos = dict(sorted(fileinfos, key=lambda x: natural_keys(sort_values[x[0]])))
filenames = [finfo for finfo in fileinfos]
else:
filenames = [finfo for finfo in fileinfos]
return filenames
def hash_image_path(image_path):
image_path_hash = hashlib.md5(image_path.encode("utf-8")).hexdigest()
cache_image_path = os.path.join(optimized_cache, image_path_hash + ".jpg")
cache_video_path = os.path.join(optimized_cache, image_path_hash + "_video.jpg")
return cache_image_path, cache_video_path
def extract_video_frame(video_path, time, image_path):
vidcap = cv2.VideoCapture(video_path)
vidcap.set(cv2.CAP_PROP_POS_MSEC, time * 1000) # time in seconds
success, image = vidcap.read()
if success:
cv2.imwrite(image_path, image)
return success
def get_thumbnail(image_video, image_list):
global optimized_cache
logger.debug(f"get_thumbnail with mode {image_video}")
optimized_cache = os.path.join(tempfile.gettempdir(),"optimized")
os.makedirs(optimized_cache,exist_ok=True)
thumbnail_list = []
for image_path in image_list:
if (image_video == "image" and os.path.splitext(image_path)[1] in image_ext_list) or (image_video == "video" and os.path.splitext(image_path)[1] in video_ext_list):
cache_image_path, cache_video_path = hash_image_path(image_path)
if os.path.isfile(cache_image_path):
thumbnail_list.append(cache_image_path)
else:
try:
if image_video == "image":
image = Image.open(image_path)
else:
extract_video_frame(image_path, 1, cache_video_path)
image = Image.open(cache_video_path)
except OSError:
# If PIL cannot open the image, use the original path
thumbnail_list.append(image_path)
continue
width, height = image.size
left = (width - min(width, height)) / 2
top = (height - min(width, height)) / 2
right = (width + min(width, height)) / 2
bottom = (height + min(width, height)) / 2
thumbnail = image.crop((left, top, right, bottom)) if opts.image_browser_thumbnail_crop else ImageOps.pad(image, (max(width, height),max(width, height)), color="#000")
thumbnail.thumbnail((opts.image_browser_thumbnail_size, opts.image_browser_thumbnail_size))
if image_video == "video":
play_button_img = Image.new('RGBA', (100, 100), (0, 0, 0, 0))
play_button_draw = ImageDraw.Draw(play_button_img)
play_button_draw.polygon([(20, 20), (80, 50), (20, 80)], fill='white')
play_button_img = play_button_img.resize((50, 50))
button_for_img = Image.new('RGBA', thumbnail.size, (0, 0, 0, 0))
button_for_img.paste(play_button_img, (thumbnail.width - play_button_img.width, thumbnail.height - play_button_img.height), mask=play_button_img)
thumbnail_play = Image.alpha_composite(thumbnail.convert('RGBA'), button_for_img)
thumbnail.close()
thumbnail = thumbnail_play
if thumbnail.mode != "RGB":
thumbnail = thumbnail.convert("RGB")
try:
thumbnail.save(cache_image_path, "JPEG")
thumbnail_list.append(cache_image_path)
except FileNotFoundError:
# Cannot save cache, use PIL object
thumbnail_list.append(thumbnail)
else:
thumbnail_list.append(image_path)
return thumbnail_list