-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdearpygui_preset_selector.py
More file actions
345 lines (289 loc) · 14 KB
/
dearpygui_preset_selector.py
File metadata and controls
345 lines (289 loc) · 14 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
#!/usr/bin/env python3
"""
Standalone example of improved preset selector using Dear PyGui
This module demonstrates a better preset selector implementation that handles
many presets more elegantly than a dropdown, with filtering capabilities.
"""
import os
import json
import dearpygui.dearpygui as dpg
from pathlib import Path
class PresetSelector:
"""An improved preset selector using Dear PyGui with search and filtering capabilities"""
def __init__(self, presets_dir="training_presets", on_select=None):
"""
Initialize the preset selector component
Args:
presets_dir: Directory containing the preset JSON files
on_select: Callback function to call when a preset is selected
"""
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"]
# Item tags
self.filter_combo_tag = "preset_filter_combo"
self.search_input_tag = "preset_search_input"
self.list_tag = "preset_list"
self.save_input_tag = "preset_save_input"
# Load available presets
self.load_presets()
def load_presets(self):
"""Load all preset files from the presets directory"""
self.presets = []
# Add default preset
self.presets.append({
"name": "Default Config",
"path": Path(self.presets_dir) / "#.json",
"is_builtin": True,
"type": "Default"
})
# Scan directory for preset files
if os.path.isdir(self.presets_dir):
for filename in os.listdir(self.presets_dir):
if filename == "#.json":
continue # Skip default
if filename.endswith(".json"):
filepath = Path(self.presets_dir) / filename
name = os.path.splitext(filename)[0]
# Determine preset type based on name
preset_type = "Custom"
if name.startswith("#"):
preset_type = "Built-in"
name = name[1:] # Remove the # prefix for display
# Try to identify the model type from filename
if "sd" in name.lower():
preset_type = "Stable Diffusion"
elif "flux" in name.lower() or "flex" in name.lower():
preset_type = "Flux"
elif "xl" in name.lower():
preset_type = "SDXL"
elif "lora" in name.lower():
preset_type = "LoRA"
elif "embedding" in name.lower():
preset_type = "Embedding"
elif "cascade" in name.lower():
preset_type = "Stable Cascade"
elif "wuerstchen" in name.lower():
preset_type = "Wuerstchen"
elif "pixart" in name.lower():
preset_type = "PixArt"
# Optional: Load the file to extract more metadata
metadata = {}
try:
with open(filepath, 'r') as f:
data = json.load(f)
if isinstance(data, dict):
# Extract useful fields for filtering/display
if "model_type" in data:
metadata["model_type"] = data["model_type"]
if "training_method" in data:
metadata["training_method"] = data["training_method"]
# Update type based on training method
if data["training_method"] == "LORA":
preset_type = "LoRA"
elif data["training_method"] == "EMBEDDING":
preset_type = "Embedding"
except Exception:
pass # Silently continue if file can't be read
self.presets.append({
"name": name,
"path": filepath,
"is_builtin": name.startswith("#"),
"type": preset_type,
"metadata": metadata
})
# Sort presets: Default first, then built-ins, then custom presets
self.presets.sort(key=lambda x: (
0 if x["name"] == "Default Config" else
(1 if x["is_builtin"] else 2),
x["name"]
))
# Update filtered list
self.update_filtered_presets()
# Build list of available preset types
self.available_types = ["All"]
type_set = set(preset["type"] for preset in self.presets)
self.available_types.extend(sorted(type_set))
def update_filtered_presets(self):
"""Update the filtered presets list based on search and filter"""
search_text = self.search_text.lower()
self.filtered_presets = []
for preset in self.presets:
# Skip if search text doesn't match
if search_text and search_text not in preset["name"].lower():
continue
# Skip if filter doesn't match
if self.current_filter != "All" and preset["type"] != self.current_filter:
continue
self.filtered_presets.append(preset)
# Update the list widget if it exists
if dpg.does_item_exist(self.list_tag):
self.update_list_widget()
def on_search_changed(self, sender, app_data):
"""Handle search input changes"""
self.search_text = app_data
self.update_filtered_presets()
def on_filter_changed(self, sender, app_data):
"""Handle filter selection changes"""
self.current_filter = app_data
self.update_filtered_presets()
def on_preset_selected(self, sender, app_data):
"""Handle preset selection in the list"""
self.selected_index = app_data
if 0 <= self.selected_index < len(self.filtered_presets):
selected_preset = self.filtered_presets[self.selected_index]
# Update save input with selected name
dpg.set_value(self.save_input_tag, selected_preset["name"])
# Call the callback if provided
if self.on_select_callback:
self.on_select_callback(selected_preset)
def on_save(self, sender, app_data):
"""Handle saving the current configuration as a preset"""
new_name = dpg.get_value(self.save_input_tag)
if not new_name:
return
# This would normally save the current configuration
print(f"Saving configuration as: {new_name}")
# Mock implementation: add new preset to the list
new_preset = {
"name": new_name,
"path": Path(self.presets_dir) / f"{new_name}.json",
"is_builtin": False,
"type": "Custom"
}
# Check if preset with this name already exists
for i, preset in enumerate(self.presets):
if preset["name"] == new_name:
self.presets[i] = new_preset
break
else:
# Add new preset
self.presets.append(new_preset)
# Sort and update filtered list
self.presets.sort(key=lambda x: (
0 if x["name"] == "Default Config" else
(1 if x["is_builtin"] else 2),
x["name"]
))
self.update_filtered_presets()
def update_list_widget(self):
"""Update the list widget with filtered presets"""
# Clear the list
dpg.delete_item(self.list_tag, children_only=True)
# Add items to the list
for i, preset in enumerate(self.filtered_presets):
name = preset["name"]
preset_type = preset["type"]
# Format built-in presets differently
if preset["is_builtin"]:
dpg.add_selectable(
label=f"[Built-in] {name}",
parent=self.list_tag,
callback=lambda s, a, u=i: self.on_preset_selected(s, u),
color=[230, 190, 100]
)
else:
dpg.add_selectable(
label=f"{name} ({preset_type})",
parent=self.list_tag,
callback=lambda s, a, u=i: self.on_preset_selected(s, u)
)
def create_widget(self, parent):
"""Create the preset selector widget"""
# Main group
with dpg.group(parent=parent, horizontal=False):
# Top controls
with dpg.group(horizontal=True):
# Filter dropdown
dpg.add_text("Type:", color=[200, 200, 200])
dpg.add_combo(
items=self.available_types,
default_value=self.current_filter,
callback=self.on_filter_changed,
width=150,
tag=self.filter_combo_tag
)
# Search box
dpg.add_text("Search:", color=[200, 200, 200])
dpg.add_input_text(
callback=self.on_search_changed,
width=200,
tag=self.search_input_tag
)
# Preset list
with dpg.child_window(height=300, width=-1, tag=self.list_tag):
pass # Will be filled by update_list_widget
# Bottom controls
with dpg.group(horizontal=True):
# Save controls
dpg.add_text("Save as:", color=[200, 200, 200])
dpg.add_input_text(width=200, tag=self.save_input_tag)
dpg.add_button(label="Save", callback=self.on_save)
# Initial list update
self.update_list_widget()
def main():
"""Main function to demonstrate the preset selector"""
# Initialize DearPyGui
dpg.create_context()
dpg.create_viewport(title="OneTrainer Preset Selector", width=600, height=500)
# Create a theme for the UI
with dpg.theme() as global_theme:
with dpg.theme_component(dpg.mvAll):
# Theme similar to CustomTkinter dark-blue
dpg.add_theme_color(dpg.mvThemeCol_WindowBg, [26, 27, 38, 255]) # Dark blue background
dpg.add_theme_color(dpg.mvThemeCol_TitleBg, [32, 34, 48, 255]) # Title bar
dpg.add_theme_color(dpg.mvThemeCol_TitleBgActive, [39, 41, 57, 255]) # Active title
dpg.add_theme_color(dpg.mvThemeCol_Button, [41, 83, 154, 255]) # Buttons (blue)
dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, [59, 113, 202, 255]) # Buttons hovered
dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, [66, 127, 227, 255]) # Buttons active
dpg.add_theme_color(dpg.mvThemeCol_FrameBg, [37, 38, 51, 255]) # Frame background
dpg.add_theme_color(dpg.mvThemeCol_ChildBg, [30, 31, 45, 255]) # Frame background
dpg.add_theme_color(dpg.mvThemeCol_CheckMark, [41, 83, 154, 255]) # Checkboxes
dpg.add_theme_color(dpg.mvThemeCol_ScrollbarBg, [30, 31, 41, 255]) # Scrollbar bg
dpg.add_theme_color(dpg.mvThemeCol_ScrollbarGrab, [41, 83, 154, 255]) # Scrollbar
dpg.add_theme_color(dpg.mvThemeCol_Header, [41, 83, 154, 255]) # Headers
# Add spacing to match CustomTkinter look
dpg.add_theme_style(dpg.mvStyleVar_FramePadding, [8, 5])
dpg.add_theme_style(dpg.mvStyleVar_ItemSpacing, [8, 5])
dpg.add_theme_style(dpg.mvStyleVar_WindowPadding, [10, 10])
dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 4.0) # Rounded corners
dpg.add_theme_style(dpg.mvStyleVar_GrabRounding, 4.0) # Rounded corners
dpg.bind_theme(global_theme)
# Callback for preset selection
def on_preset_selected(preset):
print(f"Selected preset: {preset['name']} ({preset['path']})")
# Create main window
with dpg.window(label="OneTrainer Preset Selector", tag="main_window"):
# Create preset selector
preset_selector = PresetSelector(on_select=on_preset_selected)
preset_selector.create_widget("main_window")
# Add explanation
with dpg.collapsing_header(label="About this example", default_open=True):
dpg.add_text(
"This is a demonstration of how Dear PyGui can improve the preset selector experience.\n"
"The current CustomTkinter implementation uses a dropdown menu which can become\n"
"unwieldy with many presets and often cuts off long preset names.\n\n"
"This implementation offers several advantages:\n"
"- Shows many presets in a scrollable list without truncation\n"
"- Allows filtering by preset type (SD, SDXL, LoRA, etc.)\n"
"- Provides search functionality to quickly find presets\n"
"- Visually distinguishes built-in presets from user presets\n"
"- Makes more efficient use of screen space\n"
"- Conforms to the same visual style as the rest of the app"
)
# Setup and show viewport
dpg.setup_dearpygui()
dpg.show_viewport()
# Start main loop
while dpg.is_dearpygui_running():
dpg.render_dearpygui_frame()
# Clean up
dpg.destroy_context()
if __name__ == "__main__":
main()