Skip to content

Instantly share code, notes, and snippets.

@jinalshah999
Created September 7, 2017 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jinalshah999/3c3bc5e16c8b03670539b4210ddde5bf to your computer and use it in GitHub Desktop.
Save jinalshah999/3c3bc5e16c8b03670539b4210ddde5bf to your computer and use it in GitHub Desktop.
private async Task GetEmotion(string imageUri)
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "Your_key_Bing_Emotion_API");
// Request parameters
var uri = "https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize?" + queryString;
EmotionRequest request = new EmotionRequest();
request.url = imageUri;
byte[] byteData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(request));
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync(uri, content);
var json = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
List<EmotionResponse> emotionResponse =
JsonConvert.DeserializeObject<List<EmotionResponse>>(json);
if (emotionResponse != null && emotionResponse.Count > 0)
{
var scores = emotionResponse[0].scores;
Dictionary<string, double> dScores = new Dictionary<string, double>();
dScores.Add("anger", scores.anger);
dScores.Add("contempt", scores.contempt);
dScores.Add("disgust", scores.disgust);
dScores.Add("fear", scores.fear);
dScores.Add("happiness", scores.happiness);
dScores.Add("neutral", scores.neutral);
dScores.Add("sadness", scores.sadness);
dScores.Add("surprise", scores.surprise);
var highestScore = dScores.Values.OrderByDescending(score => score).First();
//probably a more elegant way to do this.
var highestEmotion = dScores.Keys.First(key => dScores[key] == highestScore);
await Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Normal,
new Action(
() =>
{
this.MySpeechSentiment.Text = $"Emotion: {highestEmotion},";
this.MySpeechSentimentConfidence.Text =
$"confidence: {Convert.ToInt16(highestScore * 100)}%";
}));
}
else
{
this.MySpeechSentiment.Text = $"I'm not able to get the emotion, sorry.";
}
}
else
{
await Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Normal,
new Action(() => { this.MySpeechSentiment.Text = "Could not get emotion from this image";
}));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment