offmute-v2 0.0.1-opus.0 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1149 @@
1
+ // src/providers/gemini-fetch.ts
2
+ var MIME_BY_EXT = {
3
+ flac: "audio/flac",
4
+ mp3: "audio/mp3",
5
+ wav: "audio/wav",
6
+ m4a: "audio/m4a",
7
+ ogg: "audio/ogg",
8
+ opus: "audio/opus",
9
+ mp4: "video/mp4",
10
+ mov: "video/quicktime",
11
+ webm: "video/webm",
12
+ png: "image/png",
13
+ jpg: "image/jpeg",
14
+ jpeg: "image/jpeg",
15
+ webp: "image/webp"
16
+ };
17
+ function toBase64(data) {
18
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
19
+ let binary = "";
20
+ const chunk = 32768;
21
+ for (let i = 0; i < bytes.length; i += chunk) {
22
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
23
+ }
24
+ return (typeof btoa !== "undefined" ? btoa : (s) => Buffer.from(s, "binary").toString("base64"))(binary);
25
+ }
26
+ var GeminiFetchClient = class {
27
+ apiKey;
28
+ baseUrl;
29
+ constructor(opts) {
30
+ this.apiKey = opts.apiKey;
31
+ this.baseUrl = opts.baseUrl ?? "https://generativelanguage.googleapis.com/v1beta";
32
+ }
33
+ /** Generate from a prompt + inline file parts (ArrayBuffer + mimeType). */
34
+ async generate(model, prompt, files, opts = {}) {
35
+ const maxRetries = opts.maxRetries ?? 3;
36
+ const parts = [];
37
+ for (const f of files) {
38
+ const mimeType = f.mimeType ?? (f.ext ? MIME_BY_EXT[f.ext] : "audio/flac");
39
+ parts.push({ inlineData: { mimeType, data: toBase64(f.data) } });
40
+ }
41
+ parts.push({ text: prompt });
42
+ const body = {
43
+ contents: [{ role: "user", parts }],
44
+ generationConfig: {
45
+ maxOutputTokens: opts.maxOutputTokens ?? 65536,
46
+ temperature: opts.temperature ?? 0.2
47
+ }
48
+ };
49
+ if (opts.responseSchema) {
50
+ body.generationConfig.responseMimeType = "application/json";
51
+ body.generationConfig.responseSchema = opts.responseSchema;
52
+ }
53
+ if (opts.systemInstruction) body.systemInstruction = opts.systemInstruction;
54
+ let lastError;
55
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
56
+ try {
57
+ const res = await fetch(
58
+ `${this.baseUrl}/models/${model}:generateContent?key=${this.apiKey}`,
59
+ {
60
+ method: "POST",
61
+ headers: { "Content-Type": "application/json" },
62
+ body: JSON.stringify(body)
63
+ }
64
+ );
65
+ if (!res.ok) {
66
+ const txt = await res.text();
67
+ throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
68
+ }
69
+ const data = await res.json();
70
+ const text = data.candidates?.[0]?.content?.parts?.map((p) => p.text || "").join("") ?? "";
71
+ const u = data.usageMetadata || {};
72
+ return {
73
+ text,
74
+ usage: {
75
+ inputTokens: u.promptTokenCount ?? 0,
76
+ outputTokens: u.candidatesTokenCount ?? 0,
77
+ totalTokens: u.totalTokenCount ?? 0
78
+ }
79
+ };
80
+ } catch (err) {
81
+ lastError = err instanceof Error ? err.message : String(err);
82
+ if (attempt < maxRetries - 1) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
83
+ }
84
+ }
85
+ return { text: "", usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }, error: lastError };
86
+ }
87
+ async generateJson(model, prompt, files, responseSchema, opts = {}) {
88
+ const r = await this.generate(model, prompt, files, { ...opts, responseSchema });
89
+ if (r.error || !r.text) return { data: null, raw: r.text, error: r.error };
90
+ try {
91
+ let t = r.text.trim();
92
+ const f = t.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
93
+ if (f && f[1]) t = f[1];
94
+ return { data: JSON.parse(t), raw: r.text };
95
+ } catch (err) {
96
+ return { data: null, raw: r.text, error: `JSON parse: ${err instanceof Error ? err.message : String(err)}` };
97
+ }
98
+ }
99
+ };
100
+
101
+ // src/providers/assemblyai-fetch.ts
102
+ var BASE = "https://api.assemblyai.com/v2";
103
+ var AssemblyAIFetchClient = class {
104
+ constructor(apiKey) {
105
+ this.apiKey = apiKey;
106
+ }
107
+ apiKey;
108
+ async transcribe(audio, opts = {}) {
109
+ const upRes = await fetch(`${BASE}/upload`, {
110
+ method: "POST",
111
+ headers: { authorization: this.apiKey },
112
+ body: audio
113
+ });
114
+ if (!upRes.ok) throw new Error(`AssemblyAI upload ${upRes.status}: ${await upRes.text()}`);
115
+ const { upload_url } = await upRes.json();
116
+ const params = {
117
+ audio_url: upload_url,
118
+ speaker_labels: true,
119
+ speech_model: "universal"
120
+ };
121
+ if (opts.speakersExpected) params.speakers_expected = opts.speakersExpected;
122
+ const cr = await fetch(`${BASE}/transcript`, {
123
+ method: "POST",
124
+ headers: { authorization: this.apiKey, "content-type": "application/json" },
125
+ body: JSON.stringify(params)
126
+ });
127
+ if (!cr.ok) throw new Error(`AssemblyAI create ${cr.status}: ${await cr.text()}`);
128
+ const transcript = await cr.json();
129
+ let t = transcript;
130
+ while (t.status !== "completed" && t.status !== "error") {
131
+ await new Promise((r) => setTimeout(r, 2e3));
132
+ const pr = await fetch(`${BASE}/transcript/${t.id}`, { headers: { authorization: this.apiKey } });
133
+ t = await pr.json();
134
+ }
135
+ if (t.status === "error") throw new Error(`AssemblyAI error: ${t.error}`);
136
+ const toWord = (w) => ({
137
+ text: w.text,
138
+ start: (w.start || 0) / 1e3,
139
+ end: (w.end || 0) / 1e3,
140
+ confidence: w.confidence
141
+ });
142
+ const utterances = [];
143
+ const speakers = /* @__PURE__ */ new Set();
144
+ for (const u of t.utterances || []) {
145
+ const speaker = `speaker_${u.speaker}`;
146
+ speakers.add(speaker);
147
+ utterances.push({
148
+ speaker,
149
+ text: u.text,
150
+ start: (u.start || 0) / 1e3,
151
+ end: (u.end || 0) / 1e3,
152
+ confidence: u.confidence,
153
+ words: (u.words || []).map(toWord)
154
+ });
155
+ }
156
+ const words = (t.words || []).map(toWord);
157
+ const durationSec = words.length ? words[words.length - 1].end : 0;
158
+ return { utterances, words, durationSec, speakers: [...speakers].sort(), transcriptId: t.id };
159
+ }
160
+ };
161
+
162
+ // src/providers/llm-log.ts
163
+ import { appendFileSync } from "fs";
164
+ var logPath = null;
165
+ function logLlmCall(entry) {
166
+ if (!logPath) return;
167
+ try {
168
+ appendFileSync(logPath, JSON.stringify(entry) + "\n", { encoding: "utf-8" });
169
+ } catch {
170
+ }
171
+ }
172
+
173
+ // src/providers/openai-compat.ts
174
+ var PROVIDER_BASE = {
175
+ deepseek: "https://api.deepseek.com/v1",
176
+ groq: "https://api.groq.com/openai/v1",
177
+ openai: "https://api.openai.com/v1"
178
+ };
179
+ var OpenAICompatClient = class _OpenAICompatClient {
180
+ constructor(baseUrl, apiKey, defaultModel, providerName = "openai-compat") {
181
+ this.baseUrl = baseUrl;
182
+ this.apiKey = apiKey;
183
+ this.defaultModel = defaultModel;
184
+ this.providerName = providerName;
185
+ }
186
+ baseUrl;
187
+ apiKey;
188
+ defaultModel;
189
+ providerName;
190
+ static fromProvider(provider, apiKey, defaultModel) {
191
+ const base = PROVIDER_BASE[provider] ?? provider;
192
+ return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
193
+ }
194
+ async chat(model, messages, opts = {}) {
195
+ const m = model ?? this.defaultModel;
196
+ const maxRetries = opts.maxRetries ?? 2;
197
+ const body = {
198
+ model: m,
199
+ messages,
200
+ temperature: opts.temperature ?? 0.2
201
+ };
202
+ if (opts.maxTokens) body.max_tokens = opts.maxTokens;
203
+ if (opts.responseJson) {
204
+ body.response_format = { type: "json_object" };
205
+ }
206
+ let lastError;
207
+ const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
208
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
209
+ const t0 = Date.now();
210
+ try {
211
+ const res = await fetch(`${this.baseUrl}/chat/completions`, {
212
+ method: "POST",
213
+ headers: {
214
+ "Content-Type": "application/json",
215
+ Authorization: `Bearer ${this.apiKey}`
216
+ },
217
+ body: JSON.stringify(body)
218
+ });
219
+ if (!res.ok) {
220
+ const txt = await res.text();
221
+ throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
222
+ }
223
+ const data = await res.json();
224
+ const text = data.choices?.[0]?.message?.content ?? "";
225
+ const usage = {
226
+ inputTokens: data.usage?.prompt_tokens ?? 0,
227
+ outputTokens: data.usage?.completion_tokens ?? 0
228
+ };
229
+ logLlmCall({
230
+ ts: new Date(t0).toISOString(),
231
+ provider: this.providerName,
232
+ model: m,
233
+ kind: opts.logKind,
234
+ prompt: promptStr,
235
+ response: text,
236
+ usage,
237
+ durationMs: Date.now() - t0,
238
+ attempt: attempt + 1
239
+ });
240
+ return { text, usage };
241
+ } catch (err) {
242
+ lastError = err instanceof Error ? err.message : String(err);
243
+ logLlmCall({
244
+ ts: new Date(t0).toISOString(),
245
+ provider: this.providerName,
246
+ model: m,
247
+ kind: opts.logKind,
248
+ prompt: promptStr,
249
+ response: "",
250
+ durationMs: Date.now() - t0,
251
+ attempt: attempt + 1,
252
+ error: lastError
253
+ });
254
+ if (attempt < maxRetries - 1) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
255
+ }
256
+ }
257
+ return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
258
+ }
259
+ async chatJson(model, messages, opts = {}) {
260
+ const res = await this.chat(model, messages, { ...opts, responseJson: true });
261
+ if (res.error || !res.text) return { data: null, raw: res.text, error: res.error };
262
+ try {
263
+ let txt = res.text.trim();
264
+ const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
265
+ if (fence && fence[1]) txt = fence[1];
266
+ return { data: JSON.parse(txt), raw: res.text };
267
+ } catch (err) {
268
+ return { data: null, raw: res.text, error: `JSON parse: ${err instanceof Error ? err.message : String(err)}` };
269
+ }
270
+ }
271
+ };
272
+
273
+ // src/transcribe/prompts.ts
274
+ var TRANSCRIPT_SCHEMA = {
275
+ type: "OBJECT",
276
+ properties: {
277
+ segments: {
278
+ type: "ARRAY",
279
+ items: {
280
+ type: "OBJECT",
281
+ properties: {
282
+ speaker: { type: "STRING", description: "Speaker label. Use an identified name from the roster if confident, else 'Speaker A', 'Speaker B', etc." },
283
+ start: { type: "STRING", description: "Relative start time as mm:ss (00:00 = start of this audio chunk)" },
284
+ end: { type: "STRING", description: "Relative end time as mm:ss" },
285
+ text: { type: "STRING", description: "Verbatim transcribed words, including fillers and false starts" },
286
+ tone: {
287
+ type: "ARRAY",
288
+ items: { type: "STRING" },
289
+ description: "Tone/behavior tags e.g. hesitant, laughing, contemplating, urgent, sarcastic. Empty array if neutral."
290
+ }
291
+ },
292
+ required: ["speaker", "start", "end", "text"]
293
+ }
294
+ }
295
+ },
296
+ required: ["segments"]
297
+ };
298
+ function transcriptionPrompt(ctx) {
299
+ const parts = [];
300
+ parts.push(
301
+ `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.`
302
+ );
303
+ parts.push("");
304
+ parts.push("Output one segment per speaker turn (a new segment whenever the speaker changes, or after a long pause, or at an interruption).");
305
+ parts.push("");
306
+ parts.push("For each segment provide:");
307
+ 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.");
308
+ 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.");
309
+ parts.push("- text: the verbatim words, including fillers (um, uh), false starts, and corrections. Do not paraphrase.");
310
+ 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.");
311
+ parts.push("");
312
+ parts.push("Rules:");
313
+ parts.push("- Cover the ENTIRE audio with no gaps. Timestamps must be monotonic non-decreasing.");
314
+ parts.push("- Capture interruptions and overlapping talk as separate, adjacent segments even if times overlap.");
315
+ parts.push("- Do not invent content not present in the audio. If inaudible, write [inaudible].");
316
+ parts.push("- Keep speaker labels consistent within this chunk; the same voice = same label.");
317
+ if (ctx.description) {
318
+ parts.push("");
319
+ parts.push("MEETING CONTEXT:");
320
+ parts.push(ctx.description);
321
+ }
322
+ if (ctx.roster) {
323
+ parts.push("");
324
+ parts.push("SPEAKER ROSTER (prefer these labels/names when you can identify the voice):");
325
+ parts.push(ctx.roster);
326
+ }
327
+ if (ctx.previousTail) {
328
+ parts.push("");
329
+ parts.push("TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):");
330
+ parts.push(ctx.previousTail);
331
+ }
332
+ if (ctx.instructions) {
333
+ parts.push("");
334
+ parts.push("ADDITIONAL INSTRUCTIONS:");
335
+ parts.push(ctx.instructions);
336
+ }
337
+ parts.push("");
338
+ parts.push("Return JSON matching the schema: { segments: [ {speaker, start, end, text, tone} ] }");
339
+ return parts.join("\n");
340
+ }
341
+
342
+ // src/providers/gemini.ts
343
+ import { GoogleGenAI } from "@google/genai";
344
+ import { basename } from "path";
345
+
346
+ // src/utils/logger.ts
347
+ var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
348
+ var currentLevel = "info";
349
+ function setLogLevel(level) {
350
+ currentLevel = level;
351
+ }
352
+ function log(level, msg, extra) {
353
+ if (LEVELS[level] < LEVELS[currentLevel]) return;
354
+ const ts = (/* @__PURE__ */ new Date()).toISOString().substring(11, 23);
355
+ const prefix = `[${ts}] ${level.toUpperCase().padEnd(5)}`;
356
+ if (extra !== void 0) {
357
+ console[level === "error" ? "error" : "log"](prefix, msg, extra);
358
+ } else {
359
+ console[level === "error" ? "error" : "log"](prefix, msg);
360
+ }
361
+ }
362
+ var logger = {
363
+ debug: (msg, extra) => log("debug", msg, extra),
364
+ info: (msg, extra) => log("info", msg, extra),
365
+ warn: (msg, extra) => log("warn", msg, extra),
366
+ error: (msg, extra) => log("error", msg, extra),
367
+ setLevel: setLogLevel
368
+ };
369
+
370
+ // src/utils/time.ts
371
+ function secondsToTimestamp(seconds) {
372
+ const clamped = Math.max(0, seconds);
373
+ const hours = Math.floor(clamped / 3600);
374
+ const minutes = Math.floor(clamped % 3600 / 60);
375
+ const secs = Math.floor(clamped % 60);
376
+ const ms = Math.floor(clamped % 1 * 1e3);
377
+ return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")},${ms.toString().padStart(3, "0")}`;
378
+ }
379
+ function formatSrtTiming(startSeconds, endSeconds) {
380
+ return `${secondsToTimestamp(startSeconds)} --> ${secondsToTimestamp(endSeconds)}`;
381
+ }
382
+ function parseMmSs(timeStr) {
383
+ const parts = timeStr.split(":");
384
+ if (parts.length !== 2) return null;
385
+ const minutes = parseInt(parts[0], 10);
386
+ const seconds = parseInt(parts[1], 10);
387
+ if (isNaN(minutes) || isNaN(seconds)) return null;
388
+ if (seconds < 0 || seconds >= 60) return null;
389
+ return minutes * 60 + seconds;
390
+ }
391
+
392
+ // src/transcribe/llm-transcribe.ts
393
+ function toAbsolute(mmSs, offset) {
394
+ const s = parseMmSs(mmSs.trim());
395
+ return s === null ? null : s + offset;
396
+ }
397
+ function parseLlmSegments(data, chunkOffsetSec) {
398
+ const out = [];
399
+ let dropped = 0;
400
+ for (const seg of data.segments || []) {
401
+ const start = toAbsolute(seg.start, chunkOffsetSec);
402
+ const end = toAbsolute(seg.end, chunkOffsetSec);
403
+ if (start === null || end === null || end < start) {
404
+ dropped++;
405
+ logger.debug(`[llm] dropping segment (bad time ${seg.start}-${seg.end}): "${(seg.text || "").slice(0, 40)}"`);
406
+ continue;
407
+ }
408
+ out.push({
409
+ speaker: (seg.speaker || "Unknown").trim(),
410
+ startSec: start,
411
+ endSec: end,
412
+ text: (seg.text || "").trim(),
413
+ tone: Array.isArray(seg.tone) ? seg.tone.map((t) => String(t).trim()).filter(Boolean) : [],
414
+ rawStart: seg.start,
415
+ rawEnd: seg.end
416
+ });
417
+ }
418
+ return { segments: out, dropped };
419
+ }
420
+
421
+ // src/align/normalize.ts
422
+ function normalize(word) {
423
+ return word.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "").replace(/'+$/g, "").replace(/^'+/g, "");
424
+ }
425
+ function tokenize(text) {
426
+ const out = [];
427
+ for (const raw of text.split(/\s+/)) {
428
+ if (!raw) continue;
429
+ const norm = normalize(raw);
430
+ if (norm) out.push({ original: raw, norm });
431
+ }
432
+ return out;
433
+ }
434
+ function fuzzyEqual(a, b) {
435
+ if (a === b) return true;
436
+ if (Math.abs(a.length - b.length) <= 1) {
437
+ return editDistanceChars(a, b, 1) <= 1;
438
+ }
439
+ return false;
440
+ }
441
+ function editDistanceChars(a, b, max) {
442
+ const m = a.length;
443
+ const n = b.length;
444
+ if (Math.abs(m - n) > max) return max + 1;
445
+ let prev = new Array(n + 1);
446
+ for (let j = 0; j <= n; j++) prev[j] = j;
447
+ for (let i = 1; i <= m; i++) {
448
+ const cur = [i];
449
+ let rowMin = cur[0];
450
+ for (let j = 1; j <= n; j++) {
451
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
452
+ cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost);
453
+ if (cur[j] < rowMin) rowMin = cur[j];
454
+ }
455
+ if (rowMin > max) return max + 1;
456
+ prev = cur;
457
+ }
458
+ return prev[n];
459
+ }
460
+
461
+ // src/align/edit-distance.ts
462
+ var INDEL = 2;
463
+ function matchCost(a, b) {
464
+ if (a.norm === b.norm) return { cost: 0, fuzzy: false };
465
+ if (fuzzyEqual(a.norm, b.norm)) return { cost: 1, fuzzy: true };
466
+ return { cost: 2, fuzzy: false };
467
+ }
468
+ function alignWords(llm, asr) {
469
+ const m = llm.length;
470
+ const n = asr.length;
471
+ const dp = new Array(m + 1);
472
+ for (let i2 = 0; i2 <= m; i2++) {
473
+ const row = new Int32Array(n + 1);
474
+ row[0] = i2 * INDEL;
475
+ dp[i2] = row;
476
+ }
477
+ const firstRow = dp[0];
478
+ for (let j2 = 0; j2 <= n; j2++) firstRow[j2] = j2 * INDEL;
479
+ for (let i2 = 1; i2 <= m; i2++) {
480
+ const row = dp[i2];
481
+ const prev = dp[i2 - 1];
482
+ for (let j2 = 1; j2 <= n; j2++) {
483
+ const { cost } = matchCost(llm[i2 - 1], asr[j2 - 1]);
484
+ const sub = prev[j2 - 1] + cost;
485
+ const ins2 = prev[j2] + INDEL;
486
+ const del2 = row[j2 - 1] + INDEL;
487
+ row[j2] = Math.min(sub, ins2, del2);
488
+ }
489
+ }
490
+ const ops = [];
491
+ let i = m;
492
+ let j = n;
493
+ let exact = 0;
494
+ let fuzzy = 0;
495
+ let subs = 0;
496
+ let ins = 0;
497
+ let del = 0;
498
+ while (i > 0 || j > 0) {
499
+ const cur = dp[i];
500
+ if (i > 0 && j > 0) {
501
+ const { cost } = matchCost(llm[i - 1], asr[j - 1]);
502
+ const sub = dp[i - 1][j - 1] + cost;
503
+ if (cur[j] === sub) {
504
+ if (cost === 0) {
505
+ ops.push({ type: "match", llm: i - 1, asr: j - 1, fuzzy: false });
506
+ exact++;
507
+ } else if (cost === 1) {
508
+ ops.push({ type: "match", llm: i - 1, asr: j - 1, fuzzy: true });
509
+ fuzzy++;
510
+ } else {
511
+ ops.push({ type: "substitute", llm: i - 1, asr: j - 1 });
512
+ subs++;
513
+ }
514
+ i--;
515
+ j--;
516
+ continue;
517
+ }
518
+ }
519
+ if (i > 0 && cur[j] === dp[i - 1][j] + INDEL) {
520
+ ops.push({ type: "insert", llm: i - 1 });
521
+ ins++;
522
+ i--;
523
+ continue;
524
+ }
525
+ ops.push({ type: "delete", asr: j - 1 });
526
+ del++;
527
+ j--;
528
+ }
529
+ ops.reverse();
530
+ return {
531
+ ops,
532
+ exactMatches: exact,
533
+ fuzzyMatches: fuzzy,
534
+ substitutions: subs,
535
+ insertions: ins,
536
+ deletions: del
537
+ };
538
+ }
539
+
540
+ // src/align/aligner.ts
541
+ function toAsrTokens(words) {
542
+ return words.map((w) => ({
543
+ text: w.text,
544
+ start: w.start,
545
+ end: w.end,
546
+ norm: w.text.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "")
547
+ }));
548
+ }
549
+ function transferTiming(llm, asr, ops) {
550
+ const times = llm.map(() => ({ start: NaN, end: NaN, matched: false }));
551
+ for (const op of ops) {
552
+ if (op.type === "match" || op.type === "substitute") {
553
+ const a = asr[op.asr];
554
+ times[op.llm] = { start: a.start, end: a.end, matched: op.type === "match" && !op.fuzzy };
555
+ }
556
+ }
557
+ for (let k = 0; k < times.length; k++) {
558
+ if (!isNaN(times[k].start)) continue;
559
+ let prevEnd = null;
560
+ for (let p = k - 1; p >= 0; p--) {
561
+ if (!isNaN(times[p].start)) {
562
+ prevEnd = times[p].end;
563
+ break;
564
+ }
565
+ }
566
+ let nextStart = null;
567
+ for (let q = k + 1; q < times.length; q++) {
568
+ if (!isNaN(times[q].start)) {
569
+ nextStart = times[q].start;
570
+ break;
571
+ }
572
+ }
573
+ if (prevEnd !== null && nextStart !== null) {
574
+ const segIdx = llm[k].segIdx;
575
+ let runLen = 0;
576
+ for (let r = k; r < times.length && isNaN(times[r].start) && llm[r].segIdx === segIdx; r++)
577
+ runLen++;
578
+ const step = (nextStart - prevEnd) / (runLen + 1);
579
+ for (let r = 0; r < runLen; r++) {
580
+ const pt = prevEnd + step * (r + 1);
581
+ times[k + r] = { start: pt, end: pt, matched: false };
582
+ }
583
+ k += runLen - 1;
584
+ } else if (nextStart !== null) {
585
+ times[k] = { start: nextStart, end: nextStart, matched: false };
586
+ } else if (prevEnd !== null) {
587
+ times[k] = { start: prevEnd, end: prevEnd, matched: false };
588
+ }
589
+ }
590
+ return times;
591
+ }
592
+ function alignSegments(llmSegments, asrWords, opts = {}) {
593
+ const confThreshold = opts.confidenceThreshold ?? 0.5;
594
+ const margin = opts.timeMarginSec ?? 0;
595
+ const sorted = [...llmSegments].map((s, i) => ({ s, i })).sort((a, b) => a.s.startSec - b.s.startSec);
596
+ const flat = [];
597
+ const segRanges = [];
598
+ for (const { s, i } of sorted) {
599
+ const toks = tokenize(s.text);
600
+ const start = flat.length;
601
+ for (const t of toks) flat.push({ original: t.original, norm: t.norm, segIdx: i });
602
+ segRanges.push({ src: i, start, end: flat.length });
603
+ }
604
+ if (flat.length === 0 || asrWords.length === 0) {
605
+ return sorted.map(({ s, i }) => ({
606
+ speaker: s.speaker,
607
+ start: s.startSec,
608
+ end: s.endSec,
609
+ text: s.text,
610
+ tone: s.tone,
611
+ confidence: 0,
612
+ timingSource: "coarse",
613
+ words: [],
614
+ sourceIndex: i
615
+ }));
616
+ }
617
+ let asr = toAsrTokens(asrWords);
618
+ if (margin > 0) {
619
+ const lo = sorted[0].s.startSec - margin;
620
+ const hi = sorted[sorted.length - 1].s.endSec + margin;
621
+ asr = asr.filter((w) => w.end >= lo && w.start <= hi);
622
+ }
623
+ const result = alignWords(flat, asr);
624
+ const times = transferTiming(flat, asr, result.ops);
625
+ if (process.env.ALIGN_DEBUG) {
626
+ console.error(
627
+ `[align] flat=${flat.length} asr=${asr.length} exact=${result.exactMatches} fuzzy=${result.fuzzyMatches} subs=${result.substitutions} ins=${result.insertions} del=${result.deletions}`
628
+ );
629
+ }
630
+ const out = [];
631
+ for (let si = 0; si < sorted.length; si++) {
632
+ const { s, i } = sorted[si];
633
+ const range = segRanges[si];
634
+ const segTimes = times.slice(range.start, range.end);
635
+ const segOps = result.ops.filter(
636
+ (op) => (op.type === "match" || op.type === "substitute") && op.llm >= range.start && op.llm < range.end
637
+ );
638
+ const exact = segOps.filter((op) => op.type === "match" && !op.fuzzy).length;
639
+ const tokenCount = range.end - range.start;
640
+ const firstTimed = segTimes.find((t) => !isNaN(t.start));
641
+ const lastTimed = [...segTimes].reverse().find((t) => !isNaN(t.end));
642
+ let start;
643
+ let end;
644
+ let timingSource;
645
+ const confidence = tokenCount ? exact / tokenCount : 0;
646
+ if (firstTimed && lastTimed) {
647
+ start = firstTimed.start;
648
+ end = lastTimed.end;
649
+ timingSource = confidence >= confThreshold ? "aligned" : "interpolated";
650
+ } else {
651
+ start = s.startSec;
652
+ end = s.endSec;
653
+ timingSource = "coarse";
654
+ }
655
+ const words = segTimes.map((t, idx) => ({
656
+ text: flat[range.start + idx].original,
657
+ start: isNaN(t.start) ? start : t.start,
658
+ end: isNaN(t.end) ? end : t.end,
659
+ matched: t.matched
660
+ }));
661
+ out.push({
662
+ speaker: s.speaker,
663
+ start,
664
+ end,
665
+ text: s.text,
666
+ tone: s.tone,
667
+ confidence,
668
+ timingSource,
669
+ words,
670
+ sourceIndex: i
671
+ });
672
+ }
673
+ return out;
674
+ }
675
+
676
+ // src/diarize/consistency.ts
677
+ function overlap(s1, e1, s2, e2) {
678
+ return Math.max(0, Math.min(e1, e2) - Math.max(s1, s2));
679
+ }
680
+ function isGenericLabel(label) {
681
+ return /^(speaker\s+[a-z0-9]+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(label.trim());
682
+ }
683
+ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
684
+ const hasDiarization = opts.hasDiarization ?? true;
685
+ const out = segments.map((seg) => ({ seg, asrSpeaker: "" }));
686
+ const labelVotes = {};
687
+ const asrDuration = {};
688
+ for (const o of out) {
689
+ let bestSpeaker = "";
690
+ let bestOverlap = 0;
691
+ if (hasDiarization) {
692
+ for (const u of asrUtterances) {
693
+ const ov = overlap(o.seg.start, o.seg.end, u.start, u.end);
694
+ if (ov > bestOverlap) {
695
+ bestOverlap = ov;
696
+ bestSpeaker = u.speaker;
697
+ }
698
+ }
699
+ if (!bestSpeaker) {
700
+ let bestDist = Infinity;
701
+ const segMid = (o.seg.start + o.seg.end) / 2;
702
+ for (const u of asrUtterances) {
703
+ const uMid = (u.start + u.end) / 2;
704
+ const d = Math.abs(uMid - segMid);
705
+ if (d < bestDist) {
706
+ bestDist = d;
707
+ bestSpeaker = u.speaker;
708
+ }
709
+ }
710
+ bestSpeaker = bestSpeaker || "speaker_?";
711
+ }
712
+ } else {
713
+ bestSpeaker = o.seg.speaker || "speaker_?";
714
+ bestOverlap = o.seg.end - o.seg.start;
715
+ }
716
+ o.asrSpeaker = bestSpeaker;
717
+ asrDuration[o.asrSpeaker] = (asrDuration[o.asrSpeaker] ?? 0) + Math.max(bestOverlap, 0.1);
718
+ labelVotes[o.asrSpeaker] ??= {};
719
+ labelVotes[o.asrSpeaker][o.seg.speaker] = (labelVotes[o.asrSpeaker][o.seg.speaker] ?? 0) + 1;
720
+ }
721
+ const dominantLabel = {};
722
+ for (const [asrSp, votes] of Object.entries(labelVotes)) {
723
+ const best = Object.entries(votes).sort((a, b) => b[1] - a[1])[0];
724
+ dominantLabel[asrSp] = best ? best[0] : asrSp;
725
+ }
726
+ const asrToGroup = {};
727
+ const groupLabel = {};
728
+ const groupTalk = {};
729
+ const groupAsrVoices = {};
730
+ for (const asrSp of Object.keys(labelVotes)) {
731
+ const label = dominantLabel[asrSp] ?? asrSp;
732
+ let groupId;
733
+ if (!isGenericLabel(label)) {
734
+ groupId = Object.keys(groupLabel).find((g) => groupLabel[g] === label);
735
+ }
736
+ if (!groupId) {
737
+ groupId = asrSp;
738
+ groupLabel[groupId] = label;
739
+ }
740
+ asrToGroup[asrSp] = groupId;
741
+ groupTalk[groupId] = (groupTalk[groupId] ?? 0) + (asrDuration[asrSp] ?? 0);
742
+ (groupAsrVoices[groupId] ??= []).push(asrSp);
743
+ }
744
+ const groupsByTalk = Object.keys(groupTalk).sort((a, b) => groupTalk[b] - groupTalk[a]);
745
+ const groupToGlobal = {};
746
+ groupsByTalk.forEach((g, i) => {
747
+ groupToGlobal[g] = `Speaker ${String.fromCharCode(65 + i)}`;
748
+ });
749
+ const displayNames = {};
750
+ for (const g of groupsByTalk) {
751
+ const label = groupLabel[g];
752
+ displayNames[groupToGlobal[g]] = isGenericLabel(label) ? groupToGlobal[g] : label;
753
+ }
754
+ const llmLabelToAsr = {};
755
+ for (const o of out) {
756
+ llmLabelToAsr[o.seg.speaker] = groupToGlobal[asrToGroup[o.asrSpeaker]];
757
+ }
758
+ const updated = out.map((o) => {
759
+ const global = groupToGlobal[asrToGroup[o.asrSpeaker]];
760
+ return {
761
+ ...o.seg,
762
+ speaker: global,
763
+ speakerName: displayNames[global] || global
764
+ };
765
+ });
766
+ const speakerMap = {};
767
+ for (const s of updated) {
768
+ speakerMap[s.speaker] ??= { count: 0, talk: 0 };
769
+ speakerMap[s.speaker].count++;
770
+ speakerMap[s.speaker].talk += s.end - s.start;
771
+ }
772
+ const globalAsrVoices = {};
773
+ for (const [g, voices] of Object.entries(groupAsrVoices)) {
774
+ globalAsrVoices[groupToGlobal[g]] = voices;
775
+ }
776
+ const speakers = Object.entries(speakerMap).map(([id, v]) => ({
777
+ id,
778
+ name: displayNames[id],
779
+ segmentCount: v.count,
780
+ talkTime: v.talk,
781
+ asrVoices: globalAsrVoices[id]
782
+ })).filter((s) => s.talkTime > 0).sort((a, b) => (b.talkTime ?? 0) - (a.talkTime ?? 0));
783
+ return { segments: updated, speakers, displayNames, llmLabelToAsr };
784
+ }
785
+
786
+ // src/diarize/identify.ts
787
+ function buildTranscriptExcerpt(segments, speakers) {
788
+ const bySpeaker = {};
789
+ for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
790
+ const parts = [];
791
+ for (const sp of speakers) {
792
+ const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
793
+ const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
794
+ parts.push(
795
+ `### ${sp.id} (${sp.name || "unknown"}, ${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s${voices})`
796
+ );
797
+ for (const s of segs) parts.push(` ${s.text}`);
798
+ }
799
+ return parts.join("\n");
800
+ }
801
+ function identifyPrompt(transcriptExcerpt, roster, knownSpeakers) {
802
+ 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.
803
+
804
+ 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 ("").
805
+
806
+ ${knownSpeakers && knownSpeakers.length ? `Known possible speakers: ${knownSpeakers.join(", ")}
807
+ ` : ""}ROSTER:
808
+ ${roster}
809
+
810
+ TRANSCRIPT EXCERPTS BY SPEAKER:
811
+ ${transcriptExcerpt}
812
+
813
+ 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" }
814
+ Use the EXACT speaker id strings from the headers above (e.g. "Speaker A").`;
815
+ }
816
+ async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers) {
817
+ const excerpt = buildTranscriptExcerpt(segments, speakers);
818
+ const { data, error } = await client.chatJson(
819
+ model,
820
+ [{ role: "user", content: identifyPrompt(excerpt, roster, knownSpeakers) }],
821
+ { temperature: 0.1, maxTokens: 2e3, logKind: "identify" }
822
+ );
823
+ if (error || !data) {
824
+ return { nameMap: {}, speakers: [], reasoning: error || "no response" };
825
+ }
826
+ const nameMap = {};
827
+ for (const s of data.speakers || []) {
828
+ if (s.name && s.name.trim()) nameMap[s.id] = s.name.trim();
829
+ }
830
+ return { nameMap, speakers: data.speakers || [], reasoning: data.reasoning || "" };
831
+ }
832
+
833
+ // src/finalize/finalize.ts
834
+ var MIN_DUR = 0.5;
835
+ var MAX_DUR = 7;
836
+ var OVERLAP_GAP = 0.05;
837
+ function textSimilarity(a, b) {
838
+ const ta = new Set(tokenize(a).map((t) => t.norm));
839
+ const tb = new Set(tokenize(b).map((t) => t.norm));
840
+ if (ta.size === 0 && tb.size === 0) return 1;
841
+ if (ta.size === 0 || tb.size === 0) return 0;
842
+ let inter = 0;
843
+ for (const t of ta) if (tb.has(t)) inter++;
844
+ return inter / (ta.size + tb.size - inter);
845
+ }
846
+ function timeOverlapFrac(a, b) {
847
+ const ov = Math.max(0, Math.min(a.end, b.end) - Math.max(a.start, b.start));
848
+ const shorter = Math.min(a.end - a.start, b.end - b.start);
849
+ return shorter > 0 ? ov / shorter : 0;
850
+ }
851
+ function dedupSegments(segments) {
852
+ const sorted = [...segments].sort((a, b) => a.start - b.start);
853
+ const kept = [];
854
+ for (const seg of sorted) {
855
+ const dup = kept.find(
856
+ (k) => k.speaker === seg.speaker && textSimilarity(k.text, seg.text) > 0.7 && timeOverlapFrac(k, seg) > 0.2
857
+ );
858
+ if (dup) {
859
+ if (seg.confidence > dup.confidence) {
860
+ Object.assign(dup, seg);
861
+ }
862
+ continue;
863
+ }
864
+ kept.push(seg);
865
+ }
866
+ return kept;
867
+ }
868
+ function fixOverlaps(segments) {
869
+ if (segments.length === 0) return segments;
870
+ const sorted = [...segments].sort((a, b) => a.start - b.start);
871
+ for (let pass = 0; pass < 10; pass++) {
872
+ let changed = false;
873
+ for (let i = 0; i < sorted.length - 1; i++) {
874
+ const cur = sorted[i];
875
+ const next = sorted[i + 1];
876
+ if (cur.end > next.start) {
877
+ const targetEnd = next.start - OVERLAP_GAP;
878
+ const newDur = targetEnd - cur.start;
879
+ if (newDur >= MIN_DUR) {
880
+ cur.end = targetEnd;
881
+ changed = true;
882
+ } else {
883
+ const shiftedStart = cur.end + OVERLAP_GAP;
884
+ const followingStart = sorted[i + 2]?.start ?? Infinity;
885
+ if (shiftedStart < next.end - MIN_DUR && shiftedStart < followingStart) {
886
+ next.start = shiftedStart;
887
+ changed = true;
888
+ }
889
+ }
890
+ }
891
+ }
892
+ if (!changed) break;
893
+ }
894
+ return sorted;
895
+ }
896
+ function clampAndFix(segments) {
897
+ for (const s of segments) {
898
+ const dur = s.end - s.start;
899
+ if (dur < MIN_DUR) s.end = s.start + MIN_DUR;
900
+ else if (dur > MAX_DUR) s.end = s.start + MAX_DUR;
901
+ }
902
+ return fixOverlaps(segments);
903
+ }
904
+ function finalizeSegments(segments, opts = {}) {
905
+ const minSeg = opts.minSegmentSec ?? 0.2;
906
+ let deduped = dedupSegments(segments);
907
+ deduped = deduped.filter((s) => s.end - s.start >= minSeg && s.text.trim().length > 0);
908
+ const out = deduped.map((s, i) => ({
909
+ id: i + 1,
910
+ start: s.start,
911
+ end: s.end,
912
+ speaker: s.speaker,
913
+ speakerName: s.speakerName || s.speaker,
914
+ // Collapse any internal whitespace (incl. newlines) so a stray blank line in the LLM
915
+ // text can never split one SRT cue into several — SRT cues end at a blank line.
916
+ text: s.text.trim().replace(/\s+/g, " "),
917
+ tone: s.tone,
918
+ timingSource: s.timingSource,
919
+ confidence: s.confidence,
920
+ words: s.words
921
+ }));
922
+ return clampAndFix(out);
923
+ }
924
+
925
+ // src/finalize/format.ts
926
+ var MAX_CHARS = 84;
927
+ var MAX_BLOCK_SEC = 7;
928
+ function splitIntoBlocks(seg) {
929
+ const words = seg.words && seg.words.length > 0 ? seg.words : null;
930
+ if (!words) {
931
+ return [{ start: seg.start, end: seg.end, text: seg.text }];
932
+ }
933
+ const blocks = [];
934
+ let curWords = [];
935
+ let curLen = 0;
936
+ const flush = () => {
937
+ if (curWords.length === 0) return;
938
+ const first = curWords[0];
939
+ const last = curWords[curWords.length - 1];
940
+ blocks.push({
941
+ start: first.start,
942
+ end: last.end,
943
+ text: curWords.map((w) => w.text).join(" ")
944
+ });
945
+ curWords = [];
946
+ curLen = 0;
947
+ };
948
+ for (const w of words) {
949
+ const addLen = w.text.length + 1;
950
+ const blockStart = curWords.length === 0 ? w.start : curWords[0].start;
951
+ const wouldSec = w.end - blockStart;
952
+ if (curLen + addLen > MAX_CHARS || wouldSec > MAX_BLOCK_SEC) {
953
+ flush();
954
+ }
955
+ curWords.push(w);
956
+ curLen += addLen;
957
+ }
958
+ flush();
959
+ return blocks.length ? blocks : [{ start: seg.start, end: seg.end, text: seg.text }];
960
+ }
961
+ function formatSrt(result, opts = {}) {
962
+ const labelSpeakers = opts.labelSpeakers ?? true;
963
+ const showTone = opts.showTone ?? true;
964
+ let idx = 1;
965
+ const blocks = [];
966
+ for (const seg of result.segments) {
967
+ const tone = showTone && seg.tone && seg.tone.length ? ` (${seg.tone.join(", ")})` : "";
968
+ const speaker = labelSpeakers ? `${seg.speakerName || seg.speaker}: ` : "";
969
+ for (const b of splitIntoBlocks(seg)) {
970
+ blocks.push(`${idx}
971
+ ${formatSrtTiming(b.start, b.end)}
972
+ ${speaker}${b.text}${tone}
973
+ `);
974
+ idx++;
975
+ }
976
+ }
977
+ return blocks.join("\n");
978
+ }
979
+ function formatMarkdown(result, opts = {}) {
980
+ const parts = [];
981
+ parts.push(`# ${opts.title || "Transcript"}
982
+ `);
983
+ parts.push(`*Duration: ${Math.round(result.metadata.duration)}s \xB7 Speakers: ${result.speakers.length}*
984
+ `);
985
+ parts.push("\n## Speakers\n");
986
+ for (const s of result.speakers) {
987
+ const talk = s.talkTime ? ` (${Math.round(s.talkTime)}s)` : "";
988
+ parts.push(`- **${s.name || s.id}**${talk}`);
989
+ }
990
+ parts.push("\n## Transcript\n");
991
+ for (const seg of result.segments) {
992
+ const mm = Math.floor(seg.start / 60).toString().padStart(2, "0");
993
+ const ss = Math.floor(seg.start % 60).toString().padStart(2, "0");
994
+ const tone = seg.tone && seg.tone.length ? ` *(${seg.tone.join(", ")})*` : "";
995
+ parts.push(`[${mm}:${ss}] **${seg.speakerName || seg.speaker}**${tone}: ${seg.text}
996
+ `);
997
+ }
998
+ return parts.join("\n");
999
+ }
1000
+ function formatJson(result) {
1001
+ return JSON.stringify(result, null, 2);
1002
+ }
1003
+
1004
+ // src/browser-ffmpeg.ts
1005
+ var DEFAULT_CORE_BASE = "https://unpkg.com/@ffmpeg/core@0.12.10/dist/umd";
1006
+ var ffmpegInstance = null;
1007
+ async function loadFfmpeg(opts = {}) {
1008
+ if (ffmpegInstance) return ffmpegInstance;
1009
+ const { FFmpeg } = await import("@ffmpeg/ffmpeg");
1010
+ const { toBlobURL } = await import("@ffmpeg/util");
1011
+ const base = opts.coreBase ?? DEFAULT_CORE_BASE;
1012
+ const ffmpeg = new FFmpeg();
1013
+ await ffmpeg.load({
1014
+ coreURL: await toBlobURL(`${base}/ffmpeg-core.js`, "text/javascript"),
1015
+ wasmURL: await toBlobURL(`${base}/ffmpeg-core.wasm`, "application/wasm")
1016
+ });
1017
+ ffmpegInstance = ffmpeg;
1018
+ return ffmpeg;
1019
+ }
1020
+ async function writeInput(ffmpeg, blob, name) {
1021
+ const { fetchFile } = await import("@ffmpeg/util");
1022
+ await ffmpeg.writeFile(name, await fetchFile(blob));
1023
+ }
1024
+ async function preprocessInBrowser(input, chunks, opts = {}) {
1025
+ const ffmpeg = await loadFfmpeg(opts);
1026
+ const inExt = input.type.includes("video") ? "mp4" : "m4a";
1027
+ const inFile = `input.${inExt}`;
1028
+ await writeInput(ffmpeg, input, inFile);
1029
+ await ffmpeg.exec(["-i", inFile, "-vn", "-ac", "1", "-ar", "16000", "-c:a", "flac", "audio.flac"]);
1030
+ const audioData = await ffmpeg.readFile("audio.flac");
1031
+ const audio = new Blob([audioData], { type: "audio/flac" });
1032
+ const chunkBlobs = [];
1033
+ for (let i = 0; i < chunks.length; i++) {
1034
+ const c = chunks[i];
1035
+ const name = `chunk_${i}.flac`;
1036
+ await ffmpeg.exec([
1037
+ "-i",
1038
+ inFile,
1039
+ "-ss",
1040
+ c.start.toFixed(3),
1041
+ "-t",
1042
+ (c.end - c.start).toFixed(3),
1043
+ "-vn",
1044
+ "-ac",
1045
+ "1",
1046
+ "-ar",
1047
+ "16000",
1048
+ "-c:a",
1049
+ "flac",
1050
+ name
1051
+ ]);
1052
+ const data = await ffmpeg.readFile(name);
1053
+ chunkBlobs.push({ data: new Blob([data], { type: "audio/flac" }), start: c.start, end: c.end });
1054
+ try {
1055
+ await ffmpeg.deleteFile(name);
1056
+ } catch {
1057
+ }
1058
+ }
1059
+ const keyframes = [];
1060
+ if (opts.isVideo && (opts.keyframeCount ?? 0) > 0) {
1061
+ const n = opts.keyframeCount;
1062
+ for (let i = 0; i < n; i++) {
1063
+ const t = (i + 0.5) / n;
1064
+ const name = `kf_${i}.jpg`;
1065
+ await ffmpeg.exec(["-i", inFile, "-ss", (t * 1).toFixed(3), "-frames:v", "1", name]);
1066
+ const data = await ffmpeg.readFile(name);
1067
+ keyframes.push(new Blob([data], { type: "image/jpeg" }));
1068
+ try {
1069
+ await ffmpeg.deleteFile(name);
1070
+ } catch {
1071
+ }
1072
+ }
1073
+ }
1074
+ try {
1075
+ await ffmpeg.deleteFile(inFile);
1076
+ await ffmpeg.deleteFile("audio.flac");
1077
+ } catch {
1078
+ }
1079
+ return { audio, chunks: chunkBlobs, keyframes };
1080
+ }
1081
+
1082
+ // src/browser.ts
1083
+ async function transcribeBrowser(opts) {
1084
+ const model = opts.model ?? "gemini-2.5-flash";
1085
+ const level = opts.level ?? 2;
1086
+ const asr = await new AssemblyAIFetchClient(opts.assemblyaiApiKey).transcribe(opts.audio);
1087
+ const audioBuf = await opts.audio.arrayBuffer();
1088
+ const gemini = new GeminiFetchClient({ apiKey: opts.geminiApiKey });
1089
+ const gen = await gemini.generateJson(
1090
+ model,
1091
+ transcriptionPrompt({ index: 1, total: 1, instructions: opts.instructions }),
1092
+ [{ data: audioBuf, ext: opts.audioExt ?? "flac" }],
1093
+ TRANSCRIPT_SCHEMA,
1094
+ { temperature: 0.2, maxRetries: 3 }
1095
+ );
1096
+ if (!gen.data) throw new Error(`LLM transcription failed: ${gen.error ?? "no data"}`);
1097
+ const llmSegments = parseLlmSegments(gen.data, 0).segments;
1098
+ const aligned = alignSegments(llmSegments, asr.words, { timeMarginSec: 30 });
1099
+ const cons = assignGlobalSpeakers(aligned, asr.utterances);
1100
+ let segments = cons.segments;
1101
+ let speakers = cons.speakers;
1102
+ if (level >= 3 && opts.deepseekApiKey) {
1103
+ const ds = OpenAICompatClient.fromProvider("deepseek", opts.deepseekApiKey, "deepseek-chat");
1104
+ const id = await identifySpeakers(
1105
+ ds,
1106
+ "deepseek-chat",
1107
+ segments.map((s) => ({ speaker: s.speaker, text: s.text })),
1108
+ speakers,
1109
+ "(browser: no roster available \u2014 infer from transcript content)",
1110
+ opts.knownSpeakers
1111
+ );
1112
+ segments = segments.map(
1113
+ (s) => id.nameMap[s.speaker] ? { ...s, speakerName: id.nameMap[s.speaker] } : s
1114
+ );
1115
+ speakers = speakers.map((sp) => id.nameMap[sp.id] ? { ...sp, name: id.nameMap[sp.id] } : sp);
1116
+ }
1117
+ const finalSegments = finalizeSegments(segments);
1118
+ return {
1119
+ segments: finalSegments,
1120
+ speakers,
1121
+ metadata: {
1122
+ sourceFile: "browser",
1123
+ duration: asr.durationSec,
1124
+ processedAt: (/* @__PURE__ */ new Date()).toISOString(),
1125
+ models: { transcribe: model, timestamped: "assemblyai-universal-2" },
1126
+ passes: ["timestamped", "llm-transcribe", "align", "consistency", level >= 3 ? "identify" : "", "finalize"].filter(
1127
+ Boolean
1128
+ )
1129
+ }
1130
+ };
1131
+ }
1132
+ export {
1133
+ AssemblyAIFetchClient,
1134
+ GeminiFetchClient,
1135
+ OpenAICompatClient,
1136
+ TRANSCRIPT_SCHEMA,
1137
+ alignSegments,
1138
+ assignGlobalSpeakers,
1139
+ finalizeSegments,
1140
+ formatJson,
1141
+ formatMarkdown,
1142
+ formatSrt,
1143
+ identifySpeakers,
1144
+ parseLlmSegments,
1145
+ preprocessInBrowser,
1146
+ transcribeBrowser,
1147
+ transcriptionPrompt
1148
+ };
1149
+ //# sourceMappingURL=browser.browser.js.map