offmute-v2 0.0.1-opus.0 → 0.0.2
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 +67 -91
- package/dist/browser.browser.js +1149 -0
- package/dist/browser.browser.js.map +1 -0
- package/dist/browser.d.ts +437 -657
- package/dist/cli.cjs +2098 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.js +1903 -1361
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +2110 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +371 -0
- package/dist/index.d.ts +311 -453
- package/dist/index.js +1912 -1381
- package/dist/index.js.map +1 -1
- package/package.json +42 -34
- package/dist/browser.js +0 -1494
- package/dist/browser.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,802 +1,394 @@
|
|
|
1
|
-
// src/core/
|
|
2
|
-
|
|
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
|
-
}
|
|
1
|
+
// src/core/pipeline.ts
|
|
2
|
+
import { existsSync as existsSync2, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
122
3
|
|
|
123
|
-
// src/core/
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
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;
|
|
4
|
+
// src/core/config.ts
|
|
5
|
+
import { createHash } from "crypto";
|
|
6
|
+
import { basename, dirname, resolve } from "path";
|
|
7
|
+
import { statSync } from "fs";
|
|
8
|
+
var DEFAULT_PASSES = [
|
|
9
|
+
"preprocess",
|
|
10
|
+
"describe",
|
|
11
|
+
"llm-transcribe",
|
|
12
|
+
"timestamped",
|
|
13
|
+
"align",
|
|
14
|
+
"consistency",
|
|
15
|
+
"finalize"
|
|
16
|
+
];
|
|
17
|
+
var MODELS = {
|
|
18
|
+
gemini25Pro: "gemini-2.5-pro",
|
|
19
|
+
gemini25Flash: "gemini-2.5-flash",
|
|
20
|
+
gemini3Pro: "gemini-3-pro-preview",
|
|
21
|
+
deepseek: "deepseek-chat",
|
|
22
|
+
deepseekReasoner: "deepseek-reasoner",
|
|
23
|
+
gpt4o: "gpt-4o",
|
|
24
|
+
claudeSonnet: "claude-sonnet-4-5"
|
|
25
|
+
};
|
|
26
|
+
var DEFAULT_TRANSCRIBE_MODEL = MODELS.gemini25Flash;
|
|
27
|
+
var DEFAULT_REASONER_MODEL = MODELS.deepseek;
|
|
28
|
+
function resolveKeys(injected) {
|
|
29
|
+
const env = process.env;
|
|
30
|
+
return {
|
|
31
|
+
gemini: injected?.gemini || injected?.google || env.GEMINI_API_KEY || env.GOOGLE_API_KEY,
|
|
32
|
+
google: injected?.google || injected?.gemini || env.GOOGLE_API_KEY || env.GEMINI_API_KEY,
|
|
33
|
+
openai: injected?.openai || env.OPENAI_API_KEY,
|
|
34
|
+
deepseek: injected?.deepseek || env.DEEPSEEK_API_KEY,
|
|
35
|
+
groq: injected?.groq || env.GROQ_API_KEY,
|
|
36
|
+
assemblyai: injected?.assemblyai || env.ASSEMBLYAI_API_KEY,
|
|
37
|
+
anthropic: injected?.anthropic || env.ANTHROPIC_API_KEY
|
|
38
|
+
};
|
|
314
39
|
}
|
|
315
|
-
function
|
|
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;
|
|
40
|
+
function resolveOptions(opts) {
|
|
321
41
|
return {
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
42
|
+
input: opts.input,
|
|
43
|
+
outputDir: opts.outputDir,
|
|
44
|
+
intermediatesDir: opts.intermediatesDir ?? deriveIntermediatesDir(opts.input),
|
|
45
|
+
instructions: opts.instructions,
|
|
46
|
+
knownSpeakers: opts.knownSpeakers,
|
|
47
|
+
passes: (() => {
|
|
48
|
+
const p = opts.passes ?? DEFAULT_PASSES;
|
|
49
|
+
if ((opts.diarizationLevel ?? 2) >= 3 && !p.includes("identify")) {
|
|
50
|
+
const out = [...p];
|
|
51
|
+
const fi = out.indexOf("finalize");
|
|
52
|
+
if (fi >= 0) out.splice(fi, 0, "identify");
|
|
53
|
+
else out.push("identify");
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
return p;
|
|
57
|
+
})(),
|
|
58
|
+
chunkDurationSec: opts.chunkDurationSec ?? 600,
|
|
59
|
+
chunkOverlapSec: opts.chunkOverlapSec ?? 60,
|
|
60
|
+
screenshotCount: opts.screenshotCount ?? 6,
|
|
61
|
+
concurrency: opts.concurrency ?? 4,
|
|
62
|
+
saveIntermediates: opts.saveIntermediates ?? true,
|
|
63
|
+
formats: opts.formats ?? ["srt", "md", "json"],
|
|
64
|
+
diarizationLevel: opts.diarizationLevel ?? 2,
|
|
65
|
+
apiKeys: opts.apiKeys,
|
|
66
|
+
model: opts.model,
|
|
67
|
+
reasoner: opts.reasoner,
|
|
68
|
+
timestampedProvider: opts.timestampedProvider,
|
|
69
|
+
force: opts.force ?? false,
|
|
70
|
+
onlyChunk: opts.onlyChunk,
|
|
71
|
+
showProgress: opts.showProgress ?? true,
|
|
72
|
+
llmLog: opts.llmLog ?? true,
|
|
73
|
+
logLevel: opts.logLevel ?? "info"
|
|
329
74
|
};
|
|
330
75
|
}
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
const
|
|
335
|
-
|
|
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";
|
|
76
|
+
function deriveIntermediatesDir(input) {
|
|
77
|
+
const abs = resolve(input);
|
|
78
|
+
const hash = createHash("sha1").update(abs).digest("hex").slice(0, 8);
|
|
79
|
+
const base = basename(input, extOf(input)) || "input";
|
|
80
|
+
return `${dirname(abs)}/.offmute-v2-${base}-${hash}`;
|
|
354
81
|
}
|
|
355
|
-
function
|
|
356
|
-
const
|
|
357
|
-
|
|
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");
|
|
82
|
+
function extOf(p) {
|
|
83
|
+
const i = p.lastIndexOf(".");
|
|
84
|
+
return i >= 0 ? p.slice(i) : "";
|
|
387
85
|
}
|
|
388
|
-
function
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
86
|
+
function inputSignature(input) {
|
|
87
|
+
let size = 0;
|
|
88
|
+
let mtime = 0;
|
|
89
|
+
try {
|
|
90
|
+
const st = statSync(input);
|
|
91
|
+
size = st.size;
|
|
92
|
+
mtime = Math.floor(st.mtimeMs);
|
|
93
|
+
} catch {
|
|
394
94
|
}
|
|
395
|
-
return
|
|
95
|
+
return createHash("sha1").update(`${resolve(input)}|${size}|${mtime}`).digest("hex");
|
|
396
96
|
}
|
|
397
|
-
function
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
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;
|
|
97
|
+
function configSignature(o) {
|
|
98
|
+
const relevant = {
|
|
99
|
+
model: o.model ?? DEFAULT_TRANSCRIBE_MODEL,
|
|
100
|
+
reasoner: o.reasoner ?? DEFAULT_REASONER_MODEL,
|
|
101
|
+
instructions: o.instructions ?? "",
|
|
102
|
+
knownSpeakers: o.knownSpeakers ?? [],
|
|
103
|
+
chunkDurationSec: o.chunkDurationSec ?? 600,
|
|
104
|
+
chunkOverlapSec: o.chunkOverlapSec ?? 60,
|
|
105
|
+
screenshotCount: o.screenshotCount ?? 6,
|
|
106
|
+
diarizationLevel: o.diarizationLevel ?? 2,
|
|
107
|
+
timestampedProvider: o.timestampedProvider ?? "assemblyai"
|
|
430
108
|
};
|
|
431
|
-
|
|
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 };
|
|
109
|
+
return createHash("sha1").update(JSON.stringify(relevant)).digest("hex");
|
|
448
110
|
}
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
if (
|
|
459
|
-
|
|
460
|
-
|
|
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);
|
|
111
|
+
function planChunks(totalDuration, chunkDuration, overlap2) {
|
|
112
|
+
const chunks = [];
|
|
113
|
+
const step = chunkDuration - overlap2;
|
|
114
|
+
if (step <= 0) throw new Error("chunkOverlap must be < chunkDuration");
|
|
115
|
+
let start = 0;
|
|
116
|
+
let index = 0;
|
|
117
|
+
while (start < totalDuration) {
|
|
118
|
+
const end = Math.min(start + chunkDuration, totalDuration);
|
|
119
|
+
const overlapWithPrevious = index === 0 ? 0 : Math.min(overlap2, end - start);
|
|
120
|
+
if (end === totalDuration && end - start < chunkDuration / 3 && chunks.length > 0) {
|
|
121
|
+
chunks[chunks.length - 1].end = end;
|
|
122
|
+
break;
|
|
478
123
|
}
|
|
124
|
+
chunks.push({
|
|
125
|
+
index,
|
|
126
|
+
start,
|
|
127
|
+
end,
|
|
128
|
+
overlapWithPrevious,
|
|
129
|
+
trustedStart: start + overlapWithPrevious
|
|
130
|
+
});
|
|
131
|
+
start = end - overlap2;
|
|
132
|
+
if (start >= totalDuration) break;
|
|
133
|
+
index++;
|
|
479
134
|
}
|
|
480
|
-
return
|
|
481
|
-
}
|
|
482
|
-
function appendContinuation(out, text) {
|
|
483
|
-
const last = out[out.length - 1];
|
|
484
|
-
if (last) last.text = `${last.text} ${text}`.trim();
|
|
135
|
+
return chunks;
|
|
485
136
|
}
|
|
486
137
|
|
|
487
|
-
// src/
|
|
488
|
-
var
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
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");
|
|
138
|
+
// src/utils/logger.ts
|
|
139
|
+
var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
140
|
+
var currentLevel = "info";
|
|
141
|
+
function setLogLevel(level) {
|
|
142
|
+
currentLevel = level;
|
|
531
143
|
}
|
|
532
|
-
function
|
|
533
|
-
|
|
534
|
-
const
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
144
|
+
function log(level, msg, extra) {
|
|
145
|
+
if (LEVELS[level] < LEVELS[currentLevel]) return;
|
|
146
|
+
const ts = (/* @__PURE__ */ new Date()).toISOString().substring(11, 23);
|
|
147
|
+
const prefix = `[${ts}] ${level.toUpperCase().padEnd(5)}`;
|
|
148
|
+
if (extra !== void 0) {
|
|
149
|
+
console[level === "error" ? "error" : "log"](prefix, msg, extra);
|
|
150
|
+
} else {
|
|
151
|
+
console[level === "error" ? "error" : "log"](prefix, msg);
|
|
538
152
|
}
|
|
539
|
-
if (asr.utterances.length > maxUtterances) lines.push(`\u2026 (${asr.utterances.length - maxUtterances} more)`);
|
|
540
|
-
return lines.join("\n");
|
|
541
153
|
}
|
|
154
|
+
var logger = {
|
|
155
|
+
debug: (msg, extra) => log("debug", msg, extra),
|
|
156
|
+
info: (msg, extra) => log("info", msg, extra),
|
|
157
|
+
warn: (msg, extra) => log("warn", msg, extra),
|
|
158
|
+
error: (msg, extra) => log("error", msg, extra),
|
|
159
|
+
setLevel: setLogLevel
|
|
160
|
+
};
|
|
542
161
|
|
|
543
|
-
// src/
|
|
544
|
-
import { basename as basename2, dirname as dirname3, extname as extname2, join as join3 } from "path";
|
|
545
|
-
import { existsSync as existsSync2 } from "fs";
|
|
546
|
-
|
|
547
|
-
// src/media/ffmpeg.ts
|
|
162
|
+
// src/audio/ffmpeg.ts
|
|
548
163
|
import { spawn } from "child_process";
|
|
549
164
|
import { mkdir } from "fs/promises";
|
|
550
|
-
import { dirname
|
|
551
|
-
function run(cmd, args) {
|
|
552
|
-
return new Promise((
|
|
553
|
-
const child = spawn(cmd, args);
|
|
165
|
+
import { dirname as dirname2 } from "path";
|
|
166
|
+
function run(cmd, args, _opts = {}) {
|
|
167
|
+
return new Promise((resolve2, reject) => {
|
|
168
|
+
const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
554
169
|
let stdout = "";
|
|
555
170
|
let stderr = "";
|
|
556
171
|
child.stdout.on("data", (d) => stdout += d.toString());
|
|
557
172
|
child.stderr.on("data", (d) => stderr += d.toString());
|
|
558
173
|
child.on("error", reject);
|
|
559
|
-
child.on("close", (code) =>
|
|
174
|
+
child.on("close", (code) => {
|
|
175
|
+
if (code === 0) resolve2({ stdout, stderr });
|
|
176
|
+
else {
|
|
177
|
+
const tail = stderr.slice(-800);
|
|
178
|
+
reject(new Error(`${cmd} exited ${code}: ${tail}`));
|
|
179
|
+
}
|
|
180
|
+
});
|
|
560
181
|
});
|
|
561
182
|
}
|
|
562
|
-
async function
|
|
563
|
-
|
|
183
|
+
async function checkFfmpeg() {
|
|
184
|
+
try {
|
|
185
|
+
await run("ffmpeg", ["-version"]);
|
|
186
|
+
await run("ffprobe", ["-version"]);
|
|
187
|
+
return true;
|
|
188
|
+
} catch {
|
|
189
|
+
return false;
|
|
190
|
+
}
|
|
564
191
|
}
|
|
565
|
-
async function
|
|
566
|
-
const {
|
|
192
|
+
async function probe(input) {
|
|
193
|
+
const { stdout } = await run("ffprobe", [
|
|
567
194
|
"-v",
|
|
568
195
|
"error",
|
|
569
|
-
"-print_format",
|
|
570
|
-
"json",
|
|
571
196
|
"-show_format",
|
|
572
197
|
"-show_streams",
|
|
198
|
+
"-of",
|
|
199
|
+
"json",
|
|
573
200
|
input
|
|
574
201
|
]);
|
|
575
|
-
if (code !== 0) {
|
|
576
|
-
throw new Error(`ffprobe failed (${code}): ${stderr}`);
|
|
577
|
-
}
|
|
578
202
|
const data = JSON.parse(stdout);
|
|
579
|
-
const streams = data.streams
|
|
580
|
-
const
|
|
581
|
-
const
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
hasVideo: !!video,
|
|
203
|
+
const streams = data.streams || [];
|
|
204
|
+
const audio = streams.find((s) => s.codec_type === "audio");
|
|
205
|
+
const video = streams.find((s) => s.codec_type === "video");
|
|
206
|
+
return {
|
|
207
|
+
duration: parseFloat(data.format?.duration || "0") || 0,
|
|
585
208
|
hasAudio: !!audio,
|
|
586
|
-
|
|
209
|
+
hasVideo: !!video,
|
|
210
|
+
audioCodec: audio?.codec_name,
|
|
211
|
+
videoCodec: video?.codec_name,
|
|
212
|
+
sampleRate: audio ? parseInt(audio.sample_rate ?? "0", 10) : void 0,
|
|
213
|
+
channels: audio?.channels,
|
|
214
|
+
width: video?.width,
|
|
215
|
+
height: video?.height,
|
|
216
|
+
sizeBytes: parseInt(data.format?.size || "0", 10) || void 0
|
|
587
217
|
};
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
args
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
|
|
218
|
+
}
|
|
219
|
+
function audioArgs(opts) {
|
|
220
|
+
const sampleRate = opts.sampleRate ?? 16e3;
|
|
221
|
+
const channels = opts.channels ?? 1;
|
|
222
|
+
const format = opts.format ?? "flac";
|
|
223
|
+
const common = ["-vn", "-ac", String(channels), "-ar", String(sampleRate)];
|
|
224
|
+
switch (format) {
|
|
225
|
+
case "flac":
|
|
226
|
+
return [...common, "-c:a", "flac"];
|
|
227
|
+
case "mp3":
|
|
228
|
+
return [...common, "-c:a", "libmp3lame", "-b:a", opts.bitrate ?? "64k"];
|
|
229
|
+
case "opus":
|
|
230
|
+
return [...common, "-c:a", "libopus", "-b:a", opts.bitrate ?? "48k"];
|
|
231
|
+
case "wav":
|
|
232
|
+
return [...common, "-c:a", "pcm_s16le"];
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
async function extractAudio(input, output, opts = {}) {
|
|
236
|
+
await mkdir(dirname2(output), { recursive: true });
|
|
237
|
+
const args = ["-y", "-i", input, ...audioArgs(opts), output];
|
|
238
|
+
await run("ffmpeg", args);
|
|
239
|
+
}
|
|
240
|
+
async function extractChunk(input, output, startSec, endSec, opts = {}) {
|
|
241
|
+
await mkdir(dirname2(output), { recursive: true });
|
|
242
|
+
const duration = Math.max(0, endSec - startSec);
|
|
243
|
+
const args = [
|
|
244
|
+
"-y",
|
|
245
|
+
"-ss",
|
|
246
|
+
startSec.toFixed(3),
|
|
247
|
+
"-i",
|
|
248
|
+
input,
|
|
249
|
+
"-t",
|
|
250
|
+
duration.toFixed(3),
|
|
251
|
+
...audioArgs(opts),
|
|
252
|
+
output
|
|
253
|
+
];
|
|
254
|
+
await run("ffmpeg", args);
|
|
255
|
+
}
|
|
256
|
+
async function getSceneChangeTimes(input, threshold) {
|
|
257
|
+
try {
|
|
258
|
+
const { stderr } = await run("ffmpeg", [
|
|
259
|
+
"-i",
|
|
260
|
+
input,
|
|
261
|
+
"-vf",
|
|
262
|
+
`select='gt(scene,${threshold})',showinfo`,
|
|
263
|
+
"-vsync",
|
|
264
|
+
"vfr",
|
|
265
|
+
"-f",
|
|
266
|
+
"null",
|
|
267
|
+
"-"
|
|
268
|
+
]);
|
|
269
|
+
const times = [];
|
|
270
|
+
const re = /pts_time:(\d+\.?\d*)/g;
|
|
271
|
+
let m;
|
|
272
|
+
while ((m = re.exec(stderr)) !== null) times.push(parseFloat(m[1]));
|
|
273
|
+
return times;
|
|
274
|
+
} catch (err) {
|
|
275
|
+
logger.debug(`scene detection failed: ${err.message}`);
|
|
276
|
+
return [];
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
async function extractKeyframes(input, outputDir, count, opts = {}) {
|
|
635
280
|
await mkdir(outputDir, { recursive: true });
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
)
|
|
281
|
+
const width = opts.width ?? 1280;
|
|
282
|
+
const { duration } = await probe(input);
|
|
283
|
+
if (!duration) return [];
|
|
284
|
+
const sceneTimes = await getSceneChangeTimes(input, opts.sceneThreshold ?? 0.3);
|
|
285
|
+
const times = [];
|
|
286
|
+
if (sceneTimes.length >= count) {
|
|
287
|
+
const step = sceneTimes.length / count;
|
|
288
|
+
for (let i = 0; i < count; i++) {
|
|
289
|
+
const idx = Math.floor(i * step);
|
|
290
|
+
times.push(sceneTimes[idx] ?? 0);
|
|
291
|
+
}
|
|
644
292
|
} else {
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
293
|
+
times.push(...sceneTimes);
|
|
294
|
+
const need = count - times.length;
|
|
295
|
+
const start = duration * 0.02;
|
|
296
|
+
const end = duration * 0.98;
|
|
297
|
+
for (let i = 0; i < need; i++) {
|
|
298
|
+
times.push(start + (end - start) * (i + 0.5) / need);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
times.sort((a, b) => a - b);
|
|
302
|
+
const out = [];
|
|
303
|
+
for (let i = 0; i < times.length; i++) {
|
|
304
|
+
const t = times[i];
|
|
305
|
+
const path = `${outputDir}/keyframe_${String(i).padStart(3, "0")}.jpg`;
|
|
306
|
+
await run("ffmpeg", [
|
|
307
|
+
"-y",
|
|
308
|
+
"-ss",
|
|
309
|
+
t.toFixed(3),
|
|
310
|
+
"-i",
|
|
311
|
+
input,
|
|
312
|
+
"-frames:v",
|
|
313
|
+
"1",
|
|
314
|
+
"-vf",
|
|
315
|
+
`scale=${width}:-2`,
|
|
316
|
+
"-q:v",
|
|
317
|
+
"3",
|
|
318
|
+
path
|
|
319
|
+
]);
|
|
320
|
+
out.push({ path, time: t });
|
|
321
|
+
}
|
|
322
|
+
return out;
|
|
672
323
|
}
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
const
|
|
689
|
-
|
|
690
|
-
const
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
for (const u of utterances) speakerSet.add(u.speaker);
|
|
713
|
-
for (const w of words) if (w.speaker) speakerSet.add(w.speaker);
|
|
714
|
-
const asr = {
|
|
715
|
-
provider: "assemblyai",
|
|
716
|
-
model: options.speechModel,
|
|
717
|
-
words,
|
|
718
|
-
utterances,
|
|
719
|
-
speakers: [...speakerSet].sort(),
|
|
720
|
-
durationSeconds: t.audio_duration ?? (words.length ? words[words.length - 1].end : 0),
|
|
721
|
-
language: t.language_code,
|
|
722
|
-
diarized: utterances.length > 0 && speakerSet.size > 0
|
|
723
|
-
};
|
|
724
|
-
return { asr, raw: t };
|
|
324
|
+
async function detectSilence(input, opts = {}) {
|
|
325
|
+
const noise = opts.noiseDb ?? -30;
|
|
326
|
+
const minDur = opts.minDuration ?? 0.3;
|
|
327
|
+
const { stderr } = await run("ffmpeg", [
|
|
328
|
+
"-i",
|
|
329
|
+
input,
|
|
330
|
+
"-af",
|
|
331
|
+
`silencedetect=noise=${noise}dB:d=${minDur}`,
|
|
332
|
+
"-f",
|
|
333
|
+
"null",
|
|
334
|
+
"-"
|
|
335
|
+
]);
|
|
336
|
+
const starts = [];
|
|
337
|
+
const ends = [];
|
|
338
|
+
let m;
|
|
339
|
+
const startRe = /silence_start: (-?\d+\.?\d*)/g;
|
|
340
|
+
while ((m = startRe.exec(stderr)) !== null) starts.push(parseFloat(m[1]));
|
|
341
|
+
const endRe = /silence_end: (-?\d+\.?\d*)/g;
|
|
342
|
+
while ((m = endRe.exec(stderr)) !== null) ends.push(parseFloat(m[1]));
|
|
343
|
+
const ranges = [];
|
|
344
|
+
for (let i = 0; i < starts.length; i++) {
|
|
345
|
+
const s = starts[i];
|
|
346
|
+
const e = ends[i] ?? s + minDur;
|
|
347
|
+
ranges.push({ start: s, end: e, duration: e - s });
|
|
348
|
+
}
|
|
349
|
+
return ranges;
|
|
350
|
+
}
|
|
351
|
+
function snapToSilence(boundary, silences, tolerance) {
|
|
352
|
+
let best = boundary;
|
|
353
|
+
let bestDist = tolerance;
|
|
354
|
+
for (const s of silences) {
|
|
355
|
+
const mid = (s.start + s.end) / 2;
|
|
356
|
+
const dist = Math.abs(mid - boundary);
|
|
357
|
+
if (dist < bestDist) {
|
|
358
|
+
bestDist = dist;
|
|
359
|
+
best = mid;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return best;
|
|
725
363
|
}
|
|
726
364
|
|
|
727
365
|
// src/providers/gemini.ts
|
|
728
366
|
import { GoogleGenAI } from "@google/genai";
|
|
729
|
-
import { basename
|
|
367
|
+
import { basename as basename2 } from "path";
|
|
730
368
|
|
|
731
|
-
// src/
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
const msg = (e?.message ?? String(err)).toLowerCase();
|
|
737
|
-
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(
|
|
738
|
-
msg
|
|
739
|
-
);
|
|
740
|
-
}
|
|
741
|
-
async function withRetry(fn, opts = {}) {
|
|
742
|
-
const retries = opts.retries ?? 4;
|
|
743
|
-
const base = opts.baseDelayMs ?? 1e3;
|
|
744
|
-
let lastErr;
|
|
745
|
-
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
746
|
-
try {
|
|
747
|
-
return await fn();
|
|
748
|
-
} catch (err) {
|
|
749
|
-
lastErr = err;
|
|
750
|
-
if (attempt === retries || !isRetryableError(err)) throw err;
|
|
751
|
-
const delayMs = Math.min(3e4, base * 2 ** attempt) + Math.floor(Math.random() * 250);
|
|
752
|
-
opts.onRetry?.({ attempt: attempt + 1, retries, delayMs, error: err });
|
|
753
|
-
await new Promise((r) => setTimeout(r, delayMs));
|
|
754
|
-
}
|
|
755
|
-
}
|
|
756
|
-
throw lastErr;
|
|
369
|
+
// src/providers/llm-log.ts
|
|
370
|
+
import { appendFileSync } from "fs";
|
|
371
|
+
var logPath = null;
|
|
372
|
+
function setLlmLogPath(path) {
|
|
373
|
+
logPath = path ?? null;
|
|
757
374
|
}
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
LOW: { flash: 2048, pro: 2048 },
|
|
764
|
-
MEDIUM: { flash: 8192, pro: 8192 },
|
|
765
|
-
HIGH: { flash: 24576, pro: 24576 }
|
|
766
|
-
};
|
|
767
|
-
function resolveThinkingConfig(model, level, explicitBudget) {
|
|
768
|
-
const m = model.toLowerCase();
|
|
769
|
-
const isPro = m.includes("pro");
|
|
770
|
-
if (explicitBudget !== void 0 && m.includes("gemini-2.5")) {
|
|
771
|
-
return { thinkingBudget: explicitBudget };
|
|
772
|
-
}
|
|
773
|
-
if (level === void 0) return void 0;
|
|
774
|
-
if (m.includes("gemini-2.5")) {
|
|
775
|
-
return { thinkingBudget: BUDGET_BY_LEVEL[level][isPro ? "pro" : "flash"] };
|
|
776
|
-
}
|
|
777
|
-
if (m.includes("gemini-2")) {
|
|
778
|
-
return void 0;
|
|
779
|
-
}
|
|
780
|
-
if (isPro) {
|
|
781
|
-
return { thinkingLevel: level === "MINIMAL" ? "LOW" : level };
|
|
375
|
+
function logLlmCall(entry) {
|
|
376
|
+
if (!logPath) return;
|
|
377
|
+
try {
|
|
378
|
+
appendFileSync(logPath, JSON.stringify(entry) + "\n", { encoding: "utf-8" });
|
|
379
|
+
} catch {
|
|
782
380
|
}
|
|
783
|
-
return { thinkingLevel: level };
|
|
784
|
-
}
|
|
785
|
-
function isThinkingConfigError(err) {
|
|
786
|
-
const msg = (err?.message ?? String(err)).toLowerCase();
|
|
787
|
-
return /thinking[_ ]?(level|budget)|thinking.*(not supported|unsupported)/.test(msg);
|
|
788
381
|
}
|
|
789
382
|
|
|
790
383
|
// src/providers/gemini.ts
|
|
791
384
|
var MIME_BY_EXT = {
|
|
385
|
+
".flac": "audio/flac",
|
|
792
386
|
".mp3": "audio/mp3",
|
|
793
|
-
".mpga": "audio/mpeg",
|
|
794
387
|
".wav": "audio/wav",
|
|
795
|
-
".
|
|
388
|
+
".m4a": "audio/m4a",
|
|
796
389
|
".aac": "audio/aac",
|
|
797
|
-
".m4a": "audio/mp4",
|
|
798
|
-
".opus": "audio/opus",
|
|
799
390
|
".ogg": "audio/ogg",
|
|
391
|
+
".opus": "audio/opus",
|
|
800
392
|
".mp4": "video/mp4",
|
|
801
393
|
".mov": "video/quicktime",
|
|
802
394
|
".webm": "video/webm",
|
|
@@ -805,729 +397,1668 @@ var MIME_BY_EXT = {
|
|
|
805
397
|
".jpeg": "image/jpeg",
|
|
806
398
|
".webp": "image/webp"
|
|
807
399
|
};
|
|
808
|
-
function
|
|
809
|
-
const
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
)
|
|
821
|
-
}
|
|
400
|
+
function detectMime(path) {
|
|
401
|
+
const ext2 = path.slice(path.lastIndexOf(".")).toLowerCase();
|
|
402
|
+
return MIME_BY_EXT[ext2] ?? "application/octet-stream";
|
|
403
|
+
}
|
|
404
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
405
|
+
function resolveThinking(model) {
|
|
406
|
+
const m = model.toLowerCase();
|
|
407
|
+
if (m.includes("gemini-2.0")) return void 0;
|
|
408
|
+
if (m.includes("gemini-2.5")) {
|
|
409
|
+
return { thinkingBudget: m.includes("pro") ? 128 : 0 };
|
|
410
|
+
}
|
|
411
|
+
if (m.includes("gemini-3") || m.includes("flash-latest") || m.includes("pro-latest")) {
|
|
412
|
+
return { thinkingLevel: m.includes("pro") ? "LOW" : "MINIMAL" };
|
|
413
|
+
}
|
|
414
|
+
return void 0;
|
|
415
|
+
}
|
|
416
|
+
function isThinkingConfigError(message) {
|
|
417
|
+
if (!message) return false;
|
|
418
|
+
return /thinking/i.test(message) && /(not supported|invalid|unsupported|unknown name|unexpected)/i.test(message);
|
|
822
419
|
}
|
|
823
420
|
var GeminiClient = class {
|
|
824
421
|
ai;
|
|
825
|
-
/** if set, invoked once per generate() with the prompt/response/usage (for logging). */
|
|
826
|
-
onCall;
|
|
827
422
|
constructor(apiKey) {
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
const name = file.name;
|
|
841
|
-
while (file.state === "PROCESSING") {
|
|
842
|
-
await new Promise((r) => setTimeout(r, 1500));
|
|
843
|
-
file = await this.ai.files.get({ name });
|
|
423
|
+
this.ai = new GoogleGenAI({ apiKey });
|
|
424
|
+
}
|
|
425
|
+
/** Upload a file and wait until it's done processing. */
|
|
426
|
+
async upload(path, mimeType) {
|
|
427
|
+
const mt = mimeType || detectMime(path);
|
|
428
|
+
logger.debug(`[gemini] uploading ${basename2(path)} (${mt})...`);
|
|
429
|
+
let file = await this.ai.files.upload({ file: path, config: { mimeType: mt } });
|
|
430
|
+
let tries = 0;
|
|
431
|
+
while (file.state === "PROCESSING" && tries < 120) {
|
|
432
|
+
await sleep(2e3);
|
|
433
|
+
file = await this.ai.files.get({ name: file.name });
|
|
434
|
+
tries++;
|
|
844
435
|
}
|
|
845
|
-
if (file.state === "FAILED")
|
|
846
|
-
|
|
847
|
-
}
|
|
848
|
-
async deleteFile(name) {
|
|
849
|
-
try {
|
|
850
|
-
await this.ai.files.delete({ name });
|
|
851
|
-
} catch {
|
|
436
|
+
if (file.state === "FAILED") {
|
|
437
|
+
throw new Error(`Gemini file processing failed: ${path}`);
|
|
852
438
|
}
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
const
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
439
|
+
logger.debug(`[gemini] uploaded ${basename2(path)} \u2192 ${file.uri}`);
|
|
440
|
+
return file;
|
|
441
|
+
}
|
|
442
|
+
/** Generate content from a prompt + uploaded files. */
|
|
443
|
+
async generate(model, prompt, files, opts = {}) {
|
|
444
|
+
const {
|
|
445
|
+
maxRetries = 3,
|
|
446
|
+
retryDelayMs = 2e3,
|
|
447
|
+
temperature = 0.2,
|
|
448
|
+
maxOutputTokens = 65536,
|
|
449
|
+
responseSchema,
|
|
450
|
+
systemInstruction
|
|
451
|
+
} = opts;
|
|
452
|
+
const uploaded = [];
|
|
453
|
+
try {
|
|
454
|
+
for (const f of files) {
|
|
455
|
+
uploaded.push(await this.upload(f.path, f.mimeType));
|
|
868
456
|
}
|
|
457
|
+
const config = {
|
|
458
|
+
maxOutputTokens,
|
|
459
|
+
temperature
|
|
460
|
+
};
|
|
461
|
+
if (responseSchema) {
|
|
462
|
+
config.responseMimeType = "application/json";
|
|
463
|
+
config.responseSchema = responseSchema;
|
|
464
|
+
}
|
|
465
|
+
if (systemInstruction) config.systemInstruction = systemInstruction;
|
|
466
|
+
const thinking = resolveThinking(model);
|
|
467
|
+
if (thinking) config.thinkingConfig = thinking;
|
|
468
|
+
const parts = uploaded.map((f) => ({
|
|
469
|
+
fileData: { fileUri: f.uri, mimeType: f.mimeType }
|
|
470
|
+
}));
|
|
471
|
+
parts.push({ text: prompt });
|
|
472
|
+
let lastError;
|
|
473
|
+
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
474
|
+
const t0 = Date.now();
|
|
475
|
+
try {
|
|
476
|
+
const response = await this.ai.models.generateContent({
|
|
477
|
+
model,
|
|
478
|
+
contents: [{ role: "user", parts }],
|
|
479
|
+
config
|
|
480
|
+
});
|
|
481
|
+
const usage = response.usageMetadata || {};
|
|
482
|
+
const text = response.text ?? "";
|
|
483
|
+
const result = {
|
|
484
|
+
text,
|
|
485
|
+
usage: {
|
|
486
|
+
inputTokens: usage.promptTokenCount ?? 0,
|
|
487
|
+
outputTokens: usage.candidatesTokenCount ?? 0,
|
|
488
|
+
totalTokens: usage.totalTokenCount ?? 0
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
logLlmCall({
|
|
492
|
+
ts: new Date(t0).toISOString(),
|
|
493
|
+
provider: "gemini",
|
|
494
|
+
model,
|
|
495
|
+
kind: opts.logKind,
|
|
496
|
+
chunk: opts.logChunk,
|
|
497
|
+
prompt,
|
|
498
|
+
response: text,
|
|
499
|
+
usage: result.usage,
|
|
500
|
+
durationMs: Date.now() - t0,
|
|
501
|
+
attempt: attempt + 1
|
|
502
|
+
});
|
|
503
|
+
return result;
|
|
504
|
+
} catch (err) {
|
|
505
|
+
lastError = err instanceof Error ? err.message : String(err);
|
|
506
|
+
if (config.thinkingConfig && isThinkingConfigError(lastError)) {
|
|
507
|
+
delete config.thinkingConfig;
|
|
508
|
+
logger.warn(`[gemini] model ${model} rejected thinking config \u2014 retrying without it`);
|
|
509
|
+
continue;
|
|
510
|
+
}
|
|
511
|
+
logger.warn(`[gemini] attempt ${attempt + 1}/${maxRetries} failed: ${lastError}`);
|
|
512
|
+
logLlmCall({
|
|
513
|
+
ts: new Date(t0).toISOString(),
|
|
514
|
+
provider: "gemini",
|
|
515
|
+
model,
|
|
516
|
+
kind: opts.logKind,
|
|
517
|
+
chunk: opts.logChunk,
|
|
518
|
+
prompt,
|
|
519
|
+
response: "",
|
|
520
|
+
durationMs: Date.now() - t0,
|
|
521
|
+
attempt: attempt + 1,
|
|
522
|
+
error: lastError
|
|
523
|
+
});
|
|
524
|
+
if (attempt < maxRetries - 1) await sleep(retryDelayMs * (attempt + 1));
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
return { text: "", usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }, error: lastError };
|
|
528
|
+
} finally {
|
|
529
|
+
await this.cleanup(uploaded);
|
|
869
530
|
}
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
531
|
+
}
|
|
532
|
+
/** Generate and parse JSON (requires responseSchema in opts). */
|
|
533
|
+
async generateJson(model, prompt, files, responseSchema, opts = {}) {
|
|
534
|
+
const result = await this.generate(model, prompt, files, {
|
|
535
|
+
...opts,
|
|
536
|
+
responseSchema
|
|
537
|
+
});
|
|
538
|
+
if (result.error || !result.text) {
|
|
539
|
+
return { data: null, raw: result.text, usage: result.usage, error: result.error };
|
|
878
540
|
}
|
|
879
|
-
const thinking = resolveThinkingConfig(model, options.thinkingLevel, options.thinkingBudget);
|
|
880
|
-
if (thinking) config["thinkingConfig"] = thinking;
|
|
881
|
-
const call = (cfg) => this.ai.models.generateContent({ model, contents: [{ role: "user", parts: builtParts }], config: cfg });
|
|
882
|
-
const promptText = parts.filter((p) => p.text !== void 0).map((p) => p.text).join("\n");
|
|
883
|
-
const fileParts = parts.filter((p) => p.filePath || p.uploaded).length;
|
|
884
541
|
try {
|
|
885
|
-
let
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
this.onCall?.({ label: options.label, model, promptText, fileParts, responseText: "", error: err?.message ?? String(err) });
|
|
896
|
-
throw err;
|
|
897
|
-
}
|
|
898
|
-
}
|
|
899
|
-
const usage = resp.usageMetadata;
|
|
900
|
-
const result = {
|
|
901
|
-
text: resp.text ?? "",
|
|
902
|
-
usage: {
|
|
903
|
-
inputTokens: usage?.promptTokenCount,
|
|
904
|
-
outputTokens: usage?.candidatesTokenCount,
|
|
905
|
-
thoughtsTokens: usage?.thoughtsTokenCount
|
|
906
|
-
},
|
|
907
|
-
model,
|
|
908
|
-
raw: resp
|
|
542
|
+
let txt = result.text.trim();
|
|
543
|
+
const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
|
|
544
|
+
if (fence && fence[1]) txt = fence[1];
|
|
545
|
+
return { data: JSON.parse(txt), raw: result.text, usage: result.usage };
|
|
546
|
+
} catch (err) {
|
|
547
|
+
return {
|
|
548
|
+
data: null,
|
|
549
|
+
raw: result.text,
|
|
550
|
+
usage: result.usage,
|
|
551
|
+
error: `JSON parse failed: ${err instanceof Error ? err.message : String(err)}`
|
|
909
552
|
};
|
|
910
|
-
this.onCall?.({ label: options.label, model, promptText, fileParts, responseText: result.text, usage: result.usage });
|
|
911
|
-
return result;
|
|
912
|
-
} finally {
|
|
913
|
-
await Promise.all(toCleanup.map((n) => this.deleteFile(n)));
|
|
914
553
|
}
|
|
915
554
|
}
|
|
555
|
+
async cleanup(files) {
|
|
556
|
+
await Promise.allSettled(
|
|
557
|
+
files.map(async (f) => {
|
|
558
|
+
try {
|
|
559
|
+
if (f.name) await this.ai.files.delete({ name: f.name });
|
|
560
|
+
} catch {
|
|
561
|
+
}
|
|
562
|
+
})
|
|
563
|
+
);
|
|
564
|
+
}
|
|
916
565
|
};
|
|
917
566
|
|
|
918
|
-
// src/
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
567
|
+
// src/providers/assemblyai.ts
|
|
568
|
+
import { AssemblyAI } from "assemblyai";
|
|
569
|
+
import { createHash as createHash2 } from "crypto";
|
|
570
|
+
import { readFile, mkdir as mkdir2, writeFile } from "fs/promises";
|
|
571
|
+
import { existsSync } from "fs";
|
|
572
|
+
import { dirname as dirname3 } from "path";
|
|
573
|
+
async function fileHash(path) {
|
|
574
|
+
const buf = await readFile(path);
|
|
575
|
+
return createHash2("sha256").update(buf).digest("hex").slice(0, 24);
|
|
576
|
+
}
|
|
577
|
+
var AssemblyAIProvider = class {
|
|
578
|
+
client;
|
|
579
|
+
cacheDir;
|
|
580
|
+
constructor(opts) {
|
|
581
|
+
this.client = new AssemblyAI({ apiKey: opts.apiKey });
|
|
582
|
+
this.cacheDir = opts.cacheDir;
|
|
583
|
+
this.speechModel = opts.speechModel ?? "universal";
|
|
584
|
+
this.speakersExpected = opts.speakersExpected;
|
|
585
|
+
}
|
|
586
|
+
speechModel;
|
|
587
|
+
speakersExpected;
|
|
588
|
+
/** Transcribe a local audio file. Returns cached result if available. */
|
|
589
|
+
async transcribe(filePath) {
|
|
590
|
+
const hash = await fileHash(filePath);
|
|
591
|
+
const cachePath = this.cacheDir ? `${this.cacheDir}/${hash}.json` : void 0;
|
|
592
|
+
if (cachePath && existsSync(cachePath)) {
|
|
593
|
+
logger.info(`[assemblyai] cache hit ${hash}`);
|
|
594
|
+
return JSON.parse(await readFile(cachePath, "utf-8"));
|
|
595
|
+
}
|
|
596
|
+
logger.info(`[assemblyai] uploading ${filePath}...`);
|
|
597
|
+
const uploadUrl = await this.client.files.upload(filePath);
|
|
598
|
+
logger.info(`[assemblyai] transcribing (speech_model=${this.speechModel})...`);
|
|
599
|
+
const params = {
|
|
600
|
+
audio: uploadUrl,
|
|
601
|
+
speaker_labels: true,
|
|
602
|
+
speech_model: this.speechModel
|
|
603
|
+
};
|
|
604
|
+
if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
|
|
605
|
+
const transcript = await this.client.transcripts.transcribe(params);
|
|
606
|
+
if (transcript.status === "error") {
|
|
607
|
+
throw new Error(`AssemblyAI error: ${transcript.error}`);
|
|
608
|
+
}
|
|
609
|
+
const result = this.mapTranscript(transcript, hash);
|
|
610
|
+
if (cachePath) {
|
|
611
|
+
await mkdir2(dirname3(cachePath), { recursive: true });
|
|
612
|
+
await writeFile(cachePath, JSON.stringify(result, null, 2));
|
|
613
|
+
}
|
|
614
|
+
logger.info(
|
|
615
|
+
`[assemblyai] done: ${result.utterances.length} utterances, ${result.words.length} words, ${result.speakers.length} speakers`
|
|
616
|
+
);
|
|
617
|
+
return result;
|
|
618
|
+
}
|
|
619
|
+
mapTranscript(t, id) {
|
|
620
|
+
const toWord = (w) => ({
|
|
621
|
+
text: w.text,
|
|
622
|
+
start: (w.start || 0) / 1e3,
|
|
623
|
+
end: (w.end || 0) / 1e3,
|
|
624
|
+
confidence: w.confidence ?? void 0
|
|
932
625
|
});
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
626
|
+
const utterances = [];
|
|
627
|
+
const speakers = /* @__PURE__ */ new Set();
|
|
628
|
+
for (const u of t.utterances || []) {
|
|
629
|
+
const speaker = `speaker_${u.speaker}`;
|
|
630
|
+
speakers.add(speaker);
|
|
631
|
+
utterances.push({
|
|
632
|
+
speaker,
|
|
633
|
+
text: u.text,
|
|
634
|
+
start: (u.start || 0) / 1e3,
|
|
635
|
+
end: (u.end || 0) / 1e3,
|
|
636
|
+
confidence: u.confidence ?? void 0,
|
|
637
|
+
words: (u.words || []).map(toWord)
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
const words = (t.words || []).map(toWord);
|
|
641
|
+
const durationSec = words.length ? words[words.length - 1].end || 0 : utterances.length ? utterances[utterances.length - 1].end : 0;
|
|
642
|
+
return {
|
|
643
|
+
utterances,
|
|
644
|
+
words,
|
|
645
|
+
durationSec,
|
|
646
|
+
audioDurationSec: t.audio_duration ?? void 0,
|
|
647
|
+
// AssemblyAI returns seconds (not ms)
|
|
648
|
+
speakers: [...speakers].sort(),
|
|
649
|
+
transcriptId: t.id ?? id,
|
|
650
|
+
speechModelUsed: t.speech_model_used ?? void 0,
|
|
651
|
+
hasDiarization: true
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
|
|
656
|
+
// src/providers/whisper-groq.ts
|
|
657
|
+
var WhisperGroqClient = class {
|
|
658
|
+
constructor(apiKey, model = "whisper-large-v3-turbo", baseUrl = "https://api.groq.com/openai/v1") {
|
|
659
|
+
this.apiKey = apiKey;
|
|
660
|
+
this.model = model;
|
|
661
|
+
this.baseUrl = baseUrl;
|
|
662
|
+
}
|
|
663
|
+
apiKey;
|
|
664
|
+
model;
|
|
665
|
+
baseUrl;
|
|
666
|
+
async transcribe(audio) {
|
|
667
|
+
const blob = audio instanceof Blob ? audio : new Blob([audio], { type: "audio/mpeg" });
|
|
668
|
+
const form = new FormData();
|
|
669
|
+
form.append("file", blob, "audio.mp3");
|
|
670
|
+
form.append("model", this.model);
|
|
671
|
+
form.append("response_format", "verbose_json");
|
|
672
|
+
form.append("timestamp_granularities[]", "word");
|
|
673
|
+
form.append("timestamp_granularities[]", "segment");
|
|
674
|
+
const res = await fetch(`${this.baseUrl}/audio/transcriptions`, {
|
|
675
|
+
method: "POST",
|
|
676
|
+
headers: { Authorization: `Bearer ${this.apiKey}` },
|
|
677
|
+
body: form
|
|
953
678
|
});
|
|
679
|
+
if (!res.ok) {
|
|
680
|
+
const txt = await res.text();
|
|
681
|
+
throw new Error(`Groq Whisper ${res.status}: ${txt.slice(0, 300)}`);
|
|
682
|
+
}
|
|
683
|
+
const data = await res.json();
|
|
684
|
+
const words = (data.words || []).map((w) => ({
|
|
685
|
+
text: String(w.word || ""),
|
|
686
|
+
start: w.start,
|
|
687
|
+
end: w.end,
|
|
688
|
+
confidence: void 0
|
|
689
|
+
}));
|
|
690
|
+
const utterances = (data.segments || []).map((s) => ({
|
|
691
|
+
speaker: "speaker_A",
|
|
692
|
+
text: String(s.text || "").trim(),
|
|
693
|
+
start: s.start,
|
|
694
|
+
end: s.end,
|
|
695
|
+
confidence: void 0,
|
|
696
|
+
words: words.filter((w) => w.start >= s.start && w.start < s.end)
|
|
697
|
+
}));
|
|
698
|
+
return {
|
|
699
|
+
utterances,
|
|
700
|
+
words,
|
|
701
|
+
durationSec: data.duration ?? (words.length ? words[words.length - 1].end : 0),
|
|
702
|
+
speakers: ["speaker_A"],
|
|
703
|
+
hasDiarization: false,
|
|
704
|
+
transcriptId: `groq-${this.model}`
|
|
705
|
+
};
|
|
954
706
|
}
|
|
955
|
-
|
|
707
|
+
};
|
|
708
|
+
|
|
709
|
+
// src/transcribe/describe.ts
|
|
710
|
+
function descriptionPrompt(fileName, instructions) {
|
|
711
|
+
return `You are listening to a recording to prepare a transcription engine. Describe what you hear${instructions ? ` (note: ${instructions})` : ""}.
|
|
712
|
+
|
|
713
|
+
Respond in TWO sections, clearly separated by a line containing only "---":
|
|
714
|
+
|
|
715
|
+
DESCRIPTION
|
|
716
|
+
A short paragraph: what kind of recording this is, the setting, the main topics, and the overall flow.
|
|
717
|
+
|
|
718
|
+
ROSTER
|
|
719
|
+
A bulleted speaker roster. For each distinct speaker you can identify, give:
|
|
720
|
+
- A short label to use consistently (a name/role if you can infer it, e.g. "Presenter (Hrishi)", else "Speaker A").
|
|
721
|
+
- A one-line description (voice, role, accent if notable).
|
|
722
|
+
List the people you can distinguish. Do not invent names you didn't hear. If only one person speaks, say so.
|
|
723
|
+
|
|
724
|
+
File: ${fileName}`;
|
|
956
725
|
}
|
|
957
|
-
function
|
|
958
|
-
const
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
726
|
+
async function describeMeeting(client, model, files, fileName, instructions) {
|
|
727
|
+
const res = await client.generate(model, descriptionPrompt(fileName, instructions), files, {
|
|
728
|
+
temperature: 0.2,
|
|
729
|
+
maxRetries: 3,
|
|
730
|
+
logKind: "describe"
|
|
731
|
+
});
|
|
732
|
+
const text = res.text || "";
|
|
733
|
+
const parts = text.split(/\n---\n|\n\s*---\s*\n/);
|
|
734
|
+
const description = parts[0]?.trim() || text.trim();
|
|
735
|
+
const roster = parts.slice(1).join("\n---\n").trim() || "(no explicit roster)";
|
|
736
|
+
return { description, roster, raw: text };
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
// src/transcribe/prompts.ts
|
|
740
|
+
var TRANSCRIPT_SCHEMA = {
|
|
741
|
+
type: "OBJECT",
|
|
742
|
+
properties: {
|
|
743
|
+
segments: {
|
|
744
|
+
type: "ARRAY",
|
|
745
|
+
items: {
|
|
746
|
+
type: "OBJECT",
|
|
747
|
+
properties: {
|
|
748
|
+
speaker: { type: "STRING", description: "Speaker label. Use an identified name from the roster if confident, else 'Speaker A', 'Speaker B', etc." },
|
|
749
|
+
start: { type: "STRING", description: "Relative start time as mm:ss (00:00 = start of this audio chunk)" },
|
|
750
|
+
end: { type: "STRING", description: "Relative end time as mm:ss" },
|
|
751
|
+
text: { type: "STRING", description: "Verbatim transcribed words, including fillers and false starts" },
|
|
752
|
+
tone: {
|
|
753
|
+
type: "ARRAY",
|
|
754
|
+
items: { type: "STRING" },
|
|
755
|
+
description: "Tone/behavior tags e.g. hesitant, laughing, contemplating, urgent, sarcastic. Empty array if neutral."
|
|
756
|
+
}
|
|
757
|
+
},
|
|
758
|
+
required: ["speaker", "start", "end", "text"]
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
},
|
|
762
|
+
required: ["segments"]
|
|
763
|
+
};
|
|
764
|
+
function transcriptionPrompt(ctx) {
|
|
765
|
+
const parts = [];
|
|
766
|
+
parts.push(
|
|
767
|
+
`You are an expert speech transcription engine. Below is audio chunk ${ctx.index} of ${ctx.total} from a recording. Transcribe ALL speech verbatim and diarize it.`
|
|
962
768
|
);
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
769
|
+
parts.push("");
|
|
770
|
+
parts.push("Output one segment per speaker turn (a new segment whenever the speaker changes, or after a long pause, or at an interruption).");
|
|
771
|
+
parts.push("");
|
|
772
|
+
parts.push("For each segment provide:");
|
|
773
|
+
parts.push("- speaker: a label. Use an identified name/role from the roster if you are confident who is speaking; otherwise use 'Speaker A', 'Speaker B', etc. Keep labels CONSISTENT across the chunk.");
|
|
774
|
+
parts.push("- start, end: relative timestamps as mm:ss, where 00:00 is the START of this audio chunk. They must be monotonic and span the full chunk.");
|
|
775
|
+
parts.push("- text: the verbatim words, including fillers (um, uh), false starts, and corrections. Do not paraphrase.");
|
|
776
|
+
parts.push("- tone: array of behavior/emotion tags. Tag most segments \u2014 e.g. confident, hesitant, laughing, sarcastic, urgent, contemplative, whispering, emphatic, questioning, joking, frustrated. Use an empty array ONLY when nothing stands out.");
|
|
777
|
+
parts.push("");
|
|
778
|
+
parts.push("Rules:");
|
|
779
|
+
parts.push("- Cover the ENTIRE audio with no gaps. Timestamps must be monotonic non-decreasing.");
|
|
780
|
+
parts.push("- Capture interruptions and overlapping talk as separate, adjacent segments even if times overlap.");
|
|
781
|
+
parts.push("- Do not invent content not present in the audio. If inaudible, write [inaudible].");
|
|
782
|
+
parts.push("- Keep speaker labels consistent within this chunk; the same voice = same label.");
|
|
783
|
+
if (ctx.description) {
|
|
784
|
+
parts.push("");
|
|
785
|
+
parts.push("MEETING CONTEXT:");
|
|
786
|
+
parts.push(ctx.description);
|
|
787
|
+
}
|
|
788
|
+
if (ctx.roster) {
|
|
789
|
+
parts.push("");
|
|
790
|
+
parts.push("SPEAKER ROSTER (prefer these labels/names when you can identify the voice):");
|
|
791
|
+
parts.push(ctx.roster);
|
|
792
|
+
}
|
|
793
|
+
if (ctx.previousTail) {
|
|
794
|
+
parts.push("");
|
|
795
|
+
parts.push("TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):");
|
|
796
|
+
parts.push(ctx.previousTail);
|
|
797
|
+
}
|
|
798
|
+
if (ctx.instructions) {
|
|
799
|
+
parts.push("");
|
|
800
|
+
parts.push("ADDITIONAL INSTRUCTIONS:");
|
|
801
|
+
parts.push(ctx.instructions);
|
|
802
|
+
}
|
|
803
|
+
parts.push("");
|
|
804
|
+
parts.push("Return JSON matching the schema: { segments: [ {speaker, start, end, text, tone} ] }");
|
|
805
|
+
return parts.join("\n");
|
|
974
806
|
}
|
|
975
807
|
|
|
976
|
-
// src/
|
|
977
|
-
function
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
const
|
|
982
|
-
const
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
808
|
+
// src/utils/time.ts
|
|
809
|
+
function secondsToTimestamp(seconds) {
|
|
810
|
+
const clamped = Math.max(0, seconds);
|
|
811
|
+
const hours = Math.floor(clamped / 3600);
|
|
812
|
+
const minutes = Math.floor(clamped % 3600 / 60);
|
|
813
|
+
const secs = Math.floor(clamped % 60);
|
|
814
|
+
const ms = Math.floor(clamped % 1 * 1e3);
|
|
815
|
+
return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")},${ms.toString().padStart(3, "0")}`;
|
|
816
|
+
}
|
|
817
|
+
function timestampToSeconds(timestamp) {
|
|
818
|
+
const timeStr = timestamp.replace(",", ".");
|
|
819
|
+
const [timeWithoutMs, ms] = timeStr.split(".");
|
|
820
|
+
if (!timeWithoutMs) return 0;
|
|
821
|
+
const [hours, minutes, seconds] = timeWithoutMs.split(":").map(Number);
|
|
822
|
+
const h = hours || 0;
|
|
823
|
+
const m = minutes || 0;
|
|
824
|
+
const s = seconds || 0;
|
|
825
|
+
return h * 3600 + m * 60 + s + (ms ? Number(`0.${ms}`) : 0);
|
|
826
|
+
}
|
|
827
|
+
function parseSrtTiming(timingString) {
|
|
828
|
+
const parts = timingString.split("-->");
|
|
829
|
+
if (parts.length !== 2) return null;
|
|
830
|
+
return { start: timestampToSeconds(parts[0].trim()), end: timestampToSeconds(parts[1].trim()) };
|
|
831
|
+
}
|
|
832
|
+
function formatSrtTiming(startSeconds, endSeconds) {
|
|
833
|
+
return `${secondsToTimestamp(startSeconds)} --> ${secondsToTimestamp(endSeconds)}`;
|
|
834
|
+
}
|
|
835
|
+
function parseMmSs(timeStr) {
|
|
836
|
+
const parts = timeStr.split(":");
|
|
837
|
+
if (parts.length !== 2) return null;
|
|
838
|
+
const minutes = parseInt(parts[0], 10);
|
|
839
|
+
const seconds = parseInt(parts[1], 10);
|
|
840
|
+
if (isNaN(minutes) || isNaN(seconds)) return null;
|
|
841
|
+
if (seconds < 0 || seconds >= 60) return null;
|
|
842
|
+
return minutes * 60 + seconds;
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
// src/transcribe/llm-transcribe.ts
|
|
846
|
+
var MIN_SEGMENTS = 3;
|
|
847
|
+
var MIN_SPAN_RATIO = 0.6;
|
|
848
|
+
function toAbsolute(mmSs, offset) {
|
|
849
|
+
const s = parseMmSs(mmSs.trim());
|
|
850
|
+
return s === null ? null : s + offset;
|
|
851
|
+
}
|
|
852
|
+
function partitionByOwnership(segments) {
|
|
853
|
+
return segments.filter((s) => {
|
|
854
|
+
if (s.trustedStart === void 0) return true;
|
|
855
|
+
const center = (s.startSec + s.endSec) / 2;
|
|
856
|
+
return center >= s.trustedStart;
|
|
857
|
+
});
|
|
858
|
+
}
|
|
859
|
+
function parseLlmSegments(data, chunkOffsetSec) {
|
|
860
|
+
const out = [];
|
|
861
|
+
let dropped = 0;
|
|
862
|
+
for (const seg of data.segments || []) {
|
|
863
|
+
const start = toAbsolute(seg.start, chunkOffsetSec);
|
|
864
|
+
const end = toAbsolute(seg.end, chunkOffsetSec);
|
|
865
|
+
if (start === null || end === null || end < start) {
|
|
866
|
+
dropped++;
|
|
867
|
+
logger.debug(`[llm] dropping segment (bad time ${seg.start}-${seg.end}): "${(seg.text || "").slice(0, 40)}"`);
|
|
868
|
+
continue;
|
|
991
869
|
}
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
870
|
+
out.push({
|
|
871
|
+
speaker: (seg.speaker || "Unknown").trim(),
|
|
872
|
+
startSec: start,
|
|
873
|
+
endSec: end,
|
|
874
|
+
text: (seg.text || "").trim(),
|
|
875
|
+
tone: Array.isArray(seg.tone) ? seg.tone.map((t) => String(t).trim()).filter(Boolean) : [],
|
|
876
|
+
rawStart: seg.start,
|
|
877
|
+
rawEnd: seg.end
|
|
878
|
+
});
|
|
996
879
|
}
|
|
997
|
-
return
|
|
880
|
+
return { segments: out, dropped };
|
|
998
881
|
}
|
|
999
|
-
function
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
882
|
+
function validate(segments, chunkDuration) {
|
|
883
|
+
if (segments.length < MIN_SEGMENTS) {
|
|
884
|
+
return { isValid: false, spanSec: 0, segmentCount: segments.length, message: `only ${segments.length} segments (min ${MIN_SEGMENTS})` };
|
|
885
|
+
}
|
|
886
|
+
const first = segments[0].startSec;
|
|
887
|
+
const last = segments[segments.length - 1].endSec;
|
|
888
|
+
const span = last - first;
|
|
889
|
+
const minSpan = chunkDuration * MIN_SPAN_RATIO;
|
|
890
|
+
if (span < minSpan) {
|
|
891
|
+
return { isValid: false, spanSec: span, segmentCount: segments.length, message: `span ${span.toFixed(0)}s < ${minSpan.toFixed(0)}s required (${MIN_SPAN_RATIO * 100}% of chunk)` };
|
|
892
|
+
}
|
|
893
|
+
return { isValid: true, spanSec: span, segmentCount: segments.length, message: `ok (${segments.length} segments, ${span.toFixed(0)}s span)` };
|
|
1007
894
|
}
|
|
1008
|
-
function
|
|
1009
|
-
const
|
|
1010
|
-
const
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
895
|
+
async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts) {
|
|
896
|
+
const validationRetries = opts.validationRetries ?? 1;
|
|
897
|
+
const prompt = transcriptionPrompt(ctx);
|
|
898
|
+
let lastResult;
|
|
899
|
+
for (let attempt = 0; attempt <= validationRetries; attempt++) {
|
|
900
|
+
const gen = await client.generateJson(
|
|
901
|
+
model,
|
|
902
|
+
prompt,
|
|
903
|
+
[{ path: chunkPath }],
|
|
904
|
+
TRANSCRIPT_SCHEMA,
|
|
905
|
+
{
|
|
906
|
+
temperature: opts.temperature ?? 0.2,
|
|
907
|
+
maxRetries: 3,
|
|
908
|
+
logKind: "transcribe",
|
|
909
|
+
logChunk: ctx.index - 1
|
|
910
|
+
}
|
|
1014
911
|
);
|
|
1015
|
-
if (!
|
|
1016
|
-
|
|
912
|
+
if (gen.error || !gen.data) {
|
|
913
|
+
lastResult = {
|
|
914
|
+
segments: [],
|
|
915
|
+
raw: gen.raw,
|
|
916
|
+
usage: gen.usage,
|
|
917
|
+
validation: { isValid: false, spanSec: 0, segmentCount: 0, message: gen.error || "no data" },
|
|
918
|
+
error: gen.error
|
|
919
|
+
};
|
|
920
|
+
logger.warn(`[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`);
|
|
1017
921
|
continue;
|
|
1018
922
|
}
|
|
1019
|
-
|
|
1020
|
-
|
|
923
|
+
const { segments, dropped } = parseLlmSegments(gen.data, chunkStartSec);
|
|
924
|
+
const v = validate(segments, opts.chunkDurationSec);
|
|
925
|
+
lastResult = { segments, raw: gen.raw, usage: gen.usage, validation: v };
|
|
926
|
+
if (v.isValid) {
|
|
927
|
+
logger.info(`[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`);
|
|
928
|
+
return lastResult;
|
|
1021
929
|
}
|
|
930
|
+
logger.warn(`[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`);
|
|
1022
931
|
}
|
|
1023
|
-
|
|
932
|
+
logger.error(`[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`);
|
|
933
|
+
return lastResult;
|
|
1024
934
|
}
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
const minLen = Math.max(0.01, Math.min(a.end - a.start, b.end - b.start));
|
|
1030
|
-
return inter / minLen;
|
|
935
|
+
|
|
936
|
+
// src/align/normalize.ts
|
|
937
|
+
function normalize(word) {
|
|
938
|
+
return word.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "").replace(/'+$/g, "").replace(/^'+/g, "");
|
|
1031
939
|
}
|
|
1032
|
-
function
|
|
1033
|
-
const
|
|
1034
|
-
const
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
return
|
|
940
|
+
function tokenize(text) {
|
|
941
|
+
const out = [];
|
|
942
|
+
for (const raw of text.split(/\s+/)) {
|
|
943
|
+
if (!raw) continue;
|
|
944
|
+
const norm = normalize(raw);
|
|
945
|
+
if (norm) out.push({ original: raw, norm });
|
|
946
|
+
}
|
|
947
|
+
return out;
|
|
1040
948
|
}
|
|
1041
|
-
function
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
edgeDistance = Math.min(seg.start - chunk.startSeconds, chunk.endSeconds - seg.end);
|
|
949
|
+
function fuzzyEqual(a, b) {
|
|
950
|
+
if (a === b) return true;
|
|
951
|
+
if (Math.abs(a.length - b.length) <= 1) {
|
|
952
|
+
return editDistanceChars(a, b, 1) <= 1;
|
|
1046
953
|
}
|
|
1047
|
-
return
|
|
954
|
+
return false;
|
|
955
|
+
}
|
|
956
|
+
function editDistanceChars(a, b, max) {
|
|
957
|
+
const m = a.length;
|
|
958
|
+
const n = b.length;
|
|
959
|
+
if (Math.abs(m - n) > max) return max + 1;
|
|
960
|
+
let prev = new Array(n + 1);
|
|
961
|
+
for (let j = 0; j <= n; j++) prev[j] = j;
|
|
962
|
+
for (let i = 1; i <= m; i++) {
|
|
963
|
+
const cur = [i];
|
|
964
|
+
let rowMin = cur[0];
|
|
965
|
+
for (let j = 1; j <= n; j++) {
|
|
966
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
967
|
+
cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost);
|
|
968
|
+
if (cur[j] < rowMin) rowMin = cur[j];
|
|
969
|
+
}
|
|
970
|
+
if (rowMin > max) return max + 1;
|
|
971
|
+
prev = cur;
|
|
972
|
+
}
|
|
973
|
+
return prev[n];
|
|
1048
974
|
}
|
|
1049
975
|
|
|
1050
|
-
// src/
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
return {
|
|
1055
|
-
}
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
const voiceDist = {};
|
|
1078
|
-
let previousTail = "";
|
|
1079
|
-
for (const ch of timeChunks) {
|
|
1080
|
-
signal?.throwIfAborted();
|
|
1081
|
-
onProgress?.(chunked ? `Diarizing chunk ${ch.index + 1}/${timeChunks.length}` : `Diarizing`, ch.index, timeChunks.length);
|
|
1082
|
-
const windowHint = asr && asr.diarized ? buildAsrHint(sliceAsrWindow(asr, ch.startSeconds, ch.endSeconds, chunked)) : void 0;
|
|
1083
|
-
const prompt = buildDiarizationPrompt({
|
|
1084
|
-
instructions,
|
|
1085
|
-
asrHint: windowHint,
|
|
1086
|
-
chunk: chunked ? { index: ch.index, total: timeChunks.length, startSeconds: ch.startSeconds } : void 0,
|
|
1087
|
-
previousTail: chunked ? previousTail : void 0
|
|
1088
|
-
});
|
|
1089
|
-
const rawText = await diarizeChunk({ chunk: ch, index: ch.index, total: timeChunks.length, chunked, prompt });
|
|
1090
|
-
const turns = parseDiarizedText(rawText);
|
|
1091
|
-
if (turns.length === 0) throw new Error(`No diarized turns parsed from LLM output${chunked ? ` (chunk ${ch.index})` : ""}`);
|
|
1092
|
-
previousTail = turns.slice(-3).map((t) => `${t.speaker}: ${t.text}`).join("\n");
|
|
1093
|
-
if (chunked) {
|
|
1094
|
-
for (const t of turns) if (t.approxStart !== void 0) t.approxStart += ch.startSeconds;
|
|
976
|
+
// src/align/edit-distance.ts
|
|
977
|
+
var INDEL = 2;
|
|
978
|
+
function matchCost(a, b) {
|
|
979
|
+
if (a.norm === b.norm) return { cost: 0, fuzzy: false };
|
|
980
|
+
if (fuzzyEqual(a.norm, b.norm)) return { cost: 1, fuzzy: true };
|
|
981
|
+
return { cost: 2, fuzzy: false };
|
|
982
|
+
}
|
|
983
|
+
function alignWords(llm, asr) {
|
|
984
|
+
const m = llm.length;
|
|
985
|
+
const n = asr.length;
|
|
986
|
+
const dp = new Array(m + 1);
|
|
987
|
+
for (let i2 = 0; i2 <= m; i2++) {
|
|
988
|
+
const row = new Int32Array(n + 1);
|
|
989
|
+
row[0] = i2 * INDEL;
|
|
990
|
+
dp[i2] = row;
|
|
991
|
+
}
|
|
992
|
+
const firstRow = dp[0];
|
|
993
|
+
for (let j2 = 0; j2 <= n; j2++) firstRow[j2] = j2 * INDEL;
|
|
994
|
+
for (let i2 = 1; i2 <= m; i2++) {
|
|
995
|
+
const row = dp[i2];
|
|
996
|
+
const prev = dp[i2 - 1];
|
|
997
|
+
for (let j2 = 1; j2 <= n; j2++) {
|
|
998
|
+
const { cost } = matchCost(llm[i2 - 1], asr[j2 - 1]);
|
|
999
|
+
const sub = prev[j2 - 1] + cost;
|
|
1000
|
+
const ins2 = prev[j2] + INDEL;
|
|
1001
|
+
const del2 = row[j2 - 1] + INDEL;
|
|
1002
|
+
row[j2] = Math.min(sub, ins2, del2);
|
|
1095
1003
|
}
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1004
|
+
}
|
|
1005
|
+
const ops = [];
|
|
1006
|
+
let i = m;
|
|
1007
|
+
let j = n;
|
|
1008
|
+
let exact = 0;
|
|
1009
|
+
let fuzzy = 0;
|
|
1010
|
+
let subs = 0;
|
|
1011
|
+
let ins = 0;
|
|
1012
|
+
let del = 0;
|
|
1013
|
+
while (i > 0 || j > 0) {
|
|
1014
|
+
const cur = dp[i];
|
|
1015
|
+
if (i > 0 && j > 0) {
|
|
1016
|
+
const { cost } = matchCost(llm[i - 1], asr[j - 1]);
|
|
1017
|
+
const sub = dp[i - 1][j - 1] + cost;
|
|
1018
|
+
if (cur[j] === sub) {
|
|
1019
|
+
if (cost === 0) {
|
|
1020
|
+
ops.push({ type: "match", llm: i - 1, asr: j - 1, fuzzy: false });
|
|
1021
|
+
exact++;
|
|
1022
|
+
} else if (cost === 1) {
|
|
1023
|
+
ops.push({ type: "match", llm: i - 1, asr: j - 1, fuzzy: true });
|
|
1024
|
+
fuzzy++;
|
|
1025
|
+
} else {
|
|
1026
|
+
ops.push({ type: "substitute", llm: i - 1, asr: j - 1 });
|
|
1027
|
+
subs++;
|
|
1106
1028
|
}
|
|
1107
|
-
|
|
1029
|
+
i--;
|
|
1030
|
+
j--;
|
|
1031
|
+
continue;
|
|
1108
1032
|
}
|
|
1109
1033
|
}
|
|
1110
|
-
if (
|
|
1111
|
-
|
|
1112
|
-
|
|
1034
|
+
if (i > 0 && cur[j] === dp[i - 1][j] + INDEL) {
|
|
1035
|
+
ops.push({ type: "insert", llm: i - 1 });
|
|
1036
|
+
ins++;
|
|
1037
|
+
i--;
|
|
1038
|
+
continue;
|
|
1113
1039
|
}
|
|
1040
|
+
ops.push({ type: "delete", asr: j - 1 });
|
|
1041
|
+
del++;
|
|
1042
|
+
j--;
|
|
1114
1043
|
}
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1044
|
+
ops.reverse();
|
|
1045
|
+
return {
|
|
1046
|
+
ops,
|
|
1047
|
+
exactMatches: exact,
|
|
1048
|
+
fuzzyMatches: fuzzy,
|
|
1049
|
+
substitutions: subs,
|
|
1050
|
+
insertions: ins,
|
|
1051
|
+
deletions: del
|
|
1052
|
+
};
|
|
1123
1053
|
}
|
|
1124
1054
|
|
|
1125
|
-
// src/
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
}
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
return join2(this.dir, name);
|
|
1141
|
-
}
|
|
1142
|
-
/** Resolve a name to a path, ensuring its parent dir exists (supports "sub/dir/file"). */
|
|
1143
|
-
ensurePath(name) {
|
|
1144
|
-
const p = this.path(name);
|
|
1145
|
-
mkdirSync(dirname2(p), { recursive: true });
|
|
1146
|
-
return p;
|
|
1147
|
-
}
|
|
1148
|
-
has(name) {
|
|
1149
|
-
return existsSync(this.path(name));
|
|
1150
|
-
}
|
|
1151
|
-
readJSON(name) {
|
|
1152
|
-
const p = this.path(name);
|
|
1153
|
-
if (!existsSync(p)) return null;
|
|
1154
|
-
try {
|
|
1155
|
-
return JSON.parse(readFileSync(p, "utf8"));
|
|
1156
|
-
} catch {
|
|
1157
|
-
return null;
|
|
1055
|
+
// src/align/aligner.ts
|
|
1056
|
+
function toAsrTokens(words) {
|
|
1057
|
+
return words.map((w) => ({
|
|
1058
|
+
text: w.text,
|
|
1059
|
+
start: w.start,
|
|
1060
|
+
end: w.end,
|
|
1061
|
+
norm: w.text.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "")
|
|
1062
|
+
}));
|
|
1063
|
+
}
|
|
1064
|
+
function transferTiming(llm, asr, ops) {
|
|
1065
|
+
const times = llm.map(() => ({ start: NaN, end: NaN, matched: false }));
|
|
1066
|
+
for (const op of ops) {
|
|
1067
|
+
if (op.type === "match" || op.type === "substitute") {
|
|
1068
|
+
const a = asr[op.asr];
|
|
1069
|
+
times[op.llm] = { start: a.start, end: a.end, matched: op.type === "match" && !op.fuzzy };
|
|
1158
1070
|
}
|
|
1159
1071
|
}
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1072
|
+
for (let k = 0; k < times.length; k++) {
|
|
1073
|
+
if (!isNaN(times[k].start)) continue;
|
|
1074
|
+
let prevEnd = null;
|
|
1075
|
+
for (let p = k - 1; p >= 0; p--) {
|
|
1076
|
+
if (!isNaN(times[p].start)) {
|
|
1077
|
+
prevEnd = times[p].end;
|
|
1078
|
+
break;
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
let nextStart = null;
|
|
1082
|
+
for (let q = k + 1; q < times.length; q++) {
|
|
1083
|
+
if (!isNaN(times[q].start)) {
|
|
1084
|
+
nextStart = times[q].start;
|
|
1085
|
+
break;
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
if (prevEnd !== null && nextStart !== null) {
|
|
1089
|
+
const segIdx = llm[k].segIdx;
|
|
1090
|
+
let runLen = 0;
|
|
1091
|
+
for (let r = k; r < times.length && isNaN(times[r].start) && llm[r].segIdx === segIdx; r++)
|
|
1092
|
+
runLen++;
|
|
1093
|
+
const step = (nextStart - prevEnd) / (runLen + 1);
|
|
1094
|
+
for (let r = 0; r < runLen; r++) {
|
|
1095
|
+
const pt = prevEnd + step * (r + 1);
|
|
1096
|
+
times[k + r] = { start: pt, end: pt, matched: false };
|
|
1097
|
+
}
|
|
1098
|
+
k += runLen - 1;
|
|
1099
|
+
} else if (nextStart !== null) {
|
|
1100
|
+
times[k] = { start: nextStart, end: nextStart, matched: false };
|
|
1101
|
+
} else if (prevEnd !== null) {
|
|
1102
|
+
times[k] = { start: prevEnd, end: prevEnd, matched: false };
|
|
1103
|
+
}
|
|
1166
1104
|
}
|
|
1167
|
-
|
|
1168
|
-
|
|
1105
|
+
return times;
|
|
1106
|
+
}
|
|
1107
|
+
function alignSegments(llmSegments, asrWords, opts = {}) {
|
|
1108
|
+
const confThreshold = opts.confidenceThreshold ?? 0.5;
|
|
1109
|
+
const margin = opts.timeMarginSec ?? 0;
|
|
1110
|
+
const sorted = [...llmSegments].map((s, i) => ({ s, i })).sort((a, b) => a.s.startSec - b.s.startSec);
|
|
1111
|
+
const flat = [];
|
|
1112
|
+
const segRanges = [];
|
|
1113
|
+
for (const { s, i } of sorted) {
|
|
1114
|
+
const toks = tokenize(s.text);
|
|
1115
|
+
const start = flat.length;
|
|
1116
|
+
for (const t of toks) flat.push({ original: t.original, norm: t.norm, segIdx: i });
|
|
1117
|
+
segRanges.push({ src: i, start, end: flat.length });
|
|
1118
|
+
}
|
|
1119
|
+
if (flat.length === 0 || asrWords.length === 0) {
|
|
1120
|
+
return sorted.map(({ s, i }) => ({
|
|
1121
|
+
speaker: s.speaker,
|
|
1122
|
+
start: s.startSec,
|
|
1123
|
+
end: s.endSec,
|
|
1124
|
+
text: s.text,
|
|
1125
|
+
tone: s.tone,
|
|
1126
|
+
confidence: 0,
|
|
1127
|
+
timingSource: "coarse",
|
|
1128
|
+
words: [],
|
|
1129
|
+
sourceIndex: i
|
|
1130
|
+
}));
|
|
1131
|
+
}
|
|
1132
|
+
let asr = toAsrTokens(asrWords);
|
|
1133
|
+
if (margin > 0) {
|
|
1134
|
+
const lo = sorted[0].s.startSec - margin;
|
|
1135
|
+
const hi = sorted[sorted.length - 1].s.endSec + margin;
|
|
1136
|
+
asr = asr.filter((w) => w.end >= lo && w.start <= hi);
|
|
1137
|
+
}
|
|
1138
|
+
const result = alignWords(flat, asr);
|
|
1139
|
+
const times = transferTiming(flat, asr, result.ops);
|
|
1140
|
+
if (process.env.ALIGN_DEBUG) {
|
|
1141
|
+
console.error(
|
|
1142
|
+
`[align] flat=${flat.length} asr=${asr.length} exact=${result.exactMatches} fuzzy=${result.fuzzyMatches} subs=${result.substitutions} ins=${result.insertions} del=${result.deletions}`
|
|
1143
|
+
);
|
|
1169
1144
|
}
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1145
|
+
const out = [];
|
|
1146
|
+
for (let si = 0; si < sorted.length; si++) {
|
|
1147
|
+
const { s, i } = sorted[si];
|
|
1148
|
+
const range = segRanges[si];
|
|
1149
|
+
const segTimes = times.slice(range.start, range.end);
|
|
1150
|
+
const segOps = result.ops.filter(
|
|
1151
|
+
(op) => (op.type === "match" || op.type === "substitute") && op.llm >= range.start && op.llm < range.end
|
|
1152
|
+
);
|
|
1153
|
+
const exact = segOps.filter((op) => op.type === "match" && !op.fuzzy).length;
|
|
1154
|
+
const tokenCount = range.end - range.start;
|
|
1155
|
+
const firstTimed = segTimes.find((t) => !isNaN(t.start));
|
|
1156
|
+
const lastTimed = [...segTimes].reverse().find((t) => !isNaN(t.end));
|
|
1157
|
+
let start;
|
|
1158
|
+
let end;
|
|
1159
|
+
let timingSource;
|
|
1160
|
+
const confidence = tokenCount ? exact / tokenCount : 0;
|
|
1161
|
+
if (firstTimed && lastTimed) {
|
|
1162
|
+
start = firstTimed.start;
|
|
1163
|
+
end = lastTimed.end;
|
|
1164
|
+
timingSource = confidence >= confThreshold ? "aligned" : "interpolated";
|
|
1165
|
+
} else {
|
|
1166
|
+
start = s.startSec;
|
|
1167
|
+
end = s.endSec;
|
|
1168
|
+
timingSource = "coarse";
|
|
1175
1169
|
}
|
|
1176
|
-
const
|
|
1177
|
-
|
|
1178
|
-
|
|
1170
|
+
const words = segTimes.map((t, idx) => ({
|
|
1171
|
+
text: flat[range.start + idx].original,
|
|
1172
|
+
start: isNaN(t.start) ? start : t.start,
|
|
1173
|
+
end: isNaN(t.end) ? end : t.end,
|
|
1174
|
+
matched: t.matched
|
|
1175
|
+
}));
|
|
1176
|
+
out.push({
|
|
1177
|
+
speaker: s.speaker,
|
|
1178
|
+
start,
|
|
1179
|
+
end,
|
|
1180
|
+
text: s.text,
|
|
1181
|
+
tone: s.tone,
|
|
1182
|
+
confidence,
|
|
1183
|
+
timingSource,
|
|
1184
|
+
words,
|
|
1185
|
+
sourceIndex: i
|
|
1186
|
+
});
|
|
1179
1187
|
}
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1188
|
+
return out;
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
// src/align/fill-gaps.ts
|
|
1192
|
+
var MIN_GAP_SEC = 0.8;
|
|
1193
|
+
var MIN_WORDS = 1;
|
|
1194
|
+
function normSet(text) {
|
|
1195
|
+
return new Set(tokenize(text).map((t) => t.norm));
|
|
1196
|
+
}
|
|
1197
|
+
function fillAsrGaps(segments, asrWords, asrUtterances) {
|
|
1198
|
+
if (!asrWords.length) return segments;
|
|
1199
|
+
const sorted = [...segments].sort((a, b) => a.start - b.start);
|
|
1200
|
+
const ranges = [];
|
|
1201
|
+
const firstStart = sorted.length ? sorted[0].start : asrWords[asrWords.length - 1].end;
|
|
1202
|
+
if (firstStart > 0) ranges.push([0, firstStart, sorted[0]]);
|
|
1203
|
+
for (let i = 0; i < sorted.length - 1; i++) {
|
|
1204
|
+
const cur = sorted[i];
|
|
1205
|
+
const next = sorted[i + 1];
|
|
1206
|
+
if (next.start > cur.end) ranges.push([cur.end, next.start, next]);
|
|
1207
|
+
}
|
|
1208
|
+
const filled = [];
|
|
1209
|
+
for (const [gs, ge, following] of ranges) {
|
|
1210
|
+
if (ge - gs < MIN_GAP_SEC) continue;
|
|
1211
|
+
const words = asrWords.filter((w) => w.start >= gs && w.start < ge);
|
|
1212
|
+
if (words.length < MIN_WORDS) continue;
|
|
1213
|
+
if (following) {
|
|
1214
|
+
const followingWords = normSet(following.text);
|
|
1215
|
+
const gapNorms = words.map(
|
|
1216
|
+
(w) => w.text.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "")
|
|
1217
|
+
);
|
|
1218
|
+
const covered = gapNorms.filter((n) => n && followingWords.has(n)).length;
|
|
1219
|
+
if (covered / gapNorms.filter(Boolean).length >= 0.6) continue;
|
|
1184
1220
|
}
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1221
|
+
let bestSp = asrUtterances[0]?.speaker || "speaker_?";
|
|
1222
|
+
let bestOv = 0;
|
|
1223
|
+
for (const u of asrUtterances) {
|
|
1224
|
+
const ov = Math.max(0, Math.min(ge, u.end) - Math.max(gs, u.start));
|
|
1225
|
+
if (ov > bestOv) {
|
|
1226
|
+
bestOv = ov;
|
|
1227
|
+
bestSp = u.speaker;
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
filled.push({
|
|
1231
|
+
speaker: bestSp,
|
|
1232
|
+
start: words[0].start,
|
|
1233
|
+
end: words[words.length - 1].end,
|
|
1234
|
+
text: words.map((w) => w.text).join(" "),
|
|
1235
|
+
tone: [],
|
|
1236
|
+
confidence: 0,
|
|
1237
|
+
timingSource: "timestamped",
|
|
1238
|
+
words: words.map((w) => ({ text: w.text, start: w.start, end: w.end, matched: true })),
|
|
1239
|
+
sourceIndex: -1
|
|
1240
|
+
});
|
|
1188
1241
|
}
|
|
1189
|
-
|
|
1242
|
+
if (!filled.length) return sorted;
|
|
1243
|
+
return [...sorted, ...filled].sort((a, b) => a.start - b.start);
|
|
1244
|
+
}
|
|
1190
1245
|
|
|
1191
|
-
// src/
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1246
|
+
// src/diarize/consistency.ts
|
|
1247
|
+
function overlap(s1, e1, s2, e2) {
|
|
1248
|
+
return Math.max(0, Math.min(e1, e2) - Math.max(s1, s2));
|
|
1249
|
+
}
|
|
1250
|
+
function isGenericLabel(label) {
|
|
1251
|
+
return /^(speaker\s+[a-z0-9]+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(label.trim());
|
|
1252
|
+
}
|
|
1253
|
+
function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
|
|
1254
|
+
const hasDiarization = opts.hasDiarization ?? true;
|
|
1255
|
+
const out = segments.map((seg) => ({ seg, asrSpeaker: "" }));
|
|
1256
|
+
const labelVotes = {};
|
|
1257
|
+
const asrDuration = {};
|
|
1258
|
+
for (const o of out) {
|
|
1259
|
+
let bestSpeaker = "";
|
|
1260
|
+
let bestOverlap = 0;
|
|
1261
|
+
if (hasDiarization) {
|
|
1262
|
+
for (const u of asrUtterances) {
|
|
1263
|
+
const ov = overlap(o.seg.start, o.seg.end, u.start, u.end);
|
|
1264
|
+
if (ov > bestOverlap) {
|
|
1265
|
+
bestOverlap = ov;
|
|
1266
|
+
bestSpeaker = u.speaker;
|
|
1267
|
+
}
|
|
1205
1268
|
}
|
|
1269
|
+
if (!bestSpeaker) {
|
|
1270
|
+
let bestDist = Infinity;
|
|
1271
|
+
const segMid = (o.seg.start + o.seg.end) / 2;
|
|
1272
|
+
for (const u of asrUtterances) {
|
|
1273
|
+
const uMid = (u.start + u.end) / 2;
|
|
1274
|
+
const d = Math.abs(uMid - segMid);
|
|
1275
|
+
if (d < bestDist) {
|
|
1276
|
+
bestDist = d;
|
|
1277
|
+
bestSpeaker = u.speaker;
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
bestSpeaker = bestSpeaker || "speaker_?";
|
|
1281
|
+
}
|
|
1282
|
+
} else {
|
|
1283
|
+
bestSpeaker = o.seg.speaker || "speaker_?";
|
|
1284
|
+
bestOverlap = o.seg.end - o.seg.start;
|
|
1206
1285
|
}
|
|
1207
|
-
|
|
1208
|
-
|
|
1286
|
+
o.asrSpeaker = bestSpeaker;
|
|
1287
|
+
asrDuration[o.asrSpeaker] = (asrDuration[o.asrSpeaker] ?? 0) + Math.max(bestOverlap, 0.1);
|
|
1288
|
+
labelVotes[o.asrSpeaker] ??= {};
|
|
1289
|
+
labelVotes[o.asrSpeaker][o.seg.speaker] = (labelVotes[o.asrSpeaker][o.seg.speaker] ?? 0) + 1;
|
|
1290
|
+
}
|
|
1291
|
+
const dominantLabel = {};
|
|
1292
|
+
for (const [asrSp, votes] of Object.entries(labelVotes)) {
|
|
1293
|
+
const best = Object.entries(votes).sort((a, b) => b[1] - a[1])[0];
|
|
1294
|
+
dominantLabel[asrSp] = best ? best[0] : asrSp;
|
|
1295
|
+
}
|
|
1296
|
+
const asrToGroup = {};
|
|
1297
|
+
const groupLabel = {};
|
|
1298
|
+
const groupTalk = {};
|
|
1299
|
+
const groupAsrVoices = {};
|
|
1300
|
+
for (const asrSp of Object.keys(labelVotes)) {
|
|
1301
|
+
const label = dominantLabel[asrSp] ?? asrSp;
|
|
1302
|
+
let groupId;
|
|
1303
|
+
if (!isGenericLabel(label)) {
|
|
1304
|
+
groupId = Object.keys(groupLabel).find((g) => groupLabel[g] === label);
|
|
1305
|
+
}
|
|
1306
|
+
if (!groupId) {
|
|
1307
|
+
groupId = asrSp;
|
|
1308
|
+
groupLabel[groupId] = label;
|
|
1309
|
+
}
|
|
1310
|
+
asrToGroup[asrSp] = groupId;
|
|
1311
|
+
groupTalk[groupId] = (groupTalk[groupId] ?? 0) + (asrDuration[asrSp] ?? 0);
|
|
1312
|
+
(groupAsrVoices[groupId] ??= []).push(asrSp);
|
|
1313
|
+
}
|
|
1314
|
+
const groupsByTalk = Object.keys(groupTalk).sort((a, b) => groupTalk[b] - groupTalk[a]);
|
|
1315
|
+
const groupToGlobal = {};
|
|
1316
|
+
groupsByTalk.forEach((g, i) => {
|
|
1317
|
+
groupToGlobal[g] = `Speaker ${String.fromCharCode(65 + i)}`;
|
|
1318
|
+
});
|
|
1319
|
+
const displayNames = {};
|
|
1320
|
+
for (const g of groupsByTalk) {
|
|
1321
|
+
const label = groupLabel[g];
|
|
1322
|
+
displayNames[groupToGlobal[g]] = isGenericLabel(label) ? groupToGlobal[g] : label;
|
|
1323
|
+
}
|
|
1324
|
+
const llmLabelToAsr = {};
|
|
1325
|
+
for (const o of out) {
|
|
1326
|
+
llmLabelToAsr[o.seg.speaker] = groupToGlobal[asrToGroup[o.asrSpeaker]];
|
|
1327
|
+
}
|
|
1328
|
+
const updated = out.map((o) => {
|
|
1329
|
+
const global = groupToGlobal[asrToGroup[o.asrSpeaker]];
|
|
1330
|
+
return {
|
|
1331
|
+
...o.seg,
|
|
1332
|
+
speaker: global,
|
|
1333
|
+
speakerName: displayNames[global] || global
|
|
1334
|
+
};
|
|
1335
|
+
});
|
|
1336
|
+
const speakerMap = {};
|
|
1337
|
+
for (const s of updated) {
|
|
1338
|
+
speakerMap[s.speaker] ??= { count: 0, talk: 0 };
|
|
1339
|
+
speakerMap[s.speaker].count++;
|
|
1340
|
+
speakerMap[s.speaker].talk += s.end - s.start;
|
|
1341
|
+
}
|
|
1342
|
+
const globalAsrVoices = {};
|
|
1343
|
+
for (const [g, voices] of Object.entries(groupAsrVoices)) {
|
|
1344
|
+
globalAsrVoices[groupToGlobal[g]] = voices;
|
|
1345
|
+
}
|
|
1346
|
+
const speakers = Object.entries(speakerMap).map(([id, v]) => ({
|
|
1347
|
+
id,
|
|
1348
|
+
name: displayNames[id],
|
|
1349
|
+
segmentCount: v.count,
|
|
1350
|
+
talkTime: v.talk,
|
|
1351
|
+
asrVoices: globalAsrVoices[id]
|
|
1352
|
+
})).filter((s) => s.talkTime > 0).sort((a, b) => (b.talkTime ?? 0) - (a.talkTime ?? 0));
|
|
1353
|
+
return { segments: updated, speakers, displayNames, llmLabelToAsr };
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
// src/providers/openai-compat.ts
|
|
1357
|
+
var PROVIDER_BASE = {
|
|
1358
|
+
deepseek: "https://api.deepseek.com/v1",
|
|
1359
|
+
groq: "https://api.groq.com/openai/v1",
|
|
1360
|
+
openai: "https://api.openai.com/v1"
|
|
1209
1361
|
};
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1362
|
+
var OpenAICompatClient = class _OpenAICompatClient {
|
|
1363
|
+
constructor(baseUrl, apiKey, defaultModel, providerName = "openai-compat") {
|
|
1364
|
+
this.baseUrl = baseUrl;
|
|
1365
|
+
this.apiKey = apiKey;
|
|
1366
|
+
this.defaultModel = defaultModel;
|
|
1367
|
+
this.providerName = providerName;
|
|
1368
|
+
}
|
|
1369
|
+
baseUrl;
|
|
1370
|
+
apiKey;
|
|
1371
|
+
defaultModel;
|
|
1372
|
+
providerName;
|
|
1373
|
+
static fromProvider(provider, apiKey, defaultModel) {
|
|
1374
|
+
const base = PROVIDER_BASE[provider] ?? provider;
|
|
1375
|
+
return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
|
|
1376
|
+
}
|
|
1377
|
+
async chat(model, messages, opts = {}) {
|
|
1378
|
+
const m = model ?? this.defaultModel;
|
|
1379
|
+
const maxRetries = opts.maxRetries ?? 2;
|
|
1380
|
+
const body = {
|
|
1381
|
+
model: m,
|
|
1382
|
+
messages,
|
|
1383
|
+
temperature: opts.temperature ?? 0.2
|
|
1384
|
+
};
|
|
1385
|
+
if (opts.maxTokens) body.max_tokens = opts.maxTokens;
|
|
1386
|
+
if (opts.responseJson) {
|
|
1387
|
+
body.response_format = { type: "json_object" };
|
|
1388
|
+
}
|
|
1389
|
+
let lastError;
|
|
1390
|
+
const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
|
|
1391
|
+
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
1392
|
+
const t0 = Date.now();
|
|
1393
|
+
try {
|
|
1394
|
+
const res = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
1395
|
+
method: "POST",
|
|
1396
|
+
headers: {
|
|
1397
|
+
"Content-Type": "application/json",
|
|
1398
|
+
Authorization: `Bearer ${this.apiKey}`
|
|
1399
|
+
},
|
|
1400
|
+
body: JSON.stringify(body)
|
|
1401
|
+
});
|
|
1402
|
+
if (!res.ok) {
|
|
1403
|
+
const txt = await res.text();
|
|
1404
|
+
throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
|
|
1405
|
+
}
|
|
1406
|
+
const data = await res.json();
|
|
1407
|
+
const text = data.choices?.[0]?.message?.content ?? "";
|
|
1408
|
+
const usage = {
|
|
1409
|
+
inputTokens: data.usage?.prompt_tokens ?? 0,
|
|
1410
|
+
outputTokens: data.usage?.completion_tokens ?? 0
|
|
1411
|
+
};
|
|
1412
|
+
logLlmCall({
|
|
1413
|
+
ts: new Date(t0).toISOString(),
|
|
1414
|
+
provider: this.providerName,
|
|
1415
|
+
model: m,
|
|
1416
|
+
kind: opts.logKind,
|
|
1417
|
+
prompt: promptStr,
|
|
1418
|
+
response: text,
|
|
1419
|
+
usage,
|
|
1420
|
+
durationMs: Date.now() - t0,
|
|
1421
|
+
attempt: attempt + 1
|
|
1422
|
+
});
|
|
1423
|
+
return { text, usage };
|
|
1424
|
+
} catch (err) {
|
|
1425
|
+
lastError = err instanceof Error ? err.message : String(err);
|
|
1426
|
+
logLlmCall({
|
|
1427
|
+
ts: new Date(t0).toISOString(),
|
|
1428
|
+
provider: this.providerName,
|
|
1429
|
+
model: m,
|
|
1430
|
+
kind: opts.logKind,
|
|
1431
|
+
prompt: promptStr,
|
|
1432
|
+
response: "",
|
|
1433
|
+
durationMs: Date.now() - t0,
|
|
1434
|
+
attempt: attempt + 1,
|
|
1435
|
+
error: lastError
|
|
1436
|
+
});
|
|
1437
|
+
if (attempt < maxRetries - 1) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
|
|
1441
|
+
}
|
|
1442
|
+
async chatJson(model, messages, opts = {}) {
|
|
1443
|
+
const res = await this.chat(model, messages, { ...opts, responseJson: true });
|
|
1444
|
+
if (res.error || !res.text) return { data: null, raw: res.text, error: res.error };
|
|
1445
|
+
try {
|
|
1446
|
+
let txt = res.text.trim();
|
|
1447
|
+
const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
|
|
1448
|
+
if (fence && fence[1]) txt = fence[1];
|
|
1449
|
+
return { data: JSON.parse(txt), raw: res.text };
|
|
1450
|
+
} catch (err) {
|
|
1451
|
+
return { data: null, raw: res.text, error: `JSON parse: ${err instanceof Error ? err.message : String(err)}` };
|
|
1235
1452
|
}
|
|
1236
1453
|
}
|
|
1237
|
-
|
|
1454
|
+
};
|
|
1455
|
+
|
|
1456
|
+
// src/diarize/identify.ts
|
|
1457
|
+
function buildTranscriptExcerpt(segments, speakers) {
|
|
1458
|
+
const bySpeaker = {};
|
|
1459
|
+
for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
|
|
1460
|
+
const parts = [];
|
|
1461
|
+
for (const sp of speakers) {
|
|
1462
|
+
const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
|
|
1463
|
+
const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
|
|
1464
|
+
parts.push(
|
|
1465
|
+
`### ${sp.id} (${sp.name || "unknown"}, ${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s${voices})`
|
|
1466
|
+
);
|
|
1467
|
+
for (const s of segs) parts.push(` ${s.text}`);
|
|
1468
|
+
}
|
|
1469
|
+
return parts.join("\n");
|
|
1238
1470
|
}
|
|
1239
|
-
function
|
|
1240
|
-
|
|
1241
|
-
const examples = exampleTurns(turns);
|
|
1242
|
-
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.
|
|
1471
|
+
function identifyPrompt(transcriptExcerpt, roster, knownSpeakers) {
|
|
1472
|
+
return `You are identifying speakers in a transcribed recording. Below are the most substantial quotes from each speaker (labeled exactly as shown in the headers, e.g. "Speaker A"), plus a roster description.
|
|
1243
1473
|
|
|
1244
|
-
|
|
1245
|
-
- Merge labels that refer to the SAME person.
|
|
1246
|
-
- 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".
|
|
1247
|
-
- Add a short role/description if evident (e.g. "main presenter", "audience member").
|
|
1248
|
-
- 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).
|
|
1249
|
-
${options.instructions ? `- Follow these user instructions for naming/grouping: ${options.instructions}
|
|
1250
|
-
` : ""}
|
|
1251
|
-
Distinct raw labels: ${labels.map((l) => `"${l}"`).join(", ")}
|
|
1474
|
+
Identify each speaker by name and/or role using content cues: self-introductions ("my name is X"), references to themselves, their role, or context. If you cannot confidently identify a speaker, leave the name empty ("").
|
|
1252
1475
|
|
|
1253
|
-
${
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
const
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
return
|
|
1272
|
-
}
|
|
1273
|
-
|
|
1476
|
+
${knownSpeakers && knownSpeakers.length ? `Known possible speakers: ${knownSpeakers.join(", ")}
|
|
1477
|
+
` : ""}ROSTER:
|
|
1478
|
+
${roster}
|
|
1479
|
+
|
|
1480
|
+
TRANSCRIPT EXCERPTS BY SPEAKER:
|
|
1481
|
+
${transcriptExcerpt}
|
|
1482
|
+
|
|
1483
|
+
Respond as JSON: { "speakers": [ { "id": "<exact speaker id from the headers>", "name": "Full Name or Role", "confidence": "high|medium|low", "evidence": "short quote/reason" } ], "reasoning": "one-paragraph summary" }
|
|
1484
|
+
Use the EXACT speaker id strings from the headers above (e.g. "Speaker A").`;
|
|
1485
|
+
}
|
|
1486
|
+
async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers) {
|
|
1487
|
+
const excerpt = buildTranscriptExcerpt(segments, speakers);
|
|
1488
|
+
const { data, error } = await client.chatJson(
|
|
1489
|
+
model,
|
|
1490
|
+
[{ role: "user", content: identifyPrompt(excerpt, roster, knownSpeakers) }],
|
|
1491
|
+
{ temperature: 0.1, maxTokens: 2e3, logKind: "identify" }
|
|
1492
|
+
);
|
|
1493
|
+
if (error || !data) {
|
|
1494
|
+
return { nameMap: {}, speakers: [], reasoning: error || "no response" };
|
|
1495
|
+
}
|
|
1496
|
+
const nameMap = {};
|
|
1497
|
+
for (const s of data.speakers || []) {
|
|
1498
|
+
if (s.name && s.name.trim()) nameMap[s.id] = s.name.trim();
|
|
1274
1499
|
}
|
|
1500
|
+
return { nameMap, speakers: data.speakers || [], reasoning: data.reasoning || "" };
|
|
1275
1501
|
}
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
const
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1502
|
+
|
|
1503
|
+
// src/finalize/finalize.ts
|
|
1504
|
+
var MIN_DUR = 0.5;
|
|
1505
|
+
var MAX_DUR = 7;
|
|
1506
|
+
var OVERLAP_GAP = 0.05;
|
|
1507
|
+
function textSimilarity(a, b) {
|
|
1508
|
+
const ta = new Set(tokenize(a).map((t) => t.norm));
|
|
1509
|
+
const tb = new Set(tokenize(b).map((t) => t.norm));
|
|
1510
|
+
if (ta.size === 0 && tb.size === 0) return 1;
|
|
1511
|
+
if (ta.size === 0 || tb.size === 0) return 0;
|
|
1512
|
+
let inter = 0;
|
|
1513
|
+
for (const t of ta) if (tb.has(t)) inter++;
|
|
1514
|
+
return inter / (ta.size + tb.size - inter);
|
|
1515
|
+
}
|
|
1516
|
+
function timeOverlapFrac(a, b) {
|
|
1517
|
+
const ov = Math.max(0, Math.min(a.end, b.end) - Math.max(a.start, b.start));
|
|
1518
|
+
const shorter = Math.min(a.end - a.start, b.end - b.start);
|
|
1519
|
+
return shorter > 0 ? ov / shorter : 0;
|
|
1520
|
+
}
|
|
1521
|
+
function dedupSegments(segments) {
|
|
1522
|
+
const sorted = [...segments].sort((a, b) => a.start - b.start);
|
|
1523
|
+
const kept = [];
|
|
1524
|
+
for (const seg of sorted) {
|
|
1525
|
+
const dup = kept.find(
|
|
1526
|
+
(k) => k.speaker === seg.speaker && textSimilarity(k.text, seg.text) > 0.7 && timeOverlapFrac(k, seg) > 0.2
|
|
1527
|
+
);
|
|
1528
|
+
if (dup) {
|
|
1529
|
+
if (seg.confidence > dup.confidence) {
|
|
1530
|
+
Object.assign(dup, seg);
|
|
1531
|
+
}
|
|
1532
|
+
continue;
|
|
1533
|
+
}
|
|
1534
|
+
kept.push(seg);
|
|
1535
|
+
}
|
|
1536
|
+
return kept;
|
|
1537
|
+
}
|
|
1538
|
+
function fixOverlaps(segments) {
|
|
1539
|
+
if (segments.length === 0) return segments;
|
|
1540
|
+
const sorted = [...segments].sort((a, b) => a.start - b.start);
|
|
1541
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1542
|
+
let changed = false;
|
|
1543
|
+
for (let i = 0; i < sorted.length - 1; i++) {
|
|
1544
|
+
const cur = sorted[i];
|
|
1545
|
+
const next = sorted[i + 1];
|
|
1546
|
+
if (cur.end > next.start) {
|
|
1547
|
+
const targetEnd = next.start - OVERLAP_GAP;
|
|
1548
|
+
const newDur = targetEnd - cur.start;
|
|
1549
|
+
if (newDur >= MIN_DUR) {
|
|
1550
|
+
cur.end = targetEnd;
|
|
1551
|
+
changed = true;
|
|
1552
|
+
} else {
|
|
1553
|
+
const shiftedStart = cur.end + OVERLAP_GAP;
|
|
1554
|
+
const followingStart = sorted[i + 2]?.start ?? Infinity;
|
|
1555
|
+
if (shiftedStart < next.end - MIN_DUR && shiftedStart < followingStart) {
|
|
1556
|
+
next.start = shiftedStart;
|
|
1557
|
+
changed = true;
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1294
1561
|
}
|
|
1562
|
+
if (!changed) break;
|
|
1295
1563
|
}
|
|
1296
|
-
return
|
|
1564
|
+
return sorted;
|
|
1565
|
+
}
|
|
1566
|
+
function clampAndFix(segments) {
|
|
1567
|
+
for (const s of segments) {
|
|
1568
|
+
const dur = s.end - s.start;
|
|
1569
|
+
if (dur < MIN_DUR) s.end = s.start + MIN_DUR;
|
|
1570
|
+
else if (dur > MAX_DUR) s.end = s.start + MAX_DUR;
|
|
1571
|
+
}
|
|
1572
|
+
return fixOverlaps(segments);
|
|
1573
|
+
}
|
|
1574
|
+
function finalizeSegments(segments, opts = {}) {
|
|
1575
|
+
const minSeg = opts.minSegmentSec ?? 0.2;
|
|
1576
|
+
let deduped = dedupSegments(segments);
|
|
1577
|
+
deduped = deduped.filter((s) => s.end - s.start >= minSeg && s.text.trim().length > 0);
|
|
1578
|
+
const out = deduped.map((s, i) => ({
|
|
1579
|
+
id: i + 1,
|
|
1580
|
+
start: s.start,
|
|
1581
|
+
end: s.end,
|
|
1582
|
+
speaker: s.speaker,
|
|
1583
|
+
speakerName: s.speakerName || s.speaker,
|
|
1584
|
+
// Collapse any internal whitespace (incl. newlines) so a stray blank line in the LLM
|
|
1585
|
+
// text can never split one SRT cue into several — SRT cues end at a blank line.
|
|
1586
|
+
text: s.text.trim().replace(/\s+/g, " "),
|
|
1587
|
+
tone: s.tone,
|
|
1588
|
+
timingSource: s.timingSource,
|
|
1589
|
+
confidence: s.confidence,
|
|
1590
|
+
words: s.words
|
|
1591
|
+
}));
|
|
1592
|
+
return clampAndFix(out);
|
|
1297
1593
|
}
|
|
1298
1594
|
|
|
1299
|
-
// src/
|
|
1300
|
-
var
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
logLlm = true,
|
|
1322
|
-
onProgress,
|
|
1323
|
-
signal,
|
|
1324
|
-
apiKeys
|
|
1325
|
-
} = options;
|
|
1326
|
-
const progress = (stage2, message, pct) => onProgress?.({ stage: stage2, message, pct });
|
|
1327
|
-
const checkAbort = () => signal?.throwIfAborted();
|
|
1328
|
-
checkAbort();
|
|
1329
|
-
if (!existsSync2(input)) throw new Error(`Input not found: ${input}`);
|
|
1330
|
-
const base = basename2(input, extname2(input));
|
|
1331
|
-
const interDir = options.intermediatesDir ?? join3(dirname3(input), `.offmute_${base}`);
|
|
1332
|
-
const inter = new Intermediates(interDir);
|
|
1333
|
-
const sourceSig = {
|
|
1334
|
-
v: 1,
|
|
1335
|
-
key: mediaKey(input),
|
|
1336
|
-
path: input,
|
|
1337
|
-
model: llmModel,
|
|
1338
|
-
instructions: instructions ?? null,
|
|
1339
|
-
thinkingLevel: llmThinkingLevel,
|
|
1340
|
-
asr: asrProvider,
|
|
1341
|
-
subSegment,
|
|
1342
|
-
identify: identifySpeakers
|
|
1595
|
+
// src/finalize/format.ts
|
|
1596
|
+
var MAX_CHARS = 84;
|
|
1597
|
+
var MAX_BLOCK_SEC = 7;
|
|
1598
|
+
function splitIntoBlocks(seg) {
|
|
1599
|
+
const words = seg.words && seg.words.length > 0 ? seg.words : null;
|
|
1600
|
+
if (!words) {
|
|
1601
|
+
return [{ start: seg.start, end: seg.end, text: seg.text }];
|
|
1602
|
+
}
|
|
1603
|
+
const blocks = [];
|
|
1604
|
+
let curWords = [];
|
|
1605
|
+
let curLen = 0;
|
|
1606
|
+
const flush = () => {
|
|
1607
|
+
if (curWords.length === 0) return;
|
|
1608
|
+
const first = curWords[0];
|
|
1609
|
+
const last = curWords[curWords.length - 1];
|
|
1610
|
+
blocks.push({
|
|
1611
|
+
start: first.start,
|
|
1612
|
+
end: last.end,
|
|
1613
|
+
text: curWords.map((w) => w.text).join(" ")
|
|
1614
|
+
});
|
|
1615
|
+
curWords = [];
|
|
1616
|
+
curLen = 0;
|
|
1343
1617
|
};
|
|
1344
|
-
const
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
progress("probe", `Probing ${basename2(input)}`);
|
|
1351
|
-
const info = await inter.cachedJSON("media-info.json", effectiveCache, () => probeMedia(input));
|
|
1352
|
-
const isVideo = info.hasVideo && VIDEO_EXT.has(extname2(input).toLowerCase());
|
|
1353
|
-
const useVideo = (options.useVideo ?? isVideo) && info.hasVideo;
|
|
1354
|
-
progress("preprocess", "Extracting 16k mono audio");
|
|
1355
|
-
const audioPath = inter.path("audio.mp3");
|
|
1356
|
-
if (!effectiveCache || !existsSync2(audioPath)) {
|
|
1357
|
-
await extractAudio(input, audioPath, { sampleRate: 16e3, channels: 1 });
|
|
1358
|
-
}
|
|
1359
|
-
let keyframePaths = [];
|
|
1360
|
-
if (useVideo && keyframeCount > 0) {
|
|
1361
|
-
progress("preprocess", `Extracting ${keyframeCount} keyframes`);
|
|
1362
|
-
const kfDir = inter.path("keyframes");
|
|
1363
|
-
try {
|
|
1364
|
-
if (!effectiveCache || !existsSync2(kfDir)) {
|
|
1365
|
-
keyframePaths = await extractKeyframes(input, kfDir, {
|
|
1366
|
-
count: keyframeCount,
|
|
1367
|
-
durationSeconds: info.durationSeconds
|
|
1368
|
-
});
|
|
1369
|
-
} else {
|
|
1370
|
-
const { readdirSync } = await import("fs");
|
|
1371
|
-
keyframePaths = readdirSync(kfDir).filter((f) => f.endsWith(".jpg")).sort().map((f) => join3(kfDir, f));
|
|
1372
|
-
}
|
|
1373
|
-
} catch (e) {
|
|
1374
|
-
progress("preprocess", `Skipping keyframes (${e.message.slice(0, 60)})`);
|
|
1375
|
-
keyframePaths = [];
|
|
1618
|
+
for (const w of words) {
|
|
1619
|
+
const addLen = w.text.length + 1;
|
|
1620
|
+
const blockStart = curWords.length === 0 ? w.start : curWords[0].start;
|
|
1621
|
+
const wouldSec = w.end - blockStart;
|
|
1622
|
+
if (curLen + addLen > MAX_CHARS || wouldSec > MAX_BLOCK_SEC) {
|
|
1623
|
+
flush();
|
|
1376
1624
|
}
|
|
1625
|
+
curWords.push(w);
|
|
1626
|
+
curLen += addLen;
|
|
1377
1627
|
}
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1628
|
+
flush();
|
|
1629
|
+
return blocks.length ? blocks : [{ start: seg.start, end: seg.end, text: seg.text }];
|
|
1630
|
+
}
|
|
1631
|
+
function formatSrt(result, opts = {}) {
|
|
1632
|
+
const labelSpeakers = opts.labelSpeakers ?? true;
|
|
1633
|
+
const showTone = opts.showTone ?? true;
|
|
1634
|
+
let idx = 1;
|
|
1635
|
+
const blocks = [];
|
|
1636
|
+
for (const seg of result.segments) {
|
|
1637
|
+
const tone = showTone && seg.tone && seg.tone.length ? ` (${seg.tone.join(", ")})` : "";
|
|
1638
|
+
const speaker = labelSpeakers ? `${seg.speakerName || seg.speaker}: ` : "";
|
|
1639
|
+
for (const b of splitIntoBlocks(seg)) {
|
|
1640
|
+
blocks.push(`${idx}
|
|
1641
|
+
${formatSrtTiming(b.start, b.end)}
|
|
1642
|
+
${speaker}${b.text}${tone}
|
|
1643
|
+
`);
|
|
1644
|
+
idx++;
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
return blocks.join("\n");
|
|
1648
|
+
}
|
|
1649
|
+
function formatMarkdown(result, opts = {}) {
|
|
1650
|
+
const parts = [];
|
|
1651
|
+
parts.push(`# ${opts.title || "Transcript"}
|
|
1652
|
+
`);
|
|
1653
|
+
parts.push(`*Duration: ${Math.round(result.metadata.duration)}s \xB7 Speakers: ${result.speakers.length}*
|
|
1654
|
+
`);
|
|
1655
|
+
parts.push("\n## Speakers\n");
|
|
1656
|
+
for (const s of result.speakers) {
|
|
1657
|
+
const talk = s.talkTime ? ` (${Math.round(s.talkTime)}s)` : "";
|
|
1658
|
+
parts.push(`- **${s.name || s.id}**${talk}`);
|
|
1659
|
+
}
|
|
1660
|
+
parts.push("\n## Transcript\n");
|
|
1661
|
+
for (const seg of result.segments) {
|
|
1662
|
+
const mm = Math.floor(seg.start / 60).toString().padStart(2, "0");
|
|
1663
|
+
const ss = Math.floor(seg.start % 60).toString().padStart(2, "0");
|
|
1664
|
+
const tone = seg.tone && seg.tone.length ? ` *(${seg.tone.join(", ")})*` : "";
|
|
1665
|
+
parts.push(`[${mm}:${ss}] **${seg.speakerName || seg.speaker}**${tone}: ${seg.text}
|
|
1666
|
+
`);
|
|
1394
1667
|
}
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
const n = String(llmSeq++).padStart(2, "0");
|
|
1401
|
-
const stem = `llm/${n}-${rec.label ?? "call"}`;
|
|
1402
|
-
inter.writeText(`${stem}.prompt.txt`, rec.promptText + (rec.fileParts ? `
|
|
1668
|
+
return parts.join("\n");
|
|
1669
|
+
}
|
|
1670
|
+
function formatJson(result) {
|
|
1671
|
+
return JSON.stringify(result, null, 2);
|
|
1672
|
+
}
|
|
1403
1673
|
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1674
|
+
// src/core/pipeline.ts
|
|
1675
|
+
import { basename as basename3 } from "path";
|
|
1676
|
+
var JSON_OPTS = { encoding: "utf-8" };
|
|
1677
|
+
function readJson(p) {
|
|
1678
|
+
if (!existsSync2(p)) return null;
|
|
1679
|
+
try {
|
|
1680
|
+
return JSON.parse(readFileSync(p, JSON_OPTS));
|
|
1681
|
+
} catch {
|
|
1682
|
+
return null;
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
function writeJson(p, data) {
|
|
1686
|
+
writeFileSync(p, JSON.stringify(data, null, 2), JSON_OPTS);
|
|
1687
|
+
}
|
|
1688
|
+
async function mapPool(items, limit, fn) {
|
|
1689
|
+
const results = new Array(items.length);
|
|
1690
|
+
let next = 0;
|
|
1691
|
+
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
1692
|
+
while (true) {
|
|
1693
|
+
const i = next++;
|
|
1694
|
+
if (i >= items.length) break;
|
|
1695
|
+
results[i] = await fn(items[i], i);
|
|
1407
1696
|
}
|
|
1697
|
+
});
|
|
1698
|
+
await Promise.all(workers);
|
|
1699
|
+
return results;
|
|
1700
|
+
}
|
|
1701
|
+
function has(passes, p) {
|
|
1702
|
+
return passes.includes(p);
|
|
1703
|
+
}
|
|
1704
|
+
async function transcribe(opts) {
|
|
1705
|
+
if (!opts || typeof opts.input !== "string" || opts.input.length === 0) {
|
|
1706
|
+
throw new Error("transcribe(options): 'input' (path to the audio/video file) is required");
|
|
1707
|
+
}
|
|
1708
|
+
if (typeof opts.outputDir !== "string" || opts.outputDir.length === 0) {
|
|
1709
|
+
throw new Error("transcribe(options): 'outputDir' (directory for outputs) is required");
|
|
1710
|
+
}
|
|
1711
|
+
const options = resolveOptions(opts);
|
|
1712
|
+
const keys = resolveKeys(options.apiKeys);
|
|
1713
|
+
logger.setLevel(options.logLevel);
|
|
1714
|
+
if (!existsSync2(options.input)) {
|
|
1715
|
+
throw new Error(`Input file not found: ${options.input}`);
|
|
1716
|
+
}
|
|
1717
|
+
mkdirSync(options.intermediatesDir, { recursive: true });
|
|
1718
|
+
mkdirSync(options.outputDir, { recursive: true });
|
|
1719
|
+
setLlmLogPath(options.llmLog ? `${options.intermediatesDir}/llm-calls.jsonl` : null);
|
|
1720
|
+
const sourcePath = `${options.intermediatesDir}/source.json`;
|
|
1721
|
+
const sig = inputSignature(options.input);
|
|
1722
|
+
const cfgSig = configSignature(opts);
|
|
1723
|
+
const prevSig = readJson(sourcePath);
|
|
1724
|
+
const inputChanged = !prevSig || prevSig.signature !== sig;
|
|
1725
|
+
const configChanged = !prevSig || prevSig.config !== cfgSig;
|
|
1726
|
+
if (inputChanged && prevSig) {
|
|
1727
|
+
logger.warn(
|
|
1728
|
+
`input file changed since last run (was ${prevSig.input ?? "?"}) \u2014 discarding cached intermediates`
|
|
1729
|
+
);
|
|
1730
|
+
} else if (configChanged && prevSig) {
|
|
1731
|
+
logger.warn(
|
|
1732
|
+
"options changed since last run (model / chunking / instructions / provider) \u2014 discarding cached intermediates"
|
|
1733
|
+
);
|
|
1734
|
+
}
|
|
1735
|
+
const forceAll = options.force || inputChanged || configChanged;
|
|
1736
|
+
writeJson(sourcePath, {
|
|
1737
|
+
input: options.input,
|
|
1738
|
+
signature: sig,
|
|
1739
|
+
config: cfgSig,
|
|
1740
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1741
|
+
});
|
|
1742
|
+
const passes = options.passes;
|
|
1743
|
+
const models = {
|
|
1744
|
+
transcribe: options.model ?? DEFAULT_TRANSCRIBE_MODEL,
|
|
1745
|
+
reasoner: options.reasoner ?? DEFAULT_REASONER_MODEL
|
|
1408
1746
|
};
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
signal,
|
|
1418
|
-
onProgress: (msg) => progress("diarize", msg),
|
|
1419
|
-
// Node-specific: extract this chunk's audio, call Gemini, cache + log the raw text.
|
|
1420
|
-
diarizeChunk: ({ chunk, chunked, prompt }) => {
|
|
1421
|
-
const rawName = chunked ? `diarize_chunk_${chunk.index}.txt` : "diarize.txt";
|
|
1422
|
-
const label = chunked ? `diarize-chunk-${chunk.index}` : "diarize";
|
|
1423
|
-
return inter.cachedText(
|
|
1424
|
-
rawName,
|
|
1425
|
-
effectiveCache,
|
|
1426
|
-
() => stage(label, async () => {
|
|
1427
|
-
let chunkAudio = audioPath;
|
|
1428
|
-
if (chunked) {
|
|
1429
|
-
chunkAudio = inter.path(`audio_chunk_${chunk.index}.mp3`);
|
|
1430
|
-
if (!effectiveCache || !existsSync2(chunkAudio)) {
|
|
1431
|
-
await extractAudio(audioPath, chunkAudio, { sampleRate: 16e3, channels: 1, startSeconds: chunk.startSeconds, durationSeconds: chunk.endSeconds - chunk.startSeconds });
|
|
1432
|
-
}
|
|
1433
|
-
}
|
|
1434
|
-
const parts = [{ filePath: chunkAudio }, ...keyframePaths.map((p) => ({ filePath: p })), { text: prompt }];
|
|
1435
|
-
const res = await gemini.generate(parts, {
|
|
1436
|
-
model: llmModel,
|
|
1437
|
-
temperature: 0.2,
|
|
1438
|
-
maxOutputTokens: 65536,
|
|
1439
|
-
thinkingLevel: llmThinkingLevel,
|
|
1440
|
-
systemInstruction: DIARIZATION_SYSTEM,
|
|
1441
|
-
label
|
|
1442
|
-
});
|
|
1443
|
-
inter.writeJSON(`${rawName.replace(/\.txt$/, "")}.meta.json`, { model: res.model, usage: res.usage });
|
|
1444
|
-
if (!res.text.trim()) throw new Error(`Diarization returned empty text${chunked ? ` (chunk ${chunk.index})` : ""}`);
|
|
1445
|
-
return res.text;
|
|
1446
|
-
})
|
|
1447
|
-
);
|
|
1448
|
-
},
|
|
1449
|
-
// Node-specific: save raw→parsed + a running partial transcript (resume/inspect).
|
|
1450
|
-
onChunk: ({ index, chunked, turns: turns2, segmentsSoFar }) => {
|
|
1451
|
-
inter.writeJSON(chunked ? `diarize_chunk_${index}.parsed.json` : "diarize.parsed.json", turns2);
|
|
1452
|
-
inter.writeText(
|
|
1453
|
-
"transcript.partial.srt",
|
|
1454
|
-
formatSrt(segmentsSoFar.map((s2) => ({ start: s2.start, end: s2.end, speaker: s2.speakerLabel, text: s2.text })))
|
|
1747
|
+
if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
|
|
1748
|
+
if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
|
|
1749
|
+
const tsProvider = options.timestampedProvider ?? "assemblyai";
|
|
1750
|
+
const willTimestamp = has(passes, "timestamped") || has(passes, "align");
|
|
1751
|
+
if (willTimestamp) {
|
|
1752
|
+
if (tsProvider === "assemblyai" && !keys.assemblyai) {
|
|
1753
|
+
throw new Error(
|
|
1754
|
+
"ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
|
|
1455
1755
|
);
|
|
1456
1756
|
}
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
let
|
|
1462
|
-
|
|
1463
|
-
|
|
1757
|
+
if (tsProvider === "whisper-groq" && !keys.groq) {
|
|
1758
|
+
throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
let probeInfo = null;
|
|
1762
|
+
const audioPath = `${options.intermediatesDir}/audio.flac`;
|
|
1763
|
+
const probePath = `${options.intermediatesDir}/probe.json`;
|
|
1764
|
+
if (has(passes, "preprocess")) {
|
|
1765
|
+
logger.info("=== preprocess ===");
|
|
1766
|
+
probeInfo = forceAll ? null : readJson(probePath);
|
|
1767
|
+
if (!probeInfo) {
|
|
1768
|
+
probeInfo = await probe(options.input);
|
|
1769
|
+
writeJson(probePath, probeInfo);
|
|
1770
|
+
}
|
|
1771
|
+
if (!existsSync2(audioPath) || forceAll) {
|
|
1772
|
+
logger.info("extracting audio (mono 16kHz FLAC)...");
|
|
1773
|
+
await extractAudio(options.input, audioPath, { format: "flac" });
|
|
1774
|
+
}
|
|
1775
|
+
if (probeInfo.hasVideo) {
|
|
1776
|
+
const kfDir = `${options.intermediatesDir}/keyframes`;
|
|
1777
|
+
if (!existsSync2(kfDir) || forceAll) {
|
|
1778
|
+
logger.info("extracting keyframes...");
|
|
1779
|
+
await extractKeyframes(options.input, kfDir, options.screenshotCount);
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
} else {
|
|
1783
|
+
probeInfo = forceAll ? null : readJson(probePath);
|
|
1784
|
+
}
|
|
1785
|
+
if (!probeInfo) throw new Error("probe info missing (run preprocess)");
|
|
1786
|
+
const duration = probeInfo.duration;
|
|
1787
|
+
let description = null;
|
|
1788
|
+
if (has(passes, "describe")) {
|
|
1789
|
+
const descPath = `${options.intermediatesDir}/description.json`;
|
|
1790
|
+
description = forceAll ? null : readJson(descPath);
|
|
1791
|
+
if (!description) {
|
|
1792
|
+
logger.info("=== describe ===");
|
|
1793
|
+
const client = new GeminiClient(keys.gemini);
|
|
1794
|
+
const samplePath = `${options.intermediatesDir}/sample.flac`;
|
|
1795
|
+
if (!existsSync2(samplePath) || forceAll) {
|
|
1796
|
+
await extractChunk(audioPath, samplePath, 0, Math.min(300, duration), { format: "flac" });
|
|
1797
|
+
}
|
|
1798
|
+
const files = [{ path: samplePath }];
|
|
1799
|
+
const kfDir = `${options.intermediatesDir}/keyframes`;
|
|
1800
|
+
if (existsSync2(kfDir)) {
|
|
1801
|
+
for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
|
|
1802
|
+
const p = `${kfDir}/${f}`;
|
|
1803
|
+
if (existsSync2(p)) files.push({ path: p });
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
description = await describeMeeting(client, models.transcribe, files, basename3(options.input), options.instructions);
|
|
1807
|
+
writeJson(descPath, description);
|
|
1808
|
+
logger.info(`description: ${description.description.slice(0, 120)}...`);
|
|
1809
|
+
}
|
|
1810
|
+
} else {
|
|
1811
|
+
description = forceAll ? null : readJson(`${options.intermediatesDir}/description.json`);
|
|
1812
|
+
}
|
|
1813
|
+
const needChunks = has(passes, "llm-transcribe") || has(passes, "align") || has(passes, "consistency");
|
|
1814
|
+
let chunks = [];
|
|
1815
|
+
if (needChunks) {
|
|
1816
|
+
let silences = [];
|
|
1464
1817
|
try {
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1818
|
+
silences = await detectSilence(audioPath, { noiseDb: -15, minDuration: 0.3 });
|
|
1819
|
+
if (silences.length < 3) silences = await detectSilence(audioPath, { noiseDb: -12, minDuration: 0.25 });
|
|
1820
|
+
} catch {
|
|
1821
|
+
}
|
|
1822
|
+
chunks = planChunks(duration, options.chunkDurationSec, options.chunkOverlapSec);
|
|
1823
|
+
if (silences.length > 3) {
|
|
1824
|
+
chunks = chunks.map((c) => {
|
|
1825
|
+
const snapped = snapToSilence(c.start, silences, Math.min(10, options.chunkOverlapSec / 2));
|
|
1826
|
+
return { ...c, start: snapped, trustedStart: snapped + c.overlapWithPrevious };
|
|
1827
|
+
});
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
const tagWith = (r, chunk) => ({
|
|
1831
|
+
...r,
|
|
1832
|
+
segments: r.segments.map((s) => ({ ...s, chunkIndex: chunk.index, trustedStart: chunk.trustedStart }))
|
|
1833
|
+
});
|
|
1834
|
+
let llmChunkResults = [];
|
|
1835
|
+
if (has(passes, "llm-transcribe")) {
|
|
1836
|
+
logger.info("=== llm-transcribe ===");
|
|
1837
|
+
let runChunks = chunks;
|
|
1838
|
+
if (options.onlyChunk !== void 0) runChunks = chunks.filter((c) => c.index === options.onlyChunk);
|
|
1839
|
+
logger.info(`${runChunks.length} chunks (${options.chunkDurationSec}s, ${options.chunkOverlapSec}s overlap)`);
|
|
1840
|
+
const client = new GeminiClient(keys.gemini);
|
|
1841
|
+
const llmDir = `${options.intermediatesDir}/llm`;
|
|
1842
|
+
mkdirSync(llmDir, { recursive: true });
|
|
1843
|
+
llmChunkResults = await mapPool(runChunks, options.concurrency, async (chunk) => {
|
|
1844
|
+
const parsedPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_parsed.json`;
|
|
1845
|
+
const cached = forceAll ? null : readJson(parsedPath);
|
|
1846
|
+
if (cached && cached.segments.length > 0) {
|
|
1847
|
+
logger.info(`chunk ${chunk.index}: cached (${cached.segments.length} segments)`);
|
|
1848
|
+
return tagWith(cached, chunk);
|
|
1849
|
+
}
|
|
1850
|
+
const chunkPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}.flac`;
|
|
1851
|
+
if (!existsSync2(chunkPath) || forceAll) {
|
|
1852
|
+
await extractChunk(audioPath, chunkPath, chunk.start, chunk.end, { format: "flac" });
|
|
1853
|
+
}
|
|
1854
|
+
let previousTail;
|
|
1855
|
+
if (chunk.index > 0) {
|
|
1856
|
+
const prev = readJson(
|
|
1857
|
+
`${llmDir}/chunk_${String(chunk.index - 1).padStart(2, "0")}_parsed.json`
|
|
1858
|
+
);
|
|
1859
|
+
if (prev && prev.segments.length) {
|
|
1860
|
+
previousTail = prev.segments.slice(-6).map((s) => `${s.speaker}: ${s.text}`).join("\n");
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
logger.info(`chunk ${chunk.index}: transcribing [${chunk.start.toFixed(0)}-${chunk.end.toFixed(0)}]s...`);
|
|
1864
|
+
const result2 = await transcribeChunk(
|
|
1865
|
+
client,
|
|
1866
|
+
models.transcribe,
|
|
1867
|
+
chunkPath,
|
|
1868
|
+
chunk.start,
|
|
1869
|
+
{
|
|
1870
|
+
index: chunk.index + 1,
|
|
1871
|
+
total: runChunks.length,
|
|
1872
|
+
description: description?.description,
|
|
1873
|
+
roster: description?.roster,
|
|
1874
|
+
previousTail,
|
|
1875
|
+
instructions: options.instructions
|
|
1876
|
+
},
|
|
1877
|
+
{ chunkDurationSec: chunk.end - chunk.start, validationRetries: 1 }
|
|
1878
|
+
);
|
|
1879
|
+
writeJson(parsedPath, result2);
|
|
1880
|
+
writeFileSync(`${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`, result2.raw);
|
|
1881
|
+
return tagWith(result2, chunk);
|
|
1882
|
+
});
|
|
1883
|
+
const errored = llmChunkResults.filter((r) => r.error);
|
|
1884
|
+
const producedSegments = llmChunkResults.reduce((n, r) => n + r.segments.length, 0);
|
|
1885
|
+
if (llmChunkResults.length > 0 && producedSegments === 0 && errored.length === llmChunkResults.length) {
|
|
1886
|
+
throw new Error(
|
|
1887
|
+
`LLM transcription failed for all ${llmChunkResults.length} chunk(s) with model "${models.transcribe}". First error: ${errored[0].error}`
|
|
1470
1888
|
);
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1889
|
+
}
|
|
1890
|
+
} else {
|
|
1891
|
+
const llmDir = `${options.intermediatesDir}/llm`;
|
|
1892
|
+
if (!forceAll && existsSync2(llmDir)) {
|
|
1893
|
+
const files = (await import("fs/promises").then((m) => m.readdir(llmDir))).filter((f) => f.endsWith("_parsed.json")).sort();
|
|
1894
|
+
llmChunkResults = files.map((f, i) => {
|
|
1895
|
+
const r = readJson(`${llmDir}/${f}`);
|
|
1896
|
+
return r && chunks[i] ? tagWith(r, chunks[i]) : r;
|
|
1897
|
+
}).filter(Boolean);
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
let allLlmSegments = llmChunkResults.flatMap((r) => r.segments);
|
|
1901
|
+
const beforePart = allLlmSegments.length;
|
|
1902
|
+
allLlmSegments = partitionByOwnership(allLlmSegments);
|
|
1903
|
+
if (beforePart !== allLlmSegments.length) {
|
|
1904
|
+
logger.info(
|
|
1905
|
+
`ownership-partition: ${beforePart} -> ${allLlmSegments.length} (dropped ${beforePart - allLlmSegments.length} overlap duplicates)`
|
|
1906
|
+
);
|
|
1907
|
+
}
|
|
1908
|
+
logger.info(`total LLM segments: ${allLlmSegments.length}`);
|
|
1909
|
+
let asrResult = null;
|
|
1910
|
+
if (has(passes, "timestamped") || has(passes, "align")) {
|
|
1911
|
+
const provider = options.timestampedProvider ?? "assemblyai";
|
|
1912
|
+
if (provider === "whisper-groq") {
|
|
1913
|
+
logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
|
|
1914
|
+
if (!keys.groq) throw new Error("GROQ_API_KEY is required for whisper-groq");
|
|
1915
|
+
const mp3Path = `${options.intermediatesDir}/audio.mp3`;
|
|
1916
|
+
if (!existsSync2(mp3Path) || options.force) {
|
|
1917
|
+
await extractAudio(options.input, mp3Path, { format: "mp3", bitrate: "64k" });
|
|
1918
|
+
}
|
|
1919
|
+
const { readFile: readFile2 } = await import("fs/promises");
|
|
1920
|
+
const buf = await readFile2(mp3Path);
|
|
1921
|
+
const groq = new WhisperGroqClient(keys.groq);
|
|
1922
|
+
asrResult = await groq.transcribe(buf);
|
|
1923
|
+
writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
|
|
1924
|
+
} else {
|
|
1925
|
+
logger.info("=== timestamped (AssemblyAI) ===");
|
|
1926
|
+
if (!keys.assemblyai) throw new Error("ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)");
|
|
1927
|
+
const aai = new AssemblyAIProvider({ apiKey: keys.assemblyai, cacheDir: `${options.intermediatesDir}/assemblyai` });
|
|
1928
|
+
asrResult = await aai.transcribe(audioPath);
|
|
1929
|
+
writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
|
|
1930
|
+
}
|
|
1931
|
+
} else {
|
|
1932
|
+
asrResult = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
|
|
1933
|
+
}
|
|
1934
|
+
let aligned = [];
|
|
1935
|
+
if (has(passes, "align") && asrResult) {
|
|
1936
|
+
logger.info("=== align ===");
|
|
1937
|
+
aligned = alignSegments(allLlmSegments, asrResult.words, { timeMarginSec: 30 });
|
|
1938
|
+
writeJson(`${options.intermediatesDir}/aligned.json`, aligned);
|
|
1939
|
+
} else {
|
|
1940
|
+
aligned = (forceAll ? null : readJson(`${options.intermediatesDir}/aligned.json`)) ?? [];
|
|
1941
|
+
}
|
|
1942
|
+
const alignedOk = aligned.filter((a) => a.timingSource !== "coarse").length;
|
|
1943
|
+
logger.info(`aligned: ${alignedOk}/${aligned.length} with ASR timing`);
|
|
1944
|
+
if (asrResult && (has(passes, "align") || has(passes, "consistency"))) {
|
|
1945
|
+
const before = aligned.length;
|
|
1946
|
+
aligned = fillAsrGaps(aligned, asrResult.words, asrResult.utterances);
|
|
1947
|
+
const added = aligned.length - before;
|
|
1948
|
+
if (added) logger.info(`gap-filled ${added} ASR fallback segment(s)`);
|
|
1949
|
+
}
|
|
1950
|
+
let segments = aligned;
|
|
1951
|
+
let speakers = [];
|
|
1952
|
+
if (has(passes, "consistency") && asrResult) {
|
|
1953
|
+
logger.info("=== consistency ===");
|
|
1954
|
+
const cons = assignGlobalSpeakers(aligned, asrResult.utterances, {
|
|
1955
|
+
hasDiarization: asrResult.hasDiarization ?? true
|
|
1956
|
+
});
|
|
1957
|
+
segments = cons.segments;
|
|
1958
|
+
speakers = cons.speakers;
|
|
1959
|
+
writeJson(`${options.intermediatesDir}/consistent.json`, { segments, speakers });
|
|
1960
|
+
} else {
|
|
1961
|
+
const c = forceAll ? null : readJson(
|
|
1962
|
+
`${options.intermediatesDir}/consistent.json`
|
|
1963
|
+
);
|
|
1964
|
+
if (c) {
|
|
1965
|
+
segments = c.segments;
|
|
1966
|
+
speakers = c.speakers;
|
|
1475
1967
|
}
|
|
1476
1968
|
}
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1969
|
+
if (options.diarizationLevel >= 3 && has(passes, "identify") && keys.deepseek && description) {
|
|
1970
|
+
logger.info("=== identify (DeepSeek) ===");
|
|
1971
|
+
const dsClient = OpenAICompatClient.fromProvider("deepseek", keys.deepseek, models.reasoner);
|
|
1972
|
+
const id = await identifySpeakers(
|
|
1973
|
+
dsClient,
|
|
1974
|
+
models.reasoner,
|
|
1975
|
+
segments.map((s) => ({ speaker: s.speaker, text: s.text })),
|
|
1976
|
+
speakers,
|
|
1977
|
+
description.roster,
|
|
1978
|
+
options.knownSpeakers
|
|
1979
|
+
);
|
|
1980
|
+
logger.info(`identified ${Object.keys(id.nameMap).length} speakers: ${JSON.stringify(id.nameMap)}`);
|
|
1981
|
+
writeJson(`${options.intermediatesDir}/identified.json`, id);
|
|
1982
|
+
segments = segments.map(
|
|
1983
|
+
(s) => id.nameMap[s.speaker] ? { ...s, speakerName: id.nameMap[s.speaker] } : s
|
|
1984
|
+
);
|
|
1985
|
+
speakers = speakers.map(
|
|
1986
|
+
(sp) => id.nameMap[sp.id] ? { ...sp, name: id.nameMap[sp.id] } : sp
|
|
1987
|
+
);
|
|
1988
|
+
}
|
|
1989
|
+
let finalSegments = [];
|
|
1990
|
+
if (has(passes, "finalize")) {
|
|
1991
|
+
logger.info("=== finalize ===");
|
|
1992
|
+
finalSegments = finalizeSegments(segments);
|
|
1993
|
+
writeJson(`${options.intermediatesDir}/final.json`, finalSegments);
|
|
1994
|
+
} else {
|
|
1995
|
+
finalSegments = (forceAll ? null : readJson(`${options.intermediatesDir}/final.json`)) ?? [];
|
|
1996
|
+
}
|
|
1997
|
+
logger.info(`final segments: ${finalSegments.length}`);
|
|
1998
|
+
const metadata = {
|
|
1999
|
+
sourceFile: options.input,
|
|
2000
|
+
duration,
|
|
2001
|
+
processedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2002
|
+
models: {
|
|
2003
|
+
transcribe: models.transcribe,
|
|
2004
|
+
timestamped: tsProvider === "whisper-groq" ? "whisper-large-v3 (groq)" : tsProvider === "none" ? "none" : "assemblyai-universal-2"
|
|
1487
2005
|
},
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
const
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
2006
|
+
passes
|
|
2007
|
+
};
|
|
2008
|
+
const result = { segments: finalSegments, speakers, metadata };
|
|
2009
|
+
for (const fmt of options.formats) {
|
|
2010
|
+
const base = basename3(options.input, ext(options.input));
|
|
2011
|
+
if (fmt === "srt") writeFileSync(`${options.outputDir}/${base}.srt`, formatSrt(result, { title: base }));
|
|
2012
|
+
if (fmt === "md") writeFileSync(`${options.outputDir}/${base}.md`, formatMarkdown(result, { title: base }));
|
|
2013
|
+
if (fmt === "json") writeFileSync(`${options.outputDir}/${base}.json`, formatJson(result));
|
|
2014
|
+
}
|
|
2015
|
+
logger.info(`outputs written to ${options.outputDir}`);
|
|
2016
|
+
return result;
|
|
2017
|
+
}
|
|
2018
|
+
function ext(p) {
|
|
2019
|
+
const i = p.lastIndexOf(".");
|
|
2020
|
+
return i >= 0 ? p.slice(i) : "";
|
|
2021
|
+
}
|
|
2022
|
+
|
|
2023
|
+
// src/utils/srt.ts
|
|
2024
|
+
function parseSrt(content) {
|
|
2025
|
+
const clean = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
|
|
2026
|
+
const blocks = clean.split(/\r?\n\r?\n/).filter((b) => b.trim().length > 0);
|
|
2027
|
+
const entries = [];
|
|
2028
|
+
for (const block of blocks) {
|
|
2029
|
+
const lines = block.split(/\r?\n/);
|
|
2030
|
+
if (lines.length < 2) continue;
|
|
2031
|
+
let idLine = 0;
|
|
2032
|
+
let id = parseInt(lines[0].trim(), 10);
|
|
2033
|
+
if (isNaN(id)) {
|
|
2034
|
+
id = entries.length + 1;
|
|
2035
|
+
idLine = -1;
|
|
2036
|
+
}
|
|
2037
|
+
const timingLine = lines[idLine + 1].trim();
|
|
2038
|
+
const timing = parseSrtTiming(timingLine);
|
|
2039
|
+
if (!timing) continue;
|
|
2040
|
+
const text = lines.slice(idLine + 2).join("\n").trim();
|
|
2041
|
+
entries.push({
|
|
2042
|
+
id,
|
|
2043
|
+
start: timing.start,
|
|
2044
|
+
end: timing.end,
|
|
2045
|
+
text,
|
|
2046
|
+
timingString: timingLine
|
|
2047
|
+
});
|
|
2048
|
+
}
|
|
2049
|
+
entries.sort((a, b) => a.start - b.start);
|
|
2050
|
+
return entries;
|
|
1500
2051
|
}
|
|
1501
2052
|
export {
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
buildAsrHint,
|
|
1508
|
-
buildDiarizationPrompt,
|
|
1509
|
-
buildSegmentsFromTokens,
|
|
1510
|
-
buildSpeakers,
|
|
1511
|
-
fillTokenTimes,
|
|
2053
|
+
alignSegments,
|
|
2054
|
+
assignGlobalSpeakers,
|
|
2055
|
+
finalizeSegments,
|
|
2056
|
+
formatJson,
|
|
2057
|
+
formatMarkdown,
|
|
1512
2058
|
formatSrt,
|
|
1513
|
-
|
|
1514
|
-
isProvisional,
|
|
1515
|
-
normalizeToken,
|
|
1516
|
-
parseDiarizedText,
|
|
2059
|
+
identifySpeakers,
|
|
1517
2060
|
parseSrt,
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
secondsToSrtTime,
|
|
1521
|
-
slugLabel,
|
|
1522
|
-
splitSpeakerPrefix,
|
|
1523
|
-
srtCueText,
|
|
1524
|
-
srtTimeToSeconds,
|
|
1525
|
-
toJSON,
|
|
1526
|
-
toMarkdown,
|
|
1527
|
-
toSRT,
|
|
1528
|
-
toText,
|
|
1529
|
-
tokenize,
|
|
1530
|
-
transcribe,
|
|
1531
|
-
transcribeWithAssemblyAI
|
|
2061
|
+
planChunks,
|
|
2062
|
+
transcribe
|
|
1532
2063
|
};
|
|
1533
2064
|
//# sourceMappingURL=index.js.map
|