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/dist/index.js CHANGED
@@ -1,802 +1,380 @@
1
- // src/core/time.ts
2
- function secondsToSrtTime(seconds) {
3
- const s2 = Number.isFinite(seconds) ? Math.max(0, seconds) : 0;
4
- const hours = Math.floor(s2 / 3600);
5
- const minutes = Math.floor(s2 % 3600 / 60);
6
- const secs = Math.floor(s2 % 60);
7
- const ms = Math.round((s2 - Math.floor(s2)) * 1e3);
8
- let carrySecs = secs;
9
- let carryMin = minutes;
10
- let carryHrs = hours;
11
- let outMs = ms;
12
- if (outMs === 1e3) {
13
- outMs = 0;
14
- carrySecs += 1;
15
- }
16
- if (carrySecs === 60) {
17
- carrySecs = 0;
18
- carryMin += 1;
19
- }
20
- if (carryMin === 60) {
21
- carryMin = 0;
22
- carryHrs += 1;
23
- }
24
- return `${String(carryHrs).padStart(2, "0")}:${String(carryMin).padStart(2, "0")}:${String(carrySecs).padStart(2, "0")},${String(outMs).padStart(3, "0")}`;
25
- }
26
- function srtTimeToSeconds(timestamp) {
27
- const t = timestamp.trim().replace(",", ".");
28
- const [hms = "", frac] = t.split(".");
29
- const parts = hms.split(":").map((p) => parseInt(p, 10));
30
- let hours = 0;
31
- let minutes = 0;
32
- let secs = 0;
33
- if (parts.length === 3) {
34
- [hours, minutes, secs] = parts;
35
- } else if (parts.length === 2) {
36
- [minutes, secs] = parts;
37
- } else if (parts.length === 1) {
38
- [secs] = parts;
39
- }
40
- const fracSecs = frac ? parseFloat(`0.${frac}`) : 0;
41
- return hours * 3600 + minutes * 60 + secs + fracSecs;
42
- }
43
- function relTimeToSeconds(timeStr) {
44
- const parts = timeStr.trim().split(":");
45
- if (parts.length < 2 || parts.length > 3) return null;
46
- const nums = parts.map((p) => parseInt(p, 10));
47
- if (nums.some((n) => Number.isNaN(n))) return null;
48
- if (nums.length === 2) {
49
- const [m2, s3] = nums;
50
- return m2 * 60 + s3;
51
- }
52
- const [h, m, s2] = nums;
53
- return h * 3600 + m * 60 + s2;
54
- }
55
- function secondsToCompact(seconds) {
56
- const s2 = Math.max(0, Math.floor(seconds));
57
- const h = Math.floor(s2 / 3600);
58
- const m = Math.floor(s2 % 3600 / 60);
59
- const sec = s2 % 60;
60
- if (h > 0) {
61
- return `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}`;
62
- }
63
- return `${m}:${String(sec).padStart(2, "0")}`;
64
- }
65
- function formatSrtTiming(start, end) {
66
- return `${secondsToSrtTime(start)} --> ${secondsToSrtTime(end)}`;
67
- }
1
+ // src/core/pipeline.ts
2
+ import { existsSync as existsSync2, mkdirSync, readFileSync, writeFileSync } from "fs";
68
3
 
