### Package Installation Flow Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/python-git-helpers.md Demonstrates a typical package installation process using various helper utilities. This includes downloading the package, extracting the archive, setting up a Python virtual environment, installing dependencies like PyTorch, and running a setup script. ```csharp var installDir = "/path/to/install"; // 1. Download package using var progress = new Progress(); await downloadService.DownloadToFileAsync(downloadUrl, packagePath, progress); // 2. Extract archive await ArchiveHelper.ExtractAsync(packagePath, installDir, progress); // 3. Setup Python venv await PyInstallationManager.SetupVenv(installDir, pythonVersion); // 4. Install dependencies var venvPath = Path.Combine(installDir, "venv"); await pipService.InstallAsync( packages: new[] { "torch", "torchvision" }, venvPath: venvPath, index: PyTorchIndex.Cuda118, progress: progress); // 5. Run setup script await ProcessRunner.RunAsync( fileName: Path.Combine(venvPath, "python"), arguments: "install.py", workingDirectory: installDir); // 6. Save metadata package.Version = new InstalledPackageVersion { InstalledReleaseVersion = releaseVersion, InstalledCommitSha = gitSha }; ``` -------------------------------- ### Setup Output Folder Links Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Configures output folder sharing. Requires the package installation directory. ```csharp public abstract Task SetupOutputFolderLinks(DirectoryPath installDirectory) ``` -------------------------------- ### Package Management Operations Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/README.md Illustrates how to get, download, install, and run packages using the package manager. ```csharp // Get a package definition BasePackage package = packageManager.GetPackage("comfyui"); // Download package await package.DownloadPackage( installLocation: "/path/to/install", options: new DownloadPackageOptions { VersionTag = "v1.0.0" }, progress: progressReporter); // Install package await package.InstallPackage( installLocation: "/path/to/install", installedPackage: packageInfo, options: new InstallPackageOptions(), onConsoleOutput: output => logger.Log(output.Text)); // Run package await package.RunPackage( installLocation: "/path/to/install", installedPackage: packageInfo, options: new RunPackageOptions { LaunchArgs = args }); ``` -------------------------------- ### CivitModel Example Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/api-models.md Demonstrates the creation of a CivitModel object with basic properties. ```csharp var model = new CivitModel { Id = 12345, Name = "Example Model", Type = CivitModelType.Checkpoint, Creator = new CivitCreator { Username = "artist" } }; ``` -------------------------------- ### Install Package Files Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Installs or extracts package files after they have been downloaded. Allows for progress reporting, console output handling, and cancellation. ```csharp public abstract Task InstallPackage( string installLocation, InstalledPackage installedPackage, InstallPackageOptions options, IProgress? progress = null, Action? onConsoleOutput = null, CancellationToken cancellationToken = default) ``` -------------------------------- ### Get Version Information Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/README.md Shows how to access the current application version and the installed version of a package. ```csharp var currentVersion = GlobalConfig.Version; var installed = package.Version.InstalledReleaseVersion; ``` -------------------------------- ### Setup Model Folders Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Configures shared model folder connections. Requires the package installation directory and the method for shared folder management (Symlink or Configuration). ```csharp public abstract Task SetupModelFolders( DirectoryPath installDirectory, SharedFolderMethod sharedFolderMethod) ``` -------------------------------- ### Install Husky.Net and Pre-commit Hooks Source: https://github.com/lykosai/stabilitymatrix/blob/main/CONTRIBUTING.md Restore .NET tools and install Husky.Net pre-commit hooks. This can be done after building the project or by running this command directly. ```bash dotnet tool restore && dotnet husky install ``` -------------------------------- ### Example ProgressReport Initialization Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/models.md An example demonstrating how to initialize a ProgressReport with specific properties like current, total, title, message, type, and speed. ```csharp var progress = new ProgressReport( current: 512, total: 1024, title: "Download", message: "512 KB of 1 MB", type: ProgressType.Download, speedInMBps: 5.2); ``` -------------------------------- ### Run Installed Package Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Executes an installed package with specified options. Supports console output handling and cancellation. ```csharp public abstract Task RunPackage( string installLocation, InstalledPackage installedPackage, RunPackageOptions options, Action? onConsoleOutput = null, CancellationToken cancellationToken = default) ``` -------------------------------- ### Install Husky Pre-commit Hooks Source: https://github.com/lykosai/stabilitymatrix/blob/main/CONTRIBUTING.md Install Husky pre-commit hooks. This command ensures that the project's pre-commit hooks are set up. ```bash dotnet husky install ``` -------------------------------- ### Create InstalledPackageVersion Instance Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/models.md Example of creating an InstalledPackageVersion object and accessing its DisplayVersion property. Useful for initializing version information. ```csharp var version = new InstalledPackageVersion { InstalledReleaseVersion = "v2.1.0", IsPrerelease = false }; var display = version.DisplayVersion; // "v2.1.0" ``` -------------------------------- ### Example: Using ParseImageMetadata Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/inference-models.md Demonstrates how to use the ParseImageMetadata method to retrieve and display generation parameters from an image file. ```csharp var parameters = GenerationParameters.ParseImageMetadata("output.png"); if (parameters != null) { Console.WriteLine($"Model: {parameters.Model}"); Console.WriteLine($"Prompt: {parameters.Prompt}"); Console.WriteLine($"Seed: {parameters.Seed}"); } ``` -------------------------------- ### RunPackage Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Executes the installed package with specified options. Supports console output handling and cancellation. ```APIDOC ## RunPackage ### Description Execute the installed package with specified options. ### Method `public abstract Task RunPackage(...)` ### Parameters #### Path Parameters - `installLocation` (string) - Required - The directory where the package is installed #### Query Parameters - `installedPackage` (InstalledPackage) - Required - The package to run - `options` (RunPackageOptions) - Required - Options for running the package - `onConsoleOutput` (Action) - Optional - Console output handler - `cancellationToken` (CancellationToken) - Optional - Cancellation token ``` -------------------------------- ### Example .smproj JSON Structure Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/inference-models.md Illustrates the structure of a .smproj file, including project details, workflow definition, and default generation parameters. ```json { "projectId": "550e8400-e29b-41d4-a716-446655440000", "name": "My Artwork", "projectType": "ComfyUI", "createdAt": "2024-06-01T12:00:00Z", "modifiedAt": "2024-06-07T15:30:00Z", "workflow": { "1": { "class_type": "CheckpointLoader", "inputs": {"ckpt_name": "model.safetensors"} }, "2": { "class_type": "KSampler", "inputs": {"seed": 12345, "steps": 20} } }, "defaults": { "sampler": "euler", "scheduler": "normal", "steps": 20, "guidance": 7.5 } } ``` -------------------------------- ### Download Progress Reporting Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/notifications.md Example of how to report download progress, showing current and total bytes downloaded, and speed. ```csharp var progress = new Progress(report => { Console.WriteLine($"Downloaded {report.Current}/{report.Total} bytes"); Console.WriteLine($"Speed: {report.SpeedInMBps} MB/s"); }); await downloadService.DownloadToFileAsync( url, filePath, progress ); ``` -------------------------------- ### InstallPackageOptions Class Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Configuration options for installing packages. Includes fields for version tag and skipping dependencies. ```csharp public class InstallPackageOptions { public string VersionTag { get; set; } public bool SkipDependencies { get; set; } // ... additional options } ``` -------------------------------- ### Build ComfyUI KSampler Node with Connections Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/inference-models.md Example of creating a KSampler node, connecting it to a previous node, and setting input parameters. ```csharp var sampler = new ComfyNodeBuilder("KSampler") .WithConnection("model", checkpointLoader, 0) .WithInput("seed", 12345) .WithInput("steps", 20) .WithInput("cfg", 7.5) .Build(); ``` -------------------------------- ### File-scoped Namespace Example Source: https://github.com/lykosai/stabilitymatrix/blob/main/CONTRIBUTING.md Demonstrates the use of file-scoped namespaces in C#. ```csharp using System; namespace X.Y.Z; class Foo { } ``` -------------------------------- ### Define Shared Folder Setup Methods Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/models.md Enumeration for methods used to set up shared model folders, including None, Symlink, and Configuration. ```csharp public enum SharedFolderMethod { None, // No sharing Symlink, // Symbolic links Configuration, // Configuration-based sharing // ... and more } ``` -------------------------------- ### Install Pip Packages Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/python-git-helpers.md Installs Python packages using pip into a specified virtual environment, with support for custom indexes like PyTorch's CUDA-enabled indices. Progress reporting is included. ```csharp await pipService.InstallAsync( packages: new[] { "torch", "torchvision", "torchaudio" }, venvPath: venvPath, index: PyTorchIndex.Cuda118, // CUDA 11.8 index progress: progressReporter); ``` -------------------------------- ### Handle Custom Exceptions Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/README.md Demonstrates how to catch and handle specific custom exceptions like MissingPrerequisiteException, ProcessException, and AppException during package installation. ```csharp try { await package.InstallPackage(...); } catch (MissingPrerequisiteException ex) { // Handle missing dependency await notificationService.ShowError( "Missing Prerequisites", $"Please install {ex.PrerequisiteName}"); } catch (ProcessException ex) { // Handle process failure logger.Error(ex, "Process execution failed"); } catch (AppException ex) { // Handle application error await notificationService.ShowError(ex.Message, ex.Details); } ``` -------------------------------- ### InstallPackage Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Installs or extracts a downloaded package to the specified location. Supports progress reporting, console output handling, and cancellation. ```APIDOC ## InstallPackage ### Description Install/extract package after download. ### Method `public abstract Task InstallPackage(...)` ### Parameters #### Path Parameters - `installLocation` (string) - Required - Installation directory #### Query Parameters - `installedPackage` (InstalledPackage) - Required - Package configuration - `options` (InstallPackageOptions) - Required - Installation options - `progress` (IProgress) - Optional - Progress reporting - `onConsoleOutput` (Action) - Optional - Console output handler - `cancellationToken` (CancellationToken) - Optional - Cancellation token ``` -------------------------------- ### Download Package Files Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Use this method to download package files to a specified installation location. Supports progress reporting and cancellation. ```csharp public abstract Task DownloadPackage( string installLocation, DownloadPackageOptions options, IProgress? progress = null, CancellationToken cancellationToken = default) ``` -------------------------------- ### Build ComfyUI CheckpointLoader Node Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/inference-models.md Example of creating a CheckpointLoader node using the ComfyNodeBuilder fluent API. ```csharp var checkpointLoader = new ComfyNodeBuilder("CheckpointLoader") .WithInput("ckpt_name", "model.safetensors") .Build(); ``` -------------------------------- ### Execute Git Post-Install Command Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/python-git-helpers.md Retrieves and executes a post-installation command defined within a Git package, typically used for setup tasks after a package has been cloned or updated. ```csharp // Post-install setup via git hooks var postInstall = gitPackage.GetPostInstallCommand(); if (postInstall != null) { await ProcessRunner.RunAsync( fileName: postInstall.Command, arguments: postInstall.Arguments, workingDirectory: installPath); } ``` -------------------------------- ### DownloadPackage Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Downloads package files to a specified installation location. Supports progress reporting and cancellation. ```APIDOC ## DownloadPackage ### Description Download package files to installation location. ### Method `public abstract Task DownloadPackage(...)` ### Parameters #### Path Parameters - `installLocation` (string) - Required - Directory to download to #### Query Parameters - `options` (DownloadPackageOptions) - Required - Download configuration - `progress` (IProgress) - Optional - Progress reporting - `cancellationToken` (CancellationToken) - Optional - Cancellation token ``` -------------------------------- ### PackageDifficulty Enum Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Defines the difficulty levels for package installation, ranging from Easy to Expert. ```csharp public enum PackageDifficulty { Easy, // Recommended, one-click install Intermediate, // Standard installation Advanced, // Requires configuration Expert, // Manual setup recommended } ``` -------------------------------- ### InstalledPackageExtension Record Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Represents an installed extension within a package, including its name, version, and path. ```csharp public record InstalledPackageExtension { public string Name { get; set; } public string Version { get; set; } public string? Path { get; set; } } ``` -------------------------------- ### Example Notification Manifest JSON Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/notifications.md This JSON structure defines a notification with details like ID, type, priority, display dates, version constraints, localized messages, dialog content, button actions, and styling. It includes examples for both dialog and banner notification types. ```json { "version": 1, "notifications": [ { "id": "critical-update-2024-06", "type": "dialog", "priority": "critical", "startDate": "2024-06-01T00:00:00Z", "endDate": "2024-06-30T23:59:59Z", "minVersion": "1.5.0", "message": { "en": "Critical security update available", "ja": "重要なセキュリティアップデートが利用可能です" }, "dialog": { "title": { "en": "Security Update Required", "ja": "セキュリティアップデートが必要です" }, "content": { "en": "A critical security vulnerability has been discovered. Please update immediately.", "ja": "重大なセキュリティ脆弱性が発見されました。すぐに更新してください。" }, "buttons": [ { "type": "url", "url": "https://github.com/LykosAI/StabilityMatrix/releases", "label": { "en": "Download Update", "ja": "アップデートをダウンロード" }, "style": "primary", "dismissOnClick": false } ] }, "style": { "variant": "warning" }, "dismissible": false, "requireSetupComplete": false }, { "id": "model-browser-announcement", "type": "banner", "priority": "normal", "startDate": "2024-06-15T00:00:00Z", "message": { "en": "New model browser features available!", "ja": "新しいモデルブラウザー機能が利用可能です!" }, "action": { "type": "url", "url": "https://docs.example.com/new-browser-features", "label": { "en": "Learn More", "ja": "詳細を表示" } }, "style": { "variant": "success" }, "dismissible": true } ] } ``` -------------------------------- ### Save Package Launch Arguments Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/services.md Store the launch options associated with a specific package. This is used to configure how a package should be started. ```csharp void SaveLaunchArgs(Guid packageId, IEnumerable launchArgs) ``` -------------------------------- ### Setup Python Virtual Environment Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/python-git-helpers.md Sets up a Python virtual environment for a package using a specified Python version. This is useful for isolating package dependencies. ```csharp await PyInstallationManager.SetupVenv( installDir: "/path/to/package", pythonVersion: PyInstallationManager.Python_3_10_11); var venvPath = Path.Combine(installDir, "venv"); await ProcessRunner.RunAsync( fileName: venvPath + "/bin/python", arguments: "-m pip install -r requirements.txt"); ``` -------------------------------- ### Execute Process and Forget Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/python-git-helpers.md Starts a process and does not wait for it to complete. Use this for background tasks where immediate feedback is not required. ```csharp // Fire and forget ProcessRunner.Fire("command.exe"); ``` -------------------------------- ### Build Linux AppImage for Release Source: https://github.com/lykosai/stabilitymatrix/blob/main/CONTRIBUTING.md Build the Linux application as an AppImage for release. This involves installing dependencies, a .NET tool, and then running the build command. ```bash sudo apt-get -y install libfuse2 dotnet tool install -g KuiperZone.PupNet pupnet -r linux-x64 -c Release --kind appimage --app-version $RELEASE_VERSION --clean ``` -------------------------------- ### Exception Handling Pattern Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/exceptions.md Demonstrates a robust exception handling pattern for package installation. It catches specific exceptions like MissingPrerequisiteException and ProcessException, as well as generic AppException and unexpected Exceptions. ```csharp try { // Attempt operation await packageManager.InstallAsync(package, options, progress); } catch (MissingPrerequisiteException ex) { // Handle missing dependency - guide user to install it await notificationService.ShowAsync( new AppNotification { Title = "Missing Prerequisites", Message = ex.Message, Type = AppNotificationType.Dialog }); } catch (ProcessException ex) { // Handle process failure - show console output logger.Error(ex, "Process failed"); } catch (AppException ex) { // Handle application-specific error - display to user await notificationService.ShowAsync( new AppNotification { Title = "Error", Message = ex.Message, Details = ex.Details }); } catch (Exception ex) { // Log unexpected errors logger.Error(ex, "Unexpected error during installation"); } ``` -------------------------------- ### Get Content as Stream Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/services.md Fetches the content from a URL and returns it as a stream. Supports cancellation. ```csharp Task GetContentAsync(string url, CancellationToken cancellationToken = default) ``` -------------------------------- ### SettingsTransaction Example Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/configuration.md Demonstrates transactional modification of settings using a 'using' statement for automatic commit on disposal. Use this for applying multiple settings changes atomically. ```csharp using var transaction = settingsManager.BeginTransaction(); { transaction.Settings.SelectedTheme = "dark"; transaction.Settings.PreferredLanguage = "ja"; } // Auto-commits on dispose ``` -------------------------------- ### Read Application Settings Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/configuration.md Shows how to access the current application settings object and retrieve specific settings like the selected theme or installed packages. ```csharp var settings = settingsManager.Settings; var theme = settings.SelectedTheme; var installedPackages = settings.InstalledPackages; ``` -------------------------------- ### Create an AppNotification object Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/notifications.md Example of creating a banner notification with localized messages and an action URL. Ensure dates are in UTC. ```csharp var notification = new AppNotification { Id = "deprecation-v1-0", Type = AppNotificationType.Banner, Priority = AppNotificationPriority.High, StartDate = new DateTimeOffset(2024, 6, 1, 0, 0, 0, TimeSpan.Zero), EndDate = new DateTimeOffset(2024, 7, 1, 0, 0, 0, TimeSpan.Zero), Message = new Dictionary { { "en", "Version 1.0 will be unsupported after June 30." }, { "ja", "バージョン1.0は6月30日以降、サポートされなくなります。" } }, Action = new AppNotificationAction { Type = AppNotificationActionType.Url, Url = "https://docs.example.com/upgrade", Label = new Dictionary { { "en", "Learn More" }, { "ja", "詳細を表示" } } }, Style = new AppNotificationStyle { Variant = "warning" } }; ``` -------------------------------- ### Combined Progress Report Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/notifications.md An example of a comprehensive ProgressReport including progress percentage, counts, title, message, type, and speed. ```csharp var report = new ProgressReport( progress: 0.65, current: 650, total: 1000, title: "Download", message: "650 MB of 1 GB", type: ProgressType.Download, speedInMBps: 12.5 ); ``` -------------------------------- ### Get Extra Package Commands Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Retrieves a list of additional executable commands available for a package. This is a virtual method that can be overridden. ```csharp public virtual List GetExtraCommands() ``` -------------------------------- ### Get Launch Arguments Host Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/models.md Retrieves the host address from launch arguments. Use when needing to access the host configuration for a package. ```csharp public string? GetLaunchArgsHost() ``` ```csharp var package = new InstalledPackage { LaunchArgs = new List { ... } }; string? host = package.GetLaunchArgsHost(); ``` -------------------------------- ### Enable Portable Mode Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/services.md Activate portable mode for the application. This action creates a './Data' directory and a '.sm-portable' marker file in the current directory, allowing the application to run without a fixed installation path. ```csharp void SetPortableMode() ``` -------------------------------- ### Get Launch Arguments Port Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/models.md Retrieves the port number from launch arguments. Use when needing to access the port configuration for a package. ```csharp public string? GetLaunchArgsPort() ``` -------------------------------- ### Registering and Resolving Services with Dependency Injection Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/README.md Demonstrates setting up a ServiceCollection, registering core services, and building a service provider to resolve services. ```csharp var services = new ServiceCollection(); // Register core services services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); // ... more service registrations var serviceProvider = services.BuildServiceProvider(); // Use services var settingsManager = serviceProvider.GetRequiredService(); var downloadService = serviceProvider.GetRequiredService(); ``` -------------------------------- ### Get PyPI Package Information Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/python-git-helpers.md Queries the Python Package Index (PyPI) to retrieve information about a specific package, including its latest version and a dictionary of all available releases. ```csharp var response = await pypIService.GetPackageInfoAsync("torch"); var latestVersion = response.Info.Version; var releases = response.Releases; // Dictionary of versions ``` -------------------------------- ### ComfyUI extra_model_paths.yaml Configuration Source: https://github.com/lykosai/stabilitymatrix/wiki/FAQ-&-Troubleshooting Example of how to configure `extra_model_paths.yaml` for ComfyUI when using Stability Matrix's model sharing. Custom paths should be added outside the `stability_matrix` section. ```yaml foobar: checkpoints: C:\My\path\to\checkpoints ... etc ... stability_matrix: checkpoints: G:\SMData\Data\Data\Models\StableDiffusion vae: G:\SMData\Data\Data\Models\VAE loras: >- G:\SMData\Data\Data\Models\Lora G:\SMData\Data\Data\Models\LyCORIS upscale_models: >- G:\SMData\Data\Data\Models\ESRGAN G:\SMData\Data\Data\Models\RealESRGAN G:\SMData\Data\Data\Models\SwinIR embeddings: G:\SMData\Data\Data\Models\TextualInversion ... etc ... ``` -------------------------------- ### Query Hardware Capabilities Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/python-git-helpers.md Detects and retrieves information about the system's GPUs and RAM. Use this to check for specific GPU vendors or to get the total system memory. ```csharp // GPU detection bool hasNvidia = HardwareHelper.HasNvidiaGpu(); bool hasAmd = HardwareHelper.HasAmdGpu(); bool hasIntel = HardwareHelper.HasIntelGpu(); // Get GPU info var gpuInfo = HardwareHelper.GetGpuInfo(); // Returns: list of detected GPUs // System RAM long ramBytes = HardwareHelper.GetSystemRamBytes(); double ramGb = ramBytes / (1024.0 * 1024.0 * 1024.0); ``` -------------------------------- ### SetupOutputFolderLinks Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Configures output folder sharing. This method sets up the necessary configurations for sharing output directories. ```APIDOC ## SetupOutputFolderLinks ### Description Configure output folder sharing. ### Method ```csharp public abstract Task SetupOutputFolderLinks(DirectoryPath installDirectory) ``` ### Parameters #### Path Parameters - **installDirectory** (DirectoryPath) - Required - Package installation directory ``` -------------------------------- ### Get Recommended Torch Version Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Determines the optimal PyTorch backend for the current system based on hardware and user preferences. It prioritizes CUDA for NVIDIA, ROCm/ZLUDA for AMD, and falls back to CPU. ```csharp public virtual TorchIndex GetRecommendedTorchVersion() ``` -------------------------------- ### Update Installed Package Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Updates an installed package to its latest version. Provides progress reporting, console output handling, and cancellation support. Returns new version information. ```csharp public abstract Task Update( string installLocation, InstalledPackage installedPackage, UpdatePackageOptions options, IProgress? progress = null, Action? onConsoleOutput = null, CancellationToken cancellationToken = default) ``` -------------------------------- ### CheckForUpdates Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Checks if an update is available for an installed package. ```APIDOC ## CheckForUpdates ### Description Check if updates are available for an installed package. ### Method `public abstract Task CheckForUpdates(InstalledPackage package)` ### Parameters #### Path Parameters - `package` (InstalledPackage) - Required - The installed package to check ### Returns - `bool` - true if update available ``` -------------------------------- ### Download Management with Progress and Resumption Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/README.md Demonstrates downloading a file with progress reporting and handling OperationCanceledException to resume partial downloads. ```csharp var progress = new Progress(report => { Console.WriteLine($"Downloaded: {report.Percentage}%"); Console.WriteLine($"Speed: {report.SpeedInMBps} MB/s"); }); try { // Download new file await downloadService.DownloadToFileAsync( downloadUrl: "https://example.com/model.safetensors", downloadPath: "model.safetensors", progress: progress); } catch (OperationCanceledException) { // Resume partial download var fileInfo = new FileInfo("model.safetensors"); await downloadService.ResumeDownloadToFileAsync( downloadUrl: "https://example.com/model.safetensors", downloadPath: "model.safetensors", existingFileSize: fileInfo.Length, progress: progress); } ``` -------------------------------- ### Get Hierarchical Model Structure Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/database-models.md Retrieves the complete folder structure for organizing local models. ```csharp var folderStructure = await modelIndexService.FindAllFolders(); // folderStructure: Dictionary ``` -------------------------------- ### Check for Package Updates Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Determines if an update is available for an installed package. Returns a boolean indicating availability. ```csharp public abstract Task CheckForUpdates(InstalledPackage package) ``` -------------------------------- ### Get Image Stream from URL Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/services.md Retrieves an image from a URL as a stream. Returns null if the image is unavailable. ```csharp Task GetImageStreamFromUrl(string url) ``` -------------------------------- ### Remove Output Folder Links Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Removes output folder sharing configuration. Requires the package installation directory. ```csharp public abstract Task RemoveOutputFolderLinks(DirectoryPath installDirectory) ``` -------------------------------- ### Update Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Updates an installed package to its latest version. Supports progress reporting, console output handling, and cancellation. ```APIDOC ## Update ### Description Update an installed package to a new version. ### Method `public abstract Task Update(...)` ### Parameters #### Path Parameters - `installLocation` (string) - Required - The directory where the package is installed #### Query Parameters - `installedPackage` (InstalledPackage) - Required - The package to update - `options` (UpdatePackageOptions) - Required - Options for the update process - `progress` (IProgress) - Optional - Progress reporting - `onConsoleOutput` (Action) - Optional - Console output handler - `cancellationToken` (CancellationToken) - Optional - Cancellation token ### Returns - `InstalledPackageVersion` - New version information after update ``` -------------------------------- ### Modify and Observe Settings Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/README.md Demonstrates how to modify single or multiple settings using transactions and how to observe changes to specific settings. ```csharp // Modify a single setting settingsManager.Transaction(s => s.SelectedTheme, "dark"); // Modify multiple settings settingsManager.Transaction(s => { s.SelectedTheme = "dark"; s.PreferredLanguage = "ja"; }); // Observe changes using var subscription = settingsManager .ObservePropertyChanged(s => s.SelectedTheme) .Subscribe(newTheme => Console.WriteLine($"Theme: {newTheme}")); ``` -------------------------------- ### Throw AppException Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/exceptions.md Example of throwing a custom AppException with a message and details. This is used for application-specific errors that should be displayed to users. ```csharp throw new AppException("Failed to install package", "The GPU driver is out of date"); ``` -------------------------------- ### Observe Specific Setting Changes Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/configuration.md Demonstrates subscribing to changes of a specific setting property using Rx.NET. This is useful for reacting to individual setting updates in real-time. ```csharp // Subscribe to specific property changes using var subscription = settingsManager.ObservePropertyChanged( s => s.SelectedTheme) .Subscribe(newTheme => Console.WriteLine($"Theme changed to: {newTheme}")); ``` -------------------------------- ### Publish StabilityMatrix.Avalonia as a Single File for Release (Windows) Source: https://github.com/lykosai/stabilitymatrix/blob/main/CONTRIBUTING.md Publish the Avalonia project as a single executable file for Windows release, including native libraries and ReadyToRun compilation. ```bash dotnet publish ./StabilityMatrix.Avalonia/StabilityMatrix.Avalonia.csproj -r win-x64 -c Release -p:Version=$env:RELEASE_VERSION -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:PublishReadyToRun=true ``` -------------------------------- ### File System Utilities Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/python-git-helpers.md Provides utilities for file system operations, including calculating file hashes (Blake3), retrieving formatted file sizes, deleting directories, and creating symbolic links. ```csharp // Calculate file hash var hash = await FileHelper.CalculateBlake3Async("model.safetensors"); // Get file size with formatting var size = await FileHelper.GetFileSizeAsync("model.safetensors"); // Returns: FileSizeType with Bytes, MB, GB properties // Directory operations FileHelper.DeleteDirectory("temp_folder", recursive: true); FileHelper.CreateSymlink(targetPath, linkPath); ``` -------------------------------- ### SetupModelFolders Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Configures shared model folder connections. This method sets up the necessary directory structures and configurations for shared model storage. ```APIDOC ## SetupModelFolders ### Description Configure shared model folder connections. ### Method ```csharp public abstract Task SetupModelFolders( DirectoryPath installDirectory, SharedFolderMethod sharedFolderMethod) ``` ### Parameters #### Path Parameters - **installDirectory** (DirectoryPath) - Required - Package installation directory - **sharedFolderMethod** (SharedFolderMethod) - Required - Method to use (Symlink/Configuration) ``` -------------------------------- ### Handle Progress Reports Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/README.md Illustrates how to use the Progress class to report and display both indeterminate and determinate progress during asynchronous operations like file downloads. ```csharp var progress = new Progress(report => { if (report.IsIndeterminate) { // Indeterminate progress statusLabel.Text = report.Title; } else { // Determinate progress progressBar.Value = (int)report.Percentage; progressLabel.Text = $"{report.Percentage:F1}% - {report.Message}"; } }); await downloadService.DownloadToFileAsync(url, path, progress: progress); ``` -------------------------------- ### Build macOS App for Release Source: https://github.com/lykosai/stabilitymatrix/blob/main/CONTRIBUTING.md Build the macOS application for release using a provided script. Specify the release version. ```bash ./Build/build_macos_app.sh -v $RELEASE_VERSION ``` -------------------------------- ### DownloadPackageOptions Class Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Configuration options for downloading packages. Includes fields for version tag, branch, and prerelease status. ```csharp public class DownloadPackageOptions { public string VersionTag { get; set; } public string Branch { get; set; } public bool IsPrerelease { get; set; } // ... additional options } ``` -------------------------------- ### Inference System Prompt Parsing and Metadata Extraction Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/README.md Shows how to parse prompts using a syntax tree, validate them, and extract metadata from generated images. ```csharp // Parse prompt with syntax tree var promptTree = PromptSyntaxTree.Parse("1girl, blonde hair, blue eyes "); // Validate prompt bool isValid = promptTree.Validate(validationRules); // Extract metadata from generated image var metadata = GenerationParameters.ParseImageMetadata("output.png"); if (metadata != null) { Console.WriteLine($"Model: {metadata.Model}"); Console.WriteLine($"Seed: {metadata.Seed}"); } ``` -------------------------------- ### Read and Write Settings with Transaction Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/README.md Shows how to read application settings and modify them within a transactional block, which automatically commits changes upon disposal. ```csharp // Read settings var theme = settingsManager.Settings.SelectedTheme; // Modify with transaction using var transaction = settingsManager.BeginTransaction(); { transaction.Settings.SelectedTheme = "dark"; transaction.Settings.PreferredLanguage = "ja"; } // Auto-commits on dispose ``` -------------------------------- ### Start Background Model Index Refresh Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/services.md Initiates a background task to refresh the model index. This method does not block the calling thread. ```csharp void BackgroundRefreshIndex() ``` -------------------------------- ### Get Relative Directory Path Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/models.md Calculates the relative path of a directory with respect to a base directory. Useful for representing nested directory structures. ```csharp public DirectoryPath RelativeTo(DirectoryPath path) ``` ```csharp var baseDir = new DirectoryPath("/home/user/stable-diffusion"); var modelDir = new DirectoryPath("/home/user/stable-diffusion/models/checkpoints"); var relative = modelDir.RelativeTo(baseDir); // "models/checkpoints" ``` -------------------------------- ### Find and Filter Models Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/README.md Demonstrates how to retrieve all models of a specific type, filter them by path, and check for available updates. ```csharp // Get all checkpoints var checkpoints = await modelIndexService.FindByModelTypeAsync( SharedFolderType.Checkpoint); // Filter by name var filtered = checkpoints .Where(m => m.RelativePath.Contains("xyz")) .ToList(); // Check for updates await modelIndexService.CheckModelsForUpdateAsync(); var modelsWithUpdates = checkpoints.Where(m => m.HasUpdate).ToList(); ``` -------------------------------- ### Get Directory Size Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/models.md Calculates the total size of a directory's contents in bytes. Optionally includes the size of linked files and directories. ```csharp public long GetSize() public long GetSize(bool includeSymbolicLinks) ``` -------------------------------- ### Update Model Folders Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Updates model folder configuration after changes have been made. Requires the package installation directory and the method for shared folder management. ```csharp public abstract Task UpdateModelFolders( DirectoryPath installDirectory, SharedFolderMethod sharedFolderMethod) ``` -------------------------------- ### Instantiate ProgressReport Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/models.md Constructors for creating ProgressReport objects with different progress reporting styles, including percentage-based, count-based, and indeterminate progress. ```csharp // Percentage-based progress new ProgressReport(0.75, "Downloading", "50 MB of 100 MB") // Count-based progress new ProgressReport(50, 100, "Processing", "50 of 100 items") // Indeterminate progress new ProgressReport(isIndeterminate: true, title: "Extracting") ``` -------------------------------- ### Begin Settings Transaction Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/services.md Obtain a SettingsTransaction object to make multiple modifications to settings atomically. Changes are saved automatically when the transaction is disposed. ```csharp SettingsTransaction BeginTransaction() ``` -------------------------------- ### Get Remote File Size Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/services.md Retrieves the size of a remote file in bytes from a given URL. Useful for pre-allocating space or checking download progress. ```csharp Task GetFileSizeAsync( string downloadUrl, string? httpClientName = null, CancellationToken cancellationToken = default) ``` -------------------------------- ### Check Launch Option Value Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/models.md Determines if a launch option is empty or matches its default value. Use this to validate user input or configuration. ```csharp public bool IsEmptyOrDefault() ``` -------------------------------- ### Get Relative Sub-Path Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/models.md Calculates a relative sub-path from a base path. Use this static method when determining if one path is contained within another. ```csharp public static string? GetSubPath(string relativeTo, string path) ``` -------------------------------- ### Build StabilityMatrix.Avalonia for Debug Source: https://github.com/lykosai/stabilitymatrix/blob/main/CONTRIBUTING.md Build the Avalonia project with a specific runtime and configuration for debugging purposes. ```bash dotnet build ./StabilityMatrix.Avalonia/StabilityMatrix.Avalonia.csproj -r win-x64 -c Debug ``` -------------------------------- ### RunPackageOptions Class Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Specifies options for running a package, such as environment variables and launch arguments. ```csharp public class RunPackageOptions { public Dictionary EnvironmentVariables { get; set; } public List LaunchArgs { get; set; } // ... additional options } ``` -------------------------------- ### Reset Stability Matrix Window Position Source: https://github.com/lykosai/stabilitymatrix/wiki/FAQ-&-Troubleshooting Use this launch argument to reset the application window position if it appears off-screen, particularly in multi-monitor setups. ```bash stabilitymatrix.exe --reset-window-position ``` -------------------------------- ### Register Callback for Library Directory Set Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/services.md Register an action to be executed once when the library directory is successfully set. This ensures your code runs only after the library path is confirmed. ```csharp void RegisterOnLibraryDirSet(Action handler) ``` -------------------------------- ### Mark EULA as Accepted Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/services.md Record that the user has accepted the End-User License Agreement (EULA). This typically enables further application functionality. ```csharp void SetEulaAccepted() ``` -------------------------------- ### Remove Model Folder Links Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Removes model folder links or configuration. Requires the package installation directory and the method used for shared folder management. ```csharp public abstract Task RemoveModelFolderLinks( DirectoryPath installDirectory, SharedFolderMethod sharedFolderMethod) ``` -------------------------------- ### Define Launch Option Types Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/models.md Enumeration defining the types of values a launch option can hold. ```csharp public enum LaunchOptionType { Bool, Int, String } ``` -------------------------------- ### Define PyTorch Backend/Device Options Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/models.md Enumeration for PyTorch backend and device options, supporting CPU, CUDA, ROCm, ZLUDA, MPS, and DirectML. ```csharp public enum TorchIndex { Cpu, // CPU only Cuda, // NVIDIA CUDA Rocm, // AMD ROCm Zluda, // Intel/AMD ZLUDA Mps, // Apple Metal Performance Shaders DirectML, // Windows DirectML } ``` -------------------------------- ### Download File to Path Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/services.md Downloads a file from a given URL to a specified local path. Supports progress reporting and cancellation. ```csharp Task DownloadToFileAsync( string downloadUrl, string downloadPath, IProgress? progress = null, string? httpClientName = null, CancellationToken cancellationToken = default) ``` -------------------------------- ### GetExtraCommands Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Retrieves a list of extra executable commands available for the package. ```APIDOC ## GetExtraCommands ### Description Get list of extra executable commands for this package. ### Method `public virtual List GetExtraCommands()` ### Returns - `List` - List of command definitions ``` -------------------------------- ### Safely Get First Element of Collection Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/python-git-helpers.md Retrieves the first element of a collection, returning a default value if the collection is empty. Prevents exceptions when dealing with potentially empty collections. ```csharp // Safe operations var first = collection.FirstOrDefault(() => default); ``` -------------------------------- ### Execute Process with Output Handling Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/python-git-helpers.md Runs an external process asynchronously and captures its output. The provided callback handles output lines, allowing for real-time logging or processing. ```csharp // With output handling ProcessRunner.RunAsync( fileName: "python", arguments: "script.py", onOutput: output => { if (output.IsError) logger.Error(output.Text); else logger.Info(output.Text); }); ``` -------------------------------- ### Parse and Compare Semantic Versions Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/python-git-helpers.md Handles parsing and comparing semantic version strings. Use this to validate version formats and check if a current version meets a specific requirement. ```csharp // Parse semantic versions var v1 = VersionHelper.Parse("1.2.3"); var v2 = VersionHelper.Parse("1.2.4"); // Compare versions bool isNewer = v2 > v1; // Check version requirements bool meetsRequirement = VersionHelper.MeetsRequirement( currentVersion: "1.5.0", requirement: ">=1.4.0"); ``` -------------------------------- ### Git Package Operations Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/python-git-helpers.md Performs common Git operations on packages managed via Git repositories, such as retrieving branches, versions, checking for updates, and getting current commit information. ```csharp // Get available branches var branches = await gitPackage.GetAvailableBranches(); // Get available releases/tags var releases = await gitPackage.GetAvailableVersions(); // Check for updates bool hasUpdate = await gitPackage.CheckForUpdates(installedPackage); // Get current commit info var gitInfo = await gitPackage.GetGitInfo(installPath); ``` -------------------------------- ### Transactional Modification with Manual Commit Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/configuration.md Shows how to initiate a settings transaction, make modifications, and then explicitly commit the changes. This provides explicit control over the save operation. ```csharp // Transactional modification with manual commit using var transaction = settingsManager.BeginTransaction(); transaction.Settings.SelectedTheme = "dark"; transaction.Commit(); ``` -------------------------------- ### A3WebUI Package Implementation Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/packages.md Represents the A3WebUI (Automatic1111) package, a popular Stable Diffusion WebUI. It inherits from BaseGitPackage. ```csharp public class A3WebUI : BaseGitPackage ``` -------------------------------- ### Notification Filtering Logic (C#) Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/notifications.md This C# function determines whether a notification should be displayed based on dismissal status, setup completion, date ranges, and version compatibility. It consolidates multiple conditions for showing notifications. ```csharp public bool ShouldShowNotification(AppNotification notification, Settings settings, Version appVersion, bool setupComplete) { // Check dismissal if (settings.DismissedNotifications.Contains(notification.Id)) return false; // Check setup requirement if (notification.RequireSetupComplete && !setupComplete) return false; // Check date window var now = DateTimeOffset.UtcNow; if (notification.StartDate.HasValue && now < notification.StartDate) return false; if (notification.EndDate.HasValue && now > notification.EndDate) return false; // Check version window if (!string.IsNullOrEmpty(notification.MinVersion) && appVersion < Version.Parse(notification.MinVersion)) return false; if (!string.IsNullOrEmpty(notification.MaxVersion) && appVersion > Version.Parse(notification.MaxVersion)) return false; return true; } ``` -------------------------------- ### Calculate and Verify File Hashes Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/python-git-helpers.md Performs file hashing operations using Blake3 and SHA256 algorithms, and verifies file integrity against an expected hash. Use this for checking downloaded files or ensuring data hasn't been tampered with. ```csharp // Calculate Blake3 hash var blake3 = await HashHelper.CalculateBlake3Async("file.bin"); // Calculate SHA256 var sha256 = await HashHelper.CalculateSha256Async("file.bin"); // Verify hash bool isValid = await HashHelper.VerifyHashAsync( filePath: "model.safetensors", expectedHash: "abc123...", hashType: HashType.Blake3); ``` -------------------------------- ### Count-Based Progress Reporting Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/notifications.md Shows how to report progress based on a known total number of items or steps. ```csharp var total = 100; for (int i = 0; i < total; i++) { var report = new ProgressReport( current: i, total: total, title: "Processing Items", message: $"Item {i + 1} of {total}" ); progressObserver.OnNext(report); await Task.Delay(100); } ``` -------------------------------- ### Create Progress Report from Process Output Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/models.md Static method to create a ProgressReport object using data from ProcessOutput. ```csharp public static ProgressReport ForProcessOutput(ProcessOutput output) ``` -------------------------------- ### Observe Settings Property Changes with Observables Source: https://github.com/lykosai/stabilitymatrix/blob/main/_autodocs/services.md Create an observable sequence that emits values whenever a specified settings property changes. This integrates settings changes with reactive programming patterns. ```csharp IObservable ObservePropertyChanged(Expression> settingsProperty) ```