mirror of
https://github.com/jambonz/speech-utils.git
synced 2026-10-03 23:33:59 +00:00
Compare commits
39
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc211ab2e7 | ||
|
|
536f8aab31 | ||
|
|
69b3fdffbe | ||
|
|
53fe72d89e | ||
|
|
e79c15c5da | ||
|
|
a4a427e174 | ||
|
|
b697bc5268 | ||
|
|
d35d7f0aec | ||
|
|
ed1c564fa2 | ||
|
|
7189d471c1 | ||
|
|
04080cc5ec | ||
|
|
3e5ab4af27 | ||
|
|
f06dddd2f7 | ||
|
|
7b4a71f55d | ||
|
|
d552b65618 | ||
|
|
f701b50244 | ||
|
|
199e502fbe | ||
|
|
6769779189 | ||
|
|
4b43c3986c | ||
|
|
e1292772e6 | ||
|
|
37fb045431 | ||
|
|
c328df67a2 | ||
|
|
877cba7065 | ||
|
|
35a178b468 | ||
|
|
7327190471 | ||
|
|
e5b5e3d0c6 | ||
|
|
3760be088b | ||
|
|
5cb52eb8ec | ||
|
|
8a390a8edf | ||
|
|
d96ab5cdf3 | ||
|
|
3bf74671c6 | ||
|
|
a47ef6d7c4 | ||
|
|
84089fa528 | ||
|
|
72be44eea2 | ||
|
|
05d6c4b32d | ||
|
|
0c7e15d0a2 | ||
|
|
63efecf9d9 | ||
|
|
153ac3f1a4 | ||
|
|
115faa9f89 |
@@ -3,8 +3,29 @@ const {noopLogger, makeSynthKey} = require('./utils');
|
|||||||
const {JAMBONES_TTS_CACHE_DURATION_MINS} = require('./config');
|
const {JAMBONES_TTS_CACHE_DURATION_MINS} = require('./config');
|
||||||
const EXPIRES = JAMBONES_TTS_CACHE_DURATION_MINS;
|
const EXPIRES = JAMBONES_TTS_CACHE_DURATION_MINS;
|
||||||
|
|
||||||
|
function getExtensionAndSampleRate(path) {
|
||||||
|
const match = path.match(/\.([^.]*)$/);
|
||||||
|
if (!match) {
|
||||||
|
//default should be wav file.
|
||||||
|
return ['wav', 8000];
|
||||||
|
}
|
||||||
|
|
||||||
|
const extension = match[1];
|
||||||
|
const sampleRateMap = {
|
||||||
|
r8: 8000,
|
||||||
|
r16: 16000,
|
||||||
|
r24: 24000,
|
||||||
|
r44: 44100,
|
||||||
|
r48: 48000,
|
||||||
|
r96: 96000,
|
||||||
|
};
|
||||||
|
|
||||||
|
const sampleRate = sampleRateMap[extension] || 8000;
|
||||||
|
return [extension, sampleRate];
|
||||||
|
}
|
||||||
|
|
||||||
async function addFileToCache(client, logger, path,
|
async function addFileToCache(client, logger, path,
|
||||||
{account_sid, vendor, language, voice, deploymentId, engine, text}) {
|
{account_sid, vendor, language, voice, deploymentId, engine, model, text}) {
|
||||||
let key;
|
let key;
|
||||||
logger = logger || noopLogger;
|
logger = logger || noopLogger;
|
||||||
|
|
||||||
@@ -15,10 +36,18 @@ async function addFileToCache(client, logger, path,
|
|||||||
language: language || '',
|
language: language || '',
|
||||||
voice: voice || deploymentId,
|
voice: voice || deploymentId,
|
||||||
engine,
|
engine,
|
||||||
|
model,
|
||||||
text,
|
text,
|
||||||
});
|
});
|
||||||
|
const [extension, sampleRate] = getExtensionAndSampleRate(path);
|
||||||
const audioBuffer = await fs.readFile(path);
|
const audioBuffer = await fs.readFile(path);
|
||||||
await client.setex(key, EXPIRES, audioBuffer.toString('base64'));
|
await client.setex(key, EXPIRES, JSON.stringify(
|
||||||
|
{
|
||||||
|
audioContent: audioBuffer.toString('base64'),
|
||||||
|
extension,
|
||||||
|
sampleRate
|
||||||
|
}
|
||||||
|
));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error(err, 'addFileToCache: Error');
|
logger.error(err, 'addFileToCache: Error');
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -7,22 +7,23 @@ const CACHE_EXPIRY = process.env.AWS_STS_SESSION_RESET_EXPIRY || (EXPIRY - 600);
|
|||||||
|
|
||||||
async function getAwsAuthToken(
|
async function getAwsAuthToken(
|
||||||
logger, createHash, retrieveHash,
|
logger, createHash, retrieveHash,
|
||||||
{accessKeyId, secretAccessKey, region, roleArn}) {
|
{speech_credential_sid, accessKeyId, secretAccessKey, region, roleArn}) {
|
||||||
logger = logger || noopLogger;
|
logger = logger || noopLogger;
|
||||||
try {
|
try {
|
||||||
const key = makeAwsKey(roleArn || accessKeyId);
|
// if incase instance profile is used, speech_credential_sid will be used as key to lookup cache
|
||||||
|
const key = makeAwsKey(roleArn || accessKeyId || speech_credential_sid);
|
||||||
const obj = await retrieveHash(key);
|
const obj = await retrieveHash(key);
|
||||||
if (obj) return {...obj, servedFromCache: true};
|
if (obj) return {...obj, servedFromCache: true};
|
||||||
|
/* access token not found in cache, so generate it using STS */
|
||||||
let data;
|
let data;
|
||||||
|
let expiry = CACHE_EXPIRY;
|
||||||
if (roleArn) {
|
if (roleArn) {
|
||||||
const stsClient = new STSClient({ region });
|
const stsClient = new STSClient({ region });
|
||||||
const roleToAssume = { RoleArn: roleArn, RoleSessionName: 'Jambonz_Speech', DurationSeconds: EXPIRY};
|
const roleToAssume = { RoleArn: roleArn, RoleSessionName: 'Jambonz_Speech', DurationSeconds: EXPIRY};
|
||||||
const command = new AssumeRoleCommand(roleToAssume);
|
const command = new AssumeRoleCommand(roleToAssume);
|
||||||
|
|
||||||
data = await stsClient.send(command);
|
data = await stsClient.send(command);
|
||||||
} else {
|
} else if (accessKeyId) {
|
||||||
/* access token not found in cache, so generate it using STS */
|
|
||||||
const stsClient = new STSClient({
|
const stsClient = new STSClient({
|
||||||
region,
|
region,
|
||||||
credentials: {
|
credentials: {
|
||||||
@@ -32,6 +33,26 @@ async function getAwsAuthToken(
|
|||||||
});
|
});
|
||||||
const command = new GetSessionTokenCommand({DurationSeconds: EXPIRY});
|
const command = new GetSessionTokenCommand({DurationSeconds: EXPIRY});
|
||||||
data = await stsClient.send(command);
|
data = await stsClient.send(command);
|
||||||
|
} else {
|
||||||
|
// instance profile is used.
|
||||||
|
const stsClient = new STSClient({ region });
|
||||||
|
const cred = await stsClient.config.credentials();
|
||||||
|
// method in the AWS SDK automatically fetches credentials using the default credential
|
||||||
|
// provider chain. If the credentials come from an instance profile or an environment
|
||||||
|
// variable, their expiration is controlled by AWS and not explicitly by our code.
|
||||||
|
if (cred && cred.expiration) {
|
||||||
|
const currentTime = new Date();
|
||||||
|
const expiryTime = new Date(cred.expiration);
|
||||||
|
const remainingTimeInSeconds = Math.round((expiryTime - currentTime) / 1000);
|
||||||
|
expiry = remainingTimeInSeconds;
|
||||||
|
}
|
||||||
|
data = {
|
||||||
|
Credentials: {
|
||||||
|
AccessKeyId: cred.accessKeyId,
|
||||||
|
SecretAccessKey: cred.secretAccessKey,
|
||||||
|
SessionToken: cred.sessionToken
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const credentials = {
|
const credentials = {
|
||||||
@@ -40,9 +61,11 @@ async function getAwsAuthToken(
|
|||||||
sessionToken: data.Credentials.SessionToken,
|
sessionToken: data.Credentials.SessionToken,
|
||||||
securityToken: data.Credentials.SessionToken
|
securityToken: data.Credentials.SessionToken
|
||||||
};
|
};
|
||||||
|
// Only cache if expiry is good
|
||||||
createHash(key, credentials, CACHE_EXPIRY)
|
if (expiry > 0) {
|
||||||
.catch((err) => logger.error(err, `Error saving hash for key ${key}`));
|
createHash(key, credentials, expiry)
|
||||||
|
.catch((err) => logger.error(err, `Error saving hash for key ${key}`));
|
||||||
|
}
|
||||||
|
|
||||||
return {...credentials, servedFromCache: false};
|
return {...credentials, servedFromCache: false};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -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, text} = {all: true}) {
|
language, voice, deploymentId, engine, model, text} = {all: true}) {
|
||||||
logger = logger || noopLogger;
|
logger = logger || noopLogger;
|
||||||
|
|
||||||
let purgedCount = 0, error;
|
let purgedCount = 0, error;
|
||||||
@@ -33,6 +33,7 @@ async function purgeTtsCache(client, logger, {all, account_sid, vendor,
|
|||||||
language: language || '',
|
language: language || '',
|
||||||
voice: voice || deploymentId,
|
voice: voice || deploymentId,
|
||||||
engine,
|
engine,
|
||||||
|
model,
|
||||||
text,
|
text,
|
||||||
});
|
});
|
||||||
purgedCount = await client.del(key);
|
purgedCount = await client.del(key);
|
||||||
|
|||||||
+292
-104
@@ -3,6 +3,7 @@ const fs = require('fs');
|
|||||||
const bent = require('bent');
|
const bent = require('bent');
|
||||||
const ttsGoogle = require('@google-cloud/text-to-speech');
|
const ttsGoogle = require('@google-cloud/text-to-speech');
|
||||||
const { PollyClient, SynthesizeSpeechCommand } = require('@aws-sdk/client-polly');
|
const { PollyClient, SynthesizeSpeechCommand } = require('@aws-sdk/client-polly');
|
||||||
|
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 TextToSpeechV1 = require('ibm-watson/text-to-speech/v1');
|
||||||
@@ -45,7 +46,7 @@ const {
|
|||||||
JAMBONES_HTTP_PROXY_IP,
|
JAMBONES_HTTP_PROXY_IP,
|
||||||
JAMBONES_HTTP_PROXY_PORT,
|
JAMBONES_HTTP_PROXY_PORT,
|
||||||
JAMBONES_TTS_CACHE_DURATION_MINS,
|
JAMBONES_TTS_CACHE_DURATION_MINS,
|
||||||
JAMBONES_EAGERLY_PRE_CACHE_AUDIO,
|
JAMBONES_TTS_TRIM_SILENCE,
|
||||||
} = 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');
|
||||||
@@ -90,13 +91,13 @@ async function synthAudio(client, createHash, retrieveHash, logger, stats, { acc
|
|||||||
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
|
||||||
}) {
|
}) {
|
||||||
let audioBuffer;
|
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', 'ibm', 'elevenlabs',
|
||||||
'whisper', 'deepgram', 'playht', 'rimelabs', 'verbio'].includes(vendor) ||
|
'whisper', 'deepgram', 'playht', 'rimelabs', 'verbio', 'cartesia'].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) {
|
||||||
@@ -157,7 +158,9 @@ async function synthAudio(client, createHash, retrieveHash, logger, stats, { acc
|
|||||||
if (!credentials.deepgram_tts_uri) {
|
if (!credentials.deepgram_tts_uri) {
|
||||||
assert.ok(credentials.api_key, 'synthAudio requires api_key when deepgram is used');
|
assert.ok(credentials.api_key, 'synthAudio requires api_key when deepgram is used');
|
||||||
}
|
}
|
||||||
|
} else if ('cartesia' === vendor) {
|
||||||
|
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');
|
||||||
}
|
}
|
||||||
|
|
||||||
const key = makeSynthKey({
|
const key = makeSynthKey({
|
||||||
@@ -166,45 +169,26 @@ async function synthAudio(client, createHash, retrieveHash, logger, stats, { acc
|
|||||||
language: language || '',
|
language: language || '',
|
||||||
voice: voice || deploymentId,
|
voice: voice || deploymentId,
|
||||||
engine,
|
engine,
|
||||||
text,
|
// model or model_id is used to identify the tts cache.
|
||||||
renderForCaching
|
model: model || credentials.model_id,
|
||||||
|
text
|
||||||
});
|
});
|
||||||
let filePath;
|
|
||||||
filePath = makeFilePath({vendor, key, salt, renderForCaching});
|
|
||||||
debug(`synth key is ${key}`);
|
debug(`synth key is ${key}`);
|
||||||
let cached;
|
let cached;
|
||||||
if (!disableTtsCache) {
|
if (!disableTtsCache) {
|
||||||
cached = await client.get(key);
|
cached = await client.get(key);
|
||||||
/**
|
|
||||||
* If we are using tts streaming and also precaching audio, audio could have been cached by streaming (r8)
|
|
||||||
* or here in speech-utils due to precaching (mp3), so we need to check for both keys.
|
|
||||||
*/
|
|
||||||
if (!cached && JAMBONES_EAGERLY_PRE_CACHE_AUDIO) {
|
|
||||||
const preCachekey = makeSynthKey({
|
|
||||||
account_sid,
|
|
||||||
vendor,
|
|
||||||
language: language || '',
|
|
||||||
voice: voice || deploymentId,
|
|
||||||
engine,
|
|
||||||
text,
|
|
||||||
renderForCaching: true
|
|
||||||
});
|
|
||||||
cached = await client.get(preCachekey);
|
|
||||||
if (cached) {
|
|
||||||
// Precache audio is available update filpath with precache file extension.
|
|
||||||
filePath = makeFilePath({vendor, key, salt, renderForCaching: true});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (cached) {
|
if (cached) {
|
||||||
// found in cache - extend the expiry and use it
|
// found in cache - extend the expiry and use it
|
||||||
debug('result WAS found in cache');
|
debug('result WAS found in cache');
|
||||||
servedFromCache = true;
|
servedFromCache = true;
|
||||||
stats.increment('tts.cache.requests', ['found:yes']);
|
stats.increment('tts.cache.requests', ['found:yes']);
|
||||||
audioBuffer = Buffer.from(cached, 'base64');
|
audioData = JSON.parse(cached);
|
||||||
|
// convert base64 audio to buffer
|
||||||
|
audioData.audioContent = Buffer.from(audioData.audioContent, 'base64');
|
||||||
client.expire(key, EXPIRES).catch((err) => logger.info(err, 'Error setting expires'));
|
client.expire(key, EXPIRES).catch((err) => logger.info(err, 'Error setting expires'));
|
||||||
}
|
} else {
|
||||||
if (!cached) {
|
|
||||||
// not found in cache - go get it from speech vendor and add to cache
|
// not found in cache - go get it from speech vendor and add to cache
|
||||||
debug('result was NOT found in cache');
|
debug('result was NOT found in cache');
|
||||||
stats.increment('tts.cache.requests', ['found:no']);
|
stats.increment('tts.cache.requests', ['found:no']);
|
||||||
@@ -212,82 +196,93 @@ 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':
|
||||||
audioBuffer = await synthGoogle(logger, {credentials, stats, language, voice, gender, text});
|
audioData = await synthGoogle(logger, {credentials, stats, language, voice, gender, text});
|
||||||
break;
|
break;
|
||||||
case 'aws':
|
case 'aws':
|
||||||
case 'polly':
|
case 'polly':
|
||||||
vendorLabel = 'aws';
|
vendorLabel = 'aws';
|
||||||
audioBuffer = await synthPolly(createHash, retrieveHash, logger,
|
audioData = await synthPolly(createHash, retrieveHash, logger,
|
||||||
{credentials, stats, language, voice, text, engine});
|
{credentials, stats, language, voice, text, engine});
|
||||||
break;
|
break;
|
||||||
case 'azure':
|
case 'azure':
|
||||||
case 'microsoft':
|
case 'microsoft':
|
||||||
vendorLabel = 'microsoft';
|
vendorLabel = 'microsoft';
|
||||||
audioBuffer = await synthMicrosoft(logger, {credentials, stats, language, voice, text, deploymentId,
|
audioData = await synthMicrosoft(logger, {credentials, stats, language, voice, text, deploymentId,
|
||||||
filePath, renderForCaching, disableTtsStreaming});
|
renderForCaching, disableTtsStreaming});
|
||||||
break;
|
break;
|
||||||
case 'nuance':
|
case 'nuance':
|
||||||
model = model || 'enhanced';
|
model = model || 'enhanced';
|
||||||
audioBuffer = await synthNuance(client, logger, {credentials, stats, voice, model, text});
|
audioData = await synthNuance(client, logger, {credentials, stats, voice, model, text});
|
||||||
break;
|
break;
|
||||||
case 'nvidia':
|
case 'nvidia':
|
||||||
audioBuffer = await synthNvidia(client, logger, {credentials, stats, language, voice, model, text});
|
audioData = await synthNvidia(client, logger, {credentials, stats, language, voice, model, text,
|
||||||
|
renderForCaching, disableTtsStreaming});
|
||||||
break;
|
break;
|
||||||
case 'ibm':
|
case 'ibm':
|
||||||
audioBuffer = await synthIbm(logger, {credentials, stats, voice, text});
|
audioData = await synthIbm(logger, {credentials, stats, voice, text});
|
||||||
break;
|
break;
|
||||||
case 'wellsaid':
|
case 'wellsaid':
|
||||||
audioBuffer = await synthWellSaid(logger, {credentials, stats, language, voice, text, filePath});
|
audioData = await synthWellSaid(logger, {credentials, stats, language, voice, text});
|
||||||
break;
|
break;
|
||||||
case 'elevenlabs':
|
case 'elevenlabs':
|
||||||
audioBuffer = await synthElevenlabs(logger, {
|
audioData = await synthElevenlabs(logger, {
|
||||||
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming, filePath
|
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming});
|
||||||
});
|
|
||||||
break;
|
break;
|
||||||
case 'playht':
|
case 'playht':
|
||||||
audioBuffer = await synthPlayHT(client, logger, {
|
audioData = await synthPlayHT(client, logger, {
|
||||||
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming, filePath
|
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming});
|
||||||
});
|
break;
|
||||||
|
case 'cartesia':
|
||||||
|
audioData = await synthCartesia(logger, {
|
||||||
|
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming});
|
||||||
break;
|
break;
|
||||||
case 'rimelabs':
|
case 'rimelabs':
|
||||||
audioBuffer = await synthRimelabs(logger, {
|
audioData = await synthRimelabs(logger, {
|
||||||
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming, filePath
|
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming});
|
||||||
});
|
|
||||||
break;
|
break;
|
||||||
case 'whisper':
|
case 'whisper':
|
||||||
audioBuffer = await synthWhisper(logger, {
|
audioData = await synthWhisper(logger, {
|
||||||
credentials, stats, voice, text, renderForCaching, disableTtsStreaming});
|
credentials, stats, voice, text, renderForCaching, disableTtsStreaming});
|
||||||
break;
|
break;
|
||||||
case 'verbio':
|
case 'verbio':
|
||||||
audioBuffer = await synthVerbio(client, logger, {
|
audioData = await synthVerbio(client, logger, {
|
||||||
credentials, stats, voice, text, renderForCaching, disableTtsStreaming});
|
credentials, stats, voice, text, renderForCaching, disableTtsStreaming});
|
||||||
if (audioBuffer?.filePath) return audioBuffer;
|
if (audioData?.filePath) return audioData;
|
||||||
break;
|
break;
|
||||||
case 'deepgram':
|
case 'deepgram':
|
||||||
audioBuffer = await synthDeepgram(logger, {credentials, stats, model, text,
|
audioData = await synthDeepgram(logger, {credentials, stats, model, text,
|
||||||
renderForCaching, disableTtsStreaming});
|
renderForCaching, disableTtsStreaming});
|
||||||
break;
|
break;
|
||||||
case vendor.startsWith('custom') ? vendor : 'cant_match_value':
|
case vendor.startsWith('custom') ? vendor : 'cant_match_value':
|
||||||
({ audioBuffer, filePath } = await synthCustomVendor(logger,
|
audioData = await synthCustomVendor(logger,
|
||||||
{credentials, stats, language, voice, text, filePath}));
|
{credentials, stats, language, voice, text});
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
assert(`synthAudio: unsupported speech vendor ${vendor}`);
|
assert(`synthAudio: unsupported speech vendor ${vendor}`);
|
||||||
}
|
}
|
||||||
if ('filePath' in audioBuffer) return audioBuffer;
|
if ('filePath' in audioData) return audioData;
|
||||||
const diff = process.hrtime(startAt);
|
const diff = process.hrtime(startAt);
|
||||||
const time = diff[0] * 1e3 + diff[1] * 1e-6;
|
const time = diff[0] * 1e3 + diff[1] * 1e-6;
|
||||||
rtt = time.toFixed(0);
|
rtt = time.toFixed(0);
|
||||||
stats.histogram('tts.response_time', rtt, [`vendor:${vendorLabel}`]);
|
stats.histogram('tts.response_time', rtt, [`vendor:${vendorLabel}`]);
|
||||||
debug(`tts rtt time for ${text.length} chars on ${vendorLabel}: ${rtt}`);
|
debug(`tts rtt time for ${text.length} chars on ${vendorLabel}: ${rtt}`);
|
||||||
logger.info(`tts rtt time for ${text.length} chars on ${vendorLabel}: ${rtt}`);
|
logger.info(`tts rtt time for ${text.length} chars on ${vendorLabel}: ${rtt}`);
|
||||||
|
// Save audio json to cache
|
||||||
client.setex(key, EXPIRES, audioBuffer.toString('base64'))
|
client.setex(key, EXPIRES, JSON.stringify({
|
||||||
|
...audioData,
|
||||||
|
audioContent: audioData.audioContent?.toString('base64')
|
||||||
|
}))
|
||||||
.catch((err) => logger.error(err, `error calling setex on key ${key}`));
|
.catch((err) => logger.error(err, `error calling setex on key ${key}`));
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
fs.writeFile(filePath, audioBuffer, (err) => {
|
const { audioContent, extension } = audioData;
|
||||||
|
const filePath = makeFilePath({
|
||||||
|
key,
|
||||||
|
salt,
|
||||||
|
extension
|
||||||
|
});
|
||||||
|
fs.writeFile(filePath, audioContent, (err) => {
|
||||||
if (err) return reject(err);
|
if (err) return reject(err);
|
||||||
resolve({filePath, servedFromCache, rtt});
|
resolve({filePath, servedFromCache, rtt});
|
||||||
});
|
});
|
||||||
@@ -342,7 +337,13 @@ const synthPolly = async(createHash, retrieveHash, logger,
|
|||||||
.on('data', (chunk) => {
|
.on('data', (chunk) => {
|
||||||
chunks.push(chunk);
|
chunks.push(chunk);
|
||||||
})
|
})
|
||||||
.on('end', () => resolve(Buffer.concat(chunks)));
|
.on('end', () => resolve(
|
||||||
|
{
|
||||||
|
audioContent: Buffer.concat(chunks),
|
||||||
|
extension: 'mp3',
|
||||||
|
sampleRate: 8000
|
||||||
|
}
|
||||||
|
));
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.info({err}, 'synthAudio: Error synthesizing speech using aws polly');
|
logger.info({err}, 'synthAudio: Error synthesizing speech using aws polly');
|
||||||
@@ -353,6 +354,48 @@ const synthPolly = async(createHash, retrieveHash, logger,
|
|||||||
|
|
||||||
const synthGoogle = async(logger, {credentials, stats, language, voice, gender, text}) => {
|
const synthGoogle = async(logger, {credentials, stats, language, voice, gender, text}) => {
|
||||||
const client = new ttsGoogle.TextToSpeechClient(credentials);
|
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', {
|
||||||
|
'Authorization': `Bearer ${accessToken}`,
|
||||||
|
'x-goog-user-project': projectId,
|
||||||
|
'Content-Type': 'application/json; charset=utf-8'
|
||||||
|
});
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
input: {
|
||||||
|
text
|
||||||
|
},
|
||||||
|
voice: {
|
||||||
|
language_code: language,
|
||||||
|
voice_clone: {
|
||||||
|
voice_cloning_key: voice.voice_cloning_key
|
||||||
|
}
|
||||||
|
},
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const opts = {
|
const opts = {
|
||||||
voice: {
|
voice: {
|
||||||
...(typeof voice === 'string' && {name: voice}),
|
...(typeof voice === 'string' && {name: voice}),
|
||||||
@@ -367,7 +410,11 @@ const synthGoogle = async(logger, {credentials, stats, language, voice, gender,
|
|||||||
const responses = await client.synthesizeSpeech(opts);
|
const responses = 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 responses[0].audioContent;
|
return {
|
||||||
|
audioContent: responses[0].audioContent,
|
||||||
|
extension: 'mp3',
|
||||||
|
sampleRate: 8000
|
||||||
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
logger.info({err, opts}, 'synthAudio: Error synthesizing speech using google');
|
logger.info({err, opts}, 'synthAudio: Error synthesizing speech using google');
|
||||||
@@ -398,7 +445,11 @@ const synthIbm = async(logger, {credentials, stats, voice, text}) => {
|
|||||||
for await (const chunk of r.result) {
|
for await (const chunk of r.result) {
|
||||||
chunks.push(chunk);
|
chunks.push(chunk);
|
||||||
}
|
}
|
||||||
return Buffer.concat(chunks);
|
return {
|
||||||
|
audioContent: Buffer.concat(chunks),
|
||||||
|
extension: 'mp3',
|
||||||
|
sampleRate: 8000
|
||||||
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.info({err, params}, 'synthAudio: Error synthesizing speech using ibm');
|
logger.info({err, params}, 'synthAudio: Error synthesizing speech using ibm');
|
||||||
stats.increment('tts.count', ['vendor:ibm', 'accepted:no']);
|
stats.increment('tts.count', ['vendor:ibm', 'accepted:no']);
|
||||||
@@ -408,11 +459,9 @@ const synthIbm = async(logger, {credentials, stats, voice, text}) => {
|
|||||||
|
|
||||||
async function _synthOnPremMicrosoft(logger, {
|
async function _synthOnPremMicrosoft(logger, {
|
||||||
credentials,
|
credentials,
|
||||||
stats,
|
|
||||||
language,
|
language,
|
||||||
voice,
|
voice,
|
||||||
text,
|
text
|
||||||
filePath
|
|
||||||
}) {
|
}) {
|
||||||
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;
|
||||||
@@ -434,15 +483,19 @@ async function _synthOnPremMicrosoft(logger, {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const trimSilence = filePath.endsWith('.r8');
|
const trimSilence = JAMBONES_TTS_TRIM_SILENCE;
|
||||||
const post = bent('POST', 'buffer', {
|
const post = bent('POST', 'buffer', {
|
||||||
'X-Microsoft-OutputFormat': trimSilence ? 'raw-8khz-16bit-mono-pcm' : 'audio-16khz-32kbitrate-mono-mp3',
|
'X-Microsoft-OutputFormat': trimSilence ? 'raw-8khz-16bit-mono-pcm' : 'audio-16khz-32kbitrate-mono-mp3',
|
||||||
'Content-Type': 'application/ssml+xml',
|
'Content-Type': 'application/ssml+xml',
|
||||||
'User-Agent': 'Jambonz',
|
'User-Agent': 'Jambonz',
|
||||||
...(api_key && {'Ocp-Apim-Subscription-Key': api_key})
|
...(api_key && {'Ocp-Apim-Subscription-Key': api_key})
|
||||||
});
|
});
|
||||||
const mp3 = await post(custom_tts_endpoint_url, content);
|
const audioContent = await post(custom_tts_endpoint_url, content);
|
||||||
return mp3;
|
return {
|
||||||
|
audioContent,
|
||||||
|
extension: trimSilence ? 'r8' : 'mp3',
|
||||||
|
sampleRate: 8000
|
||||||
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.info({err}, '_synthMicrosoftByHttp returned error');
|
logger.info({err}, '_synthMicrosoftByHttp returned error');
|
||||||
throw err;
|
throw err;
|
||||||
@@ -455,7 +508,6 @@ const synthMicrosoft = async(logger, {
|
|||||||
language,
|
language,
|
||||||
voice,
|
voice,
|
||||||
text,
|
text,
|
||||||
filePath,
|
|
||||||
renderForCaching,
|
renderForCaching,
|
||||||
disableTtsStreaming
|
disableTtsStreaming
|
||||||
}) => {
|
}) => {
|
||||||
@@ -498,17 +550,18 @@ const synthMicrosoft = async(logger, {
|
|||||||
rtt: 0
|
rtt: 0
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
// Azure Onprem
|
||||||
if (use_custom_tts && custom_tts_endpoint_url) {
|
if (use_custom_tts && custom_tts_endpoint_url) {
|
||||||
return await _synthOnPremMicrosoft(logger, {
|
return await _synthOnPremMicrosoft(logger, {
|
||||||
credentials,
|
credentials,
|
||||||
stats,
|
stats,
|
||||||
language,
|
language,
|
||||||
voice,
|
voice,
|
||||||
text,
|
text
|
||||||
filePath
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const trimSilence = filePath.endsWith('.r8');
|
// Azure hosted service
|
||||||
|
const trimSilence = JAMBONES_TTS_TRIM_SILENCE;
|
||||||
const speechConfig = SpeechConfig.fromSubscription(apiKey, region);
|
const speechConfig = SpeechConfig.fromSubscription(apiKey, region);
|
||||||
speechConfig.speechSynthesisLanguage = language;
|
speechConfig.speechSynthesisLanguage = language;
|
||||||
speechConfig.speechSynthesisVoiceName = voice;
|
speechConfig.speechSynthesisVoiceName = voice;
|
||||||
@@ -543,7 +596,11 @@ const synthMicrosoft = async(logger, {
|
|||||||
case ResultReason.SynthesizingAudioCompleted:
|
case ResultReason.SynthesizingAudioCompleted:
|
||||||
let buffer = Buffer.from(result.audioData);
|
let buffer = Buffer.from(result.audioData);
|
||||||
if (trimSilence) buffer = trimTrailingSilence(buffer);
|
if (trimSilence) buffer = trimTrailingSilence(buffer);
|
||||||
resolve(buffer);
|
resolve({
|
||||||
|
audioContent: buffer,
|
||||||
|
extension: trimSilence ? 'r8' : 'mp3',
|
||||||
|
sampleRate: 8000
|
||||||
|
});
|
||||||
synthesizer.close();
|
synthesizer.close();
|
||||||
stats.increment('tts.count', ['vendor:microsoft', 'accepted:yes']);
|
stats.increment('tts.count', ['vendor:microsoft', 'accepted:yes']);
|
||||||
break;
|
break;
|
||||||
@@ -573,11 +630,15 @@ const synthWellSaid = async(logger, {credentials, stats, language, voice, gender
|
|||||||
'Accept': 'audio/mpeg',
|
'Accept': 'audio/mpeg',
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
});
|
});
|
||||||
const mp3 = await post('/v1/tts/stream', {
|
const audioContent = await post('/v1/tts/stream', {
|
||||||
text,
|
text,
|
||||||
speaker_id: voice
|
speaker_id: voice
|
||||||
});
|
});
|
||||||
return mp3;
|
return {
|
||||||
|
audioContent,
|
||||||
|
extension: 'mp3',
|
||||||
|
sampleRate: 8000
|
||||||
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.info({err}, 'testWellSaidTts returned error');
|
logger.info({err}, 'testWellSaidTts returned error');
|
||||||
throw err;
|
throw err;
|
||||||
@@ -614,8 +675,8 @@ const synthNuance = async(client, logger, {credentials, stats, voice, model, tex
|
|||||||
t.setText(text);
|
t.setText(text);
|
||||||
input.setText(t);
|
input.setText(t);
|
||||||
}
|
}
|
||||||
|
const sampleRate = 8000;
|
||||||
pcm.setSampleRateHz(8000);
|
pcm.setSampleRateHz(sampleRate);
|
||||||
f.setPcm(pcm);
|
f.setPcm(pcm);
|
||||||
p.setAudioFormat(f);
|
p.setAudioFormat(f);
|
||||||
v.setName(voice);
|
v.setName(voice);
|
||||||
@@ -639,20 +700,41 @@ const synthNuance = async(client, logger, {credentials, stats, voice, model, tex
|
|||||||
const details = status.getDetails();
|
const details = status.getDetails();
|
||||||
return reject({code, message, details});
|
return reject({code, message, details});
|
||||||
}
|
}
|
||||||
resolve(Buffer.from(response.getAudio()));
|
resolve({
|
||||||
|
audioContent: Buffer.from(response.getAudio()),
|
||||||
|
extension: 'r8',
|
||||||
|
sampleRate
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const synthNvidia = async(client, logger, {credentials, stats, language, voice, model, text}) => {
|
const synthNvidia = async(client, logger, {
|
||||||
|
credentials, stats, language, voice, model, text, renderForCaching, disableTtsStreaming
|
||||||
|
}) => {
|
||||||
const {riva_server_uri} = credentials;
|
const {riva_server_uri} = credentials;
|
||||||
|
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
|
let params = '';
|
||||||
|
params += `{riva_server_uri=${riva_server_uri}`;
|
||||||
|
params += `,voice=${voice}`;
|
||||||
|
params += `,language=${language}`;
|
||||||
|
params += ',write_cache_file=1';
|
||||||
|
params += '}';
|
||||||
|
|
||||||
|
return {
|
||||||
|
filePath: `say:${params}${text.replace(/\n/g, ' ')}`,
|
||||||
|
servedFromCache: false,
|
||||||
|
rtt: 0
|
||||||
|
};
|
||||||
|
}
|
||||||
let rivaClient, request;
|
let rivaClient, request;
|
||||||
|
const sampleRate = 8000;
|
||||||
try {
|
try {
|
||||||
rivaClient = await createRivaClient(riva_server_uri);
|
rivaClient = await createRivaClient(riva_server_uri);
|
||||||
request = new SynthesizeSpeechRequest();
|
request = new SynthesizeSpeechRequest();
|
||||||
request.setVoiceName(voice);
|
request.setVoiceName(voice);
|
||||||
request.setLanguageCode(language);
|
request.setLanguageCode(language);
|
||||||
request.setSampleRateHz(8000);
|
request.setSampleRateHz(sampleRate);
|
||||||
request.setEncoding(AudioEncoding.LINEAR_PCM);
|
request.setEncoding(AudioEncoding.LINEAR_PCM);
|
||||||
request.setText(text);
|
request.setText(text);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -666,7 +748,11 @@ const synthNvidia = async(client, logger, {credentials, stats, language, voice,
|
|||||||
logger.info({err, voice, language}, 'error synthesizing speech using Nvidia');
|
logger.info({err, voice, language}, 'error synthesizing speech using Nvidia');
|
||||||
return reject(err);
|
return reject(err);
|
||||||
}
|
}
|
||||||
resolve(Buffer.from(response.getAudio()));
|
resolve({
|
||||||
|
audioContent: Buffer.from(response.getAudio()),
|
||||||
|
extension: 'r8',
|
||||||
|
sampleRate
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -688,12 +774,13 @@ const synthCustomVendor = async(logger, {credentials, stats, language, voice, te
|
|||||||
text
|
text
|
||||||
});
|
});
|
||||||
|
|
||||||
const regex = /\.[^\.]*$/g;
|
|
||||||
const mime = response.headers['content-type'];
|
const mime = response.headers['content-type'];
|
||||||
const buffer = await response.arrayBuffer();
|
const buffer = await response.arrayBuffer();
|
||||||
|
const [extension, sampleRate] = getFileExtFromMime(mime);
|
||||||
return {
|
return {
|
||||||
audioBuffer: buffer,
|
audioContent: buffer,
|
||||||
filePath: filePath.replace(regex, getFileExtFromMime(mime))
|
extension,
|
||||||
|
sampleRate
|
||||||
};
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.info({err}, `Vendor ${vendor} returned error`);
|
logger.info({err}, `Vendor ${vendor} returned error`);
|
||||||
@@ -719,9 +806,13 @@ const synthElevenlabs = async(logger, {
|
|||||||
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}`;
|
||||||
|
if (opts.voice_settings?.speed !== null && opts.voice_settings?.speed !== undefined)
|
||||||
|
params += `,speed=${opts.voice_settings.speed}`;
|
||||||
if (opts.voice_settings?.use_speaker_boost === false) params += ',use_speaker_boost=false';
|
if (opts.voice_settings?.use_speaker_boost === false) params += ',use_speaker_boost=false';
|
||||||
if (opts.previous_text) params += `,previous_text=${opts.previous_text}`;
|
if (opts.previous_text) params += `,previous_text=${opts.previous_text}`;
|
||||||
if (opts.next_text) params += `,next_text=${opts.next_text}`;
|
if (opts.next_text) params += `,next_text=${opts.next_text}`;
|
||||||
|
if (opts.pronunciation_dictionary_locators && Array.isArray(opts.pronunciation_dictionary_locators))
|
||||||
|
params += `,pronunciation_dictionary_locators=${JSON.stringify(opts.pronunciation_dictionary_locators)}`;
|
||||||
params += '}';
|
params += '}';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -739,7 +830,7 @@ const synthElevenlabs = async(logger, {
|
|||||||
'Accept': 'audio/mpeg',
|
'Accept': 'audio/mpeg',
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
});
|
});
|
||||||
const mp3 = await post(`/v1/text-to-speech/${voice}${optimize_streaming_latency}`, {
|
const audioContent = await post(`/v1/text-to-speech/${voice}${optimize_streaming_latency}`, {
|
||||||
text,
|
text,
|
||||||
model_id,
|
model_id,
|
||||||
voice_settings: {
|
voice_settings: {
|
||||||
@@ -748,7 +839,11 @@ const synthElevenlabs = async(logger, {
|
|||||||
},
|
},
|
||||||
...opts
|
...opts
|
||||||
});
|
});
|
||||||
return mp3;
|
return {
|
||||||
|
audioContent,
|
||||||
|
extension: 'mp3',
|
||||||
|
sampleRate: 8000
|
||||||
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.info({err}, 'synth Elevenlabs returned error');
|
logger.info({err}, 'synth Elevenlabs returned error');
|
||||||
stats.increment('tts.count', ['vendor:elevenlabs', 'accepted:no']);
|
stats.increment('tts.count', ['vendor:elevenlabs', 'accepted:no']);
|
||||||
@@ -830,7 +925,7 @@ const synthPlayHT = async(client, logger, {
|
|||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
});
|
});
|
||||||
|
|
||||||
const mp3 = await post(synthesizeUrl, {
|
const audioContent = await post(synthesizeUrl, {
|
||||||
text,
|
text,
|
||||||
...(voice_engine === 'Play3.0' && { language }),
|
...(voice_engine === 'Play3.0' && { language }),
|
||||||
voice,
|
voice,
|
||||||
@@ -839,7 +934,11 @@ const synthPlayHT = async(client, logger, {
|
|||||||
sample_rate: 8000,
|
sample_rate: 8000,
|
||||||
...opts
|
...opts
|
||||||
});
|
});
|
||||||
return mp3;
|
return {
|
||||||
|
audioContent,
|
||||||
|
extension: 'mp3',
|
||||||
|
sampleRate: 8000
|
||||||
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.info({err}, 'synth PlayHT returned error');
|
logger.info({err}, 'synth PlayHT returned error');
|
||||||
stats.increment('tts.count', ['vendor:playht', 'accepted:no']);
|
stats.increment('tts.count', ['vendor:playht', 'accepted:no']);
|
||||||
@@ -848,7 +947,7 @@ const synthPlayHT = async(client, logger, {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const synthRimelabs = async(logger, {
|
const synthRimelabs = async(logger, {
|
||||||
credentials, options, stats, voice, text, renderForCaching, disableTtsStreaming
|
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming
|
||||||
}) => {
|
}) => {
|
||||||
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 || '{}');
|
||||||
@@ -859,6 +958,7 @@ const synthRimelabs = async(logger, {
|
|||||||
params += `{api_key=${api_key}`;
|
params += `{api_key=${api_key}`;
|
||||||
params += `,model_id=${model_id}`;
|
params += `,model_id=${model_id}`;
|
||||||
params += ',vendor=rimelabs';
|
params += ',vendor=rimelabs';
|
||||||
|
params += `,language=${language}`;
|
||||||
params += `,voice=${voice}`;
|
params += `,voice=${voice}`;
|
||||||
params += ',write_cache_file=1';
|
params += ',write_cache_file=1';
|
||||||
if (opts.speedAlpha) params += `,speed_alpha=${opts.speedAlpha}`;
|
if (opts.speedAlpha) params += `,speed_alpha=${opts.speedAlpha}`;
|
||||||
@@ -878,14 +978,20 @@ const synthRimelabs = async(logger, {
|
|||||||
'Accept': 'audio/mp3',
|
'Accept': 'audio/mp3',
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
});
|
});
|
||||||
const mp3 = await post('/v1/rime-tts', {
|
const sampleRate = 8000;
|
||||||
|
const audioContent = await post('/v1/rime-tts', {
|
||||||
speaker: voice,
|
speaker: voice,
|
||||||
text,
|
text,
|
||||||
modelId: model_id,
|
modelId: model_id,
|
||||||
samplingRate: 8000,
|
samplingRate: sampleRate,
|
||||||
|
lang: language,
|
||||||
...opts
|
...opts
|
||||||
});
|
});
|
||||||
return mp3;
|
return {
|
||||||
|
audioContent,
|
||||||
|
extension: 'mp3',
|
||||||
|
sampleRate
|
||||||
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.info({err}, 'synth rimelabs returned error');
|
logger.info({err}, 'synth rimelabs returned error');
|
||||||
stats.increment('tts.count', ['vendor:rimelabs', 'accepted:no']);
|
stats.increment('tts.count', ['vendor:rimelabs', 'accepted:no']);
|
||||||
@@ -919,13 +1025,17 @@ const synthVerbio = async(client, logger, {credentials, stats, voice, text, rend
|
|||||||
'User-Agent': 'jambonz',
|
'User-Agent': 'jambonz',
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
});
|
});
|
||||||
const r8 = await post('/api/v1/synthesize', {
|
const audioContent = await post('/api/v1/synthesize', {
|
||||||
voice_id: voice,
|
voice_id: voice,
|
||||||
output_sample_rate: '8k',
|
output_sample_rate: '8k',
|
||||||
output_encoding: 'pcm16',
|
output_encoding: 'pcm16',
|
||||||
text
|
text
|
||||||
});
|
});
|
||||||
return r8;
|
return {
|
||||||
|
audioContent,
|
||||||
|
extension: 'r8',
|
||||||
|
sampleRate: 8000
|
||||||
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.info({err}, 'synth Verbio returned error');
|
logger.info({err}, 'synth Verbio returned error');
|
||||||
stats.increment('tts.count', ['vendor:verbio', 'accepted:no']);
|
stats.increment('tts.count', ['vendor:verbio', 'accepted:no']);
|
||||||
@@ -965,7 +1075,11 @@ const synthWhisper = async(logger, {credentials, stats, voice, text, renderForCa
|
|||||||
input: text,
|
input: text,
|
||||||
response_format: 'mp3'
|
response_format: 'mp3'
|
||||||
});
|
});
|
||||||
return Buffer.from(await mp3.arrayBuffer());
|
return {
|
||||||
|
audioContent: Buffer.from(await mp3.arrayBuffer()),
|
||||||
|
extension: 'mp3',
|
||||||
|
sampleRate: 8000
|
||||||
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.info({err}, 'synth whisper returned error');
|
logger.info({err}, 'synth whisper returned error');
|
||||||
stats.increment('tts.count', ['vendor:openai', 'accepted:no']);
|
stats.increment('tts.count', ['vendor:openai', 'accepted:no']);
|
||||||
@@ -997,10 +1111,14 @@ const synthDeepgram = async(logger, {credentials, stats, model, text, renderForC
|
|||||||
'Accept': 'audio/mpeg',
|
'Accept': 'audio/mpeg',
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
});
|
});
|
||||||
const mp3 = await post(`/v1/speak?model=${model}`, {
|
const audioContent = await post(`/v1/speak?model=${model}`, {
|
||||||
text
|
text
|
||||||
});
|
});
|
||||||
return mp3;
|
return {
|
||||||
|
audioContent,
|
||||||
|
extension: 'mp3',
|
||||||
|
sampleRate: 8000
|
||||||
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.info({err}, 'synth Deepgram returned error');
|
logger.info({err}, 'synth Deepgram returned error');
|
||||||
stats.increment('tts.count', ['vendor:deepgram', 'accepted:no']);
|
stats.increment('tts.count', ['vendor:deepgram', 'accepted:no']);
|
||||||
@@ -1008,26 +1126,96 @@ const synthDeepgram = async(logger, {credentials, stats, model, text, renderForC
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const synthCartesia = async(logger, {
|
||||||
|
credentials, options, stats, voice, language, text, renderForCaching, disableTtsStreaming
|
||||||
|
}) => {
|
||||||
|
const {api_key, model_id, embedding, options: credOpts} = credentials;
|
||||||
|
const opts = !!options && Object.keys(options).length !== 0 ? options : JSON.parse(credOpts || '{}');
|
||||||
|
|
||||||
|
if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
|
||||||
|
let params = '';
|
||||||
|
params += `{api_key=${api_key}`;
|
||||||
|
params += `,model_id=${model_id}`;
|
||||||
|
params += ',vendor=cartesia';
|
||||||
|
params += `,voice=${voice}`;
|
||||||
|
params += ',write_cache_file=1';
|
||||||
|
params += `,language=${language}`;
|
||||||
|
params += `,voice_mode=${embedding ? 'embedding' : 'id'}`;
|
||||||
|
if (embedding) params += `,embedding=${embedding}`;
|
||||||
|
if (opts.speed) params += `,speed=${opts.speed}`;
|
||||||
|
if (opts.emotion) params += `,emotion=${opts.emotion}`;
|
||||||
|
params += '}';
|
||||||
|
|
||||||
|
return {
|
||||||
|
filePath: `say:${params}${text.replace(/\n/g, ' ').replace(/\r/g, ' ')}`,
|
||||||
|
servedFromCache: false,
|
||||||
|
rtt: 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const client = new CartesiaClient({ apiKey: api_key });
|
||||||
|
const sampleRate = 48000;
|
||||||
|
const mp3 = await client.tts.bytes({
|
||||||
|
modelId: model_id,
|
||||||
|
transcript: text,
|
||||||
|
voice: {
|
||||||
|
mode: embedding ? 'embedding' : 'id',
|
||||||
|
...(embedding ?
|
||||||
|
{
|
||||||
|
embedding: embedding.split(',').map(Number)
|
||||||
|
} :
|
||||||
|
{
|
||||||
|
id: voice
|
||||||
|
}
|
||||||
|
),
|
||||||
|
...(opts.speed || opts.emotion && {
|
||||||
|
experimentalControls: {
|
||||||
|
...(opts.speed !== null && opts.speed !== undefined && {speed: opts.speed}),
|
||||||
|
...(opts.emotion && {emotion: opts.emotion}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
},
|
||||||
|
language: language,
|
||||||
|
outputFormat: {
|
||||||
|
container: 'mp3',
|
||||||
|
bitRate: 128000,
|
||||||
|
sampleRate
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
audioContent: Buffer.from(mp3),
|
||||||
|
extension: 'mp3',
|
||||||
|
sampleRate
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
logger.info({err}, 'synth Cartesia returned error');
|
||||||
|
stats.increment('tts.count', ['vendor:cartesia', 'accepted:no']);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
const getFileExtFromMime = (mime) => {
|
const getFileExtFromMime = (mime) => {
|
||||||
switch (mime) {
|
switch (mime) {
|
||||||
case 'audio/wav':
|
case 'audio/wav':
|
||||||
case 'audio/x-wav':
|
case 'audio/x-wav':
|
||||||
return '.wav';
|
return ['wav', 8000];
|
||||||
case /audio\/l16.*rate=8000/.test(mime) ? mime : 'cant match value':
|
case /audio\/l16.*rate=8000/.test(mime) ? mime : 'cant match value':
|
||||||
return '.r8';
|
return ['r8', 8000];
|
||||||
case /audio\/l16.*rate=16000/.test(mime) ? mime : 'cant match value':
|
case /audio\/l16.*rate=16000/.test(mime) ? mime : 'cant match value':
|
||||||
return '.r16';
|
return ['r16', 16000];
|
||||||
case /audio\/l16.*rate=24000/.test(mime) ? mime : 'cant match value':
|
case /audio\/l16.*rate=24000/.test(mime) ? mime : 'cant match value':
|
||||||
return '.r24';
|
return ['r24', 24000];
|
||||||
case /audio\/l16.*rate=32000/.test(mime) ? mime : 'cant match value':
|
case /audio\/l16.*rate=32000/.test(mime) ? mime : 'cant match value':
|
||||||
return '.r32';
|
return ['r32', 32000];
|
||||||
case /audio\/l16.*rate=48000/.test(mime) ? mime : 'cant match value':
|
case /audio\/l16.*rate=48000/.test(mime) ? mime : 'cant match value':
|
||||||
return '.r48';
|
return ['r48', 48000];
|
||||||
case 'audio/mpeg':
|
case 'audio/mpeg':
|
||||||
case 'audio/mp3':
|
case 'audio/mp3':
|
||||||
return '.mp3';
|
return ['mp3', 8000];
|
||||||
default:
|
default:
|
||||||
return '.wav';
|
return ['wav', 8000];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+12
-45
@@ -6,7 +6,7 @@ const pool = new Pool('https://auth.crt.nuance.com');
|
|||||||
const NUANCE_AUTH_ENDPOINT = 'tts.api.nuance.com:443';
|
const NUANCE_AUTH_ENDPOINT = 'tts.api.nuance.com:443';
|
||||||
const grpc = require('@grpc/grpc-js');
|
const grpc = require('@grpc/grpc-js');
|
||||||
const formurlencoded = require('form-urlencoded');
|
const formurlencoded = require('form-urlencoded');
|
||||||
const { JAMBONES_DISABLE_TTS_STREAMING, JAMBONES_TTS_TRIM_SILENCE, TMP_FOLDER, HTTP_TIMEOUT } = require('./config');
|
const { TMP_FOLDER, HTTP_TIMEOUT } = require('./config');
|
||||||
|
|
||||||
const debug = require('debug')('jambonz:realtimedb-helpers');
|
const debug = require('debug')('jambonz:realtimedb-helpers');
|
||||||
/**
|
/**
|
||||||
@@ -17,59 +17,26 @@ const debug = require('debug')('jambonz:realtimedb-helpers');
|
|||||||
//const nuanceClientMap = new Map();
|
//const nuanceClientMap = new Map();
|
||||||
|
|
||||||
function makeSynthKey({
|
function makeSynthKey({
|
||||||
account_sid = '', vendor, language, voice, engine = '', text,
|
account_sid = '',
|
||||||
renderForCaching = false}) {
|
vendor,
|
||||||
|
language,
|
||||||
|
voice,
|
||||||
|
engine = '',
|
||||||
|
model = '',
|
||||||
|
text
|
||||||
|
}) {
|
||||||
const hash = crypto.createHash('sha1');
|
const hash = crypto.createHash('sha1');
|
||||||
hash.update(`${language}:${vendor}:${voice}:${engine}:${text}`);
|
hash.update(`${language}:${vendor}:${voice}:${engine}:${model}:${text}`);
|
||||||
const hexHashKey = hash.digest('hex');
|
const hexHashKey = hash.digest('hex');
|
||||||
const accountKey = account_sid ? `:${account_sid}` : '';
|
const accountKey = account_sid ? `:${account_sid}` : '';
|
||||||
const namespace = vendor.startsWith('custom') ? vendor : getFileExtension({vendor, renderForCaching});
|
const key = `tts${accountKey}:${hexHashKey}`;
|
||||||
const key = `tts${accountKey}:${namespace}:${hexHashKey}`;
|
|
||||||
return key;
|
return key;
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeFilePath({vendor, key, salt = '', renderForCaching = false}) {
|
function makeFilePath({key, salt = '', extension}) {
|
||||||
const extension = getFileExtension({vendor, renderForCaching});
|
|
||||||
return `${TMP_FOLDER}/${key.replace('tts:', `tts-${salt}`)}.${extension}`;
|
return `${TMP_FOLDER}/${key.replace('tts:', `tts-${salt}`)}.${extension}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getFileExtension({vendor, renderForCaching = false}) {
|
|
||||||
const mp3Extension = 'mp3';
|
|
||||||
const r8Extension = 'r8';
|
|
||||||
|
|
||||||
switch (vendor) {
|
|
||||||
case 'azure':
|
|
||||||
case 'microsoft':
|
|
||||||
if (!renderForCaching && !JAMBONES_DISABLE_TTS_STREAMING || JAMBONES_TTS_TRIM_SILENCE) {
|
|
||||||
return r8Extension;
|
|
||||||
} else {
|
|
||||||
return mp3Extension;
|
|
||||||
}
|
|
||||||
case 'deepgram':
|
|
||||||
case 'elevenlabs':
|
|
||||||
case 'rimelabs':
|
|
||||||
case 'playht':
|
|
||||||
if (renderForCaching || JAMBONES_DISABLE_TTS_STREAMING) {
|
|
||||||
return mp3Extension;
|
|
||||||
} else {
|
|
||||||
return r8Extension;
|
|
||||||
}
|
|
||||||
case 'nuance':
|
|
||||||
case 'nvidia':
|
|
||||||
case 'verbio':
|
|
||||||
return r8Extension;
|
|
||||||
default:
|
|
||||||
// If vendor is custom
|
|
||||||
if (vendor.startsWith('custom')) {
|
|
||||||
if (renderForCaching || JAMBONES_DISABLE_TTS_STREAMING) {
|
|
||||||
return mp3Extension;
|
|
||||||
} else {
|
|
||||||
return r8Extension;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return mp3Extension;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const noopLogger = {
|
const noopLogger = {
|
||||||
info: () => {},
|
info: () => {},
|
||||||
|
|||||||
Generated
+544
-615
File diff suppressed because it is too large
Load Diff
+4
-3
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@jambonz/speech-utils",
|
"name": "@jambonz/speech-utils",
|
||||||
"version": "0.1.20",
|
"version": "0.2.7",
|
||||||
"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",
|
||||||
@@ -28,7 +28,8 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@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",
|
||||||
"@google-cloud/text-to-speech": "^5.0.2",
|
"@cartesia/cartesia-js": "^2.1.0",
|
||||||
|
"@google-cloud/text-to-speech": "^5.5.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",
|
||||||
@@ -38,7 +39,7 @@
|
|||||||
"ibm-watson": "^8.0.0",
|
"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.25.0",
|
||||||
"undici": "^6.4.0"
|
"undici": "^7.5.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"config": "^3.3.11",
|
"config": "^3.3.11",
|
||||||
|
|||||||
+144
-24
@@ -5,7 +5,7 @@ const fs = require('fs');
|
|||||||
const {makeSynthKey} = require('../lib/utils');
|
const {makeSynthKey} = require('../lib/utils');
|
||||||
const logger = require('pino')();
|
const logger = require('pino')();
|
||||||
const bent = require('bent');
|
const bent = require('bent');
|
||||||
const getJSON = bent('json')
|
const getJSON = bent('json');
|
||||||
|
|
||||||
process.on('unhandledRejection', (reason, p) => {
|
process.on('unhandledRejection', (reason, p) => {
|
||||||
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
|
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
|
||||||
@@ -91,14 +91,17 @@ test('Google speech Custom voice synth tests', async(t) => {
|
|||||||
const fn = require('..');
|
const fn = require('..');
|
||||||
const {synthAudio, client} = fn(opts, logger);
|
const {synthAudio, client} = fn(opts, logger);
|
||||||
|
|
||||||
if (!process.env.GCP_CUSTOM_VOICE_FILE && !process.env.GCP_CUSTOM_VOICE_JSON_KEY || !process.env.GCP_CUSTOM_VOICE_MODEL) {
|
if (!process.env.GCP_CUSTOM_VOICE_FILE &&
|
||||||
t.pass('skipping google speech synth tests since neither GCP_CUSTOM_VOICE_FILE nor GCP_CUSTOM_VOICE_JSON_KEY provided, GCP_CUSTOM_VOICE_MODEL is not provided');
|
!process.env.GCP_CUSTOM_VOICE_JSON_KEY ||
|
||||||
|
!process.env.GCP_CUSTOM_VOICE_MODEL) {
|
||||||
|
t.pass(`skipping google speech synth tests since neither
|
||||||
|
GCP_CUSTOM_VOICE_FILE nor GCP_CUSTOM_VOICE_JSON_KEY provided, GCP_CUSTOM_VOICE_MODEL is not provided`);
|
||||||
return t.end();
|
return t.end();
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const str = process.env.GCP_CUSTOM_VOICE_JSON_KEY || fs.readFileSync(process.env.GCP_CUSTOM_VOICE_FILE);
|
const str = process.env.GCP_CUSTOM_VOICE_JSON_KEY || fs.readFileSync(process.env.GCP_CUSTOM_VOICE_FILE);
|
||||||
const creds = JSON.parse(str);
|
const creds = JSON.parse(str);
|
||||||
let opts = await synthAudio(stats, {
|
const opts = await synthAudio(stats, {
|
||||||
vendor: 'google',
|
vendor: 'google',
|
||||||
credentials: {
|
credentials: {
|
||||||
credentials: {
|
credentials: {
|
||||||
@@ -109,7 +112,7 @@ test('Google speech Custom voice synth tests', async(t) => {
|
|||||||
language: 'en-AU',
|
language: 'en-AU',
|
||||||
text: 'This is a test. This is only a test',
|
text: 'This is a test. This is only a test',
|
||||||
voice: {
|
voice: {
|
||||||
reportedUsage:"REALTIME",
|
reportedUsage: 'REALTIME',
|
||||||
model: process.env.GCP_CUSTOM_VOICE_MODEL
|
model: process.env.GCP_CUSTOM_VOICE_MODEL
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -121,6 +124,48 @@ test('Google speech Custom voice synth tests', async(t) => {
|
|||||||
client.quit();
|
client.quit();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Google speech voice cloning synth tests', async(t) => {
|
||||||
|
const fn = require('..');
|
||||||
|
const {synthAudio, client} = fn(opts, logger);
|
||||||
|
|
||||||
|
if (!process.env.GCP_CUSTOM_VOICE_FILE &&
|
||||||
|
!process.env.GCP_CUSTOM_VOICE_JSON_KEY ||
|
||||||
|
!process.env.GCP_VOICE_CLONING_FILE &&
|
||||||
|
!process.env.GCP_VOICE_CLONING_JSON_KEY) {
|
||||||
|
t.pass(`skipping google speech synth tests since neither
|
||||||
|
GCP_CUSTOM_VOICE_FILE nor GCP_CUSTOM_VOICE_JSON_KEY provided,
|
||||||
|
GCP_VOICE_CLONING_FILE nor GCP_VOICE_CLONING_JSON_KEY is not provided`);
|
||||||
|
return t.end();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const googleKey = process.env.GCP_CUSTOM_VOICE_JSON_KEY ||
|
||||||
|
fs.readFileSync(process.env.GCP_CUSTOM_VOICE_FILE);
|
||||||
|
const voice_cloning_key = process.env.GCP_VOICE_CLONING_JSON_KEY ||
|
||||||
|
fs.readFileSync(process.env.GCP_VOICE_CLONING_FILE).toString();
|
||||||
|
const creds = JSON.parse(googleKey);
|
||||||
|
const opts = await synthAudio(stats, {
|
||||||
|
vendor: 'google',
|
||||||
|
credentials: {
|
||||||
|
credentials: {
|
||||||
|
client_email: creds.client_email,
|
||||||
|
private_key: creds.private_key,
|
||||||
|
project_id: creds.project_id
|
||||||
|
},
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
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_cloning_key
|
||||||
|
}
|
||||||
|
});
|
||||||
|
t.ok(!opts.servedFromCache, `successfully synthesized google voice cloning audio to ${opts.filePath}`);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
t.end(err);
|
||||||
|
}
|
||||||
|
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);
|
||||||
@@ -509,6 +554,7 @@ test('Custom Vendor speech synth tests', async(t) => {
|
|||||||
text: 'This is a test. This is only a test',
|
text: 'This is a test. This is only a test',
|
||||||
});
|
});
|
||||||
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');
|
||||||
let obj = await getJSON(`http://127.0.0.1:3100/lastRequest/somethingnew`);
|
let obj = await getJSON(`http://127.0.0.1:3100/lastRequest/somethingnew`);
|
||||||
t.ok(obj.headers.Authorization == 'Bearer some_jwt_token', 'Custom Vendor Authentication Header is correct');
|
t.ok(obj.headers.Authorization == 'Bearer some_jwt_token', 'Custom Vendor Authentication Header is correct');
|
||||||
t.ok(obj.body.language == 'en-US', 'Custom Vendor Language is correct');
|
t.ok(obj.body.language == 'en-US', 'Custom Vendor Language is correct');
|
||||||
@@ -516,6 +562,21 @@ test('Custom Vendor speech synth tests', async(t) => {
|
|||||||
t.ok(obj.body.type == 'text', 'Custom Vendor type is correct');
|
t.ok(obj.body.type == 'text', 'Custom Vendor type is correct');
|
||||||
t.ok(obj.body.text == 'This is a test. This is only a test', 'Custom Vendor text is correct');
|
t.ok(obj.body.text == 'This is a test. This is only a test', 'Custom Vendor text is correct');
|
||||||
|
|
||||||
|
// Checking if cache is stored with wav format
|
||||||
|
opts = await synthAudio(stats, {
|
||||||
|
vendor: 'custom:somethingnew',
|
||||||
|
credentials: {
|
||||||
|
use_for_tts: 1,
|
||||||
|
custom_tts_url: "http://127.0.0.1:3100/somethingnew",
|
||||||
|
auth_token: 'some_jwt_token'
|
||||||
|
},
|
||||||
|
language: 'en-US',
|
||||||
|
voice: 'English-US.Female-1',
|
||||||
|
text: 'This is a test. This is only a test',
|
||||||
|
});
|
||||||
|
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');
|
||||||
|
|
||||||
opts = await synthAudio(stats, {
|
opts = await synthAudio(stats, {
|
||||||
vendor: 'custom:somethingnew2',
|
vendor: 'custom:somethingnew2',
|
||||||
credentials: {
|
credentials: {
|
||||||
@@ -625,7 +686,41 @@ test('PlayHT3.0 speech synth tests', async(t) => {
|
|||||||
await testPlayHT(t, 'Play3.0');
|
await testPlayHT(t, 'Play3.0');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('rimelabs speech synth tests', async(t) => {
|
test('Cartesia speech synth tests', async(t) => {
|
||||||
|
const fn = require('..');
|
||||||
|
const {synthAudio, client} = fn(opts, logger);
|
||||||
|
|
||||||
|
if (!process.env.CARTESIA_API_KEY) {
|
||||||
|
t.pass('skipping Cartesia speech synth tests since CARTESIA_API_KEY is not provided');
|
||||||
|
return t.end();
|
||||||
|
}
|
||||||
|
const text = 'Hi there and welcome to jambones! ' + Date.now();
|
||||||
|
try {
|
||||||
|
const opts = await synthAudio(stats, {
|
||||||
|
vendor: 'cartesia',
|
||||||
|
credentials: {
|
||||||
|
api_key: process.env.CARTESIA_API_KEY,
|
||||||
|
model_id: 'sonic-english',
|
||||||
|
options: JSON.stringify({
|
||||||
|
speed: 1,
|
||||||
|
emotion: 'female_happy',
|
||||||
|
})
|
||||||
|
},
|
||||||
|
language: 'en',
|
||||||
|
voice: '694f9389-aac1-45b6-b726-9d9369183238',
|
||||||
|
text,
|
||||||
|
renderForCaching: true
|
||||||
|
});
|
||||||
|
t.ok(!opts.servedFromCache, `successfully playht eleven audio to ${opts.filePath}`);
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error(JSON.stringify(err));
|
||||||
|
t.end(err);
|
||||||
|
}
|
||||||
|
client.quit();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rimelabs speech synth tests mist', async(t) => {
|
||||||
const fn = require('..');
|
const fn = require('..');
|
||||||
const {synthAudio, client} = fn(opts, logger);
|
const {synthAudio, client} = fn(opts, logger);
|
||||||
|
|
||||||
@@ -635,7 +730,7 @@ test('rimelabs speech synth tests', async(t) => {
|
|||||||
}
|
}
|
||||||
const text = 'Hi there and welcome to jambones!';
|
const text = 'Hi there and welcome to jambones!';
|
||||||
try {
|
try {
|
||||||
let opts = await synthAudio(stats, {
|
const opts = await synthAudio(stats, {
|
||||||
vendor: 'rimelabs',
|
vendor: 'rimelabs',
|
||||||
credentials: {
|
credentials: {
|
||||||
api_key: process.env.RIMELABS_API_KEY,
|
api_key: process.env.RIMELABS_API_KEY,
|
||||||
@@ -645,7 +740,7 @@ test('rimelabs speech synth tests', async(t) => {
|
|||||||
reduceLatency: false
|
reduceLatency: false
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
language: 'en-US',
|
language: 'eng',
|
||||||
voice: 'amber',
|
voice: 'amber',
|
||||||
text,
|
text,
|
||||||
renderForCaching: true
|
renderForCaching: true
|
||||||
@@ -659,6 +754,40 @@ test('rimelabs speech synth tests', async(t) => {
|
|||||||
client.quit();
|
client.quit();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('rimelabs speech synth tests mistv2', async(t) => {
|
||||||
|
const fn = require('..');
|
||||||
|
const {synthAudio, client} = fn(opts, logger);
|
||||||
|
|
||||||
|
if (!process.env.RIMELABS_API_KEY) {
|
||||||
|
t.pass('skipping rimelabs speech synth tests since RIMELABS_API_KEY is not provided');
|
||||||
|
return t.end();
|
||||||
|
}
|
||||||
|
const text = 'Hi there and welcome to jambones!';
|
||||||
|
try {
|
||||||
|
const opts = await synthAudio(stats, {
|
||||||
|
vendor: 'rimelabs',
|
||||||
|
credentials: {
|
||||||
|
api_key: process.env.RIMELABS_API_KEY,
|
||||||
|
model_id: 'mistv2',
|
||||||
|
options: JSON.stringify({
|
||||||
|
speedAlpha: 1.0,
|
||||||
|
reduceLatency: false
|
||||||
|
})
|
||||||
|
},
|
||||||
|
language: 'spa',
|
||||||
|
voice: 'pablo',
|
||||||
|
text,
|
||||||
|
renderForCaching: true
|
||||||
|
});
|
||||||
|
t.ok(!opts.servedFromCache, `successfully synthesized rimelabs mistv2 audio to ${opts.filePath}`);
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error(JSON.stringify(err));
|
||||||
|
t.end(err);
|
||||||
|
}
|
||||||
|
client.quit();
|
||||||
|
});
|
||||||
|
|
||||||
test('whisper speech synth tests', async(t) => {
|
test('whisper speech synth tests', async(t) => {
|
||||||
const fn = require('..');
|
const fn = require('..');
|
||||||
const {synthAudio, client} = fn(opts, logger);
|
const {synthAudio, client} = fn(opts, logger);
|
||||||
@@ -758,11 +887,11 @@ 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, text: i}), i);
|
await client.set(makeSynthKey({vendor: i, language: i, voice: i, engine: i, model: i, text: i}), i);
|
||||||
}
|
}
|
||||||
const count = await getTtsSize();
|
const count = await getTtsSize();
|
||||||
t.ok(count >= minRecords, 'getTtsSize worked.');
|
t.ok(count >= minRecords, 'getTtsSize worked.');
|
||||||
|
|
||||||
const {purgedCount} = await purgeTtsCache();
|
const {purgedCount} = await purgeTtsCache();
|
||||||
t.ok(purgedCount >= minRecords, `successfully purged at least ${minRecords} tts records from cache`);
|
t.ok(purgedCount >= minRecords, `successfully purged at least ${minRecords} tts records from cache`);
|
||||||
|
|
||||||
@@ -793,24 +922,15 @@ test('TTS Cache tests', async(t) => {
|
|||||||
language: 'non-existing',
|
language: 'non-existing',
|
||||||
voice: 'non-existing',
|
voice: 'non-existing',
|
||||||
});
|
});
|
||||||
t.ok(purgedCountWhenErrored === 0, `purged no records when specified key was not found`);
|
t.ok(purgedCountWhenErrored === 0, 'purged no records when specified key was not found');
|
||||||
t.ok(error, `error returned when specified key was not found`);
|
t.ok(error, 'error returned when specified key was not found');
|
||||||
|
|
||||||
// make sure other tts keys are still there
|
// make sure other tts keys are still there
|
||||||
const cached = await client.keys('tts:*')
|
const cached = await client.keys('tts:*');
|
||||||
t.ok(cached.length >= 1, `successfully kept all non-specified tts records in cache`);
|
t.ok(cached.length >= 1, 'successfully kept all non-specified tts records in cache');
|
||||||
|
|
||||||
// retrieve keys from cache and check the key contains the file extension
|
process.env.VG_TRIM_TTS_SILENCE = 'true';
|
||||||
let key = cached[0];
|
|
||||||
t.ok(key.includes('mp3'), `tts cache extension shoult be part of the key and equal mp3`);
|
|
||||||
|
|
||||||
process.env.VG_TRIM_TTS_SILENCE = 'true';
|
|
||||||
await client.set(makeSynthKey({ vendor: 'azure' }), 'value');
|
await client.set(makeSynthKey({ vendor: 'azure' }), 'value');
|
||||||
|
|
||||||
const r8Keys = await client.keys('tts:r8*');
|
|
||||||
key = r8Keys[0];
|
|
||||||
t.ok(key.includes('r8'), `tts cache extension shoult be part of the key and equal r8`);
|
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(JSON.stringify(err));
|
console.error(JSON.stringify(err));
|
||||||
t.end(err);
|
t.end(err);
|
||||||
|
|||||||
Reference in New Issue
Block a user