mirror of
https://github.com/jambonz/speech-utils.git
synced 2026-10-03 23:33:59 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04bb85ef81 | ||
|
|
c123f19898 | ||
|
|
305695d068 | ||
|
|
1477752d40 | ||
|
|
fbedfe947f | ||
|
|
ab88facd52 | ||
|
|
a2be64da89 | ||
|
|
c5e0f256e6 | ||
|
|
d0378751ba | ||
|
|
a7e391fcb2 | ||
|
|
10095de25d | ||
|
|
89007ba7cc | ||
|
|
29edccd5bf | ||
|
|
ca9538030f | ||
|
|
417d58080e | ||
|
|
62fec6f5e4 | ||
|
|
490d23a703 | ||
|
|
b91e6cc145 | ||
|
|
0e33358254 | ||
|
|
6b2b35acfb | ||
|
|
ded60cb7aa | ||
|
|
460ca70ea7 | ||
|
|
0fbbbb8053 | ||
|
|
0ea7082da2 | ||
|
|
5f7e7458bb | ||
|
|
f6714fb9e1 | ||
|
|
c04ef29f7c | ||
|
|
8154944252 | ||
|
|
16fe8dce01 | ||
|
|
11a955500d | ||
|
|
c122129b55 | ||
|
|
41b26b966b | ||
|
|
aa09c15b20 | ||
|
|
32d5f12638 | ||
|
|
4e336822a0 | ||
|
|
b898d794b0 | ||
|
|
fb754ca101 | ||
|
|
8d8195be9a | ||
|
|
eb4e1a773f | ||
|
|
6fecb8755d | ||
|
|
fdb56cbc77 | ||
|
|
5328a60de8 | ||
|
|
ea1ab301d5 | ||
|
|
0a4994c5a3 | ||
|
|
cb71460189 | ||
|
|
f08efa49b1 | ||
|
|
80eda37ef6 | ||
|
|
7768e58b19 | ||
|
|
6efc99ad83 | ||
|
|
127d01a8c1 | ||
|
|
1900b26d8b | ||
|
|
aa25a6f6d9 | ||
|
|
8dfe17b600 | ||
|
|
5463e9f56e | ||
|
|
2eb36af650 | ||
|
|
b186cbc4f2 | ||
|
|
b1b9c182a9 | ||
|
|
15c77626fc | ||
|
|
76126ec0b3 | ||
|
|
55431ee511 | ||
|
|
1c76f74b4a | ||
|
|
62ad8abb8e | ||
|
|
92734aaedb | ||
|
|
fe4ccfe7d7 | ||
|
|
ab05976032 | ||
|
|
babd8abc51 | ||
|
|
91f85e16b2 | ||
|
|
8a0c5e3dbd | ||
|
|
d40e012138 | ||
|
|
49b23f5240 | ||
|
|
043642ea5f | ||
|
|
91ea9820f9 | ||
|
|
fad0f57b13 | ||
|
|
2608e149a8 | ||
|
|
d21289acd6 | ||
|
|
a7b19e1d8a | ||
|
|
09c7aa9a5f | ||
|
|
f311c21327 | ||
|
|
535d0191da | ||
|
|
c00d4f9be4 | ||
|
|
db135ee5ad | ||
|
|
5eac4c2ad8 | ||
|
|
e23a1a6d09 | ||
|
|
3a78300a08 | ||
|
|
1d7390e7ae | ||
|
|
3c0940f657 | ||
|
|
6fb6195b16 | ||
|
|
2ff8587601 | ||
|
|
925bd26a70 | ||
|
|
ddea485f5f | ||
|
|
49de25feb8 | ||
|
|
08b55b8d79 | ||
|
|
59bca302b9 | ||
|
|
0d98f73c43 | ||
|
|
36670e0080 | ||
|
|
61672f9868 | ||
|
|
ddeca8eb99 | ||
|
|
6e8271b2f6 | ||
|
|
74a4938eb6 | ||
|
|
cb50f603cd | ||
|
|
9a524f00bc | ||
|
|
545df0b770 | ||
|
|
9409405769 |
@@ -11,13 +11,8 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: lts/*
|
node-version: '20'
|
||||||
- run: npm install
|
- run: npm install
|
||||||
- name: Install Docker Compose
|
|
||||||
run: |
|
|
||||||
sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
|
|
||||||
sudo chmod +x /usr/local/bin/docker-compose
|
|
||||||
docker-compose --version
|
|
||||||
- run: npm run jslint
|
- run: npm run jslint
|
||||||
- run: sudo apt update && sudo apt install -y squid
|
- run: sudo apt update && sudo apt install -y squid
|
||||||
- run: sudo cp test/squid.conf /etc/squid/squid.conf
|
- run: sudo cp test/squid.conf /etc/squid/squid.conf
|
||||||
@@ -28,9 +23,7 @@ jobs:
|
|||||||
AWS_REGION: ${{ secrets.AWS_REGION }}
|
AWS_REGION: ${{ secrets.AWS_REGION }}
|
||||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||||
GCP_JSON_KEY: ${{ secrets.GCP_JSON_KEY }}
|
GCP_JSON_KEY: ${{ secrets.GCP_JSON_KEY }}
|
||||||
IBM_API_KEY: ${{ secrets.IBM_API_KEY }}
|
|
||||||
IBM_TTS_API_KEY: ${{ secrets.IBM_TTS_API_KEY }}
|
|
||||||
IBM_TTS_REGION: ${{ secrets.IBM_TTS_REGION }}
|
|
||||||
MICROSOFT_API_KEY: ${{ secrets.MICROSOFT_API_KEY }}
|
MICROSOFT_API_KEY: ${{ secrets.MICROSOFT_API_KEY }}
|
||||||
MICROSOFT_REGION: ${{ secrets.MICROSOFT_REGION }}
|
MICROSOFT_REGION: ${{ secrets.MICROSOFT_REGION }}
|
||||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ module.exports = (opts, logger) => {
|
|||||||
synthAudio: require('./lib/synth-audio').bind(null, client, createHash, retrieveHash, logger),
|
synthAudio: require('./lib/synth-audio').bind(null, client, createHash, retrieveHash, logger),
|
||||||
getVerbioAccessToken: require('./lib/get-verbio-token').bind(null, client, logger),
|
getVerbioAccessToken: require('./lib/get-verbio-token').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),
|
||||||
getIbmAccessToken: require('./lib/get-ibm-access-token').bind(null, client, logger),
|
|
||||||
getAwsAuthToken: require('./lib/get-aws-sts-token').bind(null, logger, createHash, retrieveHash),
|
getAwsAuthToken: require('./lib/get-aws-sts-token').bind(null, logger, createHash, retrieveHash),
|
||||||
getTtsVoices: require('./lib/get-tts-voices').bind(null, client, createHash, retrieveHash, logger),
|
getTtsVoices: require('./lib/get-tts-voices').bind(null, client, createHash, retrieveHash, logger),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ function getExtensionAndSampleRate(path) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function addFileToCache(client, logger, path,
|
async function addFileToCache(client, logger, path,
|
||||||
{account_sid, vendor, language, voice, deploymentId, engine, model, text}) {
|
{account_sid, vendor, language, voice, deploymentId, engine, model, text, instructions}) {
|
||||||
let key;
|
let key;
|
||||||
logger = logger || noopLogger;
|
logger = logger || noopLogger;
|
||||||
|
|
||||||
@@ -38,6 +38,7 @@ async function addFileToCache(client, logger, path,
|
|||||||
engine,
|
engine,
|
||||||
model,
|
model,
|
||||||
text,
|
text,
|
||||||
|
instructions
|
||||||
});
|
});
|
||||||
const [extension, sampleRate] = getExtensionAndSampleRate(path);
|
const [extension, sampleRate] = getExtensionAndSampleRate(path);
|
||||||
const audioBuffer = await fs.readFile(path);
|
const audioBuffer = await fs.readFile(path);
|
||||||
|
|||||||
+4
-2
@@ -2,13 +2,14 @@ const JAMBONES_TTS_TRIM_SILENCE = process.env.JAMBONES_TTS_TRIM_SILENCE;
|
|||||||
const JAMBONES_DISABLE_TTS_STREAMING = process.env.JAMBONES_DISABLE_TTS_STREAMING;
|
const JAMBONES_DISABLE_TTS_STREAMING = process.env.JAMBONES_DISABLE_TTS_STREAMING;
|
||||||
const JAMBONES_DISABLE_AZURE_TTS_STREAMING = process.env.JAMBONES_DISABLE_AZURE_TTS_STREAMING;
|
const JAMBONES_DISABLE_AZURE_TTS_STREAMING = process.env.JAMBONES_DISABLE_AZURE_TTS_STREAMING;
|
||||||
const JAMBONES_EAGERLY_PRE_CACHE_AUDIO = process.env.JAMBONES_EAGERLY_PRE_CACHE_AUDIO;
|
const JAMBONES_EAGERLY_PRE_CACHE_AUDIO = process.env.JAMBONES_EAGERLY_PRE_CACHE_AUDIO;
|
||||||
|
const JAMBONES_AZURE_ENABLE_SSML = process.env.JAMBONES_AZURE_ENABLE_SSML;
|
||||||
|
|
||||||
const JAMBONES_HTTP_PROXY_IP = process.env.JAMBONES_HTTP_PROXY_IP;
|
const JAMBONES_HTTP_PROXY_IP = process.env.JAMBONES_HTTP_PROXY_IP;
|
||||||
const JAMBONES_HTTP_PROXY_PORT = process.env.JAMBONES_HTTP_PROXY_PORT;
|
const JAMBONES_HTTP_PROXY_PORT = process.env.JAMBONES_HTTP_PROXY_PORT;
|
||||||
const JAMBONES_TTS_CACHE_DURATION_MINS =
|
const JAMBONES_TTS_CACHE_DURATION_MINS =
|
||||||
(parseInt(process.env.JAMBONES_TTS_CACHE_DURATION_MINS) || 4 * 60) * 60; // cache tts for 4 hours
|
(parseInt(process.env.JAMBONES_TTS_CACHE_DURATION_MINS) || 4 * 60) * 60; // cache tts for 4 hours
|
||||||
|
|
||||||
const TMP_FOLDER = '/tmp';
|
const TMP_FOLDER = process.env.JAMBONES_TMP_FOLDER || '/tmp';
|
||||||
|
|
||||||
const HTTP_TIMEOUT = 5000;
|
const HTTP_TIMEOUT = 5000;
|
||||||
|
|
||||||
@@ -21,5 +22,6 @@ module.exports = {
|
|||||||
JAMBONES_TTS_CACHE_DURATION_MINS,
|
JAMBONES_TTS_CACHE_DURATION_MINS,
|
||||||
JAMBONES_EAGERLY_PRE_CACHE_AUDIO,
|
JAMBONES_EAGERLY_PRE_CACHE_AUDIO,
|
||||||
TMP_FOLDER,
|
TMP_FOLDER,
|
||||||
HTTP_TIMEOUT
|
HTTP_TIMEOUT,
|
||||||
|
JAMBONES_AZURE_ENABLE_SSML
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
const formurlencoded = require('form-urlencoded');
|
|
||||||
const {Pool} = require('undici');
|
|
||||||
const pool = new Pool('https://iam.cloud.ibm.com');
|
|
||||||
const {makeIbmKey, noopLogger} = require('./utils');
|
|
||||||
const { HTTP_TIMEOUT } = require('./config');
|
|
||||||
const debug = require('debug')('jambonz:realtimedb-helpers');
|
|
||||||
|
|
||||||
async function getIbmAccessToken(client, logger, apiKey) {
|
|
||||||
logger = logger || noopLogger;
|
|
||||||
try {
|
|
||||||
const key = makeIbmKey(apiKey);
|
|
||||||
const access_token = await client.get(key);
|
|
||||||
if (access_token) return {access_token, servedFromCache: true};
|
|
||||||
|
|
||||||
/* access token not found in cache, so fetch it from Ibm */
|
|
||||||
const payload = {
|
|
||||||
grant_type: 'urn:ibm:params:oauth:grant-type:apikey',
|
|
||||||
apikey: apiKey
|
|
||||||
};
|
|
||||||
const {statusCode, headers, body} = await pool.request({
|
|
||||||
path: '/identity/token',
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/x-www-form-urlencoded'
|
|
||||||
},
|
|
||||||
body: formurlencoded(payload),
|
|
||||||
timeout: HTTP_TIMEOUT,
|
|
||||||
followRedirects: false
|
|
||||||
});
|
|
||||||
|
|
||||||
if (200 !== statusCode) {
|
|
||||||
const json = await body.json();
|
|
||||||
logger.debug({statusCode, headers, body: json}, 'error fetching access token from Ibm');
|
|
||||||
const err = new Error();
|
|
||||||
err.statusCode = statusCode;
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
const json = await body.json();
|
|
||||||
await client.set(key, json.access_token, 'EX', json.expires_in - 30);
|
|
||||||
return {...json, servedFromCache: false};
|
|
||||||
} catch (err) {
|
|
||||||
debug(err, 'getIbmAccessToken: Error retrieving Ibm access token');
|
|
||||||
logger.error(err, 'getIbmAccessToken: Error retrieving Ibm access token for client_id ${clientId}');
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = getIbmAccessToken;
|
|
||||||
+1
-20
@@ -3,8 +3,6 @@ const {noopLogger, createNuanceClient, createKryptonClient} = require('./utils')
|
|||||||
const getNuanceAccessToken = require('./get-nuance-access-token');
|
const getNuanceAccessToken = require('./get-nuance-access-token');
|
||||||
const getVerbioAccessToken = require('./get-verbio-token');
|
const getVerbioAccessToken = require('./get-verbio-token');
|
||||||
const {GetVoicesRequest, Voice} = require('../stubs/nuance/synthesizer_pb');
|
const {GetVoicesRequest, Voice} = require('../stubs/nuance/synthesizer_pb');
|
||||||
const TextToSpeechV1 = require('ibm-watson/text-to-speech/v1');
|
|
||||||
const { IamAuthenticator } = require('ibm-watson/auth');
|
|
||||||
const ttsGoogle = require('@google-cloud/text-to-speech');
|
const ttsGoogle = require('@google-cloud/text-to-speech');
|
||||||
const { PollyClient, DescribeVoicesCommand } = require('@aws-sdk/client-polly');
|
const { PollyClient, DescribeVoicesCommand } = require('@aws-sdk/client-polly');
|
||||||
const getAwsAuthToken = require('./get-aws-sts-token');
|
const getAwsAuthToken = require('./get-aws-sts-token');
|
||||||
@@ -12,21 +10,6 @@ const {Pool} = require('undici');
|
|||||||
const { HTTP_TIMEOUT } = require('./config');
|
const { HTTP_TIMEOUT } = require('./config');
|
||||||
const verbioVoicePool = new Pool('https://us.rest.speechcenter.verbio.com');
|
const verbioVoicePool = new Pool('https://us.rest.speechcenter.verbio.com');
|
||||||
|
|
||||||
const getIbmVoices = async(client, logger, credentials) => {
|
|
||||||
const {tts_region, tts_api_key} = credentials;
|
|
||||||
console.log(`region: ${tts_region}, api_key: ${tts_api_key}`);
|
|
||||||
|
|
||||||
const textToSpeech = new TextToSpeechV1({
|
|
||||||
authenticator: new IamAuthenticator({
|
|
||||||
apikey: tts_api_key,
|
|
||||||
}),
|
|
||||||
serviceUrl: `https://api.${tts_region}.text-to-speech.watson.cloud.ibm.com`
|
|
||||||
});
|
|
||||||
|
|
||||||
const voices = await textToSpeech.listVoices();
|
|
||||||
return voices;
|
|
||||||
};
|
|
||||||
|
|
||||||
const getNuanceVoices = async(client, logger, credentials) => {
|
const getNuanceVoices = async(client, logger, credentials) => {
|
||||||
const {client_id: clientId, secret: secret, nuance_tts_uri} = credentials;
|
const {client_id: clientId, secret: secret, nuance_tts_uri} = credentials;
|
||||||
|
|
||||||
@@ -165,14 +148,12 @@ const getVerbioVoices = async(client, logger, credentials) => {
|
|||||||
async function getTtsVoices(client, createHash, retrieveHash, logger, {vendor, credentials}) {
|
async function getTtsVoices(client, createHash, retrieveHash, logger, {vendor, credentials}) {
|
||||||
logger = logger || noopLogger;
|
logger = logger || noopLogger;
|
||||||
|
|
||||||
assert.ok(['nuance', 'ibm', 'google', 'aws', 'polly', 'verbio'].includes(vendor),
|
assert.ok(['nuance', 'google', 'aws', 'polly', 'verbio'].includes(vendor),
|
||||||
`getTtsVoices not supported for vendor ${vendor}`);
|
`getTtsVoices not supported for vendor ${vendor}`);
|
||||||
|
|
||||||
switch (vendor) {
|
switch (vendor) {
|
||||||
case 'nuance':
|
case 'nuance':
|
||||||
return getNuanceVoices(client, logger, credentials);
|
return getNuanceVoices(client, logger, credentials);
|
||||||
case 'ibm':
|
|
||||||
return getIbmVoices(client, logger, credentials);
|
|
||||||
case 'google':
|
case 'google':
|
||||||
return getGoogleVoices(client, logger, credentials);
|
return getGoogleVoices(client, logger, credentials);
|
||||||
case 'aws':
|
case 'aws':
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ const debug = require('debug')('jambonz:realtimedb-helpers');
|
|||||||
* @returns {object} result - {error, purgedCount}
|
* @returns {object} result - {error, purgedCount}
|
||||||
*/
|
*/
|
||||||
async function purgeTtsCache(client, logger, {all, account_sid, vendor,
|
async function purgeTtsCache(client, logger, {all, account_sid, vendor,
|
||||||
language, voice, deploymentId, engine, model, text} = {all: true}) {
|
language, voice, deploymentId, engine, model, text, instructions} = {all: true}) {
|
||||||
logger = logger || noopLogger;
|
logger = logger || noopLogger;
|
||||||
|
|
||||||
let purgedCount = 0, error;
|
let purgedCount = 0, error;
|
||||||
@@ -35,6 +35,7 @@ async function purgeTtsCache(client, logger, {all, account_sid, vendor,
|
|||||||
engine,
|
engine,
|
||||||
model,
|
model,
|
||||||
text,
|
text,
|
||||||
|
instructions
|
||||||
});
|
});
|
||||||
purgedCount = await client.del(key);
|
purgedCount = await client.del(key);
|
||||||
if (purgedCount === 0) error = 'Specified item not found';
|
if (purgedCount === 0) error = 'Specified item not found';
|
||||||
|
|||||||
+424
-172
@@ -6,8 +6,7 @@ const { PollyClient, SynthesizeSpeechCommand } = require('@aws-sdk/client-polly'
|
|||||||
const { CartesiaClient } = require('@cartesia/cartesia-js');
|
const { CartesiaClient } = require('@cartesia/cartesia-js');
|
||||||
|
|
||||||
const sdk = require('microsoft-cognitiveservices-speech-sdk');
|
const sdk = require('microsoft-cognitiveservices-speech-sdk');
|
||||||
const TextToSpeechV1 = require('ibm-watson/text-to-speech/v1');
|
|
||||||
const { IamAuthenticator } = require('ibm-watson/auth');
|
|
||||||
const {
|
const {
|
||||||
ResultReason,
|
ResultReason,
|
||||||
SpeechConfig,
|
SpeechConfig,
|
||||||
@@ -47,12 +46,12 @@ const {
|
|||||||
JAMBONES_HTTP_PROXY_PORT,
|
JAMBONES_HTTP_PROXY_PORT,
|
||||||
JAMBONES_TTS_CACHE_DURATION_MINS,
|
JAMBONES_TTS_CACHE_DURATION_MINS,
|
||||||
JAMBONES_TTS_TRIM_SILENCE,
|
JAMBONES_TTS_TRIM_SILENCE,
|
||||||
|
JAMBONES_AZURE_ENABLE_SSML
|
||||||
} = require('./config');
|
} = require('./config');
|
||||||
const EXPIRES = JAMBONES_TTS_CACHE_DURATION_MINS;
|
const EXPIRES = JAMBONES_TTS_CACHE_DURATION_MINS;
|
||||||
const OpenAI = require('openai');
|
const OpenAI = require('openai');
|
||||||
const getAwsAuthToken = require('./get-aws-sts-token');
|
const getAwsAuthToken = require('./get-aws-sts-token');
|
||||||
|
|
||||||
|
|
||||||
const trimTrailingSilence = (buffer) => {
|
const trimTrailingSilence = (buffer) => {
|
||||||
assert.ok(buffer instanceof Buffer, 'trimTrailingSilence - argument is not a Buffer');
|
assert.ok(buffer instanceof Buffer, 'trimTrailingSilence - argument is not a Buffer');
|
||||||
|
|
||||||
@@ -89,15 +88,15 @@ const trimTrailingSilence = (buffer) => {
|
|||||||
*/
|
*/
|
||||||
async function synthAudio(client, createHash, retrieveHash, logger, stats, { account_sid,
|
async function synthAudio(client, createHash, retrieveHash, logger, stats, { account_sid,
|
||||||
vendor, language, voice, gender, text, engine, salt, model, credentials, deploymentId,
|
vendor, language, voice, gender, text, engine, salt, model, credentials, deploymentId,
|
||||||
disableTtsCache, renderForCaching = false, disableTtsStreaming, options
|
disableTtsCache, renderForCaching = false, disableTtsStreaming, options, instructions
|
||||||
}) {
|
}) {
|
||||||
let audioData;
|
let audioData;
|
||||||
let servedFromCache = false;
|
let servedFromCache = false;
|
||||||
let rtt;
|
let rtt;
|
||||||
logger = logger || noopLogger;
|
logger = logger || noopLogger;
|
||||||
|
|
||||||
assert.ok(['google', 'aws', 'polly', 'microsoft', 'wellsaid', 'nuance', 'nvidia', 'ibm', 'elevenlabs',
|
assert.ok(['google', 'aws', 'polly', 'microsoft', 'wellsaid', 'nuance', 'nvidia', 'elevenlabs',
|
||||||
'whisper', 'deepgram', 'playht', 'rimelabs', 'verbio', 'cartesia'].includes(vendor) ||
|
'whisper', 'deepgram', 'playht', 'rimelabs', 'verbio', 'cartesia', 'inworld', 'resemble'].includes(vendor) ||
|
||||||
vendor.startsWith('custom'),
|
vendor.startsWith('custom'),
|
||||||
`synthAudio supported vendors are google, aws, microsoft, nuance, nvidia and wellsaid ..etc, not ${vendor}`);
|
`synthAudio supported vendors are google, aws, microsoft, nuance, nvidia and wellsaid ..etc, not ${vendor}`);
|
||||||
if ('google' === vendor) {
|
if ('google' === vendor) {
|
||||||
@@ -122,11 +121,6 @@ async function synthAudio(client, createHash, retrieveHash, logger, stats, { acc
|
|||||||
assert.ok(language, 'synthAudio requires language when nvidia is used');
|
assert.ok(language, 'synthAudio requires language when nvidia is used');
|
||||||
assert.ok(credentials.riva_server_uri, 'synthAudio requires riva_server_uri in credentials when nvidia is used');
|
assert.ok(credentials.riva_server_uri, 'synthAudio requires riva_server_uri in credentials when nvidia is used');
|
||||||
}
|
}
|
||||||
else if ('ibm' === vendor) {
|
|
||||||
assert.ok(voice, 'synthAudio requires voice when ibm is used');
|
|
||||||
assert.ok(credentials.tts_region, 'synthAudio requires tts_region in credentials when ibm watson is used');
|
|
||||||
assert.ok(credentials.tts_api_key, 'synthAudio requires tts_api_key in credentials when nuance is used');
|
|
||||||
}
|
|
||||||
else if ('wellsaid' === vendor) {
|
else if ('wellsaid' === vendor) {
|
||||||
language = 'en-US'; // WellSaid only supports English atm
|
language = 'en-US'; // WellSaid only supports English atm
|
||||||
assert.ok(voice, 'synthAudio requires voice when wellsaid is used');
|
assert.ok(voice, 'synthAudio requires voice when wellsaid is used');
|
||||||
@@ -140,6 +134,10 @@ async function synthAudio(client, createHash, retrieveHash, logger, stats, { acc
|
|||||||
assert.ok(credentials.api_key, 'synthAudio requires api_key when playht is used');
|
assert.ok(credentials.api_key, 'synthAudio requires api_key when playht is used');
|
||||||
assert.ok(credentials.user_id, 'synthAudio requires user_id when playht is used');
|
assert.ok(credentials.user_id, 'synthAudio requires user_id when playht is used');
|
||||||
assert.ok(credentials.voice_engine, 'synthAudio requires voice_engine when playht is used');
|
assert.ok(credentials.voice_engine, 'synthAudio requires voice_engine when playht is used');
|
||||||
|
} else if ('inworld' === vendor) {
|
||||||
|
assert.ok(voice, 'synthAudio requires voice when inworld is used');
|
||||||
|
assert.ok(credentials.api_key, 'synthAudio requires api_key when inworld is used');
|
||||||
|
assert.ok(credentials.model_id, 'synthAudio requires model_id when inworld is used');
|
||||||
} else if ('rimelabs' === vendor) {
|
} else if ('rimelabs' === vendor) {
|
||||||
assert.ok(voice, 'synthAudio requires voice when rimelabs is used');
|
assert.ok(voice, 'synthAudio requires voice when rimelabs is used');
|
||||||
assert.ok(credentials.api_key, 'synthAudio requires api_key when rimelabs is used');
|
assert.ok(credentials.api_key, 'synthAudio requires api_key when rimelabs is used');
|
||||||
@@ -161,6 +159,9 @@ async function synthAudio(client, createHash, retrieveHash, logger, stats, { acc
|
|||||||
} else if ('cartesia' === vendor) {
|
} else if ('cartesia' === vendor) {
|
||||||
assert.ok(credentials.api_key, 'synthAudio requires api_key when cartesia is used');
|
assert.ok(credentials.api_key, 'synthAudio requires api_key when cartesia is used');
|
||||||
assert.ok(credentials.model_id, 'synthAudio requires model_id when cartesia is used');
|
assert.ok(credentials.model_id, 'synthAudio requires model_id when cartesia is used');
|
||||||
|
} else if (vendor === 'resemble') {
|
||||||
|
assert.ok(voice, 'synthAudio requires voice when resemble is used');
|
||||||
|
assert.ok(credentials.api_key, 'synthAudio requires api_key when resemble is used');
|
||||||
}
|
}
|
||||||
|
|
||||||
const key = makeSynthKey({
|
const key = makeSynthKey({
|
||||||
@@ -171,7 +172,8 @@ async function synthAudio(client, createHash, retrieveHash, logger, stats, { acc
|
|||||||
engine,
|
engine,
|
||||||
// model or model_id is used to identify the tts cache.
|
// model or model_id is used to identify the tts cache.
|
||||||
model: model || credentials.model_id,
|
model: model || credentials.model_id,
|
||||||
text
|
text,
|
||||||
|
instructions
|
||||||
});
|
});
|
||||||
|
|
||||||
debug(`synth key is ${key}`);
|
debug(`synth key is ${key}`);
|
||||||
@@ -196,66 +198,81 @@ async function synthAudio(client, createHash, retrieveHash, logger, stats, { acc
|
|||||||
const startAt = process.hrtime();
|
const startAt = process.hrtime();
|
||||||
switch (vendor) {
|
switch (vendor) {
|
||||||
case 'google':
|
case 'google':
|
||||||
audioData = await synthGoogle(logger, {credentials, stats, language, voice, gender, text});
|
audioData = await synthGoogle(logger, {
|
||||||
|
credentials, stats, language, voice, gender, key, text, model, options, instructions,
|
||||||
|
renderForCaching, disableTtsStreaming, disableTtsCache
|
||||||
|
});
|
||||||
break;
|
break;
|
||||||
case 'aws':
|
case 'aws':
|
||||||
case 'polly':
|
case 'polly':
|
||||||
vendorLabel = 'aws';
|
vendorLabel = 'aws';
|
||||||
audioData = await synthPolly(createHash, retrieveHash, logger,
|
audioData = await synthPolly(createHash, retrieveHash, logger,
|
||||||
{credentials, stats, language, voice, text, engine});
|
{credentials, stats, language, voice, key, text, engine, renderForCaching, disableTtsStreaming,
|
||||||
|
disableTtsCache});
|
||||||
break;
|
break;
|
||||||
case 'azure':
|
case 'azure':
|
||||||
case 'microsoft':
|
case 'microsoft':
|
||||||
vendorLabel = 'microsoft';
|
vendorLabel = 'microsoft';
|
||||||
audioData = await synthMicrosoft(logger, {credentials, stats, language, voice, text, deploymentId,
|
audioData = await synthMicrosoft(logger, {credentials, stats, language, voice, key, text, deploymentId,
|
||||||
renderForCaching, disableTtsStreaming});
|
renderForCaching, disableTtsStreaming, disableTtsCache});
|
||||||
break;
|
break;
|
||||||
case 'nuance':
|
case 'nuance':
|
||||||
model = model || 'enhanced';
|
model = model || 'enhanced';
|
||||||
audioData = await synthNuance(client, logger, {credentials, stats, voice, model, text});
|
audioData = await synthNuance(client, logger, {credentials, stats, voice, model, key, text});
|
||||||
break;
|
break;
|
||||||
case 'nvidia':
|
case 'nvidia':
|
||||||
audioData = await synthNvidia(client, logger, {credentials, stats, language, voice, model, text,
|
audioData = await synthNvidia(client, logger, {credentials, stats, language, voice, model, key, text,
|
||||||
renderForCaching, disableTtsStreaming});
|
renderForCaching, disableTtsStreaming, disableTtsCache});
|
||||||
break;
|
|
||||||
case 'ibm':
|
|
||||||
audioData = await synthIbm(logger, {credentials, stats, voice, text});
|
|
||||||
break;
|
break;
|
||||||
case 'wellsaid':
|
case 'wellsaid':
|
||||||
audioData = await synthWellSaid(logger, {credentials, stats, language, voice, text});
|
audioData = await synthWellSaid(logger, {credentials, stats, language, voice, key, text});
|
||||||
break;
|
break;
|
||||||
case 'elevenlabs':
|
case 'elevenlabs':
|
||||||
audioData = await synthElevenlabs(logger, {
|
audioData = await synthElevenlabs(logger, {
|
||||||
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming});
|
credentials, options, stats, language, voice, key, text, renderForCaching, disableTtsStreaming,
|
||||||
|
disableTtsCache});
|
||||||
break;
|
break;
|
||||||
case 'playht':
|
case 'playht':
|
||||||
audioData = await synthPlayHT(client, logger, {
|
audioData = await synthPlayHT(client, logger, {
|
||||||
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming});
|
credentials, options, stats, language, voice, key, text, renderForCaching, disableTtsStreaming,
|
||||||
|
disableTtsCache});
|
||||||
break;
|
break;
|
||||||
case 'cartesia':
|
case 'cartesia':
|
||||||
audioData = await synthCartesia(logger, {
|
audioData = await synthCartesia(logger, {
|
||||||
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming});
|
credentials, options, stats, language, voice, key, text, renderForCaching, disableTtsStreaming,
|
||||||
|
disableTtsCache});
|
||||||
|
break;
|
||||||
|
case 'inworld':
|
||||||
|
audioData = await synthInworld(logger, {
|
||||||
|
credentials, options, stats, language, voice, key, text, renderForCaching, disableTtsStreaming,
|
||||||
|
disableTtsCache});
|
||||||
break;
|
break;
|
||||||
case 'rimelabs':
|
case 'rimelabs':
|
||||||
audioData = await synthRimelabs(logger, {
|
audioData = await synthRimelabs(logger, {
|
||||||
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming});
|
credentials, options, stats, language, voice, key, text, renderForCaching, disableTtsStreaming,
|
||||||
|
disableTtsCache});
|
||||||
break;
|
break;
|
||||||
case 'whisper':
|
case 'whisper':
|
||||||
audioData = await synthWhisper(logger, {
|
audioData = await synthWhisper(logger, {
|
||||||
credentials, stats, voice, text, renderForCaching, disableTtsStreaming});
|
credentials, stats, voice, key, text, instructions, renderForCaching, disableTtsStreaming,
|
||||||
|
disableTtsCache});
|
||||||
break;
|
break;
|
||||||
case 'verbio':
|
case 'verbio':
|
||||||
audioData = await synthVerbio(client, logger, {
|
audioData = await synthVerbio(client, logger, {
|
||||||
credentials, stats, voice, text, renderForCaching, disableTtsStreaming});
|
credentials, stats, voice, key, text, renderForCaching, disableTtsStreaming, disableTtsCache});
|
||||||
if (audioData?.filePath) return audioData;
|
if (audioData?.filePath) return audioData;
|
||||||
break;
|
break;
|
||||||
case 'deepgram':
|
case 'deepgram':
|
||||||
audioData = await synthDeepgram(logger, {credentials, stats, model, text,
|
audioData = await synthDeepgram(logger, {credentials, stats, model, key, text,
|
||||||
renderForCaching, disableTtsStreaming});
|
renderForCaching, disableTtsStreaming, disableTtsCache});
|
||||||
|
break;
|
||||||
|
case 'resemble':
|
||||||
|
audioData = await synthResemble(logger, {
|
||||||
|
credentials, stats, voice, key, text, options, renderForCaching, disableTtsStreaming, disableTtsCache});
|
||||||
break;
|
break;
|
||||||
case vendor.startsWith('custom') ? vendor : 'cant_match_value':
|
case vendor.startsWith('custom') ? vendor : 'cant_match_value':
|
||||||
audioData = await synthCustomVendor(logger,
|
audioData = await synthCustomVendor(logger,
|
||||||
{credentials, stats, language, voice, text});
|
{credentials, stats, language, voice, key, text, renderForCaching, disableTtsStreaming, disableTtsCache});
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
assert(`synthAudio: unsupported speech vendor ${vendor}`);
|
assert(`synthAudio: unsupported speech vendor ${vendor}`);
|
||||||
@@ -290,9 +307,43 @@ async function synthAudio(client, createHash, retrieveHash, logger, stats, { acc
|
|||||||
}
|
}
|
||||||
|
|
||||||
const synthPolly = async(createHash, retrieveHash, logger,
|
const synthPolly = async(createHash, retrieveHash, logger,
|
||||||
{credentials, stats, language, voice, engine, text}) => {
|
{credentials, stats, language, voice, engine, key, text, renderForCaching, disableTtsStreaming, disableTtsCache}) => {
|
||||||
|
const {region, accessKeyId, secretAccessKey, roleArn} = credentials;
|
||||||
|
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
|
|
||||||
|
let params = '{';
|
||||||
|
params += `language=${language}`;
|
||||||
|
params += `,playback_id=${key}`;
|
||||||
|
params += `,write_cache_file=${disableTtsCache ? 0 : 1}`;
|
||||||
|
params += ',vendor=aws';
|
||||||
|
if (accessKeyId && secretAccessKey) {
|
||||||
|
if (accessKeyId) params += `,accessKeyId=${accessKeyId}`;
|
||||||
|
if (secretAccessKey) params += `,secretAccessKey=${secretAccessKey}`;
|
||||||
|
} else if (roleArn) {
|
||||||
|
const cred = await getAwsAuthToken(
|
||||||
|
logger, createHash, retrieveHash,
|
||||||
|
{
|
||||||
|
region,
|
||||||
|
roleArn
|
||||||
|
});
|
||||||
|
|
||||||
|
if (cred) {
|
||||||
|
params += `,accessKeyId=${cred.accessKeyId}`;
|
||||||
|
params += `,secretAccessKey=${cred.secretAccessKey}`;
|
||||||
|
params += `,sessionToken=${cred.sessionToken}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (region) params += `,region=${region}`;
|
||||||
|
if (engine) params += `,engine=${engine}`;
|
||||||
|
params += '}';
|
||||||
|
|
||||||
|
return {
|
||||||
|
filePath: `say:${params}${text.replace(/\n/g, ' ').replace(/\r/g, ' ')}`,
|
||||||
|
servedFromCache: false,
|
||||||
|
rtt: 0
|
||||||
|
};
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const {region, accessKeyId, secretAccessKey, roleArn} = credentials;
|
|
||||||
let polly;
|
let polly;
|
||||||
if (accessKeyId && secretAccessKey) {
|
if (accessKeyId && secretAccessKey) {
|
||||||
polly = new PollyClient({
|
polly = new PollyClient({
|
||||||
@@ -352,111 +403,129 @@ const synthPolly = async(createHash, retrieveHash, logger,
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const synthGoogle = async(logger, {credentials, stats, language, voice, gender, text}) => {
|
|
||||||
const client = new ttsGoogle.TextToSpeechClient(credentials);
|
|
||||||
// If google custom voice cloning is used.
|
|
||||||
// At this time 31 Oct 2024, google node sdk has not support voice cloning yet.
|
|
||||||
if (typeof voice === 'object' && voice.voice_cloning_key) {
|
|
||||||
try {
|
|
||||||
const accessToken = await client.auth.getAccessToken();
|
|
||||||
const projectId = await client.getProjectId();
|
|
||||||
|
|
||||||
const post = bent('https://texttospeech.googleapis.com', 'POST', 'json', {
|
const synthGoogle = async(logger, {
|
||||||
'Authorization': `Bearer ${accessToken}`,
|
credentials, stats, language, voice, gender, key, text, model, options, instructions,
|
||||||
'x-goog-user-project': projectId,
|
renderForCaching, disableTtsStreaming, disableTtsCache
|
||||||
'Content-Type': 'application/json; charset=utf-8'
|
}) => {
|
||||||
});
|
const isGemini = !!model;
|
||||||
|
const isVoiceCloning = typeof voice === 'object' && voice.voice_cloning_key;
|
||||||
|
// HD voices have pattern like en-US-Chirp3-HD-Charon
|
||||||
|
const isHDVoice = typeof voice === 'string' && voice.includes('-HD-');
|
||||||
|
|
||||||
const payload = {
|
// Streaming support for Google TTS (Gemini, HD voices, and standard voices)
|
||||||
input: {
|
// Voice cloning does not support streaming
|
||||||
text
|
if (!isVoiceCloning && !JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
},
|
// Strip SSML tags for Gemini TTS (it doesn't support SSML)
|
||||||
voice: {
|
let inputText = text;
|
||||||
language_code: language,
|
if (isGemini && text.startsWith('<speak>')) {
|
||||||
voice_clone: {
|
inputText = text.replace(/<[^>]*>/g, '').trim();
|
||||||
voice_cloning_key: voice.voice_cloning_key
|
logger.info('synthGoogle: Gemini TTS does not support SSML, stripped tags from input');
|
||||||
}
|
|
||||||
},
|
|
||||||
audioConfig: {
|
|
||||||
// Cloning voice at this time still in v1 beta version, and it support LINEAR16 in Wav format, 24.000Hz
|
|
||||||
audioEncoding: 'LINEAR16',
|
|
||||||
sample_rate_hertz: 24000
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const wav = await post('/v1beta1/text:synthesize', payload);
|
|
||||||
return {
|
|
||||||
audioContent: Buffer.from(wav.audioContent, 'base64'),
|
|
||||||
extension: 'wav',
|
|
||||||
sampleRate: 24000
|
|
||||||
};
|
|
||||||
} catch (err) {
|
|
||||||
logger.info({err: await err.text()}, 'synthGoogle returned error');
|
|
||||||
throw err;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let params = '{';
|
||||||
|
params += `credentials=${Buffer.from(JSON.stringify(credentials.credentials)).toString('base64')}`;
|
||||||
|
params += `,playback_id=${key}`;
|
||||||
|
params += ',vendor=google';
|
||||||
|
params += `,voice=${voice}`;
|
||||||
|
params += `,language_code=${language || 'en-US'}`;
|
||||||
|
params += `,write_cache_file=${disableTtsCache ? 0 : 1}`;
|
||||||
|
// api_mode: tts (standard), live (HD voices), gemini (Gemini TTS)
|
||||||
|
const apiMode = options?.apiMode || (isGemini ? 'gemini' : (isHDVoice ? 'live' : 'tts'));
|
||||||
|
params += `,api_mode=${apiMode}`;
|
||||||
|
if (model) params += `,model_name=${model}`;
|
||||||
|
if (gender) params += `,gender=${gender}`;
|
||||||
|
// comma is used to separate parameters in freeswitch tts module
|
||||||
|
const prompt = options?.prompt || instructions;
|
||||||
|
if (prompt) params += `,prompt=${prompt.replace(/\n/g, ' ').replace(/,/g, ';')}`;
|
||||||
|
params += '}';
|
||||||
|
|
||||||
|
return {
|
||||||
|
filePath: `say:${params}${(isGemini ? inputText : text).replace(/\n/g, ' ')}`,
|
||||||
|
servedFromCache: false,
|
||||||
|
rtt: 0
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const opts = {
|
const client = new ttsGoogle.TextToSpeechClient(credentials);
|
||||||
voice: {
|
|
||||||
...(typeof voice === 'string' && {name: voice}),
|
// Build input based on voice type
|
||||||
...(typeof voice === 'object' && {customVoice: voice}),
|
let input;
|
||||||
|
if (isGemini) {
|
||||||
|
// Gemini TTS does not support SSML - strip tags if present
|
||||||
|
let inputText = text;
|
||||||
|
if (text.startsWith('<speak>')) {
|
||||||
|
inputText = text.replace(/<[^>]*>/g, '').trim();
|
||||||
|
logger.info('synthGoogle: Gemini TTS does not support SSML, stripped tags from input');
|
||||||
|
}
|
||||||
|
// Use instructions as prompt for Gemini TTS style control, options.prompt can override
|
||||||
|
const prompt = options?.prompt || instructions;
|
||||||
|
input = {
|
||||||
|
text: inputText,
|
||||||
|
...(prompt && { prompt })
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
input = text.startsWith('<speak>') ? { ssml: text } : { text };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build voice selection params based on voice type
|
||||||
|
let voiceParams;
|
||||||
|
if (isGemini) {
|
||||||
|
voiceParams = {
|
||||||
|
languageCode: language || 'en-US',
|
||||||
|
name: voice,
|
||||||
|
modelName: model
|
||||||
|
};
|
||||||
|
} else if (isVoiceCloning) {
|
||||||
|
voiceParams = {
|
||||||
|
languageCode: language,
|
||||||
|
voiceClone: {
|
||||||
|
voiceCloningKey: voice.voice_cloning_key
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
voiceParams = {
|
||||||
|
...(typeof voice === 'string' && { name: voice }),
|
||||||
|
...(typeof voice === 'object' && { customVoice: voice }),
|
||||||
languageCode: language,
|
languageCode: language,
|
||||||
ssmlGender: gender || 'SSML_VOICE_GENDER_UNSPECIFIED'
|
ssmlGender: gender || 'SSML_VOICE_GENDER_UNSPECIFIED'
|
||||||
},
|
};
|
||||||
audioConfig: {audioEncoding: 'MP3'}
|
}
|
||||||
};
|
|
||||||
Object.assign(opts, {input: text.startsWith('<speak>') ? {ssml: text} : {text}});
|
// Build audio config based on voice type
|
||||||
|
let audioConfig;
|
||||||
|
let extension;
|
||||||
|
let sampleRate;
|
||||||
|
if (isVoiceCloning) {
|
||||||
|
audioConfig = { audioEncoding: 'LINEAR16', sampleRateHertz: 24000 };
|
||||||
|
extension = 'wav';
|
||||||
|
sampleRate = 24000;
|
||||||
|
} else {
|
||||||
|
audioConfig = { audioEncoding: 'MP3' };
|
||||||
|
extension = 'mp3';
|
||||||
|
sampleRate = 8000;
|
||||||
|
}
|
||||||
|
|
||||||
|
const opts = { input, voice: voiceParams, audioConfig };
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const responses = await client.synthesizeSpeech(opts);
|
logger.debug({ opts }, 'synthGoogle: request');
|
||||||
|
const [response] = await client.synthesizeSpeech(opts);
|
||||||
stats.increment('tts.count', ['vendor:google', 'accepted:yes']);
|
stats.increment('tts.count', ['vendor:google', 'accepted:yes']);
|
||||||
client.close();
|
client.close();
|
||||||
return {
|
return {
|
||||||
audioContent: responses[0].audioContent,
|
audioContent: response.audioContent,
|
||||||
extension: 'mp3',
|
extension,
|
||||||
sampleRate: 8000
|
sampleRate
|
||||||
};
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
logger.info({ err, opts }, 'synthAudio: Error synthesizing speech using google');
|
||||||
logger.info({err, opts}, 'synthAudio: Error synthesizing speech using google');
|
|
||||||
stats.increment('tts.count', ['vendor:google', 'accepted:no']);
|
stats.increment('tts.count', ['vendor:google', 'accepted:no']);
|
||||||
client && client.close();
|
client && client.close();
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const synthIbm = async(logger, {credentials, stats, voice, text}) => {
|
|
||||||
const {tts_api_key, tts_region} = credentials;
|
|
||||||
const params = {
|
|
||||||
text,
|
|
||||||
voice,
|
|
||||||
accept: 'audio/mp3'
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const textToSpeech = new TextToSpeechV1({
|
|
||||||
authenticator: new IamAuthenticator({
|
|
||||||
apikey: tts_api_key,
|
|
||||||
}),
|
|
||||||
serviceUrl: `https://api.${tts_region}.text-to-speech.watson.cloud.ibm.com`
|
|
||||||
});
|
|
||||||
|
|
||||||
const r = await textToSpeech.synthesize(params);
|
|
||||||
const chunks = [];
|
|
||||||
for await (const chunk of r.result) {
|
|
||||||
chunks.push(chunk);
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
audioContent: Buffer.concat(chunks),
|
|
||||||
extension: 'mp3',
|
|
||||||
sampleRate: 8000
|
|
||||||
};
|
|
||||||
} catch (err) {
|
|
||||||
logger.info({err, params}, 'synthAudio: Error synthesizing speech using ibm');
|
|
||||||
stats.increment('tts.count', ['vendor:ibm', 'accepted:no']);
|
|
||||||
throw new Error(err.statusText || err.message);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
async function _synthOnPremMicrosoft(logger, {
|
async function _synthOnPremMicrosoft(logger, {
|
||||||
credentials,
|
credentials,
|
||||||
language,
|
language,
|
||||||
@@ -465,7 +534,6 @@ async function _synthOnPremMicrosoft(logger, {
|
|||||||
}) {
|
}) {
|
||||||
const {use_custom_tts, custom_tts_endpoint_url, api_key} = credentials;
|
const {use_custom_tts, custom_tts_endpoint_url, api_key} = credentials;
|
||||||
let content = text;
|
let content = text;
|
||||||
|
|
||||||
if (use_custom_tts && !content.startsWith('<speak')) {
|
if (use_custom_tts && !content.startsWith('<speak')) {
|
||||||
/**
|
/**
|
||||||
* Note: it seems that to use custom voice ssml is required with the voice attribute
|
* Note: it seems that to use custom voice ssml is required with the voice attribute
|
||||||
@@ -481,6 +549,10 @@ async function _synthOnPremMicrosoft(logger, {
|
|||||||
content = `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="${language}"><voice name="${voice}">${words}</voice></speak>`;
|
content = `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="${language}"><voice name="${voice}">${words}</voice></speak>`;
|
||||||
logger.info({content}, 'synthMicrosoft');
|
logger.info({content}, 'synthMicrosoft');
|
||||||
}
|
}
|
||||||
|
else if (JAMBONES_AZURE_ENABLE_SSML && !content.startsWith('<speak')) {
|
||||||
|
// eslint-disable-next-line max-len
|
||||||
|
content = `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="${language}"><voice name="${voice}"><lang xml:lang="${language}">${text}</lang></voice></speak>`;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const trimSilence = JAMBONES_TTS_TRIM_SILENCE;
|
const trimSilence = JAMBONES_TTS_TRIM_SILENCE;
|
||||||
@@ -507,9 +579,11 @@ const synthMicrosoft = async(logger, {
|
|||||||
stats,
|
stats,
|
||||||
language,
|
language,
|
||||||
voice,
|
voice,
|
||||||
|
key,
|
||||||
text,
|
text,
|
||||||
renderForCaching,
|
renderForCaching,
|
||||||
disableTtsStreaming
|
disableTtsStreaming,
|
||||||
|
disableTtsCache
|
||||||
}) => {
|
}) => {
|
||||||
try {
|
try {
|
||||||
const {api_key: apiKey, region, use_custom_tts, custom_tts_endpoint, custom_tts_endpoint_url} = credentials;
|
const {api_key: apiKey, region, use_custom_tts, custom_tts_endpoint, custom_tts_endpoint_url} = credentials;
|
||||||
@@ -517,27 +591,32 @@ const synthMicrosoft = async(logger, {
|
|||||||
let content = text;
|
let content = text;
|
||||||
if (use_custom_tts && !content.startsWith('<speak')) {
|
if (use_custom_tts && !content.startsWith('<speak')) {
|
||||||
/**
|
/**
|
||||||
* Note: it seems that to use custom voice ssml is required with the voice attribute
|
* Note: it seems that to use custom voice ssml is required with the voice attribute
|
||||||
* Otherwise sending plain text we get "Voice does not match"
|
* Otherwise sending plain text we get "Voice does not match"
|
||||||
*/
|
*/
|
||||||
content = `<speak>${text}</speak>`;
|
content = `<speak>${text}</speak>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
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 */
|
||||||
const words = content.slice(7, -8).trim().replace(/(\r\n|\n|\r)/gm, ' ');
|
const words = content.slice(7, -8).trim().replace(/(\r\n|\n|\r)/gm, ' ');
|
||||||
// eslint-disable-next-line max-len
|
// eslint-disable-next-line max-len
|
||||||
content = `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="${language}"><voice name="${voice}">${words}</voice></speak>`;
|
content = `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="${language}"><voice name="${voice}">${words}</voice></speak>`;
|
||||||
logger.info({content}, 'synthMicrosoft');
|
logger.info({content}, 'synthMicrosoft');
|
||||||
}
|
}
|
||||||
|
else if (JAMBONES_AZURE_ENABLE_SSML && !content.startsWith('<speak')) {
|
||||||
|
// eslint-disable-next-line max-len
|
||||||
|
content = `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="${language}"><voice name="${voice}"><lang xml:lang="${language}">${text}</lang></voice></speak>`;
|
||||||
|
}
|
||||||
if (!JAMBONES_DISABLE_TTS_STREAMING && !JAMBONES_DISABLE_AZURE_TTS_STREAMING &&
|
if (!JAMBONES_DISABLE_TTS_STREAMING && !JAMBONES_DISABLE_AZURE_TTS_STREAMING &&
|
||||||
!renderForCaching && !disableTtsStreaming) {
|
!renderForCaching && !disableTtsStreaming) {
|
||||||
let params = '';
|
let params = '{';
|
||||||
params += `{api_key=${apiKey}`;
|
params += `api_key=${apiKey}`;
|
||||||
|
params += `,playback_id=${key}`;
|
||||||
params += `,language=${language}`;
|
params += `,language=${language}`;
|
||||||
params += ',vendor=microsoft';
|
params += ',vendor=microsoft';
|
||||||
params += `,voice=${voice}`;
|
params += `,voice=${voice}`;
|
||||||
params += ',write_cache_file=1';
|
params += `,write_cache_file=${disableTtsCache ? 0 : 1}`;
|
||||||
if (region) params += `,region=${region}`;
|
if (region) params += `,region=${region}`;
|
||||||
if (custom_tts_endpoint) params += `,endpointId=${custom_tts_endpoint}`;
|
if (custom_tts_endpoint) params += `,endpointId=${custom_tts_endpoint}`;
|
||||||
if (custom_tts_endpoint_url) params += `,endpoint=${custom_tts_endpoint_url}`;
|
if (custom_tts_endpoint_url) params += `,endpoint=${custom_tts_endpoint_url}`;
|
||||||
@@ -710,15 +789,16 @@ const synthNuance = async(client, logger, {credentials, stats, voice, model, tex
|
|||||||
};
|
};
|
||||||
|
|
||||||
const synthNvidia = async(client, logger, {
|
const synthNvidia = async(client, logger, {
|
||||||
credentials, stats, language, voice, model, text, renderForCaching, disableTtsStreaming
|
credentials, stats, language, voice, model, key, text, renderForCaching, disableTtsStreaming, disableTtsCache
|
||||||
}) => {
|
}) => {
|
||||||
const {riva_server_uri} = credentials;
|
const {riva_server_uri} = credentials;
|
||||||
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
let params = '';
|
let params = '';
|
||||||
params += `{riva_server_uri=${riva_server_uri}`;
|
params += `{riva_server_uri=${riva_server_uri}`;
|
||||||
|
params += `,playback_id=${key}`;
|
||||||
params += `,voice=${voice}`;
|
params += `,voice=${voice}`;
|
||||||
params += `,language=${language}`;
|
params += `,language=${language}`;
|
||||||
params += ',write_cache_file=1';
|
params += `,write_cache_file=${disableTtsCache ? 0 : 1}`;
|
||||||
params += '}';
|
params += '}';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -758,9 +838,27 @@ const synthNvidia = async(client, logger, {
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const synthCustomVendor = async(logger, {credentials, stats, language, voice, text, filePath}) => {
|
const synthCustomVendor = async(logger, {credentials, stats, language, voice,
|
||||||
|
text, filePath, renderForCaching, disableTtsStreaming, key, disableTtsCache}) => {
|
||||||
const {vendor, auth_token, custom_tts_url} = credentials;
|
const {vendor, auth_token, custom_tts_url} = credentials;
|
||||||
|
|
||||||
|
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
|
let params = '{';
|
||||||
|
params += `auth_token=${auth_token}`;
|
||||||
|
params += `,playback_id=${key}`;
|
||||||
|
params += `,custom_tts_url=${custom_tts_url}`;
|
||||||
|
params += ',vendor=custom';
|
||||||
|
params += `,voice=${voice}`;
|
||||||
|
params += `,write_cache_file=${disableTtsCache ? 0 : 1}`;
|
||||||
|
params += '}';
|
||||||
|
|
||||||
|
return {
|
||||||
|
filePath: `say:${params}${text.replace(/\n/g, ' ').replace(/\r/g, ' ')}`,
|
||||||
|
servedFromCache: false,
|
||||||
|
rtt: 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const post = bent('POST', {
|
const post = bent('POST', {
|
||||||
'Authorization': `Bearer ${auth_token}`,
|
'Authorization': `Bearer ${auth_token}`,
|
||||||
@@ -789,20 +887,24 @@ const synthCustomVendor = async(logger, {credentials, stats, language, voice, te
|
|||||||
};
|
};
|
||||||
|
|
||||||
const synthElevenlabs = async(logger, {
|
const synthElevenlabs = async(logger, {
|
||||||
credentials, options, stats, voice, text, renderForCaching, disableTtsStreaming
|
credentials, options, stats, voice, key, text, renderForCaching, disableTtsStreaming, disableTtsCache
|
||||||
}) => {
|
}) => {
|
||||||
const {api_key, model_id, options: credOpts} = credentials;
|
const {api_key, model_id, api_uri, options: credOpts} = credentials;
|
||||||
const opts = !!options && Object.keys(options).length !== 0 ? options : JSON.parse(credOpts || '{}');
|
const opts = !!options && Object.keys(options).length !== 0 ? options : JSON.parse(credOpts || '{}');
|
||||||
|
|
||||||
/* default to using the streaming interface, unless disabled by env var OR we want just a cache file */
|
/* default to using the streaming interface, unless disabled by env var OR we want just a cache file */
|
||||||
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
let params = '';
|
let params = '{';
|
||||||
params += `{api_key=${api_key}`;
|
params += `api_key=${api_key}`;
|
||||||
|
params += `,playback_id=${key}`;
|
||||||
params += ',vendor=elevenlabs';
|
params += ',vendor=elevenlabs';
|
||||||
params += `,voice=${voice}`;
|
params += `,voice=${voice}`;
|
||||||
params += `,model_id=${model_id}`;
|
params += `,model_id=${model_id}`;
|
||||||
params += `,optimize_streaming_latency=${opts.optimize_streaming_latency || 2}`;
|
params += `,write_cache_file=${disableTtsCache ? 0 : 1}`;
|
||||||
params += ',write_cache_file=1';
|
if (api_uri) params += `,api_uri=${api_uri}`;
|
||||||
|
if (opts.optimize_streaming_latency !== null && opts.optimize_streaming_latency !== undefined) {
|
||||||
|
params += `,optimize_streaming_latency=${opts.optimize_streaming_latency}`;
|
||||||
|
}
|
||||||
if (opts.voice_settings?.similarity_boost) params += `,similarity_boost=${opts.voice_settings.similarity_boost}`;
|
if (opts.voice_settings?.similarity_boost) params += `,similarity_boost=${opts.voice_settings.similarity_boost}`;
|
||||||
if (opts.voice_settings?.stability) params += `,stability=${opts.voice_settings.stability}`;
|
if (opts.voice_settings?.stability) params += `,stability=${opts.voice_settings.stability}`;
|
||||||
if (opts.voice_settings?.style) params += `,style=${opts.voice_settings.style}`;
|
if (opts.voice_settings?.style) params += `,style=${opts.voice_settings.style}`;
|
||||||
@@ -825,7 +927,7 @@ const synthElevenlabs = async(logger, {
|
|||||||
const optimize_streaming_latency = opts.optimize_streaming_latency ?
|
const optimize_streaming_latency = opts.optimize_streaming_latency ?
|
||||||
`?optimize_streaming_latency=${opts.optimize_streaming_latency}` : '';
|
`?optimize_streaming_latency=${opts.optimize_streaming_latency}` : '';
|
||||||
try {
|
try {
|
||||||
const post = bent('https://api.elevenlabs.io', 'POST', 'buffer', {
|
const post = bent(`https://${api_uri || 'api.elevenlabs.io'}`, 'POST', 'buffer', {
|
||||||
'xi-api-key': api_key,
|
'xi-api-key': api_key,
|
||||||
'Accept': 'audio/mpeg',
|
'Accept': 'audio/mpeg',
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
@@ -852,13 +954,12 @@ const synthElevenlabs = async(logger, {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const synthPlayHT = async(client, logger, {
|
const synthPlayHT = async(client, logger, {
|
||||||
credentials, options, stats, voice, language, text, renderForCaching, disableTtsStreaming
|
credentials, options, stats, voice, language, key, text, renderForCaching, disableTtsStreaming, disableTtsCache
|
||||||
}) => {
|
}) => {
|
||||||
const {api_key, user_id, voice_engine, options: credOpts} = credentials;
|
const {api_key, user_id, voice_engine, playht_tts_uri, options: credOpts} = credentials;
|
||||||
const opts = !!options && Object.keys(options).length !== 0 ? options : JSON.parse(credOpts || '{}');
|
const opts = !!options && Object.keys(options).length !== 0 ? options : JSON.parse(credOpts || '{}');
|
||||||
|
|
||||||
let synthesizeUrl = 'https://api.play.ht/api/v2/tts/stream';
|
let synthesizeUrl = playht_tts_uri ? `${playht_tts_uri}/api/v2/tts/stream` : 'https://api.play.ht/api/v2/tts/stream';
|
||||||
|
|
||||||
// If model is play3.0, the synthesizeUrl is got from authentication endpoint
|
// If model is play3.0, the synthesizeUrl is got from authentication endpoint
|
||||||
if (voice_engine === 'Play3.0') {
|
if (voice_engine === 'Play3.0') {
|
||||||
try {
|
try {
|
||||||
@@ -887,14 +988,15 @@ const synthPlayHT = async(client, logger, {
|
|||||||
|
|
||||||
/* default to using the streaming interface, unless disabled by env var OR we want just a cache file */
|
/* default to using the streaming interface, unless disabled by env var OR we want just a cache file */
|
||||||
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
let params = '';
|
let params = '{';
|
||||||
params += `{api_key=${api_key}`;
|
params += `api_key=${api_key}`;
|
||||||
|
params += `,playback_id=${key}`;
|
||||||
params += `,user_id=${user_id}`;
|
params += `,user_id=${user_id}`;
|
||||||
params += ',vendor=playht';
|
params += ',vendor=playht';
|
||||||
params += `,voice=${voice}`;
|
params += `,voice=${voice}`;
|
||||||
params += `,voice_engine=${voice_engine}`;
|
params += `,voice_engine=${voice_engine}`;
|
||||||
params += `,synthesize_url=${synthesizeUrl}`;
|
params += `,synthesize_url=${synthesizeUrl}`;
|
||||||
params += ',write_cache_file=1';
|
params += `,write_cache_file=${disableTtsCache ? 0 : 1}`;
|
||||||
params += `,language=${language}`;
|
params += `,language=${language}`;
|
||||||
if (opts.quality) params += `,quality=${opts.quality}`;
|
if (opts.quality) params += `,quality=${opts.quality}`;
|
||||||
if (opts.speed) params += `,speed=${opts.speed}`;
|
if (opts.speed) params += `,speed=${opts.speed}`;
|
||||||
@@ -946,21 +1048,87 @@ const synthPlayHT = async(client, logger, {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const synthRimelabs = async(logger, {
|
const synthInworld = async(logger, {
|
||||||
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming
|
credentials, options, stats, voice, key, text, renderForCaching, disableTtsStreaming, disableTtsCache
|
||||||
}) => {
|
}) => {
|
||||||
const {api_key, model_id, options: credOpts} = credentials;
|
const {api_key, model_id, options: credOpts} = credentials;
|
||||||
const opts = !!options && Object.keys(options).length !== 0 ? options : JSON.parse(credOpts || '{}');
|
const opts = !!options && Object.keys(options).length !== 0 ? options : JSON.parse(credOpts || '{}');
|
||||||
|
|
||||||
/* default to using the streaming interface, unless disabled by env var OR we want just a cache file */
|
/* default to using the streaming interface, unless disabled by env var OR we want just a cache file */
|
||||||
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
let params = '';
|
let params = '{';
|
||||||
params += `{api_key=${api_key}`;
|
params += `api_key=${api_key}`;
|
||||||
|
params += `,playback_id=${key}`;
|
||||||
|
params += `,model_id=${model_id}`;
|
||||||
|
params += ',vendor=inworld';
|
||||||
|
params += `,voice=${voice}`;
|
||||||
|
params += `,write_cache_file=${disableTtsCache ? 0 : 1}`;
|
||||||
|
if (opts.temperature) params += `,temperature=${opts.temperature}`;
|
||||||
|
if (opts.audioConfig?.pitch) params += `,pitch=${opts.pitch}`;
|
||||||
|
if (opts.audioConfig?.speakingRate) params += `,speakingRate=${opts.speakingRate}`;
|
||||||
|
params += '}';
|
||||||
|
|
||||||
|
return {
|
||||||
|
filePath: `say:${params}${text.replace(/\n/g, ' ').replace(/\r/g, ' ')}`,
|
||||||
|
servedFromCache: false,
|
||||||
|
rtt: 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = 'https://api.inworld.ai/tts/v1/voice';
|
||||||
|
const sampleRate = 8000;
|
||||||
|
const options = {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Basic ${api_key}`,
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
text,
|
||||||
|
voiceId: voice,
|
||||||
|
modelId: model_id,
|
||||||
|
audioConfig: {
|
||||||
|
...(opts.audioConfig || {}),
|
||||||
|
audioEncoding: 'MP3',
|
||||||
|
}
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await fetch(url, options);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(await response.text());
|
||||||
|
}
|
||||||
|
const json = await response.json();
|
||||||
|
return {
|
||||||
|
audioContent: Buffer.from(json.audioContent, 'base64'),
|
||||||
|
extension: 'mp3',
|
||||||
|
sampleRate
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
logger.info({err}, 'synth inworld returned error');
|
||||||
|
stats.increment('tts.count', ['vendor:inworld', 'accepted:no']);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const synthRimelabs = async(logger, {
|
||||||
|
credentials, options, stats, language, voice, key, text, renderForCaching, disableTtsStreaming, disableTtsCache
|
||||||
|
}) => {
|
||||||
|
const {api_key, model_id, options: credOpts} = credentials;
|
||||||
|
const opts = !!options && Object.keys(options).length !== 0 ? options : JSON.parse(credOpts || '{}');
|
||||||
|
|
||||||
|
/* default to using the streaming interface, unless disabled by env var OR we want just a cache file */
|
||||||
|
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
|
let params = '{';
|
||||||
|
params += `api_key=${api_key}`;
|
||||||
|
params += `,playback_id=${key}`;
|
||||||
params += `,model_id=${model_id}`;
|
params += `,model_id=${model_id}`;
|
||||||
params += ',vendor=rimelabs';
|
params += ',vendor=rimelabs';
|
||||||
params += `,language=${language}`;
|
params += `,language=${language}`;
|
||||||
params += `,voice=${voice}`;
|
params += `,voice=${voice}`;
|
||||||
params += ',write_cache_file=1';
|
params += `,write_cache_file=${disableTtsCache ? 0 : 1}`;
|
||||||
if (opts.speedAlpha) params += `,speed_alpha=${opts.speedAlpha}`;
|
if (opts.speedAlpha) params += `,speed_alpha=${opts.speedAlpha}`;
|
||||||
if (opts.reduceLatency) params += `,reduce_latency=${opts.reduceLatency}`;
|
if (opts.reduceLatency) params += `,reduce_latency=${opts.reduceLatency}`;
|
||||||
// Arcana model parameters
|
// Arcana model parameters
|
||||||
@@ -1003,18 +1171,21 @@ const synthRimelabs = async(logger, {
|
|||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const synthVerbio = async(client, logger, {credentials, stats, voice, text, renderForCaching, disableTtsStreaming}) => {
|
const synthVerbio = async(client, logger, {
|
||||||
|
credentials, stats, voice, key, text, renderForCaching, disableTtsStreaming, disableTtsCache
|
||||||
|
}) => {
|
||||||
//https://doc.speechcenter.verbio.com/#tag/Text-To-Speech-REST-API
|
//https://doc.speechcenter.verbio.com/#tag/Text-To-Speech-REST-API
|
||||||
if (text.length > 2000) {
|
if (text.length > 2000) {
|
||||||
throw new Error('Verbio cannot synthesize for the text length larger than 2000 characters');
|
throw new Error('Verbio cannot synthesize for the text length larger than 2000 characters');
|
||||||
}
|
}
|
||||||
const token = await getVerbioAccessToken(client, logger, credentials);
|
const token = await getVerbioAccessToken(client, logger, credentials);
|
||||||
if (!process.env.JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
if (!process.env.JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
let params = '';
|
let params = '{';
|
||||||
params += `{access_token=${token.access_token}`;
|
params += `access_token=${token.access_token}`;
|
||||||
|
params += `,playback_id=${key}`;
|
||||||
params += ',vendor=verbio';
|
params += ',vendor=verbio';
|
||||||
params += `,voice=${voice}`;
|
params += `,voice=${voice}`;
|
||||||
params += ',write_cache_file=1';
|
params += `,write_cache_file=${disableTtsCache ? 0 : 1}`;
|
||||||
params += '}';
|
params += '}';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -1048,17 +1219,21 @@ const synthVerbio = async(client, logger, {credentials, stats, voice, text, rend
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const synthWhisper = async(logger, {credentials, stats, voice, text, renderForCaching, disableTtsStreaming}) => {
|
const synthWhisper = async(logger, {credentials, stats, voice, key, text, instructions,
|
||||||
|
renderForCaching, disableTtsStreaming, disableTtsCache}) => {
|
||||||
const {api_key, model_id, baseURL, timeout, speed} = credentials;
|
const {api_key, model_id, baseURL, timeout, speed} = credentials;
|
||||||
/* if the env is set to stream then bag out, unless we are specifically rendering to generate a cache file */
|
/* if the env is set to stream then bag out, unless we are specifically rendering to generate a cache file */
|
||||||
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
let params = '';
|
let params = '{';
|
||||||
params += `{api_key=${api_key}`;
|
params += `api_key=${api_key}`;
|
||||||
|
params += `,playback_id=${key}`;
|
||||||
params += `,model_id=${model_id}`;
|
params += `,model_id=${model_id}`;
|
||||||
params += ',vendor=whisper';
|
params += ',vendor=whisper';
|
||||||
params += `,voice=${voice}`;
|
params += `,voice=${voice}`;
|
||||||
params += ',write_cache_file=1';
|
params += `,write_cache_file=${disableTtsCache ? 0 : 1}`;
|
||||||
if (speed) params += `,speed=${speed}`;
|
if (speed) params += `,speed=${speed}`;
|
||||||
|
// comma is used to separated parameters in freeswitch tts module
|
||||||
|
if (instructions) params += `,instructions=${instructions.replace(/\n/g, ' ').replace(/,/g, ';')}`;
|
||||||
params += '}';
|
params += '}';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -1078,6 +1253,7 @@ const synthWhisper = async(logger, {credentials, stats, voice, text, renderForCa
|
|||||||
model: model_id,
|
model: model_id,
|
||||||
voice,
|
voice,
|
||||||
input: text,
|
input: text,
|
||||||
|
...(instructions && {instructions}),
|
||||||
response_format: 'mp3'
|
response_format: 'mp3'
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
@@ -1092,14 +1268,16 @@ const synthWhisper = async(logger, {credentials, stats, voice, text, renderForCa
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const synthDeepgram = async(logger, {credentials, stats, model, text, renderForCaching, disableTtsStreaming}) => {
|
const synthDeepgram = async(logger, {credentials, stats, model, key, text, renderForCaching,
|
||||||
|
disableTtsStreaming, disableTtsCache}) => {
|
||||||
const {api_key, deepgram_tts_uri} = credentials;
|
const {api_key, deepgram_tts_uri} = credentials;
|
||||||
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
let params = '';
|
let params = '{';
|
||||||
params += `{api_key=${api_key}`;
|
params += `api_key=${api_key}`;
|
||||||
|
params += `,playback_id=${key}`;
|
||||||
params += ',vendor=deepgram';
|
params += ',vendor=deepgram';
|
||||||
params += `,voice=${model}`;
|
params += `,voice=${model}`;
|
||||||
params += ',write_cache_file=1';
|
params += `,write_cache_file=${disableTtsCache ? 0 : 1}`;
|
||||||
if (deepgram_tts_uri) params += `,endpoint=${deepgram_tts_uri}`;
|
if (deepgram_tts_uri) params += `,endpoint=${deepgram_tts_uri}`;
|
||||||
params += '}';
|
params += '}';
|
||||||
|
|
||||||
@@ -1132,23 +1310,25 @@ const synthDeepgram = async(logger, {credentials, stats, model, text, renderForC
|
|||||||
};
|
};
|
||||||
|
|
||||||
const synthCartesia = async(logger, {
|
const synthCartesia = async(logger, {
|
||||||
credentials, options, stats, voice, language, text, renderForCaching, disableTtsStreaming
|
credentials, options, stats, voice, language, key, text, renderForCaching, disableTtsStreaming, disableTtsCache
|
||||||
}) => {
|
}) => {
|
||||||
const {api_key, model_id, embedding, options: credOpts} = credentials;
|
const {api_key, model_id, embedding, options: credOpts} = credentials;
|
||||||
const opts = !!options && Object.keys(options).length !== 0 ? options : JSON.parse(credOpts || '{}');
|
const opts = !!options && Object.keys(options).length !== 0 ? options : JSON.parse(credOpts || '{}');
|
||||||
|
|
||||||
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
let params = '';
|
let params = '{';
|
||||||
params += `{api_key=${api_key}`;
|
params += `api_key=${api_key}`;
|
||||||
|
params += `,playback_id=${key}`;
|
||||||
params += `,model_id=${model_id}`;
|
params += `,model_id=${model_id}`;
|
||||||
params += ',vendor=cartesia';
|
params += ',vendor=cartesia';
|
||||||
params += `,voice=${voice}`;
|
params += `,voice=${voice}`;
|
||||||
params += ',write_cache_file=1';
|
params += `,write_cache_file=${disableTtsCache ? 0 : 1}`;
|
||||||
params += `,language=${language}`;
|
params += `,language=${language}`;
|
||||||
params += `,voice_mode=${embedding ? 'embedding' : 'id'}`;
|
params += `,voice_mode=${embedding ? 'embedding' : 'id'}`;
|
||||||
if (embedding) params += `,embedding=${embedding}`;
|
if (embedding) params += `,embedding=${embedding}`;
|
||||||
if (opts.speed) params += `,speed=${opts.speed}`;
|
if (opts.speed) params += `,speed=${opts.speed}`;
|
||||||
if (opts.emotion) params += `,emotion=${opts.emotion}`;
|
if (opts.emotion) params += `,emotion=${opts.emotion}`;
|
||||||
|
if (opts.volume) params += `,volume=${opts.volume}`;
|
||||||
params += '}';
|
params += '}';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -1161,7 +1341,7 @@ const synthCartesia = async(logger, {
|
|||||||
try {
|
try {
|
||||||
const client = new CartesiaClient({ apiKey: api_key });
|
const client = new CartesiaClient({ apiKey: api_key });
|
||||||
const sampleRate = 48000;
|
const sampleRate = 48000;
|
||||||
const mp3 = await client.tts.bytes({
|
const mp3Stream = await client.tts.bytes({
|
||||||
modelId: model_id,
|
modelId: model_id,
|
||||||
transcript: text,
|
transcript: text,
|
||||||
voice: {
|
voice: {
|
||||||
@@ -1174,13 +1354,20 @@ const synthCartesia = async(logger, {
|
|||||||
id: voice
|
id: voice
|
||||||
}
|
}
|
||||||
),
|
),
|
||||||
...(opts.speed || opts.emotion && {
|
...(model_id === 'sonic-2' && (opts.speed || opts.emotion) && {
|
||||||
experimentalControls: {
|
experimentalControls: {
|
||||||
...(opts.speed !== null && opts.speed !== undefined && {speed: opts.speed}),
|
...(opts.speed !== null && opts.speed !== undefined && {speed: opts.speed}),
|
||||||
...(opts.emotion && {emotion: opts.emotion}),
|
...(opts.emotion && {emotion: [opts.emotion]}),
|
||||||
}
|
}
|
||||||
})
|
}),
|
||||||
},
|
},
|
||||||
|
...(model_id === 'sonic-3' && (opts.speed || opts.emotion || opts.volume) && {
|
||||||
|
generationConfig: {
|
||||||
|
...(opts.volume !== null && opts.volume !== undefined && {volume: opts.volume}),
|
||||||
|
...(opts.speed !== null && opts.speed !== undefined && {speed: opts.speed}),
|
||||||
|
...(opts.emotion !== null && opts.emotion !== undefined && {emotion: opts.emotion}),
|
||||||
|
}
|
||||||
|
}),
|
||||||
language: language,
|
language: language,
|
||||||
outputFormat: {
|
outputFormat: {
|
||||||
container: 'mp3',
|
container: 'mp3',
|
||||||
@@ -1188,8 +1375,16 @@ const synthCartesia = async(logger, {
|
|||||||
sampleRate
|
sampleRate
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// bytes() returns a ReadableStream - collect all chunks
|
||||||
|
const chunks = [];
|
||||||
|
for await (const chunk of mp3Stream) {
|
||||||
|
chunks.push(chunk);
|
||||||
|
}
|
||||||
|
const audioBuffer = Buffer.concat(chunks);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
audioContent: Buffer.from(mp3),
|
audioContent: audioBuffer,
|
||||||
extension: 'mp3',
|
extension: 'mp3',
|
||||||
sampleRate
|
sampleRate
|
||||||
};
|
};
|
||||||
@@ -1201,6 +1396,63 @@ const synthCartesia = async(logger, {
|
|||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const synthResemble = async(logger, {
|
||||||
|
credentials, options, stats, voice, key, text, renderForCaching, disableTtsStreaming, disableTtsCache
|
||||||
|
}) => {
|
||||||
|
const {api_key, resemble_tts_uri, resemble_tts_use_tls} = credentials;
|
||||||
|
const {project_uuid, use_hd} = options || {};
|
||||||
|
|
||||||
|
/* default to using the streaming interface, unless disabled by env var OR we want just a cache file */
|
||||||
|
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
|
let params = '{';
|
||||||
|
params += `api_key=${api_key}`;
|
||||||
|
params += `,playback_id=${key}`;
|
||||||
|
params += ',vendor=resemble';
|
||||||
|
params += `,voice=${voice}`;
|
||||||
|
params += `,write_cache_file=${disableTtsCache ? 0 : 1}`;
|
||||||
|
if (project_uuid) params += `,project_uuid=${project_uuid}`;
|
||||||
|
if (use_hd) params += `,use_hd=${use_hd}`;
|
||||||
|
if (resemble_tts_uri) params += `,endpoint=${resemble_tts_uri}`;
|
||||||
|
if (resemble_tts_use_tls) params += `,use_tls=${resemble_tts_use_tls}`;
|
||||||
|
|
||||||
|
params += '}';
|
||||||
|
|
||||||
|
return {
|
||||||
|
filePath: `say:${params}${text.replace(/\n/g, ' ').replace(/\r/g, ' ')}`,
|
||||||
|
servedFromCache: false,
|
||||||
|
rtt: 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const baseUrl = resemble_tts_uri || 'https://f.cluster.resemble.ai';
|
||||||
|
const post = bent(baseUrl, 'POST', 'buffer', {
|
||||||
|
'Authorization': `Bearer ${api_key}`,
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
});
|
||||||
|
const response = await post('/synthesize', {
|
||||||
|
voice_uuid: voice,
|
||||||
|
data: text,
|
||||||
|
sample_rate: 8000,
|
||||||
|
output_format: 'mp3',
|
||||||
|
...(project_uuid && {project_uuid}),
|
||||||
|
...(use_hd && {use_hd}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const json = JSON.parse(response.toString('utf8'));
|
||||||
|
const audioContent = Buffer.from(json.audio_content, 'base64');
|
||||||
|
return {
|
||||||
|
audioContent,
|
||||||
|
extension: 'mp3',
|
||||||
|
sampleRate: 8000
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
logger.info({err}, 'synth Elevenlabs returned error');
|
||||||
|
stats.increment('tts.count', ['vendor:elevenlabs', 'accepted:no']);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const getFileExtFromMime = (mime) => {
|
const getFileExtFromMime = (mime) => {
|
||||||
switch (mime) {
|
switch (mime) {
|
||||||
case 'audio/wav':
|
case 'audio/wav':
|
||||||
|
|||||||
+4
-9
@@ -23,10 +23,11 @@ function makeSynthKey({
|
|||||||
voice,
|
voice,
|
||||||
engine = '',
|
engine = '',
|
||||||
model = '',
|
model = '',
|
||||||
text
|
text,
|
||||||
|
instructions = '',
|
||||||
}) {
|
}) {
|
||||||
const hash = crypto.createHash('sha1');
|
const hash = crypto.createHash('sha1');
|
||||||
hash.update(`${language}:${vendor}:${voice}:${engine}:${model}:${text}`);
|
hash.update(`${language}:${vendor}:${voice}:${engine}:${model}:${text}:${instructions}`);
|
||||||
const hexHashKey = hash.digest('hex');
|
const hexHashKey = hash.digest('hex');
|
||||||
const accountKey = account_sid ? `:${account_sid}` : '';
|
const accountKey = account_sid ? `:${account_sid}` : '';
|
||||||
const key = `tts${accountKey}:${hexHashKey}`;
|
const key = `tts${accountKey}:${hexHashKey}`;
|
||||||
@@ -53,12 +54,6 @@ function makeBasicAuthHeader(username, password) {
|
|||||||
return {Authorization: header};
|
return {Authorization: header};
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeIbmKey(apiKey) {
|
|
||||||
const hash = crypto.createHash('sha1');
|
|
||||||
hash.update(apiKey);
|
|
||||||
return `ibm:${hash.digest('hex')}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeAwsKey(awsAccessKeyId) {
|
function makeAwsKey(awsAccessKeyId) {
|
||||||
const hash = crypto.createHash('sha1');
|
const hash = crypto.createHash('sha1');
|
||||||
hash.update(awsAccessKeyId);
|
hash.update(awsAccessKeyId);
|
||||||
@@ -142,7 +137,7 @@ const createRivaClient = async(rivaUri) => {
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
makeSynthKey,
|
makeSynthKey,
|
||||||
makeNuanceKey,
|
makeNuanceKey,
|
||||||
makeIbmKey,
|
|
||||||
makePlayhtKey,
|
makePlayhtKey,
|
||||||
makeAwsKey,
|
makeAwsKey,
|
||||||
makeVerbioKey,
|
makeVerbioKey,
|
||||||
|
|||||||
Generated
+3031
-3292
File diff suppressed because it is too large
Load Diff
+6
-6
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@jambonz/speech-utils",
|
"name": "@jambonz/speech-utils",
|
||||||
"version": "0.2.8",
|
"version": "1.0.1",
|
||||||
"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",
|
||||||
@@ -26,23 +26,23 @@
|
|||||||
},
|
},
|
||||||
"homepage": "https://github.com/jambonz/speech-utils#readme",
|
"homepage": "https://github.com/jambonz/speech-utils#readme",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"23": "^0.0.0",
|
||||||
"@aws-sdk/client-polly": "^3.496.0",
|
"@aws-sdk/client-polly": "^3.496.0",
|
||||||
"@aws-sdk/client-sts": "^3.496.0",
|
"@aws-sdk/client-sts": "^3.496.0",
|
||||||
"@cartesia/cartesia-js": "^2.1.0",
|
"@cartesia/cartesia-js": "^2.2.7",
|
||||||
"@google-cloud/text-to-speech": "^5.5.0",
|
"@google-cloud/text-to-speech": "^6.4.0",
|
||||||
"@grpc/grpc-js": "^1.9.14",
|
"@grpc/grpc-js": "^1.9.14",
|
||||||
"@jambonz/realtimedb-helpers": "^0.8.7",
|
"@jambonz/realtimedb-helpers": "^0.8.7",
|
||||||
"bent": "^7.3.12",
|
"bent": "^7.3.12",
|
||||||
"debug": "^4.3.4",
|
"debug": "^4.3.4",
|
||||||
"form-urlencoded": "^6.1.4",
|
"form-urlencoded": "^6.1.4",
|
||||||
"google-protobuf": "^3.21.2",
|
"google-protobuf": "^3.21.2",
|
||||||
"ibm-watson": "^8.0.0",
|
|
||||||
"microsoft-cognitiveservices-speech-sdk": "1.38.0",
|
"microsoft-cognitiveservices-speech-sdk": "1.38.0",
|
||||||
"openai": "^4.25.0",
|
"openai": "^4.98.0",
|
||||||
"undici": "^7.5.0"
|
"undici": "^7.5.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"config": "^3.3.11",
|
"config": "^4.2.0",
|
||||||
"eslint": "^9.3.0",
|
"eslint": "^9.3.0",
|
||||||
"eslint-plugin-promise": "^6.2.0",
|
"eslint-plugin-promise": "^6.2.0",
|
||||||
"husky": "^9.0.11",
|
"husky": "^9.0.11",
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ const test = require('tape').test ;
|
|||||||
const exec = require('child_process').exec ;
|
const exec = require('child_process').exec ;
|
||||||
|
|
||||||
test('starting docker network..', (t) => {
|
test('starting docker network..', (t) => {
|
||||||
exec(`docker-compose -f ${__dirname}/docker-compose-testbed.yaml up -d`, (err, stdout, stderr) => {
|
exec(`docker compose -f ${__dirname}/docker-compose-testbed.yaml up -d`, (err, stdout, stderr) => {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
t.end(err);
|
t.end(err);
|
||||||
}, 2000);
|
}, 2000);
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@ const exec = require('child_process').exec ;
|
|||||||
|
|
||||||
test('stopping docker network..', (t) => {
|
test('stopping docker network..', (t) => {
|
||||||
t.timeoutAfter(10000);
|
t.timeoutAfter(10000);
|
||||||
exec(`docker-compose -f ${__dirname}/docker-compose-testbed.yaml down`, (err, stdout, stderr) => {
|
exec(`docker compose -f ${__dirname}/docker-compose-testbed.yaml down`, (err, stdout, stderr) => {
|
||||||
//console.log(`stderr: ${stderr}`);
|
//console.log(`stderr: ${stderr}`);
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
|
|||||||
-78
@@ -1,78 +0,0 @@
|
|||||||
const test = require('tape').test ;
|
|
||||||
const config = require('config');
|
|
||||||
const opts = config.get('redis');
|
|
||||||
const fs = require('fs');
|
|
||||||
const logger = require('pino')({level: 'error'});
|
|
||||||
process.on('unhandledRejection', (reason, p) => {
|
|
||||||
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
|
|
||||||
});
|
|
||||||
|
|
||||||
const stats = {
|
|
||||||
increment: () => {},
|
|
||||||
histogram: () => {}
|
|
||||||
};
|
|
||||||
|
|
||||||
test('IBM - create access key', async(t) => {
|
|
||||||
const fn = require('..');
|
|
||||||
const {client, getIbmAccessToken} = fn(opts, logger);
|
|
||||||
|
|
||||||
if (!process.env.IBM_API_KEY ) {
|
|
||||||
t.pass('skipping IBM test since no IBM api_key provided');
|
|
||||||
t.end();
|
|
||||||
client.quit();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
let obj = await getIbmAccessToken(process.env.IBM_API_KEY);
|
|
||||||
//console.log({obj}, 'received access token from IBM');
|
|
||||||
t.ok(obj.access_token && !obj.servedFromCache, 'successfull received access token from IBM');
|
|
||||||
|
|
||||||
obj = await getIbmAccessToken(process.env.IBM_API_KEY);
|
|
||||||
//console.log({obj}, 'received access token from IBM - second request');
|
|
||||||
t.ok(obj.access_token && obj.servedFromCache, 'successfully received access token from cache');
|
|
||||||
|
|
||||||
await client.flushall();
|
|
||||||
t.end();
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
t.end(err);
|
|
||||||
}
|
|
||||||
client.quit();
|
|
||||||
});
|
|
||||||
|
|
||||||
test('IBM - retrieve tts voices test', async(t) => {
|
|
||||||
const fn = require('..');
|
|
||||||
const {client, getTtsVoices} = fn(opts, logger);
|
|
||||||
|
|
||||||
if (!process.env.IBM_TTS_API_KEY || !process.env.IBM_TTS_REGION) {
|
|
||||||
t.pass('skipping IBM test since no IBM api_key and/or region provided');
|
|
||||||
t.end();
|
|
||||||
client.quit();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const opts = {
|
|
||||||
vendor: 'ibm',
|
|
||||||
credentials: {
|
|
||||||
tts_api_key: process.env.IBM_TTS_API_KEY,
|
|
||||||
tts_region: process.env.IBM_TTS_REGION
|
|
||||||
}
|
|
||||||
};
|
|
||||||
const obj = await getTtsVoices(opts);
|
|
||||||
const {voices} = obj.result;
|
|
||||||
//console.log(JSON.stringify(voices));
|
|
||||||
t.ok(voices.length > 0 && voices[0].language,
|
|
||||||
`GetVoices: successfully retrieved ${voices.length} voices from IBM`);
|
|
||||||
|
|
||||||
await client.flushall();
|
|
||||||
|
|
||||||
t.end();
|
|
||||||
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
t.end(err);
|
|
||||||
}
|
|
||||||
client.quit();
|
|
||||||
});
|
|
||||||
+1
-1
@@ -2,6 +2,6 @@ require('./docker_start');
|
|||||||
require('./synth');
|
require('./synth');
|
||||||
require('./list-voices');
|
require('./list-voices');
|
||||||
require('./aws');
|
require('./aws');
|
||||||
require('./ibm');
|
|
||||||
require('./nuance');
|
require('./nuance');
|
||||||
require('./docker_stop');
|
require('./docker_stop');
|
||||||
|
|||||||
@@ -38,71 +38,6 @@ test('Verbio - get Access key and voices', async(t) => {
|
|||||||
client.quit();
|
client.quit();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('IBM - create access key', async(t) => {
|
|
||||||
const fn = require('..');
|
|
||||||
const {client, getIbmAccessToken} = fn(opts, logger);
|
|
||||||
|
|
||||||
if (!process.env.IBM_API_KEY ) {
|
|
||||||
t.pass('skipping IBM test since no IBM api_key provided');
|
|
||||||
t.end();
|
|
||||||
client.quit();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
let obj = await getIbmAccessToken(process.env.IBM_API_KEY);
|
|
||||||
//console.log({obj}, 'received access token from IBM');
|
|
||||||
t.ok(obj.access_token && !obj.servedFromCache, 'successfull received access token from IBM');
|
|
||||||
|
|
||||||
obj = await getIbmAccessToken(process.env.IBM_API_KEY);
|
|
||||||
//console.log({obj}, 'received access token from IBM - second request');
|
|
||||||
t.ok(obj.access_token && obj.servedFromCache, 'successfully received access token from cache');
|
|
||||||
|
|
||||||
await client.flushall();
|
|
||||||
t.end();
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
t.end(err);
|
|
||||||
}
|
|
||||||
client.quit();
|
|
||||||
});
|
|
||||||
|
|
||||||
test('IBM - retrieve tts voices test', async(t) => {
|
|
||||||
const fn = require('..');
|
|
||||||
const {client, getTtsVoices} = fn(opts, logger);
|
|
||||||
|
|
||||||
if (!process.env.IBM_TTS_API_KEY || !process.env.IBM_TTS_REGION) {
|
|
||||||
t.pass('skipping IBM test since no IBM api_key and/or region provided');
|
|
||||||
t.end();
|
|
||||||
client.quit();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const opts = {
|
|
||||||
vendor: 'ibm',
|
|
||||||
credentials: {
|
|
||||||
tts_api_key: process.env.IBM_TTS_API_KEY,
|
|
||||||
tts_region: process.env.IBM_TTS_REGION
|
|
||||||
}
|
|
||||||
};
|
|
||||||
const obj = await getTtsVoices(opts);
|
|
||||||
const {voices} = obj.result;
|
|
||||||
//console.log(JSON.stringify(voices));
|
|
||||||
t.ok(voices.length > 0 && voices[0].language,
|
|
||||||
`GetVoices: successfully retrieved ${voices.length} voices from IBM`);
|
|
||||||
|
|
||||||
await client.flushall();
|
|
||||||
|
|
||||||
t.end();
|
|
||||||
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
t.end(err);
|
|
||||||
}
|
|
||||||
client.quit();
|
|
||||||
});
|
|
||||||
|
|
||||||
test('Nuance hosted tests', async(t) => {
|
test('Nuance hosted tests', async(t) => {
|
||||||
const fn = require('..');
|
const fn = require('..');
|
||||||
const {client, getTtsVoices} = fn(opts, logger);
|
const {client, getTtsVoices} = fn(opts, logger);
|
||||||
|
|||||||
+446
-48
@@ -41,6 +41,7 @@ test('Google speech synth tests', async(t) => {
|
|||||||
gender: 'FEMALE',
|
gender: 'FEMALE',
|
||||||
text: 'This is a test. This is only a test',
|
text: 'This is a test. This is only a test',
|
||||||
salt: 'foo.bar',
|
salt: 'foo.bar',
|
||||||
|
renderForCaching: true,
|
||||||
});
|
});
|
||||||
t.ok(!opts.servedFromCache, `successfully synthesized google audio to ${opts.filePath}`);
|
t.ok(!opts.servedFromCache, `successfully synthesized google audio to ${opts.filePath}`);
|
||||||
|
|
||||||
@@ -55,6 +56,7 @@ test('Google speech synth tests', async(t) => {
|
|||||||
language: 'en-GB',
|
language: 'en-GB',
|
||||||
gender: 'FEMALE',
|
gender: 'FEMALE',
|
||||||
text: 'This is a test. This is only a test',
|
text: 'This is a test. This is only a test',
|
||||||
|
renderForCaching: true,
|
||||||
});
|
});
|
||||||
t.ok(opts.servedFromCache, `successfully retrieved cached google audio from ${opts.filePath}`);
|
t.ok(opts.servedFromCache, `successfully retrieved cached google audio from ${opts.filePath}`);
|
||||||
|
|
||||||
@@ -78,6 +80,7 @@ test('Google speech synth tests', async(t) => {
|
|||||||
language: 'en-GB',
|
language: 'en-GB',
|
||||||
gender: 'FEMALE',
|
gender: 'FEMALE',
|
||||||
text: 'This is a test. This is only a test',
|
text: 'This is a test. This is only a test',
|
||||||
|
renderForCaching: true,
|
||||||
});
|
});
|
||||||
t.ok(!opts.servedFromCache, `successfully synthesized google audio regardless of current cache to ${opts.filePath}`);
|
t.ok(!opts.servedFromCache, `successfully synthesized google audio regardless of current cache to ${opts.filePath}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -114,7 +117,8 @@ GCP_CUSTOM_VOICE_FILE nor GCP_CUSTOM_VOICE_JSON_KEY provided, GCP_CUSTOM_VOICE_M
|
|||||||
voice: {
|
voice: {
|
||||||
reportedUsage: 'REALTIME',
|
reportedUsage: 'REALTIME',
|
||||||
model: process.env.GCP_CUSTOM_VOICE_MODEL
|
model: process.env.GCP_CUSTOM_VOICE_MODEL
|
||||||
}
|
},
|
||||||
|
renderForCaching: true,
|
||||||
});
|
});
|
||||||
t.ok(!opts.servedFromCache, `successfully synthesized google custom voice audio to ${opts.filePath}`);
|
t.ok(!opts.servedFromCache, `successfully synthesized google custom voice audio to ${opts.filePath}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -132,7 +136,7 @@ test('Google speech voice cloning synth tests', async(t) => {
|
|||||||
!process.env.GCP_CUSTOM_VOICE_JSON_KEY ||
|
!process.env.GCP_CUSTOM_VOICE_JSON_KEY ||
|
||||||
!process.env.GCP_VOICE_CLONING_FILE &&
|
!process.env.GCP_VOICE_CLONING_FILE &&
|
||||||
!process.env.GCP_VOICE_CLONING_JSON_KEY) {
|
!process.env.GCP_VOICE_CLONING_JSON_KEY) {
|
||||||
t.pass(`skipping google speech synth tests since neither
|
t.pass(`skipping google speech synth tests since neither
|
||||||
GCP_CUSTOM_VOICE_FILE nor GCP_CUSTOM_VOICE_JSON_KEY provided,
|
GCP_CUSTOM_VOICE_FILE nor GCP_CUSTOM_VOICE_JSON_KEY provided,
|
||||||
GCP_VOICE_CLONING_FILE nor GCP_VOICE_CLONING_JSON_KEY is not provided`);
|
GCP_VOICE_CLONING_FILE nor GCP_VOICE_CLONING_JSON_KEY is not provided`);
|
||||||
return t.end();
|
return t.end();
|
||||||
@@ -156,7 +160,8 @@ GCP_VOICE_CLONING_FILE nor GCP_VOICE_CLONING_JSON_KEY is not provided`);
|
|||||||
text: 'This is a test. This is only a test. This is a test. This is only a test. This is a test. This is only a test',
|
text: 'This is a test. This is only a test. This is a test. This is only a test. This is a test. This is only a test',
|
||||||
voice: {
|
voice: {
|
||||||
voice_cloning_key
|
voice_cloning_key
|
||||||
}
|
},
|
||||||
|
renderForCaching: true,
|
||||||
});
|
});
|
||||||
t.ok(!opts.servedFromCache, `successfully synthesized google voice cloning audio to ${opts.filePath}`);
|
t.ok(!opts.servedFromCache, `successfully synthesized google voice cloning audio to ${opts.filePath}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -166,6 +171,374 @@ GCP_VOICE_CLONING_FILE nor GCP_VOICE_CLONING_JSON_KEY is not provided`);
|
|||||||
client.quit();
|
client.quit();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Google Gemini TTS synth tests', async(t) => {
|
||||||
|
const fn = require('..');
|
||||||
|
const {synthAudio, client} = fn(opts, logger);
|
||||||
|
|
||||||
|
if (!process.env.GCP_FILE && !process.env.GCP_JSON_KEY) {
|
||||||
|
t.pass('skipping Google Gemini TTS synth tests since neither GCP_FILE nor GCP_JSON_KEY provided');
|
||||||
|
return t.end();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const str = process.env.GCP_JSON_KEY || fs.readFileSync(process.env.GCP_FILE);
|
||||||
|
const creds = JSON.parse(str);
|
||||||
|
const geminiModel = process.env.GCP_GEMINI_TTS_MODEL || 'gemini-2.5-flash-tts';
|
||||||
|
|
||||||
|
// Test Gemini TTS with model and instructions (both required for Gemini)
|
||||||
|
let result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'Kore',
|
||||||
|
model: geminiModel,
|
||||||
|
text: 'Hello, this is a test of Google Gemini text to speech.',
|
||||||
|
instructions: 'Speak clearly and naturally.',
|
||||||
|
renderForCaching: true,
|
||||||
|
});
|
||||||
|
t.ok(!result.servedFromCache, `successfully synthesized Google Gemini TTS audio to ${result.filePath}`);
|
||||||
|
t.ok(result.filePath.endsWith('.mp3'), 'Gemini TTS audio file has correct extension');
|
||||||
|
|
||||||
|
// Test Gemini TTS with different voice and instructions
|
||||||
|
result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'Charon',
|
||||||
|
model: geminiModel,
|
||||||
|
text: 'Welcome to our service. How can I help you today?',
|
||||||
|
instructions: 'Speak in a warm, friendly and professional tone.',
|
||||||
|
renderForCaching: true,
|
||||||
|
});
|
||||||
|
t.ok(!result.servedFromCache, `successfully synthesized Gemini TTS with instructions to ${result.filePath}`);
|
||||||
|
|
||||||
|
// Test cache retrieval
|
||||||
|
result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'Kore',
|
||||||
|
model: geminiModel,
|
||||||
|
text: 'Hello, this is a test of Google Gemini text to speech.',
|
||||||
|
instructions: 'Speak clearly and naturally.',
|
||||||
|
renderForCaching: true,
|
||||||
|
});
|
||||||
|
t.ok(result.servedFromCache, `successfully retrieved Gemini TTS audio from cache ${result.filePath}`);
|
||||||
|
|
||||||
|
// Test SSML stripping (Gemini doesn't support SSML)
|
||||||
|
result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'Leda',
|
||||||
|
model: geminiModel,
|
||||||
|
text: '<speak>This SSML should be stripped for Gemini TTS.</speak>',
|
||||||
|
instructions: 'Speak naturally.',
|
||||||
|
disableTtsCache: true,
|
||||||
|
renderForCaching: true,
|
||||||
|
});
|
||||||
|
t.ok(!result.servedFromCache, `successfully synthesized Gemini TTS with SSML stripped to ${result.filePath}`);
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
t.end(err);
|
||||||
|
}
|
||||||
|
client.quit();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Google TTS streaming tests (!JAMBONES_DISABLE_TTS_STREAMING)', async(t) => {
|
||||||
|
// Ensure streaming is enabled (default behavior)
|
||||||
|
delete process.env.JAMBONES_DISABLE_TTS_STREAMING;
|
||||||
|
|
||||||
|
// Clear require cache to reload config with new env var
|
||||||
|
delete require.cache[require.resolve('../lib/config')];
|
||||||
|
delete require.cache[require.resolve('../lib/synth-audio')];
|
||||||
|
delete require.cache[require.resolve('..')];
|
||||||
|
|
||||||
|
const fn = require('..');
|
||||||
|
const {synthAudio, client} = fn(opts, logger);
|
||||||
|
|
||||||
|
if (!process.env.GCP_FILE && !process.env.GCP_JSON_KEY) {
|
||||||
|
t.pass('skipping Google TTS streaming tests since neither GCP_FILE nor GCP_JSON_KEY provided');
|
||||||
|
return t.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const str = process.env.GCP_JSON_KEY || fs.readFileSync(process.env.GCP_FILE);
|
||||||
|
const creds = JSON.parse(str);
|
||||||
|
const geminiModel = process.env.GCP_GEMINI_TTS_MODEL || 'gemini-2.5-flash-tts';
|
||||||
|
|
||||||
|
// Test 1: Standard voice streaming (use_live_api=0)
|
||||||
|
let result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'en-US-Wavenet-D',
|
||||||
|
gender: 'MALE',
|
||||||
|
text: 'This is a test of standard voice streaming.',
|
||||||
|
disableTtsCache: true
|
||||||
|
});
|
||||||
|
t.ok(result.filePath.startsWith('say:'), 'Standard voice returns streaming say: path');
|
||||||
|
t.ok(result.filePath.includes('vendor=google'), 'Standard voice streaming path contains vendor=google');
|
||||||
|
t.ok(result.filePath.includes('api_mode=tts'), 'Standard voice uses api_mode=tts');
|
||||||
|
t.ok(result.filePath.includes('voice=en-US-Wavenet-D'), 'Standard voice streaming path contains voice');
|
||||||
|
// Verify credentials are base64 encoded (no raw JSON braces that would break FreeSWitch parsing)
|
||||||
|
t.ok(result.filePath.includes('credentials='), 'Standard voice streaming path contains credentials');
|
||||||
|
t.ok(!result.filePath.includes('credentials={'), 'Credentials are not raw JSON (base64 encoded)');
|
||||||
|
|
||||||
|
// Test 2: HD voice streaming (api_mode=live)
|
||||||
|
result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'en-US-Chirp3-HD-Charon',
|
||||||
|
text: 'This is a test of HD voice streaming.',
|
||||||
|
disableTtsCache: true
|
||||||
|
});
|
||||||
|
t.ok(result.filePath.startsWith('say:'), 'HD voice returns streaming say: path');
|
||||||
|
t.ok(result.filePath.includes('vendor=google'), 'HD voice streaming path contains vendor=google');
|
||||||
|
t.ok(result.filePath.includes('api_mode=live'), 'HD voice uses api_mode=live');
|
||||||
|
t.ok(result.filePath.includes('voice=en-US-Chirp3-HD-Charon'), 'HD voice streaming path contains voice');
|
||||||
|
|
||||||
|
// Test 3: Gemini TTS streaming (api_mode=gemini)
|
||||||
|
result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'Kore',
|
||||||
|
model: geminiModel,
|
||||||
|
text: 'This is a test of Gemini TTS streaming.',
|
||||||
|
instructions: 'Speak naturally.',
|
||||||
|
disableTtsCache: true
|
||||||
|
});
|
||||||
|
t.ok(result.filePath.startsWith('say:'), 'Gemini TTS returns streaming say: path');
|
||||||
|
t.ok(result.filePath.includes('vendor=google'), 'Gemini TTS streaming path contains vendor=google');
|
||||||
|
t.ok(result.filePath.includes('api_mode=gemini'), 'Gemini TTS uses api_mode=gemini');
|
||||||
|
t.ok(result.filePath.includes(`model_name=${geminiModel}`), 'Gemini TTS streaming path contains model_name');
|
||||||
|
t.ok(result.filePath.includes('prompt=Speak naturally.'), 'Gemini TTS streaming path contains prompt');
|
||||||
|
|
||||||
|
// Test 4: Gemini TTS with SSML stripping in streaming mode
|
||||||
|
result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'Leda',
|
||||||
|
model: geminiModel,
|
||||||
|
text: '<speak>This SSML should be stripped.</speak>',
|
||||||
|
instructions: 'Speak naturally.',
|
||||||
|
disableTtsCache: true
|
||||||
|
});
|
||||||
|
t.ok(result.filePath.startsWith('say:'), 'Gemini TTS with SSML returns streaming say: path');
|
||||||
|
t.ok(!result.filePath.includes('<speak>'), 'SSML tags are stripped from streaming path');
|
||||||
|
t.ok(result.filePath.includes('This SSML should be stripped.'), 'Text content is preserved after SSML stripping');
|
||||||
|
|
||||||
|
// Test 5: Gemini TTS with prompt containing special characters
|
||||||
|
result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'Kore',
|
||||||
|
model: geminiModel,
|
||||||
|
text: 'Testing special characters in prompt.',
|
||||||
|
options: { prompt: 'Speak in a warm, friendly tone' },
|
||||||
|
disableTtsCache: true
|
||||||
|
});
|
||||||
|
t.ok(result.filePath.startsWith('say:'), 'Gemini TTS with special chars returns streaming say: path');
|
||||||
|
// Commas in prompt should be replaced with semicolons
|
||||||
|
t.ok(result.filePath.includes('prompt=Speak in a warm; friendly tone'), 'Commas in prompt are escaped to semicolons');
|
||||||
|
|
||||||
|
// Test 6: options.apiMode override (force live on standard voice)
|
||||||
|
result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'en-US-Wavenet-D',
|
||||||
|
text: 'Testing apiMode option override to live.',
|
||||||
|
options: { apiMode: 'live' },
|
||||||
|
disableTtsCache: true
|
||||||
|
});
|
||||||
|
t.ok(result.filePath.includes('api_mode=live'), 'options.apiMode=live overrides default for standard voice');
|
||||||
|
|
||||||
|
// Test 7: options.apiMode override (force gemini without model)
|
||||||
|
result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'Kore',
|
||||||
|
text: 'Testing apiMode option override to gemini.',
|
||||||
|
options: { apiMode: 'gemini' },
|
||||||
|
disableTtsCache: true
|
||||||
|
});
|
||||||
|
t.ok(result.filePath.includes('api_mode=gemini'), 'options.apiMode=gemini overrides default');
|
||||||
|
|
||||||
|
// Test 8: options.apiMode override (force tts on HD voice)
|
||||||
|
result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'en-US-Chirp3-HD-Charon',
|
||||||
|
text: 'Testing apiMode option override to tts on HD voice.',
|
||||||
|
options: { apiMode: 'tts' },
|
||||||
|
disableTtsCache: true
|
||||||
|
});
|
||||||
|
t.ok(result.filePath.includes('api_mode=tts'), 'options.apiMode=tts overrides HD voice default');
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
t.end(err);
|
||||||
|
}
|
||||||
|
client.quit();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Google TTS non-streaming tests (JAMBONES_DISABLE_TTS_STREAMING=true)', async(t) => {
|
||||||
|
// Enable streaming disable flag
|
||||||
|
process.env.JAMBONES_DISABLE_TTS_STREAMING = 'true';
|
||||||
|
|
||||||
|
// Clear require cache to reload config with new env var
|
||||||
|
delete require.cache[require.resolve('../lib/config')];
|
||||||
|
delete require.cache[require.resolve('../lib/synth-audio')];
|
||||||
|
delete require.cache[require.resolve('..')];
|
||||||
|
|
||||||
|
const fn = require('..');
|
||||||
|
const {synthAudio, client} = fn(opts, logger);
|
||||||
|
|
||||||
|
if (!process.env.GCP_FILE && !process.env.GCP_JSON_KEY) {
|
||||||
|
t.pass('skipping Google TTS non-streaming tests since neither GCP_FILE nor GCP_JSON_KEY provided');
|
||||||
|
delete process.env.JAMBONES_DISABLE_TTS_STREAMING;
|
||||||
|
return t.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const str = process.env.GCP_JSON_KEY || fs.readFileSync(process.env.GCP_FILE);
|
||||||
|
const creds = JSON.parse(str);
|
||||||
|
const geminiModel = process.env.GCP_GEMINI_TTS_MODEL || 'gemini-2.5-flash-tts';
|
||||||
|
|
||||||
|
// Test 1: Standard voice falls back to non-streaming API
|
||||||
|
let result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'en-US-Wavenet-D',
|
||||||
|
gender: 'MALE',
|
||||||
|
text: 'This is a test with streaming disabled.',
|
||||||
|
disableTtsCache: true
|
||||||
|
});
|
||||||
|
t.ok(!result.filePath.startsWith('say:'), 'Standard voice does NOT return streaming say: path when disabled');
|
||||||
|
t.ok(result.filePath.endsWith('.mp3'), 'Standard voice returns mp3 file path');
|
||||||
|
|
||||||
|
// Test 2: HD voice falls back to non-streaming API
|
||||||
|
result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'en-US-Chirp3-HD-Charon',
|
||||||
|
text: 'This is a test of HD voice with streaming disabled.',
|
||||||
|
disableTtsCache: true
|
||||||
|
});
|
||||||
|
t.ok(!result.filePath.startsWith('say:'), 'HD voice does NOT return streaming say: path when disabled');
|
||||||
|
t.ok(result.filePath.endsWith('.mp3'), 'HD voice returns mp3 file path');
|
||||||
|
|
||||||
|
// Test 3: Gemini TTS falls back to non-streaming API
|
||||||
|
result = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'Kore',
|
||||||
|
model: geminiModel,
|
||||||
|
text: 'This is a test of Gemini TTS with streaming disabled.',
|
||||||
|
instructions: 'Speak naturally.',
|
||||||
|
disableTtsCache: true
|
||||||
|
});
|
||||||
|
t.ok(!result.filePath.startsWith('say:'), 'Gemini TTS does NOT return streaming say: path when disabled');
|
||||||
|
t.ok(result.filePath.endsWith('.mp3'), 'Gemini TTS returns mp3 file path');
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
t.end(err);
|
||||||
|
} finally {
|
||||||
|
// Clean up: restore default behavior
|
||||||
|
delete process.env.JAMBONES_DISABLE_TTS_STREAMING;
|
||||||
|
delete require.cache[require.resolve('../lib/config')];
|
||||||
|
delete require.cache[require.resolve('../lib/synth-audio')];
|
||||||
|
delete require.cache[require.resolve('..')];
|
||||||
|
}
|
||||||
|
client.quit();
|
||||||
|
});
|
||||||
|
|
||||||
test('AWS speech synth tests', async(t) => {
|
test('AWS speech synth tests', async(t) => {
|
||||||
const fn = require('..');
|
const fn = require('..');
|
||||||
const {synthAudio, client} = fn(opts, logger);
|
const {synthAudio, client} = fn(opts, logger);
|
||||||
@@ -185,6 +558,7 @@ test('AWS speech synth tests', async(t) => {
|
|||||||
language: 'en-US',
|
language: 'en-US',
|
||||||
voice: 'Joey',
|
voice: 'Joey',
|
||||||
text: 'This is a test. This is only a test',
|
text: 'This is a test. This is only a test',
|
||||||
|
renderForCaching: true,
|
||||||
});
|
});
|
||||||
t.ok(!opts.servedFromCache, `successfully synthesized aws audio to ${opts.filePath}`);
|
t.ok(!opts.servedFromCache, `successfully synthesized aws audio to ${opts.filePath}`);
|
||||||
|
|
||||||
@@ -198,6 +572,7 @@ test('AWS speech synth tests', async(t) => {
|
|||||||
language: 'en-US',
|
language: 'en-US',
|
||||||
voice: 'Joey',
|
voice: 'Joey',
|
||||||
text: 'This is a test. This is only a test',
|
text: 'This is a test. This is only a test',
|
||||||
|
renderForCaching: true,
|
||||||
});
|
});
|
||||||
t.ok(opts.servedFromCache, `successfully retrieved aws audio from cache ${opts.filePath}`);
|
t.ok(opts.servedFromCache, `successfully retrieved aws audio from cache ${opts.filePath}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -497,46 +872,6 @@ test('Nvidia speech synth tests', async(t) => {
|
|||||||
client.quit();
|
client.quit();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('IBM watson speech synth tests', async(t) => {
|
|
||||||
const fn = require('..');
|
|
||||||
const {synthAudio, client} = fn(opts, logger);
|
|
||||||
|
|
||||||
if (!process.env.IBM_TTS_API_KEY || !process.env.IBM_TTS_REGION) {
|
|
||||||
t.pass('skipping IBM Watson speech synth tests since IBM_TTS_API_KEY or IBM_TTS_API_KEY not provided');
|
|
||||||
return t.end();
|
|
||||||
}
|
|
||||||
const text = `<speak> Hi there and welcome to jambones! jambones is the <sub alias="seapass">CPaaS</sub> designed with the needs of communication service providers in mind. This is an example of simple text-to-speech, but there is so much more you can do. Try us out!</speak>`;
|
|
||||||
try {
|
|
||||||
let opts = await synthAudio(stats, {
|
|
||||||
vendor: 'ibm',
|
|
||||||
credentials: {
|
|
||||||
tts_api_key: process.env.IBM_TTS_API_KEY,
|
|
||||||
tts_region: process.env.IBM_TTS_REGION,
|
|
||||||
},
|
|
||||||
language: 'en-US',
|
|
||||||
voice: 'en-US_AllisonV2Voice',
|
|
||||||
text,
|
|
||||||
});
|
|
||||||
t.ok(!opts.servedFromCache, `successfully synthesized ibm audio to ${opts.filePath}`);
|
|
||||||
|
|
||||||
opts = await synthAudio(stats, {
|
|
||||||
vendor: 'ibm',
|
|
||||||
credentials: {
|
|
||||||
tts_api_key: process.env.IBM_TTS_API_KEY,
|
|
||||||
tts_region: process.env.IBM_TTS_REGION,
|
|
||||||
},
|
|
||||||
language: 'en-US',
|
|
||||||
voice: 'en-US_AllisonV2Voice',
|
|
||||||
text,
|
|
||||||
});
|
|
||||||
t.ok(opts.servedFromCache, `successfully retrieved ibm audio from cache ${opts.filePath}`);
|
|
||||||
} catch (err) {
|
|
||||||
console.error(JSON.stringify(err));
|
|
||||||
t.end(err);
|
|
||||||
}
|
|
||||||
client.quit();
|
|
||||||
});
|
|
||||||
|
|
||||||
test('Custom Vendor speech synth tests', async(t) => {
|
test('Custom Vendor speech synth tests', async(t) => {
|
||||||
const fn = require('..');
|
const fn = require('..');
|
||||||
const {synthAudio, client} = fn(opts, logger);
|
const {synthAudio, client} = fn(opts, logger);
|
||||||
@@ -552,6 +887,7 @@ test('Custom Vendor speech synth tests', async(t) => {
|
|||||||
language: 'en-US',
|
language: 'en-US',
|
||||||
voice: 'English-US.Female-1',
|
voice: 'English-US.Female-1',
|
||||||
text: 'This is a test. This is only a test',
|
text: 'This is a test. This is only a test',
|
||||||
|
renderForCaching: true
|
||||||
});
|
});
|
||||||
t.ok(!opts.servedFromCache, `successfully synthesized custom vendor audio to ${opts.filePath}`);
|
t.ok(!opts.servedFromCache, `successfully synthesized custom vendor audio to ${opts.filePath}`);
|
||||||
t.ok(opts.filePath.endsWith('wav'), 'audio is cached as wav file');
|
t.ok(opts.filePath.endsWith('wav'), 'audio is cached as wav file');
|
||||||
@@ -573,6 +909,7 @@ test('Custom Vendor speech synth tests', async(t) => {
|
|||||||
language: 'en-US',
|
language: 'en-US',
|
||||||
voice: 'English-US.Female-1',
|
voice: 'English-US.Female-1',
|
||||||
text: 'This is a test. This is only a test',
|
text: 'This is a test. This is only a test',
|
||||||
|
renderForCaching: true
|
||||||
});
|
});
|
||||||
t.ok(opts.servedFromCache, `successfully get custom vendor cached audio to ${opts.filePath}`);
|
t.ok(opts.servedFromCache, `successfully get custom vendor cached audio to ${opts.filePath}`);
|
||||||
t.ok(opts.filePath.endsWith('wav'), 'audio is cached as wav file');
|
t.ok(opts.filePath.endsWith('wav'), 'audio is cached as wav file');
|
||||||
@@ -587,6 +924,7 @@ test('Custom Vendor speech synth tests', async(t) => {
|
|||||||
language: 'en-US',
|
language: 'en-US',
|
||||||
voice: 'English-US.Female-1',
|
voice: 'English-US.Female-1',
|
||||||
text: '<speak>This is a test. This is only a test</speak>',
|
text: '<speak>This is a test. This is only a test</speak>',
|
||||||
|
renderForCaching: true
|
||||||
});
|
});
|
||||||
t.ok(!opts.servedFromCache, `successfully synthesized Custom Vendor audio to ${opts.filePath}`);
|
t.ok(!opts.servedFromCache, `successfully synthesized Custom Vendor audio to ${opts.filePath}`);
|
||||||
obj = await getJSON(`http://127.0.0.1:3100/lastRequest/somethingnew2`);
|
obj = await getJSON(`http://127.0.0.1:3100/lastRequest/somethingnew2`);
|
||||||
@@ -711,7 +1049,66 @@ test('Cartesia speech synth tests', async(t) => {
|
|||||||
text,
|
text,
|
||||||
renderForCaching: true
|
renderForCaching: true
|
||||||
});
|
});
|
||||||
t.ok(!opts.servedFromCache, `successfully playht eleven audio to ${opts.filePath}`);
|
t.ok(!opts.servedFromCache, `successfully cartesia eleven audio to ${opts.filePath}`);
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error(JSON.stringify(err));
|
||||||
|
t.end(err);
|
||||||
|
}
|
||||||
|
client.quit();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('inworld speech synth', async(t) => {
|
||||||
|
const fn = require('..');
|
||||||
|
const {synthAudio, client} = fn(opts, logger);
|
||||||
|
|
||||||
|
if (!process.env.INWORLD_API_KEY) {
|
||||||
|
t.pass('skipping inworld speech synth tests since INWORLD_API_KEY is not provided');
|
||||||
|
return t.end();
|
||||||
|
}
|
||||||
|
const text = 'Hi there and welcome to jambones!';
|
||||||
|
try {
|
||||||
|
const opts = await synthAudio(stats, {
|
||||||
|
vendor: 'inworld',
|
||||||
|
credentials: {
|
||||||
|
api_key: process.env.INWORLD_API_KEY,
|
||||||
|
model_id: 'inworld-tts-1'
|
||||||
|
},
|
||||||
|
language: 'en',
|
||||||
|
voice: 'Ashley',
|
||||||
|
text,
|
||||||
|
renderForCaching: true
|
||||||
|
});
|
||||||
|
t.ok(!opts.servedFromCache, `successfully synthesized inworld audio to ${opts.filePath}`);
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error(JSON.stringify(err));
|
||||||
|
t.end(err);
|
||||||
|
}
|
||||||
|
client.quit();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('resemble speech synth', async(t) => {
|
||||||
|
const fn = require('..');
|
||||||
|
const {synthAudio, client} = fn(opts, logger);
|
||||||
|
|
||||||
|
if (!process.env.RESEMBLE_API_KEY) {
|
||||||
|
t.pass('skipping resemble speech synth tests since RESEMBLE_API_KEY is not provided');
|
||||||
|
return t.end();
|
||||||
|
}
|
||||||
|
const text = '<speak prompt="Speak in an excited, upbeat tone">Hello from Resemble!</speak>';
|
||||||
|
try {
|
||||||
|
const opts = await synthAudio(stats, {
|
||||||
|
vendor: 'resemble',
|
||||||
|
credentials: {
|
||||||
|
api_key: process.env.RESEMBLE_API_KEY,
|
||||||
|
},
|
||||||
|
language: 'en',
|
||||||
|
voice: '3f5fb9f1',
|
||||||
|
text,
|
||||||
|
renderForCaching: true
|
||||||
|
});
|
||||||
|
t.ok(!opts.servedFromCache, `successfully synthesized resemble audio to ${opts.filePath}`);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(JSON.stringify(err));
|
console.error(JSON.stringify(err));
|
||||||
@@ -887,7 +1284,8 @@ test('TTS Cache tests', async(t) => {
|
|||||||
// 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.set(makeSynthKey({vendor: i, language: i, voice: i, engine: i, model: i, text: i}), i);
|
await client.set(makeSynthKey({vendor: i, language: i, voice: i, engine: i, model: i, text: i,
|
||||||
|
instructions: i}), i);
|
||||||
}
|
}
|
||||||
const count = await getTtsSize();
|
const count = await getTtsSize();
|
||||||
t.ok(count >= minRecords, 'getTtsSize worked.');
|
t.ok(count >= minRecords, 'getTtsSize worked.');
|
||||||
@@ -906,7 +1304,7 @@ 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.set(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, instructions: 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!'};
|
||||||
@@ -944,10 +1342,10 @@ 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.set(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, instructions: i}), i);
|
||||||
}
|
}
|
||||||
for (const i in Array(minRecords).fill(0)) {
|
for (const i in Array(minRecords).fill(0)) {
|
||||||
await client.set(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, instructions: 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}`);
|
||||||
|
|||||||
Reference in New Issue
Block a user