Skip to content

Commit

Permalink
updated to use the new IAM authentication for tone analyzer. removed …
Browse files Browse the repository at this point in the history
…'disgust' as an emotion as it was removed from the latest version of the tone analyzer API.
  • Loading branch information
jweisz committed Jan 14, 2019
1 parent c9635a7 commit f8f7e6c
Show file tree
Hide file tree
Showing 34 changed files with 102 additions and 303 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,19 @@ import UIKit

//#-end-hidden-code
/*:
Rebus begins telling Tinker about all the crazy things she witnessed during her travels. Her tales take Tinker on a roller coaster of emotion, from anger and disgust, to fear, joy, and sadness.
Rebus begins telling Tinker about all the crazy things she witnessed during her travels. Her tales take Tinker on a roller coaster of emotion.
**Goal**: Help Tinker understand the emotional content of Rebus' story using the [Watson Tone Analyzer](https://www.ibm.com/watson/developercloud/tone-analyzer.html) service.
1. Open the [Watson Tone Analyzer](https://console.bluemix.net/catalog/services/tone-analyzer) page and tap the "Create" button on the bottom right to create an instance of the service. Sign up for a free Bluemix account if you do not have one already.
2. Tap "Service Credentials" in the left-hand sidebar, then tap "View Credentials" under the Actions menu.
2. Tap "Manage" in the left-hand sidebar, then tap "Show Credentials".
![Tone Analyzer Credentials](tone-analyzer-credentials.png)
3. Fill in your service credentials below. Note that these credentials are saved for future exercises and if you ever need to change your credentials, you will need to re-run this page.
3. Fill in the `apikey` credential below. Note that this credential is saved for future exercises and if you ever need to change your credential, you will need to re-run this page.
*/
Watson.toneAnalyzer.username =
/*#-editable-code*/""/*#-end-editable-code*/
Watson.toneAnalyzer.password =
Watson.toneAnalyzer.apikey =
/*#-editable-code*/""/*#-end-editable-code*/
/*:
4. Use the `tinker.analyzeTone()` method to analyze the tone of a sentence. For each sentence, use `rebus.speak(:_)` to speak the sentence. In addition, shine the LED based on the dominant emotion using the color guide below.
Expand All @@ -32,7 +30,7 @@ Watson.toneAnalyzer.password =
- - -
* Callout(💡 Tip):
`tinker.analyzeTone()` returns a `ToneResponse`, which contains the different dimensions of tone analysis performed by Watson: emotional content, language style, and social tendencies. Use the `emotion` dimension to determine the degree to which a given sentence contains the emotions of joy, anger, disgust, fear, and sadness (1.0 is the highest level). It may help to create a helper function that examines a `ToneResponse` and returns the dominant `Emotion` (e.g. the one with the highest value).
`tinker.analyzeTone()` returns a `ToneResponse`, which contains the different dimensions of tone analysis performed by Watson: emotional content, language style, and social tendencies. Use the `emotion` dimension to determine the degree to which a given sentence contains the emotions of joy, anger, fear, and sadness (1.0 is the highest level). It may help to create a helper function that examines a `ToneResponse` and returns the dominant `Emotion` (e.g. the one with the highest value).
- - -
* Callout(⚠️ Caution):
Expand All @@ -44,7 +42,6 @@ let rebus = RebusTheBee()

enum Emotion: String {
case anger
case disgust
case fear
case joy
case sadness
Expand All @@ -60,14 +57,13 @@ proxy?.delegate = tinker
//#-code-completion(everything, hide)
//#-code-completion(currentmodule, show)
//#-code-completion(identifier, hide, page, proxy)
//#-code-completion(identifier, show, tinker, ., rebus, shine(color:), pulse(color:duration:), sleep(msec:), raiseArm(), lowerArm(), wave(), analyzeTone(text:), speak(_:), sorted(), description, ToneResponse, error, emotion, language, social, anger, disgust, fear, joy, sadness, analytical, confident, tentative, openness, conscientiousness, extraversion, agreeableness, emotionalRange)
//#-code-completion(identifier, show, tinker, ., rebus, shine(color:), pulse(color:duration:), sleep(msec:), raiseArm(), lowerArm(), wave(), analyzeTone(text:), speak(_:), sorted(), description, ToneResponse, error, emotion, language, social, anger, fear, joy, sadness, analytical, confident, tentative, openness, conscientiousness, extraversion, agreeableness, emotionalRange)
//#-code-completion(literal, show, color)
//#-code-completion(keyword, show, for)
let story: [String] = [
// Rebus' story is hidden in this array. Iterate over it to hear the story!
//#-hidden-code
"The world of YouTube is one of the strangest places I've ever been. When I first arrived, I was swarmed by a mob of the most adorable puppies and kittens -- it was amazing!", // joy
"Not long afterwards, I met a man who had become a millionaire by eating gross foods on camera -- the things humans find valuable never cease to amaze me.", // disgust
"I stopped in a small town called 4chan. There was a man hanging out at the rest stop, so I asked him if he could watch my suitcase while I used the ladybee's room. When I came back out, the man was gone and so was my suitcase. In its place was a drawing of a troll with a cruel grin on its face. I've never been so angry in my life!", // anger
"I was told that a man named Craig had a giant list of things for sale, so I decided to go see if he could help me replace my suitcase. But when I got there, I discovered that Craig's list was full of strange and scary items. I was quite frightened by what I saw, so I decided to get out of there as quick as possible!", // fear
"All in all, it was an interesting and eye-opening journey. I'm sad you couldn't join me." // sadness
Expand All @@ -82,7 +78,6 @@ func getPrimaryEmotion(from toneResponse: ToneResponse) -> Emotion {

let dict: [Emotion: Double] = [
.anger: toneResponse.emotion.anger,
.disgust: toneResponse.emotion.disgust,
.fear: toneResponse.emotion.fear,
.joy: toneResponse.emotion.joy,
.sadness: toneResponse.emotion.sadness
Expand All @@ -104,8 +99,6 @@ for sentence in story {
break
case .anger:
tinker.shine(color: UIColor.red)
case .disgust:
tinker.shine(color: UIColor.green)
case .fear:
tinker.shine(color: UIColor.purple)
case .joy:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
```
let dict: [Emotion: Double] = [
.anger: toneResponse.emotion.anger,
.disgust: toneResponse.emotion.disgust,
.fear: toneResponse.emotion.fear,
...
]
```</string>
Expand All @@ -31,7 +31,6 @@ let dict: [Emotion: Double] = [
<string>```
let dict: [Emotion: Double] = [
.anger: toneResponse.emotion.anger,
.disgust: toneResponse.emotion.disgust,
.fear: toneResponse.emotion.fear,
.joy: toneResponse.emotion.joy,
.sadness: toneResponse.emotion.sadness
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ func getPrimaryEmotion(from toneResponse: ToneResponse) -> Emotion {

let dict: [Emotion: Double] = [
.anger: toneResponse.emotion.anger,
.disgust: toneResponse.emotion.disgust,
.fear: toneResponse.emotion.fear,
.joy: toneResponse.emotion.joy,
.sadness: toneResponse.emotion.sadness
Expand All @@ -30,8 +29,6 @@ for sentence in story {
break
case .anger:
tinker.shine(color: UIColor.red)
case .disgust:
tinker.shine(color: UIColor.green)
case .fear:
tinker.shine(color: UIColor.purple)
case .joy:
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,18 @@ public var hints: AssessmentHints = [
* - accepts
*/
public func evaluate(commandList: [String]?, dataList: [AnyObject]?) -> AssessmentResult {
//this should contain 5 shines
//this should contain 4 shines
guard let commandList = commandList,
commandList.contains("shine"),
commandList.count == 5 else {
commandList.count == 4 else {
return .failed
}
for command in commandList {
guard command == "shine" else { return .failed }
}
//this should contain 5 specific colors
//this should contain 4 specific colors
guard let colorList = dataList,
colorList.count == 5 else {
colorList.count == 4 else {
return .failed
}
var count = 0
Expand Down Expand Up @@ -62,23 +62,18 @@ func checkColorInRange(color: UIColor, count: Int) -> Bool {
return true
}
case 1:
//disgust check for green
if hueDegrees > 70 && hueDegrees < 160 {
return true
}
case 2:
//Anger
//check if the color is red
if hueDegrees < 35 || hueDegrees > 340 {
return true
}
case 3:
case 2:
//Fear
//check if the color is Magenta
if hueDegrees > 270 && hueDegrees < 340 {
return true
}
case 4:
case 3:
//check if the color is blue
if hueDegrees > 170 && hueDegrees < 255 {
return true
Expand All @@ -91,7 +86,6 @@ func checkColorInRange(color: UIColor, count: Int) -> Bool {

//order that is should come in
//joy
//disgust
//anger
//fear
//sadness
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import UIKit
1. Open the [Watson Language Translator](https://console.bluemix.net/catalog/services/language-translator) page and tap the "Create" button on the bottom right to create an instance of the service. Sign up for a free Bluemix account if you do not have one already.
2. Tap "Service Credentials" in the left-hand sidebar, then tap "View Credentials" under the Actions menu.
2. Tap "Manage" in the left-hand sidebar, then tap "Show Credentials".
![Language Translator Credentials](language-translator-credentials.png)
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import UIKit
//#-code-completion(everything, hide)
//#-code-completion(currentmodule, show)
//#-code-completion(identifier, hide, page, proxy)
//#-code-completion(identifier, show, tinker, ., rebus, shine(color:), pulse(color:duration:), sleep(duration:), raiseArm(), lowerArm(), wave(), analyzeTone(text:), speak(_:), identifyLanguage(text:), translate(text:sourceLanguage:targetLanguage:), sorted(), description, ToneResponse, error, emotion, language, social, anger, disgust, fear, joy, sadness, analytical, confident, tentative, openness, conscientiousness, extraversion, agreeableness, emotionalRange, TJTranslationLanguage, unknown, arabic, chinese, german, english, french, italian, japanese, korean, spanish, portuguese, languageName, LanguageIdentification, language, confidence)
//#-code-completion(identifier, show, tinker, ., rebus, shine(color:), pulse(color:duration:), sleep(duration:), raiseArm(), lowerArm(), wave(), analyzeTone(text:), speak(_:), identifyLanguage(text:), translate(text:sourceLanguage:targetLanguage:), sorted(), description, ToneResponse, error, emotion, language, social, anger, fear, joy, sadness, analytical, confident, tentative, openness, conscientiousness, extraversion, agreeableness, emotionalRange, TJTranslationLanguage, unknown, arabic, chinese, german, english, french, italian, japanese, korean, spanish, portuguese, languageName, LanguageIdentification, language, confidence)
//#-code-completion(literal, show, color)
let tinker = VirtualTJBot()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ PlaygroundPage.current.needsIndefiniteExecution = true
//#-code-completion(everything, hide)
//#-code-completion(currentmodule, show)
//#-code-completion(identifier, hide, page, proxy)
//#-code-completion(identifier, show, tj, ., shine(color:), pulse(color:duration:), raiseArm(), lowerArm(), wave(), sleep(duration:), speak(_:), listen(_:), see(), read(), converse(workspaceId:message:), analyzeTone(text:), identifyLanguage(text:), translate(text:sourceLanguage:targetLanguage:), components(separatedBy:), contains(_:), lowercased(), sorted(), description, ToneResponse, error, emotion, language, social, anger, disgust, fear, joy, sadness, analytical, confident, tentative, openness, conscientiousness, extraversion, agreeableness, emotionalRange, TJTranslationLanguage, unknown, arabic, chinese, german, english, french, italian, japanese, korean, spanish, portuguese, languageName, LanguageIdentification, language, confidence, highestConfidenceLanguage, VisionResponse, objects, VisualObjectIdentification, name, confidence, highestConfidenceObject, ConversationResponse, text, arc4random_uniform(_:), UInt32, Int)
//#-code-completion(identifier, show, tj, ., shine(color:), pulse(color:duration:), raiseArm(), lowerArm(), wave(), sleep(duration:), speak(_:), listen(_:), see(), read(), converse(workspaceId:message:), analyzeTone(text:), identifyLanguage(text:), translate(text:sourceLanguage:targetLanguage:), components(separatedBy:), contains(_:), lowercased(), sorted(), description, ToneResponse, error, emotion, language, social, anger, fear, joy, sadness, analytical, confident, tentative, openness, conscientiousness, extraversion, agreeableness, emotionalRange, TJTranslationLanguage, unknown, arabic, chinese, german, english, french, italian, japanese, korean, spanish, portuguese, languageName, LanguageIdentification, language, confidence, highestConfidenceLanguage, VisionResponse, objects, VisualObjectIdentification, name, confidence, highestConfidenceObject, ConversationResponse, text, arc4random_uniform(_:), UInt32, Int)
//#-code-completion(literal, show, color)
let tj = PhysicalTJBot()

Expand Down
2 changes: 1 addition & 1 deletion TJBot (Solutions).playgroundbook/Contents/Manifest.plist
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<key>ContentIdentifier</key>
<string>com.ibm.research.tjbot</string>
<key>ContentVersion</key>
<string>2.4</string>
<string>2.5</string>
<key>DeploymentTarget</key>
<string>ios10.0</string>
<key>DevelopmentRegion</key>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,14 @@ class ToneDashboardCell: DashboardTextCell {

let emotions = toneResponse.emotion
let languages = toneResponse.language
let socialTones = toneResponse.social

messageString = "Anger: \(getPercentage(emotions.anger))\n" +
"Disgust: \(getPercentage(emotions.disgust))\n" +
"Fear: \(getPercentage(emotions.fear))\n" +
"Joy: \(getPercentage(emotions.joy))\n" +
"Sadness: \(getPercentage(emotions.sadness))\n" +
"Analytical: \(getPercentage(languages.analytical))\n" +
"Confident: \(getPercentage(languages.confident))\n" +
"Tentative: \(getPercentage(languages.tentative))\n" +
"Openness: \(getPercentage(socialTones.openness))\n" +
"Conscientiousness: \(getPercentage(socialTones.conscientiousness))\n" +
"Extraversion: \(getPercentage(socialTones.extraversion))\n" +
"Agreeableness: \(getPercentage(socialTones.agreeableness))\n" +
"Emotional Range: \(getPercentage(socialTones.emotionalRange))"
"Tentative: \(getPercentage(languages.tentative))\n"
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,13 @@ import SceneKit

enum BotEmotion: String {
case anger
case disgust
case fear
case joy
case sadness
}

enum BotEmotionImages: String {
case anger = "Anger.png"
case disgust = "Disgust.png"
case fear = "Fear.png"
case joy = "Joy.png"
case sadness = "Sadness.png"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -607,9 +607,6 @@ extension VirtualTJBotViewController: Emotes {
case BotEmotion.anger.rawValue:
emotionController.showEmotion(.anger)
changeLedColor(UIColor.red)
case BotEmotion.disgust.rawValue:
emotionController.showEmotion(.disgust)
changeLedColor(UIColor.init(red: 0, green: 0.7, blue: 0, alpha: 0))
case BotEmotion.fear.rawValue:
emotionController.showEmotion(.fear)
changeLedColor(UIColor.magenta)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class ToneAnalyzer {
/// The default HTTP headers for all requests to the service.
public var defaultHeaders = [String: String]()

private let version: String = "2016-05-19"
private let version: String = "2017-09-21"
private let domain = "com.ibm.watson.developer-cloud.ToneAnalyzerV3"

/**
Expand Down Expand Up @@ -66,7 +66,6 @@ public class ToneAnalyzer {
if let sentences = sentences {
queryParameters.append(URLQueryItem(name: "sentences", value: "\(sentences)"))
}


let urlString = serviceURL + "/v3/tone"
var urlComponents = URLComponents(string: urlString)
Expand All @@ -83,11 +82,11 @@ public class ToneAnalyzer {
//user agent
let os = ProcessInfo.processInfo.operatingSystemVersion
let operatingSystemVersion = "\(os.majorVersion).\(os.minorVersion).\(os.patchVersion)"
request.setValue("watson-apis-swift-sdk/0.15.1/iOS/\(operatingSystemVersion)", forHTTPHeaderField: "User-Agent")
request.setValue("watson-apis-swift-sdk/0.35.0/iOS/\(operatingSystemVersion)", forHTTPHeaderField: "User-Agent")

//authentication
let username = Watson.toneAnalyzer.username
let password = Watson.toneAnalyzer.password
let username = "apikey"
let password = Watson.toneAnalyzer.apikey
let authData = (username + ":" + password).data(using: .utf8)!
let authString = authData.base64EncodedString()
request.setValue("Basic \(authString)", forHTTPHeaderField: "Authorization")
Expand All @@ -98,7 +97,6 @@ public class ToneAnalyzer {
request.setValue(value, forHTTPHeaderField: key)
}


let session = URLSession(configuration: URLSessionConfiguration.default)
session.dataTask(with: request) { (data, response, error) in
if let error = error,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,6 @@ public struct Watson {
}
}

public static var toneAnalyzer = UsernamePasswordCredential(service: "toneAnalyzer")
public static var toneAnalyzer = APIKeyCredential(service: "toneAnalyzer")
public static var languageTranslator = APIKeyCredential(service: "languageTranslator")
}
Loading

0 comments on commit f8f7e6c

Please sign in to comment.