File size: 21,439 Bytes
19c8b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use strict"
const er = require('@electron/remote')
const dialog = er.dialog


window.voiceWorkbenchState = {
    isInit: false,
    isStarted: false,
    currentAudioFilePath: undefined,
    newAudioFilePath: undefined,
    currentEmb: undefined,
    refAEmb: undefined,
    refBEmb: undefined,
}

window.initVoiceWorkbench = () => {
    if (!window.voiceWorkbenchState.isInit) {
        window.voiceWorkbenchState.isInit = true
        window.refreshExistingCraftedVoices()
        window.initDropdowns()
        voiceWorkbenchLanguageDropdown.value = "en"
    }
    window.refreshExistingCraftedVoices()
}

window.refreshExistingCraftedVoices = () => {
    voiceWorkbenchVoicesList.innerHTML = ""
    Object.keys(window.games).sort((a,b)=>a>b?1:-1).forEach(gameId => {
        if (Object.keys(window.gameAssets).includes(gameId)) {
            const themeColour = window.gameAssets[gameId].themeColourPrimary
            window.games[gameId].models.forEach(model => {
                if (model.embOverABaseModel) {
                    const button = createElem("div.voiceType", model.voiceName)
                    button.style.background = `#${themeColour}`
                    button.addEventListener("click", () => window.voiceWorkbenchLoadOrResetCraftedVoice(model))
                    voiceWorkbenchVoicesList.appendChild(button)
                }
            })
        }
    })
}

window.voiceWorkbenchLoadOrResetCraftedVoice = (model) => {

    voiceWorkbenchModelDropdown.value = model ? model.embOverABaseModel : "<base>/base_v1.0"
    voiceWorkbenchVoiceNameInput.value = model ? model.voiceName : ""
    voiceWorkbenchVoiceIDInput.value = model ? model.variants[0].voiceId : ""
    voiceWorkbenchGenderDropdown.value = model ? model.variants[0].gender : "male"
    voiceWorkbenchAuthorInput.value = model ? (model.variants[0].author || "Anonymous") : ""
    voiceWorkbenchLanguageDropdown.value = model ? model.variants[0].lang : "en"
    voiceWorkbenchGamesDropdown.value = model ? model.gameId : "other"
    voiceWorkbenchCurrentEmbeddingInput.value = model ? model.variants[0].base_speaker_emb : ""
    window.voiceWorkbenchState.currentEmb = model ? model.variants[0].base_speaker_emb : undefined

    window.voiceWorkbenchState.currentAudioFilePath = undefined
    window.voiceWorkbenchState.newAudioFilePath = undefined
    window.voiceWorkbenchState.refAEmb = undefined
    window.voiceWorkbenchState.refBEmb = undefined

    voiceWorkbenchRefAInput.value = ""
    voiceWorkbenchRefBInput.value = ""

    if (model) {
        voiceWorkbenchDeleteButton.disabled = false
        voiceWorkbenchStartButton.click()
    }
}

