This repository has been archived by the owner on Jun 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
/
run.js
795 lines (709 loc) · 20.9 KB
/
run.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
/**
* Copyright 2017 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.
*/
/* jshint esversion: 6 */
require('dotenv').config({ silent: true });
const watson = require('watson-developer-cloud');
const FS = require('fs');
const MIC = require('mic');
const PLAYER = require('play-sound')(opts = {});
const PROBE = require('node-ffprobe');
const REQUEST = require('request-promise');
const PROMISE = require('promise');
const MLB_SEASON = process.env.MLB_SEASON;
const OFF_SEASON = (process.env.IN_OFF_SEASON == 'true' ? true : false);
console.log('Are we running during the Off-Season? ' + OFF_SEASON);
var mlbTeams;
var mlbTeamsRetrieved = false;
var mlbStandings;
var mlbStandingsRetrieved = false;
var mlbScheduleDates = [];
var mlbSchedule = [];
var scheduleDaysCollected = 0;
var mlbScheduleRetrieved = false;
var textPhoneNo = '';
var context = {};
var debug = false;
/**
* Create Watson Services.
*/
var version_date = '2018-02-16';
if (process.env.CONVERSATION_VERSION_DATE !== undefined) {
// if defined, override with value from .env
version_date = process.env.CONVERSATION_VERSION_DATE;
}
const conversation = new watson.AssistantV1({
version: version_date
});
const speech_to_text = new watson.SpeechToTextV1({
});
version_date = '2017-09-21';
if (process.env.TONE_ANALYZER_VERSION_DATE !== undefined) {
// if defined, override with value from .env
version_date = process.env.TONE_ANALYZER_VERSION_DATE;
}
const tone_analyzer = new watson.ToneAnalyzerV3({
version: version_date
});
const text_to_speech = new watson.TextToSpeechV1({
});
version_date = '2018-03-05';
if (process.env.DISCOVERY_VERSION_DATE !== undefined) {
// if defined, override with value from .env
version_date = process.env.DISCOVERY_VERSION_DATE;
}
const discovery = new watson.DiscoveryV1({
version: version_date
});
/**
* Create Twilio Client.
*/
const TWILIO = require('twilio')(
process.env.TWILIO_SID,
process.env.TWILIO_AUTH_TOKEN
);
const TWILIO_PHONE_NO = process.env.TWILIO_PHONE_NUMBER;
// If phone number to always text to is found in config file, use it.
if (process.env.TWILIO_TEXT_TO_PHONE_NUMBER) {
textPhoneNo = process.env.TWILIO_TEXT_TO_PHONE_NUMBER;
context.text_sent = 'success';
}
/**
* Retrieve key to 3rd party MLB data
*/
const MLB_DATA_KEY = process.env.MLB_FANTASY_SPORTS_KEY;
/**
* Create and configure the microphone.
*/
const MIC_PARAMS = {
rate: 44100,
channels: 2,
debug: false,
exitOnSilence: 6
};
const MIC_INSTANCE = MIC(MIC_PARAMS);
const MIC_INPUT_STREAM = MIC_INSTANCE.getAudioStream();
let pauseDuration = 0;
MIC_INPUT_STREAM.on('pauseComplete', ()=> {
console.log('Microphone paused for', pauseDuration, 'seconds.');
// Stop listening when speaker is talking.
setTimeout(function() {
MIC_INSTANCE.resume();
console.log('Microphone resumed.');
}, Math.round(pauseDuration * 1000));
});
/**
* Get current date
*/
function getCurrentDate() {
var date;
if (OFF_SEASON) {
// all saved data is from Sept 28, 2017
date = new Date(2017, 8, 28);
} else {
date = new Date();
}
return date;
}
/**
* Get current MLB team info from MLB Fantasy Data.
*/
function getMlbTeams() {
const options = {
method: 'GET',
uri: 'https://api.fantasydata.net/mlb/v2/JSON/teams',
headers: {
'Host': 'api.fantasydata.net',
'Ocp-Apim-Subscription-Key': process.env.MLB_FANTASY_SPORTS_KEY
}
};
return new PROMISE((resolve, reject) => {
REQUEST(options)
.then(function (response) {
mlbTeams = JSON.parse(response);
return resolve();
})
.catch(function (err) {
console.log('Unable to retrieve current MLB team info. ', err);
return reject(err);
});
});
}
/**
* Get current MLB standings from MLB Fantasy Data.
*/
function getMlbStandings() {
const options = {
method: 'GET',
uri: 'https://api.fantasydata.net/mlb/v2/JSON/Standings/' + MLB_SEASON,
headers: {
'Host': 'api.fantasydata.net',
'Ocp-Apim-Subscription-Key': MLB_DATA_KEY
}
};
return new PROMISE((resolve, reject) => {
REQUEST(options)
.then(function (response) {
mlbStandings = JSON.parse(response);
return resolve();
})
.catch(function (err) {
console.log('Unable to retrieve current MLB standings. ', err);
return reject(err);
});
});
}
/**
* Get current MLB schedules from MLB Fantasy Data. Just grab schedules
* from today and for the next week.
*/
function getMlbSchedules() {
var monthNames = [
'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL',
'AUG', 'SEP', 'OCT', 'NOV', 'DEC'
];
var date = getCurrentDate();
return new PROMISE((resolve, reject) => {
for (let i = 0; i < 7; i++) {
/* jshint loopfunc: true */
date.setDate(date.getDate() + 1);
month = date.getMonth();
day = ("0" + date.getDate()).slice(-2);
const options = {
method: 'GET',
uri: 'https://api.fantasydata.net/mlb/v2/JSON/GamesByDate/' + MLB_SEASON + '-' +
monthNames[month] + '-' + day,
headers: {
'Host': 'api.fantasydata.net',
'Ocp-Apim-Subscription-Key': MLB_DATA_KEY
}
};
REQUEST(options)
.then(function (response) {
daySchedule = JSON.parse(response);
if (daySchedule.length > 0) {
console.log('Retrieved schedule for date: ' + daySchedule[0].Day);
// Save each date in array so that they can be sorted
// after all dates are retrieved.
mlbScheduleDates[mlbScheduleDates.length] = daySchedule;
} else {
console.log('Retrieved schedule for date: NO GAMES FOUND');
}
scheduleDaysCollected += 1;
if (scheduleDaysCollected === 7) {
return resolve();
}
})
.catch(function (err) {
console.log('Unable to retrieve current MLB schedules. ', err);
return reject(err);
});
}
});
}
/**
* Sort the MLB schedule by date. This is needed because each day is
* requested separately, and are returned in random order.
*/
function sortSchedule() {
var date = getCurrentDate();
var daysProcessed = 0;
while (daysProcessed < 7) {
date.setDate(date.getDate() + 1);
for (let i = 0; i < mlbScheduleDates.length; i++) {
if (mlbScheduleDates[i][0].Day.substring(5,10) ===
date.toJSON().substring(5,10)) {
mlbSchedule = mlbSchedule.concat(mlbScheduleDates[i]);
daysProcessed += 1;
break;
}
}
}
}
/**
* Get current MLB standings for a specific team.
*
* @param {String} team
* Team to get standings for.
*/
function getCurrentStandings(team, standingsData) {
if (standingsData) {
let places = ['first', 'second', 'third', 'fourth', 'last'];
let placeIdx;
let place = '';
let div = '';
for (let i = 0; i < standingsData.length; i++) {
let currentDiv = standingsData[i].League + standingsData[i].Division;
if (div === '' || div !== currentDiv) {
div = currentDiv;
placeIdx = 0;
} else {
placeIdx++;
}
place = places[placeIdx];
let compTeam = standingsData[i].Name;
if (team.indexOf(compTeam) > -1) {
return place;
}
}
return 'unknown';
}
}
exports.getCurrentStandings = getCurrentStandings;
/**
* Get upcoming MLB schedule for a specific team.
*
* @param {String} team
* Team to get schedule for.
*/
function getUpcomingSchedule(team) {
// First determine abbreviated team name required for looking at schedules.
var teamKey = '';
if (mlbTeams) {
for (let i = 0; i < mlbTeams.length; i++) {
let compTeam = mlbTeams[i].Name;
if (team.indexOf(compTeam) > -1) {
teamKey = mlbTeams[i].Key;
break;
}
}
}
var schedString = 'No schedule data found for ' + team;
if (teamKey && mlbSchedule) {
schedString = 'Upcoming schedule for the ' + team + ':\n';
var gameCount = 0;
var date = getCurrentDate();
var dayCtr = 0;
var done = false;
while (! done) {
date.setDate(date.getDate() + 1);
dayCtr++;
for (let i = 0; i < mlbSchedule.length; i++) {
// Limit schedule to just next 5 games.
if (mlbSchedule[i].Day.substring(5,10) ===
date.toJSON().substring(5,10)) {
var game = '';
if (mlbSchedule[i].AwayTeam === teamKey) {
game = mlbSchedule[i].DateTime.substring(5,10) +
' ' + mlbSchedule[i].DateTime.substring(11,16) +
' @ ' + mlbSchedule[i].HomeTeam + '\n';
} else if (mlbSchedule[i].HomeTeam === teamKey) {
game = mlbSchedule[i].DateTime.substring(5,10) +
' ' + mlbSchedule[i].DateTime.substring(11,16) +
' vs. ' + mlbSchedule[i].AwayTeam + '\n';
}
if (game) {
schedString = schedString.concat(game);
gameCount += 1;
if (gameCount === 5) {
done = true;
}
break;
}
}
}
if (dayCtr === 7) {
// don't look more than a week out to find 5 games
// this is needed for end of season
done = true;
}
}
console.log("schedString " + schedString);
return schedString;
}
}
/**
* Convert phone number from words to numbers.
*
* @param {String} spokenPhoneNumber
* Text of spoken phone number that needs to be converted to digits.
*/
function getUserPhoneNumber(spokenPhoneNumber) {
// Spoken phone number is a space seperated string.
var phoneNum = '+1';
words = spokenPhoneNumber.split(' ');
for (let i = 0; i < words.length; i++) {
switch(words[i]) {
case 'one':
phoneNum = phoneNum + '1';
break;
case 'two':
phoneNum = phoneNum + '2';
break;
case 'three':
phoneNum = phoneNum + '3';
break;
case 'four':
phoneNum = phoneNum + '4';
break;
case 'five':
phoneNum = phoneNum + '5';
break;
case 'six':
phoneNum = phoneNum + '6';
break;
case 'seven':
phoneNum = phoneNum + '7';
break;
case 'eight':
phoneNum = phoneNum + '8';
break;
case 'nine':
phoneNum = phoneNum + '9';
break;
case 'zero':
phoneNum = phoneNum + '0';
break;
}
}
return phoneNum;
}
exports.getUserPhoneNumber = getUserPhoneNumber; // export for mocha unit tests
/**
* Text team info to user.
* This includes schedule, and Watson headlines
*/
function textTeamInfo() {
// Validate phone number is legitimate.
if (context.text_sent != 'success') {
// Only use number if needed (first time or last time was with invalid #).
textPhoneNo = getUserPhoneNumber(context.phoneno);
}
if (textPhoneNo.length != 12) {
console.log('Unable to text: bad phone number: ', textPhoneNo);
context.text_sent = 'failure';
return;
}
console.log('Will send text to: ', textPhoneNo);
// Query for headlines from watson news.
let headlines = [];
const numHeadlines = 2;
discovery.query({
environment_id: 'system',
collection_id: 'news',
query: context.my_team + ' baseball',
count: 5
}, (err, response) => {
if (response.results) {
for (let i = 0; i < response.results.length; i++) {
// Make sure headline is not a duplicate, which Watson news
// does on occasion.
headline = response.results[i].title + ' - ' + response.results[i].url;
var dup = false;
for (let j = 0; j < headlines.length; j++) {
if (headline === headlines[j]) {
dup = true;
break;
}
}
if (! dup) {
headlines.push(headline);
if (headlines.length >= numHeadlines) {
break;
}
}
}
}
// Get next 5 game schedule for team.
sched = getUpcomingSchedule(context.my_team);
// Text schedule to user.
context.text_sent = 'success';
TWILIO.messages.create({
to: textPhoneNo,
from: TWILIO_PHONE_NO,
body: sched,
}, function(err, message) {
console.log(message.sid);
// Now text each headline to user.
for (let i = 0; i < headlines.length; i++) {
/* jshint loopfunc: true */
TWILIO.messages.create({
to: textPhoneNo,
from: TWILIO_PHONE_NO,
body: headlines[i],
}, function(err, message) {
console.log(message.sid);
});
}
});
// Tell user text has been sent.
console.log('Schedule and headlines have been sent');
printContext('before call 4:');
conversation.message({
workspace_id: process.env.CONVERSATION_WORKSPACE_ID,
input: {'text': ''},
context: context
}, (err, response) => {
context = response.context;
printContext('after call 4:');
watsonResponse = response.output.text[0];
speakResponse(watsonResponse);
watsonSays(watsonResponse);
});
});
}
/**
* Convert speech to text.
*/
const textStream = MIC_INPUT_STREAM.pipe(
speech_to_text.createRecognizeStream({
'content_type': 'audio/l16; rate=44100; channels=2',
interim_results: true,
inactivity_timeout: -1
})).setEncoding('utf8');
/**
* Get emotional tone from speech.
*/
const getEmotion = (text) => {
// only the following emotions are handled by Watson Assistant
const valid_emotions = ['disgust', 'fear', 'anger', 'joy', 'sadness'];
return new Promise((resolve) => {
let maxScore = 0.01;
let emotion = 'default';
tone_analyzer.tone({ 'text': text }, (err, tone) => {
console.log(JSON.stringify(tone, null, 2));
if (tone && tone.document_tone) {
let tones = tone.document_tone.tones;
for (let i=0; i<tones.length; i++) {
if (tones[i].score > maxScore){
if (valid_emotions.includes(tones[i].tone_id)) {
maxScore = tones[i].score;
emotion = tones[i].tone_id;
}
}
}
}
resolve({emotion, maxScore});
});
});
};
/**
* Convert text to speech.
*/
const speakResponse = (text) => {
const params = {
text: text,
voice: process.env.TJBOT_VOICE,
accept: 'audio/wav'
};
var writeStream = text_to_speech.synthesize(params)
.pipe(FS.createWriteStream('output.wav'));
writeStream.on('close', function() {
PROBE('output.wav', function(err, probeData) {
pauseDuration = probeData.format.duration;
MIC_INSTANCE.pause();
PLAYER.play('output.wav');
});
});
writeStream.on('error', function(err) {
console.log('Text-to-speech streaming error: ' + err);
});
};
/**
* Check conversation step.
* True if we are attempting to validate the team the user wishes to follow.
*/
function validateTeamStep() {
if (context &&
context.system &&
context.system.dialog_stack[0].dialog_node === 'Validate Team') {
return true;
}
return false;
}
/**
* Check conversation step.
* True if we are attempting to validate the users team sentiment tone.
*/
function validateEmotionStep() {
if (context &&
context.system &&
context.system.dialog_stack[0].dialog_node === 'Validate Emotion') {
return true;
}
return false;
}
/**
* Check conversation step.
* True if we are attempting to text team info to the user.
*/
function textTeamInfoStep() {
if (context &&
context.system &&
context.system.dialog_stack[0].dialog_node === 'Text Team Info') {
return true;
}
return false;
}
/**
* Log Watson Conversation context values..
*
* @param {String} header
* First line of log message.
*/
function printContext(header) {
if (debug) {
console.log(header);
if (context.system) {
if (context.system.dialog_stack) {
const util = require('util');
console.log(" dialog_stack: ['" +
util.inspect(context.system.dialog_stack, false, null) + "']");
}
if (context.emotion) {
console.log(" emotion: " + context.emotion);
}
if (context.my_team) {
console.log(" my_team: " + context.my_team);
}
if (context.standings) {
console.log(" standings: " + context.standings);
}
if (context.phoneno) {
console.log(" phoneno: " + context.phoneno);
}
}
}
}
/**
* Send significant responses from Watson to the console.
*/
function watsonSays(response) {
if (typeof(response) !== 'undefined') {
console.log('Watson says:', response);
}
}
/**
* Watson conversation with user.
*/
function mlbConversation() {
console.log('TJBot is listening, you may speak now.');
speakResponse('Hi there, I am awake.');
textStream.on('data', (user_speech_text) => {
userSpeechText = user_speech_text.toLowerCase();
console.log('\n\nWatson hears: ', user_speech_text);
printContext('before call 1:');
conversation.message({
workspace_id: process.env.CONVERSATION_WORKSPACE_ID,
input: {'text': user_speech_text},
context: context
}, (err, response) => {
context = response.context;
printContext('after call 1:');
watson_response = response.output.text[0];
if (watson_response) {
speakResponse(watson_response);
}
watsonSays(watson_response);
if (validateEmotionStep()) {
// User has expressed sentiment about team.
getEmotion(context.emotion).then((detectedEmotion) => {
context.emotion = detectedEmotion.emotion;
printContext('before call 2:');
conversation.message({
workspace_id: process.env.CONVERSATION_WORKSPACE_ID,
input: {'text': userSpeechText},
context: context
}, (err, response) => {
context = response.context;
printContext('after call 2:');
watson_response = response.output.text[0];
speakResponse(watson_response);
watsonSays(watson_response);
});
});
} else if (validateTeamStep()) {
// User has identified which team they want to follow.
context.standings = getCurrentStandings(context.my_team, mlbStandings);
printContext('before call 3:');
conversation.message({
workspace_id: process.env.CONVERSATION_WORKSPACE_ID,
input: {'text': userSpeechText},
context: context
}, (err, response) => {
context = response.context;
printContext('after call 3:');
watson_response = response.output.text[0];
speakResponse(watson_response);
watsonSays(watson_response);
});
} else if (textTeamInfoStep()) {
// User has requested that team info be texted to them.
textTeamInfo();
} else {
printContext('NO STEP !!! after call 3:');
}
});
});
}
/**
* Load all MLB data and start conversation when completed.
*/
function init() {
if (OFF_SEASON) {
var fs = require('fs');
mlbTeams = JSON.parse(fs.readFileSync('data/mlb-teams.json', 'utf8'));
mlbStandings = JSON.parse(fs.readFileSync('data/mlb-standings.json', 'utf8'));
mlbScheduleDates = JSON.parse(fs.readFileSync('data/mlb-schedule.json', 'utf8'));
sortSchedule();
mlbTeamsRetrieved = true;
mlbStandingsRetrieved = true;
mlbScheduleRetrieved = true;
startConversationIfReady();
} else {
// Generate data to be used during the conversation.
getMlbTeams()
.then(function() {
console.log('Retrieved MLB Teams');
mlbTeamsRetrieved = true;
startConversationIfReady();
})
.catch(err => {
throw new Error('Error loading MLB team info');
});
getMlbStandings()
.then(function() {
console.log('Retrieved MLB standings');
mlbStandingsRetrieved = true;
startConversationIfReady();
})
.catch(err => {
throw new Error('Error loading MLB standings');
});
getMlbSchedules()
.then(function() {
console.log('Retrieved MLB schedules');
sortSchedule();
mlbScheduleRetrieved = true;
startConversationIfReady();
})
.catch(err => {
throw new Error('Error loading MLB schedules');
});
}
}
/**
* Start the conversation once all MLB data is loaded.
*/
function startConversationIfReady() {
if (mlbTeamsRetrieved && mlbStandingsRetrieved && mlbScheduleRetrieved) {
// Initialize microphone
MIC_INSTANCE.start();
// Begin watson conversation.
mlbConversation();
}
}
// Start by loading MLB data
init();