in lib/wit.js [54:128]
speech(contentType, body, context, n) {
if (typeof contentType !== 'string') {
throw new Error('Please provide a content-type (string).');
}
if (!body instanceof Readable) {
throw new Error('Please provide an audio stream (Readable).');
}
const {apiVersion, headers, logger, proxy, witURL} = this.config;
const params = {
v: apiVersion,
};
if (typeof context === 'object') {
params.context = JSON.stringify(context);
}
if (typeof n === 'number') {
params.n = JSON.stringify(n);
}
const method = 'POST';
const fullURL = witURL + '/speech?' + encodeURIParams(params);
logger.debug(method, fullURL);
const req = fetch(fullURL, {
body,
method,
proxy,
headers: {
...headers,
'Content-Type': contentType,
'Transfer-Encoding': 'chunked',
},
});
const _partialResponses = req
.then(
response =>
new Promise((resolve, reject) => {
logger.debug('status', response.status);
const bodyStream = response.body;
bodyStream.on('readable', () => {
let chunk;
let contents = '';
while (null !== (chunk = bodyStream.read())) {
contents += chunk.toString();
}
for (const {error, intents, text} of splitHttpChunks(
contents,
).map(x => JSON.parse(x))) {
if (!(error || intents)) {
logger.debug('[speech] partialTranscription:', text);
this.emit('partialTranscription', text);
} else if (text) {
logger.debug('[speech] fullTranscription:', text);
this.emit('fullTranscription', text);
}
}
});
}),
)
.catch(e => logger.error('[speech] could not parse partial response', e));
return req
.then(response => Promise.all([response.text(), response.status]))
.then(([contents, status]) => [
JSON.parse(splitHttpChunks(contents).pop()),
status,
])
.catch(e => e)
.then(makeWitResponseHandler(logger, 'speech'));
}