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