window.voiceWorkbenchGenerateVoice = async () => {

    if (!voiceWorkbenchCurrentEmbeddingInput.value.length) {
        return window.errorModal(window.i18n.ENTER_VOICE_CRAFTING_STARTING_EMB)
    }

    // Load the model if it hasn't been loaded already
    let voiceId = voiceWorkbenchModelDropdown.value.split("/").at(-1)
    if (!window.currentModel || window.currentModel.voiceId!=voiceId) {
        let modelPath
        if (voiceId.includes("Base xVAPitch Model")) {
            modelPath = `${window.path}/python/xvapitch/base_v1.0.pt`
        } else {
            const gameId = voiceWorkbenchModelDropdown.value.split("/").at(0)
            modelPath = window.userSettings[`modelspath_${gameId}`]+"/"+voiceId
        }
        await window.voiceWorkbenchChangeModel(modelPath, voiceId)
    }

    const base_lang = voiceWorkbenchLanguageDropdown.value//voiceId.includes("Base xVAPitch Model") ? "en" : window.currentModel.lang
    let newEmb = undefined

    // const currentEmbedding = voiceWorkbenchCurrentEmbeddingInput.value.split(",").map(v=>parseFloat(v))
    const currentEmbedding = window.voiceWorkbenchState.currentEmb
    // const currentDelta = voiceWorkbenchCurrentDeltaInput.value.split(",").map(v=>parseFloat(v))
    const newEmbedding = window.getVoiceWorkbenchNewEmbedding()

    const tempFileNum = `${Math.random().toString().split(".")[1]}`
    const currentTempFileLocation = `${path}/output/temp-${tempFileNum}_current.wav`
    const newTempFileLocation = `${path}/output/temp-${tempFileNum}_new.wav`

    // Do the current embedding first
    const synthRequests = []
    synthRequests.push(doSynth(JSON.stringify({
            sequence: voiceWorkbenchInputTextArea.value.trim(),
            useCleanup: true, // TODO, user setting?
            base_lang, base_emb: currentEmbedding.join(","), outfile: currentTempFileLocation
        })))
    let doingNewAudioFile = false
    if (voiceWorkbenchCurrentDeltaInput.value.length) {
        doingNewAudioFile = true
        synthRequests.push(doSynth(JSON.stringify({
            sequence: voiceWorkbenchInputTextArea.value.trim(),
            useCleanup: true, // TODO, user setting?
            base_lang, base_emb: newEmbedding.join(","), outfile: newTempFileLocation
        })))
    }

    // toggleSpinnerButtons()
    spinnerModal(`${window.i18n.SYNTHESIZING}`)
    Promise.all(synthRequests).then(res => {
        closeModal(undefined, [workbenchContainer])
        window.voiceWorkbenchState.currentAudioFilePath = currentTempFileLocation
        voiceWorkbenchAudioCurrentPlayPauseBtn.disabled = false
        voiceWorkbenchAudioCurrentSaveBtn.disabled = false

        if (doingNewAudioFile) {
            window.voiceWorkbenchState.newAudioFilePath = newTempFileLocation
            voiceWorkbenchAudioNewPlayBtn.disabled = false
            voiceWorkbenchAudioNewSaveBtn.disabled = false
        }
    })
}
const doSynth = (body) => {
    return new Promise(resolve => {
        doFetch("http://localhost:8008/synthesizeSimple", {
            method: "Post",
            body
        }).then(r=>r.text()).then(resolve)
    })
}

window.getVoiceWorkbenchNewEmbedding = () => {
    const currentDelta = voiceWorkbenchCurrentDeltaInput.value.split(",").map(v=>parseFloat(v))
    const newEmb = window.voiceWorkbenchState.currentEmb.map((v,vi) => {
        return v + currentDelta[vi]//*strength
    })
    return newEmb
}

window.voiceWorkbenchChangeModel = (modelPath, voiceId) => {
    window.currentModel = {
        outputs: undefined,
        model: modelPath.replace(".pt", ""),
        modelType: "xVAPitch",
        base_lang: voiceWorkbenchLanguageDropdown.value,
        isBaseModel: true,
        voiceId: voiceId
    }
    generateVoiceButton.dataset.modelQuery = JSON.stringify(window.currentModel)
    return window.loadModel()
}
voiceWorkbenchGenerateSampleButton.addEventListener("click", window.voiceWorkbenchGenerateVoice)


window.initDropdowns = () => {
    // Games dropdown
    Object.keys(window.games).sort((a,b)=>a>b?1:-1).forEach(gameId => {
        if (gameId!="other") {
            if (Object.keys(window.gameAssets).includes(gameId)) {
                const gameName = window.games[gameId].gameTheme.gameName
                const option = createElem("option", gameName)
                option.value = gameId
                voiceWorkbenchGamesDropdown.appendChild(option)
            }
        }
    })

    // Models dropdown
    Object.keys(window.games).forEach(gameId => {
        if (window.games[gameId].gameTheme) {
            const gameName = window.games[gameId].gameTheme.gameName
            window.games[gameId].models.forEach(modelMeta => {
                const voiceName = modelMeta.voiceName
                const voiceId = modelMeta.variants[0].voiceId

                // Variants are not supported by v3 models, so pick the first one only. Also, filter out crafted voices
                if (modelMeta.variants[0].modelType=="xVAPitch" && !modelMeta.embOverABaseModel) {

                    const option = createElem("option", `[${gameName}] ${voiceName}`)
                    option.value = `${gameId}/${voiceId}`
                    voiceWorkbenchModelDropdown.appendChild(option)
                }
            })
        }
    })
}

// Change the available languages when the model is changed
voiceWorkbenchModelDropdown.addEventListener("change", () => {
    let voiceId = voiceWorkbenchModelDropdown.value.split("/").at(-1)
    if (voiceId.includes("base_v1.0")) {
        window.populateLanguagesDropdownsFromModel(voiceWorkbenchLanguageDropdown)
        voiceWorkbenchLanguageDropdown.value = "en"
    } else {
        const gameId = voiceWorkbenchModelDropdown.value.split("/")[0]
        if (Object.keys(window.games).includes(gameId)) {
            const baseModelData = window.games[gameId].models.filter(model => {
                return model.variants[0].voiceId == voiceWorkbenchModelDropdown.value.split("/").at(-1)
            })[0]
            window.populateLanguagesDropdownsFromModel(voiceWorkbenchLanguageDropdown, baseModelData)
            voiceWorkbenchLanguageDropdown.value = baseModelData.variants[0].lang
        }
    }
})

voiceWorkbenchStartButton.addEventListener("click", () => {
    window.voiceWorkbenchState.isStarted = true

    voiceWorkbenchLoadedContent.style.display = "flex"
    voiceWorkbenchLoadedContent2.style.display = "flex"
    voiceWorkbenchStartButton.style.display = "none"


    // Load the base model's embedding as a starting point, if it's not the built-in base model
    let voiceId = voiceWorkbenchModelDropdown.value.split("/").at(-1)
    if (voiceId.includes("base_v1.0")) {
    } else {
        const gameId = voiceWorkbenchModelDropdown.value.split("/")[0]
        if (Object.keys(window.games).includes(gameId)) {
            const baseModelData = window.games[gameId].models.filter(model => {
                return model.variants[0].voiceId == voiceWorkbenchModelDropdown.value.split("/").at(-1)
            })[0]
            voiceWorkbenchCurrentEmbeddingInput.value = baseModelData.variants[0].base_speaker_emb.join(",")
            window.voiceWorkbenchState.currentEmb = baseModelData.variants[0].base_speaker_emb
        }
    }
})

window.setupVoiceWorkbenchDropArea = (container, inputField, callback=undefined) => {
    const dropFn = (eType, event) => {
        if (["dragenter", "dragover"].includes(eType)) {
            container.style.background = "#5b5b5b"
            container.style.color = "white"
        }
        if (["dragleave", "drop"].includes(eType)) {
            container.style.background = "rgba(0,0,0,0)"
            container.style.color = "white"
        }

        event.preventDefault()
        event.stopPropagation()

        const dataLines = []

        if (eType=="drop") {
            const dataTransfer = event.dataTransfer
            const files = Array.from(dataTransfer.files)

            if (files[0].path.endsWith(".wav")) {
                const filePath = String(files[0].path).replaceAll(/\\/g, "/")
                console.log("filePath", filePath)
                window.getSpeakerEmbeddingFromFilePath(filePath).then(embedding => {
                    inputField.value = embedding
                    if (callback) {
                        callback(filePath)
                    }
                })
            } else {
                window.errorModal(window.i18n.ERROR_FILE_MUST_BE_WAV)
            }
        }
    }

    container.addEventListener("dragenter", event => dropFn("dragenter", event), false)
    container.addEventListener("dragleave", event => dropFn("dragleave", event), false)
    container.addEventListener("dragover", event => dropFn("dragover", event), false)
    container.addEventListener("drop", event => dropFn("drop", event), false)
}

window.setupVoiceWorkbenchDropArea(voiceWorkbenchCurrentEmbeddingDropzone, voiceWorkbenchCurrentEmbeddingInput, () => {
    window.voiceWorkbenchState.currentEmb = voiceWorkbenchCurrentEmbeddingInput.value.split(",").map(v=>parseFloat(v))
})
voiceWorkbenchCurrentEmbeddingInput.addEventListener("change", ()=>{
    window.voiceWorkbenchState.currentEmb = voiceWorkbenchCurrentEmbeddingInput.value.split(",").map(v=>parseFloat(v))
})
window.setupVoiceWorkbenchDropArea(voiceWorkbenchRefADropzone, voiceWorkbenchRefAInput, (filePath) => {
    voiceWorkbenchRefAFilePath.innerHTML = window.i18n.FROM_FILE_IS_FILEPATH.replace("_1", filePath)
    voiceWorkshopApplyDeltaButton.disabled = false
    window.voiceWorkbenchState.refAEmb = voiceWorkbenchRefAInput.value.split(",").map(v=>parseFloat(v))
    window.voiceWorkbenchUpdateDelta()
})
window.setupVoiceWorkbenchDropArea(voiceWorkbenchRefBDropzone, voiceWorkbenchRefBInput, (filePath) => {
    voiceWorkbenchRefBFilePath.innerHTML = window.i18n.FROM_FILE_IS_FILEPATH.replace("_1", filePath)
    window.voiceWorkbenchState.refBEmb = voiceWorkbenchRefBInput.value.split(",").map(v=>parseFloat(v))
    window.voiceWorkbenchUpdateDelta()
})

voiceWorkbenchInputTextArea.addEventListener("keyup", () => {
    voiceWorkbenchGenerateSampleButton.disabled = voiceWorkbenchInputTextArea.value.trim().length==0
})
voiceWorkbenchAudioCurrentPlayPauseBtn.addEventListener("click", () => {
    const audioPreview = createElem("audio", {autoplay: false}, createElem("source", {
        src: window.voiceWorkbenchState.currentAudioFilePath
    }))
    audioPreview.setSinkId(window.userSettings.base_speaker)
})
voiceWorkbenchAudioCurrentSaveBtn.addEventListener("click", async () => {
    const userChosenPath = await dialog.showSaveDialog({ defaultPath: window.voiceWorkbenchState.currentAudioFilePath })
    if (userChosenPath && userChosenPath.filePath) {
        const outFilePath = userChosenPath.filePath.split(".").at(-1)=="wav" ? userChosenPath.filePath : userChosenPath.filePath+".wav"
        fs.copyFileSync(window.voiceWorkbenchState.currentAudioFilePath, outFilePath)
    }
})
voiceWorkbenchAudioNewPlayBtn.addEventListener("click", () => {
    const audioPreview = createElem("audio", {autoplay: false}, createElem("source", {
        src: window.voiceWorkbenchState.newAudioFilePath
    }))
    audioPreview.setSinkId(window.userSettings.base_speaker)
})
voiceWorkbenchAudioNewSaveBtn.addEventListener("click", async () => {
    const userChosenPath = await dialog.showSaveDialog({ defaultPath: window.voiceWorkbenchState.newAudioFilePath })
    if (userChosenPath && userChosenPath.filePath) {
        const outFilePath = userChosenPath.filePath.split(".").at(-1)=="wav" ? userChosenPath.filePath : userChosenPath.filePath+".wav"
        fs.copyFileSync(window.voiceWorkbenchState.newAudioFilePath, outFilePath)
    }
})

