@cartanova/qgrid-cli 2.17.1 → 2.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.ko.md +26 -0
  2. package/README.md +29 -0
  3. package/bundle/dist/_virtual/_rolldown/runtime.js +1 -0
  4. package/bundle/dist/application/qgrid/qgrid.frame.js +32 -44
  5. package/bundle/dist/application/qgrid/qgrid.types.js +5 -4
  6. package/bundle/dist/startup-migrations.js +1 -1
  7. package/bundle/dist/utils/providers/common/model-cost.js +10 -18
  8. package/bundle/dist/utils/providers/common/schema-validation.js +2 -2
  9. package/bundle/dist/utils/providers/grok/grok-types.js +3 -2
  10. package/bundle/dist/utils/providers/grok/grok-voice-client.js +12 -6
  11. package/bundle/dist/utils/providers/openai/openai-dispatcher.js +3 -2
  12. package/bundle/dist/utils/providers/openai/openai-realtime-protocol.js +4 -8
  13. package/bundle/dist/utils/speech-aligner.js +302 -0
  14. package/bundle/dist/utils/speech-alignment.js +2 -102
  15. package/bundle/src/application/qgrid/qgrid.frame.test.ts +56 -17
  16. package/bundle/src/application/qgrid/qgrid.frame.ts +46 -50
  17. package/bundle/src/application/qgrid/qgrid.types.ts +16 -11
  18. package/bundle/src/application/sonamu.generated.http +1 -0
  19. package/bundle/src/utils/providers/common/model-cost.ts +0 -1
  20. package/bundle/src/utils/providers/common/schema-validation.ts +1 -1
  21. package/bundle/src/utils/providers/grok/grok-types.ts +1 -0
  22. package/bundle/src/utils/providers/grok/grok-voice-client.test.ts +7 -4
  23. package/bundle/src/utils/providers/grok/grok-voice-client.ts +14 -1
  24. package/bundle/src/utils/providers/openai/openai-dispatcher.test.ts +18 -0
  25. package/bundle/src/utils/providers/openai/openai-dispatcher.ts +6 -1
  26. package/bundle/src/utils/providers/openai/openai-realtime-protocol.ts +3 -7
  27. package/bundle/src/utils/speech-aligner.test.ts +100 -0
  28. package/bundle/src/utils/speech-aligner.ts +435 -0
  29. package/bundle/src/utils/speech-alignment.test.ts +2 -50
  30. package/bundle/src/utils/speech-alignment.ts +1 -141
  31. package/bundle/web-dist/client/assets/{index-D56cIqxW.js → index-DYYtV8Qx.js} +3 -3
  32. package/bundle/web-dist/client/assets/{logs-pMW62Hvw.js → logs-CbDtQif1.js} +1 -1
  33. package/bundle/web-dist/client/assets/{monit-COC4S7gf.js → monit-DtW8o_yF.js} +1 -1
  34. package/bundle/web-dist/client/assets/{routes-C38qmify.js → routes-Dw227enb.js} +1 -1
  35. package/bundle/web-dist/client/assets/{settings-BWGSVpiQ.js → settings-BXmAToY1.js} +1 -1
  36. package/bundle/web-dist/client/assets/{show-aQTLNz5k.js → show-5qj6wFgp.js} +2 -2
  37. package/bundle/web-dist/client/assets/{tokens-Ha8SwMPG.js → tokens-D8L8AC4v.js} +1 -1
  38. package/bundle/web-dist/client/assets/{use-oauth-login-flow-JoEnKQis.js → use-oauth-login-flow-BcEUkszt.js} +1 -1
  39. package/bundle/web-dist/client/assets/{use-update-token-mutation-cdCVcOY5.js → use-update-token-mutation-Ca0n_WnM.js} +1 -1
  40. package/bundle/web-dist/client/assets/voice-D-c1Eyp3.js +1 -0
  41. package/bundle/web-dist/client/index.html +1 -1
  42. package/bundle/web-dist/server/assets/{show-B_l5dOcT.js → show-CnLDFCtW.js} +2 -5
  43. package/bundle/web-dist/server/assets/{voice-CHoPEIfo.js → voice-BvAl-vTr.js} +32 -8
  44. package/bundle/web-dist/server/entry-server.generated.js +3 -3
  45. package/dist/cli.js +141 -3
  46. package/package.json +1 -1
  47. package/skills/qgrid/references/ai-sdk-provider-contract.md +1 -1
  48. package/skills/qgrid/references/cli-env-and-server-boot.md +1 -0
  49. package/skills/qgrid/references/grok-runtime.md +5 -3
  50. package/skills/qgrid/references/openai-codex-runtime.md +3 -1
  51. package/skills/qgrid/references/request-log-run-lifecycle.md +1 -1
  52. package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
  53. package/bundle/web-dist/client/assets/voice-COmvUTZO.js +0 -1
