Adding Asterisk external speech to text application

This patch adds basic functionality for translating speech to text, using
the Google speech API, from audio received over a websocket after a successful
negotiation with Asterisk using the Asterisk External Application Protocol.
This commit is contained in:
Kevin Harwell 2022-02-15 13:05:43 -06:00
commit 1f701bd265
12 changed files with 2856 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
node_modules

201
LICENSE Normal file
View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

63
README.md Normal file
View file

@ -0,0 +1,63 @@
# Asterisk External Speech to Text application
This package contains an example Node.js program that uses the [Asterisk External Application Protocol](https://wiki.asterisk.org/wiki/display/AST/Asterisk+External+Application+Protocol) (AEAP) to facilitate external speech to text translation in Asterisk.
## Description
#### Background
For a while now Asterisk has had to ability to translate speech to text via its [Speech Recognition API](https://wiki.asterisk.org/wiki/display/AST/Speech+Recognition+API). Historically though, creating a new speech recognition engine required writing a new Asterisk module, typically written in "C", that implemented the backend API. Now, with the advent of AEAP, the backend speech API is abstracted away and translation can be done externally in the programming language of one's choice.
#### Example Program
This program acts as a mediator between Asterisk and the Google speech provider. Creating a websocket server it listens for incoming client connections from Asterisk. Once a connection is established, and a successful negotiation takes place using AEAP for speech audio can then be sent from Asterisk to the application, which then forwards it to the Google speech provider. Upon a confidence speech to text result received from Google, the application sends the result to Asterisk via an AEAP message.
Speech recognition will continue until the client closes, or an error occurs.
## Dependencies
* Node.js
* [Google Speech API](https://cloud.google.com/speech-to-text/docs/) credentials set in environment variable [GOOGLE_APPLICATION_CREDENTIALS](https://cloud.google.com/docs/authentication/getting-started).
## Installation
Run `npm install` from the top of the source tree. This will install the required npm packages.
## Usage
To start the websocket server on the default port (9099):
```
$ index.js
```
Or to have it listen on a different port:
```
$ index.js --port=<port number>
```
To stop the server press `Ctrl-C`
## Example Asterisk Configuration:
Configure an AEAP client in [*aeap.conf*](https://github.com/asterisk/asterisk/blob/master/configs/samples/aeap.conf.sample):
```
[my-speech-to-text]
type=client
codecs=!all,ulaw
url=ws://127.0.0.1:9099
protocol=speech_to_text
```
This will configure a "speech engine" in Asterisk that connects to the external application. When the [Asterisk Speech Recognition API](https://wiki.asterisk.org/wiki/display/AST/Speech+Recognition+API) is employed in dialplan using the above "engine", this configuration is activated and a websocket client attempts to connect to the given URL. Next, create an extension that utilizes the speech API dialplan functions, and on *SpeechCreate* give the client id specified in *aeap.conf* as the "engine" name. Example *extensions.conf*:
```
exten => 550,1,NoOp()
same => n,Answer()
same => n,SpeechCreate(my-speech-to-text)
same => n,SpeechStart()
same => n,SpeechBackground(hello-world)
same => n,Verbose(0,${SPEECH_TEXT(0)})
same => n,SpeechDestroy()
same => n,Hangup()
```
If things are configured correctly, and the sample program found here is listening at the configured address/port then when a caller dials extension `550` the following should occur:
1. Asterisk connects via websocket to the remote application.
2. The caller hears "Hello World" played back.
3. After hearing "Hello World" any spoken audio from the caller is forwarded to the remote application.
4. Once the caller is done speaking their spoken text is printed on the Asterisk CLI.
5. The Client disconnects from remote application
6. The call is hung up.

63
index.js Executable file
View file

@ -0,0 +1,63 @@
#!/usr/bin/env node
/*
* Copyright 2022 Sangoma Technologies Corporation
* Kevin Harwell <kharwell@sangoma.com>
*
* 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.
*/
const { Codecs } = require("./lib/codecs");
const { Languages } = require("./lib/languages");
const { getProvider } = require("./lib/provider");
const { getServer } = require("./lib/server");
const { dispatch } = require("./lib/dispatcher");
const argv = require("yargs/yargs")(process.argv.slice(2))
.command("$0 [options]", "Start a speech to text server", {
port: {
alias: "p",
desc: "Port to listen on",
default: 9099,
type: "number",
group: "Server",
},
})
.strict()
.argv;
const codecs = new Codecs(argv);
const languages = new Languages(argv);
const server = getServer("ws", argv);
server.on("connection", (client) => {
dispatch({
codecs: codecs,
languages: languages,
transport: client,
provider: getProvider("google", argv),
});
});
process.on("SIGINT", () => {
server.close();
process.exit(0);
});
process.on("SIGTERM", () => {
server.close();
process.exit(0);
});

102
lib/codecs.js Normal file
View file

@ -0,0 +1,102 @@
/*
* Copyright 2022 Sangoma Technologies Corporation
* Kevin Harwell <kharwell@sangoma.com>
*
* 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.
*/
const utils = require("./utils");
/**
* Supported codecs
*/
const supported = [
{
"name": "ulaw",
"sampleRate": 8000,
"attributes" : [],
},
{
"name": "slin16",
"sampleRate": 16000,
"attributes" : [],
},
{
"name": "opus",
"sampleRate": 48000,
"attributes" : [],
},
];
/**
* Checks if given codecs match.
*
* @param {Object} obj1 - A codec object
* @param {Object} obj2 - A codec object
* @return {boolean} true if codecs match otherwise false.
*/
function equal(obj1, obj2) {
return obj1.name === obj2.name;
}
/**
* Converts codecs to a comma separated string of codec names.
*
* @param {Object|Object[]} objs - Codecs to convert
* @return {string} A comma separated string of codec names.
*/
function toString(objs) {
if (!Array.isArray(objs)) {
objs = [objs];
}
return objs.map(o => o.name).join(", ");
}
/** @class Codecs. */
class Codecs {
/**
* Creates an instance of Codecs.
*
* @param {Object} options - Codec options
*/
constructor(options) {
this.codecs = options.codecs ?
utils.intersect(supported, options.codecs, equal) : supported;
this.selected = this.codecs[0]; // Default to first in list
}
/**
* Selects the first matching codec between supported and given codecs
*
* @param {Object|Object[]} codecs - Codecs to intersect with supported
* @return The first selected codec
*/
first(codecs) {
try {
let res = utils.first(this.codecs, codecs, equal);
if (res) {
return res;
}
} catch (e) {
}
throw new Error("Codec " + toString(codecs) + " not supported");
}
};
module.exports = {
Codecs,
}

175
lib/dispatcher.js Normal file
View file

@ -0,0 +1,175 @@
/*
* Copyright 2022 Sangoma Technologies Corporation
* Kevin Harwell <kharwell@sangoma.com>
*
* 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.
*/
const { randomUUID } = require('crypto');
function handleError(e, msg) {
msg.error_msg = e.message;
}
function sendMessage(speech, msg) {
speech.transport.send(JSON.stringify(msg), { binary: false });
}
function sendSetRequest(speech, params) {
request = {
request: "set",
id: randomUUID(),
params,
};
sendMessage(speech, request);
}
function handleGetRequest(speech, request, response) {
if (!request.params) {
throw new Error("Missing request parameters");
}
let params = {};
for (let p of request.params) {
if (p === "codec") {
params.codecs = speech.codecs.selected;
} else if (p === "language") {
params.language = speech.languages.selected;
} else if (p === "results") {
params.results = speech.provider.results.splice(0);
} else {
console.warn("Ignoring unsupported parameter '" + k + "' in '" +
request.request + "' request");
}
}
response.params = params;
}
function handleSetRequest(speech, request, response) {
if (!request.codecs || !request.params) {
throw new Error("Missing request parameters");
}
/*
* It's all or nothing for an incoming set request. So first validate
* all values, then set newly selected, and lastly set the response.
*/
let codec = null;
let params = {};
if (request.codecs) {
codec = speech.codecs.first(request.codecs);
}
for (let [k, v] of Object.entries(request.params)) {
if (k == "language") {
params.language = speech.languages.first(v);
} else {
console.warn("Ignoring unsupported parameter '" + k + "' in '" +
request.request + "' request");
}
}
if (codec) {
response.codecs = [speech.codecs.selected = codec];
}
if (Object.keys(params).length) {
if (params.language) {
speech.languages.selected = params.language;
}
response.params = params;
}
if (response.codecs || response.params) {
// Start/Restart provider if any parameters were changed
speech.provider.restart({
codec: speech.codecs.selected,
language: speech.languages.selected,
});
}
}
function handleRequest(speech, msg) {
const handlers = {
"get": handleGetRequest,
"set": handleSetRequest,
"setup": handleSetRequest,
};
let response = { response: msg.request, id: msg.id };
try {
handlers[msg.request](speech, msg, response);
} catch (e) {
handleError(e, response);
}
return response;
}
function handleResponse(speech, msg) {
return null; // TODO
}
/**
* Manages configuration, communication, messaging, and data between
* a connected transport and speech provider.
*
* @param {Object} speech - speech object
* @param {Object} speech.codecs - allowed codec(s)
* @param {Object} speech.languages - allowed language(s)
* @param {Object} speech.transport - remote connection
* @param {Object} speech.provider - speech provider
*/
function dispatch(speech) {
speech.transport.on("close", () => {
speech.provider.end();
});
speech.transport.on("message", (data, isBinary) => {
if (isBinary) {
speech.provider.write(data);
return;
}
console.debug("message: " + data);
let msg = JSON.parse(data);
if (msg.hasOwnProperty('request')) {
msg = handleRequest(speech, msg);
} else if (msg.hasOwnProperty('response')) {
msg = handleResponse(speech, msg);
} else {
msg = null;
}
if (msg) {
sendMessage(speech, msg);
}
});
speech.provider.on("result", (result) => {
sendSetRequest(speech, { results: [ result ] });
});
}
module.exports = {
dispatch,
}

78
lib/languages.js Normal file
View file

@ -0,0 +1,78 @@
/*
* Copyright 2022 Sangoma Technologies Corporation
* Kevin Harwell <kharwell@sangoma.com>
*
* 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.
*/
const utils = require("./utils");
/**
* Supported languages
*/
const supported = [
"en-US",
];
/**
* Converts languages to a comma separated string of language names.
*
* @param {Object|Object[]} objs - Languages to convert
* @return {string} A comma separated string of language names.
*/
function toString(objs) {
if (!Array.isArray(objs)) {
objs = [objs];
}
return objs.join(", ");
}
/** @class Languages. */
class Languages {
/**
* Creates an instance of Languages.
*
* @param {Object} options - Language options
*/
constructor(options) {
this.languages = options.languages ?
utils.intersect(supported, options.languages) : supported;
this.selected = this.languages[0]; // Default to first in list
}
/**
* Selects the first matching language between supported and given languages
*
* @param {Object|Object[]} languages - Languages to intersect with supported
* @return The first selected language
*/
first(languages) {
try {
let res = utils.first(this.languages, languages);
if (res) {
return res;
}
} catch (e) {
}
throw new Error("Language " + toString(languages) + " not supported");
}
};
module.exports = {
Languages,
}

292
lib/provider.js Normal file
View file

@ -0,0 +1,292 @@
/*
* Copyright 2022 Sangoma Technologies Corporation
* Kevin Harwell <kharwell@sangoma.com>
*
* 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.
*/
const { Writable } = require('stream');
const speech = require('@google-cloud/speech');
/*
* For speech provider implementer.
*
* Basic Provider public interface:
*
* function setConfig(config) - sets configuration used by recognize stream
* function start(config) - starts the recognize stream
* function restart(config) - restarts the recognize stream
* function end() - stops recognize and writable stream
* function write(data) - writes data to the writable stream
* event result(result) - triggered when a result is received from provider
* field results[] - cache of received results (oldest to newest)
*
* Basic result object public interface:
*
* result = {
* text: <the recognized string value>
* score: <percent based accuracy/confidence score>
* };
*/
/*
* Google Speech API:
* https://googleapis.dev/nodejs/speech/latest/
*
* Google infinite streaming speech example:
* https://cloud.google.com/speech-to-text/docs/samples/speech-transcribe-infinite-streaming
*
* Nodejs stream API:
* https://nodejs.org/api/stream.html
*/
// const encoding = 'Encoding of the audio file, e.g. LINEAR16';
// const sampleRateHertz = 16000;
// const languageCode = 'BCP-47 language code with regional subtags, e.g. en-US';
// const limit = 10000; // ms - set to low number for demo purposes
const DEFAULT_ENCODING = "MULAW";
const DEFAULT_SAMPLE_RATE = 8000;
const DEFAULT_LANGUAGE = "en-US";
const DEFAULT_RESTART_TIME = 10; // in seconds
const DEFAULT_MAX_RESULTS = 100;
/**
* @class GoogleProvider.
*
* Start, restart, and stop Google speech to text recognition. Results are
* emitted via a "result" event that is passed the following object:
*
* result = {
* text: <the recognized string value>
* score: <percent based accuracy/confidence score>
* };
*
* @extends Writable
*/
class GoogleProvider extends Writable {
/* Mapped encodings supported by Google */
static encodings = {
ulaw: "MULAW",
slin16: "LINEAR16",
opus: "OGG Opus",
};
/* Languages this provider supports */
static languages = [
"en-US",
];
/**
* Creates an instance of a Google provider stream.
*
* @param {Object} [options] - provider specific options
* @param {Object} [options.restartTime=10] - If specified auto-restart
* recognition stream after a given interval (in seconds)
* @param {Object} [options.maxResults=100] - The maximum number of results
* to cache before results are dropped (oldest dropped first)
*/
constructor(options) {
super();
this.config = {
encoding: DEFAULT_ENCODING,
sampleRateHertz: DEFAULT_SAMPLE_RATE,
languageCode: DEFAULT_LANGUAGE,
};
this.restartTimer = null;
this.restartTimeout = options && options.restartTime || DEFAULT_RESTART_TIME;
this.maxResults = options && options.maxResults || DEFAULT_MAX_RESULTS;
this.results = [];
this.recognizeStream = null;
}
_construct(callback) {
this.client = new speech.SpeechClient();
callback();
}
_write(chunk, encoding, callback) {
if (this.recognizeStream) {
this.recognizeStream.write(chunk);
}
callback();
}
_writev(chunks, callback) {
for (let chunk in chunks) {
this._write(chunk, null, callback);
}
callback();
}
_final(callback) {
this.stop();
this.client.close();
callback();
}
/**
* Sets the configuration to use on the recognition stream.
*
* @param {Object} [config] - configuration to set
* @param {Object} [config.codec] - the codec to map to an encoding
* @param {string} [config.language] - the language to use
*/
setConfig(config) {
if (!config) {
return;
}
let update = {};
if (config.codec) {
if (!(config.codec.name in GoogleProvider.encodings)) {
throw new Error("Codec '" + config.codec.name + " 'not supported");
}
update.encodingencoding = GoogleProvider.encodings[config.codec.name];
update.sampleRateHertz = config.codec.sampleRate;
}
if (config.language) {
if (!GoogleProvider.languages.includes(config.language)) {
throw new Error("Language '" + config.language + " 'not supported");
}
update.languageCode = config.language;
}
this.config = {...this.config, ...update};
}
/**
* Starts the recognition stream.
*
* @param {Object} [config] - configuration to use
* @param {Object} [config.codec] - the codec to map to an encoding
* @param {string} [config.language] - the language to use
*/
start(config) {
if (this.recognizeStream) {
return; // Already started
}
this.setConfig(config);
config = this.config;
const request = {
config,
interimResults: true,
};
this.recognizeStream = this.client
.streamingRecognize(request)
.on('error', (e) => {
console.error("GoogleProvider: " + e + " - ending stream");
this.end();
})
.on('data', (response) => {
if (response.results[0] && response.results[0].alternatives[0]) {
if (response.results[0].alternatives[0].confidence == 0) {
return;
}
let result = {
text: response.results[0].alternatives[0].transcript,
score: Math.round(response.results[0].alternatives[0].confidence * 100),
};
console.debug("GoogleProvider: result: " + JSON.stringify(result));
this.emit('result', result);
if (this.results.length == this.maxResults) {
this.results.shift();
}
this.results.push(result);
} else {
// stream limit reached restart?
console.debug("GoogleProvider: received response, but no result");
}
});
if (this.restartTimeout) {
/*
* Google's speech engine may stop transcribing after a while,
* so restart the recognize stream after a specified interval.
*/
this.restartTimer = setTimeout(() => this.restart(), this.restartTimeout * 1000);
}
while (this.writableCorked) {
this.uncork();
}
}
/**
* Stops the recognition stream.
*/
stop() {
if (this.restartTimer) {
clearInterval(this.restartTimer);
this.restartTimer = null;
}
if (!this.recognizeStream) {
return;
}
this.cork(); // Buffer any incoming data
this.recognizeStream.end();
this.recognizeStream = null;
}
/**
* Restarts the recognition stream.
*
* @param {Object} [config] - configuration to use
* @param {Object} [config.codec] - the codec to map to an encoding
* @param {string} [config.language] - the language to use
*/
restart(config) {
this.stop();
this.start(config);
}
}
/**
* Gets a speech provider
*
* @param {string} name - A speech provider name
* @param {Object} options - Provider specific options
* @return A speech provider.
*/
function getProvider(name, options) {
if (name == "google") {
return new GoogleProvider(options);
}
throw new Error("Unsupported speech provider '" + name + "'");
}
module.exports = {
getProvider,
}

119
lib/server.js Normal file
View file

@ -0,0 +1,119 @@
/*
* Copyright 2022 Sangoma Technologies Corporation
* Kevin Harwell <kharwell@sangoma.com>
*
* 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.
*/
const EventEmitter = require("events");
const { WebSocketServer } = require("ws");
/*
* For server accepting clients implementer.
*
* Basic server public interface:
*
* function close() - shutdowns the server
* event connection(client) - triggered when a client connects
*
* Basic client public interface:
*
* function send(data, { binary: <boolean> }) - sends data to client
* event close() - triggered when a client closes
* event message(data, isBinary) - triggered when data is received
*/
const DEFAULT_PORT = 9099;
/**
* @class WSServer.
*
* Wrapper around a websocket server. Starts listening on a given port, and
* emits a "connection" event when a client connects.
*
* @extends EventEmitter
*/
class WSServer extends EventEmitter {
/**
* Creates an instance of a Websocket server.
*
* @param {Object} [options] - websocket server specific options
* @param {Object} [options.port=9099] - Port to listen on
*/
constructor(options) {
super();
this.port = options && options.port || DEFAULT_PORT;
this.ws = new WebSocketServer({
port: this.port,
clientTracking: true,
});
this.ws.on("listening", () => {
console.info("Server on port '" + this.port + "': started listening");
});
this.ws.on("close", () => {
console.info("Server on port '" + this.port + "': stopped listening");
});
this.ws.on("error", (error) => {
console.error(error);
});
this.ws.on("connection", (client) => {
console.info("Server on port '" + this.port + "': client connected");
/**
* Client connect event.
*
* @event WSServer#connection
* @type {object}
*/
this.emit("connection", client);
});
}
/**
* Close/Stop the server disconnecting all clients
*/
close() {
for (let client of this.ws.clients) {
console.log("WSServer: close client");
client.close();
}
this.ws.close((error) => {
console.log("error " + error);
});
}
}
/**
* Gets a server.
*
* @param {string} name - A server type name
* @param {Object} options - Server specific options
* @return A server.
*/
function getServer(name, options) {
if (name == "ws") {
return new WSServer(options);
}
throw new Error("Unsupported server type '" + name + "'");
}
module.exports = {
getServer,
}

81
lib/utils.js Normal file
View file

@ -0,0 +1,81 @@
/*
* Copyright 2022 Sangoma Technologies Corporation
* Kevin Harwell <kharwell@sangoma.com>
*
* 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.
*/
/**
* Checks to see if given objects are equal.
*
* @param {Object} obj1
* @param {Object} obj2
* @param {requestCallback} [eq] - Object equality callback
* @return {string} A comma separated string of language names.
*/
function equals(obj1, obj2, eq) {
if (obj1 == undefined || obj1 == null ||
obj2 == undefined || obj2 == null) {
return false;
}
return obj1 == obj2 || (eq && eq(obj1, obj2));
}
/**
* Creates a list of objects that contains only those objects that are equal between
* the given lists of objects.
*
* @param {Object[]} objs1
* @param {Object[]} objs2
* @param {requestCallback} [eq] - Object equality callback
* @return {Object[]} An intersected list of objects.
*/
function intersect(objs1, objs2, eq) {
let res = [];
for (let obj1 of objs1) {
for (let obj2 of objs2) {
if (equals(obj1, obj2, eq)) {
res.push(obj1);
}
}
}
return res;
}
/**
* Finds and returns the first matching object within two given lists.
*
* @param {Object[]} objs1
* @param {Object[]} objs2
* @param {requestCallback} [eq] - Object equality callback
* @return {Object} The first matching object.
*/
function first(objs1, objs2, eq) {
if (!Array.isArray(objs1)) {
objs1 = [objs1];
}
if (!Array.isArray(objs2)) {
objs2 = [objs2];
}
return intersect(objs1, objs2, eq)[0];
}
module.exports = {
first,
intersect,
}

1656
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

25
package.json Normal file
View file

@ -0,0 +1,25 @@
{
"name": "aeap-speech-to-text",
"description": "asterisk external speech to text application",
"version": "0.1.0",
"homepage": "https://github.com/asterisk/aeap-speech-to-text#README.md",
"main": "./index.js",
"bin": "./index.js",
"license": "Apache-2.0",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "https://github.com/asterisk/aeap-speech-to-text.git"
},
"keywords": [
"asterisk",
"asterisk external application protocol",
"aeap",
"speech"
],
"dependencies": {
"@google-cloud/speech": "^4.9.0",
"ws": "^8.3.0",
"yargs": "^17.3.1"
}
}