@cartanova/qgrid-cli 2.15.5 → 2.17.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.
- package/bundle/dist/application/qgrid/qgrid.frame.js +73 -15
- package/bundle/dist/application/qgrid/qgrid.types.js +17 -3
- package/bundle/dist/utils/providers/grok/grok-types.js +10 -3
- package/bundle/dist/utils/providers/grok/grok-voice-client.js +35 -2
- package/bundle/dist/utils/speech-alignment.js +129 -0
- package/bundle/src/application/qgrid/qgrid.frame.test.ts +76 -1
- package/bundle/src/application/qgrid/qgrid.frame.ts +92 -16
- package/bundle/src/application/qgrid/qgrid.types.ts +27 -0
- package/bundle/src/application/sonamu.generated.http +3 -1
- package/bundle/src/utils/providers/grok/grok-types.ts +19 -0
- package/bundle/src/utils/providers/grok/grok-voice-client.test.ts +30 -0
- package/bundle/src/utils/providers/grok/grok-voice-client.ts +54 -0
- package/bundle/src/utils/speech-alignment.test.ts +72 -0
- package/bundle/src/utils/speech-alignment.ts +178 -0
- package/bundle/web-dist/client/assets/TimedPlayer-cuEgYA3Q.js +1 -0
- package/bundle/web-dist/client/assets/{index-Wi8Wxte6.js → index-Cb14ZYfq.js} +3 -3
- package/bundle/web-dist/client/assets/index-Co8uAhSV.css +1 -0
- package/bundle/web-dist/client/assets/{logs-Bdg3wJV2.js → logs-CSL1j0RN.js} +1 -1
- package/bundle/web-dist/client/assets/{monit-DcwHRAKu.js → monit-J69xfniH.js} +1 -1
- package/bundle/web-dist/client/assets/{routes-lxVC1DDJ.js → routes-CdWdhivH.js} +1 -1
- package/bundle/web-dist/client/assets/{settings-C0VCdd1C.js → settings-BGa41_nL.js} +1 -1
- package/bundle/web-dist/client/assets/show-CSpPVL8-.js +2 -0
- package/bundle/web-dist/client/assets/{tokens-CNRSm9sc.js → tokens-B9FeVPJk.js} +1 -1
- package/bundle/web-dist/client/assets/{use-oauth-login-flow-eQnMzp8A.js → use-oauth-login-flow-Tmy4lKYv.js} +1 -1
- package/bundle/web-dist/client/assets/{use-update-token-mutation-KnwyYQjb.js → use-update-token-mutation-CGwI6TU8.js} +1 -1
- package/bundle/web-dist/client/assets/voice-BNcGUdUd.js +1 -0
- package/bundle/web-dist/client/index.html +2 -2
- package/bundle/web-dist/server/assets/TimedPlayer-DAwjkP4z.js +54 -0
- package/bundle/web-dist/server/assets/{show-D8r2sVK0.js → show-hBbPOUZD.js} +41 -6
- package/bundle/web-dist/server/assets/{voice-C2HfwkGp.js → voice-CHoPEIfo.js} +76 -68
- package/bundle/web-dist/server/entry-server.generated.js +3 -3
- package/package.json +1 -1
- package/skills/qgrid/references/ai-sdk-provider-contract.md +2 -0
- package/skills/qgrid/references/grok-runtime.md +6 -0
- package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
- package/bundle/web-dist/client/assets/index-DyrPRt6O.css +0 -1
- package/bundle/web-dist/client/assets/show-B7QRPxsY.js +0 -2
- package/bundle/web-dist/client/assets/voice-BydIuS0A.js +0 -1
|
@@ -530,6 +530,12 @@ export const TranscribeInput = z.object({
|
|
|
530
530
|
|
|
531
531
|
export type TranscribeInput = z.infer<typeof TranscribeInput>;
|
|
532
532
|
|
|
533
|
+
const TranscribedWord = z.object({
|
|
534
|
+
text: z.string(),
|
|
535
|
+
start: z.number(),
|
|
536
|
+
end: z.number(),
|
|
537
|
+
});
|
|
538
|
+
|
|
533
539
|
export const TranscribeOutput = z.object({
|
|
534
540
|
text: z.string(),
|
|
535
541
|
language: z.string().optional(),
|
|
@@ -537,6 +543,9 @@ export const TranscribeOutput = z.object({
|
|
|
537
543
|
model: z.string(),
|
|
538
544
|
tokenName: z.string(),
|
|
539
545
|
requestLogId: z.number().optional(),
|
|
546
|
+
// Grok only: each heard word with its [start, end] seconds. OpenAI realtime transcription
|
|
547
|
+
// reports no timing.
|
|
548
|
+
words: z.array(TranscribedWord).optional(),
|
|
540
549
|
});
|
|
541
550
|
|
|
542
551
|
export type TranscribeOutput = z.infer<typeof TranscribeOutput>;
|
|
@@ -549,6 +558,10 @@ export const SpeakInput = z.object({
|
|
|
549
558
|
format: z.enum(["mp3", "wav", "pcm", "mulaw", "alaw"]).optional(),
|
|
550
559
|
// OpenAI realtime speech only: style guidance appended to the verbatim-repeat instruction.
|
|
551
560
|
instructions: z.string().min(1).max(2_000).optional(),
|
|
561
|
+
// Per-character timing in the output (`audioTimestamps`). Grok returns it natively; for OpenAI
|
|
562
|
+
// realtime (no timing data) qgrid transcribes the generated audio with Grok STT and aligns the
|
|
563
|
+
// heard words to the text (`timestampsSource: "aligned"`).
|
|
564
|
+
withTimestamps: z.boolean().optional(),
|
|
552
565
|
...MediaCallOptions,
|
|
553
566
|
});
|
|
554
567
|
|
|
@@ -560,6 +573,20 @@ export const SpeakOutput = z.object({
|
|
|
560
573
|
mimeType: z.string(),
|
|
561
574
|
tokenName: z.string(),
|
|
562
575
|
requestLogId: z.number().optional(),
|
|
576
|
+
// Only with `withTimestamps`: input characters (spaces, punctuation, tags included) and the
|
|
577
|
+
// `[start, end]` seconds of each, index-aligned; named as @ai-sdk/xai exposes them.
|
|
578
|
+
audioTimestamps: z
|
|
579
|
+
.object({
|
|
580
|
+
graphChars: z.array(z.string()),
|
|
581
|
+
graphTimes: z.array(z.tuple([z.number(), z.number()])),
|
|
582
|
+
})
|
|
583
|
+
.optional(),
|
|
584
|
+
durationSec: z.number().optional(),
|
|
585
|
+
// "provider" when the TTS provider timed the audio itself, "aligned" when qgrid inferred it from
|
|
586
|
+
// Grok STT word timing.
|
|
587
|
+
timestampsSource: z.enum(["provider", "aligned"]).optional(),
|
|
588
|
+
// Set when timestamps were requested but could not be produced; the audio is still returned.
|
|
589
|
+
timestampsError: z.string().optional(),
|
|
563
590
|
});
|
|
564
591
|
|
|
565
592
|
export type SpeakOutput = z.infer<typeof SpeakOutput>;
|
|
@@ -236,7 +236,8 @@ Content-Type: application/json
|
|
|
236
236
|
"response_json_ok": null,
|
|
237
237
|
"tool_call_count": 0,
|
|
238
238
|
"is_image_generation": false,
|
|
239
|
-
"is_structured": false
|
|
239
|
+
"is_structured": false,
|
|
240
|
+
"media_kind": null
|
|
240
241
|
}
|
|
241
242
|
]
|
|
242
243
|
}
|
|
@@ -722,6 +723,7 @@ Content-Type: application/json
|
|
|
722
723
|
"language": "LANGUAGE",
|
|
723
724
|
"format": "mp3",
|
|
724
725
|
"instructions": "INSTRUCTIONS",
|
|
726
|
+
"withTimestamps": false,
|
|
725
727
|
"tokenName": "TOKENNAME",
|
|
726
728
|
"projectName": "PROJECTNAME",
|
|
727
729
|
"logger": false
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
|
|
3
|
+
import { type CharTimestamps } from "../../speech-alignment";
|
|
3
4
|
import { type JsonValue } from "../common/provider-types";
|
|
4
5
|
import { GROK_AUTH_ISSUER } from "./grok-constants";
|
|
5
6
|
|
|
@@ -274,6 +275,18 @@ export const GrokSttResponse = z.looseObject({
|
|
|
274
275
|
text: z.string(),
|
|
275
276
|
language: z.string().optional(),
|
|
276
277
|
duration: z.number().nonnegative().optional(),
|
|
278
|
+
// Word-level timing, sent by default (verified on the subscription token 2026-11-09); `speaker`
|
|
279
|
+
// only with diarize.
|
|
280
|
+
words: z
|
|
281
|
+
.array(
|
|
282
|
+
z.looseObject({
|
|
283
|
+
text: z.string(),
|
|
284
|
+
start: z.number(),
|
|
285
|
+
end: z.number(),
|
|
286
|
+
speaker: z.number().optional(),
|
|
287
|
+
}),
|
|
288
|
+
)
|
|
289
|
+
.optional(),
|
|
277
290
|
});
|
|
278
291
|
|
|
279
292
|
export type GrokSttResponse = z.infer<typeof GrokSttResponse>;
|
|
@@ -284,6 +297,9 @@ export const GrokTtsRequest = z.object({
|
|
|
284
297
|
voice: z.string().min(1),
|
|
285
298
|
language: z.string().min(1),
|
|
286
299
|
format: z.string().min(1),
|
|
300
|
+
// true switches /tts to a JSON envelope with per-character timing (verified on the subscription
|
|
301
|
+
// token 2026-11-09).
|
|
302
|
+
with_timestamps: z.boolean().optional(),
|
|
287
303
|
});
|
|
288
304
|
|
|
289
305
|
export type GrokTtsRequest = z.infer<typeof GrokTtsRequest>;
|
|
@@ -364,6 +380,9 @@ export interface GrokTranscribeRequest {
|
|
|
364
380
|
export interface GrokSpeechResult {
|
|
365
381
|
audio: Uint8Array;
|
|
366
382
|
mediaType: string;
|
|
383
|
+
/** Only with `with_timestamps`; named as `@ai-sdk/xai` exposes it. */
|
|
384
|
+
audioTimestamps?: CharTimestamps;
|
|
385
|
+
durationSec?: number;
|
|
367
386
|
/** Epoch ms when the response headers arrived; /tts is not streamed, so this is first byte. */
|
|
368
387
|
firstByteAt?: number;
|
|
369
388
|
}
|
|
@@ -228,6 +228,36 @@ describe("GrokVoiceClient.speak", () => {
|
|
|
228
228
|
});
|
|
229
229
|
});
|
|
230
230
|
|
|
231
|
+
it("asks for timestamps and decodes the JSON envelope into audio plus character timing", async () => {
|
|
232
|
+
const fake = fakeFetch(
|
|
233
|
+
() =>
|
|
234
|
+
new Response(
|
|
235
|
+
JSON.stringify({
|
|
236
|
+
audio: Buffer.from(mp3).toString("base64"),
|
|
237
|
+
content_type: "audio/mpeg",
|
|
238
|
+
duration: 0.5,
|
|
239
|
+
audio_timestamps: { graph_chars: ["H", "i"], graph_times: [[0.08, 0.2], [0.2, 0.5]] },
|
|
240
|
+
}),
|
|
241
|
+
{ status: 200, headers: { "content-type": "application/json" } },
|
|
242
|
+
),
|
|
243
|
+
);
|
|
244
|
+
const client = new GrokVoiceClient({ fetch: fake.impl });
|
|
245
|
+
const result = await client.speak("tok", { text: "Hi", with_timestamps: true });
|
|
246
|
+
|
|
247
|
+
const body = fake.calls[0]!.init.body;
|
|
248
|
+
expect(typeof body === "string" && JSON.parse(body)).toMatchObject({ with_timestamps: true });
|
|
249
|
+
expect(result.audio).toEqual(mp3);
|
|
250
|
+
expect(result.mediaType).toBe("audio/mpeg");
|
|
251
|
+
expect(result.durationSec).toBe(0.5);
|
|
252
|
+
expect(result.audioTimestamps).toEqual({
|
|
253
|
+
graphChars: ["H", "i"],
|
|
254
|
+
graphTimes: [
|
|
255
|
+
[0.08, 0.2],
|
|
256
|
+
[0.2, 0.5],
|
|
257
|
+
],
|
|
258
|
+
});
|
|
259
|
+
});
|
|
260
|
+
|
|
231
261
|
it("falls back to the format's media type when content-type is missing", async () => {
|
|
232
262
|
const client = new GrokVoiceClient({
|
|
233
263
|
fetch: fakeFetch(() => {
|
|
@@ -118,6 +118,19 @@ function transportError(message: string, afterSend: boolean, cause: unknown): Gr
|
|
|
118
118
|
return new GrokHttpError(classification, "", {}, { cause });
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
+
// `with_timestamps: true` envelope; optional fields nullable like @ai-sdk/xai's parser.
|
|
122
|
+
const GrokTtsTimestampsResponse = z.object({
|
|
123
|
+
audio: z.string(),
|
|
124
|
+
content_type: z.string().nullish(),
|
|
125
|
+
duration: z.number().nullish(),
|
|
126
|
+
audio_timestamps: z
|
|
127
|
+
.object({
|
|
128
|
+
graph_chars: z.array(z.string()),
|
|
129
|
+
graph_times: z.array(z.tuple([z.number(), z.number()])),
|
|
130
|
+
})
|
|
131
|
+
.nullish(),
|
|
132
|
+
});
|
|
133
|
+
|
|
121
134
|
function invalidBodyError(response: Response, message: string, cause?: unknown): GrokHttpError {
|
|
122
135
|
return new GrokHttpError(
|
|
123
136
|
{ ...classifyGrokHttpError(502, "", response.headers), message, shouldRetry: false },
|
|
@@ -127,6 +140,44 @@ function invalidBodyError(response: Response, message: string, cause?: unknown):
|
|
|
127
140
|
);
|
|
128
141
|
}
|
|
129
142
|
|
|
143
|
+
/** Decodes the `with_timestamps` JSON envelope into audio bytes plus per-character timing. */
|
|
144
|
+
async function readTimestampsBody(
|
|
145
|
+
response: Response,
|
|
146
|
+
format: string,
|
|
147
|
+
firstByteAt: number,
|
|
148
|
+
): Promise<GrokSpeechResult> {
|
|
149
|
+
let parsed: z.infer<typeof GrokTtsTimestampsResponse>;
|
|
150
|
+
|
|
151
|
+
try {
|
|
152
|
+
parsed = GrokTtsTimestampsResponse.parse(await response.json());
|
|
153
|
+
} catch (error) {
|
|
154
|
+
throw invalidBodyError(response, "invalid timestamped TTS response", error);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const audio = new Uint8Array(Buffer.from(parsed.audio, "base64"));
|
|
158
|
+
|
|
159
|
+
if (audio.byteLength === 0) throw invalidBodyError(response, "empty audio body");
|
|
160
|
+
|
|
161
|
+
const result: GrokSpeechResult = {
|
|
162
|
+
audio,
|
|
163
|
+
mediaType:
|
|
164
|
+
parsed.content_type ?? MEDIA_TYPE_BY_FORMAT.get(format) ?? "application/octet-stream",
|
|
165
|
+
firstByteAt,
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
if (parsed.audio_timestamps) {
|
|
169
|
+
result.audioTimestamps = {
|
|
170
|
+
graphChars: parsed.audio_timestamps.graph_chars,
|
|
171
|
+
graphTimes: parsed.audio_timestamps.graph_times,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if (parsed.duration !== null && parsed.duration !== undefined)
|
|
176
|
+
result.durationSec = parsed.duration;
|
|
177
|
+
|
|
178
|
+
return result;
|
|
179
|
+
}
|
|
180
|
+
|
|
130
181
|
function audioExtension(mediaType: string): string {
|
|
131
182
|
const subtype = mediaType.toLowerCase().split(";")[0]?.split("/")[1]?.trim() ?? "";
|
|
132
183
|
|
|
@@ -203,6 +254,7 @@ export class GrokVoiceClient implements GrokVoicePort {
|
|
|
203
254
|
voice: request.voice ?? GROK_TTS_DEFAULT_VOICE,
|
|
204
255
|
language: request.language ?? GROK_TTS_DEFAULT_LANGUAGE,
|
|
205
256
|
format: request.format ?? GROK_TTS_DEFAULT_FORMAT,
|
|
257
|
+
with_timestamps: request.with_timestamps,
|
|
206
258
|
});
|
|
207
259
|
|
|
208
260
|
const headers = {
|
|
@@ -214,6 +266,8 @@ export class GrokVoiceClient implements GrokVoicePort {
|
|
|
214
266
|
const firstByteAt = Date.now();
|
|
215
267
|
const mediaType = contentMediaType(response);
|
|
216
268
|
|
|
269
|
+
if (body.with_timestamps) return readTimestampsBody(response, body.format, firstByteAt);
|
|
270
|
+
|
|
217
271
|
if (mediaType === "application/json" || mediaType?.startsWith("text/"))
|
|
218
272
|
throw invalidBodyError(response, `expected audio, got ${mediaType}`);
|
|
219
273
|
let audio: Uint8Array;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
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
|
+
});
|
|
53
|
+
|
|
54
|
+
it("groups per-character timing into words spanning first to last character", () => {
|
|
55
|
+
expect(
|
|
56
|
+
wordsFromCharTimestamps({
|
|
57
|
+
graphChars: ["H", "i", " ", "y", "o", "u"],
|
|
58
|
+
graphTimes: [
|
|
59
|
+
[0, 0.1],
|
|
60
|
+
[0.1, 0.2],
|
|
61
|
+
[0.2, 0.3],
|
|
62
|
+
[0.3, 0.4],
|
|
63
|
+
[0.4, 0.5],
|
|
64
|
+
[0.5, 0.6],
|
|
65
|
+
],
|
|
66
|
+
}),
|
|
67
|
+
).toEqual([
|
|
68
|
+
{ text: "Hi", start: 0, end: 0.2 },
|
|
69
|
+
{ text: "you", start: 0.3, end: 0.6 },
|
|
70
|
+
]);
|
|
71
|
+
});
|
|
72
|
+
});
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/** A word an STT model heard, with its time span in seconds. */
|
|
2
|
+
export interface TimedWord {
|
|
3
|
+
text: string;
|
|
4
|
+
start: number;
|
|
5
|
+
end: number;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** Per-character timing in the shape Grok TTS returns (`with_timestamps`). */
|
|
9
|
+
export interface CharTimestamps {
|
|
10
|
+
graphChars: string[];
|
|
11
|
+
graphTimes: Array<[number, number]>;
|
|
12
|
+
}
|
|
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
|
+
/** Words from per-character timing: each run of non-space characters, spanning its first to last. */
|
|
155
|
+
export function wordsFromCharTimestamps(timestamps: CharTimestamps): TimedWord[] {
|
|
156
|
+
const words: TimedWord[] = [];
|
|
157
|
+
let current: TimedWord | undefined;
|
|
158
|
+
|
|
159
|
+
timestamps.graphChars.forEach((char, i) => {
|
|
160
|
+
const [start, end] = timestamps.graphTimes[i]!;
|
|
161
|
+
|
|
162
|
+
if (/\s/.test(char)) {
|
|
163
|
+
current = undefined;
|
|
164
|
+
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (current) {
|
|
169
|
+
current.text += char;
|
|
170
|
+
current.end = end;
|
|
171
|
+
} else {
|
|
172
|
+
current = { text: char, start, end };
|
|
173
|
+
words.push(current);
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
return words;
|
|
178
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{i as t,r as n}from"./vendor-react-8xo7RSum.js";var r=e(t(),1),i=n();function a({src:e,words:t,autoPlay:n,className:a=`h-8 w-full`}){let o=(0,r.useRef)(null),s=(0,r.useRef)(0),[c,l]=(0,r.useState)(-1),u=()=>{l(o.current?.currentTime??-1),s.current=requestAnimationFrame(u)},d=()=>cancelAnimationFrame(s.current);return(0,r.useEffect)(()=>()=>cancelAnimationFrame(s.current),[]),(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(`audio`,{ref:o,controls:!0,autoPlay:n,src:e,className:a,onPlay:()=>{d(),u()},onPause:d,onTimeUpdate:e=>l(e.currentTarget.currentTime),onEnded:()=>{d(),l(-1)}}),t&&t.length>0&&(0,i.jsx)(`p`,{className:`flex flex-wrap gap-x-0.5 gap-y-1 text-[13px] leading-relaxed`,children:t.map((e,t)=>(0,i.jsx)(`button`,{type:`button`,onClick:()=>{let t=o.current;t&&(t.currentTime=e.start,l(e.start),t.play())},title:`${e.start.toFixed(2)}–${e.end.toFixed(2)}s · play from here`,className:`rounded px-1 transition-colors duration-75 ${c>=e.start&&c<e.end?`bg-sienna-500 text-white`:`text-sand-700 hover:bg-sand-100`}`,children:e.text},t))})]})}export{a as t};
|