Compare commits

..
Author SHA1 Message Date
Quan HL dcb7e4cffb cartesia should have speed if speed value is 0.0 2024-12-17 14:17:31 +07:00
8 changed files with 936 additions and 808 deletions
+2 -32
View File
@@ -3,29 +3,8 @@ const {noopLogger, makeSynthKey} = require('./utils');
const {JAMBONES_TTS_CACHE_DURATION_MINS} = require('./config');
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,
{account_sid, vendor, language, voice, deploymentId, engine, model, text, instructions}) {
{account_sid, vendor, language, voice, deploymentId, engine, text}) {
let key;
logger = logger || noopLogger;
@@ -36,19 +15,10 @@ async function addFileToCache(client, logger, path,
language: language || '',
voice: voice || deploymentId,
engine,
model,
text,
instructions
});
const [extension, sampleRate] = getExtensionAndSampleRate(path);
const audioBuffer = await fs.readFile(path);
await client.setex(key, EXPIRES, JSON.stringify(
{
audioContent: audioBuffer.toString('base64'),
extension,
sampleRate
}
));
await client.setex(key, EXPIRES, audioBuffer.toString('base64'));
} catch (err) {
logger.error(err, 'addFileToCache: Error');
return;
+1 -3
View File
@@ -2,7 +2,6 @@ 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_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_AZURE_ENABLE_SSML = process.env.JAMBONES_AZURE_ENABLE_SSML;
const JAMBONES_HTTP_PROXY_IP = process.env.JAMBONES_HTTP_PROXY_IP;
const JAMBONES_HTTP_PROXY_PORT = process.env.JAMBONES_HTTP_PROXY_PORT;
@@ -22,6 +21,5 @@ module.exports = {
JAMBONES_TTS_CACHE_DURATION_MINS,
JAMBONES_EAGERLY_PRE_CACHE_AUDIO,
TMP_FOLDER,
HTTP_TIMEOUT,
JAMBONES_AZURE_ENABLE_SSML
HTTP_TIMEOUT
};
+1 -3
View File
@@ -12,7 +12,7 @@ const debug = require('debug')('jambonz:realtimedb-helpers');
* @returns {object} result - {error, purgedCount}
*/
async function purgeTtsCache(client, logger, {all, account_sid, vendor,
language, voice, deploymentId, engine, model, text, instructions} = {all: true}) {
language, voice, deploymentId, engine, text} = {all: true}) {
logger = logger || noopLogger;
let purgedCount = 0, error;
@@ -33,9 +33,7 @@ async function purgeTtsCache(client, logger, {all, account_sid, vendor,
language: language || '',
voice: voice || deploymentId,
engine,
model,
text,
instructions
});
purgedCount = await client.del(key);
if (purgedCount === 0) error = 'Specified item not found';
+140 -285
View File
@@ -46,8 +46,7 @@ const {
JAMBONES_HTTP_PROXY_IP,
JAMBONES_HTTP_PROXY_PORT,
JAMBONES_TTS_CACHE_DURATION_MINS,
JAMBONES_TTS_TRIM_SILENCE,
JAMBONES_AZURE_ENABLE_SSML
JAMBONES_EAGERLY_PRE_CACHE_AUDIO,
} = require('./config');
const EXPIRES = JAMBONES_TTS_CACHE_DURATION_MINS;
const OpenAI = require('openai');
@@ -90,15 +89,15 @@ const trimTrailingSilence = (buffer) => {
*/
async function synthAudio(client, createHash, retrieveHash, logger, stats, { account_sid,
vendor, language, voice, gender, text, engine, salt, model, credentials, deploymentId,
disableTtsCache, renderForCaching = false, disableTtsStreaming, options, instructions
disableTtsCache, renderForCaching = false, disableTtsStreaming, options
}) {
let audioData;
let audioBuffer;
let servedFromCache = false;
let rtt;
logger = logger || noopLogger;
assert.ok(['google', 'aws', 'polly', 'microsoft', 'wellsaid', 'nuance', 'nvidia', 'ibm', 'elevenlabs',
'whisper', 'deepgram', 'playht', 'rimelabs', 'verbio', 'cartesia', 'inworld'].includes(vendor) ||
'whisper', 'deepgram', 'playht', 'rimelabs', 'verbio', 'cartesia'].includes(vendor) ||
vendor.startsWith('custom'),
`synthAudio supported vendors are google, aws, microsoft, nuance, nvidia and wellsaid ..etc, not ${vendor}`);
if ('google' === vendor) {
@@ -141,10 +140,6 @@ 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.user_id, 'synthAudio requires user_id 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) {
assert.ok(voice, 'synthAudio requires voice when rimelabs is used');
assert.ok(credentials.api_key, 'synthAudio requires api_key when rimelabs is used');
@@ -174,27 +169,57 @@ async function synthAudio(client, createHash, retrieveHash, logger, stats, { acc
language: language || '',
voice: voice || deploymentId,
engine,
// model or model_id is used to identify the tts cache.
model: model || credentials.model_id,
text,
instructions
renderForCaching
});
let filePath;
// used only for custom vendor
let fileExtension;
filePath = makeFilePath({vendor, voice, key, salt, renderForCaching});
debug(`synth key is ${key}`);
let cached;
if (!disableTtsCache) {
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, voice, key, salt, renderForCaching: true});
}
}
}
if (cached) {
// found in cache - extend the expiry and use it
debug('result WAS found in cache');
servedFromCache = true;
stats.increment('tts.cache.requests', ['found:yes']);
audioData = JSON.parse(cached);
// convert base64 audio to buffer
audioData.audioContent = Buffer.from(audioData.audioContent, 'base64');
if (vendor.startsWith('custom')) {
// custom vendors support multiple mime types such as: mp3, wav, r8, r16 ...etc,
// mime type/file extension is available when http response has header Content-type.
// In cache, file extension is store together with audiBuffer in a json.
// Normal cache audio will be base64 string
const payload = JSON.parse(cached);
filePath = filePath.replace(/\.[^\.]*$/g, payload.fileExtension);
audioBuffer = Buffer.from(payload.audioBuffer, 'base64');
} else {
audioBuffer = Buffer.from(cached, 'base64');
}
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
debug('result was NOT found in cache');
stats.increment('tts.cache.requests', ['found:no']);
@@ -202,97 +227,94 @@ async function synthAudio(client, createHash, retrieveHash, logger, stats, { acc
const startAt = process.hrtime();
switch (vendor) {
case 'google':
audioData = await synthGoogle(logger, {credentials, stats, language, voice, gender, text});
audioBuffer = await synthGoogle(logger, {credentials, stats, language, voice, gender, text});
break;
case 'aws':
case 'polly':
vendorLabel = 'aws';
audioData = await synthPolly(createHash, retrieveHash, logger,
audioBuffer = await synthPolly(createHash, retrieveHash, logger,
{credentials, stats, language, voice, text, engine});
break;
case 'azure':
case 'microsoft':
vendorLabel = 'microsoft';
audioData = await synthMicrosoft(logger, {credentials, stats, language, voice, text, deploymentId,
renderForCaching, disableTtsStreaming});
audioBuffer = await synthMicrosoft(logger, {credentials, stats, language, voice, text, deploymentId,
filePath, renderForCaching, disableTtsStreaming});
break;
case 'nuance':
model = model || 'enhanced';
audioData = await synthNuance(client, logger, {credentials, stats, voice, model, text});
audioBuffer = await synthNuance(client, logger, {credentials, stats, voice, model, text});
break;
case 'nvidia':
audioData = await synthNvidia(client, logger, {credentials, stats, language, voice, model, text,
renderForCaching, disableTtsStreaming});
audioBuffer = await synthNvidia(client, logger, {credentials, stats, language, voice, model, text});
break;
case 'ibm':
audioData = await synthIbm(logger, {credentials, stats, voice, text});
audioBuffer = await synthIbm(logger, {credentials, stats, voice, text});
break;
case 'wellsaid':
audioData = await synthWellSaid(logger, {credentials, stats, language, voice, text});
audioBuffer = await synthWellSaid(logger, {credentials, stats, language, voice, text, filePath});
break;
case 'elevenlabs':
audioData = await synthElevenlabs(logger, {
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming});
audioBuffer = await synthElevenlabs(logger, {
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming, filePath
});
break;
case 'playht':
audioData = await synthPlayHT(client, logger, {
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming});
audioBuffer = await synthPlayHT(client, logger, {
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming, filePath
});
break;
case 'cartesia':
audioData = await synthCartesia(logger, {
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming});
break;
case 'inworld':
audioData = await synthInworld(logger, {
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming});
audioBuffer = await synthCartesia(logger, {
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming, filePath
});
break;
case 'rimelabs':
audioData = await synthRimelabs(logger, {
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming});
audioBuffer = await synthRimelabs(logger, {
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming, filePath
});
break;
case 'whisper':
audioData = await synthWhisper(logger, {
credentials, stats, voice, text, instructions, renderForCaching, disableTtsStreaming});
audioBuffer = await synthWhisper(logger, {
credentials, stats, voice, text, renderForCaching, disableTtsStreaming});
break;
case 'verbio':
audioData = await synthVerbio(client, logger, {
audioBuffer = await synthVerbio(client, logger, {
credentials, stats, voice, text, renderForCaching, disableTtsStreaming});
if (audioData?.filePath) return audioData;
if (audioBuffer?.filePath) return audioBuffer;
break;
case 'deepgram':
audioData = await synthDeepgram(logger, {credentials, stats, model, text,
audioBuffer = await synthDeepgram(logger, {credentials, stats, model, text,
renderForCaching, disableTtsStreaming});
break;
case vendor.startsWith('custom') ? vendor : 'cant_match_value':
audioData = await synthCustomVendor(logger,
{credentials, stats, language, voice, text});
({ audioBuffer, filePath, fileExtension } = await synthCustomVendor(logger,
{credentials, stats, language, voice, text, filePath}));
break;
default:
assert(`synthAudio: unsupported speech vendor ${vendor}`);
}
if ('filePath' in audioData) return audioData;
if ('filePath' in audioBuffer) return audioBuffer;
const diff = process.hrtime(startAt);
const time = diff[0] * 1e3 + diff[1] * 1e-6;
rtt = time.toFixed(0);
stats.histogram('tts.response_time', rtt, [`vendor:${vendorLabel}`]);
debug(`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, JSON.stringify({
...audioData,
audioContent: audioData.audioContent?.toString('base64')
}))
const base64Audio = audioBuffer.toString('base64');
const cacheContent = vendor.startsWith('custom') ?
JSON.stringify({
audioBuffer: base64Audio,
fileExtension
}) : base64Audio;
client.setex(key, EXPIRES, cacheContent)
.catch((err) => logger.error(err, `error calling setex on key ${key}`));
}
return new Promise((resolve, reject) => {
const { audioContent, extension } = audioData;
const filePath = makeFilePath({
key,
salt,
extension
});
fs.writeFile(filePath, audioContent, (err) => {
fs.writeFile(filePath, audioBuffer, (err) => {
if (err) return reject(err);
resolve({filePath, servedFromCache, rtt});
});
@@ -347,13 +369,7 @@ const synthPolly = async(createHash, retrieveHash, logger,
.on('data', (chunk) => {
chunks.push(chunk);
})
.on('end', () => resolve(
{
audioContent: Buffer.concat(chunks),
extension: 'mp3',
sampleRate: 8000
}
));
.on('end', () => resolve(Buffer.concat(chunks)));
});
} catch (err) {
logger.info({err}, 'synthAudio: Error synthesizing speech using aws polly');
@@ -395,11 +411,7 @@ const synthGoogle = async(logger, {credentials, stats, language, voice, gender,
};
const wav = await post('/v1beta1/text:synthesize', payload);
return {
audioContent: Buffer.from(wav.audioContent, 'base64'),
extension: 'wav',
sampleRate: 24000
};
return Buffer.from(wav.audioContent, 'base64');
} catch (err) {
logger.info({err: await err.text()}, 'synthGoogle returned error');
throw err;
@@ -420,11 +432,7 @@ const synthGoogle = async(logger, {credentials, stats, language, voice, gender,
const responses = await client.synthesizeSpeech(opts);
stats.increment('tts.count', ['vendor:google', 'accepted:yes']);
client.close();
return {
audioContent: responses[0].audioContent,
extension: 'mp3',
sampleRate: 8000
};
return responses[0].audioContent;
} catch (err) {
console.error(err);
logger.info({err, opts}, 'synthAudio: Error synthesizing speech using google');
@@ -455,11 +463,7 @@ const synthIbm = async(logger, {credentials, stats, voice, text}) => {
for await (const chunk of r.result) {
chunks.push(chunk);
}
return {
audioContent: Buffer.concat(chunks),
extension: 'mp3',
sampleRate: 8000
};
return Buffer.concat(chunks);
} catch (err) {
logger.info({err, params}, 'synthAudio: Error synthesizing speech using ibm');
stats.increment('tts.count', ['vendor:ibm', 'accepted:no']);
@@ -469,12 +473,15 @@ const synthIbm = async(logger, {credentials, stats, voice, text}) => {
async function _synthOnPremMicrosoft(logger, {
credentials,
stats,
language,
voice,
text
text,
filePath
}) {
const {use_custom_tts, custom_tts_endpoint_url, api_key} = credentials;
let content = text;
if (use_custom_tts && !content.startsWith('<speak')) {
/**
* Note: it seems that to use custom voice ssml is required with the voice attribute
@@ -490,25 +497,17 @@ 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>`;
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 {
const trimSilence = JAMBONES_TTS_TRIM_SILENCE;
const trimSilence = filePath.endsWith('.r8');
const post = bent('POST', 'buffer', {
'X-Microsoft-OutputFormat': trimSilence ? 'raw-8khz-16bit-mono-pcm' : 'audio-16khz-32kbitrate-mono-mp3',
'Content-Type': 'application/ssml+xml',
'User-Agent': 'Jambonz',
...(api_key && {'Ocp-Apim-Subscription-Key': api_key})
});
const audioContent = await post(custom_tts_endpoint_url, content);
return {
audioContent,
extension: trimSilence ? 'r8' : 'mp3',
sampleRate: 8000
};
const mp3 = await post(custom_tts_endpoint_url, content);
return mp3;
} catch (err) {
logger.info({err}, '_synthMicrosoftByHttp returned error');
throw err;
@@ -521,6 +520,7 @@ const synthMicrosoft = async(logger, {
language,
voice,
text,
filePath,
renderForCaching,
disableTtsStreaming
}) => {
@@ -530,23 +530,19 @@ const synthMicrosoft = async(logger, {
let content = text;
if (use_custom_tts && !content.startsWith('<speak')) {
/**
* 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"
*/
* 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"
*/
content = `<speak>${text}</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, ' ');
// 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>`;
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 &&
!renderForCaching && !disableTtsStreaming) {
let params = '';
@@ -567,18 +563,17 @@ const synthMicrosoft = async(logger, {
rtt: 0
};
}
// Azure Onprem
if (use_custom_tts && custom_tts_endpoint_url) {
return await _synthOnPremMicrosoft(logger, {
credentials,
stats,
language,
voice,
text
text,
filePath
});
}
// Azure hosted service
const trimSilence = JAMBONES_TTS_TRIM_SILENCE;
const trimSilence = filePath.endsWith('.r8');
const speechConfig = SpeechConfig.fromSubscription(apiKey, region);
speechConfig.speechSynthesisLanguage = language;
speechConfig.speechSynthesisVoiceName = voice;
@@ -613,11 +608,7 @@ const synthMicrosoft = async(logger, {
case ResultReason.SynthesizingAudioCompleted:
let buffer = Buffer.from(result.audioData);
if (trimSilence) buffer = trimTrailingSilence(buffer);
resolve({
audioContent: buffer,
extension: trimSilence ? 'r8' : 'mp3',
sampleRate: 8000
});
resolve(buffer);
synthesizer.close();
stats.increment('tts.count', ['vendor:microsoft', 'accepted:yes']);
break;
@@ -647,15 +638,11 @@ const synthWellSaid = async(logger, {credentials, stats, language, voice, gender
'Accept': 'audio/mpeg',
'Content-Type': 'application/json'
});
const audioContent = await post('/v1/tts/stream', {
const mp3 = await post('/v1/tts/stream', {
text,
speaker_id: voice
});
return {
audioContent,
extension: 'mp3',
sampleRate: 8000
};
return mp3;
} catch (err) {
logger.info({err}, 'testWellSaidTts returned error');
throw err;
@@ -692,8 +679,8 @@ const synthNuance = async(client, logger, {credentials, stats, voice, model, tex
t.setText(text);
input.setText(t);
}
const sampleRate = 8000;
pcm.setSampleRateHz(sampleRate);
pcm.setSampleRateHz(8000);
f.setPcm(pcm);
p.setAudioFormat(f);
v.setName(voice);
@@ -717,41 +704,20 @@ const synthNuance = async(client, logger, {credentials, stats, voice, model, tex
const details = status.getDetails();
return reject({code, message, details});
}
resolve({
audioContent: Buffer.from(response.getAudio()),
extension: 'r8',
sampleRate
});
resolve(Buffer.from(response.getAudio()));
});
});
};
const synthNvidia = async(client, logger, {
credentials, stats, language, voice, model, text, renderForCaching, disableTtsStreaming
}) => {
const synthNvidia = async(client, logger, {credentials, stats, language, voice, model, text}) => {
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;
const sampleRate = 8000;
try {
rivaClient = await createRivaClient(riva_server_uri);
request = new SynthesizeSpeechRequest();
request.setVoiceName(voice);
request.setLanguageCode(language);
request.setSampleRateHz(sampleRate);
request.setSampleRateHz(8000);
request.setEncoding(AudioEncoding.LINEAR_PCM);
request.setText(text);
} catch (err) {
@@ -765,11 +731,7 @@ const synthNvidia = async(client, logger, {
logger.info({err, voice, language}, 'error synthesizing speech using Nvidia');
return reject(err);
}
resolve({
audioContent: Buffer.from(response.getAudio()),
extension: 'r8',
sampleRate
});
resolve(Buffer.from(response.getAudio()));
});
});
};
@@ -791,13 +753,14 @@ const synthCustomVendor = async(logger, {credentials, stats, language, voice, te
text
});
const regex = /\.[^\.]*$/g;
const mime = response.headers['content-type'];
const buffer = await response.arrayBuffer();
const [extension, sampleRate] = getFileExtFromMime(mime);
const fileExtension = getFileExtFromMime(mime);
return {
audioContent: buffer,
extension,
sampleRate
audioBuffer: buffer,
filePath: filePath.replace(regex, fileExtension),
fileExtension
};
} catch (err) {
logger.info({err}, `Vendor ${vendor} returned error`);
@@ -823,13 +786,9 @@ const synthElevenlabs = async(logger, {
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?.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.previous_text) params += `,previous_text=${opts.previous_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 += '}';
return {
@@ -847,7 +806,7 @@ const synthElevenlabs = async(logger, {
'Accept': 'audio/mpeg',
'Content-Type': 'application/json'
});
const audioContent = await post(`/v1/text-to-speech/${voice}${optimize_streaming_latency}`, {
const mp3 = await post(`/v1/text-to-speech/${voice}${optimize_streaming_latency}`, {
text,
model_id,
voice_settings: {
@@ -856,11 +815,7 @@ const synthElevenlabs = async(logger, {
},
...opts
});
return {
audioContent,
extension: 'mp3',
sampleRate: 8000
};
return mp3;
} catch (err) {
logger.info({err}, 'synth Elevenlabs returned error');
stats.increment('tts.count', ['vendor:elevenlabs', 'accepted:no']);
@@ -871,10 +826,11 @@ const synthElevenlabs = async(logger, {
const synthPlayHT = async(client, logger, {
credentials, options, stats, voice, language, text, renderForCaching, disableTtsStreaming
}) => {
const {api_key, user_id, voice_engine, playht_tts_uri, options: credOpts} = credentials;
const {api_key, user_id, voice_engine, options: credOpts} = credentials;
const opts = !!options && Object.keys(options).length !== 0 ? options : JSON.parse(credOpts || '{}');
let synthesizeUrl = playht_tts_uri ? `${playht_tts_uri}/api/v2/tts/stream` : 'https://api.play.ht/api/v2/tts/stream';
let synthesizeUrl = 'https://api.play.ht/api/v2/tts/stream';
// If model is play3.0, the synthesizeUrl is got from authentication endpoint
if (voice_engine === 'Play3.0') {
try {
@@ -941,7 +897,7 @@ const synthPlayHT = async(client, logger, {
'Content-Type': 'application/json'
});
const audioContent = await post(synthesizeUrl, {
const mp3 = await post(synthesizeUrl, {
text,
...(voice_engine === 'Play3.0' && { language }),
voice,
@@ -950,11 +906,7 @@ const synthPlayHT = async(client, logger, {
sample_rate: 8000,
...opts
});
return {
audioContent,
extension: 'mp3',
sampleRate: 8000
};
return mp3;
} catch (err) {
logger.info({err}, 'synth PlayHT returned error');
stats.increment('tts.count', ['vendor:playht', 'accepted:no']);
@@ -962,92 +914,22 @@ const synthPlayHT = async(client, logger, {
}
};
const synthInworld = async(logger, {
const synthRimelabs = async(logger, {
credentials, options, stats, voice, text, renderForCaching, disableTtsStreaming
}) => {
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 += `,model_id=${model_id}`;
params += ',vendor=inworld';
params += `,voice=${voice}`;
params += ',write_cache_file=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, text, renderForCaching, disableTtsStreaming
}) => {
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 += `,model_id=${model_id}`;
params += ',vendor=rimelabs';
params += `,language=${language}`;
params += `,voice=${voice}`;
params += ',write_cache_file=1';
if (opts.speedAlpha) params += `,speed_alpha=${opts.speedAlpha}`;
if (opts.reduceLatency) params += `,reduce_latency=${opts.reduceLatency}`;
// Arcana model parameters
if (opts.temperature) params += `,temperature=${opts.temperature}`;
if (opts.repetition_penalty) params += `,repetition_penalty=${opts.repetition_penalty}`;
if (opts.top_p) params += `,top_p=${opts.top_p}`;
if (opts.max_tokens) params += `,max_tokens=${opts.max_tokens}`;
params += '}';
return {
@@ -1063,20 +945,14 @@ const synthRimelabs = async(logger, {
'Accept': 'audio/mp3',
'Content-Type': 'application/json'
});
const sampleRate = 8000;
const audioContent = await post('/v1/rime-tts', {
const mp3 = await post('/v1/rime-tts', {
speaker: voice,
text,
modelId: model_id,
samplingRate: sampleRate,
lang: language,
samplingRate: 8000,
...opts
});
return {
audioContent,
extension: 'mp3',
sampleRate
};
return mp3;
} catch (err) {
logger.info({err}, 'synth rimelabs returned error');
stats.increment('tts.count', ['vendor:rimelabs', 'accepted:no']);
@@ -1110,17 +986,13 @@ const synthVerbio = async(client, logger, {credentials, stats, voice, text, rend
'User-Agent': 'jambonz',
'Content-Type': 'application/json'
});
const audioContent = await post('/api/v1/synthesize', {
const r8 = await post('/api/v1/synthesize', {
voice_id: voice,
output_sample_rate: '8k',
output_encoding: 'pcm16',
text
});
return {
audioContent,
extension: 'r8',
sampleRate: 8000
};
return r8;
} catch (err) {
logger.info({err}, 'synth Verbio returned error');
stats.increment('tts.count', ['vendor:verbio', 'accepted:no']);
@@ -1128,8 +1000,7 @@ const synthVerbio = async(client, logger, {credentials, stats, voice, text, rend
}
};
const synthWhisper = async(logger, {credentials, stats, voice, text, instructions,
renderForCaching, disableTtsStreaming}) => {
const synthWhisper = async(logger, {credentials, stats, voice, text, renderForCaching, disableTtsStreaming}) => {
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 (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
@@ -1140,8 +1011,6 @@ const synthWhisper = async(logger, {credentials, stats, voice, text, instruction
params += `,voice=${voice}`;
params += ',write_cache_file=1';
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 += '}';
return {
@@ -1161,14 +1030,9 @@ const synthWhisper = async(logger, {credentials, stats, voice, text, instruction
model: model_id,
voice,
input: text,
...(instructions && {instructions}),
response_format: 'mp3'
});
return {
audioContent: Buffer.from(await mp3.arrayBuffer()),
extension: 'mp3',
sampleRate: 8000
};
return Buffer.from(await mp3.arrayBuffer());
} catch (err) {
logger.info({err}, 'synth whisper returned error');
stats.increment('tts.count', ['vendor:openai', 'accepted:no']);
@@ -1200,14 +1064,10 @@ const synthDeepgram = async(logger, {credentials, stats, model, text, renderForC
'Accept': 'audio/mpeg',
'Content-Type': 'application/json'
});
const audioContent = await post(`/v1/speak?model=${model}`, {
const mp3 = await post(`/v1/speak?model=${model}`, {
text
});
return {
audioContent,
extension: 'mp3',
sampleRate: 8000
};
return mp3;
} catch (err) {
logger.info({err}, 'synth Deepgram returned error');
stats.increment('tts.count', ['vendor:deepgram', 'accepted:no']);
@@ -1244,7 +1104,6 @@ const synthCartesia = async(logger, {
try {
const client = new CartesiaClient({ apiKey: api_key });
const sampleRate = 48000;
const mp3 = await client.tts.bytes({
modelId: model_id,
transcript: text,
@@ -1269,14 +1128,10 @@ const synthCartesia = async(logger, {
outputFormat: {
container: 'mp3',
bitRate: 128000,
sampleRate
sampleRate: 8000
},
});
return {
audioContent: Buffer.from(mp3),
extension: 'mp3',
sampleRate
};
return Buffer.from(mp3);
} catch (err) {
logger.info({err}, 'synth Cartesia returned error');
stats.increment('tts.count', ['vendor:cartesia', 'accepted:no']);
@@ -1289,22 +1144,22 @@ const getFileExtFromMime = (mime) => {
switch (mime) {
case 'audio/wav':
case 'audio/x-wav':
return ['wav', 8000];
return '.wav';
case /audio\/l16.*rate=8000/.test(mime) ? mime : 'cant match value':
return ['r8', 8000];
return '.r8';
case /audio\/l16.*rate=16000/.test(mime) ? mime : 'cant match value':
return ['r16', 16000];
return '.r16';
case /audio\/l16.*rate=24000/.test(mime) ? mime : 'cant match value':
return ['r24', 24000];
return '.r24';
case /audio\/l16.*rate=32000/.test(mime) ? mime : 'cant match value':
return ['r32', 32000];
return '.r32';
case /audio\/l16.*rate=48000/.test(mime) ? mime : 'cant match value':
return ['r48', 48000];
return '.r48';
case 'audio/mpeg':
case 'audio/mp3':
return ['mp3', 8000];
return '.mp3';
default:
return ['wav', 8000];
return '.wav';
}
};
+54 -13
View File
@@ -6,7 +6,7 @@ const pool = new Pool('https://auth.crt.nuance.com');
const NUANCE_AUTH_ENDPOINT = 'tts.api.nuance.com:443';
const grpc = require('@grpc/grpc-js');
const formurlencoded = require('form-urlencoded');
const { TMP_FOLDER, HTTP_TIMEOUT } = require('./config');
const { JAMBONES_DISABLE_TTS_STREAMING, JAMBONES_TTS_TRIM_SILENCE, TMP_FOLDER, HTTP_TIMEOUT } = require('./config');
const debug = require('debug')('jambonz:realtimedb-helpers');
/**
@@ -17,27 +17,68 @@ const debug = require('debug')('jambonz:realtimedb-helpers');
//const nuanceClientMap = new Map();
function makeSynthKey({
account_sid = '',
vendor,
language,
voice,
engine = '',
model = '',
text,
instructions = '',
}) {
account_sid = '', vendor, language, voice, engine = '', text,
renderForCaching = false}) {
const hash = crypto.createHash('sha1');
hash.update(`${language}:${vendor}:${voice}:${engine}:${model}:${text}:${instructions}`);
hash.update(`${language}:${vendor}:${voice}:${engine}:${text}`);
const hexHashKey = hash.digest('hex');
const accountKey = account_sid ? `:${account_sid}` : '';
const key = `tts${accountKey}:${hexHashKey}`;
const namespace = vendor.startsWith('custom') ? vendor : getFileExtension({vendor, voice, renderForCaching});
const key = `tts${accountKey}:${namespace}:${hexHashKey}`;
return key;
}
function makeFilePath({key, salt = '', extension}) {
function makeFilePath({vendor, voice, key, salt = '', renderForCaching = false}) {
const extension = getFileExtension({vendor, renderForCaching, voice});
return `${TMP_FOLDER}/${key.replace('tts:', `tts-${salt}`)}.${extension}`;
}
function getFileExtension({vendor, voice, renderForCaching = false}) {
const mp3Extension = 'mp3';
const r8Extension = 'r8';
const wavExtension = 'wav';
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':
case 'cartesia':
if (renderForCaching || JAMBONES_DISABLE_TTS_STREAMING) {
return mp3Extension;
} else {
return r8Extension;
}
case 'nuance':
case 'nvidia':
case 'verbio':
return r8Extension;
case 'google':
// google voice cloning just support wav.
if (typeof voice === 'object' && voice.voice_cloning_key) {
return wavExtension;
} else {
return mp3Extension;
}
default:
// If vendor is custom
if (vendor.startsWith('custom')) {
if (renderForCaching || JAMBONES_DISABLE_TTS_STREAMING) {
return mp3Extension;
} else {
return r8Extension;
}
}
return mp3Extension;
}
}
const noopLogger = {
info: () => {},
+712 -389
View File
File diff suppressed because it is too large Load Diff
+3 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@jambonz/speech-utils",
"version": "0.2.13",
"version": "0.1.24",
"description": "TTS-related speech utilities for jambonz",
"main": "index.js",
"author": "Dave Horton",
@@ -26,7 +26,6 @@
},
"homepage": "https://github.com/jambonz/speech-utils#readme",
"dependencies": {
"23": "^0.0.0",
"@aws-sdk/client-polly": "^3.496.0",
"@aws-sdk/client-sts": "^3.496.0",
"@cartesia/cartesia-js": "^2.1.0",
@@ -39,8 +38,8 @@
"google-protobuf": "^3.21.2",
"ibm-watson": "^8.0.0",
"microsoft-cognitiveservices-speech-sdk": "1.38.0",
"openai": "^4.98.0",
"undici": "^7.5.0"
"openai": "^4.25.0",
"undici": "^6.4.0"
},
"devDependencies": {
"config": "^3.3.11",
+23 -79
View File
@@ -5,7 +5,7 @@ const fs = require('fs');
const {makeSynthKey} = require('../lib/utils');
const logger = require('pino')();
const bent = require('bent');
const getJSON = bent('json');
const getJSON = bent('json')
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
@@ -720,37 +720,7 @@ test('Cartesia speech synth tests', async(t) => {
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('rimelabs speech synth tests mist', async(t) => {
test('rimelabs speech synth tests', async(t) => {
const fn = require('..');
const {synthAudio, client} = fn(opts, logger);
@@ -760,7 +730,7 @@ test('rimelabs speech synth tests mist', async(t) => {
}
const text = 'Hi there and welcome to jambones!';
try {
const opts = await synthAudio(stats, {
let opts = await synthAudio(stats, {
vendor: 'rimelabs',
credentials: {
api_key: process.env.RIMELABS_API_KEY,
@@ -770,7 +740,7 @@ test('rimelabs speech synth tests mist', async(t) => {
reduceLatency: false
})
},
language: 'eng',
language: 'en-US',
voice: 'amber',
text,
renderForCaching: true
@@ -784,40 +754,6 @@ test('rimelabs speech synth tests mist', async(t) => {
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) => {
const fn = require('..');
const {synthAudio, client} = fn(opts, logger);
@@ -917,12 +853,11 @@ test('TTS Cache tests', async(t) => {
// save some random tts keys to cache
const minRecords = 8;
for (const i in Array(minRecords).fill(0)) {
await client.set(makeSynthKey({vendor: i, language: i, voice: i, engine: i, model: i, text: i,
instructions: i}), i);
await client.set(makeSynthKey({vendor: i, language: i, voice: i, engine: i, text: i}), i);
}
const count = await getTtsSize();
t.ok(count >= minRecords, 'getTtsSize worked.');
const {purgedCount} = await purgeTtsCache();
t.ok(purgedCount >= minRecords, `successfully purged at least ${minRecords} tts records from cache`);
@@ -937,7 +872,7 @@ test('TTS Cache tests', async(t) => {
try {
// save some random tts keys to cache
for (const i in Array(10).fill(0)) {
await client.set(makeSynthKey({vendor: i, language: i, voice: i, engine: i, text: i, instructions: i}), i);
await client.set(makeSynthKey({vendor: i, language: i, voice: i, engine: i, text: i}), i);
}
// save a specific key to tts cache
const opts = {vendor: 'aws', language: 'en-US', voice: 'MALE', engine: 'Engine', text: 'Hello World!'};
@@ -953,15 +888,24 @@ test('TTS Cache tests', async(t) => {
language: 'non-existing',
voice: 'non-existing',
});
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(purgedCountWhenErrored === 0, `purged no records 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
const cached = await client.keys('tts:*');
t.ok(cached.length >= 1, 'successfully kept all non-specified tts records in cache');
const cached = await client.keys('tts:*')
t.ok(cached.length >= 1, `successfully kept all non-specified tts records in cache`);
process.env.VG_TRIM_TTS_SILENCE = 'true';
// retrieve keys from cache and check the key contains the file extension
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');
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) {
console.error(JSON.stringify(err));
t.end(err);
@@ -975,10 +919,10 @@ test('TTS Cache tests', async(t) => {
const account_sid = "12412512_cabc_5aff"
const account_sid2 = "22412512_cabc_5aff"
for (const i in Array(minRecords).fill(0)) {
await client.set(makeSynthKey({account_sid, vendor: i, language: i, voice: i, engine: i, text: i, instructions: i}), i);
await client.set(makeSynthKey({account_sid, vendor: i, language: i, voice: i, engine: i, text: i}), i);
}
for (const i in Array(minRecords).fill(0)) {
await client.set(makeSynthKey({account_sid: account_sid2, vendor: i, language: i, voice: i, engine: i, text: i, instructions: i}), i);
await client.set(makeSynthKey({account_sid: account_sid2, vendor: i, language: i, voice: i, engine: i, text: i}), i);
}
const {purgedCount} = await purgeTtsCache({account_sid});
t.equal(purgedCount, minRecords, `successfully purged at least ${minRecords} tts records from cache for account_sid:${account_sid}`);