Spaces:
Running

tiny-voca-vi / worker.js
datmt24's picture
v0.2.2: foreign words with English readings, stress and rhythm
46f30da verified
Raw History Blame Contribute Delete
8.6 kB
// TinyVoca-Vi Web Worker: single-thread ORT-web WASM inference + Cache Storage + chunking.
const ORT_CDN = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.20.1/dist/";
importScripts(ORT_CDN + "ort.wasm.min.js", "./en_lexicon.js?v=0.2.2", "./g2p.js?v=0.2.2");
const MODEL_URL = "./assets/tiny-voca-vi-v0.2.2.onnx";
const HF_FALLBACK_MAP = {
"./assets/tiny-voca-vi-v0.2.2.onnx": "https://huggingface.co/datmt24/tiny-voca-vi/resolve/main/onnx/tiny-voca-vi-v0.2.2-hnvocos-fp16.onnx",
"./assets/tiny-voca-vi-v0.2.1.onnx": "https://huggingface.co/datmt24/tiny-voca-vi/resolve/main/onnx/tiny-voca-vi-v0.2.1-hnvocos-fp16.onnx",
"./assets/tiny-voca-vi-v0.2.onnx": "https://huggingface.co/datmt24/tiny-voca-vi/resolve/main/onnx/tiny-voca-vi-v0.2-hnvocos-fp16.onnx",
"./assets/tiny-voca-vi.onnx": "https://huggingface.co/datmt24/tiny-voca-vi/resolve/main/onnx/tiny-voca-vi-v0.1-1024-fp16.onnx",
"./assets/tiny-voca-vi-512.onnx": "https://huggingface.co/datmt24/tiny-voca-vi/resolve/main/onnx/tiny-voca-vi-v0.1-512-fp16.onnx",
};
const CACHE_NAME = "tiny-voca-vi-v0.2.1-p";
const SAMPLE_RATE = 24000;
let session = null;
let hasVoiceId = false;
let currentRunId = 0;
function postStatus(text, progress = null) {
postMessage({ type: "status", text, progress });
}
function isLocalHost() {
try {
const h = self.location.hostname;
return h === "localhost" || h === "127.0.0.1" || h.startsWith("192.168.") || h.startsWith("10.") || h.startsWith("100.");
} catch (_) {
return false;
}
}
async function fetchModelWithCache(url) {
const remoteUrl = HF_FALLBACK_MAP[url] || url;
const targetUrl = isLocalHost() ? url : remoteUrl;
let cache = null;
try {
if (typeof caches !== "undefined") {
cache = await caches.open(CACHE_NAME);
const hit = await cache.match(targetUrl);
if (hit) {
postStatus("Loading cached model...", 1.0);
return { bytes: new Uint8Array(await hit.arrayBuffer()), fromCache: true };
}
}
} catch (_) {
cache = null;
}
postStatus("Downloading model...", 0.0);
let resp = await fetch(targetUrl, targetUrl.startsWith("http") ? { credentials: "omit" } : undefined);
if (!resp.ok && targetUrl !== remoteUrl) {
postStatus("Fetching model from Hugging Face...", 0.0);
resp = await fetch(remoteUrl, { credentials: "omit" });
}
if (!resp.ok) throw new Error(`Failed to fetch ${targetUrl}: HTTP ${resp.status}`);
const total = Number(resp.headers.get("content-length")) || 0;
let bytes;
if (!resp.body || !total) {
bytes = new Uint8Array(await resp.arrayBuffer());
} else {
const reader = resp.body.getReader();
const parts = [];
let got = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
parts.push(value);
got += value.length;
postStatus(`Downloading model (${(got / 1e6).toFixed(1)} / ${(total / 1e6).toFixed(1)} MB)...`, got / total);
}
bytes = new Uint8Array(got);
let off = 0;
for (const p of parts) { bytes.set(p, off); off += p.length; }
}
if (cache) {
cache.put(targetUrl, new Response(bytes, { headers: { "content-type": "application/octet-stream" } })).catch(() => {});
}
return { bytes, fromCache: false };
}
function makeInt64(arr) {
return new ort.Tensor("int64", BigInt64Array.from(arr, (v) => BigInt(v)), [1, arr.length]);
}
function makeInt64Scalar1(v) {
return new ort.Tensor("int64", BigInt64Array.from([BigInt(v)]), [1]);
}
function makeFloat1(v) {
return new ort.Tensor("float32", Float32Array.from([v]), [1]);
}
async function runChunk(utt, { voiceId = 1, speed, pitchShift, pause, stress = 1 }) {
const t0 = performance.now();
const feeds = {
phoneme_ids: makeInt64(utt.phonemeIds),
tone_ids: makeInt64(utt.toneIds),
syl_pos: makeInt64(utt.sylPos),
speed: makeFloat1(speed),
pitch_shift: makeFloat1(pitchShift),
pause: makeFloat1(pause),
};
if (hasVoiceId) {
feeds.voice_id = makeInt64Scalar1(voiceId);
}
if (session.inputNames.includes("stress")) {
feeds.stress = new ort.Tensor("float32", Float32Array.from(TinyVocaG2P.stressFeatures(utt, stress)), [1, utt.phonemeIds.length, 3]);
}
const out = await session.run(feeds);
const inferMs = performance.now() - t0;
const audio = new Float32Array(out.audio.data);
// Soft peak limiter to prevent 16-bit/DAC clipping
let peak = 0;
for (let i = 0; i < audio.length; i++) {
const a = Math.abs(audio[i]);
if (a > peak) peak = a;
}
if (peak > 0.98) {
const g = 0.98 / peak;
for (let i = 0; i < audio.length; i++) audio[i] *= g;
}
return { audio, inferMs, durations: Array.from(out.durations.data, Number) };
}
async function initModel(modelUrl = MODEL_URL) {
const tStart = performance.now();
if (session) {
try { await session.release(); } catch (_) {}
session = null;
}
const tFetch0 = performance.now();
const { bytes, fromCache } = await fetchModelWithCache(modelUrl);
const fetchMs = performance.now() - tFetch0;
postStatus("Initializing WASM session (1 thread)...", 1.0);
ort.env.wasm.wasmPaths = ORT_CDN;
ort.env.wasm.numThreads = 1;
ort.env.wasm.simd = true;
const tSess = performance.now();
session = await ort.InferenceSession.create(bytes, {
executionProviders: ["wasm"],
graphOptimizationLevel: "basic",
});
hasVoiceId = Array.isArray(session.inputNames) && session.inputNames.includes("voice_id");
const sessMs = performance.now() - tSess;
postStatus("Warming up WASM JIT...", 1.0);
const tWarm = performance.now();
const warmUtt = TinyVocaG2P.phonemize("Xin chào.");
await runChunk(warmUtt, { voiceId: 1, speed: 1.0, pitchShift: 0.0, pause: 1.0 });
const warmMs = performance.now() - tWarm;
postMessage({
type: "ready",
modelUrl,
hasVoiceId,
sampleRate: SAMPLE_RATE,
modelBytes: bytes.byteLength,
fromCache,
loadMs: performance.now() - tStart,
fetchMs,
sessionMs: sessMs,
warmupMs: warmMs,
});
}
async function speak({ id, text, voiceId = 1, speed = 1.0, pitchShift = 0.0, pause = 1.0, stress = 1.0, shortFirst = true }) {
if (!session) throw new Error("Model not loaded yet");
currentRunId = id;
const tReq = performance.now();
const tG2p0 = performance.now();
const chunks = shortFirst
? TinyVocaG2P.chunkText(text)
: [TinyVocaG2P.normalizeText(text)];
const utts = chunks.map((c) => TinyVocaG2P.phonemize(c));
const g2pMs = performance.now() - tG2p0;
if (!utts.length) {
postMessage({ type: "done", id, totalMs: 0, g2pMs, totalInferMs: 0, totalAudioSec: 0 });
return;
}
let totalInferMs = 0;
let totalAudioSec = 0;
let ttfaMs = null;
for (let i = 0; i < utts.length; i++) {
if (currentRunId !== id) return; // cancelled
const utt = utts[i];
const { audio: speech, inferMs } = await runChunk(utt, { voiceId, speed, pitchShift, pause, stress });
if (currentRunId !== id) return;
// Gap after a sentence (chunks already end with ~100 ms of silence)
const gapSec = i + 1 < utts.length && /[.!?]$/.test(chunks[i]) ? 0.25 * pause / speed : 0;
const audio = new Float32Array(speech.length + Math.round(gapSec * SAMPLE_RATE));
audio.set(speech);
const audioSec = audio.length / SAMPLE_RATE;
totalInferMs += inferMs;
totalAudioSec += audioSec;
if (ttfaMs === null) ttfaMs = performance.now() - tReq;
postMessage(
{
type: "chunk",
id,
index: i,
total: utts.length,
chunkText: chunks[i],
normalizedText: utt.normalizedText,
symbols: utt.symbols,
toneIds: utt.toneIds,
audio,
sampleRate: SAMPLE_RATE,
inferMs,
audioSec,
rtf: (inferMs / 1000) / Math.max(audioSec, 1e-6),
ttfaMs,
g2pMs,
},
[audio.buffer]
);
}
postMessage({
type: "done",
id,
totalMs: performance.now() - tReq,
ttfaMs,
g2pMs,
totalInferMs,
totalAudioSec,
overallRtf: (totalInferMs / 1000) / Math.max(totalAudioSec, 1e-6),
});
}
onmessage = async ({ data }) => {
try {
if (data.type === "init") {
await initModel(data.modelUrl || MODEL_URL);
} else if (data.type === "speak") {
await speak(data);
} else if (data.type === "stop") {
currentRunId = -1;
} else if (data.type === "clearCache") {
if (typeof caches !== "undefined") await caches.delete(CACHE_NAME);
postMessage({ type: "cacheCleared" });
}
} catch (err) {
postMessage({ type: "error", id: data.id, message: String(err?.message || err) });
}
};