|
| 1 | +using Microsoft.AspNetCore.SignalR; |
| 2 | +using OnnxStack.StableDiffusion.Common; |
| 3 | +using OnnxStack.StableDiffusion.Config; |
| 4 | +using OnnxStack.WebUI.Models; |
| 5 | +using System; |
| 6 | +using System.Runtime.CompilerServices; |
| 7 | + |
| 8 | +namespace OnnxStack.Web.Hubs |
| 9 | +{ |
| 10 | + public class StableDiffusionHub : Hub |
| 11 | + { |
| 12 | + private readonly ILogger<StableDiffusionHub> _logger; |
| 13 | + private readonly IStableDiffusionService _stableDiffusionService; |
| 14 | + private readonly IWebHostEnvironment _webHostEnvironment; |
| 15 | + public StableDiffusionHub(ILogger<StableDiffusionHub> logger, IStableDiffusionService stableDiffusionService, IWebHostEnvironment webHostEnvironment) |
| 16 | + { |
| 17 | + _logger = logger; |
| 18 | + _webHostEnvironment = webHostEnvironment; |
| 19 | + _stableDiffusionService = stableDiffusionService; |
| 20 | + } |
| 21 | + |
| 22 | + public override async Task OnConnectedAsync() |
| 23 | + { |
| 24 | + _logger.Log(LogLevel.Information, "[OnConnectedAsync], Id: {0}", Context.ConnectionId); |
| 25 | + |
| 26 | + await Clients.Caller.SendAsync("OnMessage", "OnConnectedAsync"); |
| 27 | + await base.OnConnectedAsync(); |
| 28 | + } |
| 29 | + |
| 30 | + |
| 31 | + public override async Task OnDisconnectedAsync(Exception exception) |
| 32 | + { |
| 33 | + _logger.Log(LogLevel.Information, "[OnDisconnectedAsync], Id: {0}", Context.ConnectionId); |
| 34 | + |
| 35 | + await Clients.Caller.SendAsync("OnMessage", "OnDisconnectedAsync"); |
| 36 | + await base.OnDisconnectedAsync(exception); |
| 37 | + } |
| 38 | + |
| 39 | + |
| 40 | + [HubMethodName("ExecuteTextToImage")] |
| 41 | + public async IAsyncEnumerable<DiffusionResult> OnExecuteTextToImage(TextToImageOptions options, [EnumeratorCancellation] CancellationToken cancellationToken) |
| 42 | + { |
| 43 | + _logger.Log(LogLevel.Information, "[OnExecuteTextToImage] - New prompt received, Connection: {0}", Context.ConnectionId); |
| 44 | + var linkedCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(Context.ConnectionAborted, cancellationToken); |
| 45 | + |
| 46 | + var promptOptions = new PromptOptions |
| 47 | + { |
| 48 | + Prompt = options.Prompt, |
| 49 | + NegativePrompt = options.NegativePrompt, |
| 50 | + SchedulerType = options.SchedulerType |
| 51 | + }; |
| 52 | + |
| 53 | + var schedulerOptions = new SchedulerOptions |
| 54 | + { |
| 55 | + Width = options.Width, |
| 56 | + Height = options.Height, |
| 57 | + Seed = GenerateSeed(options.Seed), |
| 58 | + InferenceSteps = options.InferenceSteps, |
| 59 | + GuidanceScale = options.GuidanceScale, |
| 60 | + Strength = options.Strength, |
| 61 | + InitialNoiseLevel = options.InitialNoiseLevel |
| 62 | + }; |
| 63 | + |
| 64 | + // TODO: Add support for multiple results |
| 65 | + var result = await GenerateTextToImage(promptOptions, schedulerOptions, cancellationToken); |
| 66 | + if(result is null) |
| 67 | + yield break; |
| 68 | + |
| 69 | + yield return result; |
| 70 | + } |
| 71 | + |
| 72 | + private async Task<DiffusionResult> GenerateTextToImage(PromptOptions promptOptions, SchedulerOptions schedulerOptions, CancellationToken cancellationToken) |
| 73 | + { |
| 74 | + var rand = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); |
| 75 | + var outputImage = $"{schedulerOptions.Seed}_{promptOptions.SchedulerType}_{rand}.png"; |
| 76 | + var outputImageUrl = CreateOutputImageUrl("TextToImage", outputImage); |
| 77 | + var outputImageFile = CreateOutputImageFile(outputImageUrl); |
| 78 | + |
| 79 | + try |
| 80 | + { |
| 81 | + await _stableDiffusionService.TextToImageFile(promptOptions, schedulerOptions, outputImageFile, ProgressCallback(), cancellationToken); |
| 82 | + return new DiffusionResult(outputImage, outputImageUrl); |
| 83 | + } |
| 84 | + catch (OperationCanceledException tex) |
| 85 | + { |
| 86 | + await Clients.Caller.SendAsync("OnCanceled", tex.Message); |
| 87 | + } |
| 88 | + catch (Exception ex) |
| 89 | + { |
| 90 | + await Clients.Caller.SendAsync("OnError", ex.Message); |
| 91 | + } |
| 92 | + return null; |
| 93 | + } |
| 94 | + |
| 95 | + private int GenerateSeed(int seed) |
| 96 | + { |
| 97 | + if (seed > 0) |
| 98 | + return seed; |
| 99 | + |
| 100 | + return Random.Shared.Next(); |
| 101 | + } |
| 102 | + |
| 103 | + private Action<int, int> ProgressCallback() |
| 104 | + { |
| 105 | + return async (progress, total) => |
| 106 | + { |
| 107 | + _logger.Log(LogLevel.Information, "[OnExecuteTextToImage] - Progress: {0}/{1}, Connection: {2}", progress, total, Context.ConnectionId); |
| 108 | + await Clients.Caller.SendAsync("OnProgress", new ProgressResult(progress, total)); |
| 109 | + }; |
| 110 | + } |
| 111 | + |
| 112 | + |
| 113 | + private string CreateOutputImageFile(string url) |
| 114 | + { |
| 115 | + string webRootPath = _webHostEnvironment.WebRootPath; |
| 116 | + string physicalPath = Path.Combine(webRootPath, url.TrimStart('/').Replace('/', '\\')); |
| 117 | + return physicalPath; |
| 118 | + } |
| 119 | + |
| 120 | + private string CreateOutputImageUrl(string folder, string imageName) |
| 121 | + { |
| 122 | + return $"/images/results/{folder}/{imageName}"; |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + public record ProgressResult(int Progress, int Total); |
| 127 | + public record DiffusionResult(string OutputImage, string OutputImageUrl); |
| 128 | +} |
0 commit comments