offmute-v2 0.0.4 → 0.1.0

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.
@@ -79,10 +79,15 @@ var GeminiFetchClient = class {
79
79
  };
80
80
  } catch (err) {
81
81
  lastError = err instanceof Error ? err.message : String(err);
82
- if (attempt < maxRetries - 1) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
82
+ if (attempt < maxRetries - 1)
83
+ await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
83
84
  }
84
85
  }
85
- return { text: "", usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }, error: lastError };
86
+ return {
87
+ text: "",
88
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
89
+ error: lastError
90
+ };
86
91
  }
87
92
  async generateJson(model, prompt, files, responseSchema, opts = {}) {
88
93
  const r = await this.generate(model, prompt, files, { ...opts, responseSchema });
@@ -93,7 +98,11 @@ var GeminiFetchClient = class {
93
98
  if (f && f[1]) t = f[1];
94
99
  return { data: JSON.parse(t), raw: r.text };
95
100
  } catch (err) {
96
- return { data: null, raw: r.text, error: `JSON parse: ${err instanceof Error ? err.message : String(err)}` };
101
+ return {
102
+ data: null,
103
+ raw: r.text,
104
+ error: `JSON parse: ${err instanceof Error ? err.message : String(err)}`
105
+ };
97
106
  }
98
107
  }
99
108
  };
@@ -111,7 +120,8 @@ var AssemblyAIFetchClient = class {
111
120
  headers: { authorization: this.apiKey },
112
121
  body: audio
113
122
  });
114
- if (!upRes.ok) throw new Error(`AssemblyAI upload ${upRes.status}: ${await upRes.text()}`);
123
+ if (!upRes.ok)
124
+ throw new Error(`AssemblyAI upload ${upRes.status}: ${await upRes.text()}`);
115
125
  const { upload_url } = await upRes.json();
116
126
  const params = {
117
127
  audio_url: upload_url,
@@ -129,7 +139,9 @@ var AssemblyAIFetchClient = class {
129
139
  let t = transcript;
130
140
  while (t.status !== "completed" && t.status !== "error") {
131
141
  await new Promise((r) => setTimeout(r, 2e3));
132
- const pr = await fetch(`${BASE}/transcript/${t.id}`, { headers: { authorization: this.apiKey } });
142
+ const pr = await fetch(`${BASE}/transcript/${t.id}`, {
143
+ headers: { authorization: this.apiKey }
144
+ });
133
145
  t = await pr.json();
134
146
  }
135
147
  if (t.status === "error") throw new Error(`AssemblyAI error: ${t.error}`);
@@ -155,14 +167,39 @@ var AssemblyAIFetchClient = class {
155
167
  }
156
168
  const words = (t.words || []).map(toWord);
157
169
  const durationSec = words.length ? words[words.length - 1].end : 0;
158
- return { utterances, words, durationSec, speakers: [...speakers].sort(), transcriptId: t.id };
170
+ return {
171
+ utterances,
172
+ words,
173
+ durationSec,
174
+ speakers: [...speakers].sort(),
175
+ transcriptId: t.id
176
+ };
159
177
  }
160
178
  };
161
179
 
162
180
  // src/providers/llm-log.ts
163
181
  import { appendFileSync } from "fs";
164
182
  var logPath = null;
