File size: 7,555 Bytes
b82d373
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { getRequestHeaders } from '../../../script.js';
import { POPUP_TYPE, callGenericPopup } from '../../popup.js';
import { splitRecursive } from '../../utils.js';
import { getPreviewString, saveTtsProviderSettings } from './index.js';
import { initVoiceMap } from './index.js';

export { NovelTtsProvider };

class NovelTtsProvider {
    //########//
    // Config //
    //########//

    settings;
    voices = [];
    separator = ' . ';
    audioElement = document.createElement('audio');

    defaultSettings = {
        voiceMap: {},
        customVoices: [],
    };

    /**
     * Perform any text processing before passing to TTS engine.
     * @param {string} text Input text
     * @returns {string} Processed text
     */
    processText(text) {
        // Novel reads tilde as a word. Replace with full stop
        text = text.replace(/~/g, '.');
        // Novel reads asterisk as a word. Remove it
        text = text.replace(/\*/g, '');
        return text;
    }

    get settingsHtml() {
        let html = `
        <div class="novel_tts_hints">
            <div>Use NovelAI's TTS engine.</div>
            <div>
                The default Voice IDs are only examples. Add custom voices and Novel will create a new random voice for it.
                Feel free to try different options!
            </div>
            <i>Hint: Save an API key in the NovelAI API settings to use it here.</i>
        </div>
        <label for="tts-novel-custom-voices-add">Custom Voices</label>
        <div class="tts_custom_voices">
            <select id="tts-novel-custom-voices-select"><select>
            <i id="tts-novel-custom-voices-add" class="tts-button fa-solid fa-plus fa-xl success" title="Add"></i>
            <i id="tts-novel-custom-voices-delete" class="tts-button fa-solid fa-xmark fa-xl failure" title="Delete"></i>
        </div>
        `;
        return html;
    }


    // Add a new Novel custom voice to provider
    async addCustomVoice() {
        const voiceName = await callGenericPopup('Custom Voice name:',  POPUP_TYPE.INPUT);
        this.settings.customVoices.push(voiceName);
        this.populateCustomVoices();
        initVoiceMap(); // Update TTS extension voiceMap
        saveTtsProviderSettings();
    }

    // Delete selected custom voice from provider
    deleteCustomVoice() {
        const selected = $('#tts-novel-custom-voices-select').find(':selected').val();
        const voiceIndex = this.settings.customVoices.indexOf(selected);

        if (voiceIndex !== -1) {
            this.settings.customVoices.splice(voiceIndex, 1);
        }
        this.populateCustomVoices();
        initVoiceMap(); // Update TTS extension voiceMap
        saveTtsProviderSettings();
    }

    // Create the UI dropdown list of voices in provider
    populateCustomVoices() {
        let voiceSelect = $('#tts-novel-custom-voices-select');
        voiceSelect.empty();
        this.settings.customVoices.forEach(voice => {
            voiceSelect.append(`<option>${voice}</option>`);
        });
    }

    async loadSettings(settings) {
        // Populate Provider UI given input settings
        if (Object.keys(settings).length == 0) {
            console.info('Using default TTS Provider settings');
        }
        $('#tts-novel-custom-voices-add').on('click', () => (this.addCustomVoice()));
        $('#tts-novel-custom-voices-delete').on('click', () => (this.deleteCustomVoice()));

        // Only accept keys defined in defaultSettings
        this.settings = this.defaultSettings;

        for (const key in settings) {
            if (key in this.settings) {
                this.settings[key] = settings[key];
            } else {
                throw `Invalid setting passed to TTS Provider: ${key}`;
            }
        }

        this.populateCustomVoices();
        await this.checkReady();
        console.debug('NovelTTS: Settings loaded');
    }

    // Perform a simple readiness check by trying to fetch voiceIds
    // Doesnt really do much for Novel, not seeing a good way to test this at the moment.
    async checkReady() {
        await this.fetchTtsVoiceObjects();
    }

    async onRefreshClick() {
        return;
    }

    //#################//
    //  TTS Interfaces //
    //#################//

    async getVoice(voiceName) {
        if (!voiceName) {
            throw 'TTS Voice name not provided';
        }

        return { name: voiceName, voice_id: voiceName, lang: 'en-US', preview_url: false };
    }

    async generateTts(text, voiceId) {
        const response = await this.fetchTtsGeneration(text, voiceId);
        return response;
    }

    //###########//
    // API CALLS //
    //###########//
    async fetchTtsVoiceObjects() {
        let voices = [
            { name: 'Ligeia', voice_id: 'Ligeia', lang: 'en-US', preview_url: false },
            { name: 'Aini', voice_id: 'Aini', lang: 'en-US', preview_url: false },
            { name: 'Orea', voice_id: 'Orea', lang: 'en-US', preview_url: false },
            { name: 'Claea', voice_id: 'Claea', lang: 'en-US', preview_url: false },
            { name: 'Lim', voice_id: 'Lim', lang: 'en-US', preview_url: false },
            { name: 'Aurae', voice_id: 'Aurae', lang: 'en-US', preview_url: false },
            { name: 'Naia', voice_id: 'Naia', lang: 'en-US', preview_url: false },
            { name: 'Aulon', voice_id: 'Aulon', lang: 'en-US', preview_url: false },
            { name: 'Elei', voice_id: 'Elei', lang: 'en-US', preview_url: false },
            { name: 'Ogma', voice_id: 'Ogma', lang: 'en-US', preview_url: false },
            { name: 'Raid', voice_id: 'Raid', lang: 'en-US', preview_url: false },
            { name: 'Pega', voice_id: 'Pega', lang: 'en-US', preview_url: false },
            { name: 'Lam', voice_id: 'Lam', lang: 'en-US', preview_url: false },
        ];

        // Add in custom voices to the map
        let addVoices = this.settings.customVoices.map(voice =>
            ({ name: voice, voice_id: voice, lang: 'en-US', preview_url: false }),
        );
        voices = voices.concat(addVoices);

        return voices;
    }


    async previewTtsVoice(id) {
        this.audioElement.pause();
        this.audioElement.currentTime = 0;

        const text = getPreviewString('en-US');
        const response = await this.fetchTtsGeneration(text, id);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }

        const audio = await response.blob();
        const url = URL.createObjectURL(audio);
        this.audioElement.src = url;
        this.audioElement.play();
        this.audioElement.onended = () => URL.revokeObjectURL(url);
    }

    async* fetchTtsGeneration(inputText, voiceId) {
        const MAX_LENGTH = 1000;
        console.info(`Generating new TTS for voice_id ${voiceId}`);
        const chunks = splitRecursive(inputText, MAX_LENGTH);
        for (const chunk of chunks) {
            const response = await fetch('/api/novelai/generate-voice',
                {
                    method: 'POST',
                    headers: getRequestHeaders(),
                    body: JSON.stringify({
                        'text': chunk,
                        'voice': voiceId,
                    }),
                },
            );
            if (!response.ok) {
                toastr.error(response.statusText, 'TTS Generation Failed');
                throw new Error(`HTTP ${response.status}: ${await response.text()}`);
            }
            yield response;
        }
    }
}