add function to add an audio file generated externally to cache

This commit is contained in:
Dave Horton
2024-01-26 09:52:32 -05:00
parent 62e1c69f69
commit b31e40b8a5
3 changed files with 39 additions and 1 deletions

View File

@@ -12,6 +12,7 @@ module.exports = (opts, logger) => {
client,
getTtsSize: require('./lib/get-tts-size').bind(null, client, logger),
purgeTtsCache: require('./lib/purge-tts-cache').bind(null, client, logger),
addFileToCache: require('./lib/add-file-to-cache').bind(null, client, logger),
synthAudio: require('./lib/synth-audio').bind(null, client, logger),
getNuanceAccessToken: require('./lib/get-nuance-access-token').bind(null, client, logger),
getIbmAccessToken: require('./lib/get-ibm-access-token').bind(null, client, logger),

29
lib/add-file-to-cache.js Normal file
View File

@@ -0,0 +1,29 @@
const fs = require('fs/promises');
const {noopLogger, makeSynthKey} = require('./utils');
const EXPIRES = (process.env.JAMBONES_TTS_CACHE_DURATION_MINS || 4 * 60) * 60; // cache tts for 4 hours
async function addFileToCache(client, logger, path,
{account_sid, vendor, language, voice, deploymentId, engine, text}) {
logger = logger || noopLogger;
try {
const key = makeSynthKey({
account_sid,
vendor,
language: language || '',
voice: voice || deploymentId,
engine,
text,
});
const audioBuffer = fs.readFile(path);
await client.setex(key, EXPIRES, audioBuffer.toString('base64'));
} catch (err) {
logger.error(err, 'addFileToCache: Error');
return false;
}
logger.debug(`addFileToCache: added ${path} to cache`);
return true;
}
module.exports = addFileToCache;

View File

@@ -20,7 +20,7 @@ const stats = {
test('Google speech synth tests', async(t) => {
const fn = require('..');
const {synthAudio, client} = fn(opts, logger);
const {synthAudio, addFileToCache, client} = fn(opts, logger);
if (!process.env.GCP_FILE && !process.env.GCP_JSON_KEY) {
t.pass('skipping google speech synth tests since neither GCP_FILE nor GCP_JSON_KEY provided');
@@ -58,6 +58,14 @@ test('Google speech synth tests', async(t) => {
});
t.ok(opts.servedFromCache, `successfully retrieved cached google audio from ${opts.filePath}`);
const success = await addFileToCache(opts.filePath, {
vendor: 'google',
language: 'en-GB',
gender: 'FEMALE',
text: 'This is a test. This is only a test'
});
t.ok(success, `successfully added ${opts.filePath} to cache`);
opts = await synthAudio(stats, {
vendor: 'google',
credentials: {