Skip to content

Instantly share code, notes, and snippets.

@shanev
Created April 4, 2018 13:19
Show Gist options
  • Save shanev/c70099b3305e71c6a1232a42029f703f to your computer and use it in GitHub Desktop.
Save shanev/c70099b3305e71c6a1232a42029f703f to your computer and use it in GitHub Desktop.
Output emoji representing facial emotion for an image or video frame
import Foundation
import PlaygroundSupport
let apiKey = API_KEY
let endPointUrl = "https://westus.api.cognitive.microsoft.com/emotion/v1.0"
let url = URL(string: "\(endPointUrl)/recognize")!
let testImageString = TEST_IMAGE
struct Response: Decodable {
let scores: Score
}
struct Score: Decodable {
let anger: Float
let contempt: Float
let disgust: Float
let fear: Float
let happiness: Float
let neutral: Float
let sadness: Float
let surprise: Float
}
enum ScoreEmoji: Int {
case ๐Ÿ˜ก, ๐Ÿ™„, ๐Ÿคข, ๐Ÿ˜ฑ, ๐Ÿ˜Š, ๐Ÿ˜, ๐Ÿ˜ญ, ๐Ÿ˜ฎ
init(_ index: Int) {
self.init(rawValue: index)!
}
}
// prepare json data
let json: [String: Any] = ["url": testImageString]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
// create post request
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue(apiKey, forHTTPHeaderField: "Ocp-Apim-Subscription-Key")
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
do {
let responses = try JSONDecoder().decode([Response].self, from: data)
if let response = responses.first {
let score = response.scores
let values = [score.anger, score.contempt, score.disgust, score.fear, score.happiness, score.neutral, score.sadness, score.surprise]
if let max = values.max(), let index = values.index(of: max) {
let sentiment = ScoreEmoji(index)
print(sentiment)
}
}
} catch(let error) {
print(error)
}
PlaygroundPage.current.finishExecution()
}.resume()
PlaygroundPage.current.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment