forked from bmaltais/kohya_ss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon_gui.py
1501 lines (1252 loc) · 58.5 KB
/
common_gui.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
try:
from tkinter import filedialog, Tk
except ImportError:
pass
from easygui import msgbox, ynbox
from typing import Optional
from .custom_logging import setup_logging
import os
import re
import gradio as gr
import sys
import shlex
import json
import math
import shutil
import toml
# Set up logging
log = setup_logging()
folder_symbol = "\U0001f4c2" # 📂
refresh_symbol = "\U0001f504" # 🔄
save_style_symbol = "\U0001f4be" # 💾
document_symbol = "\U0001F4C4" # 📄
scriptdir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
if os.name == "nt":
scriptdir = scriptdir.replace("\\", "/")
# insert sd-scripts path into PYTHONPATH
sys.path.insert(0, os.path.join(scriptdir, "sd-scripts"))
# define a list of substrings to search for v2 base models
V2_BASE_MODELS = [
"stabilityai/stable-diffusion-2-1-base/blob/main/v2-1_512-ema-pruned",
"stabilityai/stable-diffusion-2-1-base",
"stabilityai/stable-diffusion-2-base",
]
# define a list of substrings to search for v_parameterization models
V_PARAMETERIZATION_MODELS = [
"stabilityai/stable-diffusion-2-1/blob/main/v2-1_768-ema-pruned",
"stabilityai/stable-diffusion-2-1",
"stabilityai/stable-diffusion-2",
]
# define a list of substrings to v1.x models
V1_MODELS = [
"CompVis/stable-diffusion-v1-4",
"runwayml/stable-diffusion-v1-5",
]
# define a list of substrings to search for SDXL base models
SDXL_MODELS = [
"stabilityai/stable-diffusion-xl-base-1.0",
"stabilityai/stable-diffusion-xl-refiner-1.0",
]
# define a list of substrings to search for
ALL_PRESET_MODELS = V2_BASE_MODELS + V_PARAMETERIZATION_MODELS + V1_MODELS + SDXL_MODELS
ENV_EXCLUSION = ["COLAB_GPU", "RUNPOD_POD_ID"]
def get_executable_path(executable_name: str = None) -> str:
"""
Retrieve and sanitize the path to an executable in the system's PATH.
Args:
executable_name (str): The name of the executable to find.
Returns:
str: The full, sanitized path to the executable if found, otherwise an empty string.
"""
if executable_name:
executable_path = shutil.which(executable_name)
if executable_path:
# Replace backslashes with forward slashes on Windows
# if os.name == "nt":
# executable_path = executable_path.replace("\\", "/")
return executable_path
else:
return "" # Return empty string if the executable is not found
else:
return "" # Return empty string if no executable name is provided
def calculate_max_train_steps(
total_steps: int,
train_batch_size: int,
gradient_accumulation_steps: int,
epoch: int,
reg_factor: int,
):
return int(
math.ceil(
float(total_steps)
/ int(train_batch_size)
/ int(gradient_accumulation_steps)
* int(epoch)
* int(reg_factor)
)
)
def check_if_model_exist(
output_name: str, output_dir: str, save_model_as: str, headless: bool = False
) -> bool:
"""
Checks if a model with the same name already exists and prompts the user to overwrite it if it does.
Parameters:
output_name (str): The name of the output model.
output_dir (str): The directory where the model is saved.
save_model_as (str): The format to save the model as.
headless (bool, optional): If True, skips the verification and returns False. Defaults to False.
Returns:
bool: True if the model already exists and the user chooses not to overwrite it, otherwise False.
"""
if headless:
log.info(
"Headless mode, skipping verification if model already exist... if model already exist it will be overwritten..."
)
return False
if save_model_as in ["diffusers", "diffusers_safetendors"]:
ckpt_folder = os.path.join(output_dir, output_name)
if os.path.isdir(ckpt_folder):
msg = f"A diffuser model with the same name {ckpt_folder} already exists. Do you want to overwrite it?"
if not ynbox(msg, "Overwrite Existing Model?"):
log.info("Aborting training due to existing model with same name...")
return True
elif save_model_as in ["ckpt", "safetensors"]:
ckpt_file = os.path.join(output_dir, output_name + "." + save_model_as)
if os.path.isfile(ckpt_file):
msg = f"A model with the same file name {ckpt_file} already exists. Do you want to overwrite it?"
if not ynbox(msg, "Overwrite Existing Model?"):
log.info("Aborting training due to existing model with same name...")
return True
else:
log.info(
'Can\'t verify if existing model exist when save model is set as "same as source model", continuing to train model...'
)
return False
return False
def output_message(msg: str = "", title: str = "", headless: bool = False) -> None:
"""
Outputs a message to the user, either in a message box or in the log.
Parameters:
msg (str, optional): The message to be displayed. Defaults to an empty string.
title (str, optional): The title of the message box. Defaults to an empty string.
headless (bool, optional): If True, the message is logged instead of displayed in a message box. Defaults to False.
Returns:
None
"""
if headless:
log.info(msg)
else:
msgbox(msg=msg, title=title)
def create_refresh_button(refresh_component, refresh_method, refreshed_args, elem_id):
"""
Creates a refresh button that can be used to update UI components.
Parameters:
refresh_component (list or object): The UI component(s) to be refreshed.
refresh_method (callable): The method to be called when the button is clicked.
refreshed_args (dict or callable): The arguments to be passed to the refresh method.
elem_id (str): The ID of the button element.
Returns:
gr.Button: The configured refresh button.
"""
# Converts refresh_component into a list for uniform processing. If it's already a list, keep it the same.
refresh_components = (
refresh_component
if isinstance(refresh_component, list)
else [refresh_component]
)
# Initialize label to None. This will store the label of the first component with a non-None label, if any.
label = None
# Iterate over each component to find the first non-None label and assign it to 'label'.
for comp in refresh_components:
label = getattr(comp, "label", None)
if label is not None:
break
# Define the refresh function that will be triggered upon clicking the refresh button.
def refresh():
# Invoke the refresh_method, which is intended to perform the refresh operation.
refresh_method()
# Determine the arguments for the refresh: call refreshed_args if it's callable, otherwise use it directly.
args = refreshed_args() if callable(refreshed_args) else refreshed_args
# For each key-value pair in args, update the corresponding properties of each component.
for k, v in args.items():
for comp in refresh_components:
setattr(comp, k, v)
# Use gr.update to refresh the UI components. If multiple components are present, update each; else, update only the first.
return (
[gr.Dropdown(**(args or {})) for _ in refresh_components]
if len(refresh_components) > 1
else gr.Dropdown(**(args or {}))
)
# Create a refresh button with the specified label (via refresh_symbol), ID, and classes.
# 'refresh_symbol' should be defined outside this function or passed as an argument, representing the button's label or icon.
refresh_button = gr.Button(
value=refresh_symbol, elem_id=elem_id, elem_classes=["tool"]
)
# Configure the button to invoke the refresh function.
refresh_button.click(fn=refresh, inputs=[], outputs=refresh_components)
# Return the configured refresh button to be used in the UI.
return refresh_button
def list_dirs(path):
if path is None or path == "None" or path == "":
return
if not os.path.exists(path):
path = os.path.dirname(path)
if not os.path.exists(path):
return
if not os.path.isdir(path):
path = os.path.dirname(path)
def natural_sort_key(s, regex=re.compile("([0-9]+)")):
return [
int(text) if text.isdigit() else text.lower() for text in regex.split(s)
]
subdirs = [
(item, os.path.join(path, item))
for item in os.listdir(path)
if os.path.isdir(os.path.join(path, item))
]
subdirs = [
filename
for item, filename in subdirs
if item[0] != "." and item not in ["__pycache__"]
]
subdirs = sorted(subdirs, key=natural_sort_key)
if os.path.dirname(path) != "":
dirs = [os.path.dirname(path), path] + subdirs
else:
dirs = [path] + subdirs
if os.sep == "\\":
dirs = [d.replace("\\", "/") for d in dirs]
for d in dirs:
yield d
def list_files(path, exts=None, all=False):
if path is None or path == "None" or path == "":
return
if not os.path.exists(path):
path = os.path.dirname(path)
if not os.path.exists(path):
return
if not os.path.isdir(path):
path = os.path.dirname(path)
files = [
(item, os.path.join(path, item))
for item in os.listdir(path)
if all or os.path.isfile(os.path.join(path, item))
]
files = [
filename
for item, filename in files
if item[0] != "." and item not in ["__pycache__"]
]
exts = set(exts) if exts is not None else None
def natural_sort_key(s, regex=re.compile("([0-9]+)")):
return [
int(text) if text.isdigit() else text.lower() for text in regex.split(s)
]
files = sorted(files, key=natural_sort_key)
if os.path.dirname(path) != "":
files = [os.path.dirname(path), path] + files
else:
files = [path] + files
if os.sep == "\\":
files = [d.replace("\\", "/") for d in files]
for filename in files:
if exts is not None:
if os.path.isdir(filename):
yield filename
_, ext = os.path.splitext(filename)
if ext.lower() not in exts:
continue
yield filename
else:
yield filename
def update_my_data(my_data):
# Update the optimizer based on the use_8bit_adam flag
use_8bit_adam = my_data.get("use_8bit_adam", False)
my_data.setdefault("optimizer", "AdamW8bit" if use_8bit_adam else "AdamW")
# Update model_list to custom if empty or pretrained_model_name_or_path is not a preset model
model_list = my_data.get("model_list", [])
pretrained_model_name_or_path = my_data.get("pretrained_model_name_or_path", "")
if not model_list or pretrained_model_name_or_path not in ALL_PRESET_MODELS:
my_data["model_list"] = "custom"
# Convert values to int if they are strings
for key in [
"adaptive_noise_scale",
"clip_skip",
"epoch",
"gradient_accumulation_steps",
"keep_tokens",
"lr_warmup",
"max_data_loader_n_workers",
"max_train_epochs",
"save_every_n_epochs",
"seed",
]:
value = my_data.get(key)
if value is not None:
try:
my_data[key] = int(value)
except ValueError:
# Handle the case where the string is not a valid float
my_data[key] = int(0)
# Convert values to int if they are strings
for key in ["lr_scheduler_num_cycles"]:
value = my_data.get(key)
if value is not None:
try:
my_data[key] = int(value)
except ValueError:
# Handle the case where the string is not a valid float
my_data[key] = int(1)
for key in [
"max_train_steps",
]:
value = my_data.get(key)
if value is not None:
try:
my_data[key] = int(value)
except ValueError:
# Handle the case where the string is not a valid float
my_data[key] = int(0)
# Convert values to int if they are strings
for key in ["max_token_length"]:
value = my_data.get(key)
if value is not None:
try:
my_data[key] = int(value)
except ValueError:
# Handle the case where the string is not a valid float
my_data[key] = int(75)
# Convert values to float if they are strings, correctly handling float representations
for key in ["noise_offset", "learning_rate", "text_encoder_lr", "unet_lr"]:
value = my_data.get(key)
if value is not None:
try:
my_data[key] = float(value)
except ValueError:
# Handle the case where the string is not a valid float
my_data[key] = float(0.0)
# Convert values to float if they are strings, correctly handling float representations
for key in ["lr_scheduler_power"]:
value = my_data.get(key)
if value is not None:
try:
my_data[key] = float(value)
except ValueError:
# Handle the case where the string is not a valid float
my_data[key] = float(1.0)
# Update LoRA_type if it is set to LoCon
if my_data.get("LoRA_type", "Standard") == "LoCon":
my_data["LoRA_type"] = "LyCORIS/LoCon"
# Update model save choices due to changes for LoRA and TI training
if "save_model_as" in my_data:
if (
my_data.get("LoRA_type") or my_data.get("num_vectors_per_token")
) and my_data.get("save_model_as") not in ["safetensors", "ckpt"]:
message = "Updating save_model_as to safetensors because the current value in the config file is no longer applicable to {}"
if my_data.get("LoRA_type"):
log.info(message.format("LoRA"))
if my_data.get("num_vectors_per_token"):
log.info(message.format("TI"))
my_data["save_model_as"] = "safetensors"
# Update xformers if it is set to True and is a boolean
xformers_value = my_data.get("xformers", None)
if isinstance(xformers_value, bool):
if xformers_value:
my_data["xformers"] = "xformers"
else:
my_data["xformers"] = "none"
# Convert use_wandb to log_with="wandb" if it is set to True
for key in ["use_wandb"]:
value = my_data.get(key)
if value is not None:
try:
if value == "True":
my_data["log_with"] = "wandb"
except ValueError:
# Handle the case where the string is not a valid float
pass
my_data.pop(key, None)
# Replace the lora_network_weights key with network_weights keeping the original value
for key in ["lora_network_weights"]:
value = my_data.get(key) # Get original value
if value is not None: # Check if the key exists in the dictionary
my_data["network_weights"] = value
my_data.pop(key, None)
return my_data
def get_dir_and_file(file_path):
dir_path, file_name = os.path.split(file_path)
return (dir_path, file_name)
def get_file_path(
file_path="", default_extension=".json", extension_name="Config files"
):
"""
Opens a file dialog to select a file, allowing the user to navigate and choose a file with a specific extension.
If no file is selected, returns the initially provided file path or an empty string if not provided.
This function is conditioned to skip the file dialog on macOS or if specific environment variables are present,
indicating a possible automated environment where a dialog cannot be displayed.
Parameters:
- file_path (str): The initial file path or an empty string by default. Used as the fallback if no file is selected.
- default_extension (str): The default file extension (e.g., ".json") for the file dialog.
- extension_name (str): The display name for the type of files being selected (e.g., "Config files").
Returns:
- str: The path of the file selected by the user, or the initial `file_path` if no selection is made.
Raises:
- TypeError: If `file_path`, `default_extension`, or `extension_name` are not strings.
Note:
- The function checks the `ENV_EXCLUSION` list against environment variables to determine if the file dialog should be skipped, aiming to prevent its appearance during automated operations.
- The dialog will also be skipped on macOS (`sys.platform != "darwin"`) as a specific behavior adjustment.
"""
# Validate parameter types
if not isinstance(file_path, str):
raise TypeError("file_path must be a string")
if not isinstance(default_extension, str):
raise TypeError("default_extension must be a string")
if not isinstance(extension_name, str):
raise TypeError("extension_name must be a string")
# Environment and platform check to decide on showing the file dialog
if not any(var in os.environ for var in ENV_EXCLUSION) and sys.platform != "darwin":
current_file_path = file_path # Backup in case no file is selected
initial_dir, initial_file = get_dir_and_file(
file_path
) # Decompose file path for dialog setup
# Initialize a hidden Tkinter window for the file dialog
root = Tk()
root.wm_attributes("-topmost", 1) # Ensure the dialog is topmost
root.withdraw() # Hide the root window to show only the dialog
# Open the file dialog and capture the selected file path
file_path = filedialog.askopenfilename(
filetypes=((extension_name, f"*{default_extension}"), ("All files", "*.*")),
defaultextension=default_extension,
initialfile=initial_file,
initialdir=initial_dir,
)
root.destroy() # Cleanup by destroying the Tkinter root window
# Fallback to the initial path if no selection is made
if not file_path:
file_path = current_file_path
# Return the selected or fallback file path
return file_path
def get_any_file_path(file_path: str = "") -> str:
"""
Opens a file dialog to select any file, allowing the user to navigate and choose a file.
If no file is selected, returns the initially provided file path or an empty string if not provided.
This function is conditioned to skip the file dialog on macOS or if specific environment variables are present,
indicating a possible automated environment where a dialog cannot be displayed.
Parameters:
- file_path (str): The initial file path or an empty string by default. Used as the fallback if no file is selected.
Returns:
- str: The path of the file selected by the user, or the initial `file_path` if no selection is made.
Raises:
- TypeError: If `file_path` is not a string.
- EnvironmentError: If there's an issue accessing environment variables.
- RuntimeError: If there's an issue initializing the file dialog.
Note:
- The function checks the `ENV_EXCLUSION` list against environment variables to determine if the file dialog should be skipped, aiming to prevent its appearance during automated operations.
- The dialog will also be skipped on macOS (`sys.platform != "darwin"`) as a specific behavior adjustment.
"""
# Validate parameter type
if not isinstance(file_path, str):
raise TypeError("file_path must be a string")
try:
# Check for environment variable conditions
if (
not any(var in os.environ for var in ENV_EXCLUSION)
and sys.platform != "darwin"
):
current_file_path: str = file_path
initial_dir, initial_file = get_dir_and_file(file_path)
# Initialize a hidden Tkinter window for the file dialog
root = Tk()
root.wm_attributes("-topmost", 1)
root.withdraw()
try:
# Open the file dialog and capture the selected file path
file_path = filedialog.askopenfilename(
initialdir=initial_dir,
initialfile=initial_file,
)
except Exception as e:
raise RuntimeError(f"Failed to open file dialog: {e}")
finally:
root.destroy()
# Fallback to the initial path if no selection is made
if not file_path:
file_path = current_file_path
except KeyError as e:
raise EnvironmentError(f"Failed to access environment variables: {e}")
# Return the selected or fallback file path
return file_path
def get_folder_path(folder_path: str = "") -> str:
"""
Opens a folder dialog to select a folder, allowing the user to navigate and choose a folder.
If no folder is selected, returns the initially provided folder path or an empty string if not provided.
This function is conditioned to skip the folder dialog on macOS or if specific environment variables are present,
indicating a possible automated environment where a dialog cannot be displayed.
Parameters:
- folder_path (str): The initial folder path or an empty string by default. Used as the fallback if no folder is selected.
Returns:
- str: The path of the folder selected by the user, or the initial `folder_path` if no selection is made.
Raises:
- TypeError: If `folder_path` is not a string.
- EnvironmentError: If there's an issue accessing environment variables.
- RuntimeError: If there's an issue initializing the folder dialog.
Note:
- The function checks the `ENV_EXCLUSION` list against environment variables to determine if the folder dialog should be skipped, aiming to prevent its appearance during automated operations.
- The dialog will also be skipped on macOS (`sys.platform != "darwin"`) as a specific behavior adjustment.
"""
# Validate parameter type
if not isinstance(folder_path, str):
raise TypeError("folder_path must be a string")
try:
# Check for environment variable conditions
if any(var in os.environ for var in ENV_EXCLUSION) or sys.platform == "darwin":
return folder_path or ""
root = Tk()
root.withdraw()
root.wm_attributes("-topmost", 1)
selected_folder = filedialog.askdirectory(initialdir=folder_path or ".")
root.destroy()
return selected_folder or folder_path
except Exception as e:
raise RuntimeError(f"Error initializing folder dialog: {e}") from e
def get_saveasfile_path(
file_path: str = "",
defaultextension: str = ".json",
extension_name: str = "Config files",
) -> str:
# Check if the current environment is not macOS and if the environment variables do not match the exclusion list
if not any(var in os.environ for var in ENV_EXCLUSION) and sys.platform != "darwin":
# Store the initial file path to use as a fallback in case no file is selected
current_file_path = file_path
# Logging the current file path for debugging purposes; helps in tracking the flow of file selection
# log.info(f'current file path: {current_file_path}')
# Split the file path into directory and file name for setting the file dialog start location and filename
initial_dir, initial_file = get_dir_and_file(file_path)
# Initialize a hidden Tkinter window to act as the parent for the file dialog, ensuring it appears on top
root = Tk()
root.wm_attributes("-topmost", 1)
root.withdraw()
save_file_path = filedialog.asksaveasfile(
filetypes=(
(f"{extension_name}", f"{defaultextension}"),
("All files", "*"),
),
defaultextension=defaultextension,
initialdir=initial_dir,
initialfile=initial_file,
)
# Close the Tkinter root window to clean up the UI
root.destroy()
# Logging the save file path for auditing purposes; useful in confirming the user's file choice
# log.info(save_file_path)
# Default to the current file path if no file is selected, ensuring there's always a valid file path
if save_file_path == None:
file_path = current_file_path
else:
# Log the selected file name for transparency and tracking user actions
# log.info(save_file_path.name)
# Update the file path with the user-selected file name, facilitating the save operation
file_path = save_file_path.name
# Log the final file path for verification, ensuring the intended file is being used
# log.info(file_path)
# Return the final file path, either the user-selected file or the fallback path
return file_path
def get_saveasfilename_path(
file_path: str = "",
extensions: str = "*",
extension_name: str = "Config files",
) -> str:
"""
Opens a file dialog to select a file name for saving, allowing the user to specify a file name and location.
If no file is selected, returns the initially provided file path or an empty string if not provided.
This function is conditioned to skip the file dialog on macOS or if specific environment variables are present,
indicating a possible automated environment where a dialog cannot be displayed.
Parameters:
- file_path (str): The initial file path or an empty string by default. Used as the fallback if no file is selected.
- extensions (str): The file extensions to filter the file dialog by. Defaults to "*" for all files.
- extension_name (str): The name to display for the file extensions in the file dialog. Defaults to "Config files".
Returns:
- str: The path of the file selected by the user, or the initial `file_path` if no selection is made.
Raises:
- TypeError: If `file_path` is not a string.
- EnvironmentError: If there's an issue accessing environment variables.
- RuntimeError: If there's an issue initializing the file dialog.
Note:
- The function checks the `ENV_EXCLUSION` list against environment variables to determine if the file dialog should be skipped, aiming to prevent its appearance during automated operations.
- The dialog will also be skipped on macOS (`sys.platform == "darwin"`) as a specific behavior adjustment.
"""
# Check if the current environment is not macOS and if the environment variables do not match the exclusion list
if not any(var in os.environ for var in ENV_EXCLUSION) and sys.platform != "darwin":
# Store the initial file path to use as a fallback in case no file is selected
current_file_path: str = file_path
# log.info(f'current file path: {current_file_path}')
# Split the file path into directory and file name for setting the file dialog start location and filename
initial_dir, initial_file = get_dir_and_file(file_path)
# Initialize a hidden Tkinter window to act as the parent for the file dialog, ensuring it appears on top
root = Tk()
root.wm_attributes("-topmost", 1)
root.withdraw()
# Open the file dialog and capture the selected file path
save_file_path = filedialog.asksaveasfilename(
filetypes=(
(f"{extension_name}", f"{extensions}"),
("All files", "*"),
),
defaultextension=extensions,
initialdir=initial_dir,
initialfile=initial_file,
)
# Close the Tkinter root window to clean up the UI
root.destroy()
# Default to the current file path if no file is selected, ensuring there's always a valid file path
if save_file_path == "":
file_path = current_file_path
else:
# Logging the save file path for auditing purposes; useful in confirming the user's file choice
# log.info(save_file_path)
# Update the file path with the user-selected file name, facilitating the save operation
file_path = save_file_path
# Return the final file path, either the user-selected file or the fallback path
return file_path
def add_pre_postfix(
folder: str = "",
prefix: str = "",
postfix: str = "",
caption_file_ext: str = ".caption",
recursive: bool = False,
) -> None:
"""
Add prefix and/or postfix to the content of caption files within a folder.
If no caption files are found, create one with the requested prefix and/or postfix.
Args:
folder (str): Path to the folder containing caption files.
prefix (str, optional): Prefix to add to the content of the caption files.
postfix (str, optional): Postfix to add to the content of the caption files.
caption_file_ext (str, optional): Extension of the caption files.
recursive (bool, optional): Whether to search for caption files recursively.
"""
# If neither prefix nor postfix is provided, return early
if prefix == "" and postfix == "":
return
# Define the image file extensions to filter
image_extensions = (".jpg", ".jpeg", ".png", ".webp")
# If recursive is true, list all image files in the folder and its subfolders
if recursive:
image_files = []
for root, dirs, files in os.walk(folder):
for file in files:
if file.lower().endswith(image_extensions):
image_files.append(os.path.join(root, file))
else:
# List all image files in the folder
image_files = [
f for f in os.listdir(folder) if f.lower().endswith(image_extensions)
]
# Iterate over the list of image files
for image_file in image_files:
# Construct the caption file name by appending the caption file extension to the image file name
caption_file_name = f"{os.path.splitext(image_file)[0]}{caption_file_ext}"
# Construct the full path to the caption file
caption_file_path = os.path.join(folder, caption_file_name)
# Check if the caption file does not exist
if not os.path.exists(caption_file_path):
# Create a new caption file with the specified prefix and/or postfix
try:
with open(caption_file_path, "w", encoding="utf-8") as f:
# Determine the separator based on whether both prefix and postfix are provided
separator = " " if prefix and postfix else ""
f.write(f"{prefix}{separator}{postfix}")
except Exception as e:
log.error(f"Error writing to file {caption_file_path}: {e}")
else:
# Open the existing caption file for reading and writing
try:
with open(caption_file_path, "r+", encoding="utf-8") as f:
# Read the content of the caption file, stripping any trailing whitespace
content = f.read().rstrip()
# Move the file pointer to the beginning of the file
f.seek(0, 0)
# Determine the separator based on whether only prefix is provided
prefix_separator = " " if prefix else ""
# Determine the separator based on whether only postfix is provided
postfix_separator = " " if postfix else ""
# Write the updated content to the caption file, adding prefix and/or postfix
f.write(
f"{prefix}{prefix_separator}{content}{postfix_separator}{postfix}"
)
except Exception as e:
log.error(f"Error writing to file {caption_file_path}: {e}")
def has_ext_files(folder_path: str, file_extension: str) -> bool:
"""
Determines whether any files within a specified folder have a given file extension.
This function iterates through each file in the specified folder and checks if
its extension matches the provided file_extension argument. The search is case-sensitive
and expects file_extension to include the dot ('.') if applicable (e.g., '.txt').
Args:
folder_path (str): The absolute or relative path to the folder to search within.
file_extension (str): The file extension to search for, including the dot ('.') if applicable.
Returns:
bool: True if at least one file with the specified extension is found, False otherwise.
"""
# Iterate directly over files in the specified folder path
for file in os.listdir(folder_path):
# Return True at the first occurrence of a file with the specified extension
if file.endswith(file_extension):
return True
# If no file with the specified extension is found, return False
return False
def find_replace(
folder_path: str = "",
caption_file_ext: str = ".caption",
search_text: str = "",
replace_text: str = "",
) -> None:
"""
Efficiently finds and replaces specified text across all caption files in a given folder.
This function iterates through each caption file matching the specified extension within the given folder path, replacing all occurrences of the search text with the replacement text. It ensures that the operation only proceeds if the search text is provided and there are caption files to process.
Args:
folder_path (str, optional): The directory path where caption files are located. Defaults to an empty string, which implies the current directory.
caption_file_ext (str, optional): The file extension for caption files. Defaults to ".caption".
search_text (str, optional): The text to search for within the caption files. Defaults to an empty string.
replace_text (str, optional): The text to use as a replacement. Defaults to an empty string.
"""
# Log the start of the caption find/replace operation
log.info("Running caption find/replace")
# Validate the presence of caption files and the search text
if not search_text or not has_ext_files(folder_path, caption_file_ext):
# Display a message box indicating no files were found
msgbox(
f"No files with extension {caption_file_ext} were found in {folder_path}..."
)
log.warning(
"No files with extension {caption_file_ext} were found in {folder_path}..."
)
# Exit the function early
return
# Check if the caption file extension is one of the supported extensions
if caption_file_ext not in [".caption", ".txt", ".txt2", ".cap"]:
log.error(
f"Unsupported file extension {caption_file_ext} for caption files. Please use .caption, .txt, .txt2, or .cap."
)
# Exit the function early
return
# Check if the folder path exists
if not os.path.exists(folder_path):
log.error(f"The provided path '{folder_path}' is not a valid folder.")
return
# List all caption files in the folder
try:
caption_files = [
f for f in os.listdir(folder_path) if f.endswith(caption_file_ext)
]
except Exception as e:
log.error(f"Error accessing folder {folder_path}: {e}")
return
# Iterate over the list of caption files
for caption_file in caption_files:
# Construct the full path for each caption file
file_path = os.path.join(folder_path, caption_file)
# Read and replace text
try:
with open(file_path, "r", errors="ignore", encoding="utf-8") as f:
content = f.read().replace(search_text, replace_text)
# Write the updated content back to the file
with open(file_path, "w", encoding="utf-8") as f:
f.write(content)
except Exception as e:
log.error(f"Error processing file {file_path}: {e}")
def color_aug_changed(color_aug):
"""
Handles the change in color augmentation checkbox.
This function is called when the color augmentation checkbox is toggled.
If color augmentation is enabled, it disables the cache latent checkbox
and returns a new checkbox with the value set to False and interactive set to False.
If color augmentation is disabled, it returns a new checkbox with interactive set to True.
Args:
color_aug (bool): The new state of the color augmentation checkbox.
Returns:
gr.Checkbox: A new checkbox with the appropriate settings based on the color augmentation state.
"""
# If color augmentation is enabled, disable cache latent and return a new checkbox
if color_aug:
msgbox(
'Disabling "Cache latent" because "Color augmentation" has been selected...'
)
return gr.Checkbox(value=False, interactive=False)
# If color augmentation is disabled, return a new checkbox with interactive set to True
else:
return gr.Checkbox(interactive=True)
def set_pretrained_model_name_or_path_input(
pretrained_model_name_or_path, refresh_method=None
):
"""
Sets the pretrained model name or path input based on the model type.
This function checks the type of the pretrained model and sets the appropriate
parameters for the model. It also handles the case where the model list is
set to 'custom' and a refresh method is provided.
Args:
pretrained_model_name_or_path (str): The name or path of the pretrained model.
refresh_method (callable, optional): A function to refresh the model list.
Returns:
tuple: A tuple containing the Dropdown widget, v2 checkbox, v_parameterization checkbox,
and sdxl checkbox.
"""
# Check if the given pretrained_model_name_or_path is in the list of SDXL models
if pretrained_model_name_or_path in SDXL_MODELS:
log.info("SDXL model selected. Setting sdxl parameters")
v2 = gr.Checkbox(value=False, visible=False)
v_parameterization = gr.Checkbox(value=False, visible=False)
sdxl = gr.Checkbox(value=True, visible=False)
return (
gr.Dropdown(),
v2,
v_parameterization,
sdxl,
)
# Check if the given pretrained_model_name_or_path is in the list of V2 base models
if pretrained_model_name_or_path in V2_BASE_MODELS:
log.info("SD v2 base model selected. Setting --v2 parameter")
v2 = gr.Checkbox(value=True, visible=False)
v_parameterization = gr.Checkbox(value=False, visible=False)
sdxl = gr.Checkbox(value=False, visible=False)
return (
gr.Dropdown(),
v2,
v_parameterization,
sdxl,
)
# Check if the given pretrained_model_name_or_path is in the list of V parameterization models
if pretrained_model_name_or_path in V_PARAMETERIZATION_MODELS:
log.info(
"SD v2 model selected. Setting --v2 and --v_parameterization parameters"
)
v2 = gr.Checkbox(value=True, visible=False)
v_parameterization = gr.Checkbox(value=True, visible=False)
sdxl = gr.Checkbox(value=False, visible=False)
return (
gr.Dropdown(),
v2,
v_parameterization,
sdxl,
)
# Check if the given pretrained_model_name_or_path is in the list of V1 models
if pretrained_model_name_or_path in V1_MODELS:
log.info(f"{pretrained_model_name_or_path} model selected.")
v2 = gr.Checkbox(value=False, visible=False)
v_parameterization = gr.Checkbox(value=False, visible=False)
sdxl = gr.Checkbox(value=False, visible=False)
return (
gr.Dropdown(),