offmute-v2 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +108 -44
- package/dist/browser.browser.js +168 -69
- package/dist/browser.browser.js.map +1 -1
- package/dist/browser.d.ts +72 -19
- package/dist/cli.js +2095 -788
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1269 -490
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +238 -18
- package/dist/index.d.ts +238 -18
- package/dist/index.js +1272 -493
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
// src/core/pipeline.ts
|
|
2
|
-
import { existsSync as
|
|
2
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
3
|
+
import { readFile as readFile2 } from "fs/promises";
|
|
4
|
+
|
|
5
|
+
// src/core/models.ts
|
|
6
|
+
var DEFAULT_TRANSCRIBE_MODEL = "gemini-4-hydrogen";
|
|
7
|
+
var PRO_TRANSCRIBE_MODEL = "gemini-4-argon";
|
|
8
|
+
var DEFAULT_REASONER_MODEL = "deepseek-chat";
|
|
3
9
|
|
|
4
10
|
// src/core/config.ts
|
|
5
11
|
import { createHash } from "crypto";
|
|
6
|
-
import { basename, dirname, resolve } from "path";
|
|
12
|
+
import { basename, dirname, join, resolve } from "path";
|
|
7
13
|
import { statSync } from "fs";
|
|
8
14
|
import { tmpdir } from "os";
|
|
9
15
|
var DEFAULT_PASSES = [
|
|
@@ -15,19 +21,6 @@ var DEFAULT_PASSES = [
|
|
|
15
21
|
"consistency",
|
|
16
22
|
"finalize"
|
|
17
23
|
];
|
|
18
|
-
var MODELS = {
|
|
19
|
-
gemini25Pro: "gemini-2.5-pro",
|
|
20
|
-
gemini25Flash: "gemini-2.5-flash",
|
|
21
|
-
gemini3Pro: "gemini-3-pro-preview",
|
|
22
|
-
gemini31Pro: "gemini-3.1-pro-preview",
|
|
23
|
-
geminiFlashLatest: "gemini-flash-latest",
|
|
24
|
-
deepseek: "deepseek-chat",
|
|
25
|
-
deepseekReasoner: "deepseek-reasoner",
|
|
26
|
-
gpt4o: "gpt-4o",
|
|
27
|
-
claudeSonnet: "claude-sonnet-4-5"
|
|
28
|
-
};
|
|
29
|
-
var DEFAULT_TRANSCRIBE_MODEL = MODELS.gemini31Pro;
|
|
30
|
-
var DEFAULT_REASONER_MODEL = MODELS.deepseek;
|
|
31
24
|
function resolveKeys(injected) {
|
|
32
25
|
const env = process.env;
|
|
33
26
|
return {
|
|
@@ -79,19 +72,22 @@ function resolveOptions(opts) {
|
|
|
79
72
|
model: opts.model,
|
|
80
73
|
reasoner: opts.reasoner,
|
|
81
74
|
timestampedProvider: opts.timestampedProvider,
|
|
75
|
+
language: opts.language,
|
|
82
76
|
force: opts.force ?? false,
|
|
83
77
|
onlyChunk: opts.onlyChunk,
|
|
84
78
|
showProgress: opts.showProgress ?? true,
|
|
85
79
|
llmLog: opts.llmLog ?? true,
|
|
86
80
|
logLevel: opts.logLevel ?? "info",
|
|
87
|
-
signal: opts.signal
|
|
81
|
+
signal: opts.signal,
|
|
82
|
+
onProgress: opts.onProgress,
|
|
83
|
+
zeroStorage: opts.zeroStorage ?? true
|
|
88
84
|
};
|
|
89
85
|
}
|
|
90
|
-
function deriveIntermediatesDir(input) {
|
|
86
|
+
function deriveIntermediatesDir(input, parent = tmpdir()) {
|
|
91
87
|
const abs = resolve(input);
|
|
92
88
|
const hash = createHash("sha1").update(abs).digest("hex").slice(0, 8);
|
|
93
89
|
const base = basename(input, extOf(input)) || "input";
|
|
94
|
-
return
|
|
90
|
+
return join(parent, `offmute-v2-${base}-${hash}`);
|
|
95
91
|
}
|
|
96
92
|
function extOf(p) {
|
|
97
93
|
const i = p.lastIndexOf(".");
|
|
@@ -111,9 +107,7 @@ function inputSignature(input) {
|
|
|
111
107
|
function configSignature(o) {
|
|
112
108
|
const relevant = {
|
|
113
109
|
model: o.model ?? DEFAULT_TRANSCRIBE_MODEL,
|
|
114
|
-
reasoner: o.reasoner ?? DEFAULT_REASONER_MODEL,
|
|
115
110
|
instructions: o.instructions ?? "",
|
|
116
|
-
knownSpeakers: o.knownSpeakers ?? [],
|
|
117
111
|
chunkDurationSec: o.chunkDurationSec ?? 600,
|
|
118
112
|
chunkOverlapSec: o.chunkOverlapSec ?? 60,
|
|
119
113
|
screenshotCount: o.screenshotCount ?? 6,
|
|
@@ -149,6 +143,15 @@ function planChunks(totalDuration, chunkDuration, overlap2) {
|
|
|
149
143
|
return chunks;
|
|
150
144
|
}
|
|
151
145
|
|
|
146
|
+
// src/core/progress.ts
|
|
147
|
+
function emitTo(listener, event) {
|
|
148
|
+
if (!listener) return;
|
|
149
|
+
try {
|
|
150
|
+
listener(event);
|
|
151
|
+
} catch {
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
152
155
|
// src/utils/logger.ts
|
|
153
156
|
var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
154
157
|
var currentLevel = "info";
|
|
@@ -382,7 +385,9 @@ function snapToSilence(boundary, silences, tolerance) {
|
|
|
382
385
|
}
|
|
383
386
|
|
|
384
387
|
// src/providers/gemini.ts
|
|
385
|
-
import {
|
|
388
|
+
import {
|
|
389
|
+
GoogleGenAI
|
|
390
|
+
} from "@google/genai";
|
|
386
391
|
import { basename as basename2 } from "path";
|
|
387
392
|
|
|
388
393
|
// src/providers/llm-log.ts
|
|
@@ -450,6 +455,38 @@ async function withRetry(label, fn, opts = {}) {
|
|
|
450
455
|
throw lastErr;
|
|
451
456
|
}
|
|
452
457
|
|
|
458
|
+
// src/providers/gemini-usage.ts
|
|
459
|
+
function usageFromMetadata(meta) {
|
|
460
|
+
const thoughtTokens = meta?.thoughtsTokenCount ?? 0;
|
|
461
|
+
return {
|
|
462
|
+
inputTokens: meta?.promptTokenCount ?? 0,
|
|
463
|
+
outputTokens: (meta?.candidatesTokenCount ?? 0) + thoughtTokens,
|
|
464
|
+
thoughtTokens,
|
|
465
|
+
totalTokens: meta?.totalTokenCount ?? 0
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// src/providers/gemini-models.ts
|
|
470
|
+
function resolveThinking(model) {
|
|
471
|
+
const m = model.toLowerCase();
|
|
472
|
+
if (m.includes("gemini-2.0")) return void 0;
|
|
473
|
+
if (m.includes("gemini-4")) return { thinkingLevel: "LOW" };
|
|
474
|
+
if (m.includes("gemini-2.5")) {
|
|
475
|
+
return { thinkingBudget: m.includes("pro") ? 128 : 0 };
|
|
476
|
+
}
|
|
477
|
+
if (m.includes("-latest")) return { thinkingLevel: "LOW" };
|
|
478
|
+
if (m.includes("gemini-3"))
|
|
479
|
+
return { thinkingLevel: m.includes("pro") ? "LOW" : "MINIMAL" };
|
|
480
|
+
return void 0;
|
|
481
|
+
}
|
|
482
|
+
function fallbackThinking(rejected) {
|
|
483
|
+
return rejected.thinkingLevel === "MINIMAL" ? { thinkingLevel: "LOW" } : void 0;
|
|
484
|
+
}
|
|
485
|
+
function isThinkingConfigError(message) {
|
|
486
|
+
if (!message) return false;
|
|
487
|
+
return /thinking/i.test(message) && /(not supported|invalid|unsupported|unknown name|unexpected)/i.test(message);
|
|
488
|
+
}
|
|
489
|
+
|
|
453
490
|
// src/providers/gemini.ts
|
|
454
491
|
var SDK_KEY_WARNING = "Both GOOGLE_API_KEY and GEMINI_API_KEY are set";
|
|
455
492
|
var originalWarn = console.warn.bind(console);
|
|
@@ -478,25 +515,15 @@ function detectMime(path) {
|
|
|
478
515
|
return MIME_BY_EXT[ext2] ?? "application/octet-stream";
|
|
479
516
|
}
|
|
480
517
|
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
481
|
-
function resolveThinking(model) {
|
|
482
|
-
const m = model.toLowerCase();
|
|
483
|
-
if (m.includes("gemini-2.0")) return void 0;
|
|
484
|
-
if (m.includes("gemini-2.5")) {
|
|
485
|
-
return { thinkingBudget: m.includes("pro") ? 128 : 0 };
|
|
486
|
-
}
|
|
487
|
-
if (m.includes("gemini-3") || m.includes("flash-latest") || m.includes("pro-latest")) {
|
|
488
|
-
return { thinkingLevel: m.includes("pro") ? "LOW" : "MINIMAL" };
|
|
489
|
-
}
|
|
490
|
-
return void 0;
|
|
491
|
-
}
|
|
492
|
-
function isThinkingConfigError(message) {
|
|
493
|
-
if (!message) return false;
|
|
494
|
-
return /thinking/i.test(message) && /(not supported|invalid|unsupported|unknown name|unexpected)/i.test(message);
|
|
495
|
-
}
|
|
496
518
|
var GeminiClient = class {
|
|
497
519
|
ai;
|
|
498
|
-
|
|
499
|
-
|
|
520
|
+
zeroStorage;
|
|
521
|
+
constructor(apiKey, opts = {}) {
|
|
522
|
+
this.ai = new GoogleGenAI({
|
|
523
|
+
apiKey,
|
|
524
|
+
...opts.baseUrl ? { httpOptions: { baseUrl: opts.baseUrl } } : {}
|
|
525
|
+
});
|
|
526
|
+
this.zeroStorage = opts.zeroStorage ?? true;
|
|
500
527
|
}
|
|
501
528
|
/** Upload a file and wait until it's done processing. Uploads ride one long HTTP
|
|
502
529
|
* request each — the retry loop in generate() doesn't cover them, and transient
|
|
@@ -539,12 +566,15 @@ var GeminiClient = class {
|
|
|
539
566
|
maxOutputTokens,
|
|
540
567
|
temperature
|
|
541
568
|
};
|
|
569
|
+
if (this.zeroStorage) config.store = false;
|
|
542
570
|
if (responseSchema) {
|
|
543
571
|
config.responseMimeType = "application/json";
|
|
544
572
|
config.responseSchema = responseSchema;
|
|
573
|
+
} else if (opts.responseJson) {
|
|
574
|
+
config.responseMimeType = "application/json";
|
|
545
575
|
}
|
|
546
576
|
if (systemInstruction) config.systemInstruction = systemInstruction;
|
|
547
|
-
|
|
577
|
+
let thinking = resolveThinking(model);
|
|
548
578
|
if (thinking) config.thinkingConfig = thinking;
|
|
549
579
|
const parts = uploaded.map((f) => ({
|
|
550
580
|
fileData: { fileUri: f.uri, mimeType: f.mimeType }
|
|
@@ -554,21 +584,31 @@ var GeminiClient = class {
|
|
|
554
584
|
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
555
585
|
const t0 = Date.now();
|
|
556
586
|
try {
|
|
557
|
-
const
|
|
587
|
+
const controller = new AbortController();
|
|
588
|
+
const stream = await this.ai.models.generateContentStream({
|
|
558
589
|
model,
|
|
559
590
|
contents: [{ role: "user", parts }],
|
|
560
|
-
config
|
|
591
|
+
config: { ...config, abortSignal: controller.signal }
|
|
561
592
|
});
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
593
|
+
let text = "";
|
|
594
|
+
let usageMeta;
|
|
595
|
+
let abortReason = null;
|
|
596
|
+
for await (const chunk of stream) {
|
|
597
|
+
text += chunk.text ?? "";
|
|
598
|
+
if (chunk.usageMetadata) usageMeta = chunk.usageMetadata;
|
|
599
|
+
abortReason = opts.shouldAbort?.(text) ?? null;
|
|
600
|
+
if (abortReason) {
|
|
601
|
+
controller.abort();
|
|
602
|
+
break;
|
|
570
603
|
}
|
|
571
|
-
}
|
|
604
|
+
}
|
|
605
|
+
const usage = usageFromMetadata(usageMeta);
|
|
606
|
+
const error = abortReason ? `aborted: ${abortReason}` : void 0;
|
|
607
|
+
if (error) {
|
|
608
|
+
logger.warn(
|
|
609
|
+
`[gemini] ${opts.logKind ?? "call"}${opts.logChunk !== void 0 ? ` chunk ${opts.logChunk}` : ""} ${error} after ${text.length} chars`
|
|
610
|
+
);
|
|
611
|
+
}
|
|
572
612
|
logLlmCall({
|
|
573
613
|
ts: new Date(t0).toISOString(),
|
|
574
614
|
provider: "gemini",
|
|
@@ -577,18 +617,22 @@ var GeminiClient = class {
|
|
|
577
617
|
chunk: opts.logChunk,
|
|
578
618
|
prompt,
|
|
579
619
|
response: text,
|
|
580
|
-
usage
|
|
620
|
+
usage,
|
|
581
621
|
durationMs: Date.now() - t0,
|
|
582
|
-
attempt: attempt + 1
|
|
622
|
+
attempt: attempt + 1,
|
|
623
|
+
...error ? { error } : {}
|
|
583
624
|
});
|
|
584
|
-
return
|
|
625
|
+
return error ? { text, usage, error } : { text, usage };
|
|
585
626
|
} catch (err) {
|
|
586
627
|
lastError = err instanceof Error ? err.message : String(err);
|
|
587
|
-
if (
|
|
588
|
-
|
|
628
|
+
if (thinking && isThinkingConfigError(lastError)) {
|
|
629
|
+
const next = fallbackThinking(thinking);
|
|
589
630
|
logger.warn(
|
|
590
|
-
`[gemini] model ${model} rejected thinking config \u2014 retrying without it`
|
|
631
|
+
`[gemini] model ${model} rejected thinking config ${JSON.stringify(thinking)} \u2014 retrying ${next ? `with ${JSON.stringify(next)}` : "without it"}`
|
|
591
632
|
);
|
|
633
|
+
thinking = next;
|
|
634
|
+
if (thinking) config.thinkingConfig = thinking;
|
|
635
|
+
else delete config.thinkingConfig;
|
|
592
636
|
continue;
|
|
593
637
|
}
|
|
594
638
|
logger.warn(
|
|
@@ -654,51 +698,93 @@ var GeminiClient = class {
|
|
|
654
698
|
};
|
|
655
699
|
|
|
656
700
|
// src/providers/assemblyai.ts
|
|
657
|
-
import {
|
|
701
|
+
import {
|
|
702
|
+
AssemblyAI
|
|
703
|
+
} from "assemblyai";
|
|
658
704
|
import { createHash as createHash2 } from "crypto";
|
|
659
|
-
import { readFile, mkdir as mkdir2, writeFile } from "fs/promises";
|
|
705
|
+
import { readFile, mkdir as mkdir2, writeFile, rm } from "fs/promises";
|
|
660
706
|
import { existsSync } from "fs";
|
|
661
707
|
import { dirname as dirname3 } from "path";
|
|
662
708
|
async function fileHash(path) {
|
|
663
709
|
const buf = await readFile(path);
|
|
664
710
|
return createHash2("sha256").update(buf).digest("hex").slice(0, 24);
|
|
665
711
|
}
|
|
712
|
+
var DELETED_TEXT = "Deleted by user.";
|
|
713
|
+
async function readPendingId(pendingPath) {
|
|
714
|
+
if (!existsSync(pendingPath)) return void 0;
|
|
715
|
+
try {
|
|
716
|
+
return JSON.parse(await readFile(pendingPath, "utf-8")).id;
|
|
717
|
+
} catch {
|
|
718
|
+
return void 0;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
666
721
|
var AssemblyAIProvider = class {
|
|
667
722
|
client;
|
|
668
723
|
cacheDir;
|
|
669
724
|
constructor(opts) {
|
|
670
|
-
this.client = new AssemblyAI({ apiKey: opts.apiKey });
|
|
725
|
+
this.client = new AssemblyAI({ apiKey: opts.apiKey, baseUrl: opts.baseUrl });
|
|
671
726
|
this.cacheDir = opts.cacheDir;
|
|
672
727
|
this.speechModel = opts.speechModel ?? "universal";
|
|
673
728
|
this.speakersExpected = opts.speakersExpected;
|
|
729
|
+
this.language = opts.language;
|
|
730
|
+
this.zeroStorage = opts.zeroStorage ?? true;
|
|
674
731
|
}
|
|
675
732
|
speechModel;
|
|
676
733
|
speakersExpected;
|
|
734
|
+
language;
|
|
735
|
+
zeroStorage;
|
|
736
|
+
/** Whether the last transcribe() was served from the content-hash cache (no paid call). */
|
|
737
|
+
lastFromCache = false;
|
|
677
738
|
/** Transcribe a local audio file. Returns cached result if available. */
|
|
678
739
|
async transcribe(filePath) {
|
|
679
740
|
const hash = await fileHash(filePath);
|
|
680
|
-
const
|
|
741
|
+
const variant = [
|
|
742
|
+
`lang-${this.language ?? "auto"}`,
|
|
743
|
+
this.speakersExpected && `spk-${this.speakersExpected}`,
|
|
744
|
+
this.speechModel !== "universal" && this.speechModel
|
|
745
|
+
].filter(Boolean).join("_");
|
|
746
|
+
const cachePath = this.cacheDir ? `${this.cacheDir}/${hash}_${variant}.json` : void 0;
|
|
747
|
+
const pendingPath = cachePath?.replace(/\.json$/, ".pending.json");
|
|
748
|
+
this.lastFromCache = false;
|
|
681
749
|
if (cachePath && existsSync(cachePath)) {
|
|
682
750
|
logger.info(`[assemblyai] cache hit ${hash}`);
|
|
751
|
+
this.lastFromCache = true;
|
|
752
|
+
if (pendingPath) await this.finish(pendingPath, await readPendingId(pendingPath));
|
|
683
753
|
return JSON.parse(await readFile(cachePath, "utf-8"));
|
|
684
754
|
}
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
755
|
+
let transcript = pendingPath ? await this.resume(pendingPath) : void 0;
|
|
756
|
+
if (!transcript) {
|
|
757
|
+
logger.info(`[assemblyai] uploading ${filePath}...`);
|
|
758
|
+
const uploadUrl = await withRetry(
|
|
759
|
+
"assemblyai upload",
|
|
760
|
+
() => this.client.files.upload(filePath)
|
|
761
|
+
);
|
|
762
|
+
logger.info(
|
|
763
|
+
`[assemblyai] transcribing (speech_model=${this.speechModel}, language=${this.language ?? "auto-detect"})...`
|
|
764
|
+
);
|
|
765
|
+
const params = {
|
|
766
|
+
audio: uploadUrl,
|
|
767
|
+
speaker_labels: true,
|
|
768
|
+
speech_model: this.speechModel
|
|
769
|
+
};
|
|
770
|
+
if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
|
|
771
|
+
if (this.language) params.language_code = this.language;
|
|
772
|
+
else params.language_detection = true;
|
|
773
|
+
const job = await withRetry(
|
|
774
|
+
"assemblyai submit",
|
|
775
|
+
() => this.client.transcripts.submit(params)
|
|
776
|
+
);
|
|
777
|
+
if (pendingPath) {
|
|
778
|
+
await mkdir2(dirname3(pendingPath), { recursive: true });
|
|
779
|
+
await writeFile(pendingPath, JSON.stringify({ id: job.id }));
|
|
780
|
+
}
|
|
781
|
+
transcript = await withRetry(
|
|
782
|
+
"assemblyai transcribe",
|
|
783
|
+
() => this.client.transcripts.waitUntilReady(job.id)
|
|
784
|
+
);
|
|
785
|
+
}
|
|
701
786
|
if (transcript.status === "error") {
|
|
787
|
+
if (pendingPath) await rm(pendingPath, { force: true });
|
|
702
788
|
throw new Error(`AssemblyAI error: ${transcript.error}`);
|
|
703
789
|
}
|
|
704
790
|
const result = this.mapTranscript(transcript, hash);
|
|
@@ -707,10 +793,53 @@ var AssemblyAIProvider = class {
|
|
|
707
793
|
await writeFile(cachePath, JSON.stringify(result, null, 2));
|
|
708
794
|
}
|
|
709
795
|
logger.info(
|
|
710
|
-
`[assemblyai] done: ${result.utterances.length} utterances, ${result.words.length} words, ${result.speakers.length} speakers`
|
|
796
|
+
`[assemblyai] done: ${result.utterances.length} utterances, ${result.words.length} words, ${result.speakers.length} speakers, language ${result.languageCode ?? "?"}`
|
|
711
797
|
);
|
|
798
|
+
if (pendingPath) await this.finish(pendingPath, transcript.id);
|
|
799
|
+
else if (this.zeroStorage && transcript.id) await this.deleteRemote(transcript.id);
|
|
712
800
|
return result;
|
|
713
801
|
}
|
|
802
|
+
/** Delete job `id` from AssemblyAI (with zero storage), then forget it. */
|
|
803
|
+
async finish(pendingPath, id) {
|
|
804
|
+
if (this.zeroStorage && id) await this.deleteRemote(id);
|
|
805
|
+
await rm(pendingPath, { force: true });
|
|
806
|
+
}
|
|
807
|
+
async deleteRemote(id) {
|
|
808
|
+
await this.client.transcripts.delete(id).then(
|
|
809
|
+
() => logger.debug(`[assemblyai] deleted transcript ${id} from AssemblyAI`),
|
|
810
|
+
(err) => logger.warn(
|
|
811
|
+
`[assemblyai] couldn't delete transcript ${id} from AssemblyAI (it expires in 30 days): ${err instanceof Error ? err.message : String(err)}`
|
|
812
|
+
)
|
|
813
|
+
);
|
|
814
|
+
}
|
|
815
|
+
/** The finished job a stopped run left at `pendingPath`, or undefined to send the audio
|
|
816
|
+
* again: when there is none, or AssemblyAI says it's gone (not found, failed, deleted).
|
|
817
|
+
* Anything less certain (offline, an outage, a refused key) is thrown with the job kept,
|
|
818
|
+
* so the next run neither pays twice nor leaves the job behind undeleted. */
|
|
819
|
+
async resume(pendingPath) {
|
|
820
|
+
const id = await readPendingId(pendingPath);
|
|
821
|
+
if (id) {
|
|
822
|
+
logger.info(`[assemblyai] picking up transcript ${id}, left by a stopped run...`);
|
|
823
|
+
let gone;
|
|
824
|
+
try {
|
|
825
|
+
const t = await withRetry(
|
|
826
|
+
"assemblyai transcribe",
|
|
827
|
+
() => this.client.transcripts.waitUntilReady(id)
|
|
828
|
+
);
|
|
829
|
+
if (t.status === "completed" && t.text !== DELETED_TEXT) return t;
|
|
830
|
+
gone = t.status === "error" ? `it failed: ${t.error}` : "it was deleted";
|
|
831
|
+
} catch (err) {
|
|
832
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
833
|
+
if (!/not found/i.test(message)) throw err;
|
|
834
|
+
gone = message;
|
|
835
|
+
}
|
|
836
|
+
logger.warn(
|
|
837
|
+
`[assemblyai] transcript ${id} is gone (${gone}) \u2014 sending the audio again`
|
|
838
|
+
);
|
|
839
|
+
}
|
|
840
|
+
await rm(pendingPath, { force: true });
|
|
841
|
+
return void 0;
|
|
842
|
+
}
|
|
714
843
|
mapTranscript(t, id) {
|
|
715
844
|
const toWord = (w) => ({
|
|
716
845
|
text: w.text,
|
|
@@ -740,6 +869,7 @@ var AssemblyAIProvider = class {
|
|
|
740
869
|
durationSec,
|
|
741
870
|
audioDurationSec: t.audio_duration ?? void 0,
|
|
742
871
|
// AssemblyAI returns seconds (not ms)
|
|
872
|
+
languageCode: t.language_code ?? void 0,
|
|
743
873
|
speakers: [...speakers].sort(),
|
|
744
874
|
transcriptId: t.id ?? id,
|
|
745
875
|
speechModelUsed: t.speech_model_used ?? void 0,
|
|
@@ -758,7 +888,7 @@ var WhisperGroqClient = class {
|
|
|
758
888
|
apiKey;
|
|
759
889
|
model;
|
|
760
890
|
baseUrl;
|
|
761
|
-
async transcribe(audio) {
|
|
891
|
+
async transcribe(audio, opts = {}) {
|
|
762
892
|
const blob = audio instanceof Blob ? audio : new Blob([audio], { type: "audio/mpeg" });
|
|
763
893
|
const form = new FormData();
|
|
764
894
|
form.append("file", blob, "audio.mp3");
|
|
@@ -766,6 +896,7 @@ var WhisperGroqClient = class {
|
|
|
766
896
|
form.append("response_format", "verbose_json");
|
|
767
897
|
form.append("timestamp_granularities[]", "word");
|
|
768
898
|
form.append("timestamp_granularities[]", "segment");
|
|
899
|
+
if (opts.language) form.append("language", opts.language);
|
|
769
900
|
const res = await fetch(`${this.baseUrl}/audio/transcriptions`, {
|
|
770
901
|
method: "POST",
|
|
771
902
|
headers: { Authorization: `Bearer ${this.apiKey}` },
|
|
@@ -820,6 +951,7 @@ var ElevenLabsClient = class {
|
|
|
820
951
|
form.append("diarize", "true");
|
|
821
952
|
form.append("tag_audio_events", "false");
|
|
822
953
|
if (opts.numSpeakers) form.append("num_speakers", String(opts.numSpeakers));
|
|
954
|
+
if (opts.languageCode) form.append("language_code", opts.languageCode);
|
|
823
955
|
for (const term of opts.keyterms ?? []) form.append("keyterms", term);
|
|
824
956
|
const data = await withRetry("elevenlabs", async () => {
|
|
825
957
|
const res = await fetch(`${this.baseUrl}/speech-to-text`, {
|
|
@@ -878,17 +1010,53 @@ var ElevenLabsClient = class {
|
|
|
878
1010
|
};
|
|
879
1011
|
|
|
880
1012
|
// src/core/pricing.ts
|
|
881
|
-
var PRICES_AS_OF = "2026-
|
|
1013
|
+
var PRICES_AS_OF = "2026-11-17";
|
|
882
1014
|
var MODEL_PRICES = {
|
|
883
|
-
|
|
1015
|
+
"gemini-4-hydrogen": { textIn: 1.5, out: 7.5 },
|
|
1016
|
+
"gemini-4-argon": {
|
|
1017
|
+
until: "2026-11-30",
|
|
1018
|
+
price: { textIn: 2, out: 10 },
|
|
1019
|
+
then: { textIn: 4, out: 20 }
|
|
1020
|
+
},
|
|
1021
|
+
"gemini-4-carbon": {
|
|
1022
|
+
until: "2026-11-30",
|
|
1023
|
+
price: { textIn: 2, out: 10 },
|
|
1024
|
+
then: { textIn: 4, out: 20 }
|
|
1025
|
+
},
|
|
884
1026
|
"gemini-3.1-pro-preview": { textIn: 2, out: 12 },
|
|
885
|
-
|
|
886
|
-
"gemini-3.
|
|
1027
|
+
// ≤200k-token prompts
|
|
1028
|
+
"gemini-3.8-flash": {
|
|
1029
|
+
until: "2026-12-31",
|
|
1030
|
+
price: { textIn: 0.75, out: 3.75 },
|
|
1031
|
+
then: { textIn: 1.5, out: 7.5 }
|
|
1032
|
+
},
|
|
1033
|
+
"gemini-3.6-flash": {
|
|
1034
|
+
until: "2026-12-31",
|
|
1035
|
+
price: { textIn: 0.75, out: 3.75 },
|
|
1036
|
+
then: { textIn: 1.5, out: 7.5 }
|
|
1037
|
+
},
|
|
1038
|
+
// Deprecated 2026-10-08; requests are served by gemini-3.6-flash (priced as such).
|
|
1039
|
+
"gemini-3.5-flash": {
|
|
1040
|
+
until: "2026-12-31",
|
|
1041
|
+
price: { textIn: 0.75, out: 3.75 },
|
|
1042
|
+
then: { textIn: 1.5, out: 7.5 }
|
|
1043
|
+
},
|
|
1044
|
+
"gemini-3.5-flash-lite": { textIn: 0.3, out: 2.5 },
|
|
887
1045
|
"gemini-3-flash-preview": { textIn: 0.5, audioIn: 1, out: 3 },
|
|
888
|
-
|
|
889
|
-
"gemini-2.5-
|
|
1046
|
+
// From 2026-12-01 Google serves (and bills) 2.5 Pro as 3.8 Flash and 2.5 Flash as 3.5 Flash-Lite.
|
|
1047
|
+
"gemini-2.5-pro": {
|
|
1048
|
+
until: "2026-11-30",
|
|
1049
|
+
price: { textIn: 1.25, out: 10 },
|
|
1050
|
+
then: { textIn: 1.5, out: 7.5 }
|
|
1051
|
+
},
|
|
1052
|
+
"gemini-2.5-flash": {
|
|
1053
|
+
until: "2026-11-30",
|
|
1054
|
+
price: { textIn: 0.3, audioIn: 1, out: 2.5 },
|
|
1055
|
+
then: { textIn: 0.3, out: 2.5 }
|
|
1056
|
+
},
|
|
890
1057
|
"gemini-2.5-flash-lite": { textIn: 0.1, audioIn: 0.3, out: 0.4 },
|
|
891
|
-
// Moving aliases
|
|
1058
|
+
// Moving aliases. Google hasn't documented their targets since January 2026; these are
|
|
1059
|
+
// the last documented targets' prices, so treat them as estimates.
|
|
892
1060
|
"gemini-pro-latest": { textIn: 2, out: 12 },
|
|
893
1061
|
"gemini-flash-latest": { textIn: 1.5, out: 9 },
|
|
894
1062
|
"gemini-flash-lite-latest": { textIn: 0.25, audioIn: 0.5, out: 1.5 },
|
|
@@ -907,17 +1075,27 @@ var ASR_HOURLY = {
|
|
|
907
1075
|
// whisper-large-v3-turbo
|
|
908
1076
|
none: 0
|
|
909
1077
|
};
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
1078
|
+
function audioTokensPerSec(model) {
|
|
1079
|
+
return model.startsWith("gemini-4") ? 32 : 25;
|
|
1080
|
+
}
|
|
1081
|
+
function priceFor(model, at = /* @__PURE__ */ new Date()) {
|
|
1082
|
+
const key = model in MODEL_PRICES ? model : Object.keys(MODEL_PRICES).filter((k) => model.startsWith(k)).sort((a, b) => b.length - a.length)[0];
|
|
1083
|
+
if (!key) return null;
|
|
1084
|
+
const p = MODEL_PRICES[key];
|
|
1085
|
+
if (!("until" in p)) return p;
|
|
1086
|
+
return at.toISOString().slice(0, 10) <= p.until ? p.price : p.then;
|
|
915
1087
|
}
|
|
916
1088
|
function asrCost(provider, durationSec) {
|
|
917
1089
|
const hourly = ASR_HOURLY[provider];
|
|
918
1090
|
if (hourly === void 0) return null;
|
|
919
1091
|
return durationSec / 3600 * hourly;
|
|
920
1092
|
}
|
|
1093
|
+
var OUTPUT_TOK_PER_AUDIO_MIN = 700;
|
|
1094
|
+
function thinkingOverhead(model) {
|
|
1095
|
+
if (model.startsWith("gemini-4-hydrogen")) return 0.5;
|
|
1096
|
+
if (model.includes("pro")) return 0.15;
|
|
1097
|
+
return 0;
|
|
1098
|
+
}
|
|
921
1099
|
function estimateRunCost(opts) {
|
|
922
1100
|
const lines = [];
|
|
923
1101
|
let total = 0;
|
|
@@ -929,9 +1107,9 @@ function estimateRunCost(opts) {
|
|
|
929
1107
|
);
|
|
930
1108
|
const billedAudioSec = opts.durationSec + Math.max(0, chunks - 1) * opts.overlapSec + Math.min(370, opts.durationSec);
|
|
931
1109
|
if (p) {
|
|
932
|
-
const audioTok = billedAudioSec *
|
|
1110
|
+
const audioTok = billedAudioSec * audioTokensPerSec(opts.model);
|
|
933
1111
|
const promptTok = chunks * 1500;
|
|
934
|
-
const outTok = opts.durationSec / 60 *
|
|
1112
|
+
const outTok = opts.durationSec / 60 * OUTPUT_TOK_PER_AUDIO_MIN * (1 + thinkingOverhead(opts.model)) + 1500;
|
|
935
1113
|
const inRate = p.audioIn ?? p.textIn;
|
|
936
1114
|
const llmUsd = (audioTok * inRate + promptTok * p.textIn + outTok * p.out) / 1e6;
|
|
937
1115
|
total += llmUsd;
|
|
@@ -959,7 +1137,7 @@ function estimateRunCost(opts) {
|
|
|
959
1137
|
}
|
|
960
1138
|
return { totalUsd: total, lines, incomplete };
|
|
961
1139
|
}
|
|
962
|
-
function computeReceipt(usage, tsProvider, durationSec) {
|
|
1140
|
+
function computeReceipt(usage, tsProvider, durationSec, asrBilled = true) {
|
|
963
1141
|
let llmUsd = 0;
|
|
964
1142
|
let incomplete = false;
|
|
965
1143
|
const lines = [];
|
|
@@ -992,11 +1170,11 @@ function computeReceipt(usage, tsProvider, durationSec) {
|
|
|
992
1170
|
`${model}: ${m.calls} call${m.calls > 1 ? "s" : ""} \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 $${usd.toFixed(2)}`
|
|
993
1171
|
);
|
|
994
1172
|
}
|
|
995
|
-
const asrUsd = tsProvider === "none" ? 0 : asrCost(tsProvider, durationSec);
|
|
1173
|
+
const asrUsd = tsProvider === "none" || !asrBilled ? 0 : asrCost(tsProvider, durationSec);
|
|
996
1174
|
if (asrUsd !== null && tsProvider !== "none") {
|
|
997
1175
|
perModel[tsProvider] = asrUsd;
|
|
998
1176
|
lines.push(
|
|
999
|
-
`${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7
|
|
1177
|
+
`${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7 ${asrBilled ? `$${asrUsd.toFixed(2)}` : "cached \xB7 $0.00"}`
|
|
1000
1178
|
);
|
|
1001
1179
|
}
|
|
1002
1180
|
return {
|
|
@@ -1025,9 +1203,9 @@ import {
|
|
|
1025
1203
|
writeFileSync
|
|
1026
1204
|
} from "fs";
|
|
1027
1205
|
import { homedir } from "os";
|
|
1028
|
-
import { join } from "path";
|
|
1206
|
+
import { join as join2 } from "path";
|
|
1029
1207
|
function statsDir() {
|
|
1030
|
-
return process.env.OFFMUTE_HOME ||
|
|
1208
|
+
return process.env.OFFMUTE_HOME || join2(homedir(), ".offmute");
|
|
1031
1209
|
}
|
|
1032
1210
|
function statsEnabled() {
|
|
1033
1211
|
return !process.env.OFFMUTE_NO_STATS;
|
|
@@ -1045,7 +1223,7 @@ var EMPTY = {
|
|
|
1045
1223
|
};
|
|
1046
1224
|
function readStats() {
|
|
1047
1225
|
try {
|
|
1048
|
-
const p =
|
|
1226
|
+
const p = join2(statsDir(), "stats.json");
|
|
1049
1227
|
if (!existsSync2(p)) return { ...EMPTY };
|
|
1050
1228
|
return { ...EMPTY, ...JSON.parse(readFileSync(p, "utf-8")) };
|
|
1051
1229
|
} catch {
|
|
@@ -1053,7 +1231,7 @@ function readStats() {
|
|
|
1053
1231
|
}
|
|
1054
1232
|
}
|
|
1055
1233
|
function withStatsLock(dir, fn) {
|
|
1056
|
-
const lock =
|
|
1234
|
+
const lock = join2(dir, ".stats.lock");
|
|
1057
1235
|
const deadline = Date.now() + 2e3;
|
|
1058
1236
|
for (; ; ) {
|
|
1059
1237
|
try {
|
|
@@ -1080,7 +1258,7 @@ function recordRun(rec, perModelCost) {
|
|
|
1080
1258
|
try {
|
|
1081
1259
|
const dir = statsDir();
|
|
1082
1260
|
mkdirSync(dir, { recursive: true });
|
|
1083
|
-
appendFileSync2(
|
|
1261
|
+
appendFileSync2(join2(dir, "history.jsonl"), JSON.stringify(rec) + "\n");
|
|
1084
1262
|
withStatsLock(dir, () => {
|
|
1085
1263
|
foldIntoAggregates(rec, perModelCost, dir);
|
|
1086
1264
|
});
|
|
@@ -1103,7 +1281,7 @@ function foldIntoAggregates(rec, perModelCost, dir) {
|
|
|
1103
1281
|
if (tModel) s.runsByModel[tModel] = (s.runsByModel[tModel] ?? 0) + 1;
|
|
1104
1282
|
s.firstRun ??= rec.ts;
|
|
1105
1283
|
s.lastRun = rec.ts;
|
|
1106
|
-
writeFileSync(
|
|
1284
|
+
writeFileSync(join2(dir, "stats.json"), JSON.stringify(s, null, 2));
|
|
1107
1285
|
}
|
|
1108
1286
|
|
|
1109
1287
|
// src/transcribe/describe.ts
|
|
@@ -1137,11 +1315,22 @@ async function describeMeeting(client, model, files, fileName, instructions, aud
|
|
|
1137
1315
|
logKind: "describe"
|
|
1138
1316
|
}
|
|
1139
1317
|
);
|
|
1140
|
-
|
|
1318
|
+
return { ...parseDescription(res.text || ""), raw: res.text || "" };
|
|
1319
|
+
}
|
|
1320
|
+
function parseDescription(text) {
|
|
1141
1321
|
const parts = text.split(/\n---\n|\n\s*---\s*\n/);
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1322
|
+
return {
|
|
1323
|
+
description: dropHeading(parts[0] ?? "", "DESCRIPTION") || text.trim(),
|
|
1324
|
+
roster: dropHeading(parts.slice(1).join("\n---\n"), "ROSTER") || "(no explicit roster)"
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
function dropHeading(section, word) {
|
|
1328
|
+
const s = section.trim();
|
|
1329
|
+
const firstLine = s.split("\n", 1)[0] ?? "";
|
|
1330
|
+
if (new RegExp(`^[#*_\\s]*${word}[#*_:\\s]*$`, "i").test(firstLine)) {
|
|
1331
|
+
return s.slice(firstLine.length).trim();
|
|
1332
|
+
}
|
|
1333
|
+
return s.replace(new RegExp(`^[#*_\\s]*${word}[*_]*\\s*:[*_]*\\s*`, "i"), "");
|
|
1145
1334
|
}
|
|
1146
1335
|
|
|
1147
1336
|
// src/transcribe/prompts.ts
|
|
@@ -1234,13 +1423,6 @@ function transcriptionPrompt(ctx) {
|
|
|
1234
1423
|
"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
1424
|
);
|
|
1236
1425
|
}
|
|
1237
|
-
if (ctx.previousTail) {
|
|
1238
|
-
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
|
-
);
|
|
1242
|
-
parts.push(ctx.previousTail);
|
|
1243
|
-
}
|
|
1244
1426
|
if (ctx.instructions) {
|
|
1245
1427
|
parts.push("");
|
|
1246
1428
|
parts.push("ADDITIONAL INSTRUCTIONS:");
|
|
@@ -1303,6 +1485,51 @@ function formatDuration(seconds) {
|
|
|
1303
1485
|
return parts.join(" ");
|
|
1304
1486
|
}
|
|
1305
1487
|
|
|
1488
|
+
// src/transcribe/degeneration.ts
|
|
1489
|
+
var DEGENERATE_COMPRESSION_RATIO = 2.2;
|
|
1490
|
+
var WINDOW_CHARS = 400;
|
|
1491
|
+
var STEP_CHARS = 200;
|
|
1492
|
+
var MIN_MATCH = 4;
|
|
1493
|
+
var MAX_MATCH = 258;
|
|
1494
|
+
var REF_COST = 3;
|
|
1495
|
+
function ratio(s) {
|
|
1496
|
+
let cost = 0;
|
|
1497
|
+
for (let i = 0; i < s.length; ) {
|
|
1498
|
+
let best = 0;
|
|
1499
|
+
for (let j = Math.max(0, i - WINDOW_CHARS); j < i; j++) {
|
|
1500
|
+
let k = 0;
|
|
1501
|
+
while (i + k < s.length && k < MAX_MATCH && s[j + k] === s[i + k]) k++;
|
|
1502
|
+
if (k > best) best = k;
|
|
1503
|
+
}
|
|
1504
|
+
if (best >= MIN_MATCH) {
|
|
1505
|
+
cost += REF_COST;
|
|
1506
|
+
i += best;
|
|
1507
|
+
} else {
|
|
1508
|
+
cost += 1;
|
|
1509
|
+
i += 1;
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
return s.length / cost;
|
|
1513
|
+
}
|
|
1514
|
+
function maxCompressionRatio(text) {
|
|
1515
|
+
if (text.length < WINDOW_CHARS) return 0;
|
|
1516
|
+
let max = 0;
|
|
1517
|
+
for (let i = 0; i + WINDOW_CHARS <= text.length; i += STEP_CHARS) {
|
|
1518
|
+
max = Math.max(max, ratio(text.slice(i, i + WINDOW_CHARS)));
|
|
1519
|
+
}
|
|
1520
|
+
return Math.max(max, ratio(text.slice(-WINDOW_CHARS)));
|
|
1521
|
+
}
|
|
1522
|
+
function tailIsDegenerate(text) {
|
|
1523
|
+
if (text.length < 2 * WINDOW_CHARS) return false;
|
|
1524
|
+
return ratio(text.slice(-WINDOW_CHARS)) > DEGENERATE_COMPRESSION_RATIO && ratio(text.slice(-2 * WINDOW_CHARS, -WINDOW_CHARS)) > DEGENERATE_COMPRESSION_RATIO;
|
|
1525
|
+
}
|
|
1526
|
+
function transcriptTextOf(partialJson) {
|
|
1527
|
+
const out = [];
|
|
1528
|
+
for (const m of partialJson.matchAll(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/g))
|
|
1529
|
+
out.push(m[1]);
|
|
1530
|
+
return out.join(" ");
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1306
1533
|
// src/transcribe/llm-transcribe.ts
|
|
1307
1534
|
var MIN_SEGMENTS = 3;
|
|
1308
1535
|
var MIN_SPAN_RATIO = 0.6;
|
|
@@ -1343,6 +1570,16 @@ function parseLlmSegments(data, chunkOffsetSec) {
|
|
|
1343
1570
|
return { segments: out, dropped };
|
|
1344
1571
|
}
|
|
1345
1572
|
function validate(segments, chunkDuration) {
|
|
1573
|
+
const compression = maxCompressionRatio(segments.map((s) => s.text).join(" "));
|
|
1574
|
+
if (compression > DEGENERATE_COMPRESSION_RATIO) {
|
|
1575
|
+
return {
|
|
1576
|
+
isValid: false,
|
|
1577
|
+
degenerate: true,
|
|
1578
|
+
spanSec: segments.length ? segments[segments.length - 1].endSec - segments[0].startSec : 0,
|
|
1579
|
+
segmentCount: segments.length,
|
|
1580
|
+
message: `degenerate repetition (compression ratio ${compression.toFixed(1)} > ${DEGENERATE_COMPRESSION_RATIO})`
|
|
1581
|
+
};
|
|
1582
|
+
}
|
|
1346
1583
|
if (segments.length < MIN_SEGMENTS) {
|
|
1347
1584
|
return {
|
|
1348
1585
|
isValid: false,
|
|
@@ -1373,72 +1610,135 @@ function validate(segments, chunkDuration) {
|
|
|
1373
1610
|
async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts) {
|
|
1374
1611
|
const validationRetries = opts.validationRetries ?? 1;
|
|
1375
1612
|
const prompt = transcriptionPrompt(ctx);
|
|
1376
|
-
let
|
|
1613
|
+
let temperature = opts.temperature ?? 0.2;
|
|
1614
|
+
let loopAborted = false;
|
|
1615
|
+
let checkedAt = 0;
|
|
1616
|
+
const shouldAbort = (raw) => {
|
|
1617
|
+
if (raw.length - checkedAt < 800) return null;
|
|
1618
|
+
checkedAt = raw.length;
|
|
1619
|
+
if (!tailIsDegenerate(transcriptTextOf(raw))) return null;
|
|
1620
|
+
loopAborted = true;
|
|
1621
|
+
return "degenerate repetition";
|
|
1622
|
+
};
|
|
1623
|
+
let best;
|
|
1624
|
+
const rank = (r) => r.validation.isValid ? 3 : r.error ? 0 : r.validation.degenerate ? 1 : 2;
|
|
1625
|
+
const keep = (r) => {
|
|
1626
|
+
if (!best || rank(r) > rank(best) || rank(r) === rank(best) && r.validation.spanSec > best.validation.spanSec)
|
|
1627
|
+
best = r;
|
|
1628
|
+
};
|
|
1377
1629
|
for (let attempt = 0; attempt <= validationRetries; attempt++) {
|
|
1630
|
+
loopAborted = false;
|
|
1631
|
+
checkedAt = 0;
|
|
1378
1632
|
const gen = await client.generateJson(
|
|
1379
1633
|
model,
|
|
1380
1634
|
prompt,
|
|
1381
1635
|
[{ path: chunkPath }],
|
|
1382
1636
|
TRANSCRIPT_SCHEMA,
|
|
1383
1637
|
{
|
|
1384
|
-
temperature
|
|
1638
|
+
temperature,
|
|
1385
1639
|
maxRetries: 3,
|
|
1386
1640
|
logKind: "transcribe",
|
|
1387
|
-
logChunk: ctx.index - 1
|
|
1641
|
+
logChunk: ctx.index - 1,
|
|
1642
|
+
shouldAbort
|
|
1388
1643
|
}
|
|
1389
1644
|
);
|
|
1390
1645
|
if (gen.error || !gen.data) {
|
|
1391
|
-
|
|
1646
|
+
keep({
|
|
1392
1647
|
segments: [],
|
|
1393
1648
|
raw: gen.raw,
|
|
1394
1649
|
usage: gen.usage,
|
|
1395
1650
|
validation: {
|
|
1396
1651
|
isValid: false,
|
|
1652
|
+
degenerate: loopAborted,
|
|
1397
1653
|
spanSec: 0,
|
|
1398
1654
|
segmentCount: 0,
|
|
1399
1655
|
message: gen.error || "no data"
|
|
1400
1656
|
},
|
|
1401
1657
|
error: gen.error
|
|
1402
|
-
};
|
|
1658
|
+
});
|
|
1403
1659
|
logger.warn(
|
|
1404
1660
|
`[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`
|
|
1405
1661
|
);
|
|
1662
|
+
if (loopAborted) temperature = Math.min(1, temperature + 0.3);
|
|
1406
1663
|
continue;
|
|
1407
1664
|
}
|
|
1408
1665
|
const { segments, dropped } = parseLlmSegments(gen.data, chunkStartSec);
|
|
1409
1666
|
const v = validate(segments, opts.chunkDurationSec);
|
|
1410
|
-
|
|
1667
|
+
const result = { segments, raw: gen.raw, usage: gen.usage, validation: v };
|
|
1668
|
+
keep(result);
|
|
1411
1669
|
if (v.isValid) {
|
|
1412
1670
|
logger.info(
|
|
1413
1671
|
`[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`
|
|
1414
1672
|
);
|
|
1415
|
-
return
|
|
1673
|
+
return result;
|
|
1416
1674
|
}
|
|
1417
1675
|
logger.warn(
|
|
1418
1676
|
`[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`
|
|
1419
1677
|
);
|
|
1678
|
+
if (v.degenerate) temperature = Math.min(1, temperature + 0.3);
|
|
1420
1679
|
}
|
|
1421
1680
|
logger.error(
|
|
1422
1681
|
`[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`
|
|
1423
1682
|
);
|
|
1424
|
-
return
|
|
1683
|
+
return best;
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
// src/transcribe/grounding.ts
|
|
1687
|
+
var MIN_GROUNDED_PRECISION = 0.3;
|
|
1688
|
+
var MIN_TOKENS = 30;
|
|
1689
|
+
var MAX_SCRIPT_SHARE_GAP = 0.2;
|
|
1690
|
+
var STOP_WORDS = Object.fromEntries(
|
|
1691
|
+
"the a an and or but so to of in on at for with is it's it i you we they he she that this be are was were do don't not yeah yes okay ok like uh um mm hmm mhm oh just i'm you're that's".split(" ").map((w) => [w, true])
|
|
1692
|
+
);
|
|
1693
|
+
var NON_LATIN = /[^\u0000-\u024F\u2000-\u206F]/u;
|
|
1694
|
+
function contentTokens(words) {
|
|
1695
|
+
const bag = /* @__PURE__ */ new Map();
|
|
1696
|
+
for (const w of words) {
|
|
1697
|
+
const t = w.toLowerCase().replace(/^[^\p{L}\p{N}']+|[^\p{L}\p{N}']+$/gu, "").replace(/^'+|'+$/g, "");
|
|
1698
|
+
if (t && !STOP_WORDS[t]) bag.set(t, (bag.get(t) ?? 0) + 1);
|
|
1699
|
+
}
|
|
1700
|
+
return bag;
|
|
1701
|
+
}
|
|
1702
|
+
function chunkGrounding(segments, asrWords, start, end) {
|
|
1703
|
+
const asrInRange = asrWords.filter((w) => w.start >= start && w.start < end);
|
|
1704
|
+
const llmWords = segments.map((s) => s.text.replace(/\[[^\]]*\]/g, " ")).join(" ").split(/\s+/).filter(Boolean);
|
|
1705
|
+
const llm = contentTokens(llmWords);
|
|
1706
|
+
const asr = contentTokens(asrInRange.map((w) => w.text));
|
|
1707
|
+
let llmTokens = 0;
|
|
1708
|
+
let asrTokens = 0;
|
|
1709
|
+
let shared = 0;
|
|
1710
|
+
for (const n of llm.values()) llmTokens += n;
|
|
1711
|
+
for (const n of asr.values()) asrTokens += n;
|
|
1712
|
+
for (const [t, n] of llm) shared += Math.min(n, asr.get(t) ?? 0);
|
|
1713
|
+
const share = (ws) => ws.length ? ws.filter((w) => NON_LATIN.test(w)).length / ws.length : 0;
|
|
1714
|
+
const scriptsMatch = Math.abs(share(llmWords) - share(asrInRange.map((w) => w.text))) <= MAX_SCRIPT_SHARE_GAP;
|
|
1715
|
+
const judged = llmTokens >= MIN_TOKENS && asrTokens >= MIN_TOKENS && scriptsMatch;
|
|
1716
|
+
const precision = llmTokens ? shared / llmTokens : 1;
|
|
1717
|
+
return {
|
|
1718
|
+
llmTokens,
|
|
1719
|
+
asrTokens,
|
|
1720
|
+
precision,
|
|
1721
|
+
judged,
|
|
1722
|
+
grounded: !judged || precision >= MIN_GROUNDED_PRECISION
|
|
1723
|
+
};
|
|
1425
1724
|
}
|
|
1426
1725
|
|
|
1427
1726
|
// src/align/normalize.ts
|
|
1428
|
-
function
|
|
1429
|
-
return word.toLowerCase().replace(
|
|
1727
|
+
function normalizeWord(word) {
|
|
1728
|
+
return word.normalize("NFKC").toLowerCase().replace(/[’‘`]/g, "'").replace(/^[^\p{L}\p{M}\p{N}']+|[^\p{L}\p{M}\p{N}']+$/gu, "").replace(/^'+|'+$/g, "");
|
|
1430
1729
|
}
|
|
1431
1730
|
function tokenize(text) {
|
|
1432
1731
|
const out = [];
|
|
1433
1732
|
for (const raw of text.split(/\s+/)) {
|
|
1434
1733
|
if (!raw) continue;
|
|
1435
|
-
const norm2 =
|
|
1734
|
+
const norm2 = normalizeWord(raw);
|
|
1436
1735
|
if (norm2) out.push({ original: raw, norm: norm2 });
|
|
1437
1736
|
}
|
|
1438
1737
|
return out;
|
|
1439
1738
|
}
|
|
1440
1739
|
function fuzzyEqual(a, b) {
|
|
1441
1740
|
if (a === b) return true;
|
|
1741
|
+
if (!a || !b) return false;
|
|
1442
1742
|
if (Math.abs(a.length - b.length) <= 1) {
|
|
1443
1743
|
return editDistanceChars(a, b, 1) <= 1;
|
|
1444
1744
|
}
|
|
@@ -1464,9 +1764,85 @@ function editDistanceChars(a, b, max) {
|
|
|
1464
1764
|
return prev[n];
|
|
1465
1765
|
}
|
|
1466
1766
|
|
|
1767
|
+
// src/transcribe/coverage.ts
|
|
1768
|
+
var MIN_COVERAGE_RATIO = 0.6;
|
|
1769
|
+
var MIN_ASR_WORDS = 200;
|
|
1770
|
+
function chunkCoverage(segments, asrWords, start, end) {
|
|
1771
|
+
const llmWords = segments.reduce(
|
|
1772
|
+
(n, s) => n + tokenize(s.text.replace(/\[[^\]]*\]/g, " ")).length,
|
|
1773
|
+
0
|
|
1774
|
+
);
|
|
1775
|
+
const asrCount = asrWords.reduce(
|
|
1776
|
+
(n, w) => n + (w.start >= start && w.start < end ? tokenize(w.text).length : 0),
|
|
1777
|
+
0
|
|
1778
|
+
);
|
|
1779
|
+
const ratio2 = asrCount ? llmWords / asrCount : Infinity;
|
|
1780
|
+
const judged = asrCount >= MIN_ASR_WORDS;
|
|
1781
|
+
return {
|
|
1782
|
+
llmWords,
|
|
1783
|
+
asrWords: asrCount,
|
|
1784
|
+
ratio: ratio2,
|
|
1785
|
+
judged,
|
|
1786
|
+
low: judged && ratio2 < MIN_COVERAGE_RATIO
|
|
1787
|
+
};
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
// src/core/retranscribe.ts
|
|
1791
|
+
import { existsSync as existsSync3 } from "fs";
|
|
1792
|
+
var HALF_OVERLAP_SEC = 5;
|
|
1793
|
+
async function transcribeInHalves(opts) {
|
|
1794
|
+
const { chunk } = opts;
|
|
1795
|
+
const mid = (chunk.start + chunk.end) / 2;
|
|
1796
|
+
const halves = [
|
|
1797
|
+
{ name: "a", from: chunk.start, to: Math.min(chunk.end, mid + HALF_OVERLAP_SEC) },
|
|
1798
|
+
{ name: "b", from: Math.max(chunk.start, mid - HALF_OVERLAP_SEC), to: chunk.end }
|
|
1799
|
+
];
|
|
1800
|
+
const results = [];
|
|
1801
|
+
for (const h of halves) {
|
|
1802
|
+
const path = `${opts.pathPrefix}_half_${h.name}.mp3`;
|
|
1803
|
+
if (!existsSync3(path))
|
|
1804
|
+
await extractChunk(opts.audioPath, path, h.from, h.to, opts.audioOpts);
|
|
1805
|
+
results.push(
|
|
1806
|
+
await transcribeChunk(opts.client, opts.model, path, h.from, opts.ctx, {
|
|
1807
|
+
chunkDurationSec: h.to - h.from,
|
|
1808
|
+
validationRetries: 0
|
|
1809
|
+
})
|
|
1810
|
+
);
|
|
1811
|
+
}
|
|
1812
|
+
const [a, b] = results;
|
|
1813
|
+
const center = (s) => (s.startSec + s.endSec) / 2;
|
|
1814
|
+
const segments = [
|
|
1815
|
+
...a.segments.filter((s) => center(s) < mid),
|
|
1816
|
+
...b.segments.filter((s) => center(s) >= mid)
|
|
1817
|
+
];
|
|
1818
|
+
const first = segments[0];
|
|
1819
|
+
const last = segments[segments.length - 1];
|
|
1820
|
+
return {
|
|
1821
|
+
segments,
|
|
1822
|
+
raw: JSON.stringify({ halves: [a.raw, b.raw] }),
|
|
1823
|
+
usage: {
|
|
1824
|
+
inputTokens: a.usage.inputTokens + b.usage.inputTokens,
|
|
1825
|
+
outputTokens: a.usage.outputTokens + b.usage.outputTokens,
|
|
1826
|
+
thoughtTokens: (a.usage.thoughtTokens ?? 0) + (b.usage.thoughtTokens ?? 0),
|
|
1827
|
+
totalTokens: a.usage.totalTokens + b.usage.totalTokens
|
|
1828
|
+
},
|
|
1829
|
+
validation: {
|
|
1830
|
+
isValid: a.validation.isValid && b.validation.isValid,
|
|
1831
|
+
degenerate: Boolean(a.validation.degenerate || b.validation.degenerate),
|
|
1832
|
+
spanSec: first && last ? last.endSec - first.startSec : 0,
|
|
1833
|
+
segmentCount: segments.length,
|
|
1834
|
+
message: `halves: ${a.validation.message} | ${b.validation.message}`
|
|
1835
|
+
},
|
|
1836
|
+
...a.error || b.error ? { error: [a.error, b.error].filter(Boolean).join(" | ") } : {}
|
|
1837
|
+
};
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1467
1840
|
// src/align/edit-distance.ts
|
|
1468
1841
|
var INDEL = 2;
|
|
1842
|
+
var OUT_OF_WINDOW = { cost: 2 * INDEL + 1, fuzzy: false };
|
|
1469
1843
|
function matchCost(a, b) {
|
|
1844
|
+
if (a.window && b.start !== void 0 && (b.start < a.window.lo || b.start > a.window.hi))
|
|
1845
|
+
return OUT_OF_WINDOW;
|
|
1470
1846
|
if (a.norm === b.norm) return { cost: 0, fuzzy: false };
|
|
1471
1847
|
if (fuzzyEqual(a.norm, b.norm)) return { cost: 1, fuzzy: true };
|
|
1472
1848
|
return { cost: 2, fuzzy: false };
|
|
@@ -1544,12 +1920,19 @@ function alignWords(llm, asr) {
|
|
|
1544
1920
|
}
|
|
1545
1921
|
|
|
1546
1922
|
// src/align/aligner.ts
|
|
1923
|
+
var WINDOW_SLACK_SEC = 2;
|
|
1924
|
+
var UNANCHORED_MAX_DRIFT_SEC = 15;
|
|
1925
|
+
var STRETCH_MIN_SEC = 30;
|
|
1926
|
+
var STRETCH_SEC_PER_WORD = 3;
|
|
1927
|
+
var MAX_INNER_GAP_SEC = 8;
|
|
1928
|
+
var SPOKEN_SEC_PER_WORD = 0.5;
|
|
1929
|
+
var UNCONFIRMED_MAX_SEC = 5;
|
|
1547
1930
|
function toAsrTokens(words) {
|
|
1548
1931
|
return words.map((w) => ({
|
|
1549
1932
|
text: w.text,
|
|
1550
1933
|
start: w.start,
|
|
1551
1934
|
end: w.end,
|
|
1552
|
-
norm: w.text
|
|
1935
|
+
norm: normalizeWord(w.text)
|
|
1553
1936
|
}));
|
|
1554
1937
|
}
|
|
1555
1938
|
function transferTiming(llm, asr, ops) {
|
|
@@ -1608,7 +1991,9 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
|
|
|
1608
1991
|
for (const { s, i } of sorted) {
|
|
1609
1992
|
const toks = tokenize(s.text);
|
|
1610
1993
|
const start = flat.length;
|
|
1611
|
-
|
|
1994
|
+
const window = s.chunkStart !== void 0 && s.chunkEnd !== void 0 ? { lo: s.chunkStart - WINDOW_SLACK_SEC, hi: s.chunkEnd + WINDOW_SLACK_SEC } : void 0;
|
|
1995
|
+
for (const t of toks)
|
|
1996
|
+
flat.push({ original: t.original, norm: t.norm, segIdx: i, window });
|
|
1612
1997
|
segRanges.push({ src: i, start, end: flat.length });
|
|
1613
1998
|
}
|
|
1614
1999
|
if (flat.length === 0 || asrWords.length === 0) {
|
|
@@ -1653,21 +2038,53 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
|
|
|
1653
2038
|
let end;
|
|
1654
2039
|
let timingSource;
|
|
1655
2040
|
const confidence = tokenCount ? exact / tokenCount : 0;
|
|
1656
|
-
|
|
2041
|
+
const unanchoredDrift = segOps.length === 0 && firstTimed ? Math.abs(firstTimed.start - s.startSec) : 0;
|
|
2042
|
+
if (firstTimed && lastTimed && unanchoredDrift <= UNANCHORED_MAX_DRIFT_SEC) {
|
|
1657
2043
|
start = firstTimed.start;
|
|
1658
2044
|
end = lastTimed.end;
|
|
1659
2045
|
timingSource = confidence >= confThreshold ? "aligned" : "interpolated";
|
|
2046
|
+
if (end - start > Math.max(STRETCH_MIN_SEC, STRETCH_SEC_PER_WORD * tokenCount)) {
|
|
2047
|
+
const runs = [];
|
|
2048
|
+
for (const t of segTimes) {
|
|
2049
|
+
if (isNaN(t.start)) continue;
|
|
2050
|
+
const run2 = runs[runs.length - 1];
|
|
2051
|
+
if (run2 && t.start - run2.end <= MAX_INNER_GAP_SEC) {
|
|
2052
|
+
run2.end = Math.max(run2.end, t.end);
|
|
2053
|
+
if (t.matched) run2.matched++;
|
|
2054
|
+
} else {
|
|
2055
|
+
runs.push({ start: t.start, end: t.end, matched: t.matched ? 1 : 0 });
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
const best = runs.reduce(
|
|
2059
|
+
(a, b) => b.matched > a.matched || b.matched === a.matched && Math.abs(b.start - s.startSec) < Math.abs(a.start - s.startSec) ? b : a
|
|
2060
|
+
);
|
|
2061
|
+
start = best.start;
|
|
2062
|
+
end = best.end;
|
|
2063
|
+
}
|
|
2064
|
+
const spoken = Math.max(1, SPOKEN_SEC_PER_WORD * tokenCount);
|
|
2065
|
+
if (exact === 0 && end - start > Math.max(UNCONFIRMED_MAX_SEC, 3 * spoken)) {
|
|
2066
|
+
end = start + spoken;
|
|
2067
|
+
}
|
|
1660
2068
|
} else {
|
|
1661
2069
|
start = s.startSec;
|
|
1662
2070
|
end = s.endSec;
|
|
1663
2071
|
timingSource = "coarse";
|
|
1664
2072
|
}
|
|
1665
|
-
const
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
2073
|
+
const step = timingSource === "coarse" && tokenCount ? (end - start) / tokenCount : 0;
|
|
2074
|
+
const inside = (x) => Math.min(Math.max(x, start), end);
|
|
2075
|
+
const words = segTimes.map(
|
|
2076
|
+
(t, idx) => timingSource === "coarse" ? {
|
|
2077
|
+
text: flat[range.start + idx].original,
|
|
2078
|
+
start: start + step * idx,
|
|
2079
|
+
end: start + step * (idx + 1),
|
|
2080
|
+
matched: false
|
|
2081
|
+
} : {
|
|
2082
|
+
text: flat[range.start + idx].original,
|
|
2083
|
+
start: isNaN(t.start) ? start : inside(t.start),
|
|
2084
|
+
end: isNaN(t.end) ? end : inside(t.end),
|
|
2085
|
+
matched: t.matched
|
|
2086
|
+
}
|
|
2087
|
+
);
|
|
1671
2088
|
out.push({
|
|
1672
2089
|
speaker: s.speaker,
|
|
1673
2090
|
start,
|
|
@@ -1682,23 +2099,90 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
|
|
|
1682
2099
|
}
|
|
1683
2100
|
return out;
|
|
1684
2101
|
}
|
|
2102
|
+
var CLOCK_ANCHOR_MIN_WORDS = 3;
|
|
2103
|
+
var CLOCK_ANCHOR_MIN_SHARE = 0.6;
|
|
2104
|
+
function toAsrClock(segments, asrWords) {
|
|
2105
|
+
if (!asrWords.length) return segments;
|
|
2106
|
+
const chunks = /* @__PURE__ */ new Map();
|
|
2107
|
+
for (const s of segments) {
|
|
2108
|
+
if (s.chunkIndex === void 0) continue;
|
|
2109
|
+
const group = chunks.get(s.chunkIndex);
|
|
2110
|
+
if (group) group.push(s);
|
|
2111
|
+
else chunks.set(s.chunkIndex, [s]);
|
|
2112
|
+
}
|
|
2113
|
+
const moved = /* @__PURE__ */ new Map();
|
|
2114
|
+
for (const group of chunks.values()) {
|
|
2115
|
+
const lo = Math.min(...group.map((s) => s.chunkStart ?? s.startSec)) - WINDOW_SLACK_SEC;
|
|
2116
|
+
const hi = Math.max(...group.map((s) => s.chunkEnd ?? s.endSec)) + WINDOW_SLACK_SEC;
|
|
2117
|
+
const aligned = alignSegments(
|
|
2118
|
+
group,
|
|
2119
|
+
asrWords.filter((w) => w.end >= lo && w.start <= hi)
|
|
2120
|
+
);
|
|
2121
|
+
const shifts = aligned.map(
|
|
2122
|
+
(a) => a.confidence >= CLOCK_ANCHOR_MIN_SHARE && a.words.filter((w) => w.matched).length >= CLOCK_ANCHOR_MIN_WORDS ? a.start - group[a.sourceIndex].startSec : void 0
|
|
2123
|
+
);
|
|
2124
|
+
for (let k = 0; k < aligned.length; k++) {
|
|
2125
|
+
let shift = shifts[k];
|
|
2126
|
+
for (let r = 1; shift === void 0 && r < aligned.length; r++) {
|
|
2127
|
+
shift = shifts[k - r] ?? shifts[k + r];
|
|
2128
|
+
}
|
|
2129
|
+
const s = group[aligned[k].sourceIndex];
|
|
2130
|
+
moved.set(s, {
|
|
2131
|
+
...s,
|
|
2132
|
+
startSec: s.startSec + (shift ?? 0),
|
|
2133
|
+
endSec: s.endSec + (shift ?? 0)
|
|
2134
|
+
});
|
|
2135
|
+
}
|
|
2136
|
+
}
|
|
2137
|
+
return segments.map((s) => moved.get(s) ?? s);
|
|
2138
|
+
}
|
|
1685
2139
|
|
|
1686
2140
|
// src/align/fill-gaps.ts
|
|
1687
2141
|
var MIN_GAP_SEC = 0.8;
|
|
1688
2142
|
var MIN_WORDS = 1;
|
|
1689
|
-
|
|
1690
|
-
|
|
2143
|
+
var HEAD_SLACK_WORDS = 5;
|
|
2144
|
+
function utteranceAt(utts, t) {
|
|
2145
|
+
let lo = 0;
|
|
2146
|
+
let hi = utts.length - 1;
|
|
2147
|
+
let found = -1;
|
|
2148
|
+
while (lo <= hi) {
|
|
2149
|
+
const mid = lo + hi >> 1;
|
|
2150
|
+
if (utts[mid].start <= t) {
|
|
2151
|
+
found = mid;
|
|
2152
|
+
lo = mid + 1;
|
|
2153
|
+
} else {
|
|
2154
|
+
hi = mid - 1;
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
return found >= 0 && t <= utts[found].end ? found : -1;
|
|
2158
|
+
}
|
|
2159
|
+
function dominantSpeaker(utts, start, end) {
|
|
2160
|
+
let best = utts[0]?.speaker || "speaker_?";
|
|
2161
|
+
let bestOv = 0;
|
|
2162
|
+
for (const u of utts) {
|
|
2163
|
+
const ov = Math.max(0, Math.min(end, u.end) - Math.max(start, u.start));
|
|
2164
|
+
if (ov > bestOv) {
|
|
2165
|
+
bestOv = ov;
|
|
2166
|
+
best = u.speaker;
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
return best;
|
|
1691
2170
|
}
|
|
1692
2171
|
function fillAsrGaps(segments, asrWords, asrUtterances) {
|
|
1693
2172
|
if (!asrWords.length) return segments;
|
|
1694
2173
|
const sorted = [...segments].sort((a, b) => a.start - b.start);
|
|
2174
|
+
const utts = [...asrUtterances].sort((a, b) => a.start - b.start);
|
|
1695
2175
|
const ranges = [];
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
2176
|
+
if (!sorted.length) {
|
|
2177
|
+
ranges.push([0, Infinity, void 0]);
|
|
2178
|
+
} else {
|
|
2179
|
+
if (sorted[0].start > 0) ranges.push([0, sorted[0].start, sorted[0]]);
|
|
2180
|
+
let coveredTo = sorted[0].end;
|
|
2181
|
+
for (const next of sorted.slice(1)) {
|
|
2182
|
+
if (next.start > coveredTo) ranges.push([coveredTo, next.start, next]);
|
|
2183
|
+
coveredTo = Math.max(coveredTo, next.end);
|
|
2184
|
+
}
|
|
2185
|
+
ranges.push([coveredTo, Infinity, void 0]);
|
|
1702
2186
|
}
|
|
1703
2187
|
const filled = [];
|
|
1704
2188
|
for (const [gs, ge, following] of ranges) {
|
|
@@ -1706,38 +2190,44 @@ function fillAsrGaps(segments, asrWords, asrUtterances) {
|
|
|
1706
2190
|
const words = asrWords.filter((w) => w.start >= gs && w.start < ge);
|
|
1707
2191
|
if (words.length < MIN_WORDS) continue;
|
|
1708
2192
|
if (following) {
|
|
1709
|
-
const
|
|
1710
|
-
const
|
|
1711
|
-
(
|
|
2193
|
+
const gapNorms = words.map((w) => normalizeWord(w.text)).filter(Boolean);
|
|
2194
|
+
const head = new Set(
|
|
2195
|
+
tokenize(following.text).slice(0, gapNorms.length + HEAD_SLACK_WORDS).map((t) => t.norm)
|
|
1712
2196
|
);
|
|
1713
|
-
const covered = gapNorms.filter((n) =>
|
|
1714
|
-
if (covered / gapNorms.
|
|
1715
|
-
}
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
const
|
|
1720
|
-
if (
|
|
1721
|
-
|
|
1722
|
-
|
|
2197
|
+
const covered = gapNorms.filter((n) => head.has(n)).length;
|
|
2198
|
+
if (covered / gapNorms.length >= 0.6) continue;
|
|
2199
|
+
}
|
|
2200
|
+
const runs = [];
|
|
2201
|
+
for (const w of words) {
|
|
2202
|
+
const u = utteranceAt(utts, w.start);
|
|
2203
|
+
const cur = runs[runs.length - 1];
|
|
2204
|
+
if (cur && (u === -1 || u === cur.utt || cur.utt === -1)) {
|
|
2205
|
+
cur.words.push(w);
|
|
2206
|
+
if (cur.utt === -1) cur.utt = u;
|
|
2207
|
+
} else {
|
|
2208
|
+
runs.push({ words: [w], utt: u });
|
|
1723
2209
|
}
|
|
1724
2210
|
}
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
2211
|
+
for (const run2 of runs) {
|
|
2212
|
+
const first = run2.words[0];
|
|
2213
|
+
const last = run2.words[run2.words.length - 1];
|
|
2214
|
+
filled.push({
|
|
2215
|
+
speaker: run2.utt >= 0 ? utts[run2.utt].speaker : dominantSpeaker(utts, first.start, last.end),
|
|
2216
|
+
start: first.start,
|
|
2217
|
+
end: last.end,
|
|
2218
|
+
text: run2.words.map((w) => w.text).join(" "),
|
|
2219
|
+
tone: [],
|
|
2220
|
+
confidence: 0,
|
|
2221
|
+
timingSource: "timestamped",
|
|
2222
|
+
words: run2.words.map((w) => ({
|
|
2223
|
+
text: w.text,
|
|
2224
|
+
start: w.start,
|
|
2225
|
+
end: w.end,
|
|
2226
|
+
matched: true
|
|
2227
|
+
})),
|
|
2228
|
+
sourceIndex: -1
|
|
2229
|
+
});
|
|
2230
|
+
}
|
|
1741
2231
|
}
|
|
1742
2232
|
if (!filled.length) return sorted;
|
|
1743
2233
|
return [...sorted, ...filled].sort((a, b) => a.start - b.start);
|
|
@@ -1989,150 +2479,31 @@ function splitMixedVoiceSegments(segments, utterances) {
|
|
|
1989
2479
|
return out.sort((a, b) => a.start - b.start);
|
|
1990
2480
|
}
|
|
1991
2481
|
|
|
1992
|
-
// src/
|
|
1993
|
-
var
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
}
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2482
|
+
// src/diarize/identify.ts
|
|
2483
|
+
var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
|
|
2484
|
+
function buildTranscriptExcerpt(segments, speakers) {
|
|
2485
|
+
const speakerHeader = (sp) => {
|
|
2486
|
+
const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
|
|
2487
|
+
return `${sp.id} (${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s talk time${voices})`;
|
|
2488
|
+
};
|
|
2489
|
+
const totalChars = segments.reduce((n, s) => n + s.text.length, 0);
|
|
2490
|
+
if (totalChars <= MAX_FULL_TRANSCRIPT_CHARS) {
|
|
2491
|
+
const parts2 = [
|
|
2492
|
+
"SPEAKERS:",
|
|
2493
|
+
...speakers.map((sp) => `- ${speakerHeader(sp)}`),
|
|
2494
|
+
"",
|
|
2495
|
+
"FULL TRANSCRIPT (in order):"
|
|
2496
|
+
];
|
|
2497
|
+
for (const s of segments) parts2.push(`[${s.speaker}] ${s.text}`);
|
|
2498
|
+
return parts2.join("\n");
|
|
2004
2499
|
}
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
}
|
|
2013
|
-
async chat(model, messages, opts = {}) {
|
|
2014
|
-
const m = model ?? this.defaultModel;
|
|
2015
|
-
const maxRetries = opts.maxRetries ?? 5;
|
|
2016
|
-
const body = {
|
|
2017
|
-
model: m,
|
|
2018
|
-
messages,
|
|
2019
|
-
temperature: opts.temperature ?? 0.2
|
|
2020
|
-
};
|
|
2021
|
-
if (opts.maxTokens) body.max_tokens = opts.maxTokens;
|
|
2022
|
-
if (opts.responseJson) {
|
|
2023
|
-
body.response_format = { type: "json_object" };
|
|
2024
|
-
}
|
|
2025
|
-
if (this.providerName === "gemini") {
|
|
2026
|
-
body.reasoning_effort = "low";
|
|
2027
|
-
}
|
|
2028
|
-
let lastError;
|
|
2029
|
-
const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
|
|
2030
|
-
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
2031
|
-
const t0 = Date.now();
|
|
2032
|
-
try {
|
|
2033
|
-
const res = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
2034
|
-
method: "POST",
|
|
2035
|
-
headers: {
|
|
2036
|
-
"Content-Type": "application/json",
|
|
2037
|
-
Authorization: `Bearer ${this.apiKey}`
|
|
2038
|
-
},
|
|
2039
|
-
body: JSON.stringify(body)
|
|
2040
|
-
});
|
|
2041
|
-
if (!res.ok) {
|
|
2042
|
-
const txt = await res.text();
|
|
2043
|
-
throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
|
|
2044
|
-
}
|
|
2045
|
-
const data = await res.json();
|
|
2046
|
-
const text = data.choices?.[0]?.message?.content ?? "";
|
|
2047
|
-
const usage = {
|
|
2048
|
-
inputTokens: data.usage?.prompt_tokens ?? 0,
|
|
2049
|
-
outputTokens: data.usage?.completion_tokens ?? 0
|
|
2050
|
-
};
|
|
2051
|
-
logLlmCall({
|
|
2052
|
-
ts: new Date(t0).toISOString(),
|
|
2053
|
-
provider: this.providerName,
|
|
2054
|
-
model: m,
|
|
2055
|
-
kind: opts.logKind,
|
|
2056
|
-
prompt: promptStr,
|
|
2057
|
-
response: text,
|
|
2058
|
-
usage,
|
|
2059
|
-
durationMs: Date.now() - t0,
|
|
2060
|
-
attempt: attempt + 1
|
|
2061
|
-
});
|
|
2062
|
-
return { text, usage };
|
|
2063
|
-
} catch (err) {
|
|
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
|
-
}
|
|
2073
|
-
logLlmCall({
|
|
2074
|
-
ts: new Date(t0).toISOString(),
|
|
2075
|
-
provider: this.providerName,
|
|
2076
|
-
model: m,
|
|
2077
|
-
kind: opts.logKind,
|
|
2078
|
-
prompt: promptStr,
|
|
2079
|
-
response: "",
|
|
2080
|
-
durationMs: Date.now() - t0,
|
|
2081
|
-
attempt: attempt + 1,
|
|
2082
|
-
error: lastError
|
|
2083
|
-
});
|
|
2084
|
-
if (attempt < maxRetries - 1)
|
|
2085
|
-
await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
|
|
2086
|
-
}
|
|
2087
|
-
}
|
|
2088
|
-
return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
|
|
2089
|
-
}
|
|
2090
|
-
async chatJson(model, messages, opts = {}) {
|
|
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
|
-
}
|
|
2106
|
-
}
|
|
2107
|
-
return { data: null, raw: lastRaw, error: lastError };
|
|
2108
|
-
}
|
|
2109
|
-
};
|
|
2110
|
-
|
|
2111
|
-
// src/diarize/identify.ts
|
|
2112
|
-
var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
|
|
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
|
-
}
|
|
2129
|
-
const bySpeaker = {};
|
|
2130
|
-
for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
|
|
2131
|
-
const parts = [];
|
|
2132
|
-
for (const sp of speakers) {
|
|
2133
|
-
const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
|
|
2134
|
-
parts.push(`### ${speakerHeader(sp)}`);
|
|
2135
|
-
for (const s of segs) parts.push(` ${s.text}`);
|
|
2500
|
+
const bySpeaker = {};
|
|
2501
|
+
for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
|
|
2502
|
+
const parts = [];
|
|
2503
|
+
for (const sp of speakers) {
|
|
2504
|
+
const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
|
|
2505
|
+
parts.push(`### ${speakerHeader(sp)}`);
|
|
2506
|
+
for (const s of segs) parts.push(` ${s.text}`);
|
|
2136
2507
|
}
|
|
2137
2508
|
return parts.join("\n");
|
|
2138
2509
|
}
|
|
@@ -2373,7 +2744,8 @@ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts
|
|
|
2373
2744
|
wantB ? runPass(reasonerB) : Promise.resolve(void 0)
|
|
2374
2745
|
]);
|
|
2375
2746
|
const passFailed = (r) => !!r && r.speakers.length === 0 && /fetch failed|HTTP \d|network|ENOTFOUND|JSON parse|no response/i.test(r.reasoning);
|
|
2376
|
-
|
|
2747
|
+
const allPassesFailed = passFailed(resA) && (!wantB || passFailed(resB));
|
|
2748
|
+
if (allPassesFailed) {
|
|
2377
2749
|
logger.warn(
|
|
2378
2750
|
`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
2751
|
);
|
|
@@ -2478,10 +2850,164 @@ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts
|
|
|
2478
2850
|
decisions,
|
|
2479
2851
|
tripwires,
|
|
2480
2852
|
passA: { ...resA, model: reasonerA.model },
|
|
2481
|
-
passB: resB ? { ...resB, model: reasonerB.model } : void 0
|
|
2853
|
+
passB: resB ? { ...resB, model: reasonerB.model } : void 0,
|
|
2854
|
+
allPassesFailed
|
|
2482
2855
|
};
|
|
2483
2856
|
}
|
|
2484
2857
|
|
|
2858
|
+
// src/providers/openai-compat.ts
|
|
2859
|
+
async function chatJsonWith(client, model, messages, opts) {
|
|
2860
|
+
let lastRaw = "";
|
|
2861
|
+
let lastError;
|
|
2862
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
2863
|
+
const res = await client.chat(model, messages, { ...opts, responseJson: true });
|
|
2864
|
+
lastRaw = res.text;
|
|
2865
|
+
lastError = res.error;
|
|
2866
|
+
if (res.error || !res.text) continue;
|
|
2867
|
+
try {
|
|
2868
|
+
let txt = res.text.trim();
|
|
2869
|
+
const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
|
|
2870
|
+
if (fence && fence[1]) txt = fence[1];
|
|
2871
|
+
return { data: JSON.parse(txt), raw: res.text };
|
|
2872
|
+
} catch (err) {
|
|
2873
|
+
lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
|
|
2874
|
+
}
|
|
2875
|
+
}
|
|
2876
|
+
return { data: null, raw: lastRaw, error: lastError };
|
|
2877
|
+
}
|
|
2878
|
+
var PROVIDER_BASE = {
|
|
2879
|
+
deepseek: "https://api.deepseek.com/v1",
|
|
2880
|
+
groq: "https://api.groq.com/openai/v1",
|
|
2881
|
+
openai: "https://api.openai.com/v1"
|
|
2882
|
+
};
|
|
2883
|
+
var OpenAICompatClient = class _OpenAICompatClient {
|
|
2884
|
+
constructor(baseUrl, apiKey, defaultModel, providerName = "openai-compat") {
|
|
2885
|
+
this.baseUrl = baseUrl;
|
|
2886
|
+
this.apiKey = apiKey;
|
|
2887
|
+
this.defaultModel = defaultModel;
|
|
2888
|
+
this.providerName = providerName;
|
|
2889
|
+
}
|
|
2890
|
+
baseUrl;
|
|
2891
|
+
apiKey;
|
|
2892
|
+
defaultModel;
|
|
2893
|
+
providerName;
|
|
2894
|
+
static fromProvider(provider, apiKey, defaultModel) {
|
|
2895
|
+
const base = PROVIDER_BASE[provider] ?? provider;
|
|
2896
|
+
return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
|
|
2897
|
+
}
|
|
2898
|
+
async chat(model, messages, opts = {}) {
|
|
2899
|
+
const m = model ?? this.defaultModel;
|
|
2900
|
+
const maxRetries = opts.maxRetries ?? 5;
|
|
2901
|
+
const body = {
|
|
2902
|
+
model: m,
|
|
2903
|
+
messages,
|
|
2904
|
+
temperature: opts.temperature ?? 0.2
|
|
2905
|
+
};
|
|
2906
|
+
if (opts.maxTokens) body.max_tokens = opts.maxTokens;
|
|
2907
|
+
if (opts.responseJson) {
|
|
2908
|
+
body.response_format = { type: "json_object" };
|
|
2909
|
+
}
|
|
2910
|
+
if (this.providerName === "gemini") {
|
|
2911
|
+
body.reasoning_effort = "low";
|
|
2912
|
+
}
|
|
2913
|
+
let lastError;
|
|
2914
|
+
const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
|
|
2915
|
+
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
2916
|
+
const t0 = Date.now();
|
|
2917
|
+
try {
|
|
2918
|
+
const res = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
2919
|
+
method: "POST",
|
|
2920
|
+
headers: {
|
|
2921
|
+
"Content-Type": "application/json",
|
|
2922
|
+
Authorization: `Bearer ${this.apiKey}`
|
|
2923
|
+
},
|
|
2924
|
+
body: JSON.stringify(body)
|
|
2925
|
+
});
|
|
2926
|
+
if (!res.ok) {
|
|
2927
|
+
const txt = await res.text();
|
|
2928
|
+
throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
|
|
2929
|
+
}
|
|
2930
|
+
const data = await res.json();
|
|
2931
|
+
const text = data.choices?.[0]?.message?.content ?? "";
|
|
2932
|
+
const usage = {
|
|
2933
|
+
inputTokens: data.usage?.prompt_tokens ?? 0,
|
|
2934
|
+
outputTokens: data.usage?.completion_tokens ?? 0
|
|
2935
|
+
};
|
|
2936
|
+
logLlmCall({
|
|
2937
|
+
ts: new Date(t0).toISOString(),
|
|
2938
|
+
provider: this.providerName,
|
|
2939
|
+
model: m,
|
|
2940
|
+
kind: opts.logKind,
|
|
2941
|
+
prompt: promptStr,
|
|
2942
|
+
response: text,
|
|
2943
|
+
usage,
|
|
2944
|
+
durationMs: Date.now() - t0,
|
|
2945
|
+
attempt: attempt + 1
|
|
2946
|
+
});
|
|
2947
|
+
return { text, usage };
|
|
2948
|
+
} catch (err) {
|
|
2949
|
+
lastError = err instanceof Error ? err.message : String(err);
|
|
2950
|
+
if (body.response_format && /response_format/i.test(lastError)) {
|
|
2951
|
+
delete body.response_format;
|
|
2952
|
+
continue;
|
|
2953
|
+
}
|
|
2954
|
+
if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
|
|
2955
|
+
delete body.reasoning_effort;
|
|
2956
|
+
continue;
|
|
2957
|
+
}
|
|
2958
|
+
logLlmCall({
|
|
2959
|
+
ts: new Date(t0).toISOString(),
|
|
2960
|
+
provider: this.providerName,
|
|
2961
|
+
model: m,
|
|
2962
|
+
kind: opts.logKind,
|
|
2963
|
+
prompt: promptStr,
|
|
2964
|
+
response: "",
|
|
2965
|
+
durationMs: Date.now() - t0,
|
|
2966
|
+
attempt: attempt + 1,
|
|
2967
|
+
error: lastError
|
|
2968
|
+
});
|
|
2969
|
+
if (attempt < maxRetries - 1)
|
|
2970
|
+
await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
|
|
2971
|
+
}
|
|
2972
|
+
}
|
|
2973
|
+
return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
|
|
2974
|
+
}
|
|
2975
|
+
chatJson(model, messages, opts = {}) {
|
|
2976
|
+
return chatJsonWith(this, model, messages, opts);
|
|
2977
|
+
}
|
|
2978
|
+
};
|
|
2979
|
+
|
|
2980
|
+
// src/providers/gemini-chat.ts
|
|
2981
|
+
var THINKING_HEADROOM_TOKENS = 4096;
|
|
2982
|
+
var GeminiChatClient = class {
|
|
2983
|
+
constructor(gemini, defaultModel) {
|
|
2984
|
+
this.gemini = gemini;
|
|
2985
|
+
this.defaultModel = defaultModel;
|
|
2986
|
+
}
|
|
2987
|
+
gemini;
|
|
2988
|
+
defaultModel;
|
|
2989
|
+
async chat(model, messages, opts = {}) {
|
|
2990
|
+
const system = messages.filter((m) => m.role === "system").map((m) => m.content);
|
|
2991
|
+
const prompt = messages.filter((m) => m.role !== "system").map((m) => m.content).join("\n\n");
|
|
2992
|
+
const r = await this.gemini.generate(model ?? this.defaultModel, prompt, [], {
|
|
2993
|
+
temperature: opts.temperature ?? 0.2,
|
|
2994
|
+
maxOutputTokens: opts.maxTokens ? opts.maxTokens + THINKING_HEADROOM_TOKENS : void 0,
|
|
2995
|
+
responseJson: opts.responseJson,
|
|
2996
|
+
systemInstruction: system.length ? system.join("\n\n") : void 0,
|
|
2997
|
+
maxRetries: opts.maxRetries ?? 5,
|
|
2998
|
+
logKind: opts.logKind
|
|
2999
|
+
});
|
|
3000
|
+
const usage = {
|
|
3001
|
+
inputTokens: r.usage.inputTokens,
|
|
3002
|
+
outputTokens: r.usage.outputTokens
|
|
3003
|
+
};
|
|
3004
|
+
return r.error ? { text: r.text, usage, error: r.error } : { text: r.text, usage };
|
|
3005
|
+
}
|
|
3006
|
+
chatJson(model, messages, opts = {}) {
|
|
3007
|
+
return chatJsonWith(this, model, messages, opts);
|
|
3008
|
+
}
|
|
3009
|
+
};
|
|
3010
|
+
|
|
2485
3011
|
// src/providers/reasoner.ts
|
|
2486
3012
|
var PROVIDERS = {
|
|
2487
3013
|
deepseek: { baseUrl: "https://api.deepseek.com/v1", keyName: "deepseek" },
|
|
@@ -2525,41 +3051,36 @@ function reasonerKey(info, keys) {
|
|
|
2525
3051
|
if (info.keyName === "gemini") return keys.gemini || keys.google;
|
|
2526
3052
|
return keys[info.keyName];
|
|
2527
3053
|
}
|
|
2528
|
-
function
|
|
3054
|
+
function clientFor(info, key, opts) {
|
|
3055
|
+
return info.provider === "gemini" ? new GeminiChatClient(
|
|
3056
|
+
new GeminiClient(key, { zeroStorage: opts.zeroStorage }),
|
|
3057
|
+
info.model
|
|
3058
|
+
) : new OpenAICompatClient(info.baseUrl, key, info.model, info.provider);
|
|
3059
|
+
}
|
|
3060
|
+
function resolveReasoner(spec, keys, opts = {}) {
|
|
2529
3061
|
const candidates = [spec, "deepseek-chat", "gemini-flash-latest"].filter(
|
|
2530
3062
|
(s) => !!s
|
|
2531
3063
|
);
|
|
2532
3064
|
for (const c of candidates) {
|
|
2533
3065
|
const info = resolveReasonerInfo(c);
|
|
2534
3066
|
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
|
-
}
|
|
3067
|
+
if (key) return { client: clientFor(info, key, opts), info };
|
|
2541
3068
|
}
|
|
2542
3069
|
return null;
|
|
2543
3070
|
}
|
|
2544
|
-
function resolveSecondReasoner(first, keys) {
|
|
3071
|
+
function resolveSecondReasoner(first, keys, opts = {}) {
|
|
2545
3072
|
const candidates = ["gemini-flash-latest", "deepseek-chat", "glm-4.7", "gpt-4o-mini"];
|
|
2546
3073
|
for (const c of candidates) {
|
|
2547
3074
|
const info = resolveReasonerInfo(c);
|
|
2548
3075
|
if (info.provider === first.provider) continue;
|
|
2549
3076
|
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
|
-
}
|
|
3077
|
+
if (key) return { client: clientFor(info, key, opts), info };
|
|
2556
3078
|
}
|
|
2557
3079
|
return null;
|
|
2558
3080
|
}
|
|
2559
3081
|
|
|
2560
3082
|
// src/finalize/finalize.ts
|
|
2561
3083
|
var MIN_DUR = 0.5;
|
|
2562
|
-
var MAX_DUR = 7;
|
|
2563
3084
|
var OVERLAP_GAP = 0.05;
|
|
2564
3085
|
function textSimilarity(a, b) {
|
|
2565
3086
|
const ta = new Set(tokenize(a).map((t) => t.norm));
|
|
@@ -2703,16 +3224,14 @@ function fixOverlaps(segments) {
|
|
|
2703
3224
|
}
|
|
2704
3225
|
function clampAndFix(segments) {
|
|
2705
3226
|
for (const s of segments) {
|
|
2706
|
-
|
|
2707
|
-
if (dur < MIN_DUR) s.end = s.start + MIN_DUR;
|
|
2708
|
-
else if (dur > MAX_DUR) s.end = s.start + MAX_DUR;
|
|
3227
|
+
if (s.end - s.start < MIN_DUR) s.end = s.start + MIN_DUR;
|
|
2709
3228
|
}
|
|
2710
3229
|
return fixOverlaps(segments);
|
|
2711
3230
|
}
|
|
2712
|
-
function finalizeSegments(segments
|
|
2713
|
-
const
|
|
2714
|
-
|
|
2715
|
-
|
|
3231
|
+
function finalizeSegments(segments) {
|
|
3232
|
+
const deduped = dedupSegments(trimSeamOverlaps(segments)).filter(
|
|
3233
|
+
(s) => s.text.trim().length > 0
|
|
3234
|
+
);
|
|
2716
3235
|
const out = deduped.map((s, i) => ({
|
|
2717
3236
|
id: i + 1,
|
|
2718
3237
|
start: s.start,
|
|
@@ -3040,9 +3559,10 @@ async function summarizeTranscript(client, model, result, instructions) {
|
|
|
3040
3559
|
|
|
3041
3560
|
// src/core/pipeline.ts
|
|
3042
3561
|
import { basename as basename3, resolve as resolve2 } from "path";
|
|
3562
|
+
import { createHash as createHash3 } from "crypto";
|
|
3043
3563
|
var JSON_OPTS = { encoding: "utf-8" };
|
|
3044
3564
|
function readJson(p) {
|
|
3045
|
-
if (!
|
|
3565
|
+
if (!existsSync4(p)) return null;
|
|
3046
3566
|
try {
|
|
3047
3567
|
return JSON.parse(readFileSync2(p, JSON_OPTS));
|
|
3048
3568
|
} catch {
|
|
@@ -3068,6 +3588,12 @@ async function mapPool(items, limit, fn) {
|
|
|
3068
3588
|
function has(passes, p) {
|
|
3069
3589
|
return passes.includes(p);
|
|
3070
3590
|
}
|
|
3591
|
+
var ASR_NAMES = {
|
|
3592
|
+
assemblyai: "AssemblyAI",
|
|
3593
|
+
elevenlabs: "ElevenLabs Scribe",
|
|
3594
|
+
"whisper-groq": "Groq Whisper",
|
|
3595
|
+
none: "none"
|
|
3596
|
+
};
|
|
3071
3597
|
function stageTag(name) {
|
|
3072
3598
|
return (err) => {
|
|
3073
3599
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -3077,6 +3603,37 @@ function stageTag(name) {
|
|
|
3077
3603
|
throw e;
|
|
3078
3604
|
};
|
|
3079
3605
|
}
|
|
3606
|
+
async function preflight(opts) {
|
|
3607
|
+
const options = resolveOptions(opts);
|
|
3608
|
+
const keys = resolveKeys(options.apiKeys);
|
|
3609
|
+
if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
|
|
3610
|
+
if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
|
|
3611
|
+
if (!has(options.passes, "timestamped") && !has(options.passes, "align")) return;
|
|
3612
|
+
const tsProvider = options.timestampedProvider ?? "assemblyai";
|
|
3613
|
+
if (tsProvider === "assemblyai" && !keys.assemblyai) {
|
|
3614
|
+
throw new Error(
|
|
3615
|
+
"ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped elevenlabs / whisper-groq)"
|
|
3616
|
+
);
|
|
3617
|
+
}
|
|
3618
|
+
if (tsProvider === "whisper-groq" && !keys.groq) {
|
|
3619
|
+
throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
|
|
3620
|
+
}
|
|
3621
|
+
if (tsProvider === "elevenlabs" && !keys.elevenlabs) {
|
|
3622
|
+
throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
|
|
3623
|
+
}
|
|
3624
|
+
}
|
|
3625
|
+
function estimateRun(opts, durationSec) {
|
|
3626
|
+
const options = resolveOptions(opts);
|
|
3627
|
+
return estimateRunCost({
|
|
3628
|
+
durationSec,
|
|
3629
|
+
model: options.model ?? DEFAULT_TRANSCRIBE_MODEL,
|
|
3630
|
+
reasoner: options.reasoner ?? DEFAULT_REASONER_MODEL,
|
|
3631
|
+
tsProvider: options.timestampedProvider ?? "assemblyai",
|
|
3632
|
+
chunkSec: options.chunkDurationSec,
|
|
3633
|
+
overlapSec: options.chunkOverlapSec,
|
|
3634
|
+
identify: options.diarizationLevel >= 3 && has(options.passes, "identify")
|
|
3635
|
+
});
|
|
3636
|
+
}
|
|
3080
3637
|
async function transcribe(opts) {
|
|
3081
3638
|
if (!opts || typeof opts.input !== "string" || opts.input.length === 0) {
|
|
3082
3639
|
throw new Error(
|
|
@@ -3086,7 +3643,7 @@ async function transcribe(opts) {
|
|
|
3086
3643
|
const options = resolveOptions(opts);
|
|
3087
3644
|
const keys = resolveKeys(options.apiKeys);
|
|
3088
3645
|
logger.setLevel(options.logLevel);
|
|
3089
|
-
if (!
|
|
3646
|
+
if (!existsSync4(options.input)) {
|
|
3090
3647
|
throw new Error(`Input file not found: ${options.input}`);
|
|
3091
3648
|
}
|
|
3092
3649
|
mkdirSync2(options.intermediatesDir, { recursive: true });
|
|
@@ -3129,23 +3686,11 @@ async function transcribe(opts) {
|
|
|
3129
3686
|
const checkAbort = () => {
|
|
3130
3687
|
options.signal?.throwIfAborted();
|
|
3131
3688
|
};
|
|
3132
|
-
|
|
3133
|
-
|
|
3689
|
+
const emit = (event) => emitTo(options.onProgress, event);
|
|
3690
|
+
const geminiOpts = { zeroStorage: options.zeroStorage };
|
|
3691
|
+
await preflight(opts);
|
|
3134
3692
|
const tsProvider = options.timestampedProvider ?? "assemblyai";
|
|
3135
3693
|
const willTimestamp = has(passes, "timestamped") || has(passes, "align");
|
|
3136
|
-
if (willTimestamp) {
|
|
3137
|
-
if (tsProvider === "assemblyai" && !keys.assemblyai) {
|
|
3138
|
-
throw new Error(
|
|
3139
|
-
"ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped elevenlabs / whisper-groq)"
|
|
3140
|
-
);
|
|
3141
|
-
}
|
|
3142
|
-
if (tsProvider === "whisper-groq" && !keys.groq) {
|
|
3143
|
-
throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
|
|
3144
|
-
}
|
|
3145
|
-
if (tsProvider === "elevenlabs" && !keys.elevenlabs) {
|
|
3146
|
-
throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
|
|
3147
|
-
}
|
|
3148
|
-
}
|
|
3149
3694
|
let probeInfo = null;
|
|
3150
3695
|
const AUDIO_OPTS = { format: "mp3", bitrate: "64k" };
|
|
3151
3696
|
const audioPath = `${options.intermediatesDir}/audio.mp3`;
|
|
@@ -3153,12 +3698,13 @@ async function transcribe(opts) {
|
|
|
3153
3698
|
if (has(passes, "preprocess")) {
|
|
3154
3699
|
checkAbort();
|
|
3155
3700
|
logger.info("=== preprocess ===");
|
|
3701
|
+
emit({ type: "stage", stage: "preprocess", state: "start" });
|
|
3156
3702
|
probeInfo = forceAll ? null : readJson(probePath);
|
|
3157
3703
|
if (!probeInfo) {
|
|
3158
3704
|
probeInfo = await probe(options.input).catch(stageTag("preprocess"));
|
|
3159
3705
|
writeJson(probePath, probeInfo);
|
|
3160
3706
|
}
|
|
3161
|
-
if (!
|
|
3707
|
+
if (!existsSync4(audioPath) || forceAll) {
|
|
3162
3708
|
logger.info("extracting audio (mono 16kHz mp3)...");
|
|
3163
3709
|
await extractAudio(options.input, audioPath, AUDIO_OPTS).catch(
|
|
3164
3710
|
stageTag("preprocess")
|
|
@@ -3166,7 +3712,7 @@ async function transcribe(opts) {
|
|
|
3166
3712
|
}
|
|
3167
3713
|
if (probeInfo.hasVideo) {
|
|
3168
3714
|
const kfDir = `${options.intermediatesDir}/keyframes`;
|
|
3169
|
-
if (!
|
|
3715
|
+
if (!existsSync4(kfDir) || forceAll) {
|
|
3170
3716
|
logger.info("extracting keyframes...");
|
|
3171
3717
|
await extractKeyframes(options.input, kfDir, options.screenshotCount).catch(
|
|
3172
3718
|
(err) => {
|
|
@@ -3182,26 +3728,124 @@ async function transcribe(opts) {
|
|
|
3182
3728
|
}
|
|
3183
3729
|
if (!probeInfo) throw new Error("probe info missing (run preprocess)");
|
|
3184
3730
|
const duration = probeInfo.duration;
|
|
3185
|
-
const estimate =
|
|
3731
|
+
const estimate = estimateRun(opts, duration);
|
|
3732
|
+
logger.info(
|
|
3733
|
+
`estimated cost ~$${estimate.totalUsd.toFixed(2)}${estimate.incomplete ? " (+unpriced parts)" : ""} [${estimate.lines.join(" \xB7 ")}]`
|
|
3734
|
+
);
|
|
3735
|
+
const naming = options.diarizationLevel >= 3 && has(passes, "identify");
|
|
3736
|
+
const reasonerA = naming || options.summary ? resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys, geminiOpts) : null;
|
|
3737
|
+
const reasonerB = naming && reasonerA && options.identifyMode === "dual" ? resolveSecondReasoner(reasonerA.info, keys, geminiOpts) : null;
|
|
3738
|
+
const asksAssemblyAI = willTimestamp && tsProvider === "assemblyai";
|
|
3739
|
+
const notAsked = options.zeroStorage ? [
|
|
3740
|
+
...willTimestamp && (tsProvider === "elevenlabs" || tsProvider === "whisper-groq") ? [{ name: ASR_NAMES[tsProvider], role: "timing" }] : [],
|
|
3741
|
+
...[reasonerA, reasonerB].flatMap(
|
|
3742
|
+
(r) => r && r.info.provider !== "gemini" ? [{ name: r.info.model, role: "text" }] : []
|
|
3743
|
+
)
|
|
3744
|
+
] : [];
|
|
3745
|
+
if (options.zeroStorage) {
|
|
3746
|
+
logger.info(
|
|
3747
|
+
`zero storage: ${asksAssemblyAI ? "Gemini and AssemblyAI are" : "Gemini is"} asked to keep nothing${notAsked.length ? `; ${notAsked.map((p) => p.name).join(", ")} can't be asked` : ""}`
|
|
3748
|
+
);
|
|
3749
|
+
}
|
|
3750
|
+
emit({
|
|
3751
|
+
type: "plan",
|
|
3186
3752
|
durationSec: duration,
|
|
3187
3753
|
model: models.transcribe,
|
|
3188
|
-
|
|
3189
|
-
|
|
3190
|
-
|
|
3191
|
-
|
|
3192
|
-
identify: options.diarizationLevel >= 3 && has(passes, "identify")
|
|
3754
|
+
asr: ASR_NAMES[tsProvider],
|
|
3755
|
+
estimateUsd: estimate.totalUsd,
|
|
3756
|
+
zeroStorage: options.zeroStorage,
|
|
3757
|
+
notAsked
|
|
3193
3758
|
});
|
|
3194
|
-
|
|
3195
|
-
|
|
3759
|
+
const runTimestamped = async () => {
|
|
3760
|
+
if (!has(passes, "timestamped") && !has(passes, "align")) {
|
|
3761
|
+
const cached = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
|
|
3762
|
+
return { result: cached, billed: false };
|
|
3763
|
+
}
|
|
3764
|
+
checkAbort();
|
|
3765
|
+
if (tsProvider === "none") {
|
|
3766
|
+
logger.info("=== timestamped: none (the LLM's own timestamps are used) ===");
|
|
3767
|
+
return { result: null, billed: false };
|
|
3768
|
+
}
|
|
3769
|
+
if (tsProvider === "whisper-groq") {
|
|
3770
|
+
logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
|
|
3771
|
+
if (!existsSync4(audioPath))
|
|
3772
|
+
await extractAudio(options.input, audioPath, AUDIO_OPTS);
|
|
3773
|
+
const groq = new WhisperGroqClient(keys.groq);
|
|
3774
|
+
const result3 = await groq.transcribe(await readFile2(audioPath), { language: options.language }).catch(stageTag("asr"));
|
|
3775
|
+
writeJson(`${options.intermediatesDir}/timestamped.json`, result3);
|
|
3776
|
+
return { result: result3, billed: true };
|
|
3777
|
+
}
|
|
3778
|
+
if (tsProvider === "elevenlabs") {
|
|
3779
|
+
logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
|
|
3780
|
+
const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs${options.language ? `-${options.language}` : ""}.json`;
|
|
3781
|
+
let result3 = forceAll ? null : readJson(cachePath);
|
|
3782
|
+
let billed = false;
|
|
3783
|
+
if (!result3) {
|
|
3784
|
+
const el = new ElevenLabsClient(keys.elevenlabs);
|
|
3785
|
+
result3 = await el.transcribe(await readFile2(audioPath), { languageCode: options.language }).catch(stageTag("asr"));
|
|
3786
|
+
billed = true;
|
|
3787
|
+
writeJson(cachePath, result3);
|
|
3788
|
+
} else {
|
|
3789
|
+
logger.info("[elevenlabs] cache hit");
|
|
3790
|
+
}
|
|
3791
|
+
writeJson(`${options.intermediatesDir}/timestamped.json`, result3);
|
|
3792
|
+
logger.info(
|
|
3793
|
+
`[elevenlabs] ${result3.utterances.length} utterances, ${result3.words.length} words`
|
|
3794
|
+
);
|
|
3795
|
+
return { result: result3, billed };
|
|
3796
|
+
}
|
|
3797
|
+
logger.info("=== timestamped (AssemblyAI) ===");
|
|
3798
|
+
const aai = new AssemblyAIProvider({
|
|
3799
|
+
apiKey: keys.assemblyai,
|
|
3800
|
+
cacheDir: `${options.intermediatesDir}/assemblyai`,
|
|
3801
|
+
language: options.language,
|
|
3802
|
+
zeroStorage: options.zeroStorage
|
|
3803
|
+
});
|
|
3804
|
+
const result2 = await aai.transcribe(audioPath).catch(stageTag("asr"));
|
|
3805
|
+
writeJson(`${options.intermediatesDir}/timestamped.json`, result2);
|
|
3806
|
+
return { result: result2, billed: !aai.lastFromCache };
|
|
3807
|
+
};
|
|
3808
|
+
const asrName = ASR_NAMES[tsProvider];
|
|
3809
|
+
if (willTimestamp && tsProvider !== "none") {
|
|
3810
|
+
emit({ type: "asr", provider: asrName, state: "start" });
|
|
3811
|
+
}
|
|
3812
|
+
const asrRun = runTimestamped().then(
|
|
3813
|
+
(r) => {
|
|
3814
|
+
if (willTimestamp && r.result) {
|
|
3815
|
+
const speakers2 = new Set(r.result.utterances.map((u) => u.speaker)).size;
|
|
3816
|
+
emit({
|
|
3817
|
+
type: "asr",
|
|
3818
|
+
provider: asrName,
|
|
3819
|
+
state: r.billed ? "done" : "cached",
|
|
3820
|
+
words: r.result.words.length,
|
|
3821
|
+
speakers: speakers2 || void 0,
|
|
3822
|
+
language: r.result.languageCode
|
|
3823
|
+
});
|
|
3824
|
+
}
|
|
3825
|
+
return r;
|
|
3826
|
+
},
|
|
3827
|
+
(err) => {
|
|
3828
|
+
emit({
|
|
3829
|
+
type: "asr",
|
|
3830
|
+
provider: asrName,
|
|
3831
|
+
state: "failed",
|
|
3832
|
+
error: err instanceof Error ? err.message : String(err)
|
|
3833
|
+
});
|
|
3834
|
+
throw err;
|
|
3835
|
+
}
|
|
3196
3836
|
);
|
|
3837
|
+
asrRun.catch(() => void 0);
|
|
3197
3838
|
let description = null;
|
|
3198
3839
|
if (has(passes, "describe")) {
|
|
3199
3840
|
const descPath = `${options.intermediatesDir}/description.json`;
|
|
3200
3841
|
description = forceAll ? null : readJson(descPath);
|
|
3201
|
-
if (
|
|
3842
|
+
if (description) {
|
|
3843
|
+
emit({ type: "stage", stage: "describe", state: "cached" });
|
|
3844
|
+
} else {
|
|
3202
3845
|
checkAbort();
|
|
3203
3846
|
logger.info("=== describe ===");
|
|
3204
|
-
|
|
3847
|
+
emit({ type: "stage", stage: "describe", state: "start" });
|
|
3848
|
+
const client = new GeminiClient(keys.gemini, geminiOpts);
|
|
3205
3849
|
const sampleSpans = duration <= 360 ? [[0, duration]] : [
|
|
3206
3850
|
[0, 150],
|
|
3207
3851
|
[Math.max(0, duration / 2 - 60), Math.min(duration, duration / 2 + 60)],
|
|
@@ -3211,17 +3855,17 @@ async function transcribe(opts) {
|
|
|
3211
3855
|
for (let i = 0; i < sampleSpans.length; i++) {
|
|
3212
3856
|
const [s, e] = sampleSpans[i];
|
|
3213
3857
|
const samplePath = `${options.intermediatesDir}/sample_${i}.mp3`;
|
|
3214
|
-
if (!
|
|
3858
|
+
if (!existsSync4(samplePath) || forceAll) {
|
|
3215
3859
|
await extractChunk(audioPath, samplePath, s, e, AUDIO_OPTS);
|
|
3216
3860
|
}
|
|
3217
3861
|
files.push({ path: samplePath });
|
|
3218
3862
|
}
|
|
3219
3863
|
const audioSampleCount = files.length;
|
|
3220
3864
|
const kfDir = `${options.intermediatesDir}/keyframes`;
|
|
3221
|
-
if (
|
|
3865
|
+
if (existsSync4(kfDir)) {
|
|
3222
3866
|
for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
|
|
3223
3867
|
const p = `${kfDir}/${f}`;
|
|
3224
|
-
if (
|
|
3868
|
+
if (existsSync4(p)) files.push({ path: p });
|
|
3225
3869
|
}
|
|
3226
3870
|
}
|
|
3227
3871
|
description = await describeMeeting(
|
|
@@ -3250,14 +3894,14 @@ async function transcribe(opts) {
|
|
|
3250
3894
|
}
|
|
3251
3895
|
chunks = planChunks(duration, options.chunkDurationSec, options.chunkOverlapSec);
|
|
3252
3896
|
if (silences.length > 3) {
|
|
3253
|
-
chunks = chunks.map((c) => {
|
|
3254
|
-
|
|
3897
|
+
chunks = chunks.map((c) => ({
|
|
3898
|
+
...c,
|
|
3899
|
+
start: snapToSilence(
|
|
3255
3900
|
c.start,
|
|
3256
3901
|
silences,
|
|
3257
3902
|
Math.min(10, options.chunkOverlapSec / 2)
|
|
3258
|
-
)
|
|
3259
|
-
|
|
3260
|
-
});
|
|
3903
|
+
)
|
|
3904
|
+
}));
|
|
3261
3905
|
}
|
|
3262
3906
|
}
|
|
3263
3907
|
const tagWith = (r, chunk) => ({
|
|
@@ -3265,20 +3909,25 @@ async function transcribe(opts) {
|
|
|
3265
3909
|
segments: r.segments.map((s) => ({
|
|
3266
3910
|
...s,
|
|
3267
3911
|
chunkIndex: chunk.index,
|
|
3268
|
-
trustedStart: chunk.trustedStart
|
|
3912
|
+
trustedStart: chunk.trustedStart,
|
|
3913
|
+
chunkStart: chunk.start,
|
|
3914
|
+
chunkEnd: chunk.end
|
|
3269
3915
|
}))
|
|
3270
3916
|
});
|
|
3917
|
+
const llmDir = `${options.intermediatesDir}/llm`;
|
|
3271
3918
|
let llmChunkResults = [];
|
|
3919
|
+
let llmChunkPlans = [];
|
|
3272
3920
|
if (has(passes, "llm-transcribe")) {
|
|
3273
3921
|
logger.info("=== llm-transcribe ===");
|
|
3922
|
+
emit({ type: "stage", stage: "transcribe", state: "start" });
|
|
3274
3923
|
let runChunks = chunks;
|
|
3275
3924
|
if (options.onlyChunk !== void 0)
|
|
3276
3925
|
runChunks = chunks.filter((c) => c.index === options.onlyChunk);
|
|
3277
3926
|
logger.info(
|
|
3278
3927
|
`${runChunks.length} chunks (${options.chunkDurationSec}s, ${options.chunkOverlapSec}s overlap)`
|
|
3279
3928
|
);
|
|
3280
|
-
|
|
3281
|
-
const
|
|
3929
|
+
emit({ type: "chunks", total: runChunks.length, chunkSec: options.chunkDurationSec });
|
|
3930
|
+
const client = new GeminiClient(keys.gemini, geminiOpts);
|
|
3282
3931
|
mkdirSync2(llmDir, { recursive: true });
|
|
3283
3932
|
const partialPath = `${options.outputDir}/${basename3(options.input, ext(options.input))}.partial.md`;
|
|
3284
3933
|
const completed = [];
|
|
@@ -3307,25 +3956,23 @@ ${lines.join("\n\n")}
|
|
|
3307
3956
|
const cached = forceAll ? null : readJson(parsedPath);
|
|
3308
3957
|
if (cached && cached.segments.length > 0) {
|
|
3309
3958
|
logger.info(`chunk ${chunk.index}: cached (${cached.segments.length} segments)`);
|
|
3959
|
+
emit({
|
|
3960
|
+
type: "chunk",
|
|
3961
|
+
index: chunk.index,
|
|
3962
|
+
state: "cached",
|
|
3963
|
+
segments: cached.segments.length
|
|
3964
|
+
});
|
|
3310
3965
|
completed.push(cached);
|
|
3311
3966
|
return tagWith(cached, chunk);
|
|
3312
3967
|
}
|
|
3313
3968
|
const chunkPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}.mp3`;
|
|
3314
|
-
if (!
|
|
3969
|
+
if (!existsSync4(chunkPath) || forceAll) {
|
|
3315
3970
|
await extractChunk(audioPath, chunkPath, chunk.start, chunk.end, AUDIO_OPTS);
|
|
3316
3971
|
}
|
|
3317
|
-
let previousTail;
|
|
3318
|
-
if (chunk.index > 0) {
|
|
3319
|
-
const prev = readJson(
|
|
3320
|
-
`${llmDir}/chunk_${String(chunk.index - 1).padStart(2, "0")}_parsed.json`
|
|
3321
|
-
);
|
|
3322
|
-
if (prev && prev.segments.length) {
|
|
3323
|
-
previousTail = prev.segments.slice(-6).map((s) => `${s.speaker}: ${s.text}`).join("\n");
|
|
3324
|
-
}
|
|
3325
|
-
}
|
|
3326
3972
|
logger.info(
|
|
3327
3973
|
`chunk ${chunk.index}: transcribing [${chunk.start.toFixed(0)}-${chunk.end.toFixed(0)}]s...`
|
|
3328
3974
|
);
|
|
3975
|
+
emit({ type: "chunk", index: chunk.index, state: "running" });
|
|
3329
3976
|
const result2 = await transcribeChunk(
|
|
3330
3977
|
client,
|
|
3331
3978
|
models.transcribe,
|
|
@@ -3336,12 +3983,19 @@ ${lines.join("\n\n")}
|
|
|
3336
3983
|
total: runChunks.length,
|
|
3337
3984
|
description: description?.description,
|
|
3338
3985
|
roster: description?.roster,
|
|
3339
|
-
previousTail,
|
|
3340
3986
|
instructions: options.instructions
|
|
3341
3987
|
},
|
|
3342
3988
|
{ chunkDurationSec: chunk.end - chunk.start, validationRetries: 1 }
|
|
3343
3989
|
);
|
|
3344
3990
|
writeJson(parsedPath, result2);
|
|
3991
|
+
emit(
|
|
3992
|
+
result2.error && result2.segments.length === 0 ? { type: "chunk", index: chunk.index, state: "failed", error: result2.error } : {
|
|
3993
|
+
type: "chunk",
|
|
3994
|
+
index: chunk.index,
|
|
3995
|
+
state: "done",
|
|
3996
|
+
segments: result2.segments.length
|
|
3997
|
+
}
|
|
3998
|
+
);
|
|
3345
3999
|
writeFileSync2(
|
|
3346
4000
|
`${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`,
|
|
3347
4001
|
result2.raw
|
|
@@ -3350,6 +4004,7 @@ ${lines.join("\n\n")}
|
|
|
3350
4004
|
writePartial();
|
|
3351
4005
|
return tagWith(result2, chunk);
|
|
3352
4006
|
});
|
|
4007
|
+
llmChunkPlans = runChunks;
|
|
3353
4008
|
const errored = llmChunkResults.filter((r) => r.error);
|
|
3354
4009
|
const producedSegments = llmChunkResults.reduce((n, r) => n + r.segments.length, 0);
|
|
3355
4010
|
if (llmChunkResults.length > 0 && producedSegments === 0 && errored.length === llmChunkResults.length) {
|
|
@@ -3358,16 +4013,118 @@ ${lines.join("\n\n")}
|
|
|
3358
4013
|
);
|
|
3359
4014
|
}
|
|
3360
4015
|
} else {
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
const r = readJson(`${llmDir}/${f}`);
|
|
3366
|
-
|
|
3367
|
-
|
|
4016
|
+
if (!forceAll && existsSync4(llmDir)) {
|
|
4017
|
+
for (const f of readdirSync(llmDir).sort()) {
|
|
4018
|
+
const m = /^chunk_(\d+)_parsed\.json$/.exec(f);
|
|
4019
|
+
const plan = m ? chunks.find((c) => c.index === Number(m[1])) : void 0;
|
|
4020
|
+
const r = plan ? readJson(`${llmDir}/${f}`) : null;
|
|
4021
|
+
if (r && plan) {
|
|
4022
|
+
llmChunkResults.push(tagWith(r, plan));
|
|
4023
|
+
llmChunkPlans.push(plan);
|
|
4024
|
+
}
|
|
4025
|
+
}
|
|
4026
|
+
}
|
|
4027
|
+
}
|
|
4028
|
+
const { result: asrResult, billed: asrBilled } = await asrRun;
|
|
4029
|
+
const quality = [];
|
|
4030
|
+
if (asrResult?.words.length) {
|
|
4031
|
+
let client;
|
|
4032
|
+
for (let i = 0; i < llmChunkResults.length; i++) {
|
|
4033
|
+
const plan = llmChunkPlans[i];
|
|
4034
|
+
const where = `chunk ${plan.index} [${plan.start.toFixed(0)}-${plan.end.toFixed(0)}]s`;
|
|
4035
|
+
let cov = chunkCoverage(
|
|
4036
|
+
llmChunkResults[i].segments,
|
|
4037
|
+
asrResult.words,
|
|
4038
|
+
plan.start,
|
|
4039
|
+
plan.end
|
|
4040
|
+
);
|
|
4041
|
+
let status = cov.low ? "low-coverage" : "ok";
|
|
4042
|
+
if (cov.low) {
|
|
4043
|
+
const retryPath = `${llmDir}/chunk_${String(plan.index).padStart(2, "0")}_retry_parsed.json`;
|
|
4044
|
+
let retry = forceAll ? null : readJson(retryPath);
|
|
4045
|
+
const span = { index: plan.index, startSec: plan.start, endSec: plan.end };
|
|
4046
|
+
if (!retry && has(passes, "llm-transcribe")) {
|
|
4047
|
+
checkAbort();
|
|
4048
|
+
logger.warn(
|
|
4049
|
+
`${where}: ${cov.llmWords} words transcribed where the ASR heard ${cov.asrWords} \u2014 transcribing it again in two halves`
|
|
4050
|
+
);
|
|
4051
|
+
emit({
|
|
4052
|
+
type: "guard",
|
|
4053
|
+
...span,
|
|
4054
|
+
state: "retrying",
|
|
4055
|
+
llmWords: cov.llmWords,
|
|
4056
|
+
asrWords: cov.asrWords
|
|
4057
|
+
});
|
|
4058
|
+
client ??= new GeminiClient(keys.gemini, geminiOpts);
|
|
4059
|
+
retry = await transcribeInHalves({
|
|
4060
|
+
client,
|
|
4061
|
+
model: models.transcribe,
|
|
4062
|
+
audioPath,
|
|
4063
|
+
chunk: plan,
|
|
4064
|
+
pathPrefix: `${llmDir}/chunk_${String(plan.index).padStart(2, "0")}`,
|
|
4065
|
+
ctx: {
|
|
4066
|
+
index: plan.index + 1,
|
|
4067
|
+
total: chunks.length,
|
|
4068
|
+
description: description?.description,
|
|
4069
|
+
roster: description?.roster,
|
|
4070
|
+
instructions: options.instructions
|
|
4071
|
+
},
|
|
4072
|
+
audioOpts: AUDIO_OPTS
|
|
4073
|
+
}).catch(stageTag("llm-transcribe"));
|
|
4074
|
+
writeJson(retryPath, retry);
|
|
4075
|
+
}
|
|
4076
|
+
if (retry) {
|
|
4077
|
+
const again = chunkCoverage(
|
|
4078
|
+
retry.segments,
|
|
4079
|
+
asrResult.words,
|
|
4080
|
+
plan.start,
|
|
4081
|
+
plan.end
|
|
4082
|
+
);
|
|
4083
|
+
logger.info(
|
|
4084
|
+
`${where}: the halves cover ${again.llmWords} words (${again.ratio.toFixed(2)} per ASR word, was ${cov.ratio.toFixed(2)})${again.ratio > cov.ratio ? " \u2014 kept" : " \u2014 first attempt kept"}`
|
|
4085
|
+
);
|
|
4086
|
+
const kept = again.ratio > cov.ratio;
|
|
4087
|
+
emit({
|
|
4088
|
+
type: "guard",
|
|
4089
|
+
...span,
|
|
4090
|
+
state: kept ? "recovered" : "unchanged",
|
|
4091
|
+
llmWords: cov.llmWords,
|
|
4092
|
+
asrWords: cov.asrWords,
|
|
4093
|
+
retryWords: again.llmWords
|
|
4094
|
+
});
|
|
4095
|
+
if (kept) {
|
|
4096
|
+
llmChunkResults[i] = tagWith(retry, plan);
|
|
4097
|
+
cov = again;
|
|
4098
|
+
status = again.low ? "low-coverage" : "retried";
|
|
4099
|
+
}
|
|
4100
|
+
}
|
|
4101
|
+
}
|
|
4102
|
+
quality.push({
|
|
4103
|
+
chunk: plan.index,
|
|
4104
|
+
start: plan.start,
|
|
4105
|
+
end: plan.end,
|
|
4106
|
+
status,
|
|
4107
|
+
llmWords: cov.llmWords,
|
|
4108
|
+
asrWords: cov.asrWords,
|
|
4109
|
+
coverage: Number.isFinite(cov.ratio) ? Number(cov.ratio.toFixed(2)) : null
|
|
4110
|
+
});
|
|
3368
4111
|
}
|
|
3369
4112
|
}
|
|
4113
|
+
const whole = asrResult?.words.length ? chunkCoverage(
|
|
4114
|
+
llmChunkResults.flatMap((r) => r.segments),
|
|
4115
|
+
asrResult.words,
|
|
4116
|
+
0,
|
|
4117
|
+
Infinity
|
|
4118
|
+
) : null;
|
|
4119
|
+
const asrMissedSpeech = !!whole && whole.llmWords >= 200 && whole.ratio > 3;
|
|
4120
|
+
if (asrMissedSpeech) {
|
|
4121
|
+
logger.warn(
|
|
4122
|
+
`the ASR (${tsProvider}) heard ${whole.asrWords} words where the transcript has ${whole.llmWords} \u2014 the recording may be in a language it didn't expect, so timings come from the LLM; re-run with --language <code> (e.g. ko, ml, hi)`
|
|
4123
|
+
);
|
|
4124
|
+
}
|
|
3370
4125
|
let allLlmSegments = llmChunkResults.flatMap((r) => r.segments);
|
|
4126
|
+
const timingWords = asrMissedSpeech ? [] : asrResult?.words ?? [];
|
|
4127
|
+
allLlmSegments = toAsrClock(allLlmSegments, timingWords);
|
|
3371
4128
|
const beforePart = allLlmSegments.length;
|
|
3372
4129
|
allLlmSegments = partitionByOwnership(allLlmSegments);
|
|
3373
4130
|
if (beforePart !== allLlmSegments.length) {
|
|
@@ -3376,81 +4133,68 @@ ${lines.join("\n\n")}
|
|
|
3376
4133
|
);
|
|
3377
4134
|
}
|
|
3378
4135
|
logger.info(`total LLM segments: ${allLlmSegments.length}`);
|
|
3379
|
-
|
|
3380
|
-
|
|
3381
|
-
|
|
3382
|
-
|
|
3383
|
-
|
|
3384
|
-
|
|
3385
|
-
|
|
3386
|
-
|
|
3387
|
-
|
|
4136
|
+
if (asrResult?.words.length && (has(passes, "align") || has(passes, "consistency"))) {
|
|
4137
|
+
const dropped = /* @__PURE__ */ new Set();
|
|
4138
|
+
for (let i = 0; i < llmChunkResults.length; i++) {
|
|
4139
|
+
const r = llmChunkResults[i];
|
|
4140
|
+
const plan = llmChunkPlans[i];
|
|
4141
|
+
const q = quality.find((x) => x.chunk === plan.index);
|
|
4142
|
+
const where = `chunk ${plan.index} [${plan.start.toFixed(0)}-${plan.end.toFixed(0)}]s`;
|
|
4143
|
+
const compression = maxCompressionRatio(r.segments.map((s) => s.text).join(" "));
|
|
4144
|
+
if (compression > DEGENERATE_COMPRESSION_RATIO) {
|
|
4145
|
+
dropped.add(plan.index);
|
|
4146
|
+
if (q) q.status = "dropped-loop";
|
|
4147
|
+
logger.warn(
|
|
4148
|
+
`${where}: dropping repetition-loop text (compression ratio ${compression.toFixed(1)}) \u2014 ASR will fill this range`
|
|
4149
|
+
);
|
|
4150
|
+
continue;
|
|
3388
4151
|
}
|
|
3389
|
-
const
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
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");
|
|
4152
|
+
const g = chunkGrounding(r.segments, asrResult.words, plan.start, plan.end);
|
|
4153
|
+
if (!g.grounded) {
|
|
4154
|
+
if (q) q.ungrounded = true;
|
|
4155
|
+
logger.warn(
|
|
4156
|
+
`${where}: only ${Math.round(g.precision * 100)}% of ${g.llmTokens} content words were also heard by the ASR \u2014 check this stretch (kept as transcribed)`
|
|
4157
|
+
);
|
|
3408
4158
|
}
|
|
3409
|
-
|
|
3410
|
-
|
|
3411
|
-
|
|
4159
|
+
}
|
|
4160
|
+
if (dropped.size) {
|
|
4161
|
+
allLlmSegments = allLlmSegments.filter(
|
|
4162
|
+
(s) => s.chunkIndex === void 0 || !dropped.has(s.chunkIndex)
|
|
3412
4163
|
);
|
|
3413
|
-
} else {
|
|
3414
|
-
logger.info("=== timestamped (AssemblyAI) ===");
|
|
3415
|
-
if (!keys.assemblyai)
|
|
3416
|
-
throw new Error(
|
|
3417
|
-
"ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
|
|
3418
|
-
);
|
|
3419
|
-
const aai = new AssemblyAIProvider({
|
|
3420
|
-
apiKey: keys.assemblyai,
|
|
3421
|
-
cacheDir: `${options.intermediatesDir}/assemblyai`
|
|
3422
|
-
});
|
|
3423
|
-
asrResult = await aai.transcribe(audioPath).catch(stageTag("asr"));
|
|
3424
|
-
writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
|
|
3425
4164
|
}
|
|
3426
|
-
} else {
|
|
3427
|
-
asrResult = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
|
|
3428
4165
|
}
|
|
3429
4166
|
let aligned = [];
|
|
3430
|
-
if (has(passes, "align") && asrResult) {
|
|
4167
|
+
if (has(passes, "align") && (asrResult || tsProvider === "none")) {
|
|
3431
4168
|
logger.info("=== align ===");
|
|
3432
|
-
|
|
4169
|
+
emit({ type: "stage", stage: "align", state: "start" });
|
|
4170
|
+
aligned = alignSegments(allLlmSegments, timingWords, { timeMarginSec: 30 });
|
|
3433
4171
|
writeJson(`${options.intermediatesDir}/aligned.json`, aligned);
|
|
3434
4172
|
} else {
|
|
3435
4173
|
aligned = (forceAll ? null : readJson(`${options.intermediatesDir}/aligned.json`)) ?? [];
|
|
3436
4174
|
}
|
|
3437
4175
|
const alignedOk = aligned.filter((a) => a.timingSource !== "coarse").length;
|
|
3438
4176
|
logger.info(`aligned: ${alignedOk}/${aligned.length} with ASR timing`);
|
|
3439
|
-
|
|
3440
|
-
|
|
4177
|
+
let gapFilledWords = 0;
|
|
4178
|
+
if (asrResult && !asrMissedSpeech && (has(passes, "align") || has(passes, "consistency"))) {
|
|
3441
4179
|
aligned = fillAsrGaps(aligned, asrResult.words, asrResult.utterances);
|
|
3442
|
-
const added = aligned.
|
|
3443
|
-
|
|
4180
|
+
const added = aligned.filter((a) => a.timingSource === "timestamped");
|
|
4181
|
+
gapFilledWords = added.reduce((n, a) => n + a.words.length, 0);
|
|
4182
|
+
if (added.length) {
|
|
4183
|
+
logger.info(
|
|
4184
|
+
`gap-filled ${added.length} ASR fallback segment(s) (${gapFilledWords} words)`
|
|
4185
|
+
);
|
|
4186
|
+
}
|
|
3444
4187
|
}
|
|
3445
4188
|
if (asrResult && (asrResult.hasDiarization ?? true) && (has(passes, "align") || has(passes, "consistency"))) {
|
|
3446
4189
|
aligned = splitMixedVoiceSegments(aligned, asrResult.utterances);
|
|
3447
4190
|
}
|
|
3448
4191
|
let segments = aligned;
|
|
3449
4192
|
let speakers = [];
|
|
3450
|
-
if (has(passes, "consistency") && asrResult) {
|
|
4193
|
+
if (has(passes, "consistency") && (asrResult || tsProvider === "none")) {
|
|
3451
4194
|
logger.info("=== consistency ===");
|
|
3452
|
-
|
|
3453
|
-
|
|
4195
|
+
emit({ type: "stage", stage: "speakers", state: "start" });
|
|
4196
|
+
const cons = assignGlobalSpeakers(aligned, asrResult?.utterances ?? [], {
|
|
4197
|
+
hasDiarization: asrResult ? asrResult.hasDiarization ?? true : false
|
|
3454
4198
|
});
|
|
3455
4199
|
segments = cons.segments;
|
|
3456
4200
|
speakers = cons.speakers;
|
|
@@ -3472,19 +4216,22 @@ ${lines.join("\n\n")}
|
|
|
3472
4216
|
(s) => s.speakerName !== s.speaker ? { ...s, speakerName: s.speaker } : s
|
|
3473
4217
|
);
|
|
3474
4218
|
speakers = speakers.map((sp) => sp.name !== sp.id ? { ...sp, name: sp.id } : sp);
|
|
3475
|
-
if (
|
|
3476
|
-
const reasonerA = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
|
|
4219
|
+
if (naming) {
|
|
3477
4220
|
if (!reasonerA) {
|
|
3478
4221
|
logger.warn(
|
|
3479
4222
|
"identify: no reasoner-capable API key found (DEEPSEEK/GEMINI/OPENAI/\u2026) \u2014 skipping speaker naming"
|
|
3480
4223
|
);
|
|
3481
4224
|
} else {
|
|
3482
4225
|
const mode = options.identifyMode;
|
|
3483
|
-
const reasonerB = mode === "dual" ? resolveSecondReasoner(reasonerA.info, keys) : null;
|
|
3484
4226
|
const idConfig = {
|
|
3485
4227
|
mode,
|
|
3486
4228
|
reasonerA: reasonerA.info.model,
|
|
3487
|
-
reasonerB: reasonerB?.info.model ?? null
|
|
4229
|
+
reasonerB: reasonerB?.info.model ?? null,
|
|
4230
|
+
knownSpeakers: options.knownSpeakers ?? [],
|
|
4231
|
+
// What the naming step reads. If a re-run changes the transcript (a re-transcribed
|
|
4232
|
+
// chunk can reorder speakers by talk time), "Speaker A" may now be the other voice,
|
|
4233
|
+
// and the cached names must not be applied to it.
|
|
4234
|
+
inputs: createHash3("sha1").update(JSON.stringify(segments.map((s) => [s.speaker, s.text]))).update(JSON.stringify(speakers.map((sp) => sp.id))).digest("hex")
|
|
3488
4235
|
};
|
|
3489
4236
|
const idCachePath = `${options.intermediatesDir}/identified.json`;
|
|
3490
4237
|
const cachedId = forceAll ? null : readJson(
|
|
@@ -3494,11 +4241,18 @@ ${lines.join("\n\n")}
|
|
|
3494
4241
|
let nameMap = null;
|
|
3495
4242
|
if (idConfigMatches && cachedId?.nameMap && Object.keys(cachedId.nameMap).length > 0) {
|
|
3496
4243
|
logger.info("=== identify (cached) ===");
|
|
4244
|
+
emit({ type: "stage", stage: "identify", state: "cached" });
|
|
3497
4245
|
nameMap = cachedId.nameMap;
|
|
3498
4246
|
} else {
|
|
3499
4247
|
logger.info(
|
|
3500
4248
|
`=== identify (${reasonerA.info.model}${reasonerB ? ` + ${reasonerB.info.model} second opinion` : ""}) ===`
|
|
3501
4249
|
);
|
|
4250
|
+
emit({
|
|
4251
|
+
type: "stage",
|
|
4252
|
+
stage: "identify",
|
|
4253
|
+
state: "start",
|
|
4254
|
+
detail: reasonerB ? `${reasonerA.info.model} + ${reasonerB.info.model}` : reasonerA.info.model
|
|
4255
|
+
});
|
|
3502
4256
|
checkAbort();
|
|
3503
4257
|
const id = await identifySpeakersV2(
|
|
3504
4258
|
{
|
|
@@ -3523,11 +4277,14 @@ ${lines.join("\n\n")}
|
|
|
3523
4277
|
).catch(stageTag("identify"));
|
|
3524
4278
|
writeJson(idCachePath, { ...id, config: idConfig });
|
|
3525
4279
|
nameMap = id.nameMap;
|
|
4280
|
+
if (id.allPassesFailed)
|
|
4281
|
+
emit({ type: "stage", stage: "identify", state: "failed" });
|
|
3526
4282
|
}
|
|
3527
4283
|
logger.info(
|
|
3528
4284
|
`identified ${Object.keys(nameMap).length} speakers: ${JSON.stringify(nameMap)}`
|
|
3529
4285
|
);
|
|
3530
4286
|
const nm = nameMap;
|
|
4287
|
+
emit({ type: "names", names: nm });
|
|
3531
4288
|
segments = segments.map(
|
|
3532
4289
|
(s) => nm[s.speaker] ? { ...s, speakerName: nm[s.speaker] } : s
|
|
3533
4290
|
);
|
|
@@ -3537,13 +4294,14 @@ ${lines.join("\n\n")}
|
|
|
3537
4294
|
let finalSegments = [];
|
|
3538
4295
|
if (has(passes, "finalize")) {
|
|
3539
4296
|
logger.info("=== finalize ===");
|
|
4297
|
+
emit({ type: "stage", stage: "finalize", state: "start" });
|
|
3540
4298
|
finalSegments = finalizeSegments(segments);
|
|
3541
4299
|
writeJson(`${options.intermediatesDir}/final.json`, finalSegments);
|
|
3542
4300
|
} else {
|
|
3543
4301
|
finalSegments = (forceAll ? null : readJson(`${options.intermediatesDir}/final.json`)) ?? [];
|
|
3544
4302
|
}
|
|
3545
4303
|
logger.info(`final segments: ${finalSegments.length}`);
|
|
3546
|
-
const receipt = computeReceipt(getLlmUsage(), tsProvider, duration);
|
|
4304
|
+
const receipt = computeReceipt(getLlmUsage(), tsProvider, duration, asrBilled);
|
|
3547
4305
|
const wallMs = Date.now() - runStartedAt;
|
|
3548
4306
|
const metadata = {
|
|
3549
4307
|
sourceFile: options.input,
|
|
@@ -3563,86 +4321,103 @@ ${lines.join("\n\n")}
|
|
|
3563
4321
|
llmCalls: receipt.totals.calls,
|
|
3564
4322
|
inputTokens: receipt.totals.inputTokens,
|
|
3565
4323
|
outputTokens: receipt.totals.outputTokens
|
|
3566
|
-
}
|
|
4324
|
+
},
|
|
4325
|
+
...asrResult ? { quality: { chunks: quality, gapFilledWords, asrMissedSpeech } } : {},
|
|
4326
|
+
zeroStorage: options.zeroStorage
|
|
3567
4327
|
};
|
|
4328
|
+
const degraded = quality.filter((q) => q.status !== "ok");
|
|
4329
|
+
if (degraded.length || asrMissedSpeech) {
|
|
4330
|
+
logger.warn(
|
|
4331
|
+
`quality: ${degraded.map((q) => `chunk ${q.chunk} ${q.status}`).join(", ") || "all chunks ok"}${asrMissedSpeech ? " \xB7 the ASR missed most of the speech" : ""} \xB7 ${gapFilledWords} words filled from the ASR`
|
|
4332
|
+
);
|
|
4333
|
+
}
|
|
3568
4334
|
const result = { segments: finalSegments, speakers, metadata };
|
|
3569
4335
|
writeJson(`${options.intermediatesDir}/result.json`, result);
|
|
4336
|
+
const base = basename3(options.input, ext(options.input));
|
|
4337
|
+
const written = [];
|
|
4338
|
+
const write = (name, content) => {
|
|
4339
|
+
const path = `${options.outputDir}/${name}`;
|
|
4340
|
+
writeFileSync2(path, content);
|
|
4341
|
+
written.push(resolve2(path));
|
|
4342
|
+
};
|
|
3570
4343
|
for (const fmt of options.formats) {
|
|
3571
|
-
|
|
3572
|
-
if (fmt === "srt")
|
|
3573
|
-
writeFileSync2(
|
|
3574
|
-
`${options.outputDir}/${base}.srt`,
|
|
3575
|
-
formatSrt(result, { title: base })
|
|
3576
|
-
);
|
|
4344
|
+
if (fmt === "srt") write(`${base}.srt`, formatSrt(result, { title: base }));
|
|
3577
4345
|
if (fmt === "md")
|
|
3578
|
-
|
|
3579
|
-
`${
|
|
4346
|
+
write(
|
|
4347
|
+
`${base}.md`,
|
|
3580
4348
|
formatMarkdown(result, { title: base, mdStyle: options.mdStyle })
|
|
3581
4349
|
);
|
|
3582
|
-
if (fmt === "txt")
|
|
3583
|
-
|
|
3584
|
-
|
|
3585
|
-
formatText(result, { title: base })
|
|
3586
|
-
);
|
|
3587
|
-
if (fmt === "html")
|
|
3588
|
-
writeFileSync2(
|
|
3589
|
-
`${options.outputDir}/${base}.html`,
|
|
3590
|
-
formatHtml(result, { title: base })
|
|
3591
|
-
);
|
|
3592
|
-
if (fmt === "json")
|
|
3593
|
-
writeFileSync2(`${options.outputDir}/${base}.json`, formatJson(result));
|
|
4350
|
+
if (fmt === "txt") write(`${base}.txt`, formatText(result, { title: base }));
|
|
4351
|
+
if (fmt === "html") write(`${base}.html`, formatHtml(result, { title: base }));
|
|
4352
|
+
if (fmt === "json") write(`${base}.json`, formatJson(result));
|
|
3594
4353
|
}
|
|
3595
4354
|
if (options.summary && finalSegments.length > 0) {
|
|
3596
|
-
|
|
3597
|
-
if (!reasoner) {
|
|
4355
|
+
if (!reasonerA) {
|
|
3598
4356
|
logger.warn("summary: no reasoner-capable key \u2014 skipping");
|
|
3599
4357
|
} else {
|
|
3600
|
-
logger.info(`=== summary (${
|
|
4358
|
+
logger.info(`=== summary (${reasonerA.info.model}) ===`);
|
|
4359
|
+
emit({
|
|
4360
|
+
type: "stage",
|
|
4361
|
+
stage: "summary",
|
|
4362
|
+
state: "start",
|
|
4363
|
+
detail: reasonerA.info.model
|
|
4364
|
+
});
|
|
3601
4365
|
try {
|
|
3602
4366
|
const summary = await summarizeTranscript(
|
|
3603
|
-
|
|
3604
|
-
|
|
4367
|
+
reasonerA.client,
|
|
4368
|
+
reasonerA.info.model,
|
|
3605
4369
|
result,
|
|
3606
4370
|
options.instructions
|
|
3607
4371
|
);
|
|
3608
|
-
|
|
3609
|
-
writeFileSync2(`${options.outputDir}/${base}.summary.md`, summary);
|
|
4372
|
+
write(`${base}.summary.md`, summary);
|
|
3610
4373
|
logger.info(`summary written to ${base}.summary.md`);
|
|
3611
4374
|
} catch (err) {
|
|
3612
4375
|
logger.warn(`summary failed: ${err instanceof Error ? err.message : err}`);
|
|
4376
|
+
emit({ type: "stage", stage: "summary", state: "failed" });
|
|
3613
4377
|
}
|
|
3614
4378
|
}
|
|
3615
4379
|
}
|
|
3616
4380
|
try {
|
|
3617
|
-
const base = basename3(options.input, ext(options.input));
|
|
3618
4381
|
const partial = `${options.outputDir}/${base}.partial.md`;
|
|
3619
|
-
if (
|
|
4382
|
+
if (existsSync4(partial)) (await import("fs/promises")).unlink(partial);
|
|
3620
4383
|
} catch {
|
|
3621
4384
|
}
|
|
3622
4385
|
logger.info(`outputs written to ${options.outputDir}`);
|
|
3623
|
-
const
|
|
3624
|
-
const
|
|
4386
|
+
const spent = computeReceipt(getLlmUsage(), tsProvider, duration, asrBilled);
|
|
4387
|
+
const runMs = Date.now() - runStartedAt;
|
|
4388
|
+
const mins = Math.floor(runMs / 6e4);
|
|
4389
|
+
const secs = Math.round(runMs % 6e4 / 1e3);
|
|
3625
4390
|
logger.info(
|
|
3626
|
-
`receipt: ${
|
|
4391
|
+
`receipt: ${spent.totals.calls} LLM calls \xB7 ${(spent.totals.inputTokens / 1e3).toFixed(0)}k in / ${(spent.totals.outputTokens / 1e3).toFixed(0)}k out \xB7 ~$${spent.totalUsd.toFixed(2)}${spent.incomplete ? " (+unpriced)" : ""} \xB7 ${mins ? `${mins}m` : ""}${secs}s`
|
|
3627
4392
|
);
|
|
3628
|
-
for (const line of
|
|
4393
|
+
for (const line of spent.lines) logger.info(` ${line}`);
|
|
3629
4394
|
recordRun(
|
|
3630
4395
|
{
|
|
3631
4396
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3632
4397
|
input: basename3(options.input),
|
|
3633
4398
|
durationSec: duration,
|
|
3634
|
-
wallMs,
|
|
4399
|
+
wallMs: runMs,
|
|
3635
4400
|
models: metadata.models,
|
|
3636
4401
|
segments: finalSegments.length,
|
|
3637
4402
|
characters: finalSegments.reduce((n, s) => n + s.text.length, 0),
|
|
3638
4403
|
speakers: speakers.length,
|
|
3639
|
-
llmCalls:
|
|
3640
|
-
inputTokens:
|
|
3641
|
-
outputTokens:
|
|
3642
|
-
costUsd:
|
|
4404
|
+
llmCalls: spent.totals.calls,
|
|
4405
|
+
inputTokens: spent.totals.inputTokens,
|
|
4406
|
+
outputTokens: spent.totals.outputTokens,
|
|
4407
|
+
costUsd: spent.totalUsd
|
|
3643
4408
|
},
|
|
3644
|
-
|
|
4409
|
+
spent.perModel
|
|
3645
4410
|
);
|
|
4411
|
+
emit({
|
|
4412
|
+
type: "done",
|
|
4413
|
+
segments: finalSegments.length,
|
|
4414
|
+
speakers: speakers.length,
|
|
4415
|
+
durationSec: duration,
|
|
4416
|
+
costUsd: spent.totalUsd,
|
|
4417
|
+
wallMs: runMs,
|
|
4418
|
+
retriedChunks: quality.filter((q) => q.status === "retried").length,
|
|
4419
|
+
outputs: written
|
|
4420
|
+
});
|
|
3646
4421
|
return result;
|
|
3647
4422
|
}
|
|
3648
4423
|
function ext(p) {
|
|
@@ -3680,6 +4455,9 @@ function parseSrt(content) {
|
|
|
3680
4455
|
return entries;
|
|
3681
4456
|
}
|
|
3682
4457
|
export {
|
|
4458
|
+
DEFAULT_REASONER_MODEL,
|
|
4459
|
+
DEFAULT_TRANSCRIBE_MODEL,
|
|
4460
|
+
PRO_TRANSCRIBE_MODEL,
|
|
3683
4461
|
alignSegments,
|
|
3684
4462
|
assignGlobalSpeakers,
|
|
3685
4463
|
finalizeSegments,
|
|
@@ -3689,6 +4467,7 @@ export {
|
|
|
3689
4467
|
formatSrt,
|
|
3690
4468
|
formatText,
|
|
3691
4469
|
identifySpeakers,
|
|
4470
|
+
identifySpeakersV2,
|
|
3692
4471
|
parseSrt,
|
|
3693
4472
|
planChunks,
|
|
3694
4473
|
summarizeTranscript,
|