offmute-v2 0.0.1-opus.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/README.md +120 -0
- package/dist/browser.d.ts +740 -0
- package/dist/browser.js +1494 -0
- package/dist/browser.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +1529 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +513 -0
- package/dist/index.js +1533 -0
- package/dist/index.js.map +1 -0
- package/package.json +77 -0
package/dist/browser.js
ADDED
|
@@ -0,0 +1,1494 @@
|
|
|
1
|
+
// src/core/time.ts
|
|
2
|
+
function secondsToSrtTime(seconds) {
|
|
3
|
+
const s2 = Number.isFinite(seconds) ? Math.max(0, seconds) : 0;
|
|
4
|
+
const hours = Math.floor(s2 / 3600);
|
|
5
|
+
const minutes = Math.floor(s2 % 3600 / 60);
|
|
6
|
+
const secs = Math.floor(s2 % 60);
|
|
7
|
+
const ms = Math.round((s2 - Math.floor(s2)) * 1e3);
|
|
8
|
+
let carrySecs = secs;
|
|
9
|
+
let carryMin = minutes;
|
|
10
|
+
let carryHrs = hours;
|
|
11
|
+
let outMs = ms;
|
|
12
|
+
if (outMs === 1e3) {
|
|
13
|
+
outMs = 0;
|
|
14
|
+
carrySecs += 1;
|
|
15
|
+
}
|
|
16
|
+
if (carrySecs === 60) {
|
|
17
|
+
carrySecs = 0;
|
|
18
|
+
carryMin += 1;
|
|
19
|
+
}
|
|
20
|
+
if (carryMin === 60) {
|
|
21
|
+
carryMin = 0;
|
|
22
|
+
carryHrs += 1;
|
|
23
|
+
}
|
|
24
|
+
return `${String(carryHrs).padStart(2, "0")}:${String(carryMin).padStart(2, "0")}:${String(carrySecs).padStart(2, "0")},${String(outMs).padStart(3, "0")}`;
|
|
25
|
+
}
|
|
26
|
+
function srtTimeToSeconds(timestamp) {
|
|
27
|
+
const t = timestamp.trim().replace(",", ".");
|
|
28
|
+
const [hms = "", frac] = t.split(".");
|
|
29
|
+
const parts = hms.split(":").map((p) => parseInt(p, 10));
|
|
30
|
+
let hours = 0;
|
|
31
|
+
let minutes = 0;
|
|
32
|
+
let secs = 0;
|
|
33
|
+
if (parts.length === 3) {
|
|
34
|
+
[hours, minutes, secs] = parts;
|
|
35
|
+
} else if (parts.length === 2) {
|
|
36
|
+
[minutes, secs] = parts;
|
|
37
|
+
} else if (parts.length === 1) {
|
|
38
|
+
[secs] = parts;
|
|
39
|
+
}
|
|
40
|
+
const fracSecs = frac ? parseFloat(`0.${frac}`) : 0;
|
|
41
|
+
return hours * 3600 + minutes * 60 + secs + fracSecs;
|
|
42
|
+
}
|
|
43
|
+
function relTimeToSeconds(timeStr) {
|
|
44
|
+
const parts = timeStr.trim().split(":");
|
|
45
|
+
if (parts.length < 2 || parts.length > 3) return null;
|
|
46
|
+
const nums = parts.map((p) => parseInt(p, 10));
|
|
47
|
+
if (nums.some((n) => Number.isNaN(n))) return null;
|
|
48
|
+
if (nums.length === 2) {
|
|
49
|
+
const [m2, s3] = nums;
|
|
50
|
+
return m2 * 60 + s3;
|
|
51
|
+
}
|
|
52
|
+
const [h, m, s2] = nums;
|
|
53
|
+
return h * 3600 + m * 60 + s2;
|
|
54
|
+
}
|
|
55
|
+
function secondsToCompact(seconds) {
|
|
56
|
+
const s2 = Math.max(0, Math.floor(seconds));
|
|
57
|
+
const h = Math.floor(s2 / 3600);
|
|
58
|
+
const m = Math.floor(s2 % 3600 / 60);
|
|
59
|
+
const sec = s2 % 60;
|
|
60
|
+
if (h > 0) {
|
|
61
|
+
return `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}`;
|
|
62
|
+
}
|
|
63
|
+
return `${m}:${String(sec).padStart(2, "0")}`;
|
|
64
|
+
}
|
|
65
|
+
function formatSrtTiming(start, end) {
|
|
66
|
+
return `${secondsToSrtTime(start)} --> ${secondsToSrtTime(end)}`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// src/core/srt.ts
|
|
70
|
+
var TIMING_RE = /(\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}|\d{1,2}:\d{2}[,.]\d{1,3})\s*-->\s*(\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}|\d{1,2}:\d{2}[,.]\d{1,3})/;
|
|
71
|
+
function splitSpeakerPrefix(text) {
|
|
72
|
+
const idx = text.indexOf(":");
|
|
73
|
+
if (idx <= 0 || idx > 40) return { body: text };
|
|
74
|
+
const prefix = text.slice(0, idx).trim();
|
|
75
|
+
const rest = text.slice(idx + 1).trim();
|
|
76
|
+
if (!rest) return { body: text };
|
|
77
|
+
if (/^\d+$/.test(prefix) || /^\d{1,2}(:\d{2})+$/.test(prefix)) return { body: text };
|
|
78
|
+
if (/[.!?]/.test(prefix)) return { body: text };
|
|
79
|
+
const wordCount = prefix.split(/\s+/).length;
|
|
80
|
+
if (wordCount > 4) return { body: text };
|
|
81
|
+
return { speaker: prefix, body: rest };
|
|
82
|
+
}
|
|
83
|
+
function parseSrt(content) {
|
|
84
|
+
const cues = [];
|
|
85
|
+
const blocks = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split(/\n\s*\n/);
|
|
86
|
+
let autoId = 0;
|
|
87
|
+
for (const block of blocks) {
|
|
88
|
+
const lines = block.split("\n").filter((l) => l.trim().length > 0);
|
|
89
|
+
if (lines.length === 0) continue;
|
|
90
|
+
let timingLineIdx = -1;
|
|
91
|
+
for (let i = 0; i < lines.length; i++) {
|
|
92
|
+
if (TIMING_RE.test(lines[i])) {
|
|
93
|
+
timingLineIdx = i;
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (timingLineIdx === -1) continue;
|
|
98
|
+
const m = lines[timingLineIdx].match(TIMING_RE);
|
|
99
|
+
if (!m) continue;
|
|
100
|
+
const start = srtTimeToSeconds(m[1]);
|
|
101
|
+
const end = srtTimeToSeconds(m[2]);
|
|
102
|
+
let id = ++autoId;
|
|
103
|
+
if (timingLineIdx > 0) {
|
|
104
|
+
const maybeId = parseInt(lines[0].trim(), 10);
|
|
105
|
+
if (!Number.isNaN(maybeId)) id = maybeId;
|
|
106
|
+
}
|
|
107
|
+
const text = lines.slice(timingLineIdx + 1).join(" ").trim();
|
|
108
|
+
const { speaker, body } = splitSpeakerPrefix(text);
|
|
109
|
+
cues.push({ id, start, end, text, speaker, body });
|
|
110
|
+
}
|
|
111
|
+
return cues;
|
|
112
|
+
}
|
|
113
|
+
function formatSrt(cues, options = {}) {
|
|
114
|
+
const { includeSpeaker = true } = options;
|
|
115
|
+
return cues.map((cue, i) => {
|
|
116
|
+
const speakerPrefix = includeSpeaker && cue.speaker ? `${cue.speaker}: ` : "";
|
|
117
|
+
return `${i + 1}
|
|
118
|
+
${formatSrtTiming(cue.start, cue.end)}
|
|
119
|
+
${speakerPrefix}${cue.text}`;
|
|
120
|
+
}).join("\n\n") + "\n";
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// src/core/align.ts
|
|
124
|
+
function normalizeToken(s2) {
|
|
125
|
+
return s2.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
126
|
+
}
|
|
127
|
+
function tokenize(text) {
|
|
128
|
+
return text.split(/\s+/).filter((t) => t.length > 0);
|
|
129
|
+
}
|
|
130
|
+
function alignTokens(a, b) {
|
|
131
|
+
const n = a.length;
|
|
132
|
+
const m = b.length;
|
|
133
|
+
const MATCH = 2;
|
|
134
|
+
const MISMATCH = -1;
|
|
135
|
+
const GAP = -1;
|
|
136
|
+
const w = m + 1;
|
|
137
|
+
const score = new Int32Array((n + 1) * w);
|
|
138
|
+
const back = new Uint8Array((n + 1) * w);
|
|
139
|
+
for (let i2 = 1; i2 <= n; i2++) {
|
|
140
|
+
score[i2 * w] = i2 * GAP;
|
|
141
|
+
back[i2 * w] = 1;
|
|
142
|
+
}
|
|
143
|
+
for (let j2 = 1; j2 <= m; j2++) {
|
|
144
|
+
score[j2] = j2 * GAP;
|
|
145
|
+
back[j2] = 2;
|
|
146
|
+
}
|
|
147
|
+
for (let i2 = 1; i2 <= n; i2++) {
|
|
148
|
+
const ai = a[i2 - 1];
|
|
149
|
+
const rowOff = i2 * w;
|
|
150
|
+
const prevRowOff = (i2 - 1) * w;
|
|
151
|
+
for (let j2 = 1; j2 <= m; j2++) {
|
|
152
|
+
const isMatch = ai === b[j2 - 1];
|
|
153
|
+
const diag = score[prevRowOff + j2 - 1] + (isMatch ? MATCH : MISMATCH);
|
|
154
|
+
const up = score[prevRowOff + j2] + GAP;
|
|
155
|
+
const left = score[rowOff + j2 - 1] + GAP;
|
|
156
|
+
let best = diag;
|
|
157
|
+
let dir = 0;
|
|
158
|
+
if (up > best) {
|
|
159
|
+
best = up;
|
|
160
|
+
dir = 1;
|
|
161
|
+
}
|
|
162
|
+
if (left > best) {
|
|
163
|
+
best = left;
|
|
164
|
+
dir = 2;
|
|
165
|
+
}
|
|
166
|
+
score[rowOff + j2] = best;
|
|
167
|
+
back[rowOff + j2] = dir;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const pairs = [];
|
|
171
|
+
let i = n;
|
|
172
|
+
let j = m;
|
|
173
|
+
while (i > 0 || j > 0) {
|
|
174
|
+
if (i > 0 && j > 0 && back[i * w + j] === 0) {
|
|
175
|
+
pairs.push({ ai: i - 1, bi: j - 1, match: a[i - 1] === b[j - 1] });
|
|
176
|
+
i--;
|
|
177
|
+
j--;
|
|
178
|
+
} else if (i > 0 && (j === 0 || back[i * w + j] === 1)) {
|
|
179
|
+
pairs.push({ ai: i - 1, bi: null, match: false });
|
|
180
|
+
i--;
|
|
181
|
+
} else {
|
|
182
|
+
pairs.push({ ai: null, bi: j - 1, match: false });
|
|
183
|
+
j--;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
pairs.reverse();
|
|
187
|
+
return pairs;
|
|
188
|
+
}
|
|
189
|
+
function alignLlmToAsr(turns, asrWords) {
|
|
190
|
+
const tokens = [];
|
|
191
|
+
turns.forEach((turn, turnIndex) => {
|
|
192
|
+
for (const surface of tokenize(turn.text)) {
|
|
193
|
+
const norm = normalizeToken(surface);
|
|
194
|
+
if (!norm) continue;
|
|
195
|
+
tokens.push({ surface, norm, turnIndex, start: null, end: null, matched: false });
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
const asrNorm = asrWords.map((w) => normalizeToken(w.text));
|
|
199
|
+
const pairs = alignTokens(
|
|
200
|
+
tokens.map((t) => t.norm),
|
|
201
|
+
asrNorm
|
|
202
|
+
);
|
|
203
|
+
for (const p of pairs) {
|
|
204
|
+
if (p.ai === null) continue;
|
|
205
|
+
const tok = tokens[p.ai];
|
|
206
|
+
if (p.match && p.bi !== null) {
|
|
207
|
+
const w = asrWords[p.bi];
|
|
208
|
+
tok.start = w.start;
|
|
209
|
+
tok.end = w.end;
|
|
210
|
+
tok.matched = true;
|
|
211
|
+
if (w.speaker) tok.asrSpeaker = w.speaker;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return tokens;
|
|
215
|
+
}
|
|
216
|
+
function fillTokenTimes(tokens, totalDuration) {
|
|
217
|
+
const n = tokens.length;
|
|
218
|
+
if (n === 0) return tokens;
|
|
219
|
+
const anchors = [];
|
|
220
|
+
for (let i = 0; i < n; i++) if (tokens[i].matched) anchors.push(i);
|
|
221
|
+
if (anchors.length === 0) {
|
|
222
|
+
for (let i = 0; i < n; i++) {
|
|
223
|
+
tokens[i].start = i / n * totalDuration;
|
|
224
|
+
tokens[i].end = (i + 1) / n * totalDuration;
|
|
225
|
+
}
|
|
226
|
+
return tokens;
|
|
227
|
+
}
|
|
228
|
+
const first = anchors[0];
|
|
229
|
+
for (let i = 0; i < first; i++) {
|
|
230
|
+
tokens[i].start = tokens[first].start;
|
|
231
|
+
tokens[i].end = tokens[first].start;
|
|
232
|
+
}
|
|
233
|
+
const last = anchors[anchors.length - 1];
|
|
234
|
+
for (let i = last + 1; i < n; i++) {
|
|
235
|
+
tokens[i].start = tokens[last].end;
|
|
236
|
+
tokens[i].end = tokens[last].end;
|
|
237
|
+
}
|
|
238
|
+
for (let a = 0; a < anchors.length - 1; a++) {
|
|
239
|
+
const lo = anchors[a];
|
|
240
|
+
const hi = anchors[a + 1];
|
|
241
|
+
const t0 = tokens[lo].end ?? tokens[lo].start ?? 0;
|
|
242
|
+
const t1 = tokens[hi].start ?? t0;
|
|
243
|
+
const gap = hi - lo;
|
|
244
|
+
for (let i = lo + 1; i < hi; i++) {
|
|
245
|
+
const frac = (i - lo) / gap;
|
|
246
|
+
const t = t0 + frac * (t1 - t0);
|
|
247
|
+
tokens[i].start = t;
|
|
248
|
+
tokens[i].end = t;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return tokens;
|
|
252
|
+
}
|
|
253
|
+
var SENTENCE_END = /[.!?…]["')\]]?$/;
|
|
254
|
+
function buildSegmentsFromTokens(turns, tokens, options = {}) {
|
|
255
|
+
const {
|
|
256
|
+
subSegment = false,
|
|
257
|
+
maxChars = 90,
|
|
258
|
+
maxDuration = 7,
|
|
259
|
+
gapSplit = 1,
|
|
260
|
+
minChars = 24
|
|
261
|
+
} = options;
|
|
262
|
+
const byTurn = /* @__PURE__ */ new Map();
|
|
263
|
+
for (const t of tokens) {
|
|
264
|
+
const arr = byTurn.get(t.turnIndex);
|
|
265
|
+
if (arr) arr.push(t);
|
|
266
|
+
else byTurn.set(t.turnIndex, [t]);
|
|
267
|
+
}
|
|
268
|
+
const segments = [];
|
|
269
|
+
for (let turnIndex = 0; turnIndex < turns.length; turnIndex++) {
|
|
270
|
+
const toks = byTurn.get(turnIndex);
|
|
271
|
+
if (!toks || toks.length === 0) continue;
|
|
272
|
+
if (!subSegment) {
|
|
273
|
+
segments.push(makeSegment(turnIndex, toks));
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
let cur = [];
|
|
277
|
+
let curChars = 0;
|
|
278
|
+
const flush = () => {
|
|
279
|
+
if (cur.length > 0) {
|
|
280
|
+
segments.push(makeSegment(turnIndex, cur));
|
|
281
|
+
cur = [];
|
|
282
|
+
curChars = 0;
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
for (let i = 0; i < toks.length; i++) {
|
|
286
|
+
const tok = toks[i];
|
|
287
|
+
cur.push(tok);
|
|
288
|
+
curChars += tok.surface.length + 1;
|
|
289
|
+
const next = toks[i + 1];
|
|
290
|
+
const curStart = cur[0].start ?? 0;
|
|
291
|
+
const curEnd = tok.end ?? curStart;
|
|
292
|
+
const dur = curEnd - curStart;
|
|
293
|
+
const bothMatched = tok.matched && (next?.matched ?? false);
|
|
294
|
+
const gapToNext = bothMatched && next && next.start !== null && tok.end !== null ? next.start - tok.end : 0;
|
|
295
|
+
const sentenceBreak = SENTENCE_END.test(tok.surface) && curChars >= minChars;
|
|
296
|
+
const tooLong = curChars >= maxChars || dur >= maxDuration;
|
|
297
|
+
const bigGap = gapToNext >= gapSplit && curChars >= minChars;
|
|
298
|
+
if (sentenceBreak || tooLong || bigGap) flush();
|
|
299
|
+
}
|
|
300
|
+
flush();
|
|
301
|
+
}
|
|
302
|
+
return segments;
|
|
303
|
+
}
|
|
304
|
+
function asrSpeakerByLabel(tokens, labelByTurn) {
|
|
305
|
+
const out = {};
|
|
306
|
+
for (const tok of tokens) {
|
|
307
|
+
if (!tok.matched || !tok.asrSpeaker) continue;
|
|
308
|
+
const label = labelByTurn[tok.turnIndex];
|
|
309
|
+
if (label === void 0) continue;
|
|
310
|
+
out[label] ??= {};
|
|
311
|
+
out[label][tok.asrSpeaker] = (out[label][tok.asrSpeaker] ?? 0) + 1;
|
|
312
|
+
}
|
|
313
|
+
return out;
|
|
314
|
+
}
|
|
315
|
+
function makeSegment(turnIndex, toks) {
|
|
316
|
+
const matched = toks.filter((t) => t.matched);
|
|
317
|
+
const starts = toks.map((t) => t.start).filter((x) => x !== null);
|
|
318
|
+
const ends = toks.map((t) => t.end).filter((x) => x !== null);
|
|
319
|
+
const start = starts.length ? Math.min(...starts) : 0;
|
|
320
|
+
const end = ends.length ? Math.max(...ends) : start;
|
|
321
|
+
return {
|
|
322
|
+
turnIndex,
|
|
323
|
+
start,
|
|
324
|
+
end: Math.max(end, start),
|
|
325
|
+
text: toks.map((t) => t.surface).join(" "),
|
|
326
|
+
matchRatio: toks.length ? matched.length / toks.length : 0,
|
|
327
|
+
tokenCount: toks.length,
|
|
328
|
+
matchedTokens: matched.length
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// src/core/format.ts
|
|
333
|
+
function speakerLabelMap(transcript) {
|
|
334
|
+
const m = /* @__PURE__ */ new Map();
|
|
335
|
+
for (const sp of transcript.speakers) m.set(sp.id, sp.label);
|
|
336
|
+
return m;
|
|
337
|
+
}
|
|
338
|
+
function srtCueText(s2) {
|
|
339
|
+
return s2.replace(/\r\n?/g, "\n").replace(/\n[ \t]*\n+/g, "\n").trim() || " ";
|
|
340
|
+
}
|
|
341
|
+
function toSRT(transcript, options = {}) {
|
|
342
|
+
const { includeSpeaker = true, includeTone = false } = options;
|
|
343
|
+
const labels = speakerLabelMap(transcript);
|
|
344
|
+
const blocks = transcript.segments.map((seg, i) => {
|
|
345
|
+
const label = labels.get(seg.speakerId) ?? seg.speakerId;
|
|
346
|
+
const prefix = includeSpeaker ? `${label}: ` : "";
|
|
347
|
+
const tone = includeTone && seg.tone ? `(${seg.tone}) ` : "";
|
|
348
|
+
const body = srtCueText(`${prefix}${tone}${seg.text}`);
|
|
349
|
+
return `${i + 1}
|
|
350
|
+
${formatSrtTiming(seg.start, Math.max(seg.start, seg.end))}
|
|
351
|
+
${body}`;
|
|
352
|
+
});
|
|
353
|
+
return blocks.join("\n\n") + "\n";
|
|
354
|
+
}
|
|
355
|
+
function toMarkdown(transcript, options = {}) {
|
|
356
|
+
const { includeTimestamps = true, includeTone = true, title = "Transcript", mergeBySpeaker = true } = options;
|
|
357
|
+
const labels = speakerLabelMap(transcript);
|
|
358
|
+
const out = [];
|
|
359
|
+
out.push(`# ${title}
|
|
360
|
+
`);
|
|
361
|
+
const m = transcript.metadata;
|
|
362
|
+
out.push(`*Duration: ${secondsToCompact(m.durationSeconds)} \xB7 ${transcript.segments.length} segments \xB7 ${transcript.speakers.length} speakers*`);
|
|
363
|
+
if (m.asrProvider || m.llmModel) {
|
|
364
|
+
out.push(`*ASR: ${m.asrProvider ?? "\u2014"} \xB7 LLM: ${m.llmModel ?? "\u2014"}*`);
|
|
365
|
+
}
|
|
366
|
+
out.push("");
|
|
367
|
+
out.push(`## Speakers
|
|
368
|
+
`);
|
|
369
|
+
for (const sp of transcript.speakers) {
|
|
370
|
+
const named = sp.named ? "" : " *(unidentified)*";
|
|
371
|
+
const desc = sp.description ? ` \u2014 ${sp.description}` : "";
|
|
372
|
+
out.push(`- **${sp.label}**${named}${desc}`);
|
|
373
|
+
}
|
|
374
|
+
out.push(`
|
|
375
|
+
## Transcript
|
|
376
|
+
`);
|
|
377
|
+
const groups = mergeBySpeaker ? groupBySpeaker(transcript.segments) : transcript.segments.map((s2) => [s2]);
|
|
378
|
+
for (const group of groups) {
|
|
379
|
+
const first = group[0];
|
|
380
|
+
const label = labels.get(first.speakerId) ?? first.speakerId;
|
|
381
|
+
const ts = includeTimestamps ? `\`[${secondsToCompact(first.start)}]\` ` : "";
|
|
382
|
+
const text = group.map((s2) => includeTone && s2.tone ? `*(${s2.tone})* ${s2.text}` : s2.text).join(" ");
|
|
383
|
+
out.push(`${ts}**${label}:** ${text}
|
|
384
|
+
`);
|
|
385
|
+
}
|
|
386
|
+
return out.join("\n");
|
|
387
|
+
}
|
|
388
|
+
function groupBySpeaker(segments) {
|
|
389
|
+
const groups = [];
|
|
390
|
+
for (const seg of segments) {
|
|
391
|
+
const last = groups[groups.length - 1];
|
|
392
|
+
if (last && last[0].speakerId === seg.speakerId) last.push(seg);
|
|
393
|
+
else groups.push([seg]);
|
|
394
|
+
}
|
|
395
|
+
return groups;
|
|
396
|
+
}
|
|
397
|
+
function toJSON(transcript) {
|
|
398
|
+
return JSON.stringify(transcript, null, 2);
|
|
399
|
+
}
|
|
400
|
+
function toText(transcript, options = {}) {
|
|
401
|
+
const { includeTimestamps = true } = options;
|
|
402
|
+
const labels = speakerLabelMap(transcript);
|
|
403
|
+
return groupBySpeaker(transcript.segments).map((group) => {
|
|
404
|
+
const first = group[0];
|
|
405
|
+
const label = labels.get(first.speakerId) ?? first.speakerId;
|
|
406
|
+
const ts = includeTimestamps ? `[${secondsToCompact(first.start)}] ` : "";
|
|
407
|
+
return `${ts}${label}: ${group.map((s2) => s2.text).join(" ")}`;
|
|
408
|
+
}).join("\n\n") + "\n";
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// src/core/speakers.ts
|
|
412
|
+
var PROVISIONAL_RE = /^(speaker|spkr|unknown|unidentified)\b/i;
|
|
413
|
+
function slugLabel(label) {
|
|
414
|
+
return label.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "speaker";
|
|
415
|
+
}
|
|
416
|
+
function isProvisional(label) {
|
|
417
|
+
return PROVISIONAL_RE.test(label.trim());
|
|
418
|
+
}
|
|
419
|
+
function buildSpeakers(rawLabels, options = {}) {
|
|
420
|
+
const { knownSpeakers = {}, resolvedNames = {}, descriptions = {} } = options;
|
|
421
|
+
const labelToId = /* @__PURE__ */ new Map();
|
|
422
|
+
const byId = /* @__PURE__ */ new Map();
|
|
423
|
+
const resolveCanonical = (raw) => {
|
|
424
|
+
if (knownSpeakers[raw]) return knownSpeakers[raw];
|
|
425
|
+
if (resolvedNames[raw]) {
|
|
426
|
+
const resolvedName = resolvedNames[raw];
|
|
427
|
+
return knownSpeakers[resolvedName] ?? resolvedName;
|
|
428
|
+
}
|
|
429
|
+
return raw;
|
|
430
|
+
};
|
|
431
|
+
for (const raw of rawLabels) {
|
|
432
|
+
if (labelToId.has(raw)) continue;
|
|
433
|
+
const canonical = resolveCanonical(raw);
|
|
434
|
+
const id = slugLabel(canonical);
|
|
435
|
+
labelToId.set(raw, id);
|
|
436
|
+
if (!byId.has(id)) {
|
|
437
|
+
byId.set(id, {
|
|
438
|
+
id,
|
|
439
|
+
label: canonical,
|
|
440
|
+
named: !isProvisional(canonical),
|
|
441
|
+
description: descriptions[canonical]
|
|
442
|
+
});
|
|
443
|
+
} else if (descriptions[canonical] && !byId.get(id).description) {
|
|
444
|
+
byId.get(id).description = descriptions[canonical];
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
return { speakers: [...byId.values()], labelToId };
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// src/core/parse-diarized.ts
|
|
451
|
+
var LINE_RE = /^\s*(?:\[(?<ts>\d{1,2}:\d{2}(?::\d{2})?)\]\s*)?(?<speaker>[^:\[\]]{1,40}?):\s*(?:\((?<tone>[^)]{1,60})\)\s*)?(?<text>.*)$/;
|
|
452
|
+
function parseDiarizedText(raw) {
|
|
453
|
+
const lines = raw.replace(/\r\n/g, "\n").split("\n");
|
|
454
|
+
const out = [];
|
|
455
|
+
for (const line of lines) {
|
|
456
|
+
const trimmed = line.trim();
|
|
457
|
+
if (!trimmed) continue;
|
|
458
|
+
if (/^```/.test(trimmed)) continue;
|
|
459
|
+
const m = trimmed.match(LINE_RE);
|
|
460
|
+
if (m && m.groups && m.groups["text"] !== void 0) {
|
|
461
|
+
const speaker = m.groups["speaker"].trim();
|
|
462
|
+
const tsStr = m.groups["ts"];
|
|
463
|
+
const tone = m.groups["tone"]?.trim();
|
|
464
|
+
const text = m.groups["text"].trim();
|
|
465
|
+
if (speaker.split(/\s+/).length > 6) {
|
|
466
|
+
appendContinuation(out, trimmed);
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
const approxStart = tsStr ? relTimeToSeconds(tsStr) ?? void 0 : void 0;
|
|
470
|
+
out.push({
|
|
471
|
+
speaker,
|
|
472
|
+
text,
|
|
473
|
+
tone: tone || void 0,
|
|
474
|
+
approxStart
|
|
475
|
+
});
|
|
476
|
+
} else {
|
|
477
|
+
appendContinuation(out, trimmed);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
return out;
|
|
481
|
+
}
|
|
482
|
+
function appendContinuation(out, text) {
|
|
483
|
+
const last = out[out.length - 1];
|
|
484
|
+
if (last) last.text = `${last.text} ${text}`.trim();
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// src/core/prompts.ts
|
|
488
|
+
var DIARIZATION_SYSTEM = `You are an expert meeting transcriptionist and diarizer. You transcribe verbatim (including filler words and false starts), attribute every utterance to the correct speaker, and you are careful and literal. You never invent content you cannot hear.`;
|
|
489
|
+
function buildDiarizationPrompt(input) {
|
|
490
|
+
const { instructions, asrHint, chunk, previousTail } = input;
|
|
491
|
+
const parts = [];
|
|
492
|
+
if (chunk && chunk.total > 1) {
|
|
493
|
+
parts.push(
|
|
494
|
+
`This is part ${chunk.index + 1} of ${chunk.total} of a longer recording. This part starts at ${secondsToCompact(chunk.startSeconds)} in the full recording. Use timestamps RELATIVE to the start of THIS clip ([mm:ss] from 0:00).`
|
|
495
|
+
);
|
|
496
|
+
} else {
|
|
497
|
+
parts.push(`This is a recorded talk/meeting. Produce a complete diarized transcript.`);
|
|
498
|
+
}
|
|
499
|
+
if (instructions) {
|
|
500
|
+
parts.push(`
|
|
501
|
+
IMPORTANT USER INSTRUCTIONS (follow these for speaker labeling and focus):
|
|
502
|
+
${instructions}`);
|
|
503
|
+
}
|
|
504
|
+
if (asrHint) {
|
|
505
|
+
parts.push(
|
|
506
|
+
`
|
|
507
|
+
A baseline speech-to-text system produced the rough diarization below. Its TIMING is reliable but its SPEAKER LABELS are often wrong (it splits one person into several, merges different people, and misses short interjections). Use it only as a hint \u2014 trust what you HEAR for who is speaking:
|
|
508
|
+
|
|
509
|
+
${asrHint}`
|
|
510
|
+
);
|
|
511
|
+
}
|
|
512
|
+
if (previousTail) {
|
|
513
|
+
parts.push(
|
|
514
|
+
`
|
|
515
|
+
For speaker continuity only, the previous part ended with the lines below. The start of THIS clip overlaps the previous part \u2014 transcribe EVERYTHING you hear in THIS clip in full (from 0:00), including any overlap; do not skip the beginning:
|
|
516
|
+
...${previousTail}`
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
parts.push(`
|
|
520
|
+
Instructions:
|
|
521
|
+
- Diarize: identify each distinct speaker. Infer real names from context (introductions, people addressing each other) when possible; otherwise label "Speaker 1", "Speaker 2", etc. Keep each speaker's label consistent throughout.
|
|
522
|
+
- Give the start timestamp of every speaker turn in [mm:ss].
|
|
523
|
+
- Add a brief tone/emotion note in parentheses when notable: (laughing), (hesitant), (emphatic), (audience member), etc. Omit when neutral.
|
|
524
|
+
- Transcribe verbatim. Start a new line whenever the speaker changes.
|
|
525
|
+
|
|
526
|
+
Output ONLY the transcript, one line per speaker turn, exactly:
|
|
527
|
+
[mm:ss] Speaker: (tone) text
|
|
528
|
+
|
|
529
|
+
Begin.`);
|
|
530
|
+
return parts.join("\n");
|
|
531
|
+
}
|
|
532
|
+
function buildAsrHint(asr, maxUtterances = 200, maxCharsPerUtterance = 160) {
|
|
533
|
+
const lines = [];
|
|
534
|
+
const utts = asr.utterances.slice(0, maxUtterances);
|
|
535
|
+
for (const u of utts) {
|
|
536
|
+
const text = u.text.length > maxCharsPerUtterance ? u.text.slice(0, maxCharsPerUtterance) + "\u2026" : u.text;
|
|
537
|
+
lines.push(`[${secondsToCompact(u.start)}] ${u.speaker}: ${text}`);
|
|
538
|
+
}
|
|
539
|
+
if (asr.utterances.length > maxUtterances) lines.push(`\u2026 (${asr.utterances.length - maxUtterances} more)`);
|
|
540
|
+
return lines.join("\n");
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// src/core/chunk.ts
|
|
544
|
+
function calculateChunks(totalSeconds, chunkSeconds, overlapSeconds) {
|
|
545
|
+
if (totalSeconds <= chunkSeconds) {
|
|
546
|
+
return [{ index: 0, startSeconds: 0, endSeconds: totalSeconds }];
|
|
547
|
+
}
|
|
548
|
+
const overlap = Math.max(0, Math.min(overlapSeconds, chunkSeconds * 0.5));
|
|
549
|
+
const step = Math.max(1, chunkSeconds - overlap);
|
|
550
|
+
const chunks = [];
|
|
551
|
+
let start = 0;
|
|
552
|
+
let index = 0;
|
|
553
|
+
while (start < totalSeconds) {
|
|
554
|
+
const end = Math.min(start + chunkSeconds, totalSeconds);
|
|
555
|
+
if (end >= totalSeconds && end - start < chunkSeconds / 3 && chunks.length > 0) {
|
|
556
|
+
chunks[chunks.length - 1].endSeconds = end;
|
|
557
|
+
break;
|
|
558
|
+
}
|
|
559
|
+
chunks.push({ index, startSeconds: start, endSeconds: end });
|
|
560
|
+
index++;
|
|
561
|
+
if (end >= totalSeconds) break;
|
|
562
|
+
start += step;
|
|
563
|
+
}
|
|
564
|
+
return chunks;
|
|
565
|
+
}
|
|
566
|
+
function chunkOwnership(chunks, totalDuration) {
|
|
567
|
+
return chunks.map((c, i) => {
|
|
568
|
+
const prev = chunks[i - 1];
|
|
569
|
+
const next = chunks[i + 1];
|
|
570
|
+
const start = i === 0 || !prev ? 0 : (prev.endSeconds + c.startSeconds) / 2;
|
|
571
|
+
const end = i === chunks.length - 1 || !next ? totalDuration : (c.endSeconds + next.startSeconds) / 2;
|
|
572
|
+
return { start, end };
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
function mergeChunkSegments(segments, chunkBoundaries) {
|
|
576
|
+
const sorted = [...segments].sort((a, b) => a.start - b.start || a.end - b.end);
|
|
577
|
+
const kept = [];
|
|
578
|
+
for (const seg of sorted) {
|
|
579
|
+
const dup = kept.find(
|
|
580
|
+
(k) => k.chunkIndex !== seg.chunkIndex && timeOverlapRatio(k, seg) > 0.5 && textSimilar(k.text, seg.text)
|
|
581
|
+
);
|
|
582
|
+
if (!dup) {
|
|
583
|
+
kept.push(seg);
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
if (segmentScore(seg, chunkBoundaries) > segmentScore(dup, chunkBoundaries)) {
|
|
587
|
+
kept[kept.indexOf(dup)] = seg;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
return kept.sort((a, b) => a.start - b.start);
|
|
591
|
+
}
|
|
592
|
+
function timeOverlapRatio(a, b) {
|
|
593
|
+
const lo = Math.max(a.start, b.start);
|
|
594
|
+
const hi = Math.min(a.end, b.end);
|
|
595
|
+
const inter = Math.max(0, hi - lo);
|
|
596
|
+
const minLen = Math.max(0.01, Math.min(a.end - a.start, b.end - b.start));
|
|
597
|
+
return inter / minLen;
|
|
598
|
+
}
|
|
599
|
+
function textSimilar(a, b) {
|
|
600
|
+
const wa = new Set(a.toLowerCase().replace(/[^a-z0-9 ]/g, "").split(/\s+/).filter(Boolean));
|
|
601
|
+
const wb = new Set(b.toLowerCase().replace(/[^a-z0-9 ]/g, "").split(/\s+/).filter(Boolean));
|
|
602
|
+
if (wa.size === 0 || wb.size === 0) return false;
|
|
603
|
+
let inter = 0;
|
|
604
|
+
for (const w of wa) if (wb.has(w)) inter++;
|
|
605
|
+
const jaccard = inter / (wa.size + wb.size - inter);
|
|
606
|
+
return jaccard > 0.4;
|
|
607
|
+
}
|
|
608
|
+
function segmentScore(seg, chunks) {
|
|
609
|
+
const chunk = chunks[seg.chunkIndex];
|
|
610
|
+
let edgeDistance = 999;
|
|
611
|
+
if (chunk) {
|
|
612
|
+
edgeDistance = Math.min(seg.start - chunk.startSeconds, chunk.endSeconds - seg.end);
|
|
613
|
+
}
|
|
614
|
+
return seg.matchRatio * 10 + Math.min(edgeDistance, 30);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// src/core/eval.ts
|
|
618
|
+
function segmentsToWords(segments) {
|
|
619
|
+
const words = [];
|
|
620
|
+
for (const seg of segments) {
|
|
621
|
+
const toks = tokenize(seg.text).map((t) => normalizeToken(t)).filter(Boolean);
|
|
622
|
+
if (toks.length === 0) continue;
|
|
623
|
+
const span = Math.max(0, seg.end - seg.start);
|
|
624
|
+
for (let i = 0; i < toks.length; i++) {
|
|
625
|
+
const frac = toks.length === 1 ? 0 : i / toks.length;
|
|
626
|
+
const fracEnd = toks.length === 1 ? 1 : (i + 1) / toks.length;
|
|
627
|
+
words.push({
|
|
628
|
+
norm: toks[i],
|
|
629
|
+
start: seg.start + frac * span,
|
|
630
|
+
end: seg.start + fracEnd * span,
|
|
631
|
+
speaker: seg.speaker,
|
|
632
|
+
isBoundary: i === 0
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
return words;
|
|
637
|
+
}
|
|
638
|
+
function percentile(sorted, p) {
|
|
639
|
+
if (sorted.length === 0) return 0;
|
|
640
|
+
const idx = Math.min(sorted.length - 1, Math.floor(p / 100 * sorted.length));
|
|
641
|
+
return sorted[idx];
|
|
642
|
+
}
|
|
643
|
+
function evaluateWords(ref, hyp) {
|
|
644
|
+
const pairs = alignTokens(
|
|
645
|
+
ref.map((w) => w.norm),
|
|
646
|
+
hyp.map((w) => w.norm)
|
|
647
|
+
);
|
|
648
|
+
let correct = 0;
|
|
649
|
+
let substitutions = 0;
|
|
650
|
+
let deletions = 0;
|
|
651
|
+
let insertions = 0;
|
|
652
|
+
const matched = [];
|
|
653
|
+
for (const p of pairs) {
|
|
654
|
+
if (p.ai !== null && p.bi !== null) {
|
|
655
|
+
if (p.match) {
|
|
656
|
+
correct++;
|
|
657
|
+
matched.push({ ri: p.ai, hi: p.bi, correct: true });
|
|
658
|
+
} else {
|
|
659
|
+
substitutions++;
|
|
660
|
+
matched.push({ ri: p.ai, hi: p.bi, correct: false });
|
|
661
|
+
}
|
|
662
|
+
} else if (p.ai !== null) {
|
|
663
|
+
deletions++;
|
|
664
|
+
} else if (p.bi !== null) {
|
|
665
|
+
insertions++;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
const refWords = ref.length;
|
|
669
|
+
const wer = refWords > 0 ? (substitutions + deletions + insertions) / refWords : 0;
|
|
670
|
+
const refSpeakers = [...new Set(ref.map((w) => w.speaker))];
|
|
671
|
+
const hypSpeakers = [...new Set(hyp.map((w) => w.speaker))];
|
|
672
|
+
const confusion = /* @__PURE__ */ new Map();
|
|
673
|
+
for (const hs of hypSpeakers) confusion.set(hs, /* @__PURE__ */ new Map());
|
|
674
|
+
for (const m of matched) {
|
|
675
|
+
const hs = hyp[m.hi].speaker;
|
|
676
|
+
const rs = ref[m.ri].speaker;
|
|
677
|
+
const row = confusion.get(hs);
|
|
678
|
+
row.set(rs, (row.get(rs) ?? 0) + 1);
|
|
679
|
+
}
|
|
680
|
+
const speakerMapping = {};
|
|
681
|
+
for (const hs of hypSpeakers) {
|
|
682
|
+
const row = confusion.get(hs);
|
|
683
|
+
let best = "";
|
|
684
|
+
let bestN = -1;
|
|
685
|
+
for (const rs of refSpeakers) {
|
|
686
|
+
const n = row.get(rs) ?? 0;
|
|
687
|
+
if (n > bestN) {
|
|
688
|
+
bestN = n;
|
|
689
|
+
best = rs;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
speakerMapping[hs] = best;
|
|
693
|
+
}
|
|
694
|
+
let speakerAgree = 0;
|
|
695
|
+
for (const m of matched) {
|
|
696
|
+
const mappedHyp = speakerMapping[hyp[m.hi].speaker];
|
|
697
|
+
if (mappedHyp === ref[m.ri].speaker) speakerAgree++;
|
|
698
|
+
}
|
|
699
|
+
const speakerAccuracy = matched.length > 0 ? speakerAgree / matched.length : 0;
|
|
700
|
+
const timeErrors = [];
|
|
701
|
+
const boundaryErrors = [];
|
|
702
|
+
for (const m of matched) {
|
|
703
|
+
if (!m.correct) continue;
|
|
704
|
+
const refW = ref[m.ri];
|
|
705
|
+
const hypW = hyp[m.hi];
|
|
706
|
+
timeErrors.push(Math.abs(hypW.start - refW.start));
|
|
707
|
+
if (refW.isBoundary) boundaryErrors.push(Math.abs(hypW.start - refW.start));
|
|
708
|
+
}
|
|
709
|
+
timeErrors.sort((a, b) => a - b);
|
|
710
|
+
boundaryErrors.sort((a, b) => a - b);
|
|
711
|
+
const timeMean = timeErrors.length > 0 ? timeErrors.reduce((a, b) => a + b, 0) / timeErrors.length : 0;
|
|
712
|
+
const boundaryMean = boundaryErrors.length > 0 ? boundaryErrors.reduce((a, b) => a + b, 0) / boundaryErrors.length : 0;
|
|
713
|
+
return {
|
|
714
|
+
refWords,
|
|
715
|
+
hypWords: hyp.length,
|
|
716
|
+
correct,
|
|
717
|
+
substitutions,
|
|
718
|
+
deletions,
|
|
719
|
+
insertions,
|
|
720
|
+
wer,
|
|
721
|
+
speakerAccuracy,
|
|
722
|
+
speakerMapping,
|
|
723
|
+
matchedForSpeaker: matched.length,
|
|
724
|
+
timeMedian: percentile(timeErrors, 50),
|
|
725
|
+
timeP90: percentile(timeErrors, 90),
|
|
726
|
+
timeMean,
|
|
727
|
+
timedMatches: timeErrors.length,
|
|
728
|
+
boundaryMedian: percentile(boundaryErrors, 50),
|
|
729
|
+
boundaryP90: percentile(boundaryErrors, 90),
|
|
730
|
+
boundaryMean,
|
|
731
|
+
boundaryMatches: boundaryErrors.length
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// src/core/retry.ts
|
|
736
|
+
function isRetryableError(err) {
|
|
737
|
+
const e = err;
|
|
738
|
+
const code = e?.status ?? e?.code;
|
|
739
|
+
if (typeof code === "number" && [408, 429, 500, 502, 503, 504].includes(code)) return true;
|
|
740
|
+
const msg = (e?.message ?? String(err)).toLowerCase();
|
|
741
|
+
return /unavailable|overloaded|rate.?limit|deadline|timeout|temporar|try again|resource.?exhausted|\b(429|500|502|503|504)\b|internal error|econnreset|etimedout|socket hang|fetch failed|network/.test(
|
|
742
|
+
msg
|
|
743
|
+
);
|
|
744
|
+
}
|
|
745
|
+
async function withRetry(fn, opts = {}) {
|
|
746
|
+
const retries = opts.retries ?? 4;
|
|
747
|
+
const base = opts.baseDelayMs ?? 1e3;
|
|
748
|
+
let lastErr;
|
|
749
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
750
|
+
try {
|
|
751
|
+
return await fn();
|
|
752
|
+
} catch (err) {
|
|
753
|
+
lastErr = err;
|
|
754
|
+
if (attempt === retries || !isRetryableError(err)) throw err;
|
|
755
|
+
const delayMs = Math.min(3e4, base * 2 ** attempt) + Math.floor(Math.random() * 250);
|
|
756
|
+
opts.onRetry?.({ attempt: attempt + 1, retries, delayMs, error: err });
|
|
757
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
throw lastErr;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
// src/core/identify.ts
|
|
764
|
+
var IDENTIFY_SCHEMA = {
|
|
765
|
+
type: "OBJECT",
|
|
766
|
+
properties: {
|
|
767
|
+
speakers: {
|
|
768
|
+
type: "ARRAY",
|
|
769
|
+
items: {
|
|
770
|
+
type: "OBJECT",
|
|
771
|
+
properties: {
|
|
772
|
+
rawLabels: { type: "ARRAY", items: { type: "STRING" } },
|
|
773
|
+
name: { type: "STRING" },
|
|
774
|
+
description: { type: "STRING" }
|
|
775
|
+
},
|
|
776
|
+
required: ["rawLabels", "name"]
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
},
|
|
780
|
+
required: ["speakers"]
|
|
781
|
+
};
|
|
782
|
+
function buildVoiceHint(dist) {
|
|
783
|
+
const lines = [];
|
|
784
|
+
for (const [label, counts] of Object.entries(dist)) {
|
|
785
|
+
const sorted = Object.entries(counts).sort((a, b) => b[1] - a[1]);
|
|
786
|
+
const total = sorted.reduce((s2, [, n]) => s2 + n, 0);
|
|
787
|
+
if (total === 0) continue;
|
|
788
|
+
const top = sorted.slice(0, 2).map(([sp, n]) => `${sp}=${Math.round(100 * n / total)}%`).join(", ");
|
|
789
|
+
lines.push(` "${label}" \u2192 voice ${top}`);
|
|
790
|
+
}
|
|
791
|
+
return lines.join("\n");
|
|
792
|
+
}
|
|
793
|
+
function exampleTurns(turns, perLabel = 2, maxChars = 200) {
|
|
794
|
+
const byLabel = /* @__PURE__ */ new Map();
|
|
795
|
+
for (const t of turns) {
|
|
796
|
+
const arr = byLabel.get(t.speaker);
|
|
797
|
+
if (arr) arr.push(t);
|
|
798
|
+
else byLabel.set(t.speaker, [t]);
|
|
799
|
+
}
|
|
800
|
+
const lines = [];
|
|
801
|
+
for (const [label, ts] of byLabel) {
|
|
802
|
+
const top = [...ts].sort((a, b) => b.text.length - a.text.length).slice(0, perLabel);
|
|
803
|
+
lines.push(`Label "${label}" (${ts.length} turns). Examples:`);
|
|
804
|
+
for (const t of top) {
|
|
805
|
+
const text = t.text.length > maxChars ? t.text.slice(0, maxChars) + "\u2026" : t.text;
|
|
806
|
+
lines.push(` - ${text}`);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
return lines.join("\n");
|
|
810
|
+
}
|
|
811
|
+
function buildIdentifyPrompt(turns, options) {
|
|
812
|
+
const labels = [...new Set(turns.map((t) => t.speaker))];
|
|
813
|
+
const examples = exampleTurns(turns);
|
|
814
|
+
return `Below is a diarized transcript's speaker labels with example utterances. The labels may be inconsistent: the same person can appear under a provisional label (like "Speaker 1") early on and under their real name later, once it became known. Different people may share a generic label.
|
|
815
|
+
|
|
816
|
+
Your job: produce the canonical set of speakers.
|
|
817
|
+
- Merge labels that refer to the SAME person.
|
|
818
|
+
- Give each canonical speaker a name if it can be inferred from the transcript (someone introduces themselves, or is addressed by name); otherwise keep a clean generic label like "Speaker 1".
|
|
819
|
+
- Add a short role/description if evident (e.g. "main presenter", "audience member").
|
|
820
|
+
- Each canonical speaker must be exactly ONE person. NEVER create a catch-all like "Panel", "Multiple", "Various", or "Mixed". If a raw label seems to cover overlapping/multiple voices, assign it to the single most likely dominant speaker (use the voice analysis below).
|
|
821
|
+
${options.instructions ? `- Follow these user instructions for naming/grouping: ${options.instructions}
|
|
822
|
+
` : ""}
|
|
823
|
+
Distinct raw labels: ${labels.map((l) => `"${l}"`).join(", ")}
|
|
824
|
+
|
|
825
|
+
${examples}
|
|
826
|
+
${options.asrSpeakerByLabel ? `
|
|
827
|
+
Voice analysis (a separate diarizer clustered the audio into voices A/B/C\u2026; this is a STRONG signal for merging \u2014 labels sharing the same dominant voice are usually the same person, regardless of what they say):
|
|
828
|
+
${buildVoiceHint(options.asrSpeakerByLabel)}
|
|
829
|
+
` : ""}
|
|
830
|
+
Respond with ONLY a JSON object (no prose, no code fence) of this shape:
|
|
831
|
+
{"speakers":[{"rawLabels":["Speaker 1","Rishi"],"name":"Rishi","description":"main presenter"}, ...]}
|
|
832
|
+
Every raw label above must appear in exactly one speaker's rawLabels.`;
|
|
833
|
+
}
|
|
834
|
+
function parseIdentifyJson(text) {
|
|
835
|
+
let t = text.trim();
|
|
836
|
+
t = t.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "");
|
|
837
|
+
const start = t.indexOf("{");
|
|
838
|
+
const end = t.lastIndexOf("}");
|
|
839
|
+
if (start === -1 || end === -1 || end < start) return null;
|
|
840
|
+
try {
|
|
841
|
+
const obj = JSON.parse(t.slice(start, end + 1));
|
|
842
|
+
if (obj && Array.isArray(obj.speakers)) return obj;
|
|
843
|
+
return null;
|
|
844
|
+
} catch {
|
|
845
|
+
return null;
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
async function identifySpeakersLLM(gen, turns, options = {}) {
|
|
849
|
+
const prompt = buildIdentifyPrompt(turns, options);
|
|
850
|
+
const res = await gen.generate([{ text: prompt }], {
|
|
851
|
+
model: options.llmModel ?? "gemini-flash-latest",
|
|
852
|
+
temperature: 0,
|
|
853
|
+
maxOutputTokens: 16384,
|
|
854
|
+
thinkingLevel: "MINIMAL",
|
|
855
|
+
schema: IDENTIFY_SCHEMA,
|
|
856
|
+
label: "identify"
|
|
857
|
+
});
|
|
858
|
+
const parsed = parseIdentifyJson(res.text);
|
|
859
|
+
const resolvedNames = {};
|
|
860
|
+
const descriptions = {};
|
|
861
|
+
if (parsed) {
|
|
862
|
+
for (const sp of parsed.speakers) {
|
|
863
|
+
if (!sp.name) continue;
|
|
864
|
+
for (const raw of sp.rawLabels ?? []) resolvedNames[raw] = sp.name;
|
|
865
|
+
if (sp.description) descriptions[sp.name] = sp.description;
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
return { resolvedNames, descriptions };
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
// src/core/assemble.ts
|
|
872
|
+
function alignTurnsToSegments(turns, asrWords, totalDuration, subSegment) {
|
|
873
|
+
if (!asrWords || asrWords.length === 0) {
|
|
874
|
+
const segments2 = turns.map((t, i) => {
|
|
875
|
+
const start = t.approxStart ?? 0;
|
|
876
|
+
const end = turns[i + 1]?.approxStart ?? totalDuration;
|
|
877
|
+
return {
|
|
878
|
+
start,
|
|
879
|
+
end: Math.max(start, end),
|
|
880
|
+
speakerLabel: t.speaker,
|
|
881
|
+
tone: t.tone,
|
|
882
|
+
text: t.text,
|
|
883
|
+
matchRatio: 0
|
|
884
|
+
};
|
|
885
|
+
});
|
|
886
|
+
return { segments: segments2, voiceDist: {} };
|
|
887
|
+
}
|
|
888
|
+
const tokens = alignLlmToAsr(turns, asrWords);
|
|
889
|
+
fillTokenTimes(tokens, totalDuration);
|
|
890
|
+
const voiceDist = asrSpeakerByLabel(tokens, turns.map((t) => t.speaker));
|
|
891
|
+
const aligned = buildSegmentsFromTokens(turns, tokens, { subSegment });
|
|
892
|
+
const segments = [];
|
|
893
|
+
const toneSeen = /* @__PURE__ */ new Set();
|
|
894
|
+
for (const s2 of aligned) {
|
|
895
|
+
if (s2.matchedTokens === 0 && s2.tokenCount <= 3) continue;
|
|
896
|
+
const turn = turns[s2.turnIndex];
|
|
897
|
+
const firstOfTurn = !toneSeen.has(s2.turnIndex);
|
|
898
|
+
toneSeen.add(s2.turnIndex);
|
|
899
|
+
segments.push({
|
|
900
|
+
start: s2.start,
|
|
901
|
+
end: s2.end,
|
|
902
|
+
speakerLabel: turn.speaker,
|
|
903
|
+
tone: firstOfTurn ? turn.tone : void 0,
|
|
904
|
+
text: s2.text,
|
|
905
|
+
matchRatio: s2.matchRatio
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
return { segments, voiceDist };
|
|
909
|
+
}
|
|
910
|
+
function buildTranscript(segments, metadata, options = {}) {
|
|
911
|
+
const { knownSpeakers, resolvedNames, descriptions } = options;
|
|
912
|
+
const { speakers, labelToId } = buildSpeakers(
|
|
913
|
+
segments.map((s2) => s2.speakerLabel),
|
|
914
|
+
{ knownSpeakers, resolvedNames, descriptions }
|
|
915
|
+
);
|
|
916
|
+
const transcriptSegments = segments.map((s2, i) => ({
|
|
917
|
+
id: i + 1,
|
|
918
|
+
start: s2.start,
|
|
919
|
+
end: s2.end,
|
|
920
|
+
speakerId: labelToId.get(s2.speakerLabel) ?? s2.speakerLabel,
|
|
921
|
+
text: s2.text,
|
|
922
|
+
tone: s2.tone,
|
|
923
|
+
timingSource: s2.matchRatio > 0 ? "asr" : "llm",
|
|
924
|
+
alignmentConfidence: s2.matchRatio
|
|
925
|
+
}));
|
|
926
|
+
return { segments: transcriptSegments, speakers, metadata };
|
|
927
|
+
}
|
|
928
|
+
function assembleTranscript(input, options = {}) {
|
|
929
|
+
const { turns, asr, durationSeconds } = input;
|
|
930
|
+
const { segments, voiceDist } = alignTurnsToSegments(
|
|
931
|
+
turns,
|
|
932
|
+
asr?.words,
|
|
933
|
+
durationSeconds,
|
|
934
|
+
true
|
|
935
|
+
);
|
|
936
|
+
const metadata = {
|
|
937
|
+
source: "browser",
|
|
938
|
+
durationSeconds,
|
|
939
|
+
processedAt: "",
|
|
940
|
+
asrProvider: asr?.provider,
|
|
941
|
+
language: asr?.language
|
|
942
|
+
};
|
|
943
|
+
const transcript = buildTranscript(segments, metadata, options);
|
|
944
|
+
return { transcript, voiceDist };
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
// src/providers/thinking.ts
|
|
948
|
+
var BUDGET_BY_LEVEL = {
|
|
949
|
+
// 2.5: flash can disable (0); pro cannot go below ~128.
|
|
950
|
+
MINIMAL: { flash: 0, pro: 128 },
|
|
951
|
+
LOW: { flash: 2048, pro: 2048 },
|
|
952
|
+
MEDIUM: { flash: 8192, pro: 8192 },
|
|
953
|
+
HIGH: { flash: 24576, pro: 24576 }
|
|
954
|
+
};
|
|
955
|
+
function resolveThinkingConfig(model, level, explicitBudget) {
|
|
956
|
+
const m = model.toLowerCase();
|
|
957
|
+
const isPro = m.includes("pro");
|
|
958
|
+
if (explicitBudget !== void 0 && m.includes("gemini-2.5")) {
|
|
959
|
+
return { thinkingBudget: explicitBudget };
|
|
960
|
+
}
|
|
961
|
+
if (level === void 0) return void 0;
|
|
962
|
+
if (m.includes("gemini-2.5")) {
|
|
963
|
+
return { thinkingBudget: BUDGET_BY_LEVEL[level][isPro ? "pro" : "flash"] };
|
|
964
|
+
}
|
|
965
|
+
if (m.includes("gemini-2")) {
|
|
966
|
+
return void 0;
|
|
967
|
+
}
|
|
968
|
+
if (isPro) {
|
|
969
|
+
return { thinkingLevel: level === "MINIMAL" ? "LOW" : level };
|
|
970
|
+
}
|
|
971
|
+
return { thinkingLevel: level };
|
|
972
|
+
}
|
|
973
|
+
function isThinkingConfigError(err) {
|
|
974
|
+
const msg = (err?.message ?? String(err)).toLowerCase();
|
|
975
|
+
return /thinking[_ ]?(level|budget)|thinking.*(not supported|unsupported)/.test(msg);
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
// src/providers/gemini-fetch.ts
|
|
979
|
+
var DEFAULT_BASE = "https://generativelanguage.googleapis.com";
|
|
980
|
+
async function toUint8(b) {
|
|
981
|
+
if (b instanceof Uint8Array) return b;
|
|
982
|
+
if (b instanceof ArrayBuffer) return new Uint8Array(b);
|
|
983
|
+
return new Uint8Array(await b.arrayBuffer());
|
|
984
|
+
}
|
|
985
|
+
async function fetchOk(url, init) {
|
|
986
|
+
const res = await fetch(url, init);
|
|
987
|
+
if (!res.ok) {
|
|
988
|
+
const body = await res.text().catch(() => "");
|
|
989
|
+
const err = new Error(`HTTP ${res.status} ${url.split("?")[0]}: ${body.slice(0, 300)}`);
|
|
990
|
+
err.status = res.status;
|
|
991
|
+
throw err;
|
|
992
|
+
}
|
|
993
|
+
return res;
|
|
994
|
+
}
|
|
995
|
+
var GeminiFetchClient = class {
|
|
996
|
+
key;
|
|
997
|
+
base;
|
|
998
|
+
/** if set, invoked once per generate() with the prompt/response/usage (for logging). */
|
|
999
|
+
onCall;
|
|
1000
|
+
constructor(apiKey, baseUrl = DEFAULT_BASE) {
|
|
1001
|
+
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
1002
|
+
const key = apiKey ?? env?.["GEMINI_API_KEY"] ?? env?.["GOOGLE_API_KEY"];
|
|
1003
|
+
if (!key) throw new Error("Missing GEMINI_API_KEY / GOOGLE_API_KEY");
|
|
1004
|
+
this.key = key;
|
|
1005
|
+
this.base = baseUrl;
|
|
1006
|
+
}
|
|
1007
|
+
/** Upload media via the Files API resumable protocol; poll until ACTIVE. */
|
|
1008
|
+
async uploadFile(bytes, mimeType, displayName = "media") {
|
|
1009
|
+
const buf = await toUint8(bytes);
|
|
1010
|
+
const numBytes = buf.byteLength;
|
|
1011
|
+
const start = await withRetry(
|
|
1012
|
+
() => fetchOk(`${this.base}/upload/v1beta/files?key=${this.key}`, {
|
|
1013
|
+
method: "POST",
|
|
1014
|
+
headers: {
|
|
1015
|
+
"X-Goog-Upload-Protocol": "resumable",
|
|
1016
|
+
"X-Goog-Upload-Command": "start",
|
|
1017
|
+
"X-Goog-Upload-Header-Content-Length": String(numBytes),
|
|
1018
|
+
"X-Goog-Upload-Header-Content-Type": mimeType,
|
|
1019
|
+
"Content-Type": "application/json"
|
|
1020
|
+
},
|
|
1021
|
+
body: JSON.stringify({ file: { display_name: displayName } })
|
|
1022
|
+
}),
|
|
1023
|
+
{ retries: 3 }
|
|
1024
|
+
);
|
|
1025
|
+
const uploadUrl = start.headers.get("x-goog-upload-url");
|
|
1026
|
+
if (!uploadUrl) throw new Error("Gemini Files API: missing upload URL");
|
|
1027
|
+
const finalize = await withRetry(
|
|
1028
|
+
() => fetchOk(uploadUrl, {
|
|
1029
|
+
method: "POST",
|
|
1030
|
+
headers: {
|
|
1031
|
+
"X-Goog-Upload-Command": "upload, finalize",
|
|
1032
|
+
"X-Goog-Upload-Offset": "0",
|
|
1033
|
+
"Content-Length": String(numBytes)
|
|
1034
|
+
},
|
|
1035
|
+
// Uint8Array is a valid BodyInit in node 18+ and browsers
|
|
1036
|
+
body: buf
|
|
1037
|
+
}),
|
|
1038
|
+
{ retries: 3 }
|
|
1039
|
+
);
|
|
1040
|
+
let file = (await finalize.json()).file;
|
|
1041
|
+
while (file.state === "PROCESSING") {
|
|
1042
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
1043
|
+
file = await fetchOk(`${this.base}/v1beta/${file.name}?key=${this.key}`, { method: "GET" }).then((r) => r.json());
|
|
1044
|
+
}
|
|
1045
|
+
if (file.state === "FAILED") throw new Error(`Gemini file processing failed: ${file.name}`);
|
|
1046
|
+
return { uri: file.uri, mimeType: file.mimeType, name: file.name, state: file.state };
|
|
1047
|
+
}
|
|
1048
|
+
async deleteFile(name) {
|
|
1049
|
+
try {
|
|
1050
|
+
await fetch(`${this.base}/v1beta/${name}?key=${this.key}`, { method: "DELETE" });
|
|
1051
|
+
} catch {
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
async generate(parts, options = {}) {
|
|
1055
|
+
const model = options.model ?? "gemini-flash-latest";
|
|
1056
|
+
const built = [];
|
|
1057
|
+
const cleanup = [];
|
|
1058
|
+
for (const p of parts) {
|
|
1059
|
+
if (p.text !== void 0) built.push({ text: p.text });
|
|
1060
|
+
else if (p.uploaded) built.push({ fileData: { fileUri: p.uploaded.uri, mimeType: p.uploaded.mimeType } });
|
|
1061
|
+
else if (p.data) {
|
|
1062
|
+
const up = await this.uploadFile(p.data.bytes, p.data.mimeType, p.data.displayName);
|
|
1063
|
+
cleanup.push(up.name);
|
|
1064
|
+
built.push({ fileData: { fileUri: up.uri, mimeType: up.mimeType } });
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
const generationConfig = { temperature: options.temperature ?? 0.2 };
|
|
1068
|
+
if (options.maxOutputTokens) generationConfig["maxOutputTokens"] = options.maxOutputTokens;
|
|
1069
|
+
const thinking = resolveThinkingConfig(model, options.thinkingLevel, options.thinkingBudget);
|
|
1070
|
+
if (thinking) generationConfig["thinkingConfig"] = thinking;
|
|
1071
|
+
if (options.schema) {
|
|
1072
|
+
generationConfig["responseMimeType"] = "application/json";
|
|
1073
|
+
generationConfig["responseSchema"] = options.schema;
|
|
1074
|
+
}
|
|
1075
|
+
const makeBody = (genCfg) => {
|
|
1076
|
+
const b = { contents: [{ role: "user", parts: built }], generationConfig: genCfg };
|
|
1077
|
+
if (options.systemInstruction) b["systemInstruction"] = { parts: [{ text: options.systemInstruction }] };
|
|
1078
|
+
return b;
|
|
1079
|
+
};
|
|
1080
|
+
const callJson = (genCfg) => withRetry(
|
|
1081
|
+
() => fetchOk(`${this.base}/v1beta/models/${model}:generateContent?key=${this.key}`, {
|
|
1082
|
+
method: "POST",
|
|
1083
|
+
headers: { "Content-Type": "application/json" },
|
|
1084
|
+
body: JSON.stringify(makeBody(genCfg))
|
|
1085
|
+
}).then((r) => r.json()),
|
|
1086
|
+
{ retries: options.retries ?? 4 }
|
|
1087
|
+
);
|
|
1088
|
+
try {
|
|
1089
|
+
let resp;
|
|
1090
|
+
try {
|
|
1091
|
+
resp = await callJson(generationConfig);
|
|
1092
|
+
} catch (err) {
|
|
1093
|
+
if (isThinkingConfigError(err) && generationConfig["thinkingConfig"]) {
|
|
1094
|
+
const { thinkingConfig: _drop, ...rest } = generationConfig;
|
|
1095
|
+
resp = await callJson(rest);
|
|
1096
|
+
} else {
|
|
1097
|
+
throw err;
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
resp = resp;
|
|
1101
|
+
const text = (resp.candidates?.[0]?.content?.parts ?? []).map((p) => p.text ?? "").join("");
|
|
1102
|
+
const u = resp.usageMetadata;
|
|
1103
|
+
const usage = { inputTokens: u?.promptTokenCount, outputTokens: u?.candidatesTokenCount, thoughtsTokens: u?.thoughtsTokenCount };
|
|
1104
|
+
this.onCall?.({
|
|
1105
|
+
label: options.label,
|
|
1106
|
+
model,
|
|
1107
|
+
promptText: parts.filter((p) => p.text !== void 0).map((p) => p.text).join("\n"),
|
|
1108
|
+
fileParts: parts.filter((p) => p.data || p.uploaded).length,
|
|
1109
|
+
responseText: text,
|
|
1110
|
+
usage
|
|
1111
|
+
});
|
|
1112
|
+
return { text, usage, model, raw: resp };
|
|
1113
|
+
} finally {
|
|
1114
|
+
await Promise.all(cleanup.map((n) => this.deleteFile(n)));
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
};
|
|
1118
|
+
|
|
1119
|
+
// src/providers/assemblyai-fetch.ts
|
|
1120
|
+
var BASE = "https://api.assemblyai.com/v2";
|
|
1121
|
+
var s = (ms) => (ms ?? 0) / 1e3;
|
|
1122
|
+
async function toBlobBody(b) {
|
|
1123
|
+
if (b instanceof Uint8Array || b instanceof ArrayBuffer) return b;
|
|
1124
|
+
return b;
|
|
1125
|
+
}
|
|
1126
|
+
async function transcribeWithAssemblyAIFetch(audio, options = {}) {
|
|
1127
|
+
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
1128
|
+
const key = options.apiKey ?? env?.["ASSEMBLYAI_API_KEY"];
|
|
1129
|
+
if (!key) throw new Error("Missing ASSEMBLYAI_API_KEY");
|
|
1130
|
+
const auth = { authorization: key };
|
|
1131
|
+
const pollMs = options.pollMs ?? 2e3;
|
|
1132
|
+
const uploaded = await withRetry(
|
|
1133
|
+
async () => {
|
|
1134
|
+
const res = await fetch(`${BASE}/upload`, { method: "POST", headers: auth, body: await toBlobBody(audio) });
|
|
1135
|
+
if (!res.ok) {
|
|
1136
|
+
const e = new Error(`AssemblyAI upload HTTP ${res.status}`);
|
|
1137
|
+
e.status = res.status;
|
|
1138
|
+
throw e;
|
|
1139
|
+
}
|
|
1140
|
+
return res.json();
|
|
1141
|
+
},
|
|
1142
|
+
{ retries: 3 }
|
|
1143
|
+
);
|
|
1144
|
+
const params = { audio_url: uploaded.upload_url, speaker_labels: options.speakerLabels !== false };
|
|
1145
|
+
if (options.speakersExpected) params["speakers_expected"] = options.speakersExpected;
|
|
1146
|
+
if (options.languageCode) params["language_code"] = options.languageCode;
|
|
1147
|
+
if (options.speechModel) params["speech_model"] = options.speechModel;
|
|
1148
|
+
const created = await withRetry(
|
|
1149
|
+
async () => {
|
|
1150
|
+
const res = await fetch(`${BASE}/transcript`, {
|
|
1151
|
+
method: "POST",
|
|
1152
|
+
headers: { ...auth, "content-type": "application/json" },
|
|
1153
|
+
body: JSON.stringify(params)
|
|
1154
|
+
});
|
|
1155
|
+
if (!res.ok) {
|
|
1156
|
+
const e = new Error(`AssemblyAI create HTTP ${res.status}`);
|
|
1157
|
+
e.status = res.status;
|
|
1158
|
+
throw e;
|
|
1159
|
+
}
|
|
1160
|
+
return res.json();
|
|
1161
|
+
},
|
|
1162
|
+
{ retries: 3 }
|
|
1163
|
+
);
|
|
1164
|
+
let t;
|
|
1165
|
+
for (; ; ) {
|
|
1166
|
+
t = await withRetry(() => fetch(`${BASE}/transcript/${created.id}`, { headers: auth }).then((r) => r.json()), { retries: 3 });
|
|
1167
|
+
if (t.status === "completed") break;
|
|
1168
|
+
if (t.status === "error") throw new Error(`AssemblyAI failed: ${t.error}`);
|
|
1169
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
1170
|
+
}
|
|
1171
|
+
const words = (t.words ?? []).map((w) => ({
|
|
1172
|
+
text: w.text,
|
|
1173
|
+
start: s(w.start),
|
|
1174
|
+
end: s(w.end),
|
|
1175
|
+
confidence: w.confidence,
|
|
1176
|
+
speaker: w.speaker ?? void 0
|
|
1177
|
+
}));
|
|
1178
|
+
const utterances = (t.utterances ?? []).map((u) => ({
|
|
1179
|
+
text: u.text,
|
|
1180
|
+
start: s(u.start),
|
|
1181
|
+
end: s(u.end),
|
|
1182
|
+
speaker: u.speaker ?? "?",
|
|
1183
|
+
confidence: u.confidence,
|
|
1184
|
+
words: u.words?.map((w) => ({ text: w.text, start: s(w.start), end: s(w.end), confidence: w.confidence, speaker: w.speaker ?? void 0 }))
|
|
1185
|
+
}));
|
|
1186
|
+
const speakers = [.../* @__PURE__ */ new Set([...utterances.map((u) => u.speaker), ...words.map((w) => w.speaker).filter(Boolean)])].sort();
|
|
1187
|
+
const asr = {
|
|
1188
|
+
provider: "assemblyai",
|
|
1189
|
+
model: options.speechModel,
|
|
1190
|
+
words,
|
|
1191
|
+
utterances,
|
|
1192
|
+
speakers,
|
|
1193
|
+
durationSeconds: t.audio_duration ?? (words.length ? words[words.length - 1].end : 0),
|
|
1194
|
+
language: t.language_code,
|
|
1195
|
+
diarized: utterances.length > 0 && speakers.length > 0
|
|
1196
|
+
};
|
|
1197
|
+
return { asr, raw: t };
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
// src/media/ffmpeg-wasm.ts
|
|
1201
|
+
var counter = 0;
|
|
1202
|
+
var tmpName = (ext) => `__offmute_${counter++}.${ext}`;
|
|
1203
|
+
async function tryDelete(ff, name) {
|
|
1204
|
+
try {
|
|
1205
|
+
await ff.deleteFile?.(name);
|
|
1206
|
+
} catch {
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
var AUDIO_CODEC = {
|
|
1210
|
+
mp3: ["-c:a", "libmp3lame"],
|
|
1211
|
+
opus: ["-c:a", "libopus"],
|
|
1212
|
+
wav: ["-c:a", "pcm_s16le"],
|
|
1213
|
+
m4a: ["-c:a", "aac"]
|
|
1214
|
+
};
|
|
1215
|
+
async function extractAudioWasm(ff, input, opts = {}) {
|
|
1216
|
+
const {
|
|
1217
|
+
sampleRate = 16e3,
|
|
1218
|
+
channels = 1,
|
|
1219
|
+
startSeconds,
|
|
1220
|
+
durationSeconds,
|
|
1221
|
+
bitrate = "64k",
|
|
1222
|
+
format = "mp3",
|
|
1223
|
+
inputName,
|
|
1224
|
+
keepInput = false
|
|
1225
|
+
} = opts;
|
|
1226
|
+
let inName = inputName;
|
|
1227
|
+
let wrote = false;
|
|
1228
|
+
if (!inName) {
|
|
1229
|
+
if (!input) throw new Error("extractAudioWasm: provide input bytes or inputName");
|
|
1230
|
+
inName = tmpName("bin");
|
|
1231
|
+
await ff.writeFile(inName, input);
|
|
1232
|
+
wrote = true;
|
|
1233
|
+
}
|
|
1234
|
+
const outName = tmpName(format);
|
|
1235
|
+
const args = [];
|
|
1236
|
+
if (startSeconds !== void 0) args.push("-ss", String(startSeconds));
|
|
1237
|
+
args.push("-i", inName);
|
|
1238
|
+
if (durationSeconds !== void 0) args.push("-t", String(durationSeconds));
|
|
1239
|
+
args.push("-vn", "-ac", String(channels), "-ar", String(sampleRate), ...AUDIO_CODEC[format] ?? AUDIO_CODEC["mp3"]);
|
|
1240
|
+
if (format !== "wav") args.push("-b:a", bitrate);
|
|
1241
|
+
args.push(outName);
|
|
1242
|
+
try {
|
|
1243
|
+
await ff.exec(args);
|
|
1244
|
+
const out = await ff.readFile(outName);
|
|
1245
|
+
return out;
|
|
1246
|
+
} finally {
|
|
1247
|
+
await tryDelete(ff, outName);
|
|
1248
|
+
if (wrote && !keepInput) await tryDelete(ff, inName);
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
async function extractKeyframesWasm(ff, input, opts) {
|
|
1252
|
+
const { atSeconds, maxSize = 768, inputName } = opts;
|
|
1253
|
+
let inName = inputName;
|
|
1254
|
+
let wrote = false;
|
|
1255
|
+
if (!inName) {
|
|
1256
|
+
if (!input) throw new Error("extractKeyframesWasm: provide input bytes or inputName");
|
|
1257
|
+
inName = tmpName("bin");
|
|
1258
|
+
await ff.writeFile(inName, input);
|
|
1259
|
+
wrote = true;
|
|
1260
|
+
}
|
|
1261
|
+
const frames = [];
|
|
1262
|
+
try {
|
|
1263
|
+
for (const t of atSeconds) {
|
|
1264
|
+
const out = tmpName("jpg");
|
|
1265
|
+
await ff.exec(["-ss", String(t), "-i", inName, "-frames:v", "1", "-vf", `scale='min(${maxSize},iw)':-2`, "-q:v", "3", out]);
|
|
1266
|
+
frames.push(await ff.readFile(out));
|
|
1267
|
+
await tryDelete(ff, out);
|
|
1268
|
+
}
|
|
1269
|
+
} finally {
|
|
1270
|
+
if (wrote) await tryDelete(ff, inName);
|
|
1271
|
+
}
|
|
1272
|
+
return frames;
|
|
1273
|
+
}
|
|
1274
|
+
async function writeInput(ff, bytes, name = "__offmute_source") {
|
|
1275
|
+
await ff.writeFile(name, bytes);
|
|
1276
|
+
return name;
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
// src/core/orchestrate.ts
|
|
1280
|
+
function sliceAsrWindow(asr, start, end, relative) {
|
|
1281
|
+
const off = relative ? start : 0;
|
|
1282
|
+
const utterances = asr.utterances.filter((u) => u.end >= start && u.start <= end).map((u) => ({ ...u, start: u.start - off, end: u.end - off }));
|
|
1283
|
+
return { ...asr, utterances, words: [] };
|
|
1284
|
+
}
|
|
1285
|
+
function mergeVoiceDist(target, source) {
|
|
1286
|
+
for (const [label, counts] of Object.entries(source)) {
|
|
1287
|
+
target[label] ??= {};
|
|
1288
|
+
for (const [sp, n] of Object.entries(counts)) target[label][sp] = (target[label][sp] ?? 0) + n;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
var toPlain = (m) => ({
|
|
1292
|
+
start: m.start,
|
|
1293
|
+
end: m.end,
|
|
1294
|
+
speakerLabel: m.speakerLabel,
|
|
1295
|
+
tone: m.tone,
|
|
1296
|
+
text: m.text,
|
|
1297
|
+
matchRatio: m.matchRatio
|
|
1298
|
+
});
|
|
1299
|
+
async function orchestrateChunks(opts) {
|
|
1300
|
+
const { asr, durationSeconds, instructions, subSegment, signal, onProgress, diarizeChunk, onChunk } = opts;
|
|
1301
|
+
const timeChunks = durationSeconds <= opts.maxSinglePassSeconds ? [{ index: 0, startSeconds: 0, endSeconds: durationSeconds }] : calculateChunks(durationSeconds, opts.chunkSeconds, opts.overlapSeconds);
|
|
1302
|
+
const chunked = timeChunks.length > 1;
|
|
1303
|
+
const ownership = chunked ? chunkOwnership(timeChunks, durationSeconds) : null;
|
|
1304
|
+
const allTurns = [];
|
|
1305
|
+
const mergeable = [];
|
|
1306
|
+
const voiceDist = {};
|
|
1307
|
+
let previousTail = "";
|
|
1308
|
+
for (const ch of timeChunks) {
|
|
1309
|
+
signal?.throwIfAborted();
|
|
1310
|
+
onProgress?.(chunked ? `Diarizing chunk ${ch.index + 1}/${timeChunks.length}` : `Diarizing`, ch.index, timeChunks.length);
|
|
1311
|
+
const windowHint = asr && asr.diarized ? buildAsrHint(sliceAsrWindow(asr, ch.startSeconds, ch.endSeconds, chunked)) : void 0;
|
|
1312
|
+
const prompt = buildDiarizationPrompt({
|
|
1313
|
+
instructions,
|
|
1314
|
+
asrHint: windowHint,
|
|
1315
|
+
chunk: chunked ? { index: ch.index, total: timeChunks.length, startSeconds: ch.startSeconds } : void 0,
|
|
1316
|
+
previousTail: chunked ? previousTail : void 0
|
|
1317
|
+
});
|
|
1318
|
+
const rawText = await diarizeChunk({ chunk: ch, index: ch.index, total: timeChunks.length, chunked, prompt });
|
|
1319
|
+
const turns = parseDiarizedText(rawText);
|
|
1320
|
+
if (turns.length === 0) throw new Error(`No diarized turns parsed from LLM output${chunked ? ` (chunk ${ch.index})` : ""}`);
|
|
1321
|
+
previousTail = turns.slice(-3).map((t) => `${t.speaker}: ${t.text}`).join("\n");
|
|
1322
|
+
if (chunked) {
|
|
1323
|
+
for (const t of turns) if (t.approxStart !== void 0) t.approxStart += ch.startSeconds;
|
|
1324
|
+
}
|
|
1325
|
+
allTurns.push(...turns);
|
|
1326
|
+
if (asr) {
|
|
1327
|
+
const windowWords = chunked ? asr.words.filter((w) => w.start >= ch.startSeconds - 2 && w.start <= ch.endSeconds + 2) : asr.words;
|
|
1328
|
+
const { segments: segments2, voiceDist: vd } = alignTurnsToSegments(turns, windowWords, durationSeconds, subSegment);
|
|
1329
|
+
mergeVoiceDist(voiceDist, vd);
|
|
1330
|
+
const own = ownership?.[ch.index];
|
|
1331
|
+
for (const s2 of segments2) {
|
|
1332
|
+
if (own) {
|
|
1333
|
+
const center = (s2.start + s2.end) / 2;
|
|
1334
|
+
if (center < own.start || center >= own.end) continue;
|
|
1335
|
+
}
|
|
1336
|
+
mergeable.push({ ...s2, chunkIndex: ch.index });
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
if (onChunk) {
|
|
1340
|
+
const segmentsSoFar = [...mergeable].sort((a, b) => a.start - b.start).map(toPlain);
|
|
1341
|
+
await onChunk({ index: ch.index, total: timeChunks.length, chunked, rawText, turns, segmentsSoFar });
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
let segments;
|
|
1345
|
+
if (asr) {
|
|
1346
|
+
const merged = chunked ? mergeChunkSegments(mergeable, timeChunks) : mergeable;
|
|
1347
|
+
segments = merged.map(toPlain);
|
|
1348
|
+
} else {
|
|
1349
|
+
segments = alignTurnsToSegments(allTurns, void 0, durationSeconds, subSegment).segments;
|
|
1350
|
+
}
|
|
1351
|
+
return { segments, allTurns, voiceDist, chunkCount: timeChunks.length };
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
// src/browser-pipeline.ts
|
|
1355
|
+
async function transcribeInBrowser(input, options) {
|
|
1356
|
+
const {
|
|
1357
|
+
ffmpeg,
|
|
1358
|
+
apiKeys,
|
|
1359
|
+
instructions,
|
|
1360
|
+
llmModel = "gemini-flash-latest",
|
|
1361
|
+
llmThinkingLevel = "MINIMAL",
|
|
1362
|
+
useVideo = false,
|
|
1363
|
+
keyframeCount = 8,
|
|
1364
|
+
subSegment = true,
|
|
1365
|
+
identifySpeakers = true,
|
|
1366
|
+
knownSpeakers,
|
|
1367
|
+
onProgress
|
|
1368
|
+
} = options;
|
|
1369
|
+
const progress = (stage, message) => onProgress?.({ stage, message });
|
|
1370
|
+
const sourceBytes = input instanceof Uint8Array ? input : new Uint8Array(await input.arrayBuffer());
|
|
1371
|
+
progress("preprocess", "Decoding audio (ffmpeg.wasm)");
|
|
1372
|
+
const sourceName = await writeInput(ffmpeg, sourceBytes, "__offmute_source");
|
|
1373
|
+
const fullAudio = await extractAudioWasm(ffmpeg, null, { inputName: sourceName, keepInput: true });
|
|
1374
|
+
const fullAudioName = await writeInput(ffmpeg, fullAudio, "__offmute_audio.mp3");
|
|
1375
|
+
progress("asr", "Transcribing for timing (AssemblyAI)");
|
|
1376
|
+
const { asr } = await transcribeWithAssemblyAIFetch(fullAudio, { apiKey: apiKeys.assemblyai, speakerLabels: true });
|
|
1377
|
+
const duration = asr.durationSeconds;
|
|
1378
|
+
let keyframes = [];
|
|
1379
|
+
if (useVideo && keyframeCount > 0) {
|
|
1380
|
+
progress("preprocess", `Extracting ${keyframeCount} keyframes`);
|
|
1381
|
+
const atSeconds = Array.from({ length: keyframeCount }, (_, i) => Math.max(0.5, (i + 0.5) / keyframeCount * duration));
|
|
1382
|
+
try {
|
|
1383
|
+
keyframes = await extractKeyframesWasm(ffmpeg, null, { inputName: sourceName, atSeconds });
|
|
1384
|
+
} catch {
|
|
1385
|
+
keyframes = [];
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
const gem = new GeminiFetchClient(apiKeys.gemini);
|
|
1389
|
+
if (options.onLlmCall) gem.onCall = options.onLlmCall;
|
|
1390
|
+
const { segments: merged, allTurns, voiceDist } = await orchestrateChunks({
|
|
1391
|
+
asr,
|
|
1392
|
+
durationSeconds: duration,
|
|
1393
|
+
instructions,
|
|
1394
|
+
subSegment,
|
|
1395
|
+
maxSinglePassSeconds: (options.maxSinglePassMinutes ?? 35) * 60,
|
|
1396
|
+
chunkSeconds: (options.chunkMinutes ?? 15) * 60,
|
|
1397
|
+
overlapSeconds: (options.chunkOverlapMinutes ?? 2) * 60,
|
|
1398
|
+
signal: options.signal,
|
|
1399
|
+
onProgress: (msg) => progress("diarize", msg),
|
|
1400
|
+
// browser-specific: slice the chunk's audio with ffmpeg.wasm, call Gemini over fetch.
|
|
1401
|
+
diarizeChunk: async ({ chunk, chunked, prompt }) => {
|
|
1402
|
+
const audioBytes = chunked ? await extractAudioWasm(ffmpeg, null, { inputName: fullAudioName, startSeconds: chunk.startSeconds, durationSeconds: chunk.endSeconds - chunk.startSeconds, keepInput: true }) : fullAudio;
|
|
1403
|
+
const res = await gem.generate(
|
|
1404
|
+
[
|
|
1405
|
+
{ data: { bytes: audioBytes, mimeType: "audio/mp3", displayName: `chunk_${chunk.index}` } },
|
|
1406
|
+
...keyframes.map((kf) => ({ data: { bytes: kf, mimeType: "image/jpeg" } })),
|
|
1407
|
+
{ text: prompt }
|
|
1408
|
+
],
|
|
1409
|
+
{ model: llmModel, temperature: 0.2, maxOutputTokens: 65536, thinkingLevel: llmThinkingLevel, systemInstruction: DIARIZATION_SYSTEM, label: chunked ? `diarize-chunk-${chunk.index}` : "diarize" }
|
|
1410
|
+
);
|
|
1411
|
+
if (!res.text.trim()) throw new Error(`Diarization returned empty text${chunked ? ` (chunk ${chunk.index})` : ""}`);
|
|
1412
|
+
return res.text;
|
|
1413
|
+
}
|
|
1414
|
+
});
|
|
1415
|
+
let resolvedNames;
|
|
1416
|
+
let descriptions;
|
|
1417
|
+
if (identifySpeakers) {
|
|
1418
|
+
progress("identify", "Resolving speaker identities");
|
|
1419
|
+
const identGen = {
|
|
1420
|
+
generate: (parts, opts) => gem.generate(parts.map((p) => ({ text: p.text })), opts)
|
|
1421
|
+
};
|
|
1422
|
+
try {
|
|
1423
|
+
const ident = await identifySpeakersLLM(identGen, allTurns, {
|
|
1424
|
+
instructions,
|
|
1425
|
+
llmModel,
|
|
1426
|
+
asrSpeakerByLabel: Object.keys(voiceDist).length ? voiceDist : void 0
|
|
1427
|
+
});
|
|
1428
|
+
resolvedNames = ident.resolvedNames;
|
|
1429
|
+
descriptions = ident.descriptions;
|
|
1430
|
+
} catch {
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
progress("format", "Formatting outputs");
|
|
1434
|
+
const transcript = buildTranscript(
|
|
1435
|
+
merged,
|
|
1436
|
+
{
|
|
1437
|
+
source: "browser-input",
|
|
1438
|
+
durationSeconds: duration,
|
|
1439
|
+
processedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1440
|
+
asrProvider: asr.provider,
|
|
1441
|
+
llmModel,
|
|
1442
|
+
userInstructions: instructions,
|
|
1443
|
+
language: asr.language
|
|
1444
|
+
},
|
|
1445
|
+
{ knownSpeakers, resolvedNames, descriptions }
|
|
1446
|
+
);
|
|
1447
|
+
progress("done", `${transcript.segments.length} segments, ${transcript.speakers.length} speakers (${secondsToCompact(duration)})`);
|
|
1448
|
+
return { transcript, srt: toSRT(transcript), markdown: toMarkdown(transcript), json: toJSON(transcript), asr };
|
|
1449
|
+
}
|
|
1450
|
+
export {
|
|
1451
|
+
DIARIZATION_SYSTEM,
|
|
1452
|
+
GeminiFetchClient,
|
|
1453
|
+
alignLlmToAsr,
|
|
1454
|
+
alignTokens,
|
|
1455
|
+
alignTurnsToSegments,
|
|
1456
|
+
asrSpeakerByLabel,
|
|
1457
|
+
assembleTranscript,
|
|
1458
|
+
buildAsrHint,
|
|
1459
|
+
buildDiarizationPrompt,
|
|
1460
|
+
buildSegmentsFromTokens,
|
|
1461
|
+
buildSpeakers,
|
|
1462
|
+
buildTranscript,
|
|
1463
|
+
calculateChunks,
|
|
1464
|
+
chunkOwnership,
|
|
1465
|
+
evaluateWords,
|
|
1466
|
+
fillTokenTimes,
|
|
1467
|
+
formatSrt,
|
|
1468
|
+
formatSrtTiming,
|
|
1469
|
+
identifySpeakersLLM,
|
|
1470
|
+
isProvisional,
|
|
1471
|
+
isRetryableError,
|
|
1472
|
+
mergeChunkSegments,
|
|
1473
|
+
normalizeToken,
|
|
1474
|
+
parseDiarizedText,
|
|
1475
|
+
parseIdentifyJson,
|
|
1476
|
+
parseSrt,
|
|
1477
|
+
relTimeToSeconds,
|
|
1478
|
+
secondsToCompact,
|
|
1479
|
+
secondsToSrtTime,
|
|
1480
|
+
segmentsToWords,
|
|
1481
|
+
slugLabel,
|
|
1482
|
+
splitSpeakerPrefix,
|
|
1483
|
+
srtCueText,
|
|
1484
|
+
srtTimeToSeconds,
|
|
1485
|
+
toJSON,
|
|
1486
|
+
toMarkdown,
|
|
1487
|
+
toSRT,
|
|
1488
|
+
toText,
|
|
1489
|
+
tokenize,
|
|
1490
|
+
transcribeInBrowser,
|
|
1491
|
+
transcribeWithAssemblyAIFetch,
|
|
1492
|
+
withRetry
|
|
1493
|
+
};
|
|
1494
|
+
//# sourceMappingURL=browser.js.map
|