offmute-v2 0.1.1 → 0.2.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 +95 -43
- 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 +1714 -649
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1211 -441
- 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 +1207 -437
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/cli.ts
|
|
4
|
-
import { Command } from "commander";
|
|
4
|
+
import { Command, Option } from "commander";
|
|
5
5
|
import { readFileSync as readFileSync6 } from "fs";
|
|
6
6
|
import { fileURLToPath } from "url";
|
|
7
|
-
import { dirname as dirname5, join as join5, basename as basename6
|
|
7
|
+
import { dirname as dirname5, join as join5, basename as basename6 } from "path";
|
|
8
8
|
|
|
9
9
|
// src/core/pipeline.ts
|
|
10
|
-
import { existsSync as
|
|
10
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
11
|
+
import { readFile as readFile2 } from "fs/promises";
|
|
12
|
+
|
|
13
|
+
// src/core/models.ts
|
|
14
|
+
var DEFAULT_TRANSCRIBE_MODEL = "gemini-4-hydrogen";
|
|
15
|
+
var PRO_TRANSCRIBE_MODEL = "gemini-4-argon";
|
|
16
|
+
var DEFAULT_REASONER_MODEL = "deepseek-chat";
|
|
11
17
|
|
|
12
18
|
// src/core/config.ts
|
|
13
19
|
import { createHash } from "crypto";
|
|
@@ -23,19 +29,6 @@ var DEFAULT_PASSES = [
|
|
|
23
29
|
"consistency",
|
|
24
30
|
"finalize"
|
|
25
31
|
];
|
|
26
|
-
var MODELS = {
|
|
27
|
-
gemini25Pro: "gemini-2.5-pro",
|
|
28
|
-
gemini25Flash: "gemini-2.5-flash",
|
|
29
|
-
gemini3Pro: "gemini-3-pro-preview",
|
|
30
|
-
gemini31Pro: "gemini-3.1-pro-preview",
|
|
31
|
-
geminiFlashLatest: "gemini-flash-latest",
|
|
32
|
-
deepseek: "deepseek-chat",
|
|
33
|
-
deepseekReasoner: "deepseek-reasoner",
|
|
34
|
-
gpt4o: "gpt-4o",
|
|
35
|
-
claudeSonnet: "claude-sonnet-4-5"
|
|
36
|
-
};
|
|
37
|
-
var DEFAULT_TRANSCRIBE_MODEL = MODELS.gemini31Pro;
|
|
38
|
-
var DEFAULT_REASONER_MODEL = MODELS.deepseek;
|
|
39
32
|
function resolveKeys(injected) {
|
|
40
33
|
const env = process.env;
|
|
41
34
|
return {
|
|
@@ -87,12 +80,15 @@ function resolveOptions(opts) {
|
|
|
87
80
|
model: opts.model,
|
|
88
81
|
reasoner: opts.reasoner,
|
|
89
82
|
timestampedProvider: opts.timestampedProvider,
|
|
83
|
+
language: opts.language,
|
|
90
84
|
force: opts.force ?? false,
|
|
91
85
|
onlyChunk: opts.onlyChunk,
|
|
92
86
|
showProgress: opts.showProgress ?? true,
|
|
93
87
|
llmLog: opts.llmLog ?? true,
|
|
94
88
|
logLevel: opts.logLevel ?? "info",
|
|
95
|
-
signal: opts.signal
|
|
89
|
+
signal: opts.signal,
|
|
90
|
+
onProgress: opts.onProgress,
|
|
91
|
+
zeroStorage: opts.zeroStorage ?? true
|
|
96
92
|
};
|
|
97
93
|
}
|
|
98
94
|
function deriveIntermediatesDir(input) {
|
|
@@ -119,9 +115,7 @@ function inputSignature(input) {
|
|
|
119
115
|
function configSignature(o) {
|
|
120
116
|
const relevant = {
|
|
121
117
|
model: o.model ?? DEFAULT_TRANSCRIBE_MODEL,
|
|
122
|
-
reasoner: o.reasoner ?? DEFAULT_REASONER_MODEL,
|
|
123
118
|
instructions: o.instructions ?? "",
|
|
124
|
-
knownSpeakers: o.knownSpeakers ?? [],
|
|
125
119
|
chunkDurationSec: o.chunkDurationSec ?? 600,
|
|
126
120
|
chunkOverlapSec: o.chunkOverlapSec ?? 60,
|
|
127
121
|
screenshotCount: o.screenshotCount ?? 6,
|
|
@@ -157,6 +151,15 @@ function planChunks(totalDuration, chunkDuration, overlap2) {
|
|
|
157
151
|
return chunks;
|
|
158
152
|
}
|
|
159
153
|
|
|
154
|
+
// src/core/progress.ts
|
|
155
|
+
function emitTo(listener, event) {
|
|
156
|
+
if (!listener) return;
|
|
157
|
+
try {
|
|
158
|
+
listener(event);
|
|
159
|
+
} catch {
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
160
163
|
// src/utils/logger.ts
|
|
161
164
|
var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
162
165
|
var currentLevel = "info";
|
|
@@ -191,7 +194,7 @@ import { spawn } from "child_process";
|
|
|
191
194
|
import { mkdir } from "fs/promises";
|
|
192
195
|
import { dirname as dirname2 } from "path";
|
|
193
196
|
function run(cmd, args, _opts = {}) {
|
|
194
|
-
return new Promise((
|
|
197
|
+
return new Promise((resolve4, reject) => {
|
|
195
198
|
const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
196
199
|
let stdout = "";
|
|
197
200
|
let stderr = "";
|
|
@@ -199,7 +202,7 @@ function run(cmd, args, _opts = {}) {
|
|
|
199
202
|
child.stderr.on("data", (d) => stderr += d.toString());
|
|
200
203
|
child.on("error", reject);
|
|
201
204
|
child.on("close", (code) => {
|
|
202
|
-
if (code === 0)
|
|
205
|
+
if (code === 0) resolve4({ stdout, stderr });
|
|
203
206
|
else {
|
|
204
207
|
const tail = stderr.slice(-800);
|
|
205
208
|
reject(new Error(`${cmd} exited ${code}: ${tail}`));
|
|
@@ -303,22 +306,22 @@ async function getSceneChangeTimes(input, threshold) {
|
|
|
303
306
|
return [];
|
|
304
307
|
}
|
|
305
308
|
}
|
|
306
|
-
async function extractKeyframes(input, outputDir,
|
|
309
|
+
async function extractKeyframes(input, outputDir, count2, opts = {}) {
|
|
307
310
|
await mkdir(outputDir, { recursive: true });
|
|
308
311
|
const width = opts.width ?? 1280;
|
|
309
312
|
const { duration } = await probe(input);
|
|
310
313
|
if (!duration) return [];
|
|
311
314
|
const sceneTimes = await getSceneChangeTimes(input, opts.sceneThreshold ?? 0.3);
|
|
312
315
|
const times = [];
|
|
313
|
-
if (sceneTimes.length >=
|
|
314
|
-
const step = sceneTimes.length /
|
|
315
|
-
for (let i = 0; i <
|
|
316
|
+
if (sceneTimes.length >= count2) {
|
|
317
|
+
const step = sceneTimes.length / count2;
|
|
318
|
+
for (let i = 0; i < count2; i++) {
|
|
316
319
|
const idx = Math.floor(i * step);
|
|
317
320
|
times.push(sceneTimes[idx] ?? 0);
|
|
318
321
|
}
|
|
319
322
|
} else {
|
|
320
323
|
times.push(...sceneTimes);
|
|
321
|
-
const need =
|
|
324
|
+
const need = count2 - times.length;
|
|
322
325
|
const start = duration * 0.02;
|
|
323
326
|
const end = duration * 0.98;
|
|
324
327
|
for (let i = 0; i < need; i++) {
|
|
@@ -390,7 +393,9 @@ function snapToSilence(boundary, silences, tolerance) {
|
|
|
390
393
|
}
|
|
391
394
|
|
|
392
395
|
// src/providers/gemini.ts
|
|
393
|
-
import {
|
|
396
|
+
import {
|
|
397
|
+
GoogleGenAI
|
|
398
|
+
} from "@google/genai";
|
|
394
399
|
import { basename as basename2 } from "path";
|
|
395
400
|
|
|
396
401
|
// src/providers/llm-log.ts
|
|
@@ -458,6 +463,38 @@ async function withRetry(label, fn, opts = {}) {
|
|
|
458
463
|
throw lastErr;
|
|
459
464
|
}
|
|
460
465
|
|
|
466
|
+
// src/providers/gemini-usage.ts
|
|
467
|
+
function usageFromMetadata(meta) {
|
|
468
|
+
const thoughtTokens = meta?.thoughtsTokenCount ?? 0;
|
|
469
|
+
return {
|
|
470
|
+
inputTokens: meta?.promptTokenCount ?? 0,
|
|
471
|
+
outputTokens: (meta?.candidatesTokenCount ?? 0) + thoughtTokens,
|
|
472
|
+
thoughtTokens,
|
|
473
|
+
totalTokens: meta?.totalTokenCount ?? 0
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// src/providers/gemini-models.ts
|
|
478
|
+
function resolveThinking(model) {
|
|
479
|
+
const m = model.toLowerCase();
|
|
480
|
+
if (m.includes("gemini-2.0")) return void 0;
|
|
481
|
+
if (m.includes("gemini-4")) return { thinkingLevel: "LOW" };
|
|
482
|
+
if (m.includes("gemini-2.5")) {
|
|
483
|
+
return { thinkingBudget: m.includes("pro") ? 128 : 0 };
|
|
484
|
+
}
|
|
485
|
+
if (m.includes("-latest")) return { thinkingLevel: "LOW" };
|
|
486
|
+
if (m.includes("gemini-3"))
|
|
487
|
+
return { thinkingLevel: m.includes("pro") ? "LOW" : "MINIMAL" };
|
|
488
|
+
return void 0;
|
|
489
|
+
}
|
|
490
|
+
function fallbackThinking(rejected) {
|
|
491
|
+
return rejected.thinkingLevel === "MINIMAL" ? { thinkingLevel: "LOW" } : void 0;
|
|
492
|
+
}
|
|
493
|
+
function isThinkingConfigError(message) {
|
|
494
|
+
if (!message) return false;
|
|
495
|
+
return /thinking/i.test(message) && /(not supported|invalid|unsupported|unknown name|unexpected)/i.test(message);
|
|
496
|
+
}
|
|
497
|
+
|
|
461
498
|
// src/providers/gemini.ts
|
|
462
499
|
var SDK_KEY_WARNING = "Both GOOGLE_API_KEY and GEMINI_API_KEY are set";
|
|
463
500
|
var originalWarn = console.warn.bind(console);
|
|
@@ -486,25 +523,15 @@ function detectMime(path) {
|
|
|
486
523
|
return MIME_BY_EXT[ext2] ?? "application/octet-stream";
|
|
487
524
|
}
|
|
488
525
|
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
489
|
-
function resolveThinking(model) {
|
|
490
|
-
const m = model.toLowerCase();
|
|
491
|
-
if (m.includes("gemini-2.0")) return void 0;
|
|
492
|
-
if (m.includes("gemini-2.5")) {
|
|
493
|
-
return { thinkingBudget: m.includes("pro") ? 128 : 0 };
|
|
494
|
-
}
|
|
495
|
-
if (m.includes("gemini-3") || m.includes("flash-latest") || m.includes("pro-latest")) {
|
|
496
|
-
return { thinkingLevel: m.includes("pro") ? "LOW" : "MINIMAL" };
|
|
497
|
-
}
|
|
498
|
-
return void 0;
|
|
499
|
-
}
|
|
500
|
-
function isThinkingConfigError(message) {
|
|
501
|
-
if (!message) return false;
|
|
502
|
-
return /thinking/i.test(message) && /(not supported|invalid|unsupported|unknown name|unexpected)/i.test(message);
|
|
503
|
-
}
|
|
504
526
|
var GeminiClient = class {
|
|
505
527
|
ai;
|
|
506
|
-
|
|
507
|
-
|
|
528
|
+
zeroStorage;
|
|
529
|
+
constructor(apiKey, opts = {}) {
|
|
530
|
+
this.ai = new GoogleGenAI({
|
|
531
|
+
apiKey,
|
|
532
|
+
...opts.baseUrl ? { httpOptions: { baseUrl: opts.baseUrl } } : {}
|
|
533
|
+
});
|
|
534
|
+
this.zeroStorage = opts.zeroStorage ?? true;
|
|
508
535
|
}
|
|
509
536
|
/** Upload a file and wait until it's done processing. Uploads ride one long HTTP
|
|
510
537
|
* request each — the retry loop in generate() doesn't cover them, and transient
|
|
@@ -547,12 +574,15 @@ var GeminiClient = class {
|
|
|
547
574
|
maxOutputTokens,
|
|
548
575
|
temperature
|
|
549
576
|
};
|
|
577
|
+
if (this.zeroStorage) config.store = false;
|
|
550
578
|
if (responseSchema) {
|
|
551
579
|
config.responseMimeType = "application/json";
|
|
552
580
|
config.responseSchema = responseSchema;
|
|
581
|
+
} else if (opts.responseJson) {
|
|
582
|
+
config.responseMimeType = "application/json";
|
|
553
583
|
}
|
|
554
584
|
if (systemInstruction) config.systemInstruction = systemInstruction;
|
|
555
|
-
|
|
585
|
+
let thinking = resolveThinking(model);
|
|
556
586
|
if (thinking) config.thinkingConfig = thinking;
|
|
557
587
|
const parts = uploaded.map((f) => ({
|
|
558
588
|
fileData: { fileUri: f.uri, mimeType: f.mimeType }
|
|
@@ -562,21 +592,31 @@ var GeminiClient = class {
|
|
|
562
592
|
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
563
593
|
const t0 = Date.now();
|
|
564
594
|
try {
|
|
565
|
-
const
|
|
595
|
+
const controller = new AbortController();
|
|
596
|
+
const stream = await this.ai.models.generateContentStream({
|
|
566
597
|
model,
|
|
567
598
|
contents: [{ role: "user", parts }],
|
|
568
|
-
config
|
|
599
|
+
config: { ...config, abortSignal: controller.signal }
|
|
569
600
|
});
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
601
|
+
let text = "";
|
|
602
|
+
let usageMeta;
|
|
603
|
+
let abortReason = null;
|
|
604
|
+
for await (const chunk of stream) {
|
|
605
|
+
text += chunk.text ?? "";
|
|
606
|
+
if (chunk.usageMetadata) usageMeta = chunk.usageMetadata;
|
|
607
|
+
abortReason = opts.shouldAbort?.(text) ?? null;
|
|
608
|
+
if (abortReason) {
|
|
609
|
+
controller.abort();
|
|
610
|
+
break;
|
|
578
611
|
}
|
|
579
|
-
}
|
|
612
|
+
}
|
|
613
|
+
const usage = usageFromMetadata(usageMeta);
|
|
614
|
+
const error = abortReason ? `aborted: ${abortReason}` : void 0;
|
|
615
|
+
if (error) {
|
|
616
|
+
logger.warn(
|
|
617
|
+
`[gemini] ${opts.logKind ?? "call"}${opts.logChunk !== void 0 ? ` chunk ${opts.logChunk}` : ""} ${error} after ${text.length} chars`
|
|
618
|
+
);
|
|
619
|
+
}
|
|
580
620
|
logLlmCall({
|
|
581
621
|
ts: new Date(t0).toISOString(),
|
|
582
622
|
provider: "gemini",
|
|
@@ -585,18 +625,22 @@ var GeminiClient = class {
|
|
|
585
625
|
chunk: opts.logChunk,
|
|
586
626
|
prompt,
|
|
587
627
|
response: text,
|
|
588
|
-
usage
|
|
628
|
+
usage,
|
|
589
629
|
durationMs: Date.now() - t0,
|
|
590
|
-
attempt: attempt + 1
|
|
630
|
+
attempt: attempt + 1,
|
|
631
|
+
...error ? { error } : {}
|
|
591
632
|
});
|
|
592
|
-
return
|
|
633
|
+
return error ? { text, usage, error } : { text, usage };
|
|
593
634
|
} catch (err) {
|
|
594
635
|
lastError = err instanceof Error ? err.message : String(err);
|
|
595
|
-
if (
|
|
596
|
-
|
|
636
|
+
if (thinking && isThinkingConfigError(lastError)) {
|
|
637
|
+
const next = fallbackThinking(thinking);
|
|
597
638
|
logger.warn(
|
|
598
|
-
`[gemini] model ${model} rejected thinking config \u2014 retrying without it`
|
|
639
|
+
`[gemini] model ${model} rejected thinking config ${JSON.stringify(thinking)} \u2014 retrying ${next ? `with ${JSON.stringify(next)}` : "without it"}`
|
|
599
640
|
);
|
|
641
|
+
thinking = next;
|
|
642
|
+
if (thinking) config.thinkingConfig = thinking;
|
|
643
|
+
else delete config.thinkingConfig;
|
|
600
644
|
continue;
|
|
601
645
|
}
|
|
602
646
|
logger.warn(
|
|
@@ -662,51 +706,93 @@ var GeminiClient = class {
|
|
|
662
706
|
};
|
|
663
707
|
|
|
664
708
|
// src/providers/assemblyai.ts
|
|
665
|
-
import {
|
|
709
|
+
import {
|
|
710
|
+
AssemblyAI
|
|
711
|
+
} from "assemblyai";
|
|
666
712
|
import { createHash as createHash2 } from "crypto";
|
|
667
|
-
import { readFile, mkdir as mkdir2, writeFile } from "fs/promises";
|
|
713
|
+
import { readFile, mkdir as mkdir2, writeFile, rm } from "fs/promises";
|
|
668
714
|
import { existsSync } from "fs";
|
|
669
715
|
import { dirname as dirname3 } from "path";
|
|
670
716
|
async function fileHash(path) {
|
|
671
717
|
const buf = await readFile(path);
|
|
672
718
|
return createHash2("sha256").update(buf).digest("hex").slice(0, 24);
|
|
673
719
|
}
|
|
720
|
+
var DELETED_TEXT = "Deleted by user.";
|
|
721
|
+
async function readPendingId(pendingPath) {
|
|
722
|
+
if (!existsSync(pendingPath)) return void 0;
|
|
723
|
+
try {
|
|
724
|
+
return JSON.parse(await readFile(pendingPath, "utf-8")).id;
|
|
725
|
+
} catch {
|
|
726
|
+
return void 0;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
674
729
|
var AssemblyAIProvider = class {
|
|
675
730
|
client;
|
|
676
731
|
cacheDir;
|
|
677
732
|
constructor(opts) {
|
|
678
|
-
this.client = new AssemblyAI({ apiKey: opts.apiKey });
|
|
733
|
+
this.client = new AssemblyAI({ apiKey: opts.apiKey, baseUrl: opts.baseUrl });
|
|
679
734
|
this.cacheDir = opts.cacheDir;
|
|
680
735
|
this.speechModel = opts.speechModel ?? "universal";
|
|
681
736
|
this.speakersExpected = opts.speakersExpected;
|
|
737
|
+
this.language = opts.language;
|
|
738
|
+
this.zeroStorage = opts.zeroStorage ?? true;
|
|
682
739
|
}
|
|
683
740
|
speechModel;
|
|
684
741
|
speakersExpected;
|
|
742
|
+
language;
|
|
743
|
+
zeroStorage;
|
|
744
|
+
/** Whether the last transcribe() was served from the content-hash cache (no paid call). */
|
|
745
|
+
lastFromCache = false;
|
|
685
746
|
/** Transcribe a local audio file. Returns cached result if available. */
|
|
686
747
|
async transcribe(filePath) {
|
|
687
748
|
const hash = await fileHash(filePath);
|
|
688
|
-
const
|
|
749
|
+
const variant = [
|
|
750
|
+
`lang-${this.language ?? "auto"}`,
|
|
751
|
+
this.speakersExpected && `spk-${this.speakersExpected}`,
|
|
752
|
+
this.speechModel !== "universal" && this.speechModel
|
|
753
|
+
].filter(Boolean).join("_");
|
|
754
|
+
const cachePath = this.cacheDir ? `${this.cacheDir}/${hash}_${variant}.json` : void 0;
|
|
755
|
+
const pendingPath = cachePath?.replace(/\.json$/, ".pending.json");
|
|
756
|
+
this.lastFromCache = false;
|
|
689
757
|
if (cachePath && existsSync(cachePath)) {
|
|
690
758
|
logger.info(`[assemblyai] cache hit ${hash}`);
|
|
759
|
+
this.lastFromCache = true;
|
|
760
|
+
if (pendingPath) await this.finish(pendingPath, await readPendingId(pendingPath));
|
|
691
761
|
return JSON.parse(await readFile(cachePath, "utf-8"));
|
|
692
762
|
}
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
763
|
+
let transcript = pendingPath ? await this.resume(pendingPath) : void 0;
|
|
764
|
+
if (!transcript) {
|
|
765
|
+
logger.info(`[assemblyai] uploading ${filePath}...`);
|
|
766
|
+
const uploadUrl = await withRetry(
|
|
767
|
+
"assemblyai upload",
|
|
768
|
+
() => this.client.files.upload(filePath)
|
|
769
|
+
);
|
|
770
|
+
logger.info(
|
|
771
|
+
`[assemblyai] transcribing (speech_model=${this.speechModel}, language=${this.language ?? "auto-detect"})...`
|
|
772
|
+
);
|
|
773
|
+
const params = {
|
|
774
|
+
audio: uploadUrl,
|
|
775
|
+
speaker_labels: true,
|
|
776
|
+
speech_model: this.speechModel
|
|
777
|
+
};
|
|
778
|
+
if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
|
|
779
|
+
if (this.language) params.language_code = this.language;
|
|
780
|
+
else params.language_detection = true;
|
|
781
|
+
const job = await withRetry(
|
|
782
|
+
"assemblyai submit",
|
|
783
|
+
() => this.client.transcripts.submit(params)
|
|
784
|
+
);
|
|
785
|
+
if (pendingPath) {
|
|
786
|
+
await mkdir2(dirname3(pendingPath), { recursive: true });
|
|
787
|
+
await writeFile(pendingPath, JSON.stringify({ id: job.id }));
|
|
788
|
+
}
|
|
789
|
+
transcript = await withRetry(
|
|
790
|
+
"assemblyai transcribe",
|
|
791
|
+
() => this.client.transcripts.waitUntilReady(job.id)
|
|
792
|
+
);
|
|
793
|
+
}
|
|
709
794
|
if (transcript.status === "error") {
|
|
795
|
+
if (pendingPath) await rm(pendingPath, { force: true });
|
|
710
796
|
throw new Error(`AssemblyAI error: ${transcript.error}`);
|
|
711
797
|
}
|
|
712
798
|
const result = this.mapTranscript(transcript, hash);
|
|
@@ -715,10 +801,53 @@ var AssemblyAIProvider = class {
|
|
|
715
801
|
await writeFile(cachePath, JSON.stringify(result, null, 2));
|
|
716
802
|
}
|
|
717
803
|
logger.info(
|
|
718
|
-
`[assemblyai] done: ${result.utterances.length} utterances, ${result.words.length} words, ${result.speakers.length} speakers`
|
|
804
|
+
`[assemblyai] done: ${result.utterances.length} utterances, ${result.words.length} words, ${result.speakers.length} speakers, language ${result.languageCode ?? "?"}`
|
|
719
805
|
);
|
|
806
|
+
if (pendingPath) await this.finish(pendingPath, transcript.id);
|
|
807
|
+
else if (this.zeroStorage && transcript.id) await this.deleteRemote(transcript.id);
|
|
720
808
|
return result;
|
|
721
809
|
}
|
|
810
|
+
/** Delete job `id` from AssemblyAI (with zero storage), then forget it. */
|
|
811
|
+
async finish(pendingPath, id) {
|
|
812
|
+
if (this.zeroStorage && id) await this.deleteRemote(id);
|
|
813
|
+
await rm(pendingPath, { force: true });
|
|
814
|
+
}
|
|
815
|
+
async deleteRemote(id) {
|
|
816
|
+
await this.client.transcripts.delete(id).then(
|
|
817
|
+
() => logger.debug(`[assemblyai] deleted transcript ${id} from AssemblyAI`),
|
|
818
|
+
(err) => logger.warn(
|
|
819
|
+
`[assemblyai] couldn't delete transcript ${id} from AssemblyAI (it expires in 30 days): ${err instanceof Error ? err.message : String(err)}`
|
|
820
|
+
)
|
|
821
|
+
);
|
|
822
|
+
}
|
|
823
|
+
/** The finished job a stopped run left at `pendingPath`, or undefined to send the audio
|
|
824
|
+
* again: when there is none, or AssemblyAI says it's gone (not found, failed, deleted).
|
|
825
|
+
* Anything less certain (offline, an outage, a refused key) is thrown with the job kept,
|
|
826
|
+
* so the next run neither pays twice nor leaves the job behind undeleted. */
|
|
827
|
+
async resume(pendingPath) {
|
|
828
|
+
const id = await readPendingId(pendingPath);
|
|
829
|
+
if (id) {
|
|
830
|
+
logger.info(`[assemblyai] picking up transcript ${id}, left by a stopped run...`);
|
|
831
|
+
let gone;
|
|
832
|
+
try {
|
|
833
|
+
const t = await withRetry(
|
|
834
|
+
"assemblyai transcribe",
|
|
835
|
+
() => this.client.transcripts.waitUntilReady(id)
|
|
836
|
+
);
|
|
837
|
+
if (t.status === "completed" && t.text !== DELETED_TEXT) return t;
|
|
838
|
+
gone = t.status === "error" ? `it failed: ${t.error}` : "it was deleted";
|
|
839
|
+
} catch (err) {
|
|
840
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
841
|
+
if (!/not found/i.test(message)) throw err;
|
|
842
|
+
gone = message;
|
|
843
|
+
}
|
|
844
|
+
logger.warn(
|
|
845
|
+
`[assemblyai] transcript ${id} is gone (${gone}) \u2014 sending the audio again`
|
|
846
|
+
);
|
|
847
|
+
}
|
|
848
|
+
await rm(pendingPath, { force: true });
|
|
849
|
+
return void 0;
|
|
850
|
+
}
|
|
722
851
|
mapTranscript(t, id) {
|
|
723
852
|
const toWord = (w) => ({
|
|
724
853
|
text: w.text,
|
|
@@ -748,6 +877,7 @@ var AssemblyAIProvider = class {
|
|
|
748
877
|
durationSec,
|
|
749
878
|
audioDurationSec: t.audio_duration ?? void 0,
|
|
750
879
|
// AssemblyAI returns seconds (not ms)
|
|
880
|
+
languageCode: t.language_code ?? void 0,
|
|
751
881
|
speakers: [...speakers].sort(),
|
|
752
882
|
transcriptId: t.id ?? id,
|
|
753
883
|
speechModelUsed: t.speech_model_used ?? void 0,
|
|
@@ -766,7 +896,7 @@ var WhisperGroqClient = class {
|
|
|
766
896
|
apiKey;
|
|
767
897
|
model;
|
|
768
898
|
baseUrl;
|
|
769
|
-
async transcribe(audio) {
|
|
899
|
+
async transcribe(audio, opts = {}) {
|
|
770
900
|
const blob = audio instanceof Blob ? audio : new Blob([audio], { type: "audio/mpeg" });
|
|
771
901
|
const form = new FormData();
|
|
772
902
|
form.append("file", blob, "audio.mp3");
|
|
@@ -774,6 +904,7 @@ var WhisperGroqClient = class {
|
|
|
774
904
|
form.append("response_format", "verbose_json");
|
|
775
905
|
form.append("timestamp_granularities[]", "word");
|
|
776
906
|
form.append("timestamp_granularities[]", "segment");
|
|
907
|
+
if (opts.language) form.append("language", opts.language);
|
|
777
908
|
const res = await fetch(`${this.baseUrl}/audio/transcriptions`, {
|
|
778
909
|
method: "POST",
|
|
779
910
|
headers: { Authorization: `Bearer ${this.apiKey}` },
|
|
@@ -828,6 +959,7 @@ var ElevenLabsClient = class {
|
|
|
828
959
|
form.append("diarize", "true");
|
|
829
960
|
form.append("tag_audio_events", "false");
|
|
830
961
|
if (opts.numSpeakers) form.append("num_speakers", String(opts.numSpeakers));
|
|
962
|
+
if (opts.languageCode) form.append("language_code", opts.languageCode);
|
|
831
963
|
for (const term of opts.keyterms ?? []) form.append("keyterms", term);
|
|
832
964
|
const data = await withRetry("elevenlabs", async () => {
|
|
833
965
|
const res = await fetch(`${this.baseUrl}/speech-to-text`, {
|
|
@@ -886,17 +1018,53 @@ var ElevenLabsClient = class {
|
|
|
886
1018
|
};
|
|
887
1019
|
|
|
888
1020
|
// src/core/pricing.ts
|
|
889
|
-
var PRICES_AS_OF = "2026-
|
|
1021
|
+
var PRICES_AS_OF = "2026-11-17";
|
|
890
1022
|
var MODEL_PRICES = {
|
|
891
|
-
|
|
1023
|
+
"gemini-4-hydrogen": { textIn: 1.5, out: 7.5 },
|
|
1024
|
+
"gemini-4-argon": {
|
|
1025
|
+
until: "2026-11-30",
|
|
1026
|
+
price: { textIn: 2, out: 10 },
|
|
1027
|
+
then: { textIn: 4, out: 20 }
|
|
1028
|
+
},
|
|
1029
|
+
"gemini-4-carbon": {
|
|
1030
|
+
until: "2026-11-30",
|
|
1031
|
+
price: { textIn: 2, out: 10 },
|
|
1032
|
+
then: { textIn: 4, out: 20 }
|
|
1033
|
+
},
|
|
892
1034
|
"gemini-3.1-pro-preview": { textIn: 2, out: 12 },
|
|
893
|
-
|
|
894
|
-
"gemini-3.
|
|
1035
|
+
// ≤200k-token prompts
|
|
1036
|
+
"gemini-3.8-flash": {
|
|
1037
|
+
until: "2026-12-31",
|
|
1038
|
+
price: { textIn: 0.75, out: 3.75 },
|
|
1039
|
+
then: { textIn: 1.5, out: 7.5 }
|
|
1040
|
+
},
|
|
1041
|
+
"gemini-3.6-flash": {
|
|
1042
|
+
until: "2026-12-31",
|
|
1043
|
+
price: { textIn: 0.75, out: 3.75 },
|
|
1044
|
+
then: { textIn: 1.5, out: 7.5 }
|
|
1045
|
+
},
|
|
1046
|
+
// Deprecated 2026-10-08; requests are served by gemini-3.6-flash (priced as such).
|
|
1047
|
+
"gemini-3.5-flash": {
|
|
1048
|
+
until: "2026-12-31",
|
|
1049
|
+
price: { textIn: 0.75, out: 3.75 },
|
|
1050
|
+
then: { textIn: 1.5, out: 7.5 }
|
|
1051
|
+
},
|
|
1052
|
+
"gemini-3.5-flash-lite": { textIn: 0.3, out: 2.5 },
|
|
895
1053
|
"gemini-3-flash-preview": { textIn: 0.5, audioIn: 1, out: 3 },
|
|
896
|
-
|
|
897
|
-
"gemini-2.5-
|
|
1054
|
+
// From 2026-12-01 Google serves (and bills) 2.5 Pro as 3.8 Flash and 2.5 Flash as 3.5 Flash-Lite.
|
|
1055
|
+
"gemini-2.5-pro": {
|
|
1056
|
+
until: "2026-11-30",
|
|
1057
|
+
price: { textIn: 1.25, out: 10 },
|
|
1058
|
+
then: { textIn: 1.5, out: 7.5 }
|
|
1059
|
+
},
|
|
1060
|
+
"gemini-2.5-flash": {
|
|
1061
|
+
until: "2026-11-30",
|
|
1062
|
+
price: { textIn: 0.3, audioIn: 1, out: 2.5 },
|
|
1063
|
+
then: { textIn: 0.3, out: 2.5 }
|
|
1064
|
+
},
|
|
898
1065
|
"gemini-2.5-flash-lite": { textIn: 0.1, audioIn: 0.3, out: 0.4 },
|
|
899
|
-
// Moving aliases
|
|
1066
|
+
// Moving aliases. Google hasn't documented their targets since January 2026; these are
|
|
1067
|
+
// the last documented targets' prices, so treat them as estimates.
|
|
900
1068
|
"gemini-pro-latest": { textIn: 2, out: 12 },
|
|
901
1069
|
"gemini-flash-latest": { textIn: 1.5, out: 9 },
|
|
902
1070
|
"gemini-flash-lite-latest": { textIn: 0.25, audioIn: 0.5, out: 1.5 },
|
|
@@ -915,17 +1083,27 @@ var ASR_HOURLY = {
|
|
|
915
1083
|
// whisper-large-v3-turbo
|
|
916
1084
|
none: 0
|
|
917
1085
|
};
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
1086
|
+
function audioTokensPerSec(model) {
|
|
1087
|
+
return model.startsWith("gemini-4") ? 32 : 25;
|
|
1088
|
+
}
|
|
1089
|
+
function priceFor(model, at = /* @__PURE__ */ new Date()) {
|
|
1090
|
+
const key = model in MODEL_PRICES ? model : Object.keys(MODEL_PRICES).filter((k) => model.startsWith(k)).sort((a, b) => b.length - a.length)[0];
|
|
1091
|
+
if (!key) return null;
|
|
1092
|
+
const p = MODEL_PRICES[key];
|
|
1093
|
+
if (!("until" in p)) return p;
|
|
1094
|
+
return at.toISOString().slice(0, 10) <= p.until ? p.price : p.then;
|
|
923
1095
|
}
|
|
924
1096
|
function asrCost(provider, durationSec) {
|
|
925
1097
|
const hourly = ASR_HOURLY[provider];
|
|
926
1098
|
if (hourly === void 0) return null;
|
|
927
1099
|
return durationSec / 3600 * hourly;
|
|
928
1100
|
}
|
|
1101
|
+
var OUTPUT_TOK_PER_AUDIO_MIN = 700;
|
|
1102
|
+
function thinkingOverhead(model) {
|
|
1103
|
+
if (model.startsWith("gemini-4-hydrogen")) return 0.5;
|
|
1104
|
+
if (model.includes("pro")) return 0.15;
|
|
1105
|
+
return 0;
|
|
1106
|
+
}
|
|
929
1107
|
function estimateRunCost(opts) {
|
|
930
1108
|
const lines = [];
|
|
931
1109
|
let total = 0;
|
|
@@ -937,9 +1115,9 @@ function estimateRunCost(opts) {
|
|
|
937
1115
|
);
|
|
938
1116
|
const billedAudioSec = opts.durationSec + Math.max(0, chunks - 1) * opts.overlapSec + Math.min(370, opts.durationSec);
|
|
939
1117
|
if (p) {
|
|
940
|
-
const audioTok = billedAudioSec *
|
|
1118
|
+
const audioTok = billedAudioSec * audioTokensPerSec(opts.model);
|
|
941
1119
|
const promptTok = chunks * 1500;
|
|
942
|
-
const outTok = opts.durationSec / 60 *
|
|
1120
|
+
const outTok = opts.durationSec / 60 * OUTPUT_TOK_PER_AUDIO_MIN * (1 + thinkingOverhead(opts.model)) + 1500;
|
|
943
1121
|
const inRate = p.audioIn ?? p.textIn;
|
|
944
1122
|
const llmUsd = (audioTok * inRate + promptTok * p.textIn + outTok * p.out) / 1e6;
|
|
945
1123
|
total += llmUsd;
|
|
@@ -950,11 +1128,11 @@ function estimateRunCost(opts) {
|
|
|
950
1128
|
incomplete = true;
|
|
951
1129
|
lines.push(`${opts.model}: unpriced`);
|
|
952
1130
|
}
|
|
953
|
-
const
|
|
954
|
-
if (
|
|
955
|
-
total +=
|
|
1131
|
+
const asr2 = asrCost(opts.tsProvider, opts.durationSec);
|
|
1132
|
+
if (asr2 !== null && opts.tsProvider !== "none") {
|
|
1133
|
+
total += asr2;
|
|
956
1134
|
lines.push(
|
|
957
|
-
`${opts.tsProvider}: ${(opts.durationSec / 60).toFixed(0)}min \u2248 $${
|
|
1135
|
+
`${opts.tsProvider}: ${(opts.durationSec / 60).toFixed(0)}min \u2248 $${asr2.toFixed(2)}`
|
|
958
1136
|
);
|
|
959
1137
|
}
|
|
960
1138
|
if (opts.identify && opts.reasoner) {
|
|
@@ -967,7 +1145,7 @@ function estimateRunCost(opts) {
|
|
|
967
1145
|
}
|
|
968
1146
|
return { totalUsd: total, lines, incomplete };
|
|
969
1147
|
}
|
|
970
|
-
function computeReceipt(usage, tsProvider, durationSec) {
|
|
1148
|
+
function computeReceipt(usage, tsProvider, durationSec, asrBilled = true) {
|
|
971
1149
|
let llmUsd = 0;
|
|
972
1150
|
let incomplete = false;
|
|
973
1151
|
const lines = [];
|
|
@@ -1000,11 +1178,11 @@ function computeReceipt(usage, tsProvider, durationSec) {
|
|
|
1000
1178
|
`${model}: ${m.calls} call${m.calls > 1 ? "s" : ""} \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 $${usd.toFixed(2)}`
|
|
1001
1179
|
);
|
|
1002
1180
|
}
|
|
1003
|
-
const asrUsd = tsProvider === "none" ? 0 : asrCost(tsProvider, durationSec);
|
|
1181
|
+
const asrUsd = tsProvider === "none" || !asrBilled ? 0 : asrCost(tsProvider, durationSec);
|
|
1004
1182
|
if (asrUsd !== null && tsProvider !== "none") {
|
|
1005
1183
|
perModel[tsProvider] = asrUsd;
|
|
1006
1184
|
lines.push(
|
|
1007
|
-
`${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7
|
|
1185
|
+
`${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7 ${asrBilled ? `$${asrUsd.toFixed(2)}` : "cached \xB7 $0.00"}`
|
|
1008
1186
|
);
|
|
1009
1187
|
}
|
|
1010
1188
|
return {
|
|
@@ -1145,11 +1323,22 @@ async function describeMeeting(client, model, files, fileName, instructions, aud
|
|
|
1145
1323
|
logKind: "describe"
|
|
1146
1324
|
}
|
|
1147
1325
|
);
|
|
1148
|
-
|
|
1326
|
+
return { ...parseDescription(res.text || ""), raw: res.text || "" };
|
|
1327
|
+
}
|
|
1328
|
+
function parseDescription(text) {
|
|
1149
1329
|
const parts = text.split(/\n---\n|\n\s*---\s*\n/);
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1330
|
+
return {
|
|
1331
|
+
description: dropHeading(parts[0] ?? "", "DESCRIPTION") || text.trim(),
|
|
1332
|
+
roster: dropHeading(parts.slice(1).join("\n---\n"), "ROSTER") || "(no explicit roster)"
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
function dropHeading(section, word) {
|
|
1336
|
+
const s = section.trim();
|
|
1337
|
+
const firstLine = s.split("\n", 1)[0] ?? "";
|
|
1338
|
+
if (new RegExp(`^[#*_\\s]*${word}[#*_:\\s]*$`, "i").test(firstLine)) {
|
|
1339
|
+
return s.slice(firstLine.length).trim();
|
|
1340
|
+
}
|
|
1341
|
+
return s.replace(new RegExp(`^[#*_\\s]*${word}[*_]*\\s*:[*_]*\\s*`, "i"), "");
|
|
1153
1342
|
}
|
|
1154
1343
|
|
|
1155
1344
|
// src/transcribe/prompts.ts
|
|
@@ -1242,13 +1431,6 @@ function transcriptionPrompt(ctx) {
|
|
|
1242
1431
|
"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."
|
|
1243
1432
|
);
|
|
1244
1433
|
}
|
|
1245
|
-
if (ctx.previousTail) {
|
|
1246
|
-
parts.push("");
|
|
1247
|
-
parts.push(
|
|
1248
|
-
"TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):"
|
|
1249
|
-
);
|
|
1250
|
-
parts.push(ctx.previousTail);
|
|
1251
|
-
}
|
|
1252
1434
|
if (ctx.instructions) {
|
|
1253
1435
|
parts.push("");
|
|
1254
1436
|
parts.push("ADDITIONAL INSTRUCTIONS:");
|
|
@@ -1293,6 +1475,51 @@ function formatDuration(seconds) {
|
|
|
1293
1475
|
return parts.join(" ");
|
|
1294
1476
|
}
|
|
1295
1477
|
|
|
1478
|
+
// src/transcribe/degeneration.ts
|
|
1479
|
+
var DEGENERATE_COMPRESSION_RATIO = 2.2;
|
|
1480
|
+
var WINDOW_CHARS = 400;
|
|
1481
|
+
var STEP_CHARS = 200;
|
|
1482
|
+
var MIN_MATCH = 4;
|
|
1483
|
+
var MAX_MATCH = 258;
|
|
1484
|
+
var REF_COST = 3;
|
|
1485
|
+
function ratio(s) {
|
|
1486
|
+
let cost = 0;
|
|
1487
|
+
for (let i = 0; i < s.length; ) {
|
|
1488
|
+
let best = 0;
|
|
1489
|
+
for (let j = Math.max(0, i - WINDOW_CHARS); j < i; j++) {
|
|
1490
|
+
let k = 0;
|
|
1491
|
+
while (i + k < s.length && k < MAX_MATCH && s[j + k] === s[i + k]) k++;
|
|
1492
|
+
if (k > best) best = k;
|
|
1493
|
+
}
|
|
1494
|
+
if (best >= MIN_MATCH) {
|
|
1495
|
+
cost += REF_COST;
|
|
1496
|
+
i += best;
|
|
1497
|
+
} else {
|
|
1498
|
+
cost += 1;
|
|
1499
|
+
i += 1;
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
return s.length / cost;
|
|
1503
|
+
}
|
|
1504
|
+
function maxCompressionRatio(text) {
|
|
1505
|
+
if (text.length < WINDOW_CHARS) return 0;
|
|
1506
|
+
let max = 0;
|
|
1507
|
+
for (let i = 0; i + WINDOW_CHARS <= text.length; i += STEP_CHARS) {
|
|
1508
|
+
max = Math.max(max, ratio(text.slice(i, i + WINDOW_CHARS)));
|
|
1509
|
+
}
|
|
1510
|
+
return Math.max(max, ratio(text.slice(-WINDOW_CHARS)));
|
|
1511
|
+
}
|
|
1512
|
+
function tailIsDegenerate(text) {
|
|
1513
|
+
if (text.length < 2 * WINDOW_CHARS) return false;
|
|
1514
|
+
return ratio(text.slice(-WINDOW_CHARS)) > DEGENERATE_COMPRESSION_RATIO && ratio(text.slice(-2 * WINDOW_CHARS, -WINDOW_CHARS)) > DEGENERATE_COMPRESSION_RATIO;
|
|
1515
|
+
}
|
|
1516
|
+
function transcriptTextOf(partialJson) {
|
|
1517
|
+
const out = [];
|
|
1518
|
+
for (const m of partialJson.matchAll(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/g))
|
|
1519
|
+
out.push(m[1]);
|
|
1520
|
+
return out.join(" ");
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1296
1523
|
// src/transcribe/llm-transcribe.ts
|
|
1297
1524
|
var MIN_SEGMENTS = 3;
|
|
1298
1525
|
var MIN_SPAN_RATIO = 0.6;
|
|
@@ -1333,6 +1560,16 @@ function parseLlmSegments(data, chunkOffsetSec) {
|
|
|
1333
1560
|
return { segments: out, dropped };
|
|
1334
1561
|
}
|
|
1335
1562
|
function validate(segments, chunkDuration) {
|
|
1563
|
+
const compression = maxCompressionRatio(segments.map((s) => s.text).join(" "));
|
|
1564
|
+
if (compression > DEGENERATE_COMPRESSION_RATIO) {
|
|
1565
|
+
return {
|
|
1566
|
+
isValid: false,
|
|
1567
|
+
degenerate: true,
|
|
1568
|
+
spanSec: segments.length ? segments[segments.length - 1].endSec - segments[0].startSec : 0,
|
|
1569
|
+
segmentCount: segments.length,
|
|
1570
|
+
message: `degenerate repetition (compression ratio ${compression.toFixed(1)} > ${DEGENERATE_COMPRESSION_RATIO})`
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1336
1573
|
if (segments.length < MIN_SEGMENTS) {
|
|
1337
1574
|
return {
|
|
1338
1575
|
isValid: false,
|
|
@@ -1343,92 +1580,155 @@ function validate(segments, chunkDuration) {
|
|
|
1343
1580
|
}
|
|
1344
1581
|
const first = segments[0].startSec;
|
|
1345
1582
|
const last = segments[segments.length - 1].endSec;
|
|
1346
|
-
const
|
|
1583
|
+
const span2 = last - first;
|
|
1347
1584
|
const minSpan = chunkDuration * MIN_SPAN_RATIO;
|
|
1348
|
-
if (
|
|
1585
|
+
if (span2 < minSpan) {
|
|
1349
1586
|
return {
|
|
1350
1587
|
isValid: false,
|
|
1351
|
-
spanSec:
|
|
1588
|
+
spanSec: span2,
|
|
1352
1589
|
segmentCount: segments.length,
|
|
1353
|
-
message: `span ${
|
|
1590
|
+
message: `span ${span2.toFixed(0)}s < ${minSpan.toFixed(0)}s required (${MIN_SPAN_RATIO * 100}% of chunk)`
|
|
1354
1591
|
};
|
|
1355
1592
|
}
|
|
1356
1593
|
return {
|
|
1357
1594
|
isValid: true,
|
|
1358
|
-
spanSec:
|
|
1595
|
+
spanSec: span2,
|
|
1359
1596
|
segmentCount: segments.length,
|
|
1360
|
-
message: `ok (${segments.length} segments, ${
|
|
1597
|
+
message: `ok (${segments.length} segments, ${span2.toFixed(0)}s span)`
|
|
1361
1598
|
};
|
|
1362
1599
|
}
|
|
1363
1600
|
async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts) {
|
|
1364
1601
|
const validationRetries = opts.validationRetries ?? 1;
|
|
1365
1602
|
const prompt = transcriptionPrompt(ctx);
|
|
1366
|
-
let
|
|
1603
|
+
let temperature = opts.temperature ?? 0.2;
|
|
1604
|
+
let loopAborted = false;
|
|
1605
|
+
let checkedAt = 0;
|
|
1606
|
+
const shouldAbort = (raw) => {
|
|
1607
|
+
if (raw.length - checkedAt < 800) return null;
|
|
1608
|
+
checkedAt = raw.length;
|
|
1609
|
+
if (!tailIsDegenerate(transcriptTextOf(raw))) return null;
|
|
1610
|
+
loopAborted = true;
|
|
1611
|
+
return "degenerate repetition";
|
|
1612
|
+
};
|
|
1613
|
+
let best;
|
|
1614
|
+
const rank = (r) => r.validation.isValid ? 3 : r.error ? 0 : r.validation.degenerate ? 1 : 2;
|
|
1615
|
+
const keep = (r) => {
|
|
1616
|
+
if (!best || rank(r) > rank(best) || rank(r) === rank(best) && r.validation.spanSec > best.validation.spanSec)
|
|
1617
|
+
best = r;
|
|
1618
|
+
};
|
|
1367
1619
|
for (let attempt = 0; attempt <= validationRetries; attempt++) {
|
|
1620
|
+
loopAborted = false;
|
|
1621
|
+
checkedAt = 0;
|
|
1368
1622
|
const gen = await client.generateJson(
|
|
1369
1623
|
model,
|
|
1370
1624
|
prompt,
|
|
1371
1625
|
[{ path: chunkPath }],
|
|
1372
1626
|
TRANSCRIPT_SCHEMA,
|
|
1373
1627
|
{
|
|
1374
|
-
temperature
|
|
1628
|
+
temperature,
|
|
1375
1629
|
maxRetries: 3,
|
|
1376
1630
|
logKind: "transcribe",
|
|
1377
|
-
logChunk: ctx.index - 1
|
|
1631
|
+
logChunk: ctx.index - 1,
|
|
1632
|
+
shouldAbort
|
|
1378
1633
|
}
|
|
1379
1634
|
);
|
|
1380
1635
|
if (gen.error || !gen.data) {
|
|
1381
|
-
|
|
1636
|
+
keep({
|
|
1382
1637
|
segments: [],
|
|
1383
1638
|
raw: gen.raw,
|
|
1384
1639
|
usage: gen.usage,
|
|
1385
1640
|
validation: {
|
|
1386
1641
|
isValid: false,
|
|
1642
|
+
degenerate: loopAborted,
|
|
1387
1643
|
spanSec: 0,
|
|
1388
1644
|
segmentCount: 0,
|
|
1389
1645
|
message: gen.error || "no data"
|
|
1390
1646
|
},
|
|
1391
1647
|
error: gen.error
|
|
1392
|
-
};
|
|
1648
|
+
});
|
|
1393
1649
|
logger.warn(
|
|
1394
1650
|
`[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`
|
|
1395
1651
|
);
|
|
1652
|
+
if (loopAborted) temperature = Math.min(1, temperature + 0.3);
|
|
1396
1653
|
continue;
|
|
1397
1654
|
}
|
|
1398
1655
|
const { segments, dropped } = parseLlmSegments(gen.data, chunkStartSec);
|
|
1399
1656
|
const v = validate(segments, opts.chunkDurationSec);
|
|
1400
|
-
|
|
1657
|
+
const result = { segments, raw: gen.raw, usage: gen.usage, validation: v };
|
|
1658
|
+
keep(result);
|
|
1401
1659
|
if (v.isValid) {
|
|
1402
1660
|
logger.info(
|
|
1403
1661
|
`[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`
|
|
1404
1662
|
);
|
|
1405
|
-
return
|
|
1663
|
+
return result;
|
|
1406
1664
|
}
|
|
1407
1665
|
logger.warn(
|
|
1408
1666
|
`[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`
|
|
1409
1667
|
);
|
|
1668
|
+
if (v.degenerate) temperature = Math.min(1, temperature + 0.3);
|
|
1410
1669
|
}
|
|
1411
1670
|
logger.error(
|
|
1412
1671
|
`[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`
|
|
1413
1672
|
);
|
|
1414
|
-
return
|
|
1673
|
+
return best;
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1676
|
+
// src/transcribe/grounding.ts
|
|
1677
|
+
var MIN_GROUNDED_PRECISION = 0.3;
|
|
1678
|
+
var MIN_TOKENS = 30;
|
|
1679
|
+
var MAX_SCRIPT_SHARE_GAP = 0.2;
|
|
1680
|
+
var STOP_WORDS = Object.fromEntries(
|
|
1681
|
+
"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])
|
|
1682
|
+
);
|
|
1683
|
+
var NON_LATIN = /[^\u0000-\u024F\u2000-\u206F]/u;
|
|
1684
|
+
function contentTokens(words) {
|
|
1685
|
+
const bag = /* @__PURE__ */ new Map();
|
|
1686
|
+
for (const w of words) {
|
|
1687
|
+
const t = w.toLowerCase().replace(/^[^\p{L}\p{N}']+|[^\p{L}\p{N}']+$/gu, "").replace(/^'+|'+$/g, "");
|
|
1688
|
+
if (t && !STOP_WORDS[t]) bag.set(t, (bag.get(t) ?? 0) + 1);
|
|
1689
|
+
}
|
|
1690
|
+
return bag;
|
|
1691
|
+
}
|
|
1692
|
+
function chunkGrounding(segments, asrWords, start, end) {
|
|
1693
|
+
const asrInRange = asrWords.filter((w) => w.start >= start && w.start < end);
|
|
1694
|
+
const llmWords = segments.map((s) => s.text.replace(/\[[^\]]*\]/g, " ")).join(" ").split(/\s+/).filter(Boolean);
|
|
1695
|
+
const llm = contentTokens(llmWords);
|
|
1696
|
+
const asr2 = contentTokens(asrInRange.map((w) => w.text));
|
|
1697
|
+
let llmTokens = 0;
|
|
1698
|
+
let asrTokens = 0;
|
|
1699
|
+
let shared = 0;
|
|
1700
|
+
for (const n of llm.values()) llmTokens += n;
|
|
1701
|
+
for (const n of asr2.values()) asrTokens += n;
|
|
1702
|
+
for (const [t, n] of llm) shared += Math.min(n, asr2.get(t) ?? 0);
|
|
1703
|
+
const share = (ws) => ws.length ? ws.filter((w) => NON_LATIN.test(w)).length / ws.length : 0;
|
|
1704
|
+
const scriptsMatch = Math.abs(share(llmWords) - share(asrInRange.map((w) => w.text))) <= MAX_SCRIPT_SHARE_GAP;
|
|
1705
|
+
const judged = llmTokens >= MIN_TOKENS && asrTokens >= MIN_TOKENS && scriptsMatch;
|
|
1706
|
+
const precision = llmTokens ? shared / llmTokens : 1;
|
|
1707
|
+
return {
|
|
1708
|
+
llmTokens,
|
|
1709
|
+
asrTokens,
|
|
1710
|
+
precision,
|
|
1711
|
+
judged,
|
|
1712
|
+
grounded: !judged || precision >= MIN_GROUNDED_PRECISION
|
|
1713
|
+
};
|
|
1415
1714
|
}
|
|
1416
1715
|
|
|
1417
1716
|
// src/align/normalize.ts
|
|
1418
|
-
function
|
|
1419
|
-
return word.toLowerCase().replace(
|
|
1717
|
+
function normalizeWord(word) {
|
|
1718
|
+
return word.normalize("NFKC").toLowerCase().replace(/[’‘`]/g, "'").replace(/^[^\p{L}\p{M}\p{N}']+|[^\p{L}\p{M}\p{N}']+$/gu, "").replace(/^'+|'+$/g, "");
|
|
1420
1719
|
}
|
|
1421
1720
|
function tokenize(text) {
|
|
1422
1721
|
const out = [];
|
|
1423
1722
|
for (const raw of text.split(/\s+/)) {
|
|
1424
1723
|
if (!raw) continue;
|
|
1425
|
-
const norm2 =
|
|
1724
|
+
const norm2 = normalizeWord(raw);
|
|
1426
1725
|
if (norm2) out.push({ original: raw, norm: norm2 });
|
|
1427
1726
|
}
|
|
1428
1727
|
return out;
|
|
1429
1728
|
}
|
|
1430
1729
|
function fuzzyEqual(a, b) {
|
|
1431
1730
|
if (a === b) return true;
|
|
1731
|
+
if (!a || !b) return false;
|
|
1432
1732
|
if (Math.abs(a.length - b.length) <= 1) {
|
|
1433
1733
|
return editDistanceChars(a, b, 1) <= 1;
|
|
1434
1734
|
}
|
|
@@ -1454,16 +1754,92 @@ function editDistanceChars(a, b, max) {
|
|
|
1454
1754
|
return prev[n];
|
|
1455
1755
|
}
|
|
1456
1756
|
|
|
1757
|
+
// src/transcribe/coverage.ts
|
|
1758
|
+
var MIN_COVERAGE_RATIO = 0.6;
|
|
1759
|
+
var MIN_ASR_WORDS = 200;
|
|
1760
|
+
function chunkCoverage(segments, asrWords, start, end) {
|
|
1761
|
+
const llmWords = segments.reduce(
|
|
1762
|
+
(n, s) => n + tokenize(s.text.replace(/\[[^\]]*\]/g, " ")).length,
|
|
1763
|
+
0
|
|
1764
|
+
);
|
|
1765
|
+
const asrCount = asrWords.reduce(
|
|
1766
|
+
(n, w) => n + (w.start >= start && w.start < end ? tokenize(w.text).length : 0),
|
|
1767
|
+
0
|
|
1768
|
+
);
|
|
1769
|
+
const ratio2 = asrCount ? llmWords / asrCount : Infinity;
|
|
1770
|
+
const judged = asrCount >= MIN_ASR_WORDS;
|
|
1771
|
+
return {
|
|
1772
|
+
llmWords,
|
|
1773
|
+
asrWords: asrCount,
|
|
1774
|
+
ratio: ratio2,
|
|
1775
|
+
judged,
|
|
1776
|
+
low: judged && ratio2 < MIN_COVERAGE_RATIO
|
|
1777
|
+
};
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
// src/core/retranscribe.ts
|
|
1781
|
+
import { existsSync as existsSync3 } from "fs";
|
|
1782
|
+
var HALF_OVERLAP_SEC = 5;
|
|
1783
|
+
async function transcribeInHalves(opts) {
|
|
1784
|
+
const { chunk } = opts;
|
|
1785
|
+
const mid = (chunk.start + chunk.end) / 2;
|
|
1786
|
+
const halves = [
|
|
1787
|
+
{ name: "a", from: chunk.start, to: Math.min(chunk.end, mid + HALF_OVERLAP_SEC) },
|
|
1788
|
+
{ name: "b", from: Math.max(chunk.start, mid - HALF_OVERLAP_SEC), to: chunk.end }
|
|
1789
|
+
];
|
|
1790
|
+
const results = [];
|
|
1791
|
+
for (const h of halves) {
|
|
1792
|
+
const path = `${opts.pathPrefix}_half_${h.name}.mp3`;
|
|
1793
|
+
if (!existsSync3(path))
|
|
1794
|
+
await extractChunk(opts.audioPath, path, h.from, h.to, opts.audioOpts);
|
|
1795
|
+
results.push(
|
|
1796
|
+
await transcribeChunk(opts.client, opts.model, path, h.from, opts.ctx, {
|
|
1797
|
+
chunkDurationSec: h.to - h.from,
|
|
1798
|
+
validationRetries: 0
|
|
1799
|
+
})
|
|
1800
|
+
);
|
|
1801
|
+
}
|
|
1802
|
+
const [a, b] = results;
|
|
1803
|
+
const center = (s) => (s.startSec + s.endSec) / 2;
|
|
1804
|
+
const segments = [
|
|
1805
|
+
...a.segments.filter((s) => center(s) < mid),
|
|
1806
|
+
...b.segments.filter((s) => center(s) >= mid)
|
|
1807
|
+
];
|
|
1808
|
+
const first = segments[0];
|
|
1809
|
+
const last = segments[segments.length - 1];
|
|
1810
|
+
return {
|
|
1811
|
+
segments,
|
|
1812
|
+
raw: JSON.stringify({ halves: [a.raw, b.raw] }),
|
|
1813
|
+
usage: {
|
|
1814
|
+
inputTokens: a.usage.inputTokens + b.usage.inputTokens,
|
|
1815
|
+
outputTokens: a.usage.outputTokens + b.usage.outputTokens,
|
|
1816
|
+
thoughtTokens: (a.usage.thoughtTokens ?? 0) + (b.usage.thoughtTokens ?? 0),
|
|
1817
|
+
totalTokens: a.usage.totalTokens + b.usage.totalTokens
|
|
1818
|
+
},
|
|
1819
|
+
validation: {
|
|
1820
|
+
isValid: a.validation.isValid && b.validation.isValid,
|
|
1821
|
+
degenerate: Boolean(a.validation.degenerate || b.validation.degenerate),
|
|
1822
|
+
spanSec: first && last ? last.endSec - first.startSec : 0,
|
|
1823
|
+
segmentCount: segments.length,
|
|
1824
|
+
message: `halves: ${a.validation.message} | ${b.validation.message}`
|
|
1825
|
+
},
|
|
1826
|
+
...a.error || b.error ? { error: [a.error, b.error].filter(Boolean).join(" | ") } : {}
|
|
1827
|
+
};
|
|
1828
|
+
}
|
|
1829
|
+
|
|
1457
1830
|
// src/align/edit-distance.ts
|
|
1458
1831
|
var INDEL = 2;
|
|
1832
|
+
var OUT_OF_WINDOW = { cost: 2 * INDEL + 1, fuzzy: false };
|
|
1459
1833
|
function matchCost(a, b) {
|
|
1834
|
+
if (a.window && b.start !== void 0 && (b.start < a.window.lo || b.start > a.window.hi))
|
|
1835
|
+
return OUT_OF_WINDOW;
|
|
1460
1836
|
if (a.norm === b.norm) return { cost: 0, fuzzy: false };
|
|
1461
1837
|
if (fuzzyEqual(a.norm, b.norm)) return { cost: 1, fuzzy: true };
|
|
1462
1838
|
return { cost: 2, fuzzy: false };
|
|
1463
1839
|
}
|
|
1464
|
-
function alignWords(llm,
|
|
1840
|
+
function alignWords(llm, asr2) {
|
|
1465
1841
|
const m = llm.length;
|
|
1466
|
-
const n =
|
|
1842
|
+
const n = asr2.length;
|
|
1467
1843
|
const dp = new Array(m + 1);
|
|
1468
1844
|
for (let i2 = 0; i2 <= m; i2++) {
|
|
1469
1845
|
const row = new Int32Array(n + 1);
|
|
@@ -1476,7 +1852,7 @@ function alignWords(llm, asr) {
|
|
|
1476
1852
|
const row = dp[i2];
|
|
1477
1853
|
const prev = dp[i2 - 1];
|
|
1478
1854
|
for (let j2 = 1; j2 <= n; j2++) {
|
|
1479
|
-
const { cost } = matchCost(llm[i2 - 1],
|
|
1855
|
+
const { cost } = matchCost(llm[i2 - 1], asr2[j2 - 1]);
|
|
1480
1856
|
const sub = prev[j2 - 1] + cost;
|
|
1481
1857
|
const ins2 = prev[j2] + INDEL;
|
|
1482
1858
|
const del2 = row[j2 - 1] + INDEL;
|
|
@@ -1494,7 +1870,7 @@ function alignWords(llm, asr) {
|
|
|
1494
1870
|
while (i > 0 || j > 0) {
|
|
1495
1871
|
const cur = dp[i];
|
|
1496
1872
|
if (i > 0 && j > 0) {
|
|
1497
|
-
const { cost } = matchCost(llm[i - 1],
|
|
1873
|
+
const { cost } = matchCost(llm[i - 1], asr2[j - 1]);
|
|
1498
1874
|
const sub = dp[i - 1][j - 1] + cost;
|
|
1499
1875
|
if (cur[j] === sub) {
|
|
1500
1876
|
if (cost === 0) {
|
|
@@ -1534,19 +1910,26 @@ function alignWords(llm, asr) {
|
|
|
1534
1910
|
}
|
|
1535
1911
|
|
|
1536
1912
|
// src/align/aligner.ts
|
|
1913
|
+
var WINDOW_SLACK_SEC = 2;
|
|
1914
|
+
var UNANCHORED_MAX_DRIFT_SEC = 15;
|
|
1915
|
+
var STRETCH_MIN_SEC = 30;
|
|
1916
|
+
var STRETCH_SEC_PER_WORD = 3;
|
|
1917
|
+
var MAX_INNER_GAP_SEC = 8;
|
|
1918
|
+
var SPOKEN_SEC_PER_WORD = 0.5;
|
|
1919
|
+
var UNCONFIRMED_MAX_SEC = 5;
|
|
1537
1920
|
function toAsrTokens(words) {
|
|
1538
1921
|
return words.map((w) => ({
|
|
1539
1922
|
text: w.text,
|
|
1540
1923
|
start: w.start,
|
|
1541
1924
|
end: w.end,
|
|
1542
|
-
norm: w.text
|
|
1925
|
+
norm: normalizeWord(w.text)
|
|
1543
1926
|
}));
|
|
1544
1927
|
}
|
|
1545
|
-
function transferTiming(llm,
|
|
1928
|
+
function transferTiming(llm, asr2, ops) {
|
|
1546
1929
|
const times = llm.map(() => ({ start: NaN, end: NaN, matched: false }));
|
|
1547
1930
|
for (const op of ops) {
|
|
1548
1931
|
if (op.type === "match" || op.type === "substitute") {
|
|
1549
|
-
const a =
|
|
1932
|
+
const a = asr2[op.asr];
|
|
1550
1933
|
times[op.llm] = {
|
|
1551
1934
|
start: a.start,
|
|
1552
1935
|
end: a.end,
|
|
@@ -1598,7 +1981,9 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
|
|
|
1598
1981
|
for (const { s, i } of sorted) {
|
|
1599
1982
|
const toks = tokenize(s.text);
|
|
1600
1983
|
const start = flat.length;
|
|
1601
|
-
|
|
1984
|
+
const window = s.chunkStart !== void 0 && s.chunkEnd !== void 0 ? { lo: s.chunkStart - WINDOW_SLACK_SEC, hi: s.chunkEnd + WINDOW_SLACK_SEC } : void 0;
|
|
1985
|
+
for (const t of toks)
|
|
1986
|
+
flat.push({ original: t.original, norm: t.norm, segIdx: i, window });
|
|
1602
1987
|
segRanges.push({ src: i, start, end: flat.length });
|
|
1603
1988
|
}
|
|
1604
1989
|
if (flat.length === 0 || asrWords.length === 0) {
|
|
@@ -1614,17 +1999,17 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
|
|
|
1614
1999
|
sourceIndex: i
|
|
1615
2000
|
}));
|
|
1616
2001
|
}
|
|
1617
|
-
let
|
|
2002
|
+
let asr2 = toAsrTokens(asrWords);
|
|
1618
2003
|
if (margin > 0) {
|
|
1619
2004
|
const lo = sorted[0].s.startSec - margin;
|
|
1620
2005
|
const hi = sorted[sorted.length - 1].s.endSec + margin;
|
|
1621
|
-
|
|
2006
|
+
asr2 = asr2.filter((w) => w.end >= lo && w.start <= hi);
|
|
1622
2007
|
}
|
|
1623
|
-
const result = alignWords(flat,
|
|
1624
|
-
const times = transferTiming(flat,
|
|
2008
|
+
const result = alignWords(flat, asr2);
|
|
2009
|
+
const times = transferTiming(flat, asr2, result.ops);
|
|
1625
2010
|
if (process.env.ALIGN_DEBUG) {
|
|
1626
2011
|
console.error(
|
|
1627
|
-
`[align] flat=${flat.length} asr=${
|
|
2012
|
+
`[align] flat=${flat.length} asr=${asr2.length} exact=${result.exactMatches} fuzzy=${result.fuzzyMatches} subs=${result.substitutions} ins=${result.insertions} del=${result.deletions}`
|
|
1628
2013
|
);
|
|
1629
2014
|
}
|
|
1630
2015
|
const out = [];
|
|
@@ -1643,21 +2028,53 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
|
|
|
1643
2028
|
let end;
|
|
1644
2029
|
let timingSource;
|
|
1645
2030
|
const confidence = tokenCount ? exact / tokenCount : 0;
|
|
1646
|
-
|
|
2031
|
+
const unanchoredDrift = segOps.length === 0 && firstTimed ? Math.abs(firstTimed.start - s.startSec) : 0;
|
|
2032
|
+
if (firstTimed && lastTimed && unanchoredDrift <= UNANCHORED_MAX_DRIFT_SEC) {
|
|
1647
2033
|
start = firstTimed.start;
|
|
1648
2034
|
end = lastTimed.end;
|
|
1649
2035
|
timingSource = confidence >= confThreshold ? "aligned" : "interpolated";
|
|
2036
|
+
if (end - start > Math.max(STRETCH_MIN_SEC, STRETCH_SEC_PER_WORD * tokenCount)) {
|
|
2037
|
+
const runs = [];
|
|
2038
|
+
for (const t of segTimes) {
|
|
2039
|
+
if (isNaN(t.start)) continue;
|
|
2040
|
+
const run2 = runs[runs.length - 1];
|
|
2041
|
+
if (run2 && t.start - run2.end <= MAX_INNER_GAP_SEC) {
|
|
2042
|
+
run2.end = Math.max(run2.end, t.end);
|
|
2043
|
+
if (t.matched) run2.matched++;
|
|
2044
|
+
} else {
|
|
2045
|
+
runs.push({ start: t.start, end: t.end, matched: t.matched ? 1 : 0 });
|
|
2046
|
+
}
|
|
2047
|
+
}
|
|
2048
|
+
const best = runs.reduce(
|
|
2049
|
+
(a, b) => b.matched > a.matched || b.matched === a.matched && Math.abs(b.start - s.startSec) < Math.abs(a.start - s.startSec) ? b : a
|
|
2050
|
+
);
|
|
2051
|
+
start = best.start;
|
|
2052
|
+
end = best.end;
|
|
2053
|
+
}
|
|
2054
|
+
const spoken = Math.max(1, SPOKEN_SEC_PER_WORD * tokenCount);
|
|
2055
|
+
if (exact === 0 && end - start > Math.max(UNCONFIRMED_MAX_SEC, 3 * spoken)) {
|
|
2056
|
+
end = start + spoken;
|
|
2057
|
+
}
|
|
1650
2058
|
} else {
|
|
1651
2059
|
start = s.startSec;
|
|
1652
2060
|
end = s.endSec;
|
|
1653
2061
|
timingSource = "coarse";
|
|
1654
2062
|
}
|
|
1655
|
-
const
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
2063
|
+
const step = timingSource === "coarse" && tokenCount ? (end - start) / tokenCount : 0;
|
|
2064
|
+
const inside = (x) => Math.min(Math.max(x, start), end);
|
|
2065
|
+
const words = segTimes.map(
|
|
2066
|
+
(t, idx) => timingSource === "coarse" ? {
|
|
2067
|
+
text: flat[range.start + idx].original,
|
|
2068
|
+
start: start + step * idx,
|
|
2069
|
+
end: start + step * (idx + 1),
|
|
2070
|
+
matched: false
|
|
2071
|
+
} : {
|
|
2072
|
+
text: flat[range.start + idx].original,
|
|
2073
|
+
start: isNaN(t.start) ? start : inside(t.start),
|
|
2074
|
+
end: isNaN(t.end) ? end : inside(t.end),
|
|
2075
|
+
matched: t.matched
|
|
2076
|
+
}
|
|
2077
|
+
);
|
|
1661
2078
|
out.push({
|
|
1662
2079
|
speaker: s.speaker,
|
|
1663
2080
|
start,
|
|
@@ -1672,23 +2089,90 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
|
|
|
1672
2089
|
}
|
|
1673
2090
|
return out;
|
|
1674
2091
|
}
|
|
2092
|
+
var CLOCK_ANCHOR_MIN_WORDS = 3;
|
|
2093
|
+
var CLOCK_ANCHOR_MIN_SHARE = 0.6;
|
|
2094
|
+
function toAsrClock(segments, asrWords) {
|
|
2095
|
+
if (!asrWords.length) return segments;
|
|
2096
|
+
const chunks = /* @__PURE__ */ new Map();
|
|
2097
|
+
for (const s of segments) {
|
|
2098
|
+
if (s.chunkIndex === void 0) continue;
|
|
2099
|
+
const group = chunks.get(s.chunkIndex);
|
|
2100
|
+
if (group) group.push(s);
|
|
2101
|
+
else chunks.set(s.chunkIndex, [s]);
|
|
2102
|
+
}
|
|
2103
|
+
const moved = /* @__PURE__ */ new Map();
|
|
2104
|
+
for (const group of chunks.values()) {
|
|
2105
|
+
const lo = Math.min(...group.map((s) => s.chunkStart ?? s.startSec)) - WINDOW_SLACK_SEC;
|
|
2106
|
+
const hi = Math.max(...group.map((s) => s.chunkEnd ?? s.endSec)) + WINDOW_SLACK_SEC;
|
|
2107
|
+
const aligned = alignSegments(
|
|
2108
|
+
group,
|
|
2109
|
+
asrWords.filter((w) => w.end >= lo && w.start <= hi)
|
|
2110
|
+
);
|
|
2111
|
+
const shifts = aligned.map(
|
|
2112
|
+
(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
|
|
2113
|
+
);
|
|
2114
|
+
for (let k = 0; k < aligned.length; k++) {
|
|
2115
|
+
let shift = shifts[k];
|
|
2116
|
+
for (let r = 1; shift === void 0 && r < aligned.length; r++) {
|
|
2117
|
+
shift = shifts[k - r] ?? shifts[k + r];
|
|
2118
|
+
}
|
|
2119
|
+
const s = group[aligned[k].sourceIndex];
|
|
2120
|
+
moved.set(s, {
|
|
2121
|
+
...s,
|
|
2122
|
+
startSec: s.startSec + (shift ?? 0),
|
|
2123
|
+
endSec: s.endSec + (shift ?? 0)
|
|
2124
|
+
});
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
return segments.map((s) => moved.get(s) ?? s);
|
|
2128
|
+
}
|
|
1675
2129
|
|
|
1676
2130
|
// src/align/fill-gaps.ts
|
|
1677
2131
|
var MIN_GAP_SEC = 0.8;
|
|
1678
2132
|
var MIN_WORDS = 1;
|
|
1679
|
-
|
|
1680
|
-
|
|
2133
|
+
var HEAD_SLACK_WORDS = 5;
|
|
2134
|
+
function utteranceAt(utts, t) {
|
|
2135
|
+
let lo = 0;
|
|
2136
|
+
let hi = utts.length - 1;
|
|
2137
|
+
let found = -1;
|
|
2138
|
+
while (lo <= hi) {
|
|
2139
|
+
const mid = lo + hi >> 1;
|
|
2140
|
+
if (utts[mid].start <= t) {
|
|
2141
|
+
found = mid;
|
|
2142
|
+
lo = mid + 1;
|
|
2143
|
+
} else {
|
|
2144
|
+
hi = mid - 1;
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
return found >= 0 && t <= utts[found].end ? found : -1;
|
|
2148
|
+
}
|
|
2149
|
+
function dominantSpeaker(utts, start, end) {
|
|
2150
|
+
let best = utts[0]?.speaker || "speaker_?";
|
|
2151
|
+
let bestOv = 0;
|
|
2152
|
+
for (const u of utts) {
|
|
2153
|
+
const ov = Math.max(0, Math.min(end, u.end) - Math.max(start, u.start));
|
|
2154
|
+
if (ov > bestOv) {
|
|
2155
|
+
bestOv = ov;
|
|
2156
|
+
best = u.speaker;
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
return best;
|
|
1681
2160
|
}
|
|
1682
2161
|
function fillAsrGaps(segments, asrWords, asrUtterances) {
|
|
1683
2162
|
if (!asrWords.length) return segments;
|
|
1684
2163
|
const sorted = [...segments].sort((a, b) => a.start - b.start);
|
|
2164
|
+
const utts = [...asrUtterances].sort((a, b) => a.start - b.start);
|
|
1685
2165
|
const ranges = [];
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
2166
|
+
if (!sorted.length) {
|
|
2167
|
+
ranges.push([0, Infinity, void 0]);
|
|
2168
|
+
} else {
|
|
2169
|
+
if (sorted[0].start > 0) ranges.push([0, sorted[0].start, sorted[0]]);
|
|
2170
|
+
let coveredTo = sorted[0].end;
|
|
2171
|
+
for (const next of sorted.slice(1)) {
|
|
2172
|
+
if (next.start > coveredTo) ranges.push([coveredTo, next.start, next]);
|
|
2173
|
+
coveredTo = Math.max(coveredTo, next.end);
|
|
2174
|
+
}
|
|
2175
|
+
ranges.push([coveredTo, Infinity, void 0]);
|
|
1692
2176
|
}
|
|
1693
2177
|
const filled = [];
|
|
1694
2178
|
for (const [gs, ge, following] of ranges) {
|
|
@@ -1696,38 +2180,44 @@ function fillAsrGaps(segments, asrWords, asrUtterances) {
|
|
|
1696
2180
|
const words = asrWords.filter((w) => w.start >= gs && w.start < ge);
|
|
1697
2181
|
if (words.length < MIN_WORDS) continue;
|
|
1698
2182
|
if (following) {
|
|
1699
|
-
const
|
|
1700
|
-
const
|
|
1701
|
-
(
|
|
2183
|
+
const gapNorms = words.map((w) => normalizeWord(w.text)).filter(Boolean);
|
|
2184
|
+
const head = new Set(
|
|
2185
|
+
tokenize(following.text).slice(0, gapNorms.length + HEAD_SLACK_WORDS).map((t) => t.norm)
|
|
1702
2186
|
);
|
|
1703
|
-
const covered = gapNorms.filter((n) =>
|
|
1704
|
-
if (covered / gapNorms.
|
|
2187
|
+
const covered = gapNorms.filter((n) => head.has(n)).length;
|
|
2188
|
+
if (covered / gapNorms.length >= 0.6) continue;
|
|
1705
2189
|
}
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
const
|
|
1710
|
-
if (
|
|
1711
|
-
|
|
1712
|
-
|
|
2190
|
+
const runs = [];
|
|
2191
|
+
for (const w of words) {
|
|
2192
|
+
const u = utteranceAt(utts, w.start);
|
|
2193
|
+
const cur = runs[runs.length - 1];
|
|
2194
|
+
if (cur && (u === -1 || u === cur.utt || cur.utt === -1)) {
|
|
2195
|
+
cur.words.push(w);
|
|
2196
|
+
if (cur.utt === -1) cur.utt = u;
|
|
2197
|
+
} else {
|
|
2198
|
+
runs.push({ words: [w], utt: u });
|
|
1713
2199
|
}
|
|
1714
2200
|
}
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
2201
|
+
for (const run2 of runs) {
|
|
2202
|
+
const first = run2.words[0];
|
|
2203
|
+
const last = run2.words[run2.words.length - 1];
|
|
2204
|
+
filled.push({
|
|
2205
|
+
speaker: run2.utt >= 0 ? utts[run2.utt].speaker : dominantSpeaker(utts, first.start, last.end),
|
|
2206
|
+
start: first.start,
|
|
2207
|
+
end: last.end,
|
|
2208
|
+
text: run2.words.map((w) => w.text).join(" "),
|
|
2209
|
+
tone: [],
|
|
2210
|
+
confidence: 0,
|
|
2211
|
+
timingSource: "timestamped",
|
|
2212
|
+
words: run2.words.map((w) => ({
|
|
2213
|
+
text: w.text,
|
|
2214
|
+
start: w.start,
|
|
2215
|
+
end: w.end,
|
|
2216
|
+
matched: true
|
|
2217
|
+
})),
|
|
2218
|
+
sourceIndex: -1
|
|
2219
|
+
});
|
|
2220
|
+
}
|
|
1731
2221
|
}
|
|
1732
2222
|
if (!filled.length) return sorted;
|
|
1733
2223
|
return [...sorted, ...filled].sort((a, b) => a.start - b.start);
|
|
@@ -1979,125 +2469,6 @@ function splitMixedVoiceSegments(segments, utterances) {
|
|
|
1979
2469
|
return out.sort((a, b) => a.start - b.start);
|
|
1980
2470
|
}
|
|
1981
2471
|
|
|
1982
|
-
// src/providers/openai-compat.ts
|
|
1983
|
-
var PROVIDER_BASE = {
|
|
1984
|
-
deepseek: "https://api.deepseek.com/v1",
|
|
1985
|
-
groq: "https://api.groq.com/openai/v1",
|
|
1986
|
-
openai: "https://api.openai.com/v1"
|
|
1987
|
-
};
|
|
1988
|
-
var OpenAICompatClient = class _OpenAICompatClient {
|
|
1989
|
-
constructor(baseUrl, apiKey, defaultModel, providerName = "openai-compat") {
|
|
1990
|
-
this.baseUrl = baseUrl;
|
|
1991
|
-
this.apiKey = apiKey;
|
|
1992
|
-
this.defaultModel = defaultModel;
|
|
1993
|
-
this.providerName = providerName;
|
|
1994
|
-
}
|
|
1995
|
-
baseUrl;
|
|
1996
|
-
apiKey;
|
|
1997
|
-
defaultModel;
|
|
1998
|
-
providerName;
|
|
1999
|
-
static fromProvider(provider, apiKey, defaultModel) {
|
|
2000
|
-
const base = PROVIDER_BASE[provider] ?? provider;
|
|
2001
|
-
return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
|
|
2002
|
-
}
|
|
2003
|
-
async chat(model, messages, opts = {}) {
|
|
2004
|
-
const m = model ?? this.defaultModel;
|
|
2005
|
-
const maxRetries = opts.maxRetries ?? 5;
|
|
2006
|
-
const body = {
|
|
2007
|
-
model: m,
|
|
2008
|
-
messages,
|
|
2009
|
-
temperature: opts.temperature ?? 0.2
|
|
2010
|
-
};
|
|
2011
|
-
if (opts.maxTokens) body.max_tokens = opts.maxTokens;
|
|
2012
|
-
if (opts.responseJson) {
|
|
2013
|
-
body.response_format = { type: "json_object" };
|
|
2014
|
-
}
|
|
2015
|
-
if (this.providerName === "gemini") {
|
|
2016
|
-
body.reasoning_effort = "low";
|
|
2017
|
-
}
|
|
2018
|
-
let lastError;
|
|
2019
|
-
const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
|
|
2020
|
-
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
2021
|
-
const t0 = Date.now();
|
|
2022
|
-
try {
|
|
2023
|
-
const res = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
2024
|
-
method: "POST",
|
|
2025
|
-
headers: {
|
|
2026
|
-
"Content-Type": "application/json",
|
|
2027
|
-
Authorization: `Bearer ${this.apiKey}`
|
|
2028
|
-
},
|
|
2029
|
-
body: JSON.stringify(body)
|
|
2030
|
-
});
|
|
2031
|
-
if (!res.ok) {
|
|
2032
|
-
const txt = await res.text();
|
|
2033
|
-
throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
|
|
2034
|
-
}
|
|
2035
|
-
const data = await res.json();
|
|
2036
|
-
const text = data.choices?.[0]?.message?.content ?? "";
|
|
2037
|
-
const usage = {
|
|
2038
|
-
inputTokens: data.usage?.prompt_tokens ?? 0,
|
|
2039
|
-
outputTokens: data.usage?.completion_tokens ?? 0
|
|
2040
|
-
};
|
|
2041
|
-
logLlmCall({
|
|
2042
|
-
ts: new Date(t0).toISOString(),
|
|
2043
|
-
provider: this.providerName,
|
|
2044
|
-
model: m,
|
|
2045
|
-
kind: opts.logKind,
|
|
2046
|
-
prompt: promptStr,
|
|
2047
|
-
response: text,
|
|
2048
|
-
usage,
|
|
2049
|
-
durationMs: Date.now() - t0,
|
|
2050
|
-
attempt: attempt + 1
|
|
2051
|
-
});
|
|
2052
|
-
return { text, usage };
|
|
2053
|
-
} catch (err) {
|
|
2054
|
-
lastError = err instanceof Error ? err.message : String(err);
|
|
2055
|
-
if (body.response_format && /response_format/i.test(lastError)) {
|
|
2056
|
-
delete body.response_format;
|
|
2057
|
-
continue;
|
|
2058
|
-
}
|
|
2059
|
-
if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
|
|
2060
|
-
delete body.reasoning_effort;
|
|
2061
|
-
continue;
|
|
2062
|
-
}
|
|
2063
|
-
logLlmCall({
|
|
2064
|
-
ts: new Date(t0).toISOString(),
|
|
2065
|
-
provider: this.providerName,
|
|
2066
|
-
model: m,
|
|
2067
|
-
kind: opts.logKind,
|
|
2068
|
-
prompt: promptStr,
|
|
2069
|
-
response: "",
|
|
2070
|
-
durationMs: Date.now() - t0,
|
|
2071
|
-
attempt: attempt + 1,
|
|
2072
|
-
error: lastError
|
|
2073
|
-
});
|
|
2074
|
-
if (attempt < maxRetries - 1)
|
|
2075
|
-
await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
|
|
2076
|
-
}
|
|
2077
|
-
}
|
|
2078
|
-
return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
|
|
2079
|
-
}
|
|
2080
|
-
async chatJson(model, messages, opts = {}) {
|
|
2081
|
-
let lastRaw = "";
|
|
2082
|
-
let lastError;
|
|
2083
|
-
for (let attempt = 0; attempt < 2; attempt++) {
|
|
2084
|
-
const res = await this.chat(model, messages, { ...opts, responseJson: true });
|
|
2085
|
-
lastRaw = res.text;
|
|
2086
|
-
lastError = res.error;
|
|
2087
|
-
if (res.error || !res.text) continue;
|
|
2088
|
-
try {
|
|
2089
|
-
let txt = res.text.trim();
|
|
2090
|
-
const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
|
|
2091
|
-
if (fence && fence[1]) txt = fence[1];
|
|
2092
|
-
return { data: JSON.parse(txt), raw: res.text };
|
|
2093
|
-
} catch (err) {
|
|
2094
|
-
lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
|
|
2095
|
-
}
|
|
2096
|
-
}
|
|
2097
|
-
return { data: null, raw: lastRaw, error: lastError };
|
|
2098
|
-
}
|
|
2099
|
-
};
|
|
2100
|
-
|
|
2101
2472
|
// src/diarize/identify.ts
|
|
2102
2473
|
var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
|
|
2103
2474
|
function buildTranscriptExcerpt(segments, speakers) {
|
|
@@ -2363,7 +2734,8 @@ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts
|
|
|
2363
2734
|
wantB ? runPass(reasonerB) : Promise.resolve(void 0)
|
|
2364
2735
|
]);
|
|
2365
2736
|
const passFailed = (r) => !!r && r.speakers.length === 0 && /fetch failed|HTTP \d|network|ENOTFOUND|JSON parse|no response/i.test(r.reasoning);
|
|
2366
|
-
|
|
2737
|
+
const allPassesFailed = passFailed(resA) && (!wantB || passFailed(resB));
|
|
2738
|
+
if (allPassesFailed) {
|
|
2367
2739
|
logger.warn(
|
|
2368
2740
|
`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).`
|
|
2369
2741
|
);
|
|
@@ -2463,14 +2835,168 @@ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts
|
|
|
2463
2835
|
);
|
|
2464
2836
|
}
|
|
2465
2837
|
}
|
|
2466
|
-
return {
|
|
2467
|
-
nameMap,
|
|
2468
|
-
decisions,
|
|
2469
|
-
tripwires,
|
|
2470
|
-
passA: { ...resA, model: reasonerA.model },
|
|
2471
|
-
passB: resB ? { ...resB, model: reasonerB.model } : void 0
|
|
2472
|
-
|
|
2473
|
-
}
|
|
2838
|
+
return {
|
|
2839
|
+
nameMap,
|
|
2840
|
+
decisions,
|
|
2841
|
+
tripwires,
|
|
2842
|
+
passA: { ...resA, model: reasonerA.model },
|
|
2843
|
+
passB: resB ? { ...resB, model: reasonerB.model } : void 0,
|
|
2844
|
+
allPassesFailed
|
|
2845
|
+
};
|
|
2846
|
+
}
|
|
2847
|
+
|
|
2848
|
+
// src/providers/openai-compat.ts
|
|
2849
|
+
async function chatJsonWith(client, model, messages, opts) {
|
|
2850
|
+
let lastRaw = "";
|
|
2851
|
+
let lastError;
|
|
2852
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
2853
|
+
const res = await client.chat(model, messages, { ...opts, responseJson: true });
|
|
2854
|
+
lastRaw = res.text;
|
|
2855
|
+
lastError = res.error;
|
|
2856
|
+
if (res.error || !res.text) continue;
|
|
2857
|
+
try {
|
|
2858
|
+
let txt = res.text.trim();
|
|
2859
|
+
const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
|
|
2860
|
+
if (fence && fence[1]) txt = fence[1];
|
|
2861
|
+
return { data: JSON.parse(txt), raw: res.text };
|
|
2862
|
+
} catch (err) {
|
|
2863
|
+
lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
|
|
2864
|
+
}
|
|
2865
|
+
}
|
|
2866
|
+
return { data: null, raw: lastRaw, error: lastError };
|
|
2867
|
+
}
|
|
2868
|
+
var PROVIDER_BASE = {
|
|
2869
|
+
deepseek: "https://api.deepseek.com/v1",
|
|
2870
|
+
groq: "https://api.groq.com/openai/v1",
|
|
2871
|
+
openai: "https://api.openai.com/v1"
|
|
2872
|
+
};
|
|
2873
|
+
var OpenAICompatClient = class _OpenAICompatClient {
|
|
2874
|
+
constructor(baseUrl, apiKey, defaultModel, providerName = "openai-compat") {
|
|
2875
|
+
this.baseUrl = baseUrl;
|
|
2876
|
+
this.apiKey = apiKey;
|
|
2877
|
+
this.defaultModel = defaultModel;
|
|
2878
|
+
this.providerName = providerName;
|
|
2879
|
+
}
|
|
2880
|
+
baseUrl;
|
|
2881
|
+
apiKey;
|
|
2882
|
+
defaultModel;
|
|
2883
|
+
providerName;
|
|
2884
|
+
static fromProvider(provider, apiKey, defaultModel) {
|
|
2885
|
+
const base = PROVIDER_BASE[provider] ?? provider;
|
|
2886
|
+
return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
|
|
2887
|
+
}
|
|
2888
|
+
async chat(model, messages, opts = {}) {
|
|
2889
|
+
const m = model ?? this.defaultModel;
|
|
2890
|
+
const maxRetries = opts.maxRetries ?? 5;
|
|
2891
|
+
const body = {
|
|
2892
|
+
model: m,
|
|
2893
|
+
messages,
|
|
2894
|
+
temperature: opts.temperature ?? 0.2
|
|
2895
|
+
};
|
|
2896
|
+
if (opts.maxTokens) body.max_tokens = opts.maxTokens;
|
|
2897
|
+
if (opts.responseJson) {
|
|
2898
|
+
body.response_format = { type: "json_object" };
|
|
2899
|
+
}
|
|
2900
|
+
if (this.providerName === "gemini") {
|
|
2901
|
+
body.reasoning_effort = "low";
|
|
2902
|
+
}
|
|
2903
|
+
let lastError;
|
|
2904
|
+
const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
|
|
2905
|
+
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
2906
|
+
const t0 = Date.now();
|
|
2907
|
+
try {
|
|
2908
|
+
const res = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
2909
|
+
method: "POST",
|
|
2910
|
+
headers: {
|
|
2911
|
+
"Content-Type": "application/json",
|
|
2912
|
+
Authorization: `Bearer ${this.apiKey}`
|
|
2913
|
+
},
|
|
2914
|
+
body: JSON.stringify(body)
|
|
2915
|
+
});
|
|
2916
|
+
if (!res.ok) {
|
|
2917
|
+
const txt = await res.text();
|
|
2918
|
+
throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
|
|
2919
|
+
}
|
|
2920
|
+
const data = await res.json();
|
|
2921
|
+
const text = data.choices?.[0]?.message?.content ?? "";
|
|
2922
|
+
const usage = {
|
|
2923
|
+
inputTokens: data.usage?.prompt_tokens ?? 0,
|
|
2924
|
+
outputTokens: data.usage?.completion_tokens ?? 0
|
|
2925
|
+
};
|
|
2926
|
+
logLlmCall({
|
|
2927
|
+
ts: new Date(t0).toISOString(),
|
|
2928
|
+
provider: this.providerName,
|
|
2929
|
+
model: m,
|
|
2930
|
+
kind: opts.logKind,
|
|
2931
|
+
prompt: promptStr,
|
|
2932
|
+
response: text,
|
|
2933
|
+
usage,
|
|
2934
|
+
durationMs: Date.now() - t0,
|
|
2935
|
+
attempt: attempt + 1
|
|
2936
|
+
});
|
|
2937
|
+
return { text, usage };
|
|
2938
|
+
} catch (err) {
|
|
2939
|
+
lastError = err instanceof Error ? err.message : String(err);
|
|
2940
|
+
if (body.response_format && /response_format/i.test(lastError)) {
|
|
2941
|
+
delete body.response_format;
|
|
2942
|
+
continue;
|
|
2943
|
+
}
|
|
2944
|
+
if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
|
|
2945
|
+
delete body.reasoning_effort;
|
|
2946
|
+
continue;
|
|
2947
|
+
}
|
|
2948
|
+
logLlmCall({
|
|
2949
|
+
ts: new Date(t0).toISOString(),
|
|
2950
|
+
provider: this.providerName,
|
|
2951
|
+
model: m,
|
|
2952
|
+
kind: opts.logKind,
|
|
2953
|
+
prompt: promptStr,
|
|
2954
|
+
response: "",
|
|
2955
|
+
durationMs: Date.now() - t0,
|
|
2956
|
+
attempt: attempt + 1,
|
|
2957
|
+
error: lastError
|
|
2958
|
+
});
|
|
2959
|
+
if (attempt < maxRetries - 1)
|
|
2960
|
+
await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
|
|
2961
|
+
}
|
|
2962
|
+
}
|
|
2963
|
+
return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
|
|
2964
|
+
}
|
|
2965
|
+
chatJson(model, messages, opts = {}) {
|
|
2966
|
+
return chatJsonWith(this, model, messages, opts);
|
|
2967
|
+
}
|
|
2968
|
+
};
|
|
2969
|
+
|
|
2970
|
+
// src/providers/gemini-chat.ts
|
|
2971
|
+
var THINKING_HEADROOM_TOKENS = 4096;
|
|
2972
|
+
var GeminiChatClient = class {
|
|
2973
|
+
constructor(gemini, defaultModel) {
|
|
2974
|
+
this.gemini = gemini;
|
|
2975
|
+
this.defaultModel = defaultModel;
|
|
2976
|
+
}
|
|
2977
|
+
gemini;
|
|
2978
|
+
defaultModel;
|
|
2979
|
+
async chat(model, messages, opts = {}) {
|
|
2980
|
+
const system = messages.filter((m) => m.role === "system").map((m) => m.content);
|
|
2981
|
+
const prompt = messages.filter((m) => m.role !== "system").map((m) => m.content).join("\n\n");
|
|
2982
|
+
const r = await this.gemini.generate(model ?? this.defaultModel, prompt, [], {
|
|
2983
|
+
temperature: opts.temperature ?? 0.2,
|
|
2984
|
+
maxOutputTokens: opts.maxTokens ? opts.maxTokens + THINKING_HEADROOM_TOKENS : void 0,
|
|
2985
|
+
responseJson: opts.responseJson,
|
|
2986
|
+
systemInstruction: system.length ? system.join("\n\n") : void 0,
|
|
2987
|
+
maxRetries: opts.maxRetries ?? 5,
|
|
2988
|
+
logKind: opts.logKind
|
|
2989
|
+
});
|
|
2990
|
+
const usage = {
|
|
2991
|
+
inputTokens: r.usage.inputTokens,
|
|
2992
|
+
outputTokens: r.usage.outputTokens
|
|
2993
|
+
};
|
|
2994
|
+
return r.error ? { text: r.text, usage, error: r.error } : { text: r.text, usage };
|
|
2995
|
+
}
|
|
2996
|
+
chatJson(model, messages, opts = {}) {
|
|
2997
|
+
return chatJsonWith(this, model, messages, opts);
|
|
2998
|
+
}
|
|
2999
|
+
};
|
|
2474
3000
|
|
|
2475
3001
|
// src/providers/reasoner.ts
|
|
2476
3002
|
var PROVIDERS = {
|
|
@@ -2515,34 +3041,30 @@ function reasonerKey(info, keys) {
|
|
|
2515
3041
|
if (info.keyName === "gemini") return keys.gemini || keys.google;
|
|
2516
3042
|
return keys[info.keyName];
|
|
2517
3043
|
}
|
|
2518
|
-
function
|
|
3044
|
+
function clientFor(info, key, opts) {
|
|
3045
|
+
return info.provider === "gemini" ? new GeminiChatClient(
|
|
3046
|
+
new GeminiClient(key, { zeroStorage: opts.zeroStorage }),
|
|
3047
|
+
info.model
|
|
3048
|
+
) : new OpenAICompatClient(info.baseUrl, key, info.model, info.provider);
|
|
3049
|
+
}
|
|
3050
|
+
function resolveReasoner(spec, keys, opts = {}) {
|
|
2519
3051
|
const candidates = [spec, "deepseek-chat", "gemini-flash-latest"].filter(
|
|
2520
3052
|
(s) => !!s
|
|
2521
3053
|
);
|
|
2522
3054
|
for (const c of candidates) {
|
|
2523
3055
|
const info = resolveReasonerInfo(c);
|
|
2524
3056
|
const key = reasonerKey(info, keys);
|
|
2525
|
-
if (key) {
|
|
2526
|
-
return {
|
|
2527
|
-
client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
|
|
2528
|
-
info
|
|
2529
|
-
};
|
|
2530
|
-
}
|
|
3057
|
+
if (key) return { client: clientFor(info, key, opts), info };
|
|
2531
3058
|
}
|
|
2532
3059
|
return null;
|
|
2533
3060
|
}
|
|
2534
|
-
function resolveSecondReasoner(first, keys) {
|
|
3061
|
+
function resolveSecondReasoner(first, keys, opts = {}) {
|
|
2535
3062
|
const candidates = ["gemini-flash-latest", "deepseek-chat", "glm-4.7", "gpt-4o-mini"];
|
|
2536
3063
|
for (const c of candidates) {
|
|
2537
3064
|
const info = resolveReasonerInfo(c);
|
|
2538
3065
|
if (info.provider === first.provider) continue;
|
|
2539
3066
|
const key = reasonerKey(info, keys);
|
|
2540
|
-
if (key) {
|
|
2541
|
-
return {
|
|
2542
|
-
client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
|
|
2543
|
-
info
|
|
2544
|
-
};
|
|
2545
|
-
}
|
|
3067
|
+
if (key) return { client: clientFor(info, key, opts), info };
|
|
2546
3068
|
}
|
|
2547
3069
|
return null;
|
|
2548
3070
|
}
|
|
@@ -2557,7 +3079,6 @@ var REASONER_PRESETS = [
|
|
|
2557
3079
|
|
|
2558
3080
|
// src/finalize/finalize.ts
|
|
2559
3081
|
var MIN_DUR = 0.5;
|
|
2560
|
-
var MAX_DUR = 7;
|
|
2561
3082
|
var OVERLAP_GAP = 0.05;
|
|
2562
3083
|
function textSimilarity(a, b) {
|
|
2563
3084
|
const ta = new Set(tokenize(a).map((t) => t.norm));
|
|
@@ -2701,16 +3222,14 @@ function fixOverlaps(segments) {
|
|
|
2701
3222
|
}
|
|
2702
3223
|
function clampAndFix(segments) {
|
|
2703
3224
|
for (const s of segments) {
|
|
2704
|
-
|
|
2705
|
-
if (dur < MIN_DUR) s.end = s.start + MIN_DUR;
|
|
2706
|
-
else if (dur > MAX_DUR) s.end = s.start + MAX_DUR;
|
|
3225
|
+
if (s.end - s.start < MIN_DUR) s.end = s.start + MIN_DUR;
|
|
2707
3226
|
}
|
|
2708
3227
|
return fixOverlaps(segments);
|
|
2709
3228
|
}
|
|
2710
|
-
function finalizeSegments(segments
|
|
2711
|
-
const
|
|
2712
|
-
|
|
2713
|
-
|
|
3229
|
+
function finalizeSegments(segments) {
|
|
3230
|
+
const deduped = dedupSegments(trimSeamOverlaps(segments)).filter(
|
|
3231
|
+
(s) => s.text.trim().length > 0
|
|
3232
|
+
);
|
|
2714
3233
|
const out = deduped.map((s, i) => ({
|
|
2715
3234
|
id: i + 1,
|
|
2716
3235
|
start: s.start,
|
|
@@ -2790,9 +3309,9 @@ function splitByChars(seg) {
|
|
|
2790
3309
|
const blocks = [];
|
|
2791
3310
|
let t = seg.start;
|
|
2792
3311
|
for (const line of lines) {
|
|
2793
|
-
const
|
|
2794
|
-
blocks.push({ start: t, end: Math.min(seg.end, t +
|
|
2795
|
-
t +=
|
|
3312
|
+
const span2 = line.length / total * dur;
|
|
3313
|
+
blocks.push({ start: t, end: Math.min(seg.end, t + span2), text: line });
|
|
3314
|
+
t += span2;
|
|
2796
3315
|
}
|
|
2797
3316
|
return blocks;
|
|
2798
3317
|
}
|
|
@@ -3038,9 +3557,10 @@ async function summarizeTranscript(client, model, result, instructions) {
|
|
|
3038
3557
|
|
|
3039
3558
|
// src/core/pipeline.ts
|
|
3040
3559
|
import { basename as basename3, resolve as resolve2 } from "path";
|
|
3560
|
+
import { createHash as createHash3 } from "crypto";
|
|
3041
3561
|
var JSON_OPTS = { encoding: "utf-8" };
|
|
3042
3562
|
function readJson(p) {
|
|
3043
|
-
if (!
|
|
3563
|
+
if (!existsSync4(p)) return null;
|
|
3044
3564
|
try {
|
|
3045
3565
|
return JSON.parse(readFileSync2(p, JSON_OPTS));
|
|
3046
3566
|
} catch {
|
|
@@ -3066,6 +3586,12 @@ async function mapPool(items, limit, fn) {
|
|
|
3066
3586
|
function has(passes, p) {
|
|
3067
3587
|
return passes.includes(p);
|
|
3068
3588
|
}
|
|
3589
|
+
var ASR_NAMES = {
|
|
3590
|
+
assemblyai: "AssemblyAI",
|
|
3591
|
+
elevenlabs: "ElevenLabs Scribe",
|
|
3592
|
+
"whisper-groq": "Groq Whisper",
|
|
3593
|
+
none: "none"
|
|
3594
|
+
};
|
|
3069
3595
|
function stageTag(name) {
|
|
3070
3596
|
return (err) => {
|
|
3071
3597
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -3084,7 +3610,7 @@ async function transcribe(opts) {
|
|
|
3084
3610
|
const options = resolveOptions(opts);
|
|
3085
3611
|
const keys = resolveKeys(options.apiKeys);
|
|
3086
3612
|
logger.setLevel(options.logLevel);
|
|
3087
|
-
if (!
|
|
3613
|
+
if (!existsSync4(options.input)) {
|
|
3088
3614
|
throw new Error(`Input file not found: ${options.input}`);
|
|
3089
3615
|
}
|
|
3090
3616
|
mkdirSync2(options.intermediatesDir, { recursive: true });
|
|
@@ -3127,6 +3653,8 @@ async function transcribe(opts) {
|
|
|
3127
3653
|
const checkAbort = () => {
|
|
3128
3654
|
options.signal?.throwIfAborted();
|
|
3129
3655
|
};
|
|
3656
|
+
const emit = (event) => emitTo(options.onProgress, event);
|
|
3657
|
+
const geminiOpts = { zeroStorage: options.zeroStorage };
|
|
3130
3658
|
if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
|
|
3131
3659
|
if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
|
|
3132
3660
|
const tsProvider = options.timestampedProvider ?? "assemblyai";
|
|
@@ -3151,12 +3679,13 @@ async function transcribe(opts) {
|
|
|
3151
3679
|
if (has(passes, "preprocess")) {
|
|
3152
3680
|
checkAbort();
|
|
3153
3681
|
logger.info("=== preprocess ===");
|
|
3682
|
+
emit({ type: "stage", stage: "preprocess", state: "start" });
|
|
3154
3683
|
probeInfo = forceAll ? null : readJson(probePath);
|
|
3155
3684
|
if (!probeInfo) {
|
|
3156
3685
|
probeInfo = await probe(options.input).catch(stageTag("preprocess"));
|
|
3157
3686
|
writeJson(probePath, probeInfo);
|
|
3158
3687
|
}
|
|
3159
|
-
if (!
|
|
3688
|
+
if (!existsSync4(audioPath) || forceAll) {
|
|
3160
3689
|
logger.info("extracting audio (mono 16kHz mp3)...");
|
|
3161
3690
|
await extractAudio(options.input, audioPath, AUDIO_OPTS).catch(
|
|
3162
3691
|
stageTag("preprocess")
|
|
@@ -3164,7 +3693,7 @@ async function transcribe(opts) {
|
|
|
3164
3693
|
}
|
|
3165
3694
|
if (probeInfo.hasVideo) {
|
|
3166
3695
|
const kfDir = `${options.intermediatesDir}/keyframes`;
|
|
3167
|
-
if (!
|
|
3696
|
+
if (!existsSync4(kfDir) || forceAll) {
|
|
3168
3697
|
logger.info("extracting keyframes...");
|
|
3169
3698
|
await extractKeyframes(options.input, kfDir, options.screenshotCount).catch(
|
|
3170
3699
|
(err) => {
|
|
@@ -3192,14 +3721,120 @@ async function transcribe(opts) {
|
|
|
3192
3721
|
logger.info(
|
|
3193
3722
|
`estimated cost ~$${estimate.totalUsd.toFixed(2)}${estimate.incomplete ? " (+unpriced parts)" : ""} [${estimate.lines.join(" \xB7 ")}]`
|
|
3194
3723
|
);
|
|
3724
|
+
const naming = options.diarizationLevel >= 3 && has(passes, "identify");
|
|
3725
|
+
const reasonerA = naming || options.summary ? resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys, geminiOpts) : null;
|
|
3726
|
+
const reasonerB = naming && reasonerA && options.identifyMode === "dual" ? resolveSecondReasoner(reasonerA.info, keys, geminiOpts) : null;
|
|
3727
|
+
const asksAssemblyAI = willTimestamp && tsProvider === "assemblyai";
|
|
3728
|
+
const notAsked = options.zeroStorage ? [
|
|
3729
|
+
...willTimestamp && (tsProvider === "elevenlabs" || tsProvider === "whisper-groq") ? [{ name: ASR_NAMES[tsProvider], role: "timing" }] : [],
|
|
3730
|
+
...[reasonerA, reasonerB].flatMap(
|
|
3731
|
+
(r) => r && r.info.provider !== "gemini" ? [{ name: r.info.model, role: "text" }] : []
|
|
3732
|
+
)
|
|
3733
|
+
] : [];
|
|
3734
|
+
if (options.zeroStorage) {
|
|
3735
|
+
logger.info(
|
|
3736
|
+
`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` : ""}`
|
|
3737
|
+
);
|
|
3738
|
+
}
|
|
3739
|
+
emit({
|
|
3740
|
+
type: "plan",
|
|
3741
|
+
durationSec: duration,
|
|
3742
|
+
model: models.transcribe,
|
|
3743
|
+
asr: ASR_NAMES[tsProvider],
|
|
3744
|
+
estimateUsd: estimate.totalUsd,
|
|
3745
|
+
zeroStorage: options.zeroStorage,
|
|
3746
|
+
notAsked
|
|
3747
|
+
});
|
|
3748
|
+
const runTimestamped = async () => {
|
|
3749
|
+
if (!has(passes, "timestamped") && !has(passes, "align")) {
|
|
3750
|
+
const cached = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
|
|
3751
|
+
return { result: cached, billed: false };
|
|
3752
|
+
}
|
|
3753
|
+
checkAbort();
|
|
3754
|
+
if (tsProvider === "none") {
|
|
3755
|
+
logger.info("=== timestamped: none (the LLM's own timestamps are used) ===");
|
|
3756
|
+
return { result: null, billed: false };
|
|
3757
|
+
}
|
|
3758
|
+
if (tsProvider === "whisper-groq") {
|
|
3759
|
+
logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
|
|
3760
|
+
if (!existsSync4(audioPath))
|
|
3761
|
+
await extractAudio(options.input, audioPath, AUDIO_OPTS);
|
|
3762
|
+
const groq = new WhisperGroqClient(keys.groq);
|
|
3763
|
+
const result3 = await groq.transcribe(await readFile2(audioPath), { language: options.language }).catch(stageTag("asr"));
|
|
3764
|
+
writeJson(`${options.intermediatesDir}/timestamped.json`, result3);
|
|
3765
|
+
return { result: result3, billed: true };
|
|
3766
|
+
}
|
|
3767
|
+
if (tsProvider === "elevenlabs") {
|
|
3768
|
+
logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
|
|
3769
|
+
const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs${options.language ? `-${options.language}` : ""}.json`;
|
|
3770
|
+
let result3 = forceAll ? null : readJson(cachePath);
|
|
3771
|
+
let billed = false;
|
|
3772
|
+
if (!result3) {
|
|
3773
|
+
const el = new ElevenLabsClient(keys.elevenlabs);
|
|
3774
|
+
result3 = await el.transcribe(await readFile2(audioPath), { languageCode: options.language }).catch(stageTag("asr"));
|
|
3775
|
+
billed = true;
|
|
3776
|
+
writeJson(cachePath, result3);
|
|
3777
|
+
} else {
|
|
3778
|
+
logger.info("[elevenlabs] cache hit");
|
|
3779
|
+
}
|
|
3780
|
+
writeJson(`${options.intermediatesDir}/timestamped.json`, result3);
|
|
3781
|
+
logger.info(
|
|
3782
|
+
`[elevenlabs] ${result3.utterances.length} utterances, ${result3.words.length} words`
|
|
3783
|
+
);
|
|
3784
|
+
return { result: result3, billed };
|
|
3785
|
+
}
|
|
3786
|
+
logger.info("=== timestamped (AssemblyAI) ===");
|
|
3787
|
+
const aai = new AssemblyAIProvider({
|
|
3788
|
+
apiKey: keys.assemblyai,
|
|
3789
|
+
cacheDir: `${options.intermediatesDir}/assemblyai`,
|
|
3790
|
+
language: options.language,
|
|
3791
|
+
zeroStorage: options.zeroStorage
|
|
3792
|
+
});
|
|
3793
|
+
const result2 = await aai.transcribe(audioPath).catch(stageTag("asr"));
|
|
3794
|
+
writeJson(`${options.intermediatesDir}/timestamped.json`, result2);
|
|
3795
|
+
return { result: result2, billed: !aai.lastFromCache };
|
|
3796
|
+
};
|
|
3797
|
+
const asrName = ASR_NAMES[tsProvider];
|
|
3798
|
+
if (willTimestamp && tsProvider !== "none") {
|
|
3799
|
+
emit({ type: "asr", provider: asrName, state: "start" });
|
|
3800
|
+
}
|
|
3801
|
+
const asrRun = runTimestamped().then(
|
|
3802
|
+
(r) => {
|
|
3803
|
+
if (willTimestamp && r.result) {
|
|
3804
|
+
const speakers2 = new Set(r.result.utterances.map((u) => u.speaker)).size;
|
|
3805
|
+
emit({
|
|
3806
|
+
type: "asr",
|
|
3807
|
+
provider: asrName,
|
|
3808
|
+
state: r.billed ? "done" : "cached",
|
|
3809
|
+
words: r.result.words.length,
|
|
3810
|
+
speakers: speakers2 || void 0,
|
|
3811
|
+
language: r.result.languageCode
|
|
3812
|
+
});
|
|
3813
|
+
}
|
|
3814
|
+
return r;
|
|
3815
|
+
},
|
|
3816
|
+
(err) => {
|
|
3817
|
+
emit({
|
|
3818
|
+
type: "asr",
|
|
3819
|
+
provider: asrName,
|
|
3820
|
+
state: "failed",
|
|
3821
|
+
error: err instanceof Error ? err.message : String(err)
|
|
3822
|
+
});
|
|
3823
|
+
throw err;
|
|
3824
|
+
}
|
|
3825
|
+
);
|
|
3826
|
+
asrRun.catch(() => void 0);
|
|
3195
3827
|
let description = null;
|
|
3196
3828
|
if (has(passes, "describe")) {
|
|
3197
3829
|
const descPath = `${options.intermediatesDir}/description.json`;
|
|
3198
3830
|
description = forceAll ? null : readJson(descPath);
|
|
3199
|
-
if (
|
|
3831
|
+
if (description) {
|
|
3832
|
+
emit({ type: "stage", stage: "describe", state: "cached" });
|
|
3833
|
+
} else {
|
|
3200
3834
|
checkAbort();
|
|
3201
3835
|
logger.info("=== describe ===");
|
|
3202
|
-
|
|
3836
|
+
emit({ type: "stage", stage: "describe", state: "start" });
|
|
3837
|
+
const client = new GeminiClient(keys.gemini, geminiOpts);
|
|
3203
3838
|
const sampleSpans = duration <= 360 ? [[0, duration]] : [
|
|
3204
3839
|
[0, 150],
|
|
3205
3840
|
[Math.max(0, duration / 2 - 60), Math.min(duration, duration / 2 + 60)],
|
|
@@ -3209,17 +3844,17 @@ async function transcribe(opts) {
|
|
|
3209
3844
|
for (let i = 0; i < sampleSpans.length; i++) {
|
|
3210
3845
|
const [s, e] = sampleSpans[i];
|
|
3211
3846
|
const samplePath = `${options.intermediatesDir}/sample_${i}.mp3`;
|
|
3212
|
-
if (!
|
|
3847
|
+
if (!existsSync4(samplePath) || forceAll) {
|
|
3213
3848
|
await extractChunk(audioPath, samplePath, s, e, AUDIO_OPTS);
|
|
3214
3849
|
}
|
|
3215
3850
|
files.push({ path: samplePath });
|
|
3216
3851
|
}
|
|
3217
3852
|
const audioSampleCount = files.length;
|
|
3218
3853
|
const kfDir = `${options.intermediatesDir}/keyframes`;
|
|
3219
|
-
if (
|
|
3854
|
+
if (existsSync4(kfDir)) {
|
|
3220
3855
|
for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
|
|
3221
3856
|
const p = `${kfDir}/${f}`;
|
|
3222
|
-
if (
|
|
3857
|
+
if (existsSync4(p)) files.push({ path: p });
|
|
3223
3858
|
}
|
|
3224
3859
|
}
|
|
3225
3860
|
description = await describeMeeting(
|
|
@@ -3248,14 +3883,14 @@ async function transcribe(opts) {
|
|
|
3248
3883
|
}
|
|
3249
3884
|
chunks = planChunks(duration, options.chunkDurationSec, options.chunkOverlapSec);
|
|
3250
3885
|
if (silences.length > 3) {
|
|
3251
|
-
chunks = chunks.map((c) => {
|
|
3252
|
-
|
|
3886
|
+
chunks = chunks.map((c) => ({
|
|
3887
|
+
...c,
|
|
3888
|
+
start: snapToSilence(
|
|
3253
3889
|
c.start,
|
|
3254
3890
|
silences,
|
|
3255
3891
|
Math.min(10, options.chunkOverlapSec / 2)
|
|
3256
|
-
)
|
|
3257
|
-
|
|
3258
|
-
});
|
|
3892
|
+
)
|
|
3893
|
+
}));
|
|
3259
3894
|
}
|
|
3260
3895
|
}
|
|
3261
3896
|
const tagWith = (r, chunk) => ({
|
|
@@ -3263,20 +3898,25 @@ async function transcribe(opts) {
|
|
|
3263
3898
|
segments: r.segments.map((s) => ({
|
|
3264
3899
|
...s,
|
|
3265
3900
|
chunkIndex: chunk.index,
|
|
3266
|
-
trustedStart: chunk.trustedStart
|
|
3901
|
+
trustedStart: chunk.trustedStart,
|
|
3902
|
+
chunkStart: chunk.start,
|
|
3903
|
+
chunkEnd: chunk.end
|
|
3267
3904
|
}))
|
|
3268
3905
|
});
|
|
3906
|
+
const llmDir = `${options.intermediatesDir}/llm`;
|
|
3269
3907
|
let llmChunkResults = [];
|
|
3908
|
+
let llmChunkPlans = [];
|
|
3270
3909
|
if (has(passes, "llm-transcribe")) {
|
|
3271
3910
|
logger.info("=== llm-transcribe ===");
|
|
3911
|
+
emit({ type: "stage", stage: "transcribe", state: "start" });
|
|
3272
3912
|
let runChunks = chunks;
|
|
3273
3913
|
if (options.onlyChunk !== void 0)
|
|
3274
3914
|
runChunks = chunks.filter((c) => c.index === options.onlyChunk);
|
|
3275
3915
|
logger.info(
|
|
3276
3916
|
`${runChunks.length} chunks (${options.chunkDurationSec}s, ${options.chunkOverlapSec}s overlap)`
|
|
3277
3917
|
);
|
|
3278
|
-
|
|
3279
|
-
const
|
|
3918
|
+
emit({ type: "chunks", total: runChunks.length, chunkSec: options.chunkDurationSec });
|
|
3919
|
+
const client = new GeminiClient(keys.gemini, geminiOpts);
|
|
3280
3920
|
mkdirSync2(llmDir, { recursive: true });
|
|
3281
3921
|
const partialPath = `${options.outputDir}/${basename3(options.input, ext(options.input))}.partial.md`;
|
|
3282
3922
|
const completed = [];
|
|
@@ -3305,25 +3945,23 @@ ${lines.join("\n\n")}
|
|
|
3305
3945
|
const cached = forceAll ? null : readJson(parsedPath);
|
|
3306
3946
|
if (cached && cached.segments.length > 0) {
|
|
3307
3947
|
logger.info(`chunk ${chunk.index}: cached (${cached.segments.length} segments)`);
|
|
3948
|
+
emit({
|
|
3949
|
+
type: "chunk",
|
|
3950
|
+
index: chunk.index,
|
|
3951
|
+
state: "cached",
|
|
3952
|
+
segments: cached.segments.length
|
|
3953
|
+
});
|
|
3308
3954
|
completed.push(cached);
|
|
3309
3955
|
return tagWith(cached, chunk);
|
|
3310
3956
|
}
|
|
3311
3957
|
const chunkPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}.mp3`;
|
|
3312
|
-
if (!
|
|
3958
|
+
if (!existsSync4(chunkPath) || forceAll) {
|
|
3313
3959
|
await extractChunk(audioPath, chunkPath, chunk.start, chunk.end, AUDIO_OPTS);
|
|
3314
3960
|
}
|
|
3315
|
-
let previousTail;
|
|
3316
|
-
if (chunk.index > 0) {
|
|
3317
|
-
const prev = readJson(
|
|
3318
|
-
`${llmDir}/chunk_${String(chunk.index - 1).padStart(2, "0")}_parsed.json`
|
|
3319
|
-
);
|
|
3320
|
-
if (prev && prev.segments.length) {
|
|
3321
|
-
previousTail = prev.segments.slice(-6).map((s) => `${s.speaker}: ${s.text}`).join("\n");
|
|
3322
|
-
}
|
|
3323
|
-
}
|
|
3324
3961
|
logger.info(
|
|
3325
3962
|
`chunk ${chunk.index}: transcribing [${chunk.start.toFixed(0)}-${chunk.end.toFixed(0)}]s...`
|
|
3326
3963
|
);
|
|
3964
|
+
emit({ type: "chunk", index: chunk.index, state: "running" });
|
|
3327
3965
|
const result2 = await transcribeChunk(
|
|
3328
3966
|
client,
|
|
3329
3967
|
models.transcribe,
|
|
@@ -3334,12 +3972,19 @@ ${lines.join("\n\n")}
|
|
|
3334
3972
|
total: runChunks.length,
|
|
3335
3973
|
description: description?.description,
|
|
3336
3974
|
roster: description?.roster,
|
|
3337
|
-
previousTail,
|
|
3338
3975
|
instructions: options.instructions
|
|
3339
3976
|
},
|
|
3340
3977
|
{ chunkDurationSec: chunk.end - chunk.start, validationRetries: 1 }
|
|
3341
3978
|
);
|
|
3342
3979
|
writeJson(parsedPath, result2);
|
|
3980
|
+
emit(
|
|
3981
|
+
result2.error && result2.segments.length === 0 ? { type: "chunk", index: chunk.index, state: "failed", error: result2.error } : {
|
|
3982
|
+
type: "chunk",
|
|
3983
|
+
index: chunk.index,
|
|
3984
|
+
state: "done",
|
|
3985
|
+
segments: result2.segments.length
|
|
3986
|
+
}
|
|
3987
|
+
);
|
|
3343
3988
|
writeFileSync2(
|
|
3344
3989
|
`${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`,
|
|
3345
3990
|
result2.raw
|
|
@@ -3348,6 +3993,7 @@ ${lines.join("\n\n")}
|
|
|
3348
3993
|
writePartial();
|
|
3349
3994
|
return tagWith(result2, chunk);
|
|
3350
3995
|
});
|
|
3996
|
+
llmChunkPlans = runChunks;
|
|
3351
3997
|
const errored = llmChunkResults.filter((r) => r.error);
|
|
3352
3998
|
const producedSegments = llmChunkResults.reduce((n, r) => n + r.segments.length, 0);
|
|
3353
3999
|
if (llmChunkResults.length > 0 && producedSegments === 0 && errored.length === llmChunkResults.length) {
|
|
@@ -3356,16 +4002,118 @@ ${lines.join("\n\n")}
|
|
|
3356
4002
|
);
|
|
3357
4003
|
}
|
|
3358
4004
|
} else {
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
const r = readJson(`${llmDir}/${f}`);
|
|
3364
|
-
|
|
3365
|
-
|
|
4005
|
+
if (!forceAll && existsSync4(llmDir)) {
|
|
4006
|
+
for (const f of readdirSync(llmDir).sort()) {
|
|
4007
|
+
const m = /^chunk_(\d+)_parsed\.json$/.exec(f);
|
|
4008
|
+
const plan = m ? chunks.find((c) => c.index === Number(m[1])) : void 0;
|
|
4009
|
+
const r = plan ? readJson(`${llmDir}/${f}`) : null;
|
|
4010
|
+
if (r && plan) {
|
|
4011
|
+
llmChunkResults.push(tagWith(r, plan));
|
|
4012
|
+
llmChunkPlans.push(plan);
|
|
4013
|
+
}
|
|
4014
|
+
}
|
|
4015
|
+
}
|
|
4016
|
+
}
|
|
4017
|
+
const { result: asrResult, billed: asrBilled } = await asrRun;
|
|
4018
|
+
const quality = [];
|
|
4019
|
+
if (asrResult?.words.length) {
|
|
4020
|
+
let client;
|
|
4021
|
+
for (let i = 0; i < llmChunkResults.length; i++) {
|
|
4022
|
+
const plan = llmChunkPlans[i];
|
|
4023
|
+
const where = `chunk ${plan.index} [${plan.start.toFixed(0)}-${plan.end.toFixed(0)}]s`;
|
|
4024
|
+
let cov = chunkCoverage(
|
|
4025
|
+
llmChunkResults[i].segments,
|
|
4026
|
+
asrResult.words,
|
|
4027
|
+
plan.start,
|
|
4028
|
+
plan.end
|
|
4029
|
+
);
|
|
4030
|
+
let status = cov.low ? "low-coverage" : "ok";
|
|
4031
|
+
if (cov.low) {
|
|
4032
|
+
const retryPath = `${llmDir}/chunk_${String(plan.index).padStart(2, "0")}_retry_parsed.json`;
|
|
4033
|
+
let retry = forceAll ? null : readJson(retryPath);
|
|
4034
|
+
const span2 = { index: plan.index, startSec: plan.start, endSec: plan.end };
|
|
4035
|
+
if (!retry && has(passes, "llm-transcribe")) {
|
|
4036
|
+
checkAbort();
|
|
4037
|
+
logger.warn(
|
|
4038
|
+
`${where}: ${cov.llmWords} words transcribed where the ASR heard ${cov.asrWords} \u2014 transcribing it again in two halves`
|
|
4039
|
+
);
|
|
4040
|
+
emit({
|
|
4041
|
+
type: "guard",
|
|
4042
|
+
...span2,
|
|
4043
|
+
state: "retrying",
|
|
4044
|
+
llmWords: cov.llmWords,
|
|
4045
|
+
asrWords: cov.asrWords
|
|
4046
|
+
});
|
|
4047
|
+
client ??= new GeminiClient(keys.gemini, geminiOpts);
|
|
4048
|
+
retry = await transcribeInHalves({
|
|
4049
|
+
client,
|
|
4050
|
+
model: models.transcribe,
|
|
4051
|
+
audioPath,
|
|
4052
|
+
chunk: plan,
|
|
4053
|
+
pathPrefix: `${llmDir}/chunk_${String(plan.index).padStart(2, "0")}`,
|
|
4054
|
+
ctx: {
|
|
4055
|
+
index: plan.index + 1,
|
|
4056
|
+
total: chunks.length,
|
|
4057
|
+
description: description?.description,
|
|
4058
|
+
roster: description?.roster,
|
|
4059
|
+
instructions: options.instructions
|
|
4060
|
+
},
|
|
4061
|
+
audioOpts: AUDIO_OPTS
|
|
4062
|
+
}).catch(stageTag("llm-transcribe"));
|
|
4063
|
+
writeJson(retryPath, retry);
|
|
4064
|
+
}
|
|
4065
|
+
if (retry) {
|
|
4066
|
+
const again = chunkCoverage(
|
|
4067
|
+
retry.segments,
|
|
4068
|
+
asrResult.words,
|
|
4069
|
+
plan.start,
|
|
4070
|
+
plan.end
|
|
4071
|
+
);
|
|
4072
|
+
logger.info(
|
|
4073
|
+
`${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"}`
|
|
4074
|
+
);
|
|
4075
|
+
const kept = again.ratio > cov.ratio;
|
|
4076
|
+
emit({
|
|
4077
|
+
type: "guard",
|
|
4078
|
+
...span2,
|
|
4079
|
+
state: kept ? "recovered" : "unchanged",
|
|
4080
|
+
llmWords: cov.llmWords,
|
|
4081
|
+
asrWords: cov.asrWords,
|
|
4082
|
+
retryWords: again.llmWords
|
|
4083
|
+
});
|
|
4084
|
+
if (kept) {
|
|
4085
|
+
llmChunkResults[i] = tagWith(retry, plan);
|
|
4086
|
+
cov = again;
|
|
4087
|
+
status = again.low ? "low-coverage" : "retried";
|
|
4088
|
+
}
|
|
4089
|
+
}
|
|
4090
|
+
}
|
|
4091
|
+
quality.push({
|
|
4092
|
+
chunk: plan.index,
|
|
4093
|
+
start: plan.start,
|
|
4094
|
+
end: plan.end,
|
|
4095
|
+
status,
|
|
4096
|
+
llmWords: cov.llmWords,
|
|
4097
|
+
asrWords: cov.asrWords,
|
|
4098
|
+
coverage: Number.isFinite(cov.ratio) ? Number(cov.ratio.toFixed(2)) : null
|
|
4099
|
+
});
|
|
3366
4100
|
}
|
|
3367
4101
|
}
|
|
4102
|
+
const whole = asrResult?.words.length ? chunkCoverage(
|
|
4103
|
+
llmChunkResults.flatMap((r) => r.segments),
|
|
4104
|
+
asrResult.words,
|
|
4105
|
+
0,
|
|
4106
|
+
Infinity
|
|
4107
|
+
) : null;
|
|
4108
|
+
const asrMissedSpeech = !!whole && whole.llmWords >= 200 && whole.ratio > 3;
|
|
4109
|
+
if (asrMissedSpeech) {
|
|
4110
|
+
logger.warn(
|
|
4111
|
+
`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)`
|
|
4112
|
+
);
|
|
4113
|
+
}
|
|
3368
4114
|
let allLlmSegments = llmChunkResults.flatMap((r) => r.segments);
|
|
4115
|
+
const timingWords = asrMissedSpeech ? [] : asrResult?.words ?? [];
|
|
4116
|
+
allLlmSegments = toAsrClock(allLlmSegments, timingWords);
|
|
3369
4117
|
const beforePart = allLlmSegments.length;
|
|
3370
4118
|
allLlmSegments = partitionByOwnership(allLlmSegments);
|
|
3371
4119
|
if (beforePart !== allLlmSegments.length) {
|
|
@@ -3374,81 +4122,68 @@ ${lines.join("\n\n")}
|
|
|
3374
4122
|
);
|
|
3375
4123
|
}
|
|
3376
4124
|
logger.info(`total LLM segments: ${allLlmSegments.length}`);
|
|
3377
|
-
|
|
3378
|
-
|
|
3379
|
-
|
|
3380
|
-
|
|
3381
|
-
|
|
3382
|
-
|
|
3383
|
-
|
|
3384
|
-
|
|
3385
|
-
|
|
4125
|
+
if (asrResult?.words.length && (has(passes, "align") || has(passes, "consistency"))) {
|
|
4126
|
+
const dropped = /* @__PURE__ */ new Set();
|
|
4127
|
+
for (let i = 0; i < llmChunkResults.length; i++) {
|
|
4128
|
+
const r = llmChunkResults[i];
|
|
4129
|
+
const plan = llmChunkPlans[i];
|
|
4130
|
+
const q = quality.find((x) => x.chunk === plan.index);
|
|
4131
|
+
const where = `chunk ${plan.index} [${plan.start.toFixed(0)}-${plan.end.toFixed(0)}]s`;
|
|
4132
|
+
const compression = maxCompressionRatio(r.segments.map((s) => s.text).join(" "));
|
|
4133
|
+
if (compression > DEGENERATE_COMPRESSION_RATIO) {
|
|
4134
|
+
dropped.add(plan.index);
|
|
4135
|
+
if (q) q.status = "dropped-loop";
|
|
4136
|
+
logger.warn(
|
|
4137
|
+
`${where}: dropping repetition-loop text (compression ratio ${compression.toFixed(1)}) \u2014 ASR will fill this range`
|
|
4138
|
+
);
|
|
4139
|
+
continue;
|
|
3386
4140
|
}
|
|
3387
|
-
const
|
|
3388
|
-
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
|
|
3394
|
-
if (!keys.elevenlabs)
|
|
3395
|
-
throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
|
|
3396
|
-
const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs.json`;
|
|
3397
|
-
asrResult = forceAll ? null : readJson(cachePath);
|
|
3398
|
-
if (!asrResult) {
|
|
3399
|
-
const { readFile: readFile2 } = await import("fs/promises");
|
|
3400
|
-
const buf = await readFile2(audioPath);
|
|
3401
|
-
const el = new ElevenLabsClient(keys.elevenlabs);
|
|
3402
|
-
asrResult = await el.transcribe(buf).catch(stageTag("asr"));
|
|
3403
|
-
writeJson(cachePath, asrResult);
|
|
3404
|
-
} else {
|
|
3405
|
-
logger.info("[elevenlabs] cache hit");
|
|
4141
|
+
const g = chunkGrounding(r.segments, asrResult.words, plan.start, plan.end);
|
|
4142
|
+
if (!g.grounded) {
|
|
4143
|
+
if (q) q.ungrounded = true;
|
|
4144
|
+
logger.warn(
|
|
4145
|
+
`${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)`
|
|
4146
|
+
);
|
|
3406
4147
|
}
|
|
3407
|
-
|
|
3408
|
-
|
|
3409
|
-
|
|
4148
|
+
}
|
|
4149
|
+
if (dropped.size) {
|
|
4150
|
+
allLlmSegments = allLlmSegments.filter(
|
|
4151
|
+
(s) => s.chunkIndex === void 0 || !dropped.has(s.chunkIndex)
|
|
3410
4152
|
);
|
|
3411
|
-
} else {
|
|
3412
|
-
logger.info("=== timestamped (AssemblyAI) ===");
|
|
3413
|
-
if (!keys.assemblyai)
|
|
3414
|
-
throw new Error(
|
|
3415
|
-
"ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
|
|
3416
|
-
);
|
|
3417
|
-
const aai = new AssemblyAIProvider({
|
|
3418
|
-
apiKey: keys.assemblyai,
|
|
3419
|
-
cacheDir: `${options.intermediatesDir}/assemblyai`
|
|
3420
|
-
});
|
|
3421
|
-
asrResult = await aai.transcribe(audioPath).catch(stageTag("asr"));
|
|
3422
|
-
writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
|
|
3423
4153
|
}
|
|
3424
|
-
} else {
|
|
3425
|
-
asrResult = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
|
|
3426
4154
|
}
|
|
3427
4155
|
let aligned = [];
|
|
3428
|
-
if (has(passes, "align") && asrResult) {
|
|
4156
|
+
if (has(passes, "align") && (asrResult || tsProvider === "none")) {
|
|
3429
4157
|
logger.info("=== align ===");
|
|
3430
|
-
|
|
4158
|
+
emit({ type: "stage", stage: "align", state: "start" });
|
|
4159
|
+
aligned = alignSegments(allLlmSegments, timingWords, { timeMarginSec: 30 });
|
|
3431
4160
|
writeJson(`${options.intermediatesDir}/aligned.json`, aligned);
|
|
3432
4161
|
} else {
|
|
3433
4162
|
aligned = (forceAll ? null : readJson(`${options.intermediatesDir}/aligned.json`)) ?? [];
|
|
3434
4163
|
}
|
|
3435
4164
|
const alignedOk = aligned.filter((a) => a.timingSource !== "coarse").length;
|
|
3436
4165
|
logger.info(`aligned: ${alignedOk}/${aligned.length} with ASR timing`);
|
|
3437
|
-
|
|
3438
|
-
|
|
4166
|
+
let gapFilledWords = 0;
|
|
4167
|
+
if (asrResult && !asrMissedSpeech && (has(passes, "align") || has(passes, "consistency"))) {
|
|
3439
4168
|
aligned = fillAsrGaps(aligned, asrResult.words, asrResult.utterances);
|
|
3440
|
-
const added = aligned.
|
|
3441
|
-
|
|
4169
|
+
const added = aligned.filter((a) => a.timingSource === "timestamped");
|
|
4170
|
+
gapFilledWords = added.reduce((n, a) => n + a.words.length, 0);
|
|
4171
|
+
if (added.length) {
|
|
4172
|
+
logger.info(
|
|
4173
|
+
`gap-filled ${added.length} ASR fallback segment(s) (${gapFilledWords} words)`
|
|
4174
|
+
);
|
|
4175
|
+
}
|
|
3442
4176
|
}
|
|
3443
4177
|
if (asrResult && (asrResult.hasDiarization ?? true) && (has(passes, "align") || has(passes, "consistency"))) {
|
|
3444
4178
|
aligned = splitMixedVoiceSegments(aligned, asrResult.utterances);
|
|
3445
4179
|
}
|
|
3446
4180
|
let segments = aligned;
|
|
3447
4181
|
let speakers = [];
|
|
3448
|
-
if (has(passes, "consistency") && asrResult) {
|
|
4182
|
+
if (has(passes, "consistency") && (asrResult || tsProvider === "none")) {
|
|
3449
4183
|
logger.info("=== consistency ===");
|
|
3450
|
-
|
|
3451
|
-
|
|
4184
|
+
emit({ type: "stage", stage: "speakers", state: "start" });
|
|
4185
|
+
const cons = assignGlobalSpeakers(aligned, asrResult?.utterances ?? [], {
|
|
4186
|
+
hasDiarization: asrResult ? asrResult.hasDiarization ?? true : false
|
|
3452
4187
|
});
|
|
3453
4188
|
segments = cons.segments;
|
|
3454
4189
|
speakers = cons.speakers;
|
|
@@ -3470,19 +4205,22 @@ ${lines.join("\n\n")}
|
|
|
3470
4205
|
(s) => s.speakerName !== s.speaker ? { ...s, speakerName: s.speaker } : s
|
|
3471
4206
|
);
|
|
3472
4207
|
speakers = speakers.map((sp) => sp.name !== sp.id ? { ...sp, name: sp.id } : sp);
|
|
3473
|
-
if (
|
|
3474
|
-
const reasonerA = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
|
|
4208
|
+
if (naming) {
|
|
3475
4209
|
if (!reasonerA) {
|
|
3476
4210
|
logger.warn(
|
|
3477
4211
|
"identify: no reasoner-capable API key found (DEEPSEEK/GEMINI/OPENAI/\u2026) \u2014 skipping speaker naming"
|
|
3478
4212
|
);
|
|
3479
4213
|
} else {
|
|
3480
4214
|
const mode = options.identifyMode;
|
|
3481
|
-
const reasonerB = mode === "dual" ? resolveSecondReasoner(reasonerA.info, keys) : null;
|
|
3482
4215
|
const idConfig = {
|
|
3483
4216
|
mode,
|
|
3484
4217
|
reasonerA: reasonerA.info.model,
|
|
3485
|
-
reasonerB: reasonerB?.info.model ?? null
|
|
4218
|
+
reasonerB: reasonerB?.info.model ?? null,
|
|
4219
|
+
knownSpeakers: options.knownSpeakers ?? [],
|
|
4220
|
+
// What the naming step reads. If a re-run changes the transcript (a re-transcribed
|
|
4221
|
+
// chunk can reorder speakers by talk time), "Speaker A" may now be the other voice,
|
|
4222
|
+
// and the cached names must not be applied to it.
|
|
4223
|
+
inputs: createHash3("sha1").update(JSON.stringify(segments.map((s) => [s.speaker, s.text]))).update(JSON.stringify(speakers.map((sp) => sp.id))).digest("hex")
|
|
3486
4224
|
};
|
|
3487
4225
|
const idCachePath = `${options.intermediatesDir}/identified.json`;
|
|
3488
4226
|
const cachedId = forceAll ? null : readJson(
|
|
@@ -3492,11 +4230,18 @@ ${lines.join("\n\n")}
|
|
|
3492
4230
|
let nameMap = null;
|
|
3493
4231
|
if (idConfigMatches && cachedId?.nameMap && Object.keys(cachedId.nameMap).length > 0) {
|
|
3494
4232
|
logger.info("=== identify (cached) ===");
|
|
4233
|
+
emit({ type: "stage", stage: "identify", state: "cached" });
|
|
3495
4234
|
nameMap = cachedId.nameMap;
|
|
3496
4235
|
} else {
|
|
3497
4236
|
logger.info(
|
|
3498
4237
|
`=== identify (${reasonerA.info.model}${reasonerB ? ` + ${reasonerB.info.model} second opinion` : ""}) ===`
|
|
3499
4238
|
);
|
|
4239
|
+
emit({
|
|
4240
|
+
type: "stage",
|
|
4241
|
+
stage: "identify",
|
|
4242
|
+
state: "start",
|
|
4243
|
+
detail: reasonerB ? `${reasonerA.info.model} + ${reasonerB.info.model}` : reasonerA.info.model
|
|
4244
|
+
});
|
|
3500
4245
|
checkAbort();
|
|
3501
4246
|
const id = await identifySpeakersV2(
|
|
3502
4247
|
{
|
|
@@ -3521,11 +4266,14 @@ ${lines.join("\n\n")}
|
|
|
3521
4266
|
).catch(stageTag("identify"));
|
|
3522
4267
|
writeJson(idCachePath, { ...id, config: idConfig });
|
|
3523
4268
|
nameMap = id.nameMap;
|
|
4269
|
+
if (id.allPassesFailed)
|
|
4270
|
+
emit({ type: "stage", stage: "identify", state: "failed" });
|
|
3524
4271
|
}
|
|
3525
4272
|
logger.info(
|
|
3526
4273
|
`identified ${Object.keys(nameMap).length} speakers: ${JSON.stringify(nameMap)}`
|
|
3527
4274
|
);
|
|
3528
4275
|
const nm = nameMap;
|
|
4276
|
+
emit({ type: "names", names: nm });
|
|
3529
4277
|
segments = segments.map(
|
|
3530
4278
|
(s) => nm[s.speaker] ? { ...s, speakerName: nm[s.speaker] } : s
|
|
3531
4279
|
);
|
|
@@ -3535,13 +4283,14 @@ ${lines.join("\n\n")}
|
|
|
3535
4283
|
let finalSegments = [];
|
|
3536
4284
|
if (has(passes, "finalize")) {
|
|
3537
4285
|
logger.info("=== finalize ===");
|
|
4286
|
+
emit({ type: "stage", stage: "finalize", state: "start" });
|
|
3538
4287
|
finalSegments = finalizeSegments(segments);
|
|
3539
4288
|
writeJson(`${options.intermediatesDir}/final.json`, finalSegments);
|
|
3540
4289
|
} else {
|
|
3541
4290
|
finalSegments = (forceAll ? null : readJson(`${options.intermediatesDir}/final.json`)) ?? [];
|
|
3542
4291
|
}
|
|
3543
4292
|
logger.info(`final segments: ${finalSegments.length}`);
|
|
3544
|
-
const receipt = computeReceipt(getLlmUsage(), tsProvider, duration);
|
|
4293
|
+
const receipt = computeReceipt(getLlmUsage(), tsProvider, duration, asrBilled);
|
|
3545
4294
|
const wallMs = Date.now() - runStartedAt;
|
|
3546
4295
|
const metadata = {
|
|
3547
4296
|
sourceFile: options.input,
|
|
@@ -3561,86 +4310,103 @@ ${lines.join("\n\n")}
|
|
|
3561
4310
|
llmCalls: receipt.totals.calls,
|
|
3562
4311
|
inputTokens: receipt.totals.inputTokens,
|
|
3563
4312
|
outputTokens: receipt.totals.outputTokens
|
|
3564
|
-
}
|
|
4313
|
+
},
|
|
4314
|
+
...asrResult ? { quality: { chunks: quality, gapFilledWords, asrMissedSpeech } } : {},
|
|
4315
|
+
zeroStorage: options.zeroStorage
|
|
3565
4316
|
};
|
|
4317
|
+
const degraded = quality.filter((q) => q.status !== "ok");
|
|
4318
|
+
if (degraded.length || asrMissedSpeech) {
|
|
4319
|
+
logger.warn(
|
|
4320
|
+
`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`
|
|
4321
|
+
);
|
|
4322
|
+
}
|
|
3566
4323
|
const result = { segments: finalSegments, speakers, metadata };
|
|
3567
4324
|
writeJson(`${options.intermediatesDir}/result.json`, result);
|
|
4325
|
+
const base = basename3(options.input, ext(options.input));
|
|
4326
|
+
const written = [];
|
|
4327
|
+
const write = (name, content) => {
|
|
4328
|
+
const path = `${options.outputDir}/${name}`;
|
|
4329
|
+
writeFileSync2(path, content);
|
|
4330
|
+
written.push(resolve2(path));
|
|
4331
|
+
};
|
|
3568
4332
|
for (const fmt of options.formats) {
|
|
3569
|
-
|
|
3570
|
-
if (fmt === "srt")
|
|
3571
|
-
writeFileSync2(
|
|
3572
|
-
`${options.outputDir}/${base}.srt`,
|
|
3573
|
-
formatSrt(result, { title: base })
|
|
3574
|
-
);
|
|
4333
|
+
if (fmt === "srt") write(`${base}.srt`, formatSrt(result, { title: base }));
|
|
3575
4334
|
if (fmt === "md")
|
|
3576
|
-
|
|
3577
|
-
`${
|
|
4335
|
+
write(
|
|
4336
|
+
`${base}.md`,
|
|
3578
4337
|
formatMarkdown(result, { title: base, mdStyle: options.mdStyle })
|
|
3579
4338
|
);
|
|
3580
|
-
if (fmt === "txt")
|
|
3581
|
-
|
|
3582
|
-
|
|
3583
|
-
formatText(result, { title: base })
|
|
3584
|
-
);
|
|
3585
|
-
if (fmt === "html")
|
|
3586
|
-
writeFileSync2(
|
|
3587
|
-
`${options.outputDir}/${base}.html`,
|
|
3588
|
-
formatHtml(result, { title: base })
|
|
3589
|
-
);
|
|
3590
|
-
if (fmt === "json")
|
|
3591
|
-
writeFileSync2(`${options.outputDir}/${base}.json`, formatJson(result));
|
|
4339
|
+
if (fmt === "txt") write(`${base}.txt`, formatText(result, { title: base }));
|
|
4340
|
+
if (fmt === "html") write(`${base}.html`, formatHtml(result, { title: base }));
|
|
4341
|
+
if (fmt === "json") write(`${base}.json`, formatJson(result));
|
|
3592
4342
|
}
|
|
3593
4343
|
if (options.summary && finalSegments.length > 0) {
|
|
3594
|
-
|
|
3595
|
-
if (!reasoner) {
|
|
4344
|
+
if (!reasonerA) {
|
|
3596
4345
|
logger.warn("summary: no reasoner-capable key \u2014 skipping");
|
|
3597
4346
|
} else {
|
|
3598
|
-
logger.info(`=== summary (${
|
|
4347
|
+
logger.info(`=== summary (${reasonerA.info.model}) ===`);
|
|
4348
|
+
emit({
|
|
4349
|
+
type: "stage",
|
|
4350
|
+
stage: "summary",
|
|
4351
|
+
state: "start",
|
|
4352
|
+
detail: reasonerA.info.model
|
|
4353
|
+
});
|
|
3599
4354
|
try {
|
|
3600
4355
|
const summary = await summarizeTranscript(
|
|
3601
|
-
|
|
3602
|
-
|
|
4356
|
+
reasonerA.client,
|
|
4357
|
+
reasonerA.info.model,
|
|
3603
4358
|
result,
|
|
3604
4359
|
options.instructions
|
|
3605
4360
|
);
|
|
3606
|
-
|
|
3607
|
-
writeFileSync2(`${options.outputDir}/${base}.summary.md`, summary);
|
|
4361
|
+
write(`${base}.summary.md`, summary);
|
|
3608
4362
|
logger.info(`summary written to ${base}.summary.md`);
|
|
3609
4363
|
} catch (err) {
|
|
3610
4364
|
logger.warn(`summary failed: ${err instanceof Error ? err.message : err}`);
|
|
4365
|
+
emit({ type: "stage", stage: "summary", state: "failed" });
|
|
3611
4366
|
}
|
|
3612
4367
|
}
|
|
3613
4368
|
}
|
|
3614
4369
|
try {
|
|
3615
|
-
const base = basename3(options.input, ext(options.input));
|
|
3616
4370
|
const partial = `${options.outputDir}/${base}.partial.md`;
|
|
3617
|
-
if (
|
|
4371
|
+
if (existsSync4(partial)) (await import("fs/promises")).unlink(partial);
|
|
3618
4372
|
} catch {
|
|
3619
4373
|
}
|
|
3620
4374
|
logger.info(`outputs written to ${options.outputDir}`);
|
|
3621
|
-
const
|
|
3622
|
-
const
|
|
4375
|
+
const spent = computeReceipt(getLlmUsage(), tsProvider, duration, asrBilled);
|
|
4376
|
+
const runMs = Date.now() - runStartedAt;
|
|
4377
|
+
const mins = Math.floor(runMs / 6e4);
|
|
4378
|
+
const secs = Math.round(runMs % 6e4 / 1e3);
|
|
3623
4379
|
logger.info(
|
|
3624
|
-
`receipt: ${
|
|
4380
|
+
`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`
|
|
3625
4381
|
);
|
|
3626
|
-
for (const line of
|
|
4382
|
+
for (const line of spent.lines) logger.info(` ${line}`);
|
|
3627
4383
|
recordRun(
|
|
3628
4384
|
{
|
|
3629
4385
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3630
4386
|
input: basename3(options.input),
|
|
3631
4387
|
durationSec: duration,
|
|
3632
|
-
wallMs,
|
|
4388
|
+
wallMs: runMs,
|
|
3633
4389
|
models: metadata.models,
|
|
3634
4390
|
segments: finalSegments.length,
|
|
3635
4391
|
characters: finalSegments.reduce((n, s) => n + s.text.length, 0),
|
|
3636
4392
|
speakers: speakers.length,
|
|
3637
|
-
llmCalls:
|
|
3638
|
-
inputTokens:
|
|
3639
|
-
outputTokens:
|
|
3640
|
-
costUsd:
|
|
4393
|
+
llmCalls: spent.totals.calls,
|
|
4394
|
+
inputTokens: spent.totals.inputTokens,
|
|
4395
|
+
outputTokens: spent.totals.outputTokens,
|
|
4396
|
+
costUsd: spent.totalUsd
|
|
3641
4397
|
},
|
|
3642
|
-
|
|
4398
|
+
spent.perModel
|
|
3643
4399
|
);
|
|
4400
|
+
emit({
|
|
4401
|
+
type: "done",
|
|
4402
|
+
segments: finalSegments.length,
|
|
4403
|
+
speakers: speakers.length,
|
|
4404
|
+
durationSec: duration,
|
|
4405
|
+
costUsd: spent.totalUsd,
|
|
4406
|
+
wallMs: runMs,
|
|
4407
|
+
retriedChunks: quality.filter((q) => q.status === "retried").length,
|
|
4408
|
+
outputs: written
|
|
4409
|
+
});
|
|
3644
4410
|
return result;
|
|
3645
4411
|
}
|
|
3646
4412
|
function ext(p) {
|
|
@@ -3650,12 +4416,20 @@ function ext(p) {
|
|
|
3650
4416
|
|
|
3651
4417
|
// src/commands/models.ts
|
|
3652
4418
|
var TRANSCRIBE_PRESETS = [
|
|
3653
|
-
{
|
|
3654
|
-
|
|
3655
|
-
|
|
3656
|
-
|
|
3657
|
-
{
|
|
3658
|
-
|
|
4419
|
+
{
|
|
4420
|
+
model: DEFAULT_TRANSCRIBE_MODEL,
|
|
4421
|
+
note: "kept 96.6% of the speech on hard chunks, $0.74/hour"
|
|
4422
|
+
},
|
|
4423
|
+
{
|
|
4424
|
+
model: PRO_TRANSCRIBE_MODEL,
|
|
4425
|
+
note: "--pro \xB7 kept the most (97.3%), slower, ~2\xD7 from 1 Dec"
|
|
4426
|
+
},
|
|
4427
|
+
{ model: "gemini-3.8-flash", note: "about a third of the cost until 1 Jan 2027" },
|
|
4428
|
+
{
|
|
4429
|
+
model: "gemini-3.1-pro-preview",
|
|
4430
|
+
note: "the 0.1.x default; dropped whole chunks on hard audio"
|
|
4431
|
+
},
|
|
4432
|
+
{ model: "gemini-flash-latest", note: "moving alias, stays current" }
|
|
3659
4433
|
];
|
|
3660
4434
|
var TIMESTAMPED_PRESETS = [
|
|
3661
4435
|
{
|
|
@@ -3706,6 +4480,14 @@ async function runModels() {
|
|
|
3706
4480
|
lines.push('(e.g. "zai:glm-4.7") works for --reasoner. Keys come from the environment');
|
|
3707
4481
|
lines.push("or can be injected via the library API.");
|
|
3708
4482
|
lines.push("");
|
|
4483
|
+
lines.push(
|
|
4484
|
+
"Zero storage (on by default) asks Gemini and AssemblyAI to keep nothing. The other"
|
|
4485
|
+
);
|
|
4486
|
+
lines.push(
|
|
4487
|
+
"providers have no way to be asked; each run's plan line names the ones it uses."
|
|
4488
|
+
);
|
|
4489
|
+
lines.push("--no-zero-storage leaves every provider to its own retention.");
|
|
4490
|
+
lines.push("");
|
|
3709
4491
|
console.log(lines.join("\n"));
|
|
3710
4492
|
}
|
|
3711
4493
|
|
|
@@ -3740,6 +4522,22 @@ function providerChecks(keys) {
|
|
|
3740
4522
|
{}
|
|
3741
4523
|
)
|
|
3742
4524
|
);
|
|
4525
|
+
for (const [model, role] of [
|
|
4526
|
+
[DEFAULT_TRANSCRIBE_MODEL, "default"],
|
|
4527
|
+
[PRO_TRANSCRIBE_MODEL, "--pro"]
|
|
4528
|
+
]) {
|
|
4529
|
+
checks.push({
|
|
4530
|
+
name: `${model} (${role})`,
|
|
4531
|
+
run: async () => {
|
|
4532
|
+
if (!keys.gemini) throw new Error("no key in environment");
|
|
4533
|
+
await ping(
|
|
4534
|
+
`https://generativelanguage.googleapis.com/v1beta/models/${model}?key=${keys.gemini}`,
|
|
4535
|
+
{}
|
|
4536
|
+
);
|
|
4537
|
+
return "available to this key";
|
|
4538
|
+
}
|
|
4539
|
+
});
|
|
4540
|
+
}
|
|
3743
4541
|
add(
|
|
3744
4542
|
"assemblyai (timestamped)",
|
|
3745
4543
|
keys.assemblyai,
|
|
@@ -3809,7 +4607,9 @@ async function runDoctor() {
|
|
|
3809
4607
|
const okByName = (needle) => checks.some(
|
|
3810
4608
|
(c, i) => c.name.startsWith(needle) && results[i]?.status === "fulfilled"
|
|
3811
4609
|
);
|
|
3812
|
-
const
|
|
4610
|
+
const keyOk = okByName("gemini (transcribe)");
|
|
4611
|
+
const modelOk = okByName(`${DEFAULT_TRANSCRIBE_MODEL} (default)`);
|
|
4612
|
+
const geminiOk = keyOk && modelOk;
|
|
3813
4613
|
const assemblyOk = okByName("assemblyai");
|
|
3814
4614
|
const elevenOk = okByName("elevenlabs");
|
|
3815
4615
|
const groqOk = okByName("groq");
|
|
@@ -3824,10 +4624,14 @@ async function runDoctor() {
|
|
|
3824
4624
|
`);
|
|
3825
4625
|
} else {
|
|
3826
4626
|
if (!ff) console.log(" Blocked: install ffmpeg (e.g. `brew install ffmpeg`).");
|
|
3827
|
-
if (!
|
|
4627
|
+
if (!keyOk)
|
|
3828
4628
|
console.log(
|
|
3829
4629
|
" Blocked: set GEMINI_API_KEY (or GOOGLE_API_KEY) \u2014 required for transcription."
|
|
3830
4630
|
);
|
|
4631
|
+
else if (!modelOk)
|
|
4632
|
+
console.log(
|
|
4633
|
+
` Blocked: this key can't use ${DEFAULT_TRANSCRIBE_MODEL}, the default \u2014 pass --model with one it can (\`offmute-v2 models\` lists them).`
|
|
4634
|
+
);
|
|
3831
4635
|
if (!assemblyOk && !elevenOk && !groqOk)
|
|
3832
4636
|
console.log(
|
|
3833
4637
|
" Degraded: no timestamped provider (ASSEMBLYAI/ELEVENLABS/GROQ key) \u2014 timestamps will be coarse."
|
|
@@ -3874,7 +4678,7 @@ No runs recorded yet (stats live in ${statsDir()}).
|
|
|
3874
4678
|
}
|
|
3875
4679
|
|
|
3876
4680
|
// src/commands/rename.ts
|
|
3877
|
-
import { existsSync as
|
|
4681
|
+
import { existsSync as existsSync5, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
|
|
3878
4682
|
import { basename as basename4, dirname as dirname4, join as join2, resolve as resolve3 } from "path";
|
|
3879
4683
|
function loadSource(path, opts) {
|
|
3880
4684
|
if (path.endsWith(".json")) {
|
|
@@ -3888,7 +4692,7 @@ function loadSource(path, opts) {
|
|
|
3888
4692
|
const cacheDir = opts.intermediates ?? deriveIntermediatesDir(path);
|
|
3889
4693
|
const resultPath = join2(cacheDir, "result.json");
|
|
3890
4694
|
const sourcePath = join2(cacheDir, "source.json");
|
|
3891
|
-
if (!
|
|
4695
|
+
if (!existsSync5(resultPath)) {
|
|
3892
4696
|
console.error(`\u2717 no cached transcript found for ${basename4(path)}`);
|
|
3893
4697
|
console.error(
|
|
3894
4698
|
` the cache lives in the OS temp dir and may have been cleaned up.
|
|
@@ -3962,7 +4766,7 @@ function runRename(path, mappings, opts) {
|
|
|
3962
4766
|
}
|
|
3963
4767
|
writeFileSync3(jsonPath, JSON.stringify(result, null, 2));
|
|
3964
4768
|
const idPath = join2(dirname4(jsonPath), "identified.json");
|
|
3965
|
-
if (basename4(jsonPath) === "result.json" &&
|
|
4769
|
+
if (basename4(jsonPath) === "result.json" && existsSync5(idPath)) {
|
|
3966
4770
|
try {
|
|
3967
4771
|
const id = JSON.parse(readFileSync3(idPath, "utf-8"));
|
|
3968
4772
|
id.nameMap ??= {};
|
|
@@ -3995,14 +4799,14 @@ function runRename(path, mappings, opts) {
|
|
|
3995
4799
|
|
|
3996
4800
|
// src/commands/watch.ts
|
|
3997
4801
|
import {
|
|
3998
|
-
existsSync as
|
|
4802
|
+
existsSync as existsSync6,
|
|
3999
4803
|
mkdirSync as mkdirSync3,
|
|
4000
4804
|
readFileSync as readFileSync4,
|
|
4001
4805
|
writeFileSync as writeFileSync4,
|
|
4002
4806
|
appendFileSync as appendFileSync3,
|
|
4003
4807
|
watch as fsWatch,
|
|
4004
4808
|
statSync as statSync2,
|
|
4005
|
-
readdirSync
|
|
4809
|
+
readdirSync as readdirSync2
|
|
4006
4810
|
} from "fs";
|
|
4007
4811
|
import { join as join3, extname, basename as basename5 } from "path";
|
|
4008
4812
|
|
|
@@ -4050,7 +4854,7 @@ function ts() {
|
|
|
4050
4854
|
return (/* @__PURE__ */ new Date()).toTimeString().slice(0, 8);
|
|
4051
4855
|
}
|
|
4052
4856
|
async function runWatch(dir, opts) {
|
|
4053
|
-
if (!
|
|
4857
|
+
if (!existsSync6(dir) || !statSync2(dir).isDirectory()) {
|
|
4054
4858
|
console.error(`\u2717 not a directory: ${dir}`);
|
|
4055
4859
|
process.exit(1);
|
|
4056
4860
|
}
|
|
@@ -4059,7 +4863,7 @@ async function runWatch(dir, opts) {
|
|
|
4059
4863
|
const statePath = join3(stateDir, "state.json");
|
|
4060
4864
|
const logPath2 = join3(stateDir, "daemon.log");
|
|
4061
4865
|
let state = { done: {} };
|
|
4062
|
-
if (
|
|
4866
|
+
if (existsSync6(statePath)) {
|
|
4063
4867
|
try {
|
|
4064
4868
|
const parsed = JSON.parse(readFileSync4(statePath, "utf-8"));
|
|
4065
4869
|
state = { done: parsed.done ?? {} };
|
|
@@ -4084,7 +4888,7 @@ async function runWatch(dir, opts) {
|
|
|
4084
4888
|
let processed = 0;
|
|
4085
4889
|
const listCandidates = () => {
|
|
4086
4890
|
try {
|
|
4087
|
-
return
|
|
4891
|
+
return readdirSync2(dir).filter((f) => !f.startsWith(".")).filter((f) => matchExts.has(extname(f).toLowerCase())).map((f) => join3(dir, f));
|
|
4088
4892
|
} catch {
|
|
4089
4893
|
return [];
|
|
4090
4894
|
}
|
|
@@ -4239,165 +5043,374 @@ async function runWatch(dir, opts) {
|
|
|
4239
5043
|
|
|
4240
5044
|
// src/utils/ui.ts
|
|
4241
5045
|
import chalk from "chalk";
|
|
4242
|
-
|
|
5046
|
+
import { stripVTControlCharacters } from "util";
|
|
4243
5047
|
var TICK = chalk.green("\u2713");
|
|
4244
5048
|
var WARN = chalk.yellow("\u25B2");
|
|
4245
5049
|
var FAIL = chalk.red("\u2717");
|
|
4246
|
-
var
|
|
5050
|
+
var DOT = chalk.dim(" \xB7 ");
|
|
5051
|
+
var STAGES = {
|
|
5052
|
+
preprocess: { doing: "preparing the media", done: "prepared the media" },
|
|
5053
|
+
describe: { doing: "listening for who's there", done: "listened for who's there" },
|
|
5054
|
+
transcribe: { doing: "transcribing", done: "transcribed" },
|
|
5055
|
+
align: {
|
|
5056
|
+
doing: "matching lines to the word times",
|
|
5057
|
+
done: "matched lines to the word times"
|
|
5058
|
+
},
|
|
5059
|
+
speakers: { doing: "telling the voices apart", done: "told the voices apart" },
|
|
5060
|
+
identify: { doing: "naming the speakers", done: "named the speakers" },
|
|
5061
|
+
finalize: { doing: "finishing", done: "finished" },
|
|
5062
|
+
summary: { doing: "writing the summary", done: "wrote the summary" }
|
|
5063
|
+
};
|
|
5064
|
+
var BARS = "\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";
|
|
5065
|
+
function meter(now, phase, paint) {
|
|
5066
|
+
let bars = "";
|
|
5067
|
+
for (let i = 0; i < 3; i++) {
|
|
5068
|
+
const level = 0.5 + 0.5 * Math.sin(now / 150 + phase + i * 2.1) * Math.sin(now / 420 + i * 1.3);
|
|
5069
|
+
bars += BARS.charAt(Math.round(level * 7));
|
|
5070
|
+
}
|
|
5071
|
+
return paint(bars);
|
|
5072
|
+
}
|
|
5073
|
+
var SHIMMER_CELLS_PER_S = 25;
|
|
4247
5074
|
var SHIMMER_PADDING = 8;
|
|
4248
5075
|
var SHIMMER_HALF_WIDTH = 5;
|
|
4249
5076
|
function shimmer(text, now) {
|
|
4250
5077
|
const chars = [...text];
|
|
4251
5078
|
const period = chars.length + SHIMMER_PADDING * 2;
|
|
4252
|
-
const
|
|
5079
|
+
const crest = now / 1e3 * SHIMMER_CELLS_PER_S % period;
|
|
4253
5080
|
let out = "";
|
|
4254
|
-
let runTier = -1;
|
|
4255
5081
|
let run2 = "";
|
|
5082
|
+
let runTier = -1;
|
|
4256
5083
|
const flush = () => {
|
|
4257
|
-
if (
|
|
4258
|
-
|
|
5084
|
+
if (run2)
|
|
5085
|
+
out += runTier === 2 ? chalk.bold(run2) : runTier === 1 ? run2 : chalk.dim(run2);
|
|
4259
5086
|
run2 = "";
|
|
4260
5087
|
};
|
|
4261
|
-
|
|
4262
|
-
const dist = Math.abs(i + SHIMMER_PADDING -
|
|
5088
|
+
chars.forEach((ch, i) => {
|
|
5089
|
+
const dist = Math.abs(i + SHIMMER_PADDING - crest);
|
|
4263
5090
|
const intensity = dist >= SHIMMER_HALF_WIDTH ? 0 : 0.5 * (1 + Math.cos(Math.PI * dist / SHIMMER_HALF_WIDTH));
|
|
4264
5091
|
const tier = intensity >= 0.65 ? 2 : intensity >= 0.2 ? 1 : 0;
|
|
4265
5092
|
if (tier !== runTier) {
|
|
4266
5093
|
flush();
|
|
4267
5094
|
runTier = tier;
|
|
4268
5095
|
}
|
|
4269
|
-
run2 +=
|
|
4270
|
-
}
|
|
5096
|
+
run2 += ch;
|
|
5097
|
+
});
|
|
4271
5098
|
flush();
|
|
4272
5099
|
return out;
|
|
4273
5100
|
}
|
|
4274
|
-
|
|
4275
|
-
|
|
4276
|
-
|
|
4277
|
-
|
|
4278
|
-
|
|
4279
|
-
|
|
4280
|
-
|
|
4281
|
-
|
|
4282
|
-
|
|
4283
|
-
|
|
4284
|
-
if (raw.startsWith("timestamped")) return raw.replace("timestamped", "timestamps");
|
|
4285
|
-
if (raw.startsWith("identify")) return raw.replace("identify", "naming speakers");
|
|
4286
|
-
return STAGE_LABELS[raw] ?? raw;
|
|
5101
|
+
function wordmark() {
|
|
5102
|
+
const letters = [..."offmute"];
|
|
5103
|
+
return letters.map((ch, i) => {
|
|
5104
|
+
const t = i / (letters.length - 1);
|
|
5105
|
+
return chalk.bold.rgb(
|
|
5106
|
+
Math.round(20 + 81 * t),
|
|
5107
|
+
Math.round(184 - 21 * t),
|
|
5108
|
+
Math.round(166 - 153 * t)
|
|
5109
|
+
)(ch);
|
|
5110
|
+
}).join("");
|
|
4287
5111
|
}
|
|
5112
|
+
var breathe = (now, i) => Math.sin(now / 130 - i * 0.8) > 0;
|
|
5113
|
+
var CELLS = {
|
|
5114
|
+
pending: () => chalk.dim("\u25B1"),
|
|
5115
|
+
running: (now, i) => breathe(now, i) ? chalk.cyan("\u25B0") : chalk.cyan("\u25B1"),
|
|
5116
|
+
done: () => chalk.green("\u25B0"),
|
|
5117
|
+
cached: () => chalk.green.dim("\u25B0"),
|
|
5118
|
+
failed: () => chalk.red("\u25B0"),
|
|
5119
|
+
retrying: (now, i) => breathe(now, i) ? chalk.yellow("\u25B0") : chalk.yellow("\u25B1"),
|
|
5120
|
+
recovered: () => chalk.yellow("\u25B0"),
|
|
5121
|
+
unchanged: () => chalk.red("\u25B0")
|
|
5122
|
+
};
|
|
5123
|
+
var MAX_CELLS = 48;
|
|
4288
5124
|
var active = false;
|
|
4289
|
-
var timer
|
|
4290
|
-
var
|
|
4291
|
-
var
|
|
4292
|
-
var
|
|
4293
|
-
|
|
5125
|
+
var timer;
|
|
5126
|
+
var liveRows = 0;
|
|
5127
|
+
var lane = null;
|
|
5128
|
+
var asr = null;
|
|
5129
|
+
var clockName = "the timing ASR";
|
|
5130
|
+
var cellsTotal = 0;
|
|
5131
|
+
var cells = /* @__PURE__ */ new Map();
|
|
5132
|
+
var redone = 0;
|
|
5133
|
+
var restoreConsole = [];
|
|
5134
|
+
function cellWidth(cp) {
|
|
5135
|
+
if (cp >= 768 && cp <= 879 || cp >= 8203 && cp <= 8207 || cp >= 65024 && cp <= 65039) {
|
|
5136
|
+
return 0;
|
|
5137
|
+
}
|
|
5138
|
+
const wide = cp >= 4352 && cp <= 4447 || cp >= 11904 && cp <= 42191 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65072 && cp <= 65103 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510 || cp >= 127744 && cp <= 129791 || cp >= 131072 && cp <= 262141;
|
|
5139
|
+
return wide ? 2 : 1;
|
|
5140
|
+
}
|
|
5141
|
+
function columnsOf(text) {
|
|
5142
|
+
let n = 0;
|
|
5143
|
+
for (const ch of stripVTControlCharacters(text)) n += cellWidth(ch.codePointAt(0));
|
|
5144
|
+
return n;
|
|
5145
|
+
}
|
|
5146
|
+
var ESCAPE_AT = /\x1b\[[0-9;?]*[A-Za-z]/y;
|
|
5147
|
+
function fit(line, max) {
|
|
5148
|
+
if (columnsOf(line) < max) return line;
|
|
5149
|
+
let out = "";
|
|
5150
|
+
let used = 0;
|
|
5151
|
+
for (let i = 0; i < line.length; ) {
|
|
5152
|
+
ESCAPE_AT.lastIndex = i;
|
|
5153
|
+
const escape = ESCAPE_AT.exec(line);
|
|
5154
|
+
if (escape) {
|
|
5155
|
+
out += escape[0];
|
|
5156
|
+
i = ESCAPE_AT.lastIndex;
|
|
5157
|
+
continue;
|
|
5158
|
+
}
|
|
5159
|
+
const ch = String.fromCodePoint(line.codePointAt(i));
|
|
5160
|
+
const w = cellWidth(ch.codePointAt(0));
|
|
5161
|
+
if (used + w > max - 2) break;
|
|
5162
|
+
out += ch;
|
|
5163
|
+
used += w;
|
|
5164
|
+
i += ch.length;
|
|
5165
|
+
}
|
|
5166
|
+
return `${out}\x1B[0m${chalk.dim("\u2026")}`;
|
|
5167
|
+
}
|
|
5168
|
+
var columns = () => Math.max(20, process.stdout.columns || 100);
|
|
5169
|
+
function eraseLive() {
|
|
5170
|
+
if (liveRows === 0) return "";
|
|
5171
|
+
const up = liveRows > 1 ? `\x1B[${liveRows - 1}A` : "";
|
|
5172
|
+
liveRows = 0;
|
|
5173
|
+
return `${up}\r\x1B[0J`;
|
|
5174
|
+
}
|
|
5175
|
+
function draw() {
|
|
5176
|
+
if (!active) return;
|
|
5177
|
+
const lines = liveLines(Date.now()).map((l) => fit(l, columns()));
|
|
5178
|
+
process.stdout.write(eraseLive() + lines.join("\n"));
|
|
5179
|
+
liveRows = lines.length;
|
|
5180
|
+
}
|
|
5181
|
+
function println(text = "") {
|
|
5182
|
+
process.stdout.write(`${eraseLive()}${text}
|
|
5183
|
+
`);
|
|
5184
|
+
draw();
|
|
5185
|
+
}
|
|
5186
|
+
function elapsed(ms) {
|
|
4294
5187
|
const s = Math.floor(ms / 1e3);
|
|
4295
|
-
return s >= 60 ? `${Math.floor(s / 60)}m${(s % 60).
|
|
5188
|
+
return s >= 60 ? `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s` : `${s}s`;
|
|
5189
|
+
}
|
|
5190
|
+
function audioLength(sec) {
|
|
5191
|
+
if (sec < 60) return `${Math.round(sec)}s`;
|
|
5192
|
+
if (sec < 3600) return `${Math.round(sec / 60)} min`;
|
|
5193
|
+
return `${Math.floor(sec / 3600)}h ${String(Math.round(sec % 3600 / 60)).padStart(2, "0")}m`;
|
|
4296
5194
|
}
|
|
4297
|
-
|
|
4298
|
-
|
|
4299
|
-
|
|
4300
|
-
|
|
5195
|
+
var count = (n) => n.toLocaleString("en-US");
|
|
5196
|
+
function languageName(code) {
|
|
5197
|
+
if (!code) return void 0;
|
|
5198
|
+
try {
|
|
5199
|
+
return new Intl.DisplayNames(["en"], { type: "language" }).of(code) ?? code;
|
|
5200
|
+
} catch {
|
|
5201
|
+
return code;
|
|
4301
5202
|
}
|
|
4302
5203
|
}
|
|
4303
|
-
function
|
|
4304
|
-
if (
|
|
4305
|
-
|
|
4306
|
-
|
|
4307
|
-
|
|
4308
|
-
|
|
4309
|
-
|
|
4310
|
-
const
|
|
4311
|
-
const
|
|
4312
|
-
|
|
4313
|
-
|
|
5204
|
+
function strip(now) {
|
|
5205
|
+
if (cellsTotal === 0 || cellsTotal > MAX_CELLS) return "";
|
|
5206
|
+
let out = "";
|
|
5207
|
+
for (let i = 0; i < cellsTotal; i++) out += CELLS[cells.get(i) ?? "pending"](now, i);
|
|
5208
|
+
return ` ${out}`;
|
|
5209
|
+
}
|
|
5210
|
+
function chunkTally() {
|
|
5211
|
+
const states = [...cells.values()];
|
|
5212
|
+
const working = states.filter((c) => c === "running" || c === "retrying").length;
|
|
5213
|
+
return chalk.dim(
|
|
5214
|
+
` ${states.length - working}/${cellsTotal} chunk${cellsTotal === 1 ? "" : "s"}${working ? ` \xB7 ${working} running` : ""}`
|
|
5215
|
+
);
|
|
4314
5216
|
}
|
|
4315
|
-
function
|
|
4316
|
-
|
|
4317
|
-
|
|
4318
|
-
|
|
4319
|
-
|
|
4320
|
-
|
|
4321
|
-
|
|
4322
|
-
|
|
4323
|
-
|
|
4324
|
-
|
|
4325
|
-
|
|
4326
|
-
|
|
4327
|
-
|
|
4328
|
-
|
|
5217
|
+
function liveLines(now) {
|
|
5218
|
+
const lines = [];
|
|
5219
|
+
if (lane) {
|
|
5220
|
+
const mid = lane.stage === "transcribe" && cellsTotal > 0 ? `${strip(now)}${chunkTally()}` : lane.status || lane.detail ? chalk.dim(` \xB7 ${lane.status || lane.detail}`) : "";
|
|
5221
|
+
lines.push(
|
|
5222
|
+
`${meter(now, 0, chalk.cyan)} ${shimmer(STAGES[lane.stage].doing, now)}${mid} ${chalk.dim(elapsed(now - lane.startedAt))}`
|
|
5223
|
+
);
|
|
5224
|
+
}
|
|
5225
|
+
if (asr) {
|
|
5226
|
+
lines.push(
|
|
5227
|
+
`${meter(now, 1.7, chalk.magenta)} ${chalk.dim(`timing every word \xB7 ${asr.provider} ${elapsed(now - asr.startedAt)}`)}`
|
|
5228
|
+
);
|
|
5229
|
+
}
|
|
5230
|
+
return lines;
|
|
4329
5231
|
}
|
|
4330
|
-
function
|
|
4331
|
-
|
|
4332
|
-
|
|
4333
|
-
|
|
5232
|
+
function completeLane() {
|
|
5233
|
+
if (!lane) return;
|
|
5234
|
+
const now = Date.now();
|
|
5235
|
+
const { stage, startedAt, detail } = lane;
|
|
5236
|
+
lane = null;
|
|
5237
|
+
let mid = detail ? chalk.dim(` \xB7 ${detail}`) : "";
|
|
5238
|
+
if (stage === "transcribe" && cellsTotal > 0) {
|
|
5239
|
+
mid = `${strip(now)}${chalk.dim(
|
|
5240
|
+
` ${cellsTotal} chunk${cellsTotal === 1 ? "" : "s"}${redone ? ` \xB7 ${redone} redone in halves` : ""}`
|
|
5241
|
+
)}`;
|
|
5242
|
+
}
|
|
5243
|
+
println(`${TICK} ${STAGES[stage].done}${mid} ${chalk.dim(elapsed(now - startedAt))}`);
|
|
5244
|
+
}
|
|
5245
|
+
var span = (startSec, endSec) => `${compactTime(startSec)}\u2013${compactTime(endSec)}`;
|
|
5246
|
+
function onProgress(e) {
|
|
5247
|
+
if (!active) return;
|
|
5248
|
+
switch (e.type) {
|
|
5249
|
+
case "plan": {
|
|
5250
|
+
completeLane();
|
|
5251
|
+
if (e.asr !== "none") clockName = e.asr;
|
|
5252
|
+
const bits = [
|
|
5253
|
+
`${chalk.bold(audioLength(e.durationSec))} of audio`,
|
|
5254
|
+
chalk.cyan(e.model),
|
|
5255
|
+
e.asr === "none" ? chalk.yellow("the LLM's own timestamps") : `timed by ${e.asr}`,
|
|
5256
|
+
`${chalk.yellow(`~$${e.estimateUsd.toFixed(2)}`)} estimated`
|
|
5257
|
+
];
|
|
5258
|
+
println(` ${bits.join(DOT)}`);
|
|
5259
|
+
if (e.zeroStorage) {
|
|
5260
|
+
const unasked = e.notAsked.map((p) => p.name).join(", ");
|
|
5261
|
+
println(
|
|
5262
|
+
` ${chalk.green("zero storage")}${unasked ? chalk.dim(` \xB7 ${unasked} can't be asked to keep nothing`) : ""}`
|
|
5263
|
+
);
|
|
5264
|
+
}
|
|
5265
|
+
println();
|
|
5266
|
+
return;
|
|
5267
|
+
}
|
|
5268
|
+
case "stage":
|
|
5269
|
+
if (e.state === "failed") {
|
|
5270
|
+
if (lane?.stage === e.stage) {
|
|
5271
|
+
const took = elapsed(Date.now() - lane.startedAt);
|
|
5272
|
+
lane = null;
|
|
5273
|
+
println(`${FAIL} ${STAGES[e.stage].doing} failed ${chalk.dim(took)}`);
|
|
5274
|
+
}
|
|
5275
|
+
return;
|
|
5276
|
+
}
|
|
5277
|
+
completeLane();
|
|
5278
|
+
if (e.state === "cached") {
|
|
5279
|
+
println(`${TICK} ${STAGES[e.stage].done}${chalk.dim(" \xB7 from the cache")}`);
|
|
5280
|
+
return;
|
|
5281
|
+
}
|
|
5282
|
+
lane = {
|
|
5283
|
+
stage: e.stage,
|
|
5284
|
+
startedAt: Date.now(),
|
|
5285
|
+
detail: e.detail ?? "",
|
|
5286
|
+
status: ""
|
|
5287
|
+
};
|
|
5288
|
+
draw();
|
|
5289
|
+
return;
|
|
5290
|
+
case "asr": {
|
|
5291
|
+
if (e.state === "start") {
|
|
5292
|
+
asr = { provider: e.provider, startedAt: Date.now() };
|
|
5293
|
+
draw();
|
|
5294
|
+
return;
|
|
5295
|
+
}
|
|
5296
|
+
const took = asr ? ` ${chalk.dim(elapsed(Date.now() - asr.startedAt))}` : "";
|
|
5297
|
+
asr = null;
|
|
5298
|
+
if (e.state === "failed") {
|
|
5299
|
+
println(
|
|
5300
|
+
`${FAIL} timing every word \xB7 ${e.provider} failed${chalk.dim(" \xB7 the run stops when transcription ends; finished chunks stay cached")}`
|
|
5301
|
+
);
|
|
5302
|
+
return;
|
|
5303
|
+
}
|
|
5304
|
+
const facts = [
|
|
5305
|
+
e.words !== void 0 && `${count(e.words)} words`,
|
|
5306
|
+
e.speakers && `${e.speakers} voices`,
|
|
5307
|
+
languageName(e.language),
|
|
5308
|
+
e.state === "cached" && "from the cache"
|
|
5309
|
+
].filter(Boolean);
|
|
5310
|
+
println(
|
|
5311
|
+
`${TICK} timed every word \xB7 ${e.provider}${chalk.dim(facts.map((f) => ` \xB7 ${f}`).join(""))}${took}`
|
|
5312
|
+
);
|
|
5313
|
+
return;
|
|
5314
|
+
}
|
|
5315
|
+
case "chunks":
|
|
5316
|
+
cellsTotal = e.total;
|
|
5317
|
+
cells.clear();
|
|
5318
|
+
redone = 0;
|
|
5319
|
+
draw();
|
|
5320
|
+
return;
|
|
5321
|
+
case "chunk":
|
|
5322
|
+
cells.set(e.index, e.state);
|
|
5323
|
+
if (e.state === "failed") {
|
|
5324
|
+
println(`${FAIL} chunk ${e.index + 1}: ${chalk.red(e.error ?? "failed")}`);
|
|
5325
|
+
}
|
|
5326
|
+
draw();
|
|
5327
|
+
return;
|
|
5328
|
+
case "guard": {
|
|
5329
|
+
const where = span(e.startSec, e.endSec);
|
|
5330
|
+
if (e.state === "retrying") {
|
|
5331
|
+
cells.set(e.index, "retrying");
|
|
5332
|
+
println(
|
|
5333
|
+
` ${chalk.yellow("\u21BB")} ${where} came back short${chalk.dim(` \xB7 ${count(e.llmWords)} words where ${clockName} heard ${count(e.asrWords)}`)} \xB7 transcribing it again in two halves`
|
|
5334
|
+
);
|
|
5335
|
+
} else if (e.state === "recovered") {
|
|
5336
|
+
cells.set(e.index, "recovered");
|
|
5337
|
+
redone++;
|
|
5338
|
+
println(
|
|
5339
|
+
` ${TICK} ${where} recovered${chalk.dim(` \xB7 ${count(e.retryWords ?? 0)} words`)}`
|
|
5340
|
+
);
|
|
5341
|
+
} else {
|
|
5342
|
+
cells.set(e.index, "unchanged");
|
|
5343
|
+
println(
|
|
5344
|
+
` ${WARN} ${where}: the halves did no better${chalk.dim(` \xB7 kept the first attempt; ${clockName}'s words fill its gaps`)}`
|
|
5345
|
+
);
|
|
5346
|
+
}
|
|
5347
|
+
draw();
|
|
5348
|
+
return;
|
|
5349
|
+
}
|
|
5350
|
+
case "names": {
|
|
5351
|
+
const pairs = Object.entries(e.names);
|
|
5352
|
+
if (pairs.length) {
|
|
5353
|
+
println(
|
|
5354
|
+
` ${chalk.magenta("\u25C6")} ${pairs.map(([id, name]) => `${chalk.dim(`${id} \u2192`)} ${chalk.bold(name)}`).join(DOT)}`
|
|
5355
|
+
);
|
|
5356
|
+
}
|
|
5357
|
+
return;
|
|
5358
|
+
}
|
|
5359
|
+
case "done":
|
|
5360
|
+
completeLane();
|
|
5361
|
+
return;
|
|
5362
|
+
}
|
|
4334
5363
|
}
|
|
4335
5364
|
function handleLine(level, msg) {
|
|
4336
|
-
if (level === "warn") {
|
|
4337
|
-
println(`${WARN} ${chalk.yellow(msg)}`);
|
|
4338
|
-
return;
|
|
4339
|
-
}
|
|
4340
5365
|
if (level === "error") {
|
|
4341
5366
|
println(`${FAIL} ${chalk.red(msg)}`);
|
|
4342
5367
|
return;
|
|
4343
5368
|
}
|
|
4344
|
-
|
|
4345
|
-
|
|
4346
|
-
|
|
5369
|
+
if (level === "warn") {
|
|
5370
|
+
if (!msg.includes("transcribing it again in two halves")) {
|
|
5371
|
+
println(`${WARN} ${chalk.yellow(msg)}`);
|
|
5372
|
+
}
|
|
4347
5373
|
return;
|
|
4348
5374
|
}
|
|
4349
|
-
|
|
4350
|
-
|
|
4351
|
-
|
|
4352
|
-
stage.chunksDone = 0;
|
|
5375
|
+
if (msg.startsWith("description:")) {
|
|
5376
|
+
completeLane();
|
|
5377
|
+
println(fit(chalk.dim(` ${msg.slice(12).trim().replace(/\s+/g, " ")}`), columns()));
|
|
4353
5378
|
return;
|
|
4354
5379
|
}
|
|
4355
|
-
if (
|
|
4356
|
-
|
|
4357
|
-
drawSpinner();
|
|
5380
|
+
if (msg.startsWith("intermediates:")) {
|
|
5381
|
+
println(chalk.dim(` cache ${msg.slice(14).trim().split(" (file://")[0]}`));
|
|
4358
5382
|
return;
|
|
4359
5383
|
}
|
|
4360
|
-
if (msg.startsWith("
|
|
4361
|
-
|
|
4362
|
-
/^estimated cost (~\$[\d.]+)(.*)$/,
|
|
4363
|
-
(_, amt, rest) => `${chalk.bold("estimate")} ${chalk.yellow(amt)}${chalk.dim(rest)}`
|
|
4364
|
-
);
|
|
4365
|
-
println(` ${pretty}`);
|
|
5384
|
+
if (msg.startsWith("identify:")) {
|
|
5385
|
+
println(` ${chalk.magenta("\u25C6")} ${chalk.dim(msg.slice(9).trim())}`);
|
|
4366
5386
|
return;
|
|
4367
5387
|
}
|
|
4368
5388
|
if (msg.startsWith("receipt:")) {
|
|
4369
|
-
|
|
4370
|
-
println(`
|
|
5389
|
+
completeLane();
|
|
5390
|
+
println(`
|
|
5391
|
+
${chalk.bold("receipt")} ${chalk.yellow(msg.slice(9))}`);
|
|
4371
5392
|
return;
|
|
4372
5393
|
}
|
|
4373
5394
|
if (msg.startsWith(" ") && /\$\d/.test(msg)) {
|
|
4374
|
-
println(chalk.dim(`
|
|
4375
|
-
return;
|
|
4376
|
-
}
|
|
4377
|
-
if (msg.startsWith("identified ") || msg.startsWith("identify:")) {
|
|
4378
|
-
println(` ${chalk.magenta("\u25C6")} ${msg}`);
|
|
4379
|
-
return;
|
|
4380
|
-
}
|
|
4381
|
-
if (msg.startsWith("description:")) {
|
|
4382
|
-
const text = msg.slice(12).trim().replace(/\s+/g, " ");
|
|
4383
|
-
println(
|
|
4384
|
-
chalk.dim(` ${text.slice(0, Math.max(40, (process.stdout.columns || 100) - 4))}`)
|
|
4385
|
-
);
|
|
4386
|
-
return;
|
|
4387
|
-
}
|
|
4388
|
-
if (msg.startsWith("intermediates:")) {
|
|
4389
|
-
const p = msg.slice(14).trim().split(" (file://")[0];
|
|
4390
|
-
println(chalk.dim(` cache ${p}`));
|
|
4391
|
-
return;
|
|
4392
|
-
}
|
|
4393
|
-
if (msg.startsWith("outputs written")) {
|
|
5395
|
+
println(chalk.dim(` ${msg.trim()}`));
|
|
4394
5396
|
return;
|
|
4395
5397
|
}
|
|
4396
|
-
if (stage) {
|
|
4397
|
-
|
|
4398
|
-
|
|
5398
|
+
if (lane?.stage === "preprocess" && msg.startsWith("extracting ")) {
|
|
5399
|
+
lane.status = msg.replace(/ \(.*\)/, "").replace(/\.{3}$/, "");
|
|
5400
|
+
draw();
|
|
4399
5401
|
}
|
|
4400
5402
|
}
|
|
5403
|
+
var showCursor = () => process.stdout.write("\x1B[?25h");
|
|
5404
|
+
function stopOnSignal(signal) {
|
|
5405
|
+
process.stdout.write(eraseLive());
|
|
5406
|
+
showCursor();
|
|
5407
|
+
process.stdout.write(
|
|
5408
|
+
`
|
|
5409
|
+
${WARN} ${chalk.yellow("stopped")}${chalk.dim(" \xB7 what finished is cached; run the same command again to carry on")}
|
|
5410
|
+
`
|
|
5411
|
+
);
|
|
5412
|
+
process.exit(signal === "SIGINT" ? 130 : 143);
|
|
5413
|
+
}
|
|
4401
5414
|
function configureUi(opts) {
|
|
4402
5415
|
active = opts.enabled;
|
|
4403
5416
|
if (!active) return;
|
|
@@ -4405,9 +5418,22 @@ function configureUi(opts) {
|
|
|
4405
5418
|
handleLine(level, msg);
|
|
4406
5419
|
return true;
|
|
4407
5420
|
});
|
|
4408
|
-
|
|
4409
|
-
|
|
4410
|
-
|
|
5421
|
+
for (const name of ["log", "info", "warn", "error"]) {
|
|
5422
|
+
const original = console[name];
|
|
5423
|
+
console[name] = (...args) => {
|
|
5424
|
+
process.stdout.write(eraseLive());
|
|
5425
|
+
original(...args);
|
|
5426
|
+
draw();
|
|
5427
|
+
};
|
|
5428
|
+
restoreConsole.push(() => {
|
|
5429
|
+
console[name] = original;
|
|
5430
|
+
});
|
|
5431
|
+
}
|
|
5432
|
+
process.stdout.write("\x1B[?25l");
|
|
5433
|
+
process.once("exit", showCursor);
|
|
5434
|
+
process.once("SIGINT", stopOnSignal);
|
|
5435
|
+
process.once("SIGTERM", stopOnSignal);
|
|
5436
|
+
timer = setInterval(draw, 80);
|
|
4411
5437
|
timer.unref();
|
|
4412
5438
|
}
|
|
4413
5439
|
function uiActive() {
|
|
@@ -4415,40 +5441,43 @@ function uiActive() {
|
|
|
4415
5441
|
}
|
|
4416
5442
|
function finishUi() {
|
|
4417
5443
|
if (!active) return;
|
|
4418
|
-
|
|
4419
|
-
|
|
4420
|
-
|
|
4421
|
-
timer
|
|
5444
|
+
completeLane();
|
|
5445
|
+
asr = null;
|
|
5446
|
+
process.stdout.write(eraseLive());
|
|
5447
|
+
clearInterval(timer);
|
|
5448
|
+
timer = void 0;
|
|
5449
|
+
for (const restore of restoreConsole.splice(0)) restore();
|
|
5450
|
+
process.removeListener("SIGINT", stopOnSignal);
|
|
5451
|
+
process.removeListener("SIGTERM", stopOnSignal);
|
|
5452
|
+
showCursor();
|
|
4422
5453
|
active = false;
|
|
4423
5454
|
logger.setSink(null);
|
|
4424
5455
|
}
|
|
4425
5456
|
function banner(version, inputName) {
|
|
4426
5457
|
if (!active) return;
|
|
4427
|
-
|
|
5458
|
+
println(
|
|
4428
5459
|
`
|
|
4429
|
-
${
|
|
4430
|
-
|
|
4431
|
-
`
|
|
5460
|
+
${wordmark()}${chalk.dim("-v2")} ${chalk.dim(version)} ${chalk.bold(inputName)}`
|
|
4432
5461
|
);
|
|
4433
5462
|
}
|
|
4434
5463
|
function outputsBlock(files, summaryLine) {
|
|
4435
|
-
clearLine();
|
|
4436
|
-
process.stdout.write("\n");
|
|
4437
|
-
for (const f of files) {
|
|
4438
|
-
process.stdout.write(` ${chalk.green("\u2192")} ${f}
|
|
4439
|
-
`);
|
|
4440
|
-
}
|
|
4441
5464
|
process.stdout.write(`
|
|
4442
|
-
${chalk.bold(summaryLine)}
|
|
5465
|
+
${TICK} ${chalk.bold(summaryLine)}
|
|
5466
|
+
|
|
4443
5467
|
`);
|
|
5468
|
+
for (const f of files) {
|
|
5469
|
+
const slash = f.lastIndexOf("/");
|
|
5470
|
+
process.stdout.write(
|
|
5471
|
+
` ${chalk.green("\u2192")} ${chalk.dim(f.slice(0, slash + 1))}${chalk.bold(f.slice(slash + 1))}
|
|
5472
|
+
`
|
|
5473
|
+
);
|
|
5474
|
+
}
|
|
4444
5475
|
}
|
|
4445
5476
|
function tipsBlock(tips) {
|
|
4446
5477
|
if (tips.length === 0) return;
|
|
4447
5478
|
process.stdout.write("\n");
|
|
4448
|
-
for (const t of tips) {
|
|
4449
|
-
|
|
4450
|
-
`));
|
|
4451
|
-
}
|
|
5479
|
+
for (const t of tips) process.stdout.write(` ${chalk.cyan("tip")} ${chalk.dim(t)}
|
|
5480
|
+
`);
|
|
4452
5481
|
}
|
|
4453
5482
|
function starFooter() {
|
|
4454
5483
|
process.stdout.write(
|
|
@@ -4460,15 +5489,15 @@ function starFooter() {
|
|
|
4460
5489
|
);
|
|
4461
5490
|
}
|
|
4462
5491
|
function errorBlock(message, hint) {
|
|
4463
|
-
|
|
4464
|
-
if (
|
|
4465
|
-
if (stage) {
|
|
5492
|
+
process.stdout.write(eraseLive());
|
|
5493
|
+
if (lane) {
|
|
4466
5494
|
process.stderr.write(
|
|
4467
|
-
`${FAIL} ${stage.
|
|
5495
|
+
`${FAIL} ${STAGES[lane.stage].doing} ${chalk.dim(elapsed(Date.now() - lane.startedAt))}
|
|
4468
5496
|
`
|
|
4469
5497
|
);
|
|
4470
|
-
|
|
5498
|
+
lane = null;
|
|
4471
5499
|
}
|
|
5500
|
+
asr = null;
|
|
4472
5501
|
process.stderr.write(`
|
|
4473
5502
|
${FAIL} ${chalk.red(message)}
|
|
4474
5503
|
`);
|
|
@@ -4477,15 +5506,18 @@ ${FAIL} ${chalk.red(message)}
|
|
|
4477
5506
|
}
|
|
4478
5507
|
|
|
4479
5508
|
// src/commands/first-run.ts
|
|
4480
|
-
import { existsSync as
|
|
5509
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync5 } from "fs";
|
|
4481
5510
|
import { join as join4 } from "path";
|
|
4482
5511
|
import chalk2 from "chalk";
|
|
5512
|
+
var WHATS_NEW = {
|
|
5513
|
+
"0.2.0": `transcribes with ${DEFAULT_TRANSCRIBE_MODEL} (--pro: ${PRO_TRANSCRIBE_MODEL}), asks providers to keep nothing (--no-zero-storage turns that off), and a stopped run picks up where it left off`
|
|
5514
|
+
};
|
|
4483
5515
|
function maybeFirstRunCheck(version) {
|
|
4484
5516
|
let last = null;
|
|
4485
5517
|
const dir = statsDir();
|
|
4486
5518
|
const path = join4(dir, "last-version");
|
|
4487
5519
|
try {
|
|
4488
|
-
if (
|
|
5520
|
+
if (existsSync7(path)) last = readFileSync5(path, "utf-8").trim();
|
|
4489
5521
|
} catch {
|
|
4490
5522
|
}
|
|
4491
5523
|
if (last === version) return false;
|
|
@@ -4502,6 +5534,8 @@ function maybeFirstRunCheck(version) {
|
|
|
4502
5534
|
`first run of ${chalk2.reset.bold(version)}${chalk2.dim(" \u2014 checking your setup (offline; `offmute-v2 doctor` pings live)")}`
|
|
4503
5535
|
)
|
|
4504
5536
|
);
|
|
5537
|
+
const news = WHATS_NEW[version];
|
|
5538
|
+
if (news) lines.push(` ${chalk2.cyan("new")} ${chalk2.dim(news)}`);
|
|
4505
5539
|
lines.push(
|
|
4506
5540
|
` ${have(keys.gemini)} GEMINI_API_KEY ${chalk2.dim("transcription \u2014 required")}`
|
|
4507
5541
|
);
|
|
@@ -4531,7 +5565,9 @@ function maybeFirstRunCheck(version) {
|
|
|
4531
5565
|
"add ELEVENLABS_API_KEY to try Scribe v2 \u2014 the sharpest speaker separation we've tested on conversational audio"
|
|
4532
5566
|
);
|
|
4533
5567
|
if (!keys.deepseek)
|
|
4534
|
-
unlocks.push(
|
|
5568
|
+
unlocks.push(
|
|
5569
|
+
"add DEEPSEEK_API_KEY so speaker naming costs ~$0.003 a run (DeepSeek can't be asked to keep nothing)"
|
|
5570
|
+
);
|
|
4535
5571
|
for (const u of unlocks.slice(0, 2)) lines.push(chalk2.dim(` unlock: ${u}`));
|
|
4536
5572
|
process.stdout.write(lines.join("\n") + "\n\n");
|
|
4537
5573
|
return true;
|
|
@@ -4549,7 +5585,7 @@ var program = new Command();
|
|
|
4549
5585
|
program.name("offmute-v2").description(
|
|
4550
5586
|
"Diarized meeting transcription with multimodal LLMs + timestamped alignment."
|
|
4551
5587
|
).version(packageVersion);
|
|
4552
|
-
function buildTips(result, opts, input) {
|
|
5588
|
+
function buildTips(result, opts, input, plan) {
|
|
4553
5589
|
const tips = [];
|
|
4554
5590
|
const genericSpeakers = result.speakers.filter(
|
|
4555
5591
|
(sp) => !sp.name || /^Speaker [A-Z]$/.test(sp.name)
|
|
@@ -4559,9 +5595,14 @@ function buildTips(result, opts, input) {
|
|
|
4559
5595
|
`${genericSpeakers.length} speaker(s) stayed generic \u2014 retcon instantly: offmute-v2 rename "${input}" "${genericSpeakers[0].id}=Name", or pass --speakers "Alice,Bob" next time`
|
|
4560
5596
|
);
|
|
4561
5597
|
}
|
|
4562
|
-
|
|
5598
|
+
const unasked = plan?.notAsked ?? [];
|
|
5599
|
+
if (unasked.length > 0) {
|
|
5600
|
+
const fixes = [
|
|
5601
|
+
unasked.some((p) => p.role === "timing") && "--timestamped assemblyai",
|
|
5602
|
+
unasked.some((p) => p.role === "text") && "--reasoner gemini-flash-latest --identify single"
|
|
5603
|
+
].filter(Boolean);
|
|
4563
5604
|
tips.push(
|
|
4564
|
-
|
|
5605
|
+
`zero storage can't ask ${unasked.map((p) => p.name).join(" or ")} to keep nothing; ${fixes.join(" ")} keeps the whole run on providers it can ask`
|
|
4565
5606
|
);
|
|
4566
5607
|
}
|
|
4567
5608
|
if (!opts.formats && !opts.summary) {
|
|
@@ -4596,6 +5637,8 @@ async function runTranscribe(input, opts) {
|
|
|
4596
5637
|
banner(packageVersion, basename6(input));
|
|
4597
5638
|
if (pretty) maybeFirstRunCheck(packageVersion);
|
|
4598
5639
|
const t0 = Date.now();
|
|
5640
|
+
let plan;
|
|
5641
|
+
let done;
|
|
4599
5642
|
const result = await transcribe({
|
|
4600
5643
|
input,
|
|
4601
5644
|
outputDir: opts.output,
|
|
@@ -4614,37 +5657,38 @@ async function runTranscribe(input, opts) {
|
|
|
4614
5657
|
knownSpeakers: opts.speakers ? opts.speakers.split(",").map((s) => s.trim()).filter(Boolean) : void 0,
|
|
4615
5658
|
diarizationLevel: level,
|
|
4616
5659
|
identifyMode: opts.identify,
|
|
4617
|
-
model: opts.model,
|
|
5660
|
+
model: opts.pro ? PRO_TRANSCRIBE_MODEL : opts.model,
|
|
4618
5661
|
reasoner: opts.reasoner,
|
|
4619
5662
|
timestampedProvider: opts.timestamped,
|
|
5663
|
+
language: opts.language,
|
|
5664
|
+
zeroStorage: opts.zeroStorage,
|
|
4620
5665
|
force: opts.force,
|
|
4621
5666
|
onlyChunk: opts.onlyChunk ? parseInt(opts.onlyChunk, 10) : void 0,
|
|
4622
5667
|
saveIntermediates: opts.saveIntermediates,
|
|
4623
5668
|
showProgress: opts.progress,
|
|
4624
5669
|
llmLog: opts.llmLog,
|
|
4625
|
-
logLevel: opts.logLevel
|
|
5670
|
+
logLevel: opts.logLevel,
|
|
5671
|
+
onProgress: (e) => {
|
|
5672
|
+
if (e.type === "plan") plan = e;
|
|
5673
|
+
if (e.type === "done") done = e;
|
|
5674
|
+
onProgress(e);
|
|
5675
|
+
}
|
|
4626
5676
|
});
|
|
5677
|
+
const cost = done?.costUsd !== void 0 ? ` \xB7 ~$${done.costUsd.toFixed(2)}` : "";
|
|
4627
5678
|
if (uiActive()) {
|
|
4628
5679
|
finishUi();
|
|
4629
|
-
const
|
|
4630
|
-
const outDir = resolve4(opts.output ?? (dirname5(resolve4(input)) || "."));
|
|
4631
|
-
const formats = opts.formats ? opts.formats.split(",") : ["md"];
|
|
4632
|
-
const files = formats.map((f) => join5(outDir, `${base}.${f.trim()}`));
|
|
4633
|
-
if (opts.summary) files.push(join5(outDir, `${base}.summary.md`));
|
|
4634
|
-
const cost = result.metadata.cost ? ` \xB7 ~$${result.metadata.cost.actualUsd.toFixed(2)}` : "";
|
|
4635
|
-
const wall = result.metadata.wallMs ? ` \xB7 ${formatDuration(Math.round(result.metadata.wallMs / 1e3))}` : "";
|
|
5680
|
+
const wall = done ? ` \xB7 ${formatDuration(Math.round(done.wallMs / 1e3))}` : "";
|
|
4636
5681
|
outputsBlock(
|
|
4637
|
-
|
|
5682
|
+
done?.outputs ?? [],
|
|
4638
5683
|
`${result.segments.length} segments \xB7 ${result.speakers.length} speakers \xB7 ${formatDuration(Math.round(result.metadata.duration))} of audio${cost}${wall}`
|
|
4639
5684
|
);
|
|
4640
|
-
tipsBlock(buildTips(result, opts, input));
|
|
5685
|
+
tipsBlock(buildTips(result, opts, input, plan));
|
|
4641
5686
|
starFooter();
|
|
4642
5687
|
process.stdout.write("\n");
|
|
4643
5688
|
} else {
|
|
4644
5689
|
console.log(`Done. ${result.segments.length} segments.`);
|
|
4645
5690
|
}
|
|
4646
5691
|
if (opts.notify && Date.now() - t0 > 12e4) {
|
|
4647
|
-
const cost = result.metadata.cost ? ` \xB7 ~$${result.metadata.cost.actualUsd.toFixed(2)}` : "";
|
|
4648
5692
|
notify(
|
|
4649
5693
|
"offmute-v2",
|
|
4650
5694
|
`${basename6(input)} transcribed \u2014 ${result.segments.length} segments${cost}`
|
|
@@ -4674,10 +5718,21 @@ function addTranscribeOptions(cmd) {
|
|
|
4674
5718
|
"--identify <mode>",
|
|
4675
5719
|
"speaker naming: dual (two reasoners, default) | single",
|
|
4676
5720
|
"dual"
|
|
4677
|
-
).option("--model <name>", "override transcription model
|
|
5721
|
+
).option("--model <name>", "override transcription model (default gemini-4-hydrogen)").addOption(
|
|
5722
|
+
new Option(
|
|
5723
|
+
"--pro",
|
|
5724
|
+
`transcribe with the pro model, ${PRO_TRANSCRIBE_MODEL}: keeps a little more speech, about 1.7\xD7 slower`
|
|
5725
|
+
).conflicts("model")
|
|
5726
|
+
).option("--reasoner <name>", "override text-reasoner model (default deepseek-chat)").option(
|
|
4678
5727
|
"--timestamped <provider>",
|
|
4679
5728
|
"timestamped provider (assemblyai|elevenlabs|whisper-groq|none)"
|
|
4680
|
-
).option(
|
|
5729
|
+
).option(
|
|
5730
|
+
"--language <code>",
|
|
5731
|
+
"spoken language for the timing ASR, e.g. ko, ml, hi (default: the ASR detects one)"
|
|
5732
|
+
).option("--force", "force reprocess cached chunk outputs", false).option(
|
|
5733
|
+
"--no-zero-storage",
|
|
5734
|
+
"let providers keep requests under their own retention (by default offmute asks Gemini and AssemblyAI to keep nothing)"
|
|
5735
|
+
).option("--only-chunk <n>", "process only a specific chunk index (debug)").option("--save-intermediates", "save intermediates (default true)", true).option("--no-progress", "hide progress output").option(
|
|
4681
5736
|
"--no-llm-log",
|
|
4682
5737
|
"disable per-call LLM logging to <intermediates>/llm-calls.jsonl"
|
|
4683
5738
|
).option("--no-notify", "skip the OS notification after long runs").option("--log-level <level>", "debug | info | warn | error", "info");
|
|
@@ -4710,7 +5765,15 @@ program.command("stats").description("lifetime stats: hours processed, character
|
|
|
4710
5765
|
program.command("watch <dir>").description("daemon mode: watch a folder, transcribe media files as they appear").option("--match <exts>", "comma-separated extensions to watch (default: common media)").option("--jobs <n>", "max concurrent transcription jobs", "1").option("--no-backlog", "skip files already in the folder at startup").option("-o, --output <dir>", "write transcripts here (default: next to each input)").option("--formats <list>", "output formats: srt,md,txt,html,json (default: md)").option("--md-style <style>", "markdown layout: merged | turns", "merged").option("--summary", "also write a summary per file", false).option("--instructions <text>", "custom instructions for the LLM").option(
|
|
4711
5766
|
"--speakers <names>",
|
|
4712
5767
|
"known speaker names, comma-separated (implies --level 3)"
|
|
4713
|
-
).option("--level <1|2|3>", "diarization level", "3").option("--identify <mode>", "speaker naming: dual | single", "dual").option("--model <name>", "override transcription model
|
|
5768
|
+
).option("--level <1|2|3>", "diarization level", "3").option("--identify <mode>", "speaker naming: dual | single", "dual").option("--model <name>", "override transcription model (default gemini-4-hydrogen)").addOption(
|
|
5769
|
+
new Option(
|
|
5770
|
+
"--pro",
|
|
5771
|
+
`transcribe with the pro model, ${PRO_TRANSCRIBE_MODEL}`
|
|
5772
|
+
).conflicts("model")
|
|
5773
|
+
).option("--reasoner <name>", "override text-reasoner model").option("--timestamped <provider>", "assemblyai|elevenlabs|whisper-groq|none").option("--language <code>", "spoken language for the timing ASR, e.g. ko, ml, hi").option(
|
|
5774
|
+
"--no-zero-storage",
|
|
5775
|
+
"let providers keep requests under their own retention (by default offmute asks them to keep nothing)"
|
|
5776
|
+
).action(
|
|
4714
5777
|
async (dir, opts) => {
|
|
4715
5778
|
let level = parseInt(opts.level, 10);
|
|
4716
5779
|
if (opts.speakers && level < 3) level = 3;
|
|
@@ -4727,9 +5790,11 @@ program.command("watch <dir>").description("daemon mode: watch a folder, transcr
|
|
|
4727
5790
|
knownSpeakers: opts.speakers ? opts.speakers.split(",").map((s) => s.trim()).filter(Boolean) : void 0,
|
|
4728
5791
|
diarizationLevel: level,
|
|
4729
5792
|
identifyMode: opts.identify,
|
|
4730
|
-
model: opts.model,
|
|
5793
|
+
model: opts.pro ? PRO_TRANSCRIBE_MODEL : opts.model,
|
|
4731
5794
|
reasoner: opts.reasoner,
|
|
4732
|
-
timestampedProvider: opts.timestamped
|
|
5795
|
+
timestampedProvider: opts.timestamped,
|
|
5796
|
+
language: opts.language,
|
|
5797
|
+
zeroStorage: opts.zeroStorage
|
|
4733
5798
|
}
|
|
4734
5799
|
});
|
|
4735
5800
|
}
|