@clipy/cli 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +265 -12
  3. package/dist/chromeForClipy.js +1 -1
  4. package/dist/context/importCmd.js +4 -1
  5. package/dist/context/readCmd.js +33 -21
  6. package/dist/context/ytdlp.js +108 -28
  7. package/dist/context-core/arec.js +66 -6
  8. package/dist/index.js +1180 -98
  9. package/dist/library.js +7 -3
  10. package/dist/local/arec.js +186 -0
  11. package/dist/local/commands.js +1103 -0
  12. package/dist/local/deps.js +42 -0
  13. package/dist/local/media.js +154 -0
  14. package/dist/local/pipeline.js +530 -0
  15. package/dist/local/ports.js +1 -0
  16. package/dist/local/speechEngine.js +260 -0
  17. package/dist/local/transcriptFile.js +54 -0
  18. package/dist/local/vendor/capture/capture.js +442 -0
  19. package/dist/local/vendor/capture/check.js +103 -0
  20. package/dist/local/vendor/capture/children.js +69 -0
  21. package/dist/local/vendor/capture/ffmpegArgs.js +108 -0
  22. package/dist/local/vendor/capture/index.js +36 -0
  23. package/dist/local/vendor/capture/proc.js +71 -0
  24. package/dist/local/vendor/capture/scripts.js +107 -0
  25. package/dist/local/vendor/capture/sidecar.js +199 -0
  26. package/dist/local/vendor/capture/sources.js +272 -0
  27. package/dist/local/vendor/capture/types.js +1 -0
  28. package/dist/local/vendor/capture/virtualDisplay.js +170 -0
  29. package/dist/local/vendor/capture/xauth.js +68 -0
  30. package/dist/local/vendor/config/errors.js +12 -0
  31. package/dist/local/vendor/config/index.js +241 -0
  32. package/dist/local/vendor/config/paths.js +37 -0
  33. package/dist/local/vendor/config/presets.js +61 -0
  34. package/dist/local/vendor/config/schema.js +66 -0
  35. package/dist/local/vendor/moments/generated/drawStrokes.js +127 -0
  36. package/dist/local/vendor/moments/generated/keyMomentsCursorContext.js +568 -0
  37. package/dist/local/vendor/moments/generated/keyMomentsFusion.js +406 -0
  38. package/dist/local/vendor/moments/generated/localMomentPlan.js +178 -0
  39. package/dist/local/vendor/moments/generated/types.js +1 -0
  40. package/dist/local/vendor/moments/index.js +147 -0
  41. package/dist/local/vendor/moments/llm.js +158 -0
  42. package/dist/local/vendor/transcribe/audio.js +251 -0
  43. package/dist/local/vendor/transcribe/chunking.js +250 -0
  44. package/dist/local/vendor/transcribe/index.js +89 -0
  45. package/dist/local/vendor/transcribe/local.js +221 -0
  46. package/dist/local/vendor/transcribe/localWorker.js +79 -0
  47. package/dist/local/vendor/transcribe/models.js +369 -0
  48. package/dist/local/vendor/transcribe/providers/assemblyai.js +61 -0
  49. package/dist/local/vendor/transcribe/providers/common.js +105 -0
  50. package/dist/local/vendor/transcribe/providers/deepgram.js +59 -0
  51. package/dist/local/vendor/transcribe/providers/elevenlabs.js +43 -0
  52. package/dist/local/vendor/transcribe/providers/gemini.js +102 -0
  53. package/dist/local/vendor/transcribe/providers/http.js +214 -0
  54. package/dist/local/vendor/transcribe/providers/openai.js +48 -0
  55. package/dist/local/vendor/transcribe/tar.js +53 -0
  56. package/dist/local/vendor/transcribe/types.js +1 -0
  57. package/dist/macBridge.js +78 -9
  58. package/dist/recheck.js +934 -0
  59. package/dist/recheckCmd.js +279 -0
  60. package/dist/skill.js +94 -3
  61. package/package.json +22 -11
