|
| 1 | +using Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training; |
| 2 | +using Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training.Models; |
| 3 | +using Microsoft.Extensions.Configuration; |
| 4 | +using Microsoft.Extensions.Hosting; |
| 5 | +using Microsoft.Extensions.Logging; |
| 6 | +using System; |
| 7 | +using System.Collections.Generic; |
| 8 | +using System.ComponentModel.DataAnnotations; |
| 9 | +using System.Text; |
| 10 | +using System.Threading; |
| 11 | +using System.Threading.Tasks; |
| 12 | + |
| 13 | +namespace Fritz.Chatbot |
| 14 | +{ |
| 15 | + public class ScreenshotTrainingService : IHostedService, ITrainHat |
| 16 | + { |
| 17 | + |
| 18 | + // TODO: Track how many images are loaded -- 5k is the maximum for the FREE service |
| 19 | + private string _CustomVisionKey = ""; |
| 20 | + private string _AzureEndpoint = ""; |
| 21 | + private string _TwitchChannel = ""; |
| 22 | + private Guid _AzureProjectId; |
| 23 | + private readonly ILogger _Logger; |
| 24 | + private CancellationTokenSource _TokenSource; |
| 25 | + |
| 26 | + private bool _CurrentlyTraining = false; |
| 27 | + private byte _TrainingCount = 0; |
| 28 | + private Task _TrainingTask; |
| 29 | + private byte _RetryCount = 0; |
| 30 | + |
| 31 | + public string TwitchScreenshotUrl => $"https://static-cdn.jtvnw.net/previews-ttv/live_user_{_TwitchChannel}-1280x720.jpg?_="; |
| 32 | + |
| 33 | + public ScreenshotTrainingService(IConfiguration configuration, ILoggerFactory loggerFactory) |
| 34 | + { |
| 35 | + |
| 36 | + _CustomVisionKey = configuration["AzureServices:HatDetection:Key"]; |
| 37 | + _AzureEndpoint = configuration["AzureServices:HatDetection:CustomVisionEndpoint"]; |
| 38 | + _TwitchChannel = configuration["StreamServices:Twitch:Channel"]; |
| 39 | + _AzureProjectId = Guid.Parse(configuration["AzureServices:HatDetection:ProjectId"]); |
| 40 | + _Logger = loggerFactory.CreateLogger("ScreenshotTraining"); |
| 41 | + |
| 42 | + } |
| 43 | + |
| 44 | + public Task StartAsync(CancellationToken cancellationToken) |
| 45 | + { |
| 46 | + |
| 47 | + _TokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| 48 | + |
| 49 | + _TrainingTask = Train(_TokenSource.Token); |
| 50 | + return Task.CompletedTask; |
| 51 | + |
| 52 | + } |
| 53 | + |
| 54 | + public async Task StopAsync(CancellationToken cancellationToken) |
| 55 | + { |
| 56 | + |
| 57 | + _TokenSource?.Cancel(); |
| 58 | + await _TrainingTask; |
| 59 | + |
| 60 | + } |
| 61 | + |
| 62 | + private async Task Train(CancellationToken token) |
| 63 | + { |
| 64 | + |
| 65 | + while (!token.IsCancellationRequested) |
| 66 | + { |
| 67 | + |
| 68 | + if (_CurrentlyTraining && _TrainingCount == 15) |
| 69 | + { |
| 70 | + _CurrentlyTraining = false; |
| 71 | + _Logger.LogTrace("Completed screenshot training"); |
| 72 | + |
| 73 | + } |
| 74 | + else if (_CurrentlyTraining) |
| 75 | + { |
| 76 | + |
| 77 | + await AddScreenshot(true); |
| 78 | + await Task.Delay(TimeSpan.FromMinutes(1)); |
| 79 | + |
| 80 | + } |
| 81 | + else |
| 82 | + { |
| 83 | + |
| 84 | + await Task.Delay(100); |
| 85 | + |
| 86 | + } |
| 87 | + |
| 88 | + } |
| 89 | + |
| 90 | + } |
| 91 | + |
| 92 | + public void StartTraining() |
| 93 | + { |
| 94 | + |
| 95 | + if (_CurrentlyTraining) return; |
| 96 | + |
| 97 | + _Logger.LogTrace("Starting screenshot training"); |
| 98 | + _TrainingCount = 0; |
| 99 | + _CurrentlyTraining = true; |
| 100 | + |
| 101 | + } |
| 102 | + |
| 103 | + private async Task AddScreenshot(bool @internal) |
| 104 | + { |
| 105 | + |
| 106 | + if (!@internal && _CurrentlyTraining) return; |
| 107 | + |
| 108 | + try |
| 109 | + { |
| 110 | + var trainingClient = new CustomVisionTrainingClient() |
| 111 | + { |
| 112 | + ApiKey = _CustomVisionKey, |
| 113 | + Endpoint = _AzureEndpoint |
| 114 | + }; |
| 115 | + |
| 116 | + var result = await trainingClient.CreateImagesFromUrlsAsync(_AzureProjectId, new ImageUrlCreateBatch( |
| 117 | + new List<ImageUrlCreateEntry> { |
| 118 | + new ImageUrlCreateEntry(TwitchScreenshotUrl + Guid.NewGuid().ToString()) |
| 119 | + } |
| 120 | + )); |
| 121 | + |
| 122 | + if (!result.IsBatchSuccessful && _RetryCount < 3) { |
| 123 | + _Logger.LogWarning($"Error while adding screenshot #{_TrainingCount} - trying again in 10 seconds"); |
| 124 | + await Task.Delay(TimeSpan.FromSeconds(10)); |
| 125 | + _RetryCount++; |
| 126 | + await AddScreenshot(true); |
| 127 | + return; |
| 128 | + } else if (_RetryCount >= 3) { |
| 129 | + |
| 130 | + _Logger.LogError("Unable to add screenshot to Azure Custom Vision service"); |
| 131 | + _RetryCount = 0; |
| 132 | + return; |
| 133 | + |
| 134 | + } |
| 135 | + |
| 136 | + _RetryCount = 0; |
| 137 | + |
| 138 | + if (_CurrentlyTraining) |
| 139 | + { |
| 140 | + _TrainingCount++; |
| 141 | + _Logger.LogTrace($"Successfully added screenshot #{_TrainingCount}"); |
| 142 | + } |
| 143 | + |
| 144 | + } |
| 145 | + catch (Exception ex) |
| 146 | + { |
| 147 | + _Logger.LogError($"Error while adding screenshot: {ex.Message}"); |
| 148 | + } |
| 149 | + |
| 150 | + } |
| 151 | + |
| 152 | + |
| 153 | + public Task AddScreenshot() |
| 154 | + { |
| 155 | + |
| 156 | + return AddScreenshot(false); |
| 157 | + |
| 158 | + } |
| 159 | + |
| 160 | + } |
| 161 | +} |
0 commit comments