offmute-v2 0.0.1-opus.0 → 0.0.2

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