@@ -0,0 +1,435 @@
1
+ import { existsSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ import type * as Ort from "onnxruntime-node";
7
+
8
+ import { type CharTimestamps } from "./speech-alignment";
9
+
10
+ /**
11
+ * In-process forced alignment of a known script to its speech, used for OpenAI realtime speech and
12
+ * transcription, which carry no timing. The model is MMS-FA (Meta's CTC forced aligner, 1,130 languages,
13
+ * CC-BY-NC 4.0) quantized to int8 ONNX: it scores every 20 ms frame of 16 kHz audio against 28
14
+ * letters, and a Viterbi pass walks the script's letters through those scores in order.
15
+ *
16
+ * The model file and `onnxruntime-node` ship in the Docker image. Elsewhere `qgrid --install-aligner`
17
+ * puts the model at DEFAULT_MODEL_PATH (`QGRID_ALIGNER_MODEL` overrides it) and the runtime under
18
+ * RUNTIME_DIR; without them alignment throws and callers return the result without timing.
19
+ */
20
+
21
+ const SAMPLE_RATE = 16_000;
22
+ const SAMPLES_PER_FRAME = 320;
23
+ const BLANK = 0;
24
+
25
+ // Model output ids 4..30, in this order (vocab of the HF conversion of torchaudio MMS_FA).
26
+ const LETTERS = "aienoutsrmkldghybpwcvjzf'qx";
27
+ const LETTER_ID = new Map([...LETTERS].map((letter, i) => [letter, i + 4]));
28
+
29
+ // Extra emission column with log-probability 0: it matches any sound. Wrapped around the script it
30
+ // absorbs speech that is not in it (a spoken preamble); over digits and other unspellable text it
31
+ // takes however they were read (a penalty made long numbers push their neighbours away instead).
32
+ const STAR = 31;
33
+ const WINDOW_SAMPLES = 30 * SAMPLE_RATE;
34
+ const CONTEXT_SAMPLES = 2 * SAMPLE_RATE;
35
+ const IDLE_UNLOAD_MS = 10 * 60_000;
36
+
37
+ // Viterbi back-pointers take frames x (2 x tokens + 1) bytes. Frames and tokens both grow with the
38
+ // audio, so the table grows with its square: 100 MB fits about 4 minutes of dense English speech.
39
+ const MAX_TRELLIS_CELLS = 100_000_000;
40
+
41
+ // Keep both paths in sync with `qgrid --install-aligner` (packages/cli/src/aligner.ts).
42
+ const DEFAULT_MODEL_PATH = join(homedir(), ".cache", "qgrid", "models", "mms-300m-fa-int8.onnx");
43
+ const RUNTIME_DIR = join(homedir(), ".cache", "qgrid", "runtime");
44
+
45
+ export class SpeechAlignerUnavailableError extends Error {}
46
+
47
+ // Revised Romanization per syllable, without cross-syllable sound changes (enough for timing).
48
+ const INITIAL = "g kk n d tt r m b pp s ss _ j jj ch k t p h".split(" ");
49
+ const MEDIAL = "a ae ya yae eo e yeo ye o wa wae oe yo u wo we wi yu eu ui i".split(" ");
50
+ const FINAL = "_ k k k n n n t l k m l l l p l m p p t t ng t t k t p t".split(" ");
51
+ const syllable = (part: string) => (part === "_" ? "" : part);
52
+
53
+ function romanizeHangul(char: string): string | undefined {
54
+ const code = char.codePointAt(0)! - 0xac00;
55
+
56
+ if (code < 0 || code > 11171) return undefined;
57
+
58
+ return (
59
+ syllable(INITIAL[Math.floor(code / 588)]!) +
60
+ MEDIAL[Math.floor((code % 588) / 28)]! +
61
+ syllable(FINAL[code % 28]!)
62
+ );
63
+ }
64
+
65
+ /**
66
+ * The model letters a character is read as: "" when silent (spaces, punctuation), undefined when
67
+ * spoken but not spellable in the model's alphabet (digits, currency signs, other scripts).
68
+ */
69
+ function lettersOf(char: string): string | undefined {
70
+ const plain = char
71
+ .normalize("NFKD")
72
+ .replace(/\p{M}/gu, "")
73
+ .toLowerCase()
74
+ .replace(/[’‘ʼ]/g, "'");
75
+
76
+ if (plain !== "" && [...plain].every((letter) => LETTER_ID.has(letter))) return plain;
77
+ const hangul = romanizeHangul(char);
78
+
79
+ if (hangul !== undefined) return hangul;
80
+
81
+ // ponytail: other scripts fall back to the star; port uroman when they need letter-level timing.
82
+ return /[\p{L}\p{N}$€£¥%&@#+=]/u.test(char) ? undefined : "";
83
+ }
84
+
85
+ /** Model token ids for a script, with the characters (code point indices) each token covers. */
86
+ export function scriptTargets(chars: string[]) {
87
+ const ids: number[] = [];
88
+ const owners: number[][] = [];
89
+ // A run of unspellable characters inside one word ("21", "3:30") is a single star.
90
+ let starRun = false;
91
+
92
+ chars.forEach((char, i) => {
93
+ const letters = lettersOf(char);
94
+
95
+ if (letters === undefined) {
96
+ if (starRun) owners.at(-1)!.push(i);
97
+ else {
98
+ ids.push(STAR);
99
+ owners.push([i]);
100
+ }
101
+
102
+ starRun = true;
103
+
104
+ return;
105
+ }
106
+
107
+ if (letters !== "" || /\s/.test(char)) starRun = false;
108
+
109
+ for (const letter of letters) {
110
+ ids.push(LETTER_ID.get(letter)!);
111
+ owners.push([i]);
112
+ }
113
+ });
114
+
115
+ return { ids, owners };
116
+ }
117
+
118
+ /** Frame-wise log-softmax over the model classes plus the star column. */
119
+ function emissionRows(logits: Float32Array, frames: number, classes: number): Float64Array[] {
120
+ return Array.from({ length: frames }, (_, t) => {
121
+ const row = new Float64Array(classes + 1);
122
+ let max = -Infinity;
123
+
124
+ for (let c = 0; c < classes; c++) max = Math.max(max, logits[t * classes + c]!);
125
+ let sum = 0;
126
+
127
+ for (let c = 0; c < classes; c++) sum += Math.exp(logits[t * classes + c]! - max);
128
+ const logSum = max + Math.log(sum);
129
+
130
+ for (let c = 0; c < classes; c++) row[c] = logits[t * classes + c]! - logSum;
131
+ row[STAR] = 0;
132
+
133
+ return row;
134
+ });
135
+ }
136
+
137
+ function assertTrellisFits(frames: number, tokens: number): void {
138
+ const states = 2 * tokens + 1;
139
+
140
+ if (frames * states <= MAX_TRELLIS_CELLS) return;
141
+ const limitSec = Math.floor((MAX_TRELLIS_CELLS / states) * (SAMPLES_PER_FRAME / SAMPLE_RATE));
142
+
143
+ throw new Error(
144
+ `speech is too long to align: this script can be timed in up to ${limitSec} s of audio`,
145
+ );
146
+ }
147
+
148
+ /** CTC Viterbi forced alignment: the [startFrame, endFrame) span of each target token. */
149
+ export function forcedAlign(emissions: Float64Array[], targets: number[]): Array<[number, number]> {
150
+ const frames = emissions.length;
151
+ const states = 2 * targets.length + 1;
152
+
153
+ if (frames < targets.length) throw new Error("speech is too short for its script");
154
+ assertTrellisFits(frames, targets.length);
155
+
156
+ const label = (s: number) => (s % 2 === 0 ? BLANK : targets[(s - 1) / 2]!);
157
+ const back = new Uint8Array(frames * states);
158
+ let previous = new Float64Array(states).fill(-Infinity);
159
+
160
+ previous[0] = emissions[0]![BLANK]!;
161
+ previous[1] = emissions[0]![label(1)]!;
162
+
163
+ for (let t = 1; t < frames; t++) {
164
+ const current = new Float64Array(states).fill(-Infinity);
165
+
166
+ for (let s = 0; s < states; s++) {
167
+ let best = previous[s]!;
168
+ let step = 0;
169
+
170
+ if (s >= 1 && previous[s - 1]! > best) [best, step] = [previous[s - 1]!, 1];
171
+
172
+ // Skipping the blank between two tokens is allowed unless they repeat the same label.
173
+ if (s >= 2 && s % 2 === 1 && label(s) !== label(s - 2) && previous[s - 2]! > best) {
174
+ [best, step] = [previous[s - 2]!, 2];
175
+ }
176
+
177
+ if (best === -Infinity) continue;
178
+ current[s] = best + emissions[t]![label(s)]!;
179
+ back[t * states + s] = step;
180
+ }
181
+
182
+ previous = current;
183
+ }
184
+
185
+ let s = previous[states - 1]! >= previous[states - 2]! ? states - 1 : states - 2;
186
+ const spans = targets.map((): [number, number] => [Infinity, -Infinity]);
187
+
188
+ for (let t = frames - 1; t >= 0; t--) {
189
+ if (s % 2 === 1) {
190
+ const span = spans[(s - 1) / 2]!;
191
+ span[0] = Math.min(span[0], t);
192
+ span[1] = Math.max(span[1], t + 1);
193
+ }
194
+
195
+ s -= back[t * states + s]!;
196
+ }
197
+
198
+ return spans;
199
+ }
200
+
201
+ const seconds = (value: number) => Math.round(value * 1000) / 1000;
202
+
203
+ /**
204
+ * Per-character timing from token spans: a star's span is split evenly over its characters; inside
205
+ * a word each timed character runs until the next one starts, untimed characters (punctuation)
206
+ * take zero length after the previous one, and whitespace takes the pause between words.
207
+ */
208
+ export function charTimestamps(
209
+ chars: string[],
210
+ owners: number[][],
211
+ spans: Array<[number, number]>,
212
+ secondsPerFrame: number,
213
+ durationSec: number,
214
+ ): CharTimestamps {
215
+ const timed: Array<[number, number] | undefined> = chars.map(() => undefined);
216
+
217
+ spans.forEach(([start, end], k) => {
218
+ const covered = owners[k]!;
219
+ const width = (end - start) / covered.length;
220
+
221
+ covered.forEach((i, n) => {
222
+ const part: [number, number] = [start + width * n, start + width * (n + 1)];
223
+ const previous = timed[i];
224
+ timed[i] = previous ? [Math.min(previous[0], part[0]), Math.max(previous[1], part[1])] : part;
225
+ });
226
+ });
227
+
228
+ const graphTimes: Array<[number, number]> = chars.map(() => [0, 0]);
229
+ let wordEnd = 0;
230
+
231
+ for (let i = 0; i < chars.length;) {
232
+ if (/\s/.test(chars[i]!)) {
233
+ let j = i;
234
+
235
+ while (j < chars.length && /\s/.test(chars[j]!)) j++;
236
+ const next = timed.slice(j).find(Boolean);
237
+ const nextStart = next ? next[0] * secondsPerFrame : durationSec;
238
+
239
+ for (let k = i; k < j; k++)
240
+ graphTimes[k] = [seconds(wordEnd), seconds(Math.max(wordEnd, nextStart))];
241
+ i = j;
242
+ continue;
243
+ }
244
+
245
+ let j = i;
246
+
247
+ while (j < chars.length && !/\s/.test(chars[j]!)) j++;
248
+ const word = Array.from({ length: j - i }, (_, n) => i + n);
249
+ const timedInWord = word.filter((k) => timed[k]);
250
+ let cursor = timedInWord.length > 0 ? timed[timedInWord[0]!]![0] * secondsPerFrame : wordEnd;
251
+
252
+ for (const k of word) {
253
+ const span = timed[k];
254
+
255
+ if (!span) {
256
+ graphTimes[k] = [seconds(cursor), seconds(cursor)];
257
+ continue;
258
+ }
259
+
260
+ const nextTimed = timedInWord[timedInWord.indexOf(k) + 1];
261
+ const end = (nextTimed === undefined ? span[1] : timed[nextTimed]![0]) * secondsPerFrame;
262
+ graphTimes[k] = [seconds(span[0] * secondsPerFrame), seconds(end)];
263
+ cursor = end;
264
+ }
265
+
266
+ wordEnd = cursor;
267
+ i = j;
268
+ }
269
+
270
+ return { graphChars: chars, graphTimes };
271
+ }
272
+
273
+ /** PCM16 little-endian mono at `sampleRate` to 16 kHz float samples (linear interpolation). */
274
+ function to16kFloat(pcm: Uint8Array, sampleRate: number): Float32Array {
275
+ const view = new DataView(pcm.buffer, pcm.byteOffset, pcm.byteLength);
276
+ const inputLength = Math.floor(pcm.byteLength / 2);
277
+ const ratio = sampleRate / SAMPLE_RATE;
278
+ const output = new Float32Array(Math.floor(inputLength / ratio));
279
+
280
+ for (let i = 0; i < output.length; i++) {
281
+ const position = i * ratio;
282
+ const left = Math.floor(position);
283
+ const right = Math.min(left + 1, inputLength - 1);
284
+ const a = view.getInt16(left * 2, true);
285
+ const b = view.getInt16(right * 2, true);
286
+ output[i] = (a + (b - a) * (position - left)) / 32768;
287
+ }
288
+
289
+ return output;
290
+ }
291
+
292
+ function normalized(samples: Float32Array): Float32Array {
293
+ const mean = samples.reduce((sum, x) => sum + x, 0) / samples.length;
294
+ const variance = samples.reduce((sum, x) => sum + (x - mean) ** 2, 0) / samples.length;
295
+ const std = Math.sqrt(variance) || 1;
296
+
297
+ return samples.map((x) => (x - mean) / std);
298
+ }
299
+
300
+ interface LoadedModel {
301
+ ort: typeof Ort;
302
+ session: Ort.InferenceSession;
303
+ }
304
+
305
+ let model: Promise<LoadedModel> | undefined;
306
+ let inFlight = 0;
307
+ let idleTimer: NodeJS.Timeout | undefined;
308
+
309
+ /** Loads the session on first use; it is released after IDLE_UNLOAD_MS without requests. */
310
+ async function loadModel(): Promise<LoadedModel> {
311
+ const path = process.env.QGRID_ALIGNER_MODEL || DEFAULT_MODEL_PATH;
312
+
313
+ if (!existsSync(path)) {
314
+ throw new SpeechAlignerUnavailableError(
315
+ `speech aligner model not found at ${path} (run \`qgrid --install-aligner\` or set QGRID_ALIGNER_MODEL)`,
316
+ );
317
+ }
318
+
319
+ model ??= openModel(path);
320
+
321
+ try {
322
+ return await model;
323
+ } catch (error) {
324
+ model = undefined;
325
+ throw error;
326
+ }
327
+ }
328
+
329
+ async function openModel(path: string): Promise<LoadedModel> {
330
+ const ort = await loadRuntime();
331
+
332
+ return { ort, session: await ort.InferenceSession.create(path) };
333
+ }
334
+
335
+ /** The installed onnxruntime-node package, else the copy `qgrid --install-aligner` unpacked. */
336
+ async function loadRuntime(): Promise<typeof Ort> {
337
+ let failure: unknown;
338
+
339
+ try {
340
+ return await import("onnxruntime-node");
341
+ } catch (error) {
342
+ failure = error;
343
+ }
344
+
345
+ try {
346
+ if (existsSync(join(RUNTIME_DIR, "node_modules", "onnxruntime-node"))) {
347
+ // SAFETY: the same pinned onnxruntime-node package, loaded from qgrid's runtime folder.
348
+ return createRequire(join(RUNTIME_DIR, "index.js"))("onnxruntime-node") as typeof Ort;
349
+ }
350
+ } catch (error) {
351
+ failure = error;
352
+ }
353
+
354
+ const reason = failure instanceof Error ? failure.message : String(failure);
355
+
356
+ throw new SpeechAlignerUnavailableError(
357
+ `speech aligner runtime onnxruntime-node failed to load: ${reason} (run \`qgrid --install-aligner\`)`,
358
+ );
359
+ }
360
+
361
+ function scheduleUnload(): void {
362
+ clearTimeout(idleTimer);
363
+ idleTimer = setTimeout(() => {
364
+ if (inFlight > 0 || !model) return;
365
+ const releasing = model;
366
+ model = undefined;
367
+ void releasing.then(({ session }) => session.release()).catch(() => undefined);
368
+ }, IDLE_UNLOAD_MS);
369
+ idleTimer.unref();
370
+ }
371
+
372
+ /** Model emissions for the whole clip, computed in 30 s windows with 2 s of context per side. */
373
+ async function emissionsFor(loaded: LoadedModel, samples: Float32Array): Promise<Float64Array[]> {
374
+ const rows: Float64Array[] = [];
375
+
376
+ for (let start = 0; start < samples.length; start += WINDOW_SAMPLES) {
377
+ const from = Math.max(0, start - CONTEXT_SAMPLES);
378
+ const to = Math.min(samples.length, start + WINDOW_SAMPLES + CONTEXT_SAMPLES);
379
+ const chunk = normalized(samples.subarray(from, to));
380
+
381
+ const output = await loaded.session.run({
382
+ input_values: new loaded.ort.Tensor("float32", chunk, [1, chunk.length]),
383
+ });
384
+
385
+ const logits = output.logits!;
386
+ // SAFETY: the MMS-FA export emits `logits` as float32 [batch, frames, classes].
387
+ const [, frames, classes] = logits.dims as [number, number, number];
388
+ const skip = (start - from) / SAMPLES_PER_FRAME;
389
+ const keep = Math.ceil(Math.min(WINDOW_SAMPLES, samples.length - start) / SAMPLES_PER_FRAME);
390
+ // SAFETY: float32 tensors expose their data as Float32Array.
391
+ const windowRows = emissionRows(logits.data as Float32Array, frames, classes);
392
+
393
+ rows.push(...windowRows.slice(skip, skip + keep));
394
+ }
395
+
396
+ return rows;
397
+ }
398
+
399
+ /**
400
+ * Per-character timing of `script` in PCM16 mono speech. Throws SpeechAlignerUnavailableError when
401
+ * the model or runtime is missing, and Error when the script has nothing to align or the audio is
402
+ * too short or too long.
403
+ */
404
+ export async function alignSpeech(
405
+ pcm: Uint8Array,
406
+ sampleRate: number,
407
+ script: string,
408
+ ): Promise<CharTimestamps> {
409
+ const chars = Array.from(script);
410
+ const { ids, owners } = scriptTargets(chars);
411
+
412
+ if (!ids.some((id) => id !== STAR)) throw new Error("script has no letters to align");
413
+ // Edge stars, unless the script already starts or ends with one (repeated labels need a blank).
414
+ const lead = ids[0] === STAR ? [] : [STAR];
415
+ const tail = ids.at(-1) === STAR ? [] : [STAR];
416
+ const targets = [...lead, ...ids, ...tail];
417
+ const durationSec = pcm.byteLength / 2 / sampleRate;
418
+ // Rejected before the model runs: emissions for a long clip take seconds of CPU.
419
+ assertTrellisFits(Math.ceil((durationSec * SAMPLE_RATE) / SAMPLES_PER_FRAME), targets.length);
420
+ // Counted before the model is awaited, so the idle unload cannot release it under this request.
421
+ inFlight++;
422
+
423
+ try {
424
+ const loaded = await loadModel();
425
+ const samples = to16kFloat(pcm, sampleRate);
426
+ const emissions = await emissionsFor(loaded, samples);
427
+ const secondsPerFrame = samples.length / SAMPLE_RATE / emissions.length;
428
+ const spans = forcedAlign(emissions, targets).slice(lead.length, lead.length + ids.length);
429
+
430
+ return charTimestamps(chars, owners, spans, secondsPerFrame, durationSec);
431
+ } finally {
432
+ inFlight--;
433
+ scheduleUnload();
434
+ }
435
+ }
@@ -1,56 +1,8 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
 
3
- import { alignScriptToWords, wordsFromCharTimestamps } from "./speech-alignment";
4
-
5
- const spanOf = (alignment: ReturnType<typeof alignScriptToWords>, script: string, word: string) => {
6
- const from = script.indexOf(word);
7
- const times = alignment.audioTimestamps.graphTimes;
8
-
9
- return [times[from]![0], times[from + word.length - 1]![1]];
10
- };
11
-
12
- describe("alignScriptToWords", () => {
13
- it("spreads each heard word over its characters and gives spaces the pause", () => {
14
- const script = "Hi there.";
15
- const result = alignScriptToWords(
16
- script,
17
- [
18
- { text: "Hi", start: 0.1, end: 0.3 },
19
- { text: "there", start: 0.5, end: 1.0 },
20
- ],
21
- 1.2,
22
- );
23
-
24
- expect(result.matchedWords).toBe(2);
25
- expect(result.audioTimestamps.graphChars.join("")).toBe(script);
26
- expect(result.audioTimestamps.graphTimes[0]).toEqual([0.1, 0.2]);
27
- expect(result.audioTimestamps.graphTimes[2]).toEqual([0.3, 0.5]); // the space
28
- expect(spanOf(result, script, "there.")).toEqual([0.5, 1.0]);
29
- });
30
-
31
- it("skips a spoken preamble, keeps a mis-heard name in place, and fills a dropped word", () => {
32
- const script = "I'm Carina. Nice to meet you.";
33
- const heard = [
34
- { text: "Okay,", start: 0.0, end: 0.3 },
35
- { text: "let's", start: 0.3, end: 0.5 },
36
- { text: "read", start: 0.5, end: 0.7 },
37
- { text: "I'm", start: 1.0, end: 1.2 },
38
- { text: "Karina,", start: 1.2, end: 1.7 },
39
- { text: "nice", start: 2.0, end: 2.3 },
40
- { text: "meet", start: 2.5, end: 2.8 },
41
- { text: "you.", start: 2.8, end: 3.1 },
42
- ];
43
-
44
- const result = alignScriptToWords(script, heard, 3.3);
45
-
46
- expect(result).toMatchObject({ matchedWords: 4, scriptWords: 6 });
47
- expect(spanOf(result, script, "I'm")).toEqual([1.0, 1.2]);
48
- expect(spanOf(result, script, "Carina.")).toEqual([1.2, 1.7]);
49
- // "to" was not heard: it takes the gap between "nice" and "meet".
50
- expect(spanOf(result, script, "to")).toEqual([2.3, 2.5]);
51
- expect(spanOf(result, script, "you.")).toEqual([2.8, 3.1]);
52
- });
3
+ import { wordsFromCharTimestamps } from "./speech-alignment";
53
4
 
5
+ describe("wordsFromCharTimestamps", () => {
54
6
  it("groups per-character timing into words spanning first to last character", () => {
55
7
  expect(
56
8
  wordsFromCharTimestamps({
@@ -1,4 +1,4 @@
1
- /** A word an STT model heard, with its time span in seconds. */
1
+ /** A word with its time span in seconds. */
2
2
  export interface TimedWord {
3
3
  text: string;
4
4
  start: number;
@@ -11,146 +11,6 @@ export interface CharTimestamps {
11
11
  graphTimes: Array<[number, number]>;
12
12
  }
13
13
 
14
- const normalize = (word: string) =>
15
- word
16
- .normalize("NFKC")
17
- .toLowerCase()
18
- .replace(/[^\p{L}\p{N}']/gu, "");
19
-
20
- /**
21
- * Infers per-character timing for a known script from the words an STT model heard in its audio.
22
- * Script and heard words are paired by an edit-distance alignment, so a mis-heard word (a name
23
- * spelled differently, a number written out) still takes the time of the word in its place, and
24
- * extra heard words (a spoken preamble) are skipped. Script words left unpaired get the gap
25
- * between their neighbours; each word's span is split over its characters by position, and the
26
- * whitespace between words takes the pause between them. `durationSec` bounds leading and
27
- * trailing gaps. `matchedWords` counts script words heard exactly (after normalization).
28
- */
29
- export function alignScriptToWords(script: string, words: TimedWord[], durationSec: number) {
30
- const tokens = [...script.matchAll(/\S+/g)].map((m) => ({
31
- from: m.index,
32
- to: m.index + m[0].length,
33
- norm: normalize(m[0]),
34
- }));
35
-
36
- const heard = words.flatMap((w) => {
37
- const norm = normalize(w.text);
38
-
39
- return norm === "" ? [] : [{ ...w, norm }];
40
- });
41
-
42
- const n = tokens.length;
43
- const m = heard.length;
44
- const width = m + 1;
45
- const cost = new Uint32Array((n + 1) * width);
46
-
47
- for (let i = 0; i <= n; i++) cost[i * width] = i;
48
-
49
- for (let j = 0; j <= m; j++) cost[j] = j;
50
-
51
- for (let i = 1; i <= n; i++) {
52
- for (let j = 1; j <= m; j++) {
53
- const same = tokens[i - 1]!.norm === heard[j - 1]!.norm;
54
-
55
- cost[i * width + j] = Math.min(
56
- cost[(i - 1) * width + (j - 1)]! + (same ? 0 : 1),
57
- cost[(i - 1) * width + j]! + 1,
58
- cost[i * width + (j - 1)]! + 1,
59
- );
60
- }
61
- }
62
-
63
- // Walk back from the corner; prefer pairing over skipping so each script word keeps a time.
64
- const spans: Array<[number, number] | undefined> = Array.from({ length: n });
65
- let matchedWords = 0;
66
-
67
- for (let i = n, j = m; i > 0 || j > 0;) {
68
- const here = cost[i * width + j]!;
69
- const same = i > 0 && j > 0 && tokens[i - 1]!.norm === heard[j - 1]!.norm;
70
-
71
- if (i > 0 && j > 0 && here === cost[(i - 1) * width + (j - 1)]! + (same ? 0 : 1)) {
72
- spans[i - 1] = [heard[j - 1]!.start, heard[j - 1]!.end];
73
-
74
- if (same) matchedWords++;
75
- i--;
76
- j--;
77
- } else if (i > 0 && here === cost[(i - 1) * width + j]! + 1) {
78
- i--; // script word not heard: filled from its neighbours below
79
- } else {
80
- j--; // extra heard word (e.g. a spoken preamble): skipped
81
- }
82
- }
83
-
84
- fillGaps(spans, tokens, durationSec);
85
-
86
- // Each character of a word takes its share of the word's span; characters between words (spaces)
87
- // take the pause from the previous word's end to the next word's start.
88
- const graphChars: string[] = [];
89
- const graphTimes: Array<[number, number]> = [];
90
- let token = 0;
91
- let previousEnd = 0;
92
-
93
- for (let c = 0; c < script.length;) {
94
- const char = String.fromCodePoint(script.codePointAt(c)!);
95
-
96
- while (token < n && tokens[token]!.to <= c) token++;
97
- const current = tokens[token];
98
-
99
- if (current && current.from <= c) {
100
- const [start, end] = spans[token]!;
101
- const length = current.to - current.from;
102
- const offset = c - current.from;
103
-
104
- const span: [number, number] = [
105
- start + ((end - start) * offset) / length,
106
- start + ((end - start) * (offset + char.length)) / length,
107
- ];
108
-
109
- graphTimes.push(span);
110
- previousEnd = span[1];
111
- } else {
112
- const nextStart = current ? spans[token]![0] : durationSec;
113
- graphTimes.push([previousEnd, Math.max(previousEnd, nextStart)]);
114
- }
115
-
116
- graphChars.push(char);
117
- c += char.length;
118
- }
119
-
120
- return { audioTimestamps: { graphChars, graphTimes }, matchedWords, scriptWords: n };
121
- }
122
-
123
- /** Gives unpaired script words a slice of the gap between paired neighbours, by length. */
124
- function fillGaps(
125
- spans: Array<[number, number] | undefined>,
126
- tokens: Array<{ from: number; to: number }>,
127
- durationSec: number,
128
- ): void {
129
- for (let k = 0; k < spans.length;) {
130
- if (spans[k]) {
131
- k++;
132
- continue;
133
- }
134
-
135
- let last = k;
136
-
137
- while (last + 1 < spans.length && !spans[last + 1]) last++;
138
- const gapStart = k > 0 ? spans[k - 1]![1] : 0;
139
- const gapEnd = last + 1 < spans.length ? spans[last + 1]![0] : durationSec;
140
- const lengths = tokens.slice(k, last + 1).map((t) => t.to - t.from);
141
- const total = lengths.reduce((sum, length) => sum + length, 0);
142
- let cursor = gapStart;
143
-
144
- lengths.forEach((length, offset) => {
145
- const width = ((gapEnd - gapStart) * length) / total;
146
- spans[k + offset] = [cursor, cursor + width];
147
- cursor += width;
148
- });
149
-
150
- k = last + 1;
151
- }
152
- }
153
-
154
14
  /** Words from per-character timing: each run of non-space characters, spanning its first to last. */
155
15
  export function wordsFromCharTimestamps(timestamps: CharTimestamps): TimedWord[] {
156
16
  const words: TimedWord[] = [];