This repository was archived by the owner on Dec 8, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
277 lines (236 loc) · 11.5 KB
/
Program.cs
File metadata and controls
277 lines (236 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
using CommandLine;
using OnnxStack.Core.Image;
using OnnxStack.Core.Video;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SuperResolution.Core;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace SuperResolution.CLI
{
internal class Program
{
private static string _benchmarkLogOutput;
private static readonly Lock _syncObject = new Lock();
private static ISuperResolutionService _superResolutionService;
static async Task Main(string[] args)
{
Log($"Loading SuperResolution Model...");
_superResolutionService = new SuperResolutionService();
await LoadSuperResolutionService();
Log($"SuperResolution Model Loaded.");
await Parser.Default
.ParseArguments<Parameters>(args)
.WithParsedAsync(ExecuteSuperResolutionAsync);
}
private static async Task LoadSuperResolutionService()
{
try
{
await _superResolutionService.LoadAsync();
}
catch (Exception ex)
{
Log($"Failed to initialize NPU library\n\n{ex.Message}");
Environment.Exit(0);
}
}
private static async Task ExecuteSuperResolutionAsync(Parameters parameters)
{
using (var cancellationTokenSource = new CancellationTokenSource())
{
try
{
Console.CursorVisible = false;
HookCancelEvents(cancellationTokenSource);
Enum.TryParse<InputType>(parameters.Type, true, out var inputType);
switch (inputType)
{
case InputType.Image:
case InputType.Video:
case InputType.Stream:
await RunSuperResolutionAsync(inputType, parameters, cancellationTokenSource.Token);
break;
case InputType.Benchmark:
await RunSuperResolutionBenchmarkAsync(parameters, cancellationTokenSource.Token);
break;
default:
break;
}
}
catch (OperationCanceledException)
{
Log($"\nOperation Canceled");
}
catch (Exception ex)
{
Log($"\nError: {ex.Message}");
}
finally
{
Console.CursorVisible = true;
cancellationTokenSource.TryCancel();
}
}
}
private static async Task RunSuperResolutionAsync(InputType inputType, Parameters parameters, CancellationToken cancellationToken)
{
Log($"\nNxEnhance {inputType} SuperResolution...");
if (string.IsNullOrEmpty(parameters.Input))
throw new ArgumentException("Input is required");
if (string.IsNullOrEmpty(parameters.Output))
throw new ArgumentException("Output is required");
var inputPath = Path.GetFullPath(parameters.Input);
var outputPath = Path.GetFullPath(parameters.Output);
if (!File.Exists(inputPath))
throw new ArgumentException("Input file not found");
Log($"Type: {parameters.Type}");
Log($"Input: {inputPath}");
Log($"Output: {outputPath}");
Log("--------------------------------------------------------------------");
var elapsed = Stopwatch.GetTimestamp();
if (inputType == InputType.Video)
{
Log($"Reading video frames...");
var timestamp = Stopwatch.GetTimestamp();
var video = await OnnxVideo.FromFileAsync(inputPath, cancellationToken: cancellationToken);
Log($"Reading video frames complete, Elapsed: {Stopwatch.GetElapsedTime(timestamp)}");
Log($"\nNPU SuperResolution - {video.Width}x{video.Height} -> {video.Width * 2}x{video.Height * 2}");
timestamp = Stopwatch.GetTimestamp();
var videoFile = await _superResolutionService.RunAsync(video, parameters.Concurrent, (r, p) =>
{
LogInplace(string.Format("Frame: {0}/{1}, Frames/Sec: {2:F2}", r + 1, video.FrameCount, r / Stopwatch.GetElapsedTime(timestamp).TotalSeconds), true);
}, cancellationToken);
video.Dispose();
Log($"\nNPU SuperResolution complete, Elapsed: {Stopwatch.GetElapsedTime(timestamp)}");
Log($"\nSaving video result to disk...");
timestamp = Stopwatch.GetTimestamp();
await videoFile.SaveAsync(outputPath, cancellationToken: cancellationToken);
Log($"Saving video result to disk complete, Elapsed: {Stopwatch.GetElapsedTime(timestamp)}");
}
else if (inputType == InputType.Stream)
{
Log($"Processing video stream...");
var timestamp = Stopwatch.GetTimestamp();
var video = await VideoHelper.ReadVideoInfoAsync(inputPath, cancellationToken: cancellationToken);
var videoStream = VideoHelper.ReadVideoStreamAsync(inputPath, cancellationToken: cancellationToken);
var superResolutionStream = _superResolutionService.RunAsync(videoStream, cancellationToken: cancellationToken);
async IAsyncEnumerable<OnnxImage> ProcessFrames(IAsyncEnumerable<OnnxImage> frames)
{
int index = 0;
await foreach (var frame in frames)
{
index++;
LogInplace(string.Format("Frame: {0}/{1}, Frames/Sec: {2:F2}", index, video.FrameCount, index / Stopwatch.GetElapsedTime(timestamp).TotalSeconds), true);
yield return frame;
}
}
Log($"\nNPU SuperResolution - {video.Width}x{video.Height} -> {video.Width * 2}x{video.Height * 2}");
await VideoHelper.WriteVideoStreamAsync(outputPath, ProcessFrames(superResolutionStream), video.FrameRate, video.Width * 2, video.Height * 2, cancellationToken: cancellationToken);
Log($"\nNPU SuperResolution complete.");
Log($"\nProcessing video stream complete.");
}
else
{
// TODO: Images Folder
Log($"Processing image...");
var inputImage = await OnnxImage.FromFileAsync(inputPath);
Log($"\nNPU SuperResolution - {inputImage.Width}x{inputImage.Height} -> {inputImage.Width * 2}x{inputImage.Height * 2}");
var timestamp = Stopwatch.GetTimestamp();
var outputImage = await _superResolutionService.RunAsync(inputImage, cancellationToken);
Log($"Image: 1/1, Image/Sec: {1000 / Stopwatch.GetElapsedTime(timestamp).TotalMilliseconds:F2}");
Log($"NPU SuperResolution complete");
outputImage.GetImage().Save(outputPath);
Log($"\nProcessing image complete.");
}
Log("--------------------------------------------------------------------");
Log($"Elapsed: {Stopwatch.GetElapsedTime(elapsed)}");
Log($"NxEnhance {inputType} SuperResolution Complete.");
}
private static async Task RunSuperResolutionBenchmarkAsync(Parameters parameters, CancellationToken cancellationToken)
{
if (!string.IsNullOrEmpty(parameters.Output))
_benchmarkLogOutput = Path.GetFullPath(parameters.Output);
Log($"\nNxEnhance Benchmark...", true);
var runs = parameters.Runs == -1 ? int.MaxValue : Math.Max(1, parameters.Runs);
var concurrent = Math.Min(Environment.ProcessorCount, Math.Max(1, parameters.Concurrent));
var benchmarkImage = Path.GetFullPath(Path.Combine("Sample", "Benchmark.jpg"));
Log($"Type: Benchmark | Runs: {(runs == int.MaxValue ? "Loop" : runs.ToString())} | Concurrent: {concurrent}", true);
if (!string.IsNullOrEmpty(parameters.Input))
{
benchmarkImage = Path.GetFullPath(parameters.Input);
if (!File.Exists(benchmarkImage))
throw new ArgumentException("Input file not found");
Log($"Input: {benchmarkImage}", true);
}
if (!string.IsNullOrEmpty(parameters.Output))
Log($"Output: {_benchmarkLogOutput}");
// Load Image
var inputImage = await OnnxImage.FromFileAsync(benchmarkImage);
Log("--------------------------------------------------------------------");
Log($"Benchmark: {inputImage.Width}x{inputImage.Height} => {inputImage.Width * 2}x{inputImage.Height * 2}");
var timestamp = Stopwatch.GetTimestamp();
var completedRuns = new ConcurrentBag<int>();
var logFormat = runs == int.MaxValue ? "Run: {0} - Images/Sec: {2:F2}" : "Run: {0}/{1} - Images/Sec: {2:F2}";
await _superResolutionService.RunBenchmarkAsync(inputImage, runs, concurrent, (r, p) =>
{
LogInplace(string.Format(logFormat, p, runs, p / Stopwatch.GetElapsedTime(timestamp).TotalSeconds), true);
}, cancellationToken);
var totalTime = Stopwatch.GetElapsedTime(timestamp);
var avarageIts = runs / totalTime.TotalSeconds;
Log("\n--------------------------------------------------------------------");
Log($"Runs: {runs} | Elapsed: {totalTime} | Images/Sec: {avarageIts:F2}", true);
Log($"NxEnhance Benchmark Complete.", true);
}
private static void Log(string message, bool toFile = false)
{
Console.WriteLine(message);
if (toFile)
LogBenchmarkFile(message);
}
private static void LogInplace(string message, bool toFile = false)
{
lock (_syncObject)
{
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(message.PadRight(84));
if (toFile)
LogBenchmarkFile(message);
}
}
private static void HookCancelEvents(CancellationTokenSource cancellationTokenSource)
{
// Handle Ctrl+C (or Ctrl+Break)
Console.CancelKeyPress += (sender, eventArgs) =>
{
cancellationTokenSource.TryCancel();
eventArgs.Cancel = true;
};
// Handle console close or process exit
AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) =>
{
if (!cancellationTokenSource.IsCancellationRequested)
cancellationTokenSource.TryCancel();
};
}
private static void LogBenchmarkFile(string message)
{
if (string.IsNullOrEmpty(message))
return;
if (string.IsNullOrEmpty(_benchmarkLogOutput))
return;
try
{
File.AppendAllLines(_benchmarkLogOutput, [message]);
}
catch
{
}
}
}
}