Files
annotations/Azaion.Suite/App.xaml.cs
T
Alex Bezdieniezhnykh 7750025631 separate load functionality from inference client to loader client. Call loader client from inference to get the model.
remove dummy dlls, remove resource loader from c#.

TODO: Load dlls separately by Loader UI and loader client

WIP
2025-06-06 20:04:03 +03:00

231 lines
8.7 KiB
C#

using System.IO;
using System.Net.Http;
using System.Text;
using System.Windows;
using System.Windows.Threading;
using Azaion.Annotator;
using Azaion.Common;
using Azaion.Common.Database;
using Azaion.Common.DTO;
using Azaion.Common.DTO.Config;
using Azaion.Common.Events;
using Azaion.Common.Extensions;
using Azaion.Common.Services;
using Azaion.CommonSecurity;
using Azaion.CommonSecurity.DTO;
using Azaion.CommonSecurity.DTO.Commands;
using Azaion.CommonSecurity.Services;
using Azaion.Dataset;
using CommandLine;
using LibVLCSharp.Shared;
using MediatR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Serilog;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
namespace Azaion.Suite;
public partial class App
{
private IMediator _mediator = null!;
private FormState _formState = null!;
private IHost _host = null!;
private static readonly Guid KeyPressTaskId = Guid.NewGuid();
private readonly ICache _cache = new MemoryCache();
private readonly CancellationTokenSource _mainCTokenSource = new();
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
Log.Logger.Error(e.Exception, "Unhandled exception");
e.Handled = true;
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Information()
.WriteTo.Console()
.WriteTo.File(
path: "Logs/log.txt",
rollingInterval: RollingInterval.Day)
.CreateLogger();
Parser.Default.ParseArguments<ApiCredentials>(e.Args)
.WithParsed(Start)
.WithNotParsed(ErrorHandling);
}
private void ErrorHandling(IEnumerable<Error> obj)
{
Log.Fatal($"Error happened: {string.Join(",", obj.Select(x => x.Tag))}");
}
private static InitConfig ReadInitConfig()
{
try
{
if (!File.Exists(SecurityConstants.CONFIG_PATH))
throw new FileNotFoundException(SecurityConstants.CONFIG_PATH);
var configStr = File.ReadAllText(SecurityConstants.CONFIG_PATH);
var config = JsonConvert.DeserializeObject<InitConfig>(configStr);
return config ?? SecurityConstants.DefaultInitConfig;
}
catch (Exception e)
{
Console.WriteLine(e);
return SecurityConstants.DefaultInitConfig;
}
}
private Stream GetSystemConfig(LoaderClient loaderClient, string apiDir)
{
try
{
return loaderClient.LoadFile("config.system.json", apiDir);
}
catch (Exception e)
{
Log.Logger.Error(e, e.Message);
return new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new
{
AnnotationConfig = Constants.DefaultAnnotationConfig,
AIRecognitionConfig = Constants.DefaultAIRecognitionConfig,
ThumbnailConfig = Constants.DefaultThumbnailConfig,
})));
}
}
private Stream GetSecuredConfig(LoaderClient loaderClient, string apiDir)
{
try
{
return loaderClient.LoadFile("config.secured.json", apiDir);
}
catch (Exception e)
{
Log.Logger.Error(e, e.Message);
throw;
}
}
private void Start(ApiCredentials credentials)
{
new ConfigUpdater().CheckConfig();
var initConfig = ReadInitConfig();
var apiDir = initConfig.DirectoriesConfig.ApiResourcesDirectory;
var loaderClient = new LoaderClient(initConfig.LoaderClientConfig, Log.Logger, _mainCTokenSource.Token);
#if DEBUG
loaderClient.StartClient();
#endif
loaderClient.Connect(); //Client app should be already started by LoaderUI
loaderClient.Login(credentials);
var azaionApi = new AzaionApi(new HttpClient { BaseAddress = new Uri(initConfig.InferenceClientConfig.ApiUrl) }, _cache, credentials);
_host = Host.CreateDefaultBuilder()
.ConfigureAppConfiguration((_, config) => config
.AddCommandLine(Environment.GetCommandLineArgs())
.AddJsonFile(SecurityConstants.CONFIG_PATH, optional: true, reloadOnChange: true)
.AddJsonStream(GetSystemConfig(loaderClient, apiDir))
.AddJsonStream(GetSecuredConfig(loaderClient, apiDir)))
.UseSerilog()
.ConfigureServices((context, services) =>
{
services.AddSingleton<MainSuite>();
services.Configure<AppConfig>(context.Configuration);
services.ConfigureSection<QueueConfig>(context.Configuration);
services.ConfigureSection<DirectoriesConfig>(context.Configuration);
services.ConfigureSection<AnnotationConfig>(context.Configuration);
services.ConfigureSection<AIRecognitionConfig>(context.Configuration);
services.ConfigureSection<ThumbnailConfig>(context.Configuration);
services.ConfigureSection<UIConfig>(context.Configuration);
services.ConfigureSection<MapConfig>(context.Configuration);
#region External Services
services.ConfigureSection<LoaderClientConfig>(context.Configuration);
services.AddSingleton(loaderClient);
services.ConfigureSection<InferenceClientConfig>(context.Configuration);
services.AddSingleton<IInferenceClient, InferenceClient>();
services.AddSingleton<IInferenceService, InferenceService>();
services.ConfigureSection<GpsDeniedClientConfig>(context.Configuration);
services.AddSingleton<IGpsMatcherClient, GpsMatcherClient>();
services.AddSingleton<IGpsMatcherService, GpsMatcherService>();
services.AddSingleton<ISatelliteDownloader, SatelliteDownloader>();
services.AddHttpClient();
services.AddSingleton<IAzaionApi>(azaionApi);
#endregion
services.AddSingleton<IConfigUpdater, ConfigUpdater>();
services.AddSingleton<Annotator.Annotator>();
services.AddSingleton<DatasetExplorer>();
services.AddSingleton<HelpWindow>();
services.AddMediatR(c => c.RegisterServicesFromAssemblies(
typeof(Annotator.Annotator).Assembly,
typeof(DatasetExplorer).Assembly,
typeof(AnnotationService).Assembly));
services.AddSingleton<LibVLC>(_ => new LibVLC());
services.AddSingleton<FormState>();
services.AddSingleton<MediaPlayer>(sp =>
{
var libVLC = sp.GetRequiredService<LibVLC>();
return new MediaPlayer(libVLC);
});
services.AddSingleton<AnnotatorEventHandler>();
services.AddSingleton<IDbFactory, DbFactory>();
services.AddSingleton<FailsafeAnnotationsProducer>();
services.AddSingleton<IAnnotationService, AnnotationService>();
services.AddSingleton<DatasetExplorer>();
services.AddSingleton<IGalleryService, GalleryService>();
services.AddSingleton<IAzaionModule, AnnotatorModule>();
services.AddSingleton<IAzaionModule, DatasetExplorerModule>();
})
.Build();
Annotation.InitializeDirs(_host.Services.GetRequiredService<IOptions<DirectoriesConfig>>().Value);
_host.Services.GetRequiredService<DatasetExplorer>();
// datasetExplorer.Show();
// datasetExplorer.Hide();
_mediator = _host.Services.GetRequiredService<IMediator>();
_formState = _host.Services.GetRequiredService<FormState>();
DispatcherUnhandledException += OnDispatcherUnhandledException;
_host.Start();
EventManager.RegisterClassHandler(typeof(UIElement), UIElement.PreviewKeyDownEvent, new RoutedEventHandler(GlobalKeyHandler));
_host.Services.GetRequiredService<MainSuite>().Show();
}
private void GlobalKeyHandler(object sender, RoutedEventArgs e)
{
var args = (KeyEventArgs)e;
var keyEvent = new KeyEvent(sender, args, _formState.ActiveWindow);
ThrottleExt.Throttle(() => _mediator.Publish(keyEvent, _mainCTokenSource.Token), KeyPressTaskId, TimeSpan.FromMilliseconds(50));
//e.Handled = true;
}
protected override async void OnExit(ExitEventArgs e)
{
base.OnExit(e);
await _host.StopAsync();
}
}