offmute-v2 0.1.0 → 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/index.cjs
CHANGED
|
@@ -30,6 +30,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
30
30
|
// src/index.ts
|
|
31
31
|
var src_exports = {};
|
|
32
32
|
__export(src_exports, {
|
|
33
|
+
DEFAULT_REASONER_MODEL: () => DEFAULT_REASONER_MODEL,
|
|
34
|
+
DEFAULT_TRANSCRIBE_MODEL: () => DEFAULT_TRANSCRIBE_MODEL,
|
|
35
|
+
PRO_TRANSCRIBE_MODEL: () => PRO_TRANSCRIBE_MODEL,
|
|
33
36
|
alignSegments: () => alignSegments,
|
|
34
37
|
assignGlobalSpeakers: () => assignGlobalSpeakers,
|
|
35
38
|
finalizeSegments: () => finalizeSegments,
|
|
@@ -39,6 +42,7 @@ __export(src_exports, {
|
|
|
39
42
|
formatSrt: () => formatSrt,
|
|
40
43
|
formatText: () => formatText,
|
|
41
44
|
identifySpeakers: () => identifySpeakers,
|
|
45
|
+
identifySpeakersV2: () => identifySpeakersV2,
|
|
42
46
|
parseSrt: () => parseSrt,
|
|
43
47
|
planChunks: () => planChunks,
|
|
44
48
|
summarizeTranscript: () => summarizeTranscript,
|
|
@@ -47,7 +51,13 @@ __export(src_exports, {
|
|
|
47
51
|
module.exports = __toCommonJS(src_exports);
|
|
48
52
|
|
|
49
53
|
// src/core/pipeline.ts
|
|
50
|
-
var
|
|
54
|
+
var import_node_fs6 = require("fs");
|
|
55
|
+
var import_promises3 = require("fs/promises");
|
|
56
|
+
|
|
57
|
+
// src/core/models.ts
|
|
58
|
+
var DEFAULT_TRANSCRIBE_MODEL = "gemini-4-hydrogen";
|
|
59
|
+
var PRO_TRANSCRIBE_MODEL = "gemini-4-argon";
|
|
60
|
+
var DEFAULT_REASONER_MODEL = "deepseek-chat";
|
|
51
61
|
|
|
52
62
|
// src/core/config.ts
|
|
53
63
|
var import_node_crypto = require("crypto");
|
|
@@ -63,19 +73,6 @@ var DEFAULT_PASSES = [
|
|
|
63
73
|
"consistency",
|
|
64
74
|
"finalize"
|
|
65
75
|
];
|
|
66
|
-
var MODELS = {
|
|
67
|
-
gemini25Pro: "gemini-2.5-pro",
|
|
68
|
-
gemini25Flash: "gemini-2.5-flash",
|
|
69
|
-
gemini3Pro: "gemini-3-pro-preview",
|
|
70
|
-
gemini31Pro: "gemini-3.1-pro-preview",
|
|
71
|
-
geminiFlashLatest: "gemini-flash-latest",
|
|
72
|
-
deepseek: "deepseek-chat",
|
|
73
|
-
deepseekReasoner: "deepseek-reasoner",
|
|
74
|
-
gpt4o: "gpt-4o",
|
|
75
|
-
claudeSonnet: "claude-sonnet-4-5"
|
|
76
|
-
};
|
|
77
|
-
var DEFAULT_TRANSCRIBE_MODEL = MODELS.gemini31Pro;
|
|
78
|
-
var DEFAULT_REASONER_MODEL = MODELS.deepseek;
|
|
79
76
|
function resolveKeys(injected) {
|
|
80
77
|
const env = process.env;
|
|
81
78
|
return {
|
|
@@ -127,12 +124,15 @@ function resolveOptions(opts) {
|
|
|
127
124
|
model: opts.model,
|
|
128
125
|
reasoner: opts.reasoner,
|
|
129
126
|
timestampedProvider: opts.timestampedProvider,
|
|
127
|
+
language: opts.language,
|
|
130
128
|
force: opts.force ?? false,
|
|
131
129
|
onlyChunk: opts.onlyChunk,
|
|
132
130
|
showProgress: opts.showProgress ?? true,
|
|
133
131
|
llmLog: opts.llmLog ?? true,
|
|
134
132
|
logLevel: opts.logLevel ?? "info",
|
|
135
|
-
signal: opts.signal
|
|
133
|
+
signal: opts.signal,
|
|
134
|
+
onProgress: opts.onProgress,
|
|
135
|
+
zeroStorage: opts.zeroStorage ?? true
|
|
136
136
|
};
|
|
137
137
|
}
|
|
138
138
|
function deriveIntermediatesDir(input) {
|
|
@@ -159,9 +159,7 @@ function inputSignature(input) {
|
|
|
159
159
|
function configSignature(o) {
|
|
160
160
|
const relevant = {
|
|
161
161
|
model: o.model ?? DEFAULT_TRANSCRIBE_MODEL,
|
|
162
|
-
reasoner: o.reasoner ?? DEFAULT_REASONER_MODEL,
|
|
163
162
|
instructions: o.instructions ?? "",
|
|
164
|
-
knownSpeakers: o.knownSpeakers ?? [],
|
|
165
163
|
chunkDurationSec: o.chunkDurationSec ?? 600,
|
|
166
164
|
chunkOverlapSec: o.chunkOverlapSec ?? 60,
|
|
167
165
|
screenshotCount: o.screenshotCount ?? 6,
|
|
@@ -197,6 +195,15 @@ function planChunks(totalDuration, chunkDuration, overlap2) {
|
|
|
197
195
|
return chunks;
|
|
198
196
|
}
|
|
199
197
|
|
|
198
|
+
// src/core/progress.ts
|
|
199
|
+
function emitTo(listener, event) {
|
|
200
|
+
if (!listener) return;
|
|
201
|
+
try {
|
|
202
|
+
listener(event);
|
|
203
|
+
} catch {
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
200
207
|
// src/utils/logger.ts
|
|
201
208
|
var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
202
209
|
var currentLevel = "info";
|
|
@@ -498,6 +505,38 @@ async function withRetry(label, fn, opts = {}) {
|
|
|
498
505
|
throw lastErr;
|
|
499
506
|
}
|
|
500
507
|
|
|
508
|
+
// src/providers/gemini-usage.ts
|
|
509
|
+
function usageFromMetadata(meta) {
|
|
510
|
+
const thoughtTokens = meta?.thoughtsTokenCount ?? 0;
|
|
511
|
+
return {
|
|
512
|
+
inputTokens: meta?.promptTokenCount ?? 0,
|
|
513
|
+
outputTokens: (meta?.candidatesTokenCount ?? 0) + thoughtTokens,
|
|
514
|
+
thoughtTokens,
|
|
515
|
+
totalTokens: meta?.totalTokenCount ?? 0
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// src/providers/gemini-models.ts
|
|
520
|
+
function resolveThinking(model) {
|
|
521
|
+
const m = model.toLowerCase();
|
|
522
|
+
if (m.includes("gemini-2.0")) return void 0;
|
|
523
|
+
if (m.includes("gemini-4")) return { thinkingLevel: "LOW" };
|
|
524
|
+
if (m.includes("gemini-2.5")) {
|
|
525
|
+
return { thinkingBudget: m.includes("pro") ? 128 : 0 };
|
|
526
|
+
}
|
|
527
|
+
if (m.includes("-latest")) return { thinkingLevel: "LOW" };
|
|
528
|
+
if (m.includes("gemini-3"))
|
|
529
|
+
return { thinkingLevel: m.includes("pro") ? "LOW" : "MINIMAL" };
|
|
530
|
+
return void 0;
|
|
531
|
+
}
|
|
532
|
+
function fallbackThinking(rejected) {
|
|
533
|
+
return rejected.thinkingLevel === "MINIMAL" ? { thinkingLevel: "LOW" } : void 0;
|
|
534
|
+
}
|
|
535
|
+
function isThinkingConfigError(message) {
|
|
536
|
+
if (!message) return false;
|
|
537
|
+
return /thinking/i.test(message) && /(not supported|invalid|unsupported|unknown name|unexpected)/i.test(message);
|
|
538
|
+
}
|
|
539
|
+
|
|
501
540
|
// src/providers/gemini.ts
|
|
502
541
|
var SDK_KEY_WARNING = "Both GOOGLE_API_KEY and GEMINI_API_KEY are set";
|
|
503
542
|
var originalWarn = console.warn.bind(console);
|
|
@@ -526,25 +565,15 @@ function detectMime(path) {
|
|
|
526
565
|
return MIME_BY_EXT[ext2] ?? "application/octet-stream";
|
|
527
566
|
}
|
|
528
567
|
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
529
|
-
function resolveThinking(model) {
|
|
530
|
-
const m = model.toLowerCase();
|
|
531
|
-
if (m.includes("gemini-2.0")) return void 0;
|
|
532
|
-
if (m.includes("gemini-2.5")) {
|
|
533
|
-
return { thinkingBudget: m.includes("pro") ? 128 : 0 };
|
|
534
|
-
}
|
|
535
|
-
if (m.includes("gemini-3") || m.includes("flash-latest") || m.includes("pro-latest")) {
|
|
536
|
-
return { thinkingLevel: m.includes("pro") ? "LOW" : "MINIMAL" };
|
|
537
|
-
}
|
|
538
|
-
return void 0;
|
|
539
|
-
}
|
|
540
|
-
function isThinkingConfigError(message) {
|
|
541
|
-
if (!message) return false;
|
|
542
|
-
return /thinking/i.test(message) && /(not supported|invalid|unsupported|unknown name|unexpected)/i.test(message);
|
|
543
|
-
}
|
|
544
568
|
var GeminiClient = class {
|
|
545
569
|
ai;
|
|
546
|
-
|
|
547
|
-
|
|
570
|
+
zeroStorage;
|
|
571
|
+
constructor(apiKey, opts = {}) {
|
|
572
|
+
this.ai = new import_genai.GoogleGenAI({
|
|
573
|
+
apiKey,
|
|
574
|
+
...opts.baseUrl ? { httpOptions: { baseUrl: opts.baseUrl } } : {}
|
|
575
|
+
});
|
|
576
|
+
this.zeroStorage = opts.zeroStorage ?? true;
|
|
548
577
|
}
|
|
549
578
|
/** Upload a file and wait until it's done processing. Uploads ride one long HTTP
|
|
550
579
|
* request each — the retry loop in generate() doesn't cover them, and transient
|
|
@@ -587,12 +616,15 @@ var GeminiClient = class {
|
|
|
587
616
|
maxOutputTokens,
|
|
588
617
|
temperature
|
|
589
618
|
};
|
|
619
|
+
if (this.zeroStorage) config.store = false;
|
|
590
620
|
if (responseSchema) {
|
|
591
621
|
config.responseMimeType = "application/json";
|
|
592
622
|
config.responseSchema = responseSchema;
|
|
623
|
+
} else if (opts.responseJson) {
|
|
624
|
+
config.responseMimeType = "application/json";
|
|
593
625
|
}
|
|
594
626
|
if (systemInstruction) config.systemInstruction = systemInstruction;
|
|
595
|
-
|
|
627
|
+
let thinking = resolveThinking(model);
|
|
596
628
|
if (thinking) config.thinkingConfig = thinking;
|
|
597
629
|
const parts = uploaded.map((f) => ({
|
|
598
630
|
fileData: { fileUri: f.uri, mimeType: f.mimeType }
|
|
@@ -602,21 +634,31 @@ var GeminiClient = class {
|
|
|
602
634
|
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
603
635
|
const t0 = Date.now();
|
|
604
636
|
try {
|
|
605
|
-
const
|
|
637
|
+
const controller = new AbortController();
|
|
638
|
+
const stream = await this.ai.models.generateContentStream({
|
|
606
639
|
model,
|
|
607
640
|
contents: [{ role: "user", parts }],
|
|
608
|
-
config
|
|
641
|
+
config: { ...config, abortSignal: controller.signal }
|
|
609
642
|
});
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
643
|
+
let text = "";
|
|
644
|
+
let usageMeta;
|
|
645
|
+
let abortReason = null;
|
|
646
|
+
for await (const chunk of stream) {
|
|
647
|
+
text += chunk.text ?? "";
|
|
648
|
+
if (chunk.usageMetadata) usageMeta = chunk.usageMetadata;
|
|
649
|
+
abortReason = opts.shouldAbort?.(text) ?? null;
|
|
650
|
+
if (abortReason) {
|
|
651
|
+
controller.abort();
|
|
652
|
+
break;
|
|
618
653
|
}
|
|
619
|
-
}
|
|
654
|
+
}
|
|
655
|
+
const usage = usageFromMetadata(usageMeta);
|
|
656
|
+
const error = abortReason ? `aborted: ${abortReason}` : void 0;
|
|
657
|
+
if (error) {
|
|
658
|
+
logger.warn(
|
|
659
|
+
`[gemini] ${opts.logKind ?? "call"}${opts.logChunk !== void 0 ? ` chunk ${opts.logChunk}` : ""} ${error} after ${text.length} chars`
|
|
660
|
+
);
|
|
661
|
+
}
|
|
620
662
|
logLlmCall({
|
|
621
663
|
ts: new Date(t0).toISOString(),
|
|
622
664
|
provider: "gemini",
|
|
@@ -625,18 +667,22 @@ var GeminiClient = class {
|
|
|
625
667
|
chunk: opts.logChunk,
|
|
626
668
|
prompt,
|
|
627
669
|
response: text,
|
|
628
|
-
usage
|
|
670
|
+
usage,
|
|
629
671
|
durationMs: Date.now() - t0,
|
|
630
|
-
attempt: attempt + 1
|
|
672
|
+
attempt: attempt + 1,
|
|
673
|
+
...error ? { error } : {}
|
|
631
674
|
});
|
|
632
|
-
return
|
|
675
|
+
return error ? { text, usage, error } : { text, usage };
|
|
633
676
|
} catch (err) {
|
|
634
677
|
lastError = err instanceof Error ? err.message : String(err);
|
|
635
|
-
if (
|
|
636
|
-
|
|
678
|
+
if (thinking && isThinkingConfigError(lastError)) {
|
|
679
|
+
const next = fallbackThinking(thinking);
|
|
637
680
|
logger.warn(
|
|
638
|
-
`[gemini] model ${model} rejected thinking config \u2014 retrying without it`
|
|
681
|
+
`[gemini] model ${model} rejected thinking config ${JSON.stringify(thinking)} \u2014 retrying ${next ? `with ${JSON.stringify(next)}` : "without it"}`
|
|
639
682
|
);
|
|
683
|
+
thinking = next;
|
|
684
|
+
if (thinking) config.thinkingConfig = thinking;
|
|
685
|
+
else delete config.thinkingConfig;
|
|
640
686
|
continue;
|
|
641
687
|
}
|
|
642
688
|
logger.warn(
|
|
@@ -711,42 +757,82 @@ async function fileHash(path) {
|
|
|
711
757
|
const buf = await (0, import_promises2.readFile)(path);
|
|
712
758
|
return (0, import_node_crypto2.createHash)("sha256").update(buf).digest("hex").slice(0, 24);
|
|
713
759
|
}
|
|
760
|
+
var DELETED_TEXT = "Deleted by user.";
|
|
761
|
+
async function readPendingId(pendingPath) {
|
|
762
|
+
if (!(0, import_node_fs3.existsSync)(pendingPath)) return void 0;
|
|
763
|
+
try {
|
|
764
|
+
return JSON.parse(await (0, import_promises2.readFile)(pendingPath, "utf-8")).id;
|
|
765
|
+
} catch {
|
|
766
|
+
return void 0;
|
|
767
|
+
}
|
|
768
|
+
}
|
|
714
769
|
var AssemblyAIProvider = class {
|
|
715
770
|
client;
|
|
716
771
|
cacheDir;
|
|
717
772
|
constructor(opts) {
|
|
718
|
-
this.client = new import_assemblyai.AssemblyAI({ apiKey: opts.apiKey });
|
|
773
|
+
this.client = new import_assemblyai.AssemblyAI({ apiKey: opts.apiKey, baseUrl: opts.baseUrl });
|
|
719
774
|
this.cacheDir = opts.cacheDir;
|
|
720
775
|
this.speechModel = opts.speechModel ?? "universal";
|
|
721
776
|
this.speakersExpected = opts.speakersExpected;
|
|
777
|
+
this.language = opts.language;
|
|
778
|
+
this.zeroStorage = opts.zeroStorage ?? true;
|
|
722
779
|
}
|
|
723
780
|
speechModel;
|
|
724
781
|
speakersExpected;
|
|
782
|
+
language;
|
|
783
|
+
zeroStorage;
|
|
784
|
+
/** Whether the last transcribe() was served from the content-hash cache (no paid call). */
|
|
785
|
+
lastFromCache = false;
|
|
725
786
|
/** Transcribe a local audio file. Returns cached result if available. */
|
|
726
787
|
async transcribe(filePath) {
|
|
727
788
|
const hash = await fileHash(filePath);
|
|
728
|
-
const
|
|
789
|
+
const variant = [
|
|
790
|
+
`lang-${this.language ?? "auto"}`,
|
|
791
|
+
this.speakersExpected && `spk-${this.speakersExpected}`,
|
|
792
|
+
this.speechModel !== "universal" && this.speechModel
|
|
793
|
+
].filter(Boolean).join("_");
|
|
794
|
+
const cachePath = this.cacheDir ? `${this.cacheDir}/${hash}_${variant}.json` : void 0;
|
|
795
|
+
const pendingPath = cachePath?.replace(/\.json$/, ".pending.json");
|
|
796
|
+
this.lastFromCache = false;
|
|
729
797
|
if (cachePath && (0, import_node_fs3.existsSync)(cachePath)) {
|
|
730
798
|
logger.info(`[assemblyai] cache hit ${hash}`);
|
|
799
|
+
this.lastFromCache = true;
|
|
800
|
+
if (pendingPath) await this.finish(pendingPath, await readPendingId(pendingPath));
|
|
731
801
|
return JSON.parse(await (0, import_promises2.readFile)(cachePath, "utf-8"));
|
|
732
802
|
}
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
803
|
+
let transcript = pendingPath ? await this.resume(pendingPath) : void 0;
|
|
804
|
+
if (!transcript) {
|
|
805
|
+
logger.info(`[assemblyai] uploading ${filePath}...`);
|
|
806
|
+
const uploadUrl = await withRetry(
|
|
807
|
+
"assemblyai upload",
|
|
808
|
+
() => this.client.files.upload(filePath)
|
|
809
|
+
);
|
|
810
|
+
logger.info(
|
|
811
|
+
`[assemblyai] transcribing (speech_model=${this.speechModel}, language=${this.language ?? "auto-detect"})...`
|
|
812
|
+
);
|
|
813
|
+
const params = {
|
|
814
|
+
audio: uploadUrl,
|
|
815
|
+
speaker_labels: true,
|
|
816
|
+
speech_model: this.speechModel
|
|
817
|
+
};
|
|
818
|
+
if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
|
|
819
|
+
if (this.language) params.language_code = this.language;
|
|
820
|
+
else params.language_detection = true;
|
|
821
|
+
const job = await withRetry(
|
|
822
|
+
"assemblyai submit",
|
|
823
|
+
() => this.client.transcripts.submit(params)
|
|
824
|
+
);
|
|
825
|
+
if (pendingPath) {
|
|
826
|
+
await (0, import_promises2.mkdir)((0, import_node_path4.dirname)(pendingPath), { recursive: true });
|
|
827
|
+
await (0, import_promises2.writeFile)(pendingPath, JSON.stringify({ id: job.id }));
|
|
828
|
+
}
|
|
829
|
+
transcript = await withRetry(
|
|
830
|
+
"assemblyai transcribe",
|
|
831
|
+
() => this.client.transcripts.waitUntilReady(job.id)
|
|
832
|
+
);
|
|
833
|
+
}
|
|
749
834
|
if (transcript.status === "error") {
|
|
835
|
+
if (pendingPath) await (0, import_promises2.rm)(pendingPath, { force: true });
|
|
750
836
|
throw new Error(`AssemblyAI error: ${transcript.error}`);
|
|
751
837
|
}
|
|
752
838
|
const result = this.mapTranscript(transcript, hash);
|
|
@@ -755,10 +841,53 @@ var AssemblyAIProvider = class {
|
|
|
755
841
|
await (0, import_promises2.writeFile)(cachePath, JSON.stringify(result, null, 2));
|
|
756
842
|
}
|
|
757
843
|
logger.info(
|
|
758
|
-
`[assemblyai] done: ${result.utterances.length} utterances, ${result.words.length} words, ${result.speakers.length} speakers`
|
|
844
|
+
`[assemblyai] done: ${result.utterances.length} utterances, ${result.words.length} words, ${result.speakers.length} speakers, language ${result.languageCode ?? "?"}`
|
|
759
845
|
);
|
|
846
|
+
if (pendingPath) await this.finish(pendingPath, transcript.id);
|
|
847
|
+
else if (this.zeroStorage && transcript.id) await this.deleteRemote(transcript.id);
|
|
760
848
|
return result;
|
|
761
849
|
}
|
|
850
|
+
/** Delete job `id` from AssemblyAI (with zero storage), then forget it. */
|
|
851
|
+
async finish(pendingPath, id) {
|
|
852
|
+
if (this.zeroStorage && id) await this.deleteRemote(id);
|
|
853
|
+
await (0, import_promises2.rm)(pendingPath, { force: true });
|
|
854
|
+
}
|
|
855
|
+
async deleteRemote(id) {
|
|
856
|
+
await this.client.transcripts.delete(id).then(
|
|
857
|
+
() => logger.debug(`[assemblyai] deleted transcript ${id} from AssemblyAI`),
|
|
858
|
+
(err) => logger.warn(
|
|
859
|
+
`[assemblyai] couldn't delete transcript ${id} from AssemblyAI (it expires in 30 days): ${err instanceof Error ? err.message : String(err)}`
|
|
860
|
+
)
|
|
861
|
+
);
|
|
862
|
+
}
|
|
863
|
+
/** The finished job a stopped run left at `pendingPath`, or undefined to send the audio
|
|
864
|
+
* again: when there is none, or AssemblyAI says it's gone (not found, failed, deleted).
|
|
865
|
+
* Anything less certain (offline, an outage, a refused key) is thrown with the job kept,
|
|
866
|
+
* so the next run neither pays twice nor leaves the job behind undeleted. */
|
|
867
|
+
async resume(pendingPath) {
|
|
868
|
+
const id = await readPendingId(pendingPath);
|
|
869
|
+
if (id) {
|
|
870
|
+
logger.info(`[assemblyai] picking up transcript ${id}, left by a stopped run...`);
|
|
871
|
+
let gone;
|
|
872
|
+
try {
|
|
873
|
+
const t = await withRetry(
|
|
874
|
+
"assemblyai transcribe",
|
|
875
|
+
() => this.client.transcripts.waitUntilReady(id)
|
|
876
|
+
);
|
|
877
|
+
if (t.status === "completed" && t.text !== DELETED_TEXT) return t;
|
|
878
|
+
gone = t.status === "error" ? `it failed: ${t.error}` : "it was deleted";
|
|
879
|
+
} catch (err) {
|
|
880
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
881
|
+
if (!/not found/i.test(message)) throw err;
|
|
882
|
+
gone = message;
|
|
883
|
+
}
|
|
884
|
+
logger.warn(
|
|
885
|
+
`[assemblyai] transcript ${id} is gone (${gone}) \u2014 sending the audio again`
|
|
886
|
+
);
|
|
887
|
+
}
|
|
888
|
+
await (0, import_promises2.rm)(pendingPath, { force: true });
|
|
889
|
+
return void 0;
|
|
890
|
+
}
|
|
762
891
|
mapTranscript(t, id) {
|
|
763
892
|
const toWord = (w) => ({
|
|
764
893
|
text: w.text,
|
|
@@ -788,6 +917,7 @@ var AssemblyAIProvider = class {
|
|
|
788
917
|
durationSec,
|
|
789
918
|
audioDurationSec: t.audio_duration ?? void 0,
|
|
790
919
|
// AssemblyAI returns seconds (not ms)
|
|
920
|
+
languageCode: t.language_code ?? void 0,
|
|
791
921
|
speakers: [...speakers].sort(),
|
|
792
922
|
transcriptId: t.id ?? id,
|
|
793
923
|
speechModelUsed: t.speech_model_used ?? void 0,
|
|
@@ -806,7 +936,7 @@ var WhisperGroqClient = class {
|
|
|
806
936
|
apiKey;
|
|
807
937
|
model;
|
|
808
938
|
baseUrl;
|
|
809
|
-
async transcribe(audio) {
|
|
939
|
+
async transcribe(audio, opts = {}) {
|
|
810
940
|
const blob = audio instanceof Blob ? audio : new Blob([audio], { type: "audio/mpeg" });
|
|
811
941
|
const form = new FormData();
|
|
812
942
|
form.append("file", blob, "audio.mp3");
|
|
@@ -814,6 +944,7 @@ var WhisperGroqClient = class {
|
|
|
814
944
|
form.append("response_format", "verbose_json");
|
|
815
945
|
form.append("timestamp_granularities[]", "word");
|
|
816
946
|
form.append("timestamp_granularities[]", "segment");
|
|
947
|
+
if (opts.language) form.append("language", opts.language);
|
|
817
948
|
const res = await fetch(`${this.baseUrl}/audio/transcriptions`, {
|
|
818
949
|
method: "POST",
|
|
819
950
|
headers: { Authorization: `Bearer ${this.apiKey}` },
|
|
@@ -868,6 +999,7 @@ var ElevenLabsClient = class {
|
|
|
868
999
|
form.append("diarize", "true");
|
|
869
1000
|
form.append("tag_audio_events", "false");
|
|
870
1001
|
if (opts.numSpeakers) form.append("num_speakers", String(opts.numSpeakers));
|
|
1002
|
+
if (opts.languageCode) form.append("language_code", opts.languageCode);
|
|
871
1003
|
for (const term of opts.keyterms ?? []) form.append("keyterms", term);
|
|
872
1004
|
const data = await withRetry("elevenlabs", async () => {
|
|
873
1005
|
const res = await fetch(`${this.baseUrl}/speech-to-text`, {
|
|
@@ -926,17 +1058,53 @@ var ElevenLabsClient = class {
|
|
|
926
1058
|
};
|
|
927
1059
|
|
|
928
1060
|
// src/core/pricing.ts
|
|
929
|
-
var PRICES_AS_OF = "2026-
|
|
1061
|
+
var PRICES_AS_OF = "2026-11-17";
|
|
930
1062
|
var MODEL_PRICES = {
|
|
931
|
-
|
|
1063
|
+
"gemini-4-hydrogen": { textIn: 1.5, out: 7.5 },
|
|
1064
|
+
"gemini-4-argon": {
|
|
1065
|
+
until: "2026-11-30",
|
|
1066
|
+
price: { textIn: 2, out: 10 },
|
|
1067
|
+
then: { textIn: 4, out: 20 }
|
|
1068
|
+
},
|
|
1069
|
+
"gemini-4-carbon": {
|
|
1070
|
+
until: "2026-11-30",
|
|
1071
|
+
price: { textIn: 2, out: 10 },
|
|
1072
|
+
then: { textIn: 4, out: 20 }
|
|
1073
|
+
},
|
|
932
1074
|
"gemini-3.1-pro-preview": { textIn: 2, out: 12 },
|
|
933
|
-
|
|
934
|
-
"gemini-3.
|
|
1075
|
+
// ≤200k-token prompts
|
|
1076
|
+
"gemini-3.8-flash": {
|
|
1077
|
+
until: "2026-12-31",
|
|
1078
|
+
price: { textIn: 0.75, out: 3.75 },
|
|
1079
|
+
then: { textIn: 1.5, out: 7.5 }
|
|
1080
|
+
},
|
|
1081
|
+
"gemini-3.6-flash": {
|
|
1082
|
+
until: "2026-12-31",
|
|
1083
|
+
price: { textIn: 0.75, out: 3.75 },
|
|
1084
|
+
then: { textIn: 1.5, out: 7.5 }
|
|
1085
|
+
},
|
|
1086
|
+
// Deprecated 2026-10-08; requests are served by gemini-3.6-flash (priced as such).
|
|
1087
|
+
"gemini-3.5-flash": {
|
|
1088
|
+
until: "2026-12-31",
|
|
1089
|
+
price: { textIn: 0.75, out: 3.75 },
|
|
1090
|
+
then: { textIn: 1.5, out: 7.5 }
|
|
1091
|
+
},
|
|
1092
|
+
"gemini-3.5-flash-lite": { textIn: 0.3, out: 2.5 },
|
|
935
1093
|
"gemini-3-flash-preview": { textIn: 0.5, audioIn: 1, out: 3 },
|
|
936
|
-
|
|
937
|
-
"gemini-2.5-
|
|
1094
|
+
// From 2026-12-01 Google serves (and bills) 2.5 Pro as 3.8 Flash and 2.5 Flash as 3.5 Flash-Lite.
|
|
1095
|
+
"gemini-2.5-pro": {
|
|
1096
|
+
until: "2026-11-30",
|
|
1097
|
+
price: { textIn: 1.25, out: 10 },
|
|
1098
|
+
then: { textIn: 1.5, out: 7.5 }
|
|
1099
|
+
},
|
|
1100
|
+
"gemini-2.5-flash": {
|
|
1101
|
+
until: "2026-11-30",
|
|
1102
|
+
price: { textIn: 0.3, audioIn: 1, out: 2.5 },
|
|
1103
|
+
then: { textIn: 0.3, out: 2.5 }
|
|
1104
|
+
},
|
|
938
1105
|
"gemini-2.5-flash-lite": { textIn: 0.1, audioIn: 0.3, out: 0.4 },
|
|
939
|
-
// Moving aliases
|
|
1106
|
+
// Moving aliases. Google hasn't documented their targets since January 2026; these are
|
|
1107
|
+
// the last documented targets' prices, so treat them as estimates.
|
|
940
1108
|
"gemini-pro-latest": { textIn: 2, out: 12 },
|
|
941
1109
|
"gemini-flash-latest": { textIn: 1.5, out: 9 },
|
|
942
1110
|
"gemini-flash-lite-latest": { textIn: 0.25, audioIn: 0.5, out: 1.5 },
|
|
@@ -955,17 +1123,27 @@ var ASR_HOURLY = {
|
|
|
955
1123
|
// whisper-large-v3-turbo
|
|
956
1124
|
none: 0
|
|
957
1125
|
};
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
1126
|
+
function audioTokensPerSec(model) {
|
|
1127
|
+
return model.startsWith("gemini-4") ? 32 : 25;
|
|
1128
|
+
}
|
|
1129
|
+
function priceFor(model, at = /* @__PURE__ */ new Date()) {
|
|
1130
|
+
const key = model in MODEL_PRICES ? model : Object.keys(MODEL_PRICES).filter((k) => model.startsWith(k)).sort((a, b) => b.length - a.length)[0];
|
|
1131
|
+
if (!key) return null;
|
|
1132
|
+
const p = MODEL_PRICES[key];
|
|
1133
|
+
if (!("until" in p)) return p;
|
|
1134
|
+
return at.toISOString().slice(0, 10) <= p.until ? p.price : p.then;
|
|
963
1135
|
}
|
|
964
1136
|
function asrCost(provider, durationSec) {
|
|
965
1137
|
const hourly = ASR_HOURLY[provider];
|
|
966
1138
|
if (hourly === void 0) return null;
|
|
967
1139
|
return durationSec / 3600 * hourly;
|
|
968
1140
|
}
|
|
1141
|
+
var OUTPUT_TOK_PER_AUDIO_MIN = 700;
|
|
1142
|
+
function thinkingOverhead(model) {
|
|
1143
|
+
if (model.startsWith("gemini-4-hydrogen")) return 0.5;
|
|
1144
|
+
if (model.includes("pro")) return 0.15;
|
|
1145
|
+
return 0;
|
|
1146
|
+
}
|
|
969
1147
|
function estimateRunCost(opts) {
|
|
970
1148
|
const lines = [];
|
|
971
1149
|
let total = 0;
|
|
@@ -977,9 +1155,9 @@ function estimateRunCost(opts) {
|
|
|
977
1155
|
);
|
|
978
1156
|
const billedAudioSec = opts.durationSec + Math.max(0, chunks - 1) * opts.overlapSec + Math.min(370, opts.durationSec);
|
|
979
1157
|
if (p) {
|
|
980
|
-
const audioTok = billedAudioSec *
|
|
1158
|
+
const audioTok = billedAudioSec * audioTokensPerSec(opts.model);
|
|
981
1159
|
const promptTok = chunks * 1500;
|
|
982
|
-
const outTok = opts.durationSec / 60 *
|
|
1160
|
+
const outTok = opts.durationSec / 60 * OUTPUT_TOK_PER_AUDIO_MIN * (1 + thinkingOverhead(opts.model)) + 1500;
|
|
983
1161
|
const inRate = p.audioIn ?? p.textIn;
|
|
984
1162
|
const llmUsd = (audioTok * inRate + promptTok * p.textIn + outTok * p.out) / 1e6;
|
|
985
1163
|
total += llmUsd;
|
|
@@ -1007,7 +1185,7 @@ function estimateRunCost(opts) {
|
|
|
1007
1185
|
}
|
|
1008
1186
|
return { totalUsd: total, lines, incomplete };
|
|
1009
1187
|
}
|
|
1010
|
-
function computeReceipt(usage, tsProvider, durationSec) {
|
|
1188
|
+
function computeReceipt(usage, tsProvider, durationSec, asrBilled = true) {
|
|
1011
1189
|
let llmUsd = 0;
|
|
1012
1190
|
let incomplete = false;
|
|
1013
1191
|
const lines = [];
|
|
@@ -1040,11 +1218,11 @@ function computeReceipt(usage, tsProvider, durationSec) {
|
|
|
1040
1218
|
`${model}: ${m.calls} call${m.calls > 1 ? "s" : ""} \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 $${usd.toFixed(2)}`
|
|
1041
1219
|
);
|
|
1042
1220
|
}
|
|
1043
|
-
const asrUsd = tsProvider === "none" ? 0 : asrCost(tsProvider, durationSec);
|
|
1221
|
+
const asrUsd = tsProvider === "none" || !asrBilled ? 0 : asrCost(tsProvider, durationSec);
|
|
1044
1222
|
if (asrUsd !== null && tsProvider !== "none") {
|
|
1045
1223
|
perModel[tsProvider] = asrUsd;
|
|
1046
1224
|
lines.push(
|
|
1047
|
-
`${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7
|
|
1225
|
+
`${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7 ${asrBilled ? `$${asrUsd.toFixed(2)}` : "cached \xB7 $0.00"}`
|
|
1048
1226
|
);
|
|
1049
1227
|
}
|
|
1050
1228
|
return {
|
|
@@ -1178,11 +1356,22 @@ async function describeMeeting(client, model, files, fileName, instructions, aud
|
|
|
1178
1356
|
logKind: "describe"
|
|
1179
1357
|
}
|
|
1180
1358
|
);
|
|
1181
|
-
|
|
1359
|
+
return { ...parseDescription(res.text || ""), raw: res.text || "" };
|
|
1360
|
+
}
|
|
1361
|
+
function parseDescription(text) {
|
|
1182
1362
|
const parts = text.split(/\n---\n|\n\s*---\s*\n/);
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1363
|
+
return {
|
|
1364
|
+
description: dropHeading(parts[0] ?? "", "DESCRIPTION") || text.trim(),
|
|
1365
|
+
roster: dropHeading(parts.slice(1).join("\n---\n"), "ROSTER") || "(no explicit roster)"
|
|
1366
|
+
};
|
|
1367
|
+
}
|
|
1368
|
+
function dropHeading(section, word) {
|
|
1369
|
+
const s = section.trim();
|
|
1370
|
+
const firstLine = s.split("\n", 1)[0] ?? "";
|
|
1371
|
+
if (new RegExp(`^[#*_\\s]*${word}[#*_:\\s]*$`, "i").test(firstLine)) {
|
|
1372
|
+
return s.slice(firstLine.length).trim();
|
|
1373
|
+
}
|
|
1374
|
+
return s.replace(new RegExp(`^[#*_\\s]*${word}[*_]*\\s*:[*_]*\\s*`, "i"), "");
|
|
1186
1375
|
}
|
|
1187
1376
|
|
|
1188
1377
|
// src/transcribe/prompts.ts
|
|
@@ -1275,13 +1464,6 @@ function transcriptionPrompt(ctx) {
|
|
|
1275
1464
|
"Use a roster name ONLY when the voice itself tells you it's that person (they self-identify, are addressed by name, or the voice description clearly matches). If two speakers sound similar and you are not sure which name belongs to which voice, use 'Speaker A' / 'Speaker B' instead \u2014 a WRONG name is much worse than a generic label; a later pass verifies names."
|
|
1276
1465
|
);
|
|
1277
1466
|
}
|
|
1278
|
-
if (ctx.previousTail) {
|
|
1279
|
-
parts.push("");
|
|
1280
|
-
parts.push(
|
|
1281
|
-
"TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):"
|
|
1282
|
-
);
|
|
1283
|
-
parts.push(ctx.previousTail);
|
|
1284
|
-
}
|
|
1285
1467
|
if (ctx.instructions) {
|
|
1286
1468
|
parts.push("");
|
|
1287
1469
|
parts.push("ADDITIONAL INSTRUCTIONS:");
|
|
@@ -1344,6 +1526,51 @@ function formatDuration(seconds) {
|
|
|
1344
1526
|
return parts.join(" ");
|
|
1345
1527
|
}
|
|
1346
1528
|
|
|
1529
|
+
// src/transcribe/degeneration.ts
|
|
1530
|
+
var DEGENERATE_COMPRESSION_RATIO = 2.2;
|
|
1531
|
+
var WINDOW_CHARS = 400;
|
|
1532
|
+
var STEP_CHARS = 200;
|
|
1533
|
+
var MIN_MATCH = 4;
|
|
1534
|
+
var MAX_MATCH = 258;
|
|
1535
|
+
var REF_COST = 3;
|
|
1536
|
+
function ratio(s) {
|
|
1537
|
+
let cost = 0;
|
|
1538
|
+
for (let i = 0; i < s.length; ) {
|
|
1539
|
+
let best = 0;
|
|
1540
|
+
for (let j = Math.max(0, i - WINDOW_CHARS); j < i; j++) {
|
|
1541
|
+
let k = 0;
|
|
1542
|
+
while (i + k < s.length && k < MAX_MATCH && s[j + k] === s[i + k]) k++;
|
|
1543
|
+
if (k > best) best = k;
|
|
1544
|
+
}
|
|
1545
|
+
if (best >= MIN_MATCH) {
|
|
1546
|
+
cost += REF_COST;
|
|
1547
|
+
i += best;
|
|
1548
|
+
} else {
|
|
1549
|
+
cost += 1;
|
|
1550
|
+
i += 1;
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
return s.length / cost;
|
|
1554
|
+
}
|
|
1555
|
+
function maxCompressionRatio(text) {
|
|
1556
|
+
if (text.length < WINDOW_CHARS) return 0;
|
|
1557
|
+
let max = 0;
|
|
1558
|
+
for (let i = 0; i + WINDOW_CHARS <= text.length; i += STEP_CHARS) {
|
|
1559
|
+
max = Math.max(max, ratio(text.slice(i, i + WINDOW_CHARS)));
|
|
1560
|
+
}
|
|
1561
|
+
return Math.max(max, ratio(text.slice(-WINDOW_CHARS)));
|
|
1562
|
+
}
|
|
1563
|
+
function tailIsDegenerate(text) {
|
|
1564
|
+
if (text.length < 2 * WINDOW_CHARS) return false;
|
|
1565
|
+
return ratio(text.slice(-WINDOW_CHARS)) > DEGENERATE_COMPRESSION_RATIO && ratio(text.slice(-2 * WINDOW_CHARS, -WINDOW_CHARS)) > DEGENERATE_COMPRESSION_RATIO;
|
|
1566
|
+
}
|
|
1567
|
+
function transcriptTextOf(partialJson) {
|
|
1568
|
+
const out = [];
|
|
1569
|
+
for (const m of partialJson.matchAll(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/g))
|
|
1570
|
+
out.push(m[1]);
|
|
1571
|
+
return out.join(" ");
|
|
1572
|
+
}
|
|
1573
|
+
|
|
1347
1574
|
// src/transcribe/llm-transcribe.ts
|
|
1348
1575
|
var MIN_SEGMENTS = 3;
|
|
1349
1576
|
var MIN_SPAN_RATIO = 0.6;
|
|
@@ -1384,6 +1611,16 @@ function parseLlmSegments(data, chunkOffsetSec) {
|
|
|
1384
1611
|
return { segments: out, dropped };
|
|
1385
1612
|
}
|
|
1386
1613
|
function validate(segments, chunkDuration) {
|
|
1614
|
+
const compression = maxCompressionRatio(segments.map((s) => s.text).join(" "));
|
|
1615
|
+
if (compression > DEGENERATE_COMPRESSION_RATIO) {
|
|
1616
|
+
return {
|
|
1617
|
+
isValid: false,
|
|
1618
|
+
degenerate: true,
|
|
1619
|
+
spanSec: segments.length ? segments[segments.length - 1].endSec - segments[0].startSec : 0,
|
|
1620
|
+
segmentCount: segments.length,
|
|
1621
|
+
message: `degenerate repetition (compression ratio ${compression.toFixed(1)} > ${DEGENERATE_COMPRESSION_RATIO})`
|
|
1622
|
+
};
|
|
1623
|
+
}
|
|
1387
1624
|
if (segments.length < MIN_SEGMENTS) {
|
|
1388
1625
|
return {
|
|
1389
1626
|
isValid: false,
|
|
@@ -1414,72 +1651,135 @@ function validate(segments, chunkDuration) {
|
|
|
1414
1651
|
async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts) {
|
|
1415
1652
|
const validationRetries = opts.validationRetries ?? 1;
|
|
1416
1653
|
const prompt = transcriptionPrompt(ctx);
|
|
1417
|
-
let
|
|
1654
|
+
let temperature = opts.temperature ?? 0.2;
|
|
1655
|
+
let loopAborted = false;
|
|
1656
|
+
let checkedAt = 0;
|
|
1657
|
+
const shouldAbort = (raw) => {
|
|
1658
|
+
if (raw.length - checkedAt < 800) return null;
|
|
1659
|
+
checkedAt = raw.length;
|
|
1660
|
+
if (!tailIsDegenerate(transcriptTextOf(raw))) return null;
|
|
1661
|
+
loopAborted = true;
|
|
1662
|
+
return "degenerate repetition";
|
|
1663
|
+
};
|
|
1664
|
+
let best;
|
|
1665
|
+
const rank = (r) => r.validation.isValid ? 3 : r.error ? 0 : r.validation.degenerate ? 1 : 2;
|
|
1666
|
+
const keep = (r) => {
|
|
1667
|
+
if (!best || rank(r) > rank(best) || rank(r) === rank(best) && r.validation.spanSec > best.validation.spanSec)
|
|
1668
|
+
best = r;
|
|
1669
|
+
};
|
|
1418
1670
|
for (let attempt = 0; attempt <= validationRetries; attempt++) {
|
|
1671
|
+
loopAborted = false;
|
|
1672
|
+
checkedAt = 0;
|
|
1419
1673
|
const gen = await client.generateJson(
|
|
1420
1674
|
model,
|
|
1421
1675
|
prompt,
|
|
1422
1676
|
[{ path: chunkPath }],
|
|
1423
1677
|
TRANSCRIPT_SCHEMA,
|
|
1424
1678
|
{
|
|
1425
|
-
temperature
|
|
1679
|
+
temperature,
|
|
1426
1680
|
maxRetries: 3,
|
|
1427
1681
|
logKind: "transcribe",
|
|
1428
|
-
logChunk: ctx.index - 1
|
|
1682
|
+
logChunk: ctx.index - 1,
|
|
1683
|
+
shouldAbort
|
|
1429
1684
|
}
|
|
1430
1685
|
);
|
|
1431
1686
|
if (gen.error || !gen.data) {
|
|
1432
|
-
|
|
1687
|
+
keep({
|
|
1433
1688
|
segments: [],
|
|
1434
1689
|
raw: gen.raw,
|
|
1435
1690
|
usage: gen.usage,
|
|
1436
1691
|
validation: {
|
|
1437
1692
|
isValid: false,
|
|
1693
|
+
degenerate: loopAborted,
|
|
1438
1694
|
spanSec: 0,
|
|
1439
1695
|
segmentCount: 0,
|
|
1440
1696
|
message: gen.error || "no data"
|
|
1441
1697
|
},
|
|
1442
1698
|
error: gen.error
|
|
1443
|
-
};
|
|
1699
|
+
});
|
|
1444
1700
|
logger.warn(
|
|
1445
1701
|
`[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`
|
|
1446
1702
|
);
|
|
1703
|
+
if (loopAborted) temperature = Math.min(1, temperature + 0.3);
|
|
1447
1704
|
continue;
|
|
1448
1705
|
}
|
|
1449
1706
|
const { segments, dropped } = parseLlmSegments(gen.data, chunkStartSec);
|
|
1450
1707
|
const v = validate(segments, opts.chunkDurationSec);
|
|
1451
|
-
|
|
1708
|
+
const result = { segments, raw: gen.raw, usage: gen.usage, validation: v };
|
|
1709
|
+
keep(result);
|
|
1452
1710
|
if (v.isValid) {
|
|
1453
1711
|
logger.info(
|
|
1454
1712
|
`[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`
|
|
1455
1713
|
);
|
|
1456
|
-
return
|
|
1714
|
+
return result;
|
|
1457
1715
|
}
|
|
1458
1716
|
logger.warn(
|
|
1459
1717
|
`[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`
|
|
1460
1718
|
);
|
|
1719
|
+
if (v.degenerate) temperature = Math.min(1, temperature + 0.3);
|
|
1461
1720
|
}
|
|
1462
1721
|
logger.error(
|
|
1463
1722
|
`[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`
|
|
1464
1723
|
);
|
|
1465
|
-
return
|
|
1724
|
+
return best;
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
// src/transcribe/grounding.ts
|
|
1728
|
+
var MIN_GROUNDED_PRECISION = 0.3;
|
|
1729
|
+
var MIN_TOKENS = 30;
|
|
1730
|
+
var MAX_SCRIPT_SHARE_GAP = 0.2;
|
|
1731
|
+
var STOP_WORDS = Object.fromEntries(
|
|
1732
|
+
"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])
|
|
1733
|
+
);
|
|
1734
|
+
var NON_LATIN = /[^\u0000-\u024F\u2000-\u206F]/u;
|
|
1735
|
+
function contentTokens(words) {
|
|
1736
|
+
const bag = /* @__PURE__ */ new Map();
|
|
1737
|
+
for (const w of words) {
|
|
1738
|
+
const t = w.toLowerCase().replace(/^[^\p{L}\p{N}']+|[^\p{L}\p{N}']+$/gu, "").replace(/^'+|'+$/g, "");
|
|
1739
|
+
if (t && !STOP_WORDS[t]) bag.set(t, (bag.get(t) ?? 0) + 1);
|
|
1740
|
+
}
|
|
1741
|
+
return bag;
|
|
1742
|
+
}
|
|
1743
|
+
function chunkGrounding(segments, asrWords, start, end) {
|
|
1744
|
+
const asrInRange = asrWords.filter((w) => w.start >= start && w.start < end);
|
|
1745
|
+
const llmWords = segments.map((s) => s.text.replace(/\[[^\]]*\]/g, " ")).join(" ").split(/\s+/).filter(Boolean);
|
|
1746
|
+
const llm = contentTokens(llmWords);
|
|
1747
|
+
const asr = contentTokens(asrInRange.map((w) => w.text));
|
|
1748
|
+
let llmTokens = 0;
|
|
1749
|
+
let asrTokens = 0;
|
|
1750
|
+
let shared = 0;
|
|
1751
|
+
for (const n of llm.values()) llmTokens += n;
|
|
1752
|
+
for (const n of asr.values()) asrTokens += n;
|
|
1753
|
+
for (const [t, n] of llm) shared += Math.min(n, asr.get(t) ?? 0);
|
|
1754
|
+
const share = (ws) => ws.length ? ws.filter((w) => NON_LATIN.test(w)).length / ws.length : 0;
|
|
1755
|
+
const scriptsMatch = Math.abs(share(llmWords) - share(asrInRange.map((w) => w.text))) <= MAX_SCRIPT_SHARE_GAP;
|
|
1756
|
+
const judged = llmTokens >= MIN_TOKENS && asrTokens >= MIN_TOKENS && scriptsMatch;
|
|
1757
|
+
const precision = llmTokens ? shared / llmTokens : 1;
|
|
1758
|
+
return {
|
|
1759
|
+
llmTokens,
|
|
1760
|
+
asrTokens,
|
|
1761
|
+
precision,
|
|
1762
|
+
judged,
|
|
1763
|
+
grounded: !judged || precision >= MIN_GROUNDED_PRECISION
|
|
1764
|
+
};
|
|
1466
1765
|
}
|
|
1467
1766
|
|
|
1468
1767
|
// src/align/normalize.ts
|
|
1469
|
-
function
|
|
1470
|
-
return word.toLowerCase().replace(
|
|
1768
|
+
function normalizeWord(word) {
|
|
1769
|
+
return word.normalize("NFKC").toLowerCase().replace(/[’‘`]/g, "'").replace(/^[^\p{L}\p{M}\p{N}']+|[^\p{L}\p{M}\p{N}']+$/gu, "").replace(/^'+|'+$/g, "");
|
|
1471
1770
|
}
|
|
1472
1771
|
function tokenize(text) {
|
|
1473
1772
|
const out = [];
|
|
1474
1773
|
for (const raw of text.split(/\s+/)) {
|
|
1475
1774
|
if (!raw) continue;
|
|
1476
|
-
const norm2 =
|
|
1775
|
+
const norm2 = normalizeWord(raw);
|
|
1477
1776
|
if (norm2) out.push({ original: raw, norm: norm2 });
|
|
1478
1777
|
}
|
|
1479
1778
|
return out;
|
|
1480
1779
|
}
|
|
1481
1780
|
function fuzzyEqual(a, b) {
|
|
1482
1781
|
if (a === b) return true;
|
|
1782
|
+
if (!a || !b) return false;
|
|
1483
1783
|
if (Math.abs(a.length - b.length) <= 1) {
|
|
1484
1784
|
return editDistanceChars(a, b, 1) <= 1;
|
|
1485
1785
|
}
|
|
@@ -1505,9 +1805,85 @@ function editDistanceChars(a, b, max) {
|
|
|
1505
1805
|
return prev[n];
|
|
1506
1806
|
}
|
|
1507
1807
|
|
|
1808
|
+
// src/transcribe/coverage.ts
|
|
1809
|
+
var MIN_COVERAGE_RATIO = 0.6;
|
|
1810
|
+
var MIN_ASR_WORDS = 200;
|
|
1811
|
+
function chunkCoverage(segments, asrWords, start, end) {
|
|
1812
|
+
const llmWords = segments.reduce(
|
|
1813
|
+
(n, s) => n + tokenize(s.text.replace(/\[[^\]]*\]/g, " ")).length,
|
|
1814
|
+
0
|
|
1815
|
+
);
|
|
1816
|
+
const asrCount = asrWords.reduce(
|
|
1817
|
+
(n, w) => n + (w.start >= start && w.start < end ? tokenize(w.text).length : 0),
|
|
1818
|
+
0
|
|
1819
|
+
);
|
|
1820
|
+
const ratio2 = asrCount ? llmWords / asrCount : Infinity;
|
|
1821
|
+
const judged = asrCount >= MIN_ASR_WORDS;
|
|
1822
|
+
return {
|
|
1823
|
+
llmWords,
|
|
1824
|
+
asrWords: asrCount,
|
|
1825
|
+
ratio: ratio2,
|
|
1826
|
+
judged,
|
|
1827
|
+
low: judged && ratio2 < MIN_COVERAGE_RATIO
|
|
1828
|
+
};
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
// src/core/retranscribe.ts
|
|
1832
|
+
var import_node_fs5 = require("fs");
|
|
1833
|
+
var HALF_OVERLAP_SEC = 5;
|
|
1834
|
+
async function transcribeInHalves(opts) {
|
|
1835
|
+
const { chunk } = opts;
|
|
1836
|
+
const mid = (chunk.start + chunk.end) / 2;
|
|
1837
|
+
const halves = [
|
|
1838
|
+
{ name: "a", from: chunk.start, to: Math.min(chunk.end, mid + HALF_OVERLAP_SEC) },
|
|
1839
|
+
{ name: "b", from: Math.max(chunk.start, mid - HALF_OVERLAP_SEC), to: chunk.end }
|
|
1840
|
+
];
|
|
1841
|
+
const results = [];
|
|
1842
|
+
for (const h of halves) {
|
|
1843
|
+
const path = `${opts.pathPrefix}_half_${h.name}.mp3`;
|
|
1844
|
+
if (!(0, import_node_fs5.existsSync)(path))
|
|
1845
|
+
await extractChunk(opts.audioPath, path, h.from, h.to, opts.audioOpts);
|
|
1846
|
+
results.push(
|
|
1847
|
+
await transcribeChunk(opts.client, opts.model, path, h.from, opts.ctx, {
|
|
1848
|
+
chunkDurationSec: h.to - h.from,
|
|
1849
|
+
validationRetries: 0
|
|
1850
|
+
})
|
|
1851
|
+
);
|
|
1852
|
+
}
|
|
1853
|
+
const [a, b] = results;
|
|
1854
|
+
const center = (s) => (s.startSec + s.endSec) / 2;
|
|
1855
|
+
const segments = [
|
|
1856
|
+
...a.segments.filter((s) => center(s) < mid),
|
|
1857
|
+
...b.segments.filter((s) => center(s) >= mid)
|
|
1858
|
+
];
|
|
1859
|
+
const first = segments[0];
|
|
1860
|
+
const last = segments[segments.length - 1];
|
|
1861
|
+
return {
|
|
1862
|
+
segments,
|
|
1863
|
+
raw: JSON.stringify({ halves: [a.raw, b.raw] }),
|
|
1864
|
+
usage: {
|
|
1865
|
+
inputTokens: a.usage.inputTokens + b.usage.inputTokens,
|
|
1866
|
+
outputTokens: a.usage.outputTokens + b.usage.outputTokens,
|
|
1867
|
+
thoughtTokens: (a.usage.thoughtTokens ?? 0) + (b.usage.thoughtTokens ?? 0),
|
|
1868
|
+
totalTokens: a.usage.totalTokens + b.usage.totalTokens
|
|
1869
|
+
},
|
|
1870
|
+
validation: {
|
|
1871
|
+
isValid: a.validation.isValid && b.validation.isValid,
|
|
1872
|
+
degenerate: Boolean(a.validation.degenerate || b.validation.degenerate),
|
|
1873
|
+
spanSec: first && last ? last.endSec - first.startSec : 0,
|
|
1874
|
+
segmentCount: segments.length,
|
|
1875
|
+
message: `halves: ${a.validation.message} | ${b.validation.message}`
|
|
1876
|
+
},
|
|
1877
|
+
...a.error || b.error ? { error: [a.error, b.error].filter(Boolean).join(" | ") } : {}
|
|
1878
|
+
};
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1508
1881
|
// src/align/edit-distance.ts
|
|
1509
1882
|
var INDEL = 2;
|
|
1883
|
+
var OUT_OF_WINDOW = { cost: 2 * INDEL + 1, fuzzy: false };
|
|
1510
1884
|
function matchCost(a, b) {
|
|
1885
|
+
if (a.window && b.start !== void 0 && (b.start < a.window.lo || b.start > a.window.hi))
|
|
1886
|
+
return OUT_OF_WINDOW;
|
|
1511
1887
|
if (a.norm === b.norm) return { cost: 0, fuzzy: false };
|
|
1512
1888
|
if (fuzzyEqual(a.norm, b.norm)) return { cost: 1, fuzzy: true };
|
|
1513
1889
|
return { cost: 2, fuzzy: false };
|
|
@@ -1585,12 +1961,19 @@ function alignWords(llm, asr) {
|
|
|
1585
1961
|
}
|
|
1586
1962
|
|
|
1587
1963
|
// src/align/aligner.ts
|
|
1964
|
+
var WINDOW_SLACK_SEC = 2;
|
|
1965
|
+
var UNANCHORED_MAX_DRIFT_SEC = 15;
|
|
1966
|
+
var STRETCH_MIN_SEC = 30;
|
|
1967
|
+
var STRETCH_SEC_PER_WORD = 3;
|
|
1968
|
+
var MAX_INNER_GAP_SEC = 8;
|
|
1969
|
+
var SPOKEN_SEC_PER_WORD = 0.5;
|
|
1970
|
+
var UNCONFIRMED_MAX_SEC = 5;
|
|
1588
1971
|
function toAsrTokens(words) {
|
|
1589
1972
|
return words.map((w) => ({
|
|
1590
1973
|
text: w.text,
|
|
1591
1974
|
start: w.start,
|
|
1592
1975
|
end: w.end,
|
|
1593
|
-
norm: w.text
|
|
1976
|
+
norm: normalizeWord(w.text)
|
|
1594
1977
|
}));
|
|
1595
1978
|
}
|
|
1596
1979
|
function transferTiming(llm, asr, ops) {
|
|
@@ -1649,7 +2032,9 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
|
|
|
1649
2032
|
for (const { s, i } of sorted) {
|
|
1650
2033
|
const toks = tokenize(s.text);
|
|
1651
2034
|
const start = flat.length;
|
|
1652
|
-
|
|
2035
|
+
const window = s.chunkStart !== void 0 && s.chunkEnd !== void 0 ? { lo: s.chunkStart - WINDOW_SLACK_SEC, hi: s.chunkEnd + WINDOW_SLACK_SEC } : void 0;
|
|
2036
|
+
for (const t of toks)
|
|
2037
|
+
flat.push({ original: t.original, norm: t.norm, segIdx: i, window });
|
|
1653
2038
|
segRanges.push({ src: i, start, end: flat.length });
|
|
1654
2039
|
}
|
|
1655
2040
|
if (flat.length === 0 || asrWords.length === 0) {
|
|
@@ -1694,21 +2079,53 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
|
|
|
1694
2079
|
let end;
|
|
1695
2080
|
let timingSource;
|
|
1696
2081
|
const confidence = tokenCount ? exact / tokenCount : 0;
|
|
1697
|
-
|
|
2082
|
+
const unanchoredDrift = segOps.length === 0 && firstTimed ? Math.abs(firstTimed.start - s.startSec) : 0;
|
|
2083
|
+
if (firstTimed && lastTimed && unanchoredDrift <= UNANCHORED_MAX_DRIFT_SEC) {
|
|
1698
2084
|
start = firstTimed.start;
|
|
1699
2085
|
end = lastTimed.end;
|
|
1700
2086
|
timingSource = confidence >= confThreshold ? "aligned" : "interpolated";
|
|
2087
|
+
if (end - start > Math.max(STRETCH_MIN_SEC, STRETCH_SEC_PER_WORD * tokenCount)) {
|
|
2088
|
+
const runs = [];
|
|
2089
|
+
for (const t of segTimes) {
|
|
2090
|
+
if (isNaN(t.start)) continue;
|
|
2091
|
+
const run2 = runs[runs.length - 1];
|
|
2092
|
+
if (run2 && t.start - run2.end <= MAX_INNER_GAP_SEC) {
|
|
2093
|
+
run2.end = Math.max(run2.end, t.end);
|
|
2094
|
+
if (t.matched) run2.matched++;
|
|
2095
|
+
} else {
|
|
2096
|
+
runs.push({ start: t.start, end: t.end, matched: t.matched ? 1 : 0 });
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
const best = runs.reduce(
|
|
2100
|
+
(a, b) => b.matched > a.matched || b.matched === a.matched && Math.abs(b.start - s.startSec) < Math.abs(a.start - s.startSec) ? b : a
|
|
2101
|
+
);
|
|
2102
|
+
start = best.start;
|
|
2103
|
+
end = best.end;
|
|
2104
|
+
}
|
|
2105
|
+
const spoken = Math.max(1, SPOKEN_SEC_PER_WORD * tokenCount);
|
|
2106
|
+
if (exact === 0 && end - start > Math.max(UNCONFIRMED_MAX_SEC, 3 * spoken)) {
|
|
2107
|
+
end = start + spoken;
|
|
2108
|
+
}
|
|
1701
2109
|
} else {
|
|
1702
2110
|
start = s.startSec;
|
|
1703
2111
|
end = s.endSec;
|
|
1704
2112
|
timingSource = "coarse";
|
|
1705
2113
|
}
|
|
1706
|
-
const
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
2114
|
+
const step = timingSource === "coarse" && tokenCount ? (end - start) / tokenCount : 0;
|
|
2115
|
+
const inside = (x) => Math.min(Math.max(x, start), end);
|
|
2116
|
+
const words = segTimes.map(
|
|
2117
|
+
(t, idx) => timingSource === "coarse" ? {
|
|
2118
|
+
text: flat[range.start + idx].original,
|
|
2119
|
+
start: start + step * idx,
|
|
2120
|
+
end: start + step * (idx + 1),
|
|
2121
|
+
matched: false
|
|
2122
|
+
} : {
|
|
2123
|
+
text: flat[range.start + idx].original,
|
|
2124
|
+
start: isNaN(t.start) ? start : inside(t.start),
|
|
2125
|
+
end: isNaN(t.end) ? end : inside(t.end),
|
|
2126
|
+
matched: t.matched
|
|
2127
|
+
}
|
|
2128
|
+
);
|
|
1712
2129
|
out.push({
|
|
1713
2130
|
speaker: s.speaker,
|
|
1714
2131
|
start,
|
|
@@ -1723,23 +2140,90 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
|
|
|
1723
2140
|
}
|
|
1724
2141
|
return out;
|
|
1725
2142
|
}
|
|
2143
|
+
var CLOCK_ANCHOR_MIN_WORDS = 3;
|
|
2144
|
+
var CLOCK_ANCHOR_MIN_SHARE = 0.6;
|
|
2145
|
+
function toAsrClock(segments, asrWords) {
|
|
2146
|
+
if (!asrWords.length) return segments;
|
|
2147
|
+
const chunks = /* @__PURE__ */ new Map();
|
|
2148
|
+
for (const s of segments) {
|
|
2149
|
+
if (s.chunkIndex === void 0) continue;
|
|
2150
|
+
const group = chunks.get(s.chunkIndex);
|
|
2151
|
+
if (group) group.push(s);
|
|
2152
|
+
else chunks.set(s.chunkIndex, [s]);
|
|
2153
|
+
}
|
|
2154
|
+
const moved = /* @__PURE__ */ new Map();
|
|
2155
|
+
for (const group of chunks.values()) {
|
|
2156
|
+
const lo = Math.min(...group.map((s) => s.chunkStart ?? s.startSec)) - WINDOW_SLACK_SEC;
|
|
2157
|
+
const hi = Math.max(...group.map((s) => s.chunkEnd ?? s.endSec)) + WINDOW_SLACK_SEC;
|
|
2158
|
+
const aligned = alignSegments(
|
|
2159
|
+
group,
|
|
2160
|
+
asrWords.filter((w) => w.end >= lo && w.start <= hi)
|
|
2161
|
+
);
|
|
2162
|
+
const shifts = aligned.map(
|
|
2163
|
+
(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
|
|
2164
|
+
);
|
|
2165
|
+
for (let k = 0; k < aligned.length; k++) {
|
|
2166
|
+
let shift = shifts[k];
|
|
2167
|
+
for (let r = 1; shift === void 0 && r < aligned.length; r++) {
|
|
2168
|
+
shift = shifts[k - r] ?? shifts[k + r];
|
|
2169
|
+
}
|
|
2170
|
+
const s = group[aligned[k].sourceIndex];
|
|
2171
|
+
moved.set(s, {
|
|
2172
|
+
...s,
|
|
2173
|
+
startSec: s.startSec + (shift ?? 0),
|
|
2174
|
+
endSec: s.endSec + (shift ?? 0)
|
|
2175
|
+
});
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
return segments.map((s) => moved.get(s) ?? s);
|
|
2179
|
+
}
|
|
1726
2180
|
|
|
1727
2181
|
// src/align/fill-gaps.ts
|
|
1728
2182
|
var MIN_GAP_SEC = 0.8;
|
|
1729
2183
|
var MIN_WORDS = 1;
|
|
1730
|
-
|
|
1731
|
-
|
|
2184
|
+
var HEAD_SLACK_WORDS = 5;
|
|
2185
|
+
function utteranceAt(utts, t) {
|
|
2186
|
+
let lo = 0;
|
|
2187
|
+
let hi = utts.length - 1;
|
|
2188
|
+
let found = -1;
|
|
2189
|
+
while (lo <= hi) {
|
|
2190
|
+
const mid = lo + hi >> 1;
|
|
2191
|
+
if (utts[mid].start <= t) {
|
|
2192
|
+
found = mid;
|
|
2193
|
+
lo = mid + 1;
|
|
2194
|
+
} else {
|
|
2195
|
+
hi = mid - 1;
|
|
2196
|
+
}
|
|
2197
|
+
}
|
|
2198
|
+
return found >= 0 && t <= utts[found].end ? found : -1;
|
|
2199
|
+
}
|
|
2200
|
+
function dominantSpeaker(utts, start, end) {
|
|
2201
|
+
let best = utts[0]?.speaker || "speaker_?";
|
|
2202
|
+
let bestOv = 0;
|
|
2203
|
+
for (const u of utts) {
|
|
2204
|
+
const ov = Math.max(0, Math.min(end, u.end) - Math.max(start, u.start));
|
|
2205
|
+
if (ov > bestOv) {
|
|
2206
|
+
bestOv = ov;
|
|
2207
|
+
best = u.speaker;
|
|
2208
|
+
}
|
|
2209
|
+
}
|
|
2210
|
+
return best;
|
|
1732
2211
|
}
|
|
1733
2212
|
function fillAsrGaps(segments, asrWords, asrUtterances) {
|
|
1734
2213
|
if (!asrWords.length) return segments;
|
|
1735
2214
|
const sorted = [...segments].sort((a, b) => a.start - b.start);
|
|
2215
|
+
const utts = [...asrUtterances].sort((a, b) => a.start - b.start);
|
|
1736
2216
|
const ranges = [];
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
2217
|
+
if (!sorted.length) {
|
|
2218
|
+
ranges.push([0, Infinity, void 0]);
|
|
2219
|
+
} else {
|
|
2220
|
+
if (sorted[0].start > 0) ranges.push([0, sorted[0].start, sorted[0]]);
|
|
2221
|
+
let coveredTo = sorted[0].end;
|
|
2222
|
+
for (const next of sorted.slice(1)) {
|
|
2223
|
+
if (next.start > coveredTo) ranges.push([coveredTo, next.start, next]);
|
|
2224
|
+
coveredTo = Math.max(coveredTo, next.end);
|
|
2225
|
+
}
|
|
2226
|
+
ranges.push([coveredTo, Infinity, void 0]);
|
|
1743
2227
|
}
|
|
1744
2228
|
const filled = [];
|
|
1745
2229
|
for (const [gs, ge, following] of ranges) {
|
|
@@ -1747,38 +2231,44 @@ function fillAsrGaps(segments, asrWords, asrUtterances) {
|
|
|
1747
2231
|
const words = asrWords.filter((w) => w.start >= gs && w.start < ge);
|
|
1748
2232
|
if (words.length < MIN_WORDS) continue;
|
|
1749
2233
|
if (following) {
|
|
1750
|
-
const
|
|
1751
|
-
const
|
|
1752
|
-
(
|
|
2234
|
+
const gapNorms = words.map((w) => normalizeWord(w.text)).filter(Boolean);
|
|
2235
|
+
const head = new Set(
|
|
2236
|
+
tokenize(following.text).slice(0, gapNorms.length + HEAD_SLACK_WORDS).map((t) => t.norm)
|
|
1753
2237
|
);
|
|
1754
|
-
const covered = gapNorms.filter((n) =>
|
|
1755
|
-
if (covered / gapNorms.
|
|
1756
|
-
}
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
const
|
|
1761
|
-
if (
|
|
1762
|
-
|
|
1763
|
-
|
|
2238
|
+
const covered = gapNorms.filter((n) => head.has(n)).length;
|
|
2239
|
+
if (covered / gapNorms.length >= 0.6) continue;
|
|
2240
|
+
}
|
|
2241
|
+
const runs = [];
|
|
2242
|
+
for (const w of words) {
|
|
2243
|
+
const u = utteranceAt(utts, w.start);
|
|
2244
|
+
const cur = runs[runs.length - 1];
|
|
2245
|
+
if (cur && (u === -1 || u === cur.utt || cur.utt === -1)) {
|
|
2246
|
+
cur.words.push(w);
|
|
2247
|
+
if (cur.utt === -1) cur.utt = u;
|
|
2248
|
+
} else {
|
|
2249
|
+
runs.push({ words: [w], utt: u });
|
|
1764
2250
|
}
|
|
1765
2251
|
}
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
2252
|
+
for (const run2 of runs) {
|
|
2253
|
+
const first = run2.words[0];
|
|
2254
|
+
const last = run2.words[run2.words.length - 1];
|
|
2255
|
+
filled.push({
|
|
2256
|
+
speaker: run2.utt >= 0 ? utts[run2.utt].speaker : dominantSpeaker(utts, first.start, last.end),
|
|
2257
|
+
start: first.start,
|
|
2258
|
+
end: last.end,
|
|
2259
|
+
text: run2.words.map((w) => w.text).join(" "),
|
|
2260
|
+
tone: [],
|
|
2261
|
+
confidence: 0,
|
|
2262
|
+
timingSource: "timestamped",
|
|
2263
|
+
words: run2.words.map((w) => ({
|
|
2264
|
+
text: w.text,
|
|
2265
|
+
start: w.start,
|
|
2266
|
+
end: w.end,
|
|
2267
|
+
matched: true
|
|
2268
|
+
})),
|
|
2269
|
+
sourceIndex: -1
|
|
2270
|
+
});
|
|
2271
|
+
}
|
|
1782
2272
|
}
|
|
1783
2273
|
if (!filled.length) return sorted;
|
|
1784
2274
|
return [...sorted, ...filled].sort((a, b) => a.start - b.start);
|
|
@@ -2030,125 +2520,6 @@ function splitMixedVoiceSegments(segments, utterances) {
|
|
|
2030
2520
|
return out.sort((a, b) => a.start - b.start);
|
|
2031
2521
|
}
|
|
2032
2522
|
|
|
2033
|
-
// src/providers/openai-compat.ts
|
|
2034
|
-
var PROVIDER_BASE = {
|
|
2035
|
-
deepseek: "https://api.deepseek.com/v1",
|
|
2036
|
-
groq: "https://api.groq.com/openai/v1",
|
|
2037
|
-
openai: "https://api.openai.com/v1"
|
|
2038
|
-
};
|
|
2039
|
-
var OpenAICompatClient = class _OpenAICompatClient {
|
|
2040
|
-
constructor(baseUrl, apiKey, defaultModel, providerName = "openai-compat") {
|
|
2041
|
-
this.baseUrl = baseUrl;
|
|
2042
|
-
this.apiKey = apiKey;
|
|
2043
|
-
this.defaultModel = defaultModel;
|
|
2044
|
-
this.providerName = providerName;
|
|
2045
|
-
}
|
|
2046
|
-
baseUrl;
|
|
2047
|
-
apiKey;
|
|
2048
|
-
defaultModel;
|
|
2049
|
-
providerName;
|
|
2050
|
-
static fromProvider(provider, apiKey, defaultModel) {
|
|
2051
|
-
const base = PROVIDER_BASE[provider] ?? provider;
|
|
2052
|
-
return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
|
|
2053
|
-
}
|
|
2054
|
-
async chat(model, messages, opts = {}) {
|
|
2055
|
-
const m = model ?? this.defaultModel;
|
|
2056
|
-
const maxRetries = opts.maxRetries ?? 5;
|
|
2057
|
-
const body = {
|
|
2058
|
-
model: m,
|
|
2059
|
-
messages,
|
|
2060
|
-
temperature: opts.temperature ?? 0.2
|
|
2061
|
-
};
|
|
2062
|
-
if (opts.maxTokens) body.max_tokens = opts.maxTokens;
|
|
2063
|
-
if (opts.responseJson) {
|
|
2064
|
-
body.response_format = { type: "json_object" };
|
|
2065
|
-
}
|
|
2066
|
-
if (this.providerName === "gemini") {
|
|
2067
|
-
body.reasoning_effort = "low";
|
|
2068
|
-
}
|
|
2069
|
-
let lastError;
|
|
2070
|
-
const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
|
|
2071
|
-
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
2072
|
-
const t0 = Date.now();
|
|
2073
|
-
try {
|
|
2074
|
-
const res = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
2075
|
-
method: "POST",
|
|
2076
|
-
headers: {
|
|
2077
|
-
"Content-Type": "application/json",
|
|
2078
|
-
Authorization: `Bearer ${this.apiKey}`
|
|
2079
|
-
},
|
|
2080
|
-
body: JSON.stringify(body)
|
|
2081
|
-
});
|
|
2082
|
-
if (!res.ok) {
|
|
2083
|
-
const txt = await res.text();
|
|
2084
|
-
throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
|
|
2085
|
-
}
|
|
2086
|
-
const data = await res.json();
|
|
2087
|
-
const text = data.choices?.[0]?.message?.content ?? "";
|
|
2088
|
-
const usage = {
|
|
2089
|
-
inputTokens: data.usage?.prompt_tokens ?? 0,
|
|
2090
|
-
outputTokens: data.usage?.completion_tokens ?? 0
|
|
2091
|
-
};
|
|
2092
|
-
logLlmCall({
|
|
2093
|
-
ts: new Date(t0).toISOString(),
|
|
2094
|
-
provider: this.providerName,
|
|
2095
|
-
model: m,
|
|
2096
|
-
kind: opts.logKind,
|
|
2097
|
-
prompt: promptStr,
|
|
2098
|
-
response: text,
|
|
2099
|
-
usage,
|
|
2100
|
-
durationMs: Date.now() - t0,
|
|
2101
|
-
attempt: attempt + 1
|
|
2102
|
-
});
|
|
2103
|
-
return { text, usage };
|
|
2104
|
-
} catch (err) {
|
|
2105
|
-
lastError = err instanceof Error ? err.message : String(err);
|
|
2106
|
-
if (body.response_format && /response_format/i.test(lastError)) {
|
|
2107
|
-
delete body.response_format;
|
|
2108
|
-
continue;
|
|
2109
|
-
}
|
|
2110
|
-
if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
|
|
2111
|
-
delete body.reasoning_effort;
|
|
2112
|
-
continue;
|
|
2113
|
-
}
|
|
2114
|
-
logLlmCall({
|
|
2115
|
-
ts: new Date(t0).toISOString(),
|
|
2116
|
-
provider: this.providerName,
|
|
2117
|
-
model: m,
|
|
2118
|
-
kind: opts.logKind,
|
|
2119
|
-
prompt: promptStr,
|
|
2120
|
-
response: "",
|
|
2121
|
-
durationMs: Date.now() - t0,
|
|
2122
|
-
attempt: attempt + 1,
|
|
2123
|
-
error: lastError
|
|
2124
|
-
});
|
|
2125
|
-
if (attempt < maxRetries - 1)
|
|
2126
|
-
await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
|
|
2127
|
-
}
|
|
2128
|
-
}
|
|
2129
|
-
return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
|
|
2130
|
-
}
|
|
2131
|
-
async chatJson(model, messages, opts = {}) {
|
|
2132
|
-
let lastRaw = "";
|
|
2133
|
-
let lastError;
|
|
2134
|
-
for (let attempt = 0; attempt < 2; attempt++) {
|
|
2135
|
-
const res = await this.chat(model, messages, { ...opts, responseJson: true });
|
|
2136
|
-
lastRaw = res.text;
|
|
2137
|
-
lastError = res.error;
|
|
2138
|
-
if (res.error || !res.text) continue;
|
|
2139
|
-
try {
|
|
2140
|
-
let txt = res.text.trim();
|
|
2141
|
-
const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
|
|
2142
|
-
if (fence && fence[1]) txt = fence[1];
|
|
2143
|
-
return { data: JSON.parse(txt), raw: res.text };
|
|
2144
|
-
} catch (err) {
|
|
2145
|
-
lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
|
|
2146
|
-
}
|
|
2147
|
-
}
|
|
2148
|
-
return { data: null, raw: lastRaw, error: lastError };
|
|
2149
|
-
}
|
|
2150
|
-
};
|
|
2151
|
-
|
|
2152
2523
|
// src/diarize/identify.ts
|
|
2153
2524
|
var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
|
|
2154
2525
|
function buildTranscriptExcerpt(segments, speakers) {
|
|
@@ -2414,7 +2785,8 @@ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts
|
|
|
2414
2785
|
wantB ? runPass(reasonerB) : Promise.resolve(void 0)
|
|
2415
2786
|
]);
|
|
2416
2787
|
const passFailed = (r) => !!r && r.speakers.length === 0 && /fetch failed|HTTP \d|network|ENOTFOUND|JSON parse|no response/i.test(r.reasoning);
|
|
2417
|
-
|
|
2788
|
+
const allPassesFailed = passFailed(resA) && (!wantB || passFailed(resB));
|
|
2789
|
+
if (allPassesFailed) {
|
|
2418
2790
|
logger.warn(
|
|
2419
2791
|
`identify: ALL passes failed (${resA.reasoning.slice(0, 80)}) \u2014 speakers left as generic labels. Re-run to retry naming cheaply (everything else is cached).`
|
|
2420
2792
|
);
|
|
@@ -2519,10 +2891,164 @@ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts
|
|
|
2519
2891
|
decisions,
|
|
2520
2892
|
tripwires,
|
|
2521
2893
|
passA: { ...resA, model: reasonerA.model },
|
|
2522
|
-
passB: resB ? { ...resB, model: reasonerB.model } : void 0
|
|
2894
|
+
passB: resB ? { ...resB, model: reasonerB.model } : void 0,
|
|
2895
|
+
allPassesFailed
|
|
2523
2896
|
};
|
|
2524
2897
|
}
|
|
2525
2898
|
|
|
2899
|
+
// src/providers/openai-compat.ts
|
|
2900
|
+
async function chatJsonWith(client, model, messages, opts) {
|
|
2901
|
+
let lastRaw = "";
|
|
2902
|
+
let lastError;
|
|
2903
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
2904
|
+
const res = await client.chat(model, messages, { ...opts, responseJson: true });
|
|
2905
|
+
lastRaw = res.text;
|
|
2906
|
+
lastError = res.error;
|
|
2907
|
+
if (res.error || !res.text) continue;
|
|
2908
|
+
try {
|
|
2909
|
+
let txt = res.text.trim();
|
|
2910
|
+
const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
|
|
2911
|
+
if (fence && fence[1]) txt = fence[1];
|
|
2912
|
+
return { data: JSON.parse(txt), raw: res.text };
|
|
2913
|
+
} catch (err) {
|
|
2914
|
+
lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
|
|
2915
|
+
}
|
|
2916
|
+
}
|
|
2917
|
+
return { data: null, raw: lastRaw, error: lastError };
|
|
2918
|
+
}
|
|
2919
|
+
var PROVIDER_BASE = {
|
|
2920
|
+
deepseek: "https://api.deepseek.com/v1",
|
|
2921
|
+
groq: "https://api.groq.com/openai/v1",
|
|
2922
|
+
openai: "https://api.openai.com/v1"
|
|
2923
|
+
};
|
|
2924
|
+
var OpenAICompatClient = class _OpenAICompatClient {
|
|
2925
|
+
constructor(baseUrl, apiKey, defaultModel, providerName = "openai-compat") {
|
|
2926
|
+
this.baseUrl = baseUrl;
|
|
2927
|
+
this.apiKey = apiKey;
|
|
2928
|
+
this.defaultModel = defaultModel;
|
|
2929
|
+
this.providerName = providerName;
|
|
2930
|
+
}
|
|
2931
|
+
baseUrl;
|
|
2932
|
+
apiKey;
|
|
2933
|
+
defaultModel;
|
|
2934
|
+
providerName;
|
|
2935
|
+
static fromProvider(provider, apiKey, defaultModel) {
|
|
2936
|
+
const base = PROVIDER_BASE[provider] ?? provider;
|
|
2937
|
+
return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
|
|
2938
|
+
}
|
|
2939
|
+
async chat(model, messages, opts = {}) {
|
|
2940
|
+
const m = model ?? this.defaultModel;
|
|
2941
|
+
const maxRetries = opts.maxRetries ?? 5;
|
|
2942
|
+
const body = {
|
|
2943
|
+
model: m,
|
|
2944
|
+
messages,
|
|
2945
|
+
temperature: opts.temperature ?? 0.2
|
|
2946
|
+
};
|
|
2947
|
+
if (opts.maxTokens) body.max_tokens = opts.maxTokens;
|
|
2948
|
+
if (opts.responseJson) {
|
|
2949
|
+
body.response_format = { type: "json_object" };
|
|
2950
|
+
}
|
|
2951
|
+
if (this.providerName === "gemini") {
|
|
2952
|
+
body.reasoning_effort = "low";
|
|
2953
|
+
}
|
|
2954
|
+
let lastError;
|
|
2955
|
+
const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
|
|
2956
|
+
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
2957
|
+
const t0 = Date.now();
|
|
2958
|
+
try {
|
|
2959
|
+
const res = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
2960
|
+
method: "POST",
|
|
2961
|
+
headers: {
|
|
2962
|
+
"Content-Type": "application/json",
|
|
2963
|
+
Authorization: `Bearer ${this.apiKey}`
|
|
2964
|
+
},
|
|
2965
|
+
body: JSON.stringify(body)
|
|
2966
|
+
});
|
|
2967
|
+
if (!res.ok) {
|
|
2968
|
+
const txt = await res.text();
|
|
2969
|
+
throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
|
|
2970
|
+
}
|
|
2971
|
+
const data = await res.json();
|
|
2972
|
+
const text = data.choices?.[0]?.message?.content ?? "";
|
|
2973
|
+
const usage = {
|
|
2974
|
+
inputTokens: data.usage?.prompt_tokens ?? 0,
|
|
2975
|
+
outputTokens: data.usage?.completion_tokens ?? 0
|
|
2976
|
+
};
|
|
2977
|
+
logLlmCall({
|
|
2978
|
+
ts: new Date(t0).toISOString(),
|
|
2979
|
+
provider: this.providerName,
|
|
2980
|
+
model: m,
|
|
2981
|
+
kind: opts.logKind,
|
|
2982
|
+
prompt: promptStr,
|
|
2983
|
+
response: text,
|
|
2984
|
+
usage,
|
|
2985
|
+
durationMs: Date.now() - t0,
|
|
2986
|
+
attempt: attempt + 1
|
|
2987
|
+
});
|
|
2988
|
+
return { text, usage };
|
|
2989
|
+
} catch (err) {
|
|
2990
|
+
lastError = err instanceof Error ? err.message : String(err);
|
|
2991
|
+
if (body.response_format && /response_format/i.test(lastError)) {
|
|
2992
|
+
delete body.response_format;
|
|
2993
|
+
continue;
|
|
2994
|
+
}
|
|
2995
|
+
if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
|
|
2996
|
+
delete body.reasoning_effort;
|
|
2997
|
+
continue;
|
|
2998
|
+
}
|
|
2999
|
+
logLlmCall({
|
|
3000
|
+
ts: new Date(t0).toISOString(),
|
|
3001
|
+
provider: this.providerName,
|
|
3002
|
+
model: m,
|
|
3003
|
+
kind: opts.logKind,
|
|
3004
|
+
prompt: promptStr,
|
|
3005
|
+
response: "",
|
|
3006
|
+
durationMs: Date.now() - t0,
|
|
3007
|
+
attempt: attempt + 1,
|
|
3008
|
+
error: lastError
|
|
3009
|
+
});
|
|
3010
|
+
if (attempt < maxRetries - 1)
|
|
3011
|
+
await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
|
|
3012
|
+
}
|
|
3013
|
+
}
|
|
3014
|
+
return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
|
|
3015
|
+
}
|
|
3016
|
+
chatJson(model, messages, opts = {}) {
|
|
3017
|
+
return chatJsonWith(this, model, messages, opts);
|
|
3018
|
+
}
|
|
3019
|
+
};
|
|
3020
|
+
|
|
3021
|
+
// src/providers/gemini-chat.ts
|
|
3022
|
+
var THINKING_HEADROOM_TOKENS = 4096;
|
|
3023
|
+
var GeminiChatClient = class {
|
|
3024
|
+
constructor(gemini, defaultModel) {
|
|
3025
|
+
this.gemini = gemini;
|
|
3026
|
+
this.defaultModel = defaultModel;
|
|
3027
|
+
}
|
|
3028
|
+
gemini;
|
|
3029
|
+
defaultModel;
|
|
3030
|
+
async chat(model, messages, opts = {}) {
|
|
3031
|
+
const system = messages.filter((m) => m.role === "system").map((m) => m.content);
|
|
3032
|
+
const prompt = messages.filter((m) => m.role !== "system").map((m) => m.content).join("\n\n");
|
|
3033
|
+
const r = await this.gemini.generate(model ?? this.defaultModel, prompt, [], {
|
|
3034
|
+
temperature: opts.temperature ?? 0.2,
|
|
3035
|
+
maxOutputTokens: opts.maxTokens ? opts.maxTokens + THINKING_HEADROOM_TOKENS : void 0,
|
|
3036
|
+
responseJson: opts.responseJson,
|
|
3037
|
+
systemInstruction: system.length ? system.join("\n\n") : void 0,
|
|
3038
|
+
maxRetries: opts.maxRetries ?? 5,
|
|
3039
|
+
logKind: opts.logKind
|
|
3040
|
+
});
|
|
3041
|
+
const usage = {
|
|
3042
|
+
inputTokens: r.usage.inputTokens,
|
|
3043
|
+
outputTokens: r.usage.outputTokens
|
|
3044
|
+
};
|
|
3045
|
+
return r.error ? { text: r.text, usage, error: r.error } : { text: r.text, usage };
|
|
3046
|
+
}
|
|
3047
|
+
chatJson(model, messages, opts = {}) {
|
|
3048
|
+
return chatJsonWith(this, model, messages, opts);
|
|
3049
|
+
}
|
|
3050
|
+
};
|
|
3051
|
+
|
|
2526
3052
|
// src/providers/reasoner.ts
|
|
2527
3053
|
var PROVIDERS = {
|
|
2528
3054
|
deepseek: { baseUrl: "https://api.deepseek.com/v1", keyName: "deepseek" },
|
|
@@ -2566,41 +3092,36 @@ function reasonerKey(info, keys) {
|
|
|
2566
3092
|
if (info.keyName === "gemini") return keys.gemini || keys.google;
|
|
2567
3093
|
return keys[info.keyName];
|
|
2568
3094
|
}
|
|
2569
|
-
function
|
|
3095
|
+
function clientFor(info, key, opts) {
|
|
3096
|
+
return info.provider === "gemini" ? new GeminiChatClient(
|
|
3097
|
+
new GeminiClient(key, { zeroStorage: opts.zeroStorage }),
|
|
3098
|
+
info.model
|
|
3099
|
+
) : new OpenAICompatClient(info.baseUrl, key, info.model, info.provider);
|
|
3100
|
+
}
|
|
3101
|
+
function resolveReasoner(spec, keys, opts = {}) {
|
|
2570
3102
|
const candidates = [spec, "deepseek-chat", "gemini-flash-latest"].filter(
|
|
2571
3103
|
(s) => !!s
|
|
2572
3104
|
);
|
|
2573
3105
|
for (const c of candidates) {
|
|
2574
3106
|
const info = resolveReasonerInfo(c);
|
|
2575
3107
|
const key = reasonerKey(info, keys);
|
|
2576
|
-
if (key) {
|
|
2577
|
-
return {
|
|
2578
|
-
client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
|
|
2579
|
-
info
|
|
2580
|
-
};
|
|
2581
|
-
}
|
|
3108
|
+
if (key) return { client: clientFor(info, key, opts), info };
|
|
2582
3109
|
}
|
|
2583
3110
|
return null;
|
|
2584
3111
|
}
|
|
2585
|
-
function resolveSecondReasoner(first, keys) {
|
|
3112
|
+
function resolveSecondReasoner(first, keys, opts = {}) {
|
|
2586
3113
|
const candidates = ["gemini-flash-latest", "deepseek-chat", "glm-4.7", "gpt-4o-mini"];
|
|
2587
3114
|
for (const c of candidates) {
|
|
2588
3115
|
const info = resolveReasonerInfo(c);
|
|
2589
3116
|
if (info.provider === first.provider) continue;
|
|
2590
3117
|
const key = reasonerKey(info, keys);
|
|
2591
|
-
if (key) {
|
|
2592
|
-
return {
|
|
2593
|
-
client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
|
|
2594
|
-
info
|
|
2595
|
-
};
|
|
2596
|
-
}
|
|
3118
|
+
if (key) return { client: clientFor(info, key, opts), info };
|
|
2597
3119
|
}
|
|
2598
3120
|
return null;
|
|
2599
3121
|
}
|
|
2600
3122
|
|
|
2601
3123
|
// src/finalize/finalize.ts
|
|
2602
3124
|
var MIN_DUR = 0.5;
|
|
2603
|
-
var MAX_DUR = 7;
|
|
2604
3125
|
var OVERLAP_GAP = 0.05;
|
|
2605
3126
|
function textSimilarity(a, b) {
|
|
2606
3127
|
const ta = new Set(tokenize(a).map((t) => t.norm));
|
|
@@ -2744,16 +3265,14 @@ function fixOverlaps(segments) {
|
|
|
2744
3265
|
}
|
|
2745
3266
|
function clampAndFix(segments) {
|
|
2746
3267
|
for (const s of segments) {
|
|
2747
|
-
|
|
2748
|
-
if (dur < MIN_DUR) s.end = s.start + MIN_DUR;
|
|
2749
|
-
else if (dur > MAX_DUR) s.end = s.start + MAX_DUR;
|
|
3268
|
+
if (s.end - s.start < MIN_DUR) s.end = s.start + MIN_DUR;
|
|
2750
3269
|
}
|
|
2751
3270
|
return fixOverlaps(segments);
|
|
2752
3271
|
}
|
|
2753
|
-
function finalizeSegments(segments
|
|
2754
|
-
const
|
|
2755
|
-
|
|
2756
|
-
|
|
3272
|
+
function finalizeSegments(segments) {
|
|
3273
|
+
const deduped = dedupSegments(trimSeamOverlaps(segments)).filter(
|
|
3274
|
+
(s) => s.text.trim().length > 0
|
|
3275
|
+
);
|
|
2757
3276
|
const out = deduped.map((s, i) => ({
|
|
2758
3277
|
id: i + 1,
|
|
2759
3278
|
start: s.start,
|
|
@@ -3081,17 +3600,18 @@ async function summarizeTranscript(client, model, result, instructions) {
|
|
|
3081
3600
|
|
|
3082
3601
|
// src/core/pipeline.ts
|
|
3083
3602
|
var import_node_path6 = require("path");
|
|
3603
|
+
var import_node_crypto3 = require("crypto");
|
|
3084
3604
|
var JSON_OPTS = { encoding: "utf-8" };
|
|
3085
3605
|
function readJson(p) {
|
|
3086
|
-
if (!(0,
|
|
3606
|
+
if (!(0, import_node_fs6.existsSync)(p)) return null;
|
|
3087
3607
|
try {
|
|
3088
|
-
return JSON.parse((0,
|
|
3608
|
+
return JSON.parse((0, import_node_fs6.readFileSync)(p, JSON_OPTS));
|
|
3089
3609
|
} catch {
|
|
3090
3610
|
return null;
|
|
3091
3611
|
}
|
|
3092
3612
|
}
|
|
3093
3613
|
function writeJson(p, data) {
|
|
3094
|
-
(0,
|
|
3614
|
+
(0, import_node_fs6.writeFileSync)(p, JSON.stringify(data, null, 2), JSON_OPTS);
|
|
3095
3615
|
}
|
|
3096
3616
|
async function mapPool(items, limit, fn) {
|
|
3097
3617
|
const results = new Array(items.length);
|
|
@@ -3109,6 +3629,12 @@ async function mapPool(items, limit, fn) {
|
|
|
3109
3629
|
function has(passes, p) {
|
|
3110
3630
|
return passes.includes(p);
|
|
3111
3631
|
}
|
|
3632
|
+
var ASR_NAMES = {
|
|
3633
|
+
assemblyai: "AssemblyAI",
|
|
3634
|
+
elevenlabs: "ElevenLabs Scribe",
|
|
3635
|
+
"whisper-groq": "Groq Whisper",
|
|
3636
|
+
none: "none"
|
|
3637
|
+
};
|
|
3112
3638
|
function stageTag(name) {
|
|
3113
3639
|
return (err) => {
|
|
3114
3640
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -3127,11 +3653,11 @@ async function transcribe(opts) {
|
|
|
3127
3653
|
const options = resolveOptions(opts);
|
|
3128
3654
|
const keys = resolveKeys(options.apiKeys);
|
|
3129
3655
|
logger.setLevel(options.logLevel);
|
|
3130
|
-
if (!(0,
|
|
3656
|
+
if (!(0, import_node_fs6.existsSync)(options.input)) {
|
|
3131
3657
|
throw new Error(`Input file not found: ${options.input}`);
|
|
3132
3658
|
}
|
|
3133
|
-
(0,
|
|
3134
|
-
(0,
|
|
3659
|
+
(0, import_node_fs6.mkdirSync)(options.intermediatesDir, { recursive: true });
|
|
3660
|
+
(0, import_node_fs6.mkdirSync)(options.outputDir, { recursive: true });
|
|
3135
3661
|
logger.info(
|
|
3136
3662
|
`intermediates: ${(0, import_node_path6.resolve)(options.intermediatesDir)} (file://${(0, import_node_path6.resolve)(options.intermediatesDir)})`
|
|
3137
3663
|
);
|
|
@@ -3170,6 +3696,8 @@ async function transcribe(opts) {
|
|
|
3170
3696
|
const checkAbort = () => {
|
|
3171
3697
|
options.signal?.throwIfAborted();
|
|
3172
3698
|
};
|
|
3699
|
+
const emit = (event) => emitTo(options.onProgress, event);
|
|
3700
|
+
const geminiOpts = { zeroStorage: options.zeroStorage };
|
|
3173
3701
|
if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
|
|
3174
3702
|
if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
|
|
3175
3703
|
const tsProvider = options.timestampedProvider ?? "assemblyai";
|
|
@@ -3194,12 +3722,13 @@ async function transcribe(opts) {
|
|
|
3194
3722
|
if (has(passes, "preprocess")) {
|
|
3195
3723
|
checkAbort();
|
|
3196
3724
|
logger.info("=== preprocess ===");
|
|
3725
|
+
emit({ type: "stage", stage: "preprocess", state: "start" });
|
|
3197
3726
|
probeInfo = forceAll ? null : readJson(probePath);
|
|
3198
3727
|
if (!probeInfo) {
|
|
3199
3728
|
probeInfo = await probe(options.input).catch(stageTag("preprocess"));
|
|
3200
3729
|
writeJson(probePath, probeInfo);
|
|
3201
3730
|
}
|
|
3202
|
-
if (!(0,
|
|
3731
|
+
if (!(0, import_node_fs6.existsSync)(audioPath) || forceAll) {
|
|
3203
3732
|
logger.info("extracting audio (mono 16kHz mp3)...");
|
|
3204
3733
|
await extractAudio(options.input, audioPath, AUDIO_OPTS).catch(
|
|
3205
3734
|
stageTag("preprocess")
|
|
@@ -3207,7 +3736,7 @@ async function transcribe(opts) {
|
|
|
3207
3736
|
}
|
|
3208
3737
|
if (probeInfo.hasVideo) {
|
|
3209
3738
|
const kfDir = `${options.intermediatesDir}/keyframes`;
|
|
3210
|
-
if (!(0,
|
|
3739
|
+
if (!(0, import_node_fs6.existsSync)(kfDir) || forceAll) {
|
|
3211
3740
|
logger.info("extracting keyframes...");
|
|
3212
3741
|
await extractKeyframes(options.input, kfDir, options.screenshotCount).catch(
|
|
3213
3742
|
(err) => {
|
|
@@ -3235,14 +3764,120 @@ async function transcribe(opts) {
|
|
|
3235
3764
|
logger.info(
|
|
3236
3765
|
`estimated cost ~$${estimate.totalUsd.toFixed(2)}${estimate.incomplete ? " (+unpriced parts)" : ""} [${estimate.lines.join(" \xB7 ")}]`
|
|
3237
3766
|
);
|
|
3767
|
+
const naming = options.diarizationLevel >= 3 && has(passes, "identify");
|
|
3768
|
+
const reasonerA = naming || options.summary ? resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys, geminiOpts) : null;
|
|
3769
|
+
const reasonerB = naming && reasonerA && options.identifyMode === "dual" ? resolveSecondReasoner(reasonerA.info, keys, geminiOpts) : null;
|
|
3770
|
+
const asksAssemblyAI = willTimestamp && tsProvider === "assemblyai";
|
|
3771
|
+
const notAsked = options.zeroStorage ? [
|
|
3772
|
+
...willTimestamp && (tsProvider === "elevenlabs" || tsProvider === "whisper-groq") ? [{ name: ASR_NAMES[tsProvider], role: "timing" }] : [],
|
|
3773
|
+
...[reasonerA, reasonerB].flatMap(
|
|
3774
|
+
(r) => r && r.info.provider !== "gemini" ? [{ name: r.info.model, role: "text" }] : []
|
|
3775
|
+
)
|
|
3776
|
+
] : [];
|
|
3777
|
+
if (options.zeroStorage) {
|
|
3778
|
+
logger.info(
|
|
3779
|
+
`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` : ""}`
|
|
3780
|
+
);
|
|
3781
|
+
}
|
|
3782
|
+
emit({
|
|
3783
|
+
type: "plan",
|
|
3784
|
+
durationSec: duration,
|
|
3785
|
+
model: models.transcribe,
|
|
3786
|
+
asr: ASR_NAMES[tsProvider],
|
|
3787
|
+
estimateUsd: estimate.totalUsd,
|
|
3788
|
+
zeroStorage: options.zeroStorage,
|
|
3789
|
+
notAsked
|
|
3790
|
+
});
|
|
3791
|
+
const runTimestamped = async () => {
|
|
3792
|
+
if (!has(passes, "timestamped") && !has(passes, "align")) {
|
|
3793
|
+
const cached = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
|
|
3794
|
+
return { result: cached, billed: false };
|
|
3795
|
+
}
|
|
3796
|
+
checkAbort();
|
|
3797
|
+
if (tsProvider === "none") {
|
|
3798
|
+
logger.info("=== timestamped: none (the LLM's own timestamps are used) ===");
|
|
3799
|
+
return { result: null, billed: false };
|
|
3800
|
+
}
|
|
3801
|
+
if (tsProvider === "whisper-groq") {
|
|
3802
|
+
logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
|
|
3803
|
+
if (!(0, import_node_fs6.existsSync)(audioPath))
|
|
3804
|
+
await extractAudio(options.input, audioPath, AUDIO_OPTS);
|
|
3805
|
+
const groq = new WhisperGroqClient(keys.groq);
|
|
3806
|
+
const result3 = await groq.transcribe(await (0, import_promises3.readFile)(audioPath), { language: options.language }).catch(stageTag("asr"));
|
|
3807
|
+
writeJson(`${options.intermediatesDir}/timestamped.json`, result3);
|
|
3808
|
+
return { result: result3, billed: true };
|
|
3809
|
+
}
|
|
3810
|
+
if (tsProvider === "elevenlabs") {
|
|
3811
|
+
logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
|
|
3812
|
+
const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs${options.language ? `-${options.language}` : ""}.json`;
|
|
3813
|
+
let result3 = forceAll ? null : readJson(cachePath);
|
|
3814
|
+
let billed = false;
|
|
3815
|
+
if (!result3) {
|
|
3816
|
+
const el = new ElevenLabsClient(keys.elevenlabs);
|
|
3817
|
+
result3 = await el.transcribe(await (0, import_promises3.readFile)(audioPath), { languageCode: options.language }).catch(stageTag("asr"));
|
|
3818
|
+
billed = true;
|
|
3819
|
+
writeJson(cachePath, result3);
|
|
3820
|
+
} else {
|
|
3821
|
+
logger.info("[elevenlabs] cache hit");
|
|
3822
|
+
}
|
|
3823
|
+
writeJson(`${options.intermediatesDir}/timestamped.json`, result3);
|
|
3824
|
+
logger.info(
|
|
3825
|
+
`[elevenlabs] ${result3.utterances.length} utterances, ${result3.words.length} words`
|
|
3826
|
+
);
|
|
3827
|
+
return { result: result3, billed };
|
|
3828
|
+
}
|
|
3829
|
+
logger.info("=== timestamped (AssemblyAI) ===");
|
|
3830
|
+
const aai = new AssemblyAIProvider({
|
|
3831
|
+
apiKey: keys.assemblyai,
|
|
3832
|
+
cacheDir: `${options.intermediatesDir}/assemblyai`,
|
|
3833
|
+
language: options.language,
|
|
3834
|
+
zeroStorage: options.zeroStorage
|
|
3835
|
+
});
|
|
3836
|
+
const result2 = await aai.transcribe(audioPath).catch(stageTag("asr"));
|
|
3837
|
+
writeJson(`${options.intermediatesDir}/timestamped.json`, result2);
|
|
3838
|
+
return { result: result2, billed: !aai.lastFromCache };
|
|
3839
|
+
};
|
|
3840
|
+
const asrName = ASR_NAMES[tsProvider];
|
|
3841
|
+
if (willTimestamp && tsProvider !== "none") {
|
|
3842
|
+
emit({ type: "asr", provider: asrName, state: "start" });
|
|
3843
|
+
}
|
|
3844
|
+
const asrRun = runTimestamped().then(
|
|
3845
|
+
(r) => {
|
|
3846
|
+
if (willTimestamp && r.result) {
|
|
3847
|
+
const speakers2 = new Set(r.result.utterances.map((u) => u.speaker)).size;
|
|
3848
|
+
emit({
|
|
3849
|
+
type: "asr",
|
|
3850
|
+
provider: asrName,
|
|
3851
|
+
state: r.billed ? "done" : "cached",
|
|
3852
|
+
words: r.result.words.length,
|
|
3853
|
+
speakers: speakers2 || void 0,
|
|
3854
|
+
language: r.result.languageCode
|
|
3855
|
+
});
|
|
3856
|
+
}
|
|
3857
|
+
return r;
|
|
3858
|
+
},
|
|
3859
|
+
(err) => {
|
|
3860
|
+
emit({
|
|
3861
|
+
type: "asr",
|
|
3862
|
+
provider: asrName,
|
|
3863
|
+
state: "failed",
|
|
3864
|
+
error: err instanceof Error ? err.message : String(err)
|
|
3865
|
+
});
|
|
3866
|
+
throw err;
|
|
3867
|
+
}
|
|
3868
|
+
);
|
|
3869
|
+
asrRun.catch(() => void 0);
|
|
3238
3870
|
let description = null;
|
|
3239
3871
|
if (has(passes, "describe")) {
|
|
3240
3872
|
const descPath = `${options.intermediatesDir}/description.json`;
|
|
3241
3873
|
description = forceAll ? null : readJson(descPath);
|
|
3242
|
-
if (
|
|
3874
|
+
if (description) {
|
|
3875
|
+
emit({ type: "stage", stage: "describe", state: "cached" });
|
|
3876
|
+
} else {
|
|
3243
3877
|
checkAbort();
|
|
3244
3878
|
logger.info("=== describe ===");
|
|
3245
|
-
|
|
3879
|
+
emit({ type: "stage", stage: "describe", state: "start" });
|
|
3880
|
+
const client = new GeminiClient(keys.gemini, geminiOpts);
|
|
3246
3881
|
const sampleSpans = duration <= 360 ? [[0, duration]] : [
|
|
3247
3882
|
[0, 150],
|
|
3248
3883
|
[Math.max(0, duration / 2 - 60), Math.min(duration, duration / 2 + 60)],
|
|
@@ -3252,17 +3887,17 @@ async function transcribe(opts) {
|
|
|
3252
3887
|
for (let i = 0; i < sampleSpans.length; i++) {
|
|
3253
3888
|
const [s, e] = sampleSpans[i];
|
|
3254
3889
|
const samplePath = `${options.intermediatesDir}/sample_${i}.mp3`;
|
|
3255
|
-
if (!(0,
|
|
3890
|
+
if (!(0, import_node_fs6.existsSync)(samplePath) || forceAll) {
|
|
3256
3891
|
await extractChunk(audioPath, samplePath, s, e, AUDIO_OPTS);
|
|
3257
3892
|
}
|
|
3258
3893
|
files.push({ path: samplePath });
|
|
3259
3894
|
}
|
|
3260
3895
|
const audioSampleCount = files.length;
|
|
3261
3896
|
const kfDir = `${options.intermediatesDir}/keyframes`;
|
|
3262
|
-
if ((0,
|
|
3897
|
+
if ((0, import_node_fs6.existsSync)(kfDir)) {
|
|
3263
3898
|
for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
|
|
3264
3899
|
const p = `${kfDir}/${f}`;
|
|
3265
|
-
if ((0,
|
|
3900
|
+
if ((0, import_node_fs6.existsSync)(p)) files.push({ path: p });
|
|
3266
3901
|
}
|
|
3267
3902
|
}
|
|
3268
3903
|
description = await describeMeeting(
|
|
@@ -3291,14 +3926,14 @@ async function transcribe(opts) {
|
|
|
3291
3926
|
}
|
|
3292
3927
|
chunks = planChunks(duration, options.chunkDurationSec, options.chunkOverlapSec);
|
|
3293
3928
|
if (silences.length > 3) {
|
|
3294
|
-
chunks = chunks.map((c) => {
|
|
3295
|
-
|
|
3929
|
+
chunks = chunks.map((c) => ({
|
|
3930
|
+
...c,
|
|
3931
|
+
start: snapToSilence(
|
|
3296
3932
|
c.start,
|
|
3297
3933
|
silences,
|
|
3298
3934
|
Math.min(10, options.chunkOverlapSec / 2)
|
|
3299
|
-
)
|
|
3300
|
-
|
|
3301
|
-
});
|
|
3935
|
+
)
|
|
3936
|
+
}));
|
|
3302
3937
|
}
|
|
3303
3938
|
}
|
|
3304
3939
|
const tagWith = (r, chunk) => ({
|
|
@@ -3306,21 +3941,26 @@ async function transcribe(opts) {
|
|
|
3306
3941
|
segments: r.segments.map((s) => ({
|
|
3307
3942
|
...s,
|
|
3308
3943
|
chunkIndex: chunk.index,
|
|
3309
|
-
trustedStart: chunk.trustedStart
|
|
3944
|
+
trustedStart: chunk.trustedStart,
|
|
3945
|
+
chunkStart: chunk.start,
|
|
3946
|
+
chunkEnd: chunk.end
|
|
3310
3947
|
}))
|
|
3311
3948
|
});
|
|
3949
|
+
const llmDir = `${options.intermediatesDir}/llm`;
|
|
3312
3950
|
let llmChunkResults = [];
|
|
3951
|
+
let llmChunkPlans = [];
|
|
3313
3952
|
if (has(passes, "llm-transcribe")) {
|
|
3314
3953
|
logger.info("=== llm-transcribe ===");
|
|
3954
|
+
emit({ type: "stage", stage: "transcribe", state: "start" });
|
|
3315
3955
|
let runChunks = chunks;
|
|
3316
3956
|
if (options.onlyChunk !== void 0)
|
|
3317
3957
|
runChunks = chunks.filter((c) => c.index === options.onlyChunk);
|
|
3318
3958
|
logger.info(
|
|
3319
3959
|
`${runChunks.length} chunks (${options.chunkDurationSec}s, ${options.chunkOverlapSec}s overlap)`
|
|
3320
3960
|
);
|
|
3321
|
-
|
|
3322
|
-
const
|
|
3323
|
-
(0,
|
|
3961
|
+
emit({ type: "chunks", total: runChunks.length, chunkSec: options.chunkDurationSec });
|
|
3962
|
+
const client = new GeminiClient(keys.gemini, geminiOpts);
|
|
3963
|
+
(0, import_node_fs6.mkdirSync)(llmDir, { recursive: true });
|
|
3324
3964
|
const partialPath = `${options.outputDir}/${(0, import_node_path6.basename)(options.input, ext(options.input))}.partial.md`;
|
|
3325
3965
|
const completed = [];
|
|
3326
3966
|
const writePartial = () => {
|
|
@@ -3332,7 +3972,7 @@ async function transcribe(opts) {
|
|
|
3332
3972
|
const ss = Math.floor(s.startSec % 60).toString().padStart(2, "0");
|
|
3333
3973
|
return `[${mm}:${ss}] **${s.speaker}**: ${s.text}`;
|
|
3334
3974
|
});
|
|
3335
|
-
(0,
|
|
3975
|
+
(0, import_node_fs6.writeFileSync)(
|
|
3336
3976
|
partialPath,
|
|
3337
3977
|
`> Partial transcript (run in progress \u2014 coarse LLM timings, speakers not yet unified)
|
|
3338
3978
|
|
|
@@ -3348,25 +3988,23 @@ ${lines.join("\n\n")}
|
|
|
3348
3988
|
const cached = forceAll ? null : readJson(parsedPath);
|
|
3349
3989
|
if (cached && cached.segments.length > 0) {
|
|
3350
3990
|
logger.info(`chunk ${chunk.index}: cached (${cached.segments.length} segments)`);
|
|
3991
|
+
emit({
|
|
3992
|
+
type: "chunk",
|
|
3993
|
+
index: chunk.index,
|
|
3994
|
+
state: "cached",
|
|
3995
|
+
segments: cached.segments.length
|
|
3996
|
+
});
|
|
3351
3997
|
completed.push(cached);
|
|
3352
3998
|
return tagWith(cached, chunk);
|
|
3353
3999
|
}
|
|
3354
4000
|
const chunkPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}.mp3`;
|
|
3355
|
-
if (!(0,
|
|
4001
|
+
if (!(0, import_node_fs6.existsSync)(chunkPath) || forceAll) {
|
|
3356
4002
|
await extractChunk(audioPath, chunkPath, chunk.start, chunk.end, AUDIO_OPTS);
|
|
3357
4003
|
}
|
|
3358
|
-
let previousTail;
|
|
3359
|
-
if (chunk.index > 0) {
|
|
3360
|
-
const prev = readJson(
|
|
3361
|
-
`${llmDir}/chunk_${String(chunk.index - 1).padStart(2, "0")}_parsed.json`
|
|
3362
|
-
);
|
|
3363
|
-
if (prev && prev.segments.length) {
|
|
3364
|
-
previousTail = prev.segments.slice(-6).map((s) => `${s.speaker}: ${s.text}`).join("\n");
|
|
3365
|
-
}
|
|
3366
|
-
}
|
|
3367
4004
|
logger.info(
|
|
3368
4005
|
`chunk ${chunk.index}: transcribing [${chunk.start.toFixed(0)}-${chunk.end.toFixed(0)}]s...`
|
|
3369
4006
|
);
|
|
4007
|
+
emit({ type: "chunk", index: chunk.index, state: "running" });
|
|
3370
4008
|
const result2 = await transcribeChunk(
|
|
3371
4009
|
client,
|
|
3372
4010
|
models.transcribe,
|
|
@@ -3377,13 +4015,20 @@ ${lines.join("\n\n")}
|
|
|
3377
4015
|
total: runChunks.length,
|
|
3378
4016
|
description: description?.description,
|
|
3379
4017
|
roster: description?.roster,
|
|
3380
|
-
previousTail,
|
|
3381
4018
|
instructions: options.instructions
|
|
3382
4019
|
},
|
|
3383
4020
|
{ chunkDurationSec: chunk.end - chunk.start, validationRetries: 1 }
|
|
3384
4021
|
);
|
|
3385
4022
|
writeJson(parsedPath, result2);
|
|
3386
|
-
(
|
|
4023
|
+
emit(
|
|
4024
|
+
result2.error && result2.segments.length === 0 ? { type: "chunk", index: chunk.index, state: "failed", error: result2.error } : {
|
|
4025
|
+
type: "chunk",
|
|
4026
|
+
index: chunk.index,
|
|
4027
|
+
state: "done",
|
|
4028
|
+
segments: result2.segments.length
|
|
4029
|
+
}
|
|
4030
|
+
);
|
|
4031
|
+
(0, import_node_fs6.writeFileSync)(
|
|
3387
4032
|
`${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`,
|
|
3388
4033
|
result2.raw
|
|
3389
4034
|
);
|
|
@@ -3391,6 +4036,7 @@ ${lines.join("\n\n")}
|
|
|
3391
4036
|
writePartial();
|
|
3392
4037
|
return tagWith(result2, chunk);
|
|
3393
4038
|
});
|
|
4039
|
+
llmChunkPlans = runChunks;
|
|
3394
4040
|
const errored = llmChunkResults.filter((r) => r.error);
|
|
3395
4041
|
const producedSegments = llmChunkResults.reduce((n, r) => n + r.segments.length, 0);
|
|
3396
4042
|
if (llmChunkResults.length > 0 && producedSegments === 0 && errored.length === llmChunkResults.length) {
|
|
@@ -3399,16 +4045,118 @@ ${lines.join("\n\n")}
|
|
|
3399
4045
|
);
|
|
3400
4046
|
}
|
|
3401
4047
|
} else {
|
|
3402
|
-
|
|
3403
|
-
|
|
3404
|
-
|
|
3405
|
-
|
|
3406
|
-
const r = readJson(`${llmDir}/${f}`);
|
|
3407
|
-
|
|
3408
|
-
|
|
4048
|
+
if (!forceAll && (0, import_node_fs6.existsSync)(llmDir)) {
|
|
4049
|
+
for (const f of (0, import_node_fs6.readdirSync)(llmDir).sort()) {
|
|
4050
|
+
const m = /^chunk_(\d+)_parsed\.json$/.exec(f);
|
|
4051
|
+
const plan = m ? chunks.find((c) => c.index === Number(m[1])) : void 0;
|
|
4052
|
+
const r = plan ? readJson(`${llmDir}/${f}`) : null;
|
|
4053
|
+
if (r && plan) {
|
|
4054
|
+
llmChunkResults.push(tagWith(r, plan));
|
|
4055
|
+
llmChunkPlans.push(plan);
|
|
4056
|
+
}
|
|
4057
|
+
}
|
|
4058
|
+
}
|
|
4059
|
+
}
|
|
4060
|
+
const { result: asrResult, billed: asrBilled } = await asrRun;
|
|
4061
|
+
const quality = [];
|
|
4062
|
+
if (asrResult?.words.length) {
|
|
4063
|
+
let client;
|
|
4064
|
+
for (let i = 0; i < llmChunkResults.length; i++) {
|
|
4065
|
+
const plan = llmChunkPlans[i];
|
|
4066
|
+
const where = `chunk ${plan.index} [${plan.start.toFixed(0)}-${plan.end.toFixed(0)}]s`;
|
|
4067
|
+
let cov = chunkCoverage(
|
|
4068
|
+
llmChunkResults[i].segments,
|
|
4069
|
+
asrResult.words,
|
|
4070
|
+
plan.start,
|
|
4071
|
+
plan.end
|
|
4072
|
+
);
|
|
4073
|
+
let status = cov.low ? "low-coverage" : "ok";
|
|
4074
|
+
if (cov.low) {
|
|
4075
|
+
const retryPath = `${llmDir}/chunk_${String(plan.index).padStart(2, "0")}_retry_parsed.json`;
|
|
4076
|
+
let retry = forceAll ? null : readJson(retryPath);
|
|
4077
|
+
const span = { index: plan.index, startSec: plan.start, endSec: plan.end };
|
|
4078
|
+
if (!retry && has(passes, "llm-transcribe")) {
|
|
4079
|
+
checkAbort();
|
|
4080
|
+
logger.warn(
|
|
4081
|
+
`${where}: ${cov.llmWords} words transcribed where the ASR heard ${cov.asrWords} \u2014 transcribing it again in two halves`
|
|
4082
|
+
);
|
|
4083
|
+
emit({
|
|
4084
|
+
type: "guard",
|
|
4085
|
+
...span,
|
|
4086
|
+
state: "retrying",
|
|
4087
|
+
llmWords: cov.llmWords,
|
|
4088
|
+
asrWords: cov.asrWords
|
|
4089
|
+
});
|
|
4090
|
+
client ??= new GeminiClient(keys.gemini, geminiOpts);
|
|
4091
|
+
retry = await transcribeInHalves({
|
|
4092
|
+
client,
|
|
4093
|
+
model: models.transcribe,
|
|
4094
|
+
audioPath,
|
|
4095
|
+
chunk: plan,
|
|
4096
|
+
pathPrefix: `${llmDir}/chunk_${String(plan.index).padStart(2, "0")}`,
|
|
4097
|
+
ctx: {
|
|
4098
|
+
index: plan.index + 1,
|
|
4099
|
+
total: chunks.length,
|
|
4100
|
+
description: description?.description,
|
|
4101
|
+
roster: description?.roster,
|
|
4102
|
+
instructions: options.instructions
|
|
4103
|
+
},
|
|
4104
|
+
audioOpts: AUDIO_OPTS
|
|
4105
|
+
}).catch(stageTag("llm-transcribe"));
|
|
4106
|
+
writeJson(retryPath, retry);
|
|
4107
|
+
}
|
|
4108
|
+
if (retry) {
|
|
4109
|
+
const again = chunkCoverage(
|
|
4110
|
+
retry.segments,
|
|
4111
|
+
asrResult.words,
|
|
4112
|
+
plan.start,
|
|
4113
|
+
plan.end
|
|
4114
|
+
);
|
|
4115
|
+
logger.info(
|
|
4116
|
+
`${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"}`
|
|
4117
|
+
);
|
|
4118
|
+
const kept = again.ratio > cov.ratio;
|
|
4119
|
+
emit({
|
|
4120
|
+
type: "guard",
|
|
4121
|
+
...span,
|
|
4122
|
+
state: kept ? "recovered" : "unchanged",
|
|
4123
|
+
llmWords: cov.llmWords,
|
|
4124
|
+
asrWords: cov.asrWords,
|
|
4125
|
+
retryWords: again.llmWords
|
|
4126
|
+
});
|
|
4127
|
+
if (kept) {
|
|
4128
|
+
llmChunkResults[i] = tagWith(retry, plan);
|
|
4129
|
+
cov = again;
|
|
4130
|
+
status = again.low ? "low-coverage" : "retried";
|
|
4131
|
+
}
|
|
4132
|
+
}
|
|
4133
|
+
}
|
|
4134
|
+
quality.push({
|
|
4135
|
+
chunk: plan.index,
|
|
4136
|
+
start: plan.start,
|
|
4137
|
+
end: plan.end,
|
|
4138
|
+
status,
|
|
4139
|
+
llmWords: cov.llmWords,
|
|
4140
|
+
asrWords: cov.asrWords,
|
|
4141
|
+
coverage: Number.isFinite(cov.ratio) ? Number(cov.ratio.toFixed(2)) : null
|
|
4142
|
+
});
|
|
3409
4143
|
}
|
|
3410
4144
|
}
|
|
4145
|
+
const whole = asrResult?.words.length ? chunkCoverage(
|
|
4146
|
+
llmChunkResults.flatMap((r) => r.segments),
|
|
4147
|
+
asrResult.words,
|
|
4148
|
+
0,
|
|
4149
|
+
Infinity
|
|
4150
|
+
) : null;
|
|
4151
|
+
const asrMissedSpeech = !!whole && whole.llmWords >= 200 && whole.ratio > 3;
|
|
4152
|
+
if (asrMissedSpeech) {
|
|
4153
|
+
logger.warn(
|
|
4154
|
+
`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)`
|
|
4155
|
+
);
|
|
4156
|
+
}
|
|
3411
4157
|
let allLlmSegments = llmChunkResults.flatMap((r) => r.segments);
|
|
4158
|
+
const timingWords = asrMissedSpeech ? [] : asrResult?.words ?? [];
|
|
4159
|
+
allLlmSegments = toAsrClock(allLlmSegments, timingWords);
|
|
3412
4160
|
const beforePart = allLlmSegments.length;
|
|
3413
4161
|
allLlmSegments = partitionByOwnership(allLlmSegments);
|
|
3414
4162
|
if (beforePart !== allLlmSegments.length) {
|
|
@@ -3417,81 +4165,68 @@ ${lines.join("\n\n")}
|
|
|
3417
4165
|
);
|
|
3418
4166
|
}
|
|
3419
4167
|
logger.info(`total LLM segments: ${allLlmSegments.length}`);
|
|
3420
|
-
|
|
3421
|
-
|
|
3422
|
-
|
|
3423
|
-
|
|
3424
|
-
|
|
3425
|
-
|
|
3426
|
-
|
|
3427
|
-
|
|
3428
|
-
|
|
4168
|
+
if (asrResult?.words.length && (has(passes, "align") || has(passes, "consistency"))) {
|
|
4169
|
+
const dropped = /* @__PURE__ */ new Set();
|
|
4170
|
+
for (let i = 0; i < llmChunkResults.length; i++) {
|
|
4171
|
+
const r = llmChunkResults[i];
|
|
4172
|
+
const plan = llmChunkPlans[i];
|
|
4173
|
+
const q = quality.find((x) => x.chunk === plan.index);
|
|
4174
|
+
const where = `chunk ${plan.index} [${plan.start.toFixed(0)}-${plan.end.toFixed(0)}]s`;
|
|
4175
|
+
const compression = maxCompressionRatio(r.segments.map((s) => s.text).join(" "));
|
|
4176
|
+
if (compression > DEGENERATE_COMPRESSION_RATIO) {
|
|
4177
|
+
dropped.add(plan.index);
|
|
4178
|
+
if (q) q.status = "dropped-loop";
|
|
4179
|
+
logger.warn(
|
|
4180
|
+
`${where}: dropping repetition-loop text (compression ratio ${compression.toFixed(1)}) \u2014 ASR will fill this range`
|
|
4181
|
+
);
|
|
4182
|
+
continue;
|
|
3429
4183
|
}
|
|
3430
|
-
const
|
|
3431
|
-
|
|
3432
|
-
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
|
|
3436
|
-
logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
|
|
3437
|
-
if (!keys.elevenlabs)
|
|
3438
|
-
throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
|
|
3439
|
-
const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs.json`;
|
|
3440
|
-
asrResult = forceAll ? null : readJson(cachePath);
|
|
3441
|
-
if (!asrResult) {
|
|
3442
|
-
const { readFile: readFile2 } = await import("fs/promises");
|
|
3443
|
-
const buf = await readFile2(audioPath);
|
|
3444
|
-
const el = new ElevenLabsClient(keys.elevenlabs);
|
|
3445
|
-
asrResult = await el.transcribe(buf).catch(stageTag("asr"));
|
|
3446
|
-
writeJson(cachePath, asrResult);
|
|
3447
|
-
} else {
|
|
3448
|
-
logger.info("[elevenlabs] cache hit");
|
|
4184
|
+
const g = chunkGrounding(r.segments, asrResult.words, plan.start, plan.end);
|
|
4185
|
+
if (!g.grounded) {
|
|
4186
|
+
if (q) q.ungrounded = true;
|
|
4187
|
+
logger.warn(
|
|
4188
|
+
`${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)`
|
|
4189
|
+
);
|
|
3449
4190
|
}
|
|
3450
|
-
|
|
3451
|
-
|
|
3452
|
-
|
|
4191
|
+
}
|
|
4192
|
+
if (dropped.size) {
|
|
4193
|
+
allLlmSegments = allLlmSegments.filter(
|
|
4194
|
+
(s) => s.chunkIndex === void 0 || !dropped.has(s.chunkIndex)
|
|
3453
4195
|
);
|
|
3454
|
-
} else {
|
|
3455
|
-
logger.info("=== timestamped (AssemblyAI) ===");
|
|
3456
|
-
if (!keys.assemblyai)
|
|
3457
|
-
throw new Error(
|
|
3458
|
-
"ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
|
|
3459
|
-
);
|
|
3460
|
-
const aai = new AssemblyAIProvider({
|
|
3461
|
-
apiKey: keys.assemblyai,
|
|
3462
|
-
cacheDir: `${options.intermediatesDir}/assemblyai`
|
|
3463
|
-
});
|
|
3464
|
-
asrResult = await aai.transcribe(audioPath).catch(stageTag("asr"));
|
|
3465
|
-
writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
|
|
3466
4196
|
}
|
|
3467
|
-
} else {
|
|
3468
|
-
asrResult = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
|
|
3469
4197
|
}
|
|
3470
4198
|
let aligned = [];
|
|
3471
|
-
if (has(passes, "align") && asrResult) {
|
|
4199
|
+
if (has(passes, "align") && (asrResult || tsProvider === "none")) {
|
|
3472
4200
|
logger.info("=== align ===");
|
|
3473
|
-
|
|
4201
|
+
emit({ type: "stage", stage: "align", state: "start" });
|
|
4202
|
+
aligned = alignSegments(allLlmSegments, timingWords, { timeMarginSec: 30 });
|
|
3474
4203
|
writeJson(`${options.intermediatesDir}/aligned.json`, aligned);
|
|
3475
4204
|
} else {
|
|
3476
4205
|
aligned = (forceAll ? null : readJson(`${options.intermediatesDir}/aligned.json`)) ?? [];
|
|
3477
4206
|
}
|
|
3478
4207
|
const alignedOk = aligned.filter((a) => a.timingSource !== "coarse").length;
|
|
3479
4208
|
logger.info(`aligned: ${alignedOk}/${aligned.length} with ASR timing`);
|
|
3480
|
-
|
|
3481
|
-
|
|
4209
|
+
let gapFilledWords = 0;
|
|
4210
|
+
if (asrResult && !asrMissedSpeech && (has(passes, "align") || has(passes, "consistency"))) {
|
|
3482
4211
|
aligned = fillAsrGaps(aligned, asrResult.words, asrResult.utterances);
|
|
3483
|
-
const added = aligned.
|
|
3484
|
-
|
|
4212
|
+
const added = aligned.filter((a) => a.timingSource === "timestamped");
|
|
4213
|
+
gapFilledWords = added.reduce((n, a) => n + a.words.length, 0);
|
|
4214
|
+
if (added.length) {
|
|
4215
|
+
logger.info(
|
|
4216
|
+
`gap-filled ${added.length} ASR fallback segment(s) (${gapFilledWords} words)`
|
|
4217
|
+
);
|
|
4218
|
+
}
|
|
3485
4219
|
}
|
|
3486
4220
|
if (asrResult && (asrResult.hasDiarization ?? true) && (has(passes, "align") || has(passes, "consistency"))) {
|
|
3487
4221
|
aligned = splitMixedVoiceSegments(aligned, asrResult.utterances);
|
|
3488
4222
|
}
|
|
3489
4223
|
let segments = aligned;
|
|
3490
4224
|
let speakers = [];
|
|
3491
|
-
if (has(passes, "consistency") && asrResult) {
|
|
4225
|
+
if (has(passes, "consistency") && (asrResult || tsProvider === "none")) {
|
|
3492
4226
|
logger.info("=== consistency ===");
|
|
3493
|
-
|
|
3494
|
-
|
|
4227
|
+
emit({ type: "stage", stage: "speakers", state: "start" });
|
|
4228
|
+
const cons = assignGlobalSpeakers(aligned, asrResult?.utterances ?? [], {
|
|
4229
|
+
hasDiarization: asrResult ? asrResult.hasDiarization ?? true : false
|
|
3495
4230
|
});
|
|
3496
4231
|
segments = cons.segments;
|
|
3497
4232
|
speakers = cons.speakers;
|
|
@@ -3513,19 +4248,22 @@ ${lines.join("\n\n")}
|
|
|
3513
4248
|
(s) => s.speakerName !== s.speaker ? { ...s, speakerName: s.speaker } : s
|
|
3514
4249
|
);
|
|
3515
4250
|
speakers = speakers.map((sp) => sp.name !== sp.id ? { ...sp, name: sp.id } : sp);
|
|
3516
|
-
if (
|
|
3517
|
-
const reasonerA = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
|
|
4251
|
+
if (naming) {
|
|
3518
4252
|
if (!reasonerA) {
|
|
3519
4253
|
logger.warn(
|
|
3520
4254
|
"identify: no reasoner-capable API key found (DEEPSEEK/GEMINI/OPENAI/\u2026) \u2014 skipping speaker naming"
|
|
3521
4255
|
);
|
|
3522
4256
|
} else {
|
|
3523
4257
|
const mode = options.identifyMode;
|
|
3524
|
-
const reasonerB = mode === "dual" ? resolveSecondReasoner(reasonerA.info, keys) : null;
|
|
3525
4258
|
const idConfig = {
|
|
3526
4259
|
mode,
|
|
3527
4260
|
reasonerA: reasonerA.info.model,
|
|
3528
|
-
reasonerB: reasonerB?.info.model ?? null
|
|
4261
|
+
reasonerB: reasonerB?.info.model ?? null,
|
|
4262
|
+
knownSpeakers: options.knownSpeakers ?? [],
|
|
4263
|
+
// What the naming step reads. If a re-run changes the transcript (a re-transcribed
|
|
4264
|
+
// chunk can reorder speakers by talk time), "Speaker A" may now be the other voice,
|
|
4265
|
+
// and the cached names must not be applied to it.
|
|
4266
|
+
inputs: (0, import_node_crypto3.createHash)("sha1").update(JSON.stringify(segments.map((s) => [s.speaker, s.text]))).update(JSON.stringify(speakers.map((sp) => sp.id))).digest("hex")
|
|
3529
4267
|
};
|
|
3530
4268
|
const idCachePath = `${options.intermediatesDir}/identified.json`;
|
|
3531
4269
|
const cachedId = forceAll ? null : readJson(
|
|
@@ -3535,11 +4273,18 @@ ${lines.join("\n\n")}
|
|
|
3535
4273
|
let nameMap = null;
|
|
3536
4274
|
if (idConfigMatches && cachedId?.nameMap && Object.keys(cachedId.nameMap).length > 0) {
|
|
3537
4275
|
logger.info("=== identify (cached) ===");
|
|
4276
|
+
emit({ type: "stage", stage: "identify", state: "cached" });
|
|
3538
4277
|
nameMap = cachedId.nameMap;
|
|
3539
4278
|
} else {
|
|
3540
4279
|
logger.info(
|
|
3541
4280
|
`=== identify (${reasonerA.info.model}${reasonerB ? ` + ${reasonerB.info.model} second opinion` : ""}) ===`
|
|
3542
4281
|
);
|
|
4282
|
+
emit({
|
|
4283
|
+
type: "stage",
|
|
4284
|
+
stage: "identify",
|
|
4285
|
+
state: "start",
|
|
4286
|
+
detail: reasonerB ? `${reasonerA.info.model} + ${reasonerB.info.model}` : reasonerA.info.model
|
|
4287
|
+
});
|
|
3543
4288
|
checkAbort();
|
|
3544
4289
|
const id = await identifySpeakersV2(
|
|
3545
4290
|
{
|
|
@@ -3564,11 +4309,14 @@ ${lines.join("\n\n")}
|
|
|
3564
4309
|
).catch(stageTag("identify"));
|
|
3565
4310
|
writeJson(idCachePath, { ...id, config: idConfig });
|
|
3566
4311
|
nameMap = id.nameMap;
|
|
4312
|
+
if (id.allPassesFailed)
|
|
4313
|
+
emit({ type: "stage", stage: "identify", state: "failed" });
|
|
3567
4314
|
}
|
|
3568
4315
|
logger.info(
|
|
3569
4316
|
`identified ${Object.keys(nameMap).length} speakers: ${JSON.stringify(nameMap)}`
|
|
3570
4317
|
);
|
|
3571
4318
|
const nm = nameMap;
|
|
4319
|
+
emit({ type: "names", names: nm });
|
|
3572
4320
|
segments = segments.map(
|
|
3573
4321
|
(s) => nm[s.speaker] ? { ...s, speakerName: nm[s.speaker] } : s
|
|
3574
4322
|
);
|
|
@@ -3578,13 +4326,14 @@ ${lines.join("\n\n")}
|
|
|
3578
4326
|
let finalSegments = [];
|
|
3579
4327
|
if (has(passes, "finalize")) {
|
|
3580
4328
|
logger.info("=== finalize ===");
|
|
4329
|
+
emit({ type: "stage", stage: "finalize", state: "start" });
|
|
3581
4330
|
finalSegments = finalizeSegments(segments);
|
|
3582
4331
|
writeJson(`${options.intermediatesDir}/final.json`, finalSegments);
|
|
3583
4332
|
} else {
|
|
3584
4333
|
finalSegments = (forceAll ? null : readJson(`${options.intermediatesDir}/final.json`)) ?? [];
|
|
3585
4334
|
}
|
|
3586
4335
|
logger.info(`final segments: ${finalSegments.length}`);
|
|
3587
|
-
const receipt = computeReceipt(getLlmUsage(), tsProvider, duration);
|
|
4336
|
+
const receipt = computeReceipt(getLlmUsage(), tsProvider, duration, asrBilled);
|
|
3588
4337
|
const wallMs = Date.now() - runStartedAt;
|
|
3589
4338
|
const metadata = {
|
|
3590
4339
|
sourceFile: options.input,
|
|
@@ -3604,86 +4353,103 @@ ${lines.join("\n\n")}
|
|
|
3604
4353
|
llmCalls: receipt.totals.calls,
|
|
3605
4354
|
inputTokens: receipt.totals.inputTokens,
|
|
3606
4355
|
outputTokens: receipt.totals.outputTokens
|
|
3607
|
-
}
|
|
4356
|
+
},
|
|
4357
|
+
...asrResult ? { quality: { chunks: quality, gapFilledWords, asrMissedSpeech } } : {},
|
|
4358
|
+
zeroStorage: options.zeroStorage
|
|
3608
4359
|
};
|
|
4360
|
+
const degraded = quality.filter((q) => q.status !== "ok");
|
|
4361
|
+
if (degraded.length || asrMissedSpeech) {
|
|
4362
|
+
logger.warn(
|
|
4363
|
+
`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`
|
|
4364
|
+
);
|
|
4365
|
+
}
|
|
3609
4366
|
const result = { segments: finalSegments, speakers, metadata };
|
|
3610
4367
|
writeJson(`${options.intermediatesDir}/result.json`, result);
|
|
4368
|
+
const base = (0, import_node_path6.basename)(options.input, ext(options.input));
|
|
4369
|
+
const written = [];
|
|
4370
|
+
const write = (name, content) => {
|
|
4371
|
+
const path = `${options.outputDir}/${name}`;
|
|
4372
|
+
(0, import_node_fs6.writeFileSync)(path, content);
|
|
4373
|
+
written.push((0, import_node_path6.resolve)(path));
|
|
4374
|
+
};
|
|
3611
4375
|
for (const fmt of options.formats) {
|
|
3612
|
-
|
|
3613
|
-
if (fmt === "srt")
|
|
3614
|
-
(0, import_node_fs5.writeFileSync)(
|
|
3615
|
-
`${options.outputDir}/${base}.srt`,
|
|
3616
|
-
formatSrt(result, { title: base })
|
|
3617
|
-
);
|
|
4376
|
+
if (fmt === "srt") write(`${base}.srt`, formatSrt(result, { title: base }));
|
|
3618
4377
|
if (fmt === "md")
|
|
3619
|
-
(
|
|
3620
|
-
`${
|
|
4378
|
+
write(
|
|
4379
|
+
`${base}.md`,
|
|
3621
4380
|
formatMarkdown(result, { title: base, mdStyle: options.mdStyle })
|
|
3622
4381
|
);
|
|
3623
|
-
if (fmt === "txt")
|
|
3624
|
-
|
|
3625
|
-
|
|
3626
|
-
formatText(result, { title: base })
|
|
3627
|
-
);
|
|
3628
|
-
if (fmt === "html")
|
|
3629
|
-
(0, import_node_fs5.writeFileSync)(
|
|
3630
|
-
`${options.outputDir}/${base}.html`,
|
|
3631
|
-
formatHtml(result, { title: base })
|
|
3632
|
-
);
|
|
3633
|
-
if (fmt === "json")
|
|
3634
|
-
(0, import_node_fs5.writeFileSync)(`${options.outputDir}/${base}.json`, formatJson(result));
|
|
4382
|
+
if (fmt === "txt") write(`${base}.txt`, formatText(result, { title: base }));
|
|
4383
|
+
if (fmt === "html") write(`${base}.html`, formatHtml(result, { title: base }));
|
|
4384
|
+
if (fmt === "json") write(`${base}.json`, formatJson(result));
|
|
3635
4385
|
}
|
|
3636
4386
|
if (options.summary && finalSegments.length > 0) {
|
|
3637
|
-
|
|
3638
|
-
if (!reasoner) {
|
|
4387
|
+
if (!reasonerA) {
|
|
3639
4388
|
logger.warn("summary: no reasoner-capable key \u2014 skipping");
|
|
3640
4389
|
} else {
|
|
3641
|
-
logger.info(`=== summary (${
|
|
4390
|
+
logger.info(`=== summary (${reasonerA.info.model}) ===`);
|
|
4391
|
+
emit({
|
|
4392
|
+
type: "stage",
|
|
4393
|
+
stage: "summary",
|
|
4394
|
+
state: "start",
|
|
4395
|
+
detail: reasonerA.info.model
|
|
4396
|
+
});
|
|
3642
4397
|
try {
|
|
3643
4398
|
const summary = await summarizeTranscript(
|
|
3644
|
-
|
|
3645
|
-
|
|
4399
|
+
reasonerA.client,
|
|
4400
|
+
reasonerA.info.model,
|
|
3646
4401
|
result,
|
|
3647
4402
|
options.instructions
|
|
3648
4403
|
);
|
|
3649
|
-
|
|
3650
|
-
(0, import_node_fs5.writeFileSync)(`${options.outputDir}/${base}.summary.md`, summary);
|
|
4404
|
+
write(`${base}.summary.md`, summary);
|
|
3651
4405
|
logger.info(`summary written to ${base}.summary.md`);
|
|
3652
4406
|
} catch (err) {
|
|
3653
4407
|
logger.warn(`summary failed: ${err instanceof Error ? err.message : err}`);
|
|
4408
|
+
emit({ type: "stage", stage: "summary", state: "failed" });
|
|
3654
4409
|
}
|
|
3655
4410
|
}
|
|
3656
4411
|
}
|
|
3657
4412
|
try {
|
|
3658
|
-
const base = (0, import_node_path6.basename)(options.input, ext(options.input));
|
|
3659
4413
|
const partial = `${options.outputDir}/${base}.partial.md`;
|
|
3660
|
-
if ((0,
|
|
4414
|
+
if ((0, import_node_fs6.existsSync)(partial)) (await import("fs/promises")).unlink(partial);
|
|
3661
4415
|
} catch {
|
|
3662
4416
|
}
|
|
3663
4417
|
logger.info(`outputs written to ${options.outputDir}`);
|
|
3664
|
-
const
|
|
3665
|
-
const
|
|
4418
|
+
const spent = computeReceipt(getLlmUsage(), tsProvider, duration, asrBilled);
|
|
4419
|
+
const runMs = Date.now() - runStartedAt;
|
|
4420
|
+
const mins = Math.floor(runMs / 6e4);
|
|
4421
|
+
const secs = Math.round(runMs % 6e4 / 1e3);
|
|
3666
4422
|
logger.info(
|
|
3667
|
-
`receipt: ${
|
|
4423
|
+
`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`
|
|
3668
4424
|
);
|
|
3669
|
-
for (const line of
|
|
4425
|
+
for (const line of spent.lines) logger.info(` ${line}`);
|
|
3670
4426
|
recordRun(
|
|
3671
4427
|
{
|
|
3672
4428
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3673
4429
|
input: (0, import_node_path6.basename)(options.input),
|
|
3674
4430
|
durationSec: duration,
|
|
3675
|
-
wallMs,
|
|
4431
|
+
wallMs: runMs,
|
|
3676
4432
|
models: metadata.models,
|
|
3677
4433
|
segments: finalSegments.length,
|
|
3678
4434
|
characters: finalSegments.reduce((n, s) => n + s.text.length, 0),
|
|
3679
4435
|
speakers: speakers.length,
|
|
3680
|
-
llmCalls:
|
|
3681
|
-
inputTokens:
|
|
3682
|
-
outputTokens:
|
|
3683
|
-
costUsd:
|
|
4436
|
+
llmCalls: spent.totals.calls,
|
|
4437
|
+
inputTokens: spent.totals.inputTokens,
|
|
4438
|
+
outputTokens: spent.totals.outputTokens,
|
|
4439
|
+
costUsd: spent.totalUsd
|
|
3684
4440
|
},
|
|
3685
|
-
|
|
4441
|
+
spent.perModel
|
|
3686
4442
|
);
|
|
4443
|
+
emit({
|
|
4444
|
+
type: "done",
|
|
4445
|
+
segments: finalSegments.length,
|
|
4446
|
+
speakers: speakers.length,
|
|
4447
|
+
durationSec: duration,
|
|
4448
|
+
costUsd: spent.totalUsd,
|
|
4449
|
+
wallMs: runMs,
|
|
4450
|
+
retriedChunks: quality.filter((q) => q.status === "retried").length,
|
|
4451
|
+
outputs: written
|
|
4452
|
+
});
|
|
3687
4453
|
return result;
|
|
3688
4454
|
}
|
|
3689
4455
|
function ext(p) {
|
|
@@ -3722,6 +4488,9 @@ function parseSrt(content) {
|
|
|
3722
4488
|
}
|
|
3723
4489
|
// Annotate the CommonJS export names for ESM import in node:
|
|
3724
4490
|
0 && (module.exports = {
|
|
4491
|
+
DEFAULT_REASONER_MODEL,
|
|
4492
|
+
DEFAULT_TRANSCRIBE_MODEL,
|
|
4493
|
+
PRO_TRANSCRIBE_MODEL,
|
|
3725
4494
|
alignSegments,
|
|
3726
4495
|
assignGlobalSpeakers,
|
|
3727
4496
|
finalizeSegments,
|
|
@@ -3731,6 +4500,7 @@ function parseSrt(content) {
|
|
|
3731
4500
|
formatSrt,
|
|
3732
4501
|
formatText,
|
|
3733
4502
|
identifySpeakers,
|
|
4503
|
+
identifySpeakersV2,
|
|
3734
4504
|
parseSrt,
|
|
3735
4505
|
planChunks,
|
|
3736
4506
|
summarizeTranscript,
|