Compare commits

...
98 Commits
Author SHA1 Message Date
Dave Horton 7b4a71f55d 0.2.3 2025-02-07 07:20:12 -05:00
Dave Horton d552b65618 Merge pull request #106 from jambonz/feat/rimelabs_voices
rimelabs support multiple model and languages
2025-02-07 07:19:47 -05:00
Quan HL f701b50244 rimelabs support multiple model and languages 2025-02-07 14:20:52 +07:00
Dave Horton 199e502fbe 0.2.2 2025-02-03 08:14:15 -05:00
Dave Horton 6769779189 Merge pull request #105 from jambonz/fix/gh_1059
tts key should include model
2025-02-03 08:13:54 -05:00
Quan HL 4b43c3986c wip 2025-02-02 19:03:09 +07:00
Quan HL e1292772e6 tts key should include model 2025-02-02 18:54:16 +07:00
Dave Horton 37fb045431 0.2.1 2024-12-18 22:16:43 -05:00
Dave Horton c328df67a2 major semver bump 2024-12-18 22:15:28 -05:00
Dave Horton 877cba7065 Merge pull request #103 from jambonz/feat/refactor_synth
remove audio extension from audio key
2024-12-18 22:13:52 -05:00
Quan HL 35a178b468 remove audio extension from audio key 2024-12-18 16:58:54 +07:00
Quan HL 7327190471 remove audio extension from audio key 2024-12-18 16:46:24 +07:00
Dave Horton e5b5e3d0c6 0.1.24 2024-12-16 07:27:18 -05:00
Dave Horton 3760be088b update deps 2024-12-16 07:26:49 -05:00
Dave Horton 5cb52eb8ec Merge pull request #101 from jambonz/feat/tts_cartesia
support cartesia tts
2024-12-16 07:25:29 -05:00
Quan HL 8a390a8edf support cartesia tts 2024-12-16 15:58:18 +07:00
Dave Horton d96ab5cdf3 Merge pull request #99 from jambonz/feat/support_aws_instance_profile
support aws instance profile to get key
2024-11-29 21:58:22 -05:00
Quan HL 3bf74671c6 support aws instance profile to get key 2024-11-30 08:40:26 +07:00
Dave Horton a47ef6d7c4 0.1.22 2024-11-04 07:38:23 -05:00
Dave Horton 84089fa528 Merge pull request #98 from jambonz/fix/freshdesk_411
Fix custom tts vendor cached file can not be played
2024-11-04 07:37:49 -05:00
Quan HL 72be44eea2 adding testcase 2024-11-04 15:53:11 +07:00
Quan HL 05d6c4b32d fixed custom vendor cache audio stores file extension 2024-11-04 15:43:44 +07:00
Dave Horton 0c7e15d0a2 0.1.21 2024-10-31 09:48:18 -04:00
Dave Horton 63efecf9d9 Merge pull request #97 from jambonz/feat/google_voice_cloning
support google voice cloning
2024-10-31 09:47:12 -04:00
Quan HL 153ac3f1a4 fix review comment 2024-10-31 20:30:35 +07:00
Quan HL 115faa9f89 support google voice cloning 2024-10-31 20:23:11 +07:00
Dave Horton f183852961 0.1.20 2024-10-18 12:23:26 -04:00
Dave Horton 34c3e01729 Merge pull request #95 from jambonz/fix/rimelabs
fix rimelabs typo issue on getFileExtension function
2024-10-18 12:22:52 -04:00
Quan HL 9b2b16199e fix rimelabs typo issue on getFileExtension function 2024-10-18 22:44:17 +07:00
Dave Horton 9112c5f0ea 0.1.19 2024-10-16 07:23:40 -04:00
Dave Horton 50783dfd0a Merge pull request #94 from jambonz/fix/playht30_lang
add language to playht3.0
2024-10-16 07:23:04 -04:00
Quan HL ca0ef76fe1 add language to playht3.0 2024-10-16 08:14:38 +07:00
Dave Horton 7c91c537e4 0.1.18 2024-10-11 07:33:37 -04:00
Dave Horton 9747526664 Merge pull request #93 from jambonz/fix/playht_3.0
fixed playht3.0 cannot be played if credential is cached
2024-10-11 07:32:57 -04:00
Quan HL 31a0c7b02c fixed playht3.0 cannot be played if credential is cached 2024-10-11 12:05:38 +07:00
Dave Horton c18fbacd1b update playht3 2024-10-09 13:29:01 -04:00
Dave Horton b0fee6bbf1 Merge pull request #92 from jambonz/feat/playht30
support playht3.0
2024-10-09 13:26:53 -04:00
Quan HL f6cead6e92 add top_p and repetition_penalty to playht3.0 2024-10-03 19:24:23 +07:00
Quan HL 05fc96edc0 wip 2024-09-27 18:24:03 +07:00
Quan HL 6794a0b3be support playht3.0 2024-09-27 12:25:47 +07:00
Quan HL 1a04fd736c support playht3.0 2024-09-27 12:08:41 +07:00
Dave Horton 1846203807 0.1.16 2024-09-16 15:53:14 -04:00
Dave Horton 75be8658c1 Merge pull request #91 from jambonz/fix/diff_playht_voice_quality
fix playht has stream and cached audio differrent quality
2024-09-16 15:52:42 -04:00
Quan HL 91a5eebbaf fixed review comment 2024-09-16 18:46:10 +07:00
Quan HL c96f1e86ee fix review comment 2024-09-16 18:15:45 +07:00
Quan HL 8016c0886a fix playht has stream and cached audio differrent quality 2024-09-16 09:01:45 +07:00
Dave Horton 8f216e64d8 0.1.15 2024-08-12 09:30:09 -04:00
Dave Horton e1f4486e01 bump version 2024-08-12 09:27:12 -04:00
Dave Horton b0d6272974 Merge pull request #84 from jambonz/feat/precache_audio_with_tts_stream
support precache audio with tts stream enabled
2024-08-12 09:26:00 -04:00
Quan HL ef23b0807a add comment 2024-08-12 20:16:24 +07:00
Quan HL ab7e25243d improve on check precache 2024-08-12 20:10:43 +07:00
Quan HL bf0ea14423 install docker 2024-08-12 18:40:47 +07:00
Quan HL 305dabd84b wip 2024-08-12 18:35:48 +07:00
Quan HL b6a3fa5081 support precache audio with tts stream enabled 2024-08-12 18:29:01 +07:00
Dave Horton 73feadc4c4 0.1.13 2024-08-06 11:01:09 -04:00
Dave Horton aad0f4d62c Merge pull request #82 from jambonz/feat/deepgram_tts_endpoint
deepgram tts support endpoint for on-premise
2024-08-06 11:00:38 -04:00
Hoan Luu Huu 602b0cc60e Merge branch 'main' into feat/deepgram_tts_endpoint 2024-07-31 14:03:41 +07:00
Dave Horton 8511e762c8 version update 2024-07-30 07:29:25 -04:00
Dave Horton b75d3068c9 Merge pull request #81 from jambonz/feat/gh_fs_832
allow configure STS session expiry
2024-07-30 07:14:06 -04:00
Quan HL 461178e726 wip 2024-07-29 20:56:55 +07:00
Quan HL e0e4d47340 wip 2024-07-29 20:53:55 +07:00
Quan HL a595faa378 deepgram tts support endpoint for on-premise 2024-07-29 19:45:13 +07:00
Quan HL 7fd1e1a3c3 allow configure STS session expiry 2024-07-29 18:18:37 +07:00
Dave Horton 7f6a3d349c 0.1.11 2024-06-14 07:37:19 -04:00
Dave Horton 50429ff535 bump version 2024-06-14 07:36:53 -04:00
Dave Horton 3bf0ef8ea3 Merge pull request #80 from jambonz/fix/aws_arnrole
fix aws arnrole
2024-06-14 07:34:22 -04:00
Quan HL e9a5e83e36 wip 2024-06-14 15:04:19 +07:00
Quan HL 86a64ac091 wip 2024-06-14 15:00:56 +07:00
Quan HL 97e06b3ab3 wip 2024-06-14 10:23:22 +07:00
Quan HL 09e833d910 wip 2024-06-14 10:19:55 +07:00
Quan HL 8c4e12e54f wip 2024-06-14 10:18:41 +07:00
Quan HL 2642bd71a4 wip 2024-06-14 10:16:57 +07:00
Quan HL c4feac916f fix aws arnrole 2024-06-14 10:15:23 +07:00
Dave Horton 2ec56f564e 0.1.9 2024-06-06 12:31:13 -04:00
Dave Horton 9399ddcb58 Merge pull request #78 from jambonz/env/disable-ms-streaming
Env/disable ms streaming
2024-06-06 12:30:48 -04:00
Dave Horton aebf4eda30 lint 2024-06-06 12:25:53 -04:00
Dave Horton 6b0bdfdf2f add env JAMBONES_DISABLE_AZURE_TTS_STREAMING to disable Microsoft TTS streaming 2024-06-06 12:25:08 -04:00
Dave Horton d214c3184f 0.1.8 2024-06-05 06:48:09 -04:00
Dave Horton c335a508a3 bump version 2024-06-05 06:47:01 -04:00
Dave Horton d7797d5691 Merge pull request #77 from jambonz/feat/improve_elevenlabs
support elevenlabs previous_text, next_text
2024-06-05 06:43:48 -04:00
Quan HL b81f3313cb support elevenlabs previous_text, next_text 2024-06-05 15:53:26 +07:00
Dave Horton 49fe64744c 0.1.6 2024-05-30 07:13:00 -04:00
Dave Horton 106238cca5 bump version 2024-05-30 07:12:37 -04:00
Dave Horton 01735ccf2f Merge pull request #76 from jambonz/fix/verbio_cache
fixed verbio tts extension
2024-05-30 07:10:50 -04:00
Quan HL ce81cb8d24 fixed verbio tts extension 2024-05-30 16:13:05 +07:00
Dave Horton c9d7a9046f 0.1.4 2024-05-29 07:24:07 -04:00
Dave Horton a9ba383667 Merge pull request #75 from Catharsis68/feat/pre-commit-hook
Update eslint, add pre commit hook
2024-05-29 07:23:41 -04:00
Markus Frindt 06b97bcb0f Update eslint, add pre commit hook 2024-05-29 10:22:10 +02:00
Dave Horton 90152b36ef 0.1.3 2024-05-28 13:02:15 -04:00
Dave Horton 92484b7441 Merge pull request #74 from jambonz/fix/lint
lint
2024-05-28 13:01:35 -04:00
Dave Horton 398904785b lint 2024-05-28 12:58:37 -04:00
Dave Horton 531fa21f88 0.1.2 2024-05-28 12:55:00 -04:00
Dave Horton 904495d819 Merge pull request #73 from Catharsis68/feat/tts-cache-improvement
Improve handling of TTS cache by adding the file extension to the cac…
2024-05-28 12:54:31 -04:00
Markus Frindt f13fc84853 merge latest main into feature branch 2024-05-28 18:44:41 +02:00
Markus Frindt 39d54050cc simplify return for streaming responses 2024-05-28 15:23:53 +02:00
Markus Frindt 7618d334db add namespace for custom provider 2024-05-27 11:04:35 +02:00
Markus Frindt 71f20178d3 add test case 2024-05-24 14:09:07 +02:00
Markus Frindt cb6ab2479f Improve handling of TTS cache by adding the file extension to the cache key 2024-05-24 14:03:31 +02:00
24 changed files with 3024 additions and 2098 deletions
-1
View File
@@ -1 +0,0 @@
test/*
-126
View File
@@ -1,126 +0,0 @@
{
"env": {
"node": true,
"es6": true
},
"parserOptions": {
"ecmaFeatures": {
"jsx": false,
"modules": false
},
"ecmaVersion": 2020
},
"plugins": ["promise"],
"rules": {
"promise/always-return": "error",
"promise/no-return-wrap": "error",
"promise/param-names": "error",
"promise/catch-or-return": "error",
"promise/no-native": "off",
"promise/no-nesting": "warn",
"promise/no-promise-in-callback": "warn",
"promise/no-callback-in-promise": "warn",
"promise/no-return-in-finally": "warn",
// Possible Errors
// http://eslint.org/docs/rules/#possible-errors
"comma-dangle": [2, "only-multiline"],
"no-control-regex": 2,
"no-debugger": 2,
"no-dupe-args": 2,
"no-dupe-keys": 2,
"no-duplicate-case": 2,
"no-empty-character-class": 2,
"no-ex-assign": 2,
"no-extra-boolean-cast" : 2,
"no-extra-parens": [2, "functions"],
"no-extra-semi": 2,
"no-func-assign": 2,
"no-invalid-regexp": 2,
"no-irregular-whitespace": 2,
"no-negated-in-lhs": 2,
"no-obj-calls": 2,
"no-proto": 2,
"no-unexpected-multiline": 2,
"no-unreachable": 2,
"use-isnan": 2,
"valid-typeof": 2,
// Best Practices
// http://eslint.org/docs/rules/#best-practices
"no-fallthrough": 2,
"no-octal": 2,
"no-redeclare": 2,
"no-self-assign": 2,
"no-unused-labels": 2,
// Strict Mode
// http://eslint.org/docs/rules/#strict-mode
"strict": [2, "never"],
// Variables
// http://eslint.org/docs/rules/#variables
"no-delete-var": 2,
"no-undef": 2,
"no-unused-vars": [2, {"args": "none"}],
// Node.js and CommonJS
// http://eslint.org/docs/rules/#nodejs-and-commonjs
"no-mixed-requires": 2,
"no-new-require": 2,
"no-path-concat": 2,
"no-restricted-modules": [2, "sys", "_linklist"],
// Stylistic Issues
// http://eslint.org/docs/rules/#stylistic-issues
"comma-spacing": 2,
"eol-last": 2,
"indent": [2, 2, {"SwitchCase": 1}],
"keyword-spacing": 2,
"max-len": [2, 120, 2],
"new-parens": 2,
"no-mixed-spaces-and-tabs": 2,
"no-multiple-empty-lines": [2, {"max": 2}],
"no-trailing-spaces": [2, {"skipBlankLines": false }],
"quotes": [2, "single", "avoid-escape"],
"semi": 2,
"space-before-blocks": [2, "always"],
"space-before-function-paren": [2, "never"],
"space-in-parens": [2, "never"],
"space-infix-ops": 2,
"space-unary-ops": 2,
// ECMAScript 6
// http://eslint.org/docs/rules/#ecmascript-6
"arrow-parens": [2, "always"],
"arrow-spacing": [2, {"before": true, "after": true}],
"constructor-super": 2,
"no-class-assign": 2,
"no-confusing-arrow": 2,
"no-const-assign": 2,
"no-dupe-class-members": 2,
"no-new-symbol": 2,
"no-this-before-super": 2,
"prefer-const": 2
},
"globals": {
"DTRACE_HTTP_CLIENT_REQUEST" : false,
"LTTNG_HTTP_CLIENT_REQUEST" : false,
"COUNTER_HTTP_CLIENT_REQUEST" : false,
"DTRACE_HTTP_CLIENT_RESPONSE" : false,
"LTTNG_HTTP_CLIENT_RESPONSE" : false,
"COUNTER_HTTP_CLIENT_RESPONSE" : false,
"DTRACE_HTTP_SERVER_REQUEST" : false,
"LTTNG_HTTP_SERVER_REQUEST" : false,
"COUNTER_HTTP_SERVER_REQUEST" : false,
"DTRACE_HTTP_SERVER_RESPONSE" : false,
"LTTNG_HTTP_SERVER_RESPONSE" : false,
"COUNTER_HTTP_SERVER_RESPONSE" : false,
"DTRACE_NET_STREAM_END" : false,
"LTTNG_NET_STREAM_END" : false,
"COUNTER_NET_SERVER_CONNECTION_CLOSE" : false,
"DTRACE_NET_SERVER_CONNECTION" : false,
"LTTNG_NET_SERVER_CONNECTION" : false,
"COUNTER_NET_SERVER_CONNECTION" : false
}
}
+5
View File
@@ -13,6 +13,11 @@ jobs:
with: with:
node-version: lts/* node-version: lts/*
- run: npm install - run: npm install
- name: Install Docker Compose
run: |
sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
docker-compose --version
- run: npm run jslint - run: npm run jslint
- run: sudo apt update && sudo apt install -y squid - run: sudo apt update && sudo apt install -y squid
- run: sudo cp test/squid.conf /etc/squid/squid.conf - run: sudo cp test/squid.conf /etc/squid/squid.conf
+2
View File
@@ -39,3 +39,5 @@ node_modules
examples/* examples/*
.vscode .vscode
.env
+3
View File
@@ -0,0 +1,3 @@
#npm audit
npm run jslint:fix || true
npm test
+140
View File
@@ -0,0 +1,140 @@
const promise = require('eslint-plugin-promise');
const globals = require('globals');
module.exports = [
{
files: ['**/*.js', '*.js'],
languageOptions: {
ecmaVersion: 2020,
parserOptions: {
'node': true,
'es6': true,
ecmaFeatures: {
jsx: false,
modules: false,
}
},
sourceType: 'module',
globals: {
...globals.node,
'DTRACE_HTTP_CLIENT_REQUEST': false,
'LTTNG_HTTP_CLIENT_REQUEST': false,
'COUNTER_HTTP_CLIENT_REQUEST': false,
'DTRACE_HTTP_CLIENT_RESPONSE': false,
'LTTNG_HTTP_CLIENT_RESPONSE': false,
'COUNTER_HTTP_CLIENT_RESPONSE': false,
'DTRACE_HTTP_SERVER_REQUEST': false,
'LTTNG_HTTP_SERVER_REQUEST': false,
'COUNTER_HTTP_SERVER_REQUEST': false,
'DTRACE_HTTP_SERVER_RESPONSE': false,
'LTTNG_HTTP_SERVER_RESPONSE': false,
'COUNTER_HTTP_SERVER_RESPONSE': false,
'DTRACE_NET_STREAM_END': false,
'LTTNG_NET_STREAM_END': false,
'COUNTER_NET_SERVER_CONNECTION_CLOSE': false,
'DTRACE_NET_SERVER_CONNECTION': false,
'LTTNG_NET_SERVER_CONNECTION': false,
'COUNTER_NET_SERVER_CONNECTION': false
},
},
'plugins': {
promise
},
'rules': {
'promise/always-return': 'error',
'promise/no-return-wrap': 'error',
'promise/param-names': 'error',
'promise/catch-or-return': 'error',
'promise/no-native': 'off',
'promise/no-nesting': 'warn',
'promise/no-promise-in-callback': 'warn',
'promise/no-callback-in-promise': 'warn',
'promise/no-return-in-finally': 'warn',
// Possible Errors
// http://eslint.org/docs/rules/#possible-errors
'comma-dangle': [2, 'only-multiline'],
'no-control-regex': 2,
'no-debugger': 2,
'no-dupe-args': 2,
'no-dupe-keys': 2,
'no-duplicate-case': 2,
'no-empty-character-class': 2,
'no-ex-assign': 2,
'no-extra-boolean-cast': 2,
'no-extra-parens': [2, 'functions'],
'no-extra-semi': 2,
'no-func-assign': 2,
'no-invalid-regexp': 2,
'no-irregular-whitespace': 2,
'no-negated-in-lhs': 2,
'no-obj-calls': 2,
'no-proto': 2,
'no-unexpected-multiline': 2,
'no-unreachable': 2,
'use-isnan': 2,
'valid-typeof': 2,
// Best Practices
// http://eslint.org/docs/rules/#best-practices
'no-fallthrough': 2,
'no-octal': 2,
'no-redeclare': 2,
'no-self-assign': 2,
'no-unused-labels': 2,
// Strict Mode
// http://eslint.org/docs/rules/#strict-mode
'strict': [2, 'never'],
// Variables
// http://eslint.org/docs/rules/#variables
'no-delete-var': 2,
'no-undef': 2,
'no-unused-vars': [2, { 'args': 'none' }],
// Node.js and CommonJS
// http://eslint.org/docs/rules/#nodejs-and-commonjs
'no-mixed-requires': 2,
'no-new-require': 2,
'no-path-concat': 2,
'no-restricted-modules': [2, 'sys', '_linklist'],
// Stylistic Issues
// http://eslint.org/docs/rules/#stylistic-issues
'comma-spacing': 2,
'eol-last': 2,
'indent': [2, 2, { 'SwitchCase': 1 }],
'keyword-spacing': 2,
'max-len': [2, 120, 2],
'new-parens': 2,
'no-mixed-spaces-and-tabs': 2,
'no-multiple-empty-lines': [2, { 'max': 2 }],
'no-trailing-spaces': [2, { 'skipBlankLines': false }],
'quotes': [2, 'single', 'avoid-escape'],
'semi': 2,
'space-before-blocks': [2, 'always'],
'space-before-function-paren': [2, 'never'],
'space-in-parens': [2, 'never'],
'space-infix-ops': 2,
'space-unary-ops': 2,
// ECMAScript 6
// http://eslint.org/docs/rules/#ecmascript-6
'arrow-parens': [2, 'always'],
'arrow-spacing': [2, { 'before': true, 'after': true }],
'constructor-super': 2,
'no-class-assign': 2,
'no-confusing-arrow': 2,
'no-const-assign': 2,
'no-dupe-class-members': 2,
'no-new-symbol': 2,
'no-this-before-super': 2,
'prefer-const': 2
},
'ignores': []
}
];
+33 -3
View File
@@ -1,9 +1,31 @@
const fs = require('fs/promises'); const fs = require('fs/promises');
const {noopLogger, makeSynthKey} = require('./utils'); const {noopLogger, makeSynthKey} = require('./utils');
const EXPIRES = (process.env.JAMBONES_TTS_CACHE_DURATION_MINS || 4 * 60) * 60; // cache tts for 4 hours 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, 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;
@@ -14,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;
+25
View File
@@ -0,0 +1,25 @@
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_HTTP_PROXY_IP = process.env.JAMBONES_HTTP_PROXY_IP;
const JAMBONES_HTTP_PROXY_PORT = process.env.JAMBONES_HTTP_PROXY_PORT;
const JAMBONES_TTS_CACHE_DURATION_MINS =
(parseInt(process.env.JAMBONES_TTS_CACHE_DURATION_MINS) || 4 * 60) * 60; // cache tts for 4 hours
const TMP_FOLDER = '/tmp';
const HTTP_TIMEOUT = 5000;
module.exports = {
JAMBONES_TTS_TRIM_SILENCE,
JAMBONES_DISABLE_TTS_STREAMING,
JAMBONES_DISABLE_AZURE_TTS_STREAMING,
JAMBONES_HTTP_PROXY_IP,
JAMBONES_HTTP_PROXY_PORT,
JAMBONES_TTS_CACHE_DURATION_MINS,
JAMBONES_EAGERLY_PRE_CACHE_AUDIO,
TMP_FOLDER,
HTTP_TIMEOUT
};
-3
View File
@@ -1,3 +0,0 @@
module.exports = {
HTTP_TIMEOUT: 5000
};
+38 -14
View File
@@ -1,35 +1,58 @@
const { STSClient, GetSessionTokenCommand, AssumeRoleCommand } = require('@aws-sdk/client-sts'); const { STSClient, GetSessionTokenCommand, AssumeRoleCommand } = require('@aws-sdk/client-sts');
const {makeAwsKey, noopLogger} = require('./utils'); const {makeAwsKey, noopLogger} = require('./utils');
const debug = require('debug')('jambonz:speech-utils'); const debug = require('debug')('jambonz:speech-utils');
const EXPIRY = 3600; const EXPIRY = process.env.AWS_STS_SESSION_DURATION || 3600;
// by default reset aws session before expiry time 10 mins
const CACHE_EXPIRY = process.env.AWS_STS_SESSION_RESET_EXPIRY || (EXPIRY - 600);
async function getAwsAuthToken( async function getAwsAuthToken(
logger, createHash, retrieveHash, logger, createHash, retrieveHash,
awsAccessKeyId, awsSecretAccessKey, awsRegion, roleArn = null) { {speech_credential_sid, accessKeyId, secretAccessKey, region, roleArn}) {
logger = logger || noopLogger; logger = logger || noopLogger;
try { try {
const key = makeAwsKey(roleArn || awsAccessKeyId); // 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: awsRegion}); 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: awsRegion, region,
credentials: { credentials: {
accessKeyId: awsAccessKeyId, accessKeyId,
secretAccessKey: awsSecretAccessKey, secretAccessKey,
} }
}); });
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 = {
@@ -38,10 +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
/* expire 10 minutes before the hour, so we don't lose the use of it during a call */ if (expiry > 0) {
createHash(key, credentials, EXPIRY - 600) createHash(key, credentials, expiry)
.catch((err) => logger.error(err, `Error saving hash for key ${key}`)); .catch((err) => logger.error(err, `Error saving hash for key ${key}`));
}
return {...credentials, servedFromCache: false}; return {...credentials, servedFromCache: false};
} catch (err) { } catch (err) {
+1 -1
View File
@@ -2,7 +2,7 @@ const formurlencoded = require('form-urlencoded');
const {Pool} = require('undici'); const {Pool} = require('undici');
const pool = new Pool('https://iam.cloud.ibm.com'); const pool = new Pool('https://iam.cloud.ibm.com');
const {makeIbmKey, noopLogger} = require('./utils'); const {makeIbmKey, noopLogger} = require('./utils');
const { HTTP_TIMEOUT } = require('./constants'); const { HTTP_TIMEOUT } = require('./config');
const debug = require('debug')('jambonz:realtimedb-helpers'); const debug = require('debug')('jambonz:realtimedb-helpers');
async function getIbmAccessToken(client, logger, apiKey) { async function getIbmAccessToken(client, logger, apiKey) {
+1 -1
View File
@@ -2,7 +2,7 @@ const formurlencoded = require('form-urlencoded');
const {Pool} = require('undici'); const {Pool} = require('undici');
const pool = new Pool('https://auth.crt.nuance.com'); const pool = new Pool('https://auth.crt.nuance.com');
const {makeNuanceKey, makeBasicAuthHeader, noopLogger} = require('./utils'); const {makeNuanceKey, makeBasicAuthHeader, noopLogger} = require('./utils');
const { HTTP_TIMEOUT } = require('./constants'); const { HTTP_TIMEOUT } = require('./config');
const debug = require('debug')('jambonz:realtimedb-helpers'); const debug = require('debug')('jambonz:realtimedb-helpers');
async function getNuanceAccessToken(client, logger, clientId, secret, scope) { async function getNuanceAccessToken(client, logger, clientId, secret, scope) {
+7 -2
View File
@@ -9,7 +9,7 @@ const ttsGoogle = require('@google-cloud/text-to-speech');
const { PollyClient, DescribeVoicesCommand } = require('@aws-sdk/client-polly'); const { PollyClient, DescribeVoicesCommand } = require('@aws-sdk/client-polly');
const getAwsAuthToken = require('./get-aws-sts-token'); const getAwsAuthToken = require('./get-aws-sts-token');
const {Pool} = require('undici'); const {Pool} = require('undici');
const { HTTP_TIMEOUT } = require('./constants'); const { HTTP_TIMEOUT } = require('./config');
const verbioVoicePool = new Pool('https://us.rest.speechcenter.verbio.com'); const verbioVoicePool = new Pool('https://us.rest.speechcenter.verbio.com');
const getIbmVoices = async(client, logger, credentials) => { const getIbmVoices = async(client, logger, credentials) => {
@@ -107,7 +107,12 @@ const getAwsVoices = async(_client, createHash, retrieveHash, logger, credential
} else if (roleArn) { } else if (roleArn) {
client = new PollyClient({ client = new PollyClient({
region, region,
credentials: await getAwsAuthToken(logger, createHash, retrieveHash, null, null, region, roleArn), credentials: await getAwsAuthToken(
logger, createHash, retrieveHash,
{
region,
roleArn
}),
}); });
} else { } else {
client = new PollyClient({region}); client = new PollyClient({region});
+1 -1
View File
@@ -1,6 +1,6 @@
const {Pool} = require('undici'); const {Pool} = require('undici');
const { noopLogger, makeVerbioKey } = require('./utils'); const { noopLogger, makeVerbioKey } = require('./utils');
const { HTTP_TIMEOUT } = require('./constants'); const { HTTP_TIMEOUT } = require('./config');
const pool = new Pool('https://auth.speechcenter.verbio.com:444'); const pool = new Pool('https://auth.speechcenter.verbio.com:444');
const debug = require('debug')('jambonz:realtimedb-helpers'); const debug = require('debug')('jambonz:realtimedb-helpers');
+2 -1
View File
@@ -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);
+352 -120
View File
@@ -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');
@@ -19,7 +20,9 @@ const {
createNuanceClient, createNuanceClient,
createKryptonClient, createKryptonClient,
createRivaClient, createRivaClient,
noopLogger noopLogger,
makeFilePath,
makePlayhtKey
} = require('./utils'); } = require('./utils');
const getNuanceAccessToken = require('./get-nuance-access-token'); const getNuanceAccessToken = require('./get-nuance-access-token');
const getVerbioAccessToken = require('./get-verbio-token'); const getVerbioAccessToken = require('./get-verbio-token');
@@ -37,8 +40,15 @@ const {
const {SynthesizeSpeechRequest} = require('../stubs/riva/proto/riva_tts_pb'); const {SynthesizeSpeechRequest} = require('../stubs/riva/proto/riva_tts_pb');
const {AudioEncoding} = require('../stubs/riva/proto/riva_audio_pb'); const {AudioEncoding} = require('../stubs/riva/proto/riva_audio_pb');
const debug = require('debug')('jambonz:realtimedb-helpers'); const debug = require('debug')('jambonz:realtimedb-helpers');
const EXPIRES = (process.env.JAMBONES_TTS_CACHE_DURATION_MINS || 4 * 60) * 60; // cache tts for 4 hours const {
const TMP_FOLDER = '/tmp'; JAMBONES_DISABLE_TTS_STREAMING,
JAMBONES_DISABLE_AZURE_TTS_STREAMING,
JAMBONES_HTTP_PROXY_IP,
JAMBONES_HTTP_PROXY_PORT,
JAMBONES_TTS_CACHE_DURATION_MINS,
JAMBONES_TTS_TRIM_SILENCE,
} = require('./config');
const EXPIRES = JAMBONES_TTS_CACHE_DURATION_MINS;
const OpenAI = require('openai'); const OpenAI = require('openai');
const getAwsAuthToken = require('./get-aws-sts-token'); const getAwsAuthToken = require('./get-aws-sts-token');
@@ -79,15 +89,15 @@ const trimTrailingSilence = (buffer) => {
*/ */
async function synthAudio(client, createHash, retrieveHash, logger, stats, { account_sid, async function synthAudio(client, createHash, retrieveHash, logger, stats, { account_sid,
vendor, language, voice, gender, text, engine, salt, model, credentials, deploymentId, vendor, language, voice, gender, text, engine, salt, model, credentials, deploymentId,
disableTtsCache, renderForCaching, 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) {
@@ -144,29 +154,26 @@ async function synthAudio(client, createHash, retrieveHash, logger, stats, { acc
assert.ok(voice, 'synthAudio requires voice when verbio is used'); assert.ok(voice, 'synthAudio requires voice when verbio is used');
assert.ok(credentials.client_id, 'synthAudio requires client_id when verbio is used'); assert.ok(credentials.client_id, 'synthAudio requires client_id when verbio is used');
assert.ok(credentials.client_secret, 'synthAudio requires client_secret when verbio is used'); assert.ok(credentials.client_secret, 'synthAudio requires client_secret when verbio is used');
} else if ('deepgram' === vendor) {
if (!credentials.deepgram_tts_uri) {
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({
account_sid, account_sid,
vendor, vendor,
language: language || '', language: language || '',
voice: voice || deploymentId, voice: voice || deploymentId,
engine, engine,
// model or model_id is used to identify the tts cache.
model: model || credentials.model_id,
text text
}); });
let filePath;
if (['nuance', 'nvidia', 'verbio'].includes(vendor) ||
(
(process.env.JAMBONES_TTS_TRIM_SILENCE || !process.env.JAMBONES_DISABLE_TTS_STREAMING) &&
['microsoft', 'azure'].includes(vendor)
) ||
(
!process.env.JAMBONES_DISABLE_TTS_STREAMING &&
['elevenlabs', 'deepgram', 'rimelabs'].includes(vendor)
)
) {
filePath = `${TMP_FOLDER}/${key.replace('tts:', `tts-${salt || ''}`)}.r8`;
}
else filePath = `${TMP_FOLDER}/${key.replace('tts:', `tts-${salt || ''}`)}.mp3`;
debug(`synth key is ${key}`); debug(`synth key is ${key}`);
let cached; let cached;
if (!disableTtsCache) { if (!disableTtsCache) {
@@ -177,10 +184,11 @@ async function synthAudio(client, createHash, retrieveHash, logger, stats, { acc
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']);
@@ -188,87 +196,92 @@ 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});
if (audioBuffer?.filePath) return audioBuffer;
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});
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});
});
if (audioBuffer?.filePath) return audioBuffer;
break; break;
case 'playht': case 'playht':
audioBuffer = await synthPlayHT(logger, { audioData = await synthPlayHT(client, logger, {
credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming, filePath credentials, options, stats, language, voice, text, renderForCaching, disableTtsStreaming});
}); break;
if (audioBuffer?.filePath) return audioBuffer; 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});
});
if (audioBuffer?.filePath) return audioBuffer;
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});
if (audioBuffer?.filePath) return audioBuffer;
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});
if (audioBuffer?.filePath) return audioBuffer;
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 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});
}); });
@@ -291,7 +304,12 @@ const synthPolly = async(createHash, retrieveHash, logger,
} else if (roleArn) { } else if (roleArn) {
polly = new PollyClient({ polly = new PollyClient({
region, region,
credentials: await getAwsAuthToken(logger, createHash, retrieveHash, null, null, region, roleArn), credentials: await getAwsAuthToken(
logger, createHash, retrieveHash,
{
region,
roleArn
}),
}); });
} else { } else {
// AWS RoleArn assigned to Instance profile // AWS RoleArn assigned to Instance profile
@@ -318,7 +336,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');
@@ -329,6 +353,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}),
@@ -343,7 +409,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');
@@ -374,7 +444,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']);
@@ -384,11 +458,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;
@@ -410,15 +482,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;
@@ -431,7 +507,6 @@ const synthMicrosoft = async(logger, {
language, language,
voice, voice,
text, text,
filePath,
renderForCaching, renderForCaching,
disableTtsStreaming disableTtsStreaming
}) => { }) => {
@@ -454,7 +529,8 @@ const synthMicrosoft = async(logger, {
content = `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="${language}"><voice name="${voice}">${words}</voice></speak>`; content = `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="${language}"><voice name="${voice}">${words}</voice></speak>`;
logger.info({content}, 'synthMicrosoft'); logger.info({content}, 'synthMicrosoft');
} }
if (!process.env.JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) { if (!JAMBONES_DISABLE_TTS_STREAMING && !JAMBONES_DISABLE_AZURE_TTS_STREAMING &&
!renderForCaching && !disableTtsStreaming) {
let params = ''; let params = '';
params += `{api_key=${apiKey}`; params += `{api_key=${apiKey}`;
params += `,language=${language}`; params += `,language=${language}`;
@@ -464,8 +540,8 @@ const synthMicrosoft = async(logger, {
if (region) params += `,region=${region}`; if (region) params += `,region=${region}`;
if (custom_tts_endpoint) params += `,endpointId=${custom_tts_endpoint}`; if (custom_tts_endpoint) params += `,endpointId=${custom_tts_endpoint}`;
if (custom_tts_endpoint_url) params += `,endpoint=${custom_tts_endpoint_url}`; if (custom_tts_endpoint_url) params += `,endpoint=${custom_tts_endpoint_url}`;
if (process.env.JAMBONES_HTTP_PROXY_IP) params += `,http_proxy_ip=${process.env.JAMBONES_HTTP_PROXY_IP}`; if (JAMBONES_HTTP_PROXY_IP) params += `,http_proxy_ip=${JAMBONES_HTTP_PROXY_IP}`;
if (process.env.JAMBONES_HTTP_PROXY_PORT) params += `,http_proxy_port=${process.env.JAMBONES_HTTP_PROXY_PORT}`; if (JAMBONES_HTTP_PROXY_PORT) params += `,http_proxy_port=${JAMBONES_HTTP_PROXY_PORT}`;
params += '}'; params += '}';
return { return {
filePath: `say:${params}${content.replace(/\n/g, ' ')}`, filePath: `say:${params}${content.replace(/\n/g, ' ')}`,
@@ -473,17 +549,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;
@@ -494,10 +571,10 @@ const synthMicrosoft = async(logger, {
SpeechSynthesisOutputFormat.Raw8Khz16BitMonoPcm : SpeechSynthesisOutputFormat.Raw8Khz16BitMonoPcm :
SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3; SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3;
if (process.env.JAMBONES_HTTP_PROXY_IP && process.env.JAMBONES_HTTP_PROXY_PORT) { if (JAMBONES_HTTP_PROXY_IP && JAMBONES_HTTP_PROXY_PORT) {
logger.debug( logger.debug(
`synthMicrosoft: using proxy ${process.env.JAMBONES_HTTP_PROXY_IP}:${process.env.JAMBONES_HTTP_PROXY_PORT}`); `synthMicrosoft: using proxy ${JAMBONES_HTTP_PROXY_IP}:${JAMBONES_HTTP_PROXY_PORT}`);
speechConfig.setProxy(process.env.JAMBONES_HTTP_PROXY_IP, process.env.JAMBONES_HTTP_PROXY_PORT); speechConfig.setProxy(JAMBONES_HTTP_PROXY_IP, JAMBONES_HTTP_PROXY_PORT);
} }
const synthesizer = new SpeechSynthesizer(speechConfig); const synthesizer = new SpeechSynthesizer(speechConfig);
@@ -518,7 +595,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;
@@ -548,11 +629,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;
@@ -589,8 +674,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);
@@ -614,7 +699,11 @@ 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
});
}); });
}); });
}; };
@@ -622,12 +711,13 @@ const synthNuance = async(client, logger, {credentials, stats, voice, model, tex
const synthNvidia = async(client, logger, {credentials, stats, language, voice, model, text}) => { const synthNvidia = async(client, logger, {credentials, stats, language, voice, model, text}) => {
const {riva_server_uri} = credentials; const {riva_server_uri} = credentials;
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) {
@@ -641,7 +731,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
});
}); });
}); });
}; };
@@ -663,12 +757,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`);
@@ -683,7 +778,7 @@ const synthElevenlabs = async(logger, {
const opts = !!options && Object.keys(options).length !== 0 ? options : JSON.parse(credOpts || '{}'); const opts = !!options && Object.keys(options).length !== 0 ? options : JSON.parse(credOpts || '{}');
/* default to using the streaming interface, unless disabled by env var OR we want just a cache file */ /* default to using the streaming interface, unless disabled by env var OR we want just a cache file */
if (!process.env.JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) { if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
let params = ''; let params = '';
params += `{api_key=${api_key}`; params += `{api_key=${api_key}`;
params += ',vendor=elevenlabs'; params += ',vendor=elevenlabs';
@@ -695,6 +790,8 @@ const synthElevenlabs = async(logger, {
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?.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.next_text) params += `,next_text=${opts.next_text}`;
params += '}'; params += '}';
return { return {
@@ -712,7 +809,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: {
@@ -721,7 +818,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']);
@@ -729,21 +830,51 @@ const synthElevenlabs = async(logger, {
} }
}; };
const synthPlayHT = async(logger, { const synthPlayHT = async(client, logger, {
credentials, options, stats, voice, text, renderForCaching, disableTtsStreaming credentials, options, stats, voice, language, text, renderForCaching, disableTtsStreaming
}) => { }) => {
const {api_key, user_id, voice_engine, 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 || '{}'); const opts = !!options && Object.keys(options).length !== 0 ? options : JSON.parse(credOpts || '{}');
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 {
const post = bent('https://api.play.ht', 'POST', 'json', 201, {
'AUTHORIZATION': api_key,
'X-USER-ID': user_id,
'Accept': 'application/json'
});
const key = makePlayhtKey(api_key);
const url = await client.get(key);
if (!url) {
const {inference_address, expires_at_ms} = await post('/api/v3/auth');
synthesizeUrl = inference_address;
const expiry = Math.floor((expires_at_ms - Date.now()) / 1000 - 30);
await client.set(key, inference_address, 'EX', expiry);
} else {
// Use cached URL
synthesizeUrl = url;
}
} catch (err) {
logger.info({err}, 'synth PlayHT returned error for authentication version 3.0');
stats.increment('tts.count', ['vendor:playht', 'accepted:no']);
throw err;
}
}
/* default to using the streaming interface, unless disabled by env var OR we want just a cache file */ /* default to using the streaming interface, unless disabled by env var OR we want just a cache file */
if (!process.env.JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) { if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
let params = ''; let params = '';
params += `{api_key=${api_key}`; params += `{api_key=${api_key}`;
params += `,user_id=${user_id}`; params += `,user_id=${user_id}`;
params += ',vendor=playht'; params += ',vendor=playht';
params += `,voice=${voice}`; params += `,voice=${voice}`;
params += `,voice_engine=${voice_engine}`; params += `,voice_engine=${voice_engine}`;
params += `,synthesize_url=${synthesizeUrl}`;
params += ',write_cache_file=1'; params += ',write_cache_file=1';
params += `,language=${language}`;
if (opts.quality) params += `,quality=${opts.quality}`; if (opts.quality) params += `,quality=${opts.quality}`;
if (opts.speed) params += `,speed=${opts.speed}`; if (opts.speed) params += `,speed=${opts.speed}`;
if (opts.seed) params += `,style=${opts.seed}`; if (opts.seed) params += `,style=${opts.seed}`;
@@ -752,6 +883,8 @@ const synthPlayHT = async(logger, {
if (opts.voice_guidance) params += `,voice_guidance=${opts.voice_guidance}`; if (opts.voice_guidance) params += `,voice_guidance=${opts.voice_guidance}`;
if (opts.style_guidance) params += `,style_guidance=${opts.style_guidance}`; if (opts.style_guidance) params += `,style_guidance=${opts.style_guidance}`;
if (opts.text_guidance) params += `,text_guidance=${opts.text_guidance}`; if (opts.text_guidance) params += `,text_guidance=${opts.text_guidance}`;
if (opts.top_p) params += `,top_p=${opts.top_p}`;
if (opts.repetition_penalty) params += `,repetition_penalty=${opts.repetition_penalty}`;
params += '}'; params += '}';
return { return {
@@ -762,21 +895,29 @@ const synthPlayHT = async(logger, {
} }
try { try {
const post = bent('https://api.play.ht', 'POST', 'buffer', { const post = bent('POST', 'buffer', {
'AUTHORIZATION': api_key, ...(voice_engine !== 'Play3.0' && {
'X-USER-ID': user_id, 'AUTHORIZATION': api_key,
'X-USER-ID': user_id,
}),
'Accept': 'audio/mpeg', 'Accept': 'audio/mpeg',
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}); });
const mp3 = await post('/api/v2/tts/stream', {
const audioContent = await post(synthesizeUrl, {
text, text,
...(voice_engine === 'Play3.0' && { language }),
voice, voice,
voice_engine, voice_engine,
output_format: 'mp3', output_format: 'mp3',
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']);
@@ -785,17 +926,18 @@ const synthPlayHT = async(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 || '{}');
/* default to using the streaming interface, unless disabled by env var OR we want just a cache file */ /* default to using the streaming interface, unless disabled by env var OR we want just a cache file */
if (!process.env.JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) { if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
let params = ''; let params = '';
params += `{api_key=${api_key}`; params += `{api_key=${api_key}`;
params += `,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}`;
@@ -815,14 +957,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']);
@@ -856,13 +1004,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']);
@@ -873,7 +1025,7 @@ const synthVerbio = async(client, logger, {credentials, stats, voice, text, rend
const synthWhisper = async(logger, {credentials, stats, voice, text, renderForCaching, disableTtsStreaming}) => { const synthWhisper = async(logger, {credentials, stats, voice, text, renderForCaching, disableTtsStreaming}) => {
const {api_key, model_id, baseURL, timeout, speed} = credentials; const {api_key, model_id, baseURL, timeout, speed} = credentials;
/* if the env is set to stream then bag out, unless we are specifically rendering to generate a cache file */ /* if the env is set to stream then bag out, unless we are specifically rendering to generate a cache file */
if (!process.env.JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) { if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
let params = ''; let params = '';
params += `{api_key=${api_key}`; params += `{api_key=${api_key}`;
params += `,model_id=${model_id}`; params += `,model_id=${model_id}`;
@@ -902,7 +1054,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']);
@@ -911,13 +1067,14 @@ const synthWhisper = async(logger, {credentials, stats, voice, text, renderForCa
}; };
const synthDeepgram = async(logger, {credentials, stats, model, text, renderForCaching, disableTtsStreaming}) => { const synthDeepgram = async(logger, {credentials, stats, model, text, renderForCaching, disableTtsStreaming}) => {
const {api_key} = credentials; const {api_key, deepgram_tts_uri} = credentials;
if (!process.env.JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) { if (!JAMBONES_DISABLE_TTS_STREAMING && !renderForCaching && !disableTtsStreaming) {
let params = ''; let params = '';
params += `{api_key=${api_key}`; params += `{api_key=${api_key}`;
params += ',vendor=deepgram'; params += ',vendor=deepgram';
params += `,voice=${model}`; params += `,voice=${model}`;
params += ',write_cache_file=1'; params += ',write_cache_file=1';
if (deepgram_tts_uri) params += `,endpoint=${deepgram_tts_uri}`;
params += '}'; params += '}';
return { return {
@@ -927,15 +1084,20 @@ const synthDeepgram = async(logger, {credentials, stats, model, text, renderForC
}; };
} }
try { try {
const post = bent('https://api.deepgram.com', 'POST', 'buffer', { const post = bent(deepgram_tts_uri || 'https://api.deepgram.com', 'POST', 'buffer', {
'Authorization': `Token ${api_key}`, // on-premise deepgram does not require to have api_key
...(api_key && {'Authorization': `Token ${api_key}`}),
'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']);
@@ -943,26 +1105,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];
} }
}; };
+28 -5
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 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 { HTTP_TIMEOUT } = require('./constants'); const { TMP_FOLDER, HTTP_TIMEOUT } = require('./config');
const debug = require('debug')('jambonz:realtimedb-helpers'); const debug = require('debug')('jambonz:realtimedb-helpers');
/** /**
@@ -16,12 +16,28 @@ const debug = require('debug')('jambonz:realtimedb-helpers');
*/ */
//const nuanceClientMap = new Map(); //const nuanceClientMap = new Map();
function makeSynthKey({account_sid = '', vendor, language, voice, engine = '', text}) { function makeSynthKey({
account_sid = '',
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}`);
return `tts${account_sid ? (':' + account_sid) : ''}:${hash.digest('hex')}`; const hexHashKey = hash.digest('hex');
const accountKey = account_sid ? `:${account_sid}` : '';
const key = `tts${accountKey}:${hexHashKey}`;
return key;
} }
function makeFilePath({key, salt = '', extension}) {
return `${TMP_FOLDER}/${key.replace('tts:', `tts-${salt}`)}.${extension}`;
}
const noopLogger = { const noopLogger = {
info: () => {}, info: () => {},
debug: () => {}, debug: () => {},
@@ -49,6 +65,11 @@ function makeAwsKey(awsAccessKeyId) {
return `aws:${hash.digest('hex')}`; return `aws:${hash.digest('hex')}`;
} }
function makePlayhtKey(apiKey) {
const hash = crypto.createHash('sha1');
hash.update(apiKey);
return `playht:${hash.digest('hex')}`;
}
function makeVerbioKey(client_id) { function makeVerbioKey(client_id) {
const hash = crypto.createHash('sha1'); const hash = crypto.createHash('sha1');
hash.update(client_id); hash.update(client_id);
@@ -122,6 +143,7 @@ module.exports = {
makeSynthKey, makeSynthKey,
makeNuanceKey, makeNuanceKey,
makeIbmKey, makeIbmKey,
makePlayhtKey,
makeAwsKey, makeAwsKey,
makeVerbioKey, makeVerbioKey,
getNuanceAccessToken, getNuanceAccessToken,
@@ -130,5 +152,6 @@ module.exports = {
createRivaClient, createRivaClient,
makeBasicAuthHeader, makeBasicAuthHeader,
NUANCE_AUTH_ENDPOINT, NUANCE_AUTH_ENDPOINT,
noopLogger noopLogger,
makeFilePath
}; };
+2193 -1778
View File
File diff suppressed because it is too large Load Diff
+13 -9
View File
@@ -1,6 +1,6 @@
{ {
"name": "@jambonz/speech-utils", "name": "@jambonz/speech-utils",
"version": "0.1.1", "version": "0.2.3",
"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",
@@ -12,7 +12,9 @@
"test": "NODE_ENV=test node test/ ", "test": "NODE_ENV=test node test/ ",
"coverage": "nyc --reporter html --report-dir ./coverage npm run test", "coverage": "nyc --reporter html --report-dir ./coverage npm run test",
"jslint": "eslint index.js lib", "jslint": "eslint index.js lib",
"build": "./build_stubs.sh" "jslint:fix": "npm run jslint --fix",
"build": "./build_stubs.sh",
"prepare": "husky"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@@ -26,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",
@@ -34,16 +37,17 @@
"form-urlencoded": "^6.1.4", "form-urlencoded": "^6.1.4",
"google-protobuf": "^3.21.2", "google-protobuf": "^3.21.2",
"ibm-watson": "^8.0.0", "ibm-watson": "^8.0.0",
"microsoft-cognitiveservices-speech-sdk": "1.36.0", "microsoft-cognitiveservices-speech-sdk": "1.38.0",
"openai": "^4.25.0", "openai": "^4.25.0",
"undici": "^6.4.0" "undici": "^6.4.0"
}, },
"devDependencies": { "devDependencies": {
"config": "^3.3.10", "config": "^3.3.11",
"eslint": "^8.56.0", "eslint": "^9.3.0",
"eslint-plugin-promise": "^6.1.1", "eslint-plugin-promise": "^6.2.0",
"husky": "^9.0.11",
"nyc": "^15.1.0", "nyc": "^15.1.0",
"pino": "^8.17.0", "pino": "^9.1.0",
"tape": "^5.7.3" "tape": "^5.7.5"
} }
} }
+3 -3
View File
@@ -62,9 +62,9 @@ function deserialize_nuance_tts_v1_UnarySynthesisResponse(buffer_arg) {
// //
// The Synthesizer service offers these functionalities: // The Synthesizer service offers these functionalities:
// - GetVoices: Queries the list of available voices, with filters to reduce the search space. // - GetVoices: Queries the list of available voices, with filters to reduce the search space.
// - Synthesize: Synthesizes audio from input text and parameters, and returns an audio stream. // - Synthesize: Synthesizes audio from input text and parameters, and returns an audio stream.
// - UnarySynthesize: Synthesizes audio from input text and parameters, and returns a single audio response. // - UnarySynthesize: Synthesizes audio from input text and parameters, and returns a single audio response.
var SynthesizerService = exports.SynthesizerService = { var SynthesizerService = exports.SynthesizerService = {
getVoices: { getVoices: {
path: '/nuance.tts.v1.Synthesizer/GetVoices', path: '/nuance.tts.v1.Synthesizer/GetVoices',
+1 -1
View File
@@ -1 +1 @@
// GENERATED CODE -- NO SERVICES IN PROTO // GENERATED CODE -- NO SERVICES IN PROTO
+5 -5
View File
@@ -57,7 +57,7 @@ function deserialize_nvidia_riva_tts_SynthesizeSpeechResponse(buffer_arg) {
var RivaSpeechSynthesisService = exports.RivaSpeechSynthesisService = { var RivaSpeechSynthesisService = exports.RivaSpeechSynthesisService = {
// Used to request text-to-speech from the service. Submit a request containing the // Used to request text-to-speech from the service. Submit a request containing the
// desired text and configuration, and receive audio bytes in the requested format. // desired text and configuration, and receive audio bytes in the requested format.
synthesize: { synthesize: {
path: '/nvidia.riva.tts.RivaSpeechSynthesis/Synthesize', path: '/nvidia.riva.tts.RivaSpeechSynthesis/Synthesize',
requestStream: false, requestStream: false,
responseStream: false, responseStream: false,
@@ -69,9 +69,9 @@ synthesize: {
responseDeserialize: deserialize_nvidia_riva_tts_SynthesizeSpeechResponse, responseDeserialize: deserialize_nvidia_riva_tts_SynthesizeSpeechResponse,
}, },
// Used to request text-to-speech returned via stream as it becomes available. // Used to request text-to-speech returned via stream as it becomes available.
// Submit a SynthesizeSpeechRequest with desired text and configuration, // Submit a SynthesizeSpeechRequest with desired text and configuration,
// and receive stream of bytes in the requested format. // and receive stream of bytes in the requested format.
synthesizeOnline: { synthesizeOnline: {
path: '/nvidia.riva.tts.RivaSpeechSynthesis/SynthesizeOnline', path: '/nvidia.riva.tts.RivaSpeechSynthesis/SynthesizeOnline',
requestStream: false, requestStream: false,
responseStream: true, responseStream: true,
@@ -83,7 +83,7 @@ synthesizeOnline: {
responseDeserialize: deserialize_nvidia_riva_tts_SynthesizeSpeechResponse, responseDeserialize: deserialize_nvidia_riva_tts_SynthesizeSpeechResponse,
}, },
// Enables clients to request the configuration of the current Synthesize service, or a specific model within the service. // Enables clients to request the configuration of the current Synthesize service, or a specific model within the service.
getRivaSynthesisConfig: { getRivaSynthesisConfig: {
path: '/nvidia.riva.tts.RivaSpeechSynthesis/GetRivaSynthesisConfig', path: '/nvidia.riva.tts.RivaSpeechSynthesis/GetRivaSynthesisConfig',
requestStream: false, requestStream: false,
responseStream: false, responseStream: false,
+10 -2
View File
@@ -19,12 +19,20 @@ test('AWS - create and cache auth token', async(t) => {
return; return;
} }
try { try {
let obj = await getAwsAuthToken(process.env.AWS_ACCESS_KEY_ID, process.env.AWS_SECRET_ACCESS_KEY, process.env.AWS_REGION); let obj = await getAwsAuthToken({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: process.env.AWS_REGION
});
//console.log({obj}, 'received auth token from AWS'); //console.log({obj}, 'received auth token from AWS');
t.ok(obj.securityToken && !obj.servedFromCache, 'successfullY generated auth token from AWS'); t.ok(obj.securityToken && !obj.servedFromCache, 'successfullY generated auth token from AWS');
await sleep(250); await sleep(250);
obj = await getAwsAuthToken(process.env.AWS_ACCESS_KEY_ID, process.env.AWS_SECRET_ACCESS_KEY, process.env.AWS_REGION); obj = await getAwsAuthToken({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: process.env.AWS_REGION
});
//console.log({obj}, 'received auth token from AWS - second request'); //console.log({obj}, 'received auth token from AWS - second request');
t.ok(obj.securityToken && obj.servedFromCache, 'successfully received access token from cache'); t.ok(obj.securityToken && obj.servedFromCache, 'successfully received access token from cache');
+161 -22
View File
@@ -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: {
@@ -574,9 +635,9 @@ test('Elevenlabs speech synth tests', async(t) => {
t.end(err); t.end(err);
} }
client.quit(); client.quit();
}) });
test('PlayHT speech synth tests', async(t) => { const testPlayHT = async(t, voice_engine) => {
const fn = require('..'); const fn = require('..');
const {synthAudio, client} = fn(opts, logger); const {synthAudio, client} = fn(opts, logger);
@@ -584,32 +645,74 @@ test('PlayHT speech synth tests', async(t) => {
t.pass('skipping PlayHT speech synth tests since PLAYHT_API_KEY or PLAYHT_USER_ID is/are not provided'); t.pass('skipping PlayHT speech synth tests since PLAYHT_API_KEY or PLAYHT_USER_ID is/are not provided');
return t.end(); return t.end();
} }
const text = 'Hi there and welcome to jambones!'; const text = 'Hi there and welcome to jambones! ' + Date.now();
try { try {
let opts = await synthAudio(stats, { const opts = await synthAudio(stats, {
vendor: 'playht', vendor: 'playht',
credentials: { credentials: {
api_key: process.env.PLAYHT_API_KEY, api_key: process.env.PLAYHT_API_KEY,
user_id: process.env.PLAYHT_USER_ID, user_id: process.env.PLAYHT_USER_ID,
voice_engine: 'PlayHT2.0-turbo', voice_engine,
options: JSON.stringify({ options: JSON.stringify({
quality: "medium", quality: 'medium',
speed: 1, speed: 1,
seed: 1, seed: 1,
temperature: 1, temperature: 1,
emotion: "female_happy", emotion: 'female_happy',
voice_guidance: 3, voice_guidance: 3,
style_guidance: 20, style_guidance: 20,
text_guidance: 1, text_guidance: 1,
}) })
}, },
language: 'en-US', language: 'english',
voice: 's3://voice-cloning-zero-shot/d9ff78ba-d016-47f6-b0ef-dd630f59414e/female-cs/manifest.json', voice: 's3://voice-cloning-zero-shot/d9ff78ba-d016-47f6-b0ef-dd630f59414e/female-cs/manifest.json',
text, text,
renderForCaching: true renderForCaching: true
}); });
t.ok(!opts.servedFromCache, `successfully playht eleven audio to ${opts.filePath}`); t.ok(!opts.servedFromCache, `successfully playht eleven audio to ${opts.filePath}`);
} catch (err) {
console.error(JSON.stringify(err));
t.end(err);
}
client.quit();
};
test('PlayHT speech synth tests', async(t) => {
await testPlayHT(t, 'PlayHT2.0-turbo');
});
test('PlayHT3.0 speech synth tests', async(t) => {
await testPlayHT(t, 'Play3.0');
});
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) { } catch (err) {
console.error(JSON.stringify(err)); console.error(JSON.stringify(err));
t.end(err); t.end(err);
@@ -617,7 +720,7 @@ test('PlayHT speech synth tests', async(t) => {
client.quit(); client.quit();
}); });
test('rimelabs speech synth tests', async(t) => { 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);
@@ -627,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,
@@ -637,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
@@ -651,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);
@@ -750,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`);
@@ -785,13 +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:*')).length; const cached = await client.keys('tts:*');
t.ok(cached >= 1, `successfully kept all non-specified tts records in cache`); t.ok(cached.length >= 1, 'successfully kept all non-specified tts records in cache');
process.env.VG_TRIM_TTS_SILENCE = 'true';
await client.set(makeSynthKey({ vendor: 'azure' }), 'value');
} catch (err) { } catch (err) {
console.error(JSON.stringify(err)); console.error(JSON.stringify(err));
t.end(err); t.end(err);