Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 14,360 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 |
"use strict"
window.speech2speechState = {
isReadingMic: false,
elapsedRecording: 0,
s2s_running: false
}
// Populate the microphone dropdown with the available options
navigator.mediaDevices.enumerateDevices().then(devices => {
devices = devices.filter(device => device.kind=="audioinput" && device.deviceId!="default" && device.deviceId!="communications")
devices.forEach(device => {
const option = createElem("option", device.label)
option.value = device.deviceId
setting_mic_selection.appendChild(option)
})
setting_mic_selection.addEventListener("change", () => {
window.userSettings.microphone = setting_mic_selection.value
window.saveUserSettings()
window.initMic()
})
if (Object.keys(window.userSettings).includes("microphone")) {
setting_mic_selection.value = window.userSettings.microphone
} else {
window.userSettings.microphone = setting_mic_selection.value
window.saveUserSettings()
}
})
window.initMic = () => {
return new Promise(resolve => {
const deviceId = window.userSettings.microphone
navigator.mediaDevices.getUserMedia({audio: {deviceId: deviceId}}).then(stream => {
const audio_context = new AudioContext
const input = audio_context.createMediaStreamSource(stream)
window.speech2speechState.stream = stream
resolve()
}).catch(err => {
console.log(err)
resolve()
})
})
}
window.initMic()
const animateRecordingProgress = () => {
const percentDone = (Date.now() - window.speech2speechState.elapsedRecording) / 10000
if (percentDone >= 1 && percentDone!=Infinity) {
if (window.speech2speechState.isReadingMic) {
window.stopRecord()
}
} else {
const circle = mic_progress_SVG_circle
const radius = circle.r.baseVal.value
const circumference = radius * 2 * Math.PI
const offset = circumference - percentDone * circumference
circle.style.strokeDasharray = `${circumference} ${circumference}`
circle.style.strokeDashoffset = circumference
circle.style.strokeDashoffset = Math.round(offset)
requestAnimationFrame(animateRecordingProgress)
}
}
window.clearVCMicSpinnerProgress = (percent=0) => {
const circle = mic_progress_SVG_circle
circle.style.stroke = "transparent"
const radius = circle.r.baseVal.value
const circumference = radius * 2 * Math.PI
const offset = circumference - percent * circumference
circle.style.strokeDasharray = `${circumference} ${circumference}`
circle.style.strokeDashoffset = circumference
circle.style.strokeDashoffset = Math.floor(offset)
}
window.clearVCMicSpinnerProgress = clearVCMicSpinnerProgress
window.startRecord = async () => {
doFetch(`http://localhost:8008/start_microphone_recording`, {
method: "Post"
})
window.speech2speechState.isReadingMic = true
window.speech2speechState.elapsedRecording = Date.now()
window.clearVCMicSpinnerProgress()
mic_progress_SVG_circle.style.stroke = "red"
requestAnimationFrame(animateRecordingProgress)
}
window.outputS2SRecording = (outPath, callback) => {
toggleSpinnerButtons()
doFetch(`http://localhost:8008/move_recorded_file`, {
method: "Post",
body: JSON.stringify({
file_path: outPath
})
}).then(r=>r.text()).then(res => {
callback()
})
}
window.useWavFileForspeech2speech = (fileName) => {
// let sequence = dialogueInput.value.trim().replace("β¦", "...")
// For some reason, the samplePlay audio element does not update the source when the file name is the same
const tempFileNum = `${Math.random().toString().split(".")[1]}`
let tempFileLocation = `${path}/output/temp-${tempFileNum}.wav`
let style_emb = window.currentModel.audioPreviewPath // Default to the preview audio file, if an embedding can't be found in the json - This shouldn't happen
try {
style_emb = window.currentModel.games[0].base_speaker_emb // If this fails, the json isn't complete
} catch (e) {
console.log(e)
}
if (window.wavesurfer) {
window.wavesurfer.stop()
wavesurferContainer.style.opacity = 0
}
window.tempFileLocation = `${__dirname.replace("/javascript", "").replace("\\javascript", "")}/output/temp-${tempFileNum}.wav`
const options = {
hz: window.userSettings.audio.hz,
padStart: window.userSettings.audio.padStart,
padEnd: window.userSettings.audio.padEnd,
bit_depth: window.userSettings.audio.bitdepth,
amplitude: window.userSettings.audio.amplitude,
pitchMult: window.userSettings.audio.pitchMult,
tempo: window.userSettings.audio.tempo,
deessing: window.userSettings.audio.deessing,
nr: window.userSettings.audio.nr,
nf: window.userSettings.audio.nf,
useNR: window.userSettings.audio.useNR,
useSR: useSRCkbx.checked,
useCleanup: useCleanupCkbx.checked
}
doFetch(`http://localhost:8008/runSpeechToSpeech`, {
method: "Post",
body: JSON.stringify({
input_path: fileName,
useSR: useSRCkbx.checked,
useCleanup: useCleanupCkbx.checked,
isBatchMode: false,
style_emb: style_emb_select.value=="default" ? window.currentModel.games[0].base_speaker_emb : style_emb_select.value.split(",").map(v=>parseFloat(v)),
audio_out_path: tempFileLocation,
doPitchShift: window.userSettings.s2s_prePitchShift,
removeNoise: window.userSettings.s2s_removeNoise, // Removed from UI
removeNoiseStrength: window.userSettings.s2s_noiseRemStrength, // Removed from UI
vc_strength: window.userSettings.vc_strength,
n_speakers: undefined,
modelPath: undefined,
voiceId: undefined,
options: JSON.stringify(options)
})
}).then(r=>r.text()).then(res => {
// This block of code sometimes gets called before the audio file has actually finished flushing to file
// I need a better way to make sure that this doesn't get called until it IS finished, but "for now",
// I've set up some recursive re-attempts, below doTheRest
window.clearVCMicSpinnerProgress()
mic_progress_SVG.style.animation = "none"
if (res=="TOO_SHORT") {
window.toggleSpinnerButtons(true)
window.errorModal(`<h3>${window.i18n.VC_TOO_SHORT}</h3>`)
return
}
generateVoiceButton.disabled = true
let hasLoaded = false
let numRetries = 0
window.toggleSpinnerButtons(true)
const doTheRest = () => {
if (hasLoaded) {
return
}
// window.wavesurfer = undefined
tempFileLocation = tempFileLocation.replaceAll(/\\/g, "/")
tempFileLocation = tempFileLocation.replaceAll('/resources/app/resources/app', "/resources/app")
tempFileLocation = tempFileLocation.replaceAll('/resources/app', "")
dialogueInput.value = ""
textEditorElem.innerHTML = ""
window.isGenerating = false
window.speech2speechState.s2s_running = true
if (res.includes("Traceback")) {
window.errorModal(`<h3>${window.i18n.SOMETHING_WENT_WRONG}</h3>${res.replaceAll("\n", "<br>")}`)
} else if (res.includes("ERROR:APP_VERSION")) {
const speech2speechModelVersion = "v"+res.split(",")[1]
window.errorModal(`${window.i18n.ERR_XVASPEECH_MODEL_VERSION.replace("_1", speech2speechModelVersion)} ${window.appVersion}`)
} else {
keepSampleButton.disabled = false
window.tempFileLocation = tempFileLocation
// Wavesurfer
if (!window.wavesurfer) {
window.initWaveSurfer(window.tempFileLocation)
} else {
window.wavesurfer.load(window.tempFileLocation)
}
window.wavesurfer.on("ready", () => {
hasLoaded = true
wavesurferContainer.style.opacity = 1
if (window.userSettings.autoPlayGen) {
if (window.userSettings.playChangedAudio) {
const playbackStartEnd = window.sequenceEditor.getChangedTimeStamps(start_index, end_index, window.wavesurfer.getDuration())
if (playbackStartEnd) {
wavesurfer.play(playbackStartEnd[0], playbackStartEnd[1])
} else {
wavesurfer.play()
}
} else {
wavesurfer.play()
}
window.sequenceEditor.adjustedLetters = new Set()
samplePlayPause.innerHTML = window.i18n.PAUSE
}
})
// Persistance across sessions
localStorage.setItem("tempFileLocation", tempFileLocation)
generateVoiceButton.innerHTML = window.i18n.GENERATE_VOICE
if (window.userSettings.s2s_autogenerate) {
speech2speechState.s2s_autogenerate = true
generateVoiceButton.click()
}
keepSampleButton.dataset.newFileLocation = `${window.userSettings[`outpath_${window.currentGame.gameId}`]}/${title.dataset.modelId}/vc_${tempFileNum}.wav`
keepSampleButton.disabled = false
keepSampleButton.style.display = "block"
samplePlayPause.style.display = "block"
setTimeout(doTheRest, 100)
}
}
doTheRest()
}).catch(e => {
console.log(e)
window.toggleSpinnerButtons(true)
window.errorModal(`<h3>${window.i18n.SOMETHING_WENT_WRONG}</h3>`)
mic_progress_SVG.style.animation = "none"
})
}
window.stopRecord = (cancelled) => {
fs.writeFileSync(`${window.path}/python/temp_stop_recording`, "")
if (!cancelled) {
window.clearVCMicSpinnerProgress(0.35)
mic_progress_SVG.style.animation = "spin 1.5s linear infinite"
mic_progress_SVG_circle.style.stroke = "white"
const fileName = `${__dirname.replace("\\javascript", "").replace("/javascript", "").replace(/\\/g,"/")}/output/recorded_file.wav`
window.sequenceEditor.clear()
window.outputS2SRecording(fileName, () => {
window.useWavFileForspeech2speech(fileName)
})
}
window.speech2speechState.isReadingMic = false
window.speech2speechState.elapsedRecording = 0
window.clearVCMicSpinnerProgress()
}
window.micClickHandler = (ctrlKey) => {
if (window.speech2speechState.isReadingMic) {
window.stopRecord()
} else {
if (window.currentModel && generateVoiceButton.innerHTML == window.i18n.GENERATE_VOICE) {
if (window.currentModel.modelType.toLowerCase()=="xvapitch") {
window.startRecord()
}
} else {
window.errorModal(window.i18n.LOAD_TARGET_MODEL)
}
}
}
mic_SVG.addEventListener("mouseenter", () => {
if (!window.currentModel || window.currentModel.modelType.toLowerCase()!="xvapitch") {
s2s_voiceId_selected_label.style.display = "inline-block"
}
})
mic_SVG.addEventListener("mouseleave", () => {
s2s_voiceId_selected_label.style.display = "none"
})
mic_SVG.addEventListener("click", event => window.micClickHandler(event.ctrlKey))
mic_SVG.addEventListener("contextmenu", () => {
if (window.speech2speechState.isReadingMic) {
window.stopRecord(true)
} else {
const audioPreview = createElem("audio", {autoplay: false}, createElem("source", {
src: `${__dirname.replace("\\javascript", "").replace("/javascript", "").replace(/\\/g,"/")}/output/recorded_file_post${window.userSettings.s2s_prePitchShift?"_praat":""}.wav`
}))
audioPreview.setSinkId(window.userSettings.base_speaker)
}
})
window.clearVCMicSpinnerProgress()
// File dragging
window.uploadS2SFile = (eType, event) => {
if (["dragenter", "dragover"].includes(eType)) {
clearVCMicSpinnerProgress(1)
mic_progress_SVG_circle.style.stroke = "white"
}
if (["dragleave", "drop"].includes(eType)) {
window.clearVCMicSpinnerProgress()
}
event.preventDefault()
event.stopPropagation()
if (eType=="drop") {
if (window.currentModel && generateVoiceButton.innerHTML == window.i18n.GENERATE_VOICE) {
const dataTransfer = event.dataTransfer
const files = Array.from(dataTransfer.files)
const file = files[0]
if (!file.name.endsWith(".wav")) {
window.errorModal(window.i18n.ONLY_WAV_S2S)
return
}
clearVCMicSpinnerProgress(0.35)
// mic_progress_SVG.style.animation = "spin 1.5s linear infinite"
// mic_progress_SVG_circle.style.stroke = "white"
const fileName = `${__dirname.replace("\\javascript", "").replace("/javascript", "").replace(/\\/g,"/")}/output/recorded_file.wav`
fs.copyFileSync(file.path, fileName)
window.sequenceEditor.clear()
toggleSpinnerButtons()
window.useWavFileForspeech2speech(fileName)
} else {
window.errorModal(window.i18n.LOAD_TARGET_MODEL)
}
}
}
micContainer.addEventListener("dragenter", event => window.uploadS2SFile("dragenter", event), false)
micContainer.addEventListener("dragleave", event => window.uploadS2SFile("dragleave", event), false)
micContainer.addEventListener("dragover", event => window.uploadS2SFile("dragover", event), false)
micContainer.addEventListener("drop", event => window.uploadS2SFile("drop", event), false)
// Disable page navigation on badly dropped file
window.document.addEventListener("dragover", event => event.preventDefault(), false)
window.document.addEventListener("drop", event => event.preventDefault(), false) |