@cartanova/qgrid-cli 2.16.0 → 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 +63 -25
- package/bundle/dist/application/qgrid/qgrid.types.js +11 -3
- package/bundle/dist/utils/providers/grok/grok-types.js +8 -2
- package/bundle/dist/utils/providers/grok/grok-voice-client.js +4 -4
- package/bundle/dist/utils/speech-alignment.js +129 -0
- package/bundle/src/application/qgrid/qgrid.frame.test.ts +57 -7
- package/bundle/src/application/qgrid/qgrid.frame.ts +67 -30
- package/bundle/src/application/qgrid/qgrid.types.ts +17 -2
- package/bundle/src/utils/providers/grok/grok-types.ts +15 -10
- package/bundle/src/utils/providers/grok/grok-voice-client.ts +4 -4
- 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-SGfYBzGT.js → index-Cb14ZYfq.js} +3 -3
- package/bundle/web-dist/client/assets/index-Co8uAhSV.css +1 -0
- package/bundle/web-dist/client/assets/{logs-DrTz38re.js → logs-CSL1j0RN.js} +1 -1
- package/bundle/web-dist/client/assets/{monit-klIY-HEI.js → monit-J69xfniH.js} +1 -1
- package/bundle/web-dist/client/assets/{routes-bGN3y2NW.js → routes-CdWdhivH.js} +1 -1
- package/bundle/web-dist/client/assets/{settings-BHwEvAZL.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-DMWMG9O5.js → tokens-B9FeVPJk.js} +1 -1
- package/bundle/web-dist/client/assets/{use-oauth-login-flow-D1v4h9zA.js → use-oauth-login-flow-Tmy4lKYv.js} +1 -1
- package/bundle/web-dist/client/assets/{use-update-token-mutation-BVBUlqBN.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 +1 -1
- package/skills/qgrid/references/grok-runtime.md +5 -1
- 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-BiJkyrfB.js +0 -2
- package/bundle/web-dist/client/assets/voice-CwD3asSF.js +0 -1
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
//#region src/utils/speech-alignment.ts
|
|
2
|
+
const normalize = (word) => word.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}']/gu, "");
|
|
3
|
+
/**
|
|
4
|
+
* Infers per-character timing for a known script from the words an STT model heard in its audio.
|
|
5
|
+
* Script and heard words are paired by an edit-distance alignment, so a mis-heard word (a name
|
|
6
|
+
* spelled differently, a number written out) still takes the time of the word in its place, and
|
|
7
|
+
* extra heard words (a spoken preamble) are skipped. Script words left unpaired get the gap
|
|
8
|
+
* between their neighbours; each word's span is split over its characters by position, and the
|
|
9
|
+
* whitespace between words takes the pause between them. `durationSec` bounds leading and
|
|
10
|
+
* trailing gaps. `matchedWords` counts script words heard exactly (after normalization).
|
|
11
|
+
*/
|
|
12
|
+
function alignScriptToWords(script, words, durationSec) {
|
|
13
|
+
const tokens = [...script.matchAll(/\S+/g)].map((m) => ({
|
|
14
|
+
from: m.index,
|
|
15
|
+
to: m.index + m[0].length,
|
|
16
|
+
norm: normalize(m[0])
|
|
17
|
+
}));
|
|
18
|
+
const heard = words.flatMap((w) => {
|
|
19
|
+
const norm = normalize(w.text);
|
|
20
|
+
return norm === "" ? [] : [{
|
|
21
|
+
...w,
|
|
22
|
+
norm
|
|
23
|
+
}];
|
|
24
|
+
});
|
|
25
|
+
const n = tokens.length;
|
|
26
|
+
const m = heard.length;
|
|
27
|
+
const width = m + 1;
|
|
28
|
+
const cost = new Uint32Array((n + 1) * width);
|
|
29
|
+
for (let i = 0; i <= n; i++) cost[i * width] = i;
|
|
30
|
+
for (let j = 0; j <= m; j++) cost[j] = j;
|
|
31
|
+
for (let i = 1; i <= n; i++) for (let j = 1; j <= m; j++) {
|
|
32
|
+
const same = tokens[i - 1].norm === heard[j - 1].norm;
|
|
33
|
+
cost[i * width + j] = Math.min(cost[(i - 1) * width + (j - 1)] + (same ? 0 : 1), cost[(i - 1) * width + j] + 1, cost[i * width + (j - 1)] + 1);
|
|
34
|
+
}
|
|
35
|
+
const spans = Array.from({ length: n });
|
|
36
|
+
let matchedWords = 0;
|
|
37
|
+
for (let i = n, j = m; i > 0 || j > 0;) {
|
|
38
|
+
const here = cost[i * width + j];
|
|
39
|
+
const same = i > 0 && j > 0 && tokens[i - 1].norm === heard[j - 1].norm;
|
|
40
|
+
if (i > 0 && j > 0 && here === cost[(i - 1) * width + (j - 1)] + (same ? 0 : 1)) {
|
|
41
|
+
spans[i - 1] = [heard[j - 1].start, heard[j - 1].end];
|
|
42
|
+
if (same) matchedWords++;
|
|
43
|
+
i--;
|
|
44
|
+
j--;
|
|
45
|
+
} else if (i > 0 && here === cost[(i - 1) * width + j] + 1) i--;
|
|
46
|
+
else j--;
|
|
47
|
+
}
|
|
48
|
+
fillGaps(spans, tokens, durationSec);
|
|
49
|
+
const graphChars = [];
|
|
50
|
+
const graphTimes = [];
|
|
51
|
+
let token = 0;
|
|
52
|
+
let previousEnd = 0;
|
|
53
|
+
for (let c = 0; c < script.length;) {
|
|
54
|
+
const char = String.fromCodePoint(script.codePointAt(c));
|
|
55
|
+
while (token < n && tokens[token].to <= c) token++;
|
|
56
|
+
const current = tokens[token];
|
|
57
|
+
if (current && current.from <= c) {
|
|
58
|
+
const [start, end] = spans[token];
|
|
59
|
+
const length = current.to - current.from;
|
|
60
|
+
const offset = c - current.from;
|
|
61
|
+
const span = [start + (end - start) * offset / length, start + (end - start) * (offset + char.length) / length];
|
|
62
|
+
graphTimes.push(span);
|
|
63
|
+
previousEnd = span[1];
|
|
64
|
+
} else {
|
|
65
|
+
const nextStart = current ? spans[token][0] : durationSec;
|
|
66
|
+
graphTimes.push([previousEnd, Math.max(previousEnd, nextStart)]);
|
|
67
|
+
}
|
|
68
|
+
graphChars.push(char);
|
|
69
|
+
c += char.length;
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
audioTimestamps: {
|
|
73
|
+
graphChars,
|
|
74
|
+
graphTimes
|
|
75
|
+
},
|
|
76
|
+
matchedWords,
|
|
77
|
+
scriptWords: n
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/** Gives unpaired script words a slice of the gap between paired neighbours, by length. */
|
|
81
|
+
function fillGaps(spans, tokens, durationSec) {
|
|
82
|
+
for (let k = 0; k < spans.length;) {
|
|
83
|
+
if (spans[k]) {
|
|
84
|
+
k++;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
let last = k;
|
|
88
|
+
while (last + 1 < spans.length && !spans[last + 1]) last++;
|
|
89
|
+
const gapStart = k > 0 ? spans[k - 1][1] : 0;
|
|
90
|
+
const gapEnd = last + 1 < spans.length ? spans[last + 1][0] : durationSec;
|
|
91
|
+
const lengths = tokens.slice(k, last + 1).map((t) => t.to - t.from);
|
|
92
|
+
const total = lengths.reduce((sum, length) => sum + length, 0);
|
|
93
|
+
let cursor = gapStart;
|
|
94
|
+
lengths.forEach((length, offset) => {
|
|
95
|
+
const width = (gapEnd - gapStart) * length / total;
|
|
96
|
+
spans[k + offset] = [cursor, cursor + width];
|
|
97
|
+
cursor += width;
|
|
98
|
+
});
|
|
99
|
+
k = last + 1;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/** Words from per-character timing: each run of non-space characters, spanning its first to last. */
|
|
103
|
+
function wordsFromCharTimestamps(timestamps) {
|
|
104
|
+
const words = [];
|
|
105
|
+
let current;
|
|
106
|
+
timestamps.graphChars.forEach((char, i) => {
|
|
107
|
+
const [start, end] = timestamps.graphTimes[i];
|
|
108
|
+
if (/\s/.test(char)) {
|
|
109
|
+
current = void 0;
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (current) {
|
|
113
|
+
current.text += char;
|
|
114
|
+
current.end = end;
|
|
115
|
+
} else {
|
|
116
|
+
current = {
|
|
117
|
+
text: char,
|
|
118
|
+
start,
|
|
119
|
+
end
|
|
120
|
+
};
|
|
121
|
+
words.push(current);
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
return words;
|
|
125
|
+
}
|
|
126
|
+
//#endregion
|
|
127
|
+
export { alignScriptToWords, wordsFromCharTimestamps };
|
|
128
|
+
|
|
129
|
+
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic3BlZWNoLWFsaWdubWVudC5qcyIsIm5hbWVzIjpbXSwic291cmNlcyI6WyIuLi8uLi9zcmMvdXRpbHMvc3BlZWNoLWFsaWdubWVudC50cyJdLCJzb3VyY2VzQ29udGVudCI6WyIvKiogQSB3b3JkIGFuIFNUVCBtb2RlbCBoZWFyZCwgd2l0aCBpdHMgdGltZSBzcGFuIGluIHNlY29uZHMuICovXG5leHBvcnQgaW50ZXJmYWNlIFRpbWVkV29yZCB7XG4gIHRleHQ6IHN0cmluZztcbiAgc3RhcnQ6IG51bWJlcjtcbiAgZW5kOiBudW1iZXI7XG59XG5cbi8qKiBQZXItY2hhcmFjdGVyIHRpbWluZyBpbiB0aGUgc2hhcGUgR3JvayBUVFMgcmV0dXJucyAoYHdpdGhfdGltZXN0YW1wc2ApLiAqL1xuZXhwb3J0IGludGVyZmFjZSBDaGFyVGltZXN0YW1wcyB7XG4gIG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BSSxTQUFTO0VBRWIsUUFBUSxTQUFTLFFBQVEsV0FBVztHQUNsQyxNQUFNLFNBQVUsU0FBUyxZQUFZLFNBQVU7R0FDL0MsTUFBTSxJQUFJLFVBQVUsQ0FBQyxRQUFRLFNBQVMsS0FBSztHQUMzQyxVQUFVO0VBQ1osQ0FBQztFQUVELElBQUksT0FBTztDQUNiO0FBQ0Y7O0FBR0EsU0FBZ0Isd0JBQXdCLFlBQXlDO0NBQy9FLE1BQU0sUUFBcUIsQ0FBQztDQUM1QixJQUFJO0NBRUosV0FBVyxXQUFXLFNBQVMsTUFBTSxNQUFNO0VBQ3pDLE1BQU0sQ0FBQyxPQUFPLE9BQU8sV0FBVyxXQUFXO0VBRTNDLElBQUksS0FBSyxLQUFLLElBQUksR0FBRztHQUNuQixVQUFVO0dBRVY7RUFDRjtFQUVBLElBQUksU0FBUztHQUNYLFFBQVEsUUFBUTtHQUNoQixRQUFRLE1BQU07RUFDaEIsT0FBTztHQUNMLFVBQVU7SUFBRSxNQUFNO0lBQU07SUFBTztHQUFJO0dBQ25DLE1BQU0sS0FBSyxPQUFPO0VBQ3BCO0NBQ0YsQ0FBQztDQUVELE9BQU87QUFDVCJ9
|
|
@@ -2179,7 +2179,15 @@ describe("QgridFrame Grok media and voice (U11)", () => {
|
|
|
2179
2179
|
|
|
2180
2180
|
it("transcribe decodes base64 audio and returns the transcript", async () => {
|
|
2181
2181
|
grok.transcribe!.mockResolvedValueOnce({
|
|
2182
|
-
result: {
|
|
2182
|
+
result: {
|
|
2183
|
+
text: "hello there",
|
|
2184
|
+
language: "en",
|
|
2185
|
+
duration: 1.5,
|
|
2186
|
+
words: [
|
|
2187
|
+
{ text: "hello", start: 0.1, end: 0.5, confidence: 0.9 },
|
|
2188
|
+
{ text: "there", start: 0.6, end: 1.0 },
|
|
2189
|
+
],
|
|
2190
|
+
},
|
|
2183
2191
|
tokenId: 3,
|
|
2184
2192
|
tokenName: "grok/a",
|
|
2185
2193
|
});
|
|
@@ -2194,6 +2202,11 @@ describe("QgridFrame Grok media and voice (U11)", () => {
|
|
|
2194
2202
|
model: "grok/grok-voice-transcribe-2.0",
|
|
2195
2203
|
tokenName: "grok/a",
|
|
2196
2204
|
requestLogId: 77,
|
|
2205
|
+
// Word timing passes through without provider-only extras.
|
|
2206
|
+
words: [
|
|
2207
|
+
{ text: "hello", start: 0.1, end: 0.5 },
|
|
2208
|
+
{ text: "there", start: 0.6, end: 1.0 },
|
|
2209
|
+
],
|
|
2197
2210
|
});
|
|
2198
2211
|
const request = grok.transcribe!.mock.calls[0]![0] as { audio: Uint8Array; mediaType: string; model: string };
|
|
2199
2212
|
expect(Buffer.from(request.audio).toString()).toBe("RIFFfakewav");
|
|
@@ -2270,14 +2283,51 @@ describe("QgridFrame Grok media and voice (U11)", () => {
|
|
|
2270
2283
|
const out = await QgridFrame.speak({ text: "hi", withTimestamps: true });
|
|
2271
2284
|
|
|
2272
2285
|
expect(grok.speak).toHaveBeenCalledWith(expect.objectContaining({ with_timestamps: true }));
|
|
2273
|
-
expect(out).toMatchObject({ audioTimestamps, durationSec: 0.3 });
|
|
2286
|
+
expect(out).toMatchObject({ audioTimestamps, durationSec: 0.3, timestampsSource: "provider" });
|
|
2287
|
+
// The step result keeps word timing for the request-log detail player.
|
|
2288
|
+
const step = appendStepMock.mock.calls.at(-1)![1] as { tool_result: string };
|
|
2289
|
+
expect(JSON.parse(step.tool_result).words).toEqual([{ text: "hi", start: 0, end: 0.3 }]);
|
|
2274
2290
|
});
|
|
2275
2291
|
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2292
|
+
describe("OpenAI speech withTimestamps", () => {
|
|
2293
|
+
// 0.5 s of silence: 44-byte header + 24,000 bytes of PCM16 at 24 kHz.
|
|
2294
|
+
const wav = new Uint8Array(44 + 24_000);
|
|
2295
|
+
let openaiSpeak: ReturnType<typeof vi.fn>;
|
|
2296
|
+
|
|
2297
|
+
beforeEach(() => {
|
|
2298
|
+
openaiSpeak = vi.fn().mockResolvedValue({
|
|
2299
|
+
result: { audio: wav, mediaType: "audio/wav", transcript: "Hi there.", usage: {}, firstAudioAt: Date.now() },
|
|
2300
|
+
tokenName: "openai/a",
|
|
2301
|
+
});
|
|
2302
|
+
Object.assign(QgridDispatcher, { openaiDispatcher: { speak: openaiSpeak } });
|
|
2303
|
+
});
|
|
2304
|
+
|
|
2305
|
+
it("aligns Grok STT word timing to the script", async () => {
|
|
2306
|
+
grok.transcribe!.mockResolvedValueOnce({
|
|
2307
|
+
result: { text: "Hi there.", words: [{ text: "Hi", start: 0.1, end: 0.2 }, { text: "there.", start: 0.25, end: 0.45 }] },
|
|
2308
|
+
tokenId: 3,
|
|
2309
|
+
tokenName: "grok/a",
|
|
2310
|
+
});
|
|
2311
|
+
|
|
2312
|
+
const out = await QgridFrame.speak({ model: "openai/gpt-realtime-2.1-mini", text: "Hi there.", withTimestamps: true });
|
|
2313
|
+
|
|
2314
|
+
expect(grok.transcribe).toHaveBeenCalledWith(expect.objectContaining({ mediaType: "audio/wav", model: "grok-voice-transcribe-2.0" }));
|
|
2315
|
+
expect(out).toMatchObject({ timestampsSource: "aligned", durationSec: 0.5 });
|
|
2316
|
+
expect(out.audioTimestamps?.graphChars.join("")).toBe("Hi there.");
|
|
2317
|
+
const [start, end] = out.audioTimestamps!.graphTimes[0]!;
|
|
2318
|
+
expect(start).toBe(0.1);
|
|
2319
|
+
expect(end).toBeCloseTo(0.15);
|
|
2320
|
+
});
|
|
2321
|
+
|
|
2322
|
+
it("still returns the audio when the timing step fails", async () => {
|
|
2323
|
+
grok.transcribe!.mockRejectedValueOnce(new Error("grok down"));
|
|
2324
|
+
|
|
2325
|
+
const out = await QgridFrame.speak({ model: "openai/gpt-realtime-2.1-mini", text: "Hi there.", withTimestamps: true });
|
|
2326
|
+
|
|
2327
|
+
expect(out.audio).toBe(Buffer.from(wav).toString("base64"));
|
|
2328
|
+
expect(out.audioTimestamps).toBeUndefined();
|
|
2329
|
+
expect(out.timestampsError).toBe("grok down");
|
|
2330
|
+
});
|
|
2281
2331
|
});
|
|
2282
2332
|
|
|
2283
2333
|
it("speak keeps the byte-count placeholder for audio a browser cannot play", async () => {
|
|
@@ -80,9 +80,11 @@ import {
|
|
|
80
80
|
OPENAI_REALTIME_DEFAULT_SPEECH_MODEL,
|
|
81
81
|
OPENAI_REALTIME_DEFAULT_TRANSCRIPTION_MODEL,
|
|
82
82
|
OPENAI_REALTIME_DEFAULT_VOICE,
|
|
83
|
+
OPENAI_REALTIME_SAMPLE_RATE,
|
|
83
84
|
wrapPcmAsWav,
|
|
84
85
|
} from "../../utils/providers/openai/openai-realtime-protocol";
|
|
85
86
|
import { OpenAIVoiceInputError } from "../../utils/providers/openai/openai-voice-client";
|
|
87
|
+
import { alignScriptToWords, wordsFromCharTimestamps } from "../../utils/speech-alignment";
|
|
86
88
|
import {
|
|
87
89
|
type FinishRunParams,
|
|
88
90
|
MICRO_USD,
|
|
@@ -832,22 +834,12 @@ type MediaLogSuccess = {
|
|
|
832
834
|
// Voice rows embed browser-playable audio (TTS output in the response, STT input in the user
|
|
833
835
|
// prompt) so the request-log detail page can play it, as image rows embed their images. Other
|
|
834
836
|
// formats (raw PCM, mu-law, A-law) keep the byte-count placeholder.
|
|
835
|
-
const LOG_PLAYABLE_AUDIO =
|
|
836
|
-
"audio/wav",
|
|
837
|
-
"audio/x-wav",
|
|
838
|
-
"audio/wave",
|
|
839
|
-
"audio/mpeg",
|
|
840
|
-
"audio/mp3",
|
|
841
|
-
"audio/mp4",
|
|
842
|
-
"audio/ogg",
|
|
843
|
-
"audio/webm",
|
|
844
|
-
"audio/flac",
|
|
845
|
-
]);
|
|
837
|
+
const LOG_PLAYABLE_AUDIO = /^audio\/(wav|x-wav|wave|mpeg|mp3|mp4|ogg|webm|flac)$/;
|
|
846
838
|
|
|
847
839
|
function audioForLog(b64: string, mimeType: string, byteLength: number): string {
|
|
848
840
|
const base = mimeType.split(";")[0]!.trim().toLowerCase();
|
|
849
841
|
|
|
850
|
-
return LOG_PLAYABLE_AUDIO.
|
|
842
|
+
return LOG_PLAYABLE_AUDIO.test(base)
|
|
851
843
|
? `<audio src="data:${base};base64,${b64}"></audio>`
|
|
852
844
|
: `[audio ${mimeType} ${byteLength} bytes]`;
|
|
853
845
|
}
|
|
@@ -1165,6 +1157,35 @@ async function transcribeOpenAI(input: TranscribeInput): Promise<TranscribeOutpu
|
|
|
1165
1157
|
});
|
|
1166
1158
|
}
|
|
1167
1159
|
|
|
1160
|
+
/**
|
|
1161
|
+
* OpenAI realtime speech carries no timing, so the generated audio is transcribed with Grok STT and
|
|
1162
|
+
* the heard words are aligned to the script (`alignScriptToWords`). The Grok call goes through the
|
|
1163
|
+
* Grok dispatcher on an automatically selected token, like any Grok STT request.
|
|
1164
|
+
*/
|
|
1165
|
+
async function alignOpenAISpeech(wav: Uint8Array, script: string, signal: AbortSignal) {
|
|
1166
|
+
const selection = await resolveGrokTokenSelection(undefined);
|
|
1167
|
+
|
|
1168
|
+
const dispatched = await grokVoice().transcribe({
|
|
1169
|
+
audio: wav,
|
|
1170
|
+
mediaType: "audio/wav",
|
|
1171
|
+
model: GROK_STT_DEFAULT_MODEL,
|
|
1172
|
+
signal,
|
|
1173
|
+
...selection,
|
|
1174
|
+
});
|
|
1175
|
+
|
|
1176
|
+
const words = dispatched.result.words ?? [];
|
|
1177
|
+
|
|
1178
|
+
if (words.length === 0) throw new Error("Grok STT returned no word timing");
|
|
1179
|
+
// 44-byte WAV header, PCM16 mono at the realtime sample rate.
|
|
1180
|
+
const durationSec = (wav.byteLength - 44) / (2 * OPENAI_REALTIME_SAMPLE_RATE);
|
|
1181
|
+
|
|
1182
|
+
return {
|
|
1183
|
+
...alignScriptToWords(script, words, durationSec),
|
|
1184
|
+
durationSec,
|
|
1185
|
+
heard: dispatched.result.text,
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1168
1189
|
/**
|
|
1169
1190
|
* OpenAI realtime speech (openai/<id>): a conversational realtime model repeating the text over
|
|
1170
1191
|
* the direct realtime socket. Output is PCM16 24 kHz, wrapped as WAV unless `format` is pcm.
|
|
@@ -1216,10 +1237,21 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
|
|
|
1216
1237
|
if (requestLogId !== undefined) output.requestLogId = requestLogId;
|
|
1217
1238
|
|
|
1218
1239
|
// pcm output is always 24 kHz PCM16, so the log copy is wrapped as WAV to stay playable.
|
|
1219
|
-
const
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1240
|
+
const wav = mediaType === "audio/wav" ? audio : wrapPcmAsWav(audio);
|
|
1241
|
+
const logAudio = mediaType === "audio/wav" ? output.audio : Buffer.from(wav).toString("base64");
|
|
1242
|
+
let alignment: Awaited<ReturnType<typeof alignOpenAISpeech>> | undefined;
|
|
1243
|
+
|
|
1244
|
+
if (input.withTimestamps) {
|
|
1245
|
+
try {
|
|
1246
|
+
alignment = await alignOpenAISpeech(wav, input.text, signal);
|
|
1247
|
+
output.audioTimestamps = alignment.audioTimestamps;
|
|
1248
|
+
output.durationSec = alignment.durationSec;
|
|
1249
|
+
output.timestampsSource = "aligned";
|
|
1250
|
+
} catch (error) {
|
|
1251
|
+
// The speech itself succeeded; timing is best-effort and its failure is reported, not thrown.
|
|
1252
|
+
output.timestampsError = error instanceof Error ? error.message : String(error);
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1223
1255
|
|
|
1224
1256
|
const log: MediaRunLog = {
|
|
1225
1257
|
tokenName: output.tokenName,
|
|
@@ -1235,6 +1267,7 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
|
|
|
1235
1267
|
voice: request.voice,
|
|
1236
1268
|
format: request.format ?? "wav",
|
|
1237
1269
|
instructions: input.instructions,
|
|
1270
|
+
withTimestamps: input.withTimestamps,
|
|
1238
1271
|
characters: input.text.length,
|
|
1239
1272
|
},
|
|
1240
1273
|
result: JSON.stringify({
|
|
@@ -1242,6 +1275,14 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
|
|
|
1242
1275
|
audioBytes: audio.byteLength,
|
|
1243
1276
|
transcript,
|
|
1244
1277
|
usage,
|
|
1278
|
+
alignment: alignment && {
|
|
1279
|
+
heard: alignment.heard,
|
|
1280
|
+
matchedWords: alignment.matchedWords,
|
|
1281
|
+
scriptWords: alignment.scriptWords,
|
|
1282
|
+
},
|
|
1283
|
+
timestampsError: output.timestampsError,
|
|
1284
|
+
// Word timing for the request-log detail player.
|
|
1285
|
+
words: alignment && wordsFromCharTimestamps(alignment.audioTimestamps),
|
|
1245
1286
|
}),
|
|
1246
1287
|
},
|
|
1247
1288
|
],
|
|
@@ -2227,7 +2268,7 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2227
2268
|
...selection,
|
|
2228
2269
|
});
|
|
2229
2270
|
|
|
2230
|
-
const { text, language, duration } = dispatched.result;
|
|
2271
|
+
const { text, language, duration, words } = dispatched.result;
|
|
2231
2272
|
|
|
2232
2273
|
const output: TranscribeOutput = { text, model: route, tokenName: dispatched.tokenName };
|
|
2233
2274
|
|
|
@@ -2237,6 +2278,8 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2237
2278
|
|
|
2238
2279
|
if (requestLogId !== undefined) output.requestLogId = requestLogId;
|
|
2239
2280
|
|
|
2281
|
+
if (words) output.words = words.map((w) => ({ text: w.text, start: w.start, end: w.end }));
|
|
2282
|
+
|
|
2240
2283
|
const log: MediaRunLog = {
|
|
2241
2284
|
tokenName: output.tokenName,
|
|
2242
2285
|
response: output.text,
|
|
@@ -2255,6 +2298,8 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2255
2298
|
text: output.text,
|
|
2256
2299
|
language: output.language,
|
|
2257
2300
|
durationSec: output.durationSec,
|
|
2301
|
+
// Word timing of the input audio for the request-log detail player.
|
|
2302
|
+
words: output.words,
|
|
2258
2303
|
}),
|
|
2259
2304
|
},
|
|
2260
2305
|
],
|
|
@@ -2269,17 +2314,7 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2269
2314
|
async speak(params: SpeakInput): Promise<SpeakOutput> {
|
|
2270
2315
|
const input = parseMediaInput(SpeakInput, params);
|
|
2271
2316
|
|
|
2272
|
-
if (voiceProvider(input.model) === "openai")
|
|
2273
|
-
if (input.withTimestamps) {
|
|
2274
|
-
throw new BadRequestException(
|
|
2275
|
-
SD("qgrid.openaiVoiceInvalidRequest")(
|
|
2276
|
-
"withTimestamps is available only for grok/ speech; OpenAI realtime has no timing data",
|
|
2277
|
-
),
|
|
2278
|
-
);
|
|
2279
|
-
}
|
|
2280
|
-
|
|
2281
|
-
return speakOpenAI(input);
|
|
2282
|
-
}
|
|
2317
|
+
if (voiceProvider(input.model) === "openai") return speakOpenAI(input);
|
|
2283
2318
|
|
|
2284
2319
|
const voice = grokVoice();
|
|
2285
2320
|
const selection = await resolveGrokTokenSelection(input.tokenName);
|
|
@@ -2290,7 +2325,7 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2290
2325
|
voice: input.voice ?? GROK_TTS_DEFAULT_VOICE,
|
|
2291
2326
|
language: input.language ?? GROK_TTS_DEFAULT_LANGUAGE,
|
|
2292
2327
|
format: input.format ?? GROK_TTS_DEFAULT_FORMAT,
|
|
2293
|
-
|
|
2328
|
+
with_timestamps: input.withTimestamps,
|
|
2294
2329
|
};
|
|
2295
2330
|
|
|
2296
2331
|
const start = {
|
|
@@ -2315,6 +2350,7 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2315
2350
|
|
|
2316
2351
|
if (dispatched.result.audioTimestamps) {
|
|
2317
2352
|
output.audioTimestamps = dispatched.result.audioTimestamps;
|
|
2353
|
+
output.timestampsSource = "provider";
|
|
2318
2354
|
}
|
|
2319
2355
|
|
|
2320
2356
|
if (dispatched.result.durationSec !== undefined) {
|
|
@@ -2341,7 +2377,8 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2341
2377
|
mimeType: output.mimeType,
|
|
2342
2378
|
audioBytes,
|
|
2343
2379
|
durationSec: output.durationSec,
|
|
2344
|
-
|
|
2380
|
+
// Word timing for the request-log detail player.
|
|
2381
|
+
words: output.audioTimestamps && wordsFromCharTimestamps(output.audioTimestamps),
|
|
2345
2382
|
}),
|
|
2346
2383
|
},
|
|
2347
2384
|
],
|
|
@@ -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,8 +558,9 @@ 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(),
|
|
552
|
-
//
|
|
553
|
-
// no timing data
|
|
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"`).
|
|
554
564
|
withTimestamps: z.boolean().optional(),
|
|
555
565
|
...MediaCallOptions,
|
|
556
566
|
});
|
|
@@ -572,6 +582,11 @@ export const SpeakOutput = z.object({
|
|
|
572
582
|
})
|
|
573
583
|
.optional(),
|
|
574
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(),
|
|
575
590
|
});
|
|
576
591
|
|
|
577
592
|
export type SpeakOutput = z.infer<typeof SpeakOutput>;
|
|
@@ -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>;
|
|
@@ -364,19 +377,11 @@ export interface GrokTranscribeRequest {
|
|
|
364
377
|
signal?: AbortSignal;
|
|
365
378
|
}
|
|
366
379
|
|
|
367
|
-
/** Per-character timing of the spoken text, named as `@ai-sdk/xai` exposes it. */
|
|
368
|
-
export interface GrokAudioTimestamps {
|
|
369
|
-
/** Input characters, including spaces, punctuation and speech tags. */
|
|
370
|
-
graphChars: string[];
|
|
371
|
-
/** `[start, end]` seconds for the character at the same index. */
|
|
372
|
-
graphTimes: Array<[number, number]>;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
380
|
export interface GrokSpeechResult {
|
|
376
381
|
audio: Uint8Array;
|
|
377
382
|
mediaType: string;
|
|
378
|
-
/** Only with `with_timestamps
|
|
379
|
-
audioTimestamps?:
|
|
383
|
+
/** Only with `with_timestamps`; named as `@ai-sdk/xai` exposes it. */
|
|
384
|
+
audioTimestamps?: CharTimestamps;
|
|
380
385
|
durationSec?: number;
|
|
381
386
|
/** Epoch ms when the response headers arrived; /tts is not streamed, so this is first byte. */
|
|
382
387
|
firstByteAt?: number;
|
|
@@ -118,9 +118,9 @@ 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;
|
|
121
|
+
// `with_timestamps: true` envelope; optional fields nullable like @ai-sdk/xai's parser.
|
|
122
122
|
const GrokTtsTimestampsResponse = z.object({
|
|
123
|
-
audio: z.string()
|
|
123
|
+
audio: z.string(),
|
|
124
124
|
content_type: z.string().nullish(),
|
|
125
125
|
duration: z.number().nullish(),
|
|
126
126
|
audio_timestamps: z
|
|
@@ -154,7 +154,7 @@ async function readTimestampsBody(
|
|
|
154
154
|
throw invalidBodyError(response, "invalid timestamped TTS response", error);
|
|
155
155
|
}
|
|
156
156
|
|
|
157
|
-
const audio = new Uint8Array(Buffer.from(parsed.audio
|
|
157
|
+
const audio = new Uint8Array(Buffer.from(parsed.audio, "base64"));
|
|
158
158
|
|
|
159
159
|
if (audio.byteLength === 0) throw invalidBodyError(response, "empty audio body");
|
|
160
160
|
|
|
@@ -254,7 +254,7 @@ export class GrokVoiceClient implements GrokVoicePort {
|
|
|
254
254
|
voice: request.voice ?? GROK_TTS_DEFAULT_VOICE,
|
|
255
255
|
language: request.language ?? GROK_TTS_DEFAULT_LANGUAGE,
|
|
256
256
|
format: request.format ?? GROK_TTS_DEFAULT_FORMAT,
|
|
257
|
-
|
|
257
|
+
with_timestamps: request.with_timestamps,
|
|
258
258
|
});
|
|
259
259
|
|
|
260
260
|
const headers = {
|
|
@@ -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
|
+
});
|