-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
378 lines (344 loc) · 9.08 KB
/
index.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
/*******************************************************************************
* Copyright (c) 2015 IBM Corp.
*
* 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.
*******************************************************************************/
/*eslint-env node */
'use strict';
var sys = require('util');
var nats = require('nats').connect();
var exec = require('child_process').exec;
var execSync = require('child_process').execSync;
var soap = require('soap');
var crypto = require('crypto');
var net = require('net');
var fs = require('fs');
var Buffer = require('buffer').Buffer;
var path = require('path');
var watson = require('watson-developer-cloud');
//var Sound = require('node-aplay');
var HumixSense = require('humix-sense');
var log = require('humix-logger').createLogger('humix-dialog-module', {
consoleLevel : 'debug'
});
var HumixSpeech = require('./lib/HumixSpeech').HumixSpeech;
var config = require('./config');
var voice_path = path.join(__dirname, 'voice');
var url = 'http://tts.itri.org.tw/TTSService/Soap_1_3.php?wsdl';
var kGoogle = 0;
var kWatson = 1;
var OpenCC = require('opencc');
var opencc = new OpenCC('s2t.json');
var engineIndex = {
'google' : kGoogle,
'watson' : kWatson
};
var ttsWatson;
var retry = 0;
//iflytec flag
var TTS_busy = false;
if (config['tts-engine'] === 'watson') {
ttsWatson = watson.text_to_speech({
username : config.tts.watson.username,
password : config.tts.watson.passwd,
version : 'v1',
});
}
var moduleConfig = {
moduleName : 'humix-dialog',
commands : [ 'say' ],
events : [ 'speech' ],
debug : true
}
var humix = new HumixSense(moduleConfig);
var hsm;
humix.on('connection', function(humixSensorModule) {
hsm = humixSensorModule;
log.debug('Communication with humix-sense is now ready.');
hsm.on('say', function(data) {
log.debug('data:', data);
text2Speech(data);
}); // end of say command
});
/*
* Speech To Text Processing
*/
//start HumixSpeech here
var hs;
var commandRE = /---="(.*)"=---/;
/**
* callback function that is called when
* HumixSpeech detect a valid command/sentence
* @param cmdstr a command/sentence in this format:
* '----="command string"=---'
*/
function receiveCommand(cmdstr) {
cmdstr = cmdstr.trim();
if (config['stt-engine']) {
log.debug('command found:', cmdstr);
if (hsm) {
if (config.lang == 'cht')
hsm.event('speech', opencc.convertSync(cmdstr));
else
hsm.event('speech', cmdstr)
}
} else {
log.debug('No stt engine configured. Skip');
}
}
try {
var defaultOpts = {
vad_threshold: '3.5',
upperf: '1000',
hmm: './deps/pocketsphinx-5prealpha/model/en-us/en-us',
//http://www.speech.cs.cmu.edu/tools/lmtool.html use this website
//to generate lm and dict file based on your keyword-name
lm: './lm/humix.lm',
dict: './lm/humix.dic',
'keyword-name': 'HUMIX', //all capital characters
samprate: '16000',
maxwpf: '5',
topn: '2',
maxhmmpf: '3000',
pl_window: '7',
ds: '2',
cmdproc: './util/processcmd.sh',
lang: 'zh-tw',
'wav-proc': './voice/interlude/beep2.wav',
'wav-bye': './voice/interlude/beep1.wav',
logfn: '/dev/null'
};
var options = config.options || {};
for(var option in options) {
defaultOpts[option] = options[option];
}
hs = new HumixSpeech(defaultOpts);
var engine = config['stt-engine'] || 'watson';
hs.engine(config.stt[engine].username, config.stt[engine].passwd,
engineIndex[engine], require('./lib/' + engine).startSession);
hs.start(receiveCommand);
} catch (error) {
log.error(error);
}
/*
* Text To Speech Processing
*/
function text2Speech(msg) {
log.debug('Received a message:', msg);
var text
var wav_file = '';
try {
text = JSON.parse(msg).text;
} catch (e) {
log.error('invalid JSON format,', e);
return;
}
if (!text) {
return log.error('Missing property: msg.text');
}
//for safe
text = text.trim();
var person = 'xiaoyan'
if (config['tts-engine'] === 'iflytek') {
try {
person = JSON.parse(msg).person;
} catch (e) {
person = 'xiaoyan';
}
IflytekTTS(text, person);
return;
}
var hash = crypto.createHash('md5').update(text).digest('hex');
var filename = path.join(voice_path, 'text', hash + '.wav');
if (fs.existsSync(filename)) {
log.debug('Wav file exist. Play cached file:', filename);
sendAplay2HumixSpeech(filename);
} else {
log.debug('Wav file does not exist');
var ttsEngine = config['tts-engine'];
log.debug('tts-engine:', engine);
if (ttsEngine === 'itri') {
log.debug('username :', config.tts.itri.username);
ItriTTS(text, function(err, id) {
if (err) {
log.error('failed to download wav from ITRI. Error:', err);
} else {
retry = 0;
setTimeout(ItriDownload, 1000, id, filename);
}
});
} else if (ttsEngine === 'watson') {
WatsonTTS(text, filename);
}
}
}
/**
* call the underlying HumixSpeech to play wave file
* @param file wave file
*/
function sendAplay2HumixSpeech(file) {
if (hs) {
hs.play(file);
}
}
/*
* Watson TTS Processing
*/
function WatsonTTS(text, filename) {
ttsWatson.synthesize({
text : text,
accept : 'audio/wav'
}, function(err) {
if (err) {
log.error('error:', err);
return;
}
fs.writeFileSync(filename, new Buffer(arguments[1]));
sendAplay2HumixSpeech(filename);
});
}
/*
* Iflytek TTS Processing
*/
function IflytekTTS(text, person) {
if (!TTS_busy) {
TTS_busy = true;
var execFile = './tts';
var spawn = require('child_process').spawn;
var free = spawn(execFile, [ text, 'tts.wav', person ]);
free.stdout.on('data', function(data) {
log.debug('out', data);
});
free.stderr.on('data', function(data) {
log.debug('err', data);
});
free.on('exit', function(code, signal) {
TTS_busy = false;
log.debug('exit', code);
});
} else {
log.error('TTS is Busy!');
}
}
/*
* ITRI TTS Processing
*/
function ItriTTS(text, callback) {
var args = {
accountID : config.tts.itri.username,
password : config.tts.itri.passwd,
TTStext : text,
TTSSpeaker : config.tts.itri.speaker,
volume : 50,
speed : -2,
outType : 'wav'
};
soap.createClient(url, function(err, client) {
client.ConvertText(args, function(err, result) {
if (err) {
log.error('err:', err);
callback(err, null);
}
try {
var id = result.Result.$value.split('&')[2];
if (id) {
log.debug('get id:', id);
callback(null, id);
} else {
throw 'failed to convert text!';
}
} catch (e) {
log.error(error);
callback(error, null);
}
});
});
}
function ItriGetConvertStatus(id, filename, callback) {
var args = {
//accountIDhasOwnProperty: config.tts.itri.username,
accountID : config.tts.itri.username,
password : config.tts.itri.passwd,
convertID : id
};
soap.createClient(url, function(err, client) {
log.debug('msg_id', id);
client.GetConvertStatus(args, function(err, result) {
if (err) {
log.error('err:', err);
callback(err, null);
}
var downloadUrl = result.Result.$value.split('&')[4];
if (downloadUrl) {
log.debug(id, downloadUrl);
execSync('wget ' + downloadUrl + ' -O ' + filename, {
stdio : [ 'ignore', 'ignore', 'ignore' ]
});
callback(null, filename);
} else {
var error = 'Still converting! result: ' + JSON.stringify(result);
log.error(error);
callback(error, null);
}
});
});
}
function ItriDownload(id, filename) {
retry++;
ItriGetConvertStatus(id, filename, function(err) {
if (err) {
log.error('err:', err);
if (retry < 10) {
log.debug('retry', retry);
setTimeout(ItriDownload, 2000, id, filename);
}
} else {
log.debug('Play wav file:', filename);
sendAplay2HumixSpeech(filename);
}
});
}
/*
* Signal Handling
*/
process.stdin.resume();
function cleanup() {
if (hs) {
hs.stop();
}
}
process.on('SIGINT', function() {
cleanup();
process.exit(0);
});
process.on('SIGHUP', function() {
cleanup();
process.exit(0);
});
process.on('SIGTERM', function() {
cleanup();
process.exit(0);
});
process.on('exit', function() {
cleanup();
});
process.on('error', function() {
cleanup();
});
process.on('uncaughtException', function(err) {
if (err.toString().indexOf('connect ECONNREFUSED')) {
//log.error('exception,', JSON.stringify(err));
//cleanup();
//process.exit(0);
}
});