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