-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
290 lines (243 loc) · 6.93 KB
/
Copy pathserver.js
File metadata and controls
290 lines (243 loc) · 6.93 KB
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
const http = require('http');
const socketIO = require('socket.io');
const DeepSpeech = require('deepspeech');
const VAD = require('node-vad');
let DEEPSPEECH_MODEL = __dirname + '/deepspeech-0.9.3-models'; // path to deepspeech english model directory
let SILENCE_THRESHOLD = 200; // how many milliseconds of inactivity before processing the audio
const SERVER_PORT = '4000'; // websocket server port
let words = 0;
let durationMin = 0.0;
let lastRate = 0;
// const VAD_MODE = VAD.Mode.NORMAL;
// const VAD_MODE = VAD.Mode.LOW_BITRATE;
// const VAD_MODE = VAD.Mode.AGGRESSIVE;
const VAD_MODE = VAD.Mode.VERY_AGGRESSIVE;
const vad = new VAD(VAD_MODE);
function createModel(modelDir) {
let modelPath = modelDir + '.pbmm';
let scorerPath = modelDir + '.scorer';
let model = new DeepSpeech.Model(modelPath);
model.enableExternalScorer(scorerPath);
return model;
}
let englishModel = createModel(DEEPSPEECH_MODEL);
let modelStream;
let recordedChunks = 0;
let silenceStart = null;
let recordedAudioLength = 0;
let endTimeout = null;
let silenceBuffers = [];
//added
let afterSilenceStart = 0.0;
function processAudioStream(data, callback) {
vad.processAudio(data, 16000).then((res) => {
switch (res) {
case VAD.Event.ERROR:
console.log("VAD ERROR");
break;
case VAD.Event.NOISE:
console.log("VAD NOISE");
break;
case VAD.Event.SILENCE:
processSilence(data, callback);
break;
case VAD.Event.VOICE:
processVoice(data);
break;
default:
console.log('default', res);
}
});
// timeout after 1s of inactivity
clearTimeout(endTimeout);
endTimeout = setTimeout(function() {
console.log('timeout');
resetAudioStream();
},1000);
}
function endAudioStream(callback) {
console.log('[end]');
let results = intermediateDecode();
if (results) {
if (callback) {
callback(results);
}
}
}
function resetAudioStream() {
clearTimeout(endTimeout);
console.log('[reset]');
intermediateDecode(); // ignore results
recordedChunks = 0;
silenceStart = null;
}
function processSilence(data, callback) {
if (recordedChunks > 0) { // recording is on
process.stdout.write('-'); // silence detected while recording
feedAudioContent(data);
if (silenceStart === null) {
silenceStart = new Date().getTime();
}
else {
let now = new Date().getTime();
if (now - silenceStart > SILENCE_THRESHOLD) {
silenceStart = null;
console.log('[end]');
let results = intermediateDecode();
if (results) {
if (callback) {
callback(results);
}
}
}
}
}
else {
process.stdout.write('.'); // silence detected while not recording
bufferSilence(data);
}
}
function bufferSilence(data) {
// VAD has a tendency to cut the first bit of audio data from the start of a recording
// so keep a buffer of that first bit of audio and in addBufferedSilence() reattach it to the beginning of the recording
silenceBuffers.push(data);
if (silenceBuffers.length >= 3) {
silenceBuffers.shift();
}
}
function addBufferedSilence(data) {
let audioBuffer;
if (silenceBuffers.length) {
silenceBuffers.push(data);
let length = 0;
silenceBuffers.forEach(function (buf) {
length += buf.length;
});
audioBuffer = Buffer.concat(silenceBuffers, length);
silenceBuffers = [];
}
else audioBuffer = data;
return audioBuffer;
}
function processVoice(data) {
silenceStart = null;
if (recordedChunks === 0) {
console.log('');
process.stdout.write('[start]'); // recording started
//added
afterSilenceStart = new Date().getTime();
}
else {
process.stdout.write('='); // still recording
}
recordedChunks++;
data = addBufferedSilence(data);
feedAudioContent(data);
}
function createStream() {
modelStream = englishModel.createStream();
recordedChunks = 0;
recordedAudioLength = 0;
}
//=============================server printout
function finishStream() {
if (modelStream) {
let start = new Date();
let text = modelStream.finishStream();
if (text) {
console.log('');
console.log('Recognized Text:', text);
let recogTime = new Date().getTime() - start.getTime();
words += text.split(' ').length;
//added
let recordDur = (new Date().getTime() - afterSilenceStart)/1000;
durationMin += (recordDur / 60);
console.log("========================================");
console.log('Duration: ', recordDur, 'sec'); //speaking to the end
console.log('Duration: ', (recordDur / 60), 'min');
console.log('numWords: ', text.split(' ').length);
dash = "";
rate = parseInt(words / durationMin);
for(i = 0; i < rate; i++)
{
dash += "-";
}
let differenceRate = 0;
differenceRate = parseInt(rate - lastRate);
differentRateString = "";
differentRateString = differenceRate.toString();
console.log("Difference: ", differenceRate);
console.log("DifferenceStr: ", differentRateString);
if(differenceRate > 0.0) {
differentRateString = "+" + differenceRate.toString();
}
lastRate = rate;
text = text + "@" + recordDur.toString() + "@" + rate.toString() + "@" + dash + "@" + differentRateString;
if (rate < 120 ) {
text += "@" + "You should talk faster";
}
else if(rate > 150)
{
text += "@" + "You should talk slower";
}
else
{
text += "@" + "";
}
console.log('New Text: ', text);
console.log("Rate of speech", Math.ceil(rate));
console.log("-------------")
console.log('total word: ', words);
console.log("total duration: ", durationMin, "min");
console.log("========================================");
console.log();
return {
text,
recogTime,
audioLength: Math.round(recordedAudioLength)
};
}
}
silenceBuffers = [];
modelStream = null;
}
function intermediateDecode() {
let results = finishStream();
createStream();
return results;
}
function feedAudioContent(chunk) {
recordedAudioLength += (chunk.length / 2) * (1 / 16000) * 1000;
modelStream.feedAudioContent(chunk);
}
const app = http.createServer(function (req, res) {
res.writeHead(200);
res.write('web-microphone-websocket');
res.end();
});
const io = socketIO(app, {});
io.set('origins', '*:*');
io.on('connection', function(socket) {
console.log('client connected');
socket.once('disconnect', () => {
console.log('client disconnected');
});
createStream();
socket.on('stream-data', function(data) {
processAudioStream(data, (results) => {
socket.emit('recognize', results);
});
});
socket.on('stream-end', function() {
endAudioStream((results) => {
socket.emit('recognize', results);
});
});
socket.on('stream-reset', function() {
resetAudioStream();
});
});
app.listen(SERVER_PORT, 'localhost', () => {
console.log('Socket server listening on:', SERVER_PORT);
});
module.exports = app;