69
- // src/core/srt.ts
70
- var TIMING_RE = /(\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}|\d{1,2}:\d{2}[,.]\d{1,3})\s*-->\s*(\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}|\d{1,2}:\d{2}[,.]\d{1,3})/;
71
- function splitSpeakerPrefix(text) {
72
- const idx = text.indexOf(":");
73
- if (idx <= 0 || idx > 40) return { body: text };
74
- const prefix = text.slice(0, idx).trim();
75
- const rest = text.slice(idx + 1).trim();
76
- if (!rest) return { body: text };
77
- if (/^\d+$/.test(prefix) || /^\d{1,2}(:\d{2})+$/.test(prefix)) return { body: text };
78
- if (/[.!?]/.test(prefix)) return { body: text };
79
- const wordCount = prefix.split(/\s+/).length;
80
- if (wordCount > 4) return { body: text };
81
- return { speaker: prefix, body: rest };
82
- }
83
- function parseSrt(content) {
84
- const cues = [];
85
- const blocks = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split(/\n\s*\n/);
86
- let autoId = 0;
87
- for (const block of blocks) {
88
- const lines = block.split("\n").filter((l) => l.trim().length > 0);
89
- if (lines.length === 0) continue;
90
- let timingLineIdx = -1;
91
- for (let i = 0; i < lines.length; i++) {
92
- if (TIMING_RE.test(lines[i])) {
93
- timingLineIdx = i;
94
- break;
95
- }
96
- }
97
- if (timingLineIdx === -1) continue;
98
- const m = lines[timingLineIdx].match(TIMING_RE);
99
- if (!m) continue;
100
- const start = srtTimeToSeconds(m[1]);
101
- const end = srtTimeToSeconds(m[2]);
102
- let id = ++autoId;
103
- if (timingLineIdx > 0) {
104
- const maybeId = parseInt(lines[0].trim(), 10);
105
- if (!Number.isNaN(maybeId)) id = maybeId;
106
- }
107
- const text = lines.slice(timingLineIdx + 1).join(" ").trim();
108
- const { speaker, body } = splitSpeakerPrefix(text);
109
- cues.push({ id, start, end, text, speaker, body });
110
- }
111
- return cues;
112
- }
113
- function formatSrt(cues, options = {}) {
114
- const { includeSpeaker = true } = options;
115
- return cues.map((cue, i) => {
116
- const speakerPrefix = includeSpeaker && cue.speaker ? `${cue.speaker}: ` : "";
117
- return `${i + 1}
118
- ${formatSrtTiming(cue.start, cue.end)}
119
- ${speakerPrefix}${cue.text}`;
120
- }).join("\n\n") + "\n";
121
- }
122
-
123
- // src/core/align.ts
124
- function normalizeToken(s2) {
125
- return s2.toLowerCase().replace(/[^a-z0-9]/g, "");
126
- }
127
- function tokenize(text) {
128
- return text.split(/\s+/).filter((t) => t.length > 0);
129
- }
130
- function alignTokens(a, b) {
131
- const n = a.length;
132
- const m = b.length;
133
- const MATCH = 2;
134
- const MISMATCH = -1;
135
- const GAP = -1;
136
- const w = m + 1;
137
- const score = new Int32Array((n + 1) * w);
138
- const back = new Uint8Array((n + 1) * w);
139
- for (let i2 = 1; i2 <= n; i2++) {
140
- score[i2 * w] = i2 * GAP;
141
- back[i2 * w] = 1;
142
- }
143
- for (let j2 = 1; j2 <= m; j2++) {
144
- score[j2] = j2 * GAP;
145
- back[j2] = 2;
146
- }
147
- for (let i2 = 1; i2 <= n; i2++) {
148
- const ai = a[i2 - 1];
149
- const rowOff = i2 * w;
150
- const prevRowOff = (i2 - 1) * w;
151
- for (let j2 = 1; j2 <= m; j2++) {
152
- const isMatch = ai === b[j2 - 1];
153
- const diag = score[prevRowOff + j2 - 1] + (isMatch ? MATCH : MISMATCH);
154
- const up = score[prevRowOff + j2] + GAP;
155
- const left = score[rowOff + j2 - 1] + GAP;
156
- let best = diag;
157
- let dir = 0;
158
- if (up > best) {
159
- best = up;
160
- dir = 1;
161
- }
162
- if (left > best) {
163
- best = left;
164
- dir = 2;
165
- }
166
- score[rowOff + j2] = best;
167
- back[rowOff + j2] = dir;
168
- }
169
- }
170
- const pairs = [];
171
- let i = n;
172
- let j = m;
173
- while (i > 0 || j > 0) {
174
- if (i > 0 && j > 0 && back[i * w + j] === 0) {
175
- pairs.push({ ai: i - 1, bi: j - 1, match: a[i - 1] === b[j - 1] });
176
- i--;
177
- j--;
178
- } else if (i > 0 && (j === 0 || back[i * w + j] === 1)) {
179
- pairs.push({ ai: i - 1, bi: null, match: false });
180
- i--;
181
- } else {
182
- pairs.push({ ai: null, bi: j - 1, match: false });
183
- j--;
184
- }
185
- }
186
- pairs.reverse();
187
- return pairs;
188
- }
189
- function alignLlmToAsr(turns, asrWords) {
190
- const tokens = [];
191
- turns.forEach((turn, turnIndex) => {
192
- for (const surface of tokenize(turn.text)) {
193
- const norm = normalizeToken(surface);
194
- if (!norm) continue;
195
- tokens.push({ surface, norm, turnIndex, start: null, end: null, matched: false });
196
- }
197
- });
198
- const asrNorm = asrWords.map((w) => normalizeToken(w.text));
199
- const pairs = alignTokens(
200
- tokens.map((t) => t.norm),
201
- asrNorm
202
- );
203
- for (const p of pairs) {
204
- if (p.ai === null) continue;
205
- const tok = tokens[p.ai];
206
- if (p.match && p.bi !== null) {
207
- const w = asrWords[p.bi];
208
- tok.start = w.start;
209
- tok.end = w.end;
210
- tok.matched = true;
211
- if (w.speaker) tok.asrSpeaker = w.speaker;
212
- }
213
- }
214
- return tokens;
215
- }
216
- function fillTokenTimes(tokens, totalDuration) {
217
- const n = tokens.length;
218
- if (n === 0) return tokens;
219
- const anchors = [];
220
- for (let i = 0; i < n; i++) if (tokens[i].matched) anchors.push(i);
221
- if (anchors.length === 0) {
222
- for (let i = 0; i < n; i++) {
223
- tokens[i].start = i / n * totalDuration;
224
- tokens[i].end = (i + 1) / n * totalDuration;
225
- }
226
- return tokens;
227
- }
228
- const first = anchors[0];
229
- for (let i = 0; i < first; i++) {
230
- tokens[i].start = tokens[first].start;
231
- tokens[i].end = tokens[first].start;
232
- }
233
- const last = anchors[anchors.length - 1];
234
- for (let i = last + 1; i < n; i++) {
235
- tokens[i].start = tokens[last].end;
236
- tokens[i].end = tokens[last].end;
237
- }
238
- for (let a = 0; a < anchors.length - 1; a++) {
239
- const lo = anchors[a];
240
- const hi = anchors[a + 1];
241
- const t0 = tokens[lo].end ?? tokens[lo].start ?? 0;
242
- const t1 = tokens[hi].start ?? t0;
243
- const gap = hi - lo;
244
- for (let i = lo + 1; i < hi; i++) {
245
- const frac = (i - lo) / gap;
246
- const t = t0 + frac * (t1 - t0);
247
- tokens[i].start = t;
248
- tokens[i].end = t;
249
- }
250
- }
251
- return tokens;
252
- }
253
- var SENTENCE_END = /[.!?…]["')\]]?$/;
254
- function buildSegmentsFromTokens(turns, tokens, options = {}) {
255
- const {
256
- subSegment = false,
257
- maxChars = 90,
258
- maxDuration = 7,
259
- gapSplit = 1,
260
- minChars = 24
261
- } = options;
262
- const byTurn = /* @__PURE__ */ new Map();
263
- for (const t of tokens) {
264
- const arr = byTurn.get(t.turnIndex);
265
- if (arr) arr.push(t);
266
- else byTurn.set(t.turnIndex, [t]);
267
- }
268
- const segments = [];
269
- for (let turnIndex = 0; turnIndex < turns.length; turnIndex++) {
270
- const toks = byTurn.get(turnIndex);
271
- if (!toks || toks.length === 0) continue;
272
- if (!subSegment) {
273
- segments.push(makeSegment(turnIndex, toks));
274
- continue;
275
- }
276
- let cur = [];
277
- let curChars = 0;
278
- const flush = () => {
279
- if (cur.length > 0) {
280
- segments.push(makeSegment(turnIndex, cur));
281
- cur = [];
282
- curChars = 0;
283
- }
284
- };
285
- for (let i = 0; i < toks.length; i++) {
286
- const tok = toks[i];
287
- cur.push(tok);
288
- curChars += tok.surface.length + 1;
289
- const next = toks[i + 1];
290
- const curStart = cur[0].start ?? 0;
291
- const curEnd = tok.end ?? curStart;
292
- const dur = curEnd - curStart;
293
- const bothMatched = tok.matched && (next?.matched ?? false);
294
- const gapToNext = bothMatched && next && next.start !== null && tok.end !== null ? next.start - tok.end : 0;
295
- const sentenceBreak = SENTENCE_END.test(tok.surface) && curChars >= minChars;
296
- const tooLong = curChars >= maxChars || dur >= maxDuration;
297
- const bigGap = gapToNext >= gapSplit && curChars >= minChars;
298
- if (sentenceBreak || tooLong || bigGap) flush();
299
- }
300
- flush();
301
- }
302
- return segments;
303
- }
304
- function asrSpeakerByLabel(tokens, labelByTurn) {
305
- const out = {};
306
- for (const tok of tokens) {
307
- if (!tok.matched || !tok.asrSpeaker) continue;
308
- const label = labelByTurn[tok.turnIndex];
309
- if (label === void 0) continue;
310
- out[label] ??= {};
311
- out[label][tok.asrSpeaker] = (out[label][tok.asrSpeaker] ?? 0) + 1;
312
- }
313
- return out;
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 makeSegment(turnIndex, toks) {
316
- const matched = toks.filter((t) => t.matched);
317
- const starts = toks.map((t) => t.start).filter((x) => x !== null);
318
- const ends = toks.map((t) => t.end).filter((x) => x !== null);
319
- const start = starts.length ? Math.min(...starts) : 0;
320
- const end = ends.length ? Math.max(...ends) : start;
40
+ function resolveOptions(opts) {
321
41
  return {
322
- turnIndex,
323
- start,
324
- end: Math.max(end, start),
325
- text: toks.map((t) => t.surface).join(" "),
326
- matchRatio: toks.length ? matched.length / toks.length : 0,
327
- tokenCount: toks.length,
328
- matchedTokens: matched.length
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
- // src/core/format.ts
333
- function speakerLabelMap(transcript) {
334
- const m = /* @__PURE__ */ new Map();
335
- for (const sp of transcript.speakers) m.set(sp.id, sp.label);
336
- return m;
337
- }
338
- function srtCueText(s2) {
339
- return s2.replace(/\r\n?/g, "\n").replace(/\n[ \t]*\n+/g, "\n").trim() || " ";
340
- }
341
- function toSRT(transcript, options = {}) {
342
- const { includeSpeaker = true, includeTone = false } = options;
343
- const labels = speakerLabelMap(transcript);
344
- const blocks = transcript.segments.map((seg, i) => {
345
- const label = labels.get(seg.speakerId) ?? seg.speakerId;
346
- const prefix = includeSpeaker ? `${label}: ` : "";
347
- const tone = includeTone && seg.tone ? `(${seg.tone}) ` : "";
348
- const body = srtCueText(`${prefix}${tone}${seg.text}`);
349
- return `${i + 1}
350
- ${formatSrtTiming(seg.start, Math.max(seg.start, seg.end))}
351
- ${body}`;
352
- });
353
- return blocks.join("\n\n") + "\n";
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 toMarkdown(transcript, options = {}) {
356
- const { includeTimestamps = true, includeTone = true, title = "Transcript", mergeBySpeaker = true } = options;
357
- const labels = speakerLabelMap(transcript);
358
- const out = [];
359
- out.push(`# ${title}
360
- `);
361
- const m = transcript.metadata;
362
- out.push(`*Duration: ${secondsToCompact(m.durationSeconds)} \xB7 ${transcript.segments.length} segments \xB7 ${transcript.speakers.length} speakers*`);
363
- if (m.asrProvider || m.llmModel) {
364
- out.push(`*ASR: ${m.asrProvider ?? "\u2014"} \xB7 LLM: ${m.llmModel ?? "\u2014"}*`);
365
- }
366
- out.push("");
367
- out.push(`## Speakers
368
- `);
369
- for (const sp of transcript.speakers) {
370
- const named = sp.named ? "" : " *(unidentified)*";
371
- const desc = sp.description ? ` \u2014 ${sp.description}` : "";
372
- out.push(`- **${sp.label}**${named}${desc}`);
373
- }
374
- out.push(`
375
- ## Transcript
376
- `);
377
- const groups = mergeBySpeaker ? groupBySpeaker(transcript.segments) : transcript.segments.map((s2) => [s2]);
378
- for (const group of groups) {
379
- const first = group[0];
380
- const label = labels.get(first.speakerId) ?? first.speakerId;
381
- const ts = includeTimestamps ? `\`[${secondsToCompact(first.start)}]\` ` : "";
382
- const text = group.map((s2) => includeTone && s2.tone ? `*(${s2.tone})* ${s2.text}` : s2.text).join(" ");
383
- out.push(`${ts}**${label}:** ${text}
384
- `);
385
- }
386
- return out.join("\n");
82
+ function extOf(p) {
83
+ const i = p.lastIndexOf(".");
84
+ return i >= 0 ? p.slice(i) : "";
387
85
  }
388
- function groupBySpeaker(segments) {
389
- const groups = [];
390
- for (const seg of segments) {
391
- const last = groups[groups.length - 1];
392
- if (last && last[0].speakerId === seg.speakerId) last.push(seg);
393
- else groups.push([seg]);
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 groups;
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 toText(transcript, options = {}) {
401
- const { includeTimestamps = true } = options;
402
- const labels = speakerLabelMap(transcript);
403
- return groupBySpeaker(transcript.segments).map((group) => {
404
- const first = group[0];
405
- const label = labels.get(first.speakerId) ?? first.speakerId;
406
- const ts = includeTimestamps ? `[${secondsToCompact(first.start)}] ` : "";
407
- return `${ts}${label}: ${group.map((s2) => s2.text).join(" ")}`;
408
- }).join("\n\n") + "\n";
409
- }
410
-
411
- // src/core/speakers.ts
412
- var PROVISIONAL_RE = /^(speaker|spkr|unknown|unidentified)\b/i;
413
- function slugLabel(label) {
414
- return label.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "speaker";
415
- }
416
- function isProvisional(label) {
417
- return PROVISIONAL_RE.test(label.trim());
418
- }
419
- function buildSpeakers(rawLabels, options = {}) {
420
- const { knownSpeakers = {}, resolvedNames = {}, descriptions = {} } = options;
421
- const labelToId = /* @__PURE__ */ new Map();
422
- const byId = /* @__PURE__ */ new Map();
423
- const resolveCanonical = (raw) => {
424
- if (knownSpeakers[raw]) return knownSpeakers[raw];
425
- if (resolvedNames[raw]) {
426
- const resolvedName = resolvedNames[raw];
427
- return knownSpeakers[resolvedName] ?? resolvedName;
428
- }
429
- return raw;
430
- };
431
- for (const raw of rawLabels) {
432
- if (labelToId.has(raw)) continue;
433
- const canonical = resolveCanonical(raw);
434
- const id = slugLabel(canonical);
435
- labelToId.set(raw, id);
436
- if (!byId.has(id)) {
437
- byId.set(id, {
438
- id,
439
- label: canonical,
440
- named: !isProvisional(canonical),
441
- description: descriptions[canonical]
442
- });
443
- } else if (descriptions[canonical] && !byId.get(id).description) {
444
- byId.get(id).description = descriptions[canonical];
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 { speakers: [...byId.values()], labelToId };
121
+ return chunks;
448
122
  }
449
123
 
450
- // src/core/parse-diarized.ts
451
- var LINE_RE = /^\s*(?:\[(?<ts>\d{1,2}:\d{2}(?::\d{2})?)\]\s*)?(?<speaker>[^:\[\]]{1,40}?):\s*(?:\((?<tone>[^)]{1,60})\)\s*)?(?<text>.*)$/;
452
- function parseDiarizedText(raw) {
453
- const lines = raw.replace(/\r\n/g, "\n").split("\n");
454
- const out = [];
455
- for (const line of lines) {
456
- const trimmed = line.trim();
457
- if (!trimmed) continue;
458
- if (/^```/.test(trimmed)) continue;
459
- const m = trimmed.match(LINE_RE);
460
- if (m && m.groups && m.groups["text"] !== void 0) {
461
- const speaker = m.groups["speaker"].trim();
462
- const tsStr = m.groups["ts"];
463
- const tone = m.groups["tone"]?.trim();
464
- const text = m.groups["text"].trim();
465
- if (speaker.split(/\s+/).length > 6) {
466
- appendContinuation(out, trimmed);
467
- continue;
468
- }
469
- const approxStart = tsStr ? relTimeToSeconds(tsStr) ?? void 0 : void 0;
470
- out.push({
471
- speaker,
472
- text,
473
- tone: tone || void 0,
474
- approxStart
475
- });
476
- } else {
477
- appendContinuation(out, trimmed);
478
- }
479
- }
480
- return out;
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 appendContinuation(out, text) {
483
- const last = out[out.length - 1];
484
- if (last) last.text = `${last.text} ${text}`.trim();
485
- }
486
-
487
- // src/core/prompts.ts
488
- var DIARIZATION_SYSTEM = `You are an expert meeting transcriptionist and diarizer. You transcribe verbatim (including filler words and false starts), attribute every utterance to the correct speaker, and you are careful and literal. You never invent content you cannot hear.`;
489
- function buildDiarizationPrompt(input) {
490
- const { instructions, asrHint, chunk, previousTail } = input;
491
- const parts = [];
492
- if (chunk && chunk.total > 1) {
493
- parts.push(
494
- `This is part ${chunk.index + 1} of ${chunk.total} of a longer recording. This part starts at ${secondsToCompact(chunk.startSeconds)} in the full recording. Use timestamps RELATIVE to the start of THIS clip ([mm:ss] from 0:00).`
495
- );
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
- parts.push(`This is a recorded talk/meeting. Produce a complete diarized transcript.`);
498
- }
499
- if (instructions) {
500
- parts.push(`
501
- IMPORTANT USER INSTRUCTIONS (follow these for speaker labeling and focus):
502
- ${instructions}`);
503
- }
504
- if (asrHint) {
505
- parts.push(
506
- `
507
- A baseline speech-to-text system produced the rough diarization below. Its TIMING is reliable but its SPEAKER LABELS are often wrong (it splits one person into several, merges different people, and misses short interjections). Use it only as a hint \u2014 trust what you HEAR for who is speaking:
508
-
509
- ${asrHint}`
510
- );
511
- }
512
- if (previousTail) {
513
- parts.push(
514
- `
515
- For speaker continuity only, the previous part ended with the lines below. The start of THIS clip overlaps the previous part \u2014 transcribe EVERYTHING you hear in THIS clip in full (from 0:00), including any overlap; do not skip the beginning:
516
- ...${previousTail}`
517
- );
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
- function buildAsrHint(asr, maxUtterances = 200, maxCharsPerUtterance = 160) {
533
- const lines = [];
534
- const utts = asr.utterances.slice(0, maxUtterances);
535
- for (const u of utts) {
536
- const text = u.text.length > maxCharsPerUtterance ? u.text.slice(0, maxCharsPerUtterance) + "\u2026" : u.text;
537
- lines.push(`[${secondsToCompact(u.start)}] ${u.speaker}: ${text}`);
538
- }
539
- if (asr.utterances.length > maxUtterances) lines.push(`\u2026 (${asr.utterances.length - maxUtterances} more)`);
540
- return lines.join("\n");
541
- }
542
-
543
- // src/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/media/ffmpeg.ts
148
+ // src/audio/ffmpeg.ts
548
149
  import { spawn } from "child_process";
549
150
  import { mkdir } from "fs/promises";
550
- import { dirname, join } from "path";
551
- function run(cmd, args) {
552
- return new Promise((resolve, reject) => {
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) => resolve({ code: code ?? -1, stdout, stderr }));
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 ensureDir(filePath) {
563
- await mkdir(dirname(filePath), { recursive: true });
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 probeMedia(input) {
566
- const { code, stdout, stderr } = await run("ffprobe", [
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 video = streams.find((s2) => s2["codec_type"] === "video");
581
- const audio = streams.find((s2) => s2["codec_type"] === "audio");
582
- const info = {
583
- durationSeconds: parseFloat(data.format?.duration ?? "0") || 0,
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
- sizeBytes: data.format?.size ? parseInt(data.format.size, 10) : void 0
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
- if (video) {
589
- info.width = Number(video["width"]) || void 0;
590
- info.height = Number(video["height"]) || void 0;
591
- info.videoCodec = video["codec_name"] || void 0;
592
- }
593
- if (audio) {
594
- info.audioCodec = audio["codec_name"] || void 0;
595
- info.sampleRate = Number(audio["sample_rate"]) || void 0;
596
- info.channels = Number(audio["channels"]) || void 0;
597
- }
598
- return info;
599
- }
600
- async function extractAudio(input, output, options = {}) {
601
- const {
602
- sampleRate = 16e3,
603
- channels = 1,
604
- startSeconds,
605
- durationSeconds,
606
- bitrate = "64k",
607
- overwrite = true
608
- } = options;
609
- await ensureDir(output);
610
- const args = [];
611
- if (overwrite) args.push("-y");
612
- if (startSeconds !== void 0) args.push("-ss", String(startSeconds));
613
- args.push("-i", input);
614
- if (durationSeconds !== void 0) args.push("-t", String(durationSeconds));
615
- args.push("-vn", "-ac", String(channels), "-ar", String(sampleRate));
616
- const ext = output.slice(output.lastIndexOf(".") + 1).toLowerCase();
617
- if (ext === "mp3") {
618
- args.push("-c:a", "libmp3lame", "-b:a", bitrate);
619
- } else if (ext === "opus") {
620
- args.push("-c:a", "libopus", "-b:a", bitrate);
621
- } else if (ext === "wav") {
622
- args.push("-c:a", "pcm_s16le");
623
- } else if (ext === "flac") {
624
- args.push("-c:a", "flac");
625
- } else if (ext === "m4a" || ext === "aac") {
626
- args.push("-c:a", "aac", "-b:a", bitrate);
627
- }
628
- args.push(output);
629
- const { code, stderr } = await run("ffmpeg", args);
630
- if (code !== 0) throw new Error(`ffmpeg extractAudio failed (${code}): ${stderr}`);
631
- return output;
632
- }
633
- async function extractKeyframes(input, outputDir, options = {}) {
634
- const { atSeconds, count, maxSize = 768, durationSeconds, overwrite = true } = options;
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
- let times;
637
- if (atSeconds && atSeconds.length > 0) {
638
- times = atSeconds;
639
- } else if (count && durationSeconds) {
640
- times = Array.from(
641
- { length: count },
642
- (_, i) => Math.max(0.5, (i + 0.5) / count * durationSeconds)
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
- throw new Error("extractKeyframes: provide atSeconds, or count + durationSeconds");
646
- }
647
- const paths = [];
648
- await Promise.all(
649
- times.map(async (t, i) => {
650
- const out = join(outputDir, `frame_${String(i).padStart(3, "0")}_${Math.round(t)}s.jpg`);
651
- const args = [];
652
- if (overwrite) args.push("-y");
653
- args.push(
654
- "-ss",
655
- String(t),
656
- "-i",
657
- input,
658
- "-frames:v",
659
- "1",
660
- "-vf",
661
- `scale='min(${maxSize},iw)':-2`,
662
- "-q:v",
663
- "3",
664
- out
665
- );
666
- const { code, stderr } = await run("ffmpeg", args);
667
- if (code !== 0) throw new Error(`ffmpeg keyframe @${t}s failed: ${stderr}`);
668
- paths[i] = out;
669
- })
670
- );
671
- return paths;
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
- // src/providers/assemblyai.ts
675
- import { AssemblyAI } from "assemblyai";
676
- var s = (ms) => (ms ?? 0) / 1e3;
677
- async function transcribeWithAssemblyAI(audioPath, options = {}) {
678
- const apiKey = options.apiKey ?? process.env.ASSEMBLYAI_API_KEY;
679
- if (!apiKey) throw new Error("Missing ASSEMBLYAI_API_KEY");
680
- const client = new AssemblyAI({ apiKey });
681
- const params = {
682
- audio: audioPath,
683
- speaker_labels: options.speakerLabels !== false
684
- };
685
- if (options.speakersExpected) params["speakers_expected"] = options.speakersExpected;
686
- if (options.speechModel) params["speech_model"] = options.speechModel;
687
- if (options.languageCode) params["language_code"] = options.languageCode;
688
- const t = await client.transcripts.transcribe(params);
689
- if (t.status === "error") throw new Error(`AssemblyAI failed: ${t.error}`);
690
- const words = (t.words ?? []).map((w) => ({
691
- text: w.text,
692
- start: s(w.start),
693
- end: s(w.end),
694
- confidence: w.confidence,
695
- speaker: w.speaker ?? void 0
696
- }));
697
- const utterances = (t.utterances ?? []).map((u) => ({
698
- text: u.text,
699
- start: s(u.start),
700
- end: s(u.end),
701
- speaker: u.speaker ?? "?",
702
- confidence: u.confidence,
703
- words: u.words?.map((w) => ({
704
- text: w.text,
705
- start: s(w.start),
706
- end: s(w.end),
707
- confidence: w.confidence,
708
- speaker: w.speaker ?? void 0
709
- }))
710
- }));
711
- const speakerSet = /* @__PURE__ */ new Set();
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, extname } from "path";
353
+ import { basename as basename2 } from "path";
730
354
 
731
- // src/core/retry.ts
732
- function isRetryableError(err) {
733
- const e = err;
734
- const code = e?.status ?? e?.code;
735
- if (typeof code === "number" && [408, 429, 500, 502, 503, 504].includes(code)) return true;
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
- async function withRetry(fn, opts = {}) {
742
- const retries = opts.retries ?? 4;
743
- const base = opts.baseDelayMs ?? 1e3;
744
- let lastErr;
745
- for (let attempt = 0; attempt <= retries; attempt++) {
746
- try {
747
- return await fn();
748
- } catch (err) {
749
- lastErr = err;
750
- if (attempt === retries || !isRetryableError(err)) throw err;
751
- const delayMs = Math.min(3e4, base * 2 ** attempt) + Math.floor(Math.random() * 250);
752
- opts.onRetry?.({ attempt: attempt + 1, retries, delayMs, error: err });
753
- await new Promise((r) => setTimeout(r, delayMs));
754
- }
755
- }
756
- throw lastErr;
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
- ".flac": "audio/flac",
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 mimeForPath(path) {
809
- const ext = extname(path).toLowerCase();
810
- const m = MIME_BY_EXT[ext];
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
- const key = apiKey ?? process.env.GEMINI_API_KEY ?? process.env.GOOGLE_API_KEY;
829
- if (!key) throw new Error("Missing GEMINI_API_KEY / GOOGLE_API_KEY");
830
- this.ai = new GoogleGenAI({ apiKey: key });
831
- }
832
- /** Upload a local file via the Files API and wait until it's ACTIVE. */
833
- async uploadFile(filePath, mimeType) {
834
- const mt = mimeType ?? mimeForPath(filePath);
835
- const uploaded = await retry(
836
- () => this.ai.files.upload({ file: filePath, config: { mimeType: mt, displayName: basename(filePath) } }),
837
- `upload ${basename(filePath)}`
838
- );
839
- let file = uploaded;
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") throw new Error(`Gemini file processing failed: ${name}`);
846
- return { uri: file.uri, mimeType: file.mimeType ?? mt, name };
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
- /** Generate content from a mix of files (paths or pre-uploaded) and text. */
855
- async generate(parts, options = {}) {
856
- const model = options.model ?? "gemini-flash-latest";
857
- const builtParts = [];
858
- const toCleanup = [];
859
- for (const p of parts) {
860
- if (p.text !== void 0) {
861
- builtParts.push({ text: p.text });
862
- } else if (p.uploaded) {
863
- builtParts.push({ fileData: { fileUri: p.uploaded.uri, mimeType: p.uploaded.mimeType } });
864
- } else if (p.filePath) {
865
- const up = await this.uploadFile(p.filePath);
866
- toCleanup.push(up.name);
867
- builtParts.push({ fileData: { fileUri: up.uri, mimeType: up.mimeType } });
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
- const config = {
871
- temperature: options.temperature ?? 0.2
872
- };
873
- if (options.maxOutputTokens) config["maxOutputTokens"] = options.maxOutputTokens;
874
- if (options.systemInstruction) config["systemInstruction"] = options.systemInstruction;
875
- if (options.schema) {
876
- config["responseMimeType"] = "application/json";
877
- config["responseSchema"] = options.schema;
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 resp;
886
- try {
887
- resp = await retry(() => call(config), `generate ${model}`, options.retries ?? 4);
888
- } catch (err) {
889
- if (isThinkingConfigError(err) && config["thinkingConfig"]) {
890
- process.stderr.write(`
891
- [thinking config unsupported for ${model}; retrying without it]`);
892
- const { thinkingConfig: _drop, ...rest } = config;
893
- resp = await retry(() => call(rest), `generate ${model} (no-thinking)`, options.retries ?? 4);
894
- } else {
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/core/assemble.ts
919
- function alignTurnsToSegments(turns, asrWords, totalDuration, subSegment) {
920
- if (!asrWords || asrWords.length === 0) {
921
- const segments2 = turns.map((t, i) => {
922
- const start = t.approxStart ?? 0;
923
- const end = turns[i + 1]?.approxStart ?? totalDuration;
924
- return {
925
- start,
926
- end: Math.max(start, end),
927
- speakerLabel: t.speaker,
928
- tone: t.tone,
929
- text: t.text,
930
- matchRatio: 0
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
- return { segments: segments2, voiceDist: {} };
934
- }
935
- const tokens = alignLlmToAsr(turns, asrWords);
936
- fillTokenTimes(tokens, totalDuration);
937
- const voiceDist = asrSpeakerByLabel(tokens, turns.map((t) => t.speaker));
938
- const aligned = buildSegmentsFromTokens(turns, tokens, { subSegment });
939
- const segments = [];
940
- const toneSeen = /* @__PURE__ */ new Set();
941
- for (const s2 of aligned) {
942
- if (s2.matchedTokens === 0 && s2.tokenCount <= 3) continue;
943
- const turn = turns[s2.turnIndex];
944
- const firstOfTurn = !toneSeen.has(s2.turnIndex);
945
- toneSeen.add(s2.turnIndex);
946
- segments.push({
947
- start: s2.start,
948
- end: s2.end,
949
- speakerLabel: turn.speaker,
950
- tone: firstOfTurn ? turn.tone : void 0,
951
- text: s2.text,
952
- matchRatio: s2.matchRatio
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
- return { segments, voiceDist };
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
- function buildTranscript(segments, metadata, options = {}) {
958
- const { knownSpeakers, resolvedNames, descriptions } = options;
959
- const { speakers, labelToId } = buildSpeakers(
960
- segments.map((s2) => s2.speakerLabel),
961
- { knownSpeakers, resolvedNames, descriptions }
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
- const transcriptSegments = segments.map((s2, i) => ({
964
- id: i + 1,
965
- start: s2.start,
966
- end: s2.end,
967
- speakerId: labelToId.get(s2.speakerLabel) ?? s2.speakerLabel,
968
- text: s2.text,
969
- tone: s2.tone,
970
- timingSource: s2.matchRatio > 0 ? "asr" : "llm",
971
- alignmentConfidence: s2.matchRatio
972
- }));
973
- return { segments: transcriptSegments, speakers, metadata };
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/core/chunk.ts
977
- function calculateChunks(totalSeconds, chunkSeconds, overlapSeconds) {
978
- if (totalSeconds <= chunkSeconds) {
979
- return [{ index: 0, startSeconds: 0, endSeconds: totalSeconds }];
980
- }
981
- const overlap = Math.max(0, Math.min(overlapSeconds, chunkSeconds * 0.5));
982
- const step = Math.max(1, chunkSeconds - overlap);
983
- const chunks = [];
984
- let start = 0;
985
- let index = 0;
986
- while (start < totalSeconds) {
987
- const end = Math.min(start + chunkSeconds, totalSeconds);
988
- if (end >= totalSeconds && end - start < chunkSeconds / 3 && chunks.length > 0) {
989
- chunks[chunks.length - 1].endSeconds = end;
990
- break;
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
- chunks.push({ index, startSeconds: start, endSeconds: end });
993
- index++;
994
- if (end >= totalSeconds) break;
995
- start += step;
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 chunks;
844
+ return { segments: out, dropped };
998
845
  }
999
- function chunkOwnership(chunks, totalDuration) {
1000
- return chunks.map((c, i) => {
1001
- const prev = chunks[i - 1];
1002
- const next = chunks[i + 1];
1003
- const start = i === 0 || !prev ? 0 : (prev.endSeconds + c.startSeconds) / 2;
1004
- const end = i === chunks.length - 1 || !next ? totalDuration : (c.endSeconds + next.startSeconds) / 2;
1005
- return { start, end };
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 mergeChunkSegments(segments, chunkBoundaries) {
1009
- const sorted = [...segments].sort((a, b) => a.start - b.start || a.end - b.end);
1010
- const kept = [];
1011
- for (const seg of sorted) {
1012
- const dup = kept.find(
1013
- (k) => k.chunkIndex !== seg.chunkIndex && timeOverlapRatio(k, seg) > 0.5 && textSimilar(k.text, seg.text)
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 (!dup) {
1016
- kept.push(seg);
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
- if (segmentScore(seg, chunkBoundaries) > segmentScore(dup, chunkBoundaries)) {
1020
- kept[kept.indexOf(dup)] = seg;
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
- return kept.sort((a, b) => a.start - b.start);
896
+ logger.error(`[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`);
897
+ return lastResult;
1024
898
  }
1025
- function timeOverlapRatio(a, b) {
1026
- const lo = Math.max(a.start, b.start);
1027
- const hi = Math.min(a.end, b.end);
1028
- const inter = Math.max(0, hi - lo);
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 textSimilar(a, b) {
1033
- const wa = new Set(a.toLowerCase().replace(/[^a-z0-9 ]/g, "").split(/\s+/).filter(Boolean));
1034
- const wb = new Set(b.toLowerCase().replace(/[^a-z0-9 ]/g, "").split(/\s+/).filter(Boolean));
1035
- if (wa.size === 0 || wb.size === 0) return false;
1036
- let inter = 0;
1037
- for (const w of wa) if (wb.has(w)) inter++;
1038
- const jaccard = inter / (wa.size + wb.size - inter);
1039
- return jaccard > 0.4;
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 segmentScore(seg, chunks) {
1042
- const chunk = chunks[seg.chunkIndex];
1043
- let edgeDistance = 999;
1044
- if (chunk) {
1045
- edgeDistance = Math.min(seg.start - chunk.startSeconds, chunk.endSeconds - seg.end);
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 seg.matchRatio * 10 + Math.min(edgeDistance, 30);
937
+ return prev[n];
1048
938
  }
1049
939
 
1050
- // src/core/orchestrate.ts
1051
- function sliceAsrWindow(asr, start, end, relative) {
1052
- const off = relative ? start : 0;
1053
- const utterances = asr.utterances.filter((u) => u.end >= start && u.start <= end).map((u) => ({ ...u, start: u.start - off, end: u.end - off }));
1054
- return { ...asr, utterances, words: [] };
1055
- }
1056
- function mergeVoiceDist(target, source) {
1057
- for (const [label, counts] of Object.entries(source)) {
1058
- target[label] ??= {};
1059
- for (const [sp, n] of Object.entries(counts)) target[label][sp] = (target[label][sp] ?? 0) + n;
1060
- }
1061
- }
1062
- var toPlain = (m) => ({
1063
- start: m.start,
1064
- end: m.end,
1065
- speakerLabel: m.speakerLabel,
1066
- tone: m.tone,
1067
- text: m.text,
1068
- matchRatio: m.matchRatio
1069
- });
1070
- async function orchestrateChunks(opts) {
1071
- const { asr, durationSeconds, instructions, subSegment, signal, onProgress, diarizeChunk, onChunk } = opts;
1072
- const timeChunks = durationSeconds <= opts.maxSinglePassSeconds ? [{ index: 0, startSeconds: 0, endSeconds: durationSeconds }] : calculateChunks(durationSeconds, opts.chunkSeconds, opts.overlapSeconds);
1073
- const chunked = timeChunks.length > 1;
1074
- const ownership = chunked ? chunkOwnership(timeChunks, durationSeconds) : null;
1075
- const allTurns = [];
1076
- const mergeable = [];
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
- allTurns.push(...turns);
1097
- if (asr) {
1098
- const windowWords = chunked ? asr.words.filter((w) => w.start >= ch.startSeconds - 2 && w.start <= ch.endSeconds + 2) : asr.words;
1099
- const { segments: segments2, voiceDist: vd } = alignTurnsToSegments(turns, windowWords, durationSeconds, subSegment);
1100
- mergeVoiceDist(voiceDist, vd);
1101
- const own = ownership?.[ch.index];
1102
- for (const s2 of segments2) {
1103
- if (own) {
1104
- const center = (s2.start + s2.end) / 2;
1105
- if (center < own.start || center >= own.end) continue;
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
- mergeable.push({ ...s2, chunkIndex: ch.index });
993
+ i--;
994
+ j--;
995
+ continue;
1108
996
  }
1109
997
  }
1110
- if (onChunk) {
1111
- const segmentsSoFar = [...mergeable].sort((a, b) => a.start - b.start).map(toPlain);
1112
- await onChunk({ index: ch.index, total: timeChunks.length, chunked, rawText, turns, segmentsSoFar });
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
- let segments;
1116
- if (asr) {
1117
- const merged = chunked ? mergeChunkSegments(mergeable, timeChunks) : mergeable;
1118
- segments = merged.map(toPlain);
1119
- } else {
1120
- segments = alignTurnsToSegments(allTurns, void 0, durationSeconds, subSegment).segments;
1121
- }
1122
- return { segments, allTurns, voiceDist, chunkCount: timeChunks.length };
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/node/intermediates.ts
1126
- import { createHash } from "crypto";
1127
- import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "fs";
1128
- import { dirname as dirname2, join as join2 } from "path";
1129
- function mediaKey(filePath) {
1130
- const st = statSync(filePath);
1131
- return createHash("sha256").update(`${filePath}:${st.size}:${st.mtimeMs}`).digest("hex").slice(0, 16);
1132
- }
1133
- var Intermediates = class {
1134
- constructor(dir) {
1135
- this.dir = dir;
1136
- mkdirSync(dir, { recursive: true });
1137
- }
1138
- dir;
1139
- path(name) {
1140
- return join2(this.dir, name);
1141
- }
1142
- /** Resolve a name to a path, ensuring its parent dir exists (supports "sub/dir/file"). */
1143
- ensurePath(name) {
1144
- const p = this.path(name);
1145
- mkdirSync(dirname2(p), { recursive: true });
1146
- return p;
1147
- }
1148
- has(name) {
1149
- return existsSync(this.path(name));
1150
- }
1151
- readJSON(name) {
1152
- const p = this.path(name);
1153
- if (!existsSync(p)) return null;
1154
- try {
1155
- return JSON.parse(readFileSync(p, "utf8"));
1156
- } catch {
1157
- return null;
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
- writeJSON(name, data) {
1161
- writeFileSync(this.ensurePath(name), JSON.stringify(data, null, 2));
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
- readText(name) {
1164
- const p = this.path(name);
1165
- return existsSync(p) ? readFileSync(p, "utf8") : null;
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
- writeText(name, data) {
1168
- writeFileSync(this.ensurePath(name), data);
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
- /** Run `producer` unless a cached JSON exists (and cache is enabled). */
1171
- async cachedJSON(name, enabled, producer) {
1172
- if (enabled) {
1173
- const hit = this.readJSON(name);
1174
- if (hit !== null) return hit;
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
- const result = await producer();
1177
- this.writeJSON(name, result);
1178
- return result;
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 cachedText(name, enabled, producer) {
1181
- if (enabled) {
1182
- const hit = this.readText(name);
1183
- if (hit !== null) return hit;
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/core/identify.ts
1192
- var IDENTIFY_SCHEMA = {
1193
- type: "OBJECT",
1194
- properties: {
1195
- speakers: {
1196
- type: "ARRAY",
1197
- items: {
1198
- type: "OBJECT",
1199
- properties: {
1200
- rawLabels: { type: "ARRAY", items: { type: "STRING" } },
1201
- name: { type: "STRING" },
1202
- description: { type: "STRING" }
1203
- },
1204
- required: ["rawLabels", "name"]
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
- required: ["speakers"]
1209
- };
1210
- function buildVoiceHint(dist) {
1211
- const lines = [];
1212
- for (const [label, counts] of Object.entries(dist)) {
1213
- const sorted = Object.entries(counts).sort((a, b) => b[1] - a[1]);
1214
- const total = sorted.reduce((s2, [, n]) => s2 + n, 0);
1215
- if (total === 0) continue;
1216
- const top = sorted.slice(0, 2).map(([sp, n]) => `${sp}=${Math.round(100 * n / total)}%`).join(", ");
1217
- lines.push(` "${label}" \u2192 voice ${top}`);
1218
- }
1219
- return lines.join("\n");
1220
- }
1221
- function exampleTurns(turns, perLabel = 2, maxChars = 200) {
1222
- const byLabel = /* @__PURE__ */ new Map();
1223
- for (const t of turns) {
1224
- const arr = byLabel.get(t.speaker);
1225
- if (arr) arr.push(t);
1226
- else byLabel.set(t.speaker, [t]);
1227
- }
1228
- const lines = [];
1229
- for (const [label, ts] of byLabel) {
1230
- const top = [...ts].sort((a, b) => b.text.length - a.text.length).slice(0, perLabel);
1231
- lines.push(`Label "${label}" (${ts.length} turns). Examples:`);
1232
- for (const t of top) {
1233
- const text = t.text.length > maxChars ? t.text.slice(0, maxChars) + "\u2026" : t.text;
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 lines.join("\n");
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
- Your job: produce the canonical set of speakers.
1245
- - Merge labels that refer to the SAME person.
1246
- - Give each canonical speaker a name if it can be inferred from the transcript (someone introduces themselves, or is addressed by name); otherwise keep a clean generic label like "Speaker 1".
1247
- - Add a short role/description if evident (e.g. "main presenter", "audience member").
1248
- - Each canonical speaker must be exactly ONE person. NEVER create a catch-all like "Panel", "Multiple", "Various", or "Mixed". If a raw label seems to cover overlapping/multiple voices, assign it to the single most likely dominant speaker (use the voice analysis below).
1249
- ${options.instructions ? `- Follow these user instructions for naming/grouping: ${options.instructions}
1250
- ` : ""}
1251
- Distinct raw labels: ${labels.map((l) => `"${l}"`).join(", ")}
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
- ${examples}
1254
- ${options.asrSpeakerByLabel ? `
1255
- Voice analysis (a separate diarizer clustered the audio into voices A/B/C\u2026; this is a STRONG signal for merging \u2014 labels sharing the same dominant voice are usually the same person, regardless of what they say):
1256
- ${buildVoiceHint(options.asrSpeakerByLabel)}
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
- const obj = JSON.parse(t.slice(start, end + 1));
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
- async function identifySpeakersLLM(gen, turns, options = {}) {
1277
- const prompt = buildIdentifyPrompt(turns, options);
1278
- const res = await gen.generate([{ text: prompt }], {
1279
- model: options.llmModel ?? "gemini-flash-latest",
1280
- temperature: 0,
1281
- maxOutputTokens: 16384,
1282
- thinkingLevel: "MINIMAL",
1283
- schema: IDENTIFY_SCHEMA,
1284
- label: "identify"
1285
- });
1286
- const parsed = parseIdentifyJson(res.text);
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
- return { resolvedNames, descriptions };
1661
+ });
1662
+ await Promise.all(workers);
1663
+ return results;
1297
1664
  }
1298
-
1299
- // src/pipeline.ts
1300
- var VIDEO_EXT = /* @__PURE__ */ new Set([".mp4", ".mov", ".mkv", ".webm", ".avi", ".m4v"]);
1301
- async function stage(name, fn) {
1302
- try {
1303
- return await fn();
1304
- } catch (e) {
1305
- const err = e;
1306
- if (err?.name === "AbortError") throw err;
1307
- throw new Error(`[${name}] ${err?.message ?? String(e)}`, { cause: err });
1308
- }
1309
- }
1310
- async function transcribe(input, options = {}) {
1311
- const {
1312
- instructions,
1313
- asr: asrProvider = "assemblyai",
1314
- llmModel = "gemini-flash-latest",
1315
- llmThinkingLevel = "MINIMAL",
1316
- keyframeCount = 8,
1317
- subSegment = true,
1318
- identifySpeakers = true,
1319
- knownSpeakers,
1320
- cache = true,
1321
- logLlm = true,
1322
- onProgress,
1323
- signal,
1324
- apiKeys
1325
- } = options;
1326
- const progress = (stage2, message, pct) => onProgress?.({ stage: stage2, message, pct });
1327
- const checkAbort = () => signal?.throwIfAborted();
1328
- checkAbort();
1329
- if (!existsSync2(input)) throw new Error(`Input not found: ${input}`);
1330
- const base = basename2(input, extname2(input));
1331
- const interDir = options.intermediatesDir ?? join3(dirname3(input), `.offmute_${base}`);
1332
- const inter = new Intermediates(interDir);
1333
- const sourceSig = {
1334
- v: 1,
1335
- key: mediaKey(input),
1336
- path: input,
1337
- model: llmModel,
1338
- instructions: instructions ?? null,
1339
- thinkingLevel: llmThinkingLevel,
1340
- asr: asrProvider,
1341
- subSegment,
1342
- identify: identifySpeakers
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
- const prevSig = inter.readJSON("source.json");
1345
- const effectiveCache = cache && !!prevSig && JSON.stringify(prevSig) === JSON.stringify(sourceSig);
1346
- if (cache && !effectiveCache && prevSig) {
1347
- progress("probe", "Input/config changed \u2014 ignoring stale cache");
1348
- }
1349
- inter.writeJSON("source.json", sourceSig);
1350
- progress("probe", `Probing ${basename2(input)}`);
1351
- const info = await inter.cachedJSON("media-info.json", effectiveCache, () => probeMedia(input));
1352
- const isVideo = info.hasVideo && VIDEO_EXT.has(extname2(input).toLowerCase());
1353
- const useVideo = (options.useVideo ?? isVideo) && info.hasVideo;
1354
- progress("preprocess", "Extracting 16k mono audio");
1355
- const audioPath = inter.path("audio.mp3");
1356
- if (!effectiveCache || !existsSync2(audioPath)) {
1357
- await extractAudio(input, audioPath, { sampleRate: 16e3, channels: 1 });
1358
- }
1359
- let keyframePaths = [];
1360
- if (useVideo && keyframeCount > 0) {
1361
- progress("preprocess", `Extracting ${keyframeCount} keyframes`);
1362
- const kfDir = inter.path("keyframes");
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
- if (!effectiveCache || !existsSync2(kfDir)) {
1365
- keyframePaths = await extractKeyframes(input, kfDir, {
1366
- count: keyframeCount,
1367
- durationSeconds: info.durationSeconds
1368
- });
1369
- } else {
1370
- const { readdirSync } = await import("fs");
1371
- keyframePaths = readdirSync(kfDir).filter((f) => f.endsWith(".jpg")).sort().map((f) => join3(kfDir, f));
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
- } catch (e) {
1374
- progress("preprocess", `Skipping keyframes (${e.message.slice(0, 60)})`);
1375
- keyframePaths = [];
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
- checkAbort();
1379
- let asr;
1380
- if (asrProvider === "assemblyai") {
1381
- progress("asr", "Transcribing for word-level timing (AssemblyAI)");
1382
- asr = await inter.cachedJSON(
1383
- "asr.json",
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
- const gemini = new GeminiClient(apiKeys?.gemini);
1396
- let llmSeq = 0;
1397
- gemini.onCall = (rec) => {
1398
- options.onLlmCall?.(rec);
1399
- if (logLlm) {
1400
- const n = String(llmSeq++).padStart(2, "0");
1401
- const stem = `llm/${n}-${rec.label ?? "call"}`;
1402
- inter.writeText(`${stem}.prompt.txt`, rec.promptText + (rec.fileParts ? `
1403
-
1404
- [+${rec.fileParts} file part(s)]` : ""));
1405
- inter.writeText(`${stem}.response.txt`, rec.responseText || `[error] ${rec.error ?? "unknown"}`);
1406
- inter.writeJSON(`${stem}.meta.json`, { model: rec.model, label: rec.label, usage: rec.usage, fileParts: rec.fileParts, error: rec.error });
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
- const { segments, allTurns, voiceDist } = await orchestrateChunks({
1410
- asr,
1411
- durationSeconds: info.durationSeconds,
1412
- instructions,
1413
- subSegment,
1414
- maxSinglePassSeconds: (options.maxSinglePassMinutes ?? 35) * 60,
1415
- chunkSeconds: (options.chunkMinutes ?? 15) * 60,
1416
- overlapSeconds: (options.chunkOverlapMinutes ?? 2) * 60,
1417
- signal,
1418
- onProgress: (msg) => progress("diarize", msg),
1419
- // Node-specific: extract this chunk's audio, call Gemini, cache + log the raw text.
1420
- diarizeChunk: ({ chunk, chunked, prompt }) => {
1421
- const rawName = chunked ? `diarize_chunk_${chunk.index}.txt` : "diarize.txt";
1422
- const label = chunked ? `diarize-chunk-${chunk.index}` : "diarize";
1423
- return inter.cachedText(
1424
- rawName,
1425
- effectiveCache,
1426
- () => stage(label, async () => {
1427
- let chunkAudio = audioPath;
1428
- if (chunked) {
1429
- chunkAudio = inter.path(`audio_chunk_${chunk.index}.mp3`);
1430
- if (!effectiveCache || !existsSync2(chunkAudio)) {
1431
- await extractAudio(audioPath, chunkAudio, { sampleRate: 16e3, channels: 1, startSeconds: chunk.startSeconds, durationSeconds: chunk.endSeconds - chunk.startSeconds });
1432
- }
1433
- }
1434
- const parts = [{ filePath: chunkAudio }, ...keyframePaths.map((p) => ({ filePath: p })), { text: prompt }];
1435
- const res = await gemini.generate(parts, {
1436
- model: llmModel,
1437
- temperature: 0.2,
1438
- maxOutputTokens: 65536,
1439
- thinkingLevel: llmThinkingLevel,
1440
- systemInstruction: DIARIZATION_SYSTEM,
1441
- label
1442
- });
1443
- inter.writeJSON(`${rawName.replace(/\.txt$/, "")}.meta.json`, { model: res.model, usage: res.usage });
1444
- if (!res.text.trim()) throw new Error(`Diarization returned empty text${chunked ? ` (chunk ${chunk.index})` : ""}`);
1445
- return res.text;
1446
- })
1447
- );
1448
- },
1449
- // Node-specific: save raw→parsed + a running partial transcript (resume/inspect).
1450
- onChunk: ({ index, chunked, turns: turns2, segmentsSoFar }) => {
1451
- inter.writeJSON(chunked ? `diarize_chunk_${index}.parsed.json` : "diarize.parsed.json", turns2);
1452
- inter.writeText(
1453
- "transcript.partial.srt",
1454
- formatSrt(segmentsSoFar.map((s2) => ({ start: s2.start, end: s2.end, speaker: s2.speakerLabel, text: s2.text })))
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
- const turns = allTurns;
1459
- checkAbort();
1460
- let resolvedNames;
1461
- let descriptions;
1462
- if (identifySpeakers && turns.length > 0) {
1463
- progress("identify", "Resolving speaker identities");
1464
- try {
1465
- const voiceHint = Object.keys(voiceDist).length ? voiceDist : void 0;
1466
- const ident = await inter.cachedJSON(
1467
- "identify.json",
1468
- effectiveCache,
1469
- () => identifySpeakersLLM(gemini, turns, { instructions, llmModel, asrSpeakerByLabel: voiceHint })
1470
- );
1471
- resolvedNames = ident.resolvedNames;
1472
- descriptions = ident.descriptions;
1473
- } catch (e) {
1474
- progress("identify", `Identify pass failed, using raw labels: ${e.message}`);
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
- const transcript = buildTranscript(
1478
- segments,
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
- DIARIZATION_SYSTEM,
1503
- GeminiClient,
1504
- alignLlmToAsr,
1505
- alignTokens,
1506
- asrSpeakerByLabel,
1507
- buildAsrHint,
1508
- buildDiarizationPrompt,
1509
- buildSegmentsFromTokens,
1510
- buildSpeakers,
1511
- fillTokenTimes,
1978
+ alignSegments,
1979
+ assignGlobalSpeakers,
1980
+ finalizeSegments,
1981
+ formatJson,
1982
+ formatMarkdown,
1512
1983
  formatSrt,
1513
- formatSrtTiming,
1514
- isProvisional,
1515
- normalizeToken,
1516
- parseDiarizedText,
1984
+ identifySpeakers,
1517
1985
  parseSrt,
1518
- relTimeToSeconds,
1519
- secondsToCompact,
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