You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
257 lines
9.3 KiB
257 lines
9.3 KiB
1 year ago
|
using System;
|
||
|
using System.Collections.Generic;
|
||
1 year ago
|
using System.Collections.ObjectModel;
|
||
1 year ago
|
using System.Diagnostics;
|
||
1 year ago
|
using System.IO;
|
||
|
using System.Linq;
|
||
1 year ago
|
using System.Threading.Tasks;
|
||
1 year ago
|
using Avalonia.Data;
|
||
1 year ago
|
using CommunityToolkit.Mvvm.ComponentModel;
|
||
|
using CommunityToolkit.Mvvm.Input;
|
||
1 year ago
|
using FluentAvalonia.UI.Controls;
|
||
1 year ago
|
using NLog;
|
||
1 year ago
|
using StabilityMatrix.Avalonia.ViewModels.Base;
|
||
1 year ago
|
using StabilityMatrix.Core.Extensions;
|
||
|
using StabilityMatrix.Core.Helper;
|
||
1 year ago
|
using StabilityMatrix.Core.Models;
|
||
1 year ago
|
using StabilityMatrix.Core.Models.Progress;
|
||
1 year ago
|
using StabilityMatrix.Core.Processes;
|
||
1 year ago
|
|
||
1 year ago
|
namespace StabilityMatrix.Avalonia.ViewModels.CheckpointManager;
|
||
1 year ago
|
|
||
1 year ago
|
public partial class CheckpointFile : ViewModelBase
|
||
1 year ago
|
{
|
||
1 year ago
|
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
|
||
|
|
||
1 year ago
|
/// <summary>
|
||
|
/// Absolute path to the checkpoint file.
|
||
|
/// </summary>
|
||
1 year ago
|
[ObservableProperty, NotifyPropertyChangedFor(nameof(FileName))]
|
||
1 year ago
|
private string filePath = string.Empty;
|
||
1 year ago
|
|
||
1 year ago
|
/// <summary>
|
||
|
/// Custom title for UI.
|
||
|
/// </summary>
|
||
1 year ago
|
[ObservableProperty]
|
||
|
private string title = string.Empty;
|
||
1 year ago
|
|
||
|
/// <summary>
|
||
|
/// Path to preview image. Can be local or remote URL.
|
||
|
/// </summary>
|
||
|
[ObservableProperty]
|
||
|
private string? previewImagePath;
|
||
1 year ago
|
|
||
1 year ago
|
[ObservableProperty]
|
||
|
private ConnectedModelInfo? connectedModel;
|
||
1 year ago
|
public bool IsConnectedModel => ConnectedModel != null;
|
||
|
|
||
|
[ObservableProperty] private bool isLoading;
|
||
1 year ago
|
|
||
1 year ago
|
public string FileName => Path.GetFileName((string?) FilePath);
|
||
1 year ago
|
|
||
1 year ago
|
public ObservableCollection<string> Badges { get; set; } = new();
|
||
|
|
||
1 year ago
|
private static readonly string[] SupportedCheckpointExtensions = { ".safetensors", ".pt", ".ckpt", ".pth", "bin" };
|
||
1 year ago
|
private static readonly string[] SupportedImageExtensions = { ".png", ".jpg", ".jpeg" };
|
||
1 year ago
|
private static readonly string[] SupportedMetadataExtensions = { ".json" };
|
||
1 year ago
|
|
||
1 year ago
|
partial void OnConnectedModelChanged(ConnectedModelInfo? value)
|
||
|
{
|
||
|
// Update title, first check user defined, then connected model name
|
||
1 year ago
|
Title = value?.UserTitle ?? value?.ModelName ?? string.Empty;
|
||
|
// Update badges
|
||
|
Badges.Clear();
|
||
1 year ago
|
var fpType = value?.FileMetadata.Fp?.GetStringValue().ToUpperInvariant();
|
||
1 year ago
|
if (fpType != null)
|
||
|
{
|
||
|
Badges.Add(fpType);
|
||
|
}
|
||
1 year ago
|
if (!string.IsNullOrWhiteSpace(value?.BaseModel))
|
||
1 year ago
|
{
|
||
|
Badges.Add(value.BaseModel);
|
||
|
}
|
||
1 year ago
|
}
|
||
|
|
||
1 year ago
|
private string GetConnectedModelInfoFilePath()
|
||
|
{
|
||
|
if (string.IsNullOrEmpty(FilePath))
|
||
|
{
|
||
|
throw new InvalidOperationException(
|
||
|
"Cannot get connected model info file path when FilePath is empty");
|
||
|
}
|
||
1 year ago
|
var modelNameNoExt = Path.GetFileNameWithoutExtension((string?) FilePath);
|
||
|
var modelDir = Path.GetDirectoryName((string?) FilePath) ?? "";
|
||
1 year ago
|
return Path.Combine(modelDir, $"{modelNameNoExt}.cm-info.json");
|
||
|
}
|
||
|
|
||
1 year ago
|
[RelayCommand]
|
||
1 year ago
|
private async Task DeleteAsync()
|
||
1 year ago
|
{
|
||
|
if (File.Exists(FilePath))
|
||
|
{
|
||
1 year ago
|
IsLoading = true;
|
||
|
try
|
||
1 year ago
|
{
|
||
1 year ago
|
await using var delay = new MinimumDelay(200, 500);
|
||
1 year ago
|
await Task.Run(() => File.Delete(FilePath));
|
||
|
if (PreviewImagePath != null && File.Exists(PreviewImagePath))
|
||
|
{
|
||
|
await Task.Run(() => File.Delete(PreviewImagePath));
|
||
|
}
|
||
1 year ago
|
if (ConnectedModel != null)
|
||
|
{
|
||
|
var cmInfoPath = GetConnectedModelInfoFilePath();
|
||
|
if (File.Exists(cmInfoPath))
|
||
|
{
|
||
|
await Task.Run(() => File.Delete(cmInfoPath));
|
||
|
}
|
||
|
}
|
||
1 year ago
|
}
|
||
1 year ago
|
catch (IOException ex)
|
||
1 year ago
|
{
|
||
1 year ago
|
Logger.Warn($"Failed to delete checkpoint file {FilePath}: {ex.Message}");
|
||
1 year ago
|
return; // Don't delete from collection
|
||
|
}
|
||
1 year ago
|
finally
|
||
|
{
|
||
|
IsLoading = false;
|
||
|
}
|
||
1 year ago
|
}
|
||
1 year ago
|
RemoveFromParentList();
|
||
1 year ago
|
}
|
||
|
|
||
|
[RelayCommand]
|
||
|
private async Task RenameAsync()
|
||
|
{
|
||
1 year ago
|
// Parent folder path
|
||
1 year ago
|
var parentPath = Path.GetDirectoryName((string?) FilePath) ?? "";
|
||
1 year ago
|
|
||
|
var textFields = new TextBoxField[]
|
||
|
{
|
||
|
new()
|
||
|
{
|
||
|
Label = "File name",
|
||
|
Validator = text =>
|
||
|
{
|
||
|
if (string.IsNullOrWhiteSpace(text)) throw new
|
||
|
DataValidationException("File name is required");
|
||
|
|
||
|
if (File.Exists(Path.Combine(parentPath, text))) throw new
|
||
|
DataValidationException("File name already exists");
|
||
1 year ago
|
},
|
||
|
Text = FileName
|
||
1 year ago
|
}
|
||
|
};
|
||
|
|
||
|
var dialog = DialogHelper.CreateTextEntryDialog("Rename Model", "", textFields);
|
||
1 year ago
|
|
||
1 year ago
|
if (await dialog.ShowAsync() == ContentDialogResult.Primary)
|
||
|
{
|
||
|
var name = textFields[0].Text;
|
||
1 year ago
|
var nameNoExt = Path.GetFileNameWithoutExtension(name);
|
||
|
var originalNameNoExt = Path.GetFileNameWithoutExtension(FileName);
|
||
1 year ago
|
// Rename file in OS
|
||
|
try
|
||
|
{
|
||
|
var newFilePath = Path.Combine(parentPath, name);
|
||
|
File.Move(FilePath, newFilePath);
|
||
|
FilePath = newFilePath;
|
||
1 year ago
|
// If preview image exists, rename it too
|
||
|
if (PreviewImagePath != null && File.Exists(PreviewImagePath))
|
||
|
{
|
||
1 year ago
|
var newPreviewImagePath = Path.Combine(parentPath, $"{nameNoExt}.preview{Path.GetExtension((string?) PreviewImagePath)}");
|
||
1 year ago
|
File.Move(PreviewImagePath, newPreviewImagePath);
|
||
|
PreviewImagePath = newPreviewImagePath;
|
||
|
}
|
||
|
// If connected model info exists, rename it too (<name>.cm-info.json)
|
||
|
if (ConnectedModel != null)
|
||
|
{
|
||
|
var cmInfoPath = Path.Combine(parentPath, $"{originalNameNoExt}.cm-info.json");
|
||
|
if (File.Exists(cmInfoPath))
|
||
|
{
|
||
|
File.Move(cmInfoPath, Path.Combine(parentPath, $"{nameNoExt}.cm-info.json"));
|
||
|
}
|
||
|
}
|
||
1 year ago
|
}
|
||
|
catch (Exception e)
|
||
|
{
|
||
|
Logger.Warn(e, $"Failed to rename checkpoint file {FilePath}");
|
||
|
}
|
||
|
}
|
||
1 year ago
|
}
|
||
1 year ago
|
|
||
|
[RelayCommand]
|
||
|
private void OpenOnCivitAi()
|
||
|
{
|
||
1 year ago
|
if (ConnectedModel?.ModelId == null) return;
|
||
1 year ago
|
ProcessRunner.OpenUrl($"https://civitai.com/models/{ConnectedModel.ModelId}");
|
||
|
}
|
||
1 year ago
|
|
||
|
/// <summary>
|
||
|
/// Indexes directory and yields all checkpoint files.
|
||
|
/// First we match all files with supported extensions.
|
||
|
/// If found, we also look for
|
||
1 year ago
|
/// - {filename}.preview.{image-extensions} (preview image)
|
||
|
/// - {filename}.cm-info.json (connected model info)
|
||
1 year ago
|
/// </summary>
|
||
1 year ago
|
public static IEnumerable<CheckpointFile> FromDirectoryIndex(string directory, SearchOption searchOption = SearchOption.TopDirectoryOnly)
|
||
1 year ago
|
{
|
||
|
// Get all files with supported extensions
|
||
1 year ago
|
var allExtensions = SupportedCheckpointExtensions
|
||
|
.Concat(SupportedImageExtensions)
|
||
1 year ago
|
.Concat(SupportedMetadataExtensions);
|
||
1 year ago
|
|
||
|
var files = allExtensions.AsParallel()
|
||
|
.SelectMany(pattern => Directory.EnumerateFiles(directory, $"*{pattern}", searchOption)).ToDictionary<string, string>(Path.GetFileName);
|
||
|
|
||
|
foreach (var file in files.Keys.Where(k => SupportedCheckpointExtensions.Contains(Path.GetExtension(k))))
|
||
|
{
|
||
1 year ago
|
var checkpointFile = new CheckpointFile()
|
||
1 year ago
|
{
|
||
|
Title = Path.GetFileNameWithoutExtension(file),
|
||
|
FilePath = Path.Combine(directory, file),
|
||
|
};
|
||
1 year ago
|
|
||
|
// Check for connected model info
|
||
|
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
|
||
|
var cmInfoPath = $"{fileNameWithoutExtension}.cm-info.json";
|
||
1 year ago
|
if (files.TryGetValue(cmInfoPath, out var jsonPath))
|
||
1 year ago
|
{
|
||
|
try
|
||
|
{
|
||
1 year ago
|
var jsonData = File.ReadAllText(jsonPath);
|
||
1 year ago
|
checkpointFile.ConnectedModel = ConnectedModelInfo.FromJson(jsonData);
|
||
|
}
|
||
|
catch (IOException e)
|
||
|
{
|
||
|
Debug.WriteLine($"Failed to parse {cmInfoPath}: {e}");
|
||
|
}
|
||
|
}
|
||
1 year ago
|
|
||
|
// Check for preview image
|
||
1 year ago
|
var previewImage = SupportedImageExtensions.Select(ext => $"{fileNameWithoutExtension}.preview{ext}").FirstOrDefault(files.ContainsKey);
|
||
1 year ago
|
if (previewImage != null)
|
||
|
{
|
||
1 year ago
|
checkpointFile.PreviewImagePath = files[previewImage];
|
||
1 year ago
|
}
|
||
|
|
||
|
yield return checkpointFile;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/// <summary>
|
||
|
/// Index with progress reporting.
|
||
|
/// </summary>
|
||
1 year ago
|
public static IEnumerable<CheckpointFile> FromDirectoryIndex(string directory, IProgress<ProgressReport> progress,
|
||
1 year ago
|
SearchOption searchOption = SearchOption.TopDirectoryOnly)
|
||
|
{
|
||
|
var current = 0ul;
|
||
1 year ago
|
foreach (var checkpointFile in FromDirectoryIndex(directory, searchOption))
|
||
1 year ago
|
{
|
||
|
current++;
|
||
|
progress.Report(new ProgressReport(current, "Indexing", checkpointFile.FileName));
|
||
|
yield return checkpointFile;
|
||
|
}
|
||
|
}
|
||
|
}
|