SillyTavern/public/scripts/extensions/tts/elevenlabs.js

264 lines
9.3 KiB
JavaScript
Raw Normal View History

2023-12-02 20:11:06 +01:00
import { saveTtsProviderSettings } from './index.js';
export { ElevenLabsTtsProvider };
2023-07-20 19:32:15 +02:00
class ElevenLabsTtsProvider {
//########//
// Config //
//########//
2023-12-02 20:11:06 +01:00
settings;
voices = [];
separator = ' ... ... ... ';
2023-07-20 19:32:15 +02:00
defaultSettings = {
stability: 0.75,
similarity_boost: 0.75,
2023-12-02 19:04:51 +01:00
apiKey: '',
2023-10-22 13:46:54 +02:00
model: 'eleven_monolingual_v1',
2023-12-02 21:06:57 +01:00
voiceMap: {},
2023-12-02 20:11:06 +01:00
};
2023-07-20 19:32:15 +02:00
get settingsHtml() {
let html = `
<div class="elevenlabs_tts_settings">
<label for="elevenlabs_tts_api_key">API Key</label>
<input id="elevenlabs_tts_api_key" type="text" class="text_pole" placeholder="<API Key>"/>
2023-10-22 13:46:54 +02:00
<label for="elevenlabs_tts_model">Model</label>
<select id="elevenlabs_tts_model" class="text_pole">
<option value="eleven_monolingual_v1">Monolingual</option>
<option value="eleven_multilingual_v1">Multilingual v1</option>
<option value="eleven_multilingual_v2">Multilingual v2</option>
</select>
<input id="eleven_labs_connect" class="menu_button" type="button" value="Connect" />
<label for="elevenlabs_tts_stability">Stability: <span id="elevenlabs_tts_stability_output"></span></label>
<input id="elevenlabs_tts_stability" type="range" value="${this.defaultSettings.stability}" min="0" max="1" step="0.05" />
<label for="elevenlabs_tts_similarity_boost">Similarity Boost: <span id="elevenlabs_tts_similarity_boost_output"></span></label>
<input id="elevenlabs_tts_similarity_boost" type="range" value="${this.defaultSettings.similarity_boost}" min="0" max="1" step="0.05" />
</div>
2023-12-02 20:11:06 +01:00
`;
return html;
2023-07-20 19:32:15 +02:00
}
onSettingsChange() {
// Update dynamically
2023-12-02 20:11:06 +01:00
this.settings.stability = $('#elevenlabs_tts_stability').val();
this.settings.similarity_boost = $('#elevenlabs_tts_similarity_boost').val();
this.settings.model = $('#elevenlabs_tts_model').find(':selected').val();
2023-11-12 01:28:03 +01:00
$('#elevenlabs_tts_stability_output').text(this.settings.stability);
$('#elevenlabs_tts_similarity_boost_output').text(this.settings.similarity_boost);
2023-12-02 20:11:06 +01:00
saveTtsProviderSettings();
2023-07-20 19:32:15 +02:00
}
async loadSettings(settings) {
2023-07-20 19:32:15 +02:00
// Pupulate Provider UI given input settings
if (Object.keys(settings).length == 0) {
2023-12-02 20:11:06 +01:00
console.info('Using default TTS Provider settings');
2023-07-20 19:32:15 +02:00
}
// Only accept keys defined in defaultSettings
2023-12-02 20:11:06 +01:00
this.settings = this.defaultSettings;
2023-07-20 19:32:15 +02:00
2023-10-22 13:46:54 +02:00
// Migrate old settings
if (settings['multilingual'] !== undefined) {
settings.model = settings.multilingual ? 'eleven_multilingual_v1' : 'eleven_monolingual_v1';
delete settings['multilingual'];
}
for (const key in settings) {
if (key in this.settings) {
2023-12-02 20:11:06 +01:00
this.settings[key] = settings[key];
2023-07-20 19:32:15 +02:00
} else {
2023-12-02 20:11:06 +01:00
throw `Invalid setting passed to TTS Provider: ${key}`;
2023-07-20 19:32:15 +02:00
}
}
2023-10-22 13:46:54 +02:00
2023-12-02 20:11:06 +01:00
$('#elevenlabs_tts_stability').val(this.settings.stability);
$('#elevenlabs_tts_similarity_boost').val(this.settings.similarity_boost);
$('#elevenlabs_tts_api_key').val(this.settings.apiKey);
2023-10-22 13:46:54 +02:00
$('#elevenlabs_tts_model').val(this.settings.model);
2023-12-02 20:11:06 +01:00
$('#eleven_labs_connect').on('click', () => { this.onConnectClick(); });
$('#elevenlabs_tts_similarity_boost').on('input', this.onSettingsChange.bind(this));
$('#elevenlabs_tts_stability').on('input', this.onSettingsChange.bind(this));
$('#elevenlabs_tts_model').on('change', this.onSettingsChange.bind(this));
2023-11-12 01:28:03 +01:00
$('#elevenlabs_tts_stability_output').text(this.settings.stability);
$('#elevenlabs_tts_similarity_boost_output').text(this.settings.similarity_boost);
2023-10-22 13:46:54 +02:00
try {
2023-12-02 20:11:06 +01:00
await this.checkReady();
console.debug('ElevenLabs: Settings loaded');
2023-10-22 13:46:54 +02:00
} catch {
2023-12-02 20:11:06 +01:00
console.debug('ElevenLabs: Settings loaded, but not ready');
2023-10-22 13:46:54 +02:00
}
2023-07-20 19:32:15 +02:00
}
2023-08-22 15:30:33 +02:00
// Perform a simple readiness check by trying to fetch voiceIds
2023-10-22 13:46:54 +02:00
async checkReady() {
2023-12-02 20:11:06 +01:00
await this.fetchTtsVoiceObjects();
2023-08-22 15:30:33 +02:00
}
2023-08-26 05:52:26 +02:00
async onRefreshClick() {
}
async onConnectClick() {
2023-07-20 19:32:15 +02:00
// Update on Apply click
2023-10-22 13:46:54 +02:00
return await this.updateApiKey().catch((error) => {
2023-12-02 20:11:06 +01:00
toastr.error(`ElevenLabs: ${error}`);
});
2023-07-20 19:32:15 +02:00
}
async updateApiKey() {
// Using this call to validate API key
2023-12-02 20:11:06 +01:00
this.settings.apiKey = $('#elevenlabs_tts_api_key').val();
2023-07-20 19:32:15 +02:00
2023-08-26 05:52:26 +02:00
await this.fetchTtsVoiceObjects().catch(error => {
2023-12-02 20:11:06 +01:00
throw 'TTS API key validation failed';
});
console.debug(`Saved new API_KEY: ${this.settings.apiKey}`);
$('#tts_status').text('');
this.onSettingsChange();
2023-07-20 19:32:15 +02:00
}
//#################//
// TTS Interfaces //
//#################//
async getVoice(voiceName) {
if (this.voices.length == 0) {
2023-12-02 20:11:06 +01:00
this.voices = await this.fetchTtsVoiceObjects();
2023-07-20 19:32:15 +02:00
}
const match = this.voices.filter(
2023-12-02 21:06:57 +01:00
elevenVoice => elevenVoice.name == voiceName,
2023-12-02 20:11:06 +01:00
)[0];
2023-07-20 19:32:15 +02:00
if (!match) {
2023-12-02 20:11:06 +01:00
throw `TTS Voice name ${voiceName} not found in ElevenLabs account`;
2023-07-20 19:32:15 +02:00
}
2023-12-02 20:11:06 +01:00
return match;
2023-07-20 19:32:15 +02:00
}
2023-10-22 13:46:54 +02:00
async generateTts(text, voiceId) {
2023-12-02 20:11:06 +01:00
const historyId = await this.findTtsGenerationInHistory(text, voiceId);
2023-07-20 19:32:15 +02:00
2023-12-02 20:11:06 +01:00
let response;
2023-07-20 19:32:15 +02:00
if (historyId) {
2023-12-02 20:11:06 +01:00
console.debug(`Found existing TTS generation with id ${historyId}`);
response = await this.fetchTtsFromHistory(historyId);
2023-07-20 19:32:15 +02:00
} else {
2023-12-02 20:11:06 +01:00
console.debug('No existing TTS generation found, requesting new generation');
response = await this.fetchTtsGeneration(text, voiceId);
2023-07-20 19:32:15 +02:00
}
2023-12-02 20:11:06 +01:00
return response;
2023-07-20 19:32:15 +02:00
}
//###################//
// Helper Functions //
//###################//
async findTtsGenerationInHistory(message, voiceId) {
2023-12-02 20:11:06 +01:00
const ttsHistory = await this.fetchTtsHistory();
2023-07-20 19:32:15 +02:00
for (const history of ttsHistory) {
2023-12-02 20:11:06 +01:00
const text = history.text;
const itemId = history.history_item_id;
2023-07-20 19:32:15 +02:00
if (message === text && history.voice_id == voiceId) {
2023-12-02 20:11:06 +01:00
console.info(`Existing TTS history item ${itemId} found: ${text} `);
return itemId;
2023-07-20 19:32:15 +02:00
}
}
2023-12-02 20:11:06 +01:00
return '';
2023-07-20 19:32:15 +02:00
}
//###########//
// API CALLS //
//###########//
2023-08-26 05:52:26 +02:00
async fetchTtsVoiceObjects() {
2023-07-20 19:32:15 +02:00
const headers = {
2023-12-02 21:06:57 +01:00
'xi-api-key': this.settings.apiKey,
2023-12-02 20:11:06 +01:00
};
2023-12-02 19:04:51 +01:00
const response = await fetch('https://api.elevenlabs.io/v1/voices', {
2023-12-02 21:06:57 +01:00
headers: headers,
2023-12-02 20:11:06 +01:00
});
2023-07-20 19:32:15 +02:00
if (!response.ok) {
2023-12-02 20:11:06 +01:00
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
2023-07-20 19:32:15 +02:00
}
2023-12-02 20:11:06 +01:00
const responseJson = await response.json();
return responseJson.voices;
2023-07-20 19:32:15 +02:00
}
async fetchTtsVoiceSettings() {
const headers = {
2023-12-02 21:06:57 +01:00
'xi-api-key': this.settings.apiKey,
2023-12-02 20:11:06 +01:00
};
2023-07-20 19:32:15 +02:00
const response = await fetch(
2023-12-02 19:04:51 +01:00
'https://api.elevenlabs.io/v1/voices/settings/default',
2023-07-20 19:32:15 +02:00
{
2023-12-02 21:06:57 +01:00
headers: headers,
},
2023-12-02 20:11:06 +01:00
);
2023-07-20 19:32:15 +02:00
if (!response.ok) {
2023-12-02 20:11:06 +01:00
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
2023-07-20 19:32:15 +02:00
}
2023-12-02 20:11:06 +01:00
return response.json();
2023-07-20 19:32:15 +02:00
}
async fetchTtsGeneration(text, voiceId) {
2023-12-02 19:04:51 +01:00
let model = this.settings.model ?? 'eleven_monolingual_v1';
2023-12-02 20:11:06 +01:00
console.info(`Generating new TTS for voice_id ${voiceId}, model ${model}`);
2023-07-20 19:32:15 +02:00
const response = await fetch(
`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`,
{
method: 'POST',
headers: {
'xi-api-key': this.settings.apiKey,
2023-12-02 21:06:57 +01:00
'Content-Type': 'application/json',
2023-07-20 19:32:15 +02:00
},
body: JSON.stringify({
2023-10-22 13:46:54 +02:00
model_id: model,
2023-07-20 19:32:15 +02:00
text: text,
2023-10-22 13:46:54 +02:00
voice_settings: {
stability: Number(this.settings.stability),
similarity_boost: Number(this.settings.similarity_boost),
},
2023-12-02 21:06:57 +01:00
}),
},
2023-12-02 20:11:06 +01:00
);
2023-07-20 19:32:15 +02:00
if (!response.ok) {
toastr.error(response.statusText, 'TTS Generation Failed');
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
2023-12-02 20:11:06 +01:00
return response;
2023-07-20 19:32:15 +02:00
}
async fetchTtsFromHistory(history_item_id) {
2023-12-02 20:11:06 +01:00
console.info(`Fetched existing TTS with history_item_id ${history_item_id}`);
2023-07-20 19:32:15 +02:00
const response = await fetch(
`https://api.elevenlabs.io/v1/history/${history_item_id}/audio`,
{
headers: {
2023-12-02 21:06:57 +01:00
'xi-api-key': this.settings.apiKey,
},
},
2023-12-02 20:11:06 +01:00
);
2023-07-20 19:32:15 +02:00
if (!response.ok) {
2023-12-02 20:11:06 +01:00
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
2023-07-20 19:32:15 +02:00
}
2023-12-02 20:11:06 +01:00
return response;
2023-07-20 19:32:15 +02:00
}
async fetchTtsHistory() {
const headers = {
2023-12-02 21:06:57 +01:00
'xi-api-key': this.settings.apiKey,
2023-12-02 20:11:06 +01:00
};
2023-12-02 19:04:51 +01:00
const response = await fetch('https://api.elevenlabs.io/v1/history', {
2023-12-02 21:06:57 +01:00
headers: headers,
2023-12-02 20:11:06 +01:00
});
2023-07-20 19:32:15 +02:00
if (!response.ok) {
2023-12-02 20:11:06 +01:00
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
2023-07-20 19:32:15 +02:00
}
2023-12-02 20:11:06 +01:00
const responseJson = await response.json();
return responseJson.history;
2023-07-20 19:32:15 +02:00
}
}