Created
November 1, 2017 00:17
-
-
Save shanev/cee17b95b44e32adcdfe548c336e1af5 to your computer and use it in GitHub Desktop.
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 = "https://pbs.twimg.com/profile_images/853106910861643776/tZh0rhmL.jpg" | |
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