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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
/* global OfflineRecognizer, createVad */

const SAMPLE_RATE = 16000;
const VAD_WINDOW = 512;
const SHORT_UTTERANCE_MIN_SECONDS = 0.12;
const LIVE_PRE_ROLL_SECONDS = 0.32;
const LIVE_PRE_ROLL_SAMPLES = Math.round(SAMPLE_RATE * LIVE_PRE_ROLL_SECONDS);
const LIVE_HISTORY_LIMIT = SAMPLE_RATE * 90;
const PREVIEW_MIN_SECONDS = 3;
const SPARSE_RETRY_MIN_SECONDS = 5;
const SPARSE_RETRY_WORDS_PER_SECOND = 2.5;
const SPARSE_RETRY_SHIFT_SAMPLES = 64;
const SPARSE_RETRY_MIN_EXTRA_WORDS = 3;

// A private Hugging Face static Space signs its iframe URL. Worker subrequests
// do not inherit that signature, so carry it to runtime scripts and model files.
function signedAsset(path) {
  const base = new URL(self.location.href);
  const url = new URL(path, base);
  const signature = base.searchParams.get("__sign");
  if (signature && url.origin === base.origin) url.searchParams.set("__sign", signature);
  return url.href;
}

let runtimeResolve;
const runtimeReady = new Promise((resolve) => {
  runtimeResolve = resolve;
});

var Module = {
  locateFile(path) {
    return signedAsset(path);
  },
  setStatus(status) {
    self.postMessage({type: "runtime-status", status});
  },
  onRuntimeInitialized() {
    runtimeResolve();
  },
  print(text) {
    self.postMessage({type: "runtime-log", message: String(text)});
  },
  printErr(text) {
    self.postMessage({type: "runtime-log", message: String(text)});
  },
};
self.Module = Module;

importScripts(signedAsset("sherpa-onnx-asr.js"), signedAsset("sherpa-onnx-vad.js"));
importScripts(signedAsset("sherpa-onnx-wasm-main-vad-asr.js"));

let recognizer = null;
let vad = null;
let initialization = null;
let liveCarry = new Float32Array(0);
let liveHistory = new Float32Array(0);
let liveHistoryStart = 0;
let liveSamplesAccepted = 0;
let previewStart = null;
let nextPreviewSample = 0;
let lastLiveResultEndSample = null;

function concatenate(left, right) {
  const output = new Float32Array(left.length + right.length);
  output.set(left);
  output.set(right, left.length);
  return output;
}

function resetLiveAudio() {
  liveCarry = new Float32Array(0);
  liveHistory = new Float32Array(0);
  liveHistoryStart = 0;
  liveSamplesAccepted = 0;
  previewStart = null;
  nextPreviewSample = 0;
  lastLiveResultEndSample = null;
}

function clearLivePreview() {
  if (previewStart === null) return;
  previewStart = null;
  nextPreviewSample = 0;
  self.postMessage({type: "live-preview-clear"});
}

function appendLiveHistory(samples) {
  liveHistory = concatenate(liveHistory, samples);
  liveSamplesAccepted += samples.length;
  if (liveHistory.length > LIVE_HISTORY_LIMIT) {
    const discard = liveHistory.length - LIVE_HISTORY_LIMIT;
    liveHistory = liveHistory.slice(discard);
    liveHistoryStart += discard;
  }
}

function addSegmentPreRoll(segment) {
  const segmentStart = Number(segment.start);
  const prefixStart = Math.max(liveHistoryStart, segmentStart - LIVE_PRE_ROLL_SAMPLES);
  const prefixEnd = Math.min(segmentStart, liveHistoryStart + liveHistory.length);
  if (prefixEnd <= prefixStart) {
    return {samples: segment.samples, start: segmentStart};
  }
  const from = prefixStart - liveHistoryStart;
  const to = prefixEnd - liveHistoryStart;
  return {
    samples: concatenate(liveHistory.slice(from, to), segment.samples),
    start: prefixStart,
  };
}

function retainRecentPreRoll() {
  const keepFrom = Math.max(
    liveHistoryStart,
    (lastLiveResultEndSample ?? liveSamplesAccepted) - LIVE_PRE_ROLL_SAMPLES,
  );
  const discard = keepFrom - liveHistoryStart;
  if (discard > 0) {
    liveHistory = liveHistory.slice(discard);
    liveHistoryStart = keepFrom;
  }
}