window.voiceWorkbenchUpdateDelta = () => {
    // Don't do anything if reference file A isn't given
    if (!window.voiceWorkbenchState.refAEmb) {
        return
    }

    const strengthValue = parseFloat(voiceWorkbenchStrengthInput.value)

    let delta

    // When only Ref A is used, the delta is from <current> towards the first reference file A
    if (window.voiceWorkbenchState.refBEmb == undefined) {
        delta = window.voiceWorkbenchState.currentEmb.map((v,vi) => {
            return (window.voiceWorkbenchState.refAEmb[vi] - v) * strengthValue
        })
    } else {
        // When Ref B is also used, the delta is from ref A to ref B
        delta = window.voiceWorkbenchState.refAEmb.map((v,vi) => {
            return (window.voiceWorkbenchState.refBEmb[vi] - v) * strengthValue
        })
    }

    voiceWorkbenchCurrentDeltaInput.value = delta.join(",")
}

voiceWorkbenchStrengthSlider.addEventListener("change", () => {
    voiceWorkbenchStrengthInput.value = voiceWorkbenchStrengthSlider.value
    window.voiceWorkbenchUpdateDelta()
})
voiceWorkbenchStrengthInput.addEventListener("change", () => {
    voiceWorkbenchStrengthSlider.value = voiceWorkbenchStrengthInput.value
    window.voiceWorkbenchUpdateDelta()
})
voiceWorkshopApplyDeltaButton.addEventListener("click", () => {
    if (voiceWorkbenchCurrentDeltaInput.value.length) {
        const newEmb = window.getVoiceWorkbenchNewEmbedding()
        window.voiceWorkbenchState.currentEmb = newEmb
        voiceWorkbenchCurrentEmbeddingInput.value = newEmb.join(",")
        voiceWorkbenchCurrentDeltaInput.value = ""
        voiceWorkshopApplyDeltaButton.disabled = true
        voiceWorkbenchRefAInput.value = ""
        window.voiceWorkbenchState.refAEmb = undefined
        voiceWorkbenchRefBInput.value = ""
        window.voiceWorkbenchState.refBEmb = undefined
    }
})

/*
Drop file A over the reference audio file A area, to get its embedding
    When only the reference A file is used, the current delta is this embedding multiplied by the strength

Drop file B over the B area, to get a second embedding
    When both this and A are active, the current delta is the direction from A to B, multiplied by the strength
        direction meaning B minus A, instead of <current> minus A
*/

voiceWorkbenchSaveButton.addEventListener("click", () => {

    const voiceName = voiceWorkbenchVoiceNameInput.value
    const voiceId = voiceWorkbenchVoiceIDInput.value
    const gender = voiceWorkbenchGenderDropdown.value
    const author = voiceWorkbenchAuthorInput.value || "Anonymous"
    const lang = voiceWorkbenchLanguageDropdown.value


    if (!voiceName.trim().length) {
        return window.errorModal(window.i18n.ENTER_VOICE_NAME)
    }
    if (!voiceId.trim().length) {
        return window.errorModal(window.i18n.ENTER_VOICE_ID)
    }

    const modelJson = {
        "version": "3.0",
        "modelVersion": "3.0",
        "modelType": "xVAPitch",
        "author": author,
        "lang": lang,
        "embOverABaseModel": voiceWorkbenchModelDropdown.value,
        "games": [
            {
                "gameId": voiceWorkbenchGamesDropdown.value,
                "voiceId": voiceId,
                "variant": "Default",
                "voiceName": voiceName,
                "base_speaker_emb": window.voiceWorkbenchState.currentEmb,
                "gender": gender
            }
        ]
    }
    const gameModelsPath = `${window.userSettings[`modelspath_${voiceWorkbenchGamesDropdown.value}`]}`

    const jsonDestination = `${gameModelsPath}/${voiceId}.json`
    fs.writeFileSync(jsonDestination, JSON.stringify(modelJson, null, 4))

    doSynth(JSON.stringify({
        sequence: " This is what my voice sounds like. ",
        useCleanup: true, // TODO, user setting?
        base_lang: lang,
        base_emb: window.voiceWorkbenchState.currentEmb.join(","), outfile: jsonDestination.replace(".json", ".wav")
    })).then(() => {
        voiceWorkbenchDeleteButton.disabled = false
        window.currentModel = undefined
        generateVoiceButton.dataset.modelQuery = null
        window.infoModal(window.i18n.VOICE_CREATED_AT.replace("_1", jsonDestination))

        // Clean up the temp file from the clean-up post-processing, if it exists
        if (fs.existsSync(jsonDestination.replace(".json", "_preCleanup.wav"))) {
            fs.unlinkSync(jsonDestination.replace(".json", "_preCleanup.wav"))
        }

        window.loadAllModels().then(() => {
            window.refreshExistingCraftedVoices()

            // Refresh the main page voice models if the same game is loaded as the target game models directory as saved into
            if (window.currentGame.gameId==voiceWorkbenchGamesDropdown.value) {
                window.changeGame(window.currentGame)
                window.refreshExistingCraftedVoices()
            }
        })
    })
})

