-
Notifications
You must be signed in to change notification settings - Fork 324
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
311 lines (267 loc) · 11.3 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
311 lines (267 loc) · 11.3 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE.md in the repo root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;
using Microsoft.ML.OnnxRuntime;
using Microsoft.Win32;
using Microsoft.Windows.AI.MachineLearning;
using WindowsML.Shared;
namespace WindowsMLSampleForWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, IDisposable
{
private string? _selectedImagePath;
private InferenceSession? _session;
private OrtEnv? _ortEnv;
private List<string> _labels = new();
private bool _disposed;
public MainWindow()
{
InitializeComponent(); // Must match x:Class in XAML
Loaded += MainWindow_Loaded;
Closed += MainWindow_Closed;
}
private void MainWindow_Closed(object? sender, EventArgs e)
{
Dispose();
}
public void Dispose()
{
if (_disposed) return;
_session?.Dispose();
_ortEnv?.Dispose();
_disposed = true;
}
private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
await InitializeAsync();
}
private async Task InitializeAsync()
{
try
{
ResultsTextBox.Text = "Getting available providers...\n";
var catalog = ExecutionProviderCatalog.GetDefault();
var providers = catalog.FindAllProviders();
var providerInfo = new StringBuilder();
providerInfo.AppendLine("Available Execution Providers:");
providerInfo.AppendLine("========================================");
if (providers is not null)
{
foreach (var provider in providers)
{
providerInfo.AppendLine($"Provider: {provider.Name}");
providerInfo.AppendLine($" Ready state: {provider.ReadyState}");
providerInfo.AppendLine();
}
}
bool allowDownload = AllowProviderDownloadCheckBox.IsChecked ?? false;
await ModelManager.InitializeExecutionProvidersAsync(allowDownload: allowDownload);
// Create the single OrtEnv instance for this application
_ortEnv ??= ModelManager.CreateEnvironment("WindowsMLSampleForWPF");
var devices = _ortEnv.GetEpDevices();
var epGroups = devices
.GroupBy(d => d.EpName)
.OrderBy(g => g.Key, StringComparer.OrdinalIgnoreCase)
.ToList();
EpCombo.Items.Clear();
foreach (var grp in epGroups)
{
EpCombo.Items.Add(grp.Key);
}
if (EpCombo.Items.Count > 0)
{
EpCombo.SelectedIndex = 0;
}
PopulateDeviceCombo(_ortEnv);
EpCombo.SelectionChanged += EpCombo_SelectionChanged;
ReloadSessionButton.Click += ReloadSessionButton_Click;
providerInfo.AppendLine("========================================");
providerInfo.AppendLine("Select EP/device (if required) then click 'Load / Reload Model'.");
ResultsTextBox.Text = providerInfo.ToString();
}
catch (Exception ex)
{
ResultsTextBox.Text = $"Failed to initialize: {ex.Message}";
}
}
private async Task LoadModelAndLabelsAsync()
{
if (EpCombo.SelectedItem == null)
{
ResultsTextBox.Text = "Select an execution provider first.";
return;
}
_session?.Dispose();
_session = null;
bool allowDownload = AllowProviderDownloadCheckBox.IsChecked ?? false;
// Create OrtEnv only once per application instance
_ortEnv ??= ModelManager.CreateEnvironment("WindowsMLSampleForWPF");
await ModelManager.InitializeExecutionProvidersAsync(allowDownload: allowDownload);
var options = new Options
{
ModelPath = "SqueezeNet.onnx",
EpName = EpCombo.SelectedItem?.ToString(),
DeviceType = (DeviceCombo.IsEnabled ? DeviceCombo.SelectedItem?.ToString() : null),
PerfMode = GetSelectedPerformanceMode()
};
if (DeviceCombo.IsEnabled && DeviceCombo.SelectedItem == null)
{
ResultsTextBox.Text = "Select a device type for the selected execution provider.";
return;
}
var (modelPath, compiledModelPath, labelsPath) = await ModelManager.ResolvePaths(options, _ortEnv);
string actualModelPath = ModelManager.ResolveActualModelPath(options, modelPath, compiledModelPath, _ortEnv);
_session = ModelManager.CreateSession(actualModelPath, options, _ortEnv);
_labels = ResultProcessor.LoadLabels(labelsPath).ToList();
}
private void SelectImageButton_Click(object sender, RoutedEventArgs e)
{
var openFileDialog = new OpenFileDialog
{
Title = "Select Image File",
Filter = "Image files (*.jpg, *.jpeg, *.png)|*.jpg;*.jpeg;*.png",
FilterIndex = 1
};
if (openFileDialog.ShowDialog() == true)
{
_selectedImagePath = openFileDialog.FileName;
ImagePathTextBox.Text = Path.GetFileName(_selectedImagePath);
try
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(_selectedImagePath);
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
SelectedImage.Source = bitmap;
RunInferenceButton.IsEnabled = true;
ResultsTextBox.Text = "Image selected. Click 'Run Inference' to classify the image.";
}
catch (Exception ex)
{
MessageBox.Show($"Error loading image: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
private async void RunInferenceButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(_selectedImagePath) || _session == null)
{
ResultsTextBox.Text = "Please select an image first.";
return;
}
try
{
ResultsTextBox.Text = "Running inference...";
Dispatcher.Invoke(() => { }, System.Windows.Threading.DispatcherPriority.Render);
var videoFrame = await ImageProcessor.LoadImageFileAsync(_selectedImagePath);
var inputTensor = await ImageProcessor.PreprocessImageAsync(videoFrame);
using var results = InferenceEngine.RunInference(_session, inputTensor);
var resultTensor = InferenceEngine.ExtractResults(_session, results);
var topPredictions = ResultProcessor.GetTopPredictions(resultTensor, _labels, 5);
ResultsTextBox.Text = FormatResultsForUI(topPredictions);
}
catch (Exception ex)
{
ResultsTextBox.Text = $"Error during inference: {ex.Message}";
}
}
private void PopulateDeviceCombo(OrtEnv env)
{
DeviceCombo.Items.Clear();
DeviceCombo.IsEnabled = false;
var selectedEp = EpCombo.SelectedItem?.ToString();
if (string.IsNullOrEmpty(selectedEp))
{
return;
}
var devices = env.GetEpDevices()
.Where(d => d.EpName == selectedEp)
.ToList();
// Generalized: any EP with multiple distinct hardware device types
var types = devices
.Select(d => d.HardwareDevice.Type.ToString())
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(s => s, StringComparer.OrdinalIgnoreCase)
.ToList();
if (types.Count == 1)
{
// Single device type – show it but keep combo disabled
DeviceCombo.IsEnabled = false;
DeviceCombo.Items.Add(types[0]);
DeviceCombo.SelectedIndex = 0;
}
else if (types.Count > 1)
{
// Multiple device types – enable selection
DeviceCombo.IsEnabled = true;
foreach (var t in types)
{
DeviceCombo.Items.Add(t);
}
DeviceCombo.SelectedIndex = 0;
}
else
{
// Log an error – no devices for selected EP
ResultsTextBox.Text = $"No devices found for selected execution provider: {selectedEp}";
}
}
private async void ReloadSessionButton_Click(object sender, RoutedEventArgs e)
{
ResultsTextBox.Text = "Loading / reloading model...";
await LoadModelAndLabelsAsync();
if (_session != null)
{
ResultsTextBox.Text += "\nModel loaded. Select an image and click 'Run Inference'.";
}
}
private void EpCombo_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
try
{
// Use the shared OrtEnv instance for device refresh
if (_ortEnv != null)
{
PopulateDeviceCombo(_ortEnv);
}
}
catch (Exception ex)
{
ResultsTextBox.Text = $"Failed refreshing devices: {ex.Message}";
}
}
private PerformanceMode GetSelectedPerformanceMode()
{
if (PerfModeMaxPerfRadio.IsChecked == true)
return PerformanceMode.MaxPerformance;
if (PerfModeMaxEffRadio.IsChecked == true)
return PerformanceMode.MaxEfficiency;
return PerformanceMode.Default;
}
private static string FormatResultsForUI(List<(string Label, float Confidence)> predictions)
{
var sb = new StringBuilder();
sb.AppendLine("Top 5 Predictions:");
sb.AppendLine("-------------------------------------------");
sb.AppendLine($"{"Label",-32} {"Confidence",10}");
sb.AppendLine("-------------------------------------------");
foreach (var (label, confidence) in predictions)
{
sb.AppendLine($"{label,-32} {confidence:P2}");
}
sb.AppendLine("-------------------------------------------");
return sb.ToString();
}
}
}