File size: 1,302 Bytes
33af36b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Runs the aligner off the main thread so the page stays responsive while the model loads and
// while long recordings are processed window by window.
import { AlignmentError, ForcedAligner } from "./aligner.js";

let aligner = null;

self.addEventListener("message", async ({ data }) => {
  const { id, type } = data;
  try {
    if (type === "load") {
      aligner = await ForcedAligner.load(data.model, {
        device: data.device,
        dtype: data.dtype,
        progress_callback: (p) => self.postMessage({ type: "progress", p }),
      });
      // Warm-up: the first run allocates buffers and picks kernels, so the first alignment is fast.
      await aligner._logits(new Float32Array(16000));
      self.postMessage({ id, type: "loaded", info: aligner.info });
    } else if (type === "align") {
      if (!aligner) throw new Error("The model is not loaded yet.");
      const res = await aligner.align(data.wav, data.text, {
        ...data.options,
        onProgress: (p) => self.postMessage({ id, type: "window", p }),
      });
      self.postMessage({ id, type: "result", res: { ...res, unknown: [...res.unknown.entries()] } });
    }
  } catch (err) {
    self.postMessage({ id, type: "error", message: String(err?.message ?? err), user: err instanceof AlignmentError });
  }
});