Ionite
1 year ago
committed by
GitHub
89 changed files with 4143 additions and 993 deletions
@ -0,0 +1,51 @@
|
||||
<Styles xmlns="https://github.com/avaloniaui" |
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" |
||||
xmlns:selectableImageCard="clr-namespace:StabilityMatrix.Avalonia.Controls.SelectableImageCard" |
||||
xmlns:controls="clr-namespace:StabilityMatrix.Avalonia.Controls"> |
||||
<Design.PreviewWith> |
||||
<Border Padding="20"> |
||||
<!-- Add Controls for Previewer Here --> |
||||
<selectableImageCard:SelectableImageButton |
||||
Source="https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/78fd2a0a-42b6-42b0-9815-81cb11bb3d05/00009-2423234823.jpeg" /> |
||||
</Border> |
||||
</Design.PreviewWith> |
||||
|
||||
<!-- Add Styles Here --> |
||||
<Style Selector="selectableImageCard|SelectableImageButton"> |
||||
<Setter Property="Template"> |
||||
<ControlTemplate> |
||||
<Grid> |
||||
<CheckBox VerticalAlignment="Top" |
||||
HorizontalAlignment="Right" |
||||
Margin="14,8" |
||||
Padding="0" |
||||
IsChecked="{Binding IsSelected, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" |
||||
ZIndex="100"> |
||||
<CheckBox.RenderTransform> |
||||
<ScaleTransform ScaleX="1.5" ScaleY="1.5" /> |
||||
</CheckBox.RenderTransform> |
||||
<CheckBox.Styles> |
||||
<Style Selector="CheckBox"> |
||||
<Setter Property="CornerRadius" Value="16" /> |
||||
</Style> |
||||
</CheckBox.Styles> |
||||
</CheckBox> |
||||
<Button |
||||
Margin="0" |
||||
Padding="4" |
||||
CornerRadius="12" |
||||
Command="{TemplateBinding Command}" |
||||
CommandParameter="{TemplateBinding CommandParameter}"> |
||||
<controls:BetterAdvancedImage |
||||
Width="300" |
||||
Height="300" |
||||
Stretch="UniformToFill" |
||||
CornerRadius="8" |
||||
ContextFlyout="{TemplateBinding ContextFlyout}" |
||||
Source="{TemplateBinding Source}" /> |
||||
</Button> |
||||
</Grid> |
||||
</ControlTemplate> |
||||
</Setter> |
||||
</Style> |
||||
</Styles> |
@ -0,0 +1,25 @@
|
||||
using Avalonia; |
||||
using Avalonia.Controls; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls.SelectableImageCard; |
||||
|
||||
public class SelectableImageButton : Button |
||||
{ |
||||
public static readonly StyledProperty<bool?> IsSelectedProperty = |
||||
CheckBox.IsCheckedProperty.AddOwner<SelectableImageButton>(); |
||||
|
||||
public static readonly StyledProperty<string?> SourceProperty = |
||||
BetterAdvancedImage.SourceProperty.AddOwner<SelectableImageButton>(); |
||||
|
||||
public bool? IsSelected |
||||
{ |
||||
get => GetValue(IsSelectedProperty); |
||||
set => SetValue(IsSelectedProperty, value); |
||||
} |
||||
|
||||
public string? Source |
||||
{ |
||||
get => GetValue(SourceProperty); |
||||
set => SetValue(SourceProperty, value); |
||||
} |
||||
} |
@ -0,0 +1,73 @@
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.Collections.Immutable; |
||||
using System.ComponentModel.DataAnnotations; |
||||
using System.Diagnostics.CodeAnalysis; |
||||
using System.Linq; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Models.Inference; |
||||
|
||||
public record FileNameFormat |
||||
{ |
||||
public string Template { get; } |
||||
|
||||
public string Prefix { get; set; } = ""; |
||||
|
||||
public string Postfix { get; set; } = ""; |
||||
|
||||
public IReadOnlyList<FileNameFormatPart> Parts { get; } |
||||
|
||||
private FileNameFormat(string template, IReadOnlyList<FileNameFormatPart> parts) |
||||
{ |
||||
Template = template; |
||||
Parts = parts; |
||||
} |
||||
|
||||
public FileNameFormat WithBatchPostFix(int current, int total) |
||||
{ |
||||
return this with { Postfix = Postfix + $" ({current}-{total})" }; |
||||
} |
||||
|
||||
public FileNameFormat WithGridPrefix() |
||||
{ |
||||
return this with { Prefix = Prefix + "Grid_" }; |
||||
} |
||||
|
||||
public string GetFileName() |
||||
{ |
||||
return Prefix |
||||
+ string.Join( |
||||
"", |
||||
Parts.Select( |
||||
part => part.Match(constant => constant, substitution => substitution.Invoke()) |
||||
) |
||||
) |
||||
+ Postfix; |
||||
} |
||||
|
||||
public static FileNameFormat Parse(string template, FileNameFormatProvider provider) |
||||
{ |
||||
var parts = provider.GetParts(template).ToImmutableArray(); |
||||
return new FileNameFormat(template, parts); |
||||
} |
||||
|
||||
public static bool TryParse( |
||||
string template, |
||||
FileNameFormatProvider provider, |
||||
[NotNullWhen(true)] out FileNameFormat? format |
||||
) |
||||
{ |
||||
try |
||||
{ |
||||
format = Parse(template, provider); |
||||
return true; |
||||
} |
||||
catch (ArgumentException) |
||||
{ |
||||
format = null; |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
public const string DefaultTemplate = "{date}_{time}-{model_name}-{seed}"; |
||||
} |
@ -0,0 +1,16 @@
|
||||
using System; |
||||
using System.Runtime.InteropServices; |
||||
using CSharpDiscriminatedUnion.Attributes; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Models.Inference; |
||||
|
||||
[GenerateDiscriminatedUnion(CaseFactoryPrefix = "From")] |
||||
[StructLayout(LayoutKind.Auto)] |
||||
public readonly partial struct FileNameFormatPart |
||||
{ |
||||
[StructCase("Constant", isDefaultValue: true)] |
||||
private readonly string constant; |
||||
|
||||
[StructCase("Substitution")] |
||||
private readonly Func<string?> substitution; |
||||
} |
@ -0,0 +1,192 @@
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.Collections.Immutable; |
||||
using System.ComponentModel.DataAnnotations; |
||||
using System.Diagnostics.Contracts; |
||||
using System.Linq; |
||||
using System.Text.RegularExpressions; |
||||
using Avalonia.Data; |
||||
using StabilityMatrix.Core.Extensions; |
||||
using StabilityMatrix.Core.Models; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Models.Inference; |
||||
|
||||
public partial class FileNameFormatProvider |
||||
{ |
||||
public GenerationParameters? GenerationParameters { get; init; } |
||||
|
||||
public InferenceProjectType? ProjectType { get; init; } |
||||
|
||||
public string? ProjectName { get; init; } |
||||
|
||||
private Dictionary<string, Func<string?>>? _substitutions; |
||||
|
||||
public Dictionary<string, Func<string?>> Substitutions => |
||||
_substitutions ??= new Dictionary<string, Func<string?>> |
||||
{ |
||||
{ "seed", () => GenerationParameters?.Seed.ToString() }, |
||||
{ "prompt", () => GenerationParameters?.PositivePrompt }, |
||||
{ "negative_prompt", () => GenerationParameters?.NegativePrompt }, |
||||
{ "model_name", () => GenerationParameters?.ModelName }, |
||||
{ "model_hash", () => GenerationParameters?.ModelHash }, |
||||
{ "width", () => GenerationParameters?.Width.ToString() }, |
||||
{ "height", () => GenerationParameters?.Height.ToString() }, |
||||
{ "project_type", () => ProjectType?.GetStringValue() }, |
||||
{ "project_name", () => ProjectName }, |
||||
{ "date", () => DateTime.Now.ToString("yyyy-MM-dd") }, |
||||
{ "time", () => DateTime.Now.ToString("HH-mm-ss") } |
||||
}; |
||||
|
||||
/// <summary> |
||||
/// Validate a format string |
||||
/// </summary> |
||||
/// <param name="format">Format string</param> |
||||
/// <exception cref="DataValidationException">Thrown if the format string contains an unknown variable</exception> |
||||
[Pure] |
||||
public ValidationResult Validate(string format) |
||||
{ |
||||
var regex = BracketRegex(); |
||||
var matches = regex.Matches(format); |
||||
var variables = matches.Select(m => m.Groups[1].Value); |
||||
|
||||
foreach (var variableText in variables) |
||||
{ |
||||
try |
||||
{ |
||||
var (variable, _) = ExtractVariableAndSlice(variableText); |
||||
|
||||
if (!Substitutions.ContainsKey(variable)) |
||||
{ |
||||
return new ValidationResult($"Unknown variable '{variable}'"); |
||||
} |
||||
} |
||||
catch (Exception e) |
||||
{ |
||||
return new ValidationResult($"Invalid variable '{variableText}': {e.Message}"); |
||||
} |
||||
} |
||||
|
||||
return ValidationResult.Success!; |
||||
} |
||||
|
||||
public IEnumerable<FileNameFormatPart> GetParts(string template) |
||||
{ |
||||
var regex = BracketRegex(); |
||||
var matches = regex.Matches(template); |
||||
|
||||
var parts = new List<FileNameFormatPart>(); |
||||
|
||||
// Loop through all parts of the string, including matches and non-matches |
||||
var currentIndex = 0; |
||||
|
||||
foreach (var result in matches.Cast<Match>()) |
||||
{ |
||||
// If the match is not at the start of the string, add a constant part |
||||
if (result.Index != currentIndex) |
||||
{ |
||||
var constant = template[currentIndex..result.Index]; |
||||
parts.Add(FileNameFormatPart.FromConstant(constant)); |
||||
|
||||
currentIndex += constant.Length; |
||||
} |
||||
|
||||
// Now we're at start of the current match, add the variable part |
||||
var (variable, slice) = ExtractVariableAndSlice(result.Groups[1].Value); |
||||
var substitution = Substitutions[variable]; |
||||
|
||||
// Slice string if necessary |
||||
if (slice is not null) |
||||
{ |
||||
parts.Add( |
||||
FileNameFormatPart.FromSubstitution(() => |
||||
{ |
||||
var value = substitution(); |
||||
if (value is null) |
||||
return null; |
||||
|
||||
if (slice.End is null) |
||||
{ |
||||
value = value[(slice.Start ?? 0)..]; |
||||
} |
||||
else |
||||
{ |
||||
var length = |
||||
Math.Min(value.Length, slice.End.Value) - (slice.Start ?? 0); |
||||
value = value.Substring(slice.Start ?? 0, length); |
||||
} |
||||
|
||||
return value; |
||||
}) |
||||
); |
||||
} |
||||
else |
||||
{ |
||||
parts.Add(FileNameFormatPart.FromSubstitution(substitution)); |
||||
} |
||||
|
||||
currentIndex += result.Length; |
||||
} |
||||
|
||||
// Add remaining as constant |
||||
if (currentIndex != template.Length) |
||||
{ |
||||
var constant = template[currentIndex..]; |
||||
parts.Add(FileNameFormatPart.FromConstant(constant)); |
||||
} |
||||
|
||||
return parts; |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Return a sample provider for UI preview |
||||
/// </summary> |
||||
public static FileNameFormatProvider GetSample() |
||||
{ |
||||
return new FileNameFormatProvider |
||||
{ |
||||
GenerationParameters = GenerationParameters.GetSample(), |
||||
ProjectType = InferenceProjectType.TextToImage, |
||||
ProjectName = "Sample Project" |
||||
}; |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Extract variable and index from a combined string |
||||
/// </summary> |
||||
private static (string Variable, Slice? Slice) ExtractVariableAndSlice(string combined) |
||||
{ |
||||
if (IndexRegex().Matches(combined).FirstOrDefault() is not { Success: true } match) |
||||
{ |
||||
return (combined, null); |
||||
} |
||||
|
||||
// Variable is everything before the match |
||||
var variable = combined[..match.Groups[0].Index]; |
||||
|
||||
var start = match.Groups["start"].Value; |
||||
var end = match.Groups["end"].Value; |
||||
var step = match.Groups["step"].Value; |
||||
|
||||
var slice = new Slice( |
||||
string.IsNullOrEmpty(start) ? null : int.Parse(start), |
||||
string.IsNullOrEmpty(end) ? null : int.Parse(end), |
||||
string.IsNullOrEmpty(step) ? null : int.Parse(step) |
||||
); |
||||
|
||||
return (variable, slice); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Regex for matching contents within a curly brace. |
||||
/// </summary> |
||||
[GeneratedRegex(@"\{([a-z_:\d\[\]]+)\}")]
|
||||
private static partial Regex BracketRegex(); |
||||
|
||||
/// <summary> |
||||
/// Regex for matching a Python-like array index. |
||||
/// </summary> |
||||
[GeneratedRegex(@"\[(?:(?<start>-?\d+)?)\:(?:(?<end>-?\d+)?)?(?:\:(?<step>-?\d+))?\]")]
|
||||
private static partial Regex IndexRegex(); |
||||
|
||||
private record Slice(int? Start, int? End, int? Step); |
||||
} |
@ -0,0 +1,8 @@
|
||||
namespace StabilityMatrix.Avalonia.Models.Inference; |
||||
|
||||
public record FileNameFormatVar |
||||
{ |
||||
public required string Variable { get; init; } |
||||
|
||||
public string? Example { get; init; } |
||||
} |
@ -0,0 +1,7 @@
|
||||
namespace StabilityMatrix.Avalonia.Models; |
||||
|
||||
public class PackageOutputCategory |
||||
{ |
||||
public required string Name { get; set; } |
||||
public required string Path { get; set; } |
||||
} |
@ -0,0 +1,19 @@
|
||||
using System; |
||||
using CommunityToolkit.Mvvm.ComponentModel; |
||||
using StabilityMatrix.Avalonia.ViewModels.Base; |
||||
using StabilityMatrix.Core.Models.Database; |
||||
|
||||
namespace StabilityMatrix.Avalonia.ViewModels.OutputsPage; |
||||
|
||||
public partial class OutputImageViewModel : ViewModelBase |
||||
{ |
||||
public LocalImageFile ImageFile { get; } |
||||
|
||||
[ObservableProperty] |
||||
private bool isSelected; |
||||
|
||||
public OutputImageViewModel(LocalImageFile imageFile) |
||||
{ |
||||
ImageFile = imageFile; |
||||
} |
||||
} |
@ -0,0 +1,402 @@
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.Collections.ObjectModel; |
||||
using System.Diagnostics; |
||||
using System.IO; |
||||
using System.Linq; |
||||
using System.Reactive.Linq; |
||||
using System.Threading; |
||||
using System.Threading.Tasks; |
||||
using AsyncAwaitBestPractices; |
||||
using AsyncImageLoader; |
||||
using Avalonia; |
||||
using Avalonia.Controls; |
||||
using Avalonia.Threading; |
||||
using CommunityToolkit.Mvvm.ComponentModel; |
||||
using DynamicData; |
||||
using DynamicData.Binding; |
||||
using FluentAvalonia.UI.Controls; |
||||
using Microsoft.Extensions.Logging; |
||||
using StabilityMatrix.Avalonia.Controls; |
||||
using StabilityMatrix.Avalonia.Extensions; |
||||
using StabilityMatrix.Avalonia.Languages; |
||||
using StabilityMatrix.Avalonia.Models; |
||||
using StabilityMatrix.Avalonia.Services; |
||||
using StabilityMatrix.Avalonia.ViewModels.Base; |
||||
using StabilityMatrix.Avalonia.ViewModels.Dialogs; |
||||
using StabilityMatrix.Avalonia.ViewModels.Inference; |
||||
using StabilityMatrix.Avalonia.ViewModels.OutputsPage; |
||||
using StabilityMatrix.Core.Attributes; |
||||
using StabilityMatrix.Core.Helper; |
||||
using StabilityMatrix.Core.Helper.Factory; |
||||
using StabilityMatrix.Core.Models; |
||||
using StabilityMatrix.Core.Models.Database; |
||||
using StabilityMatrix.Core.Models.FileInterfaces; |
||||
using StabilityMatrix.Core.Processes; |
||||
using StabilityMatrix.Core.Services; |
||||
using Symbol = FluentIcons.Common.Symbol; |
||||
using SymbolIconSource = FluentIcons.FluentAvalonia.SymbolIconSource; |
||||
|
||||
namespace StabilityMatrix.Avalonia.ViewModels; |
||||
|
||||
[View(typeof(Views.OutputsPage))] |
||||
public partial class OutputsPageViewModel : PageViewModelBase |
||||
{ |
||||
private readonly ISettingsManager settingsManager; |
||||
private readonly IPackageFactory packageFactory; |
||||
private readonly INotificationService notificationService; |
||||
private readonly INavigationService navigationService; |
||||
private readonly ILogger<OutputsPageViewModel> logger; |
||||
public override string Title => Resources.Label_OutputsPageTitle; |
||||
|
||||
public override IconSource IconSource => |
||||
new SymbolIconSource { Symbol = Symbol.Grid, IsFilled = true }; |
||||
|
||||
public SourceCache<OutputImageViewModel, string> OutputsCache { get; } = |
||||
new(p => p.ImageFile.AbsolutePath); |
||||
|
||||
public IObservableCollection<OutputImageViewModel> Outputs { get; set; } = |
||||
new ObservableCollectionExtended<OutputImageViewModel>(); |
||||
|
||||
public IEnumerable<SharedOutputType> OutputTypes { get; } = Enum.GetValues<SharedOutputType>(); |
||||
|
||||
[ObservableProperty] |
||||
private ObservableCollection<PackageOutputCategory> categories; |
||||
|
||||
[ObservableProperty] |
||||
[NotifyPropertyChangedFor(nameof(CanShowOutputTypes))] |
||||
private PackageOutputCategory selectedCategory; |
||||
|
||||
[ObservableProperty] |
||||
private SharedOutputType selectedOutputType; |
||||
|
||||
[ObservableProperty] |
||||
[NotifyPropertyChangedFor(nameof(NumImagesSelected))] |
||||
private int numItemsSelected; |
||||
|
||||
[ObservableProperty] |
||||
private string searchQuery; |
||||
|
||||
public bool CanShowOutputTypes => |
||||
SelectedCategory?.Name?.Equals("Shared Output Folder") ?? false; |
||||
|
||||
public string NumImagesSelected => |
||||
NumItemsSelected == 1 |
||||
? Resources.Label_OneImageSelected |
||||
: string.Format(Resources.Label_NumImagesSelected, NumItemsSelected); |
||||
|
||||
public OutputsPageViewModel( |
||||
ISettingsManager settingsManager, |
||||
IPackageFactory packageFactory, |
||||
INotificationService notificationService, |
||||
INavigationService navigationService, |
||||
ILogger<OutputsPageViewModel> logger |
||||
) |
||||
{ |
||||
this.settingsManager = settingsManager; |
||||
this.packageFactory = packageFactory; |
||||
this.notificationService = notificationService; |
||||
this.navigationService = navigationService; |
||||
this.logger = logger; |
||||
|
||||
var predicate = this.WhenPropertyChanged(vm => vm.SearchQuery) |
||||
.Throttle(TimeSpan.FromMilliseconds(50))! |
||||
.Select<PropertyValue<OutputsPageViewModel, string>, Func<OutputImageViewModel, bool>>( |
||||
propertyValue => |
||||
output => |
||||
{ |
||||
if (string.IsNullOrWhiteSpace(propertyValue.Value)) |
||||
return true; |
||||
|
||||
return output.ImageFile.FileName.Contains( |
||||
propertyValue.Value, |
||||
StringComparison.OrdinalIgnoreCase |
||||
) |
||||
|| ( |
||||
output.ImageFile.GenerationParameters?.PositivePrompt != null |
||||
&& output.ImageFile.GenerationParameters.PositivePrompt.Contains( |
||||
propertyValue.Value, |
||||
StringComparison.OrdinalIgnoreCase |
||||
) |
||||
); |
||||
} |
||||
) |
||||
.AsObservable(); |
||||
|
||||
OutputsCache |
||||
.Connect() |
||||
.DeferUntilLoaded() |
||||
.Filter(predicate) |
||||
.SortBy(x => x.ImageFile.CreatedAt, SortDirection.Descending) |
||||
.Bind(Outputs) |
||||
.WhenPropertyChanged(p => p.IsSelected) |
||||
.Subscribe(_ => |
||||
{ |
||||
NumItemsSelected = Outputs.Count(o => o.IsSelected); |
||||
}); |
||||
} |
||||
|
||||
public override void OnLoaded() |
||||
{ |
||||
if (Design.IsDesignMode) |
||||
return; |
||||
|
||||
if (!settingsManager.IsLibraryDirSet) |
||||
return; |
||||
|
||||
Directory.CreateDirectory(settingsManager.ImagesDirectory); |
||||
var packageCategories = settingsManager.Settings.InstalledPackages |
||||
.Where(x => !x.UseSharedOutputFolder) |
||||
.Select(p => |
||||
{ |
||||
var basePackage = packageFactory[p.PackageName!]; |
||||
if (basePackage is null) |
||||
return null; |
||||
|
||||
return new PackageOutputCategory |
||||
{ |
||||
Path = Path.Combine(p.FullPath, basePackage.OutputFolderName), |
||||
Name = p.DisplayName |
||||
}; |
||||
}) |
||||
.ToList(); |
||||
|
||||
packageCategories.Insert( |
||||
0, |
||||
new PackageOutputCategory |
||||
{ |
||||
Path = settingsManager.ImagesDirectory, |
||||
Name = "Shared Output Folder" |
||||
} |
||||
); |
||||
|
||||
Categories = new ObservableCollection<PackageOutputCategory>(packageCategories); |
||||
SelectedCategory = Categories.First(); |
||||
SelectedOutputType = SharedOutputType.All; |
||||
SearchQuery = string.Empty; |
||||
|
||||
var path = |
||||
CanShowOutputTypes && SelectedOutputType != SharedOutputType.All |
||||
? Path.Combine(SelectedCategory.Path, SelectedOutputType.ToString()) |
||||
: SelectedCategory.Path; |
||||
GetOutputs(path); |
||||
} |
||||
|
||||
partial void OnSelectedCategoryChanged( |
||||
PackageOutputCategory? oldValue, |
||||
PackageOutputCategory? newValue |
||||
) |
||||
{ |
||||
if (oldValue == newValue || newValue == null) |
||||
return; |
||||
|
||||
var path = |
||||
CanShowOutputTypes && SelectedOutputType != SharedOutputType.All |
||||
? Path.Combine(newValue.Path, SelectedOutputType.ToString()) |
||||
: SelectedCategory.Path; |
||||
GetOutputs(path); |
||||
} |
||||
|
||||
partial void OnSelectedOutputTypeChanged(SharedOutputType oldValue, SharedOutputType newValue) |
||||
{ |
||||
if (oldValue == newValue) |
||||
return; |
||||
|
||||
var path = |
||||
newValue == SharedOutputType.All |
||||
? SelectedCategory.Path |
||||
: Path.Combine(SelectedCategory.Path, newValue.ToString()); |
||||
GetOutputs(path); |
||||
} |
||||
|
||||
public async Task OnImageClick(OutputImageViewModel item) |
||||
{ |
||||
// Select image if we're in "select mode" |
||||
if (NumItemsSelected > 0) |
||||
{ |
||||
item.IsSelected = !item.IsSelected; |
||||
} |
||||
else |
||||
{ |
||||
await ShowImageDialog(item); |
||||
} |
||||
} |
||||
|
||||
public async Task ShowImageDialog(OutputImageViewModel item) |
||||
{ |
||||
var currentIndex = Outputs.IndexOf(item); |
||||
|
||||
var image = new ImageSource(new FilePath(item.ImageFile.AbsolutePath)); |
||||
|
||||
// Preload |
||||
await image.GetBitmapAsync(); |
||||
|
||||
var vm = new ImageViewerViewModel { ImageSource = image, LocalImageFile = item.ImageFile }; |
||||
|
||||
using var onNext = Observable |
||||
.FromEventPattern<DirectionalNavigationEventArgs>( |
||||
vm, |
||||
nameof(ImageViewerViewModel.NavigationRequested) |
||||
) |
||||
.Subscribe(ctx => |
||||
{ |
||||
Dispatcher.UIThread |
||||
.InvokeAsync(async () => |
||||
{ |
||||
var sender = (ImageViewerViewModel)ctx.Sender!; |
||||
var newIndex = currentIndex + (ctx.EventArgs.IsNext ? 1 : -1); |
||||
|
||||
if (newIndex >= 0 && newIndex < Outputs.Count) |
||||
{ |
||||
var newImage = Outputs[newIndex]; |
||||
var newImageSource = new ImageSource( |
||||
new FilePath(newImage.ImageFile.AbsolutePath) |
||||
); |
||||
|
||||
// Preload |
||||
await newImageSource.GetBitmapAsync(); |
||||
|
||||
sender.ImageSource = newImageSource; |
||||
sender.LocalImageFile = newImage.ImageFile; |
||||
|
||||
currentIndex = newIndex; |
||||
} |
||||
}) |
||||
.SafeFireAndForget(); |
||||
}); |
||||
|
||||
await vm.GetDialog().ShowAsync(); |
||||
} |
||||
|
||||
public async Task CopyImage(string imagePath) |
||||
{ |
||||
var clipboard = App.Clipboard; |
||||
|
||||
await clipboard.SetFileDataObjectAsync(imagePath); |
||||
} |
||||
|
||||
public async Task OpenImage(string imagePath) => await ProcessRunner.OpenFileBrowser(imagePath); |
||||
|
||||
public async Task DeleteImage(OutputImageViewModel? item) |
||||
{ |
||||
if (item is null) |
||||
return; |
||||
|
||||
var confirmationDialog = new BetterContentDialog |
||||
{ |
||||
Title = "Are you sure you want to delete this image?", |
||||
Content = "This action cannot be undone.", |
||||
PrimaryButtonText = Resources.Action_Delete, |
||||
SecondaryButtonText = Resources.Action_Cancel, |
||||
DefaultButton = ContentDialogButton.Primary, |
||||
IsSecondaryButtonEnabled = true, |
||||
}; |
||||
var dialogResult = await confirmationDialog.ShowAsync(); |
||||
if (dialogResult != ContentDialogResult.Primary) |
||||
return; |
||||
|
||||
// Delete the file |
||||
var imageFile = new FilePath(item.ImageFile.AbsolutePath); |
||||
var result = await notificationService.TryAsync(imageFile.DeleteAsync()); |
||||
|
||||
if (!result.IsSuccessful) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
OutputsCache.Remove(item); |
||||
|
||||
// Invalidate cache |
||||
if (ImageLoader.AsyncImageLoader is FallbackRamCachedWebImageLoader loader) |
||||
{ |
||||
loader.RemoveAllNamesFromCache(imageFile.Name); |
||||
} |
||||
} |
||||
|
||||
public void SendToTextToImage(OutputImageViewModel vm) |
||||
{ |
||||
navigationService.NavigateTo<InferenceViewModel>(); |
||||
EventManager.Instance.OnInferenceTextToImageRequested(vm.ImageFile); |
||||
} |
||||
|
||||
public void SendToUpscale(OutputImageViewModel vm) |
||||
{ |
||||
navigationService.NavigateTo<InferenceViewModel>(); |
||||
EventManager.Instance.OnInferenceUpscaleRequested(vm.ImageFile); |
||||
} |
||||
|
||||
public void ClearSelection() |
||||
{ |
||||
foreach (var output in Outputs) |
||||
{ |
||||
output.IsSelected = false; |
||||
} |
||||
} |
||||
|
||||
public void SelectAll() |
||||
{ |
||||
foreach (var output in Outputs) |
||||
{ |
||||
output.IsSelected = true; |
||||
} |
||||
} |
||||
|
||||
public async Task DeleteAllSelected() |
||||
{ |
||||
var confirmationDialog = new BetterContentDialog |
||||
{ |
||||
Title = $"Are you sure you want to delete {NumItemsSelected} images?", |
||||
Content = "This action cannot be undone.", |
||||
PrimaryButtonText = Resources.Action_Delete, |
||||
SecondaryButtonText = Resources.Action_Cancel, |
||||
DefaultButton = ContentDialogButton.Primary, |
||||
IsSecondaryButtonEnabled = true, |
||||
}; |
||||
var dialogResult = await confirmationDialog.ShowAsync(); |
||||
if (dialogResult != ContentDialogResult.Primary) |
||||
return; |
||||
|
||||
var selected = Outputs.Where(o => o.IsSelected).ToList(); |
||||
Debug.Assert(selected.Count == NumItemsSelected); |
||||
foreach (var output in selected) |
||||
{ |
||||
// Delete the file |
||||
var imageFile = new FilePath(output.ImageFile.AbsolutePath); |
||||
var result = await notificationService.TryAsync(imageFile.DeleteAsync()); |
||||
|
||||
if (!result.IsSuccessful) |
||||
{ |
||||
continue; |
||||
} |
||||
OutputsCache.Remove(output); |
||||
|
||||
// Invalidate cache |
||||
if (ImageLoader.AsyncImageLoader is FallbackRamCachedWebImageLoader loader) |
||||
{ |
||||
loader.RemoveAllNamesFromCache(imageFile.Name); |
||||
} |
||||
} |
||||
|
||||
NumItemsSelected = 0; |
||||
ClearSelection(); |
||||
} |
||||
|
||||
private void GetOutputs(string directory) |
||||
{ |
||||
if (!settingsManager.IsLibraryDirSet) |
||||
return; |
||||
|
||||
if (!Directory.Exists(directory) && SelectedOutputType != SharedOutputType.All) |
||||
{ |
||||
Directory.CreateDirectory(directory); |
||||
return; |
||||
} |
||||
|
||||
var list = Directory |
||||
.EnumerateFiles(directory, "*.png", SearchOption.AllDirectories) |
||||
.Select(file => new OutputImageViewModel(LocalImageFile.FromPath(file))) |
||||
.OrderByDescending(f => f.ImageFile.CreatedAt); |
||||
|
||||
OutputsCache.EditDiff(list, (x, y) => x.ImageFile.AbsolutePath == y.ImageFile.AbsolutePath); |
||||
} |
||||
} |
@ -0,0 +1,213 @@
|
||||
<controls:UserControlBase |
||||
x:Class="StabilityMatrix.Avalonia.Views.OutputsPage" |
||||
xmlns="https://github.com/avaloniaui" |
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" |
||||
xmlns:avaloniaEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" |
||||
xmlns:controls="clr-namespace:StabilityMatrix.Avalonia.Controls" |
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" |
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" |
||||
xmlns:mocks="clr-namespace:StabilityMatrix.Avalonia.DesignData" |
||||
xmlns:ui="using:FluentAvalonia.UI.Controls" |
||||
xmlns:vm="clr-namespace:StabilityMatrix.Avalonia.ViewModels" |
||||
xmlns:lang="clr-namespace:StabilityMatrix.Avalonia.Languages" |
||||
xmlns:models1="clr-namespace:StabilityMatrix.Avalonia.Models" |
||||
xmlns:fluentAvalonia="clr-namespace:FluentIcons.FluentAvalonia;assembly=FluentIcons.FluentAvalonia" |
||||
xmlns:outputsPage="clr-namespace:StabilityMatrix.Avalonia.ViewModels.OutputsPage" |
||||
xmlns:selectableImageCard="clr-namespace:StabilityMatrix.Avalonia.Controls.SelectableImageCard" |
||||
xmlns:avalonia="clr-namespace:Projektanker.Icons.Avalonia;assembly=Projektanker.Icons.Avalonia" |
||||
d:DataContext="{x:Static mocks:DesignData.OutputsPageViewModel}" |
||||
d:DesignHeight="450" |
||||
d:DesignWidth="700" |
||||
x:CompileBindings="True" |
||||
x:DataType="vm:OutputsPageViewModel" |
||||
mc:Ignorable="d"> |
||||
<Grid RowDefinitions="Auto, *" Margin="16"> |
||||
<Grid Grid.Row="0" Margin="0,0,0,16" |
||||
HorizontalAlignment="Stretch" |
||||
RowDefinitions="Auto, Auto" |
||||
ColumnDefinitions="Auto, Auto, Auto, Auto, *, Auto, Auto"> |
||||
<TextBlock Grid.Row="0" |
||||
Grid.Column="0" |
||||
Text="{x:Static lang:Resources.Label_OutputFolder}" |
||||
Margin="4" /> |
||||
<ComboBox Grid.Column="0" |
||||
Grid.Row="1" ItemsSource="{Binding Categories}" |
||||
CornerRadius="8" |
||||
Margin="4,0" |
||||
SelectedItem="{Binding SelectedCategory}" |
||||
VerticalAlignment="Stretch" |
||||
MinWidth="150"> |
||||
<ComboBox.Styles> |
||||
<Style |
||||
Selector="ComboBox /template/ ContentControl#ContentPresenter > StackPanel > TextBlock:nth-child(2)"> |
||||
<Setter Property="IsVisible" Value="False" /> |
||||
</Style> |
||||
</ComboBox.Styles> |
||||
<ComboBox.ItemTemplate> |
||||
<DataTemplate DataType="{x:Type models1:PackageOutputCategory}"> |
||||
<StackPanel> |
||||
<TextBlock |
||||
Margin="0,4,0,4" |
||||
Text="{Binding Name, Mode=OneWay}" /> |
||||
<TextBlock Text="{Binding Path, Mode=OneWay}" /> |
||||
</StackPanel> |
||||
</DataTemplate> |
||||
</ComboBox.ItemTemplate> |
||||
</ComboBox> |
||||
|
||||
<TextBlock Grid.Row="0" |
||||
Grid.Column="1" |
||||
Text="{x:Static lang:Resources.Label_OutputType}" |
||||
Margin="4" |
||||
IsVisible="{Binding CanShowOutputTypes}" /> |
||||
<ComboBox Grid.Column="1" Grid.Row="1" ItemsSource="{Binding OutputTypes}" |
||||
IsVisible="{Binding CanShowOutputTypes}" |
||||
CornerRadius="8" |
||||
SelectedItem="{Binding SelectedOutputType}" |
||||
MinWidth="150" |
||||
Margin="4,0" |
||||
VerticalAlignment="Stretch" |
||||
VerticalContentAlignment="Center" /> |
||||
|
||||
<TextBlock Grid.Row="0" |
||||
Grid.Column="2" |
||||
Margin="4" |
||||
Text="Search"/> |
||||
<TextBox Grid.Row="1" |
||||
Grid.Column="2" |
||||
Text="{Binding SearchQuery, Mode=TwoWay}" |
||||
Watermark="Search" |
||||
Margin="4, 0" |
||||
VerticalContentAlignment="Center" |
||||
MinWidth="150"/> |
||||
|
||||
<TextBlock Grid.Row="1" |
||||
Grid.Column="4" |
||||
IsVisible="{Binding !!NumItemsSelected}" |
||||
FontSize="16" |
||||
Margin="8, 0" |
||||
VerticalAlignment="Center" |
||||
TextAlignment="Center" |
||||
HorizontalAlignment="Right" |
||||
Text="{Binding NumImagesSelected, FallbackValue=1234 images selected}" /> |
||||
|
||||
<Button Grid.Row="1" |
||||
Grid.Column="5" |
||||
VerticalAlignment="Bottom" |
||||
CornerRadius="8" |
||||
Padding="12, 0" |
||||
Height="40" |
||||
Classes="danger" |
||||
Command="{Binding DeleteAllSelected}" |
||||
IsVisible="{Binding !!NumItemsSelected}" > |
||||
<avalonia:Icon Value="fa-solid fa-trash-can"/> |
||||
</Button> |
||||
|
||||
<Button Grid.Row="1" |
||||
Grid.Column="6" |
||||
Content="{x:Static lang:Resources.Action_ClearSelection}" |
||||
VerticalAlignment="Bottom" |
||||
CornerRadius="8" |
||||
Margin="8, 0" |
||||
Height="40" |
||||
Command="{Binding ClearSelection}" |
||||
IsVisible="{Binding !!NumItemsSelected}" /> |
||||
<Button Grid.Row="1" |
||||
Grid.Column="6" |
||||
Content="{x:Static lang:Resources.Action_SelectAll}" |
||||
VerticalAlignment="Bottom" |
||||
Classes="accent" |
||||
CornerRadius="8" |
||||
Margin="8, 0" |
||||
Height="40" |
||||
Command="{Binding SelectAll}" |
||||
IsVisible="{Binding !NumItemsSelected}" /> |
||||
</Grid> |
||||
|
||||
<ScrollViewer Grid.Row="1"> |
||||
<ItemsRepeater |
||||
ItemsSource="{Binding Outputs}" |
||||
VerticalAlignment="Top"> |
||||
<ItemsRepeater.Layout> |
||||
<UniformGridLayout MinColumnSpacing="16" MinRowSpacing="16" /> |
||||
</ItemsRepeater.Layout> |
||||
<ItemsRepeater.ItemTemplate> |
||||
<DataTemplate DataType="{x:Type outputsPage:OutputImageViewModel}"> |
||||
<selectableImageCard:SelectableImageButton |
||||
Command="{Binding $parent[ItemsRepeater].((vm:OutputsPageViewModel)DataContext).OnImageClick}" |
||||
CommandParameter="{Binding }" |
||||
IsSelected="{Binding IsSelected}" |
||||
Source="{Binding ImageFile.AbsolutePath}"> |
||||
<selectableImageCard:SelectableImageButton.ContextFlyout> |
||||
<ui:FAMenuFlyout> |
||||
<ui:MenuFlyoutItem |
||||
HotKey="{x:Null}" |
||||
Text="{x:Static lang:Resources.Action_Copy}" |
||||
IconSource="Copy" |
||||
Command="{Binding $parent[ItemsRepeater].((vm:OutputsPageViewModel)DataContext).CopyImage}" |
||||
CommandParameter="{Binding ImageFile.AbsolutePath}" /> |
||||
<ui:MenuFlyoutItem |
||||
HotKey="{x:Null}" |
||||
Text="{x:Static lang:Resources.Action_OpenInExplorer}" |
||||
IconSource="Folder" |
||||
Command="{Binding $parent[ItemsRepeater].((vm:OutputsPageViewModel)DataContext).OpenImage}" |
||||
CommandParameter="{Binding ImageFile.AbsolutePath}" /> |
||||
<ui:MenuFlyoutItem |
||||
HotKey="{x:Null}" |
||||
Text="{x:Static lang:Resources.Action_OpenInViewer}" |
||||
IconSource="Image" |
||||
IsVisible="{Binding !!$parent[ItemsRepeater].((vm:OutputsPageViewModel)DataContext).NumItemsSelected}" |
||||
Command="{Binding $parent[ItemsRepeater].((vm:OutputsPageViewModel)DataContext).ShowImageDialog}" |
||||
CommandParameter="{Binding }" /> |
||||
<ui:MenuFlyoutItem |
||||
HotKey="{x:Null}" |
||||
Text="{x:Static lang:Resources.Action_Delete}" |
||||
IconSource="Delete" |
||||
Command="{Binding $parent[ItemsRepeater].((vm:OutputsPageViewModel)DataContext).DeleteImage}" |
||||
CommandParameter="{Binding }" /> |
||||
|
||||
<ui:MenuFlyoutSeparator |
||||
IsVisible="{Binding ImageFile.GenerationParameters, Converter={x:Static ObjectConverters.IsNotNull}}" /> |
||||
|
||||
<ui:MenuFlyoutSubItem Text="{x:Static lang:Resources.Action_SendToInference}" |
||||
IconSource="Share" |
||||
IsVisible="{Binding ImageFile.GenerationParameters, Converter={x:Static ObjectConverters.IsNotNull}}"> |
||||
<ui:MenuFlyoutItem |
||||
HotKey="{x:Null}" |
||||
Text="{x:Static lang:Resources.Label_TextToImage}" |
||||
IconSource="FullScreenMaximize" |
||||
Command="{Binding $parent[ItemsRepeater].((vm:OutputsPageViewModel)DataContext).SendToTextToImage}" |
||||
CommandParameter="{Binding }" /> |
||||
<ui:MenuFlyoutItem |
||||
HotKey="{x:Null}" |
||||
Text="{x:Static lang:Resources.Label_ImageToImage}" |
||||
IsEnabled="False" |
||||
IconSource="ImageCopy" |
||||
CommandParameter="{Binding }" /> |
||||
<ui:MenuFlyoutItem |
||||
Text="{x:Static lang:Resources.Label_Inpainting}" |
||||
IconSource="ImageEdit" |
||||
IsEnabled="False" |
||||
HotKey="{x:Null}" |
||||
CommandParameter="{Binding }" /> |
||||
<ui:MenuFlyoutItem |
||||
Text="{x:Static lang:Resources.Label_Upscale}" |
||||
HotKey="{x:Null}" |
||||
Command="{Binding $parent[ItemsRepeater].((vm:OutputsPageViewModel)DataContext).SendToUpscale}" |
||||
CommandParameter="{Binding }"> |
||||
<ui:MenuFlyoutItem.IconSource> |
||||
<fluentAvalonia:SymbolIconSource |
||||
FontSize="10" |
||||
Symbol="ResizeImage" /> |
||||
</ui:MenuFlyoutItem.IconSource> |
||||
</ui:MenuFlyoutItem> |
||||
</ui:MenuFlyoutSubItem> |
||||
</ui:FAMenuFlyout> |
||||
</selectableImageCard:SelectableImageButton.ContextFlyout> |
||||
</selectableImageCard:SelectableImageButton> |
||||
</DataTemplate> |
||||
</ItemsRepeater.ItemTemplate> |
||||
</ItemsRepeater> |
||||
</ScrollViewer> |
||||
</Grid> |
||||
</controls:UserControlBase> |
@ -0,0 +1,14 @@
|
||||
using Avalonia; |
||||
using Avalonia.Controls; |
||||
using Avalonia.Markup.Xaml; |
||||
using StabilityMatrix.Avalonia.Controls; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Views; |
||||
|
||||
public partial class OutputsPage : UserControlBase |
||||
{ |
||||
public OutputsPage() |
||||
{ |
||||
InitializeComponent(); |
||||
} |
||||
} |
@ -1,25 +1,30 @@
|
||||
using System.Runtime.Versioning; |
||||
using StabilityMatrix.Core.Models.Progress; |
||||
using StabilityMatrix.Core.Processes; |
||||
|
||||
namespace StabilityMatrix.Core.Helper; |
||||
|
||||
public interface IPrerequisiteHelper |
||||
{ |
||||
string GitBinPath { get; } |
||||
|
||||
|
||||
bool IsPythonInstalled { get; } |
||||
|
||||
|
||||
Task InstallAllIfNecessary(IProgress<ProgressReport>? progress = null); |
||||
Task UnpackResourcesIfNecessary(IProgress<ProgressReport>? progress = null); |
||||
Task InstallGitIfNecessary(IProgress<ProgressReport>? progress = null); |
||||
Task InstallPythonIfNecessary(IProgress<ProgressReport>? progress = null); |
||||
|
||||
|
||||
[SupportedOSPlatform("Windows")] |
||||
Task InstallVcRedistIfNecessary(IProgress<ProgressReport>? progress = null); |
||||
|
||||
/// <summary> |
||||
/// Run embedded git with the given arguments. |
||||
/// </summary> |
||||
Task RunGit(string? workingDirectory = null, params string[] args); |
||||
Task RunGit( |
||||
string? workingDirectory = null, |
||||
Action<ProcessOutput>? onProcessOutput = null, |
||||
params string[] args |
||||
); |
||||
Task<string> GetGitOutput(string? workingDirectory = null, params string[] args); |
||||
} |
||||
|
@ -0,0 +1,247 @@
|
||||
using System.Diagnostics.CodeAnalysis; |
||||
using System.Text.Json.Nodes; |
||||
using System.Text.RegularExpressions; |
||||
using NLog; |
||||
using StabilityMatrix.Core.Helper; |
||||
using StabilityMatrix.Core.Helper.Cache; |
||||
using StabilityMatrix.Core.Models.FileInterfaces; |
||||
using StabilityMatrix.Core.Models.Progress; |
||||
using StabilityMatrix.Core.Processes; |
||||
using StabilityMatrix.Core.Python; |
||||
using StabilityMatrix.Core.Services; |
||||
|
||||
namespace StabilityMatrix.Core.Models.Packages; |
||||
|
||||
public class StableDiffusionDirectMl : BaseGitPackage |
||||
{ |
||||
private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); |
||||
|
||||
public override string Name => "stable-diffusion-webui-directml"; |
||||
public override string DisplayName { get; set; } = "Stable Diffusion Web UI"; |
||||
public override string Author => "lshqqytiger"; |
||||
public override string LicenseType => "AGPL-3.0"; |
||||
public override string LicenseUrl => |
||||
"https://github.com/lshqqytiger/stable-diffusion-webui-directml/blob/master/LICENSE.txt"; |
||||
public override string Blurb => |
||||
"A fork of Automatic1111's Stable Diffusion WebUI with DirectML support"; |
||||
public override string LaunchCommand => "launch.py"; |
||||
public override Uri PreviewImageUri => |
||||
new( |
||||
"https://github.com/lshqqytiger/stable-diffusion-webui-directml/raw/master/screenshot.png" |
||||
); |
||||
|
||||
public override SharedFolderMethod RecommendedSharedFolderMethod => SharedFolderMethod.Symlink; |
||||
|
||||
public StableDiffusionDirectMl( |
||||
IGithubApiCache githubApi, |
||||
ISettingsManager settingsManager, |
||||
IDownloadService downloadService, |
||||
IPrerequisiteHelper prerequisiteHelper |
||||
) |
||||
: base(githubApi, settingsManager, downloadService, prerequisiteHelper) { } |
||||
|
||||
public override Dictionary<SharedFolderType, IReadOnlyList<string>> SharedFolders => |
||||
new() |
||||
{ |
||||
[SharedFolderType.StableDiffusion] = new[] { "models/Stable-diffusion" }, |
||||
[SharedFolderType.ESRGAN] = new[] { "models/ESRGAN" }, |
||||
[SharedFolderType.RealESRGAN] = new[] { "models/RealESRGAN" }, |
||||
[SharedFolderType.SwinIR] = new[] { "models/SwinIR" }, |
||||
[SharedFolderType.Lora] = new[] { "models/Lora" }, |
||||
[SharedFolderType.LyCORIS] = new[] { "models/LyCORIS" }, |
||||
[SharedFolderType.ApproxVAE] = new[] { "models/VAE-approx" }, |
||||
[SharedFolderType.VAE] = new[] { "models/VAE" }, |
||||
[SharedFolderType.DeepDanbooru] = new[] { "models/deepbooru" }, |
||||
[SharedFolderType.Karlo] = new[] { "models/karlo" }, |
||||
[SharedFolderType.TextualInversion] = new[] { "embeddings" }, |
||||
[SharedFolderType.Hypernetwork] = new[] { "models/hypernetworks" }, |
||||
[SharedFolderType.ControlNet] = new[] { "models/ControlNet" }, |
||||
[SharedFolderType.Codeformer] = new[] { "models/Codeformer" }, |
||||
[SharedFolderType.LDSR] = new[] { "models/LDSR" }, |
||||
[SharedFolderType.AfterDetailer] = new[] { "models/adetailer" } |
||||
}; |
||||
|
||||
public override Dictionary<SharedOutputType, IReadOnlyList<string>>? SharedOutputFolders => |
||||
new() |
||||
{ |
||||
[SharedOutputType.Extras] = new[] { "outputs/extras-images" }, |
||||
[SharedOutputType.Saved] = new[] { "log/images" }, |
||||
[SharedOutputType.Img2Img] = new[] { "outputs/img2img-images" }, |
||||
[SharedOutputType.Text2Img] = new[] { "outputs/txt2img-images" }, |
||||
[SharedOutputType.Img2ImgGrids] = new[] { "outputs/img2img-grids" }, |
||||
[SharedOutputType.Text2ImgGrids] = new[] { "outputs/txt2img-grids" } |
||||
}; |
||||
|
||||
[SuppressMessage("ReSharper", "ArrangeObjectCreationWhenTypeNotEvident")] |
||||
public override List<LaunchOptionDefinition> LaunchOptions => |
||||
new() |
||||
{ |
||||
new() |
||||
{ |
||||
Name = "Host", |
||||
Type = LaunchOptionType.String, |
||||
DefaultValue = "localhost", |
||||
Options = new() { "--server-name" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "Port", |
||||
Type = LaunchOptionType.String, |
||||
DefaultValue = "7860", |
||||
Options = new() { "--port" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "VRAM", |
||||
Type = LaunchOptionType.Bool, |
||||
InitialValue = HardwareHelper |
||||
.IterGpuInfo() |
||||
.Select(gpu => gpu.MemoryLevel) |
||||
.Max() switch |
||||
{ |
||||
Level.Low => "--lowvram", |
||||
Level.Medium => "--medvram", |
||||
_ => null |
||||
}, |
||||
Options = new() { "--lowvram", "--medvram", "--medvram-sdxl" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "Xformers", |
||||
Type = LaunchOptionType.Bool, |
||||
InitialValue = HardwareHelper.HasNvidiaGpu(), |
||||
Options = new() { "--xformers" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "API", |
||||
Type = LaunchOptionType.Bool, |
||||
InitialValue = true, |
||||
Options = new() { "--api" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "Auto Launch Web UI", |
||||
Type = LaunchOptionType.Bool, |
||||
InitialValue = false, |
||||
Options = new() { "--autolaunch" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "Skip Torch CUDA Check", |
||||
Type = LaunchOptionType.Bool, |
||||
InitialValue = !HardwareHelper.HasNvidiaGpu(), |
||||
Options = new() { "--skip-torch-cuda-test" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "Skip Python Version Check", |
||||
Type = LaunchOptionType.Bool, |
||||
InitialValue = true, |
||||
Options = new() { "--skip-python-version-check" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "No Half", |
||||
Type = LaunchOptionType.Bool, |
||||
Description = "Do not switch the model to 16-bit floats", |
||||
InitialValue = HardwareHelper.HasAmdGpu(), |
||||
Options = new() { "--no-half" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "Skip SD Model Download", |
||||
Type = LaunchOptionType.Bool, |
||||
InitialValue = false, |
||||
Options = new() { "--no-download-sd-model" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "Skip Install", |
||||
Type = LaunchOptionType.Bool, |
||||
Options = new() { "--skip-install" } |
||||
}, |
||||
LaunchOptionDefinition.Extras |
||||
}; |
||||
|
||||
public override IEnumerable<SharedFolderMethod> AvailableSharedFolderMethods => |
||||
new[] { SharedFolderMethod.Symlink, SharedFolderMethod.None }; |
||||
|
||||
public override IEnumerable<TorchVersion> AvailableTorchVersions => |
||||
new[] { TorchVersion.Cpu, TorchVersion.DirectMl }; |
||||
|
||||
public override Task<string> GetLatestVersion() => Task.FromResult("master"); |
||||
|
||||
public override bool ShouldIgnoreReleases => true; |
||||
|
||||
public override string OutputFolderName => "outputs"; |
||||
|
||||
public override async Task InstallPackage( |
||||
string installLocation, |
||||
TorchVersion torchVersion, |
||||
DownloadPackageVersionOptions versionOptions, |
||||
IProgress<ProgressReport>? progress = null, |
||||
Action<ProcessOutput>? onConsoleOutput = null |
||||
) |
||||
{ |
||||
progress?.Report(new ProgressReport(-1f, "Setting up venv", isIndeterminate: true)); |
||||
// Setup venv |
||||
await using var venvRunner = new PyVenvRunner(Path.Combine(installLocation, "venv")); |
||||
venvRunner.WorkingDirectory = installLocation; |
||||
await venvRunner.Setup(true, onConsoleOutput).ConfigureAwait(false); |
||||
|
||||
switch (torchVersion) |
||||
{ |
||||
case TorchVersion.DirectMl: |
||||
await InstallDirectMlTorch(venvRunner, progress, onConsoleOutput) |
||||
.ConfigureAwait(false); |
||||
break; |
||||
case TorchVersion.Cpu: |
||||
await InstallCpuTorch(venvRunner, progress, onConsoleOutput).ConfigureAwait(false); |
||||
break; |
||||
} |
||||
|
||||
// Install requirements file |
||||
progress?.Report( |
||||
new ProgressReport(-1f, "Installing Package Requirements", isIndeterminate: true) |
||||
); |
||||
Logger.Info("Installing requirements_versions.txt"); |
||||
|
||||
var requirements = new FilePath(installLocation, "requirements_versions.txt"); |
||||
await venvRunner |
||||
.PipInstallFromRequirements(requirements, onConsoleOutput, excludes: "torch") |
||||
.ConfigureAwait(false); |
||||
|
||||
progress?.Report(new ProgressReport(1f, "Install complete", isIndeterminate: false)); |
||||
} |
||||
|
||||
public override async Task RunPackage( |
||||
string installedPackagePath, |
||||
string command, |
||||
string arguments, |
||||
Action<ProcessOutput>? onConsoleOutput |
||||
) |
||||
{ |
||||
await SetupVenv(installedPackagePath).ConfigureAwait(false); |
||||
|
||||
void HandleConsoleOutput(ProcessOutput s) |
||||
{ |
||||
onConsoleOutput?.Invoke(s); |
||||
|
||||
if (!s.Text.Contains("Running on", StringComparison.OrdinalIgnoreCase)) |
||||
return; |
||||
|
||||
var regex = new Regex(@"(https?:\/\/)([^:\s]+):(\d+)"); |
||||
var match = regex.Match(s.Text); |
||||
if (!match.Success) |
||||
return; |
||||
|
||||
WebUrl = match.Value; |
||||
OnStartupComplete(WebUrl); |
||||
} |
||||
|
||||
var args = $"\"{Path.Combine(installedPackagePath, command)}\" {arguments}"; |
||||
|
||||
VenvRunner.RunDetached(args.TrimEnd(), HandleConsoleOutput, OnExit); |
||||
} |
||||
} |
@ -0,0 +1,267 @@
|
||||
using System.Diagnostics.CodeAnalysis; |
||||
using System.Text.Json.Nodes; |
||||
using System.Text.RegularExpressions; |
||||
using NLog; |
||||
using StabilityMatrix.Core.Helper; |
||||
using StabilityMatrix.Core.Helper.Cache; |
||||
using StabilityMatrix.Core.Models.FileInterfaces; |
||||
using StabilityMatrix.Core.Models.Progress; |
||||
using StabilityMatrix.Core.Processes; |
||||
using StabilityMatrix.Core.Python; |
||||
using StabilityMatrix.Core.Services; |
||||
|
||||
namespace StabilityMatrix.Core.Models.Packages; |
||||
|
||||
public class StableDiffusionUx : BaseGitPackage |
||||
{ |
||||
private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); |
||||
|
||||
public override string Name => "stable-diffusion-webui-ux"; |
||||
public override string DisplayName { get; set; } = "Stable Diffusion Web UI-UX"; |
||||
public override string Author => "anapnoe"; |
||||
public override string LicenseType => "AGPL-3.0"; |
||||
public override string LicenseUrl => |
||||
"https://github.com/anapnoe/stable-diffusion-webui-ux/blob/master/LICENSE.txt"; |
||||
public override string Blurb => |
||||
"A pixel perfect design, mobile friendly, customizable interface that adds accessibility, " |
||||
+ "ease of use and extended functionallity to the stable diffusion web ui."; |
||||
public override string LaunchCommand => "launch.py"; |
||||
public override Uri PreviewImageUri => |
||||
new( |
||||
"https://user-images.githubusercontent.com/124302297/227973574-6003142d-0c7c-41c6-9966-0792a94549e9.png" |
||||
); |
||||
|
||||
public override SharedFolderMethod RecommendedSharedFolderMethod => SharedFolderMethod.Symlink; |
||||
|
||||
public StableDiffusionUx( |
||||
IGithubApiCache githubApi, |
||||
ISettingsManager settingsManager, |
||||
IDownloadService downloadService, |
||||
IPrerequisiteHelper prerequisiteHelper |
||||
) |
||||
: base(githubApi, settingsManager, downloadService, prerequisiteHelper) { } |
||||
|
||||
public override Dictionary<SharedFolderType, IReadOnlyList<string>> SharedFolders => |
||||
new() |
||||
{ |
||||
[SharedFolderType.StableDiffusion] = new[] { "models/Stable-diffusion" }, |
||||
[SharedFolderType.ESRGAN] = new[] { "models/ESRGAN" }, |
||||
[SharedFolderType.RealESRGAN] = new[] { "models/RealESRGAN" }, |
||||
[SharedFolderType.SwinIR] = new[] { "models/SwinIR" }, |
||||
[SharedFolderType.Lora] = new[] { "models/Lora" }, |
||||
[SharedFolderType.LyCORIS] = new[] { "models/LyCORIS" }, |
||||
[SharedFolderType.ApproxVAE] = new[] { "models/VAE-approx" }, |
||||
[SharedFolderType.VAE] = new[] { "models/VAE" }, |
||||
[SharedFolderType.DeepDanbooru] = new[] { "models/deepbooru" }, |
||||
[SharedFolderType.Karlo] = new[] { "models/karlo" }, |
||||
[SharedFolderType.TextualInversion] = new[] { "embeddings" }, |
||||
[SharedFolderType.Hypernetwork] = new[] { "models/hypernetworks" }, |
||||
[SharedFolderType.ControlNet] = new[] { "models/ControlNet" }, |
||||
[SharedFolderType.Codeformer] = new[] { "models/Codeformer" }, |
||||
[SharedFolderType.LDSR] = new[] { "models/LDSR" }, |
||||
[SharedFolderType.AfterDetailer] = new[] { "models/adetailer" } |
||||
}; |
||||
|
||||
public override Dictionary<SharedOutputType, IReadOnlyList<string>>? SharedOutputFolders => |
||||
new() |
||||
{ |
||||
[SharedOutputType.Extras] = new[] { "outputs/extras-images" }, |
||||
[SharedOutputType.Saved] = new[] { "log/images" }, |
||||
[SharedOutputType.Img2Img] = new[] { "outputs/img2img-images" }, |
||||
[SharedOutputType.Text2Img] = new[] { "outputs/txt2img-images" }, |
||||
[SharedOutputType.Img2ImgGrids] = new[] { "outputs/img2img-grids" }, |
||||
[SharedOutputType.Text2ImgGrids] = new[] { "outputs/txt2img-grids" } |
||||
}; |
||||
|
||||
[SuppressMessage("ReSharper", "ArrangeObjectCreationWhenTypeNotEvident")] |
||||
public override List<LaunchOptionDefinition> LaunchOptions => |
||||
new() |
||||
{ |
||||
new() |
||||
{ |
||||
Name = "Host", |
||||
Type = LaunchOptionType.String, |
||||
DefaultValue = "localhost", |
||||
Options = new() { "--server-name" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "Port", |
||||
Type = LaunchOptionType.String, |
||||
DefaultValue = "7860", |
||||
Options = new() { "--port" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "VRAM", |
||||
Type = LaunchOptionType.Bool, |
||||
InitialValue = HardwareHelper |
||||
.IterGpuInfo() |
||||
.Select(gpu => gpu.MemoryLevel) |
||||
.Max() switch |
||||
{ |
||||
Level.Low => "--lowvram", |
||||
Level.Medium => "--medvram", |
||||
_ => null |
||||
}, |
||||
Options = new() { "--lowvram", "--medvram", "--medvram-sdxl" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "Xformers", |
||||
Type = LaunchOptionType.Bool, |
||||
InitialValue = HardwareHelper.HasNvidiaGpu(), |
||||
Options = new() { "--xformers" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "API", |
||||
Type = LaunchOptionType.Bool, |
||||
InitialValue = true, |
||||
Options = new() { "--api" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "Auto Launch Web UI", |
||||
Type = LaunchOptionType.Bool, |
||||
InitialValue = false, |
||||
Options = new() { "--autolaunch" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "Skip Torch CUDA Check", |
||||
Type = LaunchOptionType.Bool, |
||||
InitialValue = !HardwareHelper.HasNvidiaGpu(), |
||||
Options = new() { "--skip-torch-cuda-test" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "Skip Python Version Check", |
||||
Type = LaunchOptionType.Bool, |
||||
InitialValue = true, |
||||
Options = new() { "--skip-python-version-check" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "No Half", |
||||
Type = LaunchOptionType.Bool, |
||||
Description = "Do not switch the model to 16-bit floats", |
||||
InitialValue = HardwareHelper.HasAmdGpu(), |
||||
Options = new() { "--no-half" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "Skip SD Model Download", |
||||
Type = LaunchOptionType.Bool, |
||||
InitialValue = false, |
||||
Options = new() { "--no-download-sd-model" } |
||||
}, |
||||
new() |
||||
{ |
||||
Name = "Skip Install", |
||||
Type = LaunchOptionType.Bool, |
||||
Options = new() { "--skip-install" } |
||||
}, |
||||
LaunchOptionDefinition.Extras |
||||
}; |
||||
|
||||
public override IEnumerable<SharedFolderMethod> AvailableSharedFolderMethods => |
||||
new[] { SharedFolderMethod.Symlink, SharedFolderMethod.None }; |
||||
|
||||
public override IEnumerable<TorchVersion> AvailableTorchVersions => |
||||
new[] { TorchVersion.Cpu, TorchVersion.Cuda, TorchVersion.Rocm }; |
||||
|
||||
public override Task<string> GetLatestVersion() => Task.FromResult("master"); |
||||
|
||||
public override bool ShouldIgnoreReleases => true; |
||||
|
||||
public override string OutputFolderName => "outputs"; |
||||
|
||||
public override async Task InstallPackage( |
||||
string installLocation, |
||||
TorchVersion torchVersion, |
||||
DownloadPackageVersionOptions versionOptions, |
||||
IProgress<ProgressReport>? progress = null, |
||||
Action<ProcessOutput>? onConsoleOutput = null |
||||
) |
||||
{ |
||||
progress?.Report(new ProgressReport(-1f, "Setting up venv", isIndeterminate: true)); |
||||
// Setup venv |
||||
await using var venvRunner = new PyVenvRunner(Path.Combine(installLocation, "venv")); |
||||
venvRunner.WorkingDirectory = installLocation; |
||||
await venvRunner.Setup(true, onConsoleOutput).ConfigureAwait(false); |
||||
|
||||
switch (torchVersion) |
||||
{ |
||||
case TorchVersion.Cpu: |
||||
await InstallCpuTorch(venvRunner, progress, onConsoleOutput).ConfigureAwait(false); |
||||
break; |
||||
case TorchVersion.Cuda: |
||||
await InstallCudaTorch(venvRunner, progress, onConsoleOutput).ConfigureAwait(false); |
||||
break; |
||||
case TorchVersion.Rocm: |
||||
await InstallRocmTorch(venvRunner, progress, onConsoleOutput).ConfigureAwait(false); |
||||
break; |
||||
} |
||||
|
||||
// Install requirements file |
||||
progress?.Report( |
||||
new ProgressReport(-1f, "Installing Package Requirements", isIndeterminate: true) |
||||
); |
||||
Logger.Info("Installing requirements_versions.txt"); |
||||
|
||||
var requirements = new FilePath(installLocation, "requirements_versions.txt"); |
||||
await venvRunner |
||||
.PipInstallFromRequirements(requirements, onConsoleOutput, excludes: "torch") |
||||
.ConfigureAwait(false); |
||||
|
||||
progress?.Report(new ProgressReport(1f, "Install complete", isIndeterminate: false)); |
||||
} |
||||
|
||||
public override async Task RunPackage( |
||||
string installedPackagePath, |
||||
string command, |
||||
string arguments, |
||||
Action<ProcessOutput>? onConsoleOutput |
||||
) |
||||
{ |
||||
await SetupVenv(installedPackagePath).ConfigureAwait(false); |
||||
|
||||
void HandleConsoleOutput(ProcessOutput s) |
||||
{ |
||||
onConsoleOutput?.Invoke(s); |
||||
|
||||
if (!s.Text.Contains("Running on", StringComparison.OrdinalIgnoreCase)) |
||||
return; |
||||
|
||||
var regex = new Regex(@"(https?:\/\/)([^:\s]+):(\d+)"); |
||||
var match = regex.Match(s.Text); |
||||
if (!match.Success) |
||||
return; |
||||
|
||||
WebUrl = match.Value; |
||||
OnStartupComplete(WebUrl); |
||||
} |
||||
|
||||
var args = $"\"{Path.Combine(installedPackagePath, command)}\" {arguments}"; |
||||
|
||||
VenvRunner.RunDetached(args.TrimEnd(), HandleConsoleOutput, OnExit); |
||||
} |
||||
|
||||
private async Task InstallRocmTorch( |
||||
PyVenvRunner venvRunner, |
||||
IProgress<ProgressReport>? progress = null, |
||||
Action<ProcessOutput>? onConsoleOutput = null |
||||
) |
||||
{ |
||||
progress?.Report( |
||||
new ProgressReport(-1f, "Installing PyTorch for ROCm", isIndeterminate: true) |
||||
); |
||||
|
||||
await venvRunner.PipInstall("--upgrade pip wheel", onConsoleOutput).ConfigureAwait(false); |
||||
|
||||
await venvRunner |
||||
.PipInstall(PyVenvRunner.TorchPipInstallArgsRocm511, onConsoleOutput) |
||||
.ConfigureAwait(false); |
||||
} |
||||
} |
@ -0,0 +1,12 @@
|
||||
namespace StabilityMatrix.Core.Models; |
||||
|
||||
public enum SharedOutputType |
||||
{ |
||||
All, |
||||
Text2Img, |
||||
Img2Img, |
||||
Extras, |
||||
Text2ImgGrids, |
||||
Img2ImgGrids, |
||||
Saved |
||||
} |
@ -0,0 +1,28 @@
|
||||
using System.ComponentModel.DataAnnotations; |
||||
using StabilityMatrix.Avalonia.Models.Inference; |
||||
|
||||
namespace StabilityMatrix.Tests.Avalonia; |
||||
|
||||
[TestClass] |
||||
public class FileNameFormatProviderTests |
||||
{ |
||||
[TestMethod] |
||||
public void TestFileNameFormatProviderValidate_Valid_ShouldNotThrow() |
||||
{ |
||||
var provider = new FileNameFormatProvider(); |
||||
|
||||
var result = provider.Validate("{date}_{time}-{model_name}-{seed}"); |
||||
Assert.AreEqual(ValidationResult.Success, result); |
||||
} |
||||
|
||||
[TestMethod] |
||||
public void TestFileNameFormatProviderValidate_Invalid_ShouldThrow() |
||||
{ |
||||
var provider = new FileNameFormatProvider(); |
||||
|
||||
var result = provider.Validate("{date}_{time}-{model_name}-{seed}-{invalid}"); |
||||
Assert.AreNotEqual(ValidationResult.Success, result); |
||||
|
||||
Assert.AreEqual("Unknown variable 'invalid'", result.ErrorMessage); |
||||
} |
||||
} |
@ -0,0 +1,24 @@
|
||||
using StabilityMatrix.Avalonia.Models; |
||||
using StabilityMatrix.Avalonia.Models.Inference; |
||||
using StabilityMatrix.Core.Models; |
||||
|
||||
namespace StabilityMatrix.Tests.Avalonia; |
||||
|
||||
[TestClass] |
||||
public class FileNameFormatTests |
||||
{ |
||||
[TestMethod] |
||||
public void TestFileNameFormatParse() |
||||
{ |
||||
var provider = new FileNameFormatProvider |
||||
{ |
||||
GenerationParameters = new GenerationParameters { Seed = 123 }, |
||||
ProjectName = "uwu", |
||||
ProjectType = InferenceProjectType.TextToImage, |
||||
}; |
||||
|
||||
var format = FileNameFormat.Parse("{project_type} - {project_name} ({seed})", provider); |
||||
|
||||
Assert.AreEqual("TextToImage - uwu (123)", format.GetFileName()); |
||||
} |
||||
} |
Loading…
Reference in new issue