function peakNormalize(samples) {
  let peak = 0;
  for (let index = 0; index < samples.length; index += 1) {
    peak = Math.max(peak, Math.abs(samples[index]));
  }
  if (peak === 0 || peak === 0.95) {
    return samples;
  }
  const scale = 0.95 / peak;
  const normalized = new Float32Array(samples.length);
  for (let index = 0; index < samples.length; index += 1) {
    normalized[index] = samples[index] * scale;
  }
  return normalized;
}

async function sha256(bytes) {
  const digest = await crypto.subtle.digest("SHA-256", bytes.buffer);
  return Array.from(new Uint8Array(digest), (value) => value.toString(16).padStart(2, "0")).join("");
}

async function fetchVerified(file, completedBytes, totalBytes) {
  const url = signedAsset(file.url);
  let cache = null;
  try { cache = await self.caches?.open("ekko-browser-models-v1"); } catch { /* Storage is optional. */ }
  for (let attempt = 0; attempt < 2; attempt += 1) {
    let cached = null;
    if (!attempt && cache) {
      try { cached = await cache.match(url); } catch { /* Use the network. */ }
    }
    const response = cached || await fetch(url, {cache: attempt ? "reload" : "force-cache"});
    if (!response.ok || !response.body) {
      throw new Error(`Kunne ikke hente ${file.path} (${response.status})`);
    }
    const reader = response.body.getReader();
    const bytes = new Uint8Array(file.bytes);
    let loaded = 0;
    while (true) {
      const {done, value} = await reader.read();
      if (done) break;
      if (loaded + value.byteLength > bytes.length) {
        await reader.cancel();
        loaded = bytes.length + 1;
        break;
      }
      bytes.set(value, loaded);
      loaded += value.byteLength;
      self.postMessage({
        type: "model-progress",
        cached: Boolean(cached),
        file: file.path,
        loaded,
        fileBytes: file.bytes,
        overall: Math.min(1, (completedBytes + loaded) / totalBytes),
      });
    }
    if (loaded === file.bytes && await sha256(bytes) === file.sha256) {
      if (!cached && cache) {
        try { await cache.put(url, new Response(bytes)); } catch { /* Keep using the verified bytes. */ }
      }
      return bytes;
    }
    if (cached) {
      try { await cache.delete(url); } catch { /* Retry without this entry. */ }
    }
    if (attempt) throw new Error(`${file.path} fejlede størrelses- eller SHA-256-kontrol`);
  }
}

function createRecognizer(runtimeConfig) {
  recognizer = new OfflineRecognizer(
    {
      featConfig: {
        sampleRate: runtimeConfig.sampleRate,
        featureDim: runtimeConfig.featureDim,
      },
      modelConfig: {
        transducer: {
          encoder: "./nemo-transducer-encoder.onnx",
          decoder: "./nemo-transducer-decoder.onnx",
          joiner: "./nemo-transducer-joiner.onnx",
        },
        tokens: "./tokens.txt",
        modelType: runtimeConfig.modelType,
        provider: "cpu",
        numThreads: 1,
        debug: 0,
      },
      decodingMethod: "greedy_search",
      maxActivePaths: 4,
    },
    Module,
  );
  vad = createVad(Module, {
    sileroVad: {
      model: "./silero_vad.onnx",
      threshold: 0.5,
      minSilenceDuration: 0.5,
      minSpeechDuration: SHORT_UTTERANCE_MIN_SECONDS,
      maxSpeechDuration: 20,
      windowSize: VAD_WINDOW,
    },
    sampleRate: SAMPLE_RATE,
    numThreads: 1,
    provider: "cpu",
    debug: 0,
    bufferSizeInSeconds: 90,
  });
}

