offmute-v2 0.0.5 → 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.
- package/README.md +231 -214
- package/dist/browser.browser.js +471 -82
- package/dist/browser.browser.js.map +1 -1
- package/dist/browser.d.ts +31 -7
- package/dist/cli.js +2973 -350
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1740 -163
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +71 -9
- package/dist/index.d.ts +71 -9
- package/dist/index.js +1740 -159
- package/dist/index.js.map +1 -1
- package/package.json +7 -4
- package/dist/cli.cjs +0 -2152
- package/dist/cli.cjs.map +0 -1
- package/dist/cli.d.cts +0 -1
package/dist/index.cjs
CHANGED
|
@@ -33,18 +33,21 @@ __export(src_exports, {
|
|
|
33
33
|
alignSegments: () => alignSegments,
|
|
34
34
|
assignGlobalSpeakers: () => assignGlobalSpeakers,
|
|
35
35
|
finalizeSegments: () => finalizeSegments,
|
|
36
|
+
formatHtml: () => formatHtml,
|
|
36
37
|
formatJson: () => formatJson,
|
|
37
38
|
formatMarkdown: () => formatMarkdown,
|
|
38
39
|
formatSrt: () => formatSrt,
|
|
40
|
+
formatText: () => formatText,
|
|
39
41
|
identifySpeakers: () => identifySpeakers,
|
|
40
42
|
parseSrt: () => parseSrt,
|
|
41
43
|
planChunks: () => planChunks,
|
|
44
|
+
summarizeTranscript: () => summarizeTranscript,
|
|
42
45
|
transcribe: () => transcribe
|
|
43
46
|
});
|
|
44
47
|
module.exports = __toCommonJS(src_exports);
|
|
45
48
|
|
|
46
49
|
// src/core/pipeline.ts
|
|
47
|
-
var
|
|
50
|
+
var import_node_fs5 = require("fs");
|
|
48
51
|
|
|
49
52
|
// src/core/config.ts
|
|
50
53
|
var import_node_crypto = require("crypto");
|
|
@@ -82,7 +85,10 @@ function resolveKeys(injected) {
|
|
|
82
85
|
deepseek: injected?.deepseek || env.DEEPSEEK_API_KEY,
|
|
83
86
|
groq: injected?.groq || env.GROQ_API_KEY,
|
|
84
87
|
assemblyai: injected?.assemblyai || env.ASSEMBLYAI_API_KEY,
|
|
85
|
-
anthropic: injected?.anthropic || env.ANTHROPIC_API_KEY
|
|
88
|
+
anthropic: injected?.anthropic || env.ANTHROPIC_API_KEY,
|
|
89
|
+
zai: injected?.zai || env.ZAI_API_KEY || env.GLM_API_KEY,
|
|
90
|
+
kimi: injected?.kimi || env.KIMI_API_KEY || env.MOONSHOT_API_KEY,
|
|
91
|
+
elevenlabs: injected?.elevenlabs || env.ELEVENLABS_API_KEY
|
|
86
92
|
};
|
|
87
93
|
}
|
|
88
94
|
function resolveOptions(opts) {
|
|
@@ -95,7 +101,7 @@ function resolveOptions(opts) {
|
|
|
95
101
|
knownSpeakers: opts.knownSpeakers,
|
|
96
102
|
passes: (() => {
|
|
97
103
|
const p = opts.passes ?? DEFAULT_PASSES;
|
|
98
|
-
if ((opts.diarizationLevel ??
|
|
104
|
+
if ((opts.diarizationLevel ?? 3) >= 3 && !p.includes("identify")) {
|
|
99
105
|
const out = [...p];
|
|
100
106
|
const fi = out.indexOf("finalize");
|
|
101
107
|
if (fi >= 0) out.splice(fi, 0, "identify");
|
|
@@ -110,7 +116,13 @@ function resolveOptions(opts) {
|
|
|
110
116
|
concurrency: opts.concurrency ?? 4,
|
|
111
117
|
saveIntermediates: opts.saveIntermediates ?? true,
|
|
112
118
|
formats: opts.formats ?? ["md"],
|
|
113
|
-
|
|
119
|
+
mdStyle: opts.mdStyle ?? "merged",
|
|
120
|
+
summary: opts.summary ?? false,
|
|
121
|
+
// Level 3 is the default: display names must come from the VERIFIED identify pass.
|
|
122
|
+
// (A describe-pass roster once bound names to the wrong voices and level 2 shipped
|
|
123
|
+
// them unchecked — the Jay-call flip. Level 2 now shows honest Speaker A/B labels.)
|
|
124
|
+
diarizationLevel: opts.diarizationLevel ?? 3,
|
|
125
|
+
identifyMode: opts.identifyMode ?? "dual",
|
|
114
126
|
apiKeys: opts.apiKeys,
|
|
115
127
|
model: opts.model,
|
|
116
128
|
reasoner: opts.reasoner,
|
|
@@ -119,7 +131,8 @@ function resolveOptions(opts) {
|
|
|
119
131
|
onlyChunk: opts.onlyChunk,
|
|
120
132
|
showProgress: opts.showProgress ?? true,
|
|
121
133
|
llmLog: opts.llmLog ?? true,
|
|
122
|
-
logLevel: opts.logLevel ?? "info"
|
|
134
|
+
logLevel: opts.logLevel ?? "info",
|
|
135
|
+
signal: opts.signal
|
|
123
136
|
};
|
|
124
137
|
}
|
|
125
138
|
function deriveIntermediatesDir(input) {
|
|
@@ -152,7 +165,7 @@ function configSignature(o) {
|
|
|
152
165
|
chunkDurationSec: o.chunkDurationSec ?? 600,
|
|
153
166
|
chunkOverlapSec: o.chunkOverlapSec ?? 60,
|
|
154
167
|
screenshotCount: o.screenshotCount ?? 6,
|
|
155
|
-
diarizationLevel: o.diarizationLevel ??
|
|
168
|
+
diarizationLevel: o.diarizationLevel ?? 3,
|
|
156
169
|
timestampedProvider: o.timestampedProvider ?? "assemblyai"
|
|
157
170
|
};
|
|
158
171
|
return (0, import_node_crypto.createHash)("sha1").update(JSON.stringify(relevant)).digest("hex");
|
|
@@ -187,11 +200,13 @@ function planChunks(totalDuration, chunkDuration, overlap2) {
|
|
|
187
200
|
// src/utils/logger.ts
|
|
188
201
|
var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
189
202
|
var currentLevel = "info";
|
|
203
|
+
var sink = null;
|
|
190
204
|
function setLogLevel(level) {
|
|
191
205
|
currentLevel = level;
|
|
192
206
|
}
|
|
193
207
|
function log(level, msg, extra) {
|
|
194
208
|
if (LEVELS[level] < LEVELS[currentLevel]) return;
|
|
209
|
+
if (sink && extra === void 0 && sink(level, msg)) return;
|
|
195
210
|
const ts = (/* @__PURE__ */ new Date()).toISOString().substring(11, 23);
|
|
196
211
|
const prefix = `[${ts}] ${level.toUpperCase().padEnd(5)}`;
|
|
197
212
|
if (extra !== void 0) {
|
|
@@ -205,7 +220,10 @@ var logger = {
|
|
|
205
220
|
info: (msg, extra) => log("info", msg, extra),
|
|
206
221
|
warn: (msg, extra) => log("warn", msg, extra),
|
|
207
222
|
error: (msg, extra) => log("error", msg, extra),
|
|
208
|
-
setLevel: setLogLevel
|
|
223
|
+
setLevel: setLogLevel,
|
|
224
|
+
setSink: (s) => {
|
|
225
|
+
sink = s;
|
|
226
|
+
}
|
|
209
227
|
};
|
|
210
228
|
|
|
211
229
|
// src/audio/ffmpeg.ts
|
|
@@ -418,10 +436,35 @@ var import_node_path3 = require("path");
|
|
|
418
436
|
// src/providers/llm-log.ts
|
|
419
437
|
var import_node_fs2 = require("fs");
|
|
420
438
|
var logPath = null;
|
|
439
|
+
var usageRecords = /* @__PURE__ */ new Map();
|
|
421
440
|
function setLlmLogPath(path) {
|
|
422
441
|
logPath = path ?? null;
|
|
423
442
|
}
|
|
443
|
+
function resetLlmUsage() {
|
|
444
|
+
usageRecords = /* @__PURE__ */ new Map();
|
|
445
|
+
}
|
|
446
|
+
function getLlmUsage() {
|
|
447
|
+
return [...usageRecords.values()];
|
|
448
|
+
}
|
|
424
449
|
function logLlmCall(entry) {
|
|
450
|
+
try {
|
|
451
|
+
const key = `${entry.model}|${entry.kind ?? ""}`;
|
|
452
|
+
const rec = usageRecords.get(key) ?? {
|
|
453
|
+
provider: entry.provider,
|
|
454
|
+
model: entry.model,
|
|
455
|
+
kind: entry.kind,
|
|
456
|
+
inputTokens: 0,
|
|
457
|
+
outputTokens: 0,
|
|
458
|
+
calls: 0,
|
|
459
|
+
errors: 0
|
|
460
|
+
};
|
|
461
|
+
rec.inputTokens += entry.usage?.inputTokens ?? 0;
|
|
462
|
+
rec.outputTokens += entry.usage?.outputTokens ?? 0;
|
|
463
|
+
rec.calls += 1;
|
|
464
|
+
if (entry.error) rec.errors += 1;
|
|
465
|
+
usageRecords.set(key, rec);
|
|
466
|
+
} catch {
|
|
467
|
+
}
|
|
425
468
|
if (!logPath) return;
|
|
426
469
|
try {
|
|
427
470
|
(0, import_node_fs2.appendFileSync)(logPath, JSON.stringify(entry) + "\n", { encoding: "utf-8" });
|
|
@@ -429,7 +472,39 @@ function logLlmCall(entry) {
|
|
|
429
472
|
}
|
|
430
473
|
}
|
|
431
474
|
|
|
475
|
+
// src/utils/retry.ts
|
|
476
|
+
var TRANSIENT_RE = /fetch failed|network|ENOTFOUND|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|socket|aborted|HTTP (?:429|5\d\d)|status (?:429|5\d\d)|\b(?:429|500|502|503|504)\b/i;
|
|
477
|
+
function isTransient(err) {
|
|
478
|
+
const msg = err instanceof Error ? `${err.message} ${err.cause ?? ""}` : String(err);
|
|
479
|
+
return TRANSIENT_RE.test(msg);
|
|
480
|
+
}
|
|
481
|
+
async function withRetry(label, fn, opts = {}) {
|
|
482
|
+
const retries = opts.retries ?? 5;
|
|
483
|
+
const base = opts.baseDelayMs ?? 2e3;
|
|
484
|
+
let lastErr;
|
|
485
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
486
|
+
try {
|
|
487
|
+
return await fn();
|
|
488
|
+
} catch (err) {
|
|
489
|
+
lastErr = err;
|
|
490
|
+
if (attempt === retries || !isTransient(err)) throw err;
|
|
491
|
+
const delay = base * 2 ** attempt * (0.7 + Math.random() * 0.6);
|
|
492
|
+
logger.warn(
|
|
493
|
+
`[${label}] transient failure (${err instanceof Error ? err.message : err}) \u2014 retry ${attempt + 1}/${retries} in ${(delay / 1e3).toFixed(1)}s`
|
|
494
|
+
);
|
|
495
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
throw lastErr;
|
|
499
|
+
}
|
|
500
|
+
|
|
432
501
|
// src/providers/gemini.ts
|
|
502
|
+
var SDK_KEY_WARNING = "Both GOOGLE_API_KEY and GEMINI_API_KEY are set";
|
|
503
|
+
var originalWarn = console.warn.bind(console);
|
|
504
|
+
console.warn = (...args) => {
|
|
505
|
+
if (typeof args[0] === "string" && args[0].startsWith(SDK_KEY_WARNING)) return;
|
|
506
|
+
originalWarn(...args);
|
|
507
|
+
};
|
|
433
508
|
var MIME_BY_EXT = {
|
|
434
509
|
".flac": "audio/flac",
|
|
435
510
|
".mp3": "audio/mp3",
|
|
@@ -471,11 +546,16 @@ var GeminiClient = class {
|
|
|
471
546
|
constructor(apiKey) {
|
|
472
547
|
this.ai = new import_genai.GoogleGenAI({ apiKey });
|
|
473
548
|
}
|
|
474
|
-
/** Upload a file and wait until it's done processing.
|
|
549
|
+
/** Upload a file and wait until it's done processing. Uploads ride one long HTTP
|
|
550
|
+
* request each — the retry loop in generate() doesn't cover them, and transient
|
|
551
|
+
* "fetch failed" blips here killed live runs, so they get their own retry. */
|
|
475
552
|
async upload(path, mimeType) {
|
|
476
553
|
const mt = mimeType || detectMime(path);
|
|
477
554
|
logger.debug(`[gemini] uploading ${(0, import_node_path3.basename)(path)} (${mt})...`);
|
|
478
|
-
let file = await
|
|
555
|
+
let file = await withRetry(
|
|
556
|
+
`gemini upload ${(0, import_node_path3.basename)(path)}`,
|
|
557
|
+
() => this.ai.files.upload({ file: path, config: { mimeType: mt } })
|
|
558
|
+
);
|
|
479
559
|
let tries = 0;
|
|
480
560
|
while (file.state === "PROCESSING" && tries < 120) {
|
|
481
561
|
await sleep(2e3);
|
|
@@ -554,10 +634,14 @@ var GeminiClient = class {
|
|
|
554
634
|
lastError = err instanceof Error ? err.message : String(err);
|
|
555
635
|
if (config.thinkingConfig && isThinkingConfigError(lastError)) {
|
|
556
636
|
delete config.thinkingConfig;
|
|
557
|
-
logger.warn(
|
|
637
|
+
logger.warn(
|
|
638
|
+
`[gemini] model ${model} rejected thinking config \u2014 retrying without it`
|
|
639
|
+
);
|
|
558
640
|
continue;
|
|
559
641
|
}
|
|
560
|
-
logger.warn(
|
|
642
|
+
logger.warn(
|
|
643
|
+
`[gemini] attempt ${attempt + 1}/${maxRetries} failed: ${lastError}`
|
|
644
|
+
);
|
|
561
645
|
logLlmCall({
|
|
562
646
|
ts: new Date(t0).toISOString(),
|
|
563
647
|
provider: "gemini",
|
|
@@ -573,7 +657,11 @@ var GeminiClient = class {
|
|
|
573
657
|
if (attempt < maxRetries - 1) await sleep(retryDelayMs * (attempt + 1));
|
|
574
658
|
}
|
|
575
659
|
}
|
|
576
|
-
return {
|
|
660
|
+
return {
|
|
661
|
+
text: "",
|
|
662
|
+
usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
|
|
663
|
+
error: lastError
|
|
664
|
+
};
|
|
577
665
|
} finally {
|
|
578
666
|
await this.cleanup(uploaded);
|
|
579
667
|
}
|
|
@@ -643,7 +731,10 @@ var AssemblyAIProvider = class {
|
|
|
643
731
|
return JSON.parse(await (0, import_promises2.readFile)(cachePath, "utf-8"));
|
|
644
732
|
}
|
|
645
733
|
logger.info(`[assemblyai] uploading ${filePath}...`);
|
|
646
|
-
const uploadUrl = await
|
|
734
|
+
const uploadUrl = await withRetry(
|
|
735
|
+
"assemblyai upload",
|
|
736
|
+
() => this.client.files.upload(filePath)
|
|
737
|
+
);
|
|
647
738
|
logger.info(`[assemblyai] transcribing (speech_model=${this.speechModel})...`);
|
|
648
739
|
const params = {
|
|
649
740
|
audio: uploadUrl,
|
|
@@ -651,7 +742,10 @@ var AssemblyAIProvider = class {
|
|
|
651
742
|
speech_model: this.speechModel
|
|
652
743
|
};
|
|
653
744
|
if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
|
|
654
|
-
const transcript = await
|
|
745
|
+
const transcript = await withRetry(
|
|
746
|
+
"assemblyai transcribe",
|
|
747
|
+
() => this.client.transcripts.transcribe(params)
|
|
748
|
+
);
|
|
655
749
|
if (transcript.status === "error") {
|
|
656
750
|
throw new Error(`AssemblyAI error: ${transcript.error}`);
|
|
657
751
|
}
|
|
@@ -755,9 +849,308 @@ var WhisperGroqClient = class {
|
|
|
755
849
|
}
|
|
756
850
|
};
|
|
757
851
|
|
|
852
|
+
// src/providers/elevenlabs.ts
|
|
853
|
+
var MAX_UTTERANCE_GAP_SEC = 1.5;
|
|
854
|
+
var ElevenLabsClient = class {
|
|
855
|
+
constructor(apiKey, baseUrl = "https://api.elevenlabs.io/v1") {
|
|
856
|
+
this.apiKey = apiKey;
|
|
857
|
+
this.baseUrl = baseUrl;
|
|
858
|
+
}
|
|
859
|
+
apiKey;
|
|
860
|
+
baseUrl;
|
|
861
|
+
async transcribe(audio, opts = {}) {
|
|
862
|
+
const model = opts.model ?? "scribe_v2";
|
|
863
|
+
const blob = audio instanceof Blob ? audio : new Blob([audio], { type: "audio/mpeg" });
|
|
864
|
+
const form = new FormData();
|
|
865
|
+
form.append("file", blob, "audio.mp3");
|
|
866
|
+
form.append("model_id", model);
|
|
867
|
+
form.append("timestamps_granularity", "word");
|
|
868
|
+
form.append("diarize", "true");
|
|
869
|
+
form.append("tag_audio_events", "false");
|
|
870
|
+
if (opts.numSpeakers) form.append("num_speakers", String(opts.numSpeakers));
|
|
871
|
+
for (const term of opts.keyterms ?? []) form.append("keyterms", term);
|
|
872
|
+
const data = await withRetry("elevenlabs", async () => {
|
|
873
|
+
const res = await fetch(`${this.baseUrl}/speech-to-text`, {
|
|
874
|
+
method: "POST",
|
|
875
|
+
headers: { "xi-api-key": this.apiKey },
|
|
876
|
+
body: form
|
|
877
|
+
});
|
|
878
|
+
if (!res.ok) {
|
|
879
|
+
const txt = await res.text();
|
|
880
|
+
throw new Error(`ElevenLabs Scribe ${res.status}: ${txt.slice(0, 300)}`);
|
|
881
|
+
}
|
|
882
|
+
return await res.json();
|
|
883
|
+
});
|
|
884
|
+
const words = [];
|
|
885
|
+
for (const w of data.words ?? []) {
|
|
886
|
+
if (w.type !== "word") continue;
|
|
887
|
+
if (w.start === void 0 || w.end === void 0) continue;
|
|
888
|
+
words.push({
|
|
889
|
+
text: w.text.trim(),
|
|
890
|
+
start: w.start,
|
|
891
|
+
end: w.end,
|
|
892
|
+
speaker: w.speaker_id ?? "speaker_0"
|
|
893
|
+
});
|
|
894
|
+
}
|
|
895
|
+
const utterances = [];
|
|
896
|
+
let cur = [];
|
|
897
|
+
const flush = () => {
|
|
898
|
+
if (cur.length === 0) return;
|
|
899
|
+
utterances.push({
|
|
900
|
+
speaker: cur[0].speaker,
|
|
901
|
+
start: cur[0].start,
|
|
902
|
+
end: cur[cur.length - 1].end,
|
|
903
|
+
text: cur.map((w) => w.text).join(" "),
|
|
904
|
+
words: cur.map(({ text, start, end }) => ({ text, start, end }))
|
|
905
|
+
});
|
|
906
|
+
cur = [];
|
|
907
|
+
};
|
|
908
|
+
for (const w of words) {
|
|
909
|
+
const prev = cur[cur.length - 1];
|
|
910
|
+
if (prev && (w.speaker !== prev.speaker || w.start - prev.end > MAX_UTTERANCE_GAP_SEC)) {
|
|
911
|
+
flush();
|
|
912
|
+
}
|
|
913
|
+
cur.push(w);
|
|
914
|
+
}
|
|
915
|
+
flush();
|
|
916
|
+
const speakers = [...new Set(words.map((w) => w.speaker))];
|
|
917
|
+
return {
|
|
918
|
+
utterances,
|
|
919
|
+
words: words.map(({ text, start, end }) => ({ text, start, end })),
|
|
920
|
+
durationSec: data.audio_duration_secs ?? (words.length ? words[words.length - 1].end : 0),
|
|
921
|
+
speakers,
|
|
922
|
+
hasDiarization: true,
|
|
923
|
+
transcriptId: data.transcription_id ?? `elevenlabs-${model}`
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
|
|
928
|
+
// src/core/pricing.ts
|
|
929
|
+
var PRICES_AS_OF = "2026-07";
|
|
930
|
+
var MODEL_PRICES = {
|
|
931
|
+
// Gemini (ai.google.dev/gemini-api/docs/pricing, standard tier, <=200k prompts)
|
|
932
|
+
"gemini-3.1-pro-preview": { textIn: 2, out: 12 },
|
|
933
|
+
"gemini-3-pro-preview": { textIn: 2, out: 12 },
|
|
934
|
+
"gemini-3.5-flash": { textIn: 1.5, out: 9 },
|
|
935
|
+
"gemini-3-flash-preview": { textIn: 0.5, audioIn: 1, out: 3 },
|
|
936
|
+
"gemini-2.5-pro": { textIn: 1.25, out: 10 },
|
|
937
|
+
"gemini-2.5-flash": { textIn: 0.3, audioIn: 1, out: 2.5 },
|
|
938
|
+
"gemini-2.5-flash-lite": { textIn: 0.1, audioIn: 0.3, out: 0.4 },
|
|
939
|
+
// Moving aliases — priced as their current targets.
|
|
940
|
+
"gemini-pro-latest": { textIn: 2, out: 12 },
|
|
941
|
+
"gemini-flash-latest": { textIn: 1.5, out: 9 },
|
|
942
|
+
"gemini-flash-lite-latest": { textIn: 0.25, audioIn: 0.5, out: 1.5 },
|
|
943
|
+
// Text reasoners
|
|
944
|
+
"deepseek-chat": { textIn: 0.28, out: 0.42 },
|
|
945
|
+
"deepseek-reasoner": { textIn: 0.28, out: 0.42 },
|
|
946
|
+
"gpt-4o-mini": { textIn: 0.15, out: 0.6 },
|
|
947
|
+
"glm-4.7": { textIn: 0.6, out: 2.2 }
|
|
948
|
+
};
|
|
949
|
+
var ASR_HOURLY = {
|
|
950
|
+
assemblyai: 0.15,
|
|
951
|
+
// universal-2, diarization included
|
|
952
|
+
elevenlabs: 0.4,
|
|
953
|
+
// scribe v2 (standard tier; business tier is lower)
|
|
954
|
+
"whisper-groq": 0.04,
|
|
955
|
+
// whisper-large-v3-turbo
|
|
956
|
+
none: 0
|
|
957
|
+
};
|
|
958
|
+
var AUDIO_TOKENS_PER_SEC = 32;
|
|
959
|
+
function priceFor(model) {
|
|
960
|
+
if (MODEL_PRICES[model]) return MODEL_PRICES[model];
|
|
961
|
+
const hit = Object.keys(MODEL_PRICES).find((k) => model.startsWith(k));
|
|
962
|
+
return hit ? MODEL_PRICES[hit] : null;
|
|
963
|
+
}
|
|
964
|
+
function asrCost(provider, durationSec) {
|
|
965
|
+
const hourly = ASR_HOURLY[provider];
|
|
966
|
+
if (hourly === void 0) return null;
|
|
967
|
+
return durationSec / 3600 * hourly;
|
|
968
|
+
}
|
|
969
|
+
function estimateRunCost(opts) {
|
|
970
|
+
const lines = [];
|
|
971
|
+
let total = 0;
|
|
972
|
+
let incomplete = false;
|
|
973
|
+
const p = priceFor(opts.model);
|
|
974
|
+
const chunks = Math.max(
|
|
975
|
+
1,
|
|
976
|
+
Math.ceil((opts.durationSec - opts.overlapSec) / (opts.chunkSec - opts.overlapSec))
|
|
977
|
+
);
|
|
978
|
+
const billedAudioSec = opts.durationSec + Math.max(0, chunks - 1) * opts.overlapSec + Math.min(370, opts.durationSec);
|
|
979
|
+
if (p) {
|
|
980
|
+
const audioTok = billedAudioSec * AUDIO_TOKENS_PER_SEC;
|
|
981
|
+
const promptTok = chunks * 1500;
|
|
982
|
+
const outTok = opts.durationSec / 60 * 150 + 1500;
|
|
983
|
+
const inRate = p.audioIn ?? p.textIn;
|
|
984
|
+
const llmUsd = (audioTok * inRate + promptTok * p.textIn + outTok * p.out) / 1e6;
|
|
985
|
+
total += llmUsd;
|
|
986
|
+
lines.push(
|
|
987
|
+
`${opts.model}: ${chunks} chunk${chunks > 1 ? "s" : ""} + describe \u2248 $${llmUsd.toFixed(2)}`
|
|
988
|
+
);
|
|
989
|
+
} else {
|
|
990
|
+
incomplete = true;
|
|
991
|
+
lines.push(`${opts.model}: unpriced`);
|
|
992
|
+
}
|
|
993
|
+
const asr = asrCost(opts.tsProvider, opts.durationSec);
|
|
994
|
+
if (asr !== null && opts.tsProvider !== "none") {
|
|
995
|
+
total += asr;
|
|
996
|
+
lines.push(
|
|
997
|
+
`${opts.tsProvider}: ${(opts.durationSec / 60).toFixed(0)}min \u2248 $${asr.toFixed(2)}`
|
|
998
|
+
);
|
|
999
|
+
}
|
|
1000
|
+
if (opts.identify && opts.reasoner) {
|
|
1001
|
+
const rp = priceFor(opts.reasoner);
|
|
1002
|
+
if (rp) {
|
|
1003
|
+
const idUsd = (8e3 * rp.textIn + 1e3 * rp.out) / 1e6;
|
|
1004
|
+
total += idUsd;
|
|
1005
|
+
lines.push(`${opts.reasoner} (identify) \u2248 $${idUsd.toFixed(3)}`);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
return { totalUsd: total, lines, incomplete };
|
|
1009
|
+
}
|
|
1010
|
+
function computeReceipt(usage, tsProvider, durationSec) {
|
|
1011
|
+
let llmUsd = 0;
|
|
1012
|
+
let incomplete = false;
|
|
1013
|
+
const lines = [];
|
|
1014
|
+
const perModel = {};
|
|
1015
|
+
const totals = { calls: 0, inputTokens: 0, outputTokens: 0 };
|
|
1016
|
+
const byModel = /* @__PURE__ */ new Map();
|
|
1017
|
+
for (const r of usage) {
|
|
1018
|
+
totals.calls += r.calls;
|
|
1019
|
+
totals.inputTokens += r.inputTokens;
|
|
1020
|
+
totals.outputTokens += r.outputTokens;
|
|
1021
|
+
const m = byModel.get(r.model) ?? { in: 0, out: 0, calls: 0 };
|
|
1022
|
+
m.in += r.inputTokens;
|
|
1023
|
+
m.out += r.outputTokens;
|
|
1024
|
+
m.calls += r.calls;
|
|
1025
|
+
byModel.set(r.model, m);
|
|
1026
|
+
}
|
|
1027
|
+
for (const [model, m] of byModel) {
|
|
1028
|
+
const p = priceFor(model);
|
|
1029
|
+
if (!p) {
|
|
1030
|
+
incomplete = true;
|
|
1031
|
+
lines.push(
|
|
1032
|
+
`${model}: ${m.calls} calls \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 unpriced`
|
|
1033
|
+
);
|
|
1034
|
+
continue;
|
|
1035
|
+
}
|
|
1036
|
+
const usd = (m.in * (p.audioIn ?? p.textIn) + m.out * p.out) / 1e6;
|
|
1037
|
+
llmUsd += usd;
|
|
1038
|
+
perModel[model] = usd;
|
|
1039
|
+
lines.push(
|
|
1040
|
+
`${model}: ${m.calls} call${m.calls > 1 ? "s" : ""} \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 $${usd.toFixed(2)}`
|
|
1041
|
+
);
|
|
1042
|
+
}
|
|
1043
|
+
const asrUsd = tsProvider === "none" ? 0 : asrCost(tsProvider, durationSec);
|
|
1044
|
+
if (asrUsd !== null && tsProvider !== "none") {
|
|
1045
|
+
perModel[tsProvider] = asrUsd;
|
|
1046
|
+
lines.push(
|
|
1047
|
+
`${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7 $${asrUsd.toFixed(2)}`
|
|
1048
|
+
);
|
|
1049
|
+
}
|
|
1050
|
+
return {
|
|
1051
|
+
totalUsd: llmUsd + (asrUsd ?? 0),
|
|
1052
|
+
llmUsd,
|
|
1053
|
+
asrUsd,
|
|
1054
|
+
lines,
|
|
1055
|
+
totals,
|
|
1056
|
+
perModel,
|
|
1057
|
+
incomplete
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
function fmtTok(n) {
|
|
1061
|
+
if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
|
|
1062
|
+
if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
|
|
1063
|
+
return String(n);
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
// src/core/stats.ts
|
|
1067
|
+
var import_node_fs4 = require("fs");
|
|
1068
|
+
var import_node_os2 = require("os");
|
|
1069
|
+
var import_node_path5 = require("path");
|
|
1070
|
+
function statsDir() {
|
|
1071
|
+
return process.env.OFFMUTE_HOME || (0, import_node_path5.join)((0, import_node_os2.homedir)(), ".offmute");
|
|
1072
|
+
}
|
|
1073
|
+
function statsEnabled() {
|
|
1074
|
+
return !process.env.OFFMUTE_NO_STATS;
|
|
1075
|
+
}
|
|
1076
|
+
var EMPTY = {
|
|
1077
|
+
runs: 0,
|
|
1078
|
+
mediaSeconds: 0,
|
|
1079
|
+
characters: 0,
|
|
1080
|
+
llmCalls: 0,
|
|
1081
|
+
inputTokens: 0,
|
|
1082
|
+
outputTokens: 0,
|
|
1083
|
+
costUsd: 0,
|
|
1084
|
+
costByModel: {},
|
|
1085
|
+
runsByModel: {}
|
|
1086
|
+
};
|
|
1087
|
+
function readStats() {
|
|
1088
|
+
try {
|
|
1089
|
+
const p = (0, import_node_path5.join)(statsDir(), "stats.json");
|
|
1090
|
+
if (!(0, import_node_fs4.existsSync)(p)) return { ...EMPTY };
|
|
1091
|
+
return { ...EMPTY, ...JSON.parse((0, import_node_fs4.readFileSync)(p, "utf-8")) };
|
|
1092
|
+
} catch {
|
|
1093
|
+
return { ...EMPTY };
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
function withStatsLock(dir, fn) {
|
|
1097
|
+
const lock = (0, import_node_path5.join)(dir, ".stats.lock");
|
|
1098
|
+
const deadline = Date.now() + 2e3;
|
|
1099
|
+
for (; ; ) {
|
|
1100
|
+
try {
|
|
1101
|
+
(0, import_node_fs4.mkdirSync)(lock);
|
|
1102
|
+
break;
|
|
1103
|
+
} catch {
|
|
1104
|
+
if (Date.now() > deadline) break;
|
|
1105
|
+
const until = Date.now() + 25;
|
|
1106
|
+
while (Date.now() < until) {
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
try {
|
|
1111
|
+
fn();
|
|
1112
|
+
} finally {
|
|
1113
|
+
try {
|
|
1114
|
+
(0, import_node_fs4.rmdirSync)(lock);
|
|
1115
|
+
} catch {
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
function recordRun(rec, perModelCost) {
|
|
1120
|
+
if (!statsEnabled()) return;
|
|
1121
|
+
try {
|
|
1122
|
+
const dir = statsDir();
|
|
1123
|
+
(0, import_node_fs4.mkdirSync)(dir, { recursive: true });
|
|
1124
|
+
(0, import_node_fs4.appendFileSync)((0, import_node_path5.join)(dir, "history.jsonl"), JSON.stringify(rec) + "\n");
|
|
1125
|
+
withStatsLock(dir, () => {
|
|
1126
|
+
foldIntoAggregates(rec, perModelCost, dir);
|
|
1127
|
+
});
|
|
1128
|
+
} catch {
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
function foldIntoAggregates(rec, perModelCost, dir) {
|
|
1132
|
+
const s = readStats();
|
|
1133
|
+
s.runs += 1;
|
|
1134
|
+
s.mediaSeconds += rec.durationSec;
|
|
1135
|
+
s.characters += rec.characters;
|
|
1136
|
+
s.llmCalls += rec.llmCalls;
|
|
1137
|
+
s.inputTokens += rec.inputTokens;
|
|
1138
|
+
s.outputTokens += rec.outputTokens;
|
|
1139
|
+
if (rec.costUsd !== null) s.costUsd += rec.costUsd;
|
|
1140
|
+
for (const [model, usd] of Object.entries(perModelCost)) {
|
|
1141
|
+
s.costByModel[model] = (s.costByModel[model] ?? 0) + usd;
|
|
1142
|
+
}
|
|
1143
|
+
const tModel = rec.models.transcribe;
|
|
1144
|
+
if (tModel) s.runsByModel[tModel] = (s.runsByModel[tModel] ?? 0) + 1;
|
|
1145
|
+
s.firstRun ??= rec.ts;
|
|
1146
|
+
s.lastRun = rec.ts;
|
|
1147
|
+
(0, import_node_fs4.writeFileSync)((0, import_node_path5.join)(dir, "stats.json"), JSON.stringify(s, null, 2));
|
|
1148
|
+
}
|
|
1149
|
+
|
|
758
1150
|
// src/transcribe/describe.ts
|
|
759
|
-
function descriptionPrompt(fileName, instructions) {
|
|
760
|
-
|
|
1151
|
+
function descriptionPrompt(fileName, instructions, sampleCount = 1) {
|
|
1152
|
+
const sampleNote = sampleCount > 1 ? `You are given ${sampleCount} audio samples from a longer recording \u2014 taken from the beginning, middle, and end \u2014 plus any keyframes. Speakers may appear in only one sample.` : `You are listening to a recording.`;
|
|
1153
|
+
return `${sampleNote} Your job is to prepare context for a transcription engine. Describe what you hear${instructions ? ` (note: ${instructions})` : ""}.
|
|
761
1154
|
|
|
762
1155
|
Respond in TWO sections, clearly separated by a line containing only "---":
|
|
763
1156
|
|
|
@@ -767,17 +1160,24 @@ A short paragraph: what kind of recording this is, the setting, the main topics,
|
|
|
767
1160
|
ROSTER
|
|
768
1161
|
A bulleted speaker roster. For each distinct speaker you can identify, give:
|
|
769
1162
|
- A short label to use consistently (a name/role if you can infer it, e.g. "Presenter (Hrishi)", else "Speaker A").
|
|
770
|
-
- A one-line description (
|
|
1163
|
+
- A one-line description anchored to the VOICE itself (pitch, pace, accent, audio quality/mic distance) plus role if evident.
|
|
771
1164
|
List the people you can distinguish. Do not invent names you didn't hear. If only one person speaks, say so.
|
|
772
1165
|
|
|
1166
|
+
IMPORTANT \u2014 name-to-voice binding: knowing WHO is present is not the same as knowing WHICH voice is whose. If the voices are similar (same accent, same register) or you are not certain which voice a name belongs to, say so explicitly in the roster (e.g. "one of the two voices \u2014 binding uncertain") instead of asserting it. Never describe a speaker by conversational role alone (e.g. "the primary speaker who drives the conversation") \u2014 that changes call to call and misleads downstream labeling; anchor to the voice.
|
|
1167
|
+
|
|
773
1168
|
File: ${fileName}`;
|
|
774
1169
|
}
|
|
775
|
-
async function describeMeeting(client, model, files, fileName, instructions) {
|
|
776
|
-
const res = await client.generate(
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
1170
|
+
async function describeMeeting(client, model, files, fileName, instructions, audioSampleCount = 1) {
|
|
1171
|
+
const res = await client.generate(
|
|
1172
|
+
model,
|
|
1173
|
+
descriptionPrompt(fileName, instructions, audioSampleCount),
|
|
1174
|
+
files,
|
|
1175
|
+
{
|
|
1176
|
+
temperature: 0.2,
|
|
1177
|
+
maxRetries: 3,
|
|
1178
|
+
logKind: "describe"
|
|
1179
|
+
}
|
|
1180
|
+
);
|
|
781
1181
|
const text = res.text || "";
|
|
782
1182
|
const parts = text.split(/\n---\n|\n\s*---\s*\n/);
|
|
783
1183
|
const description = parts[0]?.trim() || text.trim();
|
|
@@ -794,14 +1194,23 @@ var TRANSCRIPT_SCHEMA = {
|
|
|
794
1194
|
items: {
|
|
795
1195
|
type: "OBJECT",
|
|
796
1196
|
properties: {
|
|
797
|
-
speaker: {
|
|
798
|
-
|
|
1197
|
+
speaker: {
|
|
1198
|
+
type: "STRING",
|
|
1199
|
+
description: "Speaker label. Use an identified name from the roster if confident, else 'Speaker A', 'Speaker B', etc."
|
|
1200
|
+
},
|
|
1201
|
+
start: {
|
|
1202
|
+
type: "STRING",
|
|
1203
|
+
description: "Relative start time as mm:ss (00:00 = start of this audio chunk)"
|
|
1204
|
+
},
|
|
799
1205
|
end: { type: "STRING", description: "Relative end time as mm:ss" },
|
|
800
|
-
text: {
|
|
1206
|
+
text: {
|
|
1207
|
+
type: "STRING",
|
|
1208
|
+
description: "Verbatim transcribed words, including fillers and false starts"
|
|
1209
|
+
},
|
|
801
1210
|
tone: {
|
|
802
1211
|
type: "ARRAY",
|
|
803
1212
|
items: { type: "STRING" },
|
|
804
|
-
description: "Tone
|
|
1213
|
+
description: "Tone tags ONLY when something clearly stands out (laughing, sarcastic, agitated, whispering). Empty array for normal speech \u2014 most segments."
|
|
805
1214
|
}
|
|
806
1215
|
},
|
|
807
1216
|
required: ["speaker", "start", "end", "text"]
|
|
@@ -816,19 +1225,40 @@ function transcriptionPrompt(ctx) {
|
|
|
816
1225
|
`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.`
|
|
817
1226
|
);
|
|
818
1227
|
parts.push("");
|
|
819
|
-
parts.push(
|
|
1228
|
+
parts.push(
|
|
1229
|
+
`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.`
|
|
1230
|
+
);
|
|
820
1231
|
parts.push("");
|
|
821
1232
|
parts.push("For each segment provide:");
|
|
822
|
-
parts.push(
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
parts.push(
|
|
1233
|
+
parts.push(
|
|
1234
|
+
"- 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."
|
|
1235
|
+
);
|
|
1236
|
+
parts.push(
|
|
1237
|
+
"- 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."
|
|
1238
|
+
);
|
|
1239
|
+
parts.push(
|
|
1240
|
+
"- text: the verbatim words, including fillers (um, uh), false starts, and corrections. Do not paraphrase."
|
|
1241
|
+
);
|
|
1242
|
+
parts.push(
|
|
1243
|
+
'- 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".'
|
|
1244
|
+
);
|
|
826
1245
|
parts.push("");
|
|
827
1246
|
parts.push("Rules:");
|
|
828
|
-
parts.push(
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
parts.push(
|
|
1247
|
+
parts.push(
|
|
1248
|
+
"- Cover the ENTIRE audio with no gaps. Timestamps must be monotonic non-decreasing."
|
|
1249
|
+
);
|
|
1250
|
+
parts.push(
|
|
1251
|
+
"- Capture interruptions and overlapping talk as separate, adjacent segments even if times overlap."
|
|
1252
|
+
);
|
|
1253
|
+
parts.push(
|
|
1254
|
+
"- Listen for voice characteristics (pitch, accent, mic distance), not just content. Two people agreeing with each other are still two segments."
|
|
1255
|
+
);
|
|
1256
|
+
parts.push(
|
|
1257
|
+
"- Do not invent content not present in the audio. If inaudible, write [inaudible]."
|
|
1258
|
+
);
|
|
1259
|
+
parts.push(
|
|
1260
|
+
"- Keep speaker labels consistent within this chunk; the same voice = same label."
|
|
1261
|
+
);
|
|
832
1262
|
if (ctx.description) {
|
|
833
1263
|
parts.push("");
|
|
834
1264
|
parts.push("MEETING CONTEXT:");
|
|
@@ -836,12 +1266,20 @@ function transcriptionPrompt(ctx) {
|
|
|
836
1266
|
}
|
|
837
1267
|
if (ctx.roster) {
|
|
838
1268
|
parts.push("");
|
|
839
|
-
parts.push(
|
|
1269
|
+
parts.push(
|
|
1270
|
+
"SPEAKER ROSTER (context about who is present \u2014 but its name-to-voice binding may be wrong):"
|
|
1271
|
+
);
|
|
840
1272
|
parts.push(ctx.roster);
|
|
1273
|
+
parts.push("");
|
|
1274
|
+
parts.push(
|
|
1275
|
+
"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."
|
|
1276
|
+
);
|
|
841
1277
|
}
|
|
842
1278
|
if (ctx.previousTail) {
|
|
843
1279
|
parts.push("");
|
|
844
|
-
parts.push(
|
|
1280
|
+
parts.push(
|
|
1281
|
+
"TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):"
|
|
1282
|
+
);
|
|
845
1283
|
parts.push(ctx.previousTail);
|
|
846
1284
|
}
|
|
847
1285
|
if (ctx.instructions) {
|
|
@@ -850,7 +1288,9 @@ function transcriptionPrompt(ctx) {
|
|
|
850
1288
|
parts.push(ctx.instructions);
|
|
851
1289
|
}
|
|
852
1290
|
parts.push("");
|
|
853
|
-
parts.push(
|
|
1291
|
+
parts.push(
|
|
1292
|
+
"Return JSON matching the schema: { segments: [ {speaker, start, end, text, tone} ] }"
|
|
1293
|
+
);
|
|
854
1294
|
return parts.join("\n");
|
|
855
1295
|
}
|
|
856
1296
|
|
|
@@ -876,7 +1316,10 @@ function timestampToSeconds(timestamp) {
|
|
|
876
1316
|
function parseSrtTiming(timingString) {
|
|
877
1317
|
const parts = timingString.split("-->");
|
|
878
1318
|
if (parts.length !== 2) return null;
|
|
879
|
-
return {
|
|
1319
|
+
return {
|
|
1320
|
+
start: timestampToSeconds(parts[0].trim()),
|
|
1321
|
+
end: timestampToSeconds(parts[1].trim())
|
|
1322
|
+
};
|
|
880
1323
|
}
|
|
881
1324
|
function formatSrtTiming(startSeconds, endSeconds) {
|
|
882
1325
|
return `${secondsToTimestamp(startSeconds)} --> ${secondsToTimestamp(endSeconds)}`;
|
|
@@ -890,6 +1333,16 @@ function parseMmSs(timeStr) {
|
|
|
890
1333
|
if (seconds < 0 || seconds >= 60) return null;
|
|
891
1334
|
return minutes * 60 + seconds;
|
|
892
1335
|
}
|
|
1336
|
+
function formatDuration(seconds) {
|
|
1337
|
+
const hours = Math.floor(seconds / 3600);
|
|
1338
|
+
const minutes = Math.floor(seconds % 3600 / 60);
|
|
1339
|
+
const remaining = Math.floor(seconds % 60);
|
|
1340
|
+
const parts = [];
|
|
1341
|
+
if (hours > 0) parts.push(`${hours}h`);
|
|
1342
|
+
if (minutes > 0) parts.push(`${minutes}m`);
|
|
1343
|
+
parts.push(`${remaining}s`);
|
|
1344
|
+
return parts.join(" ");
|
|
1345
|
+
}
|
|
893
1346
|
|
|
894
1347
|
// src/transcribe/llm-transcribe.ts
|
|
895
1348
|
var MIN_SEGMENTS = 3;
|
|
@@ -913,7 +1366,9 @@ function parseLlmSegments(data, chunkOffsetSec) {
|
|
|
913
1366
|
const end = toAbsolute(seg.end, chunkOffsetSec);
|
|
914
1367
|
if (start === null || end === null || end < start) {
|
|
915
1368
|
dropped++;
|
|
916
|
-
logger.debug(
|
|
1369
|
+
logger.debug(
|
|
1370
|
+
`[llm] dropping segment (bad time ${seg.start}-${seg.end}): "${(seg.text || "").slice(0, 40)}"`
|
|
1371
|
+
);
|
|
917
1372
|
continue;
|
|
918
1373
|
}
|
|
919
1374
|
out.push({
|
|
@@ -930,16 +1385,31 @@ function parseLlmSegments(data, chunkOffsetSec) {
|
|
|
930
1385
|
}
|
|
931
1386
|
function validate(segments, chunkDuration) {
|
|
932
1387
|
if (segments.length < MIN_SEGMENTS) {
|
|
933
|
-
return {
|
|
1388
|
+
return {
|
|
1389
|
+
isValid: false,
|
|
1390
|
+
spanSec: 0,
|
|
1391
|
+
segmentCount: segments.length,
|
|
1392
|
+
message: `only ${segments.length} segments (min ${MIN_SEGMENTS})`
|
|
1393
|
+
};
|
|
934
1394
|
}
|
|
935
1395
|
const first = segments[0].startSec;
|
|
936
1396
|
const last = segments[segments.length - 1].endSec;
|
|
937
1397
|
const span = last - first;
|
|
938
1398
|
const minSpan = chunkDuration * MIN_SPAN_RATIO;
|
|
939
1399
|
if (span < minSpan) {
|
|
940
|
-
return {
|
|
1400
|
+
return {
|
|
1401
|
+
isValid: false,
|
|
1402
|
+
spanSec: span,
|
|
1403
|
+
segmentCount: segments.length,
|
|
1404
|
+
message: `span ${span.toFixed(0)}s < ${minSpan.toFixed(0)}s required (${MIN_SPAN_RATIO * 100}% of chunk)`
|
|
1405
|
+
};
|
|
941
1406
|
}
|
|
942
|
-
return {
|
|
1407
|
+
return {
|
|
1408
|
+
isValid: true,
|
|
1409
|
+
spanSec: span,
|
|
1410
|
+
segmentCount: segments.length,
|
|
1411
|
+
message: `ok (${segments.length} segments, ${span.toFixed(0)}s span)`
|
|
1412
|
+
};
|
|
943
1413
|
}
|
|
944
1414
|
async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts) {
|
|
945
1415
|
const validationRetries = opts.validationRetries ?? 1;
|
|
@@ -963,22 +1433,35 @@ async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opt
|
|
|
963
1433
|
segments: [],
|
|
964
1434
|
raw: gen.raw,
|
|
965
1435
|
usage: gen.usage,
|
|
966
|
-
validation: {
|
|
1436
|
+
validation: {
|
|
1437
|
+
isValid: false,
|
|
1438
|
+
spanSec: 0,
|
|
1439
|
+
segmentCount: 0,
|
|
1440
|
+
message: gen.error || "no data"
|
|
1441
|
+
},
|
|
967
1442
|
error: gen.error
|
|
968
1443
|
};
|
|
969
|
-
logger.warn(
|
|
1444
|
+
logger.warn(
|
|
1445
|
+
`[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`
|
|
1446
|
+
);
|
|
970
1447
|
continue;
|
|
971
1448
|
}
|
|
972
1449
|
const { segments, dropped } = parseLlmSegments(gen.data, chunkStartSec);
|
|
973
1450
|
const v = validate(segments, opts.chunkDurationSec);
|
|
974
1451
|
lastResult = { segments, raw: gen.raw, usage: gen.usage, validation: v };
|
|
975
1452
|
if (v.isValid) {
|
|
976
|
-
logger.info(
|
|
1453
|
+
logger.info(
|
|
1454
|
+
`[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`
|
|
1455
|
+
);
|
|
977
1456
|
return lastResult;
|
|
978
1457
|
}
|
|
979
|
-
logger.warn(
|
|
1458
|
+
logger.warn(
|
|
1459
|
+
`[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`
|
|
1460
|
+
);
|
|
980
1461
|
}
|
|
981
|
-
logger.error(
|
|
1462
|
+
logger.error(
|
|
1463
|
+
`[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`
|
|
1464
|
+
);
|
|
982
1465
|
return lastResult;
|
|
983
1466
|
}
|
|
984
1467
|
|
|
@@ -990,8 +1473,8 @@ function tokenize(text) {
|
|
|
990
1473
|
const out = [];
|
|
991
1474
|
for (const raw of text.split(/\s+/)) {
|
|
992
1475
|
if (!raw) continue;
|
|
993
|
-
const
|
|
994
|
-
if (
|
|
1476
|
+
const norm2 = normalize(raw);
|
|
1477
|
+
if (norm2) out.push({ original: raw, norm: norm2 });
|
|
995
1478
|
}
|
|
996
1479
|
return out;
|
|
997
1480
|
}
|
|
@@ -1115,7 +1598,11 @@ function transferTiming(llm, asr, ops) {
|
|
|
1115
1598
|
for (const op of ops) {
|
|
1116
1599
|
if (op.type === "match" || op.type === "substitute") {
|
|
1117
1600
|
const a = asr[op.asr];
|
|
1118
|
-
times[op.llm] = {
|
|
1601
|
+
times[op.llm] = {
|
|
1602
|
+
start: a.start,
|
|
1603
|
+
end: a.end,
|
|
1604
|
+
matched: op.type === "match" && !op.fuzzy
|
|
1605
|
+
};
|
|
1119
1606
|
}
|
|
1120
1607
|
}
|
|
1121
1608
|
for (let k = 0; k < times.length; k++) {
|
|
@@ -1284,7 +1771,12 @@ function fillAsrGaps(segments, asrWords, asrUtterances) {
|
|
|
1284
1771
|
tone: [],
|
|
1285
1772
|
confidence: 0,
|
|
1286
1773
|
timingSource: "timestamped",
|
|
1287
|
-
words: words.map((w) => ({
|
|
1774
|
+
words: words.map((w) => ({
|
|
1775
|
+
text: w.text,
|
|
1776
|
+
start: w.start,
|
|
1777
|
+
end: w.end,
|
|
1778
|
+
matched: true
|
|
1779
|
+
})),
|
|
1288
1780
|
sourceIndex: -1
|
|
1289
1781
|
});
|
|
1290
1782
|
}
|
|
@@ -1297,8 +1789,19 @@ function overlap(s1, e1, s2, e2) {
|
|
|
1297
1789
|
return Math.max(0, Math.min(e1, e2) - Math.max(s1, s2));
|
|
1298
1790
|
}
|
|
1299
1791
|
function isGenericLabel(label) {
|
|
1300
|
-
return /^(speaker\s+[a-z0-9]+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(
|
|
1792
|
+
return /^(speaker\s+[a-z0-9]+|voice\s+\S+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(
|
|
1793
|
+
label.trim()
|
|
1794
|
+
);
|
|
1795
|
+
}
|
|
1796
|
+
function countTurnTransitions(utterances, a, b) {
|
|
1797
|
+
const seq = [...utterances].sort((x, y) => x.start - y.start).map((u) => u.speaker).filter((s) => s === a || s === b);
|
|
1798
|
+
let transitions = 0;
|
|
1799
|
+
for (let i = 1; i < seq.length; i++) {
|
|
1800
|
+
if (seq[i] !== seq[i - 1]) transitions++;
|
|
1801
|
+
}
|
|
1802
|
+
return transitions;
|
|
1301
1803
|
}
|
|
1804
|
+
var MAX_MERGE_TRANSITIONS = 3;
|
|
1302
1805
|
function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
|
|
1303
1806
|
const hasDiarization = opts.hasDiarization ?? true;
|
|
1304
1807
|
const out = segments.map((seg) => ({ seg, asrSpeaker: "" }));
|
|
@@ -1350,7 +1853,18 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
|
|
|
1350
1853
|
const label = dominantLabel[asrSp] ?? asrSp;
|
|
1351
1854
|
let groupId;
|
|
1352
1855
|
if (!isGenericLabel(label)) {
|
|
1353
|
-
|
|
1856
|
+
const candidate = Object.keys(groupLabel).find((g) => groupLabel[g] === label);
|
|
1857
|
+
if (candidate && hasDiarization) {
|
|
1858
|
+
const partners = groupAsrVoices[candidate] ?? [];
|
|
1859
|
+
const maxTransitions = Math.max(
|
|
1860
|
+
...partners.map((p) => countTurnTransitions(asrUtterances, p, asrSp))
|
|
1861
|
+
);
|
|
1862
|
+
if (maxTransitions <= MAX_MERGE_TRANSITIONS) {
|
|
1863
|
+
groupId = candidate;
|
|
1864
|
+
}
|
|
1865
|
+
} else if (candidate) {
|
|
1866
|
+
groupId = candidate;
|
|
1867
|
+
}
|
|
1354
1868
|
}
|
|
1355
1869
|
if (!groupId) {
|
|
1356
1870
|
groupId = asrSp;
|
|
@@ -1360,15 +1874,24 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
|
|
|
1360
1874
|
groupTalk[groupId] = (groupTalk[groupId] ?? 0) + (asrDuration[asrSp] ?? 0);
|
|
1361
1875
|
(groupAsrVoices[groupId] ??= []).push(asrSp);
|
|
1362
1876
|
}
|
|
1363
|
-
const groupsByTalk = Object.keys(groupTalk).sort(
|
|
1877
|
+
const groupsByTalk = Object.keys(groupTalk).sort(
|
|
1878
|
+
(a, b) => groupTalk[b] - groupTalk[a]
|
|
1879
|
+
);
|
|
1364
1880
|
const groupToGlobal = {};
|
|
1365
1881
|
groupsByTalk.forEach((g, i) => {
|
|
1366
1882
|
groupToGlobal[g] = `Speaker ${String.fromCharCode(65 + i)}`;
|
|
1367
1883
|
});
|
|
1884
|
+
const labelGroupCount = {};
|
|
1885
|
+
for (const g of groupsByTalk) {
|
|
1886
|
+
const label = groupLabel[g];
|
|
1887
|
+
if (!isGenericLabel(label))
|
|
1888
|
+
labelGroupCount[label] = (labelGroupCount[label] ?? 0) + 1;
|
|
1889
|
+
}
|
|
1368
1890
|
const displayNames = {};
|
|
1369
1891
|
for (const g of groupsByTalk) {
|
|
1370
1892
|
const label = groupLabel[g];
|
|
1371
|
-
|
|
1893
|
+
const contested = (labelGroupCount[label] ?? 0) > 1;
|
|
1894
|
+
displayNames[groupToGlobal[g]] = isGenericLabel(label) || contested ? groupToGlobal[g] : label;
|
|
1372
1895
|
}
|
|
1373
1896
|
const llmLabelToAsr = {};
|
|
1374
1897
|
for (const o of out) {
|
|
@@ -1402,6 +1925,111 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
|
|
|
1402
1925
|
return { segments: updated, speakers, displayNames, llmLabelToAsr };
|
|
1403
1926
|
}
|
|
1404
1927
|
|
|
1928
|
+
// src/diarize/split-mixed.ts
|
|
1929
|
+
var MIN_RUN_WORDS = 5;
|
|
1930
|
+
var MIN_RUN_SEC = 2;
|
|
1931
|
+
function clusterAt(utterances, t) {
|
|
1932
|
+
let best = "";
|
|
1933
|
+
let bestDist = Infinity;
|
|
1934
|
+
for (const u of utterances) {
|
|
1935
|
+
if (t >= u.start && t <= u.end) return u.speaker;
|
|
1936
|
+
const d = t < u.start ? u.start - t : t - u.end;
|
|
1937
|
+
if (d < bestDist) {
|
|
1938
|
+
bestDist = d;
|
|
1939
|
+
best = u.speaker;
|
|
1940
|
+
}
|
|
1941
|
+
}
|
|
1942
|
+
return best;
|
|
1943
|
+
}
|
|
1944
|
+
function buildRuns(words, utterances) {
|
|
1945
|
+
const clusters = words.map(
|
|
1946
|
+
(w) => w.matched ? clusterAt(utterances, (w.start + w.end) / 2) : null
|
|
1947
|
+
);
|
|
1948
|
+
for (let i = 1; i < clusters.length; i++) {
|
|
1949
|
+
if (clusters[i] === null) clusters[i] = clusters[i - 1] ?? null;
|
|
1950
|
+
}
|
|
1951
|
+
for (let i = clusters.length - 2; i >= 0; i--) {
|
|
1952
|
+
if (clusters[i] === null) clusters[i] = clusters[i + 1] ?? null;
|
|
1953
|
+
}
|
|
1954
|
+
const runs = [];
|
|
1955
|
+
for (let i = 0; i < clusters.length; i++) {
|
|
1956
|
+
const c = clusters[i] ?? "";
|
|
1957
|
+
const last = runs[runs.length - 1];
|
|
1958
|
+
if (last && last.cluster === c) last.endIdx = i + 1;
|
|
1959
|
+
else runs.push({ cluster: c, startIdx: i, endIdx: i + 1 });
|
|
1960
|
+
}
|
|
1961
|
+
return runs;
|
|
1962
|
+
}
|
|
1963
|
+
function runSec(run2, words) {
|
|
1964
|
+
return words[run2.endIdx - 1].end - words[run2.startIdx].start;
|
|
1965
|
+
}
|
|
1966
|
+
function foldShortRuns(runs, words) {
|
|
1967
|
+
let out = runs;
|
|
1968
|
+
let changed = true;
|
|
1969
|
+
while (changed && out.length > 1) {
|
|
1970
|
+
changed = false;
|
|
1971
|
+
for (let i = 0; i < out.length; i++) {
|
|
1972
|
+
const r = out[i];
|
|
1973
|
+
const nWords = r.endIdx - r.startIdx;
|
|
1974
|
+
if (nWords >= MIN_RUN_WORDS || runSec(r, words) >= MIN_RUN_SEC) continue;
|
|
1975
|
+
const prev = out[i - 1];
|
|
1976
|
+
const next = out[i + 1];
|
|
1977
|
+
const target = prev && next ? prev.endIdx - prev.startIdx >= next.endIdx - next.startIdx ? prev : next : prev ?? next;
|
|
1978
|
+
if (!target) continue;
|
|
1979
|
+
if (target === prev) prev.endIdx = r.endIdx;
|
|
1980
|
+
else next.startIdx = r.startIdx;
|
|
1981
|
+
out = out.filter((_, j) => j !== i);
|
|
1982
|
+
changed = true;
|
|
1983
|
+
break;
|
|
1984
|
+
}
|
|
1985
|
+
const merged = [];
|
|
1986
|
+
for (const r of out) {
|
|
1987
|
+
const last = merged[merged.length - 1];
|
|
1988
|
+
if (last && last.cluster === r.cluster) last.endIdx = r.endIdx;
|
|
1989
|
+
else merged.push({ ...r });
|
|
1990
|
+
}
|
|
1991
|
+
out = merged;
|
|
1992
|
+
}
|
|
1993
|
+
return out;
|
|
1994
|
+
}
|
|
1995
|
+
function splitMixedVoiceSegments(segments, utterances) {
|
|
1996
|
+
if (utterances.length === 0) return segments;
|
|
1997
|
+
const out = [];
|
|
1998
|
+
let splits = 0;
|
|
1999
|
+
for (const seg of segments) {
|
|
2000
|
+
const matched = seg.words.filter((w) => w.matched).length;
|
|
2001
|
+
if (seg.words.length < MIN_RUN_WORDS * 2 || matched < seg.words.length * 0.4) {
|
|
2002
|
+
out.push(seg);
|
|
2003
|
+
continue;
|
|
2004
|
+
}
|
|
2005
|
+
const runs = foldShortRuns(buildRuns(seg.words, utterances), seg.words);
|
|
2006
|
+
if (runs.length <= 1) {
|
|
2007
|
+
out.push(seg);
|
|
2008
|
+
continue;
|
|
2009
|
+
}
|
|
2010
|
+
splits += runs.length - 1;
|
|
2011
|
+
const lens = runs.map((r) => r.endIdx - r.startIdx);
|
|
2012
|
+
const dominantIdx = lens.indexOf(Math.max(...lens));
|
|
2013
|
+
runs.forEach((run2, ri) => {
|
|
2014
|
+
const words = seg.words.slice(run2.startIdx, run2.endIdx);
|
|
2015
|
+
out.push({
|
|
2016
|
+
...seg,
|
|
2017
|
+
start: words[0].start,
|
|
2018
|
+
end: words[words.length - 1].end,
|
|
2019
|
+
text: words.map((w) => w.text).join(" "),
|
|
2020
|
+
words,
|
|
2021
|
+
speaker: ri === dominantIdx ? seg.speaker : `Voice ${run2.cluster}`
|
|
2022
|
+
});
|
|
2023
|
+
});
|
|
2024
|
+
}
|
|
2025
|
+
if (splits > 0) {
|
|
2026
|
+
logger.info(
|
|
2027
|
+
`split ${splits} mixed-voice boundary(ies) across ${segments.length} segments`
|
|
2028
|
+
);
|
|
2029
|
+
}
|
|
2030
|
+
return out.sort((a, b) => a.start - b.start);
|
|
2031
|
+
}
|
|
2032
|
+
|
|
1405
2033
|
// src/providers/openai-compat.ts
|
|
1406
2034
|
var PROVIDER_BASE = {
|
|
1407
2035
|
deepseek: "https://api.deepseek.com/v1",
|
|
@@ -1425,7 +2053,7 @@ var OpenAICompatClient = class _OpenAICompatClient {
|
|
|
1425
2053
|
}
|
|
1426
2054
|
async chat(model, messages, opts = {}) {
|
|
1427
2055
|
const m = model ?? this.defaultModel;
|
|
1428
|
-
const maxRetries = opts.maxRetries ??
|
|
2056
|
+
const maxRetries = opts.maxRetries ?? 5;
|
|
1429
2057
|
const body = {
|
|
1430
2058
|
model: m,
|
|
1431
2059
|
messages,
|
|
@@ -1435,6 +2063,9 @@ var OpenAICompatClient = class _OpenAICompatClient {
|
|
|
1435
2063
|
if (opts.responseJson) {
|
|
1436
2064
|
body.response_format = { type: "json_object" };
|
|
1437
2065
|
}
|
|
2066
|
+
if (this.providerName === "gemini") {
|
|
2067
|
+
body.reasoning_effort = "low";
|
|
2068
|
+
}
|
|
1438
2069
|
let lastError;
|
|
1439
2070
|
const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
|
|
1440
2071
|
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
@@ -1472,6 +2103,14 @@ var OpenAICompatClient = class _OpenAICompatClient {
|
|
|
1472
2103
|
return { text, usage };
|
|
1473
2104
|
} catch (err) {
|
|
1474
2105
|
lastError = err instanceof Error ? err.message : String(err);
|
|
2106
|
+
if (body.response_format && /response_format/i.test(lastError)) {
|
|
2107
|
+
delete body.response_format;
|
|
2108
|
+
continue;
|
|
2109
|
+
}
|
|
2110
|
+
if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
|
|
2111
|
+
delete body.reasoning_effort;
|
|
2112
|
+
continue;
|
|
2113
|
+
}
|
|
1475
2114
|
logLlmCall({
|
|
1476
2115
|
ts: new Date(t0).toISOString(),
|
|
1477
2116
|
provider: this.providerName,
|
|
@@ -1483,61 +2122,109 @@ var OpenAICompatClient = class _OpenAICompatClient {
|
|
|
1483
2122
|
attempt: attempt + 1,
|
|
1484
2123
|
error: lastError
|
|
1485
2124
|
});
|
|
1486
|
-
if (attempt < maxRetries - 1)
|
|
2125
|
+
if (attempt < maxRetries - 1)
|
|
2126
|
+
await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
|
|
1487
2127
|
}
|
|
1488
2128
|
}
|
|
1489
2129
|
return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
|
|
1490
2130
|
}
|
|
1491
2131
|
async chatJson(model, messages, opts = {}) {
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
2132
|
+
let lastRaw = "";
|
|
2133
|
+
let lastError;
|
|
2134
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
2135
|
+
const res = await this.chat(model, messages, { ...opts, responseJson: true });
|
|
2136
|
+
lastRaw = res.text;
|
|
2137
|
+
lastError = res.error;
|
|
2138
|
+
if (res.error || !res.text) continue;
|
|
2139
|
+
try {
|
|
2140
|
+
let txt = res.text.trim();
|
|
2141
|
+
const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
|
|
2142
|
+
if (fence && fence[1]) txt = fence[1];
|
|
2143
|
+
return { data: JSON.parse(txt), raw: res.text };
|
|
2144
|
+
} catch (err) {
|
|
2145
|
+
lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
|
|
2146
|
+
}
|
|
1501
2147
|
}
|
|
2148
|
+
return { data: null, raw: lastRaw, error: lastError };
|
|
1502
2149
|
}
|
|
1503
2150
|
};
|
|
1504
2151
|
|
|
1505
2152
|
// src/diarize/identify.ts
|
|
2153
|
+
var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
|
|
1506
2154
|
function buildTranscriptExcerpt(segments, speakers) {
|
|
2155
|
+
const speakerHeader = (sp) => {
|
|
2156
|
+
const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
|
|
2157
|
+
return `${sp.id} (${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s talk time${voices})`;
|
|
2158
|
+
};
|
|
2159
|
+
const totalChars = segments.reduce((n, s) => n + s.text.length, 0);
|
|
2160
|
+
if (totalChars <= MAX_FULL_TRANSCRIPT_CHARS) {
|
|
2161
|
+
const parts2 = [
|
|
2162
|
+
"SPEAKERS:",
|
|
2163
|
+
...speakers.map((sp) => `- ${speakerHeader(sp)}`),
|
|
2164
|
+
"",
|
|
2165
|
+
"FULL TRANSCRIPT (in order):"
|
|
2166
|
+
];
|
|
2167
|
+
for (const s of segments) parts2.push(`[${s.speaker}] ${s.text}`);
|
|
2168
|
+
return parts2.join("\n");
|
|
2169
|
+
}
|
|
1507
2170
|
const bySpeaker = {};
|
|
1508
2171
|
for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
|
|
1509
2172
|
const parts = [];
|
|
1510
2173
|
for (const sp of speakers) {
|
|
1511
2174
|
const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
|
|
1512
|
-
|
|
1513
|
-
parts.push(
|
|
1514
|
-
`### ${sp.id} (${sp.name || "unknown"}, ${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s${voices})`
|
|
1515
|
-
);
|
|
2175
|
+
parts.push(`### ${speakerHeader(sp)}`);
|
|
1516
2176
|
for (const s of segs) parts.push(` ${s.text}`);
|
|
1517
2177
|
}
|
|
1518
2178
|
return parts.join("\n");
|
|
1519
2179
|
}
|
|
1520
|
-
function identifyPrompt(transcriptExcerpt, roster, knownSpeakers) {
|
|
1521
|
-
|
|
2180
|
+
function identifyPrompt(transcriptExcerpt, roster, knownSpeakers, nameHints, sourceFileName) {
|
|
2181
|
+
const hintBlock = nameHints && Object.keys(nameHints).length ? `
|
|
2182
|
+
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):
|
|
2183
|
+
${Object.entries(
|
|
2184
|
+
nameHints
|
|
2185
|
+
).map(([id, n]) => ` ${id} was tentatively called "${n}"`).join("\n")}
|
|
2186
|
+
` : "";
|
|
2187
|
+
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.
|
|
1522
2188
|
|
|
1523
2189
|
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 ("").
|
|
1524
2190
|
|
|
2191
|
+
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.
|
|
2192
|
+
|
|
2193
|
+
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.
|
|
2194
|
+
|
|
2195
|
+
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).
|
|
2196
|
+
|
|
1525
2197
|
${knownSpeakers && knownSpeakers.length ? `Known possible speakers: ${knownSpeakers.join(", ")}
|
|
2198
|
+
` : ""}${sourceFileName ? `RECORDING FILENAME (often names participants): ${sourceFileName}
|
|
1526
2199
|
` : ""}ROSTER:
|
|
1527
2200
|
${roster}
|
|
1528
|
-
|
|
1529
|
-
TRANSCRIPT
|
|
2201
|
+
${hintBlock}
|
|
2202
|
+
TRANSCRIPT:
|
|
1530
2203
|
${transcriptExcerpt}
|
|
1531
2204
|
|
|
1532
|
-
Respond as JSON: { "speakers": [ { "id": "<exact speaker id from the headers>", "name": "Full Name or Role", "confidence": "high|medium|low", "evidence": "short quote
|
|
1533
|
-
Use the EXACT speaker id strings
|
|
2205
|
+
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" }
|
|
2206
|
+
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.`;
|
|
1534
2207
|
}
|
|
1535
|
-
async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers) {
|
|
2208
|
+
async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers, nameHints, sourceFileName) {
|
|
1536
2209
|
const excerpt = buildTranscriptExcerpt(segments, speakers);
|
|
1537
2210
|
const { data, error } = await client.chatJson(
|
|
1538
2211
|
model,
|
|
1539
|
-
[
|
|
1540
|
-
|
|
2212
|
+
[
|
|
2213
|
+
{
|
|
2214
|
+
role: "user",
|
|
2215
|
+
content: identifyPrompt(
|
|
2216
|
+
excerpt,
|
|
2217
|
+
roster,
|
|
2218
|
+
knownSpeakers,
|
|
2219
|
+
nameHints,
|
|
2220
|
+
sourceFileName
|
|
2221
|
+
)
|
|
2222
|
+
}
|
|
2223
|
+
],
|
|
2224
|
+
// 8000 tokens: verbose models quote long verbatim evidence, and Gemini's compat
|
|
2225
|
+
// endpoint spends part of the budget on thinking — tighter caps truncated
|
|
2226
|
+
// mid-JSON and silently emptied whole identify passes (observed live, twice).
|
|
2227
|
+
{ temperature: 0.1, maxTokens: 8e3, logKind: "identify" }
|
|
1541
2228
|
);
|
|
1542
2229
|
if (error || !data) {
|
|
1543
2230
|
return { nameMap: {}, speakers: [], reasoning: error || "no response" };
|
|
@@ -1549,6 +2236,368 @@ async function identifySpeakers(client, model, segments, speakers, roster, known
|
|
|
1549
2236
|
return { nameMap, speakers: data.speakers || [], reasoning: data.reasoning || "" };
|
|
1550
2237
|
}
|
|
1551
2238
|
|
|
2239
|
+
// src/diarize/identify2.ts
|
|
2240
|
+
var norm = (s) => s.toLowerCase().replace(/['’]/g, "").replace(/[^\p{L}\p{N}\s]/gu, " ").replace(/\s+/g, " ").trim();
|
|
2241
|
+
function withinOneEdit(a, b) {
|
|
2242
|
+
if (a === b) return true;
|
|
2243
|
+
if (Math.abs(a.length - b.length) > 1) return false;
|
|
2244
|
+
const [s, l] = a.length <= b.length ? [a, b] : [b, a];
|
|
2245
|
+
let i = 0;
|
|
2246
|
+
let j = 0;
|
|
2247
|
+
let edits = 0;
|
|
2248
|
+
while (i < s.length && j < l.length) {
|
|
2249
|
+
if (s[i] === l[j]) {
|
|
2250
|
+
i++;
|
|
2251
|
+
j++;
|
|
2252
|
+
continue;
|
|
2253
|
+
}
|
|
2254
|
+
if (++edits > 1) return false;
|
|
2255
|
+
if (s.length === l.length) i++;
|
|
2256
|
+
j++;
|
|
2257
|
+
}
|
|
2258
|
+
return edits + (l.length - j) <= 1;
|
|
2259
|
+
}
|
|
2260
|
+
function tokensMatch(a, b) {
|
|
2261
|
+
if (a === b) return true;
|
|
2262
|
+
return a.length >= 5 && b.length >= 5 && withinOneEdit(a, b);
|
|
2263
|
+
}
|
|
2264
|
+
function namesMatch(a, b) {
|
|
2265
|
+
const na = norm(a);
|
|
2266
|
+
const nb = norm(b);
|
|
2267
|
+
if (!na || !nb) return false;
|
|
2268
|
+
if (na === nb) return true;
|
|
2269
|
+
const ta = na.split(" ");
|
|
2270
|
+
const tb = nb.split(" ");
|
|
2271
|
+
const [small, big] = ta.length <= tb.length ? [ta, tb] : [tb, ta];
|
|
2272
|
+
return small.every((t) => big.some((u) => tokensMatch(t, u)));
|
|
2273
|
+
}
|
|
2274
|
+
function evidenceInTranscript(evidence, transcript) {
|
|
2275
|
+
if (!evidence) return false;
|
|
2276
|
+
const ne = norm(evidence);
|
|
2277
|
+
if (ne.length < 8) return false;
|
|
2278
|
+
return transcript.includes(ne);
|
|
2279
|
+
}
|
|
2280
|
+
var INTRO_RE = /\b(?:[Mm]y name is|I am|I'm)[,\s]+([A-Z][\p{L}'’-]+(?:\s+[A-Z][\p{L}'’-]+)?)/gu;
|
|
2281
|
+
var INTRO_STOPWORDS = /* @__PURE__ */ new Set([
|
|
2282
|
+
"i",
|
|
2283
|
+
"im",
|
|
2284
|
+
"ive",
|
|
2285
|
+
"id",
|
|
2286
|
+
"ill",
|
|
2287
|
+
"you",
|
|
2288
|
+
"we",
|
|
2289
|
+
"they",
|
|
2290
|
+
"he",
|
|
2291
|
+
"she",
|
|
2292
|
+
"it",
|
|
2293
|
+
"so",
|
|
2294
|
+
"not",
|
|
2295
|
+
"just",
|
|
2296
|
+
"here",
|
|
2297
|
+
"there",
|
|
2298
|
+
"going",
|
|
2299
|
+
"gonna",
|
|
2300
|
+
"really",
|
|
2301
|
+
"very",
|
|
2302
|
+
"also",
|
|
2303
|
+
"still",
|
|
2304
|
+
"sure",
|
|
2305
|
+
"sorry",
|
|
2306
|
+
"happy",
|
|
2307
|
+
"glad",
|
|
2308
|
+
"excited",
|
|
2309
|
+
"curious",
|
|
2310
|
+
"the",
|
|
2311
|
+
"a",
|
|
2312
|
+
"an",
|
|
2313
|
+
"okay",
|
|
2314
|
+
"ok",
|
|
2315
|
+
"now",
|
|
2316
|
+
"like",
|
|
2317
|
+
"actually",
|
|
2318
|
+
"basically",
|
|
2319
|
+
"kind",
|
|
2320
|
+
"sort",
|
|
2321
|
+
"definitely"
|
|
2322
|
+
]);
|
|
2323
|
+
function findSelfIntroductions(segments) {
|
|
2324
|
+
const out = [];
|
|
2325
|
+
for (const seg of segments) {
|
|
2326
|
+
for (const m of seg.text.matchAll(INTRO_RE)) {
|
|
2327
|
+
const name = m[1].trim();
|
|
2328
|
+
const tokens = name.split(/\s+/).map((t) => t.toLowerCase().replace(/['’]/g, ""));
|
|
2329
|
+
if (tokens.some((t) => INTRO_STOPWORDS.has(t))) continue;
|
|
2330
|
+
if (name.replace(/[^\p{L}]/gu, "").length < 3) continue;
|
|
2331
|
+
out.push({
|
|
2332
|
+
speakerId: seg.speaker,
|
|
2333
|
+
introducedName: name,
|
|
2334
|
+
segmentText: seg.text.slice(0, 160)
|
|
2335
|
+
});
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
return out;
|
|
2339
|
+
}
|
|
2340
|
+
function pickCompleteName(a, b) {
|
|
2341
|
+
if (!a) return b ?? "";
|
|
2342
|
+
if (!b) return a;
|
|
2343
|
+
return b.trim().split(/\s+/).length > a.trim().split(/\s+/).length ? b.trim() : a.trim();
|
|
2344
|
+
}
|
|
2345
|
+
function adjudicate(speakerId, a, b, transcriptNorm, intro, introCorroborated = false) {
|
|
2346
|
+
const base = {
|
|
2347
|
+
speakerId,
|
|
2348
|
+
nameA: a.name,
|
|
2349
|
+
nameB: b?.name,
|
|
2350
|
+
outcome: "kept-generic"
|
|
2351
|
+
};
|
|
2352
|
+
const aName = a.name?.trim() || void 0;
|
|
2353
|
+
const bName = b?.name?.trim() || void 0;
|
|
2354
|
+
if (b === void 0) {
|
|
2355
|
+
if (!aName) return base;
|
|
2356
|
+
return { ...base, outcome: "a-only", finalName: aName };
|
|
2357
|
+
}
|
|
2358
|
+
if (aName && bName && namesMatch(aName, bName)) {
|
|
2359
|
+
return { ...base, outcome: "agreed", finalName: pickCompleteName(aName, bName) };
|
|
2360
|
+
}
|
|
2361
|
+
if (intro) {
|
|
2362
|
+
if (aName && namesMatch(aName, intro))
|
|
2363
|
+
return { ...base, outcome: "tripwire", finalName: aName, note: `intro "${intro}"` };
|
|
2364
|
+
if (bName && namesMatch(bName, intro))
|
|
2365
|
+
return { ...base, outcome: "tripwire", finalName: bName, note: `intro "${intro}"` };
|
|
2366
|
+
if (introCorroborated) {
|
|
2367
|
+
return {
|
|
2368
|
+
...base,
|
|
2369
|
+
outcome: "tripwire",
|
|
2370
|
+
finalName: intro,
|
|
2371
|
+
note: `intro "${intro}" corroborated by roster/known speakers`
|
|
2372
|
+
};
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
if (aName && !bName) return { ...base, outcome: "a-only", finalName: aName };
|
|
2376
|
+
if (bName && !aName) return { ...base, outcome: "b-only", finalName: bName };
|
|
2377
|
+
const aOk = evidenceInTranscript(a.evidence, transcriptNorm);
|
|
2378
|
+
const bOk = evidenceInTranscript(b.evidence, transcriptNorm);
|
|
2379
|
+
if (aOk && !bOk)
|
|
2380
|
+
return {
|
|
2381
|
+
...base,
|
|
2382
|
+
outcome: "evidence-break",
|
|
2383
|
+
finalName: aName,
|
|
2384
|
+
note: "B evidence not in transcript"
|
|
2385
|
+
};
|
|
2386
|
+
if (bOk && !aOk)
|
|
2387
|
+
return {
|
|
2388
|
+
...base,
|
|
2389
|
+
outcome: "evidence-break",
|
|
2390
|
+
finalName: bName,
|
|
2391
|
+
note: "A evidence not in transcript"
|
|
2392
|
+
};
|
|
2393
|
+
return {
|
|
2394
|
+
...base,
|
|
2395
|
+
outcome: "kept-generic",
|
|
2396
|
+
note: "disagreement unresolved \u2014 not inventing a name"
|
|
2397
|
+
};
|
|
2398
|
+
}
|
|
2399
|
+
async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts) {
|
|
2400
|
+
const mode = opts.mode ?? "dual";
|
|
2401
|
+
const runPass = (r) => identifySpeakers(
|
|
2402
|
+
r.client,
|
|
2403
|
+
r.model,
|
|
2404
|
+
segments,
|
|
2405
|
+
speakers,
|
|
2406
|
+
opts.roster,
|
|
2407
|
+
opts.knownSpeakers,
|
|
2408
|
+
opts.nameHints,
|
|
2409
|
+
opts.sourceFileName
|
|
2410
|
+
);
|
|
2411
|
+
const wantB = mode === "dual" && reasonerB !== null;
|
|
2412
|
+
const [resA, resB] = await Promise.all([
|
|
2413
|
+
runPass(reasonerA),
|
|
2414
|
+
wantB ? runPass(reasonerB) : Promise.resolve(void 0)
|
|
2415
|
+
]);
|
|
2416
|
+
const passFailed = (r) => !!r && r.speakers.length === 0 && /fetch failed|HTTP \d|network|ENOTFOUND|JSON parse|no response/i.test(r.reasoning);
|
|
2417
|
+
if (passFailed(resA) && (!wantB || passFailed(resB))) {
|
|
2418
|
+
logger.warn(
|
|
2419
|
+
`identify: ALL passes failed (${resA.reasoning.slice(0, 80)}) \u2014 speakers left as generic labels. Re-run to retry naming cheaply (everything else is cached).`
|
|
2420
|
+
);
|
|
2421
|
+
}
|
|
2422
|
+
const transcriptNorm = norm(segments.map((s) => s.text).join(" "));
|
|
2423
|
+
const tripwires = findSelfIntroductions(segments);
|
|
2424
|
+
const introBySpeaker = /* @__PURE__ */ new Map();
|
|
2425
|
+
const conflicted = /* @__PURE__ */ new Set();
|
|
2426
|
+
for (const t of tripwires) {
|
|
2427
|
+
const prev = introBySpeaker.get(t.speakerId);
|
|
2428
|
+
if (prev && !namesMatch(prev, t.introducedName)) conflicted.add(t.speakerId);
|
|
2429
|
+
else introBySpeaker.set(t.speakerId, t.introducedName);
|
|
2430
|
+
}
|
|
2431
|
+
for (const id of conflicted) introBySpeaker.delete(id);
|
|
2432
|
+
const byIdA = new Map(resA.speakers.map((s) => [s.id, s]));
|
|
2433
|
+
const byIdB = resB ? new Map(resB.speakers.map((s) => [s.id, s])) : void 0;
|
|
2434
|
+
const decisions = [];
|
|
2435
|
+
const corroborationText = norm(
|
|
2436
|
+
`${opts.roster ?? ""} ${(opts.knownSpeakers ?? []).join(" ")}`
|
|
2437
|
+
);
|
|
2438
|
+
const isCorroborated = (name) => {
|
|
2439
|
+
if (!name) return false;
|
|
2440
|
+
const n = norm(name);
|
|
2441
|
+
return n.length >= 3 && corroborationText.includes(n);
|
|
2442
|
+
};
|
|
2443
|
+
const nameMap = {};
|
|
2444
|
+
for (const sp of speakers) {
|
|
2445
|
+
const a = byIdA.get(sp.id) ?? { name: resA.nameMap[sp.id] };
|
|
2446
|
+
const b = byIdB ? byIdB.get(sp.id) ?? { name: resB.nameMap[sp.id] } : void 0;
|
|
2447
|
+
const intro = introBySpeaker.get(sp.id);
|
|
2448
|
+
const d = adjudicate(
|
|
2449
|
+
sp.id,
|
|
2450
|
+
a ?? {},
|
|
2451
|
+
wantB ? b ?? {} : void 0,
|
|
2452
|
+
transcriptNorm,
|
|
2453
|
+
intro,
|
|
2454
|
+
isCorroborated(intro)
|
|
2455
|
+
);
|
|
2456
|
+
decisions.push(d);
|
|
2457
|
+
if (d.finalName) nameMap[sp.id] = d.finalName;
|
|
2458
|
+
}
|
|
2459
|
+
const STRENGTH = {
|
|
2460
|
+
agreed: 4,
|
|
2461
|
+
tripwire: 3,
|
|
2462
|
+
"evidence-break": 2,
|
|
2463
|
+
"a-only": 1,
|
|
2464
|
+
"b-only": 1,
|
|
2465
|
+
elimination: 1,
|
|
2466
|
+
"conflict-fallback": 0,
|
|
2467
|
+
"kept-generic": 0
|
|
2468
|
+
};
|
|
2469
|
+
const named = decisions.filter((d) => d.finalName);
|
|
2470
|
+
for (let i = 0; i < named.length; i++) {
|
|
2471
|
+
for (let j = i + 1; j < named.length; j++) {
|
|
2472
|
+
const di = named[i];
|
|
2473
|
+
const dj = named[j];
|
|
2474
|
+
if (!di.finalName || !dj.finalName) continue;
|
|
2475
|
+
if (!namesMatch(di.finalName, dj.finalName)) continue;
|
|
2476
|
+
const si = STRENGTH[di.outcome];
|
|
2477
|
+
const sj = STRENGTH[dj.outcome];
|
|
2478
|
+
const losers = si === sj ? [di, dj] : si < sj ? [di] : [dj];
|
|
2479
|
+
for (const loser of losers) {
|
|
2480
|
+
loser.note = `demoted: "${loser.finalName}" also claimed by another speaker with ${si === sj ? "equal" : "stronger"} evidence`;
|
|
2481
|
+
loser.finalName = void 0;
|
|
2482
|
+
loser.outcome = "conflict-fallback";
|
|
2483
|
+
delete nameMap[loser.speakerId];
|
|
2484
|
+
}
|
|
2485
|
+
}
|
|
2486
|
+
}
|
|
2487
|
+
if (opts.knownSpeakers?.length) {
|
|
2488
|
+
const unusedNames = opts.knownSpeakers.filter(
|
|
2489
|
+
(n) => !decisions.some((d) => d.finalName && namesMatch(d.finalName, n))
|
|
2490
|
+
);
|
|
2491
|
+
const unnamed = decisions.filter((d) => !d.finalName);
|
|
2492
|
+
if (unusedNames.length === 1 && unnamed.length === 1) {
|
|
2493
|
+
const d = unnamed[0];
|
|
2494
|
+
d.finalName = unusedNames[0];
|
|
2495
|
+
d.outcome = "elimination";
|
|
2496
|
+
d.note = `only remaining known speaker`;
|
|
2497
|
+
nameMap[d.speakerId] = d.finalName;
|
|
2498
|
+
logger.info(
|
|
2499
|
+
`identify: "${d.speakerId}" \u2192 ${d.finalName} (by elimination from --speakers)`
|
|
2500
|
+
);
|
|
2501
|
+
}
|
|
2502
|
+
}
|
|
2503
|
+
for (const d of decisions) {
|
|
2504
|
+
if (d.outcome === "conflict-fallback") {
|
|
2505
|
+
logger.info(`identify: "${d.speakerId}" kept generic \u2014 ${d.note}`);
|
|
2506
|
+
}
|
|
2507
|
+
if (d.outcome === "kept-generic" && (d.nameA || d.nameB)) {
|
|
2508
|
+
logger.info(
|
|
2509
|
+
`identify: kept "${d.speakerId}" generic \u2014 passes disagreed (${d.nameA ?? "\u2014"} vs ${d.nameB ?? "\u2014"})`
|
|
2510
|
+
);
|
|
2511
|
+
} else if (d.outcome === "tripwire") {
|
|
2512
|
+
logger.info(
|
|
2513
|
+
`identify: "${d.speakerId}" \u2192 ${d.finalName} (self-introduction tripwire)`
|
|
2514
|
+
);
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
return {
|
|
2518
|
+
nameMap,
|
|
2519
|
+
decisions,
|
|
2520
|
+
tripwires,
|
|
2521
|
+
passA: { ...resA, model: reasonerA.model },
|
|
2522
|
+
passB: resB ? { ...resB, model: reasonerB.model } : void 0
|
|
2523
|
+
};
|
|
2524
|
+
}
|
|
2525
|
+
|
|
2526
|
+
// src/providers/reasoner.ts
|
|
2527
|
+
var PROVIDERS = {
|
|
2528
|
+
deepseek: { baseUrl: "https://api.deepseek.com/v1", keyName: "deepseek" },
|
|
2529
|
+
openai: { baseUrl: "https://api.openai.com/v1", keyName: "openai" },
|
|
2530
|
+
groq: { baseUrl: "https://api.groq.com/openai/v1", keyName: "groq" },
|
|
2531
|
+
gemini: {
|
|
2532
|
+
baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai",
|
|
2533
|
+
keyName: "gemini"
|
|
2534
|
+
},
|
|
2535
|
+
zai: { baseUrl: "https://api.z.ai/api/paas/v4", keyName: "zai" },
|
|
2536
|
+
kimi: { baseUrl: "https://api.moonshot.ai/v1", keyName: "kimi" },
|
|
2537
|
+
anthropic: { baseUrl: "https://api.anthropic.com/v1", keyName: "anthropic" }
|
|
2538
|
+
};
|
|
2539
|
+
function inferProvider(model) {
|
|
2540
|
+
const m = model.toLowerCase();
|
|
2541
|
+
if (m.startsWith("deepseek")) return "deepseek";
|
|
2542
|
+
if (m.startsWith("gemini") || m.startsWith("gemma")) return "gemini";
|
|
2543
|
+
if (m.startsWith("glm")) return "zai";
|
|
2544
|
+
if (m.startsWith("kimi") || m.startsWith("moonshot")) return "kimi";
|
|
2545
|
+
if (m.startsWith("claude")) return "anthropic";
|
|
2546
|
+
if (m.startsWith("gpt") || m.startsWith("o1") || m.startsWith("o3") || m.startsWith("o4"))
|
|
2547
|
+
return "openai";
|
|
2548
|
+
if (m.includes("llama") || m.includes("mixtral")) return "groq";
|
|
2549
|
+
return "openai";
|
|
2550
|
+
}
|
|
2551
|
+
function resolveReasonerInfo(spec) {
|
|
2552
|
+
let provider;
|
|
2553
|
+
let model;
|
|
2554
|
+
const colon = spec.indexOf(":");
|
|
2555
|
+
if (colon > 0 && PROVIDERS[spec.slice(0, colon)]) {
|
|
2556
|
+
provider = spec.slice(0, colon);
|
|
2557
|
+
model = spec.slice(colon + 1);
|
|
2558
|
+
} else {
|
|
2559
|
+
model = spec;
|
|
2560
|
+
provider = inferProvider(spec);
|
|
2561
|
+
}
|
|
2562
|
+
const p = PROVIDERS[provider] ?? PROVIDERS.openai;
|
|
2563
|
+
return { provider, model, keyName: p.keyName, baseUrl: p.baseUrl };
|
|
2564
|
+
}
|
|
2565
|
+
function reasonerKey(info, keys) {
|
|
2566
|
+
if (info.keyName === "gemini") return keys.gemini || keys.google;
|
|
2567
|
+
return keys[info.keyName];
|
|
2568
|
+
}
|
|
2569
|
+
function resolveReasoner(spec, keys) {
|
|
2570
|
+
const candidates = [spec, "deepseek-chat", "gemini-flash-latest"].filter(
|
|
2571
|
+
(s) => !!s
|
|
2572
|
+
);
|
|
2573
|
+
for (const c of candidates) {
|
|
2574
|
+
const info = resolveReasonerInfo(c);
|
|
2575
|
+
const key = reasonerKey(info, keys);
|
|
2576
|
+
if (key) {
|
|
2577
|
+
return {
|
|
2578
|
+
client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
|
|
2579
|
+
info
|
|
2580
|
+
};
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
return null;
|
|
2584
|
+
}
|
|
2585
|
+
function resolveSecondReasoner(first, keys) {
|
|
2586
|
+
const candidates = ["gemini-flash-latest", "deepseek-chat", "glm-4.7", "gpt-4o-mini"];
|
|
2587
|
+
for (const c of candidates) {
|
|
2588
|
+
const info = resolveReasonerInfo(c);
|
|
2589
|
+
if (info.provider === first.provider) continue;
|
|
2590
|
+
const key = reasonerKey(info, keys);
|
|
2591
|
+
if (key) {
|
|
2592
|
+
return {
|
|
2593
|
+
client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
|
|
2594
|
+
info
|
|
2595
|
+
};
|
|
2596
|
+
}
|
|
2597
|
+
}
|
|
2598
|
+
return null;
|
|
2599
|
+
}
|
|
2600
|
+
|
|
1552
2601
|
// src/finalize/finalize.ts
|
|
1553
2602
|
var MIN_DUR = 0.5;
|
|
1554
2603
|
var MAX_DUR = 7;
|
|
@@ -1567,6 +2616,87 @@ function timeOverlapFrac(a, b) {
|
|
|
1567
2616
|
const shorter = Math.min(a.end - a.start, b.end - b.start);
|
|
1568
2617
|
return shorter > 0 ? ov / shorter : 0;
|
|
1569
2618
|
}
|
|
2619
|
+
var SEAM_WINDOW = 250;
|
|
2620
|
+
var SEAM_MIN_TOKENS = 6;
|
|
2621
|
+
var SEAM_MIN_SCORE_RATIO = 0.5;
|
|
2622
|
+
function suffixPrefixOverlap(a, b) {
|
|
2623
|
+
const n = a.length;
|
|
2624
|
+
const m = b.length;
|
|
2625
|
+
if (n === 0 || m === 0) return null;
|
|
2626
|
+
const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
|
|
2627
|
+
const origin = Array.from(
|
|
2628
|
+
{ length: n + 1 },
|
|
2629
|
+
() => new Array(m + 1).fill(0)
|
|
2630
|
+
);
|
|
2631
|
+
for (let i = 0; i <= n; i++) {
|
|
2632
|
+
dp[i][0] = 0;
|
|
2633
|
+
origin[i][0] = i;
|
|
2634
|
+
}
|
|
2635
|
+
for (let j = 1; j <= m; j++) {
|
|
2636
|
+
dp[0][j] = -j;
|
|
2637
|
+
origin[0][j] = 0;
|
|
2638
|
+
}
|
|
2639
|
+
for (let i = 1; i <= n; i++) {
|
|
2640
|
+
for (let j = 1; j <= m; j++) {
|
|
2641
|
+
const diag = dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 1 : -1);
|
|
2642
|
+
const up = dp[i - 1][j] - 1;
|
|
2643
|
+
const left = dp[i][j - 1] - 1;
|
|
2644
|
+
if (diag >= up && diag >= left) {
|
|
2645
|
+
dp[i][j] = diag;
|
|
2646
|
+
origin[i][j] = origin[i - 1][j - 1];
|
|
2647
|
+
} else if (up >= left) {
|
|
2648
|
+
dp[i][j] = up;
|
|
2649
|
+
origin[i][j] = origin[i - 1][j];
|
|
2650
|
+
} else {
|
|
2651
|
+
dp[i][j] = left;
|
|
2652
|
+
origin[i][j] = origin[i][j - 1];
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
}
|
|
2656
|
+
let bestJ = 0;
|
|
2657
|
+
let bestScore = -Infinity;
|
|
2658
|
+
for (let j = 1; j <= m; j++) {
|
|
2659
|
+
if (dp[n][j] > bestScore) {
|
|
2660
|
+
bestScore = dp[n][j];
|
|
2661
|
+
bestJ = j;
|
|
2662
|
+
}
|
|
2663
|
+
}
|
|
2664
|
+
if (bestJ < SEAM_MIN_TOKENS) return null;
|
|
2665
|
+
if (bestScore < bestJ * SEAM_MIN_SCORE_RATIO) return null;
|
|
2666
|
+
return { aStart: origin[n][bestJ], bLen: bestJ };
|
|
2667
|
+
}
|
|
2668
|
+
function trimSeamOverlaps(segments) {
|
|
2669
|
+
const sorted = [...segments].sort((a, b) => a.start - b.start);
|
|
2670
|
+
const lastIdxBySpeaker = /* @__PURE__ */ new Map();
|
|
2671
|
+
const out = [];
|
|
2672
|
+
for (const seg of sorted) {
|
|
2673
|
+
const prevIdx = lastIdxBySpeaker.get(seg.speaker);
|
|
2674
|
+
const prev = prevIdx !== void 0 ? out[prevIdx] : void 0;
|
|
2675
|
+
if (prev && prev.words?.length && seg.words?.length) {
|
|
2676
|
+
const prevWin = Math.min(SEAM_WINDOW, prev.words.length);
|
|
2677
|
+
const prevToks = prev.words.slice(-prevWin).map((w) => tokenize(w.text)[0]?.norm ?? "");
|
|
2678
|
+
const segToks = seg.words.slice(0, SEAM_WINDOW).map((w) => tokenize(w.text)[0]?.norm ?? "");
|
|
2679
|
+
const hit = suffixPrefixOverlap(prevToks, segToks);
|
|
2680
|
+
if (hit) {
|
|
2681
|
+
const trimFrom = prev.words.length - prevWin + hit.aStart;
|
|
2682
|
+
const kept = prev.words.slice(0, trimFrom);
|
|
2683
|
+
if (kept.length === 0) {
|
|
2684
|
+
out[prevIdx] = null;
|
|
2685
|
+
} else {
|
|
2686
|
+
out[prevIdx] = {
|
|
2687
|
+
...prev,
|
|
2688
|
+
words: kept,
|
|
2689
|
+
end: kept[kept.length - 1].end,
|
|
2690
|
+
text: kept.map((w) => w.text).join(" ")
|
|
2691
|
+
};
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
2694
|
+
}
|
|
2695
|
+
out.push(seg);
|
|
2696
|
+
lastIdxBySpeaker.set(seg.speaker, out.length - 1);
|
|
2697
|
+
}
|
|
2698
|
+
return out.filter((s) => s !== null);
|
|
2699
|
+
}
|
|
1570
2700
|
function dedupSegments(segments) {
|
|
1571
2701
|
const sorted = [...segments].sort((a, b) => a.start - b.start);
|
|
1572
2702
|
const kept = [];
|
|
@@ -1622,7 +2752,7 @@ function clampAndFix(segments) {
|
|
|
1622
2752
|
}
|
|
1623
2753
|
function finalizeSegments(segments, opts = {}) {
|
|
1624
2754
|
const minSeg = opts.minSegmentSec ?? 0.2;
|
|
1625
|
-
let deduped = dedupSegments(segments);
|
|
2755
|
+
let deduped = dedupSegments(trimSeamOverlaps(segments));
|
|
1626
2756
|
deduped = deduped.filter((s) => s.end - s.start >= minSeg && s.text.trim().length > 0);
|
|
1627
2757
|
const out = deduped.map((s, i) => ({
|
|
1628
2758
|
id: i + 1,
|
|
@@ -1644,11 +2774,17 @@ function finalizeSegments(segments, opts = {}) {
|
|
|
1644
2774
|
// src/finalize/format.ts
|
|
1645
2775
|
var MAX_CHARS = 84;
|
|
1646
2776
|
var MAX_BLOCK_SEC = 7;
|
|
1647
|
-
function
|
|
1648
|
-
const
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
2777
|
+
function compactTime(sec) {
|
|
2778
|
+
const s = Math.max(0, Math.floor(sec));
|
|
2779
|
+
const h = Math.floor(s / 3600);
|
|
2780
|
+
const m = Math.floor(s % 3600 / 60);
|
|
2781
|
+
const r = s % 60;
|
|
2782
|
+
const mm = m.toString().padStart(2, "0");
|
|
2783
|
+
const rr = r.toString().padStart(2, "0");
|
|
2784
|
+
return h > 0 ? `${h}:${mm}:${rr}` : `${mm}:${rr}`;
|
|
2785
|
+
}
|
|
2786
|
+
function splitByWords(seg) {
|
|
2787
|
+
const words = seg.words;
|
|
1652
2788
|
const blocks = [];
|
|
1653
2789
|
let curWords = [];
|
|
1654
2790
|
let curLen = 0;
|
|
@@ -1675,6 +2811,36 @@ function splitIntoBlocks(seg) {
|
|
|
1675
2811
|
curLen += addLen;
|
|
1676
2812
|
}
|
|
1677
2813
|
flush();
|
|
2814
|
+
return blocks;
|
|
2815
|
+
}
|
|
2816
|
+
function splitByChars(seg) {
|
|
2817
|
+
const text = seg.text.trim();
|
|
2818
|
+
if (text.length <= MAX_CHARS) return [{ start: seg.start, end: seg.end, text }];
|
|
2819
|
+
const words = text.split(/\s+/);
|
|
2820
|
+
const lines = [];
|
|
2821
|
+
let cur = "";
|
|
2822
|
+
for (const w of words) {
|
|
2823
|
+
if (cur && cur.length + 1 + w.length > MAX_CHARS) {
|
|
2824
|
+
lines.push(cur);
|
|
2825
|
+
cur = w;
|
|
2826
|
+
} else {
|
|
2827
|
+
cur = cur ? `${cur} ${w}` : w;
|
|
2828
|
+
}
|
|
2829
|
+
}
|
|
2830
|
+
if (cur) lines.push(cur);
|
|
2831
|
+
const total = lines.reduce((n, l) => n + l.length, 0) || 1;
|
|
2832
|
+
const dur = Math.max(0, seg.end - seg.start);
|
|
2833
|
+
const blocks = [];
|
|
2834
|
+
let t = seg.start;
|
|
2835
|
+
for (const line of lines) {
|
|
2836
|
+
const span = line.length / total * dur;
|
|
2837
|
+
blocks.push({ start: t, end: Math.min(seg.end, t + span), text: line });
|
|
2838
|
+
t += span;
|
|
2839
|
+
}
|
|
2840
|
+
return blocks;
|
|
2841
|
+
}
|
|
2842
|
+
function splitIntoBlocks(seg) {
|
|
2843
|
+
const blocks = seg.words && seg.words.length > 0 ? splitByWords(seg) : splitByChars(seg);
|
|
1678
2844
|
return blocks.length ? blocks : [{ start: seg.start, end: seg.end, text: seg.text }];
|
|
1679
2845
|
}
|
|
1680
2846
|
function formatSrt(result, opts = {}) {
|
|
@@ -1685,54 +2851,247 @@ function formatSrt(result, opts = {}) {
|
|
|
1685
2851
|
for (const seg of result.segments) {
|
|
1686
2852
|
const tone = showTone && seg.tone && seg.tone.length ? ` (${seg.tone.join(", ")})` : "";
|
|
1687
2853
|
const speaker = labelSpeakers ? `${seg.speakerName || seg.speaker}: ` : "";
|
|
1688
|
-
|
|
1689
|
-
|
|
2854
|
+
const segBlocks = splitIntoBlocks(seg);
|
|
2855
|
+
for (let i = 0; i < segBlocks.length; i++) {
|
|
2856
|
+
const b = segBlocks[i];
|
|
2857
|
+
const t = i === 0 ? tone : "";
|
|
2858
|
+
blocks.push(
|
|
2859
|
+
`${idx}
|
|
1690
2860
|
${formatSrtTiming(b.start, b.end)}
|
|
1691
|
-
${speaker}${b.text}${
|
|
1692
|
-
`
|
|
2861
|
+
${speaker}${b.text}${t}
|
|
2862
|
+
`
|
|
2863
|
+
);
|
|
1693
2864
|
idx++;
|
|
1694
2865
|
}
|
|
1695
2866
|
}
|
|
1696
2867
|
return blocks.join("\n");
|
|
1697
2868
|
}
|
|
1698
|
-
function
|
|
2869
|
+
function groupBySpeaker(segments) {
|
|
2870
|
+
const groups = [];
|
|
2871
|
+
for (const seg of segments) {
|
|
2872
|
+
const last = groups[groups.length - 1];
|
|
2873
|
+
const key = (s) => s.speakerName || s.speaker;
|
|
2874
|
+
if (last && key(last[0]) === key(seg)) last.push(seg);
|
|
2875
|
+
else groups.push([seg]);
|
|
2876
|
+
}
|
|
2877
|
+
return groups;
|
|
2878
|
+
}
|
|
2879
|
+
function groupText(group, showTone) {
|
|
2880
|
+
const parts = [];
|
|
2881
|
+
let lastTone = "";
|
|
2882
|
+
for (const s of group) {
|
|
2883
|
+
const toneStr = s.tone && s.tone.length ? s.tone.join(", ") : "";
|
|
2884
|
+
if (showTone && toneStr && toneStr !== lastTone) {
|
|
2885
|
+
parts.push(`*(${toneStr})* ${s.text}`);
|
|
2886
|
+
} else {
|
|
2887
|
+
parts.push(s.text);
|
|
2888
|
+
}
|
|
2889
|
+
lastTone = toneStr;
|
|
2890
|
+
}
|
|
2891
|
+
return parts.join(" ");
|
|
2892
|
+
}
|
|
2893
|
+
function mdHeader(result, opts) {
|
|
1699
2894
|
const parts = [];
|
|
1700
2895
|
parts.push(`# ${opts.title || "Transcript"}
|
|
1701
2896
|
`);
|
|
1702
|
-
parts.push(
|
|
1703
|
-
|
|
2897
|
+
parts.push(
|
|
2898
|
+
`*Duration: ${formatDuration(result.metadata.duration)} \xB7 ${result.speakers.length} speakers \xB7 ${result.segments.length} turns*
|
|
2899
|
+
`
|
|
2900
|
+
);
|
|
1704
2901
|
parts.push("\n## Speakers\n");
|
|
1705
2902
|
for (const s of result.speakers) {
|
|
1706
|
-
const talk = s.talkTime ? `
|
|
1707
|
-
|
|
2903
|
+
const talk = s.talkTime ? ` \u2014 ${formatDuration(Math.round(s.talkTime))}` : "";
|
|
2904
|
+
const desc = s.description ? ` \xB7 ${s.description}` : "";
|
|
2905
|
+
parts.push(`- **${s.name || s.id}**${talk}${desc}`);
|
|
1708
2906
|
}
|
|
1709
2907
|
parts.push("\n## Transcript\n");
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
2908
|
+
return parts;
|
|
2909
|
+
}
|
|
2910
|
+
function formatMarkdown(result, opts = {}) {
|
|
2911
|
+
const showTone = opts.showTone ?? true;
|
|
2912
|
+
const timestamps = opts.timestamps ?? true;
|
|
2913
|
+
const style = opts.mdStyle ?? "merged";
|
|
2914
|
+
const parts = mdHeader(result, opts);
|
|
2915
|
+
const groups = style === "merged" ? groupBySpeaker(result.segments) : result.segments.map((s) => [s]);
|
|
2916
|
+
for (const group of groups) {
|
|
2917
|
+
const first = group[0];
|
|
2918
|
+
const ts = timestamps ? `\`[${compactTime(first.start)}]\` ` : "";
|
|
2919
|
+
const name = first.speakerName || first.speaker;
|
|
2920
|
+
parts.push(`${ts}**${name}:** ${groupText(group, showTone)}
|
|
1715
2921
|
`);
|
|
1716
2922
|
}
|
|
1717
2923
|
return parts.join("\n");
|
|
1718
2924
|
}
|
|
2925
|
+
function formatText(result, opts = {}) {
|
|
2926
|
+
const timestamps = opts.timestamps ?? true;
|
|
2927
|
+
const showTone = opts.showTone ?? false;
|
|
2928
|
+
const lines = [];
|
|
2929
|
+
for (const group of groupBySpeaker(result.segments)) {
|
|
2930
|
+
const first = group[0];
|
|
2931
|
+
const ts = timestamps ? `[${compactTime(first.start)}] ` : "";
|
|
2932
|
+
const name = first.speakerName || first.speaker;
|
|
2933
|
+
const text = group.map(
|
|
2934
|
+
(s) => showTone && s.tone?.length ? `(${s.tone.join(", ")}) ${s.text}` : s.text
|
|
2935
|
+
).join(" ");
|
|
2936
|
+
lines.push(`${ts}${name}: ${text}`);
|
|
2937
|
+
}
|
|
2938
|
+
return lines.join("\n\n") + "\n";
|
|
2939
|
+
}
|
|
1719
2940
|
function formatJson(result) {
|
|
1720
2941
|
return JSON.stringify(result, null, 2);
|
|
1721
2942
|
}
|
|
1722
2943
|
|
|
2944
|
+
// src/finalize/html.ts
|
|
2945
|
+
var PALETTE = [
|
|
2946
|
+
"#2563eb",
|
|
2947
|
+
"#059669",
|
|
2948
|
+
"#d97706",
|
|
2949
|
+
"#dc2626",
|
|
2950
|
+
"#7c3aed",
|
|
2951
|
+
"#0891b2",
|
|
2952
|
+
"#be185d",
|
|
2953
|
+
"#4d7c0f",
|
|
2954
|
+
"#b45309",
|
|
2955
|
+
"#6d28d9"
|
|
2956
|
+
];
|
|
2957
|
+
var esc = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
2958
|
+
function groupBySpeaker2(segments) {
|
|
2959
|
+
const groups = [];
|
|
2960
|
+
for (const seg of segments) {
|
|
2961
|
+
const last = groups[groups.length - 1];
|
|
2962
|
+
const key = (s) => s.speakerName || s.speaker;
|
|
2963
|
+
if (last && key(last[0]) === key(seg)) last.push(seg);
|
|
2964
|
+
else groups.push([seg]);
|
|
2965
|
+
}
|
|
2966
|
+
return groups;
|
|
2967
|
+
}
|
|
2968
|
+
function formatHtml(result, opts = {}) {
|
|
2969
|
+
const title = opts.title || "Transcript";
|
|
2970
|
+
const colorOf = /* @__PURE__ */ new Map();
|
|
2971
|
+
result.speakers.forEach((sp, i) => {
|
|
2972
|
+
colorOf.set(sp.name || sp.id, PALETTE[i % PALETTE.length]);
|
|
2973
|
+
});
|
|
2974
|
+
const color = (name) => colorOf.get(name) ?? "#64748b";
|
|
2975
|
+
const legend = result.speakers.map((sp) => {
|
|
2976
|
+
const name = sp.name || sp.id;
|
|
2977
|
+
const talk = sp.talkTime ? ` \xB7 ${formatDuration(Math.round(sp.talkTime))}` : "";
|
|
2978
|
+
return `<span class="who"><i style="background:${color(name)}"></i>${esc(name)}<small>${talk}</small></span>`;
|
|
2979
|
+
}).join("");
|
|
2980
|
+
const paragraphs = groupBySpeaker2(result.segments).map((group) => {
|
|
2981
|
+
const first = group[0];
|
|
2982
|
+
const name = first.speakerName || first.speaker;
|
|
2983
|
+
let lastTone = "";
|
|
2984
|
+
const body = group.map((s) => {
|
|
2985
|
+
const toneStr = s.tone?.length ? s.tone.join(", ") : "";
|
|
2986
|
+
const badge = toneStr && toneStr !== lastTone ? `<em class="tone">${esc(toneStr)}</em> ` : "";
|
|
2987
|
+
lastTone = toneStr;
|
|
2988
|
+
return `${badge}${esc(s.text)}`;
|
|
2989
|
+
}).join(" ");
|
|
2990
|
+
return `<div class="turn" style="border-color:${color(name)}">
|
|
2991
|
+
<div class="meta"><b style="color:${color(name)}">${esc(name)}</b><time data-t="${compactTime(first.start)}" title="click to copy">${compactTime(first.start)}</time></div>
|
|
2992
|
+
<p>${body}</p>
|
|
2993
|
+
</div>`;
|
|
2994
|
+
}).join("\n");
|
|
2995
|
+
const m = result.metadata;
|
|
2996
|
+
const cost = m.cost ? ` \xB7 ~$${m.cost.actualUsd.toFixed(2)}` : "";
|
|
2997
|
+
const footer = `${esc(m.models.transcribe ?? "")} + ${esc(m.models.timestamped ?? "")}${cost} \xB7 ${new Date(m.processedAt).toLocaleDateString()}`;
|
|
2998
|
+
return `<!doctype html>
|
|
2999
|
+
<html lang="en">
|
|
3000
|
+
<meta charset="utf-8">
|
|
3001
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
3002
|
+
<title>${esc(title)}</title>
|
|
3003
|
+
<style>
|
|
3004
|
+
:root{--bg:#ffffff;--fg:#1e293b;--muted:#64748b;--line:#e2e8f0;--chip:#f1f5f9}
|
|
3005
|
+
@media(prefers-color-scheme:dark){:root{--bg:#0f172a;--fg:#e2e8f0;--muted:#94a3b8;--line:#1e293b;--chip:#1e293b}}
|
|
3006
|
+
*{box-sizing:border-box}
|
|
3007
|
+
body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
|
|
3008
|
+
main{max-width:760px;margin:0 auto;padding:2rem 1.25rem 4rem}
|
|
3009
|
+
h1{font-size:1.5rem;margin:0 0 .25rem}
|
|
3010
|
+
.sub{color:var(--muted);font-size:.9rem;margin-bottom:1rem}
|
|
3011
|
+
header.legend{position:sticky;top:0;background:var(--bg);padding:.6rem 0;border-bottom:1px solid var(--line);display:flex;flex-wrap:wrap;gap:.4rem .9rem;z-index:1}
|
|
3012
|
+
.who{display:inline-flex;align-items:center;gap:.4rem;font-size:.85rem}
|
|
3013
|
+
.who i{width:.65rem;height:.65rem;border-radius:50%;display:inline-block}
|
|
3014
|
+
.who small{color:var(--muted)}
|
|
3015
|
+
.turn{border-left:3px solid;padding:.15rem 0 .15rem 1rem;margin:1.1rem 0}
|
|
3016
|
+
.turn .meta{display:flex;align-items:baseline;gap:.6rem;font-size:.85rem}
|
|
3017
|
+
.turn time{color:var(--muted);font-family:ui-monospace,Menlo,monospace;font-size:.78rem;cursor:pointer}
|
|
3018
|
+
.turn time:hover{text-decoration:underline}
|
|
3019
|
+
.turn p{margin:.25rem 0 0}
|
|
3020
|
+
.tone{background:var(--chip);color:var(--muted);border-radius:.5rem;padding:0 .45rem;font-size:.75rem;font-style:italic;white-space:nowrap}
|
|
3021
|
+
footer{margin-top:3rem;color:var(--muted);font-size:.8rem;border-top:1px solid var(--line);padding-top:1rem}
|
|
3022
|
+
</style>
|
|
3023
|
+
<main>
|
|
3024
|
+
<h1>${esc(title)}</h1>
|
|
3025
|
+
<div class="sub">${formatDuration(m.duration)} \xB7 ${result.speakers.length} speakers \xB7 ${result.segments.length} turns</div>
|
|
3026
|
+
<header class="legend">${legend}</header>
|
|
3027
|
+
${paragraphs}
|
|
3028
|
+
<footer>${footer}</footer>
|
|
3029
|
+
</main>
|
|
3030
|
+
<script>
|
|
3031
|
+
document.querySelectorAll("time").forEach(t=>t.addEventListener("click",()=>{
|
|
3032
|
+
navigator.clipboard&&navigator.clipboard.writeText(t.dataset.t);
|
|
3033
|
+
const o=t.textContent;t.textContent="copied";setTimeout(()=>t.textContent=o,700);
|
|
3034
|
+
}));
|
|
3035
|
+
</script>
|
|
3036
|
+
</html>
|
|
3037
|
+
`;
|
|
3038
|
+
}
|
|
3039
|
+
|
|
3040
|
+
// src/finalize/summary.ts
|
|
3041
|
+
function summaryPrompt(result, instructions) {
|
|
3042
|
+
const lines = result.segments.map((s) => {
|
|
3043
|
+
const name = s.speakerName || s.speaker;
|
|
3044
|
+
return `[${compactTime(s.start)}] ${name}: ${s.text}`;
|
|
3045
|
+
});
|
|
3046
|
+
return `Below is a diarized meeting transcript. Write a summary in clean markdown with these sections (omit a section entirely if there is nothing for it):
|
|
3047
|
+
|
|
3048
|
+
## TL;DR
|
|
3049
|
+
2-4 sentences. What was this, what mattered.
|
|
3050
|
+
|
|
3051
|
+
## Decisions
|
|
3052
|
+
Bullet list of decisions actually made (not topics discussed). Attribute who decided when clear.
|
|
3053
|
+
|
|
3054
|
+
## Action items
|
|
3055
|
+
Bullet list, "**Owner** \u2014 action" format. Only real commitments, with the timestamp in [mm:ss].
|
|
3056
|
+
|
|
3057
|
+
## By speaker
|
|
3058
|
+
One short paragraph per speaker: their main points and positions.
|
|
3059
|
+
|
|
3060
|
+
## Open questions
|
|
3061
|
+
Things raised but not resolved.
|
|
3062
|
+
|
|
3063
|
+
Be specific and quote sparingly. Do not invent content.${instructions ? `
|
|
3064
|
+
|
|
3065
|
+
Additional instructions: ${instructions}` : ""}
|
|
3066
|
+
|
|
3067
|
+
TRANSCRIPT:
|
|
3068
|
+
${lines.join("\n")}`;
|
|
3069
|
+
}
|
|
3070
|
+
async function summarizeTranscript(client, model, result, instructions) {
|
|
3071
|
+
const res = await client.chat(
|
|
3072
|
+
model,
|
|
3073
|
+
[{ role: "user", content: summaryPrompt(result, instructions) }],
|
|
3074
|
+
{ temperature: 0.3, maxTokens: 4e3, logKind: "summary" }
|
|
3075
|
+
);
|
|
3076
|
+
if (res.error || !res.text) {
|
|
3077
|
+
throw new Error(`summary failed: ${res.error || "empty response"}`);
|
|
3078
|
+
}
|
|
3079
|
+
return res.text.trim() + "\n";
|
|
3080
|
+
}
|
|
3081
|
+
|
|
1723
3082
|
// src/core/pipeline.ts
|
|
1724
|
-
var
|
|
3083
|
+
var import_node_path6 = require("path");
|
|
1725
3084
|
var JSON_OPTS = { encoding: "utf-8" };
|
|
1726
3085
|
function readJson(p) {
|
|
1727
|
-
if (!(0,
|
|
3086
|
+
if (!(0, import_node_fs5.existsSync)(p)) return null;
|
|
1728
3087
|
try {
|
|
1729
|
-
return JSON.parse((0,
|
|
3088
|
+
return JSON.parse((0, import_node_fs5.readFileSync)(p, JSON_OPTS));
|
|
1730
3089
|
} catch {
|
|
1731
3090
|
return null;
|
|
1732
3091
|
}
|
|
1733
3092
|
}
|
|
1734
3093
|
function writeJson(p, data) {
|
|
1735
|
-
(0,
|
|
3094
|
+
(0, import_node_fs5.writeFileSync)(p, JSON.stringify(data, null, 2), JSON_OPTS);
|
|
1736
3095
|
}
|
|
1737
3096
|
async function mapPool(items, limit, fn) {
|
|
1738
3097
|
const results = new Array(items.length);
|
|
@@ -1750,6 +3109,15 @@ async function mapPool(items, limit, fn) {
|
|
|
1750
3109
|
function has(passes, p) {
|
|
1751
3110
|
return passes.includes(p);
|
|
1752
3111
|
}
|
|
3112
|
+
function stageTag(name) {
|
|
3113
|
+
return (err) => {
|
|
3114
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3115
|
+
if (msg.startsWith(`[${name}]`)) throw err;
|
|
3116
|
+
const e = new Error(`[${name}] ${msg}`);
|
|
3117
|
+
if (err instanceof Error && err.stack) e.stack = err.stack;
|
|
3118
|
+
throw e;
|
|
3119
|
+
};
|
|
3120
|
+
}
|
|
1753
3121
|
async function transcribe(opts) {
|
|
1754
3122
|
if (!opts || typeof opts.input !== "string" || opts.input.length === 0) {
|
|
1755
3123
|
throw new Error(
|
|
@@ -1759,15 +3127,17 @@ async function transcribe(opts) {
|
|
|
1759
3127
|
const options = resolveOptions(opts);
|
|
1760
3128
|
const keys = resolveKeys(options.apiKeys);
|
|
1761
3129
|
logger.setLevel(options.logLevel);
|
|
1762
|
-
if (!(0,
|
|
3130
|
+
if (!(0, import_node_fs5.existsSync)(options.input)) {
|
|
1763
3131
|
throw new Error(`Input file not found: ${options.input}`);
|
|
1764
3132
|
}
|
|
1765
|
-
(0,
|
|
1766
|
-
(0,
|
|
3133
|
+
(0, import_node_fs5.mkdirSync)(options.intermediatesDir, { recursive: true });
|
|
3134
|
+
(0, import_node_fs5.mkdirSync)(options.outputDir, { recursive: true });
|
|
1767
3135
|
logger.info(
|
|
1768
|
-
`intermediates: ${(0,
|
|
3136
|
+
`intermediates: ${(0, import_node_path6.resolve)(options.intermediatesDir)} (file://${(0, import_node_path6.resolve)(options.intermediatesDir)})`
|
|
1769
3137
|
);
|
|
1770
3138
|
setLlmLogPath(options.llmLog ? `${options.intermediatesDir}/llm-calls.jsonl` : null);
|
|
3139
|
+
resetLlmUsage();
|
|
3140
|
+
const runStartedAt = Date.now();
|
|
1771
3141
|
const sourcePath = `${options.intermediatesDir}/source.json`;
|
|
1772
3142
|
const sig = inputSignature(options.input);
|
|
1773
3143
|
const cfgSig = configSignature(opts);
|
|
@@ -1797,6 +3167,9 @@ async function transcribe(opts) {
|
|
|
1797
3167
|
transcribe: options.model ?? DEFAULT_TRANSCRIBE_MODEL,
|
|
1798
3168
|
reasoner: options.reasoner ?? DEFAULT_REASONER_MODEL
|
|
1799
3169
|
};
|
|
3170
|
+
const checkAbort = () => {
|
|
3171
|
+
options.signal?.throwIfAborted();
|
|
3172
|
+
};
|
|
1800
3173
|
if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
|
|
1801
3174
|
if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
|
|
1802
3175
|
const tsProvider = options.timestampedProvider ?? "assemblyai";
|
|
@@ -1804,33 +3177,45 @@ async function transcribe(opts) {
|
|
|
1804
3177
|
if (willTimestamp) {
|
|
1805
3178
|
if (tsProvider === "assemblyai" && !keys.assemblyai) {
|
|
1806
3179
|
throw new Error(
|
|
1807
|
-
"ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
|
|
3180
|
+
"ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped elevenlabs / whisper-groq)"
|
|
1808
3181
|
);
|
|
1809
3182
|
}
|
|
1810
3183
|
if (tsProvider === "whisper-groq" && !keys.groq) {
|
|
1811
3184
|
throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
|
|
1812
3185
|
}
|
|
3186
|
+
if (tsProvider === "elevenlabs" && !keys.elevenlabs) {
|
|
3187
|
+
throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
|
|
3188
|
+
}
|
|
1813
3189
|
}
|
|
1814
3190
|
let probeInfo = null;
|
|
1815
3191
|
const AUDIO_OPTS = { format: "mp3", bitrate: "64k" };
|
|
1816
3192
|
const audioPath = `${options.intermediatesDir}/audio.mp3`;
|
|
1817
3193
|
const probePath = `${options.intermediatesDir}/probe.json`;
|
|
1818
3194
|
if (has(passes, "preprocess")) {
|
|
3195
|
+
checkAbort();
|
|
1819
3196
|
logger.info("=== preprocess ===");
|
|
1820
3197
|
probeInfo = forceAll ? null : readJson(probePath);
|
|
1821
3198
|
if (!probeInfo) {
|
|
1822
|
-
probeInfo = await probe(options.input);
|
|
3199
|
+
probeInfo = await probe(options.input).catch(stageTag("preprocess"));
|
|
1823
3200
|
writeJson(probePath, probeInfo);
|
|
1824
3201
|
}
|
|
1825
|
-
if (!(0,
|
|
3202
|
+
if (!(0, import_node_fs5.existsSync)(audioPath) || forceAll) {
|
|
1826
3203
|
logger.info("extracting audio (mono 16kHz mp3)...");
|
|
1827
|
-
await extractAudio(options.input, audioPath, AUDIO_OPTS)
|
|
3204
|
+
await extractAudio(options.input, audioPath, AUDIO_OPTS).catch(
|
|
3205
|
+
stageTag("preprocess")
|
|
3206
|
+
);
|
|
1828
3207
|
}
|
|
1829
3208
|
if (probeInfo.hasVideo) {
|
|
1830
3209
|
const kfDir = `${options.intermediatesDir}/keyframes`;
|
|
1831
|
-
if (!(0,
|
|
3210
|
+
if (!(0, import_node_fs5.existsSync)(kfDir) || forceAll) {
|
|
1832
3211
|
logger.info("extracting keyframes...");
|
|
1833
|
-
await extractKeyframes(options.input, kfDir, options.screenshotCount)
|
|
3212
|
+
await extractKeyframes(options.input, kfDir, options.screenshotCount).catch(
|
|
3213
|
+
(err) => {
|
|
3214
|
+
logger.warn(
|
|
3215
|
+
`keyframe extraction failed (continuing audio-only): ${err instanceof Error ? err.message : err}`
|
|
3216
|
+
);
|
|
3217
|
+
}
|
|
3218
|
+
);
|
|
1834
3219
|
}
|
|
1835
3220
|
}
|
|
1836
3221
|
} else {
|
|
@@ -1838,32 +3223,56 @@ async function transcribe(opts) {
|
|
|
1838
3223
|
}
|
|
1839
3224
|
if (!probeInfo) throw new Error("probe info missing (run preprocess)");
|
|
1840
3225
|
const duration = probeInfo.duration;
|
|
3226
|
+
const estimate = estimateRunCost({
|
|
3227
|
+
durationSec: duration,
|
|
3228
|
+
model: models.transcribe,
|
|
3229
|
+
reasoner: models.reasoner,
|
|
3230
|
+
tsProvider,
|
|
3231
|
+
chunkSec: options.chunkDurationSec,
|
|
3232
|
+
overlapSec: options.chunkOverlapSec,
|
|
3233
|
+
identify: options.diarizationLevel >= 3 && has(passes, "identify")
|
|
3234
|
+
});
|
|
3235
|
+
logger.info(
|
|
3236
|
+
`estimated cost ~$${estimate.totalUsd.toFixed(2)}${estimate.incomplete ? " (+unpriced parts)" : ""} [${estimate.lines.join(" \xB7 ")}]`
|
|
3237
|
+
);
|
|
1841
3238
|
let description = null;
|
|
1842
3239
|
if (has(passes, "describe")) {
|
|
1843
3240
|
const descPath = `${options.intermediatesDir}/description.json`;
|
|
1844
3241
|
description = forceAll ? null : readJson(descPath);
|
|
1845
3242
|
if (!description) {
|
|
3243
|
+
checkAbort();
|
|
1846
3244
|
logger.info("=== describe ===");
|
|
1847
3245
|
const client = new GeminiClient(keys.gemini);
|
|
1848
|
-
const
|
|
1849
|
-
|
|
1850
|
-
|
|
3246
|
+
const sampleSpans = duration <= 360 ? [[0, duration]] : [
|
|
3247
|
+
[0, 150],
|
|
3248
|
+
[Math.max(0, duration / 2 - 60), Math.min(duration, duration / 2 + 60)],
|
|
3249
|
+
[Math.max(0, duration - 120), duration]
|
|
3250
|
+
];
|
|
3251
|
+
const files = [];
|
|
3252
|
+
for (let i = 0; i < sampleSpans.length; i++) {
|
|
3253
|
+
const [s, e] = sampleSpans[i];
|
|
3254
|
+
const samplePath = `${options.intermediatesDir}/sample_${i}.mp3`;
|
|
3255
|
+
if (!(0, import_node_fs5.existsSync)(samplePath) || forceAll) {
|
|
3256
|
+
await extractChunk(audioPath, samplePath, s, e, AUDIO_OPTS);
|
|
3257
|
+
}
|
|
3258
|
+
files.push({ path: samplePath });
|
|
1851
3259
|
}
|
|
1852
|
-
const
|
|
3260
|
+
const audioSampleCount = files.length;
|
|
1853
3261
|
const kfDir = `${options.intermediatesDir}/keyframes`;
|
|
1854
|
-
if ((0,
|
|
3262
|
+
if ((0, import_node_fs5.existsSync)(kfDir)) {
|
|
1855
3263
|
for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
|
|
1856
3264
|
const p = `${kfDir}/${f}`;
|
|
1857
|
-
if ((0,
|
|
3265
|
+
if ((0, import_node_fs5.existsSync)(p)) files.push({ path: p });
|
|
1858
3266
|
}
|
|
1859
3267
|
}
|
|
1860
3268
|
description = await describeMeeting(
|
|
1861
3269
|
client,
|
|
1862
3270
|
models.transcribe,
|
|
1863
3271
|
files,
|
|
1864
|
-
(0,
|
|
1865
|
-
options.instructions
|
|
1866
|
-
|
|
3272
|
+
(0, import_node_path6.basename)(options.input),
|
|
3273
|
+
options.instructions,
|
|
3274
|
+
audioSampleCount
|
|
3275
|
+
).catch(stageTag("describe"));
|
|
1867
3276
|
writeJson(descPath, description);
|
|
1868
3277
|
logger.info(`description: ${description.description.slice(0, 120)}...`);
|
|
1869
3278
|
}
|
|
@@ -1911,16 +3320,39 @@ async function transcribe(opts) {
|
|
|
1911
3320
|
);
|
|
1912
3321
|
const client = new GeminiClient(keys.gemini);
|
|
1913
3322
|
const llmDir = `${options.intermediatesDir}/llm`;
|
|
1914
|
-
(0,
|
|
3323
|
+
(0, import_node_fs5.mkdirSync)(llmDir, { recursive: true });
|
|
3324
|
+
const partialPath = `${options.outputDir}/${(0, import_node_path6.basename)(options.input, ext(options.input))}.partial.md`;
|
|
3325
|
+
const completed = [];
|
|
3326
|
+
const writePartial = () => {
|
|
3327
|
+
try {
|
|
3328
|
+
const segs = completed.flatMap((r) => r.segments).sort((a, b) => a.startSec - b.startSec);
|
|
3329
|
+
if (segs.length === 0) return;
|
|
3330
|
+
const lines = segs.map((s) => {
|
|
3331
|
+
const mm = Math.floor(s.startSec / 60).toString().padStart(2, "0");
|
|
3332
|
+
const ss = Math.floor(s.startSec % 60).toString().padStart(2, "0");
|
|
3333
|
+
return `[${mm}:${ss}] **${s.speaker}**: ${s.text}`;
|
|
3334
|
+
});
|
|
3335
|
+
(0, import_node_fs5.writeFileSync)(
|
|
3336
|
+
partialPath,
|
|
3337
|
+
`> Partial transcript (run in progress \u2014 coarse LLM timings, speakers not yet unified)
|
|
3338
|
+
|
|
3339
|
+
${lines.join("\n\n")}
|
|
3340
|
+
`
|
|
3341
|
+
);
|
|
3342
|
+
} catch {
|
|
3343
|
+
}
|
|
3344
|
+
};
|
|
1915
3345
|
llmChunkResults = await mapPool(runChunks, options.concurrency, async (chunk) => {
|
|
3346
|
+
checkAbort();
|
|
1916
3347
|
const parsedPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_parsed.json`;
|
|
1917
3348
|
const cached = forceAll ? null : readJson(parsedPath);
|
|
1918
3349
|
if (cached && cached.segments.length > 0) {
|
|
1919
3350
|
logger.info(`chunk ${chunk.index}: cached (${cached.segments.length} segments)`);
|
|
3351
|
+
completed.push(cached);
|
|
1920
3352
|
return tagWith(cached, chunk);
|
|
1921
3353
|
}
|
|
1922
3354
|
const chunkPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}.mp3`;
|
|
1923
|
-
if (!(0,
|
|
3355
|
+
if (!(0, import_node_fs5.existsSync)(chunkPath) || forceAll) {
|
|
1924
3356
|
await extractChunk(audioPath, chunkPath, chunk.start, chunk.end, AUDIO_OPTS);
|
|
1925
3357
|
}
|
|
1926
3358
|
let previousTail;
|
|
@@ -1951,10 +3383,12 @@ async function transcribe(opts) {
|
|
|
1951
3383
|
{ chunkDurationSec: chunk.end - chunk.start, validationRetries: 1 }
|
|
1952
3384
|
);
|
|
1953
3385
|
writeJson(parsedPath, result2);
|
|
1954
|
-
(0,
|
|
3386
|
+
(0, import_node_fs5.writeFileSync)(
|
|
1955
3387
|
`${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`,
|
|
1956
3388
|
result2.raw
|
|
1957
3389
|
);
|
|
3390
|
+
completed.push(result2);
|
|
3391
|
+
writePartial();
|
|
1958
3392
|
return tagWith(result2, chunk);
|
|
1959
3393
|
});
|
|
1960
3394
|
const errored = llmChunkResults.filter((r) => r.error);
|
|
@@ -1966,7 +3400,7 @@ async function transcribe(opts) {
|
|
|
1966
3400
|
}
|
|
1967
3401
|
} else {
|
|
1968
3402
|
const llmDir = `${options.intermediatesDir}/llm`;
|
|
1969
|
-
if (!forceAll && (0,
|
|
3403
|
+
if (!forceAll && (0, import_node_fs5.existsSync)(llmDir)) {
|
|
1970
3404
|
const files = (await import("fs/promises").then((m) => m.readdir(llmDir))).filter((f) => f.endsWith("_parsed.json")).sort();
|
|
1971
3405
|
llmChunkResults = files.map((f, i) => {
|
|
1972
3406
|
const r = readJson(`${llmDir}/${f}`);
|
|
@@ -1985,18 +3419,38 @@ async function transcribe(opts) {
|
|
|
1985
3419
|
logger.info(`total LLM segments: ${allLlmSegments.length}`);
|
|
1986
3420
|
let asrResult = null;
|
|
1987
3421
|
if (has(passes, "timestamped") || has(passes, "align")) {
|
|
3422
|
+
checkAbort();
|
|
1988
3423
|
const provider = options.timestampedProvider ?? "assemblyai";
|
|
1989
3424
|
if (provider === "whisper-groq") {
|
|
1990
3425
|
logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
|
|
1991
3426
|
if (!keys.groq) throw new Error("GROQ_API_KEY is required for whisper-groq");
|
|
1992
|
-
if (!(0,
|
|
3427
|
+
if (!(0, import_node_fs5.existsSync)(audioPath) || forceAll) {
|
|
1993
3428
|
await extractAudio(options.input, audioPath, AUDIO_OPTS);
|
|
1994
3429
|
}
|
|
1995
3430
|
const { readFile: readFile2 } = await import("fs/promises");
|
|
1996
3431
|
const buf = await readFile2(audioPath);
|
|
1997
3432
|
const groq = new WhisperGroqClient(keys.groq);
|
|
1998
|
-
asrResult = await groq.transcribe(buf);
|
|
3433
|
+
asrResult = await groq.transcribe(buf).catch(stageTag("asr"));
|
|
1999
3434
|
writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
|
|
3435
|
+
} else if (provider === "elevenlabs") {
|
|
3436
|
+
logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
|
|
3437
|
+
if (!keys.elevenlabs)
|
|
3438
|
+
throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
|
|
3439
|
+
const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs.json`;
|
|
3440
|
+
asrResult = forceAll ? null : readJson(cachePath);
|
|
3441
|
+
if (!asrResult) {
|
|
3442
|
+
const { readFile: readFile2 } = await import("fs/promises");
|
|
3443
|
+
const buf = await readFile2(audioPath);
|
|
3444
|
+
const el = new ElevenLabsClient(keys.elevenlabs);
|
|
3445
|
+
asrResult = await el.transcribe(buf).catch(stageTag("asr"));
|
|
3446
|
+
writeJson(cachePath, asrResult);
|
|
3447
|
+
} else {
|
|
3448
|
+
logger.info("[elevenlabs] cache hit");
|
|
3449
|
+
}
|
|
3450
|
+
writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
|
|
3451
|
+
logger.info(
|
|
3452
|
+
`[elevenlabs] ${asrResult.utterances.length} utterances, ${asrResult.words.length} words, ${asrResult.speakers?.length ?? "?"} speakers`
|
|
3453
|
+
);
|
|
2000
3454
|
} else {
|
|
2001
3455
|
logger.info("=== timestamped (AssemblyAI) ===");
|
|
2002
3456
|
if (!keys.assemblyai)
|
|
@@ -2007,7 +3461,7 @@ async function transcribe(opts) {
|
|
|
2007
3461
|
apiKey: keys.assemblyai,
|
|
2008
3462
|
cacheDir: `${options.intermediatesDir}/assemblyai`
|
|
2009
3463
|
});
|
|
2010
|
-
asrResult = await aai.transcribe(audioPath);
|
|
3464
|
+
asrResult = await aai.transcribe(audioPath).catch(stageTag("asr"));
|
|
2011
3465
|
writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
|
|
2012
3466
|
}
|
|
2013
3467
|
} else {
|
|
@@ -2029,6 +3483,9 @@ async function transcribe(opts) {
|
|
|
2029
3483
|
const added = aligned.length - before;
|
|
2030
3484
|
if (added) logger.info(`gap-filled ${added} ASR fallback segment(s)`);
|
|
2031
3485
|
}
|
|
3486
|
+
if (asrResult && (asrResult.hasDiarization ?? true) && (has(passes, "align") || has(passes, "consistency"))) {
|
|
3487
|
+
aligned = splitMixedVoiceSegments(aligned, asrResult.utterances);
|
|
3488
|
+
}
|
|
2032
3489
|
let segments = aligned;
|
|
2033
3490
|
let speakers = [];
|
|
2034
3491
|
if (has(passes, "consistency") && asrResult) {
|
|
@@ -2048,31 +3505,75 @@ async function transcribe(opts) {
|
|
|
2048
3505
|
speakers = c.speakers;
|
|
2049
3506
|
}
|
|
2050
3507
|
}
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
3508
|
+
const nameHints = {};
|
|
3509
|
+
for (const sp of speakers) {
|
|
3510
|
+
if (sp.name && sp.name !== sp.id) nameHints[sp.id] = sp.name;
|
|
3511
|
+
}
|
|
3512
|
+
segments = segments.map(
|
|
3513
|
+
(s) => s.speakerName !== s.speaker ? { ...s, speakerName: s.speaker } : s
|
|
3514
|
+
);
|
|
3515
|
+
speakers = speakers.map((sp) => sp.name !== sp.id ? { ...sp, name: sp.id } : sp);
|
|
3516
|
+
if (options.diarizationLevel >= 3 && has(passes, "identify")) {
|
|
3517
|
+
const reasonerA = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
|
|
3518
|
+
if (!reasonerA) {
|
|
3519
|
+
logger.warn(
|
|
3520
|
+
"identify: no reasoner-capable API key found (DEEPSEEK/GEMINI/OPENAI/\u2026) \u2014 skipping speaker naming"
|
|
3521
|
+
);
|
|
3522
|
+
} else {
|
|
3523
|
+
const mode = options.identifyMode;
|
|
3524
|
+
const reasonerB = mode === "dual" ? resolveSecondReasoner(reasonerA.info, keys) : null;
|
|
3525
|
+
const idConfig = {
|
|
3526
|
+
mode,
|
|
3527
|
+
reasonerA: reasonerA.info.model,
|
|
3528
|
+
reasonerB: reasonerB?.info.model ?? null
|
|
3529
|
+
};
|
|
3530
|
+
const idCachePath = `${options.intermediatesDir}/identified.json`;
|
|
3531
|
+
const cachedId = forceAll ? null : readJson(
|
|
3532
|
+
idCachePath
|
|
3533
|
+
);
|
|
3534
|
+
const idConfigMatches = cachedId?.config && JSON.stringify(cachedId.config) === JSON.stringify(idConfig);
|
|
3535
|
+
let nameMap = null;
|
|
3536
|
+
if (idConfigMatches && cachedId?.nameMap && Object.keys(cachedId.nameMap).length > 0) {
|
|
3537
|
+
logger.info("=== identify (cached) ===");
|
|
3538
|
+
nameMap = cachedId.nameMap;
|
|
3539
|
+
} else {
|
|
3540
|
+
logger.info(
|
|
3541
|
+
`=== identify (${reasonerA.info.model}${reasonerB ? ` + ${reasonerB.info.model} second opinion` : ""}) ===`
|
|
3542
|
+
);
|
|
3543
|
+
checkAbort();
|
|
3544
|
+
const id = await identifySpeakersV2(
|
|
3545
|
+
{
|
|
3546
|
+
client: reasonerA.client,
|
|
3547
|
+
model: reasonerA.info.model,
|
|
3548
|
+
provider: reasonerA.info.provider
|
|
3549
|
+
},
|
|
3550
|
+
reasonerB ? {
|
|
3551
|
+
client: reasonerB.client,
|
|
3552
|
+
model: reasonerB.info.model,
|
|
3553
|
+
provider: reasonerB.info.provider
|
|
3554
|
+
} : null,
|
|
3555
|
+
segments.map((s) => ({ speaker: s.speaker, text: s.text })),
|
|
3556
|
+
speakers,
|
|
3557
|
+
{
|
|
3558
|
+
roster: description?.roster ?? "(no roster available \u2014 infer from the transcript alone)",
|
|
3559
|
+
knownSpeakers: options.knownSpeakers,
|
|
3560
|
+
mode,
|
|
3561
|
+
nameHints,
|
|
3562
|
+
sourceFileName: (0, import_node_path6.basename)(options.input)
|
|
3563
|
+
}
|
|
3564
|
+
).catch(stageTag("identify"));
|
|
3565
|
+
writeJson(idCachePath, { ...id, config: idConfig });
|
|
3566
|
+
nameMap = id.nameMap;
|
|
3567
|
+
}
|
|
3568
|
+
logger.info(
|
|
3569
|
+
`identified ${Object.keys(nameMap).length} speakers: ${JSON.stringify(nameMap)}`
|
|
3570
|
+
);
|
|
3571
|
+
const nm = nameMap;
|
|
3572
|
+
segments = segments.map(
|
|
3573
|
+
(s) => nm[s.speaker] ? { ...s, speakerName: nm[s.speaker] } : s
|
|
3574
|
+
);
|
|
3575
|
+
speakers = speakers.map((sp) => nm[sp.id] ? { ...sp, name: nm[sp.id] } : sp);
|
|
3576
|
+
}
|
|
2076
3577
|
}
|
|
2077
3578
|
let finalSegments = [];
|
|
2078
3579
|
if (has(passes, "finalize")) {
|
|
@@ -2083,33 +3584,106 @@ async function transcribe(opts) {
|
|
|
2083
3584
|
finalSegments = (forceAll ? null : readJson(`${options.intermediatesDir}/final.json`)) ?? [];
|
|
2084
3585
|
}
|
|
2085
3586
|
logger.info(`final segments: ${finalSegments.length}`);
|
|
3587
|
+
const receipt = computeReceipt(getLlmUsage(), tsProvider, duration);
|
|
3588
|
+
const wallMs = Date.now() - runStartedAt;
|
|
2086
3589
|
const metadata = {
|
|
2087
3590
|
sourceFile: options.input,
|
|
2088
3591
|
duration,
|
|
2089
3592
|
processedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2090
3593
|
models: {
|
|
2091
3594
|
transcribe: models.transcribe,
|
|
2092
|
-
timestamped: tsProvider === "whisper-groq" ? "whisper-large-v3 (groq)" : tsProvider === "none" ? "none" : "assemblyai-universal-2"
|
|
3595
|
+
timestamped: tsProvider === "whisper-groq" ? "whisper-large-v3 (groq)" : tsProvider === "elevenlabs" ? "scribe-v2 (elevenlabs)" : tsProvider === "none" ? "none" : "assemblyai-universal-2"
|
|
2093
3596
|
},
|
|
2094
|
-
passes
|
|
3597
|
+
passes,
|
|
3598
|
+
wallMs,
|
|
3599
|
+
cost: {
|
|
3600
|
+
estimatedUsd: estimate.totalUsd,
|
|
3601
|
+
actualUsd: receipt.totalUsd,
|
|
3602
|
+
pricesAsOf: PRICES_AS_OF,
|
|
3603
|
+
lines: receipt.lines,
|
|
3604
|
+
llmCalls: receipt.totals.calls,
|
|
3605
|
+
inputTokens: receipt.totals.inputTokens,
|
|
3606
|
+
outputTokens: receipt.totals.outputTokens
|
|
3607
|
+
}
|
|
2095
3608
|
};
|
|
2096
3609
|
const result = { segments: finalSegments, speakers, metadata };
|
|
3610
|
+
writeJson(`${options.intermediatesDir}/result.json`, result);
|
|
2097
3611
|
for (const fmt of options.formats) {
|
|
2098
|
-
const base = (0,
|
|
3612
|
+
const base = (0, import_node_path6.basename)(options.input, ext(options.input));
|
|
2099
3613
|
if (fmt === "srt")
|
|
2100
|
-
(0,
|
|
3614
|
+
(0, import_node_fs5.writeFileSync)(
|
|
2101
3615
|
`${options.outputDir}/${base}.srt`,
|
|
2102
3616
|
formatSrt(result, { title: base })
|
|
2103
3617
|
);
|
|
2104
3618
|
if (fmt === "md")
|
|
2105
|
-
(0,
|
|
3619
|
+
(0, import_node_fs5.writeFileSync)(
|
|
2106
3620
|
`${options.outputDir}/${base}.md`,
|
|
2107
|
-
formatMarkdown(result, { title: base })
|
|
3621
|
+
formatMarkdown(result, { title: base, mdStyle: options.mdStyle })
|
|
3622
|
+
);
|
|
3623
|
+
if (fmt === "txt")
|
|
3624
|
+
(0, import_node_fs5.writeFileSync)(
|
|
3625
|
+
`${options.outputDir}/${base}.txt`,
|
|
3626
|
+
formatText(result, { title: base })
|
|
3627
|
+
);
|
|
3628
|
+
if (fmt === "html")
|
|
3629
|
+
(0, import_node_fs5.writeFileSync)(
|
|
3630
|
+
`${options.outputDir}/${base}.html`,
|
|
3631
|
+
formatHtml(result, { title: base })
|
|
2108
3632
|
);
|
|
2109
3633
|
if (fmt === "json")
|
|
2110
|
-
(0,
|
|
3634
|
+
(0, import_node_fs5.writeFileSync)(`${options.outputDir}/${base}.json`, formatJson(result));
|
|
3635
|
+
}
|
|
3636
|
+
if (options.summary && finalSegments.length > 0) {
|
|
3637
|
+
const reasoner = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
|
|
3638
|
+
if (!reasoner) {
|
|
3639
|
+
logger.warn("summary: no reasoner-capable key \u2014 skipping");
|
|
3640
|
+
} else {
|
|
3641
|
+
logger.info(`=== summary (${reasoner.info.model}) ===`);
|
|
3642
|
+
try {
|
|
3643
|
+
const summary = await summarizeTranscript(
|
|
3644
|
+
reasoner.client,
|
|
3645
|
+
reasoner.info.model,
|
|
3646
|
+
result,
|
|
3647
|
+
options.instructions
|
|
3648
|
+
);
|
|
3649
|
+
const base = (0, import_node_path6.basename)(options.input, ext(options.input));
|
|
3650
|
+
(0, import_node_fs5.writeFileSync)(`${options.outputDir}/${base}.summary.md`, summary);
|
|
3651
|
+
logger.info(`summary written to ${base}.summary.md`);
|
|
3652
|
+
} catch (err) {
|
|
3653
|
+
logger.warn(`summary failed: ${err instanceof Error ? err.message : err}`);
|
|
3654
|
+
}
|
|
3655
|
+
}
|
|
3656
|
+
}
|
|
3657
|
+
try {
|
|
3658
|
+
const base = (0, import_node_path6.basename)(options.input, ext(options.input));
|
|
3659
|
+
const partial = `${options.outputDir}/${base}.partial.md`;
|
|
3660
|
+
if ((0, import_node_fs5.existsSync)(partial)) (await import("fs/promises")).unlink(partial);
|
|
3661
|
+
} catch {
|
|
2111
3662
|
}
|
|
2112
3663
|
logger.info(`outputs written to ${options.outputDir}`);
|
|
3664
|
+
const mins = Math.floor(wallMs / 6e4);
|
|
3665
|
+
const secs = Math.round(wallMs % 6e4 / 1e3);
|
|
3666
|
+
logger.info(
|
|
3667
|
+
`receipt: ${receipt.totals.calls} LLM calls \xB7 ${(receipt.totals.inputTokens / 1e3).toFixed(0)}k in / ${(receipt.totals.outputTokens / 1e3).toFixed(0)}k out \xB7 ~$${receipt.totalUsd.toFixed(2)}${receipt.incomplete ? " (+unpriced)" : ""} \xB7 ${mins ? `${mins}m` : ""}${secs}s`
|
|
3668
|
+
);
|
|
3669
|
+
for (const line of receipt.lines) logger.info(` ${line}`);
|
|
3670
|
+
recordRun(
|
|
3671
|
+
{
|
|
3672
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3673
|
+
input: (0, import_node_path6.basename)(options.input),
|
|
3674
|
+
durationSec: duration,
|
|
3675
|
+
wallMs,
|
|
3676
|
+
models: metadata.models,
|
|
3677
|
+
segments: finalSegments.length,
|
|
3678
|
+
characters: finalSegments.reduce((n, s) => n + s.text.length, 0),
|
|
3679
|
+
speakers: speakers.length,
|
|
3680
|
+
llmCalls: receipt.totals.calls,
|
|
3681
|
+
inputTokens: receipt.totals.inputTokens,
|
|
3682
|
+
outputTokens: receipt.totals.outputTokens,
|
|
3683
|
+
costUsd: receipt.totalUsd
|
|
3684
|
+
},
|
|
3685
|
+
receipt.perModel
|
|
3686
|
+
);
|
|
2113
3687
|
return result;
|
|
2114
3688
|
}
|
|
2115
3689
|
function ext(p) {
|
|
@@ -2151,12 +3725,15 @@ function parseSrt(content) {
|
|
|
2151
3725
|
alignSegments,
|
|
2152
3726
|
assignGlobalSpeakers,
|
|
2153
3727
|
finalizeSegments,
|
|
3728
|
+
formatHtml,
|
|
2154
3729
|
formatJson,
|
|
2155
3730
|
formatMarkdown,
|
|
2156
3731
|
formatSrt,
|
|
3732
|
+
formatText,
|
|
2157
3733
|
identifySpeakers,
|
|
2158
3734
|
parseSrt,
|
|
2159
3735
|
planChunks,
|
|
3736
|
+
summarizeTranscript,
|
|
2160
3737
|
transcribe
|
|
2161
3738
|
});
|
|
2162
3739
|
//# sourceMappingURL=index.cjs.map
|