|
| 1 | +using SixLabors.ImageSharp; |
| 2 | +using StableDiffusion.ML.OnnxRuntime; |
| 3 | +using System.Globalization; |
| 4 | + |
| 5 | +public class StableDiffusionService |
| 6 | +{ |
| 7 | + private readonly StableDiffusionConfig _config; |
| 8 | + private readonly ILogger<StableDiffusionService> _logger; |
| 9 | + |
| 10 | + public StableDiffusionService(IConfiguration configuration, ILogger<StableDiffusionService> logger) |
| 11 | + { |
| 12 | + _logger = logger; |
| 13 | + var sdConfigSection = configuration.GetSection("StableDiffusionConfig"); |
| 14 | + var configModelPath = sdConfigSection["ModelPath"]; |
| 15 | + |
| 16 | + var modelPath = string.IsNullOrEmpty(configModelPath) ? |
| 17 | + throw new ArgumentNullException("Model path is not configured.") : |
| 18 | + configModelPath; |
| 19 | + |
| 20 | + _config = new StableDiffusionConfig |
| 21 | + { |
| 22 | + NumInferenceSteps = int.Parse(sdConfigSection["NumInferenceSteps"]!), |
| 23 | + GuidanceScale = double.Parse(sdConfigSection["GuidanceScale"]!, CultureInfo.InvariantCulture), |
| 24 | + ExecutionProviderTarget = Enum.Parse<StableDiffusionConfig.ExecutionProvider>(sdConfigSection["ExecutionProviderTarget"]!), |
| 25 | + TextEncoderOnnxPath = Path.Combine(modelPath, "text_encoder", "model.onnx"), |
| 26 | + UnetOnnxPath = Path.Combine(modelPath, "unet", "model.onnx"), |
| 27 | + VaeDecoderOnnxPath = Path.Combine(modelPath, "vae_decoder", "model.onnx"), |
| 28 | + TokenizerOnnxPath = Path.Combine(Directory.GetCurrentDirectory(), "cliptokenizer.onnx"), |
| 29 | + OrtExtensionsPath = Path.Combine(Directory.GetCurrentDirectory(), "ortextensions.dll"), |
| 30 | + }; |
| 31 | + } |
| 32 | + |
| 33 | + public Image GenerateImage(string prompt) |
| 34 | + { |
| 35 | + try |
| 36 | + { |
| 37 | + _logger.LogInformation("Generating image for prompt: {Prompt}", prompt); |
| 38 | + return UNet.Inference(prompt, _config); |
| 39 | + } |
| 40 | + catch (Exception ex) |
| 41 | + { |
| 42 | + _logger.LogError(ex, "Error generating image for prompt: {Prompt}", prompt); |
| 43 | + throw; |
| 44 | + } |
| 45 | + } |
| 46 | +} |
0 commit comments