async function initialize(configUrl) {
  if (recognizer) return;
  await runtimeReady;
  const response = await fetch(signedAsset(configUrl), {cache: "no-cache"});
  if (!response.ok) throw new Error("Kunne ikke hente modelkonfigurationen");
  const config = await response.json();
  if (config.schema !== "ekko-browser-model-v1") {
    throw new Error("Ukendt modelkonfiguration");
  }
  if (!Module.FS) throw new Error("WASM-filsystemet er ikke eksporteret");

  const totalBytes = config.files.reduce((sum, file) => sum + file.bytes, 0);
  let completedBytes = 0;
  let runtimeConfig = null;
  for (const file of config.files) {
    const bytes = await fetchVerified(file, completedBytes, totalBytes);
    if (file.path === "runtime-config.json") {
      runtimeConfig = JSON.parse(new TextDecoder().decode(bytes));
    } else {
      Module.FS.writeFile(file.path, bytes);
    }
    completedBytes += bytes.byteLength;
  }
  if (
    runtimeConfig?.schema !== "ekko-tiny-onnx-runtime-v1" ||
    runtimeConfig.sampleRate !== SAMPLE_RATE ||
    runtimeConfig.featureDim !== 80 ||
    runtimeConfig.modelType !== "nemo_transducer"
  ) {
    throw new Error("Ukendt Tiny runtimekonfiguration");
  }
  createRecognizer(runtimeConfig);
  self.postMessage({
    type: "ready",
    model: config.name,
    runtime: config.runtime,
    bytes: totalBytes,
  });
}

function toWords(result, duration, timeOffset = 0) {
  const tokens = Array.isArray(result.tokens) ? result.tokens : [];
  const timestamps = Array.isArray(result.timestamps) ? result.timestamps : [];
  const durations = Array.isArray(result.durations) ? result.durations : [];
  if (tokens.length !== timestamps.length) return [];
  const words = [];
  let text = "";
  let start = null;
  let tokenIndices = [];

  const finish = (endHint) => {
    if (!text || start === null) return;
    let end = endHint;
    if (durations.length === tokens.length) {
      for (const index of tokenIndices) {
        end = Math.max(end, Number(timestamps[index]) + Number(durations[index]));
      }
    }
    words.push({
      text,
      start: timeOffset + start,
      end: timeOffset + Math.min(duration, Math.max(start, end)),
    });
  };

  tokens.forEach((rawToken, index) => {
    const token = String(rawToken);
    const timestamp = Number(timestamps[index]);
    if (token === " " || token.startsWith("▁")) {
      finish(timestamp);
      text = token.trim().replace(/^▁/, "");
      start = timestamp;
      tokenIndices = [index];
    } else {
      if (start === null) start = timestamp;
      text += token;
      tokenIndices.push(index);
    }
  });
  if (text && start !== null) {
    const fallback = timestamps.length ? Number(timestamps[timestamps.length - 1]) + 0.08 : start;
    finish(fallback);
  }
  // The recognizer's text is authoritative. A partial token/timestamp list
  // must never become a partial transcript downstream.
  const decodedText = String(result.text || "").trim().replace(/\s+/g, " ");
  if (words.map((word) => word.text).join(" ") !== decodedText) return [];
  return words;
}

function decodeSamples(samples, source, timeOffset = 0) {
  if (!recognizer) throw new Error("Modellen er ikke klar");
  const normalized = peakNormalize(samples);
  const duration = normalized.length / SAMPLE_RATE;
  const stream = recognizer.createStream();
  try {
    stream.acceptWaveform(SAMPLE_RATE, normalized);
    recognizer.decode(stream);
    const result = recognizer.getResult(stream);
    return {
      source,
      text: String(result.text || "").trim(),
      start: timeOffset,
      end: timeOffset + duration,
      duration,
      words: toWords(result, duration, timeOffset),
    };
  } finally {
    stream.free();
  }
}

function wordCount(text) {
  const trimmed = text.trim();
  return trimmed ? trimmed.split(/\s+/).length : 0;
}

function retrySparseSegment(buffered, result) {
  const duration = buffered.samples.length / SAMPLE_RATE;
  const originalCount = wordCount(result.text);
  if (duration < SPARSE_RETRY_MIN_SECONDS ||
      originalCount >= duration * SPARSE_RETRY_WORDS_PER_SECOND) return result;

  let best = result;
  let bestCount = originalCount;
  for (const shift of [SPARSE_RETRY_SHIFT_SAMPLES, -SPARSE_RETRY_SHIFT_SAMPLES]) {
    const start = buffered.start + shift;
    const end = start + buffered.samples.length;
    if (start < liveHistoryStart || end > liveHistoryStart + liveHistory.length) continue;
    const samples = liveHistory.slice(start - liveHistoryStart, end - liveHistoryStart);
    const candidate = decodeSamples(samples, "microphone", start / SAMPLE_RATE);
    const count = wordCount(candidate.text);
    if (count > bestCount) {
      best = candidate;
      bestCount = count;
    }
  }
  if (bestCount < originalCount + SPARSE_RETRY_MIN_EXTRA_WORDS) return result;

  // Keep the VAD span stable for gap recovery and downstream punctuation.
  const correction = result.start - best.start;
  return {
    ...best,
    start: result.start,
    end: result.end,
    duration: result.duration,
    words: best.words.map((word) => ({
      ...word,
      start: word.start + correction,
      end: word.end + correction,
    })),
  };
}

