StableDiffusionNet.Core 1.1.3

There is a newer version of this package available.
See the version list below for details.
dotnet add package StableDiffusionNet.Core --version 1.1.3
                    
NuGet\Install-Package StableDiffusionNet.Core -Version 1.1.3
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="StableDiffusionNet.Core" Version="1.1.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="StableDiffusionNet.Core" Version="1.1.3" />
                    
Directory.Packages.props
<PackageReference Include="StableDiffusionNet.Core" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add StableDiffusionNet.Core --version 1.1.3
                    
#r "nuget: StableDiffusionNet.Core, 1.1.3"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package StableDiffusionNet.Core@1.1.3
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=StableDiffusionNet.Core&version=1.1.3
                    
Install as a Cake Addin
#tool nuget:?package=StableDiffusionNet.Core&version=1.1.3
                    
Install as a Cake Tool

StableDiffusionNet.Core

Core библиотека для работы с Stable Diffusion WebUI API.

Особенности

  • Минимальные зависимости: только Newtonsoft.Json для сериализации
  • 🚀 Без DI: простой в использовании без инфраструктуры DI
  • 🔄 Встроенный Retry: надежная и быстрая собственная реализация retry логики
  • Асинхронные операции: полная поддержка async/await и CancellationToken
  • 📝 XML документация: для всех публичных API
  • 🎯 Builder Pattern: удобное создание клиента
  • 📊 Собственное логирование: минималистичная абстракция без Microsoft.Extensions
  • 🎨 Multi-targeting: поддержка .NET Standard 2.0, 2.1, .NET 6.0, .NET 8.0

Установка

dotnet add package StableDiffusionNet.Core

Или через NuGet Package Manager:

Install-Package StableDiffusionNet.Core

Быстрый старт

Простейший вариант

using StableDiffusionNet;
using StableDiffusionNet.Models.Requests;

// Создание клиента с настройками по умолчанию
var client = StableDiffusionClientBuilder.CreateDefault("http://localhost:7860");

// Генерация изображения
var request = new TextToImageRequest
{
    Prompt = "a beautiful sunset over mountains, highly detailed, 4k",
    NegativePrompt = "blurry, low quality",
    Width = 512,
    Height = 512,
    Steps = 30
};

var response = await client.TextToImage.GenerateAsync(request);

Использование Builder для настройки

using StableDiffusionNet;
using StableDiffusionNet.Logging;

// Создание клиента с дополнительными настройками
var client = new StableDiffusionClientBuilder()
    .WithBaseUrl("http://localhost:7860")
    .WithTimeout(600)
    .WithRetry(retryCount: 3, retryDelayMilliseconds: 1000)
    .WithApiKey("your-api-key-if-needed")
    .WithDetailedLogging()
    .Build();

Использование с собственным логированием

// Реализуйте IStableDiffusionLogger
public class ConsoleLogger : IStableDiffusionLogger
{
    public void Log(LogLevel logLevel, string message)
    {
        Console.WriteLine($"[{logLevel}] {message}");
    }

    public void Log(LogLevel logLevel, Exception exception, string message)
    {
        Console.WriteLine($"[{logLevel}] {message}: {exception}");
    }

    public bool IsEnabled(LogLevel logLevel) => true;
}

// Реализуйте IStableDiffusionLoggerFactory
public class ConsoleLoggerFactory : IStableDiffusionLoggerFactory
{
    public IStableDiffusionLogger CreateLogger<T>() => new ConsoleLogger();
    public IStableDiffusionLogger CreateLogger(string categoryName) => new ConsoleLogger();
}

// Используйте с Builder
var client = new StableDiffusionClientBuilder()
    .WithBaseUrl("http://localhost:7860")
    .WithLoggerFactory(new ConsoleLoggerFactory())
    .Build();

Основные возможности

Text-to-Image генерация

var request = new TextToImageRequest
{
    Prompt = "a cute cat, highly detailed",
    Width = 512,
    Height = 512,
    Steps = 20,
    CfgScale = 7.5
};

var response = await client.TextToImage.GenerateAsync(request);
ImageHelper.Base64ToImage(response.Images[0], "output.png");

Image-to-Image генерация

var initImage = ImageHelper.ImageToBase64("input.png");

var request = new ImageToImageRequest
{
    InitImages = new List<string> { initImage },
    Prompt = "transform into van gogh style",
    DenoisingStrength = 0.7
};

var response = await client.ImageToImage.GenerateAsync(request);

Работа с моделями

// Получить список моделей
var models = await client.Models.GetModelsAsync();

// Получить текущую модель
var currentModel = await client.Models.GetCurrentModelAsync();

// Установить модель
await client.Models.SetModelAsync("sd_xl_base_1.0.safetensors");

Мониторинг прогресса

var progress = await client.Progress.GetProgressAsync();
Console.WriteLine($"Progress: {progress.Progress:P}");

Retry логика

Библиотека включает надежную собственную реализацию retry с экспоненциальной задержкой:

  • Автоматические повторы для транзитных ошибок (500, 502, 503, 504)
  • Специальная обработка rate limiting (HTTP 429)
  • Экспоненциальный backoff с jitter для избежания thundering herd
  • Настраиваемое количество попыток и задержки

Обработка ошибок

using StableDiffusionNet.Exceptions;

try
{
    var response = await client.TextToImage.GenerateAsync(request);
}
catch (ApiException ex)
{
    Console.WriteLine($"API Error: {ex.Message}");
    Console.WriteLine($"Status Code: {ex.StatusCode}");
    Console.WriteLine($"Response: {ex.ResponseBody}");
}
catch (ConfigurationException ex)
{
    Console.WriteLine($"Configuration Error: {ex.Message}");
}
catch (StableDiffusionException ex)
{
    Console.WriteLine($"General Error: {ex.Message}");
}

Нужен Dependency Injection?

Если вам нужна интеграция с Microsoft.Extensions.DependencyInjection, используйте пакет StableDiffusionNet.DependencyInjection:

dotnet add package StableDiffusionNet.DependencyInjection
services.AddStableDiffusion(options =>
{
    options.BaseUrl = "http://localhost:7860";
});

Лицензия

MIT License

Ссылки

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on StableDiffusionNet.Core:

Package Downloads
StableDiffusionNet.DependencyInjection

Dependency Injection extensions for StableDiffusionNet.Core. Provides Microsoft.Extensions.DependencyInjection integration, logging adapters, and IOptions pattern support for Stable Diffusion WebUI API client. Compatible with .NET Standard 2.0+, .NET Framework 4.7.2+, .NET Core 2.0+, .NET 5.0+.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.5 288 10/28/2025
1.1.4 240 10/27/2025
1.1.3 244 10/26/2025
1.1.2 242 10/26/2025
1.1.1 241 10/26/2025
1.1.0 231 10/26/2025

See CHANGELOG.md for details