offmute-v2 0.0.5 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +231 -214
- package/dist/browser.browser.js +471 -82
- package/dist/browser.browser.js.map +1 -1
- package/dist/browser.d.ts +31 -7
- package/dist/cli.js +2973 -350
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1740 -163
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +71 -9
- package/dist/index.d.ts +71 -9
- package/dist/index.js +1740 -159
- package/dist/index.js.map +1 -1
- package/package.json +7 -4
- package/dist/cli.cjs +0 -2152
- package/dist/cli.cjs.map +0 -1
- package/dist/cli.d.cts +0 -1
package/dist/cli.cjs
DELETED
|
@@ -1,2152 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
"use strict";
|
|
3
|
-
var __create = Object.create;
|
|
4
|
-
var __defProp = Object.defineProperty;
|
|
5
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
-
var __copyProps = (to, from, except, desc) => {
|
|
10
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
-
for (let key of __getOwnPropNames(from))
|
|
12
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
-
}
|
|
15
|
-
return to;
|
|
16
|
-
};
|
|
17
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
18
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
19
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
20
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
21
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
22
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
23
|
-
mod
|
|
24
|
-
));
|
|
25
|
-
|
|
26
|
-
// node_modules/tsup/assets/cjs_shims.js
|
|
27
|
-
var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
|
|
28
|
-
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
|
|
29
|
-
|
|
30
|
-
// src/cli.ts
|
|
31
|
-
var import_commander = require("commander");
|
|
32
|
-
var import_node_fs5 = require("fs");
|
|
33
|
-
var import_node_url = require("url");
|
|
34
|
-
var import_node_path6 = require("path");
|
|
35
|
-
|
|
36
|
-
// src/core/pipeline.ts
|
|
37
|
-
var import_node_fs4 = require("fs");
|
|
38
|
-
|
|
39
|
-
// src/core/config.ts
|
|
40
|
-
var import_node_crypto = require("crypto");
|
|
41
|
-
var import_node_path = require("path");
|
|
42
|
-
var import_node_fs = require("fs");
|
|
43
|
-
var import_node_os = require("os");
|
|
44
|
-
var DEFAULT_PASSES = [
|
|
45
|
-
"preprocess",
|
|
46
|
-
"describe",
|
|
47
|
-
"llm-transcribe",
|
|
48
|
-
"timestamped",
|
|
49
|
-
"align",
|
|
50
|
-
"consistency",
|
|
51
|
-
"finalize"
|
|
52
|
-
];
|
|
53
|
-
var MODELS = {
|
|
54
|
-
gemini25Pro: "gemini-2.5-pro",
|
|
55
|
-
gemini25Flash: "gemini-2.5-flash",
|
|
56
|
-
gemini3Pro: "gemini-3-pro-preview",
|
|
57
|
-
gemini31Pro: "gemini-3.1-pro-preview",
|
|
58
|
-
geminiFlashLatest: "gemini-flash-latest",
|
|
59
|
-
deepseek: "deepseek-chat",
|
|
60
|
-
deepseekReasoner: "deepseek-reasoner",
|
|
61
|
-
gpt4o: "gpt-4o",
|
|
62
|
-
claudeSonnet: "claude-sonnet-4-5"
|
|
63
|
-
};
|
|
64
|
-
var DEFAULT_TRANSCRIBE_MODEL = MODELS.gemini31Pro;
|
|
65
|
-
var DEFAULT_REASONER_MODEL = MODELS.deepseek;
|
|
66
|
-
function resolveKeys(injected) {
|
|
67
|
-
const env = process.env;
|
|
68
|
-
return {
|
|
69
|
-
gemini: injected?.gemini || injected?.google || env.GEMINI_API_KEY || env.GOOGLE_API_KEY,
|
|
70
|
-
google: injected?.google || injected?.gemini || env.GOOGLE_API_KEY || env.GEMINI_API_KEY,
|
|
71
|
-
openai: injected?.openai || env.OPENAI_API_KEY,
|
|
72
|
-
deepseek: injected?.deepseek || env.DEEPSEEK_API_KEY,
|
|
73
|
-
groq: injected?.groq || env.GROQ_API_KEY,
|
|
74
|
-
assemblyai: injected?.assemblyai || env.ASSEMBLYAI_API_KEY,
|
|
75
|
-
anthropic: injected?.anthropic || env.ANTHROPIC_API_KEY
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
function resolveOptions(opts2) {
|
|
79
|
-
return {
|
|
80
|
-
input: opts2.input,
|
|
81
|
-
// Default: write next to the input file (e.g. meeting.md beside meeting.mp4) — no ./output folder.
|
|
82
|
-
outputDir: opts2.outputDir ?? (0, import_node_path.dirname)((0, import_node_path.resolve)(opts2.input)),
|
|
83
|
-
intermediatesDir: opts2.intermediatesDir ?? deriveIntermediatesDir(opts2.input),
|
|
84
|
-
instructions: opts2.instructions,
|
|
85
|
-
knownSpeakers: opts2.knownSpeakers,
|
|
86
|
-
passes: (() => {
|
|
87
|
-
const p = opts2.passes ?? DEFAULT_PASSES;
|
|
88
|
-
if ((opts2.diarizationLevel ?? 2) >= 3 && !p.includes("identify")) {
|
|
89
|
-
const out = [...p];
|
|
90
|
-
const fi = out.indexOf("finalize");
|
|
91
|
-
if (fi >= 0) out.splice(fi, 0, "identify");
|
|
92
|
-
else out.push("identify");
|
|
93
|
-
return out;
|
|
94
|
-
}
|
|
95
|
-
return p;
|
|
96
|
-
})(),
|
|
97
|
-
chunkDurationSec: opts2.chunkDurationSec ?? 600,
|
|
98
|
-
chunkOverlapSec: opts2.chunkOverlapSec ?? 60,
|
|
99
|
-
screenshotCount: opts2.screenshotCount ?? 6,
|
|
100
|
-
concurrency: opts2.concurrency ?? 4,
|
|
101
|
-
saveIntermediates: opts2.saveIntermediates ?? true,
|
|
102
|
-
formats: opts2.formats ?? ["md"],
|
|
103
|
-
diarizationLevel: opts2.diarizationLevel ?? 2,
|
|
104
|
-
apiKeys: opts2.apiKeys,
|
|
105
|
-
model: opts2.model,
|
|
106
|
-
reasoner: opts2.reasoner,
|
|
107
|
-
timestampedProvider: opts2.timestampedProvider,
|
|
108
|
-
force: opts2.force ?? false,
|
|
109
|
-
onlyChunk: opts2.onlyChunk,
|
|
110
|
-
showProgress: opts2.showProgress ?? true,
|
|
111
|
-
llmLog: opts2.llmLog ?? true,
|
|
112
|
-
logLevel: opts2.logLevel ?? "info"
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
function deriveIntermediatesDir(input2) {
|
|
116
|
-
const abs = (0, import_node_path.resolve)(input2);
|
|
117
|
-
const hash = (0, import_node_crypto.createHash)("sha1").update(abs).digest("hex").slice(0, 8);
|
|
118
|
-
const base = (0, import_node_path.basename)(input2, extOf(input2)) || "input";
|
|
119
|
-
return `${(0, import_node_os.tmpdir)()}/offmute-v2-${base}-${hash}`;
|
|
120
|
-
}
|
|
121
|
-
function extOf(p) {
|
|
122
|
-
const i = p.lastIndexOf(".");
|
|
123
|
-
return i >= 0 ? p.slice(i) : "";
|
|
124
|
-
}
|
|
125
|
-
function inputSignature(input2) {
|
|
126
|
-
let size = 0;
|
|
127
|
-
let mtime = 0;
|
|
128
|
-
try {
|
|
129
|
-
const st = (0, import_node_fs.statSync)(input2);
|
|
130
|
-
size = st.size;
|
|
131
|
-
mtime = Math.floor(st.mtimeMs);
|
|
132
|
-
} catch {
|
|
133
|
-
}
|
|
134
|
-
return (0, import_node_crypto.createHash)("sha1").update(`${(0, import_node_path.resolve)(input2)}|${size}|${mtime}`).digest("hex");
|
|
135
|
-
}
|
|
136
|
-
function configSignature(o) {
|
|
137
|
-
const relevant = {
|
|
138
|
-
model: o.model ?? DEFAULT_TRANSCRIBE_MODEL,
|
|
139
|
-
reasoner: o.reasoner ?? DEFAULT_REASONER_MODEL,
|
|
140
|
-
instructions: o.instructions ?? "",
|
|
141
|
-
knownSpeakers: o.knownSpeakers ?? [],
|
|
142
|
-
chunkDurationSec: o.chunkDurationSec ?? 600,
|
|
143
|
-
chunkOverlapSec: o.chunkOverlapSec ?? 60,
|
|
144
|
-
screenshotCount: o.screenshotCount ?? 6,
|
|
145
|
-
diarizationLevel: o.diarizationLevel ?? 2,
|
|
146
|
-
timestampedProvider: o.timestampedProvider ?? "assemblyai"
|
|
147
|
-
};
|
|
148
|
-
return (0, import_node_crypto.createHash)("sha1").update(JSON.stringify(relevant)).digest("hex");
|
|
149
|
-
}
|
|
150
|
-
function planChunks(totalDuration, chunkDuration, overlap2) {
|
|
151
|
-
const chunks = [];
|
|
152
|
-
const step = chunkDuration - overlap2;
|
|
153
|
-
if (step <= 0) throw new Error("chunkOverlap must be < chunkDuration");
|
|
154
|
-
let start = 0;
|
|
155
|
-
let index = 0;
|
|
156
|
-
while (start < totalDuration) {
|
|
157
|
-
const end = Math.min(start + chunkDuration, totalDuration);
|
|
158
|
-
const overlapWithPrevious = index === 0 ? 0 : Math.min(overlap2, end - start);
|
|
159
|
-
if (end === totalDuration && end - start < chunkDuration / 3 && chunks.length > 0) {
|
|
160
|
-
chunks[chunks.length - 1].end = end;
|
|
161
|
-
break;
|
|
162
|
-
}
|
|
163
|
-
chunks.push({
|
|
164
|
-
index,
|
|
165
|
-
start,
|
|
166
|
-
end,
|
|
167
|
-
overlapWithPrevious,
|
|
168
|
-
trustedStart: start + overlapWithPrevious
|
|
169
|
-
});
|
|
170
|
-
start = end - overlap2;
|
|
171
|
-
if (start >= totalDuration) break;
|
|
172
|
-
index++;
|
|
173
|
-
}
|
|
174
|
-
return chunks;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// src/utils/logger.ts
|
|
178
|
-
var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
179
|
-
var currentLevel = "info";
|
|
180
|
-
function setLogLevel(level2) {
|
|
181
|
-
currentLevel = level2;
|
|
182
|
-
}
|
|
183
|
-
function log(level2, msg, extra) {
|
|
184
|
-
if (LEVELS[level2] < LEVELS[currentLevel]) return;
|
|
185
|
-
const ts = (/* @__PURE__ */ new Date()).toISOString().substring(11, 23);
|
|
186
|
-
const prefix = `[${ts}] ${level2.toUpperCase().padEnd(5)}`;
|
|
187
|
-
if (extra !== void 0) {
|
|
188
|
-
console[level2 === "error" ? "error" : "log"](prefix, msg, extra);
|
|
189
|
-
} else {
|
|
190
|
-
console[level2 === "error" ? "error" : "log"](prefix, msg);
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
var logger = {
|
|
194
|
-
debug: (msg, extra) => log("debug", msg, extra),
|
|
195
|
-
info: (msg, extra) => log("info", msg, extra),
|
|
196
|
-
warn: (msg, extra) => log("warn", msg, extra),
|
|
197
|
-
error: (msg, extra) => log("error", msg, extra),
|
|
198
|
-
setLevel: setLogLevel
|
|
199
|
-
};
|
|
200
|
-
|
|
201
|
-
// src/audio/ffmpeg.ts
|
|
202
|
-
var import_node_child_process = require("child_process");
|
|
203
|
-
var import_promises = require("fs/promises");
|
|
204
|
-
var import_node_path2 = require("path");
|
|
205
|
-
function run(cmd, args, _opts = {}) {
|
|
206
|
-
return new Promise((resolve3, reject) => {
|
|
207
|
-
const child = (0, import_node_child_process.spawn)(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
208
|
-
let stdout = "";
|
|
209
|
-
let stderr = "";
|
|
210
|
-
child.stdout.on("data", (d) => stdout += d.toString());
|
|
211
|
-
child.stderr.on("data", (d) => stderr += d.toString());
|
|
212
|
-
child.on("error", reject);
|
|
213
|
-
child.on("close", (code) => {
|
|
214
|
-
if (code === 0) resolve3({ stdout, stderr });
|
|
215
|
-
else {
|
|
216
|
-
const tail = stderr.slice(-800);
|
|
217
|
-
reject(new Error(`${cmd} exited ${code}: ${tail}`));
|
|
218
|
-
}
|
|
219
|
-
});
|
|
220
|
-
});
|
|
221
|
-
}
|
|
222
|
-
async function checkFfmpeg() {
|
|
223
|
-
try {
|
|
224
|
-
await run("ffmpeg", ["-version"]);
|
|
225
|
-
await run("ffprobe", ["-version"]);
|
|
226
|
-
return true;
|
|
227
|
-
} catch {
|
|
228
|
-
return false;
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
async function probe(input2) {
|
|
232
|
-
const { stdout } = await run("ffprobe", [
|
|
233
|
-
"-v",
|
|
234
|
-
"error",
|
|
235
|
-
"-show_format",
|
|
236
|
-
"-show_streams",
|
|
237
|
-
"-of",
|
|
238
|
-
"json",
|
|
239
|
-
input2
|
|
240
|
-
]);
|
|
241
|
-
const data = JSON.parse(stdout);
|
|
242
|
-
const streams = data.streams || [];
|
|
243
|
-
const audio = streams.find((s) => s.codec_type === "audio");
|
|
244
|
-
const video = streams.find((s) => s.codec_type === "video");
|
|
245
|
-
return {
|
|
246
|
-
duration: parseFloat(data.format?.duration || "0") || 0,
|
|
247
|
-
hasAudio: !!audio,
|
|
248
|
-
hasVideo: !!video,
|
|
249
|
-
audioCodec: audio?.codec_name,
|
|
250
|
-
videoCodec: video?.codec_name,
|
|
251
|
-
sampleRate: audio ? parseInt(audio.sample_rate ?? "0", 10) : void 0,
|
|
252
|
-
channels: audio?.channels,
|
|
253
|
-
width: video?.width,
|
|
254
|
-
height: video?.height,
|
|
255
|
-
sizeBytes: parseInt(data.format?.size || "0", 10) || void 0
|
|
256
|
-
};
|
|
257
|
-
}
|
|
258
|
-
function audioArgs(opts2) {
|
|
259
|
-
const sampleRate = opts2.sampleRate ?? 16e3;
|
|
260
|
-
const channels = opts2.channels ?? 1;
|
|
261
|
-
const format = opts2.format ?? "flac";
|
|
262
|
-
const common = ["-vn", "-ac", String(channels), "-ar", String(sampleRate)];
|
|
263
|
-
switch (format) {
|
|
264
|
-
case "flac":
|
|
265
|
-
return [...common, "-c:a", "flac"];
|
|
266
|
-
case "mp3":
|
|
267
|
-
return [...common, "-c:a", "libmp3lame", "-b:a", opts2.bitrate ?? "64k"];
|
|
268
|
-
case "opus":
|
|
269
|
-
return [...common, "-c:a", "libopus", "-b:a", opts2.bitrate ?? "48k"];
|
|
270
|
-
case "wav":
|
|
271
|
-
return [...common, "-c:a", "pcm_s16le"];
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
async function extractAudio(input2, output, opts2 = {}) {
|
|
275
|
-
await (0, import_promises.mkdir)((0, import_node_path2.dirname)(output), { recursive: true });
|
|
276
|
-
const args = ["-y", "-i", input2, ...audioArgs(opts2), output];
|
|
277
|
-
await run("ffmpeg", args);
|
|
278
|
-
}
|
|
279
|
-
async function extractChunk(input2, output, startSec, endSec, opts2 = {}) {
|
|
280
|
-
await (0, import_promises.mkdir)((0, import_node_path2.dirname)(output), { recursive: true });
|
|
281
|
-
const duration = Math.max(0, endSec - startSec);
|
|
282
|
-
const args = [
|
|
283
|
-
"-y",
|
|
284
|
-
"-ss",
|
|
285
|
-
startSec.toFixed(3),
|
|
286
|
-
"-i",
|
|
287
|
-
input2,
|
|
288
|
-
"-t",
|
|
289
|
-
duration.toFixed(3),
|
|
290
|
-
...audioArgs(opts2),
|
|
291
|
-
output
|
|
292
|
-
];
|
|
293
|
-
await run("ffmpeg", args);
|
|
294
|
-
}
|
|
295
|
-
async function getSceneChangeTimes(input2, threshold) {
|
|
296
|
-
try {
|
|
297
|
-
const { stderr } = await run("ffmpeg", [
|
|
298
|
-
"-i",
|
|
299
|
-
input2,
|
|
300
|
-
"-vf",
|
|
301
|
-
`select='gt(scene,${threshold})',showinfo`,
|
|
302
|
-
"-vsync",
|
|
303
|
-
"vfr",
|
|
304
|
-
"-f",
|
|
305
|
-
"null",
|
|
306
|
-
"-"
|
|
307
|
-
]);
|
|
308
|
-
const times = [];
|
|
309
|
-
const re = /pts_time:(\d+\.?\d*)/g;
|
|
310
|
-
let m;
|
|
311
|
-
while ((m = re.exec(stderr)) !== null) times.push(parseFloat(m[1]));
|
|
312
|
-
return times;
|
|
313
|
-
} catch (err) {
|
|
314
|
-
logger.debug(`scene detection failed: ${err.message}`);
|
|
315
|
-
return [];
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
async function extractKeyframes(input2, outputDir, count, opts2 = {}) {
|
|
319
|
-
await (0, import_promises.mkdir)(outputDir, { recursive: true });
|
|
320
|
-
const width = opts2.width ?? 1280;
|
|
321
|
-
const { duration } = await probe(input2);
|
|
322
|
-
if (!duration) return [];
|
|
323
|
-
const sceneTimes = await getSceneChangeTimes(input2, opts2.sceneThreshold ?? 0.3);
|
|
324
|
-
const times = [];
|
|
325
|
-
if (sceneTimes.length >= count) {
|
|
326
|
-
const step = sceneTimes.length / count;
|
|
327
|
-
for (let i = 0; i < count; i++) {
|
|
328
|
-
const idx = Math.floor(i * step);
|
|
329
|
-
times.push(sceneTimes[idx] ?? 0);
|
|
330
|
-
}
|
|
331
|
-
} else {
|
|
332
|
-
times.push(...sceneTimes);
|
|
333
|
-
const need = count - times.length;
|
|
334
|
-
const start = duration * 0.02;
|
|
335
|
-
const end = duration * 0.98;
|
|
336
|
-
for (let i = 0; i < need; i++) {
|
|
337
|
-
times.push(start + (end - start) * (i + 0.5) / need);
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
times.sort((a, b) => a - b);
|
|
341
|
-
const out = [];
|
|
342
|
-
for (let i = 0; i < times.length; i++) {
|
|
343
|
-
const t = times[i];
|
|
344
|
-
const path = `${outputDir}/keyframe_${String(i).padStart(3, "0")}.jpg`;
|
|
345
|
-
await run("ffmpeg", [
|
|
346
|
-
"-y",
|
|
347
|
-
"-ss",
|
|
348
|
-
t.toFixed(3),
|
|
349
|
-
"-i",
|
|
350
|
-
input2,
|
|
351
|
-
"-frames:v",
|
|
352
|
-
"1",
|
|
353
|
-
"-vf",
|
|
354
|
-
`scale=${width}:-2`,
|
|
355
|
-
"-q:v",
|
|
356
|
-
"3",
|
|
357
|
-
path
|
|
358
|
-
]);
|
|
359
|
-
out.push({ path, time: t });
|
|
360
|
-
}
|
|
361
|
-
return out;
|
|
362
|
-
}
|
|
363
|
-
async function detectSilence(input2, opts2 = {}) {
|
|
364
|
-
const noise = opts2.noiseDb ?? -30;
|
|
365
|
-
const minDur = opts2.minDuration ?? 0.3;
|
|
366
|
-
const { stderr } = await run("ffmpeg", [
|
|
367
|
-
"-i",
|
|
368
|
-
input2,
|
|
369
|
-
"-af",
|
|
370
|
-
`silencedetect=noise=${noise}dB:d=${minDur}`,
|
|
371
|
-
"-f",
|
|
372
|
-
"null",
|
|
373
|
-
"-"
|
|
374
|
-
]);
|
|
375
|
-
const starts = [];
|
|
376
|
-
const ends = [];
|
|
377
|
-
let m;
|
|
378
|
-
const startRe = /silence_start: (-?\d+\.?\d*)/g;
|
|
379
|
-
while ((m = startRe.exec(stderr)) !== null) starts.push(parseFloat(m[1]));
|
|
380
|
-
const endRe = /silence_end: (-?\d+\.?\d*)/g;
|
|
381
|
-
while ((m = endRe.exec(stderr)) !== null) ends.push(parseFloat(m[1]));
|
|
382
|
-
const ranges = [];
|
|
383
|
-
for (let i = 0; i < starts.length; i++) {
|
|
384
|
-
const s = starts[i];
|
|
385
|
-
const e = ends[i] ?? s + minDur;
|
|
386
|
-
ranges.push({ start: s, end: e, duration: e - s });
|
|
387
|
-
}
|
|
388
|
-
return ranges;
|
|
389
|
-
}
|
|
390
|
-
function snapToSilence(boundary, silences, tolerance) {
|
|
391
|
-
let best = boundary;
|
|
392
|
-
let bestDist = tolerance;
|
|
393
|
-
for (const s of silences) {
|
|
394
|
-
const mid = (s.start + s.end) / 2;
|
|
395
|
-
const dist = Math.abs(mid - boundary);
|
|
396
|
-
if (dist < bestDist) {
|
|
397
|
-
bestDist = dist;
|
|
398
|
-
best = mid;
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
return best;
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
// src/providers/gemini.ts
|
|
405
|
-
var import_genai = require("@google/genai");
|
|
406
|
-
var import_node_path3 = require("path");
|
|
407
|
-
|
|
408
|
-
// src/providers/llm-log.ts
|
|
409
|
-
var import_node_fs2 = require("fs");
|
|
410
|
-
var logPath = null;
|
|
411
|
-
function setLlmLogPath(path) {
|
|
412
|
-
logPath = path ?? null;
|
|
413
|
-
}
|
|
414
|
-
function logLlmCall(entry) {
|
|
415
|
-
if (!logPath) return;
|
|
416
|
-
try {
|
|
417
|
-
(0, import_node_fs2.appendFileSync)(logPath, JSON.stringify(entry) + "\n", { encoding: "utf-8" });
|
|
418
|
-
} catch {
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
// src/providers/gemini.ts
|
|
423
|
-
var MIME_BY_EXT = {
|
|
424
|
-
".flac": "audio/flac",
|
|
425
|
-
".mp3": "audio/mp3",
|
|
426
|
-
".wav": "audio/wav",
|
|
427
|
-
".m4a": "audio/m4a",
|
|
428
|
-
".aac": "audio/aac",
|
|
429
|
-
".ogg": "audio/ogg",
|
|
430
|
-
".opus": "audio/opus",
|
|
431
|
-
".mp4": "video/mp4",
|
|
432
|
-
".mov": "video/quicktime",
|
|
433
|
-
".webm": "video/webm",
|
|
434
|
-
".png": "image/png",
|
|
435
|
-
".jpg": "image/jpeg",
|
|
436
|
-
".jpeg": "image/jpeg",
|
|
437
|
-
".webp": "image/webp"
|
|
438
|
-
};
|
|
439
|
-
function detectMime(path) {
|
|
440
|
-
const ext2 = path.slice(path.lastIndexOf(".")).toLowerCase();
|
|
441
|
-
return MIME_BY_EXT[ext2] ?? "application/octet-stream";
|
|
442
|
-
}
|
|
443
|
-
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
444
|
-
function resolveThinking(model) {
|
|
445
|
-
const m = model.toLowerCase();
|
|
446
|
-
if (m.includes("gemini-2.0")) return void 0;
|
|
447
|
-
if (m.includes("gemini-2.5")) {
|
|
448
|
-
return { thinkingBudget: m.includes("pro") ? 128 : 0 };
|
|
449
|
-
}
|
|
450
|
-
if (m.includes("gemini-3") || m.includes("flash-latest") || m.includes("pro-latest")) {
|
|
451
|
-
return { thinkingLevel: m.includes("pro") ? "LOW" : "MINIMAL" };
|
|
452
|
-
}
|
|
453
|
-
return void 0;
|
|
454
|
-
}
|
|
455
|
-
function isThinkingConfigError(message) {
|
|
456
|
-
if (!message) return false;
|
|
457
|
-
return /thinking/i.test(message) && /(not supported|invalid|unsupported|unknown name|unexpected)/i.test(message);
|
|
458
|
-
}
|
|
459
|
-
var GeminiClient = class {
|
|
460
|
-
ai;
|
|
461
|
-
constructor(apiKey) {
|
|
462
|
-
this.ai = new import_genai.GoogleGenAI({ apiKey });
|
|
463
|
-
}
|
|
464
|
-
/** Upload a file and wait until it's done processing. */
|
|
465
|
-
async upload(path, mimeType) {
|
|
466
|
-
const mt = mimeType || detectMime(path);
|
|
467
|
-
logger.debug(`[gemini] uploading ${(0, import_node_path3.basename)(path)} (${mt})...`);
|
|
468
|
-
let file = await this.ai.files.upload({ file: path, config: { mimeType: mt } });
|
|
469
|
-
let tries = 0;
|
|
470
|
-
while (file.state === "PROCESSING" && tries < 120) {
|
|
471
|
-
await sleep(2e3);
|
|
472
|
-
file = await this.ai.files.get({ name: file.name });
|
|
473
|
-
tries++;
|
|
474
|
-
}
|
|
475
|
-
if (file.state === "FAILED") {
|
|
476
|
-
throw new Error(`Gemini file processing failed: ${path}`);
|
|
477
|
-
}
|
|
478
|
-
logger.debug(`[gemini] uploaded ${(0, import_node_path3.basename)(path)} \u2192 ${file.uri}`);
|
|
479
|
-
return file;
|
|
480
|
-
}
|
|
481
|
-
/** Generate content from a prompt + uploaded files. */
|
|
482
|
-
async generate(model, prompt, files, opts2 = {}) {
|
|
483
|
-
const {
|
|
484
|
-
maxRetries = 3,
|
|
485
|
-
retryDelayMs = 2e3,
|
|
486
|
-
temperature = 0.2,
|
|
487
|
-
maxOutputTokens = 65536,
|
|
488
|
-
responseSchema,
|
|
489
|
-
systemInstruction
|
|
490
|
-
} = opts2;
|
|
491
|
-
const uploaded = [];
|
|
492
|
-
try {
|
|
493
|
-
for (const f of files) {
|
|
494
|
-
uploaded.push(await this.upload(f.path, f.mimeType));
|
|
495
|
-
}
|
|
496
|
-
const config = {
|
|
497
|
-
maxOutputTokens,
|
|
498
|
-
temperature
|
|
499
|
-
};
|
|
500
|
-
if (responseSchema) {
|
|
501
|
-
config.responseMimeType = "application/json";
|
|
502
|
-
config.responseSchema = responseSchema;
|
|
503
|
-
}
|
|
504
|
-
if (systemInstruction) config.systemInstruction = systemInstruction;
|
|
505
|
-
const thinking = resolveThinking(model);
|
|
506
|
-
if (thinking) config.thinkingConfig = thinking;
|
|
507
|
-
const parts = uploaded.map((f) => ({
|
|
508
|
-
fileData: { fileUri: f.uri, mimeType: f.mimeType }
|
|
509
|
-
}));
|
|
510
|
-
parts.push({ text: prompt });
|
|
511
|
-
let lastError;
|
|
512
|
-
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
513
|
-
const t0 = Date.now();
|
|
514
|
-
try {
|
|
515
|
-
const response = await this.ai.models.generateContent({
|
|
516
|
-
model,
|
|
517
|
-
contents: [{ role: "user", parts }],
|
|
518
|
-
config
|
|
519
|
-
});
|
|
520
|
-
const usage = response.usageMetadata || {};
|
|
521
|
-
const text = response.text ?? "";
|
|
522
|
-
const result = {
|
|
523
|
-
text,
|
|
524
|
-
usage: {
|
|
525
|
-
inputTokens: usage.promptTokenCount ?? 0,
|
|
526
|
-
outputTokens: usage.candidatesTokenCount ?? 0,
|
|
527
|
-
totalTokens: usage.totalTokenCount ?? 0
|
|
528
|
-
}
|
|
529
|
-
};
|
|
530
|
-
logLlmCall({
|
|
531
|
-
ts: new Date(t0).toISOString(),
|
|
532
|
-
provider: "gemini",
|
|
533
|
-
model,
|
|
534
|
-
kind: opts2.logKind,
|
|
535
|
-
chunk: opts2.logChunk,
|
|
536
|
-
prompt,
|
|
537
|
-
response: text,
|
|
538
|
-
usage: result.usage,
|
|
539
|
-
durationMs: Date.now() - t0,
|
|
540
|
-
attempt: attempt + 1
|
|
541
|
-
});
|
|
542
|
-
return result;
|
|
543
|
-
} catch (err) {
|
|
544
|
-
lastError = err instanceof Error ? err.message : String(err);
|
|
545
|
-
if (config.thinkingConfig && isThinkingConfigError(lastError)) {
|
|
546
|
-
delete config.thinkingConfig;
|
|
547
|
-
logger.warn(`[gemini] model ${model} rejected thinking config \u2014 retrying without it`);
|
|
548
|
-
continue;
|
|
549
|
-
}
|
|
550
|
-
logger.warn(`[gemini] attempt ${attempt + 1}/${maxRetries} failed: ${lastError}`);
|
|
551
|
-
logLlmCall({
|
|
552
|
-
ts: new Date(t0).toISOString(),
|
|
553
|
-
provider: "gemini",
|
|
554
|
-
model,
|
|
555
|
-
kind: opts2.logKind,
|
|
556
|
-
chunk: opts2.logChunk,
|
|
557
|
-
prompt,
|
|
558
|
-
response: "",
|
|
559
|
-
durationMs: Date.now() - t0,
|
|
560
|
-
attempt: attempt + 1,
|
|
561
|
-
error: lastError
|
|
562
|
-
});
|
|
563
|
-
if (attempt < maxRetries - 1) await sleep(retryDelayMs * (attempt + 1));
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
return { text: "", usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }, error: lastError };
|
|
567
|
-
} finally {
|
|
568
|
-
await this.cleanup(uploaded);
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
/** Generate and parse JSON (requires responseSchema in opts). */
|
|
572
|
-
async generateJson(model, prompt, files, responseSchema, opts2 = {}) {
|
|
573
|
-
const result = await this.generate(model, prompt, files, {
|
|
574
|
-
...opts2,
|
|
575
|
-
responseSchema
|
|
576
|
-
});
|
|
577
|
-
if (result.error || !result.text) {
|
|
578
|
-
return { data: null, raw: result.text, usage: result.usage, error: result.error };
|
|
579
|
-
}
|
|
580
|
-
try {
|
|
581
|
-
let txt = result.text.trim();
|
|
582
|
-
const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
|
|
583
|
-
if (fence && fence[1]) txt = fence[1];
|
|
584
|
-
return { data: JSON.parse(txt), raw: result.text, usage: result.usage };
|
|
585
|
-
} catch (err) {
|
|
586
|
-
return {
|
|
587
|
-
data: null,
|
|
588
|
-
raw: result.text,
|
|
589
|
-
usage: result.usage,
|
|
590
|
-
error: `JSON parse failed: ${err instanceof Error ? err.message : String(err)}`
|
|
591
|
-
};
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
async cleanup(files) {
|
|
595
|
-
await Promise.allSettled(
|
|
596
|
-
files.map(async (f) => {
|
|
597
|
-
try {
|
|
598
|
-
if (f.name) await this.ai.files.delete({ name: f.name });
|
|
599
|
-
} catch {
|
|
600
|
-
}
|
|
601
|
-
})
|
|
602
|
-
);
|
|
603
|
-
}
|
|
604
|
-
};
|
|
605
|
-
|
|
606
|
-
// src/providers/assemblyai.ts
|
|
607
|
-
var import_assemblyai = require("assemblyai");
|
|
608
|
-
var import_node_crypto2 = require("crypto");
|
|
609
|
-
var import_promises2 = require("fs/promises");
|
|
610
|
-
var import_node_fs3 = require("fs");
|
|
611
|
-
var import_node_path4 = require("path");
|
|
612
|
-
async function fileHash(path) {
|
|
613
|
-
const buf = await (0, import_promises2.readFile)(path);
|
|
614
|
-
return (0, import_node_crypto2.createHash)("sha256").update(buf).digest("hex").slice(0, 24);
|
|
615
|
-
}
|
|
616
|
-
var AssemblyAIProvider = class {
|
|
617
|
-
client;
|
|
618
|
-
cacheDir;
|
|
619
|
-
constructor(opts2) {
|
|
620
|
-
this.client = new import_assemblyai.AssemblyAI({ apiKey: opts2.apiKey });
|
|
621
|
-
this.cacheDir = opts2.cacheDir;
|
|
622
|
-
this.speechModel = opts2.speechModel ?? "universal";
|
|
623
|
-
this.speakersExpected = opts2.speakersExpected;
|
|
624
|
-
}
|
|
625
|
-
speechModel;
|
|
626
|
-
speakersExpected;
|
|
627
|
-
/** Transcribe a local audio file. Returns cached result if available. */
|
|
628
|
-
async transcribe(filePath) {
|
|
629
|
-
const hash = await fileHash(filePath);
|
|
630
|
-
const cachePath = this.cacheDir ? `${this.cacheDir}/${hash}.json` : void 0;
|
|
631
|
-
if (cachePath && (0, import_node_fs3.existsSync)(cachePath)) {
|
|
632
|
-
logger.info(`[assemblyai] cache hit ${hash}`);
|
|
633
|
-
return JSON.parse(await (0, import_promises2.readFile)(cachePath, "utf-8"));
|
|
634
|
-
}
|
|
635
|
-
logger.info(`[assemblyai] uploading ${filePath}...`);
|
|
636
|
-
const uploadUrl = await this.client.files.upload(filePath);
|
|
637
|
-
logger.info(`[assemblyai] transcribing (speech_model=${this.speechModel})...`);
|
|
638
|
-
const params = {
|
|
639
|
-
audio: uploadUrl,
|
|
640
|
-
speaker_labels: true,
|
|
641
|
-
speech_model: this.speechModel
|
|
642
|
-
};
|
|
643
|
-
if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
|
|
644
|
-
const transcript = await this.client.transcripts.transcribe(params);
|
|
645
|
-
if (transcript.status === "error") {
|
|
646
|
-
throw new Error(`AssemblyAI error: ${transcript.error}`);
|
|
647
|
-
}
|
|
648
|
-
const result = this.mapTranscript(transcript, hash);
|
|
649
|
-
if (cachePath) {
|
|
650
|
-
await (0, import_promises2.mkdir)((0, import_node_path4.dirname)(cachePath), { recursive: true });
|
|
651
|
-
await (0, import_promises2.writeFile)(cachePath, JSON.stringify(result, null, 2));
|
|
652
|
-
}
|
|
653
|
-
logger.info(
|
|
654
|
-
`[assemblyai] done: ${result.utterances.length} utterances, ${result.words.length} words, ${result.speakers.length} speakers`
|
|
655
|
-
);
|
|
656
|
-
return result;
|
|
657
|
-
}
|
|
658
|
-
mapTranscript(t, id) {
|
|
659
|
-
const toWord = (w) => ({
|
|
660
|
-
text: w.text,
|
|
661
|
-
start: (w.start || 0) / 1e3,
|
|
662
|
-
end: (w.end || 0) / 1e3,
|
|
663
|
-
confidence: w.confidence ?? void 0
|
|
664
|
-
});
|
|
665
|
-
const utterances = [];
|
|
666
|
-
const speakers = /* @__PURE__ */ new Set();
|
|
667
|
-
for (const u of t.utterances || []) {
|
|
668
|
-
const speaker = `speaker_${u.speaker}`;
|
|
669
|
-
speakers.add(speaker);
|
|
670
|
-
utterances.push({
|
|
671
|
-
speaker,
|
|
672
|
-
text: u.text,
|
|
673
|
-
start: (u.start || 0) / 1e3,
|
|
674
|
-
end: (u.end || 0) / 1e3,
|
|
675
|
-
confidence: u.confidence ?? void 0,
|
|
676
|
-
words: (u.words || []).map(toWord)
|
|
677
|
-
});
|
|
678
|
-
}
|
|
679
|
-
const words = (t.words || []).map(toWord);
|
|
680
|
-
const durationSec = words.length ? words[words.length - 1].end || 0 : utterances.length ? utterances[utterances.length - 1].end : 0;
|
|
681
|
-
return {
|
|
682
|
-
utterances,
|
|
683
|
-
words,
|
|
684
|
-
durationSec,
|
|
685
|
-
audioDurationSec: t.audio_duration ?? void 0,
|
|
686
|
-
// AssemblyAI returns seconds (not ms)
|
|
687
|
-
speakers: [...speakers].sort(),
|
|
688
|
-
transcriptId: t.id ?? id,
|
|
689
|
-
speechModelUsed: t.speech_model_used ?? void 0,
|
|
690
|
-
hasDiarization: true
|
|
691
|
-
};
|
|
692
|
-
}
|
|
693
|
-
};
|
|
694
|
-
|
|
695
|
-
// src/providers/whisper-groq.ts
|
|
696
|
-
var WhisperGroqClient = class {
|
|
697
|
-
constructor(apiKey, model = "whisper-large-v3-turbo", baseUrl = "https://api.groq.com/openai/v1") {
|
|
698
|
-
this.apiKey = apiKey;
|
|
699
|
-
this.model = model;
|
|
700
|
-
this.baseUrl = baseUrl;
|
|
701
|
-
}
|
|
702
|
-
apiKey;
|
|
703
|
-
model;
|
|
704
|
-
baseUrl;
|
|
705
|
-
async transcribe(audio) {
|
|
706
|
-
const blob = audio instanceof Blob ? audio : new Blob([audio], { type: "audio/mpeg" });
|
|
707
|
-
const form = new FormData();
|
|
708
|
-
form.append("file", blob, "audio.mp3");
|
|
709
|
-
form.append("model", this.model);
|
|
710
|
-
form.append("response_format", "verbose_json");
|
|
711
|
-
form.append("timestamp_granularities[]", "word");
|
|
712
|
-
form.append("timestamp_granularities[]", "segment");
|
|
713
|
-
const res = await fetch(`${this.baseUrl}/audio/transcriptions`, {
|
|
714
|
-
method: "POST",
|
|
715
|
-
headers: { Authorization: `Bearer ${this.apiKey}` },
|
|
716
|
-
body: form
|
|
717
|
-
});
|
|
718
|
-
if (!res.ok) {
|
|
719
|
-
const txt = await res.text();
|
|
720
|
-
throw new Error(`Groq Whisper ${res.status}: ${txt.slice(0, 300)}`);
|
|
721
|
-
}
|
|
722
|
-
const data = await res.json();
|
|
723
|
-
const words = (data.words || []).map((w) => ({
|
|
724
|
-
text: String(w.word || ""),
|
|
725
|
-
start: w.start,
|
|
726
|
-
end: w.end,
|
|
727
|
-
confidence: void 0
|
|
728
|
-
}));
|
|
729
|
-
const utterances = (data.segments || []).map((s) => ({
|
|
730
|
-
speaker: "speaker_A",
|
|
731
|
-
text: String(s.text || "").trim(),
|
|
732
|
-
start: s.start,
|
|
733
|
-
end: s.end,
|
|
734
|
-
confidence: void 0,
|
|
735
|
-
words: words.filter((w) => w.start >= s.start && w.start < s.end)
|
|
736
|
-
}));
|
|
737
|
-
return {
|
|
738
|
-
utterances,
|
|
739
|
-
words,
|
|
740
|
-
durationSec: data.duration ?? (words.length ? words[words.length - 1].end : 0),
|
|
741
|
-
speakers: ["speaker_A"],
|
|
742
|
-
hasDiarization: false,
|
|
743
|
-
transcriptId: `groq-${this.model}`
|
|
744
|
-
};
|
|
745
|
-
}
|
|
746
|
-
};
|
|
747
|
-
|
|
748
|
-
// src/transcribe/describe.ts
|
|
749
|
-
function descriptionPrompt(fileName, instructions) {
|
|
750
|
-
return `You are listening to a recording to prepare a transcription engine. Describe what you hear${instructions ? ` (note: ${instructions})` : ""}.
|
|
751
|
-
|
|
752
|
-
Respond in TWO sections, clearly separated by a line containing only "---":
|
|
753
|
-
|
|
754
|
-
DESCRIPTION
|
|
755
|
-
A short paragraph: what kind of recording this is, the setting, the main topics, and the overall flow.
|
|
756
|
-
|
|
757
|
-
ROSTER
|
|
758
|
-
A bulleted speaker roster. For each distinct speaker you can identify, give:
|
|
759
|
-
- A short label to use consistently (a name/role if you can infer it, e.g. "Presenter (Hrishi)", else "Speaker A").
|
|
760
|
-
- A one-line description (voice, role, accent if notable).
|
|
761
|
-
List the people you can distinguish. Do not invent names you didn't hear. If only one person speaks, say so.
|
|
762
|
-
|
|
763
|
-
File: ${fileName}`;
|
|
764
|
-
}
|
|
765
|
-
async function describeMeeting(client, model, files, fileName, instructions) {
|
|
766
|
-
const res = await client.generate(model, descriptionPrompt(fileName, instructions), files, {
|
|
767
|
-
temperature: 0.2,
|
|
768
|
-
maxRetries: 3,
|
|
769
|
-
logKind: "describe"
|
|
770
|
-
});
|
|
771
|
-
const text = res.text || "";
|
|
772
|
-
const parts = text.split(/\n---\n|\n\s*---\s*\n/);
|
|
773
|
-
const description = parts[0]?.trim() || text.trim();
|
|
774
|
-
const roster = parts.slice(1).join("\n---\n").trim() || "(no explicit roster)";
|
|
775
|
-
return { description, roster, raw: text };
|
|
776
|
-
}
|
|
777
|
-
|
|
778
|
-
// src/transcribe/prompts.ts
|
|
779
|
-
var TRANSCRIPT_SCHEMA = {
|
|
780
|
-
type: "OBJECT",
|
|
781
|
-
properties: {
|
|
782
|
-
segments: {
|
|
783
|
-
type: "ARRAY",
|
|
784
|
-
items: {
|
|
785
|
-
type: "OBJECT",
|
|
786
|
-
properties: {
|
|
787
|
-
speaker: { type: "STRING", description: "Speaker label. Use an identified name from the roster if confident, else 'Speaker A', 'Speaker B', etc." },
|
|
788
|
-
start: { type: "STRING", description: "Relative start time as mm:ss (00:00 = start of this audio chunk)" },
|
|
789
|
-
end: { type: "STRING", description: "Relative end time as mm:ss" },
|
|
790
|
-
text: { type: "STRING", description: "Verbatim transcribed words, including fillers and false starts" },
|
|
791
|
-
tone: {
|
|
792
|
-
type: "ARRAY",
|
|
793
|
-
items: { type: "STRING" },
|
|
794
|
-
description: "Tone/behavior tags e.g. hesitant, laughing, contemplating, urgent, sarcastic. Empty array if neutral."
|
|
795
|
-
}
|
|
796
|
-
},
|
|
797
|
-
required: ["speaker", "start", "end", "text"]
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
},
|
|
801
|
-
required: ["segments"]
|
|
802
|
-
};
|
|
803
|
-
function transcriptionPrompt(ctx) {
|
|
804
|
-
const parts = [];
|
|
805
|
-
parts.push(
|
|
806
|
-
`You are an expert speech transcription engine. Below is audio chunk ${ctx.index} of ${ctx.total} from a recording. Transcribe ALL speech verbatim and diarize it.`
|
|
807
|
-
);
|
|
808
|
-
parts.push("");
|
|
809
|
-
parts.push("Output one segment per speaker turn (a new segment whenever the speaker changes, or after a long pause, or at an interruption).");
|
|
810
|
-
parts.push("");
|
|
811
|
-
parts.push("For each segment provide:");
|
|
812
|
-
parts.push("- speaker: a label. Use an identified name/role from the roster if you are confident who is speaking; otherwise use 'Speaker A', 'Speaker B', etc. Keep labels CONSISTENT across the chunk.");
|
|
813
|
-
parts.push("- start, end: relative timestamps as mm:ss, where 00:00 is the START of this audio chunk. They must be monotonic and span the full chunk.");
|
|
814
|
-
parts.push("- text: the verbatim words, including fillers (um, uh), false starts, and corrections. Do not paraphrase.");
|
|
815
|
-
parts.push("- tone: array of behavior/emotion tags. Tag most segments \u2014 e.g. confident, hesitant, laughing, sarcastic, urgent, contemplative, whispering, emphatic, questioning, joking, frustrated. Use an empty array ONLY when nothing stands out.");
|
|
816
|
-
parts.push("");
|
|
817
|
-
parts.push("Rules:");
|
|
818
|
-
parts.push("- Cover the ENTIRE audio with no gaps. Timestamps must be monotonic non-decreasing.");
|
|
819
|
-
parts.push("- Capture interruptions and overlapping talk as separate, adjacent segments even if times overlap.");
|
|
820
|
-
parts.push("- Do not invent content not present in the audio. If inaudible, write [inaudible].");
|
|
821
|
-
parts.push("- Keep speaker labels consistent within this chunk; the same voice = same label.");
|
|
822
|
-
if (ctx.description) {
|
|
823
|
-
parts.push("");
|
|
824
|
-
parts.push("MEETING CONTEXT:");
|
|
825
|
-
parts.push(ctx.description);
|
|
826
|
-
}
|
|
827
|
-
if (ctx.roster) {
|
|
828
|
-
parts.push("");
|
|
829
|
-
parts.push("SPEAKER ROSTER (prefer these labels/names when you can identify the voice):");
|
|
830
|
-
parts.push(ctx.roster);
|
|
831
|
-
}
|
|
832
|
-
if (ctx.previousTail) {
|
|
833
|
-
parts.push("");
|
|
834
|
-
parts.push("TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):");
|
|
835
|
-
parts.push(ctx.previousTail);
|
|
836
|
-
}
|
|
837
|
-
if (ctx.instructions) {
|
|
838
|
-
parts.push("");
|
|
839
|
-
parts.push("ADDITIONAL INSTRUCTIONS:");
|
|
840
|
-
parts.push(ctx.instructions);
|
|
841
|
-
}
|
|
842
|
-
parts.push("");
|
|
843
|
-
parts.push("Return JSON matching the schema: { segments: [ {speaker, start, end, text, tone} ] }");
|
|
844
|
-
return parts.join("\n");
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
// src/utils/time.ts
|
|
848
|
-
function secondsToTimestamp(seconds) {
|
|
849
|
-
const clamped = Math.max(0, seconds);
|
|
850
|
-
const hours = Math.floor(clamped / 3600);
|
|
851
|
-
const minutes = Math.floor(clamped % 3600 / 60);
|
|
852
|
-
const secs = Math.floor(clamped % 60);
|
|
853
|
-
const ms = Math.floor(clamped % 1 * 1e3);
|
|
854
|
-
return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")},${ms.toString().padStart(3, "0")}`;
|
|
855
|
-
}
|
|
856
|
-
function formatSrtTiming(startSeconds, endSeconds) {
|
|
857
|
-
return `${secondsToTimestamp(startSeconds)} --> ${secondsToTimestamp(endSeconds)}`;
|
|
858
|
-
}
|
|
859
|
-
function parseMmSs(timeStr) {
|
|
860
|
-
const parts = timeStr.split(":");
|
|
861
|
-
if (parts.length !== 2) return null;
|
|
862
|
-
const minutes = parseInt(parts[0], 10);
|
|
863
|
-
const seconds = parseInt(parts[1], 10);
|
|
864
|
-
if (isNaN(minutes) || isNaN(seconds)) return null;
|
|
865
|
-
if (seconds < 0 || seconds >= 60) return null;
|
|
866
|
-
return minutes * 60 + seconds;
|
|
867
|
-
}
|
|
868
|
-
|
|
869
|
-
// src/transcribe/llm-transcribe.ts
|
|
870
|
-
var MIN_SEGMENTS = 3;
|
|
871
|
-
var MIN_SPAN_RATIO = 0.6;
|
|
872
|
-
function toAbsolute(mmSs, offset) {
|
|
873
|
-
const s = parseMmSs(mmSs.trim());
|
|
874
|
-
return s === null ? null : s + offset;
|
|
875
|
-
}
|
|
876
|
-
function partitionByOwnership(segments) {
|
|
877
|
-
return segments.filter((s) => {
|
|
878
|
-
if (s.trustedStart === void 0) return true;
|
|
879
|
-
const center = (s.startSec + s.endSec) / 2;
|
|
880
|
-
return center >= s.trustedStart;
|
|
881
|
-
});
|
|
882
|
-
}
|
|
883
|
-
function parseLlmSegments(data, chunkOffsetSec) {
|
|
884
|
-
const out = [];
|
|
885
|
-
let dropped = 0;
|
|
886
|
-
for (const seg of data.segments || []) {
|
|
887
|
-
const start = toAbsolute(seg.start, chunkOffsetSec);
|
|
888
|
-
const end = toAbsolute(seg.end, chunkOffsetSec);
|
|
889
|
-
if (start === null || end === null || end < start) {
|
|
890
|
-
dropped++;
|
|
891
|
-
logger.debug(`[llm] dropping segment (bad time ${seg.start}-${seg.end}): "${(seg.text || "").slice(0, 40)}"`);
|
|
892
|
-
continue;
|
|
893
|
-
}
|
|
894
|
-
out.push({
|
|
895
|
-
speaker: (seg.speaker || "Unknown").trim(),
|
|
896
|
-
startSec: start,
|
|
897
|
-
endSec: end,
|
|
898
|
-
text: (seg.text || "").trim(),
|
|
899
|
-
tone: Array.isArray(seg.tone) ? seg.tone.map((t) => String(t).trim()).filter(Boolean) : [],
|
|
900
|
-
rawStart: seg.start,
|
|
901
|
-
rawEnd: seg.end
|
|
902
|
-
});
|
|
903
|
-
}
|
|
904
|
-
return { segments: out, dropped };
|
|
905
|
-
}
|
|
906
|
-
function validate(segments, chunkDuration) {
|
|
907
|
-
if (segments.length < MIN_SEGMENTS) {
|
|
908
|
-
return { isValid: false, spanSec: 0, segmentCount: segments.length, message: `only ${segments.length} segments (min ${MIN_SEGMENTS})` };
|
|
909
|
-
}
|
|
910
|
-
const first = segments[0].startSec;
|
|
911
|
-
const last = segments[segments.length - 1].endSec;
|
|
912
|
-
const span = last - first;
|
|
913
|
-
const minSpan = chunkDuration * MIN_SPAN_RATIO;
|
|
914
|
-
if (span < minSpan) {
|
|
915
|
-
return { isValid: false, spanSec: span, segmentCount: segments.length, message: `span ${span.toFixed(0)}s < ${minSpan.toFixed(0)}s required (${MIN_SPAN_RATIO * 100}% of chunk)` };
|
|
916
|
-
}
|
|
917
|
-
return { isValid: true, spanSec: span, segmentCount: segments.length, message: `ok (${segments.length} segments, ${span.toFixed(0)}s span)` };
|
|
918
|
-
}
|
|
919
|
-
async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts2) {
|
|
920
|
-
const validationRetries = opts2.validationRetries ?? 1;
|
|
921
|
-
const prompt = transcriptionPrompt(ctx);
|
|
922
|
-
let lastResult;
|
|
923
|
-
for (let attempt = 0; attempt <= validationRetries; attempt++) {
|
|
924
|
-
const gen = await client.generateJson(
|
|
925
|
-
model,
|
|
926
|
-
prompt,
|
|
927
|
-
[{ path: chunkPath }],
|
|
928
|
-
TRANSCRIPT_SCHEMA,
|
|
929
|
-
{
|
|
930
|
-
temperature: opts2.temperature ?? 0.2,
|
|
931
|
-
maxRetries: 3,
|
|
932
|
-
logKind: "transcribe",
|
|
933
|
-
logChunk: ctx.index - 1
|
|
934
|
-
}
|
|
935
|
-
);
|
|
936
|
-
if (gen.error || !gen.data) {
|
|
937
|
-
lastResult = {
|
|
938
|
-
segments: [],
|
|
939
|
-
raw: gen.raw,
|
|
940
|
-
usage: gen.usage,
|
|
941
|
-
validation: { isValid: false, spanSec: 0, segmentCount: 0, message: gen.error || "no data" },
|
|
942
|
-
error: gen.error
|
|
943
|
-
};
|
|
944
|
-
logger.warn(`[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`);
|
|
945
|
-
continue;
|
|
946
|
-
}
|
|
947
|
-
const { segments, dropped } = parseLlmSegments(gen.data, chunkStartSec);
|
|
948
|
-
const v = validate(segments, opts2.chunkDurationSec);
|
|
949
|
-
lastResult = { segments, raw: gen.raw, usage: gen.usage, validation: v };
|
|
950
|
-
if (v.isValid) {
|
|
951
|
-
logger.info(`[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`);
|
|
952
|
-
return lastResult;
|
|
953
|
-
}
|
|
954
|
-
logger.warn(`[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`);
|
|
955
|
-
}
|
|
956
|
-
logger.error(`[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`);
|
|
957
|
-
return lastResult;
|
|
958
|
-
}
|
|
959
|
-
|
|
960
|
-
// src/align/normalize.ts
|
|
961
|
-
function normalize(word) {
|
|
962
|
-
return word.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "").replace(/'+$/g, "").replace(/^'+/g, "");
|
|
963
|
-
}
|
|
964
|
-
function tokenize(text) {
|
|
965
|
-
const out = [];
|
|
966
|
-
for (const raw of text.split(/\s+/)) {
|
|
967
|
-
if (!raw) continue;
|
|
968
|
-
const norm = normalize(raw);
|
|
969
|
-
if (norm) out.push({ original: raw, norm });
|
|
970
|
-
}
|
|
971
|
-
return out;
|
|
972
|
-
}
|
|
973
|
-
function fuzzyEqual(a, b) {
|
|
974
|
-
if (a === b) return true;
|
|
975
|
-
if (Math.abs(a.length - b.length) <= 1) {
|
|
976
|
-
return editDistanceChars(a, b, 1) <= 1;
|
|
977
|
-
}
|
|
978
|
-
return false;
|
|
979
|
-
}
|
|
980
|
-
function editDistanceChars(a, b, max) {
|
|
981
|
-
const m = a.length;
|
|
982
|
-
const n = b.length;
|
|
983
|
-
if (Math.abs(m - n) > max) return max + 1;
|
|
984
|
-
let prev = new Array(n + 1);
|
|
985
|
-
for (let j = 0; j <= n; j++) prev[j] = j;
|
|
986
|
-
for (let i = 1; i <= m; i++) {
|
|
987
|
-
const cur = [i];
|
|
988
|
-
let rowMin = cur[0];
|
|
989
|
-
for (let j = 1; j <= n; j++) {
|
|
990
|
-
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
991
|
-
cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost);
|
|
992
|
-
if (cur[j] < rowMin) rowMin = cur[j];
|
|
993
|
-
}
|
|
994
|
-
if (rowMin > max) return max + 1;
|
|
995
|
-
prev = cur;
|
|
996
|
-
}
|
|
997
|
-
return prev[n];
|
|
998
|
-
}
|
|
999
|
-
|
|
1000
|
-
// src/align/edit-distance.ts
|
|
1001
|
-
var INDEL = 2;
|
|
1002
|
-
function matchCost(a, b) {
|
|
1003
|
-
if (a.norm === b.norm) return { cost: 0, fuzzy: false };
|
|
1004
|
-
if (fuzzyEqual(a.norm, b.norm)) return { cost: 1, fuzzy: true };
|
|
1005
|
-
return { cost: 2, fuzzy: false };
|
|
1006
|
-
}
|
|
1007
|
-
function alignWords(llm, asr) {
|
|
1008
|
-
const m = llm.length;
|
|
1009
|
-
const n = asr.length;
|
|
1010
|
-
const dp = new Array(m + 1);
|
|
1011
|
-
for (let i2 = 0; i2 <= m; i2++) {
|
|
1012
|
-
const row = new Int32Array(n + 1);
|
|
1013
|
-
row[0] = i2 * INDEL;
|
|
1014
|
-
dp[i2] = row;
|
|
1015
|
-
}
|
|
1016
|
-
const firstRow = dp[0];
|
|
1017
|
-
for (let j2 = 0; j2 <= n; j2++) firstRow[j2] = j2 * INDEL;
|
|
1018
|
-
for (let i2 = 1; i2 <= m; i2++) {
|
|
1019
|
-
const row = dp[i2];
|
|
1020
|
-
const prev = dp[i2 - 1];
|
|
1021
|
-
for (let j2 = 1; j2 <= n; j2++) {
|
|
1022
|
-
const { cost } = matchCost(llm[i2 - 1], asr[j2 - 1]);
|
|
1023
|
-
const sub = prev[j2 - 1] + cost;
|
|
1024
|
-
const ins2 = prev[j2] + INDEL;
|
|
1025
|
-
const del2 = row[j2 - 1] + INDEL;
|
|
1026
|
-
row[j2] = Math.min(sub, ins2, del2);
|
|
1027
|
-
}
|
|
1028
|
-
}
|
|
1029
|
-
const ops = [];
|
|
1030
|
-
let i = m;
|
|
1031
|
-
let j = n;
|
|
1032
|
-
let exact = 0;
|
|
1033
|
-
let fuzzy = 0;
|
|
1034
|
-
let subs = 0;
|
|
1035
|
-
let ins = 0;
|
|
1036
|
-
let del = 0;
|
|
1037
|
-
while (i > 0 || j > 0) {
|
|
1038
|
-
const cur = dp[i];
|
|
1039
|
-
if (i > 0 && j > 0) {
|
|
1040
|
-
const { cost } = matchCost(llm[i - 1], asr[j - 1]);
|
|
1041
|
-
const sub = dp[i - 1][j - 1] + cost;
|
|
1042
|
-
if (cur[j] === sub) {
|
|
1043
|
-
if (cost === 0) {
|
|
1044
|
-
ops.push({ type: "match", llm: i - 1, asr: j - 1, fuzzy: false });
|
|
1045
|
-
exact++;
|
|
1046
|
-
} else if (cost === 1) {
|
|
1047
|
-
ops.push({ type: "match", llm: i - 1, asr: j - 1, fuzzy: true });
|
|
1048
|
-
fuzzy++;
|
|
1049
|
-
} else {
|
|
1050
|
-
ops.push({ type: "substitute", llm: i - 1, asr: j - 1 });
|
|
1051
|
-
subs++;
|
|
1052
|
-
}
|
|
1053
|
-
i--;
|
|
1054
|
-
j--;
|
|
1055
|
-
continue;
|
|
1056
|
-
}
|
|
1057
|
-
}
|
|
1058
|
-
if (i > 0 && cur[j] === dp[i - 1][j] + INDEL) {
|
|
1059
|
-
ops.push({ type: "insert", llm: i - 1 });
|
|
1060
|
-
ins++;
|
|
1061
|
-
i--;
|
|
1062
|
-
continue;
|
|
1063
|
-
}
|
|
1064
|
-
ops.push({ type: "delete", asr: j - 1 });
|
|
1065
|
-
del++;
|
|
1066
|
-
j--;
|
|
1067
|
-
}
|
|
1068
|
-
ops.reverse();
|
|
1069
|
-
return {
|
|
1070
|
-
ops,
|
|
1071
|
-
exactMatches: exact,
|
|
1072
|
-
fuzzyMatches: fuzzy,
|
|
1073
|
-
substitutions: subs,
|
|
1074
|
-
insertions: ins,
|
|
1075
|
-
deletions: del
|
|
1076
|
-
};
|
|
1077
|
-
}
|
|
1078
|
-
|
|
1079
|
-
// src/align/aligner.ts
|
|
1080
|
-
function toAsrTokens(words) {
|
|
1081
|
-
return words.map((w) => ({
|
|
1082
|
-
text: w.text,
|
|
1083
|
-
start: w.start,
|
|
1084
|
-
end: w.end,
|
|
1085
|
-
norm: w.text.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "")
|
|
1086
|
-
}));
|
|
1087
|
-
}
|
|
1088
|
-
function transferTiming(llm, asr, ops) {
|
|
1089
|
-
const times = llm.map(() => ({ start: NaN, end: NaN, matched: false }));
|
|
1090
|
-
for (const op of ops) {
|
|
1091
|
-
if (op.type === "match" || op.type === "substitute") {
|
|
1092
|
-
const a = asr[op.asr];
|
|
1093
|
-
times[op.llm] = { start: a.start, end: a.end, matched: op.type === "match" && !op.fuzzy };
|
|
1094
|
-
}
|
|
1095
|
-
}
|
|
1096
|
-
for (let k = 0; k < times.length; k++) {
|
|
1097
|
-
if (!isNaN(times[k].start)) continue;
|
|
1098
|
-
let prevEnd = null;
|
|
1099
|
-
for (let p = k - 1; p >= 0; p--) {
|
|
1100
|
-
if (!isNaN(times[p].start)) {
|
|
1101
|
-
prevEnd = times[p].end;
|
|
1102
|
-
break;
|
|
1103
|
-
}
|
|
1104
|
-
}
|
|
1105
|
-
let nextStart = null;
|
|
1106
|
-
for (let q = k + 1; q < times.length; q++) {
|
|
1107
|
-
if (!isNaN(times[q].start)) {
|
|
1108
|
-
nextStart = times[q].start;
|
|
1109
|
-
break;
|
|
1110
|
-
}
|
|
1111
|
-
}
|
|
1112
|
-
if (prevEnd !== null && nextStart !== null) {
|
|
1113
|
-
const segIdx = llm[k].segIdx;
|
|
1114
|
-
let runLen = 0;
|
|
1115
|
-
for (let r = k; r < times.length && isNaN(times[r].start) && llm[r].segIdx === segIdx; r++)
|
|
1116
|
-
runLen++;
|
|
1117
|
-
const step = (nextStart - prevEnd) / (runLen + 1);
|
|
1118
|
-
for (let r = 0; r < runLen; r++) {
|
|
1119
|
-
const pt = prevEnd + step * (r + 1);
|
|
1120
|
-
times[k + r] = { start: pt, end: pt, matched: false };
|
|
1121
|
-
}
|
|
1122
|
-
k += runLen - 1;
|
|
1123
|
-
} else if (nextStart !== null) {
|
|
1124
|
-
times[k] = { start: nextStart, end: nextStart, matched: false };
|
|
1125
|
-
} else if (prevEnd !== null) {
|
|
1126
|
-
times[k] = { start: prevEnd, end: prevEnd, matched: false };
|
|
1127
|
-
}
|
|
1128
|
-
}
|
|
1129
|
-
return times;
|
|
1130
|
-
}
|
|
1131
|
-
function alignSegments(llmSegments, asrWords, opts2 = {}) {
|
|
1132
|
-
const confThreshold = opts2.confidenceThreshold ?? 0.5;
|
|
1133
|
-
const margin = opts2.timeMarginSec ?? 0;
|
|
1134
|
-
const sorted = [...llmSegments].map((s, i) => ({ s, i })).sort((a, b) => a.s.startSec - b.s.startSec);
|
|
1135
|
-
const flat = [];
|
|
1136
|
-
const segRanges = [];
|
|
1137
|
-
for (const { s, i } of sorted) {
|
|
1138
|
-
const toks = tokenize(s.text);
|
|
1139
|
-
const start = flat.length;
|
|
1140
|
-
for (const t of toks) flat.push({ original: t.original, norm: t.norm, segIdx: i });
|
|
1141
|
-
segRanges.push({ src: i, start, end: flat.length });
|
|
1142
|
-
}
|
|
1143
|
-
if (flat.length === 0 || asrWords.length === 0) {
|
|
1144
|
-
return sorted.map(({ s, i }) => ({
|
|
1145
|
-
speaker: s.speaker,
|
|
1146
|
-
start: s.startSec,
|
|
1147
|
-
end: s.endSec,
|
|
1148
|
-
text: s.text,
|
|
1149
|
-
tone: s.tone,
|
|
1150
|
-
confidence: 0,
|
|
1151
|
-
timingSource: "coarse",
|
|
1152
|
-
words: [],
|
|
1153
|
-
sourceIndex: i
|
|
1154
|
-
}));
|
|
1155
|
-
}
|
|
1156
|
-
let asr = toAsrTokens(asrWords);
|
|
1157
|
-
if (margin > 0) {
|
|
1158
|
-
const lo = sorted[0].s.startSec - margin;
|
|
1159
|
-
const hi = sorted[sorted.length - 1].s.endSec + margin;
|
|
1160
|
-
asr = asr.filter((w) => w.end >= lo && w.start <= hi);
|
|
1161
|
-
}
|
|
1162
|
-
const result = alignWords(flat, asr);
|
|
1163
|
-
const times = transferTiming(flat, asr, result.ops);
|
|
1164
|
-
if (process.env.ALIGN_DEBUG) {
|
|
1165
|
-
console.error(
|
|
1166
|
-
`[align] flat=${flat.length} asr=${asr.length} exact=${result.exactMatches} fuzzy=${result.fuzzyMatches} subs=${result.substitutions} ins=${result.insertions} del=${result.deletions}`
|
|
1167
|
-
);
|
|
1168
|
-
}
|
|
1169
|
-
const out = [];
|
|
1170
|
-
for (let si = 0; si < sorted.length; si++) {
|
|
1171
|
-
const { s, i } = sorted[si];
|
|
1172
|
-
const range = segRanges[si];
|
|
1173
|
-
const segTimes = times.slice(range.start, range.end);
|
|
1174
|
-
const segOps = result.ops.filter(
|
|
1175
|
-
(op) => (op.type === "match" || op.type === "substitute") && op.llm >= range.start && op.llm < range.end
|
|
1176
|
-
);
|
|
1177
|
-
const exact = segOps.filter((op) => op.type === "match" && !op.fuzzy).length;
|
|
1178
|
-
const tokenCount = range.end - range.start;
|
|
1179
|
-
const firstTimed = segTimes.find((t) => !isNaN(t.start));
|
|
1180
|
-
const lastTimed = [...segTimes].reverse().find((t) => !isNaN(t.end));
|
|
1181
|
-
let start;
|
|
1182
|
-
let end;
|
|
1183
|
-
let timingSource;
|
|
1184
|
-
const confidence = tokenCount ? exact / tokenCount : 0;
|
|
1185
|
-
if (firstTimed && lastTimed) {
|
|
1186
|
-
start = firstTimed.start;
|
|
1187
|
-
end = lastTimed.end;
|
|
1188
|
-
timingSource = confidence >= confThreshold ? "aligned" : "interpolated";
|
|
1189
|
-
} else {
|
|
1190
|
-
start = s.startSec;
|
|
1191
|
-
end = s.endSec;
|
|
1192
|
-
timingSource = "coarse";
|
|
1193
|
-
}
|
|
1194
|
-
const words = segTimes.map((t, idx) => ({
|
|
1195
|
-
text: flat[range.start + idx].original,
|
|
1196
|
-
start: isNaN(t.start) ? start : t.start,
|
|
1197
|
-
end: isNaN(t.end) ? end : t.end,
|
|
1198
|
-
matched: t.matched
|
|
1199
|
-
}));
|
|
1200
|
-
out.push({
|
|
1201
|
-
speaker: s.speaker,
|
|
1202
|
-
start,
|
|
1203
|
-
end,
|
|
1204
|
-
text: s.text,
|
|
1205
|
-
tone: s.tone,
|
|
1206
|
-
confidence,
|
|
1207
|
-
timingSource,
|
|
1208
|
-
words,
|
|
1209
|
-
sourceIndex: i
|
|
1210
|
-
});
|
|
1211
|
-
}
|
|
1212
|
-
return out;
|
|
1213
|
-
}
|
|
1214
|
-
|
|
1215
|
-
// src/align/fill-gaps.ts
|
|
1216
|
-
var MIN_GAP_SEC = 0.8;
|
|
1217
|
-
var MIN_WORDS = 1;
|
|
1218
|
-
function normSet(text) {
|
|
1219
|
-
return new Set(tokenize(text).map((t) => t.norm));
|
|
1220
|
-
}
|
|
1221
|
-
function fillAsrGaps(segments, asrWords, asrUtterances) {
|
|
1222
|
-
if (!asrWords.length) return segments;
|
|
1223
|
-
const sorted = [...segments].sort((a, b) => a.start - b.start);
|
|
1224
|
-
const ranges = [];
|
|
1225
|
-
const firstStart = sorted.length ? sorted[0].start : asrWords[asrWords.length - 1].end;
|
|
1226
|
-
if (firstStart > 0) ranges.push([0, firstStart, sorted[0]]);
|
|
1227
|
-
for (let i = 0; i < sorted.length - 1; i++) {
|
|
1228
|
-
const cur = sorted[i];
|
|
1229
|
-
const next = sorted[i + 1];
|
|
1230
|
-
if (next.start > cur.end) ranges.push([cur.end, next.start, next]);
|
|
1231
|
-
}
|
|
1232
|
-
const filled = [];
|
|
1233
|
-
for (const [gs, ge, following] of ranges) {
|
|
1234
|
-
if (ge - gs < MIN_GAP_SEC) continue;
|
|
1235
|
-
const words = asrWords.filter((w) => w.start >= gs && w.start < ge);
|
|
1236
|
-
if (words.length < MIN_WORDS) continue;
|
|
1237
|
-
if (following) {
|
|
1238
|
-
const followingWords = normSet(following.text);
|
|
1239
|
-
const gapNorms = words.map(
|
|
1240
|
-
(w) => w.text.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "")
|
|
1241
|
-
);
|
|
1242
|
-
const covered = gapNorms.filter((n) => n && followingWords.has(n)).length;
|
|
1243
|
-
if (covered / gapNorms.filter(Boolean).length >= 0.6) continue;
|
|
1244
|
-
}
|
|
1245
|
-
let bestSp = asrUtterances[0]?.speaker || "speaker_?";
|
|
1246
|
-
let bestOv = 0;
|
|
1247
|
-
for (const u of asrUtterances) {
|
|
1248
|
-
const ov = Math.max(0, Math.min(ge, u.end) - Math.max(gs, u.start));
|
|
1249
|
-
if (ov > bestOv) {
|
|
1250
|
-
bestOv = ov;
|
|
1251
|
-
bestSp = u.speaker;
|
|
1252
|
-
}
|
|
1253
|
-
}
|
|
1254
|
-
filled.push({
|
|
1255
|
-
speaker: bestSp,
|
|
1256
|
-
start: words[0].start,
|
|
1257
|
-
end: words[words.length - 1].end,
|
|
1258
|
-
text: words.map((w) => w.text).join(" "),
|
|
1259
|
-
tone: [],
|
|
1260
|
-
confidence: 0,
|
|
1261
|
-
timingSource: "timestamped",
|
|
1262
|
-
words: words.map((w) => ({ text: w.text, start: w.start, end: w.end, matched: true })),
|
|
1263
|
-
sourceIndex: -1
|
|
1264
|
-
});
|
|
1265
|
-
}
|
|
1266
|
-
if (!filled.length) return sorted;
|
|
1267
|
-
return [...sorted, ...filled].sort((a, b) => a.start - b.start);
|
|
1268
|
-
}
|
|
1269
|
-
|
|
1270
|
-
// src/diarize/consistency.ts
|
|
1271
|
-
function overlap(s1, e1, s2, e2) {
|
|
1272
|
-
return Math.max(0, Math.min(e1, e2) - Math.max(s1, s2));
|
|
1273
|
-
}
|
|
1274
|
-
function isGenericLabel(label) {
|
|
1275
|
-
return /^(speaker\s+[a-z0-9]+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(label.trim());
|
|
1276
|
-
}
|
|
1277
|
-
function assignGlobalSpeakers(segments, asrUtterances, opts2 = {}) {
|
|
1278
|
-
const hasDiarization = opts2.hasDiarization ?? true;
|
|
1279
|
-
const out = segments.map((seg) => ({ seg, asrSpeaker: "" }));
|
|
1280
|
-
const labelVotes = {};
|
|
1281
|
-
const asrDuration = {};
|
|
1282
|
-
for (const o of out) {
|
|
1283
|
-
let bestSpeaker = "";
|
|
1284
|
-
let bestOverlap = 0;
|
|
1285
|
-
if (hasDiarization) {
|
|
1286
|
-
for (const u of asrUtterances) {
|
|
1287
|
-
const ov = overlap(o.seg.start, o.seg.end, u.start, u.end);
|
|
1288
|
-
if (ov > bestOverlap) {
|
|
1289
|
-
bestOverlap = ov;
|
|
1290
|
-
bestSpeaker = u.speaker;
|
|
1291
|
-
}
|
|
1292
|
-
}
|
|
1293
|
-
if (!bestSpeaker) {
|
|
1294
|
-
let bestDist = Infinity;
|
|
1295
|
-
const segMid = (o.seg.start + o.seg.end) / 2;
|
|
1296
|
-
for (const u of asrUtterances) {
|
|
1297
|
-
const uMid = (u.start + u.end) / 2;
|
|
1298
|
-
const d = Math.abs(uMid - segMid);
|
|
1299
|
-
if (d < bestDist) {
|
|
1300
|
-
bestDist = d;
|
|
1301
|
-
bestSpeaker = u.speaker;
|
|
1302
|
-
}
|
|
1303
|
-
}
|
|
1304
|
-
bestSpeaker = bestSpeaker || "speaker_?";
|
|
1305
|
-
}
|
|
1306
|
-
} else {
|
|
1307
|
-
bestSpeaker = o.seg.speaker || "speaker_?";
|
|
1308
|
-
bestOverlap = o.seg.end - o.seg.start;
|
|
1309
|
-
}
|
|
1310
|
-
o.asrSpeaker = bestSpeaker;
|
|
1311
|
-
asrDuration[o.asrSpeaker] = (asrDuration[o.asrSpeaker] ?? 0) + Math.max(bestOverlap, 0.1);
|
|
1312
|
-
labelVotes[o.asrSpeaker] ??= {};
|
|
1313
|
-
labelVotes[o.asrSpeaker][o.seg.speaker] = (labelVotes[o.asrSpeaker][o.seg.speaker] ?? 0) + 1;
|
|
1314
|
-
}
|
|
1315
|
-
const dominantLabel = {};
|
|
1316
|
-
for (const [asrSp, votes] of Object.entries(labelVotes)) {
|
|
1317
|
-
const best = Object.entries(votes).sort((a, b) => b[1] - a[1])[0];
|
|
1318
|
-
dominantLabel[asrSp] = best ? best[0] : asrSp;
|
|
1319
|
-
}
|
|
1320
|
-
const asrToGroup = {};
|
|
1321
|
-
const groupLabel = {};
|
|
1322
|
-
const groupTalk = {};
|
|
1323
|
-
const groupAsrVoices = {};
|
|
1324
|
-
for (const asrSp of Object.keys(labelVotes)) {
|
|
1325
|
-
const label = dominantLabel[asrSp] ?? asrSp;
|
|
1326
|
-
let groupId;
|
|
1327
|
-
if (!isGenericLabel(label)) {
|
|
1328
|
-
groupId = Object.keys(groupLabel).find((g) => groupLabel[g] === label);
|
|
1329
|
-
}
|
|
1330
|
-
if (!groupId) {
|
|
1331
|
-
groupId = asrSp;
|
|
1332
|
-
groupLabel[groupId] = label;
|
|
1333
|
-
}
|
|
1334
|
-
asrToGroup[asrSp] = groupId;
|
|
1335
|
-
groupTalk[groupId] = (groupTalk[groupId] ?? 0) + (asrDuration[asrSp] ?? 0);
|
|
1336
|
-
(groupAsrVoices[groupId] ??= []).push(asrSp);
|
|
1337
|
-
}
|
|
1338
|
-
const groupsByTalk = Object.keys(groupTalk).sort((a, b) => groupTalk[b] - groupTalk[a]);
|
|
1339
|
-
const groupToGlobal = {};
|
|
1340
|
-
groupsByTalk.forEach((g, i) => {
|
|
1341
|
-
groupToGlobal[g] = `Speaker ${String.fromCharCode(65 + i)}`;
|
|
1342
|
-
});
|
|
1343
|
-
const displayNames = {};
|
|
1344
|
-
for (const g of groupsByTalk) {
|
|
1345
|
-
const label = groupLabel[g];
|
|
1346
|
-
displayNames[groupToGlobal[g]] = isGenericLabel(label) ? groupToGlobal[g] : label;
|
|
1347
|
-
}
|
|
1348
|
-
const llmLabelToAsr = {};
|
|
1349
|
-
for (const o of out) {
|
|
1350
|
-
llmLabelToAsr[o.seg.speaker] = groupToGlobal[asrToGroup[o.asrSpeaker]];
|
|
1351
|
-
}
|
|
1352
|
-
const updated = out.map((o) => {
|
|
1353
|
-
const global = groupToGlobal[asrToGroup[o.asrSpeaker]];
|
|
1354
|
-
return {
|
|
1355
|
-
...o.seg,
|
|
1356
|
-
speaker: global,
|
|
1357
|
-
speakerName: displayNames[global] || global
|
|
1358
|
-
};
|
|
1359
|
-
});
|
|
1360
|
-
const speakerMap = {};
|
|
1361
|
-
for (const s of updated) {
|
|
1362
|
-
speakerMap[s.speaker] ??= { count: 0, talk: 0 };
|
|
1363
|
-
speakerMap[s.speaker].count++;
|
|
1364
|
-
speakerMap[s.speaker].talk += s.end - s.start;
|
|
1365
|
-
}
|
|
1366
|
-
const globalAsrVoices = {};
|
|
1367
|
-
for (const [g, voices] of Object.entries(groupAsrVoices)) {
|
|
1368
|
-
globalAsrVoices[groupToGlobal[g]] = voices;
|
|
1369
|
-
}
|
|
1370
|
-
const speakers = Object.entries(speakerMap).map(([id, v]) => ({
|
|
1371
|
-
id,
|
|
1372
|
-
name: displayNames[id],
|
|
1373
|
-
segmentCount: v.count,
|
|
1374
|
-
talkTime: v.talk,
|
|
1375
|
-
asrVoices: globalAsrVoices[id]
|
|
1376
|
-
})).filter((s) => s.talkTime > 0).sort((a, b) => (b.talkTime ?? 0) - (a.talkTime ?? 0));
|
|
1377
|
-
return { segments: updated, speakers, displayNames, llmLabelToAsr };
|
|
1378
|
-
}
|
|
1379
|
-
|
|
1380
|
-
// src/providers/openai-compat.ts
|
|
1381
|
-
var PROVIDER_BASE = {
|
|
1382
|
-
deepseek: "https://api.deepseek.com/v1",
|
|
1383
|
-
groq: "https://api.groq.com/openai/v1",
|
|
1384
|
-
openai: "https://api.openai.com/v1"
|
|
1385
|
-
};
|
|
1386
|
-
var OpenAICompatClient = class _OpenAICompatClient {
|
|
1387
|
-
constructor(baseUrl, apiKey, defaultModel, providerName = "openai-compat") {
|
|
1388
|
-
this.baseUrl = baseUrl;
|
|
1389
|
-
this.apiKey = apiKey;
|
|
1390
|
-
this.defaultModel = defaultModel;
|
|
1391
|
-
this.providerName = providerName;
|
|
1392
|
-
}
|
|
1393
|
-
baseUrl;
|
|
1394
|
-
apiKey;
|
|
1395
|
-
defaultModel;
|
|
1396
|
-
providerName;
|
|
1397
|
-
static fromProvider(provider, apiKey, defaultModel) {
|
|
1398
|
-
const base = PROVIDER_BASE[provider] ?? provider;
|
|
1399
|
-
return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
|
|
1400
|
-
}
|
|
1401
|
-
async chat(model, messages, opts2 = {}) {
|
|
1402
|
-
const m = model ?? this.defaultModel;
|
|
1403
|
-
const maxRetries = opts2.maxRetries ?? 2;
|
|
1404
|
-
const body = {
|
|
1405
|
-
model: m,
|
|
1406
|
-
messages,
|
|
1407
|
-
temperature: opts2.temperature ?? 0.2
|
|
1408
|
-
};
|
|
1409
|
-
if (opts2.maxTokens) body.max_tokens = opts2.maxTokens;
|
|
1410
|
-
if (opts2.responseJson) {
|
|
1411
|
-
body.response_format = { type: "json_object" };
|
|
1412
|
-
}
|
|
1413
|
-
let lastError;
|
|
1414
|
-
const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
|
|
1415
|
-
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
1416
|
-
const t0 = Date.now();
|
|
1417
|
-
try {
|
|
1418
|
-
const res = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
1419
|
-
method: "POST",
|
|
1420
|
-
headers: {
|
|
1421
|
-
"Content-Type": "application/json",
|
|
1422
|
-
Authorization: `Bearer ${this.apiKey}`
|
|
1423
|
-
},
|
|
1424
|
-
body: JSON.stringify(body)
|
|
1425
|
-
});
|
|
1426
|
-
if (!res.ok) {
|
|
1427
|
-
const txt = await res.text();
|
|
1428
|
-
throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
|
|
1429
|
-
}
|
|
1430
|
-
const data = await res.json();
|
|
1431
|
-
const text = data.choices?.[0]?.message?.content ?? "";
|
|
1432
|
-
const usage = {
|
|
1433
|
-
inputTokens: data.usage?.prompt_tokens ?? 0,
|
|
1434
|
-
outputTokens: data.usage?.completion_tokens ?? 0
|
|
1435
|
-
};
|
|
1436
|
-
logLlmCall({
|
|
1437
|
-
ts: new Date(t0).toISOString(),
|
|
1438
|
-
provider: this.providerName,
|
|
1439
|
-
model: m,
|
|
1440
|
-
kind: opts2.logKind,
|
|
1441
|
-
prompt: promptStr,
|
|
1442
|
-
response: text,
|
|
1443
|
-
usage,
|
|
1444
|
-
durationMs: Date.now() - t0,
|
|
1445
|
-
attempt: attempt + 1
|
|
1446
|
-
});
|
|
1447
|
-
return { text, usage };
|
|
1448
|
-
} catch (err) {
|
|
1449
|
-
lastError = err instanceof Error ? err.message : String(err);
|
|
1450
|
-
logLlmCall({
|
|
1451
|
-
ts: new Date(t0).toISOString(),
|
|
1452
|
-
provider: this.providerName,
|
|
1453
|
-
model: m,
|
|
1454
|
-
kind: opts2.logKind,
|
|
1455
|
-
prompt: promptStr,
|
|
1456
|
-
response: "",
|
|
1457
|
-
durationMs: Date.now() - t0,
|
|
1458
|
-
attempt: attempt + 1,
|
|
1459
|
-
error: lastError
|
|
1460
|
-
});
|
|
1461
|
-
if (attempt < maxRetries - 1) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
|
|
1462
|
-
}
|
|
1463
|
-
}
|
|
1464
|
-
return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
|
|
1465
|
-
}
|
|
1466
|
-
async chatJson(model, messages, opts2 = {}) {
|
|
1467
|
-
const res = await this.chat(model, messages, { ...opts2, responseJson: true });
|
|
1468
|
-
if (res.error || !res.text) return { data: null, raw: res.text, error: res.error };
|
|
1469
|
-
try {
|
|
1470
|
-
let txt = res.text.trim();
|
|
1471
|
-
const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
|
|
1472
|
-
if (fence && fence[1]) txt = fence[1];
|
|
1473
|
-
return { data: JSON.parse(txt), raw: res.text };
|
|
1474
|
-
} catch (err) {
|
|
1475
|
-
return { data: null, raw: res.text, error: `JSON parse: ${err instanceof Error ? err.message : String(err)}` };
|
|
1476
|
-
}
|
|
1477
|
-
}
|
|
1478
|
-
};
|
|
1479
|
-
|
|
1480
|
-
// src/diarize/identify.ts
|
|
1481
|
-
function buildTranscriptExcerpt(segments, speakers) {
|
|
1482
|
-
const bySpeaker = {};
|
|
1483
|
-
for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
|
|
1484
|
-
const parts = [];
|
|
1485
|
-
for (const sp of speakers) {
|
|
1486
|
-
const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
|
|
1487
|
-
const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
|
|
1488
|
-
parts.push(
|
|
1489
|
-
`### ${sp.id} (${sp.name || "unknown"}, ${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s${voices})`
|
|
1490
|
-
);
|
|
1491
|
-
for (const s of segs) parts.push(` ${s.text}`);
|
|
1492
|
-
}
|
|
1493
|
-
return parts.join("\n");
|
|
1494
|
-
}
|
|
1495
|
-
function identifyPrompt(transcriptExcerpt, roster, knownSpeakers) {
|
|
1496
|
-
return `You are identifying speakers in a transcribed recording. Below are the most substantial quotes from each speaker (labeled exactly as shown in the headers, e.g. "Speaker A"), plus a roster description.
|
|
1497
|
-
|
|
1498
|
-
Identify each speaker by name and/or role using content cues: self-introductions ("my name is X"), references to themselves, their role, or context. If you cannot confidently identify a speaker, leave the name empty ("").
|
|
1499
|
-
|
|
1500
|
-
${knownSpeakers && knownSpeakers.length ? `Known possible speakers: ${knownSpeakers.join(", ")}
|
|
1501
|
-
` : ""}ROSTER:
|
|
1502
|
-
${roster}
|
|
1503
|
-
|
|
1504
|
-
TRANSCRIPT EXCERPTS BY SPEAKER:
|
|
1505
|
-
${transcriptExcerpt}
|
|
1506
|
-
|
|
1507
|
-
Respond as JSON: { "speakers": [ { "id": "<exact speaker id from the headers>", "name": "Full Name or Role", "confidence": "high|medium|low", "evidence": "short quote/reason" } ], "reasoning": "one-paragraph summary" }
|
|
1508
|
-
Use the EXACT speaker id strings from the headers above (e.g. "Speaker A").`;
|
|
1509
|
-
}
|
|
1510
|
-
async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers) {
|
|
1511
|
-
const excerpt = buildTranscriptExcerpt(segments, speakers);
|
|
1512
|
-
const { data, error } = await client.chatJson(
|
|
1513
|
-
model,
|
|
1514
|
-
[{ role: "user", content: identifyPrompt(excerpt, roster, knownSpeakers) }],
|
|
1515
|
-
{ temperature: 0.1, maxTokens: 2e3, logKind: "identify" }
|
|
1516
|
-
);
|
|
1517
|
-
if (error || !data) {
|
|
1518
|
-
return { nameMap: {}, speakers: [], reasoning: error || "no response" };
|
|
1519
|
-
}
|
|
1520
|
-
const nameMap = {};
|
|
1521
|
-
for (const s of data.speakers || []) {
|
|
1522
|
-
if (s.name && s.name.trim()) nameMap[s.id] = s.name.trim();
|
|
1523
|
-
}
|
|
1524
|
-
return { nameMap, speakers: data.speakers || [], reasoning: data.reasoning || "" };
|
|
1525
|
-
}
|
|
1526
|
-
|
|
1527
|
-
// src/finalize/finalize.ts
|
|
1528
|
-
var MIN_DUR = 0.5;
|
|
1529
|
-
var MAX_DUR = 7;
|
|
1530
|
-
var OVERLAP_GAP = 0.05;
|
|
1531
|
-
function textSimilarity(a, b) {
|
|
1532
|
-
const ta = new Set(tokenize(a).map((t) => t.norm));
|
|
1533
|
-
const tb = new Set(tokenize(b).map((t) => t.norm));
|
|
1534
|
-
if (ta.size === 0 && tb.size === 0) return 1;
|
|
1535
|
-
if (ta.size === 0 || tb.size === 0) return 0;
|
|
1536
|
-
let inter = 0;
|
|
1537
|
-
for (const t of ta) if (tb.has(t)) inter++;
|
|
1538
|
-
return inter / (ta.size + tb.size - inter);
|
|
1539
|
-
}
|
|
1540
|
-
function timeOverlapFrac(a, b) {
|
|
1541
|
-
const ov = Math.max(0, Math.min(a.end, b.end) - Math.max(a.start, b.start));
|
|
1542
|
-
const shorter = Math.min(a.end - a.start, b.end - b.start);
|
|
1543
|
-
return shorter > 0 ? ov / shorter : 0;
|
|
1544
|
-
}
|
|
1545
|
-
function dedupSegments(segments) {
|
|
1546
|
-
const sorted = [...segments].sort((a, b) => a.start - b.start);
|
|
1547
|
-
const kept = [];
|
|
1548
|
-
for (const seg of sorted) {
|
|
1549
|
-
const dup = kept.find(
|
|
1550
|
-
(k) => k.speaker === seg.speaker && textSimilarity(k.text, seg.text) > 0.7 && timeOverlapFrac(k, seg) > 0.2
|
|
1551
|
-
);
|
|
1552
|
-
if (dup) {
|
|
1553
|
-
if (seg.confidence > dup.confidence) {
|
|
1554
|
-
Object.assign(dup, seg);
|
|
1555
|
-
}
|
|
1556
|
-
continue;
|
|
1557
|
-
}
|
|
1558
|
-
kept.push(seg);
|
|
1559
|
-
}
|
|
1560
|
-
return kept;
|
|
1561
|
-
}
|
|
1562
|
-
function fixOverlaps(segments) {
|
|
1563
|
-
if (segments.length === 0) return segments;
|
|
1564
|
-
const sorted = [...segments].sort((a, b) => a.start - b.start);
|
|
1565
|
-
for (let pass = 0; pass < 10; pass++) {
|
|
1566
|
-
let changed = false;
|
|
1567
|
-
for (let i = 0; i < sorted.length - 1; i++) {
|
|
1568
|
-
const cur = sorted[i];
|
|
1569
|
-
const next = sorted[i + 1];
|
|
1570
|
-
if (cur.end > next.start) {
|
|
1571
|
-
const targetEnd = next.start - OVERLAP_GAP;
|
|
1572
|
-
const newDur = targetEnd - cur.start;
|
|
1573
|
-
if (newDur >= MIN_DUR) {
|
|
1574
|
-
cur.end = targetEnd;
|
|
1575
|
-
changed = true;
|
|
1576
|
-
} else {
|
|
1577
|
-
const shiftedStart = cur.end + OVERLAP_GAP;
|
|
1578
|
-
const followingStart = sorted[i + 2]?.start ?? Infinity;
|
|
1579
|
-
if (shiftedStart < next.end - MIN_DUR && shiftedStart < followingStart) {
|
|
1580
|
-
next.start = shiftedStart;
|
|
1581
|
-
changed = true;
|
|
1582
|
-
}
|
|
1583
|
-
}
|
|
1584
|
-
}
|
|
1585
|
-
}
|
|
1586
|
-
if (!changed) break;
|
|
1587
|
-
}
|
|
1588
|
-
return sorted;
|
|
1589
|
-
}
|
|
1590
|
-
function clampAndFix(segments) {
|
|
1591
|
-
for (const s of segments) {
|
|
1592
|
-
const dur = s.end - s.start;
|
|
1593
|
-
if (dur < MIN_DUR) s.end = s.start + MIN_DUR;
|
|
1594
|
-
else if (dur > MAX_DUR) s.end = s.start + MAX_DUR;
|
|
1595
|
-
}
|
|
1596
|
-
return fixOverlaps(segments);
|
|
1597
|
-
}
|
|
1598
|
-
function finalizeSegments(segments, opts2 = {}) {
|
|
1599
|
-
const minSeg = opts2.minSegmentSec ?? 0.2;
|
|
1600
|
-
let deduped = dedupSegments(segments);
|
|
1601
|
-
deduped = deduped.filter((s) => s.end - s.start >= minSeg && s.text.trim().length > 0);
|
|
1602
|
-
const out = deduped.map((s, i) => ({
|
|
1603
|
-
id: i + 1,
|
|
1604
|
-
start: s.start,
|
|
1605
|
-
end: s.end,
|
|
1606
|
-
speaker: s.speaker,
|
|
1607
|
-
speakerName: s.speakerName || s.speaker,
|
|
1608
|
-
// Collapse any internal whitespace (incl. newlines) so a stray blank line in the LLM
|
|
1609
|
-
// text can never split one SRT cue into several — SRT cues end at a blank line.
|
|
1610
|
-
text: s.text.trim().replace(/\s+/g, " "),
|
|
1611
|
-
tone: s.tone,
|
|
1612
|
-
timingSource: s.timingSource,
|
|
1613
|
-
confidence: s.confidence,
|
|
1614
|
-
words: s.words
|
|
1615
|
-
}));
|
|
1616
|
-
return clampAndFix(out);
|
|
1617
|
-
}
|
|
1618
|
-
|
|
1619
|
-
// src/finalize/format.ts
|
|
1620
|
-
var MAX_CHARS = 84;
|
|
1621
|
-
var MAX_BLOCK_SEC = 7;
|
|
1622
|
-
function splitIntoBlocks(seg) {
|
|
1623
|
-
const words = seg.words && seg.words.length > 0 ? seg.words : null;
|
|
1624
|
-
if (!words) {
|
|
1625
|
-
return [{ start: seg.start, end: seg.end, text: seg.text }];
|
|
1626
|
-
}
|
|
1627
|
-
const blocks = [];
|
|
1628
|
-
let curWords = [];
|
|
1629
|
-
let curLen = 0;
|
|
1630
|
-
const flush = () => {
|
|
1631
|
-
if (curWords.length === 0) return;
|
|
1632
|
-
const first = curWords[0];
|
|
1633
|
-
const last = curWords[curWords.length - 1];
|
|
1634
|
-
blocks.push({
|
|
1635
|
-
start: first.start,
|
|
1636
|
-
end: last.end,
|
|
1637
|
-
text: curWords.map((w) => w.text).join(" ")
|
|
1638
|
-
});
|
|
1639
|
-
curWords = [];
|
|
1640
|
-
curLen = 0;
|
|
1641
|
-
};
|
|
1642
|
-
for (const w of words) {
|
|
1643
|
-
const addLen = w.text.length + 1;
|
|
1644
|
-
const blockStart = curWords.length === 0 ? w.start : curWords[0].start;
|
|
1645
|
-
const wouldSec = w.end - blockStart;
|
|
1646
|
-
if (curLen + addLen > MAX_CHARS || wouldSec > MAX_BLOCK_SEC) {
|
|
1647
|
-
flush();
|
|
1648
|
-
}
|
|
1649
|
-
curWords.push(w);
|
|
1650
|
-
curLen += addLen;
|
|
1651
|
-
}
|
|
1652
|
-
flush();
|
|
1653
|
-
return blocks.length ? blocks : [{ start: seg.start, end: seg.end, text: seg.text }];
|
|
1654
|
-
}
|
|
1655
|
-
function formatSrt(result, opts2 = {}) {
|
|
1656
|
-
const labelSpeakers = opts2.labelSpeakers ?? true;
|
|
1657
|
-
const showTone = opts2.showTone ?? true;
|
|
1658
|
-
let idx = 1;
|
|
1659
|
-
const blocks = [];
|
|
1660
|
-
for (const seg of result.segments) {
|
|
1661
|
-
const tone = showTone && seg.tone && seg.tone.length ? ` (${seg.tone.join(", ")})` : "";
|
|
1662
|
-
const speaker = labelSpeakers ? `${seg.speakerName || seg.speaker}: ` : "";
|
|
1663
|
-
for (const b of splitIntoBlocks(seg)) {
|
|
1664
|
-
blocks.push(`${idx}
|
|
1665
|
-
${formatSrtTiming(b.start, b.end)}
|
|
1666
|
-
${speaker}${b.text}${tone}
|
|
1667
|
-
`);
|
|
1668
|
-
idx++;
|
|
1669
|
-
}
|
|
1670
|
-
}
|
|
1671
|
-
return blocks.join("\n");
|
|
1672
|
-
}
|
|
1673
|
-
function formatMarkdown(result, opts2 = {}) {
|
|
1674
|
-
const parts = [];
|
|
1675
|
-
parts.push(`# ${opts2.title || "Transcript"}
|
|
1676
|
-
`);
|
|
1677
|
-
parts.push(`*Duration: ${Math.round(result.metadata.duration)}s \xB7 Speakers: ${result.speakers.length}*
|
|
1678
|
-
`);
|
|
1679
|
-
parts.push("\n## Speakers\n");
|
|
1680
|
-
for (const s of result.speakers) {
|
|
1681
|
-
const talk = s.talkTime ? ` (${Math.round(s.talkTime)}s)` : "";
|
|
1682
|
-
parts.push(`- **${s.name || s.id}**${talk}`);
|
|
1683
|
-
}
|
|
1684
|
-
parts.push("\n## Transcript\n");
|
|
1685
|
-
for (const seg of result.segments) {
|
|
1686
|
-
const mm = Math.floor(seg.start / 60).toString().padStart(2, "0");
|
|
1687
|
-
const ss = Math.floor(seg.start % 60).toString().padStart(2, "0");
|
|
1688
|
-
const tone = seg.tone && seg.tone.length ? ` *(${seg.tone.join(", ")})*` : "";
|
|
1689
|
-
parts.push(`[${mm}:${ss}] **${seg.speakerName || seg.speaker}**${tone}: ${seg.text}
|
|
1690
|
-
`);
|
|
1691
|
-
}
|
|
1692
|
-
return parts.join("\n");
|
|
1693
|
-
}
|
|
1694
|
-
function formatJson(result) {
|
|
1695
|
-
return JSON.stringify(result, null, 2);
|
|
1696
|
-
}
|
|
1697
|
-
|
|
1698
|
-
// src/core/pipeline.ts
|
|
1699
|
-
var import_node_path5 = require("path");
|
|
1700
|
-
var JSON_OPTS = { encoding: "utf-8" };
|
|
1701
|
-
function readJson(p) {
|
|
1702
|
-
if (!(0, import_node_fs4.existsSync)(p)) return null;
|
|
1703
|
-
try {
|
|
1704
|
-
return JSON.parse((0, import_node_fs4.readFileSync)(p, JSON_OPTS));
|
|
1705
|
-
} catch {
|
|
1706
|
-
return null;
|
|
1707
|
-
}
|
|
1708
|
-
}
|
|
1709
|
-
function writeJson(p, data) {
|
|
1710
|
-
(0, import_node_fs4.writeFileSync)(p, JSON.stringify(data, null, 2), JSON_OPTS);
|
|
1711
|
-
}
|
|
1712
|
-
async function mapPool(items, limit, fn) {
|
|
1713
|
-
const results = new Array(items.length);
|
|
1714
|
-
let next = 0;
|
|
1715
|
-
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
1716
|
-
while (true) {
|
|
1717
|
-
const i = next++;
|
|
1718
|
-
if (i >= items.length) break;
|
|
1719
|
-
results[i] = await fn(items[i], i);
|
|
1720
|
-
}
|
|
1721
|
-
});
|
|
1722
|
-
await Promise.all(workers);
|
|
1723
|
-
return results;
|
|
1724
|
-
}
|
|
1725
|
-
function has(passes2, p) {
|
|
1726
|
-
return passes2.includes(p);
|
|
1727
|
-
}
|
|
1728
|
-
async function transcribe(opts2) {
|
|
1729
|
-
if (!opts2 || typeof opts2.input !== "string" || opts2.input.length === 0) {
|
|
1730
|
-
throw new Error(
|
|
1731
|
-
"transcribe(options): 'input' (path to the audio/video file) is required"
|
|
1732
|
-
);
|
|
1733
|
-
}
|
|
1734
|
-
const options = resolveOptions(opts2);
|
|
1735
|
-
const keys = resolveKeys(options.apiKeys);
|
|
1736
|
-
logger.setLevel(options.logLevel);
|
|
1737
|
-
if (!(0, import_node_fs4.existsSync)(options.input)) {
|
|
1738
|
-
throw new Error(`Input file not found: ${options.input}`);
|
|
1739
|
-
}
|
|
1740
|
-
(0, import_node_fs4.mkdirSync)(options.intermediatesDir, { recursive: true });
|
|
1741
|
-
(0, import_node_fs4.mkdirSync)(options.outputDir, { recursive: true });
|
|
1742
|
-
logger.info(
|
|
1743
|
-
`intermediates: ${(0, import_node_path5.resolve)(options.intermediatesDir)} (file://${(0, import_node_path5.resolve)(options.intermediatesDir)})`
|
|
1744
|
-
);
|
|
1745
|
-
setLlmLogPath(options.llmLog ? `${options.intermediatesDir}/llm-calls.jsonl` : null);
|
|
1746
|
-
const sourcePath = `${options.intermediatesDir}/source.json`;
|
|
1747
|
-
const sig = inputSignature(options.input);
|
|
1748
|
-
const cfgSig = configSignature(opts2);
|
|
1749
|
-
const prevSig = readJson(
|
|
1750
|
-
sourcePath
|
|
1751
|
-
);
|
|
1752
|
-
const inputChanged = !prevSig || prevSig.signature !== sig;
|
|
1753
|
-
const configChanged = !prevSig || prevSig.config !== cfgSig;
|
|
1754
|
-
if (inputChanged && prevSig) {
|
|
1755
|
-
logger.warn(
|
|
1756
|
-
`input file changed since last run (was ${prevSig.input ?? "?"}) \u2014 discarding cached intermediates`
|
|
1757
|
-
);
|
|
1758
|
-
} else if (configChanged && prevSig) {
|
|
1759
|
-
logger.warn(
|
|
1760
|
-
"options changed since last run (model / chunking / instructions / provider) \u2014 discarding cached intermediates"
|
|
1761
|
-
);
|
|
1762
|
-
}
|
|
1763
|
-
const forceAll = options.force || inputChanged || configChanged;
|
|
1764
|
-
writeJson(sourcePath, {
|
|
1765
|
-
input: options.input,
|
|
1766
|
-
signature: sig,
|
|
1767
|
-
config: cfgSig,
|
|
1768
|
-
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1769
|
-
});
|
|
1770
|
-
const passes2 = options.passes;
|
|
1771
|
-
const models = {
|
|
1772
|
-
transcribe: options.model ?? DEFAULT_TRANSCRIBE_MODEL,
|
|
1773
|
-
reasoner: options.reasoner ?? DEFAULT_REASONER_MODEL
|
|
1774
|
-
};
|
|
1775
|
-
if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
|
|
1776
|
-
if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
|
|
1777
|
-
const tsProvider = options.timestampedProvider ?? "assemblyai";
|
|
1778
|
-
const willTimestamp = has(passes2, "timestamped") || has(passes2, "align");
|
|
1779
|
-
if (willTimestamp) {
|
|
1780
|
-
if (tsProvider === "assemblyai" && !keys.assemblyai) {
|
|
1781
|
-
throw new Error(
|
|
1782
|
-
"ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
|
|
1783
|
-
);
|
|
1784
|
-
}
|
|
1785
|
-
if (tsProvider === "whisper-groq" && !keys.groq) {
|
|
1786
|
-
throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
|
|
1787
|
-
}
|
|
1788
|
-
}
|
|
1789
|
-
let probeInfo = null;
|
|
1790
|
-
const AUDIO_OPTS = { format: "mp3", bitrate: "64k" };
|
|
1791
|
-
const audioPath = `${options.intermediatesDir}/audio.mp3`;
|
|
1792
|
-
const probePath = `${options.intermediatesDir}/probe.json`;
|
|
1793
|
-
if (has(passes2, "preprocess")) {
|
|
1794
|
-
logger.info("=== preprocess ===");
|
|
1795
|
-
probeInfo = forceAll ? null : readJson(probePath);
|
|
1796
|
-
if (!probeInfo) {
|
|
1797
|
-
probeInfo = await probe(options.input);
|
|
1798
|
-
writeJson(probePath, probeInfo);
|
|
1799
|
-
}
|
|
1800
|
-
if (!(0, import_node_fs4.existsSync)(audioPath) || forceAll) {
|
|
1801
|
-
logger.info("extracting audio (mono 16kHz mp3)...");
|
|
1802
|
-
await extractAudio(options.input, audioPath, AUDIO_OPTS);
|
|
1803
|
-
}
|
|
1804
|
-
if (probeInfo.hasVideo) {
|
|
1805
|
-
const kfDir = `${options.intermediatesDir}/keyframes`;
|
|
1806
|
-
if (!(0, import_node_fs4.existsSync)(kfDir) || forceAll) {
|
|
1807
|
-
logger.info("extracting keyframes...");
|
|
1808
|
-
await extractKeyframes(options.input, kfDir, options.screenshotCount);
|
|
1809
|
-
}
|
|
1810
|
-
}
|
|
1811
|
-
} else {
|
|
1812
|
-
probeInfo = forceAll ? null : readJson(probePath);
|
|
1813
|
-
}
|
|
1814
|
-
if (!probeInfo) throw new Error("probe info missing (run preprocess)");
|
|
1815
|
-
const duration = probeInfo.duration;
|
|
1816
|
-
let description = null;
|
|
1817
|
-
if (has(passes2, "describe")) {
|
|
1818
|
-
const descPath = `${options.intermediatesDir}/description.json`;
|
|
1819
|
-
description = forceAll ? null : readJson(descPath);
|
|
1820
|
-
if (!description) {
|
|
1821
|
-
logger.info("=== describe ===");
|
|
1822
|
-
const client = new GeminiClient(keys.gemini);
|
|
1823
|
-
const samplePath = `${options.intermediatesDir}/sample.mp3`;
|
|
1824
|
-
if (!(0, import_node_fs4.existsSync)(samplePath) || forceAll) {
|
|
1825
|
-
await extractChunk(audioPath, samplePath, 0, Math.min(300, duration), AUDIO_OPTS);
|
|
1826
|
-
}
|
|
1827
|
-
const files = [{ path: samplePath }];
|
|
1828
|
-
const kfDir = `${options.intermediatesDir}/keyframes`;
|
|
1829
|
-
if ((0, import_node_fs4.existsSync)(kfDir)) {
|
|
1830
|
-
for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
|
|
1831
|
-
const p = `${kfDir}/${f}`;
|
|
1832
|
-
if ((0, import_node_fs4.existsSync)(p)) files.push({ path: p });
|
|
1833
|
-
}
|
|
1834
|
-
}
|
|
1835
|
-
description = await describeMeeting(
|
|
1836
|
-
client,
|
|
1837
|
-
models.transcribe,
|
|
1838
|
-
files,
|
|
1839
|
-
(0, import_node_path5.basename)(options.input),
|
|
1840
|
-
options.instructions
|
|
1841
|
-
);
|
|
1842
|
-
writeJson(descPath, description);
|
|
1843
|
-
logger.info(`description: ${description.description.slice(0, 120)}...`);
|
|
1844
|
-
}
|
|
1845
|
-
} else {
|
|
1846
|
-
description = forceAll ? null : readJson(`${options.intermediatesDir}/description.json`);
|
|
1847
|
-
}
|
|
1848
|
-
const needChunks = has(passes2, "llm-transcribe") || has(passes2, "align") || has(passes2, "consistency");
|
|
1849
|
-
let chunks = [];
|
|
1850
|
-
if (needChunks) {
|
|
1851
|
-
let silences = [];
|
|
1852
|
-
try {
|
|
1853
|
-
silences = await detectSilence(audioPath, { noiseDb: -15, minDuration: 0.3 });
|
|
1854
|
-
if (silences.length < 3)
|
|
1855
|
-
silences = await detectSilence(audioPath, { noiseDb: -12, minDuration: 0.25 });
|
|
1856
|
-
} catch {
|
|
1857
|
-
}
|
|
1858
|
-
chunks = planChunks(duration, options.chunkDurationSec, options.chunkOverlapSec);
|
|
1859
|
-
if (silences.length > 3) {
|
|
1860
|
-
chunks = chunks.map((c) => {
|
|
1861
|
-
const snapped = snapToSilence(
|
|
1862
|
-
c.start,
|
|
1863
|
-
silences,
|
|
1864
|
-
Math.min(10, options.chunkOverlapSec / 2)
|
|
1865
|
-
);
|
|
1866
|
-
return { ...c, start: snapped, trustedStart: snapped + c.overlapWithPrevious };
|
|
1867
|
-
});
|
|
1868
|
-
}
|
|
1869
|
-
}
|
|
1870
|
-
const tagWith = (r, chunk) => ({
|
|
1871
|
-
...r,
|
|
1872
|
-
segments: r.segments.map((s) => ({
|
|
1873
|
-
...s,
|
|
1874
|
-
chunkIndex: chunk.index,
|
|
1875
|
-
trustedStart: chunk.trustedStart
|
|
1876
|
-
}))
|
|
1877
|
-
});
|
|
1878
|
-
let llmChunkResults = [];
|
|
1879
|
-
if (has(passes2, "llm-transcribe")) {
|
|
1880
|
-
logger.info("=== llm-transcribe ===");
|
|
1881
|
-
let runChunks = chunks;
|
|
1882
|
-
if (options.onlyChunk !== void 0)
|
|
1883
|
-
runChunks = chunks.filter((c) => c.index === options.onlyChunk);
|
|
1884
|
-
logger.info(
|
|
1885
|
-
`${runChunks.length} chunks (${options.chunkDurationSec}s, ${options.chunkOverlapSec}s overlap)`
|
|
1886
|
-
);
|
|
1887
|
-
const client = new GeminiClient(keys.gemini);
|
|
1888
|
-
const llmDir = `${options.intermediatesDir}/llm`;
|
|
1889
|
-
(0, import_node_fs4.mkdirSync)(llmDir, { recursive: true });
|
|
1890
|
-
llmChunkResults = await mapPool(runChunks, options.concurrency, async (chunk) => {
|
|
1891
|
-
const parsedPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_parsed.json`;
|
|
1892
|
-
const cached = forceAll ? null : readJson(parsedPath);
|
|
1893
|
-
if (cached && cached.segments.length > 0) {
|
|
1894
|
-
logger.info(`chunk ${chunk.index}: cached (${cached.segments.length} segments)`);
|
|
1895
|
-
return tagWith(cached, chunk);
|
|
1896
|
-
}
|
|
1897
|
-
const chunkPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}.mp3`;
|
|
1898
|
-
if (!(0, import_node_fs4.existsSync)(chunkPath) || forceAll) {
|
|
1899
|
-
await extractChunk(audioPath, chunkPath, chunk.start, chunk.end, AUDIO_OPTS);
|
|
1900
|
-
}
|
|
1901
|
-
let previousTail;
|
|
1902
|
-
if (chunk.index > 0) {
|
|
1903
|
-
const prev = readJson(
|
|
1904
|
-
`${llmDir}/chunk_${String(chunk.index - 1).padStart(2, "0")}_parsed.json`
|
|
1905
|
-
);
|
|
1906
|
-
if (prev && prev.segments.length) {
|
|
1907
|
-
previousTail = prev.segments.slice(-6).map((s) => `${s.speaker}: ${s.text}`).join("\n");
|
|
1908
|
-
}
|
|
1909
|
-
}
|
|
1910
|
-
logger.info(
|
|
1911
|
-
`chunk ${chunk.index}: transcribing [${chunk.start.toFixed(0)}-${chunk.end.toFixed(0)}]s...`
|
|
1912
|
-
);
|
|
1913
|
-
const result2 = await transcribeChunk(
|
|
1914
|
-
client,
|
|
1915
|
-
models.transcribe,
|
|
1916
|
-
chunkPath,
|
|
1917
|
-
chunk.start,
|
|
1918
|
-
{
|
|
1919
|
-
index: chunk.index + 1,
|
|
1920
|
-
total: runChunks.length,
|
|
1921
|
-
description: description?.description,
|
|
1922
|
-
roster: description?.roster,
|
|
1923
|
-
previousTail,
|
|
1924
|
-
instructions: options.instructions
|
|
1925
|
-
},
|
|
1926
|
-
{ chunkDurationSec: chunk.end - chunk.start, validationRetries: 1 }
|
|
1927
|
-
);
|
|
1928
|
-
writeJson(parsedPath, result2);
|
|
1929
|
-
(0, import_node_fs4.writeFileSync)(
|
|
1930
|
-
`${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`,
|
|
1931
|
-
result2.raw
|
|
1932
|
-
);
|
|
1933
|
-
return tagWith(result2, chunk);
|
|
1934
|
-
});
|
|
1935
|
-
const errored = llmChunkResults.filter((r) => r.error);
|
|
1936
|
-
const producedSegments = llmChunkResults.reduce((n, r) => n + r.segments.length, 0);
|
|
1937
|
-
if (llmChunkResults.length > 0 && producedSegments === 0 && errored.length === llmChunkResults.length) {
|
|
1938
|
-
throw new Error(
|
|
1939
|
-
`LLM transcription failed for all ${llmChunkResults.length} chunk(s) with model "${models.transcribe}". First error: ${errored[0].error}`
|
|
1940
|
-
);
|
|
1941
|
-
}
|
|
1942
|
-
} else {
|
|
1943
|
-
const llmDir = `${options.intermediatesDir}/llm`;
|
|
1944
|
-
if (!forceAll && (0, import_node_fs4.existsSync)(llmDir)) {
|
|
1945
|
-
const files = (await import("fs/promises").then((m) => m.readdir(llmDir))).filter((f) => f.endsWith("_parsed.json")).sort();
|
|
1946
|
-
llmChunkResults = files.map((f, i) => {
|
|
1947
|
-
const r = readJson(`${llmDir}/${f}`);
|
|
1948
|
-
return r && chunks[i] ? tagWith(r, chunks[i]) : r;
|
|
1949
|
-
}).filter(Boolean);
|
|
1950
|
-
}
|
|
1951
|
-
}
|
|
1952
|
-
let allLlmSegments = llmChunkResults.flatMap((r) => r.segments);
|
|
1953
|
-
const beforePart = allLlmSegments.length;
|
|
1954
|
-
allLlmSegments = partitionByOwnership(allLlmSegments);
|
|
1955
|
-
if (beforePart !== allLlmSegments.length) {
|
|
1956
|
-
logger.info(
|
|
1957
|
-
`ownership-partition: ${beforePart} -> ${allLlmSegments.length} (dropped ${beforePart - allLlmSegments.length} overlap duplicates)`
|
|
1958
|
-
);
|
|
1959
|
-
}
|
|
1960
|
-
logger.info(`total LLM segments: ${allLlmSegments.length}`);
|
|
1961
|
-
let asrResult = null;
|
|
1962
|
-
if (has(passes2, "timestamped") || has(passes2, "align")) {
|
|
1963
|
-
const provider = options.timestampedProvider ?? "assemblyai";
|
|
1964
|
-
if (provider === "whisper-groq") {
|
|
1965
|
-
logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
|
|
1966
|
-
if (!keys.groq) throw new Error("GROQ_API_KEY is required for whisper-groq");
|
|
1967
|
-
if (!(0, import_node_fs4.existsSync)(audioPath) || forceAll) {
|
|
1968
|
-
await extractAudio(options.input, audioPath, AUDIO_OPTS);
|
|
1969
|
-
}
|
|
1970
|
-
const { readFile: readFile2 } = await import("fs/promises");
|
|
1971
|
-
const buf = await readFile2(audioPath);
|
|
1972
|
-
const groq = new WhisperGroqClient(keys.groq);
|
|
1973
|
-
asrResult = await groq.transcribe(buf);
|
|
1974
|
-
writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
|
|
1975
|
-
} else {
|
|
1976
|
-
logger.info("=== timestamped (AssemblyAI) ===");
|
|
1977
|
-
if (!keys.assemblyai)
|
|
1978
|
-
throw new Error(
|
|
1979
|
-
"ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
|
|
1980
|
-
);
|
|
1981
|
-
const aai = new AssemblyAIProvider({
|
|
1982
|
-
apiKey: keys.assemblyai,
|
|
1983
|
-
cacheDir: `${options.intermediatesDir}/assemblyai`
|
|
1984
|
-
});
|
|
1985
|
-
asrResult = await aai.transcribe(audioPath);
|
|
1986
|
-
writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
|
|
1987
|
-
}
|
|
1988
|
-
} else {
|
|
1989
|
-
asrResult = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
|
|
1990
|
-
}
|
|
1991
|
-
let aligned = [];
|
|
1992
|
-
if (has(passes2, "align") && asrResult) {
|
|
1993
|
-
logger.info("=== align ===");
|
|
1994
|
-
aligned = alignSegments(allLlmSegments, asrResult.words, { timeMarginSec: 30 });
|
|
1995
|
-
writeJson(`${options.intermediatesDir}/aligned.json`, aligned);
|
|
1996
|
-
} else {
|
|
1997
|
-
aligned = (forceAll ? null : readJson(`${options.intermediatesDir}/aligned.json`)) ?? [];
|
|
1998
|
-
}
|
|
1999
|
-
const alignedOk = aligned.filter((a) => a.timingSource !== "coarse").length;
|
|
2000
|
-
logger.info(`aligned: ${alignedOk}/${aligned.length} with ASR timing`);
|
|
2001
|
-
if (asrResult && (has(passes2, "align") || has(passes2, "consistency"))) {
|
|
2002
|
-
const before = aligned.length;
|
|
2003
|
-
aligned = fillAsrGaps(aligned, asrResult.words, asrResult.utterances);
|
|
2004
|
-
const added = aligned.length - before;
|
|
2005
|
-
if (added) logger.info(`gap-filled ${added} ASR fallback segment(s)`);
|
|
2006
|
-
}
|
|
2007
|
-
let segments = aligned;
|
|
2008
|
-
let speakers = [];
|
|
2009
|
-
if (has(passes2, "consistency") && asrResult) {
|
|
2010
|
-
logger.info("=== consistency ===");
|
|
2011
|
-
const cons = assignGlobalSpeakers(aligned, asrResult.utterances, {
|
|
2012
|
-
hasDiarization: asrResult.hasDiarization ?? true
|
|
2013
|
-
});
|
|
2014
|
-
segments = cons.segments;
|
|
2015
|
-
speakers = cons.speakers;
|
|
2016
|
-
writeJson(`${options.intermediatesDir}/consistent.json`, { segments, speakers });
|
|
2017
|
-
} else {
|
|
2018
|
-
const c = forceAll ? null : readJson(
|
|
2019
|
-
`${options.intermediatesDir}/consistent.json`
|
|
2020
|
-
);
|
|
2021
|
-
if (c) {
|
|
2022
|
-
segments = c.segments;
|
|
2023
|
-
speakers = c.speakers;
|
|
2024
|
-
}
|
|
2025
|
-
}
|
|
2026
|
-
if (options.diarizationLevel >= 3 && has(passes2, "identify") && keys.deepseek && description) {
|
|
2027
|
-
logger.info("=== identify (DeepSeek) ===");
|
|
2028
|
-
const dsClient = OpenAICompatClient.fromProvider(
|
|
2029
|
-
"deepseek",
|
|
2030
|
-
keys.deepseek,
|
|
2031
|
-
models.reasoner
|
|
2032
|
-
);
|
|
2033
|
-
const id = await identifySpeakers(
|
|
2034
|
-
dsClient,
|
|
2035
|
-
models.reasoner,
|
|
2036
|
-
segments.map((s) => ({ speaker: s.speaker, text: s.text })),
|
|
2037
|
-
speakers,
|
|
2038
|
-
description.roster,
|
|
2039
|
-
options.knownSpeakers
|
|
2040
|
-
);
|
|
2041
|
-
logger.info(
|
|
2042
|
-
`identified ${Object.keys(id.nameMap).length} speakers: ${JSON.stringify(id.nameMap)}`
|
|
2043
|
-
);
|
|
2044
|
-
writeJson(`${options.intermediatesDir}/identified.json`, id);
|
|
2045
|
-
segments = segments.map(
|
|
2046
|
-
(s) => id.nameMap[s.speaker] ? { ...s, speakerName: id.nameMap[s.speaker] } : s
|
|
2047
|
-
);
|
|
2048
|
-
speakers = speakers.map(
|
|
2049
|
-
(sp) => id.nameMap[sp.id] ? { ...sp, name: id.nameMap[sp.id] } : sp
|
|
2050
|
-
);
|
|
2051
|
-
}
|
|
2052
|
-
let finalSegments = [];
|
|
2053
|
-
if (has(passes2, "finalize")) {
|
|
2054
|
-
logger.info("=== finalize ===");
|
|
2055
|
-
finalSegments = finalizeSegments(segments);
|
|
2056
|
-
writeJson(`${options.intermediatesDir}/final.json`, finalSegments);
|
|
2057
|
-
} else {
|
|
2058
|
-
finalSegments = (forceAll ? null : readJson(`${options.intermediatesDir}/final.json`)) ?? [];
|
|
2059
|
-
}
|
|
2060
|
-
logger.info(`final segments: ${finalSegments.length}`);
|
|
2061
|
-
const metadata = {
|
|
2062
|
-
sourceFile: options.input,
|
|
2063
|
-
duration,
|
|
2064
|
-
processedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2065
|
-
models: {
|
|
2066
|
-
transcribe: models.transcribe,
|
|
2067
|
-
timestamped: tsProvider === "whisper-groq" ? "whisper-large-v3 (groq)" : tsProvider === "none" ? "none" : "assemblyai-universal-2"
|
|
2068
|
-
},
|
|
2069
|
-
passes: passes2
|
|
2070
|
-
};
|
|
2071
|
-
const result = { segments: finalSegments, speakers, metadata };
|
|
2072
|
-
for (const fmt of options.formats) {
|
|
2073
|
-
const base = (0, import_node_path5.basename)(options.input, ext(options.input));
|
|
2074
|
-
if (fmt === "srt")
|
|
2075
|
-
(0, import_node_fs4.writeFileSync)(
|
|
2076
|
-
`${options.outputDir}/${base}.srt`,
|
|
2077
|
-
formatSrt(result, { title: base })
|
|
2078
|
-
);
|
|
2079
|
-
if (fmt === "md")
|
|
2080
|
-
(0, import_node_fs4.writeFileSync)(
|
|
2081
|
-
`${options.outputDir}/${base}.md`,
|
|
2082
|
-
formatMarkdown(result, { title: base })
|
|
2083
|
-
);
|
|
2084
|
-
if (fmt === "json")
|
|
2085
|
-
(0, import_node_fs4.writeFileSync)(`${options.outputDir}/${base}.json`, formatJson(result));
|
|
2086
|
-
}
|
|
2087
|
-
logger.info(`outputs written to ${options.outputDir}`);
|
|
2088
|
-
return result;
|
|
2089
|
-
}
|
|
2090
|
-
function ext(p) {
|
|
2091
|
-
const i = p.lastIndexOf(".");
|
|
2092
|
-
return i >= 0 ? p.slice(i) : "";
|
|
2093
|
-
}
|
|
2094
|
-
|
|
2095
|
-
// src/cli.ts
|
|
2096
|
-
var packageVersion = "0.0.0";
|
|
2097
|
-
try {
|
|
2098
|
-
const here = (0, import_node_path6.dirname)((0, import_node_url.fileURLToPath)(importMetaUrl));
|
|
2099
|
-
const pkg = JSON.parse((0, import_node_fs5.readFileSync)((0, import_node_path6.join)(here, "..", "package.json"), "utf-8"));
|
|
2100
|
-
packageVersion = pkg.version;
|
|
2101
|
-
} catch {
|
|
2102
|
-
}
|
|
2103
|
-
var program = new import_commander.Command();
|
|
2104
|
-
program.name("offmute-v2").description("Diarized meeting transcription with multimodal LLMs + timestamped alignment.").version(packageVersion).argument("<input>", "input video/audio file").option("-o, --output <dir>", "output directory (default: next to the input file)").option(
|
|
2105
|
-
"-i, --intermediates <dir>",
|
|
2106
|
-
"intermediates directory (default: auto-derived per input file so caches never collide)"
|
|
2107
|
-
).option("--instructions <text>", "custom instructions for the LLM").option("--passes <list>", "comma-separated passes to run").option("--chunk-seconds <n>", "chunk duration in seconds", "600").option("--overlap-seconds <n>", "chunk overlap in seconds", "60").option("--concurrency <n>", "max concurrent chunk requests", "4").option("--screenshots <n>", "number of keyframes to extract (video)", "6").option("--formats <list>", "output formats: srt,md,json (default: md)").option("--level <1|2|3>", "diarization level (1=separation, 2=consistent, 3=identify)", "2").option("--model <name>", "override transcription model").option("--reasoner <name>", "override text-reasoner model (default deepseek-chat)").option("--timestamped <provider>", "timestamped provider (assemblyai|whisper-groq|none)").option("--force", "force reprocess cached chunk outputs", false).option("--only-chunk <n>", "process only a specific chunk index (debug)").option("--save-intermediates", "save intermediates (default true)", true).option("--no-progress", "hide progress output").option("--no-llm-log", "disable per-call LLM logging to <intermediates>/llm-calls.jsonl").option("--log-level <level>", "debug | info | warn | error", "info");
|
|
2108
|
-
program.parse();
|
|
2109
|
-
var opts = program.opts();
|
|
2110
|
-
var input = program.args[0];
|
|
2111
|
-
if (!input) {
|
|
2112
|
-
console.error("Error: input file is required.");
|
|
2113
|
-
process.exit(1);
|
|
2114
|
-
}
|
|
2115
|
-
var passes = opts.passes?.split(",");
|
|
2116
|
-
var level = parseInt(opts.level, 10);
|
|
2117
|
-
transcribe({
|
|
2118
|
-
input,
|
|
2119
|
-
outputDir: opts.output,
|
|
2120
|
-
// undefined → defaults to the input file's directory
|
|
2121
|
-
intermediatesDir: opts.intermediates,
|
|
2122
|
-
instructions: opts.instructions,
|
|
2123
|
-
passes,
|
|
2124
|
-
chunkDurationSec: parseInt(opts.chunkSeconds, 10),
|
|
2125
|
-
chunkOverlapSec: parseInt(opts.overlapSeconds, 10),
|
|
2126
|
-
concurrency: parseInt(opts.concurrency, 10),
|
|
2127
|
-
screenshotCount: parseInt(opts.screenshots, 10),
|
|
2128
|
-
formats: opts.formats ? opts.formats.split(",") : void 0,
|
|
2129
|
-
// undefined → defaults to ["md"]
|
|
2130
|
-
diarizationLevel: level,
|
|
2131
|
-
model: opts.model,
|
|
2132
|
-
reasoner: opts.reasoner,
|
|
2133
|
-
timestampedProvider: opts.timestamped,
|
|
2134
|
-
force: opts.force,
|
|
2135
|
-
onlyChunk: opts.onlyChunk ? parseInt(opts.onlyChunk, 10) : void 0,
|
|
2136
|
-
saveIntermediates: opts.saveIntermediates,
|
|
2137
|
-
showProgress: opts.progress,
|
|
2138
|
-
llmLog: opts.llmLog,
|
|
2139
|
-
logLevel: opts.logLevel
|
|
2140
|
-
}).then((result) => {
|
|
2141
|
-
const segs = result.segments.length;
|
|
2142
|
-
console.log(`Done. ${segs} segments.`);
|
|
2143
|
-
}).catch((err) => {
|
|
2144
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
2145
|
-
console.error(`
|
|
2146
|
-
\u2717 ${msg}`);
|
|
2147
|
-
if (opts.logLevel === "debug" || process.env.OFFMUTE_DEBUG) {
|
|
2148
|
-
console.error(err instanceof Error ? err.stack : err);
|
|
2149
|
-
}
|
|
2150
|
-
process.exit(1);
|
|
2151
|
-
});
|
|
2152
|
-
//# sourceMappingURL=cli.cjs.map
|