Created
April 4, 2018 13:19
-
-
Save shanev/c70099b3305e71c6a1232a42029f703f to your computer and use it in GitHub Desktop.
Output emoji representing facial emotion for an image or video frame
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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