Compare commits

...
26 Commits
Author SHA1 Message Date
Dave Horton 98f679f43a 0.0.16 2023-07-19 10:04:17 -04:00
Dave Horton 7e7841b5ff Merge pull request #23 from jambonz/feature/trim-silence
trim trailing silence from azure tts when JAMBONES_TTS_TRIM_SILENCE i…
2023-07-19 10:03:42 -04:00
Dave Horton 75ce537db1 linting 2023-07-19 10:02:10 -04:00
Dave Horton 830be783b8 trim trailing silence from azure tts when JAMBONES_TTS_TRIM_SILENCE is set 2023-07-19 10:00:31 -04:00
Dave Horton 38c3219425 Merge pull request #21 from jambonz/snyk-fix-255777535fcb48b70c964213f7dd9fe8
[Snyk] Security upgrade @aws-sdk/client-polly from 3.303.0 to 3.347.1
2023-06-07 13:09:27 -04:00
snyk-bot e37b96a9c2 fix: package.json & package-lock.json to reduce vulnerabilities
The following vulnerabilities are fixed with an upgrade:
- https://snyk.io/vuln/SNYK-JS-FASTXMLPARSER-5668858
2023-06-07 15:35:04 +00:00
Dave Horton c184fbae26 0.0.15 2023-06-03 09:15:48 -04:00
Dave Horton 66d33ebd60 change default tts cache duration to 4 hours 2023-06-03 09:15:45 -04:00
Dave Horton 98e1bf62f9 0.0.14 2023-05-31 11:15:38 -04:00
Dave Horton 63edbc2883 Merge pull request #20 from jambonz/feat/clear_tts
feat: ioredis and getsize of tts cache
2023-05-31 11:13:48 -04:00
Quan HL fb75de6af5 feat: ioredis and getsize of tts cache 2023-05-31 21:56:50 +07:00
Quan HL 617f7af4af feat: ioredis and getsize of tts cache 2023-05-31 21:53:18 +07:00
Dave Horton 6c5c8e734f 0.0.13 2023-05-10 07:39:21 -04:00
Dave Horton 4349cd7e40 Merge pull request #19 from jambonz/fix/nvidia
fixes for riva tts
2023-05-10 07:38:58 -04:00
Dave Horton b6058ca242 fix nvidia test 2023-05-10 07:36:25 -04:00
Dave Horton 68cbd63bbd minor logging 2023-05-09 13:59:38 -04:00
Dave Horton 521560e276 fixes for riva tts 2023-05-09 13:57:41 -04:00
Dave Horton d606141f57 fix issue in prev commit for microsoft 2023-04-01 13:19:27 -04:00
Dave Horton 0d58954537 bump version 2023-04-01 10:48:05 -04:00
Dave Horton 7c0eafded3 Merge pull request #18 from jambonz/fix/microsoft-buffer
fix: microsft retrun arrayBuffer not buffer, convert it now to buffer
2023-04-01 10:46:40 -04:00
Quan HL ab7d145288 fix: microsft retrun arrayBuffer not buffer, convert it now to buffer 2023-04-01 13:39:33 +07:00
Dave Horton 11746d3f22 bump version and minor changes 2023-03-31 20:05:07 -04:00
Dave Horton 3fcfbd10a1 Merge pull request #17 from jambonz/fix/imterim_audio_cut
fix: use synthesized audio data directly from microsoft sdk
2023-03-31 20:03:38 -04:00
Quan HL df8acbed0e fix: audioData is getter 2023-04-01 06:58:55 +07:00
Quan HL 4296ed7256 fix: user synthesized audio data directly from microsoft sdk 2023-04-01 06:37:33 +07:00
Quan HL f4b271c7b3 fix: user synthesized audio data directly from microsoft sdk 2023-04-01 06:36:15 +07:00
13 changed files with 1205 additions and 1011 deletions
+3 -1
View File
@@ -8,6 +8,8 @@
}, },
"redis-auth": { "redis-auth": {
"host": "127.0.0.1", "host": "127.0.0.1",
"port": 3380 "port": 3380,
"username": "daveh",
"password": "foobarbazzle"
} }
} }
+16 -7
View File
@@ -1,15 +1,23 @@
const {noopLogger} = require('./lib/utils'); const {noopLogger} = require('./lib/utils');
const promisify = require('@jambonz/promisify-redis'); const Redis = require('ioredis');
const redis = promisify(require('redis'));
module.exports = (opts, logger) => { module.exports = (opts, logger) => {
const {host = '127.0.0.1', port = 6379, tls = false} = opts;
logger = logger || noopLogger; logger = logger || noopLogger;
const connectionOpts = {...opts};
// Support legacy app
if (process.env.JAMBONES_REDIS_USERNAME && process.env.JAMBONES_REDIS_PASSWORD) {
if (Array.isArray(connectionOpts)) {
for (const o of opts) {
o.username = process.env.JAMBONES_REDIS_USERNAME;
o.password = process.env.JAMBONES_REDIS_PASSWORD;
}
} else {
connectionOpts.username = process.env.JAMBONES_REDIS_USERNAME;
connectionOpts.password = process.env.JAMBONES_REDIS_PASSWORD;
}
}
const url = process.env.JAMBONES_REDIS_USERNAME && process.env.JAMBONES_REDIS_PASSWORD ? const client = new Redis(connectionOpts);
`${process.env.JAMBONES_REDIS_USERNAME}:${process.env.JAMBONES_REDIS_PASSWORD}@${host}:${port}` :
`${host}:${port}`;
const client = redis.createClient(tls ? `rediss://${url}` : `redis://${url}`);
['ready', 'connect', 'reconnecting', 'error', 'end', 'warning'] ['ready', 'connect', 'reconnecting', 'error', 'end', 'warning']
.forEach((event) => { .forEach((event) => {
client.on(event, (...args) => { client.on(event, (...args) => {
@@ -23,6 +31,7 @@ module.exports = (opts, logger) => {
return { return {
client, client,
getTtsSize: require('./lib/get-tts-size').bind(null, client, logger),
purgeTtsCache: require('./lib/purge-tts-cache').bind(null, client, logger), purgeTtsCache: require('./lib/purge-tts-cache').bind(null, client, logger),
synthAudio: require('./lib/synth-audio').bind(null, client, logger), synthAudio: require('./lib/synth-audio').bind(null, client, logger),
getNuanceAccessToken: require('./lib/get-nuance-access-token').bind(null, client, logger), getNuanceAccessToken: require('./lib/get-nuance-access-token').bind(null, client, logger),
+1 -1
View File
@@ -9,7 +9,7 @@ async function getIbmAccessToken(client, logger, apiKey) {
logger = logger || noopLogger; logger = logger || noopLogger;
try { try {
const key = makeIbmKey(apiKey); const key = makeIbmKey(apiKey);
const access_token = await client.getAsync(key); const access_token = await client.get(key);
if (access_token) return {access_token, servedFromCache: true}; if (access_token) return {access_token, servedFromCache: true};
/* access token not found in cache, so fetch it from Ibm */ /* access token not found in cache, so fetch it from Ibm */
+1 -1
View File
@@ -9,7 +9,7 @@ async function getNuanceAccessToken(client, logger, clientId, secret, scope) {
logger = logger || noopLogger; logger = logger || noopLogger;
try { try {
const key = makeNuanceKey(clientId, secret, scope); const key = makeNuanceKey(clientId, secret, scope);
const access_token = await client.getAsync(key); const access_token = await client.get(key);
if (access_token) return {access_token, servedFromCache: true}; if (access_token) return {access_token, servedFromCache: true};
/* access token not found in cache, so fetch it from Nuance */ /* access token not found in cache, so fetch it from Nuance */
+11
View File
@@ -0,0 +1,11 @@
async function getTtsSize(client, logger, pattern = null) {
let keys;
if (pattern) {
keys = await client.keys(pattern);
} else {
keys = await client.keys('tts:*');
}
return keys.length;
}
module.exports = getTtsSize;
+5 -5
View File
@@ -19,12 +19,12 @@ async function purgeTtsCache(client, logger, {all, account_sid, vendor,
try { try {
if (all) { if (all) {
const keys = await client.keysAsync('tts:*'); const keys = await client.keys('tts:*');
purgedCount = await client.delAsync(keys); purgedCount = await client.del(keys);
} else if (account_sid && !vendor && !language && !voice && !engine && !text) { } else if (account_sid && !vendor && !language && !voice && !engine && !text) {
const keys = await client.keysAsync(`tts:${account_sid}:*`); const keys = await client.keys(`tts:${account_sid}:*`);
purgedCount = await client.delAsync(keys); purgedCount = await client.del(keys);
} }
else { else {
const key = makeSynthKey({ const key = makeSynthKey({
@@ -35,7 +35,7 @@ async function purgeTtsCache(client, logger, {all, account_sid, vendor,
engine, engine,
text, text,
}); });
purgedCount = await client.delAsync(key); purgedCount = await client.del(key);
if (purgedCount === 0) error = 'Specified item not found'; if (purgedCount === 0) error = 'Specified item not found';
} }
+53 -28
View File
@@ -2,14 +2,12 @@ const assert = require('assert');
const fs = require('fs'); const fs = require('fs');
const bent = require('bent'); const bent = require('bent');
const ttsGoogle = require('@google-cloud/text-to-speech'); const ttsGoogle = require('@google-cloud/text-to-speech');
//const Polly = require('aws-sdk/clients/polly');
const { PollyClient, SynthesizeSpeechCommand } = require('@aws-sdk/client-polly'); const { PollyClient, SynthesizeSpeechCommand } = require('@aws-sdk/client-polly');
const sdk = require('microsoft-cognitiveservices-speech-sdk'); const sdk = require('microsoft-cognitiveservices-speech-sdk');
const TextToSpeechV1 = require('ibm-watson/text-to-speech/v1'); const TextToSpeechV1 = require('ibm-watson/text-to-speech/v1');
const { IamAuthenticator } = require('ibm-watson/auth'); const { IamAuthenticator } = require('ibm-watson/auth');
const { const {
AudioConfig,
ResultReason, ResultReason,
SpeechConfig, SpeechConfig,
SpeechSynthesizer, SpeechSynthesizer,
@@ -32,9 +30,27 @@ const {
const {SynthesizeSpeechRequest} = require('../stubs/riva/proto/riva_tts_pb'); const {SynthesizeSpeechRequest} = require('../stubs/riva/proto/riva_tts_pb');
const {AudioEncoding} = require('../stubs/riva/proto/riva_audio_pb'); const {AudioEncoding} = require('../stubs/riva/proto/riva_audio_pb');
const debug = require('debug')('jambonz:realtimedb-helpers'); const debug = require('debug')('jambonz:realtimedb-helpers');
const EXPIRES = (process.env.JAMBONES_TTS_CACHE_DURATION_MINS || 24 * 60) * 60; // cache tts for 24 hours const EXPIRES = (process.env.JAMBONES_TTS_CACHE_DURATION_MINS || 4 * 60) * 60; // cache tts for 4 hours
const TMP_FOLDER = '/tmp'; const TMP_FOLDER = '/tmp';
const trimTrailingSilence = (buffer) => {
assert.ok(buffer instanceof Buffer, 'trimTrailingSilence - argument is not a Buffer');
let offset = buffer.length;
while (offset > 0) {
// Get 16-bit value from the buffer (read in reverse)
const value = buffer.readUInt16BE(offset - 2);
if (value !== 0) {
break;
}
offset -= 2;
}
// Trim the silence from the end
return offset === buffer.length ? buffer : buffer.subarray(0, offset);
};
/** /**
* Synthesize speech to an mp3 file, and also cache the generated speech * Synthesize speech to an mp3 file, and also cache the generated speech
* in redis (base64 format) for 24 hours so as to avoid unnecessarily paying * in redis (base64 format) for 24 hours so as to avoid unnecessarily paying
@@ -83,7 +99,7 @@ async function synthAudio(client, logger, stats, { account_sid,
else if ('nvidia' === vendor) { else if ('nvidia' === vendor) {
assert.ok(voice, 'synthAudio requires voice when nvidia is used'); assert.ok(voice, 'synthAudio requires voice when nvidia is used');
assert.ok(language, 'synthAudio requires language when nvidia is used'); assert.ok(language, 'synthAudio requires language when nvidia is used');
assert.ok(credentials.riva_uri, 'synthAudio requires riva_uri in credentials when nuance is used'); assert.ok(credentials.riva_server_uri, 'synthAudio requires riva_server_uri in credentials when nvidia is used');
} }
else if ('ibm' === vendor) { else if ('ibm' === vendor) {
assert.ok(voice, 'synthAudio requires voice when ibm is used'); assert.ok(voice, 'synthAudio requires voice when ibm is used');
@@ -106,14 +122,19 @@ async function synthAudio(client, logger, stats, { account_sid,
text text
}); });
let filePath; let filePath;
if (['nuance', 'nvidia'].includes(vendor)) { if (['nuance', 'nvidia'].includes(vendor) ||
(
process.env.JAMBONES_TTS_TRIM_SILENCE &&
['microsoft', 'azure'].includes(vendor)
)
) {
filePath = `${TMP_FOLDER}/${key.replace('tts:', `tts-${salt || ''}`)}.r8`; filePath = `${TMP_FOLDER}/${key.replace('tts:', `tts-${salt || ''}`)}.r8`;
} }
else filePath = `${TMP_FOLDER}/${key.replace('tts:', `tts-${salt || ''}`)}.mp3`; else filePath = `${TMP_FOLDER}/${key.replace('tts:', `tts-${salt || ''}`)}.mp3`;
debug(`synth key is ${key}`); debug(`synth key is ${key}`);
let cached; let cached;
if (!disableTtsCache) { if (!disableTtsCache) {
cached = await client.getAsync(key); cached = await client.get(key);
} }
if (cached) { if (cached) {
// found in cache - extend the expiry and use it // found in cache - extend the expiry and use it
@@ -121,7 +142,7 @@ async function synthAudio(client, logger, stats, { account_sid,
servedFromCache = true; servedFromCache = true;
stats.increment('tts.cache.requests', ['found:yes']); stats.increment('tts.cache.requests', ['found:yes']);
audioBuffer = Buffer.from(cached, 'base64'); audioBuffer = Buffer.from(cached, 'base64');
client.expireAsync(key, EXPIRES).catch((err) => logger.info(err, 'Error setting expires')); client.expire(key, EXPIRES).catch((err) => logger.info(err, 'Error setting expires'));
} }
if (!cached) { if (!cached) {
// not found in cache - go get it from speech vendor and add to cache // not found in cache - go get it from speech vendor and add to cache
@@ -170,10 +191,8 @@ async function synthAudio(client, logger, stats, { account_sid,
debug(`tts rtt time for ${text.length} chars on ${vendorLabel}: ${rtt}`); debug(`tts rtt time for ${text.length} chars on ${vendorLabel}: ${rtt}`);
logger.info(`tts rtt time for ${text.length} chars on ${vendorLabel}: ${rtt}`); logger.info(`tts rtt time for ${text.length} chars on ${vendorLabel}: ${rtt}`);
client.setexAsync(key, EXPIRES, audioBuffer.toString('base64')) client.setex(key, EXPIRES, audioBuffer.toString('base64'))
.catch((err) => logger.error(err, `error calling setex on key ${key}`)); .catch((err) => logger.error(err, `error calling setex on key ${key}`));
if (['microsoft'].includes(vendor)) return {filePath, servedFromCache, rtt};
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@@ -288,6 +307,7 @@ const synthMicrosoft = async(logger, {
}) => { }) => {
try { try {
const {api_key: apiKey, region, use_custom_tts, custom_tts_endpoint} = credentials; const {api_key: apiKey, region, use_custom_tts, custom_tts_endpoint} = credentials;
const trimSilence = filePath.endsWith('.r8');
let content = text; let content = text;
const speechConfig = SpeechConfig.fromSubscription(apiKey, region); const speechConfig = SpeechConfig.fromSubscription(apiKey, region);
speechConfig.speechSynthesisLanguage = language; speechConfig.speechSynthesisLanguage = language;
@@ -301,9 +321,10 @@ const synthMicrosoft = async(logger, {
*/ */
if (!content.startsWith('<speak')) content = `<speak>${text}</speak>`; if (!content.startsWith('<speak')) content = `<speak>${text}</speak>`;
} }
speechConfig.speechSynthesisOutputFormat = SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3; speechConfig.speechSynthesisOutputFormat = trimSilence ?
const config = AudioConfig.fromAudioFileOutput(filePath); SpeechSynthesisOutputFormat.Raw8Khz16BitMonoPcm :
const synthesizer = new SpeechSynthesizer(speechConfig, config); SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3;
const synthesizer = new SpeechSynthesizer(speechConfig);
if (content.startsWith('<speak>')) { if (content.startsWith('<speak>')) {
/* microsoft enforces some properties and uses voice xml element so if the user did not supply do it for them */ /* microsoft enforces some properties and uses voice xml element so if the user did not supply do it for them */
@@ -328,12 +349,11 @@ const synthMicrosoft = async(logger, {
reject(cancellation.errorDetails); reject(cancellation.errorDetails);
break; break;
case ResultReason.SynthesizingAudioCompleted: case ResultReason.SynthesizingAudioCompleted:
stats.increment('tts.count', ['vendor:microsoft', 'accepted:yes']); let buffer = Buffer.from(result.audioData);
if (trimSilence) buffer = trimTrailingSilence(buffer);
resolve(buffer);
synthesizer.close(); synthesizer.close();
fs.readFile(filePath, (err, data) => { stats.increment('tts.count', ['vendor:microsoft', 'accepted:yes']);
if (err) return reject(err);
resolve(data);
});
break; break;
default: default:
logger.info({result}, 'synthAudio: (Microsoft) unexpected result'); logger.info({result}, 'synthAudio: (Microsoft) unexpected result');
@@ -433,20 +453,25 @@ const synthNuance = async(client, logger, {credentials, stats, voice, model, tex
}; };
const synthNvidia = async(client, logger, {credentials, stats, language, voice, model, text}) => { const synthNvidia = async(client, logger, {credentials, stats, language, voice, model, text}) => {
const {riva_uri} = credentials; const {riva_server_uri} = credentials;
const rivaClient = await createRivaClient(riva_uri); let rivaClient, request;
try {
const request = new SynthesizeSpeechRequest(); rivaClient = await createRivaClient(riva_server_uri);
request.setVoiceName(voice); request = new SynthesizeSpeechRequest();
request.setLanguageCode(language); request.setVoiceName(voice);
request.setSampleRateHz(8000); request.setLanguageCode(language);
request.setEncoding(AudioEncoding.LINEAR_PCM); request.setSampleRateHz(8000);
request.setText(text); request.setEncoding(AudioEncoding.LINEAR_PCM);
request.setText(text);
} catch (err) {
logger.info({err}, 'error creating riva client');
return Promise.reject(err);
}
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
rivaClient.synthesize(request, (err, response) => { rivaClient.synthesize(request, (err, response) => {
if (err) { if (err) {
console.error(err); logger.info({err, voice, language}, 'error synthesizing speech using Nvidia');
return reject(err); return reject(err);
} }
resolve(Buffer.from(response.getAudio())); resolve(Buffer.from(response.getAudio()));
+1086 -941
View File
File diff suppressed because it is too large Load Diff
+4 -5
View File
@@ -1,6 +1,6 @@
{ {
"name": "@jambonz/speech-utils", "name": "@jambonz/speech-utils",
"version": "0.0.9", "version": "0.0.16",
"description": "TTS-related speech utilities for jambonz", "description": "TTS-related speech utilities for jambonz",
"main": "index.js", "main": "index.js",
"author": "Dave Horton", "author": "Dave Horton",
@@ -9,7 +9,7 @@
"test": "test" "test": "test"
}, },
"scripts": { "scripts": {
"test": "NODE_ENV=test JAMBONES_REDIS_USERNAME=daveh JAMBONES_REDIS_PASSWORD=foobarbazzle node test/ ", "test": "NODE_ENV=test node test/ ",
"coverage": "nyc --reporter html --report-dir ./coverage npm run test", "coverage": "nyc --reporter html --report-dir ./coverage npm run test",
"jslint": "eslint index.js lib", "jslint": "eslint index.js lib",
"build": "./build_stubs.sh" "build": "./build_stubs.sh"
@@ -24,17 +24,16 @@
}, },
"homepage": "https://github.com/jambonz/speech-utils#readme", "homepage": "https://github.com/jambonz/speech-utils#readme",
"dependencies": { "dependencies": {
"@aws-sdk/client-polly": "^3.303.0", "@aws-sdk/client-polly": "^3.347.1",
"@google-cloud/text-to-speech": "^4.2.1", "@google-cloud/text-to-speech": "^4.2.1",
"@grpc/grpc-js": "^1.8.13", "@grpc/grpc-js": "^1.8.13",
"@jambonz/promisify-redis": "^0.0.6",
"bent": "^7.3.12", "bent": "^7.3.12",
"debug": "^4.3.4", "debug": "^4.3.4",
"form-urlencoded": "^6.1.0", "form-urlencoded": "^6.1.0",
"google-protobuf": "^3.21.2", "google-protobuf": "^3.21.2",
"ibm-watson": "^8.0.0", "ibm-watson": "^8.0.0",
"microsoft-cognitiveservices-speech-sdk": "^1.26.0", "microsoft-cognitiveservices-speech-sdk": "^1.26.0",
"redis": "^3.1.2", "ioredis": "^5.3.2",
"undici": "^5.21.0" "undici": "^5.21.0"
}, },
"devDependencies": { "devDependencies": {
+2 -2
View File
@@ -31,7 +31,7 @@ test('IBM - create access key', async(t) => {
//console.log({obj}, 'received access token from IBM - second request'); //console.log({obj}, 'received access token from IBM - second request');
t.ok(obj.access_token && obj.servedFromCache, 'successfully received access token from cache'); t.ok(obj.access_token && obj.servedFromCache, 'successfully received access token from cache');
await client.flushallAsync(); await client.flushall();
t.end(); t.end();
} }
catch (err) { catch (err) {
@@ -65,7 +65,7 @@ test('IBM - retrieve tts voices test', async(t) => {
t.ok(voices.length > 0 && voices[0].language, t.ok(voices.length > 0 && voices[0].language,
`GetVoices: successfully retrieved ${voices.length} voices from IBM`); `GetVoices: successfully retrieved ${voices.length} voices from IBM`);
await client.flushallAsync(); await client.flushall();
t.end(); t.end();
+6 -6
View File
@@ -31,7 +31,7 @@ test('IBM - create access key', async(t) => {
//console.log({obj}, 'received access token from IBM - second request'); //console.log({obj}, 'received access token from IBM - second request');
t.ok(obj.access_token && obj.servedFromCache, 'successfully received access token from cache'); t.ok(obj.access_token && obj.servedFromCache, 'successfully received access token from cache');
await client.flushallAsync(); await client.flushall();
t.end(); t.end();
} }
catch (err) { catch (err) {
@@ -65,7 +65,7 @@ test('IBM - retrieve tts voices test', async(t) => {
t.ok(voices.length > 0 && voices[0].language, t.ok(voices.length > 0 && voices[0].language,
`GetVoices: successfully retrieved ${voices.length} voices from IBM`); `GetVoices: successfully retrieved ${voices.length} voices from IBM`);
await client.flushallAsync(); await client.flushall();
t.end(); t.end();
@@ -99,7 +99,7 @@ test('Nuance hosted tests', async(t) => {
t.ok(voices.length > 0 && voices[0].language, t.ok(voices.length > 0 && voices[0].language,
`GetVoices: successfully retrieved ${voices.length} voices from Nuance`); `GetVoices: successfully retrieved ${voices.length} voices from Nuance`);
await client.flushallAsync(); await client.flushall();
t.end(); t.end();
@@ -132,7 +132,7 @@ test('Nuance on-prem tests', async(t) => {
t.ok(voices.length > 0 && voices[0].language, t.ok(voices.length > 0 && voices[0].language,
`GetVoices: successfully retrieved ${voices.length} voices from Nuance`); `GetVoices: successfully retrieved ${voices.length} voices from Nuance`);
await client.flushallAsync(); await client.flushall();
t.end(); t.end();
@@ -162,7 +162,7 @@ test('Google tests', async(t) => {
let result = await getTtsVoices(opts); let result = await getTtsVoices(opts);
t.ok(result[0].voices.length > 0, `GetVoices: successfully retrieved ${result[0].voices.length} voices from Google`); t.ok(result[0].voices.length > 0, `GetVoices: successfully retrieved ${result[0].voices.length} voices from Google`);
await client.flushallAsync(); await client.flushall();
t.end(); t.end();
} }
@@ -193,7 +193,7 @@ test('AWS tests', async(t) => {
let result = await getTtsVoices(opts); let result = await getTtsVoices(opts);
t.ok(result?.Voices?.length > 0, `GetVoices: successfully retrieved ${result.Voices.length} voices from AWS`); t.ok(result?.Voices?.length > 0, `GetVoices: successfully retrieved ${result.Voices.length} voices from AWS`);
await client.flushallAsync(); await client.flushall();
t.end(); t.end();
} }
+2 -2
View File
@@ -34,7 +34,7 @@ test('Nuance hosted tests', async(t) => {
t.ok(voices.length > 0 && voices[0].language, t.ok(voices.length > 0 && voices[0].language,
`GetVoices: successfully retrieved ${voices.length} voices from Nuance`); `GetVoices: successfully retrieved ${voices.length} voices from Nuance`);
await client.flushallAsync(); await client.flushall();
t.end(); t.end();
@@ -67,7 +67,7 @@ test('Nuance on-prem tests', async(t) => {
t.ok(voices.length > 0 && voices[0].language, t.ok(voices.length > 0 && voices[0].language,
`GetVoices: successfully retrieved ${voices.length} voices from Nuance`); `GetVoices: successfully retrieved ${voices.length} voices from Nuance`);
await client.flushallAsync(); await client.flushall();
t.end(); t.end();
+15 -12
View File
@@ -300,7 +300,7 @@ test('Nvidia speech synth tests', async(t) => {
let opts = await synthAudio(stats, { let opts = await synthAudio(stats, {
vendor: 'nvidia', vendor: 'nvidia',
credentials: { credentials: {
riva_uri: process.env.RIVA_URI, riva_server_uri: process.env.RIVA_URI,
}, },
language: 'en-US', language: 'en-US',
voice: 'English-US.Female-1', voice: 'English-US.Female-1',
@@ -311,7 +311,7 @@ test('Nvidia speech synth tests', async(t) => {
opts = await synthAudio(stats, { opts = await synthAudio(stats, {
vendor: 'nvidia', vendor: 'nvidia',
credentials: { credentials: {
riva_uri: process.env.RIVA_URI, riva_server_uri: process.env.RIVA_URI,
}, },
language: 'en-US', language: 'en-US',
voice: 'English-US.Female-1', voice: 'English-US.Female-1',
@@ -413,18 +413,21 @@ test('Custom Vendor speech synth tests', async(t) => {
test('TTS Cache tests', async(t) => { test('TTS Cache tests', async(t) => {
const fn = require('..'); const fn = require('..');
const {purgeTtsCache, client} = fn(opts, logger); const {purgeTtsCache, getTtsSize, client} = fn(opts, logger);
try { try {
// save some random tts keys to cache // save some random tts keys to cache
const minRecords = 8; const minRecords = 8;
for (const i in Array(minRecords).fill(0)) { for (const i in Array(minRecords).fill(0)) {
await client.setAsync(makeSynthKey({vendor: i, language: i, voice: i, engine: i, text: i}), i); await client.set(makeSynthKey({vendor: i, language: i, voice: i, engine: i, text: i}), i);
} }
const count = await getTtsSize();
t.ok(count >= minRecords, 'getTtsSize worked.');
const {purgedCount} = await purgeTtsCache(); const {purgedCount} = await purgeTtsCache();
t.ok(purgedCount >= minRecords, `successfully purged at least ${minRecords} tts records from cache`); t.ok(purgedCount >= minRecords, `successfully purged at least ${minRecords} tts records from cache`);
const cached = (await client.keysAsync('tts:*')).length; const cached = (await client.keys('tts:*')).length;
t.equal(cached, 0, `successfully purged all tts records from cache`); t.equal(cached, 0, `successfully purged all tts records from cache`);
} catch (err) { } catch (err) {
@@ -435,11 +438,11 @@ test('TTS Cache tests', async(t) => {
try { try {
// save some random tts keys to cache // save some random tts keys to cache
for (const i in Array(10).fill(0)) { for (const i in Array(10).fill(0)) {
await client.setAsync(makeSynthKey({vendor: i, language: i, voice: i, engine: i, text: i}), i); await client.set(makeSynthKey({vendor: i, language: i, voice: i, engine: i, text: i}), i);
} }
// save a specific key to tts cache // save a specific key to tts cache
const opts = {vendor: 'aws', language: 'en-US', voice: 'MALE', engine: 'Engine', text: 'Hello World!'}; const opts = {vendor: 'aws', language: 'en-US', voice: 'MALE', engine: 'Engine', text: 'Hello World!'};
await client.setAsync(makeSynthKey(opts), opts.text); await client.set(makeSynthKey(opts), opts.text);
const {purgedCount} = await purgeTtsCache({all: false, ...opts}); const {purgedCount} = await purgeTtsCache({all: false, ...opts});
t.ok(purgedCount === 1, `successfully purged one specific tts record from cache`); t.ok(purgedCount === 1, `successfully purged one specific tts record from cache`);
@@ -455,7 +458,7 @@ test('TTS Cache tests', async(t) => {
t.ok(error, `error returned when specified key was not found`); t.ok(error, `error returned when specified key was not found`);
// make sure other tts keys are still there // make sure other tts keys are still there
const cached = (await client.keysAsync('tts:*')).length; const cached = (await client.keys('tts:*')).length;
t.ok(cached >= 1, `successfully kept all non-specified tts records in cache`); t.ok(cached >= 1, `successfully kept all non-specified tts records in cache`);
} catch (err) { } catch (err) {
@@ -471,21 +474,21 @@ test('TTS Cache tests', async(t) => {
const account_sid = "12412512_cabc_5aff" const account_sid = "12412512_cabc_5aff"
const account_sid2 = "22412512_cabc_5aff" const account_sid2 = "22412512_cabc_5aff"
for (const i in Array(minRecords).fill(0)) { for (const i in Array(minRecords).fill(0)) {
await client.setAsync(makeSynthKey({account_sid, vendor: i, language: i, voice: i, engine: i, text: i}), i); await client.set(makeSynthKey({account_sid, vendor: i, language: i, voice: i, engine: i, text: i}), i);
} }
for (const i in Array(minRecords).fill(0)) { for (const i in Array(minRecords).fill(0)) {
await client.setAsync(makeSynthKey({account_sid: account_sid2, vendor: i, language: i, voice: i, engine: i, text: i}), i); await client.set(makeSynthKey({account_sid: account_sid2, vendor: i, language: i, voice: i, engine: i, text: i}), i);
} }
const {purgedCount} = await purgeTtsCache({account_sid}); const {purgedCount} = await purgeTtsCache({account_sid});
t.equal(purgedCount, minRecords, `successfully purged at least ${minRecords} tts records from cache for account_sid:${account_sid}`); t.equal(purgedCount, minRecords, `successfully purged at least ${minRecords} tts records from cache for account_sid:${account_sid}`);
let cached = (await client.keysAsync('tts:*')).length; let cached = (await client.keys('tts:*')).length;
t.equal(cached, minRecords, `successfully purged all tts records from cache for account_sid:${account_sid}`); t.equal(cached, minRecords, `successfully purged all tts records from cache for account_sid:${account_sid}`);
const {purgedCount: purgedCount2} = await purgeTtsCache({account_sid: account_sid2}); const {purgedCount: purgedCount2} = await purgeTtsCache({account_sid: account_sid2});
t.equal(purgedCount2, minRecords, `successfully purged at least ${minRecords} tts records from cache for account_sid:${account_sid2}`); t.equal(purgedCount2, minRecords, `successfully purged at least ${minRecords} tts records from cache for account_sid:${account_sid2}`);
cached = (await client.keysAsync('tts:*')).length; cached = (await client.keys('tts:*')).length;
t.equal(cached, 0, `successfully purged all tts records from cache`); t.equal(cached, 0, `successfully purged all tts records from cache`);
} catch (err) { } catch (err) {