@jambonz/speech-utils 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintignore ADDED
@@ -0,0 +1 @@
1
+ test/*
package/.eslintrc.json ADDED
@@ -0,0 +1,126 @@
1
+ {
2
+ "env": {
3
+ "node": true,
4
+ "es6": true
5
+ },
6
+ "parserOptions": {
7
+ "ecmaFeatures": {
8
+ "jsx": false,
9
+ "modules": false
10
+ },
11
+ "ecmaVersion": 2020
12
+ },
13
+ "plugins": ["promise"],
14
+ "rules": {
15
+ "promise/always-return": "error",
16
+ "promise/no-return-wrap": "error",
17
+ "promise/param-names": "error",
18
+ "promise/catch-or-return": "error",
19
+ "promise/no-native": "off",
20
+ "promise/no-nesting": "warn",
21
+ "promise/no-promise-in-callback": "warn",
22
+ "promise/no-callback-in-promise": "warn",
23
+ "promise/no-return-in-finally": "warn",
24
+
25
+ // Possible Errors
26
+ // http://eslint.org/docs/rules/#possible-errors
27
+ "comma-dangle": [2, "only-multiline"],
28
+ "no-control-regex": 2,
29
+ "no-debugger": 2,
30
+ "no-dupe-args": 2,
31
+ "no-dupe-keys": 2,
32
+ "no-duplicate-case": 2,
33
+ "no-empty-character-class": 2,
34
+ "no-ex-assign": 2,
35
+ "no-extra-boolean-cast" : 2,
36
+ "no-extra-parens": [2, "functions"],
37
+ "no-extra-semi": 2,
38
+ "no-func-assign": 2,
39
+ "no-invalid-regexp": 2,
40
+ "no-irregular-whitespace": 2,
41
+ "no-negated-in-lhs": 2,
42
+ "no-obj-calls": 2,
43
+ "no-proto": 2,
44
+ "no-unexpected-multiline": 2,
45
+ "no-unreachable": 2,
46
+ "use-isnan": 2,
47
+ "valid-typeof": 2,
48
+
49
+ // Best Practices
50
+ // http://eslint.org/docs/rules/#best-practices
51
+ "no-fallthrough": 2,
52
+ "no-octal": 2,
53
+ "no-redeclare": 2,
54
+ "no-self-assign": 2,
55
+ "no-unused-labels": 2,
56
+
57
+ // Strict Mode
58
+ // http://eslint.org/docs/rules/#strict-mode
59
+ "strict": [2, "never"],
60
+
61
+ // Variables
62
+ // http://eslint.org/docs/rules/#variables
63
+ "no-delete-var": 2,
64
+ "no-undef": 2,
65
+ "no-unused-vars": [2, {"args": "none"}],
66
+
67
+ // Node.js and CommonJS
68
+ // http://eslint.org/docs/rules/#nodejs-and-commonjs
69
+ "no-mixed-requires": 2,
70
+ "no-new-require": 2,
71
+ "no-path-concat": 2,
72
+ "no-restricted-modules": [2, "sys", "_linklist"],
73
+
74
+ // Stylistic Issues
75
+ // http://eslint.org/docs/rules/#stylistic-issues
76
+ "comma-spacing": 2,
77
+ "eol-last": 2,
78
+ "indent": [2, 2, {"SwitchCase": 1}],
79
+ "keyword-spacing": 2,
80
+ "max-len": [2, 120, 2],
81
+ "new-parens": 2,
82
+ "no-mixed-spaces-and-tabs": 2,
83
+ "no-multiple-empty-lines": [2, {"max": 2}],
84
+ "no-trailing-spaces": [2, {"skipBlankLines": false }],
85
+ "quotes": [2, "single", "avoid-escape"],
86
+ "semi": 2,
87
+ "space-before-blocks": [2, "always"],
88
+ "space-before-function-paren": [2, "never"],
89
+ "space-in-parens": [2, "never"],
90
+ "space-infix-ops": 2,
91
+ "space-unary-ops": 2,
92
+
93
+ // ECMAScript 6
94
+ // http://eslint.org/docs/rules/#ecmascript-6
95
+ "arrow-parens": [2, "always"],
96
+ "arrow-spacing": [2, {"before": true, "after": true}],
97
+ "constructor-super": 2,
98
+ "no-class-assign": 2,
99
+ "no-confusing-arrow": 2,
100
+ "no-const-assign": 2,
101
+ "no-dupe-class-members": 2,
102
+ "no-new-symbol": 2,
103
+ "no-this-before-super": 2,
104
+ "prefer-const": 2
105
+ },
106
+ "globals": {
107
+ "DTRACE_HTTP_CLIENT_REQUEST" : false,
108
+ "LTTNG_HTTP_CLIENT_REQUEST" : false,
109
+ "COUNTER_HTTP_CLIENT_REQUEST" : false,
110
+ "DTRACE_HTTP_CLIENT_RESPONSE" : false,
111
+ "LTTNG_HTTP_CLIENT_RESPONSE" : false,
112
+ "COUNTER_HTTP_CLIENT_RESPONSE" : false,
113
+ "DTRACE_HTTP_SERVER_REQUEST" : false,
114
+ "LTTNG_HTTP_SERVER_REQUEST" : false,
115
+ "COUNTER_HTTP_SERVER_REQUEST" : false,
116
+ "DTRACE_HTTP_SERVER_RESPONSE" : false,
117
+ "LTTNG_HTTP_SERVER_RESPONSE" : false,
118
+ "COUNTER_HTTP_SERVER_RESPONSE" : false,
119
+ "DTRACE_NET_STREAM_END" : false,
120
+ "LTTNG_NET_STREAM_END" : false,
121
+ "COUNTER_NET_SERVER_CONNECTION_CLOSE" : false,
122
+ "DTRACE_NET_SERVER_CONNECTION" : false,
123
+ "LTTNG_NET_SERVER_CONNECTION" : false,
124
+ "COUNTER_NET_SERVER_CONNECTION" : false
125
+ }
126
+ }
@@ -0,0 +1,27 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ workflow_dispatch:
6
+
7
+ jobs:
8
+ build:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v3
12
+ - uses: actions/setup-node@v3
13
+ with:
14
+ node-version: lts/*
15
+ - run: npm install
16
+ - run: npm run jslint
17
+ - run: npm test
18
+ env:
19
+ AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
20
+ AWS_REGION: ${{ secrets.AWS_REGION }}
21
+ AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
22
+ GCP_JSON_KEY: ${{ secrets.GCP_JSON_KEY }}
23
+ IBM_API_KEY: ${{ secrets.IBM_API_KEY }}
24
+ IBM_TTS_API_KEY: ${{ secrets.IBM_TTS_API_KEY }}
25
+ IBM_TTS_REGION: ${{ secrets.IBM_TTS_REGION }}
26
+ MICROSOFT_API_KEY: ${{ secrets.MICROSOFT_API_KEY }}
27
+ MICROSOFT_REGION: ${{ secrets.MICROSOFT_REGION }}
@@ -0,0 +1,23 @@
1
+ name: npm-publish
2
+
3
+ # run when a tag is pushed or kick off manually
4
+ on:
5
+ push:
6
+ tags:
7
+ - '*'
8
+ workflow_dispatch:
9
+
10
+ jobs:
11
+ build:
12
+ runs-on: ubuntu-latest
13
+
14
+ steps:
15
+ - uses: actions/checkout@v3
16
+ - uses: actions/setup-node@v3
17
+ with:
18
+ node-version: lts/*
19
+ registry-url: 'https://registry.npmjs.org'
20
+ - run: npm install
21
+ - run: npm publish --access public
22
+ env:
23
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 jambonz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # speech-utils
2
+ TTS-related speech utilities for jambonz
package/build_stubs.sh ADDED
@@ -0,0 +1,11 @@
1
+ #!/bin/sh
2
+
3
+ mkdir -p stubs/nuance
4
+
5
+ for FILE in ./protos/nuance/*; do
6
+ grpc_tools_node_protoc \
7
+ --js_out=import_style=commonjs,binary:./stubs/nuance \
8
+ --grpc_out=grpc_js:./stubs/nuance \
9
+ --proto_path=./protos/nuance \
10
+ $FILE
11
+ done
@@ -0,0 +1,13 @@
1
+ {
2
+ "logging": {
3
+ "level": "error"
4
+ },
5
+ "redis": {
6
+ "host": "127.0.0.1",
7
+ "port": 3379
8
+ },
9
+ "redis-auth": {
10
+ "host": "127.0.0.1",
11
+ "port": 3380
12
+ }
13
+ }
package/index.js ADDED
@@ -0,0 +1,32 @@
1
+ const {noopLogger} = require('./lib/utils');
2
+ const promisify = require('@jambonz/promisify-redis');
3
+ const redis = promisify(require('redis'));
4
+
5
+ module.exports = (opts, logger) => {
6
+ const {host = '127.0.0.1', port = 6379, tls = false} = opts;
7
+ logger = logger || noopLogger;
8
+
9
+ const url = process.env.JAMBONES_REDIS_USERNAME && process.env.JAMBONES_REDIS_PASSWORD ?
10
+ `${process.env.JAMBONES_REDIS_USERNAME}:${process.env.JAMBONES_REDIS_PASSWORD}@${host}:${port}` :
11
+ `${host}:${port}`;
12
+ const client = redis.createClient(tls ? `rediss://${url}` : `redis://${url}`);
13
+ ['ready', 'connect', 'reconnecting', 'error', 'end', 'warning']
14
+ .forEach((event) => {
15
+ client.on(event, (...args) => {
16
+ if ('error' === event) {
17
+ if (process.env.NODE_ENV === 'test' && args[0]?.code === 'ECONNREFUSED') return;
18
+ logger.error({...args}, '@jambonz/realtimedb-helpers - redis error');
19
+ }
20
+ else logger.debug({args}, `redis event ${event}`);
21
+ });
22
+ });
23
+
24
+ return {
25
+ client,
26
+ purgeTtsCache: require('./lib/purge-tts-cache').bind(null, client, logger),
27
+ synthAudio: require('./lib/synth-audio').bind(null, client, logger),
28
+ getNuanceAccessToken: require('./lib/get-nuance-access-token').bind(null, client, logger),
29
+ getIbmAccessToken: require('./lib/get-ibm-access-token').bind(null, client, logger),
30
+ getTtsVoices: require('./lib/get-tts-voices').bind(null, client, logger),
31
+ };
32
+ };
@@ -0,0 +1,48 @@
1
+ const formurlencoded = require('form-urlencoded');
2
+ const {Pool} = require('undici');
3
+ const pool = new Pool('https://iam.cloud.ibm.com');
4
+ const {makeIbmKey, noopLogger} = require('./utils');
5
+ const debug = require('debug')('jambonz:realtimedb-helpers');
6
+ const HTTP_TIMEOUT = 5000;
7
+
8
+ async function getIbmAccessToken(client, logger, apiKey) {
9
+ logger = logger || noopLogger;
10
+ try {
11
+ const key = makeIbmKey(apiKey);
12
+ const access_token = await client.getAsync(key);
13
+ if (access_token) return {access_token, servedFromCache: true};
14
+
15
+ /* access token not found in cache, so fetch it from Ibm */
16
+ const payload = {
17
+ grant_type: 'urn:ibm:params:oauth:grant-type:apikey',
18
+ apikey: apiKey
19
+ };
20
+ const {statusCode, headers, body} = await pool.request({
21
+ path: '/identity/token',
22
+ method: 'POST',
23
+ headers: {
24
+ 'Content-Type': 'application/x-www-form-urlencoded'
25
+ },
26
+ body: formurlencoded(payload),
27
+ timeout: HTTP_TIMEOUT,
28
+ followRedirects: false
29
+ });
30
+
31
+ if (200 !== statusCode) {
32
+ const json = await body.json();
33
+ logger.debug({statusCode, headers, body: json}, 'error fetching access token from Ibm');
34
+ const err = new Error();
35
+ err.statusCode = statusCode;
36
+ throw err;
37
+ }
38
+ const json = await body.json();
39
+ await client.set(key, json.access_token, 'EX', json.expires_in - 30);
40
+ return {...json, servedFromCache: false};
41
+ } catch (err) {
42
+ debug(err, 'getIbmAccessToken: Error retrieving Ibm access token');
43
+ logger.error(err, 'getIbmAccessToken: Error retrieving Ibm access token for client_id ${clientId}');
44
+ throw err;
45
+ }
46
+ }
47
+
48
+ module.exports = getIbmAccessToken;
@@ -0,0 +1,49 @@
1
+ const formurlencoded = require('form-urlencoded');
2
+ const {Pool} = require('undici');
3
+ const pool = new Pool('https://auth.crt.nuance.com');
4
+ const {makeNuanceKey, makeBasicAuthHeader, noopLogger} = require('./utils');
5
+ const debug = require('debug')('jambonz:realtimedb-helpers');
6
+ const HTTP_TIMEOUT = 5000;
7
+
8
+ async function getNuanceAccessToken(client, logger, clientId, secret, scope) {
9
+ logger = logger || noopLogger;
10
+ try {
11
+ const key = makeNuanceKey(clientId, secret, scope);
12
+ const access_token = await client.getAsync(key);
13
+ if (access_token) return {access_token, servedFromCache: true};
14
+
15
+ /* access token not found in cache, so fetch it from Nuance */
16
+ const payload = {
17
+ grant_type: 'client_credentials',
18
+ scope
19
+ };
20
+ const auth = makeBasicAuthHeader(clientId, secret);
21
+ const {statusCode, headers, body} = await pool.request({
22
+ path: '/oauth2/token',
23
+ method: 'POST',
24
+ headers: {
25
+ ...auth,
26
+ 'Content-Type': 'application/x-www-form-urlencoded'
27
+ },
28
+ body: formurlencoded(payload),
29
+ timeout: HTTP_TIMEOUT,
30
+ followRedirects: false
31
+ });
32
+
33
+ if (200 !== statusCode) {
34
+ logger.debug({statusCode, headers, body: body.text()}, 'error fetching access token from Nuance');
35
+ const err = new Error();
36
+ err.statusCode = statusCode;
37
+ throw err;
38
+ }
39
+ const json = await body.json();
40
+ await client.set(key, json.access_token, 'EX', json.expires_in - 30);
41
+ return {...json, servedFromCache: false};
42
+ } catch (err) {
43
+ debug(err, `getNuanceAccessToken: Error retrieving Nuance access token for client_id ${clientId}`);
44
+ logger.error(err, `getNuanceAccessToken: Error retrieving Nuance access token for client_id ${clientId}`);
45
+ throw err;
46
+ }
47
+ }
48
+
49
+ module.exports = getNuanceAccessToken;
@@ -0,0 +1,111 @@
1
+ const assert = require('assert');
2
+ const {noopLogger, createNuanceClient} = require('./utils');
3
+ const getNuanceAccessToken = require('./get-nuance-access-token');
4
+ const {GetVoicesRequest, Voice} = require('../stubs/nuance/synthesizer_pb');
5
+ const TextToSpeechV1 = require('ibm-watson/text-to-speech/v1');
6
+ const { IamAuthenticator } = require('ibm-watson/auth');
7
+
8
+ const getIbmVoices = async(client, logger, credentials) => {
9
+ const {tts_region, tts_api_key} = credentials;
10
+ console.log(`region: ${tts_region}, api_key: ${tts_api_key}`);
11
+
12
+ const textToSpeech = new TextToSpeechV1({
13
+ authenticator: new IamAuthenticator({
14
+ apikey: tts_api_key,
15
+ }),
16
+ serviceUrl: `https://api.${tts_region}.text-to-speech.watson.cloud.ibm.com`
17
+ });
18
+
19
+ const voices = await textToSpeech.listVoices();
20
+ return voices;
21
+ };
22
+
23
+ const getNuanceVoices = async(client, logger, credentials) => {
24
+ const {client_id: clientId, secret: secret} = credentials;
25
+
26
+ return new Promise(async(resolve, reject) => {
27
+ /* get a nuance access token */
28
+ let token, nuanceClient;
29
+ try {
30
+ const access_token = await getNuanceAccessToken(client, logger, clientId, secret, 'tts');
31
+ token = access_token.access_token;
32
+ nuanceClient = await createNuanceClient(token);
33
+ } catch (err) {
34
+ logger.error({err}, 'getTtsVoices: error retrieving access token');
35
+ return reject(err);
36
+ }
37
+ /* retrieve all voices */
38
+ const v = new Voice();
39
+ const request = new GetVoicesRequest();
40
+ request.setVoice(v);
41
+
42
+ nuanceClient.getVoices(request, (err, response) => {
43
+ if (err) {
44
+ logger.error({err, clientId, secret, token}, 'getTtsVoices: error retrieving voices');
45
+ return reject(err);
46
+ }
47
+
48
+ /* return all the voices that are not restricted and eliminate duplicates */
49
+ const voices = response.getVoicesList()
50
+ .map((v) => {
51
+ return {
52
+ language: v.getLanguage(),
53
+ name: v.getName(),
54
+ model: v.getModel(),
55
+ gender: v.getGender() === 1 ? 'male' : 'female',
56
+ restricted: v.getRestricted()
57
+ };
58
+ });
59
+ const v = voices
60
+ .filter((v) => v.restricted === false)
61
+ .map((v) => {
62
+ delete v.restricted;
63
+ return v;
64
+ })
65
+ .sort((a, b) => {
66
+ if (a.language < b.language) return -1;
67
+ if (a.language > b.language) return 1;
68
+ if (a.name < b.name) return -1;
69
+ return 1;
70
+ });
71
+ const arr = [...new Set(v.map((v) => JSON.stringify(v)))]
72
+ .map((v) => JSON.parse(v));
73
+ resolve(arr);
74
+ });
75
+ });
76
+ };
77
+
78
+ /**
79
+ * Synthesize speech to an mp3 file, and also cache the generated speech
80
+ * in redis (base64 format) for 24 hours so as to avoid unnecessarily paying
81
+ * time and again for speech synthesis of the same text.
82
+ * It is the responsibility of the caller to unlink the mp3 file after use.
83
+ *
84
+ * @param {*} client - redis client
85
+ * @param {*} logger - pino logger
86
+ * @param {object} opts - options
87
+ * @param {string} opts.vendor - 'google' or 'aws' ('polly' is an alias for 'aws')
88
+ * @param {string} opt.language - language code
89
+ * @param {string} opts.voice - voice identifier
90
+ * @param {string} opts.text - text or ssml to synthesize
91
+ * @returns object containing filepath to an mp3 file in the /tmp folder containing
92
+ * the synthesized audio, and a variable indicating whether it was served from cache
93
+ */
94
+ async function getTtsVoices(client, logger, {vendor, credentials}) {
95
+ logger = logger || noopLogger;
96
+
97
+ assert.ok(['nuance', 'ibm'].includes(vendor),
98
+ `getTtsVoices not supported for vendor ${vendor}`);
99
+
100
+ switch (vendor) {
101
+ case 'nuance':
102
+ return getNuanceVoices(client, logger, credentials);
103
+ case 'ibm':
104
+ return getIbmVoices(client, logger, credentials);
105
+ default:
106
+ break;
107
+ }
108
+ }
109
+
110
+
111
+ module.exports = getTtsVoices;
@@ -0,0 +1,46 @@
1
+ const {noopLogger, makeSynthKey} = require('./utils');
2
+ const debug = require('debug')('jambonz:realtimedb-helpers');
3
+
4
+ /**
5
+ * Scan TTS Cache and purge records, use specific settings to purge just one
6
+ * @param {object} opts - options
7
+ * @param {boolean} opts.all - purge all records or only one specific, true by default
8
+ * @param {string} opts.vendor - 'google' or 'aws' ('polly' is an alias for 'aws')
9
+ * @param {string} opts.language - language code
10
+ * @param {string} opts.voice - voice identifier
11
+ * @param {string} opts.text - text or ssml to synthesize
12
+ * @returns {object} result - {error, purgedCount}
13
+ */
14
+ async function purgeTtsCache(client, logger, {all, vendor, language, voice, deploymentId, engine, text} = {all: true}) {
15
+ logger = logger || noopLogger;
16
+
17
+ let purgedCount = 0, error;
18
+
19
+ try {
20
+ if (all) {
21
+ const keys = await client.keysAsync('tts:*');
22
+ purgedCount = await client.delAsync(keys);
23
+
24
+ } else {
25
+ const key = makeSynthKey({
26
+ vendor,
27
+ language: language || '',
28
+ voice: voice || deploymentId,
29
+ engine,
30
+ text,
31
+ });
32
+ purgedCount = await client.delAsync(key);
33
+ if (purgedCount === 0) error = 'Specified item not found';
34
+ }
35
+
36
+ } catch (err) {
37
+ debug(err, 'purgeTtsCache: Error');
38
+ logger.error(err, 'purgeTtsCache: Error');
39
+ error = err.message ?? 'Unknown Error';
40
+ }
41
+
42
+ logger.info(`purgeTtsCache: purged ${purgedCount} records`);
43
+ return {error, purgedCount};
44
+ }
45
+
46
+ module.exports = purgeTtsCache;