import {TtsSession} from '@mintplex-labs/piper-tts-web'; import {trackModelDownload} from './piper-download-progress.mjs'; import {localPiperModelUrl} from './piper-model-routing.mjs'; import {createOnnxWasmPaths} from './piper-onnx-config.mjs'; const VOICE_ID = 'sv_SE-nst-medium'; const ASSET_ROOT = '/static/piper-wasm-v1'; const localFetch = self.fetch.bind(self); function reportStage(id, stage) { if (Number.isSafeInteger(id)) self.postMessage({id, type: 'progress', progress: {stage}}); } // Keep the TTS library's OPFS cache logic, but serve models/config from the // same-origin static asset service instead of its built-in external model URL. self.fetch = async (resource, options) => { const requestedUrl = resource instanceof Request ? resource.url : String(resource); const localModelUrl = localPiperModelUrl(requestedUrl, self.location.origin); if (!localModelUrl) { if (activeRequestId && requestedUrl.includes('/static/piper-wasm-v1/onnx/')) { reportStage(activeRequestId, 'loading-runtime-assets'); } return localFetch(resource, options); } const isModel = localModelUrl.endsWith('.onnx'); if (activeRequestId) reportStage(activeRequestId, isModel ? 'loading-model' : 'loading-model-info'); const redirected = resource instanceof Request ? new Request(localModelUrl, resource) : localModelUrl; const response = await localFetch(redirected, options); if (!activeRequestId || !isModel) return response; reportStage(activeRequestId, 'reading-model'); return trackModelDownload(response, { id: activeRequestId, postMessage: message => self.postMessage(message), }); }; let sessionPromise; let inferenceQueue = Promise.resolve(); let activeRequestId = null; async function getSession() { if (!sessionPromise) { sessionPromise = TtsSession.create({ voiceId: VOICE_ID, wasmPaths: { onnxWasm: createOnnxWasmPaths(self.location.origin), piperData: `${ASSET_ROOT}/piper/piper_phonemize.data`, piperWasm: `${ASSET_ROOT}/piper/piper_phonemize.wasm`, }, }).catch(error => { sessionPromise = null; throw error; }); } return sessionPromise; } async function synthesizeMessage(event) { const {id, text} = event.data || {}; if (!Number.isSafeInteger(id) || typeof text !== 'string') return; activeRequestId = id; reportStage(id, 'loading-runtime'); try { const session = await getSession(); reportStage(id, 'model-ready'); const blob = await session.predict(text); const audio = await blob.arrayBuffer(); self.postMessage({id, type: 'audio', audio}, [audio]); } catch (error) { self.postMessage({id, type: 'error', error: String(error?.message || error)}); } finally { activeRequestId = null; } } self.addEventListener('message', event => { inferenceQueue = inferenceQueue.then(() => synthesizeMessage(event)); });