forced-aligner / aligner.js
CiscoR's picture
In-browser forced aligner (transformers.js, int8 ONNX)
33af36b verified
Raw History Blame Contribute Delete
25.7 kB
/**
* Word-level CTC forced alignment in JavaScript with Cis-Labs/omniasr-ctc-300m-forced-aligner.
*
* A port of aligner.py from the Cis Labs Forced Aligner Python Space, which mirrors
* ctc-forced-aligner's native-script path (`--romanize` off, CLI default `--star_frequency edges`):
*
* 1. Audio is 16 kHz mono float32 (the page decodes and resamples it with WebAudio).
* 2. Emissions are computed in 30 s windows with 2 s of context on each side
* (ctc-forced-aligner's `generate_emissions`), so memory stays flat on long files.
* 3. The transcript is lowercased, stripped of punctuation and mapped character by character onto
* the model's 10,288-character native-script vocabulary. Spaces become the word separator `|`.
* 4. A Viterbi pass over the CTC trellis (same recursion and tie-breaking as
* `torchaudio.functional.forced_align`) finds the best path; a zero-cost `<star>` token at both
* ends absorbs untranscribed lead-in and trail-out audio.
* 5. Each word's span is padded into the neighbouring blank gap up to its midpoint
* (ctc-forced-aligner's `get_spans` rule), giving gap-free word boundaries.
*
* Everything except `ForcedAligner.load` / `emissions` is plain JavaScript with no dependencies, so
* the text handling, the Viterbi and the output formats also run in Node.
*
* Usage:
* const aligner = await ForcedAligner.load("Cis-Labs/omniasr-ctc-300m-forced-aligner");
* const { units, unknown } = await aligner.align(wav16k, "the transcript", { lang: "eng" });
* console.log(units.map((u) => [u.text, u.start, u.end, u.score]));
*/
export const MODEL_ID = "Cis-Labs/omniasr-ctc-300m-forced-aligner";
export const SAMPLE_RATE = 16000;
export const WINDOW_S = 30; // ctc-forced-aligner defaults (--window_size / --context_size)
export const CONTEXT_S = 2;
// Languages written without spaces between words: default to character granularity.
export const CJK_LANGS = new Set(["cmn", "zho", "chi", "yue", "jpn", "wuu", "nan", "hak", "gan", "hsn", "lzh"]);
export class AlignmentError extends Error {
constructor(message) {
super(message);
this.name = "AlignmentError";
}
}
// ---------------------------------------------------------------------------------------------
// Unicode tables (generated from Python 3.12 unicodedata 15.0, the reference implementation's)
// ---------------------------------------------------------------------------------------------
// Code points whose Unicode name starts with CJK UNIFIED, CJK COMPATIBILITY IDEOGRAPH, HIRAGANA,
// KATAKANA or HANGUL SYLLABLE (aligner.py `_is_cjk`).
const CJK_RANGES = [0x3041,0x3096,0x309b,0x30ff,0x31f0,0x31ff,0x3400,0x4dbf,0x4e00,0x9fff,0xac00,0xd7a3,0xf900,0xfa6d,0xfa70,0xfad9,0x1aff0,0x1aff3,0x1aff5,0x1affb,0x1affd,0x1affe,0x1b000,0x1b001,0x1b11f,0x1b122,0x1b132,0x1b132,0x1b150,0x1b152,0x1b155,0x1b155,0x1b164,0x1b167,0x20000,0x2a6df,0x2a700,0x2b739,0x2b740,0x2b81d,0x2b820,0x2cea1,0x2ceb0,0x2ebe0,0x2f800,0x2fa1d,0x30000,0x3134a,0x31350,0x323af];
// East Asian Width W or F: counted double in subtitle line lengths (aligner.py `_width`).
const WIDE_RANGES = [0x1100,0x115f,0x231a,0x231b,0x2329,0x232a,0x23e9,0x23ec,0x23f0,0x23f0,0x23f3,0x23f3,0x25fd,0x25fe,0x2614,0x2615,0x2648,0x2653,0x267f,0x267f,0x2693,0x2693,0x26a1,0x26a1,0x26aa,0x26ab,0x26bd,0x26be,0x26c4,0x26c5,0x26ce,0x26ce,0x26d4,0x26d4,0x26ea,0x26ea,0x26f2,0x26f3,0x26f5,0x26f5,0x26fa,0x26fa,0x26fd,0x26fd,0x2705,0x2705,0x270a,0x270b,0x2728,0x2728,0x274c,0x274c,0x274e,0x274e,0x2753,0x2755,0x2757,0x2757,0x2795,0x2797,0x27b0,0x27b0,0x27bf,0x27bf,0x2b1b,0x2b1c,0x2b50,0x2b50,0x2b55,0x2b55,0x2e80,0x2e99,0x2e9b,0x2ef3,0x2f00,0x2fd5,0x2ff0,0x2ffb,0x3000,0x303e,0x3041,0x3096,0x3099,0x30ff,0x3105,0x312f,0x3131,0x318e,0x3190,0x31e3,0x31f0,0x321e,0x3220,0x3247,0x3250,0x4dbf,0x4e00,0xa48c,0xa490,0xa4c6,0xa960,0xa97c,0xac00,0xd7a3,0xf900,0xfaff,0xfe10,0xfe19,0xfe30,0xfe52,0xfe54,0xfe66,0xfe68,0xfe6b,0xff01,0xff60,0xffe0,0xffe6,0x16fe0,0x16fe4,0x16ff0,0x16ff1,0x17000,0x187f7,0x18800,0x18cd5,0x18d00,0x18d08,0x1aff0,0x1aff3,0x1aff5,0x1affb,0x1affd,0x1affe,0x1b000,0x1b122,0x1b132,0x1b132,0x1b150,0x1b152,0x1b155,0x1b155,0x1b164,0x1b167,0x1b170,0x1b2fb,0x1f004,0x1f004,0x1f0cf,0x1f0cf,0x1f18e,0x1f18e,0x1f191,0x1f19a,0x1f200,0x1f202,0x1f210,0x1f23b,0x1f240,0x1f248,0x1f250,0x1f251,0x1f260,0x1f265,0x1f300,0x1f320,0x1f32d,0x1f335,0x1f337,0x1f37c,0x1f37e,0x1f393,0x1f3a0,0x1f3ca,0x1f3cf,0x1f3d3,0x1f3e0,0x1f3f0,0x1f3f4,0x1f3f4,0x1f3f8,0x1f43e,0x1f440,0x1f440,0x1f442,0x1f4fc,0x1f4ff,0x1f53d,0x1f54b,0x1f54e,0x1f550,0x1f567,0x1f57a,0x1f57a,0x1f595,0x1f596,0x1f5a4,0x1f5a4,0x1f5fb,0x1f64f,0x1f680,0x1f6c5,0x1f6cc,0x1f6cc,0x1f6d0,0x1f6d2,0x1f6d5,0x1f6d7,0x1f6dc,0x1f6df,0x1f6eb,0x1f6ec,0x1f6f4,0x1f6fc,0x1f7e0,0x1f7eb,0x1f7f0,0x1f7f0,0x1f90c,0x1f93a,0x1f93c,0x1f945,0x1f947,0x1f9ff,0x1fa70,0x1fa7c,0x1fa80,0x1fa88,0x1fa90,0x1fabd,0x1fabf,0x1fac5,0x1face,0x1fadb,0x1fae0,0x1fae8,0x1faf0,0x1faf8,0x20000,0x2fffd,0x30000,0x3fffd];
function inRanges(table, cp) {
let lo = 0;
let hi = table.length / 2 - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (cp < table[2 * mid]) hi = mid - 1;
else if (cp > table[2 * mid + 1]) lo = mid + 1;
else return true;
}
return false;
}
// Python's whitespace set (str.isspace, re "\s").
const PY_WS = "\\t\\n\\x0b\\x0c\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
const NON_SPACE_RUNS = new RegExp(`[^${PY_WS}]+`, "gu");
const RE_PUNCT = /^[\p{P}\p{S}]/u; // category P* or S*
const RE_OTHER_OR_SEP = /^[\p{C}\p{Z}]/u; // category C* or Z*
const RE_MARK = /^\p{M}/u;
const RE_ALNUM = /^[\p{L}\p{N}]/u; // str.isalnum() for one character (checked against unicodedata 15.0)
const RE_OPENING = /^[\p{Ps}\p{Pi}]/u;
const isPunct = (ch) => RE_PUNCT.test(ch);
const isCJK = (ch) => inRanges(CJK_RANGES, ch.codePointAt(0));
const isAlnum = (ch) => RE_ALNUM.test(ch);
const APOSTROPHES = new Set(["’", "‘", "‛", "ʼ"]); // mapped to ASCII '
const HYPHENS = new Set(["‐", "‑"]); // mapped to ASCII '-', which the model emits in words
const cpRange = (a, b) => Array.from({ length: b - a + 1 }, (_, i) => String.fromCodePoint(a + i));
// ctc-forced-aligner / MMS deletion list: Arabic harakat and subscript alef, for every language;
// plus the tatweel (U+0640), a purely typographic elongation.
const DELETE = new Set([...cpRange(0x064b, 0x0652), "ٖ", "ٗ", "ـ"]);
const DELETE_BY_LANG = { heb: new Set(cpRange(0x05b0, 0x05cf)) };
const ARABIC_MAP = [
["ٱ", "ا"], ["ٰ", "ا"], ["ۥ", "و"], ["ۦ", "ي"],
["ٓ", ""], ["ٔ", "ء"], ["ٕ", "ء"],
];
const MAP_BY_LANG = { ara: ARABIC_MAP, arb: ARABIC_MAP };
const SENTENCE_END = [...".?!…。?!؟।॥።"];
const CLOSERS = new Set([..."\"'”’»)]」』)"]);
// ---------------------------------------------------------------------------------------------
// Text
// ---------------------------------------------------------------------------------------------
/** One alignable unit (a word, or a character for CJK) as shown to the user. */
function unit(text, spaceBefore) {
return { text, space_before: spaceBefore, ids: [], start: null, end: null, score: null };
}
/** Split a transcript into display units, remembering where the whitespace was. */
export function splitUnits(text, granularity) {
const units = [];
for (const m of text.matchAll(NON_SPACE_RUNS)) {
let space = m.index > 0;
const token = m[0];
if (granularity !== "characters") {
units.push(unit(token, space));
continue;
}
// characters: CJK characters stand alone; runs of other letters/digits stay together;
// combining marks stick to their base character.
let buf = "";
for (const ch of token) {
if (isCJK(ch) || isPunct(ch)) {
if (buf) {
units.push(unit(buf, space));
space = false;
buf = "";
}
units.push(unit(ch, space));
space = false;
} else if (RE_MARK.test(ch) && !buf && units.length) {
units[units.length - 1].text += ch;
} else {
buf += ch;
}
}
if (buf) units.push(unit(buf, space));
}
return units;
}
/**
* ctc-forced-aligner-compatible normalization of one unit: NFKC, lowercase, no punctuation.
* Word-internal apostrophes and hyphens are kept (the model emits them, as in "don't");
* format characters (zero-width joiners, direction marks) are dropped silently.
*/
export function normalizeChars(token, lang) {
let s = token.normalize("NFKC").toLowerCase();
for (const [from, to] of MAP_BY_LANG[lang] || []) s = s.replaceAll(from, to);
const del = DELETE_BY_LANG[lang];
const cs = Array.from(s);
let out = "";
for (let i = 0; i < cs.length; i++) {
let ch = cs[i];
if (APOSTROPHES.has(ch)) ch = "'";
else if (HYPHENS.has(ch)) ch = "-";
if (DELETE.has(ch) || del?.has(ch) || RE_OTHER_OR_SEP.test(ch)) continue;
if (ch === "'" || ch === "-") {
if (i > 0 && i < cs.length - 1 && isAlnum(cs[i - 1]) && isAlnum(cs[i + 1])) out += ch;
continue;
}
if (isPunct(ch)) continue;
out += ch;
}
return out;
}
export function joinUnits(units) {
return units.map((u, i) => (i && u.space_before ? " " : "") + u.text).join("");
}
/**
* Attach units that are pure punctuation (a lone dash, CJK commas, quotes) to a neighbour.
* Opening brackets and quotes go to the next unit; everything else to the previous one.
*/
function mergePunctuation(units) {
const out = [];
let pending = [];
for (const u of units) {
if (!u.ids.length && Array.from(u.text).every(isPunct)) {
const opening = RE_OPENING.test(u.text);
if (out.length && !opening) out[out.length - 1].text += (u.space_before ? " " : "") + u.text;
else pending.push(u);
continue;
}
if (pending.length) {
u.text = joinUnits(pending) + (u.space_before ? " " : "") + u.text;
u.space_before = pending[0].space_before;
pending = [];
}
out.push(u);
}
if (pending.length && out.length) out[out.length - 1].text += " " + joinUnits(pending);
return out;
}
/** Lowercased vocabulary (ctc-forced-aligner and WhisperX both look characters up this way). */
export function lowercaseVocab(vocab) {
const out = new Map();
for (const [k, v] of Object.entries(vocab)) out.set(k.toLowerCase(), v);
return out;
}
/**
* Units + characters that had to be skipped (not in the model vocabulary).
* @returns {{units: object[], unknown: Map<string, number>}}
*/
export function tokenize(text, vocab, { lang = "eng", granularity = "words", blank = 0, sep = 4 } = {}) {
const units = splitUnits(text, granularity);
const unknown = new Map();
for (const u of units) {
for (const ch of normalizeChars(u.text, lang)) {
const id = vocab.get(ch);
if (id === undefined || id === blank || id === sep) unknown.set(ch, (unknown.get(ch) || 0) + 1);
else u.ids.push(id);
}
}
return { units: mergePunctuation(units), unknown };
}
/**
* Target sequence for the trellis: <star> chars [| chars ...] <star>, over a reduced set of
* columns (blank first, then the characters the transcript uses, then <star>).
*/
export function buildTargets(units, { blank = 0, sep = 4, useSeparator = true } = {}) {
const aligned = [];
units.forEach((u, i) => u.ids.length && aligned.push(i));
if (!aligned.length) {
throw new AlignmentError(
"None of the transcript's characters are in the model vocabulary. Check the transcript and language.");
}
const targets = [];
const owner = [];
aligned.forEach((ui, n) => {
if (useSeparator && n > 0 && units[ui].space_before) {
targets.push(sep);
owner.push(-1);
}
for (const id of units[ui].ids) {
targets.push(id);
owner.push(ui);
}
});
const rest = [...new Set(targets)].filter((t) => t !== blank).sort((a, b) => a - b);
const columns = [blank, ...rest];
const col = new Map(columns.map((c, i) => [c, i]));
const star = columns.length;
const tgt = [star, ...targets.map((t) => col.get(t)), star];
return { aligned, columns, tgt, owner: [-1, ...owner, -1] };
}
// ---------------------------------------------------------------------------------------------
// Viterbi
// ---------------------------------------------------------------------------------------------
const NEG = Math.fround(-1e30);
/**
* Best CTC path for `tgt` through log-probs `lp` (T x C, row-major Float32Array), blank = 0.
* Same recursion, float32 arithmetic and tie-breaking as torchaudio's CPU forced_align kernel
* (ties prefer staying, then the previous state). Backpointers use 2 bits per cell.
* @returns {{path: Int32Array, logp: Float32Array}} label (column) and its log-prob per frame
*/
export function forcedAlign(lp, T, C, tgt, blank = 0) {
const S = 2 * tgt.length + 1;
const ext = new Int32Array(S).fill(blank);
for (let k = 0; k < tgt.length; k++) ext[2 * k + 1] = tgt[k];
const skip = new Uint8Array(S);
for (let s = 3; s < S; s += 2) skip[s] = ext[s] !== ext[s - 2] ? 1 : 0;
let alpha = new Float32Array(S).fill(NEG);
let next = new Float32Array(S);
alpha[0] = lp[ext[0]];
alpha[1] = lp[ext[1]];
const back = new Uint8Array(Math.ceil((T * S) / 4));
for (let t = 1; t < T; t++) {
const row = t * C;
const base = t * S;
for (let s = 0; s < S; s++) {
let best = alpha[s];
let choice = 0;
const c1 = s >= 1 ? alpha[s - 1] : NEG;
if (c1 > best) {
best = c1;
choice = 1;
}
if (s >= 2 && skip[s]) {
const c2 = alpha[s - 2];
if (c2 > best) {
best = c2;
choice = 2;
}
} else if (NEG > best) {
best = NEG;
choice = 2;
}
next[s] = best + lp[row + ext[s]]; // Float32Array store rounds to float32, like numpy/torch
if (choice) {
const i = base + s;
back[i >> 2] |= choice << ((i & 3) << 1);
}
}
const tmp = alpha;
alpha = next;
next = tmp;
}
let s = S > 1 && alpha[S - 1] > alpha[S - 2] ? S - 1 : S - 2;
const path = new Int32Array(T);
const logp = new Float32Array(T);
for (let t = T - 1; t >= 0; t--) {
path[t] = ext[s];
logp[t] = lp[t * C + ext[s]];
const i = t * S + s;
s -= (back[i >> 2] >> ((i & 3) << 1)) & 3;
}
return { path, logp };
}
/**
* Turn emissions + targets into unit timestamps (aligner.py `Aligner.align` after emissions).
* @param {object[]} units output of tokenize(); start/end/score are filled in place
* @param {object} targets output of buildTargets()
* @param {Float32Array} em T x (columns + 1) log-probs, the last column being <star> (0)
*/
export function alignUnits(units, targets, em, T, frameS) {
const { aligned, tgt, owner } = targets;
const C = targets.columns.length + 1;
let repeats = 0;
for (let i = 1; i < tgt.length; i++) if (tgt[i] === tgt[i - 1]) repeats++;
if (T < tgt.length + repeats) {
throw new AlignmentError(
`The transcript is too long for this audio (${tgt.length} characters for ` +
`${(T * frameS).toFixed(1)} s). Check that the transcript matches the recording.`);
}
const { path, logp } = forcedAlign(em, T, C, tgt);
// Merge repeated frames into segments; non-blank segments map 1:1 onto targets.
const segs = []; // [target_index, first_frame, last_frame]
let k = 0;
for (let t = 0; t < T; ) {
let t2 = t;
while (t2 + 1 < T && path[t2 + 1] === path[t]) t2++;
if (path[t] !== 0) segs.push([k++, t, t2]);
t = t2 + 1;
}
if (k !== tgt.length) throw new Error(`internal: ${k} segments for ${tgt.length} targets`);
const first = new Map();
const last = new Map();
const charScores = new Map();
for (const [ti, a, b] of segs) {
const ui = owner[ti];
if (ui < 0) continue;
if (!first.has(ui)) first.set(ui, a);
last.set(ui, b);
let sum = 0;
for (let t = a; t <= b; t++) sum += Math.exp(logp[t]);
if (!charScores.has(ui)) charScores.set(ui, []);
charScores.get(ui).push(sum / (b - a + 1));
}
const leadEnd = segs[0][2]; // last frame of the leading <star>
const trailStart = segs[segs.length - 1][1]; // first frame of the trailing <star>
// Pad each word into neighbouring gaps up to the midpoint (ctc-forced-aligner rule).
aligned.forEach((ui, n) => {
let s = first.get(ui);
let e = last.get(ui);
const prevEnd = n > 0 ? last.get(aligned[n - 1]) : leadEnd;
const nextStart = n + 1 < aligned.length ? first.get(aligned[n + 1]) : trailStart;
if (s - prevEnd > 1) s = n === 0 ? prevEnd + 1 : Math.floor((prevEnd + 1 + s - 1) / 2);
if (nextStart - e > 1) e = n + 1 === aligned.length ? nextStart - 1 : Math.floor((e + 1 + nextStart - 1) / 2);
const u = units[ui];
u.start = s * frameS;
u.end = (e + 1) * frameS;
const cs = charScores.get(ui);
u.score = cs.reduce((x, y) => x + y, 0) / cs.length;
});
let prev = null;
for (const u of units) {
if (u.start === null) continue;
if (prev && u.start < prev.end) u.start = prev.end;
prev = u;
}
// Units with nothing alignable inherit a zero-length slot at the previous boundary.
let tLast = 0;
for (const u of units) {
if (u.start === null) u.start = u.end = tLast;
else tLast = u.end;
}
for (const u of units) {
u.start = round(u.start, 3);
u.end = round(u.end, 3);
}
return units;
}
const round = (x, d) => Number(x.toFixed(d));
// ---------------------------------------------------------------------------------------------
// Model
// ---------------------------------------------------------------------------------------------
export class ForcedAligner {
constructor(model, vocab, info, Tensor) {
this.model = model;
this.vocab = vocab; // lowercased Map
this.blank = vocab.get("<pad>");
this.sep = vocab.get("|");
const strides = model.config?.conv_stride || [5, 2, 2, 2, 2, 2, 2];
this.ratio = strides.reduce((a, b) => a * b, 1); // 320 samples = 20 ms
this.frameS = this.ratio / SAMPLE_RATE;
this.info = info;
this.Tensor = Tensor;
}
/**
* Load the ONNX model (transformers.js) and the vocabulary.
* @param {string} modelId Hub repo id, or a same-origin path / URL to a folder with the same layout
* @param {object} [opts]
* @param {string} [opts.dtype="q8"] "q8" = onnx/model_quantized.onnx, "fp32" = onnx/model.onnx
* @param {string} [opts.device="wasm"] "wasm" or "webgpu"
* @param {(p: object) => void} [opts.progress_callback] transformers.js download progress
*/
static async load(modelId = MODEL_ID, { dtype = "q8", device = "wasm", progress_callback = null } = {}) {
const { AutoModelForCTC, Tensor, env } = await import("./deps.js");
const local = /^(\.{0,2}\/|https?:)/.test(modelId);
if (local) {
env.allowLocalModels = true; // a folder served next to the page (testing before release)
env.allowRemoteModels = false;
}
const vocabUrl = local
? `${modelId.replace(/\/$/, "")}/vocab.json`
: `${env.remoteHost.replace(/\/$/, "")}/${modelId}/resolve/main/vocab.json`;
const vocabPromise = fetch(vocabUrl).then((r) => {
if (!r.ok) throw new Error(`vocab.json: HTTP ${r.status}`);
return r.json();
});
const model = await AutoModelForCTC.from_pretrained(modelId, { dtype, device, progress_callback });
const vocab = lowercaseVocab(await vocabPromise);
const info = {
modelId, dtype, device,
threads: device === "wasm" ? (env.backends?.onnx?.wasm?.numThreads ?? null) : null,
};
return new ForcedAligner(model, vocab, info, Tensor);
}
async _logits(samples) {
const input = new this.Tensor("float32", samples, [1, samples.length]);
const { logits } = await this.model({ input_values: input });
return logits; // [1, frames, vocab]
}
/**
* Log-probabilities (T x (columns + 1)) computed window by window, plus a zero <star> column.
* Same chunking as ctc-forced-aligner's generate_emissions (30 s windows, 2 s context), but only
* the vocabulary columns the transcript needs are kept.
*/
async emissions(wav, columns, onProgress = null) {
const window = WINDOW_S * SAMPLE_RATE;
const context = CONTEXT_S * SAMPLE_RATE;
const cf = Math.floor(context / this.ratio);
const wf = Math.floor(window / this.ratio);
const C = columns.length + 1;
const parts = [];
let total = 0;
const take = (logits, from, count) => {
const V = logits.dims[2];
const data = logits.data;
const out = new Float32Array(count * C); // <star> column stays 0
for (let f = 0; f < count; f++) {
const o = (from + f) * V;
let max = -Infinity;
for (let v = 0; v < V; v++) if (data[o + v] > max) max = data[o + v];
let sum = 0;
for (let v = 0; v < V; v++) sum += Math.exp(data[o + v] - max);
const lse = max + Math.log(sum);
for (let c = 0; c < columns.length; c++) out[f * C + c] = data[o + columns[c]] - lse;
}
logits.dispose?.();
parts.push(out);
total += count;
};
if (wav.length < window) {
onProgress?.({ done: 0, total: 1 });
const logits = await this._logits(wav);
take(logits, 0, logits.dims[1]);
onProgress?.({ done: 1, total: 1 });
} else {
const n = wav.length;
const k = Math.ceil(n / window);
const extension = k * window - n;
const padded = new Float32Array(context + n + context + extension);
padded.set(wav, context);
const size = window + 2 * context;
for (let i = 0; i < k; i++) {
onProgress?.({ done: i, total: k });
const logits = await this._logits(padded.slice(i * window, i * window + size));
take(logits, cf, Math.min(wf, logits.dims[1] - cf));
}
onProgress?.({ done: k, total: k });
// aligner.py drops extension // ratio trailing frames (and none when that is 0).
total -= Math.floor(extension / this.ratio);
}
const em = new Float32Array(total * C);
let off = 0;
for (const p of parts) {
const len = Math.min(p.length, em.length - off);
em.set(p.subarray(0, len), off);
off += len;
if (off >= em.length) break;
}
return { em, T: total };
}
/**
* Align `text` to 16 kHz mono `wav` (Float32Array).
* useSeparator=false reproduces ctc-forced-aligner's CLI output exactly (it does not put the
* word separator between words); true follows the model's training format.
* @returns {Promise<{units: object[], unknown: Map<string, number>, timing: object}>}
*/
async align(wav, text, { lang = "eng", granularity = "words", useSeparator = true, onProgress = null } = {}) {
const t0 = performance.now();
const { units, unknown } = tokenize(text, this.vocab, { lang, granularity, blank: this.blank, sep: this.sep });
const targets = buildTargets(units, { blank: this.blank, sep: this.sep, useSeparator });
const { em, T } = await this.emissions(wav, targets.columns, onProgress);
const t1 = performance.now();
alignUnits(units, targets, em, T, this.frameS);
const t2 = performance.now();
return { units, unknown, timing: { modelMs: t1 - t0, alignMs: t2 - t1, frames: T } };
}
}
// ---------------------------------------------------------------------------------------------
// Output formats
// ---------------------------------------------------------------------------------------------
function width(s) {
let w = 0;
for (const ch of s) w += inRanges(WIDE_RANGES, ch.codePointAt(0)) ? 2 : 1;
return w;
}
function rstripClosers(s) {
const cs = Array.from(s);
while (cs.length && CLOSERS.has(cs[cs.length - 1])) cs.pop();
return cs.join("");
}
/** Group units into subtitle cues: break on sentence ends, pauses, length and duration. */
export function groupCues(units, { maxChars = 42, maxGap = 0.6, maxDuration = 6.0, onePerCue = false } = {}) {
const cues = [];
let cur = [];
let length = 0;
for (const u of units) {
let add = width(u.text) + (cur.length && u.space_before ? 1 : 0);
if (cur.length && (onePerCue ||
length + add > maxChars ||
u.start - cur[cur.length - 1].end > maxGap ||
u.end - cur[0].start > maxDuration ||
SENTENCE_END.some((p) => rstripClosers(cur[cur.length - 1].text).endsWith(p)))) {
cues.push(cur);
cur = [];
length = 0;
add = width(u.text);
}
cur.push(u);
length += add;
}
if (cur.length) cues.push(cur);
return cues;
}
function ts(t) {
let ms = Math.round(t * 1000);
const h = Math.floor(ms / 3600000);
ms -= h * 3600000;
const m = Math.floor(ms / 60000);
ms -= m * 60000;
const s = Math.floor(ms / 1000);
ms -= s * 1000;
const p = (x, n) => String(x).padStart(n, "0");
return `${p(h, 2)}:${p(m, 2)}:${p(s, 2)},${p(ms, 3)}`;
}
export function toSrt(cues) {
return cues
.map((cue, i) => {
const start = cue[0].start;
const end = Math.max(cue[cue.length - 1].end, cue[0].start + 0.04);
return `${i + 1}\n${ts(start)} --> ${ts(end)}\n${joinUnits(cue)}\n`;
})
.join("\n");
}
/** WhisperX-style result: segments (subtitle cues) with words, plus a flat word list. */
export function toJson(units, cues, { text, language, granularity, duration, modelId = MODEL_ID }) {
const word = (u) => ({ word: u.text, start: u.start, end: u.end, score: u.score === null ? null : round(u.score, 3) });
return {
model: modelId,
language,
granularity,
duration: round(duration, 3),
text,
segments: cues.map((c) => ({
start: c[0].start, end: c[c.length - 1].end, text: joinUnits(c), words: c.map(word),
})),
word_segments: units.map(word),
};
}