| 12 | * first, if it has not yet been saved to opfs yet. |
| 13 | */ |
| 14 | export async function predict(config: InferenceConfg, callback?: ProgressCallback): Promise<Blob> { |
| 15 | module = module ?? (await import('./piper.js')); |
| 16 | ort = ort ?? (await import('onnxruntime-web')); |
| 17 | |
| 18 | const path = PATH_MAP[config.voiceId]; |
| 19 | const input = JSON.stringify([{ text: config.text.trim() }]); |
| 20 | |
| 21 | ort.env.allowLocalModels = false; |
| 22 | ort.env.wasm.numThreads = navigator.hardwareConcurrency; |
| 23 | ort.env.wasm.wasmPaths = ONNX_BASE; |
| 24 | |
| 25 | const modelConfigBlob = await getBlob(`${HF_BASE}/${path}.json`); |
| 26 | const modelConfig = JSON.parse(await modelConfigBlob.text()); |
| 27 | |
| 28 | const phonemeIds: string[] = await new Promise(async (resolve) => { |
| 29 | const phonemizer = await module.createPiperPhonemize({ |
| 30 | print: (data: any) => { |
| 31 | resolve(JSON.parse(data).phoneme_ids); |
| 32 | }, |
| 33 | printErr: (message: any) => { |
| 34 | throw new Error(message); |
| 35 | }, |
| 36 | locateFile: (url: string) => { |
| 37 | if (url.endsWith('.wasm')) return `${WASM_BASE}.wasm`; |
| 38 | if (url.endsWith('.data')) return `${WASM_BASE}.data`; |
| 39 | return url; |
| 40 | }, |
| 41 | }); |
| 42 | |
| 43 | phonemizer.callMain([ |
| 44 | '-l', |
| 45 | modelConfig.espeak.voice, |
| 46 | '--input', |
| 47 | input, |
| 48 | '--espeak_data', |
| 49 | '/espeak-ng-data', |
| 50 | ]); |
| 51 | }); |
| 52 | |
| 53 | const speakerId = 0; |
| 54 | const sampleRate = modelConfig.audio.sample_rate; |
| 55 | const noiseScale = modelConfig.inference.noise_scale; |
| 56 | const lengthScale = modelConfig.inference.length_scale; |
| 57 | const noiseW = modelConfig.inference.noise_w; |
| 58 | |
| 59 | const modelBlob = await getBlob(`${HF_BASE}/${path}`, callback); |
| 60 | const session = await ort.InferenceSession.create(await modelBlob.arrayBuffer()); |
| 61 | const feeds = { |
| 62 | input: new ort.Tensor('int64', phonemeIds, [1, phonemeIds.length]), |
| 63 | input_lengths: new ort.Tensor('int64', [phonemeIds.length]), |
| 64 | scales: new ort.Tensor('float32', [noiseScale, lengthScale, noiseW]), |
| 65 | }; |
| 66 | if (Object.keys(modelConfig.speaker_id_map).length) { |
| 67 | Object.assign(feeds, { sid: new ort.Tensor('int64', [speakerId]) }); |
| 68 | } |
| 69 | |
| 70 | const { |
| 71 | output: { data: pcm }, |