function recoverSpeechGap(nextStartSample) {
  if (lastLiveResultEndSample === null) return;
  const start = Math.max(lastLiveResultEndSample, liveHistoryStart);
  const end = Math.min(nextStartSample, liveHistoryStart + liveHistory.length);
  if (end - start < SAMPLE_RATE * 2) return;
  const samples = liveHistory.slice(start - liveHistoryStart, end - liveHistoryStart);
  let sumSquares = 0;
  for (const value of samples) sumSquares += value * value;
  if (Math.sqrt(sumSquares / samples.length) < 0.018) return;
  const result = decodeSamples(samples, "microphone-gap", start / SAMPLE_RATE);
  if (result.text.trim().split(/\s+/).length < 3) return;
  self.postMessage({type: "live-result", result});
  lastLiveResultEndSample = end;
  retainRecentPreRoll();
}

function drainVad() {
  while (!vad.isEmpty()) {
    const segment = vad.front();
    vad.pop();
    const buffered = addSegmentPreRoll(segment);
    const result = retrySparseSegment(
      buffered,
      decodeSamples(buffered.samples, "microphone", buffered.start / SAMPLE_RATE),
    );
    recoverSpeechGap(Math.round(result.start * SAMPLE_RATE));
    clearLivePreview();
    if (result.text) {
      self.postMessage({type: "live-result", result});
      lastLiveResultEndSample = Math.round(result.end * SAMPLE_RATE);
      retainRecentPreRoll();
    }
  }
}

function maybePreviewSpeech() {
  if (!vad.isDetected()) {
    clearLivePreview();
    return;
  }
  if (previewStart === null) {
    previewStart = Math.max(liveHistoryStart, liveSamplesAccepted - SAMPLE_RATE / 2);
    nextPreviewSample = previewStart + PREVIEW_MIN_SECONDS * SAMPLE_RATE;
  }
  if (liveSamplesAccepted < nextPreviewSample) return;
  const start = Math.max(previewStart, liveHistoryStart);
  const samples = liveHistory.slice(start - liveHistoryStart);
  const result = decodeSamples(samples, "preview", start / SAMPLE_RATE);
  if (result.text) self.postMessage({type: "live-preview", result});
  const duration = samples.length / SAMPLE_RATE;
  nextPreviewSample = liveSamplesAccepted + Math.max(PREVIEW_MIN_SECONDS, duration / 6) * SAMPLE_RATE;
}

function acceptLiveChunk(samples) {
  liveCarry = concatenate(liveCarry, samples);
  while (liveCarry.length >= VAD_WINDOW) {
    const frame = liveCarry.slice(0, VAD_WINDOW);
    liveCarry = liveCarry.slice(VAD_WINDOW);
    appendLiveHistory(frame);
    vad.acceptWaveform(frame);
    self.postMessage({type: "speech-state", detected: vad.isDetected()});
    drainVad();
    maybePreviewSpeech();
  }
}

function stopLive() {
  if (liveCarry.length) {
    const padded = new Float32Array(VAD_WINDOW);
    padded.set(liveCarry);
    appendLiveHistory(padded);
    vad.acceptWaveform(padded);
  }
  vad.flush();
  drainVad();
  recoverSpeechGap(liveSamplesAccepted);
  clearLivePreview();
  vad.reset();
  resetLiveAudio();
  self.postMessage({type: "live-stopped"});
}

self.onmessage = async (event) => {
  const message = event.data || {};
  try {
    if (message.type === "init") {
      initialization ||= initialize(message.configUrl || "model-config.json");
      await initialization;
    } else if (message.type === "live-start") {
      await initialization;
      vad.reset();
      resetLiveAudio();
    } else if (message.type === "live-chunk") {
      await initialization;
      acceptLiveChunk(new Float32Array(message.samples));
    } else if (message.type === "live-stop") {
      await initialization;
      stopLive();
    }
  } catch (error) {
    self.postMessage({
      type: "error",
      requestId: message.requestId,
      message: error instanceof Error ? error.message : String(error),
    });
  }
};