183
+ var usageRecords = /* @__PURE__ */ new Map();
165
184
  function logLlmCall(entry) {
185
+ try {
186
+ const key = `${entry.model}|${entry.kind ?? ""}`;
187
+ const rec = usageRecords.get(key) ?? {
188
+ provider: entry.provider,
189
+ model: entry.model,
190
+ kind: entry.kind,
191
+ inputTokens: 0,
192
+ outputTokens: 0,
193
+ calls: 0,
194
+ errors: 0
195
+ };
196
+ rec.inputTokens += entry.usage?.inputTokens ?? 0;
197
+ rec.outputTokens += entry.usage?.outputTokens ?? 0;
198
+ rec.calls += 1;
199
+ if (entry.error) rec.errors += 1;
200
+ usageRecords.set(key, rec);
201
+ } catch {
202
+ }
166
203
  if (!logPath) return;
167
204
  try {
168
205
  appendFileSync(logPath, JSON.stringify(entry) + "\n", { encoding: "utf-8" });
@@ -193,7 +230,7 @@ var OpenAICompatClient = class _OpenAICompatClient {
193
230
  }
194
231
  async chat(model, messages, opts = {}) {
195
232
  const m = model ?? this.defaultModel;
196
- const maxRetries = opts.maxRetries ?? 2;
233
+ const maxRetries = opts.maxRetries ?? 5;
197
234
  const body = {
198
235
  model: m,
199
236
  messages,
@@ -203,6 +240,9 @@ var OpenAICompatClient = class _OpenAICompatClient {
203
240
  if (opts.responseJson) {
204
241
  body.response_format = { type: "json_object" };
205
242
  }
243
+ if (this.providerName === "gemini") {
244
+ body.reasoning_effort = "low";
245
+ }
206
246
  let lastError;
207
247
  const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
208
248
  for (let attempt = 0; attempt < maxRetries; attempt++) {
@@ -240,6 +280,14 @@ var OpenAICompatClient = class _OpenAICompatClient {
240
280
  return { text, usage };
241
281
  } catch (err) {
242
282
  lastError = err instanceof Error ? err.message : String(err);
283
+ if (body.response_format && /response_format/i.test(lastError)) {
284
+ delete body.response_format;
285
+ continue;
286
+ }
287
+ if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
288
+ delete body.reasoning_effort;
289
+ continue;
290
+ }
243
291
  logLlmCall({
244
292
  ts: new Date(t0).toISOString(),
245
293
  provider: this.providerName,
@@ -251,22 +299,30 @@ var OpenAICompatClient = class _OpenAICompatClient {
251
299
  attempt: attempt + 1,
252
300
  error: lastError
253
301
  });
254
- if (attempt < maxRetries - 1) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
302
+ if (attempt < maxRetries - 1)
303
+ await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
255
304
  }
256
305
  }
257
306
  return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
258
307
  }
259
308
  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)}` };
309
+ let lastRaw = "";
310
+ let lastError;
311
+ for (let attempt = 0; attempt < 2; attempt++) {
312
+ const res = await this.chat(model, messages, { ...opts, responseJson: true });
313
+ lastRaw = res.text;
314
+ lastError = res.error;
315
+ if (res.error || !res.text) continue;
316
+ try {
317
+ let txt = res.text.trim();
318
+ const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
319
+ if (fence && fence[1]) txt = fence[1];
320
+ return { data: JSON.parse(txt), raw: res.text };
321
+ } catch (err) {
322
+ lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
323
+ }
269
324
  }
325
+ return { data: null, raw: lastRaw, error: lastError };
270
326
  }
271
327
  };
272
328
 
@@ -279,14 +335,23 @@ var TRANSCRIPT_SCHEMA = {
279
335
  items: {
280
336
  type: "OBJECT",
281
337
  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)" },
338
+ speaker: {
339
+ type: "STRING",
340
+ description: "Speaker label. Use an identified name from the roster if confident, else 'Speaker A', 'Speaker B', etc."
341
+ },
342
+ start: {
343
+ type: "STRING",
344
+ description: "Relative start time as mm:ss (00:00 = start of this audio chunk)"
345
+ },
284
346
  end: { type: "STRING", description: "Relative end time as mm:ss" },
285
- text: { type: "STRING", description: "Verbatim transcribed words, including fillers and false starts" },
347
+ text: {
348
+ type: "STRING",
349
+ description: "Verbatim transcribed words, including fillers and false starts"
350
+ },
286
351
  tone: {
287
352
  type: "ARRAY",
288
353
  items: { type: "STRING" },
289
- description: "Tone/behavior tags e.g. hesitant, laughing, contemplating, urgent, sarcastic. Empty array if neutral."
354
+ description: "Tone tags ONLY when something clearly stands out (laughing, sarcastic, agitated, whispering). Empty array for normal speech \u2014 most segments."
290
355
  }
291
356
  },
292
357
  required: ["speaker", "start", "end", "text"]
@@ -301,19 +366,40 @@ function transcriptionPrompt(ctx) {
301
366
  `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
367
  );
303
368
  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).");
369
+ parts.push(
370
+ `Start a NEW segment on EVERY voice change \u2014 this is the single most important rule. That includes one-word interjections, backchannels ("yeah", "right", "oh my god"), and replies inside someone else's story. If a different voice says even a single word, it gets its own segment with its own speaker label. Never fold another person's words into the current speaker's segment. Also break on long pauses and interruptions.`
371
+ );
305
372
  parts.push("");
306
373
  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.");
374
+ parts.push(
375
+ "- 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."
376
+ );
377
+ parts.push(
378
+ "- 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."
379
+ );
380
+ parts.push(
381
+ "- text: the verbatim words, including fillers (um, uh), false starts, and corrections. Do not paraphrase."
382
+ );
383
+ parts.push(
384
+ '- tone: tags ONLY when the delivery clearly stands out \u2014 laughing, sarcastic, agitated, whispering, mock-serious, exasperated. Normal conversational speech (even confident/casual/curious speech) gets an EMPTY array. Most segments should have no tone tags; a tag should mean "a reader would want to know this".'
385
+ );
311
386
  parts.push("");
312
387
  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.");
388
+ parts.push(
389
+ "- Cover the ENTIRE audio with no gaps. Timestamps must be monotonic non-decreasing."
390
+ );
391
+ parts.push(
392
+ "- Capture interruptions and overlapping talk as separate, adjacent segments even if times overlap."
393
+ );
394
+ parts.push(
395
+ "- Listen for voice characteristics (pitch, accent, mic distance), not just content. Two people agreeing with each other are still two segments."
396
+ );
397
+ parts.push(
398
+ "- Do not invent content not present in the audio. If inaudible, write [inaudible]."
399
+ );
400
+ parts.push(
401
+ "- Keep speaker labels consistent within this chunk; the same voice = same label."
402
+ );
317
403
  if (ctx.description) {
318
404
  parts.push("");
319
405
  parts.push("MEETING CONTEXT:");
@@ -321,12 +407,20 @@ function transcriptionPrompt(ctx) {
321
407
  }
322
408
  if (ctx.roster) {
323
409
  parts.push("");
324
- parts.push("SPEAKER ROSTER (prefer these labels/names when you can identify the voice):");
410
+ parts.push(
411
+ "SPEAKER ROSTER (context about who is present \u2014 but its name-to-voice binding may be wrong):"
412
+ );
325
413
  parts.push(ctx.roster);
414
+ parts.push("");
415
+ parts.push(
416
+ "Use a roster name ONLY when the voice itself tells you it's that person (they self-identify, are addressed by name, or the voice description clearly matches). If two speakers sound similar and you are not sure which name belongs to which voice, use 'Speaker A' / 'Speaker B' instead \u2014 a WRONG name is much worse than a generic label; a later pass verifies names."
417
+ );
326
418
  }
327
419
  if (ctx.previousTail) {
328
420
  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):");
421
+ parts.push(
422
+ "TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):"
423
+ );
330
424
  parts.push(ctx.previousTail);
331
425
  }
