forked from microsoft/Cognitive-Samples-IntelligentKiosk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMallKioskPage.xaml.cs
405 lines (347 loc) · 17 KB
/
MallKioskPage.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//
// 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.Controls;
using IntelligentKioskSample.MallKioskPageConfig;
using Microsoft.Azure.CognitiveServices.Vision.Face.Models;
using ServiceHelpers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Popups;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace IntelligentKioskSample.Views
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
[KioskExperience(Title = "Mall Kiosk", ImagePath = "ms-appx:/Assets/mall.png", ExperienceType = ExperienceType.Kiosk)]
public sealed partial class MallKioskPage : Page
{
private MallKioskDemoSettings kioskSettings;
private Recommendation currentRecommendation;
public ObservableCollection<EmotionExpressionCapture> EmotionFaces { get; set; } = new ObservableCollection<EmotionExpressionCapture>();
public MallKioskPage()
{
this.InitializeComponent();
this.cameraControl.ImageCaptured += CameraControl_ImageCaptured;
this.cameraControl.CameraRestarted += CameraControl_CameraRestarted;
this.cameraControl.FilterOutSmallFaces = true;
this.speechToTextControl.SpeechRecognitionAndSentimentProcessed += OnSpeechRecognitionAndSentimentProcessed;
this.emotionFacesGrid.DataContext = this;
}
private async void CameraControl_CameraRestarted(object sender, EventArgs e)
{
await this.ResetRecommendationUI();
}
private async Task ResetRecommendationUI()
{
this.webView.NavigateToString("");
this.webView.Visibility = Visibility.Collapsed;
// We induce a delay here to give the camera some time to start rendering before we hide the last captured photo.
// This avoids a black flash.
await Task.Delay(500);
this.imageFromCameraWithFaces.DataContext = null;
this.imageFromCameraWithFaces.Visibility = Visibility.Collapsed;
}
private void OnSpeechRecognitionAndSentimentProcessed(object sender, SpeechRecognitionAndSentimentResult e)
{
if (this.currentRecommendation != null)
{
string alternativeUrl = null;
// See if there is an alternative result based on keywords in the spoken text
if (this.currentRecommendation.SpeechKeywordBehavior != null)
{
BehaviorAction behaviorAction = this.currentRecommendation.SpeechKeywordBehavior.FirstOrDefault(behavior => e.SpeechRecognitionText.IndexOf(behavior.Key, StringComparison.OrdinalIgnoreCase) != -1);
if (behaviorAction != null)
{
alternativeUrl = behaviorAction.Url;
}
}
// If we didn't find an alternative based on keywords see if we have a generic one based on the sentiment of the spoken text
if (string.IsNullOrEmpty(alternativeUrl) && this.currentRecommendation.SpeechSentimentBehavior != null)
{
BehaviorAction behaviorAction = null;
if (e.TextAnalysisSentiment <= 0.33)
{
// look for an override for negative sentiment
behaviorAction = this.currentRecommendation.SpeechSentimentBehavior.FirstOrDefault(behavior => string.Compare(behavior.Key, "Negative", true) == 0);
}
else if (e.TextAnalysisSentiment >= 0.66)
{
// look for an override for positive sentiment
behaviorAction = this.currentRecommendation.SpeechSentimentBehavior.FirstOrDefault(behavior => string.Compare(behavior.Key, "Positive", true) == 0);
}
if (behaviorAction != null)
{
alternativeUrl = behaviorAction.Url;
}
}
if (!string.IsNullOrEmpty(alternativeUrl))
{
webView.Navigate(new Uri(alternativeUrl));
}
}
}
private async void CameraControl_ImageCaptured(object sender, ImageAnalyzer e)
{
this.imageFromCameraWithFaces.DataContext = e;
this.imageFromCameraWithFaces.Visibility = Visibility.Visible;
// We induce a delay here to give the captured image some time to render before we hide the camera.
// This avoids a black flash.
await Task.Delay(50);
await this.cameraControl.StopStreamAsync();
e.FaceRecognitionCompleted += (s, args) =>
{
ShowRecommendations(e);
};
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
if (!string.IsNullOrEmpty(SettingsHelper.Instance.MallKioskDemoCustomSettings))
{
try
{
string escapedContent = SettingsHelper.Instance.MallKioskDemoCustomSettings.Replace("&", "&");
this.kioskSettings = await MallKioskDemoSettings.FromContentAsync(escapedContent);
}
catch (Exception ex)
{
await Util.GenericApiCallExceptionHandler(ex, "Failure parsing custom recommendation URLs. Will use default values instead.");
}
}
if (this.kioskSettings == null)
{
this.kioskSettings = await MallKioskDemoSettings.FromFileAsync("Views\\MallKioskDemoConfig\\MallKioskDemoSettings.xml");
}
EnterKioskMode();
if (string.IsNullOrEmpty(SettingsHelper.Instance.FaceApiKey))
{
await new MessageDialog("Missing Face API Key. Please enter a key in the Settings page.", "Missing Face API Key").ShowAsync();
}
await this.cameraControl.StartStreamAsync(isForRealTimeProcessing: true);
this.UpdateWebCamHostGridSize();
this.StartEmotionProcessingLoop();
base.OnNavigatedTo(e);
}
private void UpdateWebCamHostGridSize()
{
this.webCamHostGrid.Width = Math.Round(this.ActualWidth * 0.25);
this.webCamHostGrid.Height = Math.Round(this.webCamHostGrid.Width / (this.cameraControl.CameraAspectRatio != 0 ? this.cameraControl.CameraAspectRatio : 1.777777777777));
}
private void EnterKioskMode()
{
ApplicationView view = ApplicationView.GetForCurrentView();
if (!view.IsFullScreenMode)
{
view.TryEnterFullScreenMode();
}
}
protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
this.isProcessingLoopInProgress = false;
await this.cameraControl.StopStreamAsync();
this.speechToTextControl.DisposeSpeechRecognizer();
base.OnNavigatingFrom(e);
}
private void ShowRecommendations(ImageAnalyzer imageWithFaces)
{
Recommendation recommendation = null;
this.currentRecommendation = null;
int numberOfPeople = imageWithFaces.DetectedFaces.Count();
if (numberOfPeople == 1)
{
// Single person
IdentifiedPerson identifiedPerson = imageWithFaces.IdentifiedPersons.FirstOrDefault();
if (identifiedPerson != null)
{
// See if we have a personalized recommendation for this person.
recommendation = this.kioskSettings.PersonalizedRecommendations.FirstOrDefault(r => r.Id.Equals(identifiedPerson.Person.Name, StringComparison.OrdinalIgnoreCase));
}
if (recommendation == null)
{
// Didn't find a personalized recommendation (or we don't have anyone recognized), so default to
// the age/gender-based generic recommendation
DetectedFace face = imageWithFaces.DetectedFaces.First();
recommendation = this.kioskSettings.GetGenericRecommendationForPerson((int)face.FaceAttributes.Age, face.FaceAttributes.Gender);
}
}
else if (numberOfPeople > 1 && imageWithFaces.DetectedFaces.Any(f => f.FaceAttributes.Age <= 12) &&
imageWithFaces.DetectedFaces.Any(f => f.FaceAttributes.Age > 12))
{
// Group with at least one child
recommendation = this.kioskSettings.GenericRecommendations.FirstOrDefault(r => r.Id == "ChildWithOneOrMoreAdults");
}
else if (numberOfPeople > 1 && !imageWithFaces.DetectedFaces.Any(f => f.FaceAttributes.Age <= 12))
{
// Group of adults without a child
recommendation = this.kioskSettings.GenericRecommendations.FirstOrDefault(r => r.Id == "TwoOrMoreAdults");
}
if (recommendation != null)
{
webView.Navigate(new Uri(recommendation.Url));
webView.Visibility = Visibility.Visible;
this.currentRecommendation = recommendation;
}
}
private void PageSizeChanged(object sender, SizeChangedEventArgs e)
{
this.UpdateWebCamHostGridSize();
}
#region Real-time Emotion Feed
private Task processingLoopTask;
private bool isProcessingLoopInProgress;
private bool isProcessingPhoto;
private bool isEmotionResponseFlyoutOpened;
private async void OnEmotionTrackingFlyoutOpened(object sender, object e)
{
await this.cameraControl.StartStreamAsync();
this.isEmotionResponseFlyoutOpened = true;
}
private async void OnEmotionTrackingFlyoutClosed(object sender, object e)
{
this.isEmotionResponseFlyoutOpened = false;
await this.ResetRecommendationUI();
}
private void StartEmotionProcessingLoop()
{
this.isProcessingLoopInProgress = true;
if (this.processingLoopTask == null || this.processingLoopTask.Status != TaskStatus.Running)
{
this.processingLoopTask = Task.Run(() => this.ProcessingLoop());
}
}
private async void ProcessingLoop()
{
while (this.isProcessingLoopInProgress)
{
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
if (!this.isProcessingPhoto && this.isEmotionResponseFlyoutOpened)
{
this.isProcessingPhoto = true;
if (this.cameraControl.NumFacesOnLastFrame == 0)
{
await ProcessCameraCapture(null);
}
else
{
await this.ProcessCameraCapture(await this.cameraControl.CaptureFrameAsync());
}
}
});
await Task.Delay(1000);
}
}
private async Task ProcessCameraCapture(ImageAnalyzer e)
{
if (e == null)
{
this.isProcessingPhoto = false;
return;
}
// detect emotions
await e.DetectFacesAsync(detectFaceAttributes: true);
if (e.DetectedFaces.Any())
{
// Update the average emotion response
Emotion averageScores = new Emotion
{
Happiness = e.DetectedFaces.Average(f => f.FaceAttributes.Emotion.Happiness),
Anger = e.DetectedFaces.Average(f => f.FaceAttributes.Emotion.Anger),
Sadness = e.DetectedFaces.Average(f => f.FaceAttributes.Emotion.Sadness),
Contempt = e.DetectedFaces.Average(f => f.FaceAttributes.Emotion.Contempt),
Disgust = e.DetectedFaces.Average(f => f.FaceAttributes.Emotion.Disgust),
Neutral = e.DetectedFaces.Average(f => f.FaceAttributes.Emotion.Neutral),
Fear = e.DetectedFaces.Average(f => f.FaceAttributes.Emotion.Fear),
Surprise = e.DetectedFaces.Average(f => f.FaceAttributes.Emotion.Surprise)
};
double positiveEmotionResponse = Math.Min(averageScores.Happiness + averageScores.Surprise, 1);
double negativeEmotionResponse = Math.Min(averageScores.Sadness + averageScores.Fear + averageScores.Disgust + averageScores.Contempt, 1);
double netResponse = ((positiveEmotionResponse - negativeEmotionResponse) * 0.5) + 0.5;
this.sentimentControl.Sentiment = netResponse;
// show captured faces and their emotion
if (this.emotionFacesGrid.Visibility == Visibility.Visible)
{
foreach (var face in e.DetectedFaces)
{
// Get top emotion on this face
KeyValuePair<string, double> topEmotion = Util.EmotionToRankedList(face.FaceAttributes.Emotion).First();
// Crop this face
FaceRectangle rect = face.FaceRectangle;
double heightScaleFactor = 1.8;
double widthScaleFactor = 1.8;
FaceRectangle biggerRectangle = new FaceRectangle
{
Height = Math.Min((int)(rect.Height * heightScaleFactor), e.DecodedImageHeight),
Width = Math.Min((int)(rect.Width * widthScaleFactor), e.DecodedImageWidth)
};
biggerRectangle.Left = Math.Max(0, rect.Left - (int)(rect.Width * ((widthScaleFactor - 1) / 2)));
biggerRectangle.Top = Math.Max(0, rect.Top - (int)(rect.Height * ((heightScaleFactor - 1) / 1.4)));
ImageSource croppedImage = await Util.GetCroppedBitmapAsync(e.GetImageStreamCallback, biggerRectangle);
// Add the face and emotion to the collection of faces
if (croppedImage != null && biggerRectangle.Height > 0 && biggerRectangle.Width > 0)
{
if (this.EmotionFaces.Count >= 9)
{
this.EmotionFaces.Clear();
}
this.EmotionFaces.Add(new EmotionExpressionCapture { CroppedFace = croppedImage, TopEmotion = topEmotion.Key });
}
}
}
}
this.isProcessingPhoto = false;
}
#endregion
private void OnEmotionFacesToggleUnchecked(object sender, RoutedEventArgs e)
{
emotionFacesGrid.Visibility = Visibility.Collapsed;
}
private void OnEmotionFacesToggleChecked(object sender, RoutedEventArgs e)
{
emotionFacesGrid.Visibility = Visibility.Visible;
}
}
public class EmotionExpressionCapture
{
public ImageSource CroppedFace { get; set; }
public string TopEmotion { get; set; }
}
}