offmute-v2 0.0.5 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/core/pipeline.ts
|
|
2
|
-
import { existsSync as
|
|
2
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
3
3
|
|
|
4
4
|
// src/core/config.ts
|
|
5
5
|
import { createHash } from "crypto";
|
|
@@ -37,7 +37,10 @@ function resolveKeys(injected) {
|
|
|
37
37
|
deepseek: injected?.deepseek || env.DEEPSEEK_API_KEY,
|
|
38
38
|
groq: injected?.groq || env.GROQ_API_KEY,
|
|
39
39
|
assemblyai: injected?.assemblyai || env.ASSEMBLYAI_API_KEY,
|
|
40
|
-
anthropic: injected?.anthropic || env.ANTHROPIC_API_KEY
|
|
40
|
+
anthropic: injected?.anthropic || env.ANTHROPIC_API_KEY,
|
|
41
|
+
zai: injected?.zai || env.ZAI_API_KEY || env.GLM_API_KEY,
|
|
42
|
+
kimi: injected?.kimi || env.KIMI_API_KEY || env.MOONSHOT_API_KEY,
|
|
43
|
+
elevenlabs: injected?.elevenlabs || env.ELEVENLABS_API_KEY
|
|
41
44
|
};
|
|
42
45
|
}
|
|
43
46
|
function resolveOptions(opts) {
|
|
@@ -50,7 +53,7 @@ function resolveOptions(opts) {
|
|
|
50
53
|
knownSpeakers: opts.knownSpeakers,
|
|
51
54
|
passes: (() => {
|
|
52
55
|
const p = opts.passes ?? DEFAULT_PASSES;
|
|
53
|
-
if ((opts.diarizationLevel ??
|
|
56
|
+
if ((opts.diarizationLevel ?? 3) >= 3 && !p.includes("identify")) {
|
|
54
57
|
const out = [...p];
|
|
55
58
|
const fi = out.indexOf("finalize");
|
|
56
59
|
if (fi >= 0) out.splice(fi, 0, "identify");
|
|
@@ -65,7 +68,13 @@ function resolveOptions(opts) {
|
|
|
65
68
|
concurrency: opts.concurrency ?? 4,
|
|
66
69
|
saveIntermediates: opts.saveIntermediates ?? true,
|
|
67
70
|
formats: opts.formats ?? ["md"],
|
|
68
|
-
|
|
71
|
+
mdStyle: opts.mdStyle ?? "merged",
|
|
72
|
+
summary: opts.summary ?? false,
|
|
73
|
+
// Level 3 is the default: display names must come from the VERIFIED identify pass.
|
|
74
|
+
// (A describe-pass roster once bound names to the wrong voices and level 2 shipped
|
|
75
|
+
// them unchecked — the Jay-call flip. Level 2 now shows honest Speaker A/B labels.)
|
|
76
|
+
diarizationLevel: opts.diarizationLevel ?? 3,
|
|
77
|
+
identifyMode: opts.identifyMode ?? "dual",
|
|
69
78
|
apiKeys: opts.apiKeys,
|
|
70
79
|
model: opts.model,
|
|
71
80
|
reasoner: opts.reasoner,
|
|
@@ -74,7 +83,8 @@ function resolveOptions(opts) {
|
|
|
74
83
|
onlyChunk: opts.onlyChunk,
|
|
75
84
|
showProgress: opts.showProgress ?? true,
|
|
76
85
|
llmLog: opts.llmLog ?? true,
|
|
77
|
-
logLevel: opts.logLevel ?? "info"
|
|
86
|
+
logLevel: opts.logLevel ?? "info",
|
|
87
|
+
signal: opts.signal
|
|
78
88
|
};
|
|
79
89
|
}
|
|
80
90
|
function deriveIntermediatesDir(input) {
|
|
@@ -107,7 +117,7 @@ function configSignature(o) {
|
|
|
107
117
|
chunkDurationSec: o.chunkDurationSec ?? 600,
|
|
108
118
|
chunkOverlapSec: o.chunkOverlapSec ?? 60,
|
|
109
119
|
screenshotCount: o.screenshotCount ?? 6,
|
|
110
|
-
diarizationLevel: o.diarizationLevel ??
|
|
120
|
+
diarizationLevel: o.diarizationLevel ?? 3,
|
|
111
121
|
timestampedProvider: o.timestampedProvider ?? "assemblyai"
|
|
112
122
|
};
|
|
113
123
|
return createHash("sha1").update(JSON.stringify(relevant)).digest("hex");
|
|
@@ -142,11 +152,13 @@ function planChunks(totalDuration, chunkDuration, overlap2) {
|
|
|
142
152
|
// src/utils/logger.ts
|
|
143
153
|
var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
144
154
|
var currentLevel = "info";
|
|
155
|
+
var sink = null;
|
|
145
156
|
function setLogLevel(level) {
|
|
146
157
|
currentLevel = level;
|
|
147
158
|
}
|
|
148
159
|
function log(level, msg, extra) {
|
|
149
160
|
if (LEVELS[level] < LEVELS[currentLevel]) return;
|
|
161
|
+
if (sink && extra === void 0 && sink(level, msg)) return;
|
|
150
162
|
const ts = (/* @__PURE__ */ new Date()).toISOString().substring(11, 23);
|
|
151
163
|
const prefix = `[${ts}] ${level.toUpperCase().padEnd(5)}`;
|
|
152
164
|
if (extra !== void 0) {
|
|
@@ -160,7 +172,10 @@ var logger = {
|
|
|
160
172
|
info: (msg, extra) => log("info", msg, extra),
|
|
161
173
|
warn: (msg, extra) => log("warn", msg, extra),
|
|
162
174
|
error: (msg, extra) => log("error", msg, extra),
|
|
163
|
-
setLevel: setLogLevel
|
|
175
|
+
setLevel: setLogLevel,
|
|
176
|
+
setSink: (s) => {
|
|
177
|
+
sink = s;
|
|
178
|
+
}
|
|
164
179
|
};
|
|
165
180
|
|
|
166
181
|
// src/audio/ffmpeg.ts
|
|
@@ -373,10 +388,35 @@ import { basename as basename2 } from "path";
|
|
|
373
388
|
// src/providers/llm-log.ts
|
|
374
389
|
import { appendFileSync } from "fs";
|
|
375
390
|
var logPath = null;
|
|
391
|
+
var usageRecords = /* @__PURE__ */ new Map();
|
|
376
392
|
function setLlmLogPath(path) {
|
|
377
393
|
logPath = path ?? null;
|
|
378
394
|
}
|
|
395
|
+
function resetLlmUsage() {
|
|
396
|
+
usageRecords = /* @__PURE__ */ new Map();
|
|
397
|
+
}
|
|
398
|
+
function getLlmUsage() {
|
|
399
|
+
return [...usageRecords.values()];
|
|
400
|
+
}
|
|
379
401
|
function logLlmCall(entry) {
|
|
402
|
+
try {
|
|
403
|
+
const key = `${entry.model}|${entry.kind ?? ""}`;
|
|
404
|
+
const rec = usageRecords.get(key) ?? {
|
|
405
|
+
provider: entry.provider,
|
|
406
|
+
model: entry.model,
|
|
407
|
+
kind: entry.kind,
|
|
408
|
+
inputTokens: 0,
|
|
409
|
+
outputTokens: 0,
|
|
410
|
+
calls: 0,
|
|
411
|
+
errors: 0
|
|
412
|
+
};
|
|
413
|
+
rec.inputTokens += entry.usage?.inputTokens ?? 0;
|
|
414
|
+
rec.outputTokens += entry.usage?.outputTokens ?? 0;
|
|
415
|
+
rec.calls += 1;
|
|
416
|
+
if (entry.error) rec.errors += 1;
|
|
417
|
+
usageRecords.set(key, rec);
|
|
418
|
+
} catch {
|
|
419
|
+
}
|
|
380
420
|
if (!logPath) return;
|
|
381
421
|
try {
|
|
382
422
|
appendFileSync(logPath, JSON.stringify(entry) + "\n", { encoding: "utf-8" });
|
|
@@ -384,7 +424,39 @@ function logLlmCall(entry) {
|
|
|
384
424
|
}
|
|
385
425
|
}
|
|
386
426
|
|
|
427
|
+
// src/utils/retry.ts
|
|
428
|
+
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;
|
|
429
|
+
function isTransient(err) {
|
|
430
|
+
const msg = err instanceof Error ? `${err.message} ${err.cause ?? ""}` : String(err);
|
|
431
|
+
return TRANSIENT_RE.test(msg);
|
|
432
|
+
}
|
|
433
|
+
async function withRetry(label, fn, opts = {}) {
|
|
434
|
+
const retries = opts.retries ?? 5;
|
|
435
|
+
const base = opts.baseDelayMs ?? 2e3;
|
|
436
|
+
let lastErr;
|
|
437
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
438
|
+
try {
|
|
439
|
+
return await fn();
|
|
440
|
+
} catch (err) {
|
|
441
|
+
lastErr = err;
|
|
442
|
+
if (attempt === retries || !isTransient(err)) throw err;
|
|
443
|
+
const delay = base * 2 ** attempt * (0.7 + Math.random() * 0.6);
|
|
444
|
+
logger.warn(
|
|
445
|
+
`[${label}] transient failure (${err instanceof Error ? err.message : err}) \u2014 retry ${attempt + 1}/${retries} in ${(delay / 1e3).toFixed(1)}s`
|
|
446
|
+
);
|
|
447
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
throw lastErr;
|
|
451
|
+
}
|
|
452
|
+
|
|
387
453
|
// src/providers/gemini.ts
|
|
454
|
+
var SDK_KEY_WARNING = "Both GOOGLE_API_KEY and GEMINI_API_KEY are set";
|
|
455
|
+
var originalWarn = console.warn.bind(console);
|
|
456
|
+
console.warn = (...args) => {
|
|
457
|
+
if (typeof args[0] === "string" && args[0].startsWith(SDK_KEY_WARNING)) return;
|
|
458
|
+
originalWarn(...args);
|
|
459
|
+
};
|
|
388
460
|
var MIME_BY_EXT = {
|
|
389
461
|
".flac": "audio/flac",
|
|
390
462
|
".mp3": "audio/mp3",
|
|
@@ -426,11 +498,16 @@ var GeminiClient = class {
|
|
|
426
498
|
constructor(apiKey) {
|
|
427
499
|
this.ai = new GoogleGenAI({ apiKey });
|
|
428
500
|
}
|
|
429
|
-
/** Upload a file and wait until it's done processing.
|
|
501
|
+
/** Upload a file and wait until it's done processing. Uploads ride one long HTTP
|
|
502
|
+
* request each — the retry loop in generate() doesn't cover them, and transient
|
|
503
|
+
* "fetch failed" blips here killed live runs, so they get their own retry. */
|
|
430
504
|
async upload(path, mimeType) {
|
|
431
505
|
const mt = mimeType || detectMime(path);
|
|
432
506
|
logger.debug(`[gemini] uploading ${basename2(path)} (${mt})...`);
|
|
433
|
-
let file = await
|
|
507
|
+
let file = await withRetry(
|
|
508
|
+
`gemini upload ${basename2(path)}`,
|
|
509
|
+
() => this.ai.files.upload({ file: path, config: { mimeType: mt } })
|
|
510
|
+
);
|
|
434
511
|
let tries = 0;
|
|
435
512
|
while (file.state === "PROCESSING" && tries < 120) {
|
|
436
513
|
await sleep(2e3);
|
|
@@ -509,10 +586,14 @@ var GeminiClient = class {
|
|
|
509
586
|
lastError = err instanceof Error ? err.message : String(err);
|
|
510
587
|
if (config.thinkingConfig && isThinkingConfigError(lastError)) {
|
|
511
588
|
delete config.thinkingConfig;
|
|
512
|
-
logger.warn(
|
|
589
|
+
logger.warn(
|
|
590
|
+
`[gemini] model ${model} rejected thinking config \u2014 retrying without it`
|
|
591
|
+
);
|
|
513
592
|
continue;
|
|
514
593
|
}
|
|
515
|
-
logger.warn(
|
|
594
|
+
logger.warn(
|
|
595
|
+
`[gemini] attempt ${attempt + 1}/${maxRetries} failed: ${lastError}`
|
|
596
|
+
);
|
|
516
597
|
logLlmCall({
|
|
517
598
|
ts: new Date(t0).toISOString(),
|
|
518
599
|
provider: "gemini",
|
|
@@ -528,7 +609,11 @@ var GeminiClient = class {
|
|
|
528
609
|
if (attempt < maxRetries - 1) await sleep(retryDelayMs * (attempt + 1));
|
|
529
610
|
}
|
|
530
611
|
}
|
|
531
|
-
return {
|
|
612
|
+
return {
|
|
613
|
+
text: "",
|
|
614
|
+
usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
|
|
615
|
+
error: lastError
|
|
616
|
+
};
|
|
532
617
|
} finally {
|
|
533
618
|
await this.cleanup(uploaded);
|
|
534
619
|
}
|
|
@@ -598,7 +683,10 @@ var AssemblyAIProvider = class {
|
|
|
598
683
|
return JSON.parse(await readFile(cachePath, "utf-8"));
|
|
599
684
|
}
|
|
600
685
|
logger.info(`[assemblyai] uploading ${filePath}...`);
|
|
601
|
-
const uploadUrl = await
|
|
686
|
+
const uploadUrl = await withRetry(
|
|
687
|
+
"assemblyai upload",
|
|
688
|
+
() => this.client.files.upload(filePath)
|
|
689
|
+
);
|
|
602
690
|
logger.info(`[assemblyai] transcribing (speech_model=${this.speechModel})...`);
|
|
603
691
|
const params = {
|
|
604
692
|
audio: uploadUrl,
|
|
@@ -606,7 +694,10 @@ var AssemblyAIProvider = class {
|
|
|
606
694
|
speech_model: this.speechModel
|
|
607
695
|
};
|
|
608
696
|
if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
|
|
609
|
-
const transcript = await
|
|
697
|
+
const transcript = await withRetry(
|
|
698
|
+
"assemblyai transcribe",
|
|
699
|
+
() => this.client.transcripts.transcribe(params)
|
|
700
|
+
);
|
|
610
701
|
if (transcript.status === "error") {
|
|
611
702
|
throw new Error(`AssemblyAI error: ${transcript.error}`);
|
|
612
703
|
}
|
|
@@ -710,9 +801,315 @@ var WhisperGroqClient = class {
|
|
|
710
801
|
}
|
|
711
802
|
};
|
|
712
803
|
|
|
804
|
+
// src/providers/elevenlabs.ts
|
|
805
|
+
var MAX_UTTERANCE_GAP_SEC = 1.5;
|
|
806
|
+
var ElevenLabsClient = class {
|
|
807
|
+
constructor(apiKey, baseUrl = "https://api.elevenlabs.io/v1") {
|
|
808
|
+
this.apiKey = apiKey;
|
|
809
|
+
this.baseUrl = baseUrl;
|
|
810
|
+
}
|
|
811
|
+
apiKey;
|
|
812
|
+
baseUrl;
|
|
813
|
+
async transcribe(audio, opts = {}) {
|
|
814
|
+
const model = opts.model ?? "scribe_v2";
|
|
815
|
+
const blob = audio instanceof Blob ? audio : new Blob([audio], { type: "audio/mpeg" });
|
|
816
|
+
const form = new FormData();
|
|
817
|
+
form.append("file", blob, "audio.mp3");
|
|
818
|
+
form.append("model_id", model);
|
|
819
|
+
form.append("timestamps_granularity", "word");
|
|
820
|
+
form.append("diarize", "true");
|
|
821
|
+
form.append("tag_audio_events", "false");
|
|
822
|
+
if (opts.numSpeakers) form.append("num_speakers", String(opts.numSpeakers));
|
|
823
|
+
for (const term of opts.keyterms ?? []) form.append("keyterms", term);
|
|
824
|
+
const data = await withRetry("elevenlabs", async () => {
|
|
825
|
+
const res = await fetch(`${this.baseUrl}/speech-to-text`, {
|
|
826
|
+
method: "POST",
|
|
827
|
+
headers: { "xi-api-key": this.apiKey },
|
|
828
|
+
body: form
|
|
829
|
+
});
|
|
830
|
+
if (!res.ok) {
|
|
831
|
+
const txt = await res.text();
|
|
832
|
+
throw new Error(`ElevenLabs Scribe ${res.status}: ${txt.slice(0, 300)}`);
|
|
833
|
+
}
|
|
834
|
+
return await res.json();
|
|
835
|
+
});
|
|
836
|
+
const words = [];
|
|
837
|
+
for (const w of data.words ?? []) {
|
|
838
|
+
if (w.type !== "word") continue;
|
|
839
|
+
if (w.start === void 0 || w.end === void 0) continue;
|
|
840
|
+
words.push({
|
|
841
|
+
text: w.text.trim(),
|
|
842
|
+
start: w.start,
|
|
843
|
+
end: w.end,
|
|
844
|
+
speaker: w.speaker_id ?? "speaker_0"
|
|
845
|
+
});
|
|
846
|
+
}
|
|
847
|
+
const utterances = [];
|
|
848
|
+
let cur = [];
|
|
849
|
+
const flush = () => {
|
|
850
|
+
if (cur.length === 0) return;
|
|
851
|
+
utterances.push({
|
|
852
|
+
speaker: cur[0].speaker,
|
|
853
|
+
start: cur[0].start,
|
|
854
|
+
end: cur[cur.length - 1].end,
|
|
855
|
+
text: cur.map((w) => w.text).join(" "),
|
|
856
|
+
words: cur.map(({ text, start, end }) => ({ text, start, end }))
|
|
857
|
+
});
|
|
858
|
+
cur = [];
|
|
859
|
+
};
|
|
860
|
+
for (const w of words) {
|
|
861
|
+
const prev = cur[cur.length - 1];
|
|
862
|
+
if (prev && (w.speaker !== prev.speaker || w.start - prev.end > MAX_UTTERANCE_GAP_SEC)) {
|
|
863
|
+
flush();
|
|
864
|
+
}
|
|
865
|
+
cur.push(w);
|
|
866
|
+
}
|
|
867
|
+
flush();
|
|
868
|
+
const speakers = [...new Set(words.map((w) => w.speaker))];
|
|
869
|
+
return {
|
|
870
|
+
utterances,
|
|
871
|
+
words: words.map(({ text, start, end }) => ({ text, start, end })),
|
|
872
|
+
durationSec: data.audio_duration_secs ?? (words.length ? words[words.length - 1].end : 0),
|
|
873
|
+
speakers,
|
|
874
|
+
hasDiarization: true,
|
|
875
|
+
transcriptId: data.transcription_id ?? `elevenlabs-${model}`
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
|
|
880
|
+
// src/core/pricing.ts
|
|
881
|
+
var PRICES_AS_OF = "2026-07";
|
|
882
|
+
var MODEL_PRICES = {
|
|
883
|
+
// Gemini (ai.google.dev/gemini-api/docs/pricing, standard tier, <=200k prompts)
|
|
884
|
+
"gemini-3.1-pro-preview": { textIn: 2, out: 12 },
|
|
885
|
+
"gemini-3-pro-preview": { textIn: 2, out: 12 },
|
|
886
|
+
"gemini-3.5-flash": { textIn: 1.5, out: 9 },
|
|
887
|
+
"gemini-3-flash-preview": { textIn: 0.5, audioIn: 1, out: 3 },
|
|
888
|
+
"gemini-2.5-pro": { textIn: 1.25, out: 10 },
|
|
889
|
+
"gemini-2.5-flash": { textIn: 0.3, audioIn: 1, out: 2.5 },
|
|
890
|
+
"gemini-2.5-flash-lite": { textIn: 0.1, audioIn: 0.3, out: 0.4 },
|
|
891
|
+
// Moving aliases — priced as their current targets.
|
|
892
|
+
"gemini-pro-latest": { textIn: 2, out: 12 },
|
|
893
|
+
"gemini-flash-latest": { textIn: 1.5, out: 9 },
|
|
894
|
+
"gemini-flash-lite-latest": { textIn: 0.25, audioIn: 0.5, out: 1.5 },
|
|
895
|
+
// Text reasoners
|
|
896
|
+
"deepseek-chat": { textIn: 0.28, out: 0.42 },
|
|
897
|
+
"deepseek-reasoner": { textIn: 0.28, out: 0.42 },
|
|
898
|
+
"gpt-4o-mini": { textIn: 0.15, out: 0.6 },
|
|
899
|
+
"glm-4.7": { textIn: 0.6, out: 2.2 }
|
|
900
|
+
};
|
|
901
|
+
var ASR_HOURLY = {
|
|
902
|
+
assemblyai: 0.15,
|
|
903
|
+
// universal-2, diarization included
|
|
904
|
+
elevenlabs: 0.4,
|
|
905
|
+
// scribe v2 (standard tier; business tier is lower)
|
|
906
|
+
"whisper-groq": 0.04,
|
|
907
|
+
// whisper-large-v3-turbo
|
|
908
|
+
none: 0
|
|
909
|
+
};
|
|
910
|
+
var AUDIO_TOKENS_PER_SEC = 32;
|
|
911
|
+
function priceFor(model) {
|
|
912
|
+
if (MODEL_PRICES[model]) return MODEL_PRICES[model];
|
|
913
|
+
const hit = Object.keys(MODEL_PRICES).find((k) => model.startsWith(k));
|
|
914
|
+
return hit ? MODEL_PRICES[hit] : null;
|
|
915
|
+
}
|
|
916
|
+
function asrCost(provider, durationSec) {
|
|
917
|
+
const hourly = ASR_HOURLY[provider];
|
|
918
|
+
if (hourly === void 0) return null;
|
|
919
|
+
return durationSec / 3600 * hourly;
|
|
920
|
+
}
|
|
921
|
+
function estimateRunCost(opts) {
|
|
922
|
+
const lines = [];
|
|
923
|
+
let total = 0;
|
|
924
|
+
let incomplete = false;
|
|
925
|
+
const p = priceFor(opts.model);
|
|
926
|
+
const chunks = Math.max(
|
|
927
|
+
1,
|
|
928
|
+
Math.ceil((opts.durationSec - opts.overlapSec) / (opts.chunkSec - opts.overlapSec))
|
|
929
|
+
);
|
|
930
|
+
const billedAudioSec = opts.durationSec + Math.max(0, chunks - 1) * opts.overlapSec + Math.min(370, opts.durationSec);
|
|
931
|
+
if (p) {
|
|
932
|
+
const audioTok = billedAudioSec * AUDIO_TOKENS_PER_SEC;
|
|
933
|
+
const promptTok = chunks * 1500;
|
|
934
|
+
const outTok = opts.durationSec / 60 * 150 + 1500;
|
|
935
|
+
const inRate = p.audioIn ?? p.textIn;
|
|
936
|
+
const llmUsd = (audioTok * inRate + promptTok * p.textIn + outTok * p.out) / 1e6;
|
|
937
|
+
total += llmUsd;
|
|
938
|
+
lines.push(
|
|
939
|
+
`${opts.model}: ${chunks} chunk${chunks > 1 ? "s" : ""} + describe \u2248 $${llmUsd.toFixed(2)}`
|
|
940
|
+
);
|
|
941
|
+
} else {
|
|
942
|
+
incomplete = true;
|
|
943
|
+
lines.push(`${opts.model}: unpriced`);
|
|
944
|
+
}
|
|
945
|
+
const asr = asrCost(opts.tsProvider, opts.durationSec);
|
|
946
|
+
if (asr !== null && opts.tsProvider !== "none") {
|
|
947
|
+
total += asr;
|
|
948
|
+
lines.push(
|
|
949
|
+
`${opts.tsProvider}: ${(opts.durationSec / 60).toFixed(0)}min \u2248 $${asr.toFixed(2)}`
|
|
950
|
+
);
|
|
951
|
+
}
|
|
952
|
+
if (opts.identify && opts.reasoner) {
|
|
953
|
+
const rp = priceFor(opts.reasoner);
|
|
954
|
+
if (rp) {
|
|
955
|
+
const idUsd = (8e3 * rp.textIn + 1e3 * rp.out) / 1e6;
|
|
956
|
+
total += idUsd;
|
|
957
|
+
lines.push(`${opts.reasoner} (identify) \u2248 $${idUsd.toFixed(3)}`);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
return { totalUsd: total, lines, incomplete };
|
|
961
|
+
}
|
|
962
|
+
function computeReceipt(usage, tsProvider, durationSec) {
|
|
963
|
+
let llmUsd = 0;
|
|
964
|
+
let incomplete = false;
|
|
965
|
+
const lines = [];
|
|
966
|
+
const perModel = {};
|
|
967
|
+
const totals = { calls: 0, inputTokens: 0, outputTokens: 0 };
|
|
968
|
+
const byModel = /* @__PURE__ */ new Map();
|
|
969
|
+
for (const r of usage) {
|
|
970
|
+
totals.calls += r.calls;
|
|
971
|
+
totals.inputTokens += r.inputTokens;
|
|
972
|
+
totals.outputTokens += r.outputTokens;
|
|
973
|
+
const m = byModel.get(r.model) ?? { in: 0, out: 0, calls: 0 };
|
|
974
|
+
m.in += r.inputTokens;
|
|
975
|
+
m.out += r.outputTokens;
|
|
976
|
+
m.calls += r.calls;
|
|
977
|
+
byModel.set(r.model, m);
|
|
978
|
+
}
|
|
979
|
+
for (const [model, m] of byModel) {
|
|
980
|
+
const p = priceFor(model);
|
|
981
|
+
if (!p) {
|
|
982
|
+
incomplete = true;
|
|
983
|
+
lines.push(
|
|
984
|
+
`${model}: ${m.calls} calls \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 unpriced`
|
|
985
|
+
);
|
|
986
|
+
continue;
|
|
987
|
+
}
|
|
988
|
+
const usd = (m.in * (p.audioIn ?? p.textIn) + m.out * p.out) / 1e6;
|
|
989
|
+
llmUsd += usd;
|
|
990
|
+
perModel[model] = usd;
|
|
991
|
+
lines.push(
|
|
992
|
+
`${model}: ${m.calls} call${m.calls > 1 ? "s" : ""} \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 $${usd.toFixed(2)}`
|
|
993
|
+
);
|
|
994
|
+
}
|
|
995
|
+
const asrUsd = tsProvider === "none" ? 0 : asrCost(tsProvider, durationSec);
|
|
996
|
+
if (asrUsd !== null && tsProvider !== "none") {
|
|
997
|
+
perModel[tsProvider] = asrUsd;
|
|
998
|
+
lines.push(
|
|
999
|
+
`${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7 $${asrUsd.toFixed(2)}`
|
|
1000
|
+
);
|
|
1001
|
+
}
|
|
1002
|
+
return {
|
|
1003
|
+
totalUsd: llmUsd + (asrUsd ?? 0),
|
|
1004
|
+
llmUsd,
|
|
1005
|
+
asrUsd,
|
|
1006
|
+
lines,
|
|
1007
|
+
totals,
|
|
1008
|
+
perModel,
|
|
1009
|
+
incomplete
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
function fmtTok(n) {
|
|
1013
|
+
if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
|
|
1014
|
+
if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
|
|
1015
|
+
return String(n);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
// src/core/stats.ts
|
|
1019
|
+
import {
|
|
1020
|
+
appendFileSync as appendFileSync2,
|
|
1021
|
+
existsSync as existsSync2,
|
|
1022
|
+
mkdirSync,
|
|
1023
|
+
readFileSync,
|
|
1024
|
+
rmdirSync,
|
|
1025
|
+
writeFileSync
|
|
1026
|
+
} from "fs";
|
|
1027
|
+
import { homedir } from "os";
|
|
1028
|
+
import { join } from "path";
|
|
1029
|
+
function statsDir() {
|
|
1030
|
+
return process.env.OFFMUTE_HOME || join(homedir(), ".offmute");
|
|
1031
|
+
}
|
|
1032
|
+
function statsEnabled() {
|
|
1033
|
+
return !process.env.OFFMUTE_NO_STATS;
|
|
1034
|
+
}
|
|
1035
|
+
var EMPTY = {
|
|
1036
|
+
runs: 0,
|
|
1037
|
+
mediaSeconds: 0,
|
|
1038
|
+
characters: 0,
|
|
1039
|
+
llmCalls: 0,
|
|
1040
|
+
inputTokens: 0,
|
|
1041
|
+
outputTokens: 0,
|
|
1042
|
+
costUsd: 0,
|
|
1043
|
+
costByModel: {},
|
|
1044
|
+
runsByModel: {}
|
|
1045
|
+
};
|
|
1046
|
+
function readStats() {
|
|
1047
|
+
try {
|
|
1048
|
+
const p = join(statsDir(), "stats.json");
|
|
1049
|
+
if (!existsSync2(p)) return { ...EMPTY };
|
|
1050
|
+
return { ...EMPTY, ...JSON.parse(readFileSync(p, "utf-8")) };
|
|
1051
|
+
} catch {
|
|
1052
|
+
return { ...EMPTY };
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
function withStatsLock(dir, fn) {
|
|
1056
|
+
const lock = join(dir, ".stats.lock");
|
|
1057
|
+
const deadline = Date.now() + 2e3;
|
|
1058
|
+
for (; ; ) {
|
|
1059
|
+
try {
|
|
1060
|
+
mkdirSync(lock);
|
|
1061
|
+
break;
|
|
1062
|
+
} catch {
|
|
1063
|
+
if (Date.now() > deadline) break;
|
|
1064
|
+
const until = Date.now() + 25;
|
|
1065
|
+
while (Date.now() < until) {
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
try {
|
|
1070
|
+
fn();
|
|
1071
|
+
} finally {
|
|
1072
|
+
try {
|
|
1073
|
+
rmdirSync(lock);
|
|
1074
|
+
} catch {
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
function recordRun(rec, perModelCost) {
|
|
1079
|
+
if (!statsEnabled()) return;
|
|
1080
|
+
try {
|
|
1081
|
+
const dir = statsDir();
|
|
1082
|
+
mkdirSync(dir, { recursive: true });
|
|
1083
|
+
appendFileSync2(join(dir, "history.jsonl"), JSON.stringify(rec) + "\n");
|
|
1084
|
+
withStatsLock(dir, () => {
|
|
1085
|
+
foldIntoAggregates(rec, perModelCost, dir);
|
|
1086
|
+
});
|
|
1087
|
+
} catch {
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
function foldIntoAggregates(rec, perModelCost, dir) {
|
|
1091
|
+
const s = readStats();
|
|
1092
|
+
s.runs += 1;
|
|
1093
|
+
s.mediaSeconds += rec.durationSec;
|
|
1094
|
+
s.characters += rec.characters;
|
|
1095
|
+
s.llmCalls += rec.llmCalls;
|
|
1096
|
+
s.inputTokens += rec.inputTokens;
|
|
1097
|
+
s.outputTokens += rec.outputTokens;
|
|
1098
|
+
if (rec.costUsd !== null) s.costUsd += rec.costUsd;
|
|
1099
|
+
for (const [model, usd] of Object.entries(perModelCost)) {
|
|
1100
|
+
s.costByModel[model] = (s.costByModel[model] ?? 0) + usd;
|
|
1101
|
+
}
|
|
1102
|
+
const tModel = rec.models.transcribe;
|
|
1103
|
+
if (tModel) s.runsByModel[tModel] = (s.runsByModel[tModel] ?? 0) + 1;
|
|
1104
|
+
s.firstRun ??= rec.ts;
|
|
1105
|
+
s.lastRun = rec.ts;
|
|
1106
|
+
writeFileSync(join(dir, "stats.json"), JSON.stringify(s, null, 2));
|
|
1107
|
+
}
|
|
1108
|
+
|
|
713
1109
|
// src/transcribe/describe.ts
|
|
714
|
-
function descriptionPrompt(fileName, instructions) {
|
|
715
|
-
|
|
1110
|
+
function descriptionPrompt(fileName, instructions, sampleCount = 1) {
|
|
1111
|
+
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.`;
|
|
1112
|
+
return `${sampleNote} Your job is to prepare context for a transcription engine. Describe what you hear${instructions ? ` (note: ${instructions})` : ""}.
|
|
716
1113
|
|
|
717
1114
|
Respond in TWO sections, clearly separated by a line containing only "---":
|
|
718
1115
|
|
|
@@ -722,17 +1119,24 @@ A short paragraph: what kind of recording this is, the setting, the main topics,
|
|
|
722
1119
|
ROSTER
|
|
723
1120
|
A bulleted speaker roster. For each distinct speaker you can identify, give:
|
|
724
1121
|
- A short label to use consistently (a name/role if you can infer it, e.g. "Presenter (Hrishi)", else "Speaker A").
|
|
725
|
-
- A one-line description (
|
|
1122
|
+
- A one-line description anchored to the VOICE itself (pitch, pace, accent, audio quality/mic distance) plus role if evident.
|
|
726
1123
|
List the people you can distinguish. Do not invent names you didn't hear. If only one person speaks, say so.
|
|
727
1124
|
|
|
1125
|
+
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.
|
|
1126
|
+
|
|
728
1127
|
File: ${fileName}`;
|
|
729
1128
|
}
|
|
730
|
-
async function describeMeeting(client, model, files, fileName, instructions) {
|
|
731
|
-
const res = await client.generate(
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
1129
|
+
async function describeMeeting(client, model, files, fileName, instructions, audioSampleCount = 1) {
|
|
1130
|
+
const res = await client.generate(
|
|
1131
|
+
model,
|
|
1132
|
+
descriptionPrompt(fileName, instructions, audioSampleCount),
|
|
1133
|
+
files,
|
|
1134
|
+
{
|
|
1135
|
+
temperature: 0.2,
|
|
1136
|
+
maxRetries: 3,
|
|
1137
|
+
logKind: "describe"
|
|
1138
|
+
}
|
|
1139
|
+
);
|
|
736
1140
|
const text = res.text || "";
|
|
737
1141
|
const parts = text.split(/\n---\n|\n\s*---\s*\n/);
|
|
738
1142
|
const description = parts[0]?.trim() || text.trim();
|
|
@@ -749,14 +1153,23 @@ var TRANSCRIPT_SCHEMA = {
|
|
|
749
1153
|
items: {
|
|
750
1154
|
type: "OBJECT",
|
|
751
1155
|
properties: {
|
|
752
|
-
speaker: {
|
|
753
|
-
|
|
1156
|
+
speaker: {
|
|
1157
|
+
type: "STRING",
|
|
1158
|
+
description: "Speaker label. Use an identified name from the roster if confident, else 'Speaker A', 'Speaker B', etc."
|
|
1159
|
+
},
|
|
1160
|
+
start: {
|
|
1161
|
+
type: "STRING",
|
|
1162
|
+
description: "Relative start time as mm:ss (00:00 = start of this audio chunk)"
|
|
1163
|
+
},
|
|
754
1164
|
end: { type: "STRING", description: "Relative end time as mm:ss" },
|
|
755
|
-
text: {
|
|
1165
|
+
text: {
|
|
1166
|
+
type: "STRING",
|
|
1167
|
+
description: "Verbatim transcribed words, including fillers and false starts"
|
|
1168
|
+
},
|
|
756
1169
|
tone: {
|
|
757
1170
|
type: "ARRAY",
|
|
758
1171
|
items: { type: "STRING" },
|
|
759
|
-
description: "Tone
|
|
1172
|
+
description: "Tone tags ONLY when something clearly stands out (laughing, sarcastic, agitated, whispering). Empty array for normal speech \u2014 most segments."
|
|
760
1173
|
}
|
|
761
1174
|
},
|
|
762
1175
|
required: ["speaker", "start", "end", "text"]
|
|
@@ -771,19 +1184,40 @@ function transcriptionPrompt(ctx) {
|
|
|
771
1184
|
`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.`
|
|
772
1185
|
);
|
|
773
1186
|
parts.push("");
|
|
774
|
-
parts.push(
|
|
1187
|
+
parts.push(
|
|
1188
|
+
`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.`
|
|
1189
|
+
);
|
|
775
1190
|
parts.push("");
|
|
776
1191
|
parts.push("For each segment provide:");
|
|
777
|
-
parts.push(
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
parts.push(
|
|
1192
|
+
parts.push(
|
|
1193
|
+
"- 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."
|
|
1194
|
+
);
|
|
1195
|
+
parts.push(
|
|
1196
|
+
"- 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."
|
|
1197
|
+
);
|
|
1198
|
+
parts.push(
|
|
1199
|
+
"- text: the verbatim words, including fillers (um, uh), false starts, and corrections. Do not paraphrase."
|
|
1200
|
+
);
|
|
1201
|
+
parts.push(
|
|
1202
|
+
'- 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".'
|
|
1203
|
+
);
|
|
781
1204
|
parts.push("");
|
|
782
1205
|
parts.push("Rules:");
|
|
783
|
-
parts.push(
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
parts.push(
|
|
1206
|
+
parts.push(
|
|
1207
|
+
"- Cover the ENTIRE audio with no gaps. Timestamps must be monotonic non-decreasing."
|
|
1208
|
+
);
|
|
1209
|
+
parts.push(
|
|
1210
|
+
"- Capture interruptions and overlapping talk as separate, adjacent segments even if times overlap."
|
|
1211
|
+
);
|
|
1212
|
+
parts.push(
|
|
1213
|
+
"- Listen for voice characteristics (pitch, accent, mic distance), not just content. Two people agreeing with each other are still two segments."
|
|
1214
|
+
);
|
|
1215
|
+
parts.push(
|
|
1216
|
+
"- Do not invent content not present in the audio. If inaudible, write [inaudible]."
|
|
1217
|
+
);
|
|
1218
|
+
parts.push(
|
|
1219
|
+
"- Keep speaker labels consistent within this chunk; the same voice = same label."
|
|
1220
|
+
);
|
|
787
1221
|
if (ctx.description) {
|
|
788
1222
|
parts.push("");
|
|
789
1223
|
parts.push("MEETING CONTEXT:");
|
|
@@ -791,12 +1225,20 @@ function transcriptionPrompt(ctx) {
|
|
|
791
1225
|
}
|
|
792
1226
|
if (ctx.roster) {
|
|
793
1227
|
parts.push("");
|
|
794
|
-
parts.push(
|
|
1228
|
+
parts.push(
|
|
1229
|
+
"SPEAKER ROSTER (context about who is present \u2014 but its name-to-voice binding may be wrong):"
|
|
1230
|
+
);
|
|
795
1231
|
parts.push(ctx.roster);
|
|
1232
|
+
parts.push("");
|
|
1233
|
+
parts.push(
|
|
1234
|
+
"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."
|
|
1235
|
+
);
|
|
796
1236
|
}
|
|
797
1237
|
if (ctx.previousTail) {
|
|
798
1238
|
parts.push("");
|
|
799
|
-
parts.push(
|
|
1239
|
+
parts.push(
|
|
1240
|
+
"TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):"
|
|
1241
|
+
);
|
|
800
1242
|
parts.push(ctx.previousTail);
|
|
801
1243
|
}
|
|
802
1244
|
if (ctx.instructions) {
|
|
@@ -805,7 +1247,9 @@ function transcriptionPrompt(ctx) {
|
|
|
805
1247
|
parts.push(ctx.instructions);
|
|
806
1248
|
}
|
|
807
1249
|
parts.push("");
|
|
808
|
-
parts.push(
|
|
1250
|
+
parts.push(
|
|
1251
|
+
"Return JSON matching the schema: { segments: [ {speaker, start, end, text, tone} ] }"
|
|
1252
|
+
);
|
|
809
1253
|
return parts.join("\n");
|
|
810
1254
|
}
|
|
811
1255
|
|
|
@@ -831,7 +1275,10 @@ function timestampToSeconds(timestamp) {
|
|
|
831
1275
|
function parseSrtTiming(timingString) {
|
|
832
1276
|
const parts = timingString.split("-->");
|
|
833
1277
|
if (parts.length !== 2) return null;
|
|
834
|
-
return {
|
|
1278
|
+
return {
|
|
1279
|
+
start: timestampToSeconds(parts[0].trim()),
|
|
1280
|
+
end: timestampToSeconds(parts[1].trim())
|
|
1281
|
+
};
|
|
835
1282
|
}
|
|
836
1283
|
function formatSrtTiming(startSeconds, endSeconds) {
|
|
837
1284
|
return `${secondsToTimestamp(startSeconds)} --> ${secondsToTimestamp(endSeconds)}`;
|
|
@@ -845,6 +1292,16 @@ function parseMmSs(timeStr) {
|
|
|
845
1292
|
if (seconds < 0 || seconds >= 60) return null;
|
|
846
1293
|
return minutes * 60 + seconds;
|
|
847
1294
|
}
|
|
1295
|
+
function formatDuration(seconds) {
|
|
1296
|
+
const hours = Math.floor(seconds / 3600);
|
|
1297
|
+
const minutes = Math.floor(seconds % 3600 / 60);
|
|
1298
|
+
const remaining = Math.floor(seconds % 60);
|
|
1299
|
+
const parts = [];
|
|
1300
|
+
if (hours > 0) parts.push(`${hours}h`);
|
|
1301
|
+
if (minutes > 0) parts.push(`${minutes}m`);
|
|
1302
|
+
parts.push(`${remaining}s`);
|
|
1303
|
+
return parts.join(" ");
|
|
1304
|
+
}
|
|
848
1305
|
|
|
849
1306
|
// src/transcribe/llm-transcribe.ts
|
|
850
1307
|
var MIN_SEGMENTS = 3;
|
|
@@ -868,7 +1325,9 @@ function parseLlmSegments(data, chunkOffsetSec) {
|
|
|
868
1325
|
const end = toAbsolute(seg.end, chunkOffsetSec);
|
|
869
1326
|
if (start === null || end === null || end < start) {
|
|
870
1327
|
dropped++;
|
|
871
|
-
logger.debug(
|
|
1328
|
+
logger.debug(
|
|
1329
|
+
`[llm] dropping segment (bad time ${seg.start}-${seg.end}): "${(seg.text || "").slice(0, 40)}"`
|
|
1330
|
+
);
|
|
872
1331
|
continue;
|
|
873
1332
|
}
|
|
874
1333
|
out.push({
|
|
@@ -885,16 +1344,31 @@ function parseLlmSegments(data, chunkOffsetSec) {
|
|
|
885
1344
|
}
|
|
886
1345
|
function validate(segments, chunkDuration) {
|
|
887
1346
|
if (segments.length < MIN_SEGMENTS) {
|
|
888
|
-
return {
|
|
1347
|
+
return {
|
|
1348
|
+
isValid: false,
|
|
1349
|
+
spanSec: 0,
|
|
1350
|
+
segmentCount: segments.length,
|
|
1351
|
+
message: `only ${segments.length} segments (min ${MIN_SEGMENTS})`
|
|
1352
|
+
};
|
|
889
1353
|
}
|
|
890
1354
|
const first = segments[0].startSec;
|
|
891
1355
|
const last = segments[segments.length - 1].endSec;
|
|
892
1356
|
const span = last - first;
|
|
893
1357
|
const minSpan = chunkDuration * MIN_SPAN_RATIO;
|
|
894
1358
|
if (span < minSpan) {
|
|
895
|
-
return {
|
|
1359
|
+
return {
|
|
1360
|
+
isValid: false,
|
|
1361
|
+
spanSec: span,
|
|
1362
|
+
segmentCount: segments.length,
|
|
1363
|
+
message: `span ${span.toFixed(0)}s < ${minSpan.toFixed(0)}s required (${MIN_SPAN_RATIO * 100}% of chunk)`
|
|
1364
|
+
};
|
|
896
1365
|
}
|
|
897
|
-
return {
|
|
1366
|
+
return {
|
|
1367
|
+
isValid: true,
|
|
1368
|
+
spanSec: span,
|
|
1369
|
+
segmentCount: segments.length,
|
|
1370
|
+
message: `ok (${segments.length} segments, ${span.toFixed(0)}s span)`
|
|
1371
|
+
};
|
|
898
1372
|
}
|
|
899
1373
|
async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts) {
|
|
900
1374
|
const validationRetries = opts.validationRetries ?? 1;
|
|
@@ -918,22 +1392,35 @@ async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opt
|
|
|
918
1392
|
segments: [],
|
|
919
1393
|
raw: gen.raw,
|
|
920
1394
|
usage: gen.usage,
|
|
921
|
-
validation: {
|
|
1395
|
+
validation: {
|
|
1396
|
+
isValid: false,
|
|
1397
|
+
spanSec: 0,
|
|
1398
|
+
segmentCount: 0,
|
|
1399
|
+
message: gen.error || "no data"
|
|
1400
|
+
},
|
|
922
1401
|
error: gen.error
|
|
923
1402
|
};
|
|
924
|
-
logger.warn(
|
|
1403
|
+
logger.warn(
|
|
1404
|
+
`[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`
|
|
1405
|
+
);
|
|
925
1406
|
continue;
|
|
926
1407
|
}
|
|
927
1408
|
const { segments, dropped } = parseLlmSegments(gen.data, chunkStartSec);
|
|
928
1409
|
const v = validate(segments, opts.chunkDurationSec);
|
|
929
1410
|
lastResult = { segments, raw: gen.raw, usage: gen.usage, validation: v };
|
|
930
1411
|
if (v.isValid) {
|
|
931
|
-
logger.info(
|
|
1412
|
+
logger.info(
|
|
1413
|
+
`[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`
|
|
1414
|
+
);
|
|
932
1415
|
return lastResult;
|
|
933
1416
|
}
|
|
934
|
-
logger.warn(
|
|
1417
|
+
logger.warn(
|
|
1418
|
+
`[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`
|
|
1419
|
+
);
|
|
935
1420
|
}
|
|
936
|
-
logger.error(
|
|
1421
|
+
logger.error(
|
|
1422
|
+
`[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`
|
|
1423
|
+
);
|
|
937
1424
|
return lastResult;
|
|
938
1425
|
}
|
|
939
1426
|
|
|
@@ -945,8 +1432,8 @@ function tokenize(text) {
|
|
|
945
1432
|
const out = [];
|
|
946
1433
|
for (const raw of text.split(/\s+/)) {
|
|
947
1434
|
if (!raw) continue;
|
|
948
|
-
const
|
|
949
|
-
if (
|
|
1435
|
+
const norm2 = normalize(raw);
|
|
1436
|
+
if (norm2) out.push({ original: raw, norm: norm2 });
|
|
950
1437
|
}
|
|
951
1438
|
return out;
|
|
952
1439
|
}
|
|
@@ -1070,7 +1557,11 @@ function transferTiming(llm, asr, ops) {
|
|
|
1070
1557
|
for (const op of ops) {
|
|
1071
1558
|
if (op.type === "match" || op.type === "substitute") {
|
|
1072
1559
|
const a = asr[op.asr];
|
|
1073
|
-
times[op.llm] = {
|
|
1560
|
+
times[op.llm] = {
|
|
1561
|
+
start: a.start,
|
|
1562
|
+
end: a.end,
|
|
1563
|
+
matched: op.type === "match" && !op.fuzzy
|
|
1564
|
+
};
|
|
1074
1565
|
}
|
|
1075
1566
|
}
|
|
1076
1567
|
for (let k = 0; k < times.length; k++) {
|
|
@@ -1239,7 +1730,12 @@ function fillAsrGaps(segments, asrWords, asrUtterances) {
|
|
|
1239
1730
|
tone: [],
|
|
1240
1731
|
confidence: 0,
|
|
1241
1732
|
timingSource: "timestamped",
|
|
1242
|
-
words: words.map((w) => ({
|
|
1733
|
+
words: words.map((w) => ({
|
|
1734
|
+
text: w.text,
|
|
1735
|
+
start: w.start,
|
|
1736
|
+
end: w.end,
|
|
1737
|
+
matched: true
|
|
1738
|
+
})),
|
|
1243
1739
|
sourceIndex: -1
|
|
1244
1740
|
});
|
|
1245
1741
|
}
|
|
@@ -1252,8 +1748,19 @@ function overlap(s1, e1, s2, e2) {
|
|
|
1252
1748
|
return Math.max(0, Math.min(e1, e2) - Math.max(s1, s2));
|
|
1253
1749
|
}
|
|
1254
1750
|
function isGenericLabel(label) {
|
|
1255
|
-
return /^(speaker\s+[a-z0-9]+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(
|
|
1751
|
+
return /^(speaker\s+[a-z0-9]+|voice\s+\S+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(
|
|
1752
|
+
label.trim()
|
|
1753
|
+
);
|
|
1754
|
+
}
|
|
1755
|
+
function countTurnTransitions(utterances, a, b) {
|
|
1756
|
+
const seq = [...utterances].sort((x, y) => x.start - y.start).map((u) => u.speaker).filter((s) => s === a || s === b);
|
|
1757
|
+
let transitions = 0;
|
|
1758
|
+
for (let i = 1; i < seq.length; i++) {
|
|
1759
|
+
if (seq[i] !== seq[i - 1]) transitions++;
|
|
1760
|
+
}
|
|
1761
|
+
return transitions;
|
|
1256
1762
|
}
|
|
1763
|
+
var MAX_MERGE_TRANSITIONS = 3;
|
|
1257
1764
|
function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
|
|
1258
1765
|
const hasDiarization = opts.hasDiarization ?? true;
|
|
1259
1766
|
const out = segments.map((seg) => ({ seg, asrSpeaker: "" }));
|
|
@@ -1305,7 +1812,18 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
|
|
|
1305
1812
|
const label = dominantLabel[asrSp] ?? asrSp;
|
|
1306
1813
|
let groupId;
|
|
1307
1814
|
if (!isGenericLabel(label)) {
|
|
1308
|
-
|
|
1815
|
+
const candidate = Object.keys(groupLabel).find((g) => groupLabel[g] === label);
|
|
1816
|
+
if (candidate && hasDiarization) {
|
|
1817
|
+
const partners = groupAsrVoices[candidate] ?? [];
|
|
1818
|
+
const maxTransitions = Math.max(
|
|
1819
|
+
...partners.map((p) => countTurnTransitions(asrUtterances, p, asrSp))
|
|
1820
|
+
);
|
|
1821
|
+
if (maxTransitions <= MAX_MERGE_TRANSITIONS) {
|
|
1822
|
+
groupId = candidate;
|
|
1823
|
+
}
|
|
1824
|
+
} else if (candidate) {
|
|
1825
|
+
groupId = candidate;
|
|
1826
|
+
}
|
|
1309
1827
|
}
|
|
1310
1828
|
if (!groupId) {
|
|
1311
1829
|
groupId = asrSp;
|
|
@@ -1315,15 +1833,24 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
|
|
|
1315
1833
|
groupTalk[groupId] = (groupTalk[groupId] ?? 0) + (asrDuration[asrSp] ?? 0);
|
|
1316
1834
|
(groupAsrVoices[groupId] ??= []).push(asrSp);
|
|
1317
1835
|
}
|
|
1318
|
-
const groupsByTalk = Object.keys(groupTalk).sort(
|
|
1836
|
+
const groupsByTalk = Object.keys(groupTalk).sort(
|
|
1837
|
+
(a, b) => groupTalk[b] - groupTalk[a]
|
|
1838
|
+
);
|
|
1319
1839
|
const groupToGlobal = {};
|
|
1320
1840
|
groupsByTalk.forEach((g, i) => {
|
|
1321
1841
|
groupToGlobal[g] = `Speaker ${String.fromCharCode(65 + i)}`;
|
|
1322
1842
|
});
|
|
1843
|
+
const labelGroupCount = {};
|
|
1844
|
+
for (const g of groupsByTalk) {
|
|
1845
|
+
const label = groupLabel[g];
|
|
1846
|
+
if (!isGenericLabel(label))
|
|
1847
|
+
labelGroupCount[label] = (labelGroupCount[label] ?? 0) + 1;
|
|
1848
|
+
}
|
|
1323
1849
|
const displayNames = {};
|
|
1324
1850
|
for (const g of groupsByTalk) {
|
|
1325
1851
|
const label = groupLabel[g];
|
|
1326
|
-
|
|
1852
|
+
const contested = (labelGroupCount[label] ?? 0) > 1;
|
|
1853
|
+
displayNames[groupToGlobal[g]] = isGenericLabel(label) || contested ? groupToGlobal[g] : label;
|
|
1327
1854
|
}
|
|
1328
1855
|
const llmLabelToAsr = {};
|
|
1329
1856
|
for (const o of out) {
|
|
@@ -1357,6 +1884,111 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
|
|
|
1357
1884
|
return { segments: updated, speakers, displayNames, llmLabelToAsr };
|
|
1358
1885
|
}
|
|
1359
1886
|
|
|
1887
|
+
// src/diarize/split-mixed.ts
|
|
1888
|
+
var MIN_RUN_WORDS = 5;
|
|
1889
|
+
var MIN_RUN_SEC = 2;
|
|
1890
|
+
function clusterAt(utterances, t) {
|
|
1891
|
+
let best = "";
|
|
1892
|
+
let bestDist = Infinity;
|
|
1893
|
+
for (const u of utterances) {
|
|
1894
|
+
if (t >= u.start && t <= u.end) return u.speaker;
|
|
1895
|
+
const d = t < u.start ? u.start - t : t - u.end;
|
|
1896
|
+
if (d < bestDist) {
|
|
1897
|
+
bestDist = d;
|
|
1898
|
+
best = u.speaker;
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1901
|
+
return best;
|
|
1902
|
+
}
|
|
1903
|
+
function buildRuns(words, utterances) {
|
|
1904
|
+
const clusters = words.map(
|
|
1905
|
+
(w) => w.matched ? clusterAt(utterances, (w.start + w.end) / 2) : null
|
|
1906
|
+
);
|
|
1907
|
+
for (let i = 1; i < clusters.length; i++) {
|
|
1908
|
+
if (clusters[i] === null) clusters[i] = clusters[i - 1] ?? null;
|
|
1909
|
+
}
|
|
1910
|
+
for (let i = clusters.length - 2; i >= 0; i--) {
|
|
1911
|
+
if (clusters[i] === null) clusters[i] = clusters[i + 1] ?? null;
|
|
1912
|
+
}
|
|
1913
|
+
const runs = [];
|
|
1914
|
+
for (let i = 0; i < clusters.length; i++) {
|
|
1915
|
+
const c = clusters[i] ?? "";
|
|
1916
|
+
const last = runs[runs.length - 1];
|
|
1917
|
+
if (last && last.cluster === c) last.endIdx = i + 1;
|
|
1918
|
+
else runs.push({ cluster: c, startIdx: i, endIdx: i + 1 });
|
|
1919
|
+
}
|
|
1920
|
+
return runs;
|
|
1921
|
+
}
|
|
1922
|
+
function runSec(run2, words) {
|
|
1923
|
+
return words[run2.endIdx - 1].end - words[run2.startIdx].start;
|
|
1924
|
+
}
|
|
1925
|
+
function foldShortRuns(runs, words) {
|
|
1926
|
+
let out = runs;
|
|
1927
|
+
let changed = true;
|
|
1928
|
+
while (changed && out.length > 1) {
|
|
1929
|
+
changed = false;
|
|
1930
|
+
for (let i = 0; i < out.length; i++) {
|
|
1931
|
+
const r = out[i];
|
|
1932
|
+
const nWords = r.endIdx - r.startIdx;
|
|
1933
|
+
if (nWords >= MIN_RUN_WORDS || runSec(r, words) >= MIN_RUN_SEC) continue;
|
|
1934
|
+
const prev = out[i - 1];
|
|
1935
|
+
const next = out[i + 1];
|
|
1936
|
+
const target = prev && next ? prev.endIdx - prev.startIdx >= next.endIdx - next.startIdx ? prev : next : prev ?? next;
|
|
1937
|
+
if (!target) continue;
|
|
1938
|
+
if (target === prev) prev.endIdx = r.endIdx;
|
|
1939
|
+
else next.startIdx = r.startIdx;
|
|
1940
|
+
out = out.filter((_, j) => j !== i);
|
|
1941
|
+
changed = true;
|
|
1942
|
+
break;
|
|
1943
|
+
}
|
|
1944
|
+
const merged = [];
|
|
1945
|
+
for (const r of out) {
|
|
1946
|
+
const last = merged[merged.length - 1];
|
|
1947
|
+
if (last && last.cluster === r.cluster) last.endIdx = r.endIdx;
|
|
1948
|
+
else merged.push({ ...r });
|
|
1949
|
+
}
|
|
1950
|
+
out = merged;
|
|
1951
|
+
}
|
|
1952
|
+
return out;
|
|
1953
|
+
}
|
|
1954
|
+
function splitMixedVoiceSegments(segments, utterances) {
|
|
1955
|
+
if (utterances.length === 0) return segments;
|
|
1956
|
+
const out = [];
|
|
1957
|
+
let splits = 0;
|
|
1958
|
+
for (const seg of segments) {
|
|
1959
|
+
const matched = seg.words.filter((w) => w.matched).length;
|
|
1960
|
+
if (seg.words.length < MIN_RUN_WORDS * 2 || matched < seg.words.length * 0.4) {
|
|
1961
|
+
out.push(seg);
|
|
1962
|
+
continue;
|
|
1963
|
+
}
|
|
1964
|
+
const runs = foldShortRuns(buildRuns(seg.words, utterances), seg.words);
|
|
1965
|
+
if (runs.length <= 1) {
|
|
1966
|
+
out.push(seg);
|
|
1967
|
+
continue;
|
|
1968
|
+
}
|
|
1969
|
+
splits += runs.length - 1;
|
|
1970
|
+
const lens = runs.map((r) => r.endIdx - r.startIdx);
|
|
1971
|
+
const dominantIdx = lens.indexOf(Math.max(...lens));
|
|
1972
|
+
runs.forEach((run2, ri) => {
|
|
1973
|
+
const words = seg.words.slice(run2.startIdx, run2.endIdx);
|
|
1974
|
+
out.push({
|
|
1975
|
+
...seg,
|
|
1976
|
+
start: words[0].start,
|
|
1977
|
+
end: words[words.length - 1].end,
|
|
1978
|
+
text: words.map((w) => w.text).join(" "),
|
|
1979
|
+
words,
|
|
1980
|
+
speaker: ri === dominantIdx ? seg.speaker : `Voice ${run2.cluster}`
|
|
1981
|
+
});
|
|
1982
|
+
});
|
|
1983
|
+
}
|
|
1984
|
+
if (splits > 0) {
|
|
1985
|
+
logger.info(
|
|
1986
|
+
`split ${splits} mixed-voice boundary(ies) across ${segments.length} segments`
|
|
1987
|
+
);
|
|
1988
|
+
}
|
|
1989
|
+
return out.sort((a, b) => a.start - b.start);
|
|
1990
|
+
}
|
|
1991
|
+
|
|
1360
1992
|
// src/providers/openai-compat.ts
|
|
1361
1993
|
var PROVIDER_BASE = {
|
|
1362
1994
|
deepseek: "https://api.deepseek.com/v1",
|
|
@@ -1380,7 +2012,7 @@ var OpenAICompatClient = class _OpenAICompatClient {
|
|
|
1380
2012
|
}
|
|
1381
2013
|
async chat(model, messages, opts = {}) {
|
|
1382
2014
|
const m = model ?? this.defaultModel;
|
|
1383
|
-
const maxRetries = opts.maxRetries ??
|
|
2015
|
+
const maxRetries = opts.maxRetries ?? 5;
|
|
1384
2016
|
const body = {
|
|
1385
2017
|
model: m,
|
|
1386
2018
|
messages,
|
|
@@ -1390,6 +2022,9 @@ var OpenAICompatClient = class _OpenAICompatClient {
|
|
|
1390
2022
|
if (opts.responseJson) {
|
|
1391
2023
|
body.response_format = { type: "json_object" };
|
|
1392
2024
|
}
|
|
2025
|
+
if (this.providerName === "gemini") {
|
|
2026
|
+
body.reasoning_effort = "low";
|
|
2027
|
+
}
|
|
1393
2028
|
let lastError;
|
|
1394
2029
|
const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
|
|
1395
2030
|
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
@@ -1427,6 +2062,14 @@ var OpenAICompatClient = class _OpenAICompatClient {
|
|
|
1427
2062
|
return { text, usage };
|
|
1428
2063
|
} catch (err) {
|
|
1429
2064
|
lastError = err instanceof Error ? err.message : String(err);
|
|
2065
|
+
if (body.response_format && /response_format/i.test(lastError)) {
|
|
2066
|
+
delete body.response_format;
|
|
2067
|
+
continue;
|
|
2068
|
+
}
|
|
2069
|
+
if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
|
|
2070
|
+
delete body.reasoning_effort;
|
|
2071
|
+
continue;
|
|
2072
|
+
}
|
|
1430
2073
|
logLlmCall({
|
|
1431
2074
|
ts: new Date(t0).toISOString(),
|
|
1432
2075
|
provider: this.providerName,
|
|
@@ -1438,61 +2081,109 @@ var OpenAICompatClient = class _OpenAICompatClient {
|
|
|
1438
2081
|
attempt: attempt + 1,
|
|
1439
2082
|
error: lastError
|
|
1440
2083
|
});
|
|
1441
|
-
if (attempt < maxRetries - 1)
|
|
2084
|
+
if (attempt < maxRetries - 1)
|
|
2085
|
+
await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
|
|
1442
2086
|
}
|
|
1443
2087
|
}
|
|
1444
2088
|
return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
|
|
1445
2089
|
}
|
|
1446
2090
|
async chatJson(model, messages, opts = {}) {
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
2091
|
+
let lastRaw = "";
|
|
2092
|
+
let lastError;
|
|
2093
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
2094
|
+
const res = await this.chat(model, messages, { ...opts, responseJson: true });
|
|
2095
|
+
lastRaw = res.text;
|
|
2096
|
+
lastError = res.error;
|
|
2097
|
+
if (res.error || !res.text) continue;
|
|
2098
|
+
try {
|
|
2099
|
+
let txt = res.text.trim();
|
|
2100
|
+
const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
|
|
2101
|
+
if (fence && fence[1]) txt = fence[1];
|
|
2102
|
+
return { data: JSON.parse(txt), raw: res.text };
|
|
2103
|
+
} catch (err) {
|
|
2104
|
+
lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
|
|
2105
|
+
}
|
|
1456
2106
|
}
|
|
2107
|
+
return { data: null, raw: lastRaw, error: lastError };
|
|
1457
2108
|
}
|
|
1458
2109
|
};
|
|
1459
2110
|
|
|
1460
2111
|
// src/diarize/identify.ts
|
|
2112
|
+
var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
|
|
1461
2113
|
function buildTranscriptExcerpt(segments, speakers) {
|
|
2114
|
+
const speakerHeader = (sp) => {
|
|
2115
|
+
const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
|
|
2116
|
+
return `${sp.id} (${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s talk time${voices})`;
|
|
2117
|
+
};
|
|
2118
|
+
const totalChars = segments.reduce((n, s) => n + s.text.length, 0);
|
|
2119
|
+
if (totalChars <= MAX_FULL_TRANSCRIPT_CHARS) {
|
|
2120
|
+
const parts2 = [
|
|
2121
|
+
"SPEAKERS:",
|
|
2122
|
+
...speakers.map((sp) => `- ${speakerHeader(sp)}`),
|
|
2123
|
+
"",
|
|
2124
|
+
"FULL TRANSCRIPT (in order):"
|
|
2125
|
+
];
|
|
2126
|
+
for (const s of segments) parts2.push(`[${s.speaker}] ${s.text}`);
|
|
2127
|
+
return parts2.join("\n");
|
|
2128
|
+
}
|
|
1462
2129
|
const bySpeaker = {};
|
|
1463
2130
|
for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
|
|
1464
2131
|
const parts = [];
|
|
1465
2132
|
for (const sp of speakers) {
|
|
1466
2133
|
const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
|
|
1467
|
-
|
|
1468
|
-
parts.push(
|
|
1469
|
-
`### ${sp.id} (${sp.name || "unknown"}, ${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s${voices})`
|
|
1470
|
-
);
|
|
2134
|
+
parts.push(`### ${speakerHeader(sp)}`);
|
|
1471
2135
|
for (const s of segs) parts.push(` ${s.text}`);
|
|
1472
2136
|
}
|
|
1473
2137
|
return parts.join("\n");
|
|
1474
2138
|
}
|
|
1475
|
-
function identifyPrompt(transcriptExcerpt, roster, knownSpeakers) {
|
|
1476
|
-
|
|
2139
|
+
function identifyPrompt(transcriptExcerpt, roster, knownSpeakers, nameHints, sourceFileName) {
|
|
2140
|
+
const hintBlock = nameHints && Object.keys(nameHints).length ? `
|
|
2141
|
+
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):
|
|
2142
|
+
${Object.entries(
|
|
2143
|
+
nameHints
|
|
2144
|
+
).map(([id, n]) => ` ${id} was tentatively called "${n}"`).join("\n")}
|
|
2145
|
+
` : "";
|
|
2146
|
+
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.
|
|
1477
2147
|
|
|
1478
2148
|
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 ("").
|
|
1479
2149
|
|
|
2150
|
+
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.
|
|
2151
|
+
|
|
2152
|
+
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.
|
|
2153
|
+
|
|
2154
|
+
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).
|
|
2155
|
+
|
|
1480
2156
|
${knownSpeakers && knownSpeakers.length ? `Known possible speakers: ${knownSpeakers.join(", ")}
|
|
2157
|
+
` : ""}${sourceFileName ? `RECORDING FILENAME (often names participants): ${sourceFileName}
|
|
1481
2158
|
` : ""}ROSTER:
|
|
1482
2159
|
${roster}
|
|
1483
|
-
|
|
1484
|
-
TRANSCRIPT
|
|
2160
|
+
${hintBlock}
|
|
2161
|
+
TRANSCRIPT:
|
|
1485
2162
|
${transcriptExcerpt}
|
|
1486
2163
|
|
|
1487
|
-
Respond as JSON: { "speakers": [ { "id": "<exact speaker id from the headers>", "name": "Full Name or Role", "confidence": "high|medium|low", "evidence": "short quote
|
|
1488
|
-
Use the EXACT speaker id strings
|
|
2164
|
+
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" }
|
|
2165
|
+
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.`;
|
|
1489
2166
|
}
|
|
1490
|
-
async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers) {
|
|
2167
|
+
async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers, nameHints, sourceFileName) {
|
|
1491
2168
|
const excerpt = buildTranscriptExcerpt(segments, speakers);
|
|
1492
2169
|
const { data, error } = await client.chatJson(
|
|
1493
2170
|
model,
|
|
1494
|
-
[
|
|
1495
|
-
|
|
2171
|
+
[
|
|
2172
|
+
{
|
|
2173
|
+
role: "user",
|
|
2174
|
+
content: identifyPrompt(
|
|
2175
|
+
excerpt,
|
|
2176
|
+
roster,
|
|
2177
|
+
knownSpeakers,
|
|
2178
|
+
nameHints,
|
|
2179
|
+
sourceFileName
|
|
2180
|
+
)
|
|
2181
|
+
}
|
|
2182
|
+
],
|
|
2183
|
+
// 8000 tokens: verbose models quote long verbatim evidence, and Gemini's compat
|
|
2184
|
+
// endpoint spends part of the budget on thinking — tighter caps truncated
|
|
2185
|
+
// mid-JSON and silently emptied whole identify passes (observed live, twice).
|
|
2186
|
+
{ temperature: 0.1, maxTokens: 8e3, logKind: "identify" }
|
|
1496
2187
|
);
|
|
1497
2188
|
if (error || !data) {
|
|
1498
2189
|
return { nameMap: {}, speakers: [], reasoning: error || "no response" };
|
|
@@ -1504,6 +2195,368 @@ async function identifySpeakers(client, model, segments, speakers, roster, known
|
|
|
1504
2195
|
return { nameMap, speakers: data.speakers || [], reasoning: data.reasoning || "" };
|
|
1505
2196
|
}
|
|
1506
2197
|
|
|
2198
|
+
// src/diarize/identify2.ts
|
|
2199
|
+
var norm = (s) => s.toLowerCase().replace(/['’]/g, "").replace(/[^\p{L}\p{N}\s]/gu, " ").replace(/\s+/g, " ").trim();
|
|
2200
|
+
function withinOneEdit(a, b) {
|
|
2201
|
+
if (a === b) return true;
|
|
2202
|
+
if (Math.abs(a.length - b.length) > 1) return false;
|
|
2203
|
+
const [s, l] = a.length <= b.length ? [a, b] : [b, a];
|
|
2204
|
+
let i = 0;
|
|
2205
|
+
let j = 0;
|
|
2206
|
+
let edits = 0;
|
|
2207
|
+
while (i < s.length && j < l.length) {
|
|
2208
|
+
if (s[i] === l[j]) {
|
|
2209
|
+
i++;
|
|
2210
|
+
j++;
|
|
2211
|
+
continue;
|
|
2212
|
+
}
|
|
2213
|
+
if (++edits > 1) return false;
|
|
2214
|
+
if (s.length === l.length) i++;
|
|
2215
|
+
j++;
|
|
2216
|
+
}
|
|
2217
|
+
return edits + (l.length - j) <= 1;
|
|
2218
|
+
}
|
|
2219
|
+
function tokensMatch(a, b) {
|
|
2220
|
+
if (a === b) return true;
|
|
2221
|
+
return a.length >= 5 && b.length >= 5 && withinOneEdit(a, b);
|
|
2222
|
+
}
|
|
2223
|
+
function namesMatch(a, b) {
|
|
2224
|
+
const na = norm(a);
|
|
2225
|
+
const nb = norm(b);
|
|
2226
|
+
if (!na || !nb) return false;
|
|
2227
|
+
if (na === nb) return true;
|
|
2228
|
+
const ta = na.split(" ");
|
|
2229
|
+
const tb = nb.split(" ");
|
|
2230
|
+
const [small, big] = ta.length <= tb.length ? [ta, tb] : [tb, ta];
|
|
2231
|
+
return small.every((t) => big.some((u) => tokensMatch(t, u)));
|
|
2232
|
+
}
|
|
2233
|
+
function evidenceInTranscript(evidence, transcript) {
|
|
2234
|
+
if (!evidence) return false;
|
|
2235
|
+
const ne = norm(evidence);
|
|
2236
|
+
if (ne.length < 8) return false;
|
|
2237
|
+
return transcript.includes(ne);
|
|
2238
|
+
}
|
|
2239
|
+
var INTRO_RE = /\b(?:[Mm]y name is|I am|I'm)[,\s]+([A-Z][\p{L}'’-]+(?:\s+[A-Z][\p{L}'’-]+)?)/gu;
|
|
2240
|
+
var INTRO_STOPWORDS = /* @__PURE__ */ new Set([
|
|
2241
|
+
"i",
|
|
2242
|
+
"im",
|
|
2243
|
+
"ive",
|
|
2244
|
+
"id",
|
|
2245
|
+
"ill",
|
|
2246
|
+
"you",
|
|
2247
|
+
"we",
|
|
2248
|
+
"they",
|
|
2249
|
+
"he",
|
|
2250
|
+
"she",
|
|
2251
|
+
"it",
|
|
2252
|
+
"so",
|
|
2253
|
+
"not",
|
|
2254
|
+
"just",
|
|
2255
|
+
"here",
|
|
2256
|
+
"there",
|
|
2257
|
+
"going",
|
|
2258
|
+
"gonna",
|
|
2259
|
+
"really",
|
|
2260
|
+
"very",
|
|
2261
|
+
"also",
|
|
2262
|
+
"still",
|
|
2263
|
+
"sure",
|
|
2264
|
+
"sorry",
|
|
2265
|
+
"happy",
|
|
2266
|
+
"glad",
|
|
2267
|
+
"excited",
|
|
2268
|
+
"curious",
|
|
2269
|
+
"the",
|
|
2270
|
+
"a",
|
|
2271
|
+
"an",
|
|
2272
|
+
"okay",
|
|
2273
|
+
"ok",
|
|
2274
|
+
"now",
|
|
2275
|
+
"like",
|
|
2276
|
+
"actually",
|
|
2277
|
+
"basically",
|
|
2278
|
+
"kind",
|
|
2279
|
+
"sort",
|
|
2280
|
+
"definitely"
|
|
2281
|
+
]);
|
|
2282
|
+
function findSelfIntroductions(segments) {
|
|
2283
|
+
const out = [];
|
|
2284
|
+
for (const seg of segments) {
|
|
2285
|
+
for (const m of seg.text.matchAll(INTRO_RE)) {
|
|
2286
|
+
const name = m[1].trim();
|
|
2287
|
+
const tokens = name.split(/\s+/).map((t) => t.toLowerCase().replace(/['’]/g, ""));
|
|
2288
|
+
if (tokens.some((t) => INTRO_STOPWORDS.has(t))) continue;
|
|
2289
|
+
if (name.replace(/[^\p{L}]/gu, "").length < 3) continue;
|
|
2290
|
+
out.push({
|
|
2291
|
+
speakerId: seg.speaker,
|
|
2292
|
+
introducedName: name,
|
|
2293
|
+
segmentText: seg.text.slice(0, 160)
|
|
2294
|
+
});
|
|
2295
|
+
}
|
|
2296
|
+
}
|
|
2297
|
+
return out;
|
|
2298
|
+
}
|
|
2299
|
+
function pickCompleteName(a, b) {
|
|
2300
|
+
if (!a) return b ?? "";
|
|
2301
|
+
if (!b) return a;
|
|
2302
|
+
return b.trim().split(/\s+/).length > a.trim().split(/\s+/).length ? b.trim() : a.trim();
|
|
2303
|
+
}
|
|
2304
|
+
function adjudicate(speakerId, a, b, transcriptNorm, intro, introCorroborated = false) {
|
|
2305
|
+
const base = {
|
|
2306
|
+
speakerId,
|
|
2307
|
+
nameA: a.name,
|
|
2308
|
+
nameB: b?.name,
|
|
2309
|
+
outcome: "kept-generic"
|
|
2310
|
+
};
|
|
2311
|
+
const aName = a.name?.trim() || void 0;
|
|
2312
|
+
const bName = b?.name?.trim() || void 0;
|
|
2313
|
+
if (b === void 0) {
|
|
2314
|
+
if (!aName) return base;
|
|
2315
|
+
return { ...base, outcome: "a-only", finalName: aName };
|
|
2316
|
+
}
|
|
2317
|
+
if (aName && bName && namesMatch(aName, bName)) {
|
|
2318
|
+
return { ...base, outcome: "agreed", finalName: pickCompleteName(aName, bName) };
|
|
2319
|
+
}
|
|
2320
|
+
if (intro) {
|
|
2321
|
+
if (aName && namesMatch(aName, intro))
|
|
2322
|
+
return { ...base, outcome: "tripwire", finalName: aName, note: `intro "${intro}"` };
|
|
2323
|
+
if (bName && namesMatch(bName, intro))
|
|
2324
|
+
return { ...base, outcome: "tripwire", finalName: bName, note: `intro "${intro}"` };
|
|
2325
|
+
if (introCorroborated) {
|
|
2326
|
+
return {
|
|
2327
|
+
...base,
|
|
2328
|
+
outcome: "tripwire",
|
|
2329
|
+
finalName: intro,
|
|
2330
|
+
note: `intro "${intro}" corroborated by roster/known speakers`
|
|
2331
|
+
};
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
if (aName && !bName) return { ...base, outcome: "a-only", finalName: aName };
|
|
2335
|
+
if (bName && !aName) return { ...base, outcome: "b-only", finalName: bName };
|
|
2336
|
+
const aOk = evidenceInTranscript(a.evidence, transcriptNorm);
|
|
2337
|
+
const bOk = evidenceInTranscript(b.evidence, transcriptNorm);
|
|
2338
|
+
if (aOk && !bOk)
|
|
2339
|
+
return {
|
|
2340
|
+
...base,
|
|
2341
|
+
outcome: "evidence-break",
|
|
2342
|
+
finalName: aName,
|
|
2343
|
+
note: "B evidence not in transcript"
|
|
2344
|
+
};
|
|
2345
|
+
if (bOk && !aOk)
|
|
2346
|
+
return {
|
|
2347
|
+
...base,
|
|
2348
|
+
outcome: "evidence-break",
|
|
2349
|
+
finalName: bName,
|
|
2350
|
+
note: "A evidence not in transcript"
|
|
2351
|
+
};
|
|
2352
|
+
return {
|
|
2353
|
+
...base,
|
|
2354
|
+
outcome: "kept-generic",
|
|
2355
|
+
note: "disagreement unresolved \u2014 not inventing a name"
|
|
2356
|
+
};
|
|
2357
|
+
}
|
|
2358
|
+
async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts) {
|
|
2359
|
+
const mode = opts.mode ?? "dual";
|
|
2360
|
+
const runPass = (r) => identifySpeakers(
|
|
2361
|
+
r.client,
|
|
2362
|
+
r.model,
|
|
2363
|
+
segments,
|
|
2364
|
+
speakers,
|
|
2365
|
+
opts.roster,
|
|
2366
|
+
opts.knownSpeakers,
|
|
2367
|
+
opts.nameHints,
|
|
2368
|
+
opts.sourceFileName
|
|
2369
|
+
);
|
|
2370
|
+
const wantB = mode === "dual" && reasonerB !== null;
|
|
2371
|
+
const [resA, resB] = await Promise.all([
|
|
2372
|
+
runPass(reasonerA),
|
|
2373
|
+
wantB ? runPass(reasonerB) : Promise.resolve(void 0)
|
|
2374
|
+
]);
|
|
2375
|
+
const passFailed = (r) => !!r && r.speakers.length === 0 && /fetch failed|HTTP \d|network|ENOTFOUND|JSON parse|no response/i.test(r.reasoning);
|
|
2376
|
+
if (passFailed(resA) && (!wantB || passFailed(resB))) {
|
|
2377
|
+
logger.warn(
|
|
2378
|
+
`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).`
|
|
2379
|
+
);
|
|
2380
|
+
}
|
|
2381
|
+
const transcriptNorm = norm(segments.map((s) => s.text).join(" "));
|
|
2382
|
+
const tripwires = findSelfIntroductions(segments);
|
|
2383
|
+
const introBySpeaker = /* @__PURE__ */ new Map();
|
|
2384
|
+
const conflicted = /* @__PURE__ */ new Set();
|
|
2385
|
+
for (const t of tripwires) {
|
|
2386
|
+
const prev = introBySpeaker.get(t.speakerId);
|
|
2387
|
+
if (prev && !namesMatch(prev, t.introducedName)) conflicted.add(t.speakerId);
|
|
2388
|
+
else introBySpeaker.set(t.speakerId, t.introducedName);
|
|
2389
|
+
}
|
|
2390
|
+
for (const id of conflicted) introBySpeaker.delete(id);
|
|
2391
|
+
const byIdA = new Map(resA.speakers.map((s) => [s.id, s]));
|
|
2392
|
+
const byIdB = resB ? new Map(resB.speakers.map((s) => [s.id, s])) : void 0;
|
|
2393
|
+
const decisions = [];
|
|
2394
|
+
const corroborationText = norm(
|
|
2395
|
+
`${opts.roster ?? ""} ${(opts.knownSpeakers ?? []).join(" ")}`
|
|
2396
|
+
);
|
|
2397
|
+
const isCorroborated = (name) => {
|
|
2398
|
+
if (!name) return false;
|
|
2399
|
+
const n = norm(name);
|
|
2400
|
+
return n.length >= 3 && corroborationText.includes(n);
|
|
2401
|
+
};
|
|
2402
|
+
const nameMap = {};
|
|
2403
|
+
for (const sp of speakers) {
|
|
2404
|
+
const a = byIdA.get(sp.id) ?? { name: resA.nameMap[sp.id] };
|
|
2405
|
+
const b = byIdB ? byIdB.get(sp.id) ?? { name: resB.nameMap[sp.id] } : void 0;
|
|
2406
|
+
const intro = introBySpeaker.get(sp.id);
|
|
2407
|
+
const d = adjudicate(
|
|
2408
|
+
sp.id,
|
|
2409
|
+
a ?? {},
|
|
2410
|
+
wantB ? b ?? {} : void 0,
|
|
2411
|
+
transcriptNorm,
|
|
2412
|
+
intro,
|
|
2413
|
+
isCorroborated(intro)
|
|
2414
|
+
);
|
|
2415
|
+
decisions.push(d);
|
|
2416
|
+
if (d.finalName) nameMap[sp.id] = d.finalName;
|
|
2417
|
+
}
|
|
2418
|
+
const STRENGTH = {
|
|
2419
|
+
agreed: 4,
|
|
2420
|
+
tripwire: 3,
|
|
2421
|
+
"evidence-break": 2,
|
|
2422
|
+
"a-only": 1,
|
|
2423
|
+
"b-only": 1,
|
|
2424
|
+
elimination: 1,
|
|
2425
|
+
"conflict-fallback": 0,
|
|
2426
|
+
"kept-generic": 0
|
|
2427
|
+
};
|
|
2428
|
+
const named = decisions.filter((d) => d.finalName);
|
|
2429
|
+
for (let i = 0; i < named.length; i++) {
|
|
2430
|
+
for (let j = i + 1; j < named.length; j++) {
|
|
2431
|
+
const di = named[i];
|
|
2432
|
+
const dj = named[j];
|
|
2433
|
+
if (!di.finalName || !dj.finalName) continue;
|
|
2434
|
+
if (!namesMatch(di.finalName, dj.finalName)) continue;
|
|
2435
|
+
const si = STRENGTH[di.outcome];
|
|
2436
|
+
const sj = STRENGTH[dj.outcome];
|
|
2437
|
+
const losers = si === sj ? [di, dj] : si < sj ? [di] : [dj];
|
|
2438
|
+
for (const loser of losers) {
|
|
2439
|
+
loser.note = `demoted: "${loser.finalName}" also claimed by another speaker with ${si === sj ? "equal" : "stronger"} evidence`;
|
|
2440
|
+
loser.finalName = void 0;
|
|
2441
|
+
loser.outcome = "conflict-fallback";
|
|
2442
|
+
delete nameMap[loser.speakerId];
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
if (opts.knownSpeakers?.length) {
|
|
2447
|
+
const unusedNames = opts.knownSpeakers.filter(
|
|
2448
|
+
(n) => !decisions.some((d) => d.finalName && namesMatch(d.finalName, n))
|
|
2449
|
+
);
|
|
2450
|
+
const unnamed = decisions.filter((d) => !d.finalName);
|
|
2451
|
+
if (unusedNames.length === 1 && unnamed.length === 1) {
|
|
2452
|
+
const d = unnamed[0];
|
|
2453
|
+
d.finalName = unusedNames[0];
|
|
2454
|
+
d.outcome = "elimination";
|
|
2455
|
+
d.note = `only remaining known speaker`;
|
|
2456
|
+
nameMap[d.speakerId] = d.finalName;
|
|
2457
|
+
logger.info(
|
|
2458
|
+
`identify: "${d.speakerId}" \u2192 ${d.finalName} (by elimination from --speakers)`
|
|
2459
|
+
);
|
|
2460
|
+
}
|
|
2461
|
+
}
|
|
2462
|
+
for (const d of decisions) {
|
|
2463
|
+
if (d.outcome === "conflict-fallback") {
|
|
2464
|
+
logger.info(`identify: "${d.speakerId}" kept generic \u2014 ${d.note}`);
|
|
2465
|
+
}
|
|
2466
|
+
if (d.outcome === "kept-generic" && (d.nameA || d.nameB)) {
|
|
2467
|
+
logger.info(
|
|
2468
|
+
`identify: kept "${d.speakerId}" generic \u2014 passes disagreed (${d.nameA ?? "\u2014"} vs ${d.nameB ?? "\u2014"})`
|
|
2469
|
+
);
|
|
2470
|
+
} else if (d.outcome === "tripwire") {
|
|
2471
|
+
logger.info(
|
|
2472
|
+
`identify: "${d.speakerId}" \u2192 ${d.finalName} (self-introduction tripwire)`
|
|
2473
|
+
);
|
|
2474
|
+
}
|
|
2475
|
+
}
|
|
2476
|
+
return {
|
|
2477
|
+
nameMap,
|
|
2478
|
+
decisions,
|
|
2479
|
+
tripwires,
|
|
2480
|
+
passA: { ...resA, model: reasonerA.model },
|
|
2481
|
+
passB: resB ? { ...resB, model: reasonerB.model } : void 0
|
|
2482
|
+
};
|
|
2483
|
+
}
|
|
2484
|
+
|
|
2485
|
+
// src/providers/reasoner.ts
|
|
2486
|
+
var PROVIDERS = {
|
|
2487
|
+
deepseek: { baseUrl: "https://api.deepseek.com/v1", keyName: "deepseek" },
|
|
2488
|
+
openai: { baseUrl: "https://api.openai.com/v1", keyName: "openai" },
|
|
2489
|
+
groq: { baseUrl: "https://api.groq.com/openai/v1", keyName: "groq" },
|
|
2490
|
+
gemini: {
|
|
2491
|
+
baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai",
|
|
2492
|
+
keyName: "gemini"
|
|
2493
|
+
},
|
|
2494
|
+
zai: { baseUrl: "https://api.z.ai/api/paas/v4", keyName: "zai" },
|
|
2495
|
+
kimi: { baseUrl: "https://api.moonshot.ai/v1", keyName: "kimi" },
|
|
2496
|
+
anthropic: { baseUrl: "https://api.anthropic.com/v1", keyName: "anthropic" }
|
|
2497
|
+
};
|
|
2498
|
+
function inferProvider(model) {
|
|
2499
|
+
const m = model.toLowerCase();
|
|
2500
|
+
if (m.startsWith("deepseek")) return "deepseek";
|
|
2501
|
+
if (m.startsWith("gemini") || m.startsWith("gemma")) return "gemini";
|
|
2502
|
+
if (m.startsWith("glm")) return "zai";
|
|
2503
|
+
if (m.startsWith("kimi") || m.startsWith("moonshot")) return "kimi";
|
|
2504
|
+
if (m.startsWith("claude")) return "anthropic";
|
|
2505
|
+
if (m.startsWith("gpt") || m.startsWith("o1") || m.startsWith("o3") || m.startsWith("o4"))
|
|
2506
|
+
return "openai";
|
|
2507
|
+
if (m.includes("llama") || m.includes("mixtral")) return "groq";
|
|
2508
|
+
return "openai";
|
|
2509
|
+
}
|
|
2510
|
+
function resolveReasonerInfo(spec) {
|
|
2511
|
+
let provider;
|
|
2512
|
+
let model;
|
|
2513
|
+
const colon = spec.indexOf(":");
|
|
2514
|
+
if (colon > 0 && PROVIDERS[spec.slice(0, colon)]) {
|
|
2515
|
+
provider = spec.slice(0, colon);
|
|
2516
|
+
model = spec.slice(colon + 1);
|
|
2517
|
+
} else {
|
|
2518
|
+
model = spec;
|
|
2519
|
+
provider = inferProvider(spec);
|
|
2520
|
+
}
|
|
2521
|
+
const p = PROVIDERS[provider] ?? PROVIDERS.openai;
|
|
2522
|
+
return { provider, model, keyName: p.keyName, baseUrl: p.baseUrl };
|
|
2523
|
+
}
|
|
2524
|
+
function reasonerKey(info, keys) {
|
|
2525
|
+
if (info.keyName === "gemini") return keys.gemini || keys.google;
|
|
2526
|
+
return keys[info.keyName];
|
|
2527
|
+
}
|
|
2528
|
+
function resolveReasoner(spec, keys) {
|
|
2529
|
+
const candidates = [spec, "deepseek-chat", "gemini-flash-latest"].filter(
|
|
2530
|
+
(s) => !!s
|
|
2531
|
+
);
|
|
2532
|
+
for (const c of candidates) {
|
|
2533
|
+
const info = resolveReasonerInfo(c);
|
|
2534
|
+
const key = reasonerKey(info, keys);
|
|
2535
|
+
if (key) {
|
|
2536
|
+
return {
|
|
2537
|
+
client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
|
|
2538
|
+
info
|
|
2539
|
+
};
|
|
2540
|
+
}
|
|
2541
|
+
}
|
|
2542
|
+
return null;
|
|
2543
|
+
}
|
|
2544
|
+
function resolveSecondReasoner(first, keys) {
|
|
2545
|
+
const candidates = ["gemini-flash-latest", "deepseek-chat", "glm-4.7", "gpt-4o-mini"];
|
|
2546
|
+
for (const c of candidates) {
|
|
2547
|
+
const info = resolveReasonerInfo(c);
|
|
2548
|
+
if (info.provider === first.provider) continue;
|
|
2549
|
+
const key = reasonerKey(info, keys);
|
|
2550
|
+
if (key) {
|
|
2551
|
+
return {
|
|
2552
|
+
client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
|
|
2553
|
+
info
|
|
2554
|
+
};
|
|
2555
|
+
}
|
|
2556
|
+
}
|
|
2557
|
+
return null;
|
|
2558
|
+
}
|
|
2559
|
+
|
|
1507
2560
|
// src/finalize/finalize.ts
|
|
1508
2561
|
var MIN_DUR = 0.5;
|
|
1509
2562
|
var MAX_DUR = 7;
|
|
@@ -1522,6 +2575,87 @@ function timeOverlapFrac(a, b) {
|
|
|
1522
2575
|
const shorter = Math.min(a.end - a.start, b.end - b.start);
|
|
1523
2576
|
return shorter > 0 ? ov / shorter : 0;
|
|
1524
2577
|
}
|
|
2578
|
+
var SEAM_WINDOW = 250;
|
|
2579
|
+
var SEAM_MIN_TOKENS = 6;
|
|
2580
|
+
var SEAM_MIN_SCORE_RATIO = 0.5;
|
|
2581
|
+
function suffixPrefixOverlap(a, b) {
|
|
2582
|
+
const n = a.length;
|
|
2583
|
+
const m = b.length;
|
|
2584
|
+
if (n === 0 || m === 0) return null;
|
|
2585
|
+
const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
|
|
2586
|
+
const origin = Array.from(
|
|
2587
|
+
{ length: n + 1 },
|
|
2588
|
+
() => new Array(m + 1).fill(0)
|
|
2589
|
+
);
|
|
2590
|
+
for (let i = 0; i <= n; i++) {
|
|
2591
|
+
dp[i][0] = 0;
|
|
2592
|
+
origin[i][0] = i;
|
|
2593
|
+
}
|
|
2594
|
+
for (let j = 1; j <= m; j++) {
|
|
2595
|
+
dp[0][j] = -j;
|
|
2596
|
+
origin[0][j] = 0;
|
|
2597
|
+
}
|
|
2598
|
+
for (let i = 1; i <= n; i++) {
|
|
2599
|
+
for (let j = 1; j <= m; j++) {
|
|
2600
|
+
const diag = dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 1 : -1);
|
|
2601
|
+
const up = dp[i - 1][j] - 1;
|
|
2602
|
+
const left = dp[i][j - 1] - 1;
|
|
2603
|
+
if (diag >= up && diag >= left) {
|
|
2604
|
+
dp[i][j] = diag;
|
|
2605
|
+
origin[i][j] = origin[i - 1][j - 1];
|
|
2606
|
+
} else if (up >= left) {
|
|
2607
|
+
dp[i][j] = up;
|
|
2608
|
+
origin[i][j] = origin[i - 1][j];
|
|
2609
|
+
} else {
|
|
2610
|
+
dp[i][j] = left;
|
|
2611
|
+
origin[i][j] = origin[i][j - 1];
|
|
2612
|
+
}
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
let bestJ = 0;
|
|
2616
|
+
let bestScore = -Infinity;
|
|
2617
|
+
for (let j = 1; j <= m; j++) {
|
|
2618
|
+
if (dp[n][j] > bestScore) {
|
|
2619
|
+
bestScore = dp[n][j];
|
|
2620
|
+
bestJ = j;
|
|
2621
|
+
}
|
|
2622
|
+
}
|
|
2623
|
+
if (bestJ < SEAM_MIN_TOKENS) return null;
|
|
2624
|
+
if (bestScore < bestJ * SEAM_MIN_SCORE_RATIO) return null;
|
|
2625
|
+
return { aStart: origin[n][bestJ], bLen: bestJ };
|
|
2626
|
+
}
|
|
2627
|
+
function trimSeamOverlaps(segments) {
|
|
2628
|
+
const sorted = [...segments].sort((a, b) => a.start - b.start);
|
|
2629
|
+
const lastIdxBySpeaker = /* @__PURE__ */ new Map();
|
|
2630
|
+
const out = [];
|
|
2631
|
+
for (const seg of sorted) {
|
|
2632
|
+
const prevIdx = lastIdxBySpeaker.get(seg.speaker);
|
|
2633
|
+
const prev = prevIdx !== void 0 ? out[prevIdx] : void 0;
|
|
2634
|
+
if (prev && prev.words?.length && seg.words?.length) {
|
|
2635
|
+
const prevWin = Math.min(SEAM_WINDOW, prev.words.length);
|
|
2636
|
+
const prevToks = prev.words.slice(-prevWin).map((w) => tokenize(w.text)[0]?.norm ?? "");
|
|
2637
|
+
const segToks = seg.words.slice(0, SEAM_WINDOW).map((w) => tokenize(w.text)[0]?.norm ?? "");
|
|
2638
|
+
const hit = suffixPrefixOverlap(prevToks, segToks);
|
|
2639
|
+
if (hit) {
|
|
2640
|
+
const trimFrom = prev.words.length - prevWin + hit.aStart;
|
|
2641
|
+
const kept = prev.words.slice(0, trimFrom);
|
|
2642
|
+
if (kept.length === 0) {
|
|
2643
|
+
out[prevIdx] = null;
|
|
2644
|
+
} else {
|
|
2645
|
+
out[prevIdx] = {
|
|
2646
|
+
...prev,
|
|
2647
|
+
words: kept,
|
|
2648
|
+
end: kept[kept.length - 1].end,
|
|
2649
|
+
text: kept.map((w) => w.text).join(" ")
|
|
2650
|
+
};
|
|
2651
|
+
}
|
|
2652
|
+
}
|
|
2653
|
+
}
|
|
2654
|
+
out.push(seg);
|
|
2655
|
+
lastIdxBySpeaker.set(seg.speaker, out.length - 1);
|
|
2656
|
+
}
|
|
2657
|
+
return out.filter((s) => s !== null);
|
|
2658
|
+
}
|
|
1525
2659
|
function dedupSegments(segments) {
|
|
1526
2660
|
const sorted = [...segments].sort((a, b) => a.start - b.start);
|
|
1527
2661
|
const kept = [];
|
|
@@ -1577,7 +2711,7 @@ function clampAndFix(segments) {
|
|
|
1577
2711
|
}
|
|
1578
2712
|
function finalizeSegments(segments, opts = {}) {
|
|
1579
2713
|
const minSeg = opts.minSegmentSec ?? 0.2;
|
|
1580
|
-
let deduped = dedupSegments(segments);
|
|
2714
|
+
let deduped = dedupSegments(trimSeamOverlaps(segments));
|
|
1581
2715
|
deduped = deduped.filter((s) => s.end - s.start >= minSeg && s.text.trim().length > 0);
|
|
1582
2716
|
const out = deduped.map((s, i) => ({
|
|
1583
2717
|
id: i + 1,
|
|
@@ -1599,11 +2733,17 @@ function finalizeSegments(segments, opts = {}) {
|
|
|
1599
2733
|
// src/finalize/format.ts
|
|
1600
2734
|
var MAX_CHARS = 84;
|
|
1601
2735
|
var MAX_BLOCK_SEC = 7;
|
|
1602
|
-
function
|
|
1603
|
-
const
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
2736
|
+
function compactTime(sec) {
|
|
2737
|
+
const s = Math.max(0, Math.floor(sec));
|
|
2738
|
+
const h = Math.floor(s / 3600);
|
|
2739
|
+
const m = Math.floor(s % 3600 / 60);
|
|
2740
|
+
const r = s % 60;
|
|
2741
|
+
const mm = m.toString().padStart(2, "0");
|
|
2742
|
+
const rr = r.toString().padStart(2, "0");
|
|
2743
|
+
return h > 0 ? `${h}:${mm}:${rr}` : `${mm}:${rr}`;
|
|
2744
|
+
}
|
|
2745
|
+
function splitByWords(seg) {
|
|
2746
|
+
const words = seg.words;
|
|
1607
2747
|
const blocks = [];
|
|
1608
2748
|
let curWords = [];
|
|
1609
2749
|
let curLen = 0;
|
|
@@ -1630,6 +2770,36 @@ function splitIntoBlocks(seg) {
|
|
|
1630
2770
|
curLen += addLen;
|
|
1631
2771
|
}
|
|
1632
2772
|
flush();
|
|
2773
|
+
return blocks;
|
|
2774
|
+
}
|
|
2775
|
+
function splitByChars(seg) {
|
|
2776
|
+
const text = seg.text.trim();
|
|
2777
|
+
if (text.length <= MAX_CHARS) return [{ start: seg.start, end: seg.end, text }];
|
|
2778
|
+
const words = text.split(/\s+/);
|
|
2779
|
+
const lines = [];
|
|
2780
|
+
let cur = "";
|
|
2781
|
+
for (const w of words) {
|
|
2782
|
+
if (cur && cur.length + 1 + w.length > MAX_CHARS) {
|
|
2783
|
+
lines.push(cur);
|
|
2784
|
+
cur = w;
|
|
2785
|
+
} else {
|
|
2786
|
+
cur = cur ? `${cur} ${w}` : w;
|
|
2787
|
+
}
|
|
2788
|
+
}
|
|
2789
|
+
if (cur) lines.push(cur);
|
|
2790
|
+
const total = lines.reduce((n, l) => n + l.length, 0) || 1;
|
|
2791
|
+
const dur = Math.max(0, seg.end - seg.start);
|
|
2792
|
+
const blocks = [];
|
|
2793
|
+
let t = seg.start;
|
|
2794
|
+
for (const line of lines) {
|
|
2795
|
+
const span = line.length / total * dur;
|
|
2796
|
+
blocks.push({ start: t, end: Math.min(seg.end, t + span), text: line });
|
|
2797
|
+
t += span;
|
|
2798
|
+
}
|
|
2799
|
+
return blocks;
|
|
2800
|
+
}
|
|
2801
|
+
function splitIntoBlocks(seg) {
|
|
2802
|
+
const blocks = seg.words && seg.words.length > 0 ? splitByWords(seg) : splitByChars(seg);
|
|
1633
2803
|
return blocks.length ? blocks : [{ start: seg.start, end: seg.end, text: seg.text }];
|
|
1634
2804
|
}
|
|
1635
2805
|
function formatSrt(result, opts = {}) {
|
|
@@ -1640,54 +2810,247 @@ function formatSrt(result, opts = {}) {
|
|
|
1640
2810
|
for (const seg of result.segments) {
|
|
1641
2811
|
const tone = showTone && seg.tone && seg.tone.length ? ` (${seg.tone.join(", ")})` : "";
|
|
1642
2812
|
const speaker = labelSpeakers ? `${seg.speakerName || seg.speaker}: ` : "";
|
|
1643
|
-
|
|
1644
|
-
|
|
2813
|
+
const segBlocks = splitIntoBlocks(seg);
|
|
2814
|
+
for (let i = 0; i < segBlocks.length; i++) {
|
|
2815
|
+
const b = segBlocks[i];
|
|
2816
|
+
const t = i === 0 ? tone : "";
|
|
2817
|
+
blocks.push(
|
|
2818
|
+
`${idx}
|
|
1645
2819
|
${formatSrtTiming(b.start, b.end)}
|
|
1646
|
-
${speaker}${b.text}${
|
|
1647
|
-
`
|
|
2820
|
+
${speaker}${b.text}${t}
|
|
2821
|
+
`
|
|
2822
|
+
);
|
|
1648
2823
|
idx++;
|
|
1649
2824
|
}
|
|
1650
2825
|
}
|
|
1651
2826
|
return blocks.join("\n");
|
|
1652
2827
|
}
|
|
1653
|
-
function
|
|
2828
|
+
function groupBySpeaker(segments) {
|
|
2829
|
+
const groups = [];
|
|
2830
|
+
for (const seg of segments) {
|
|
2831
|
+
const last = groups[groups.length - 1];
|
|
2832
|
+
const key = (s) => s.speakerName || s.speaker;
|
|
2833
|
+
if (last && key(last[0]) === key(seg)) last.push(seg);
|
|
2834
|
+
else groups.push([seg]);
|
|
2835
|
+
}
|
|
2836
|
+
return groups;
|
|
2837
|
+
}
|
|
2838
|
+
function groupText(group, showTone) {
|
|
2839
|
+
const parts = [];
|
|
2840
|
+
let lastTone = "";
|
|
2841
|
+
for (const s of group) {
|
|
2842
|
+
const toneStr = s.tone && s.tone.length ? s.tone.join(", ") : "";
|
|
2843
|
+
if (showTone && toneStr && toneStr !== lastTone) {
|
|
2844
|
+
parts.push(`*(${toneStr})* ${s.text}`);
|
|
2845
|
+
} else {
|
|
2846
|
+
parts.push(s.text);
|
|
2847
|
+
}
|
|
2848
|
+
lastTone = toneStr;
|
|
2849
|
+
}
|
|
2850
|
+
return parts.join(" ");
|
|
2851
|
+
}
|
|
2852
|
+
function mdHeader(result, opts) {
|
|
1654
2853
|
const parts = [];
|
|
1655
2854
|
parts.push(`# ${opts.title || "Transcript"}
|
|
1656
2855
|
`);
|
|
1657
|
-
parts.push(
|
|
1658
|
-
|
|
2856
|
+
parts.push(
|
|
2857
|
+
`*Duration: ${formatDuration(result.metadata.duration)} \xB7 ${result.speakers.length} speakers \xB7 ${result.segments.length} turns*
|
|
2858
|
+
`
|
|
2859
|
+
);
|
|
1659
2860
|
parts.push("\n## Speakers\n");
|
|
1660
2861
|
for (const s of result.speakers) {
|
|
1661
|
-
const talk = s.talkTime ? `
|
|
1662
|
-
|
|
2862
|
+
const talk = s.talkTime ? ` \u2014 ${formatDuration(Math.round(s.talkTime))}` : "";
|
|
2863
|
+
const desc = s.description ? ` \xB7 ${s.description}` : "";
|
|
2864
|
+
parts.push(`- **${s.name || s.id}**${talk}${desc}`);
|
|
1663
2865
|
}
|
|
1664
2866
|
parts.push("\n## Transcript\n");
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
2867
|
+
return parts;
|
|
2868
|
+
}
|
|
2869
|
+
function formatMarkdown(result, opts = {}) {
|
|
2870
|
+
const showTone = opts.showTone ?? true;
|
|
2871
|
+
const timestamps = opts.timestamps ?? true;
|
|
2872
|
+
const style = opts.mdStyle ?? "merged";
|
|
2873
|
+
const parts = mdHeader(result, opts);
|
|
2874
|
+
const groups = style === "merged" ? groupBySpeaker(result.segments) : result.segments.map((s) => [s]);
|
|
2875
|
+
for (const group of groups) {
|
|
2876
|
+
const first = group[0];
|
|
2877
|
+
const ts = timestamps ? `\`[${compactTime(first.start)}]\` ` : "";
|
|
2878
|
+
const name = first.speakerName || first.speaker;
|
|
2879
|
+
parts.push(`${ts}**${name}:** ${groupText(group, showTone)}
|
|
1670
2880
|
`);
|
|
1671
2881
|
}
|
|
1672
2882
|
return parts.join("\n");
|
|
1673
2883
|
}
|
|
2884
|
+
function formatText(result, opts = {}) {
|
|
2885
|
+
const timestamps = opts.timestamps ?? true;
|
|
2886
|
+
const showTone = opts.showTone ?? false;
|
|
2887
|
+
const lines = [];
|
|
2888
|
+
for (const group of groupBySpeaker(result.segments)) {
|
|
2889
|
+
const first = group[0];
|
|
2890
|
+
const ts = timestamps ? `[${compactTime(first.start)}] ` : "";
|
|
2891
|
+
const name = first.speakerName || first.speaker;
|
|
2892
|
+
const text = group.map(
|
|
2893
|
+
(s) => showTone && s.tone?.length ? `(${s.tone.join(", ")}) ${s.text}` : s.text
|
|
2894
|
+
).join(" ");
|
|
2895
|
+
lines.push(`${ts}${name}: ${text}`);
|
|
2896
|
+
}
|
|
2897
|
+
return lines.join("\n\n") + "\n";
|
|
2898
|
+
}
|
|
1674
2899
|
function formatJson(result) {
|
|
1675
2900
|
return JSON.stringify(result, null, 2);
|
|
1676
2901
|
}
|
|
1677
2902
|
|
|
2903
|
+
// src/finalize/html.ts
|
|
2904
|
+
var PALETTE = [
|
|
2905
|
+
"#2563eb",
|
|
2906
|
+
"#059669",
|
|
2907
|
+
"#d97706",
|
|
2908
|
+
"#dc2626",
|
|
2909
|
+
"#7c3aed",
|
|
2910
|
+
"#0891b2",
|
|
2911
|
+
"#be185d",
|
|
2912
|
+
"#4d7c0f",
|
|
2913
|
+
"#b45309",
|
|
2914
|
+
"#6d28d9"
|
|
2915
|
+
];
|
|
2916
|
+
var esc = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
2917
|
+
function groupBySpeaker2(segments) {
|
|
2918
|
+
const groups = [];
|
|
2919
|
+
for (const seg of segments) {
|
|
2920
|
+
const last = groups[groups.length - 1];
|
|
2921
|
+
const key = (s) => s.speakerName || s.speaker;
|
|
2922
|
+
if (last && key(last[0]) === key(seg)) last.push(seg);
|
|
2923
|
+
else groups.push([seg]);
|
|
2924
|
+
}
|
|
2925
|
+
return groups;
|
|
2926
|
+
}
|
|
2927
|
+
function formatHtml(result, opts = {}) {
|
|
2928
|
+
const title = opts.title || "Transcript";
|
|
2929
|
+
const colorOf = /* @__PURE__ */ new Map();
|
|
2930
|
+
result.speakers.forEach((sp, i) => {
|
|
2931
|
+
colorOf.set(sp.name || sp.id, PALETTE[i % PALETTE.length]);
|
|
2932
|
+
});
|
|
2933
|
+
const color = (name) => colorOf.get(name) ?? "#64748b";
|
|
2934
|
+
const legend = result.speakers.map((sp) => {
|
|
2935
|
+
const name = sp.name || sp.id;
|
|
2936
|
+
const talk = sp.talkTime ? ` \xB7 ${formatDuration(Math.round(sp.talkTime))}` : "";
|
|
2937
|
+
return `<span class="who"><i style="background:${color(name)}"></i>${esc(name)}<small>${talk}</small></span>`;
|
|
2938
|
+
}).join("");
|
|
2939
|
+
const paragraphs = groupBySpeaker2(result.segments).map((group) => {
|
|
2940
|
+
const first = group[0];
|
|
2941
|
+
const name = first.speakerName || first.speaker;
|
|
2942
|
+
let lastTone = "";
|
|
2943
|
+
const body = group.map((s) => {
|
|
2944
|
+
const toneStr = s.tone?.length ? s.tone.join(", ") : "";
|
|
2945
|
+
const badge = toneStr && toneStr !== lastTone ? `<em class="tone">${esc(toneStr)}</em> ` : "";
|
|
2946
|
+
lastTone = toneStr;
|
|
2947
|
+
return `${badge}${esc(s.text)}`;
|
|
2948
|
+
}).join(" ");
|
|
2949
|
+
return `<div class="turn" style="border-color:${color(name)}">
|
|
2950
|
+
<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>
|
|
2951
|
+
<p>${body}</p>
|
|
2952
|
+
</div>`;
|
|
2953
|
+
}).join("\n");
|
|
2954
|
+
const m = result.metadata;
|
|
2955
|
+
const cost = m.cost ? ` \xB7 ~$${m.cost.actualUsd.toFixed(2)}` : "";
|
|
2956
|
+
const footer = `${esc(m.models.transcribe ?? "")} + ${esc(m.models.timestamped ?? "")}${cost} \xB7 ${new Date(m.processedAt).toLocaleDateString()}`;
|
|
2957
|
+
return `<!doctype html>
|
|
2958
|
+
<html lang="en">
|
|
2959
|
+
<meta charset="utf-8">
|
|
2960
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
2961
|
+
<title>${esc(title)}</title>
|
|
2962
|
+
<style>
|
|
2963
|
+
:root{--bg:#ffffff;--fg:#1e293b;--muted:#64748b;--line:#e2e8f0;--chip:#f1f5f9}
|
|
2964
|
+
@media(prefers-color-scheme:dark){:root{--bg:#0f172a;--fg:#e2e8f0;--muted:#94a3b8;--line:#1e293b;--chip:#1e293b}}
|
|
2965
|
+
*{box-sizing:border-box}
|
|
2966
|
+
body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
|
|
2967
|
+
main{max-width:760px;margin:0 auto;padding:2rem 1.25rem 4rem}
|
|
2968
|
+
h1{font-size:1.5rem;margin:0 0 .25rem}
|
|
2969
|
+
.sub{color:var(--muted);font-size:.9rem;margin-bottom:1rem}
|
|
2970
|
+
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}
|
|
2971
|
+
.who{display:inline-flex;align-items:center;gap:.4rem;font-size:.85rem}
|
|
2972
|
+
.who i{width:.65rem;height:.65rem;border-radius:50%;display:inline-block}
|
|
2973
|
+
.who small{color:var(--muted)}
|
|
2974
|
+
.turn{border-left:3px solid;padding:.15rem 0 .15rem 1rem;margin:1.1rem 0}
|
|
2975
|
+
.turn .meta{display:flex;align-items:baseline;gap:.6rem;font-size:.85rem}
|
|
2976
|
+
.turn time{color:var(--muted);font-family:ui-monospace,Menlo,monospace;font-size:.78rem;cursor:pointer}
|
|
2977
|
+
.turn time:hover{text-decoration:underline}
|
|
2978
|
+
.turn p{margin:.25rem 0 0}
|
|
2979
|
+
.tone{background:var(--chip);color:var(--muted);border-radius:.5rem;padding:0 .45rem;font-size:.75rem;font-style:italic;white-space:nowrap}
|
|
2980
|
+
footer{margin-top:3rem;color:var(--muted);font-size:.8rem;border-top:1px solid var(--line);padding-top:1rem}
|
|
2981
|
+
</style>
|
|
2982
|
+
<main>
|
|
2983
|
+
<h1>${esc(title)}</h1>
|
|
2984
|
+
<div class="sub">${formatDuration(m.duration)} \xB7 ${result.speakers.length} speakers \xB7 ${result.segments.length} turns</div>
|
|
2985
|
+
<header class="legend">${legend}</header>
|
|
2986
|
+
${paragraphs}
|
|
2987
|
+
<footer>${footer}</footer>
|
|
2988
|
+
</main>
|
|
2989
|
+
<script>
|
|
2990
|
+
document.querySelectorAll("time").forEach(t=>t.addEventListener("click",()=>{
|
|
2991
|
+
navigator.clipboard&&navigator.clipboard.writeText(t.dataset.t);
|
|
2992
|
+
const o=t.textContent;t.textContent="copied";setTimeout(()=>t.textContent=o,700);
|
|
2993
|
+
}));
|
|
2994
|
+
</script>
|
|
2995
|
+
</html>
|
|
2996
|
+
`;
|
|
2997
|
+
}
|
|
2998
|
+
|
|
2999
|
+
// src/finalize/summary.ts
|
|
3000
|
+
function summaryPrompt(result, instructions) {
|
|
3001
|
+
const lines = result.segments.map((s) => {
|
|
3002
|
+
const name = s.speakerName || s.speaker;
|
|
3003
|
+
return `[${compactTime(s.start)}] ${name}: ${s.text}`;
|
|
3004
|
+
});
|
|
3005
|
+
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):
|
|
3006
|
+
|
|
3007
|
+
## TL;DR
|
|
3008
|
+
2-4 sentences. What was this, what mattered.
|
|
3009
|
+
|
|
3010
|
+
## Decisions
|
|
3011
|
+
Bullet list of decisions actually made (not topics discussed). Attribute who decided when clear.
|
|
3012
|
+
|
|
3013
|
+
## Action items
|
|
3014
|
+
Bullet list, "**Owner** \u2014 action" format. Only real commitments, with the timestamp in [mm:ss].
|
|
3015
|
+
|
|
3016
|
+
## By speaker
|
|
3017
|
+
One short paragraph per speaker: their main points and positions.
|
|
3018
|
+
|
|
3019
|
+
## Open questions
|
|
3020
|
+
Things raised but not resolved.
|
|
3021
|
+
|
|
3022
|
+
Be specific and quote sparingly. Do not invent content.${instructions ? `
|
|
3023
|
+
|
|
3024
|
+
Additional instructions: ${instructions}` : ""}
|
|
3025
|
+
|
|
3026
|
+
TRANSCRIPT:
|
|
3027
|
+
${lines.join("\n")}`;
|
|
3028
|
+
}
|
|
3029
|
+
async function summarizeTranscript(client, model, result, instructions) {
|
|
3030
|
+
const res = await client.chat(
|
|
3031
|
+
model,
|
|
3032
|
+
[{ role: "user", content: summaryPrompt(result, instructions) }],
|
|
3033
|
+
{ temperature: 0.3, maxTokens: 4e3, logKind: "summary" }
|
|
3034
|
+
);
|
|
3035
|
+
if (res.error || !res.text) {
|
|
3036
|
+
throw new Error(`summary failed: ${res.error || "empty response"}`);
|
|
3037
|
+
}
|
|
3038
|
+
return res.text.trim() + "\n";
|
|
3039
|
+
}
|
|
3040
|
+
|
|
1678
3041
|
// src/core/pipeline.ts
|
|
1679
3042
|
import { basename as basename3, resolve as resolve2 } from "path";
|
|
1680
3043
|
var JSON_OPTS = { encoding: "utf-8" };
|
|
1681
3044
|
function readJson(p) {
|
|
1682
|
-
if (!
|
|
3045
|
+
if (!existsSync3(p)) return null;
|
|
1683
3046
|
try {
|
|
1684
|
-
return JSON.parse(
|
|
3047
|
+
return JSON.parse(readFileSync2(p, JSON_OPTS));
|
|
1685
3048
|
} catch {
|
|
1686
3049
|
return null;
|
|
1687
3050
|
}
|
|
1688
3051
|
}
|
|
1689
3052
|
function writeJson(p, data) {
|
|
1690
|
-
|
|
3053
|
+
writeFileSync2(p, JSON.stringify(data, null, 2), JSON_OPTS);
|
|
1691
3054
|
}
|
|
1692
3055
|
async function mapPool(items, limit, fn) {
|
|
1693
3056
|
const results = new Array(items.length);
|
|
@@ -1705,6 +3068,15 @@ async function mapPool(items, limit, fn) {
|
|
|
1705
3068
|
function has(passes, p) {
|
|
1706
3069
|
return passes.includes(p);
|
|
1707
3070
|
}
|
|
3071
|
+
function stageTag(name) {
|
|
3072
|
+
return (err) => {
|
|
3073
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3074
|
+
if (msg.startsWith(`[${name}]`)) throw err;
|
|
3075
|
+
const e = new Error(`[${name}] ${msg}`);
|
|
3076
|
+
if (err instanceof Error && err.stack) e.stack = err.stack;
|
|
3077
|
+
throw e;
|
|
3078
|
+
};
|
|
3079
|
+
}
|
|
1708
3080
|
async function transcribe(opts) {
|
|
1709
3081
|
if (!opts || typeof opts.input !== "string" || opts.input.length === 0) {
|
|
1710
3082
|
throw new Error(
|
|
@@ -1714,15 +3086,17 @@ async function transcribe(opts) {
|
|
|
1714
3086
|
const options = resolveOptions(opts);
|
|
1715
3087
|
const keys = resolveKeys(options.apiKeys);
|
|
1716
3088
|
logger.setLevel(options.logLevel);
|
|
1717
|
-
if (!
|
|
3089
|
+
if (!existsSync3(options.input)) {
|
|
1718
3090
|
throw new Error(`Input file not found: ${options.input}`);
|
|
1719
3091
|
}
|
|
1720
|
-
|
|
1721
|
-
|
|
3092
|
+
mkdirSync2(options.intermediatesDir, { recursive: true });
|
|
3093
|
+
mkdirSync2(options.outputDir, { recursive: true });
|
|
1722
3094
|
logger.info(
|
|
1723
3095
|
`intermediates: ${resolve2(options.intermediatesDir)} (file://${resolve2(options.intermediatesDir)})`
|
|
1724
3096
|
);
|
|
1725
3097
|
setLlmLogPath(options.llmLog ? `${options.intermediatesDir}/llm-calls.jsonl` : null);
|
|
3098
|
+
resetLlmUsage();
|
|
3099
|
+
const runStartedAt = Date.now();
|
|
1726
3100
|
const sourcePath = `${options.intermediatesDir}/source.json`;
|
|
1727
3101
|
const sig = inputSignature(options.input);
|
|
1728
3102
|
const cfgSig = configSignature(opts);
|
|
@@ -1752,6 +3126,9 @@ async function transcribe(opts) {
|
|
|
1752
3126
|
transcribe: options.model ?? DEFAULT_TRANSCRIBE_MODEL,
|
|
1753
3127
|
reasoner: options.reasoner ?? DEFAULT_REASONER_MODEL
|
|
1754
3128
|
};
|
|
3129
|
+
const checkAbort = () => {
|
|
3130
|
+
options.signal?.throwIfAborted();
|
|
3131
|
+
};
|
|
1755
3132
|
if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
|
|
1756
3133
|
if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
|
|
1757
3134
|
const tsProvider = options.timestampedProvider ?? "assemblyai";
|
|
@@ -1759,33 +3136,45 @@ async function transcribe(opts) {
|
|
|
1759
3136
|
if (willTimestamp) {
|
|
1760
3137
|
if (tsProvider === "assemblyai" && !keys.assemblyai) {
|
|
1761
3138
|
throw new Error(
|
|
1762
|
-
"ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
|
|
3139
|
+
"ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped elevenlabs / whisper-groq)"
|
|
1763
3140
|
);
|
|
1764
3141
|
}
|
|
1765
3142
|
if (tsProvider === "whisper-groq" && !keys.groq) {
|
|
1766
3143
|
throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
|
|
1767
3144
|
}
|
|
3145
|
+
if (tsProvider === "elevenlabs" && !keys.elevenlabs) {
|
|
3146
|
+
throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
|
|
3147
|
+
}
|
|
1768
3148
|
}
|
|
1769
3149
|
let probeInfo = null;
|
|
1770
3150
|
const AUDIO_OPTS = { format: "mp3", bitrate: "64k" };
|
|
1771
3151
|
const audioPath = `${options.intermediatesDir}/audio.mp3`;
|
|
1772
3152
|
const probePath = `${options.intermediatesDir}/probe.json`;
|
|
1773
3153
|
if (has(passes, "preprocess")) {
|
|
3154
|
+
checkAbort();
|
|
1774
3155
|
logger.info("=== preprocess ===");
|
|
1775
3156
|
probeInfo = forceAll ? null : readJson(probePath);
|
|
1776
3157
|
if (!probeInfo) {
|
|
1777
|
-
probeInfo = await probe(options.input);
|
|
3158
|
+
probeInfo = await probe(options.input).catch(stageTag("preprocess"));
|
|
1778
3159
|
writeJson(probePath, probeInfo);
|
|
1779
3160
|
}
|
|
1780
|
-
if (!
|
|
3161
|
+
if (!existsSync3(audioPath) || forceAll) {
|
|
1781
3162
|
logger.info("extracting audio (mono 16kHz mp3)...");
|
|
1782
|
-
await extractAudio(options.input, audioPath, AUDIO_OPTS)
|
|
3163
|
+
await extractAudio(options.input, audioPath, AUDIO_OPTS).catch(
|
|
3164
|
+
stageTag("preprocess")
|
|
3165
|
+
);
|
|
1783
3166
|
}
|
|
1784
3167
|
if (probeInfo.hasVideo) {
|
|
1785
3168
|
const kfDir = `${options.intermediatesDir}/keyframes`;
|
|
1786
|
-
if (!
|
|
3169
|
+
if (!existsSync3(kfDir) || forceAll) {
|
|
1787
3170
|
logger.info("extracting keyframes...");
|
|
1788
|
-
await extractKeyframes(options.input, kfDir, options.screenshotCount)
|
|
3171
|
+
await extractKeyframes(options.input, kfDir, options.screenshotCount).catch(
|
|
3172
|
+
(err) => {
|
|
3173
|
+
logger.warn(
|
|
3174
|
+
`keyframe extraction failed (continuing audio-only): ${err instanceof Error ? err.message : err}`
|
|
3175
|
+
);
|
|
3176
|
+
}
|
|
3177
|
+
);
|
|
1789
3178
|
}
|
|
1790
3179
|
}
|
|
1791
3180
|
} else {
|
|
@@ -1793,23 +3182,46 @@ async function transcribe(opts) {
|
|
|
1793
3182
|
}
|
|
1794
3183
|
if (!probeInfo) throw new Error("probe info missing (run preprocess)");
|
|
1795
3184
|
const duration = probeInfo.duration;
|
|
3185
|
+
const estimate = estimateRunCost({
|
|
3186
|
+
durationSec: duration,
|
|
3187
|
+
model: models.transcribe,
|
|
3188
|
+
reasoner: models.reasoner,
|
|
3189
|
+
tsProvider,
|
|
3190
|
+
chunkSec: options.chunkDurationSec,
|
|
3191
|
+
overlapSec: options.chunkOverlapSec,
|
|
3192
|
+
identify: options.diarizationLevel >= 3 && has(passes, "identify")
|
|
3193
|
+
});
|
|
3194
|
+
logger.info(
|
|
3195
|
+
`estimated cost ~$${estimate.totalUsd.toFixed(2)}${estimate.incomplete ? " (+unpriced parts)" : ""} [${estimate.lines.join(" \xB7 ")}]`
|
|
3196
|
+
);
|
|
1796
3197
|
let description = null;
|
|
1797
3198
|
if (has(passes, "describe")) {
|
|
1798
3199
|
const descPath = `${options.intermediatesDir}/description.json`;
|
|
1799
3200
|
description = forceAll ? null : readJson(descPath);
|
|
1800
3201
|
if (!description) {
|
|
3202
|
+
checkAbort();
|
|
1801
3203
|
logger.info("=== describe ===");
|
|
1802
3204
|
const client = new GeminiClient(keys.gemini);
|
|
1803
|
-
const
|
|
1804
|
-
|
|
1805
|
-
|
|
3205
|
+
const sampleSpans = duration <= 360 ? [[0, duration]] : [
|
|
3206
|
+
[0, 150],
|
|
3207
|
+
[Math.max(0, duration / 2 - 60), Math.min(duration, duration / 2 + 60)],
|
|
3208
|
+
[Math.max(0, duration - 120), duration]
|
|
3209
|
+
];
|
|
3210
|
+
const files = [];
|
|
3211
|
+
for (let i = 0; i < sampleSpans.length; i++) {
|
|
3212
|
+
const [s, e] = sampleSpans[i];
|
|
3213
|
+
const samplePath = `${options.intermediatesDir}/sample_${i}.mp3`;
|
|
3214
|
+
if (!existsSync3(samplePath) || forceAll) {
|
|
3215
|
+
await extractChunk(audioPath, samplePath, s, e, AUDIO_OPTS);
|
|
3216
|
+
}
|
|
3217
|
+
files.push({ path: samplePath });
|
|
1806
3218
|
}
|
|
1807
|
-
const
|
|
3219
|
+
const audioSampleCount = files.length;
|
|
1808
3220
|
const kfDir = `${options.intermediatesDir}/keyframes`;
|
|
1809
|
-
if (
|
|
3221
|
+
if (existsSync3(kfDir)) {
|
|
1810
3222
|
for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
|
|
1811
3223
|
const p = `${kfDir}/${f}`;
|
|
1812
|
-
if (
|
|
3224
|
+
if (existsSync3(p)) files.push({ path: p });
|
|
1813
3225
|
}
|
|
1814
3226
|
}
|
|
1815
3227
|
description = await describeMeeting(
|
|
@@ -1817,8 +3229,9 @@ async function transcribe(opts) {
|
|
|
1817
3229
|
models.transcribe,
|
|
1818
3230
|
files,
|
|
1819
3231
|
basename3(options.input),
|
|
1820
|
-
options.instructions
|
|
1821
|
-
|
|
3232
|
+
options.instructions,
|
|
3233
|
+
audioSampleCount
|
|
3234
|
+
).catch(stageTag("describe"));
|
|
1822
3235
|
writeJson(descPath, description);
|
|
1823
3236
|
logger.info(`description: ${description.description.slice(0, 120)}...`);
|
|
1824
3237
|
}
|
|
@@ -1866,16 +3279,39 @@ async function transcribe(opts) {
|
|
|
1866
3279
|
);
|
|
1867
3280
|
const client = new GeminiClient(keys.gemini);
|
|
1868
3281
|
const llmDir = `${options.intermediatesDir}/llm`;
|
|
1869
|
-
|
|
3282
|
+
mkdirSync2(llmDir, { recursive: true });
|
|
3283
|
+
const partialPath = `${options.outputDir}/${basename3(options.input, ext(options.input))}.partial.md`;
|
|
3284
|
+
const completed = [];
|
|
3285
|
+
const writePartial = () => {
|
|
3286
|
+
try {
|
|
3287
|
+
const segs = completed.flatMap((r) => r.segments).sort((a, b) => a.startSec - b.startSec);
|
|
3288
|
+
if (segs.length === 0) return;
|
|
3289
|
+
const lines = segs.map((s) => {
|
|
3290
|
+
const mm = Math.floor(s.startSec / 60).toString().padStart(2, "0");
|
|
3291
|
+
const ss = Math.floor(s.startSec % 60).toString().padStart(2, "0");
|
|
3292
|
+
return `[${mm}:${ss}] **${s.speaker}**: ${s.text}`;
|
|
3293
|
+
});
|
|
3294
|
+
writeFileSync2(
|
|
3295
|
+
partialPath,
|
|
3296
|
+
`> Partial transcript (run in progress \u2014 coarse LLM timings, speakers not yet unified)
|
|
3297
|
+
|
|
3298
|
+
${lines.join("\n\n")}
|
|
3299
|
+
`
|
|
3300
|
+
);
|
|
3301
|
+
} catch {
|
|
3302
|
+
}
|
|
3303
|
+
};
|
|
1870
3304
|
llmChunkResults = await mapPool(runChunks, options.concurrency, async (chunk) => {
|
|
3305
|
+
checkAbort();
|
|
1871
3306
|
const parsedPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_parsed.json`;
|
|
1872
3307
|
const cached = forceAll ? null : readJson(parsedPath);
|
|
1873
3308
|
if (cached && cached.segments.length > 0) {
|
|
1874
3309
|
logger.info(`chunk ${chunk.index}: cached (${cached.segments.length} segments)`);
|
|
3310
|
+
completed.push(cached);
|
|
1875
3311
|
return tagWith(cached, chunk);
|
|
1876
3312
|
}
|
|
1877
3313
|
const chunkPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}.mp3`;
|
|
1878
|
-
if (!
|
|
3314
|
+
if (!existsSync3(chunkPath) || forceAll) {
|
|
1879
3315
|
await extractChunk(audioPath, chunkPath, chunk.start, chunk.end, AUDIO_OPTS);
|
|
1880
3316
|
}
|
|
1881
3317
|
let previousTail;
|
|
@@ -1906,10 +3342,12 @@ async function transcribe(opts) {
|
|
|
1906
3342
|
{ chunkDurationSec: chunk.end - chunk.start, validationRetries: 1 }
|
|
1907
3343
|
);
|
|
1908
3344
|
writeJson(parsedPath, result2);
|
|
1909
|
-
|
|
3345
|
+
writeFileSync2(
|
|
1910
3346
|
`${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`,
|
|
1911
3347
|
result2.raw
|
|
1912
3348
|
);
|
|
3349
|
+
completed.push(result2);
|
|
3350
|
+
writePartial();
|
|
1913
3351
|
return tagWith(result2, chunk);
|
|
1914
3352
|
});
|
|
1915
3353
|
const errored = llmChunkResults.filter((r) => r.error);
|
|
@@ -1921,7 +3359,7 @@ async function transcribe(opts) {
|
|
|
1921
3359
|
}
|
|
1922
3360
|
} else {
|
|
1923
3361
|
const llmDir = `${options.intermediatesDir}/llm`;
|
|
1924
|
-
if (!forceAll &&
|
|
3362
|
+
if (!forceAll && existsSync3(llmDir)) {
|
|
1925
3363
|
const files = (await import("fs/promises").then((m) => m.readdir(llmDir))).filter((f) => f.endsWith("_parsed.json")).sort();
|
|
1926
3364
|
llmChunkResults = files.map((f, i) => {
|
|
1927
3365
|
const r = readJson(`${llmDir}/${f}`);
|
|
@@ -1940,18 +3378,38 @@ async function transcribe(opts) {
|
|
|
1940
3378
|
logger.info(`total LLM segments: ${allLlmSegments.length}`);
|
|
1941
3379
|
let asrResult = null;
|
|
1942
3380
|
if (has(passes, "timestamped") || has(passes, "align")) {
|
|
3381
|
+
checkAbort();
|
|
1943
3382
|
const provider = options.timestampedProvider ?? "assemblyai";
|
|
1944
3383
|
if (provider === "whisper-groq") {
|
|
1945
3384
|
logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
|
|
1946
3385
|
if (!keys.groq) throw new Error("GROQ_API_KEY is required for whisper-groq");
|
|
1947
|
-
if (!
|
|
3386
|
+
if (!existsSync3(audioPath) || forceAll) {
|
|
1948
3387
|
await extractAudio(options.input, audioPath, AUDIO_OPTS);
|
|
1949
3388
|
}
|
|
1950
3389
|
const { readFile: readFile2 } = await import("fs/promises");
|
|
1951
3390
|
const buf = await readFile2(audioPath);
|
|
1952
3391
|
const groq = new WhisperGroqClient(keys.groq);
|
|
1953
|
-
asrResult = await groq.transcribe(buf);
|
|
3392
|
+
asrResult = await groq.transcribe(buf).catch(stageTag("asr"));
|
|
3393
|
+
writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
|
|
3394
|
+
} else if (provider === "elevenlabs") {
|
|
3395
|
+
logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
|
|
3396
|
+
if (!keys.elevenlabs)
|
|
3397
|
+
throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
|
|
3398
|
+
const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs.json`;
|
|
3399
|
+
asrResult = forceAll ? null : readJson(cachePath);
|
|
3400
|
+
if (!asrResult) {
|
|
3401
|
+
const { readFile: readFile2 } = await import("fs/promises");
|
|
3402
|
+
const buf = await readFile2(audioPath);
|
|
3403
|
+
const el = new ElevenLabsClient(keys.elevenlabs);
|
|
3404
|
+
asrResult = await el.transcribe(buf).catch(stageTag("asr"));
|
|
3405
|
+
writeJson(cachePath, asrResult);
|
|
3406
|
+
} else {
|
|
3407
|
+
logger.info("[elevenlabs] cache hit");
|
|
3408
|
+
}
|
|
1954
3409
|
writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
|
|
3410
|
+
logger.info(
|
|
3411
|
+
`[elevenlabs] ${asrResult.utterances.length} utterances, ${asrResult.words.length} words, ${asrResult.speakers?.length ?? "?"} speakers`
|
|
3412
|
+
);
|
|
1955
3413
|
} else {
|
|
1956
3414
|
logger.info("=== timestamped (AssemblyAI) ===");
|
|
1957
3415
|
if (!keys.assemblyai)
|
|
@@ -1962,7 +3420,7 @@ async function transcribe(opts) {
|
|
|
1962
3420
|
apiKey: keys.assemblyai,
|
|
1963
3421
|
cacheDir: `${options.intermediatesDir}/assemblyai`
|
|
1964
3422
|
});
|
|
1965
|
-
asrResult = await aai.transcribe(audioPath);
|
|
3423
|
+
asrResult = await aai.transcribe(audioPath).catch(stageTag("asr"));
|
|
1966
3424
|
writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
|
|
1967
3425
|
}
|
|
1968
3426
|
} else {
|
|
@@ -1984,6 +3442,9 @@ async function transcribe(opts) {
|
|
|
1984
3442
|
const added = aligned.length - before;
|
|
1985
3443
|
if (added) logger.info(`gap-filled ${added} ASR fallback segment(s)`);
|
|
1986
3444
|
}
|
|
3445
|
+
if (asrResult && (asrResult.hasDiarization ?? true) && (has(passes, "align") || has(passes, "consistency"))) {
|
|
3446
|
+
aligned = splitMixedVoiceSegments(aligned, asrResult.utterances);
|
|
3447
|
+
}
|
|
1987
3448
|
let segments = aligned;
|
|
1988
3449
|
let speakers = [];
|
|
1989
3450
|
if (has(passes, "consistency") && asrResult) {
|
|
@@ -2003,31 +3464,75 @@ async function transcribe(opts) {
|
|
|
2003
3464
|
speakers = c.speakers;
|
|
2004
3465
|
}
|
|
2005
3466
|
}
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
3467
|
+
const nameHints = {};
|
|
3468
|
+
for (const sp of speakers) {
|
|
3469
|
+
if (sp.name && sp.name !== sp.id) nameHints[sp.id] = sp.name;
|
|
3470
|
+
}
|
|
3471
|
+
segments = segments.map(
|
|
3472
|
+
(s) => s.speakerName !== s.speaker ? { ...s, speakerName: s.speaker } : s
|
|
3473
|
+
);
|
|
3474
|
+
speakers = speakers.map((sp) => sp.name !== sp.id ? { ...sp, name: sp.id } : sp);
|
|
3475
|
+
if (options.diarizationLevel >= 3 && has(passes, "identify")) {
|
|
3476
|
+
const reasonerA = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
|
|
3477
|
+
if (!reasonerA) {
|
|
3478
|
+
logger.warn(
|
|
3479
|
+
"identify: no reasoner-capable API key found (DEEPSEEK/GEMINI/OPENAI/\u2026) \u2014 skipping speaker naming"
|
|
3480
|
+
);
|
|
3481
|
+
} else {
|
|
3482
|
+
const mode = options.identifyMode;
|
|
3483
|
+
const reasonerB = mode === "dual" ? resolveSecondReasoner(reasonerA.info, keys) : null;
|
|
3484
|
+
const idConfig = {
|
|
3485
|
+
mode,
|
|
3486
|
+
reasonerA: reasonerA.info.model,
|
|
3487
|
+
reasonerB: reasonerB?.info.model ?? null
|
|
3488
|
+
};
|
|
3489
|
+
const idCachePath = `${options.intermediatesDir}/identified.json`;
|
|
3490
|
+
const cachedId = forceAll ? null : readJson(
|
|
3491
|
+
idCachePath
|
|
3492
|
+
);
|
|
3493
|
+
const idConfigMatches = cachedId?.config && JSON.stringify(cachedId.config) === JSON.stringify(idConfig);
|
|
3494
|
+
let nameMap = null;
|
|
3495
|
+
if (idConfigMatches && cachedId?.nameMap && Object.keys(cachedId.nameMap).length > 0) {
|
|
3496
|
+
logger.info("=== identify (cached) ===");
|
|
3497
|
+
nameMap = cachedId.nameMap;
|
|
3498
|
+
} else {
|
|
3499
|
+
logger.info(
|
|
3500
|
+
`=== identify (${reasonerA.info.model}${reasonerB ? ` + ${reasonerB.info.model} second opinion` : ""}) ===`
|
|
3501
|
+
);
|
|
3502
|
+
checkAbort();
|
|
3503
|
+
const id = await identifySpeakersV2(
|
|
3504
|
+
{
|
|
3505
|
+
client: reasonerA.client,
|
|
3506
|
+
model: reasonerA.info.model,
|
|
3507
|
+
provider: reasonerA.info.provider
|
|
3508
|
+
},
|
|
3509
|
+
reasonerB ? {
|
|
3510
|
+
client: reasonerB.client,
|
|
3511
|
+
model: reasonerB.info.model,
|
|
3512
|
+
provider: reasonerB.info.provider
|
|
3513
|
+
} : null,
|
|
3514
|
+
segments.map((s) => ({ speaker: s.speaker, text: s.text })),
|
|
3515
|
+
speakers,
|
|
3516
|
+
{
|
|
3517
|
+
roster: description?.roster ?? "(no roster available \u2014 infer from the transcript alone)",
|
|
3518
|
+
knownSpeakers: options.knownSpeakers,
|
|
3519
|
+
mode,
|
|
3520
|
+
nameHints,
|
|
3521
|
+
sourceFileName: basename3(options.input)
|
|
3522
|
+
}
|
|
3523
|
+
).catch(stageTag("identify"));
|
|
3524
|
+
writeJson(idCachePath, { ...id, config: idConfig });
|
|
3525
|
+
nameMap = id.nameMap;
|
|
3526
|
+
}
|
|
3527
|
+
logger.info(
|
|
3528
|
+
`identified ${Object.keys(nameMap).length} speakers: ${JSON.stringify(nameMap)}`
|
|
3529
|
+
);
|
|
3530
|
+
const nm = nameMap;
|
|
3531
|
+
segments = segments.map(
|
|
3532
|
+
(s) => nm[s.speaker] ? { ...s, speakerName: nm[s.speaker] } : s
|
|
3533
|
+
);
|
|
3534
|
+
speakers = speakers.map((sp) => nm[sp.id] ? { ...sp, name: nm[sp.id] } : sp);
|
|
3535
|
+
}
|
|
2031
3536
|
}
|
|
2032
3537
|
let finalSegments = [];
|
|
2033
3538
|
if (has(passes, "finalize")) {
|
|
@@ -2038,33 +3543,106 @@ async function transcribe(opts) {
|
|
|
2038
3543
|
finalSegments = (forceAll ? null : readJson(`${options.intermediatesDir}/final.json`)) ?? [];
|
|
2039
3544
|
}
|
|
2040
3545
|
logger.info(`final segments: ${finalSegments.length}`);
|
|
3546
|
+
const receipt = computeReceipt(getLlmUsage(), tsProvider, duration);
|
|
3547
|
+
const wallMs = Date.now() - runStartedAt;
|
|
2041
3548
|
const metadata = {
|
|
2042
3549
|
sourceFile: options.input,
|
|
2043
3550
|
duration,
|
|
2044
3551
|
processedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2045
3552
|
models: {
|
|
2046
3553
|
transcribe: models.transcribe,
|
|
2047
|
-
timestamped: tsProvider === "whisper-groq" ? "whisper-large-v3 (groq)" : tsProvider === "none" ? "none" : "assemblyai-universal-2"
|
|
3554
|
+
timestamped: tsProvider === "whisper-groq" ? "whisper-large-v3 (groq)" : tsProvider === "elevenlabs" ? "scribe-v2 (elevenlabs)" : tsProvider === "none" ? "none" : "assemblyai-universal-2"
|
|
2048
3555
|
},
|
|
2049
|
-
passes
|
|
3556
|
+
passes,
|
|
3557
|
+
wallMs,
|
|
3558
|
+
cost: {
|
|
3559
|
+
estimatedUsd: estimate.totalUsd,
|
|
3560
|
+
actualUsd: receipt.totalUsd,
|
|
3561
|
+
pricesAsOf: PRICES_AS_OF,
|
|
3562
|
+
lines: receipt.lines,
|
|
3563
|
+
llmCalls: receipt.totals.calls,
|
|
3564
|
+
inputTokens: receipt.totals.inputTokens,
|
|
3565
|
+
outputTokens: receipt.totals.outputTokens
|
|
3566
|
+
}
|
|
2050
3567
|
};
|
|
2051
3568
|
const result = { segments: finalSegments, speakers, metadata };
|
|
3569
|
+
writeJson(`${options.intermediatesDir}/result.json`, result);
|
|
2052
3570
|
for (const fmt of options.formats) {
|
|
2053
3571
|
const base = basename3(options.input, ext(options.input));
|
|
2054
3572
|
if (fmt === "srt")
|
|
2055
|
-
|
|
3573
|
+
writeFileSync2(
|
|
2056
3574
|
`${options.outputDir}/${base}.srt`,
|
|
2057
3575
|
formatSrt(result, { title: base })
|
|
2058
3576
|
);
|
|
2059
3577
|
if (fmt === "md")
|
|
2060
|
-
|
|
3578
|
+
writeFileSync2(
|
|
2061
3579
|
`${options.outputDir}/${base}.md`,
|
|
2062
|
-
formatMarkdown(result, { title: base })
|
|
3580
|
+
formatMarkdown(result, { title: base, mdStyle: options.mdStyle })
|
|
3581
|
+
);
|
|
3582
|
+
if (fmt === "txt")
|
|
3583
|
+
writeFileSync2(
|
|
3584
|
+
`${options.outputDir}/${base}.txt`,
|
|
3585
|
+
formatText(result, { title: base })
|
|
3586
|
+
);
|
|
3587
|
+
if (fmt === "html")
|
|
3588
|
+
writeFileSync2(
|
|
3589
|
+
`${options.outputDir}/${base}.html`,
|
|
3590
|
+
formatHtml(result, { title: base })
|
|
2063
3591
|
);
|
|
2064
3592
|
if (fmt === "json")
|
|
2065
|
-
|
|
3593
|
+
writeFileSync2(`${options.outputDir}/${base}.json`, formatJson(result));
|
|
3594
|
+
}
|
|
3595
|
+
if (options.summary && finalSegments.length > 0) {
|
|
3596
|
+
const reasoner = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
|
|
3597
|
+
if (!reasoner) {
|
|
3598
|
+
logger.warn("summary: no reasoner-capable key \u2014 skipping");
|
|
3599
|
+
} else {
|
|
3600
|
+
logger.info(`=== summary (${reasoner.info.model}) ===`);
|
|
3601
|
+
try {
|
|
3602
|
+
const summary = await summarizeTranscript(
|
|
3603
|
+
reasoner.client,
|
|
3604
|
+
reasoner.info.model,
|
|
3605
|
+
result,
|
|
3606
|
+
options.instructions
|
|
3607
|
+
);
|
|
3608
|
+
const base = basename3(options.input, ext(options.input));
|
|
3609
|
+
writeFileSync2(`${options.outputDir}/${base}.summary.md`, summary);
|
|
3610
|
+
logger.info(`summary written to ${base}.summary.md`);
|
|
3611
|
+
} catch (err) {
|
|
3612
|
+
logger.warn(`summary failed: ${err instanceof Error ? err.message : err}`);
|
|
3613
|
+
}
|
|
3614
|
+
}
|
|
3615
|
+
}
|
|
3616
|
+
try {
|
|
3617
|
+
const base = basename3(options.input, ext(options.input));
|
|
3618
|
+
const partial = `${options.outputDir}/${base}.partial.md`;
|
|
3619
|
+
if (existsSync3(partial)) (await import("fs/promises")).unlink(partial);
|
|
3620
|
+
} catch {
|
|
2066
3621
|
}
|
|
2067
3622
|
logger.info(`outputs written to ${options.outputDir}`);
|
|
3623
|
+
const mins = Math.floor(wallMs / 6e4);
|
|
3624
|
+
const secs = Math.round(wallMs % 6e4 / 1e3);
|
|
3625
|
+
logger.info(
|
|
3626
|
+
`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`
|
|
3627
|
+
);
|
|
3628
|
+
for (const line of receipt.lines) logger.info(` ${line}`);
|
|
3629
|
+
recordRun(
|
|
3630
|
+
{
|
|
3631
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3632
|
+
input: basename3(options.input),
|
|
3633
|
+
durationSec: duration,
|
|
3634
|
+
wallMs,
|
|
3635
|
+
models: metadata.models,
|
|
3636
|
+
segments: finalSegments.length,
|
|
3637
|
+
characters: finalSegments.reduce((n, s) => n + s.text.length, 0),
|
|
3638
|
+
speakers: speakers.length,
|
|
3639
|
+
llmCalls: receipt.totals.calls,
|
|
3640
|
+
inputTokens: receipt.totals.inputTokens,
|
|
3641
|
+
outputTokens: receipt.totals.outputTokens,
|
|
3642
|
+
costUsd: receipt.totalUsd
|
|
3643
|
+
},
|
|
3644
|
+
receipt.perModel
|
|
3645
|
+
);
|
|
2068
3646
|
return result;
|
|
2069
3647
|
}
|
|
2070
3648
|
function ext(p) {
|
|
@@ -2105,12 +3683,15 @@ export {
|
|
|
2105
3683
|
alignSegments,
|
|
2106
3684
|
assignGlobalSpeakers,
|
|
2107
3685
|
finalizeSegments,
|
|
3686
|
+
formatHtml,
|
|
2108
3687
|
formatJson,
|
|
2109
3688
|
formatMarkdown,
|
|
2110
3689
|
formatSrt,
|
|
3690
|
+
formatText,
|
|
2111
3691
|
identifySpeakers,
|
|
2112
3692
|
parseSrt,
|
|
2113
3693
|
planChunks,
|
|
3694
|
+
summarizeTranscript,
|
|
2114
3695
|
transcribe
|
|
2115
3696
|
};
|
|
2116
3697
|
//# sourceMappingURL=index.js.map
|