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