voiceWorkbenchGamesDropdown.addEventListener("change", () => {
    const gameModelsPath = `${window.userSettings[`modelspath_${voiceWorkbenchGamesDropdown.value}`]}`
    const voiceId = voiceWorkbenchVoiceIDInput.value
    const jsonLocation = `${gameModelsPath}/${voiceId}.json`
    voiceWorkbenchDeleteButton.disabled = !fs.existsSync(jsonLocation)
})
voiceWorkbenchVoiceIDInput.addEventListener("change", () => {
    const gameModelsPath = `${window.userSettings[`modelspath_${voiceWorkbenchGamesDropdown.value}`]}`
    const voiceId = voiceWorkbenchVoiceIDInput.value
    const jsonLocation = `${gameModelsPath}/${voiceId}.json`
    voiceWorkbenchDeleteButton.disabled = !fs.existsSync(jsonLocation)
})
voiceWorkbenchDeleteButton.addEventListener("click", () => {
    const gameModelsPath = `${window.userSettings[`modelspath_${voiceWorkbenchGamesDropdown.value}`]}`
    const voiceId = voiceWorkbenchVoiceIDInput.value
    const jsonLocation = `${gameModelsPath}/${voiceId}.json`
    window.confirmModal(window.i18n.CONFIRM_DELETE_CRAFTED_VOICE.replace("_1", voiceWorkbenchVoiceNameInput.value).replace("_2", jsonLocation)).then(resp => {
        if (resp) {
            if (fs.existsSync(jsonLocation.replace(".json", ".wav"))) {
                fs.unlinkSync(jsonLocation.replace(".json", ".wav"))
            }
            fs.unlinkSync(jsonLocation)
        }
        window.infoModal(window.i18n.SUCCESSFULLY_DELETED_CRAFTED_VOICE)
        window.loadAllModels().then(() => {

            // Refresh the main page voice models if the same game is loaded as the target game models directory deleted from
            if (window.currentGame.gameId==voiceWorkbenchGamesDropdown.value) {

                window.changeGame(window.currentGame)
                window.refreshExistingCraftedVoices()
            }
            voiceWorkbenchCancelButton.click()
        })
    })
})



voiceWorkbenchCancelButton.addEventListener("click", () => {
    window.voiceWorkbenchState.isStarted = false

    voiceWorkbenchLoadedContent.style.display = "none"
    voiceWorkbenchLoadedContent2.style.display = "none"
    voiceWorkbenchStartButton.style.display = "flex"

    window.voiceWorkbenchLoadOrResetCraftedVoice()
})