332
426
  if (ctx.instructions) {
@@ -335,7 +429,9 @@ function transcriptionPrompt(ctx) {
335
429
  parts.push(ctx.instructions);
336
430
  }
337
431
  parts.push("");
338
- parts.push("Return JSON matching the schema: { segments: [ {speaker, start, end, text, tone} ] }");
432
+ parts.push(
433
+ "Return JSON matching the schema: { segments: [ {speaker, start, end, text, tone} ] }"
434
+ );
339
435
  return parts.join("\n");
340
436
  }
341
437
 
@@ -346,11 +442,13 @@ import { basename } from "path";
346
442
  // src/utils/logger.ts
347
443
  var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
348
444
  var currentLevel = "info";
445
+ var sink = null;
349
446
  function setLogLevel(level) {
350
447
  currentLevel = level;
351
448
  }
352
449
  function log(level, msg, extra) {
353
450
  if (LEVELS[level] < LEVELS[currentLevel]) return;
451
+ if (sink && extra === void 0 && sink(level, msg)) return;
354
452
  const ts = (/* @__PURE__ */ new Date()).toISOString().substring(11, 23);
355
453
  const prefix = `[${ts}] ${level.toUpperCase().padEnd(5)}`;
356
454
  if (extra !== void 0) {
@@ -364,7 +462,18 @@ var logger = {
364
462
  info: (msg, extra) => log("info", msg, extra),
365
463
  warn: (msg, extra) => log("warn", msg, extra),
366
464
  error: (msg, extra) => log("error", msg, extra),
367
- setLevel: setLogLevel
465
+ setLevel: setLogLevel,
466
+ setSink: (s) => {
467
+ sink = s;
468
+ }
469
+ };
470
+
471
+ // src/providers/gemini.ts
472
+ var SDK_KEY_WARNING = "Both GOOGLE_API_KEY and GEMINI_API_KEY are set";
473
+ var originalWarn = console.warn.bind(console);
474
+ console.warn = (...args) => {
475
+ if (typeof args[0] === "string" && args[0].startsWith(SDK_KEY_WARNING)) return;
476
+ originalWarn(...args);
368
477
  };
369
478
 
370
479
  // src/utils/time.ts
@@ -388,6 +497,16 @@ function parseMmSs(timeStr) {
388
497
  if (seconds < 0 || seconds >= 60) return null;
389
498
  return minutes * 60 + seconds;
390
499
  }
500
+ function formatDuration(seconds) {
501
+ const hours = Math.floor(seconds / 3600);
502
+ const minutes = Math.floor(seconds % 3600 / 60);
503
+ const remaining = Math.floor(seconds % 60);
504
+ const parts = [];
505
+ if (hours > 0) parts.push(`${hours}h`);
506
+ if (minutes > 0) parts.push(`${minutes}m`);
507
+ parts.push(`${remaining}s`);
508
+ return parts.join(" ");
509
+ }
391
510
 
392
511
  // src/transcribe/llm-transcribe.ts
393
512
  function toAbsolute(mmSs, offset) {
@@ -402,7 +521,9 @@ function parseLlmSegments(data, chunkOffsetSec) {
402
521
  const end = toAbsolute(seg.end, chunkOffsetSec);
403
522
  if (start === null || end === null || end < start) {
404
523
  dropped++;
405
- logger.debug(`[llm] dropping segment (bad time ${seg.start}-${seg.end}): "${(seg.text || "").slice(0, 40)}"`);
524
+ logger.debug(
525
+ `[llm] dropping segment (bad time ${seg.start}-${seg.end}): "${(seg.text || "").slice(0, 40)}"`
526
+ );
406
527
  continue;
407
528
  }
408
529
  out.push({
@@ -551,7 +672,11 @@ function transferTiming(llm, asr, ops) {
551
672
  for (const op of ops) {
552
673
  if (op.type === "match" || op.type === "substitute") {
553
674
  const a = asr[op.asr];
554
- times[op.llm] = { start: a.start, end: a.end, matched: op.type === "match" && !op.fuzzy };
675
+ times[op.llm] = {
676
+ start: a.start,
677
+ end: a.end,
678
+ matched: op.type === "match" && !op.fuzzy
679
+ };
555
680
  }
556
681
  }
557
682
  for (let k = 0; k < times.length; k++) {
@@ -678,8 +803,19 @@ function overlap(s1, e1, s2, e2) {
678
803
  return Math.max(0, Math.min(e1, e2) - Math.max(s1, s2));
679
804
  }
680
805
  function isGenericLabel(label) {
681
- return /^(speaker\s+[a-z0-9]+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(label.trim());
806
+ return /^(speaker\s+[a-z0-9]+|voice\s+\S+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(
807
+ label.trim()
808
+ );
809
+ }
810
+ function countTurnTransitions(utterances, a, b) {
811
+ const seq = [...utterances].sort((x, y) => x.start - y.start).map((u) => u.speaker).filter((s) => s === a || s === b);
812
+ let transitions = 0;
813
+ for (let i = 1; i < seq.length; i++) {
814
+ if (seq[i] !== seq[i - 1]) transitions++;
815
+ }
816
+ return transitions;
682
817
  }
818
+ var MAX_MERGE_TRANSITIONS = 3;
683
819
  function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
684
820
  const hasDiarization = opts.hasDiarization ?? true;
685
821
  const out = segments.map((seg) => ({ seg, asrSpeaker: "" }));
@@ -731,7 +867,18 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
731
867
  const label = dominantLabel[asrSp] ?? asrSp;
732
868
  let groupId;
733
869
  if (!isGenericLabel(label)) {
734
- groupId = Object.keys(groupLabel).find((g) => groupLabel[g] === label);
870
+ const candidate = Object.keys(groupLabel).find((g) => groupLabel[g] === label);
871
+ if (candidate && hasDiarization) {
872
+ const partners = groupAsrVoices[candidate] ?? [];
873
+ const maxTransitions = Math.max(
874
+ ...partners.map((p) => countTurnTransitions(asrUtterances, p, asrSp))
875
+ );
876
+ if (maxTransitions <= MAX_MERGE_TRANSITIONS) {
877
+ groupId = candidate;
878
+ }
879
+ } else if (candidate) {
880
+ groupId = candidate;
881
+ }
735
882
  }
736
883
  if (!groupId) {
737
884
  groupId = asrSp;
@@ -741,15 +888,24 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
741
888
  groupTalk[groupId] = (groupTalk[groupId] ?? 0) + (asrDuration[asrSp] ?? 0);
742
889
  (groupAsrVoices[groupId] ??= []).push(asrSp);
743
890
  }
744
- const groupsByTalk = Object.keys(groupTalk).sort((a, b) => groupTalk[b] - groupTalk[a]);
891
+ const groupsByTalk = Object.keys(groupTalk).sort(
892
+ (a, b) => groupTalk[b] - groupTalk[a]
893
+ );
745
894
  const groupToGlobal = {};
746
895
  groupsByTalk.forEach((g, i) => {
747
896
  groupToGlobal[g] = `Speaker ${String.fromCharCode(65 + i)}`;
748
897
  });
898
+ const labelGroupCount = {};
899
+ for (const g of groupsByTalk) {
900
+ const label = groupLabel[g];
901
+ if (!isGenericLabel(label))
902
+ labelGroupCount[label] = (labelGroupCount[label] ?? 0) + 1;
903
+ }
749
904
  const displayNames = {};
750
905
  for (const g of groupsByTalk) {
751
906
  const label = groupLabel[g];
752
- displayNames[groupToGlobal[g]] = isGenericLabel(label) ? groupToGlobal[g] : label;
907
+ const contested = (labelGroupCount[label] ?? 0) > 1;
908
+ displayNames[groupToGlobal[g]] = isGenericLabel(label) || contested ? groupToGlobal[g] : label;
753
909
  }
754
910
  const llmLabelToAsr = {};
755
911
  for (const o of out) {
@@ -784,41 +940,81 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
784
940
  }
785
941
 
786
942
  // src/diarize/identify.ts
943
+ var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
787
944
  function buildTranscriptExcerpt(segments, speakers) {
945
+ const speakerHeader = (sp) => {
946
+ const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
947
+ return `${sp.id} (${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s talk time${voices})`;
948
+ };
949
+ const totalChars = segments.reduce((n, s) => n + s.text.length, 0);
950
+ if (totalChars <= MAX_FULL_TRANSCRIPT_CHARS) {
951
+ const parts2 = [
952
+ "SPEAKERS:",
953
+ ...speakers.map((sp) => `- ${speakerHeader(sp)}`),
954
+ "",
955
+ "FULL TRANSCRIPT (in order):"
956
+ ];
957
+ for (const s of segments) parts2.push(`[${s.speaker}] ${s.text}`);
958
+ return parts2.join("\n");
959
+ }
788
960
  const bySpeaker = {};
789
961
  for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
790
962
  const parts = [];
791
963
  for (const sp of speakers) {
792
964
  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
- );
965
+ parts.push(`### ${speakerHeader(sp)}`);
797
966
  for (const s of segs) parts.push(` ${s.text}`);
798
967
  }
799
968
  return parts.join("\n");
800
969
  }
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.
970
+ function identifyPrompt(transcriptExcerpt, roster, knownSpeakers, nameHints, sourceFileName) {
971
+ const hintBlock = nameHints && Object.keys(nameHints).length ? `
972
+ TENTATIVE LABELS (from the transcription model \u2014 UNVERIFIED and possibly SWAPPED between speakers; treat as weak hints to confirm or refute, never as ground truth):
973
+ ${Object.entries(
974
+ nameHints
975
+ ).map(([id, n]) => ` ${id} was tentatively called "${n}"`).join("\n")}
976
+ ` : "";
977
+ return `You are identifying speakers in a transcribed recording. Below is the diarized transcript (speaker ids like "Speaker A" are stable voice clusters), plus a roster description.
803
978
 
804
979
  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
980
 
981
+ CRITICAL \u2014 direction of address: when a speaker says a name, work out whether they are talking ABOUT themselves or TO someone else. "Thanks, Rishi" or "I'm stealing your update, Rishi" is spoken TO Rishi \u2014 so that speaker is NOT Rishi, and Rishi is one of the OTHER speakers. Only first-person statements ("I'm Rishi", "my name is...") identify the speaker themselves. Misreading address direction is the most common error in this task.
982
+
983
+ BEWARE the roster and tentative labels: they describe who is PRESENT, but their name-to-voice binding may be wrong or swapped (this happens when speakers sound similar). Verify every name against first-person evidence in the transcript itself. If the transcript contradicts a tentative label, trust the transcript. If you cannot verify which of two speakers a name belongs to, leave both names empty rather than guess.
984
+
985
+ Prefer real human names over screen handles/usernames when both are available for the same person (e.g. a recording named after "Jay" whose call UI shows a handle \u2014 the person is Jay).
986
+
806
987
  ${knownSpeakers && knownSpeakers.length ? `Known possible speakers: ${knownSpeakers.join(", ")}
988
+ ` : ""}${sourceFileName ? `RECORDING FILENAME (often names participants): ${sourceFileName}
807
989
  ` : ""}ROSTER:
808
990
  ${roster}
809
-
810
- TRANSCRIPT EXCERPTS BY SPEAKER:
991
+ ${hintBlock}
992
+ TRANSCRIPT:
811
993
  ${transcriptExcerpt}
812
994
 
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").`;
995
+ Respond as JSON: { "speakers": [ { "id": "<exact speaker id from the headers>", "name": "Full Name or Role", "confidence": "high|medium|low", "evidence": "a short quote copied VERBATIM from the transcript above that supports the name" } ], "reasoning": "one-paragraph summary" }
996
+ Use the EXACT speaker id strings (e.g. "Speaker A"). The evidence field must be an exact quote from the TRANSCRIPT \u2014 never the filename, roster, or your own words; an unverifiable evidence quote disqualifies the name.`;
815
997
  }
816
- async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers) {
998
+ async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers, nameHints, sourceFileName) {
817
999
  const excerpt = buildTranscriptExcerpt(segments, speakers);
818
1000
  const { data, error } = await client.chatJson(
819
1001
  model,
820
- [{ role: "user", content: identifyPrompt(excerpt, roster, knownSpeakers) }],
821
- { temperature: 0.1, maxTokens: 2e3, logKind: "identify" }
1002
+ [
1003
+ {
1004
+ role: "user",
1005
+ content: identifyPrompt(
1006
+ excerpt,
1007
+ roster,
1008
+ knownSpeakers,
1009
+ nameHints,
1010
+ sourceFileName
1011
+ )
1012
+ }
1013
+ ],
1014
+ // 8000 tokens: verbose models quote long verbatim evidence, and Gemini's compat
1015
+ // endpoint spends part of the budget on thinking — tighter caps truncated
1016
+ // mid-JSON and silently emptied whole identify passes (observed live, twice).
1017
+ { temperature: 0.1, maxTokens: 8e3, logKind: "identify" }
822
1018
  );
823
1019
  if (error || !data) {
824
1020
  return { nameMap: {}, speakers: [], reasoning: error || "no response" };
@@ -848,6 +1044,87 @@ function timeOverlapFrac(a, b) {
848
1044
  const shorter = Math.min(a.end - a.start, b.end - b.start);
849
1045
  return shorter > 0 ? ov / shorter : 0;
850
1046
  }
1047
+ var SEAM_WINDOW = 250;
1048
+ var SEAM_MIN_TOKENS = 6;
1049
+ var SEAM_MIN_SCORE_RATIO = 0.5;
1050
+ function suffixPrefixOverlap(a, b) {
1051
+ const n = a.length;
1052
+ const m = b.length;
1053
+ if (n === 0 || m === 0) return null;
1054
+ const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
1055
+ const origin = Array.from(
1056
+ { length: n + 1 },
1057
+ () => new Array(m + 1).fill(0)
1058
+ );
1059
+ for (let i = 0; i <= n; i++) {
1060
+ dp[i][0] = 0;
1061
+ origin[i][0] = i;
1062
+ }
1063
+ for (let j = 1; j <= m; j++) {
1064
+ dp[0][j] = -j;
1065
+ origin[0][j] = 0;
1066
+ }
1067
+ for (let i = 1; i <= n; i++) {
1068
+ for (let j = 1; j <= m; j++) {
1069
+ const diag = dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 1 : -1);
1070
+ const up = dp[i - 1][j] - 1;
1071
+ const left = dp[i][j - 1] - 1;
1072
+ if (diag >= up && diag >= left) {
1073
+ dp[i][j] = diag;
1074
+ origin[i][j] = origin[i - 1][j - 1];
1075
+ } else if (up >= left) {
1076
+ dp[i][j] = up;
1077
+ origin[i][j] = origin[i - 1][j];
1078
+ } else {
1079
+ dp[i][j] = left;
1080
+ origin[i][j] = origin[i][j - 1];
1081
+ }
1082
+ }
1083
+ }
1084
+ let bestJ = 0;
1085
+ let bestScore = -Infinity;
1086
+ for (let j = 1; j <= m; j++) {
1087
+ if (dp[n][j] > bestScore) {
1088
+ bestScore = dp[n][j];
1089
+ bestJ = j;
1090
+ }
1091
+ }
1092
+ if (bestJ < SEAM_MIN_TOKENS) return null;
1093
+ if (bestScore < bestJ * SEAM_MIN_SCORE_RATIO) return null;
1094
+ return { aStart: origin[n][bestJ], bLen: bestJ };
1095
+ }
1096
+ function trimSeamOverlaps(segments) {
1097
+ const sorted = [...segments].sort((a, b) => a.start - b.start);
1098
+ const lastIdxBySpeaker = /* @__PURE__ */ new Map();
1099
+ const out = [];
1100
+ for (const seg of sorted) {
1101
+ const prevIdx = lastIdxBySpeaker.get(seg.speaker);
1102
+ const prev = prevIdx !== void 0 ? out[prevIdx] : void 0;
1103
+ if (prev && prev.words?.length && seg.words?.length) {
1104
+ const prevWin = Math.min(SEAM_WINDOW, prev.words.length);
1105
+ const prevToks = prev.words.slice(-prevWin).map((w) => tokenize(w.text)[0]?.norm ?? "");
1106
+ const segToks = seg.words.slice(0, SEAM_WINDOW).map((w) => tokenize(w.text)[0]?.norm ?? "");
1107
+ const hit = suffixPrefixOverlap(prevToks, segToks);
1108
+ if (hit) {
1109
+ const trimFrom = prev.words.length - prevWin + hit.aStart;
1110
+ const kept = prev.words.slice(0, trimFrom);
1111
+ if (kept.length === 0) {
1112
+ out[prevIdx] = null;
1113
+ } else {
1114
+ out[prevIdx] = {
1115
+ ...prev,
1116
+ words: kept,
1117
+ end: kept[kept.length - 1].end,
1118
+ text: kept.map((w) => w.text).join(" ")
1119
+ };
1120
+ }
1121
+ }
1122
+ }
1123
+ out.push(seg);
1124
+ lastIdxBySpeaker.set(seg.speaker, out.length - 1);
1125
+ }
1126
+ return out.filter((s) => s !== null);
1127
+ }
851
1128
  function dedupSegments(segments) {
852
1129
  const sorted = [...segments].sort((a, b) => a.start - b.start);
853
1130
  const kept = [];
@@ -903,7 +1180,7 @@ function clampAndFix(segments) {
903
1180
  }
904
1181
  function finalizeSegments(segments, opts = {}) {
905
1182
  const minSeg = opts.minSegmentSec ?? 0.2;
906
- let deduped = dedupSegments(segments);
1183
+ let deduped = dedupSegments(trimSeamOverlaps(segments));
907
1184
  deduped = deduped.filter((s) => s.end - s.start >= minSeg && s.text.trim().length > 0);
908
1185
  const out = deduped.map((s, i) => ({
909
1186
  id: i + 1,
@@ -925,11 +1202,17 @@ function finalizeSegments(segments, opts = {}) {
925
1202
  // src/finalize/format.ts
926
1203
  var MAX_CHARS = 84;
927
1204
  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
- }
1205
+ function compactTime(sec) {
1206
+ const s = Math.max(0, Math.floor(sec));
1207
+ const h = Math.floor(s / 3600);
1208
+ const m = Math.floor(s % 3600 / 60);
1209
+ const r = s % 60;
1210
+ const mm = m.toString().padStart(2, "0");
1211
+ const rr = r.toString().padStart(2, "0");
1212
+ return h > 0 ? `${h}:${mm}:${rr}` : `${mm}:${rr}`;
1213
+ }
1214
+ function splitByWords(seg) {
1215
+ const words = seg.words;
933
1216
  const blocks = [];
934
1217
  let curWords = [];
935
1218
  let curLen = 0;
@@ -956,6 +1239,36 @@ function splitIntoBlocks(seg) {
956
1239
  curLen += addLen;
957
1240
  }
958
1241
  flush();
1242
+ return blocks;
1243
+ }
1244
+ function splitByChars(seg) {
1245
+ const text = seg.text.trim();
1246
+ if (text.length <= MAX_CHARS) return [{ start: seg.start, end: seg.end, text }];
1247
+ const words = text.split(/\s+/);
1248
+ const lines = [];
1249
+ let cur = "";
1250
+ for (const w of words) {
1251
+ if (cur && cur.length + 1 + w.length > MAX_CHARS) {
1252
+ lines.push(cur);
1253
+ cur = w;
1254
+ } else {
1255
+ cur = cur ? `${cur} ${w}` : w;
1256
+ }
1257
+ }
1258
+ if (cur) lines.push(cur);
1259
+ const total = lines.reduce((n, l) => n + l.length, 0) || 1;
1260
+ const dur = Math.max(0, seg.end - seg.start);
1261
+ const blocks = [];
1262
+ let t = seg.start;
1263
+ for (const line of lines) {
1264
+ const span = line.length / total * dur;
1265
+ blocks.push({ start: t, end: Math.min(seg.end, t + span), text: line });
1266
+ t += span;
1267
+ }
1268
+ return blocks;
1269
+ }
1270
+ function splitIntoBlocks(seg) {
1271
+ const blocks = seg.words && seg.words.length > 0 ? splitByWords(seg) : splitByChars(seg);
959
1272
  return blocks.length ? blocks : [{ start: seg.start, end: seg.end, text: seg.text }];
960
1273
  }
961
1274
  function formatSrt(result, opts = {}) {
@@ -966,33 +1279,73 @@ function formatSrt(result, opts = {}) {
966
1279
  for (const seg of result.segments) {
967
1280
  const tone = showTone && seg.tone && seg.tone.length ? ` (${seg.tone.join(", ")})` : "";
968
1281
  const speaker = labelSpeakers ? `${seg.speakerName || seg.speaker}: ` : "";
969
- for (const b of splitIntoBlocks(seg)) {
970
- blocks.push(`${idx}
1282
+ const segBlocks = splitIntoBlocks(seg);
1283
+ for (let i = 0; i < segBlocks.length; i++) {
1284
+ const b = segBlocks[i];
1285
+ const t = i === 0 ? tone : "";
1286
+ blocks.push(
1287
+ `${idx}
971
1288
  ${formatSrtTiming(b.start, b.end)}
972
- ${speaker}${b.text}${tone}
973
- `);
1289
+ ${speaker}${b.text}${t}
1290
+ `
1291
+ );
974
1292
  idx++;
975
1293
  }
976
1294
  }
977
1295
  return blocks.join("\n");
978
1296
  }
979
- function formatMarkdown(result, opts = {}) {
1297
+ function groupBySpeaker(segments) {
1298
+ const groups = [];
1299
+ for (const seg of segments) {
1300
+ const last = groups[groups.length - 1];
1301
+ const key = (s) => s.speakerName || s.speaker;
1302
+ if (last && key(last[0]) === key(seg)) last.push(seg);
1303
+ else groups.push([seg]);
1304
+ }
1305
+ return groups;
1306
+ }
1307
+ function groupText(group, showTone) {
1308
+ const parts = [];
1309
+ let lastTone = "";
1310
+ for (const s of group) {
1311
+ const toneStr = s.tone && s.tone.length ? s.tone.join(", ") : "";
1312
+ if (showTone && toneStr && toneStr !== lastTone) {
1313
+ parts.push(`*(${toneStr})* ${s.text}`);
1314
+ } else {
1315
+ parts.push(s.text);
1316
+ }
1317
+ lastTone = toneStr;
1318
+ }
1319
+ return parts.join(" ");
1320
+ }
1321
+ function mdHeader(result, opts) {
980
1322
  const parts = [];
981
1323
  parts.push(`# ${opts.title || "Transcript"}
982
1324
  `);
983
- parts.push(`*Duration: ${Math.round(result.metadata.duration)}s \xB7 Speakers: ${result.speakers.length}*
984
- `);
1325
+ parts.push(
1326
+ `*Duration: ${formatDuration(result.metadata.duration)} \xB7 ${result.speakers.length} speakers \xB7 ${result.segments.length} turns*
1327
+ `
1328
+ );
985
1329
  parts.push("\n## Speakers\n");
986
1330
  for (const s of result.speakers) {
987
- const talk = s.talkTime ? ` (${Math.round(s.talkTime)}s)` : "";
988
- parts.push(`- **${s.name || s.id}**${talk}`);
1331
+ const talk = s.talkTime ? ` \u2014 ${formatDuration(Math.round(s.talkTime))}` : "";
1332
+ const desc = s.description ? ` \xB7 ${s.description}` : "";
1333
+ parts.push(`- **${s.name || s.id}**${talk}${desc}`);
989
1334
  }
990
1335
  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}
1336
+ return parts;
1337
+ }
1338
+ function formatMarkdown(result, opts = {}) {
1339
+ const showTone = opts.showTone ?? true;
1340
+ const timestamps = opts.timestamps ?? true;
1341
+ const style = opts.mdStyle ?? "merged";
1342
+ const parts = mdHeader(result, opts);
1343
+ const groups = style === "merged" ? groupBySpeaker(result.segments) : result.segments.map((s) => [s]);
1344
+ for (const group of groups) {
1345
+ const first = group[0];
1346
+ const ts = timestamps ? `\`[${compactTime(first.start)}]\` ` : "";
1347
+ const name = first.speakerName || first.speaker;
1348
+ parts.push(`${ts}**${name}:** ${groupText(group, showTone)}
996
1349
  `);
997
1350
  }
998
1351
  return parts.join("\n");
@@ -1026,7 +1379,18 @@ async function preprocessInBrowser(input, chunks, opts = {}) {
1026
1379
  const inExt = input.type.includes("video") ? "mp4" : "m4a";
1027
1380
  const inFile = `input.${inExt}`;
1028
1381
  await writeInput(ffmpeg, input, inFile);
1029
- await ffmpeg.exec(["-i", inFile, "-vn", "-ac", "1", "-ar", "16000", "-c:a", "flac", "audio.flac"]);
1382
+ await ffmpeg.exec([
1383
+ "-i",
1384
+ inFile,
1385
+ "-vn",
1386
+ "-ac",
1387
+ "1",
1388
+ "-ar",
1389
+ "16000",
1390
+ "-c:a",
1391
+ "flac",
1392
+ "audio.flac"
1393
+ ]);
1030
1394
  const audioData = await ffmpeg.readFile("audio.flac");
1031
1395
  const audio = new Blob([audioData], { type: "audio/flac" });
1032
1396
  const chunkBlobs = [];
@@ -1050,7 +1414,11 @@ async function preprocessInBrowser(input, chunks, opts = {}) {
1050
1414
  name
1051
1415
  ]);
1052
1416
  const data = await ffmpeg.readFile(name);
1053
- chunkBlobs.push({ data: new Blob([data], { type: "audio/flac" }), start: c.start, end: c.end });
1417
+ chunkBlobs.push({
1418
+ data: new Blob([data], { type: "audio/flac" }),
1419
+ start: c.start,
1420
+ end: c.end
1421
+ });
1054
1422
  try {
1055
1423
  await ffmpeg.deleteFile(name);
1056
1424
  } catch {
@@ -1062,7 +1430,15 @@ async function preprocessInBrowser(input, chunks, opts = {}) {
1062
1430
  for (let i = 0; i < n; i++) {
1063
1431
  const t = (i + 0.5) / n;
1064
1432
  const name = `kf_${i}.jpg`;
1065
- await ffmpeg.exec(["-i", inFile, "-ss", (t * 1).toFixed(3), "-frames:v", "1", name]);
1433
+ await ffmpeg.exec([
1434
+ "-i",
1435
+ inFile,
1436
+ "-ss",
1437
+ (t * 1).toFixed(3),
1438
+ "-frames:v",
1439
+ "1",
1440
+ name
1441
+ ]);
1066
1442
  const data = await ffmpeg.readFile(name);
1067
1443
  keyframes.push(new Blob([data], { type: "image/jpeg" }));
1068
1444
  try {
@@ -1083,7 +1459,9 @@ async function preprocessInBrowser(input, chunks, opts = {}) {
1083
1459
  async function transcribeBrowser(opts) {
1084
1460
  const model = opts.model ?? "gemini-2.5-flash";
1085
1461
  const level = opts.level ?? 2;
1086
- const asr = await new AssemblyAIFetchClient(opts.assemblyaiApiKey).transcribe(opts.audio);
1462
+ const asr = await new AssemblyAIFetchClient(opts.assemblyaiApiKey).transcribe(
1463
+ opts.audio
1464
+ );
1087
1465
  const audioBuf = await opts.audio.arrayBuffer();
1088
1466
  const gemini = new GeminiFetchClient({ apiKey: opts.geminiApiKey });
1089
1467
  const gen = await gemini.generateJson(
@@ -1100,7 +1478,11 @@ async function transcribeBrowser(opts) {
1100
1478
  let segments = cons.segments;
1101
1479
  let speakers = cons.speakers;
1102
1480
  if (level >= 3 && opts.deepseekApiKey) {
1103
- const ds = OpenAICompatClient.fromProvider("deepseek", opts.deepseekApiKey, "deepseek-chat");
1481
+ const ds = OpenAICompatClient.fromProvider(
1482
+ "deepseek",
1483
+ opts.deepseekApiKey,
1484
+ "deepseek-chat"
1485
+ );
1104
1486
  const id = await identifySpeakers(
1105
1487
  ds,
1106
1488
  "deepseek-chat",
@@ -1112,7 +1494,9 @@ async function transcribeBrowser(opts) {
1112
1494
  segments = segments.map(
1113
1495
  (s) => id.nameMap[s.speaker] ? { ...s, speakerName: id.nameMap[s.speaker] } : s
1114
1496
  );
1115
- speakers = speakers.map((sp) => id.nameMap[sp.id] ? { ...sp, name: id.nameMap[sp.id] } : sp);
1497
+ speakers = speakers.map(
1498
+ (sp) => id.nameMap[sp.id] ? { ...sp, name: id.nameMap[sp.id] } : sp
1499
+ );
1116
1500
  }
1117
1501
  const finalSegments = finalizeSegments(segments);
1118
1502
  return {
@@ -1123,9 +1507,14 @@ async function transcribeBrowser(opts) {
1123
1507
  duration: asr.durationSec,
1124
1508
  processedAt: (/* @__PURE__ */ new Date()).toISOString(),
1125
1509
  models: { transcribe: model, timestamped: "assemblyai-universal-2" },
1126
- passes: ["timestamped", "llm-transcribe", "align", "consistency", level >= 3 ? "identify" : "", "finalize"].filter(
1127
- Boolean
1128
- )
1510
+ passes: [
1511
+ "timestamped",
1512
+ "llm-transcribe",
1513
+ "align",
1514
+ "consistency",
1515
+ level >= 3 ? "identify" : "",
1516
+ "finalize"
1517
+ ].filter(Boolean)
1129
1518
  }
1130
1519
  };
1131
1520
  }