File size: 54,838 Bytes
c120a1c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 |
import { cancelTtsPlay, eventSource, event_types, getCurrentChatId, isStreamingEnabled, name2, saveSettingsDebounced, substituteParams } from '../../../script.js';
import { ModuleWorkerWrapper, extension_settings, getContext, renderExtensionTemplateAsync } from '../../extensions.js';
import { delay, escapeRegex, getBase64Async, getStringHash, onlyUnique } from '../../utils.js';
import { EdgeTtsProvider } from './edge.js';
import { ElevenLabsTtsProvider } from './elevenlabs.js';
import { SileroTtsProvider } from './silerotts.js';
import { GptSovitsV2Provider } from './gpt-sovits-v2.js';
import { CoquiTtsProvider } from './coqui.js';
import { SystemTtsProvider } from './system.js';
import { NovelTtsProvider } from './novel.js';
import { power_user } from '../../power-user.js';
import { OpenAITtsProvider } from './openai.js';
import { OpenAICompatibleTtsProvider } from './openai-compatible.js';
import { XTTSTtsProvider } from './xtts.js';
import { VITSTtsProvider } from './vits.js';
import { GSVITtsProvider } from './gsvi.js';
import { SBVits2TtsProvider } from './sbvits2.js';
import { AllTalkTtsProvider } from './alltalk.js';
import { CosyVoiceProvider } from './cosyvoice.js';
import { SpeechT5TtsProvider } from './speecht5.js';
import { AzureTtsProvider } from './azure.js';
import { SlashCommandParser } from '../../slash-commands/SlashCommandParser.js';
import { SlashCommand } from '../../slash-commands/SlashCommand.js';
import { ARGUMENT_TYPE, SlashCommandArgument, SlashCommandNamedArgument } from '../../slash-commands/SlashCommandArgument.js';
import { debounce_timeout } from '../../constants.js';
import { SlashCommandEnumValue, enumTypes } from '../../slash-commands/SlashCommandEnumValue.js';
import { enumIcons } from '../../slash-commands/SlashCommandCommonEnumsProvider.js';
import { POPUP_TYPE, callGenericPopup } from '../../popup.js';
import { GoogleTranslateTtsProvider } from './google-translate.js';
import { GoogleNativeTtsProvider } from './google-native.js';
import { ChatterboxTtsProvider } from './chatterbox.js';
import { KokoroTtsProvider } from './kokoro.js';
import { TtsWebuiProvider } from './tts-webui.js';
import { PollinationsTtsProvider } from './pollinations.js';
import { MiniMaxTtsProvider } from './minimax.js';
import { ElectronHubTtsProvider } from './electronhub.js';
const UPDATE_INTERVAL = 1000;
const wrapper = new ModuleWorkerWrapper(moduleWorker);
let voiceMapEntries = [];
let voiceMap = {}; // {charName:voiceid, charName2:voiceid2}
let lastChatId = null;
let lastMessage = null;
let lastMessageHash = null;
let periodicMessageGenerationTimer = null;
let lastPositionOfParagraphEnd = -1;
let currentInitVoiceMapPromise = null;
const DEFAULT_VOICE_MARKER = '[Default Voice]';
const DISABLED_VOICE_MARKER = 'disabled';
export function getPreviewString(lang) {
const previewStrings = {
'en-US': 'The quick brown fox jumps over the lazy dog',
'en-GB': 'Sphinx of black quartz, judge my vow',
'fr-FR': 'Portez ce vieux whisky au juge blond qui fume',
'de-DE': 'Victor jagt zwölf Boxkämpfer quer über den großen Sylter Deich',
'it-IT': 'Pranzo d\'acqua fa volti sghembi',
'es-ES': 'Quiere la boca exhausta vid, kiwi, piña y fugaz jamón',
'es-MX': 'Fabio me exige, sin tapujos, que añada cerveza al whisky',
'ru-RU': 'В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!',
'pt-BR': 'Vejo xá gritando que fez show sem playback.',
'pt-PR': 'Todo pajé vulgar faz boquinha sexy com kiwi.',
'uk-UA': 'Фабрикуймо гідність, лящім їжею, ґав хапаймо, з\'єднавці чаш!',
'pl-PL': 'Pchnąć w tę łódź jeża lub ośm skrzyń fig',
'cs-CZ': 'Příliš žluťoučký kůň úpěl ďábelské ódy',
'sk-SK': 'Vyhŕňme si rukávy a vyprážajme čínske ryžové cestoviny',
'hu-HU': 'Árvíztűrő tükörfúrógép',
'tr-TR': 'Pijamalı hasta yağız şoföre çabucak güvendi',
'nl-NL': 'De waard heeft een kalfje en een pinkje opgegeten',
'sv-SE': 'Yxskaftbud, ge vårbygd, zinkqvarn',
'da-DK': 'Quizdeltagerne spiste jordbær med fløde, mens cirkusklovnen Walther spillede på xylofon',
'ja-JP': 'いろはにほへと ちりぬるを わかよたれそ つねならむ うゐのおくやま けふこえて あさきゆめみし ゑひもせす',
'ko-KR': '가나다라마바사아자차카타파하',
'zh-CN': '我能吞下玻璃而不伤身体',
'ro-RO': 'Muzicologă în bej vând whisky și tequila, preț fix',
'bg-BG': 'Щъркелите се разпръснаха по цялото небе',
'el-GR': 'Ταχίστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός',
'fi-FI': 'Voi veljet, miksi juuri teille myin nämä vehkeet?',
'he-IL': 'הקצינים צעקו: "כל הכבוד לצבא הצבאות!"',
'id-ID': 'Jangkrik itu memang enak, apalagi kalau digoreng',
'ms-MY': 'Muzik penyanyi wanita itu menggambarkan kehidupan yang penuh dengan duka nestapa',
'th-TH': 'เป็นไงบ้างครับ ผมชอบกินข้าวผัดกระเพราหมูกรอบ',
'vi-VN': 'Cô bé quàng khăn đỏ đang ngồi trên bãi cỏ xanh',
'ar-SA': 'أَبْجَدِيَّة عَرَبِيَّة',
'hi-IN': 'श्वेता ने श्वेता के श्वेते हाथों में श्वेता का श्वेता चावल पकड़ा',
};
const fallbackPreview = 'Neque porro quisquam est qui dolorem ipsum quia dolor sit amet';
return previewStrings[lang] ?? fallbackPreview;
}
/**
* Registers a TTS provider.
* @param {string} name Name of the TTS provider to register.
* @param {function} provider Provider class.
*/
export function registerTtsProvider(name, provider) {
if (!name || typeof name !== 'string') {
throw new Error(`TTS provider name ${name} is not a valid string.`);
}
if (!provider || typeof provider !== 'function') {
throw new Error(`TTS provider ${name} is not a valid provider class.`);
}
if (ttsProviders[name]) {
throw new Error(`TTS provider ${name} is already registered.`);
}
ttsProviders[name] = provider;
console.info(`Registered TTS provider: ${name}`);
$('#tts_provider').append($('<option />').val(name).text(name));
// Load if it was previously selected
if (extension_settings.tts.currentProvider === name) {
loadTtsProvider(name);
}
}
const ttsProviders = {
AllTalk: AllTalkTtsProvider,
Azure: AzureTtsProvider,
Chatterbox: ChatterboxTtsProvider,
Coqui: CoquiTtsProvider,
'CosyVoice (Unofficial)': CosyVoiceProvider,
Edge: EdgeTtsProvider,
ElevenLabs: ElevenLabsTtsProvider,
'Electron Hub': ElectronHubTtsProvider,
'Google Translate': GoogleTranslateTtsProvider,
'Google Gemini TTS': GoogleNativeTtsProvider,
GSVI: GSVITtsProvider,
'GPT-SoVITS-V2 (Unofficial)': GptSovitsV2Provider,
Kokoro: KokoroTtsProvider,
MiniMax: MiniMaxTtsProvider,
Novel: NovelTtsProvider,
OpenAI: OpenAITtsProvider,
'OpenAI Compatible': OpenAICompatibleTtsProvider,
Pollinations: PollinationsTtsProvider,
SBVits2: SBVits2TtsProvider,
Silero: SileroTtsProvider,
SpeechT5: SpeechT5TtsProvider,
System: SystemTtsProvider,
'TTS WebUI': TtsWebuiProvider,
VITS: VITSTtsProvider,
XTTSv2: XTTSTtsProvider,
};
let ttsProvider;
let ttsProviderName;
async function onNarrateOneMessage() {
audioElement.src = '/sounds/silence.mp3';
const context = getContext();
const id = $(this).closest('.mes').attr('mesid');
const message = context.chat[id];
if (!message) {
return;
}
resetTtsPlayback();
processAndQueueTtsMessage(message);
moduleWorker();
}
async function onNarrateText(args, text) {
if (!text) {
return '';
}
audioElement.src = '/sounds/silence.mp3';
// To load all characters in the voice map, set unrestricted to true
await initVoiceMap(true);
const baseName = args?.voice || name2;
const name = (baseName === 'SillyTavern System' ? DEFAULT_VOICE_MARKER : baseName) || DEFAULT_VOICE_MARKER;
const voiceMapEntry = voiceMap[name] === DEFAULT_VOICE_MARKER
? voiceMap[DEFAULT_VOICE_MARKER]
: voiceMap[name];
if (!voiceMapEntry || voiceMapEntry === DISABLED_VOICE_MARKER) {
toastr.info(`Specified voice for ${name} was not found. Check the TTS extension settings.`);
return;
}
resetTtsPlayback();
processAndQueueTtsMessage({ mes: text, name: name });
await moduleWorker();
// Return back to the chat voices
await initVoiceMap(false);
return '';
}
async function moduleWorker() {
if (!extension_settings.tts.enabled) {
return;
}
processTtsQueue();
processAudioJobQueue();
updateUiAudioPlayState();
}
function resetTtsPlayback() {
// Stop system TTS utterance
cancelTtsPlay();
// Clear currently processing jobs
currentTtsJob = null;
currentAudioJob = null;
// Reset audio element
audioElement.currentTime = 0;
audioElement.src = '';
// Clear any queue items
ttsJobQueue.splice(0, ttsJobQueue.length);
audioJobQueue.splice(0, audioJobQueue.length);
// Set audio ready to process again
audioQueueProcessorReady = true;
}
function isTtsProcessing() {
let processing = false;
// Check job queues
if (ttsJobQueue.length > 0 || audioJobQueue.length > 0) {
processing = true;
}
// Check current jobs
if (currentTtsJob != null || currentAudioJob != null) {
processing = true;
}
return processing;
}
/**
* Splits a message into lines and adds each non-empty line to the TTS job queue.
* @param {Object} message - The message object to be processed.
* @param {string} message.mes - The text of the message to be split into lines.
* @param {string} message.name - The name associated with the message.
* @returns {void}
*/
function processAndQueueTtsMessage(message) {
if (!extension_settings.tts.narrate_by_paragraphs) {
ttsJobQueue.push(message);
return;
}
const lines = message.mes.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.length === 0) {
continue;
}
ttsJobQueue.push(
Object.assign({}, message, {
mes: line,
}),
);
}
}
function debugTtsPlayback() {
console.log(JSON.stringify(
{
'ttsProviderName': ttsProviderName,
'voiceMap': voiceMap,
'audioPaused': audioPaused,
'audioJobQueue': audioJobQueue,
'currentAudioJob': currentAudioJob,
'audioQueueProcessorReady': audioQueueProcessorReady,
'ttsJobQueue': ttsJobQueue,
'currentTtsJob': currentTtsJob,
'ttsConfig': extension_settings.tts,
},
));
}
window['debugTtsPlayback'] = debugTtsPlayback;
//##################//
// Audio Control //
//##################//
let audioElement = new Audio();
audioElement.id = 'tts_audio';
audioElement.autoplay = true;
/**
* @type AudioJob[] Audio job queue
* @typedef {{audioBlob: Blob | string, char: string}} AudioJob Audio job object
*/
let audioJobQueue = [];
/**
* @type AudioJob Current audio job
*/
let currentAudioJob;
let audioPaused = false;
let audioQueueProcessorReady = true;
/**
* Play audio data from audio job object.
* @param {AudioJob} audioJob Audio job object
* @returns {Promise<void>} Promise that resolves when audio playback is started
*/
async function playAudioData(audioJob) {
const { audioBlob, char } = audioJob;
// Since current audio job can be cancelled, don't playback if it is null
if (currentAudioJob == null) {
console.log('Cancelled TTS playback because currentAudioJob was null');
}
if (audioBlob instanceof Blob) {
const srcUrl = await getBase64Async(audioBlob);
// VRM lip sync
if (extension_settings.vrm?.enabled && typeof window['vrmLipSync'] === 'function') {
await window['vrmLipSync'](audioBlob, char);
}
audioElement.src = srcUrl;
} else if (typeof audioBlob === 'string') {
audioElement.src = audioBlob;
} else {
throw `TTS received invalid audio data type ${typeof audioBlob}`;
}
audioElement.addEventListener('ended', completeCurrentAudioJob);
audioElement.addEventListener('canplay', () => {
console.debug('Starting TTS playback');
audioElement.playbackRate = extension_settings.tts.playback_rate;
audioElement.play();
});
}
window['tts_preview'] = function (id) {
const audio = document.getElementById(id);
if (audio instanceof HTMLAudioElement && !$(audio).data('disabled')) {
audio.play();
}
else {
ttsProvider.previewTtsVoice(id);
}
};
async function onTtsVoicesClick() {
let popupText = '';
try {
const voiceIds = await ttsProvider.fetchTtsVoiceObjects();
for (const voice of voiceIds) {
popupText += `
<div class="voice_preview">
<span class="voice_lang">${voice.lang || ''}</span>
<b class="voice_name">${voice.name}</b>
<i onclick="tts_preview('${voice.voice_id}')" class="fa-solid fa-play"></i>
</div>`;
if (voice.preview_url) {
popupText += `<audio id="${voice.voice_id}" src="${voice.preview_url}" data-disabled="${voice.preview_url == false}"></audio>`;
}
}
} catch {
popupText = 'Could not load voices list. Check your API key.';
}
callGenericPopup(popupText, POPUP_TYPE.TEXT, '', { allowVerticalScrolling: true });
}
function updateUiAudioPlayState() {
if (extension_settings.tts.enabled == true) {
$('#ttsExtensionMenuItem').show();
let img;
// Give user feedback that TTS is active by setting the stop icon if processing or playing
if (!audioElement.paused || isTtsProcessing()) {
img = 'fa-solid fa-stop-circle extensionsMenuExtensionButton';
} else {
img = 'fa-solid fa-circle-play extensionsMenuExtensionButton';
}
$('#tts_media_control').attr('class', img);
} else {
$('#ttsExtensionMenuItem').hide();
}
}
function onAudioControlClicked() {
audioElement.src = '/sounds/silence.mp3';
let context = getContext();
// Not pausing, doing a full stop to anything TTS is doing. Better UX as pause is not as useful
if (!audioElement.paused || isTtsProcessing()) {
resetTtsPlayback();
} else {
// Default play behavior if not processing or playing is to play the last message.
processAndQueueTtsMessage(context.chat[context.chat.length - 1]);
}
updateUiAudioPlayState();
}
function addAudioControl() {
$('#tts_wand_container').append(`
<div id="ttsExtensionMenuItem" class="list-group-item flex-container flexGap5">
<div id="tts_media_control" class="extensionsMenuExtensionButton "/></div>
TTS Playback
</div>`);
$('#tts_wand_container').append(`
<div id="ttsExtensionNarrateAll" class="list-group-item flex-container flexGap5">
<div class="extensionsMenuExtensionButton fa-solid fa-radio"></div>
Narrate All Chat
</div>`);
$('#ttsExtensionMenuItem').attr('title', 'TTS play/pause').on('click', onAudioControlClicked);
$('#ttsExtensionNarrateAll').attr('title', 'Narrate all messages in the current chat. Includes user messages, excludes hidden comments.').on('click', playFullConversation);
updateUiAudioPlayState();
}
function completeCurrentAudioJob() {
audioQueueProcessorReady = true;
currentAudioJob = null;
// updateUiPlayState();
wrapper.update();
}
/**
* Accepts an HTTP response containing audio/mpeg data, and puts the data as a Blob() on the queue for playback
* @param {Response} response
*/
async function addAudioJob(response, char) {
if (typeof response === 'string') {
audioJobQueue.push({ audioBlob: response, char: char });
} else {
const audioData = await response.blob();
if (!audioData.type.startsWith('audio/')) {
throw `TTS received HTTP response with invalid data format. Expecting audio/*, got ${audioData.type}`;
}
audioJobQueue.push({ audioBlob: audioData, char: char });
}
console.debug('Pushed audio job to queue.');
}
async function processAudioJobQueue() {
// Nothing to do, audio not completed, or audio paused - stop processing.
if (audioJobQueue.length == 0 || !audioQueueProcessorReady || audioPaused) {
return;
}
try {
audioQueueProcessorReady = false;
currentAudioJob = audioJobQueue.shift();
playAudioData(currentAudioJob);
} catch (error) {
toastr.error(error.toString());
console.error(error);
audioQueueProcessorReady = true;
}
}
//################//
// TTS Control //
//################//
let ttsJobQueue = [];
let currentTtsJob; // Null if nothing is currently being processed
function completeTtsJob() {
console.info(`Current TTS job for ${currentTtsJob?.name} completed.`);
currentTtsJob = null;
}
async function tts(text, voiceId, char, voiceMapKey = null) {
async function processResponse(response) {
// RVC injection
if (typeof window['rvcVoiceConversion'] === 'function' && extension_settings.rvc.enabled)
response = await window['rvcVoiceConversion'](response, char, text);
await addAudioJob(response, char);
}
// voiceMapKey can also include segment qualifiers, e.g. '{char} ("Quotes")'
let response = await ttsProvider.generateTts(text, voiceId, voiceMapKey);
// If async generator, process every chunk as it comes in
if (typeof response[Symbol.asyncIterator] === 'function') {
for await (const chunk of response) {
await processResponse(chunk);
}
} else {
await processResponse(response);
}
completeTtsJob();
}
function parseMessageSegments(text) {
if (!extension_settings.tts.multi_voice_enabled) {
return [{ type: 'other', text: text }];
}
const segments = [];
const segmentRegex = /(\*[^*]*?\*)|(".*?")|(\u201C.*?\u201D)|(\u00AB.*?\u00BB)|(\u300C.*?\u300D)|(\u300E.*?\u300F)|(\uFF02.*?\uFF02)/gim;
let lastIndex = 0;
let match;
segmentRegex.lastIndex = 0;
while ((match = segmentRegex.exec(text)) !== null) {
// Add other text before this match
if (match.index > lastIndex) {
const otherText = text.substring(lastIndex, match.index).trim();
if (otherText && otherText.length > 0) {
segments.push({ type: 'other', text: otherText });
}
}
const matchedText = match[0];
let segmentType = 'other';
let content = '';
if (match[1]) {
// Asterisk content (*action*)
segmentType = 'action';
content = matchedText.slice(1, -1);
} else if (match[2] || match[3] || match[4] || match[5] || match[6] || match[7]) {
// Various quote types ("dialogue")
segmentType = 'dialogue';
content = matchedText.slice(1, -1);
}
// Trim and check for actual content
content = content.trim();
if (content.length > 0) {
segments.push({
type: segmentType,
text: content,
});
}
lastIndex = match.index + matchedText.length;
}
// Add remaining other text after last match
if (lastIndex < text.length) {
const otherText = text.substring(lastIndex).trim();
if (otherText.length > 0) {
segments.push({ type: 'other', text: otherText });
}
}
// If no segments found and not empty, treat whole text as other text
if (segments.length === 0 && text.trim().length > 0) {
segments.push({ type: 'other', text: text.trim() });
}
return segments;
}
async function processTtsQueue() {
// Called each moduleWorker iteration to pull chat messages from queue
if (currentTtsJob || ttsJobQueue.length <= 0 || audioPaused) {
return;
}
console.debug('New message found, running TTS');
currentTtsJob = ttsJobQueue.shift();
// Handle segmented jobs that already have processed text
if (currentTtsJob.segmentType && currentTtsJob.segmentText) {
const char = currentTtsJob.name;
const segmentText = currentTtsJob.segmentText;
const segmentType = currentTtsJob.segmentType;
console.log(`TTS (${segmentType}): ${segmentText}`);
try {
let voiceMapKey = char;
// If multi-voice is enabled, modify the voice map key based on segment type
if (extension_settings.tts.multi_voice_enabled && char !== DEFAULT_VOICE_MARKER) {
switch (segmentType) {
case 'dialogue':
voiceMapKey = `${char} ("Quotes")`;
break;
case 'action':
voiceMapKey = `${char} (*Text inside asterisks*)`;
break;
case 'other':
default:
voiceMapKey = `${char} (Other text)`;
break;
}
}
const voiceMapEntry = voiceMap[voiceMapKey] === DEFAULT_VOICE_MARKER ? voiceMap[DEFAULT_VOICE_MARKER] : voiceMap[voiceMapKey];
if (!voiceMapEntry || voiceMapEntry === DISABLED_VOICE_MARKER) {
throw `${char} not in voicemap. Configure character in extension settings voice map`;
}
const voice = await ttsProvider.getVoice(voiceMapEntry);
const voiceId = voice.voice_id;
if (voiceId == null) {
toastr.error(`Specified voice for ${char} was not found. Check the TTS extension settings.`);
throw `Unable to attain voiceId for ${char}`;
}
// Pass the full voiceMapKey (e.g., "User ("Quotes")") as well with character name
await tts(segmentText, voiceId, char, voiceMapKey);
} catch (error) {
toastr.error(error.toString());
console.error(error);
currentTtsJob = null;
}
return;
}
// Process unsegmented job (first time processing)
let text = extension_settings.tts.narrate_translated_only ? (currentTtsJob?.extra?.display_text || currentTtsJob.mes) : currentTtsJob.mes;
// Substitute macros
text = substituteParams(text);
if (extension_settings.tts.skip_codeblocks) {
text = text.replace(/^\s{4}.*$/gm, '').trim();
text = text.replace(/```.*?```/gs, '').trim();
text = text.replace(/~~~.*?~~~/gs, '').trim();
}
if (extension_settings.tts.skip_tags) {
text = text.replace(/<.*?>[\s\S]*?<\/.*?>/g, '').trim();
}
if (!extension_settings.tts.pass_asterisks) {
text = extension_settings.tts.narrate_dialogues_only
? text.replace(/\*[^*]*?(\*|$)/g, '').trim() // remove asterisks content
: text.replaceAll('*', '').trim(); // remove just the asterisks
}
if (extension_settings.tts.narrate_quoted_only) {
const partJoiner = (ttsProvider?.separator || ' ... ');
text = joinQuotedBlocks(text, { separator: partJoiner, includeQuotes: true });
}
// Remove embedded images
text = text.replace(/!\[.*?]\([^)]*\)/g, '');
if (typeof ttsProvider?.processText === 'function') {
text = await ttsProvider.processText(text);
}
// Collapse newlines and spaces into single space
text = text.replace(/\s+/g, ' ').trim();
console.log(`TTS: ${text}`);
const char = currentTtsJob.name;
// Remove character name from start of the line if power user setting is disabled
if (char && !power_user.allow_name2_display) {
const escapedChar = escapeRegex(char);
text = text.replace(new RegExp(`^${escapedChar}:`, 'gm'), '');
}
try {
if (!text) {
console.warn('Got empty text in TTS queue job.');
completeTtsJob();
return;
}
// Parse message into segments if multi-voice is enabled
const segments = parseMessageSegments(text);
if (segments.length === 0) {
console.warn('No valid segments found in text.');
completeTtsJob();
return;
}
// Add all segments to the queue as separate jobs (in reverse order so they process in correct order)
for (let i = segments.length - 1; i >= 0; i--) {
const segmentJob = {
name: char,
segmentType: segments[i].type,
segmentText: segments[i].text,
is_user: currentTtsJob.is_user,
mes: currentTtsJob.mes,
extra: currentTtsJob.extra,
};
ttsJobQueue.unshift(segmentJob);
}
// Clear current job so the segmented jobs can be processed
currentTtsJob = null;
} catch (error) {
toastr.error(error.toString());
console.error(error);
currentTtsJob = null;
}
}
/**
* Extract and join quoted blocks with proper matching pairs and nesting.
* - Captures outermost quotes and everything inside (including different inner quote styles).
* - Requires matching opener/closer style (e.g., “ ... ”, 「 ... 」, « ... », etc.).
* - Ignores incomplete/unclosed quotes (doesn't include them in the result).
* - Symmetric quotes like "..." and "..." are supported (not nesting the same symmetric style).
*
* @param {string} text - The text to process
* @param {object} [opts={}] - Optional options object
* @param {string} [opts.separator=' ... '] - String to join multiple quoted blocks
* @param {boolean} [opts.includeQuotes=true] - Keep the quote chars around the captured text
* @param {boolean} [opts.returnEmptyOnNoQuotes=false] - Return an empty string if no quotes are found
* @param {Array<[string,string]>} [opts.pairs] - Custom quote pairs; defaults cover EN/DE/FR/JP
* @returns {string} The joined quoted blocks, or the original text if no quotes found
*/
function joinQuotedBlocks(text, opts = {}) {
const {
separator = ' ... ',
includeQuotes = true,
returnEmptyOnNoQuotes = false,
pairs = [
// typographic doubles
['„', '“'], // DE low-high
['“', '”'], // EN
['«', '»'], // FR open « close »
['»', '«'], // Some locales open »
// typographic singles
['‘', '’'],
['‚', '‘'],
// Japanese corner quotes
['「', '」'],
['『', '』'],
// symmetric doubles
['"', '"'],
['"', '"'],
],
} = opts;
if (!text || typeof text !== 'string') return text;
const openToClose = Object.fromEntries(pairs);
const segments = [];
const stack = []; // [{ opener, expectedClose, start }]
for (let i = 0; i < text.length; i++) {
const ch = text[i];
const top = stack[stack.length - 1];
// Prefer closing the current open pair if the char matches its expected closer
if (top && ch === top.expectedClose) {
const finished = stack.pop();
if (stack.length === 0) {
// Only collect outermost quotes (contains all nested content)
segments.push(text.slice(finished.start, i + 1));
}
continue;
}
// Otherwise, see if this is a new opener
if (openToClose[ch]) {
stack.push({ opener: ch, expectedClose: openToClose[ch], start: i });
continue;
}
// If it's a stray closer that doesn't match current top, ignore
}
if (!segments.length) return returnEmptyOnNoQuotes ? '' : text;
const cleaned = includeQuotes
? segments
: segments.map(s => s.slice(1, -1)); // all defined pairs are single-char quotes
return cleaned.join(separator);
}
async function playFullConversation() {
resetTtsPlayback();
if (!extension_settings.tts.enabled) {
return toastr.warning('TTS is disabled. Please enable it in the extension settings.');
}
const context = getContext();
const chat = context.chat.filter(x => !x.is_system && x.mes !== '...' && x.mes !== '');
if (chat.length === 0) {
return toastr.info('No messages to narrate.');
}
ttsJobQueue = chat;
}
window['playFullConversation'] = playFullConversation;
//#############################//
// Extension UI and Settings //
//#############################//
function loadSettings() {
if (Object.keys(extension_settings.tts).length === 0) {
Object.assign(extension_settings.tts, defaultSettings);
}
for (const key in defaultSettings) {
if (!(key in extension_settings.tts)) {
extension_settings.tts[key] = defaultSettings[key];
}
}
$('#tts_provider').val(extension_settings.tts.currentProvider);
$('#tts_enabled').prop(
'checked',
extension_settings.tts.enabled,
);
$('#tts_narrate_dialogues').prop('checked', extension_settings.tts.narrate_dialogues_only);
$('#tts_narrate_quoted').prop('checked', extension_settings.tts.narrate_quoted_only);
$('#tts_auto_generation').prop('checked', extension_settings.tts.auto_generation);
$('#tts_periodic_auto_generation').prop('checked', extension_settings.tts.periodic_auto_generation);
$('#tts_narrate_by_paragraphs').prop('checked', extension_settings.tts.narrate_by_paragraphs);
$('#tts_narrate_translated_only').prop('checked', extension_settings.tts.narrate_translated_only);
$('#tts_narrate_user').prop('checked', extension_settings.tts.narrate_user);
$('#tts_pass_asterisks').prop('checked', extension_settings.tts.pass_asterisks);
$('#tts_skip_codeblocks').prop('checked', extension_settings.tts.skip_codeblocks);
$('#tts_skip_tags').prop('checked', extension_settings.tts.skip_tags);
$('#tts_multi_voice_enabled').prop('checked', extension_settings.tts.multi_voice_enabled);
$('#playback_rate').val(extension_settings.tts.playback_rate);
$('#playback_rate_counter').val(Number(extension_settings.tts.playback_rate).toFixed(2));
$('#playback_rate_block').toggle(extension_settings.tts.currentProvider !== 'System');
$('body').toggleClass('tts', extension_settings.tts.enabled);
}
const defaultSettings = {
voiceMap: '',
ttsEnabled: false,
currentProvider: 'ElevenLabs',
auto_generation: true,
narrate_user: false,
playback_rate: 1,
multi_voice_enabled: false,
};
function setTtsStatus(status, success) {
$('#tts_status').text(status);
if (success) {
$('#tts_status').removeAttr('style');
} else {
$('#tts_status').css('color', 'red');
}
}
function onRefreshClick() {
Promise.all([
ttsProvider.onRefreshClick(),
// updateVoiceMap()
]).then(() => {
extension_settings.tts[ttsProviderName] = ttsProvider.settings;
saveSettingsDebounced();
setTtsStatus('Successfully applied settings', true);
console.info(`Saved settings ${ttsProviderName} ${JSON.stringify(ttsProvider.settings)}`);
initVoiceMap();
updateVoiceMap();
}).catch(error => {
toastr.error(error.toString());
console.error(error);
setTtsStatus(error, false);
});
}
function onEnableClick() {
extension_settings.tts.enabled = $('#tts_enabled').is(
':checked',
);
updateUiAudioPlayState();
saveSettingsDebounced();
$('body').toggleClass('tts', extension_settings.tts.enabled);
}
function onAutoGenerationClick() {
extension_settings.tts.auto_generation = !!$('#tts_auto_generation').prop('checked');
saveSettingsDebounced();
}
function onPeriodicAutoGenerationClick() {
extension_settings.tts.periodic_auto_generation = !!$('#tts_periodic_auto_generation').prop('checked');
saveSettingsDebounced();
}
function onNarrateByParagraphsClick() {
extension_settings.tts.narrate_by_paragraphs = !!$('#tts_narrate_by_paragraphs').prop('checked');
saveSettingsDebounced();
}
function onNarrateDialoguesClick() {
extension_settings.tts.narrate_dialogues_only = !!$('#tts_narrate_dialogues').prop('checked');
saveSettingsDebounced();
}
function onNarrateUserClick() {
extension_settings.tts.narrate_user = !!$('#tts_narrate_user').prop('checked');
saveSettingsDebounced();
}
function onNarrateQuotedClick() {
extension_settings.tts.narrate_quoted_only = !!$('#tts_narrate_quoted').prop('checked');
saveSettingsDebounced();
}
function onNarrateTranslatedOnlyClick() {
extension_settings.tts.narrate_translated_only = !!$('#tts_narrate_translated_only').prop('checked');
saveSettingsDebounced();
}
function onSkipCodeblocksClick() {
extension_settings.tts.skip_codeblocks = !!$('#tts_skip_codeblocks').prop('checked');
saveSettingsDebounced();
}
function onSkipTagsClick() {
extension_settings.tts.skip_tags = !!$('#tts_skip_tags').prop('checked');
saveSettingsDebounced();
}
function onPassAsterisksClick() {
extension_settings.tts.pass_asterisks = !!$('#tts_pass_asterisks').prop('checked');
saveSettingsDebounced();
console.log('setting pass asterisks', extension_settings.tts.pass_asterisks);
}
function onMultiVoiceClick() {
extension_settings.tts.multi_voice_enabled = !!$('#tts_multi_voice_enabled').prop('checked');
saveSettingsDebounced();
// Reinitialize voice map to show/hide voices
initVoiceMap();
}
//##############//
// TTS Provider //
//##############//
async function loadTtsProvider(provider) {
//Clear the current config and add new config
$('#tts_provider_settings').html('');
if (!provider) {
return;
}
// Init provider references
extension_settings.tts.currentProvider = provider;
ttsProviderName = provider;
ttsProvider = new ttsProviders[provider];
// Init provider settings
$('#tts_provider_settings').append(ttsProvider.settingsHtml);
if (!(ttsProviderName in extension_settings.tts)) {
console.warn(`Provider ${ttsProviderName} not in Extension Settings, initiatilizing provider in settings`);
extension_settings.tts[ttsProviderName] = {};
}
await ttsProvider.loadSettings(extension_settings.tts[ttsProviderName]);
await initVoiceMap();
}
function onTtsProviderChange() {
if (typeof ttsProvider?.dispose === 'function') {
ttsProvider.dispose();
}
const ttsProviderSelection = $('#tts_provider').val();
extension_settings.tts.currentProvider = ttsProviderSelection;
$('#playback_rate_block').toggle(extension_settings.tts.currentProvider !== 'System');
loadTtsProvider(ttsProviderSelection);
}
// Ensure that TTS provider settings are saved to extension settings.
export function saveTtsProviderSettings() {
extension_settings.tts[ttsProviderName] = ttsProvider.settings;
updateVoiceMap();
saveSettingsDebounced();
console.info(`Saved settings ${ttsProviderName} ${JSON.stringify(ttsProvider.settings)}`);
}
//###################//
// voiceMap Handling //
//###################//
async function onChatChanged() {
await onGenerationEnded();
resetTtsPlayback();
const voiceMapInit = initVoiceMap();
await Promise.race([voiceMapInit, delay(debounce_timeout.relaxed)]);
lastMessage = null;
}
async function onMessageEvent(messageId, lastCharIndex) {
// If TTS is disabled, do nothing
if (!extension_settings.tts.enabled) {
return;
}
// Auto generation is disabled
if (!extension_settings.tts.auto_generation) {
return;
}
const context = getContext();
// no characters or group selected
if (!context.groupId && context.characterId === undefined) {
return;
}
// Chat changed
if (context.chatId !== lastChatId) {
lastChatId = context.chatId;
lastMessageHash = getStringHash(context.chat[messageId]?.mes ?? '');
// Force to speak on the first message in the new chat
if (context.chat.length === 1) {
lastMessageHash = -1;
}
}
// clone message object, as things go haywire if message object is altered below (it's passed by reference)
const message = structuredClone(context.chat[messageId]);
const hashNew = getStringHash(message?.mes ?? '');
// Ignore prompt-hidden messages
if (message.is_system) {
return;
}
// if no new messages, or same message, or same message hash, do nothing
if (hashNew === lastMessageHash) {
return;
}
// if we only want to process part of the message
if (lastCharIndex) {
message.mes = message.mes.substring(0, lastCharIndex);
}
const isLastMessageInCurrent = () =>
lastMessage &&
typeof lastMessage === 'object' &&
message.swipe_id === lastMessage.swipe_id &&
message.name === lastMessage.name &&
message.is_user === lastMessage.is_user &&
message.mes.indexOf(lastMessage.mes) !== -1;
// if last message within current message, message got extended. only send diff to TTS.
if (isLastMessageInCurrent()) {
const tmp = structuredClone(message);
message.mes = message.mes.replace(lastMessage.mes, '');
lastMessage = tmp;
} else {
lastMessage = structuredClone(message);
}
// We're currently swiping. Don't generate voice
if (!message || message.mes === '...' || message.mes === '') {
return;
}
// Don't generate if message doesn't have a display text
if (extension_settings.tts.narrate_translated_only && !(message?.extra?.display_text)) {
return;
}
// Don't generate if message is a user message and user message narration is disabled
if (message.is_user && !extension_settings.tts.narrate_user) {
return;
}
// New messages, add new chat to history
lastMessageHash = hashNew;
lastChatId = context.chatId;
console.debug(`Adding message from ${message.name} for TTS processing: "${message.mes}"`);
if (extension_settings.tts.periodic_auto_generation && isStreamingEnabled()) {
ttsJobQueue.push(message);
} else {
processAndQueueTtsMessage(message);
}
}
async function onMessageDeleted() {
const context = getContext();
// update internal references to new last message
lastChatId = context.chatId;
// compare against lastMessageHash. If it's the same, we did not delete the last chat item, so no need to reset tts queue
const messageHash = getStringHash((context.chat.length && context.chat[context.chat.length - 1].mes) ?? '');
if (messageHash === lastMessageHash) {
return;
}
lastMessageHash = messageHash;
lastMessage = context.chat.length ? structuredClone(context.chat[context.chat.length - 1]) : null;
// stop any tts playback since message might not exist anymore
resetTtsPlayback();
}
async function onGenerationStarted(generationType, _args, isDryRun) {
// If dry running or quiet mode, do nothing
if (isDryRun || ['quiet', 'impersonate'].includes(generationType)) {
return;
}
// If TTS is disabled, do nothing
if (!extension_settings.tts.enabled) {
return;
}
// Auto generation is disabled
if (!extension_settings.tts.auto_generation) {
return;
}
// Periodic auto generation is disabled
if (!extension_settings.tts.periodic_auto_generation) {
return;
}
// If the reply is not being streamed
if (!isStreamingEnabled()) {
return;
}
// start the timer
if (!periodicMessageGenerationTimer) {
periodicMessageGenerationTimer = setInterval(onPeriodicMessageGenerationTick, UPDATE_INTERVAL);
}
}
async function onGenerationEnded() {
if (periodicMessageGenerationTimer) {
clearInterval(periodicMessageGenerationTimer);
periodicMessageGenerationTimer = null;
}
lastPositionOfParagraphEnd = -1;
}
async function onPeriodicMessageGenerationTick() {
const context = getContext();
// no characters or group selected
if (!context.groupId && context.characterId === undefined) {
return;
}
const lastMessageId = context.chat.length - 1;
// the last message was from the user
if (context.chat[lastMessageId].is_user) {
return;
}
const lastMessage = structuredClone(context.chat[lastMessageId]);
const lastMessageText = lastMessage?.mes ?? '';
// look for double ending lines which should indicate the end of a paragraph
let newLastPositionOfParagraphEnd = lastMessageText
.indexOf('\n\n', lastPositionOfParagraphEnd + 1);
// if not found, look for a single ending line which should indicate the end of a paragraph
if (newLastPositionOfParagraphEnd === -1) {
newLastPositionOfParagraphEnd = lastMessageText
.indexOf('\n', lastPositionOfParagraphEnd + 1);
}
// send the message to the tts module if we found the new end of a paragraph
if (newLastPositionOfParagraphEnd > -1) {
onMessageEvent(lastMessageId, newLastPositionOfParagraphEnd);
if (periodicMessageGenerationTimer) {
lastPositionOfParagraphEnd = newLastPositionOfParagraphEnd;
}
}
}
/**
* Get characters in current chat
* @param {boolean} unrestricted - If true, will include all characters in voiceMapEntries, even if they are not in the current chat.
* @returns {string[]} - Array of character names
*/
function getCharacters(unrestricted) {
const context = getContext();
if (unrestricted) {
const names = context.characters.map(char => char.name);
names.unshift(DEFAULT_VOICE_MARKER);
return names.filter(onlyUnique);
}
let characters = [];
if (context.groupId === null) {
// Single char chat
characters.push(DEFAULT_VOICE_MARKER);
characters.push(context.name1);
characters.push(context.name2);
} else {
// Group chat
characters.push(DEFAULT_VOICE_MARKER);
characters.push(context.name1);
const group = context.groups.find(group => context.groupId == group.id);
for (let member of group.members) {
const character = context.characters.find(char => char.avatar == member);
if (character) {
characters.push(character.name);
}
}
}
characters = characters.filter(onlyUnique);
// If multi-voice is enabled, expand characters to include segment types
if (extension_settings.tts.multi_voice_enabled) {
const expandedCharacters = [];
for (const char of characters) {
if (char === DEFAULT_VOICE_MARKER || char === 'SillyTavern System') {
expandedCharacters.push(char);
} else {
expandedCharacters.push(`${char} ("Quotes")`);
expandedCharacters.push(`${char} (*Text inside asterisks*)`);
expandedCharacters.push(`${char} (Other text)`);
}
}
return expandedCharacters;
}
return characters;
}
export function sanitizeId(input) {
// Remove any non-alphanumeric characters except underscore (_) and hyphen (-)
let sanitized = encodeURIComponent(input).replace(/[^a-zA-Z0-9-_]/g, '');
// Ensure first character is always a letter
if (!/^[a-zA-Z]/.test(sanitized)) {
sanitized = 'element_' + sanitized;
}
return sanitized;
}
function parseVoiceMap(voiceMapString) {
let parsedVoiceMap = {};
for (const [charName, voiceId] of voiceMapString
.split(',')
.map(s => s.split(':'))) {
if (charName && voiceId) {
parsedVoiceMap[charName.trim()] = voiceId.trim();
}
}
return parsedVoiceMap;
}
/**
* Apply voiceMap based on current voiceMapEntries
*/
function updateVoiceMap() {
const tempVoiceMap = {};
for (const voice of voiceMapEntries) {
if (voice.voiceId === null) {
continue;
}
tempVoiceMap[voice.name] = voice.voiceId;
}
if (Object.keys(tempVoiceMap).length !== 0) {
voiceMap = tempVoiceMap;
console.log(`Voicemap updated to ${JSON.stringify(voiceMap)}`);
}
if (!extension_settings.tts[ttsProviderName].voiceMap) {
extension_settings.tts[ttsProviderName].voiceMap = {};
}
Object.assign(extension_settings.tts[ttsProviderName].voiceMap, voiceMap);
saveSettingsDebounced();
}
class VoiceMapEntry {
name;
voiceId;
selectElement;
constructor(name, voiceId = DEFAULT_VOICE_MARKER) {
this.name = name;
this.voiceId = voiceId;
this.selectElement = null;
}
addUI(voiceIds) {
let sanitizedName = sanitizeId(this.name);
let defaultOption = this.name === DEFAULT_VOICE_MARKER ?
`<option>${DISABLED_VOICE_MARKER}</option>` :
`<option>${DEFAULT_VOICE_MARKER}</option><option>${DISABLED_VOICE_MARKER}</option>`;
let template = `
<div class='tts_voicemap_block_char flex-container flexGap5'>
<span id='tts_voicemap_char_${sanitizedName}'>${this.name}</span>
<select id='tts_voicemap_char_${sanitizedName}_voice'>
${defaultOption}
</select>
</div>
`;
$('#tts_voicemap_block').append(template);
// Populate voice ID select list
for (const voiceId of voiceIds) {
const option = document.createElement('option');
option.innerText = voiceId.name;
option.value = voiceId.name;
$(`#tts_voicemap_char_${sanitizedName}_voice`).append(option);
}
this.selectElement = $(`#tts_voicemap_char_${sanitizedName}_voice`);
this.selectElement.on('change', args => this.onSelectChange(args));
this.selectElement.val(this.voiceId);
}
onSelectChange(args) {
this.voiceId = this.selectElement.find(':selected').val();
updateVoiceMap();
}
}
/**
* Init voiceMapEntries for character select list.
* If an initialization is already in progress, it returns the existing Promise instead of starting a new one.
* @param {boolean} unrestricted - If true, will include all characters in voiceMapEntries, even if they are not in the current chat.
* @returns {Promise} A promise that resolves when the initialization is complete.
*/
export async function initVoiceMap(unrestricted = false) {
// Preventing parallel execution
if (currentInitVoiceMapPromise) {
return currentInitVoiceMapPromise;
}
currentInitVoiceMapPromise = (async () => {
const initialChatId = getCurrentChatId();
try {
await initVoiceMapInternal(unrestricted);
} finally {
currentInitVoiceMapPromise = null;
}
const currentChatId = getCurrentChatId();
if (initialChatId !== currentChatId) {
// Chat changed during initialization, reinitialize
await initVoiceMap(unrestricted);
}
})();
return currentInitVoiceMapPromise;
}
/**
* Init voiceMapEntries for character select list.
* @param {boolean} unrestricted - If true, will include all characters in voiceMapEntries, even if they are not in the current chat.
*/
async function initVoiceMapInternal(unrestricted) {
// Gate initialization if not enabled or TTS Provider not ready. Prevents error popups.
const enabled = $('#tts_enabled').is(':checked');
if (!enabled) {
return;
}
// Keep errors inside extension UI rather than toastr. Toastr errors for TTS are annoying.
try {
await ttsProvider.checkReady();
} catch (error) {
const message = `TTS Provider not ready. ${error}`;
setTtsStatus(message, false);
return;
}
setTtsStatus('TTS Provider Loaded', true);
// Clear existing voiceMap state
$('#tts_voicemap_block').empty();
voiceMapEntries = [];
// Get characters in current chat
const characters = getCharacters(unrestricted);
// Get saved voicemap from provider settings, handling new and old representations
let voiceMapFromSettings = {};
if ('voiceMap' in extension_settings.tts[ttsProviderName]) {
// Handle previous representation
if (typeof extension_settings.tts[ttsProviderName].voiceMap === 'string') {
voiceMapFromSettings = parseVoiceMap(extension_settings.tts[ttsProviderName].voiceMap);
// Handle new representation
} else if (typeof extension_settings.tts[ttsProviderName].voiceMap === 'object') {
voiceMapFromSettings = extension_settings.tts[ttsProviderName].voiceMap;
}
}
// Get voiceIds from provider
let voiceIdsFromProvider;
try {
voiceIdsFromProvider = await ttsProvider.fetchTtsVoiceObjects();
}
catch {
toastr.error('TTS Provider failed to return voice ids.');
}
// Build UI using VoiceMapEntry objects
for (const character of characters) {
if (character === 'SillyTavern System') {
continue;
}
// Check provider settings for voiceIds
let voiceId;
if (character in voiceMapFromSettings) {
voiceId = voiceMapFromSettings[character];
} else if (character === DEFAULT_VOICE_MARKER) {
voiceId = DISABLED_VOICE_MARKER;
} else {
voiceId = DEFAULT_VOICE_MARKER;
}
const voiceMapEntry = new VoiceMapEntry(character, voiceId);
voiceMapEntry.addUI(voiceIdsFromProvider);
voiceMapEntries.push(voiceMapEntry);
}
updateVoiceMap();
}
jQuery(async function () {
async function addExtensionControls() {
const settingsHtml = $(await renderExtensionTemplateAsync('tts', 'settings'));
$('#tts_container').append(settingsHtml);
$('#tts_refresh').on('click', onRefreshClick);
$('#tts_enabled').on('click', onEnableClick);
$('#tts_narrate_dialogues').on('click', onNarrateDialoguesClick);
$('#tts_narrate_quoted').on('click', onNarrateQuotedClick);
$('#tts_narrate_translated_only').on('click', onNarrateTranslatedOnlyClick);
$('#tts_skip_codeblocks').on('click', onSkipCodeblocksClick);
$('#tts_skip_tags').on('click', onSkipTagsClick);
$('#tts_pass_asterisks').on('click', onPassAsterisksClick);
$('#tts_auto_generation').on('click', onAutoGenerationClick);
$('#tts_periodic_auto_generation').on('click', onPeriodicAutoGenerationClick);
$('#tts_narrate_by_paragraphs').on('click', onNarrateByParagraphsClick);
$('#tts_narrate_user').on('click', onNarrateUserClick);
$('#tts_multi_voice_enabled').on('click', onMultiVoiceClick);
$('#playback_rate').on('input', function () {
const value = $(this).val();
const formattedValue = Number(value).toFixed(2);
extension_settings.tts.playback_rate = value;
$('#playback_rate_counter').val(formattedValue);
saveSettingsDebounced();
});
$('#tts_voices').on('click', onTtsVoicesClick);
for (const provider in ttsProviders) {
$('#tts_provider').append($('<option />').val(provider).text(provider));
}
$('#tts_provider').on('change', onTtsProviderChange);
$(document).on('click', '.mes_narrate', onNarrateOneMessage);
}
await addExtensionControls(); // No init dependencies
loadSettings(); // Depends on Extension Controls and loadTtsProvider
loadTtsProvider(extension_settings.tts.currentProvider); // No dependencies
addAudioControl(); // Depends on Extension Controls
setInterval(wrapper.update.bind(wrapper), UPDATE_INTERVAL); // Init depends on all the things
eventSource.on(event_types.MESSAGE_SWIPED, resetTtsPlayback);
eventSource.on(event_types.CHAT_CHANGED, onChatChanged);
eventSource.on(event_types.MESSAGE_DELETED, onMessageDeleted);
eventSource.on(event_types.GROUP_UPDATED, onChatChanged);
eventSource.on(event_types.GENERATION_STARTED, onGenerationStarted);
eventSource.on(event_types.GENERATION_ENDED, onGenerationEnded);
eventSource.makeLast(event_types.CHARACTER_MESSAGE_RENDERED, (messageId) => onMessageEvent(messageId));
eventSource.makeLast(event_types.USER_MESSAGE_RENDERED, (messageId) => onMessageEvent(messageId));
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
name: 'speak',
callback: async (args, value) => {
await onNarrateText(args, value);
return '';
},
aliases: ['narrate', 'tts'],
namedArgumentList: [
SlashCommandNamedArgument.fromProps({
name: 'voice',
description: 'character voice name',
typeList: [ARGUMENT_TYPE.STRING],
isRequired: false,
enumProvider: () => Object.keys(voiceMap).map(voiceName => new SlashCommandEnumValue(voiceName, null, enumTypes.enum, enumIcons.voice)),
}),
],
unnamedArgumentList: [
new SlashCommandArgument(
'text', [ARGUMENT_TYPE.STRING], true,
),
],
helpString: `
<div>
Narrate any text using currently selected character's voice.
</div>
<div>
Use <code>voice="Character Name"</code> argument to set other voice from the voice map.
</div>
<div>
<strong>Example:</strong>
<ul>
<li>
<pre><code>/speak voice="Donald Duck" Quack!</code></pre>
</li>
</ul>
</div>
`,
}));
document.body.appendChild(audioElement);
});
|