forked from microsoft/Cognitive-Samples-IntelligentKiosk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnomalyDetectorDemo.xaml.cs
290 lines (257 loc) · 11.4 KB
/
AnomalyDetectorDemo.xaml.cs
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
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Cognitive Services: http://www.microsoft.com/cognitive
//
// Microsoft Cognitive Services Github:
// https://github.com/Microsoft/Cognitive
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using IntelligentKioskSample.Models;
using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Media;
using Windows.Media.Capture;
using Windows.Media.Capture.Frames;
using Windows.Media.MediaProperties;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace IntelligentKioskSample.Views.AnomalyDetector
{
[KioskExperience(Id = "AnomalyDetector",
DisplayName = "Anomaly Detector",
Description = "An AI service that helps you foresee problems before they occur",
ImagePath = "ms-appx:/Assets/DemoGallery/Anomaly detector.jpg",
ExperienceType = ExperienceType.Preview | ExperienceType.Business,
TechnologyArea = TechnologyAreaType.Decision,
TechnologiesUsed = TechnologyType.AnomalyDetector,
DateAdded = "2019/09/03")]
public sealed partial class AnomalyDetectorDemo : Page, INotifyPropertyChanged
{
private MediaCapture mediaCapture;
private MediaFrameReader mediaFrameReader;
private float maxVolumeInSampleBuffer = 0;
public TabHeader BikeRentalTab = new TabHeader() { Name = "Bike rental" };
public TabHeader TelecomTab = new TabHeader() { Name = "Telecom" };
public TabHeader ManufacturingTab = new TabHeader() { Name = "Manufacturing" };
public TabHeader LiveTab = new TabHeader() { Name = "Live sound" };
private PivotItem selectedTab;
public PivotItem SelectedTab
{
get => selectedTab;
set
{
if (SetProperty(ref selectedTab, value))
{
TabChanged(SelectedTab);
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
private bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Equals(storage, value))
{
return false;
}
storage = value;
OnPropertyChanged(propertyName);
return true;
}
public AnomalyDetectorDemo()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
try
{
if (string.IsNullOrEmpty(SettingsHelper.Instance.AnomalyDetectorApiKey))
{
this.pivot.IsEnabled = false;
await new MessageDialog("Missing Anomaly Detector Key. Please enter the key in the Settings page.", "Missing API Key").ShowAsync();
}
else
{
this.pivot.IsEnabled = true;
await CheckMicrophoneAccessAsync();
if (AnomalyDetectorScenarioLoader.AllModelData == null || !AnomalyDetectorScenarioLoader.AllModelData.Any())
{
await AnomalyDetectorScenarioLoader.InitUserStories();
}
// initialize default tab
this.bikerentalChart.ResetState();
this.bikerentalChart.InitializeChart(AnomalyDetectionScenarioType.BikeRental, AnomalyDetectorServiceType.Streaming, sensitivy: 80);
}
}
catch (Exception ex)
{
await Util.GenericApiCallExceptionHandler(ex, "Failure during navigation to Anomaly Detector Demo.");
}
base.OnNavigatedTo(e);
}
private async Task CheckMicrophoneAccessAsync()
{
try
{
await InitMicrophoneAsync();
this.livePivotItem.IsEnabled = true;
}
catch (Exception ex)
{
this.livePivotItem.IsEnabled = false;
await Util.GenericApiCallExceptionHandler(ex, "Failure during initializing Microphone device. Live demo is disabled.");
}
}
private void TabChanged(PivotItem selectedPivot)
{
bool isAnyData = AnomalyDetectorScenarioLoader.AllModelData != null && AnomalyDetectorScenarioLoader.AllModelData.Any();
if (selectedPivot.Header is TabHeader selectedTab && isAnyData)
{
// clear chart
this.bikerentalChart.ResetState();
this.telecomChart.ResetState();
this.manufacturingChart.ResetState();
this.liveChart.ResetState();
// initialize new chart
if (selectedTab == BikeRentalTab)
{
this.bikerentalChart.InitializeChart(AnomalyDetectionScenarioType.BikeRental, AnomalyDetectorServiceType.Streaming, sensitivy: 80);
}
else if (selectedTab == TelecomTab)
{
this.telecomChart.InitializeChart(AnomalyDetectionScenarioType.Telecom, AnomalyDetectorServiceType.Streaming, sensitivy: 85);
}
else if (selectedTab == ManufacturingTab)
{
this.manufacturingChart.InitializeChart(AnomalyDetectionScenarioType.Manufacturing, AnomalyDetectorServiceType.Streaming, sensitivy: 80);
}
else if (selectedTab == LiveTab)
{
this.liveChart.InitializeChart(AnomalyDetectionScenarioType.Live, AnomalyDetectorServiceType.Streaming, sensitivy: 80);
}
}
}
/// <summary>
/// Process audio frames with MediaFrameReader:
/// https://docs.microsoft.com/en-us/windows/uwp/audio-video-camera/process-audio-frames-with-mediaframereader
/// </summary>
/// <returns></returns>
private async Task InitMicrophoneAsync()
{
mediaCapture = new MediaCapture();
MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings()
{
StreamingCaptureMode = StreamingCaptureMode.Audio,
};
await mediaCapture.InitializeAsync(settings);
var audioFrameSources = mediaCapture.FrameSources.Where(x => x.Value.Info.MediaStreamType == MediaStreamType.Audio);
if (audioFrameSources.Count() == 0)
{
throw new Exception("No audio frame source was found.");
}
MediaFrameSource frameSource = audioFrameSources.FirstOrDefault().Value;
MediaFrameFormat format = frameSource.CurrentFormat;
if (format.Subtype != MediaEncodingSubtypes.Float)
{
throw new Exception($"MediaFrameSource.Subtype is {format.Subtype} and NOT expected.");
}
if (format.AudioEncodingProperties.ChannelCount <= 0)
{
throw new Exception($"AudioEncodingProperties.ChannelCount is 0 and NOT expected.");
}
mediaFrameReader = await mediaCapture.CreateFrameReaderAsync(frameSource);
mediaFrameReader.AcquisitionMode = MediaFrameReaderAcquisitionMode.Buffered;
mediaFrameReader.FrameArrived += MediaFrameReader_AudioFrameArrived;
}
private void MediaFrameReader_AudioFrameArrived(MediaFrameReader sender, MediaFrameArrivedEventArgs args)
{
using (MediaFrameReference reference = sender.TryAcquireLatestFrame())
{
if (reference != null)
{
ProcessAudioFrame(reference.AudioMediaFrame);
}
}
}
unsafe private void ProcessAudioFrame(AudioMediaFrame audioMediaFrame)
{
using (AudioFrame audioFrame = audioMediaFrame.GetAudioFrame())
using (AudioBuffer buffer = audioFrame.LockBuffer(AudioBufferAccessMode.Read))
using (IMemoryBufferReference reference = buffer.CreateReference())
{
((IMemoryBufferByteAccess)reference).GetBuffer(out byte* dataInBytes, out uint capacityInBytes);
// The requested format was float
float* dataInFloat = (float*)dataInBytes;
// Duration can be gotten off the frame reference OR the audioFrame
TimeSpan duration = audioMediaFrame.FrameReference.Duration;
// frameDurMs is in milliseconds, while SampleRate is given per second.
uint frameDurMs = (uint)duration.TotalMilliseconds;
uint sampleRate = audioMediaFrame.AudioEncodingProperties.SampleRate;
uint sampleCount = (frameDurMs * sampleRate) / 1000;
maxVolumeInSampleBuffer = 0;
for (int i = 0; i < sampleCount; i++)
{
maxVolumeInSampleBuffer = Math.Max(maxVolumeInSampleBuffer, dataInFloat[i]);
}
// update volume value
this.liveChart.SetVolumeValue(maxVolumeInSampleBuffer);
}
}
private async void OnStartLiveAudio(object sender, EventArgs e)
{
if (mediaFrameReader != null)
{
MediaFrameReaderStartStatus status = await mediaFrameReader.StartAsync();
if (status != MediaFrameReaderStartStatus.Success)
{
throw new Exception("The MediaFrameReader couldn't start.");
}
}
}
private async void OnStopLiveAudio(object sender, EventArgs e)
{
if (mediaFrameReader != null)
{
await mediaFrameReader.StopAsync();
}
}
}
[ComImport]
[Guid("5B0D3235-4DBA-4D44-865E-8F1D0E4FD04D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
unsafe interface IMemoryBufferByteAccess
{
void GetBuffer(out byte* buffer, out uint capacity);
}
}