This repository has been archived by the owner on Jul 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 106
/
tone_detection.js
executable file
·289 lines (261 loc) · 9.88 KB
/
tone_detection.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/**
* Copyright 2018 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
'use strict';
/* eslint-env es6 */
var Promise = require('bluebird');
/**
* Thresholds for identifying meaningful tones returned by the Watson Tone
* Analyzer. Current values are based on the recommendations made by the Watson
* Tone Analyzer at
* https://www.ibm.com/watson/developercloud/doc/tone-analyzer/understanding-tone.shtml
* These thresholds can be adjusted to client/domain requirements.
*/
var PRIMARY_EMOTION_SCORE_THRESHOLD = 0.5;
var LANGUAGE_HIGH_SCORE_THRESHOLD = 0.75;
var LANGUAGE_NO_SCORE_THRESHOLD = 0.0;
var SOCIAL_HIGH_SCORE_THRESHOLD = 0.75;
var SOCIAL_LOW_SCORE_THRESHOLD = 0.25;
/**
* Labels for the tone categories returned by the Watson Tone Analyzer
*/
var EMOTION_TONE_LABEL = 'emotion_tone';
var LANGUAGE_TONE_LABEL = 'language_tone';
var SOCIAL_TONE_LABEL = 'social_tone';
/**
* Public functions for this module
*/
module.exports = {
updateUserTone: updateUserTone,
invokeToneAsync: invokeToneAsync,
initUser: initUser
};
/**
* invokeToneAsync is an asynchronous function that calls the Tone Analyzer
* service and returns a Promise
*
* @param {Json}
* conversationPayload json object returned by the Watson
* Conversation Service
* @param {Object}
* toneAnalyzer an instance of the Watson Tone Analyzer service
* @returns {Promise} a Promise for the result of calling the toneAnalyzer with
* the conversationPayload (which contains the user's input text)
*/
function invokeToneAsync(conversationPayload, toneAnalyzer) {
if (!conversationPayload.input || !conversationPayload.input.text || conversationPayload.input.text.trim() == '')
conversationPayload.input.text = '<empty>';
return new Promise(function(resolve, reject) {
toneAnalyzer.tone({
text: conversationPayload.input.text
}, (error, data) => {
if (error) {
reject(error);
} else {
resolve(data);
}
});
});
}
/**
* updateUserTone processes the Tone Analyzer payload to pull out the emotion,
* language and social tones, and identify the meaningful tones (i.e., those
* tones that meet the specified thresholds). The conversationPayload json
* object is updated to include these tones.
*
* @param {Json}
* conversationPayload json object returned by the Watson
* Conversation Service
* @param {Json}
* toneAnalyzerPayload json object returned by the Watson Tone
* Analyzer Service
* @param {boolean}
* maintainHistory set history for each user turn in the history
* context variable
* @returns {void}
*/
function updateUserTone(conversationPayload, toneAnalyzerPayload, maintainHistory) {
var emotionTone = null;
var languageTone = null;
var socialTone = null;
if (!conversationPayload.context) {
conversationPayload.context = {};
}
if (!conversationPayload.context.user) {
conversationPayload.context.user = initUser();
}
// For convenience sake, define a variable for the user object
var user = conversationPayload.context.user;
// Extract the tones - emotion, language and social
if (toneAnalyzerPayload && toneAnalyzerPayload.document_tone) {
toneAnalyzerPayload.document_tone.tone_categories.forEach(function(toneCategory) {
if (toneCategory.category_id === EMOTION_TONE_LABEL) {
emotionTone = toneCategory;
}
if (toneCategory.category_id === LANGUAGE_TONE_LABEL) {
languageTone = toneCategory;
}
if (toneCategory.category_id === SOCIAL_TONE_LABEL) {
socialTone = toneCategory;
}
});
updateEmotionTone(user, emotionTone, maintainHistory);
updateLanguageTone(user, languageTone, maintainHistory);
updateSocialTone(user, socialTone, maintainHistory);
}
conversationPayload.context.user = user;
return conversationPayload;
}
/**
* initToneContext initializes a user object containing tone data (from the
* Watson Tone Analyzer)
*
* @returns {Json} user json object with the emotion, language and social tones.
* The current tone identifies the tone for a specific conversation
* turn, and the history provides the conversation for all tones up to
* the current tone for a conversation instance with a user.
*/
function initUser() {
return ({
'tone': {
'emotion': {
'current': null
},
'language': {
'current': null
},
'social': {
'current': null
}
}
});
}
/**
* updateEmotionTone updates the user emotion tone with the primary emotion -
* the emotion tone that has a score greater than or equal to the
* EMOTION_SCORE_THRESHOLD; otherwise primary emotion will be 'neutral'
*
* @param {Json}
* user a json object representing user information (tone) to be
* used in conversing with the Conversation Service
* @param {Json}
* emotionTone a json object containing the emotion tones in the
* payload returned by the Tone Analyzer
* @param {boolean}
* maintainHistory set history for each user turn in the history
* context variable
* @returns {void}
*/
function updateEmotionTone(user, emotionTone, maintainHistory) {
var maxScore = 0.0;
var primaryEmotion = null;
var primaryEmotionScore = null;
emotionTone.tones.forEach(function(tone) {
if (tone.score > maxScore) {
maxScore = tone.score;
primaryEmotion = tone.tone_name.toLowerCase();
primaryEmotionScore = tone.score;
}
});
if (maxScore <= PRIMARY_EMOTION_SCORE_THRESHOLD) {
primaryEmotion = 'neutral';
primaryEmotionScore = null;
}
// update user emotion tone
user.tone.emotion.current = primaryEmotion;
if (maintainHistory) {
if (typeof user.tone.emotion.history === 'undefined') {
user.tone.emotion.history = [];
}
user.tone.emotion.history.push({'tone_name': primaryEmotion, 'score': primaryEmotionScore});
}
}
/**
* updateLanguageTone updates the user with the language tones interpreted based
* on the specified thresholds
*
* @param {Json}
* user a json object representing user information (tone) to be
* used in conversing with the Conversation Service
* @param {Json}
* languageTone a json object containing the language tones in
* the payload returned by the Tone Analyzer
* @param {boolean}
* maintainHistory set history for each user turn in the history
* context variable
* @returns {void}
*/
function updateLanguageTone(user, languageTone, maintainHistory) {
var currentLanguage = [];
var currentLanguageObject = [];
// Process each language tone and determine if it is high or low
languageTone.tones.forEach(function(tone) {
if (tone.score >= LANGUAGE_HIGH_SCORE_THRESHOLD) {
currentLanguage.push(tone.tone_name.toLowerCase() + '_high');
currentLanguageObject.push({'tone_name': tone.tone_name.toLowerCase(), 'score': tone.score, 'interpretation': 'likely high'});
} else if (tone.score <= LANGUAGE_NO_SCORE_THRESHOLD) {
currentLanguageObject.push({'tone_name': tone.tone_name.toLowerCase(), 'score': tone.score, 'interpretation': 'no evidence'});
} else {
currentLanguageObject.push({'tone_name': tone.tone_name.toLowerCase(), 'score': tone.score, 'interpretation': 'likely medium'});
}
});
// update user language tone
user.tone.language.current = currentLanguage;
if (maintainHistory) {
if (typeof user.tone.language.history === 'undefined') {
user.tone.language.history = [];
}
user.tone.language.history.push(currentLanguageObject);
}
}
/**
* updateSocialTone updates the user with the social tones interpreted based on
* the specified thresholds
*
* @param {Json}
* user a json object representing user information (tone) to be
* used in conversing with the Conversation Service
* @param {Json}
* socialTone a json object containing the social tones in the
* payload returned by the Tone Analyzer
* @param {boolean}
* maintainHistory set history for each user turn in the history
* context variable
* @returns {void}
*/
function updateSocialTone(user, socialTone, maintainHistory) {
var currentSocial = [];
var currentSocialObject = [];
// Process each social tone and determine if it is high or low
socialTone.tones.forEach(function(tone) {
if (tone.score >= SOCIAL_HIGH_SCORE_THRESHOLD) {
currentSocial.push(tone.tone_name.toLowerCase() + '_high');
currentSocialObject.push({'tone_name': tone.tone_name.toLowerCase(), 'score': tone.score, 'interpretation': 'likely high'});
} else if (tone.score <= SOCIAL_LOW_SCORE_THRESHOLD) {
currentSocial.push(tone.tone_name.toLowerCase() + '_low');
currentSocialObject.push({'tone_name': tone.tone_name.toLowerCase(), 'score': tone.score, 'interpretation': 'likely low'});
} else {
currentSocialObject.push({'tone_name': tone.tone_name.toLowerCase(), 'score': tone.score, 'interpretation': 'likely medium'});
}
});
// update user social tone
user.tone.social.current = currentSocial;
if (maintainHistory) {
if (typeof user.tone.social.history === 'undefined') {
user.tone.social.history = [];
}
user.tone.social.history.push(currentSocialObject);
}
}