-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfix_dpg_ui_layout.py
More file actions
executable file
·1727 lines (1399 loc) · 59.1 KB
/
fix_dpg_ui_layout.py
File metadata and controls
executable file
·1727 lines (1399 loc) · 59.1 KB
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
#!/usr/bin/env python3
"""
Fix UI layout issues in the DearPyGui version of OneTrainer
This script corrects tab ordering, missing fields, and layout issues in the DPG UI.
"""
import os
import sys
import json
# Add the current directory to the path
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
sys.path.insert(0, current_dir)
def fix_app_py():
"""Fix tab ordering in app.py"""
print("Fixing tab order in app.py...")
app_py_path = os.path.join(current_dir, "dpg_ui", "app.py")
if not os.path.exists(app_py_path):
print(f"Error: {app_py_path} not found")
return False
# Create a backup
backup_path = f"{app_py_path}.bak"
if not os.path.exists(backup_path):
with open(app_py_path, "r") as src:
with open(backup_path, "w") as dst:
dst.write(src.read())
print(f"Created backup: {backup_path}")
with open(app_py_path, "r") as f:
content = f.read()
# Fix tab order in the import_tabs method
old_tab_modules = """ tab_modules = [
("training_tab", "TrainingTab"),
("model_tab", "ModelTab"),
("lora_tab", "LoraTab"),
("concept_tab", "ConceptTab"),
("sampling_tab", "SamplingTab"),
("cloud_tab", "CloudTab")
]"""
new_tab_modules = """ tab_modules = [
("model_tab", "ModelTab"),
("training_tab", "TrainingTab"),
("lora_tab", "LoraTab"),
("concept_tab", "ConceptTab"),
("sampling_tab", "SamplingTab"),
("additional_embeddings_tab", "AdditionalEmbeddingsTab"),
("cloud_tab", "CloudTab")
]"""
content = content.replace(old_tab_modules, new_tab_modules)
# Fix tab order in the create_tabs method
old_tab_config = """ tab_config = [
("training", "Training", "training_tab"),
("model", "Model", "model_tab"),
("lora", "LoRA", "lora_tab"),
("concept", "Concept", "concept_tab"),
("sampling", "Sampling", "sampling_tab"),
("cloud", "Cloud", "cloud_tab")
]"""
new_tab_config = """ tab_config = [
("model", "Model", "model_tab"),
("training", "Training", "training_tab"),
("lora", "LoRA", "lora_tab"),
("concept", "Concept", "concept_tab"),
("sampling", "Sampling", "sampling_tab"),
("additional_embeddings", "Additional Embeddings", "additional_embeddings_tab"),
("cloud", "Cloud", "cloud_tab")
]"""
content = content.replace(old_tab_config, new_tab_config)
# Change the default selected tab
content = content.replace('self.window.select_tab("training")', 'self.window.select_tab("model")')
# Write the changes back
with open(app_py_path, "w") as f:
f.write(content)
return True
def fix_top_bar():
"""Fix top bar issues"""
print("Fixing top bar in top_bar.py...")
top_bar_path = os.path.join(current_dir, "dpg_ui", "tabs", "top_bar.py")
if not os.path.exists(top_bar_path):
print(f"Error: {top_bar_path} not found")
# Try adapter path
top_bar_path = os.path.join(current_dir, "dpg_ui", "adapters", "top_bar.py")
if not os.path.exists(top_bar_path):
print(f"Error: {top_bar_path} not found")
return False
# Create a backup
backup_path = f"{top_bar_path}.bak"
if not os.path.exists(backup_path):
with open(top_bar_path, "r") as src:
with open(backup_path, "w") as dst:
dst.write(src.read())
print(f"Created backup: {backup_path}")
with open(top_bar_path, "r") as f:
content = f.read()
# Enhance the top bar implementation
if "create_preset_selector" not in content:
improved_content = """#!/usr/bin/env python3
\"\"\"
Top bar implementation for the Dear PyGui version of OneTrainer
This module provides the top bar UI component for the OneTrainer DPG UI.
\"\"\"
import os
import sys
import dearpygui.dearpygui as dpg
import json
from typing import Any, Dict, Optional, List, Callable
# Add the parent directory to sys.path to allow importing from the modules package
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))
if parent_dir not in sys.path:
sys.path.insert(0, parent_dir)
from modules.util.enum.ModelType import ModelType
from modules.util.enum.TrainingMethod import TrainingMethod
from modules.util import path_util
# Import components
from dpg_ui.components.preset_selector import PresetSelector
class TopBar:
\"\"\"
Top bar implementation for the OneTrainer UI
This class provides the top bar UI component that contains the logo,
version information, and main actions.
\"\"\"
def __init__(self, parent: int, state_manager: Any):
\"\"\"
Initialize the top bar
Args:
parent: Parent container ID
state_manager: State manager instance
\"\"\"
self.parent = parent
self.state_manager = state_manager
self.presets_dir = "training_presets"
self.presets = []
self.preset_selector = None
# Create the UI
self.create_ui()
def create_ui(self):
\"\"\"Create the top bar UI\"\"\"
with dpg.group(parent=self.parent, horizontal=True):
# Logo and title
self.create_logo_section()
# Add spacer
dpg.add_spacer(width=20)
# Model type selector
self.create_model_type_selector()
# Add spacer
dpg.add_spacer(width=20)
# Training method selector
self.create_training_method_selector()
# Add spacer
dpg.add_spacer(width=20)
# Preset selector
self.create_preset_selector()
# Add spacer
dpg.add_spacer(width=20)
# Action buttons
self.create_action_buttons()
# Add right-aligned version info
with dpg.group(horizontal=True):
dpg.add_spacer(width=20)
dpg.add_text("DPG Edition (LyCORIS Enabled)", tag="version_info")
def create_logo_section(self):
\"\"\"Create the logo and title\"\"\"
# Logo would go here if available
logo_path = os.path.join("resources", "icons", "icon.png")
if os.path.exists(logo_path):
try:
width, height, channels, data = dpg.load_image(logo_path)
texture_id = f"logo_texture_{dpg.generate_uuid()}"
dpg.add_static_texture(width, height, data, tag=texture_id)
dpg.add_image(texture_id, width=40, height=40)
except Exception as e:
print(f"Error loading logo: {e}")
# Fallback to a colored rectangle
with dpg.drawlist(width=40, height=40):
dpg.draw_rectangle((0, 0), (40, 40), color=(41, 83, 154, 255),
fill=(41, 83, 154, 255))
else:
# Use a colored rectangle instead
with dpg.drawlist(width=40, height=40):
dpg.draw_rectangle((0, 0), (40, 40), color=(41, 83, 154, 255),
fill=(41, 83, 154, 255))
# Add title text
dpg.add_text("OneTrainer", color=(255, 255, 0), tag="app_title")
def create_model_type_selector(self):
\"\"\"Create the model type selector\"\"\"
# Add model type label
dpg.add_text("Model Type:", color=(220, 220, 220))
# Get model types
model_types = []
for model_type in ModelType:
model_types.append(model_type.name)
# Add selector
self.model_selector = dpg.add_combo(
items=model_types,
default_value="STABLE_DIFFUSION_15",
callback=self.on_model_change,
width=200
)
def create_training_method_selector(self):
\"\"\"Create the training method selector\"\"\"
# Add training method label
dpg.add_text("Training Method:", color=(220, 220, 220))
# Get training methods
training_methods = []
for method in TrainingMethod:
training_methods.append(method.name)
# Add selector
self.training_method_selector = dpg.add_combo(
items=training_methods,
default_value="LORA",
callback=self.on_training_method_change,
width=150
)
def create_preset_selector(self):
\"\"\"Create the preset selector\"\"\"
# Add preset selector label
dpg.add_text("Preset:", color=(220, 220, 220))
# Load presets
with dpg.group(horizontal=True):
self.preset_combo = dpg.add_combo(
items=self.get_preset_names(),
default_value="-- Select Preset --",
callback=self.on_preset_change,
width=200
)
# Add load button
load_button = dpg.add_button(
label="Load",
callback=self.on_load_preset,
width=60
)
# Add save button
save_button = dpg.add_button(
label="Save",
callback=self.on_save_preset,
width=60
)
def create_action_buttons(self):
\"\"\"Create action buttons\"\"\"
# Load config button
load_button = dpg.add_button(
label="Load Config",
callback=self.on_load_config,
width=100
)
# Save config button
save_button = dpg.add_button(
label="Save Config",
callback=self.on_save_config,
width=100
)
def get_preset_names(self) -> List[str]:
\"\"\"Get the list of available preset names\"\"\"
self.presets = ["-- Select Preset --"]
# Check if presets directory exists
if not os.path.exists(self.presets_dir):
try:
os.makedirs(self.presets_dir)
except Exception as e:
print(f"Error creating presets directory: {e}")
return self.presets
# Load presets from directory
try:
for file in os.listdir(self.presets_dir):
if file.endswith(".json"):
# Remove .json extension and add to list
preset_name = os.path.splitext(file)[0]
self.presets.append(preset_name)
except Exception as e:
print(f"Error loading presets: {e}")
return self.presets
def on_model_change(self, sender, app_data):
\"\"\"
Handle model type change
Args:
sender: Sender ID
app_data: Selected model type name
\"\"\"
# Update status
dpg.set_value("app_title", f"OneTrainer - {app_data}")
# Update state manager if available
if hasattr(self.state_manager, "set_state"):
try:
from modules.util.enum.ModelType import ModelType
model_type = ModelType[app_data]
self.state_manager.set_state("model_type", model_type)
except Exception as e:
print(f"Error setting model type: {e}")
def on_training_method_change(self, sender, app_data):
\"\"\"
Handle training method change
Args:
sender: Sender ID
app_data: Selected training method name
\"\"\"
# Update state manager if available
if hasattr(self.state_manager, "set_state"):
try:
from modules.util.enum.TrainingMethod import TrainingMethod
training_method = TrainingMethod[app_data]
self.state_manager.set_state("training_method", training_method)
except Exception as e:
print(f"Error setting training method: {e}")
def on_preset_change(self, sender, app_data):
\"\"\"
Handle preset selection change
Args:
sender: Sender ID
app_data: Selected preset name
\"\"\"
pass
def on_load_preset(self):
\"\"\"Handle load preset button\"\"\"
preset_name = dpg.get_value(self.preset_combo)
if preset_name == "-- Select Preset --":
return
preset_path = os.path.join(self.presets_dir, f"{preset_name}.json")
if os.path.exists(preset_path):
try:
# Load preset data
with open(preset_path, "r") as f:
preset_data = json.load(f)
# Update state manager
if hasattr(self.state_manager, "set_config"):
self.state_manager.set_config(preset_data)
print(f"Loaded preset: {preset_name}")
except Exception as e:
print(f"Error loading preset {preset_name}: {e}")
def on_save_preset(self):
\"\"\"Handle save preset button\"\"\"
# Create a save dialog
with dpg.window(label="Save Preset", modal=True, width=400, height=150,
pos=(dpg.get_viewport_width() // 2 - 200, dpg.get_viewport_height() // 2 - 75)):
dpg.add_text("Enter preset name:")
# Add input field for preset name
input_id = dpg.add_input_text(width=380)
with dpg.group(horizontal=True):
dpg.add_button(label="Save", callback=lambda: self.save_preset(dpg.get_value(input_id)))
dpg.add_button(label="Cancel", callback=lambda: dpg.delete_item(dpg.get_current_parent_id()))
def save_preset(self, preset_name):
\"\"\"
Save the current config as a preset
Args:
preset_name: Name of the preset to save
\"\"\"
if not preset_name:
print("Error: Preset name cannot be empty")
return
# Close the dialog
dpg.delete_item(dpg.get_current_parent_id())
# Get current config from state manager
config_data = {}
if hasattr(self.state_manager, "get_config"):
config_data = self.state_manager.get_config()
# Save config to preset file
preset_path = os.path.join(self.presets_dir, f"{preset_name}.json")
try:
# Create presets directory if it doesn't exist
if not os.path.exists(self.presets_dir):
os.makedirs(self.presets_dir)
# Write data to file
with open(preset_path, "w") as f:
json.dump(config_data, f, indent=2)
print(f"Saved preset: {preset_name}")
# Update preset list
dpg.set_item_callback(self.preset_combo, None)
dpg.configure_item(self.preset_combo, items=self.get_preset_names())
dpg.set_value(self.preset_combo, preset_name)
dpg.set_item_callback(self.preset_combo, self.on_preset_change)
except Exception as e:
print(f"Error saving preset {preset_name}: {e}")
def on_load_config(self):
\"\"\"Handle load config button\"\"\"
# Update status
dpg.set_value("app_title", "OneTrainer - Loading Config...")
# Create a file dialog
with dpg.file_dialog(label="Load Config", directory_selector=False, callback=self.load_config_callback,
width=700, height=400):
dpg.add_file_extension(".json", color=(0, 255, 0, 255))
def load_config_callback(self, sender, app_data):
\"\"\"
Handle file dialog result for loading config
Args:
sender: Sender ID
app_data: File dialog data
\"\"\"
if "file_path_name" in app_data:
config_path = app_data["file_path_name"]
try:
# Load config data
with open(config_path, "r") as f:
config_data = json.load(f)
# Update state manager
if hasattr(self.state_manager, "set_config"):
self.state_manager.set_config(config_data)
print(f"Loaded config: {config_path}")
except Exception as e:
print(f"Error loading config {config_path}: {e}")
# Restore status
dpg.set_value("app_title", "OneTrainer")
def on_save_config(self):
\"\"\"Handle save config button\"\"\"
# Update status
dpg.set_value("app_title", "OneTrainer - Saving Config...")
# Create a file dialog
with dpg.file_dialog(label="Save Config", directory_selector=False, callback=self.save_config_callback,
width=700, height=400):
dpg.add_file_extension(".json", color=(0, 255, 0, 255))
def save_config_callback(self, sender, app_data):
\"\"\"
Handle file dialog result for saving config
Args:
sender: Sender ID
app_data: File dialog data
\"\"\"
if "file_path_name" in app_data:
config_path = app_data["file_path_name"]
# Add .json extension if not present
if not config_path.lower().endswith(".json"):
config_path += ".json"
# Get current config from state manager
config_data = {}
if hasattr(self.state_manager, "get_config"):
config_data = self.state_manager.get_config()
try:
# Write data to file
with open(config_path, "w") as f:
json.dump(config_data, f, indent=2)
print(f"Saved config: {config_path}")
except Exception as e:
print(f"Error saving config {config_path}: {e}")
# Restore status
dpg.set_value("app_title", "OneTrainer")
"""
# Write the improved content
with open(top_bar_path, "w") as f:
f.write(improved_content)
# Create preset selector component if it doesn't exist
preset_selector_path = os.path.join(current_dir, "dpg_ui", "components", "preset_selector.py")
if not os.path.exists(preset_selector_path):
os.makedirs(os.path.dirname(preset_selector_path), exist_ok=True)
with open(preset_selector_path, "w") as f:
f.write("""#!/usr/bin/env python3
\"\"\"
Preset selector component for DPG UI
This module provides a preset selector component for the OneTrainer DPG UI.
\"\"\"
import os
import json
import dearpygui.dearpygui as dpg
from typing import List, Callable, Dict, Any, Optional
class PresetSelector:
\"\"\"Preset selector component for DPG UI\"\"\"
def __init__(self, parent: int, presets_dir: str = "training_presets", on_select: Callable = None):
\"\"\"
Initialize the preset selector component
Args:
parent: Parent container ID
presets_dir: Directory containing preset files
on_select: Callback function to call when a preset is selected
\"\"\"
self.parent = parent
self.presets_dir = presets_dir
self.on_select_callback = on_select
# State variables
self.presets = []
self.filtered_presets = []
self.selected_index = -1
self.search_text = ""
self.current_filter = "All"
self.available_types = ["All"]
# Load presets
self.load_presets()
# Create UI
self.create_ui()
def load_presets(self):
\"\"\"Load available presets\"\"\"
self.presets = []
# Add default "None" preset
self.presets.append({
"name": "-- None --",
"path": "",
"type": "None"
})
# Check if presets directory exists
if not os.path.exists(self.presets_dir):
try:
os.makedirs(self.presets_dir)
except Exception as e:
print(f"Error creating presets directory: {e}")
return
# Add presets from directory
for file in os.listdir(self.presets_dir):
if file.endswith(".json"):
preset_path = os.path.join(self.presets_dir, file)
preset_name = os.path.splitext(file)[0]
# Determine preset type from filename
preset_type = "Other"
if "#sd" in preset_name.lower():
preset_type = "SD"
elif "#sdxl" in preset_name.lower():
preset_type = "SDXL"
elif "#lora" in preset_name.lower():
preset_type = "LoRA"
elif "#embedding" in preset_name.lower():
preset_type = "Embedding"
# Add preset to list
self.presets.append({
"name": preset_name,
"path": preset_path,
"type": preset_type
})
# Add type to available types if not already present
if preset_type not in self.available_types:
self.available_types.append(preset_type)
# Update filtered presets
self.filter_presets()
def filter_presets(self):
\"\"\"Filter presets based on current filter and search text\"\"\"
self.filtered_presets = []
for preset in self.presets:
# Apply type filter
if self.current_filter != "All" and preset["type"] != self.current_filter:
continue
# Apply search filter
if self.search_text and self.search_text.lower() not in preset["name"].lower():
continue
# Add to filtered list
self.filtered_presets.append(preset)
def create_ui(self):
\"\"\"Create the preset selector UI\"\"\"
with dpg.group(parent=self.parent, horizontal=True):
# Filter by type
dpg.add_text("Type:")
combo_id = dpg.add_combo(
items=self.available_types,
default_value=self.current_filter,
width=100,
callback=self.on_filter_change
)
# Search box
dpg.add_text("Search:")
search_id = dpg.add_input_text(
width=150,
callback=self.on_search_change
)
# Preset selector
dpg.add_text("Preset:")
# Create preset combo with items from filtered_presets
preset_names = [preset["name"] for preset in self.filtered_presets]
self.combo_id = dpg.add_combo(
items=preset_names,
default_value=preset_names[0] if preset_names else "",
width=200,
callback=self.on_preset_selected
)
# Load button
load_id = dpg.add_button(
label="Load",
callback=self.on_load_preset
)
# Save button
save_id = dpg.add_button(
label="Save",
callback=self.on_save_preset
)
def on_filter_change(self, sender, app_data):
\"\"\"
Handle filter type change
Args:
sender: Sender ID
app_data: Selected filter type
\"\"\"
self.current_filter = app_data
self.filter_presets()
# Update combo items
preset_names = [preset["name"] for preset in self.filtered_presets]
dpg.configure_item(self.combo_id, items=preset_names)
if preset_names:
dpg.set_value(self.combo_id, preset_names[0])
def on_search_change(self, sender, app_data):
\"\"\"
Handle search text change
Args:
sender: Sender ID
app_data: Search text
\"\"\"
self.search_text = app_data
self.filter_presets()
# Update combo items
preset_names = [preset["name"] for preset in self.filtered_presets]
dpg.configure_item(self.combo_id, items=preset_names)
if preset_names:
dpg.set_value(self.combo_id, preset_names[0])
def on_preset_selected(self, sender, app_data):
\"\"\"
Handle preset selection
Args:
sender: Sender ID
app_data: Selected preset name
\"\"\"
# Find the selected preset
selected_preset = None
for preset in self.filtered_presets:
if preset["name"] == app_data:
selected_preset = preset
break
# Call callback if set
if selected_preset and self.on_select_callback:
self.on_select_callback(selected_preset)
def on_load_preset(self):
\"\"\"Handle load preset button\"\"\"
# Get selected preset name
preset_name = dpg.get_value(self.combo_id)
# Find the selected preset
selected_preset = None
for preset in self.filtered_presets:
if preset["name"] == preset_name:
selected_preset = preset
break
# Skip if no preset or empty path
if not selected_preset or not selected_preset["path"]:
print("No preset selected or preset has no path")
return
# Load the preset
try:
with open(selected_preset["path"], "r") as f:
preset_data = json.load(f)
# Call callback if set
if self.on_select_callback:
self.on_select_callback(preset_data)
print(f"Loaded preset: {selected_preset['name']}")
except Exception as e:
print(f"Error loading preset: {e}")
def on_save_preset(self):
\"\"\"Handle save preset button\"\"\"
# Create a save dialog
with dpg.window(label="Save Preset", modal=True, width=400, height=150,
pos=(dpg.get_viewport_width() // 2 - 200, dpg.get_viewport_height() // 2 - 75)):
dpg.add_text("Enter preset name:")
# Add input field for preset name
input_id = dpg.add_input_text(width=380)
with dpg.group(horizontal=True):
dpg.add_button(label="Save", callback=lambda: self.save_preset(dpg.get_value(input_id)))
dpg.add_button(label="Cancel", callback=lambda: dpg.delete_item(dpg.get_current_parent_id()))
def save_preset(self, preset_name):
\"\"\"
Save the current config as a preset
Args:
preset_name: Name of the preset to save
\"\"\"
if not preset_name:
print("Error: Preset name cannot be empty")
return
# Close the dialog
dpg.delete_item(dpg.get_current_parent_id())
# Get current config from host
# This will be implemented by the host application
# For now, just create an empty config
config_data = {}
# Save config to preset file
preset_path = os.path.join(self.presets_dir, f"{preset_name}.json")
try:
# Create presets directory if it doesn't exist
if not os.path.exists(self.presets_dir):
os.makedirs(self.presets_dir)
# Write data to file
with open(preset_path, "w") as f:
json.dump(config_data, f, indent=2)
print(f"Saved preset: {preset_name}")
# Reload presets
self.load_presets()
# Update combo items
preset_names = [preset["name"] for preset in self.filtered_presets]
dpg.configure_item(self.combo_id, items=preset_names)
# Select the new preset
for i, preset in enumerate(self.filtered_presets):
if preset["name"] == preset_name:
dpg.set_value(self.combo_id, preset_name)
break
except Exception as e:
print(f"Error saving preset: {e}")
""")
else:
print("Top bar already has preset selector implementation")
return True
def create_additional_embeddings_tab():
"""Create additional embeddings tab if it doesn't exist"""
print("Creating additional embeddings tab...")
tab_dir = os.path.join(current_dir, "dpg_ui", "tabs")
target_path = os.path.join(tab_dir, "additional_embeddings_tab.py")
if os.path.exists(target_path):
print(f"Additional embeddings tab already exists at {target_path}")
return True
# Create the file with a basic implementation
with open(target_path, "w") as f:
f.write("""#!/usr/bin/env python3
\"\"\"
Additional Embeddings tab implementation for the Dear PyGui version of OneTrainer
This module provides the additional embeddings tab UI component.
\"\"\"
import os
import sys
import dearpygui.dearpygui as dpg
from typing import Any, Dict, List, Optional
# Add parent directory to system path
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))
if parent_dir not in sys.path:
sys.path.insert(0, parent_dir)
# Import components
from dpg_ui.components.basic import Components
class AdditionalEmbeddingsTab:
\"\"\"
Additional Embeddings tab implementation
This class provides the additional embeddings tab UI component.
\"\"\"
def __init__(self, parent: int, state_manager: Any):
\"\"\"
Initialize the additional embeddings tab
Args:
parent: Parent container ID
state_manager: State manager instance
\"\"\"
self.parent = parent
self.state_manager = state_manager
# Create the UI
self.create_ui()
def create_ui(self):
\"\"\"Create the UI elements\"\"\"
with dpg.group(parent=self.parent):
# Header
Components.label(dpg.last_item(), "Additional Text Embeddings", color=(255, 255, 0))
dpg.add_text("Control which text embeddings are used for text conditioning.")
# Add separator
dpg.add_separator()
# Settings section
with dpg.collapsing_header(label="Text Embedding Models", default_open=True):
# CLIP Embeddings section
Components.label(dpg.last_item(), "CLIP Text Embeddings", color=(220, 220, 150))
# Use Open CLIP
use_open_clip = Components.switch(
dpg.last_item(),
label="Use OpenCLIP",
default_value=False,
callback=self.on_use_open_clip_change,
tooltip="Use OpenCLIP model for text embeddings"
)
# CLIP skip
with dpg.group(horizontal=True):
Components.label(dpg.last_item(), "CLIP Skip:", tooltip="Number of layers to skip in CLIP model")
clip_skip = dpg.add_slider_int(
default_value=1,
min_value=1,
max_value=12,
callback=self.on_clip_skip_change,
width=200
)
dpg.add_separator()
# T5 Embeddings section
Components.label(dpg.last_item(), "T5 Text Embeddings", color=(220, 220, 150))
# Use T5
use_t5 = Components.switch(
dpg.last_item(),
label="Use T5",
default_value=False,
callback=self.on_use_t5_change,
tooltip="Use T5 model for additional text embeddings"
)
# T5 model
with dpg.group(horizontal=True):
Components.label(dpg.last_item(), "T5 Model:", tooltip="T5 model to use")
t5_model = Components.options(
dpg.last_item(),
values=["t5-small", "t5-base", "t5-large", "flan-t5-small", "flan-t5-base", "flan-t5-large"],
default_value="t5-base",
callback=self.on_t5_model_change,
width=200,
tooltip="Select T5 model variant"
)
dpg.add_separator()
# BERT Embeddings section
Components.label(dpg.last_item(), "BERT Text Embeddings", color=(220, 220, 150))
# Use BERT
use_bert = Components.switch(
dpg.last_item(),
label="Use BERT",
default_value=False,
callback=self.on_use_bert_change,
tooltip="Use BERT model for additional text embeddings"
)
# BERT model
with dpg.group(horizontal=True):
Components.label(dpg.last_item(), "BERT Model:", tooltip="BERT model to use")
bert_model = Components.options(
dpg.last_item(),
values=["bert-base-uncased", "bert-large-uncased", "bert-base-cased", "bert-large-cased"],
default_value="bert-base-uncased",
callback=self.on_bert_model_change,
width=200,
tooltip="Select BERT model variant"
)
dpg.add_separator()
# LLaMA Embeddings section
Components.label(dpg.last_item(), "LLaMA Text Embeddings", color=(220, 220, 150))
# Use LLaMA
use_llama = Components.switch(
dpg.last_item(),