Files
annotations/Azaion.Common/Services/InferenceService.cs
T
Alex Bezdieniezhnykh 6429ad62c2 refactor external clients
put model batch size as parameter in config
2025-03-24 00:33:41 +02:00

50 lines
1.8 KiB
C#

using System.Text;
using Azaion.Common.Database;
using Azaion.Common.DTO.Config;
using Azaion.CommonSecurity;
using Azaion.CommonSecurity.DTO.Commands;
using Azaion.CommonSecurity.Services;
using MessagePack;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Azaion.Common.Services;
public interface IInferenceService
{
Task RunInference(List<string> mediaPaths, Func<AnnotationImage, Task> processAnnotation, CancellationToken ct = default);
}
public class InferenceService(ILogger<InferenceService> logger, [FromKeyedServices(SecurityConstants.EXTERNAL_INFERENCE_PATH)] IExternalClient externalClient, IOptions<AIRecognitionConfig> aiConfigOptions) : IInferenceService
{
public async Task RunInference(List<string> mediaPaths, Func<AnnotationImage, Task> processAnnotation, CancellationToken ct = default)
{
var aiConfig = aiConfigOptions.Value;
aiConfig.Paths = mediaPaths;
externalClient.Send(RemoteCommand.Create(CommandType.Inference, aiConfig));
while (!ct.IsCancellationRequested)
{
try
{
var bytes = externalClient.GetBytes(ct: ct);
if (bytes == null)
throw new Exception("Can't get bytes from inference client");
if (bytes.Length == 4 && Encoding.UTF8.GetString(bytes) == "DONE")
return;
var annotationImage = MessagePackSerializer.Deserialize<AnnotationImage>(bytes, cancellationToken: ct);
await processAnnotation(annotationImage);
}
catch (Exception e)
{
logger.LogError(e, e.Message);
break;
}
}
}
}