@@ -0,0 +1,250 @@
1
+ const START_RE = /silence_start:\s*(-?[0-9.]+)/;
2
+ const END_RE = /silence_end:\s*([0-9.]+)\s*\|\s*silence_duration:\s*([0-9.]+)/;
3
+ /**
4
+ * Parse ffmpeg `silencedetect` stderr. A silence still open at the end of the
5
+ * file is closed at `totalSec` when given.
6
+ */
7
+ export function parseSilencedetectOutput(output, totalSec) {
8
+ const spans = [];
9
+ let open = null;
10
+ for (const line of output.split(/\r?\n/)) {
11
+ const start = START_RE.exec(line);
12
+ if (start) {
13
+ open = Math.max(0, Number(start[1]));
14
+ continue;
15
+ }
16
+ const end = END_RE.exec(line);
17
+ if (!end)
18
+ continue;
19
+ const endSec = Number(end[1]);
20
+ const startSec = open ?? endSec - Number(end[2]);
21
+ open = null;
22
+ if (Number.isFinite(startSec) && Number.isFinite(endSec) && endSec > startSec) {
23
+ spans.push({ startSec: Math.max(0, startSec), endSec });
24
+ }
25
+ }
26
+ if (open !== null && totalSec !== undefined && totalSec > open) {
27
+ spans.push({ startSec: open, endSec: totalSec });
28
+ }
29
+ return spans;
30
+ }
31
+ /**
32
+ * Plan pieces no longer than `maxSec`, cut at silence midpoints near
33
+ * `targetSec`. A recording that fits in one piece is one piece. Every piece's
34
+ * extract length is at most `maxSec`.
35
+ */
36
+ export function planChunks(silences, totalSec, opts) {
37
+ const { targetSec, overlapSec, maxSec } = opts;
38
+ if (!(totalSec > 0))
39
+ return [];
40
+ if (totalSec <= maxSec) {
41
+ return [{ index: 0, extractStartSec: 0, extractDurSec: totalSec, keepStartSec: -Infinity, keepEndSec: Infinity, hardCut: false }];
42
+ }
43
+ // An inner piece carries overlap on both sides, the first and last on one.
44
+ const innerCore = maxSec - 2 * overlapSec;
45
+ if (!(innerCore > 0))
46
+ throw new Error("chunk overlap leaves no room for audio");
47
+ const mids = silences
48
+ .filter((s) => s.endSec > s.startSec)
49
+ .map((s) => (s.startSec + s.endSec) / 2)
50
+ .filter((m) => m > 0 && m < totalSec)
51
+ .sort((a, b) => a - b);
52
+ const cuts = [];
53
+ let pos = 0;
54
+ for (;;) {
55
+ const remaining = totalSec - pos;
56
+ if (pos > 0 && remaining + overlapSec <= maxSec)
57
+ break; // the rest is the last piece
58
+ const coreLimit = pos === 0 ? maxSec - overlapSec : innerCore;
59
+ const minSec = Math.min(opts.minSec, coreLimit / 2);
60
+ const lo = pos + minSec;
61
+ const hi = pos + coreLimit;
62
+ const target = pos + Math.min(targetSec, coreLimit);
63
+ let best = null;
64
+ for (const m of mids) {
65
+ if (m < lo || m > hi)
66
+ continue;
67
+ if (best === null || Math.abs(m - target) < Math.abs(best - target))
68
+ best = m;
69
+ }
70
+ const at = best ?? target;
71
+ cuts.push({ at, hard: best === null });
72
+ pos = at;
73
+ }
74
+ const bounds = [0, ...cuts.map((c) => c.at), totalSec];
75
+ const plan = [];
76
+ for (let i = 0; i < bounds.length - 1; i++) {
77
+ const coreStart = bounds[i];
78
+ const coreEnd = bounds[i + 1];
79
+ const extractStartSec = Math.max(0, coreStart - overlapSec);
80
+ const extractEndSec = Math.min(totalSec, coreEnd + overlapSec);
81
+ plan.push({
82
+ index: i,
83
+ extractStartSec,
84
+ extractDurSec: extractEndSec - extractStartSec,
85
+ keepStartSec: i === 0 ? -Infinity : coreStart,
86
+ keepEndSec: i === bounds.length - 2 ? Infinity : coreEnd,
87
+ hardCut: (i > 0 && cuts[i - 1].hard) || (i < cuts.length && cuts[i].hard),
88
+ });
89
+ }
90
+ return plan;
91
+ }
92
+ /** Seconds of [startSec, endSec) not covered by any silence. */
93
+ export function speechSecIn(silences, startSec, endSec) {
94
+ let silent = 0;
95
+ for (const s of silences) {
96
+ const a = Math.max(startSec, s.startSec);
97
+ const b = Math.min(endSec, s.endSec);
98
+ if (b > a)
99
+ silent += b - a;
100
+ }
101
+ return Math.max(0, endSec - startSec - silent);
102
+ }
103
+ /** Shrink [startSec, endSec) past silences touching either edge. */
104
+ export function trimToSpeech(silences, startSec, endSec) {
105
+ let a = startSec;
106
+ let b = endSec;
107
+ for (const s of silences) {
108
+ if (s.startSec <= a && s.endSec > a)
109
+ a = Math.min(s.endSec, b);
110
+ if (s.startSec < b && s.endSec >= b)
111
+ b = Math.max(s.startSec, a);
112
+ }
113
+ return { startSec: a, endSec: b };
114
+ }
115
+ /**
116
+ * Put every piece's segments on the recording's timeline, keep each segment
117
+ * only from the piece whose core holds its centre (so overlap is never
118
+ * transcribed twice), then sort and nudge so segments never overlap.
119
+ */
120
+ export function mergePieces(pieces) {
121
+ const kept = [];
122
+ for (const { plan, segments } of pieces) {
123
+ for (const s of segments) {
124
+ const start = s.start + plan.extractStartSec;
125
+ const end = Math.max(s.end, s.start) + plan.extractStartSec;
126
+ const centre = (start + end) / 2;
127
+ if (centre < plan.keepStartSec || centre >= plan.keepEndSec)
128
+ continue;
129
+ const text = s.text.trim();
130
+ if (text)
131
+ kept.push({ start, end, text });
132
+ }
133
+ }
134
+ kept.sort((a, b) => a.start - b.start || a.end - b.end);
135
+ const out = [];
136
+ for (const s of kept) {
137
+ const prev = out[out.length - 1];
138
+ let startMs = Math.round(s.start * 1000);
139
+ if (prev && startMs < prev.endMs)
140
+ startMs = prev.endMs;
141
+ const endMs = Math.max(Math.round(s.end * 1000), startMs);
142
+ out.push({ startMs, endMs, text: s.text });
143
+ }
144
+ return out;
145
+ }
146
+ /** Split into a new segment after a pause this long, or once a segment runs this long. */
147
+ export const SEGMENT_GAP_SEC = 0.8;
148
+ export const SEGMENT_MAX_SEC = 18;
149
+ /** The recognizer reports when a token starts; a word ends a short tail after its last token. */
150
+ const TOKEN_TAIL_SEC = 0.4;
151
+ /**
152
+ * Group sub-word tokens (with their start times) into segments, the way the
153
+ * hosted service does: a long pause or a long run starts a new segment.
154
+ * Punctuation never starts a segment (CTC models often emit the full stop
155
+ * after the pause that follows it), and a long run is only split where a new
156
+ * word begins.
157
+ */
158
+ export function groupTokensIntoSegments(tokens, timestamps) {
159
+ const segs = [];
160
+ let cur = [];
161
+ let segStart = timestamps[0] ?? 0;
162
+ let prev = segStart;
163
+ const flush = () => {
164
+ const text = cur.join("").replace(/\s+/g, " ").trim();
165
+ if (text)
166
+ segs.push({ start: segStart, end: Math.max(prev + TOKEN_TAIL_SEC, segStart), text });
167
+ cur = [];
168
+ };
169
+ for (let i = 0; i < tokens.length; i++) {
170
+ const token = tokens[i];
171
+ const t = typeof timestamps[i] === "number" && Number.isFinite(timestamps[i]) ? timestamps[i] : prev;
172
+ if (cur.length > 0 && !/[\p{L}\p{N}]/u.test(token)) {
173
+ cur.push(token);
174
+ continue;
175
+ }
176
+ const startsWord = /^\s/.test(token);
177
+ if (cur.length > 0 && (t - prev > SEGMENT_GAP_SEC || (startsWord && t - segStart > SEGMENT_MAX_SEC))) {
178
+ flush();
179
+ }
180
+ if (cur.length === 0)
181
+ segStart = t;
182
+ cur.push(token);
183
+ prev = t;
184
+ }
185
+ flush();
186
+ // The tail must not run into the next segment.
187
+ for (let i = 0; i + 1 < segs.length; i++) {
188
+ if (segs[i].end > segs[i + 1].start)
189
+ segs[i].end = Math.max(segs[i].start, segs[i + 1].start);
190
+ }
191
+ return segs;
192
+ }
193
+ /**
194
+ * The tokens a piece owns, on the recording's timeline: those whose start
195
+ * falls in the piece's core. Merging at token level (rather than segment
196
+ * level) means a sentence that runs across a cut is never kept twice.
197
+ */
198
+ export function tokensInCore(plan, tokens, timestamps) {
199
+ const out = [];
200
+ for (let i = 0; i < tokens.length; i++) {
201
+ const rel = timestamps[i];
202
+ if (typeof rel !== "number" || !Number.isFinite(rel))
203
+ continue;
204
+ const t = rel + plan.extractStartSec;
205
+ if (t < plan.keepStartSec || t >= plan.keepEndSec)
206
+ continue;
207
+ out.push({ token: tokens[i], t });
208
+ }
209
+ return out;
210
+ }
211
+ /** Segments that are already on the recording's timeline (seconds) as sorted, non-overlapping ms segments. */
212
+ export function toTimeline(segments) {
213
+ return mergePieces([
214
+ { plan: { index: 0, extractStartSec: 0, extractDurSec: Infinity, keepStartSec: -Infinity, keepEndSec: Infinity, hardCut: false }, segments },
215
+ ]);
216
+ }
217
+ const SENTENCE_END = /[.!?。!?]["')\]]*$/;
218
+ /**
219
+ * Group words into readable segments: break at a sentence end once a segment
220
+ * has a few seconds in it, at a long pause, or once it runs too long.
221
+ */
222
+ export function groupWordsIntoSegments(words, joiner = " ") {
223
+ const segs = [];
224
+ let cur = [];
225
+ const flush = () => {
226
+ if (cur.length === 0)
227
+ return;
228
+ const text = cur
229
+ .map((w) => w.text.trim())
230
+ .filter(Boolean)
231
+ .join(joiner)
232
+ .replace(/\s+([,.!?;:])/g, "$1")
233
+ .trim();
234
+ if (text)
235
+ segs.push({ start: cur[0].start, end: Math.max(cur[cur.length - 1].end, cur[0].start), text });
236
+ cur = [];
237
+ };
238
+ for (const w of words) {
239
+ if (!w.text.trim())
240
+ continue;
241
+ const last = cur[cur.length - 1];
242
+ if (last && (w.start - last.end > SEGMENT_GAP_SEC || w.end - cur[0].start > SEGMENT_MAX_SEC))
243
+ flush();
244
+ cur.push(w);
245
+ if (SENTENCE_END.test(w.text.trim()) && w.end - cur[0].start >= 3)
246
+ flush();
247
+ }
248
+ flush();
249
+ return segs;
250
+ }
@@ -0,0 +1,89 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/transcribe/src/index.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ /**
4
+ * @clipy/transcribe: a recording's speech as timestamped segments.
5
+ *
6
+ * - `none`: no transcript; the result has one gap over the whole file.
7
+ * - `local`: a downloaded model run on this machine (nothing leaves it).
8
+ * - every other kind: the audio is sent to that provider with the user's key.
9
+ *
10
+ * Nothing here logs. Errors name the provider and HTTP status, never a key,
11
+ * a response body or transcript text.
12
+ */
13
+ import { mkdtemp, rm } from "node:fs/promises";
14
+ import { tmpdir } from "node:os";
15
+ import { join } from "node:path";
16
+ import { extractAudio, NoAudioTrackError, probeMedia, readWavInfo, throwIfAborted } from "./audio.js";
17
+ import { transcribeLocal } from "./local.js";
18
+ import { transcribeAssemblyAI } from "./providers/assemblyai.js";
19
+ import { audioInputFor } from "./providers/common.js";
20
+ import { transcribeDeepgram } from "./providers/deepgram.js";
21
+ import { transcribeElevenLabs } from "./providers/elevenlabs.js";
22
+ import { transcribeGemini } from "./providers/gemini.js";
23
+ import { transcribeOpenAICompatible } from "./providers/openai.js";
24
+ export { extractAudio, NoAudioTrackError } from "./audio.js";
25
+ export { defaultModelDir, downloadModel, LOCAL_MODELS, modelStatus, ChecksumError, DownloadTooLargeError } from "./models.js";
26
+ export { ModelNotInstalledError } from "./local.js";
27
+ export { ProviderError } from "./providers/http.js";
28
+ /** Transcribe a video or audio file. The audio is extracted to a temporary folder that is always removed. */
29
+ export async function transcribe(inputPath, config, options = {}) {
30
+ const { signal, onProgress } = options;
31
+ throwIfAborted(signal);
32
+ onProgress?.({ stage: "extract", fraction: 0 });
33
+ // Nothing to extract: only the length is needed (and a video-only file has no audio to extract).
34
+ if (config.kind === "none") {
35
+ const totalMs = await durationMs(inputPath, signal);
36
+ onProgress?.({ stage: "extract", fraction: 1 });
37
+ return { segments: [], engine: "none", gaps: wholeFileGap(totalMs, "transcription off") };
38
+ }
39
+ const dir = await mkdtemp(join(tmpdir(), "clipy-transcribe-"));
40
+ try {
41
+ const wavPath = join(dir, "audio.wav");
42
+ try {
43
+ await extractAudio(inputPath, wavPath, signal);
44
+ }
45
+ catch (err) {
46
+ if (!(err instanceof NoAudioTrackError))
47
+ throw err;
48
+ const totalMs = await durationMs(inputPath, signal);
49
+ onProgress?.({ stage: "extract", fraction: 1 });
50
+ return { segments: [], engine: "none", gaps: wholeFileGap(totalMs, "no audio track") };
51
+ }
52
+ const info = await readWavInfo(wavPath);
53
+ onProgress?.({ stage: "extract", fraction: 1 });
54
+ const input = audioInputFor(wavPath, info, signal, (fraction) => onProgress?.({ stage: "transcribe", fraction }));
55
+ input.onProgress?.(0);
56
+ const out = await runEngine(input, config, options);
57
+ return { segments: out.segments, engine: out.engine, ...(out.language ? { language: out.language } : {}), gaps: out.gaps };
58
+ }
59
+ finally {
60
+ await rm(dir, { recursive: true, force: true }).catch(() => undefined);
61
+ }
62
+ }
63
+ async function durationMs(inputPath, signal) {
64
+ const { durationSec } = await probeMedia(inputPath, signal);
65
+ return durationSec !== null && durationSec > 0 ? Math.round(durationSec * 1000) : 0;
66
+ }
67
+ function wholeFileGap(totalMs, reason) {
68
+ return totalMs > 0 ? [{ startMs: 0, endMs: totalMs, reason }] : [];
69
+ }
70
+ function runEngine(input, config, options) {
71
+ switch (config.kind) {
72
+ case "local":
73
+ return transcribeLocal(input, config.model, options.modelDir, options.speechEngine);
74
+ case "openai-compatible":
75
+ return transcribeOpenAICompatible(input, config);
76
+ case "deepgram":
77
+ return transcribeDeepgram(input, config);
78
+ case "assemblyai":
79
+ return transcribeAssemblyAI(input, config);
80
+ case "elevenlabs":
81
+ return transcribeElevenLabs(input, config);
82
+ case "gemini":
83
+ return transcribeGemini(input, config);
84
+ default: {
85
+ const kind = config.kind;
86
+ throw new Error(`Unknown transcription kind "${String(kind)}"`);
87
+ }
88
+ }
89
+ }
@@ -0,0 +1,221 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/transcribe/src/local.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ /**
4
+ * On-device transcription with sherpa-onnx (k2-fsa's Node addon), run in a
5
+ * child process (see localWorker.ts). Nothing leaves the machine.
6
+ */
7
+ import { fork } from "node:child_process";
8
+ import { existsSync } from "node:fs";
9
+ import { createRequire } from "node:module";
10
+ import { availableParallelism } from "node:os";
11
+ import { fileURLToPath } from "node:url";
12
+ import { throwIfAborted } from "./audio.js";
13
+ import { groupTokensIntoSegments, planChunks, tokensInCore, toTimeline, trimToSpeech, } from "./chunking.js";
14
+ import { formatBytes, LOCAL_MODELS, modelFilePaths, modelStatus } from "./models.js";
15
+ import { NO_SPEECH_GAP_REASON, pieceGap, piecesWithoutSpeech } from "./providers/common.js";
16
+ /**
17
+ * Piece sizes per model. Parakeet aborts on input much past 3 minutes, so a
18
+ * piece is never longer than 180 s (about 130 s preferred, cut in a silence,
19
+ * with 2.5 s of overlap so a word at a seam is whole in one piece). Whisper
20
+ * reads at most 30 s, so pieces stay under 28 s with no overlap (it gives no
21
+ * word times to de-duplicate with).
22
+ */
23
+ export const LOCAL_CHUNKING = {
24
+ "english-fast": { targetSec: 130, maxSec: 180, overlapSec: 2.5, minSec: 15 },
25
+ multilingual: { targetSec: 24, maxSec: 28, overlapSec: 0, minSec: 5 },
26
+ };
27
+ /** Speech kept on each side of a trimmed piece. */
28
+ const TRIM_PAD_SEC = 0.5;
29
+ /** The piece with dead silence cut off both ends of the audio sent; the core it owns is unchanged. */
30
+ export function trimPieceToSpeech(p, quiet) {
31
+ const end = p.extractStartSec + p.extractDurSec;
32
+ const speech = trimToSpeech(quiet, p.extractStartSec, end);
33
+ if (!(speech.endSec > speech.startSec))
34
+ return p;
35
+ const start = Math.max(p.extractStartSec, speech.startSec - TRIM_PAD_SEC);
36
+ const stop = Math.min(end, speech.endSec + TRIM_PAD_SEC);
37
+ return { ...p, extractStartSec: start, extractDurSec: stop - start };
38
+ }
39
+ export class ModelNotInstalledError extends Error {
40
+ model;
41
+ sizeBytes;
42
+ constructor(model) {
43
+ const spec = LOCAL_MODELS[model];
44
+ super(`The "${spec.label}" model is not installed. It is a one-time ${formatBytes(spec.sizeBytes)} download: ` +
45
+ `run "clipy models download ${model}" (or choose another transcription option).`);
46
+ this.name = "ModelNotInstalledError";
47
+ this.model = model;
48
+ this.sizeBytes = spec.sizeBytes;
49
+ }
50
+ }
51
+ function recognizerConfig(model, dir, threads) {
52
+ const p = modelFilePaths(model, dir);
53
+ const common = { tokens: p["tokens.txt"], numThreads: threads, provider: "cpu", debug: 0 };
54
+ return {
55
+ featConfig: { sampleRate: 16000, featureDim: 80 },
56
+ modelConfig: model === "english-fast"
57
+ ? { ...common, nemoCtc: { model: p["model.int8.onnx"] } }
58
+ : { ...common, whisper: { encoder: p["encoder.int8.onnx"], decoder: p["decoder.int8.onnx"], language: "", task: "transcribe" } },
59
+ };
60
+ }
61
+ function workerPath() {
62
+ const js = fileURLToPath(new URL("./localWorker.js", import.meta.url));
63
+ if (existsSync(js))
64
+ return { path: js, execArgv: [] };
65
+ // Running from source (tests): Node 22.18+ strips the type annotations itself.
66
+ return { path: fileURLToPath(new URL("./localWorker.ts", import.meta.url)), execArgv: ["--no-warnings"] };
67
+ }
68
+ /**
69
+ * Run the pieces in one child. Resolves with the pieces it did not get to
70
+ * when the child died mid-way (the one it was on counts as failed).
71
+ */
72
+ function runChild(job, pieces, signal, onAnswer) {
73
+ return new Promise((resolve, reject) => {
74
+ const { path, execArgv } = workerPath();
75
+ const child = fork(path, [], { execArgv, stdio: ["ignore", "ignore", "ignore", "ipc"], serialization: "advanced" });
76
+ const answered = new Set();
77
+ let current = null;
78
+ let fatal = null;
79
+ let settled = false;
80
+ const finish = (fn) => {
81
+ if (settled)
82
+ return;
83
+ settled = true;
84
+ signal?.removeEventListener("abort", onAbort);
85
+ fn();
86
+ };
87
+ const onAbort = () => {
88
+ child.kill("SIGKILL");
89
+ const err = new Error("Transcription was cancelled");
90
+ err.name = "AbortError";
91
+ finish(() => reject(err));
92
+ };
93
+ signal?.addEventListener("abort", onAbort, { once: true });
94
+ child.on("message", (m) => {
95
+ if (m.type === "started")
96
+ current = m.index;
97
+ else if (m.type === "result") {
98
+ answered.add(m.index);
99
+ current = null;
100
+ onAnswer(m.index, { text: m.text, tokens: m.tokens, timestamps: m.timestamps, lang: m.lang });
101
+ }
102
+ else if (m.type === "error") {
103
+ answered.add(m.index);
104
+ current = null;
105
+ onAnswer(m.index, null);
106
+ }
107
+ else if (m.type === "fatal")
108
+ fatal = m.message;
109
+ });
110
+ child.on("error", (err) => finish(() => reject(new Error(`the local speech engine could not start: ${err.message}`))));
111
+ child.on("exit", () => {
112
+ if (fatal)
113
+ return finish(() => reject(new Error(`Local transcription failed: ${fatal}`)));
114
+ if (current !== null && !answered.has(current)) {
115
+ answered.add(current);
116
+ onAnswer(current, null);
117
+ }
118
+ finish(() => resolve({ remaining: pieces.filter((p) => !answered.has(p.index)) }));
119
+ });
120
+ child.send({ type: "run", recognizerConfig: job.config, engine: job.engine, wav: job.wav, pieces: pieces.map((p) => ({ index: p.index, startSec: p.extractStartSec, durSec: p.extractDurSec })) });
121
+ });
122
+ }
123
+ /** The engine to load: the host's copy when it names one, else one this package can resolve. */
124
+ function resolveEngine(speechEngine) {
125
+ if (speechEngine)
126
+ return existsSync(speechEngine) ? speechEngine : false;
127
+ try {
128
+ createRequire(import.meta.url).resolve("sherpa-onnx-node");
129
+ return null;
130
+ }
131
+ catch {
132
+ return false;
133
+ }
134
+ }
135
+ export async function transcribeLocal(input, model, modelDir, speechEngine) {
136
+ const status = modelStatus(model, modelDir);
137
+ if (!status.installed)
138
+ throw new ModelNotInstalledError(model);
139
+ const engine = resolveEngine(speechEngine);
140
+ if (engine === false) {
141
+ throw new Error("Local transcription needs the speech engine (sherpa-onnx-node), which is not installed: " +
142
+ "run clipy speech install, or choose a transcription key (clipy local setup --transcribe openai --transcribe-key -).");
143
+ }
144
+ throwIfAborted(input.signal);
145
+ const total = input.info.durationSec;
146
+ const opts = LOCAL_CHUNKING[model];
147
+ const silences = await input.silences();
148
+ const plan = planChunks(silences, total, opts);
149
+ // A piece with no speech is not run (Whisper invents words in silence), and says so as a gap.
150
+ const noSpeech = await piecesWithoutSpeech(input, plan, model === "english-fast" ? "strict" : "invents");
151
+ // Parakeet loses speech in a piece that is mostly dead silence (it normalises
152
+ // over the whole piece), so each piece is trimmed to its speech first.
153
+ const quiet = input.noSpeech ? await input.noSpeech() : [];
154
+ const withSpeech = plan.filter((p) => !noSpeech.has(p.index)).map((p) => trimPieceToSpeech(p, quiet));
155
+ const threads = Math.max(1, Math.min(4, Math.floor(availableParallelism() / 2)));
156
+ const job = {
157
+ config: recognizerConfig(model, status.dir, threads),
158
+ engine,
159
+ wav: { path: input.wavPath, dataOffset: input.info.dataOffset, dataBytes: input.info.dataBytes, sampleRate: input.info.sampleRate },
160
+ };
161
+ const answers = new Map();
162
+ const skipped = plan.length - withSpeech.length;
163
+ const onAnswer = (index, a) => {
164
+ answers.set(index, a);
165
+ input.onProgress?.((answers.size + skipped) / Math.max(1, plan.length));
166
+ };
167
+ let queue = withSpeech;
168
+ let restarts = 0;
169
+ while (queue.length > 0) {
170
+ const { remaining } = await runChild(job, queue, input.signal, onAnswer);
171
+ if (remaining.length === queue.length)
172
+ restarts++;
173
+ if (restarts > 2) {
174
+ for (const p of remaining)
175
+ answers.set(p.index, null);
176
+ break;
177
+ }
178
+ queue = remaining;
179
+ }
180
+ // Token-level merge for models with token times (Parakeet), so a sentence
181
+ // running across a cut is kept once; one segment per piece otherwise (Whisper).
182
+ const timed = [];
183
+ const wholePieces = [];
184
+ const gaps = plan.filter((p) => noSpeech.has(p.index)).map((p) => pieceGap(p, NO_SPEECH_GAP_REASON));
185
+ const langs = new Map();
186
+ let succeeded = 0;
187
+ for (const p of withSpeech) {
188
+ const a = answers.get(p.index);
189
+ if (!a) {
190
+ gaps.push(pieceGap(p, "the local model could not transcribe this part"));
191
+ continue;
192
+ }
193
+ succeeded++;
194
+ if (a.lang)
195
+ langs.set(a.lang, (langs.get(a.lang) ?? 0) + 1);
196
+ if (a.tokens.length > 0 && a.timestamps.length === a.tokens.length) {
197
+ timed.push(...tokensInCore(p, a.tokens, a.timestamps));
198
+ }
199
+ else {
200
+ // Whisper gives no token times: one segment over the speech in the piece.
201
+ const text = a.text.trim();
202
+ const span = trimToSpeech(silences, p.extractStartSec, p.extractStartSec + p.extractDurSec);
203
+ if (text)
204
+ wholePieces.push({ start: span.startSec, end: span.endSec, text });
205
+ }
206
+ }
207
+ timed.sort((x, y) => x.t - y.t);
208
+ const segments = toTimeline([
209
+ ...groupTokensIntoSegments(timed.map((x) => x.token), timed.map((x) => x.t)),
210
+ ...wholePieces,
211
+ ]);
212
+ if (withSpeech.length > 0 && succeeded === 0) {
213
+ throw new Error("Local transcription failed on every part of this recording.");
214
+ }
215
+ gaps.sort((a, b) => a.startMs - b.startMs);
216
+ input.onProgress?.(1);
217
+ let language = model === "english-fast" ? "en" : undefined;
218
+ if (model === "multilingual" && langs.size > 0)
219
+ language = [...langs.entries()].sort((a, b) => b[1] - a[1])[0][0];
220
+ return { segments, engine: `local:${model}`, language, gaps };
221
+ }
@@ -0,0 +1,79 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/transcribe/src/localWorker.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ /**
4
+ * Child process that runs sherpa-onnx on pieces of a WAV file. It runs in its
5
+ * own process because a native crash in the model (Parakeet aborts on input
6
+ * that is too long) would otherwise take the whole CLI down; here it only
7
+ * costs one piece, which the parent records as a gap.
8
+ *
9
+ * Self-contained on purpose (Node built-ins and sherpa-onnx-node only, type
10
+ * annotations only), so Node can also run it straight from source. The parent
11
+ * names the engine's entry file when it lives outside this package (the CLI
12
+ * installs it on first use into a folder of its own).
13
+ */
14
+ import { createRequire } from "node:module";
15
+ import { closeSync, openSync, readSync } from "node:fs";
16
+ function send(msg) {
17
+ return new Promise((resolve) => {
18
+ if (!process.send)
19
+ return resolve();
20
+ process.send(msg, undefined, {}, () => resolve());
21
+ });
22
+ }
23
+ function readPiece(fd, wav, piece) {
24
+ const startSample = Math.max(0, Math.round(piece.startSec * wav.sampleRate));
25
+ const startByte = Math.min(wav.dataBytes, startSample * 2);
26
+ const endByte = Math.min(wav.dataBytes, Math.round((piece.startSec + piece.durSec) * wav.sampleRate) * 2);
27
+ const len = Math.max(0, endByte - startByte) & ~1;
28
+ const buf = Buffer.alloc(len);
29
+ if (len > 0)
30
+ readSync(fd, buf, 0, len, wav.dataOffset + startByte);
31
+ const out = new Float32Array(len / 2);
32
+ for (let i = 0; i < out.length; i++)
33
+ out[i] = buf.readInt16LE(i * 2) / 32768;
34
+ return out;
35
+ }
36
+ async function run(msg) {
37
+ const require = createRequire(import.meta.url);
38
+ let recognizer;
39
+ try {
40
+ const sherpa = require(msg.engine ?? "sherpa-onnx-node");
41
+ recognizer = await sherpa.OfflineRecognizer.createAsync(msg.recognizerConfig);
42
+ }
43
+ catch (err) {
44
+ await send({ type: "fatal", message: `the speech model could not be loaded: ${err.message.split("\n")[0]}` });
45
+ process.exit(2);
46
+ }
47
+ const fd = openSync(msg.wav.path, "r");
48
+ try {
49
+ for (const piece of msg.pieces) {
50
+ await send({ type: "started", index: piece.index });
51
+ try {
52
+ const samples = readPiece(fd, msg.wav, piece);
53
+ const stream = recognizer.createStream();
54
+ stream.acceptWaveform({ samples, sampleRate: msg.wav.sampleRate });
55
+ const r = await recognizer.decodeAsync(stream);
56
+ await send({
57
+ type: "result",
58
+ index: piece.index,
59
+ text: r.text ?? "",
60
+ tokens: r.tokens ?? [],
61
+ timestamps: r.timestamps ?? [],
62
+ lang: r.lang || undefined,
63
+ });
64
+ }
65
+ catch (err) {
66
+ await send({ type: "error", index: piece.index, message: err.name });
67
+ }
68
+ }
69
+ }
70
+ finally {
71
+ closeSync(fd);
72
+ }
73
+ await send({ type: "done" });
74
+ process.exit(0);
75
+ }
76
+ process.on("message", (msg) => {
77
+ if (msg && msg.type === "run")
78
+ void run(msg);
79
+ });