forked from LykosAI/StabilityMatrix-Dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInferenceSettingsViewModel.cs
More file actions
350 lines (293 loc) · 11.3 KB
/
InferenceSettingsViewModel.cs
File metadata and controls
350 lines (293 loc) · 11.3 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
using System.Collections.Immutable;
using System.ComponentModel.DataAnnotations;
using System.Reactive.Linq;
using Avalonia.Controls.Notifications;
using Avalonia.Data;
using Avalonia.Platform.Storage;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DynamicData.Binding;
using FluentAvalonia.UI.Controls;
using FluentIcons.Common;
using Injectio.Attributes;
using NLog;
using StabilityMatrix.Avalonia.Extensions;
using StabilityMatrix.Avalonia.Models.Inference;
using StabilityMatrix.Avalonia.Models.TagCompletion;
using StabilityMatrix.Avalonia.Services;
using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Avalonia.Views.Settings;
using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Models;
using StabilityMatrix.Core.Models.FileInterfaces;
using StabilityMatrix.Core.Python;
using StabilityMatrix.Core.Services;
using Symbol = FluentIcons.Common.Symbol;
using SymbolIconSource = FluentIcons.Avalonia.Fluent.SymbolIconSource;
namespace StabilityMatrix.Avalonia.ViewModels.Settings;
[View(typeof(InferenceSettingsPage))]
[ManagedService]
[RegisterSingleton<InferenceSettingsViewModel>]
public partial class InferenceSettingsViewModel : PageViewModelBase
{
private readonly INotificationService notificationService;
private readonly ISettingsManager settingsManager;
private readonly ICompletionProvider completionProvider;
/// <inheritdoc />
public override string Title => "Inference";
/// <inheritdoc />
public override IconSource IconSource =>
new SymbolIconSource { Symbol = Symbol.Settings, IconVariant = IconVariant.Filled };
[ObservableProperty]
private bool isPromptCompletionEnabled = true;
[ObservableProperty]
private IReadOnlyList<string> availableTagCompletionCsvs = Array.Empty<string>();
[ObservableProperty]
private string? selectedTagCompletionCsv;
[ObservableProperty]
private bool isCompletionRemoveUnderscoresEnabled = true;
[ObservableProperty]
[CustomValidation(typeof(InferenceSettingsViewModel), nameof(ValidateOutputImageFileNameFormat))]
private string? outputImageFileNameFormat;
[ObservableProperty]
private string? outputImageFileNameFormatSample;
[ObservableProperty]
private bool isInferenceImageBrowserUseRecycleBinForDelete = true;
[ObservableProperty]
private bool filterExtraNetworksByBaseModel;
private List<string> ignoredFileNameFormatVars =
[
"author",
"model_version_name",
"base_model",
"file_name",
"model_type",
"model_id",
"model_version_id",
"file_id",
];
[ObservableProperty]
public partial int InferenceDimensionStepChange { get; set; }
[ObservableProperty]
public partial ObservableHashSet<string> FavoriteDimensions { get; set; } = [];
public IEnumerable<FileNameFormatVar> OutputImageFileNameFormatVars =>
FileNameFormatProvider
.GetSample()
.Substitutions.Where(kv => !ignoredFileNameFormatVars.Contains(kv.Key))
.Select(kv => new FileNameFormatVar { Variable = $"{{{kv.Key}}}", Example = kv.Value.Invoke() });
[ObservableProperty]
private bool isImageViewerPixelGridEnabled = true;
public InferenceSettingsViewModel(
INotificationService notificationService,
IPrerequisiteHelper prerequisiteHelper,
IPyRunner pyRunner,
IServiceManager<ViewModelBase> dialogFactory,
ICompletionProvider completionProvider,
ITrackedDownloadService trackedDownloadService,
IModelIndexService modelIndexService,
INavigationService<SettingsViewModel> settingsNavigationService,
IAccountsService accountsService,
ISettingsManager settingsManager
)
{
this.settingsManager = settingsManager;
this.notificationService = notificationService;
this.completionProvider = completionProvider;
settingsManager.RelayPropertyFor(
this,
vm => vm.SelectedTagCompletionCsv,
settings => settings.TagCompletionCsv
);
settingsManager.RelayPropertyFor(
this,
vm => vm.IsPromptCompletionEnabled,
settings => settings.IsPromptCompletionEnabled,
true
);
settingsManager.RelayPropertyFor(
this,
vm => vm.IsCompletionRemoveUnderscoresEnabled,
settings => settings.IsCompletionRemoveUnderscoresEnabled,
true
);
settingsManager.RelayPropertyFor(
this,
vm => vm.IsInferenceImageBrowserUseRecycleBinForDelete,
settings => settings.IsInferenceImageBrowserUseRecycleBinForDelete,
true
);
settingsManager.RelayPropertyFor(
this,
vm => vm.FilterExtraNetworksByBaseModel,
settings => settings.FilterExtraNetworksByBaseModel,
true
);
this.WhenPropertyChanged(vm => vm.OutputImageFileNameFormat)
.Throttle(TimeSpan.FromMilliseconds(50))
.ObserveOn(SynchronizationContext.Current)
.Subscribe(formatProperty =>
{
var provider = FileNameFormatProvider.GetSample();
var template = formatProperty.Value ?? string.Empty;
if (
!string.IsNullOrEmpty(template)
&& provider.Validate(template) == ValidationResult.Success
)
{
var format = FileNameFormat.Parse(template, provider);
OutputImageFileNameFormatSample = format.GetFileName() + ".png";
}
else
{
// Use default format if empty
var defaultFormat = FileNameFormat.Parse(FileNameFormat.DefaultTemplate, provider);
OutputImageFileNameFormatSample = defaultFormat.GetFileName() + ".png";
}
});
settingsManager.RelayPropertyFor(
this,
vm => vm.OutputImageFileNameFormat,
settings => settings.InferenceOutputImageFileNameFormat,
true
);
settingsManager.RelayPropertyFor(
this,
vm => vm.IsImageViewerPixelGridEnabled,
settings => settings.IsImageViewerPixelGridEnabled,
true
);
settingsManager.RelayPropertyFor(
this,
vm => vm.InferenceDimensionStepChange,
settings => settings.InferenceDimensionStepChange,
true
);
FavoriteDimensions
.ToObservableChangeSet()
.Throttle(TimeSpan.FromMilliseconds(50))
.ObserveOn(SynchronizationContext.Current)
.Subscribe(_ =>
{
if (
FavoriteDimensions is not { Count: > 0 }
|| FavoriteDimensions.SetEquals(settingsManager.Settings.SavedInferenceDimensions)
)
return;
settingsManager.Transaction(s => s.SavedInferenceDimensions = FavoriteDimensions.ToHashSet());
});
ImportTagCsvCommand.WithNotificationErrorHandler(notificationService, LogLevel.Warn);
}
/// <summary>
/// Validator for <see cref="OutputImageFileNameFormat"/>
/// </summary>
public static ValidationResult ValidateOutputImageFileNameFormat(
string? format,
ValidationContext context
)
{
return FileNameFormatProvider.GetSample().Validate(format ?? string.Empty);
}
/// <inheritdoc />
public override void OnLoaded()
{
base.OnLoaded();
FavoriteDimensions.Clear();
FavoriteDimensions.AddRange(
settingsManager.Settings.SavedInferenceDimensions.OrderDescending(
DimensionStringComparer.Instance
)
);
UpdateAvailableTagCompletionCsvs();
}
#region Commands
[RelayCommand(FlowExceptionsToTaskScheduler = true)]
private async Task ImportTagCsv()
{
var storage = App.StorageProvider;
var files = await storage.OpenFilePickerAsync(
new FilePickerOpenOptions
{
FileTypeFilter = new List<FilePickerFileType> { new("CSV") { Patterns = ["*.csv"] } },
}
);
if (files.Count == 0)
return;
var sourceFile = new FilePath(files[0].TryGetLocalPath()!);
var tagsDir = settingsManager.TagsDirectory;
tagsDir.Create();
// Copy to tags directory
var targetFile = tagsDir.JoinFile(sourceFile.Name);
await sourceFile.CopyToAsync(targetFile);
// Update index
UpdateAvailableTagCompletionCsvs();
// Trigger load
completionProvider.BackgroundLoadFromFile(targetFile, true);
notificationService.Show(
$"Imported {sourceFile.Name}",
$"The {sourceFile.Name} file has been imported.",
NotificationType.Success
);
}
[RelayCommand]
private async Task AddRow()
{
// FavoriteDimensions.Add(string.Empty);
var textFields = new TextBoxField[]
{
new()
{
Label = "Width",
Validator = text =>
{
if (string.IsNullOrWhiteSpace(text))
throw new DataValidationException("Width is required");
if (!int.TryParse(text, out var width) || width <= 0)
throw new DataValidationException("Width must be a positive integer");
},
Watermark = "1024",
},
new()
{
Label = "Height",
Validator = text =>
{
if (string.IsNullOrWhiteSpace(text))
throw new DataValidationException("Height is required");
if (!int.TryParse(text, out var height) || height <= 0)
throw new DataValidationException("Height must be a positive integer");
},
Watermark = "1024",
},
};
var dialog = DialogHelper.CreateTextEntryDialog("Add Favorite Dimensions", "", textFields);
if (await dialog.ShowAsync() != ContentDialogResult.Primary)
return;
var width = textFields[0].Text;
var height = textFields[1].Text;
if (string.IsNullOrWhiteSpace(width) || string.IsNullOrWhiteSpace(height))
return;
FavoriteDimensions.Add($"{width} x {height}");
}
[RelayCommand]
private void RemoveSelectedRow(string item)
{
FavoriteDimensions.Remove(item);
}
#endregion
private void UpdateAvailableTagCompletionCsvs()
{
if (!settingsManager.IsLibraryDirSet)
return;
if (settingsManager.TagsDirectory is not { Exists: true } tagsDir)
return;
var csvFiles = tagsDir.Info.EnumerateFiles("*.csv");
AvailableTagCompletionCsvs = csvFiles.Select(f => f.Name).ToImmutableArray();
// Set selected to current if exists
var settingsCsv = settingsManager.Settings.TagCompletionCsv;
if (settingsCsv is not null && AvailableTagCompletionCsvs.Contains(settingsCsv))
{
SelectedTagCompletionCsv = settingsCsv;
}
}
}