Spaces:
Running

File size: 8,598 Bytes
48842af
 
46f30da
48842af
46f30da
48842af
46f30da
31cfba2
adb961d
48842af
 
 
31cfba2
48842af
 
 
adb961d
48842af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adb961d
 
 
48842af
 
 
 
46f30da
48842af
adb961d
48842af
 
 
 
 
 
adb961d
 
 
 
46f30da
 
 
adb961d
48842af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adb961d
48842af
 
 
 
 
adb961d
48842af
 
 
 
 
adb961d
48842af
 
 
 
 
 
 
 
 
 
46f30da
48842af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46f30da
48842af
31cfba2
 
 
 
48842af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// 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) });
  }
};