@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.
- package/LICENSE-APACHE +202 -0
- package/README.md +265 -12
- package/dist/chromeForClipy.js +1 -1
- package/dist/context/importCmd.js +4 -1
- package/dist/context/readCmd.js +33 -21
- package/dist/context/ytdlp.js +108 -28
- package/dist/context-core/arec.js +66 -6
- package/dist/index.js +1180 -98
- package/dist/library.js +7 -3
- package/dist/local/arec.js +186 -0
- package/dist/local/commands.js +1103 -0
- package/dist/local/deps.js +42 -0
- package/dist/local/media.js +154 -0
- package/dist/local/pipeline.js +530 -0
- package/dist/local/ports.js +1 -0
- package/dist/local/speechEngine.js +260 -0
- package/dist/local/transcriptFile.js +54 -0
- package/dist/local/vendor/capture/capture.js +442 -0
- package/dist/local/vendor/capture/check.js +103 -0
- package/dist/local/vendor/capture/children.js +69 -0
- package/dist/local/vendor/capture/ffmpegArgs.js +108 -0
- package/dist/local/vendor/capture/index.js +36 -0
- package/dist/local/vendor/capture/proc.js +71 -0
- package/dist/local/vendor/capture/scripts.js +107 -0
- package/dist/local/vendor/capture/sidecar.js +199 -0
- package/dist/local/vendor/capture/sources.js +272 -0
- package/dist/local/vendor/capture/types.js +1 -0
- package/dist/local/vendor/capture/virtualDisplay.js +170 -0
- package/dist/local/vendor/capture/xauth.js +68 -0
- package/dist/local/vendor/config/errors.js +12 -0
- package/dist/local/vendor/config/index.js +241 -0
- package/dist/local/vendor/config/paths.js +37 -0
- package/dist/local/vendor/config/presets.js +61 -0
- package/dist/local/vendor/config/schema.js +66 -0
- package/dist/local/vendor/moments/generated/drawStrokes.js +127 -0
- package/dist/local/vendor/moments/generated/keyMomentsCursorContext.js +568 -0
- package/dist/local/vendor/moments/generated/keyMomentsFusion.js +406 -0
- package/dist/local/vendor/moments/generated/localMomentPlan.js +178 -0
- package/dist/local/vendor/moments/generated/types.js +1 -0
- package/dist/local/vendor/moments/index.js +147 -0
- package/dist/local/vendor/moments/llm.js +158 -0
- package/dist/local/vendor/transcribe/audio.js +251 -0
- package/dist/local/vendor/transcribe/chunking.js +250 -0
- package/dist/local/vendor/transcribe/index.js +89 -0
- package/dist/local/vendor/transcribe/local.js +221 -0
- package/dist/local/vendor/transcribe/localWorker.js +79 -0
- package/dist/local/vendor/transcribe/models.js +369 -0
- package/dist/local/vendor/transcribe/providers/assemblyai.js +61 -0
- package/dist/local/vendor/transcribe/providers/common.js +105 -0
- package/dist/local/vendor/transcribe/providers/deepgram.js +59 -0
- package/dist/local/vendor/transcribe/providers/elevenlabs.js +43 -0
- package/dist/local/vendor/transcribe/providers/gemini.js +102 -0
- package/dist/local/vendor/transcribe/providers/http.js +214 -0
- package/dist/local/vendor/transcribe/providers/openai.js +48 -0
- package/dist/local/vendor/transcribe/tar.js +53 -0
- package/dist/local/vendor/transcribe/types.js +1 -0
- package/dist/macBridge.js +78 -9
- package/dist/recheck.js +934 -0
- package/dist/recheckCmd.js +279 -0
- package/dist/skill.js +94 -3
- package/package.json +22 -11
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// GENERATED from oss/packages/transcribe/src/models.ts by cli/scripts/sync-local.mjs. Do not edit here.
|
|
3
|
+
/**
|
|
4
|
+
* Downloadable speech models for on-device transcription. Nothing is ever
|
|
5
|
+
* downloaded unless `downloadModel` is called, which the app or CLI does only
|
|
6
|
+
* after the user agrees. Every file is checked against a pinned SHA-256, and a
|
|
7
|
+
* model is staged in a temporary folder that is renamed into place only once
|
|
8
|
+
* every file has verified, so a model folder is either complete or absent.
|
|
9
|
+
*/
|
|
10
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
11
|
+
import { createRequire } from "node:module";
|
|
12
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
13
|
+
import { mkdir, open, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
14
|
+
import { homedir } from "node:os";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
import { Worker } from "node:worker_threads";
|
|
17
|
+
import { readTar } from "./tar.js";
|
|
18
|
+
/** Bumped when a model's files change, so an older install reads as not installed. */
|
|
19
|
+
const MODEL_VERSIONS = {
|
|
20
|
+
"english-fast": "parakeet-tdt-ctc-110m-en-int8-1",
|
|
21
|
+
multilingual: "whisper-base-int8-1",
|
|
22
|
+
};
|
|
23
|
+
const PARAKEET_ARCHIVE = "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-nemo-parakeet_tdt_ctc_110m-en-36000-int8.tar.bz2";
|
|
24
|
+
const PARAKEET_DIR = "sherpa-onnx-nemo-parakeet_tdt_ctc_110m-en-36000-int8";
|
|
25
|
+
// Pinned to a commit so the bytes behind the URL cannot change under the checksum.
|
|
26
|
+
const WHISPER_BASE = "https://huggingface.co/csukuangfj/sherpa-onnx-whisper-base/resolve/bb53ee204431c90d314c1cc08d28d23e5b7927cc";
|
|
27
|
+
export const LOCAL_MODELS = {
|
|
28
|
+
// NVIDIA Parakeet TDT-CTC 110M, English only, int8, run as a CTC model.
|
|
29
|
+
// Same model as Clipy's hosted fast English path. It is only published as
|
|
30
|
+
// an archive (104 MB download, 132 MB unpacked). It fails on long input, so
|
|
31
|
+
// audio is fed in pieces of at most 180 seconds.
|
|
32
|
+
"english-fast": {
|
|
33
|
+
label: "English, fast (Parakeet TDT-CTC 110M)",
|
|
34
|
+
license: "CC-BY-4.0",
|
|
35
|
+
attribution: "NVIDIA Parakeet TDT-CTC 110M (https://huggingface.co/nvidia/parakeet-tdt_ctc-110m), CC-BY-4.0, converted to ONNX int8 by the sherpa-onnx project",
|
|
36
|
+
sizeBytes: 104_337_827,
|
|
37
|
+
files: [
|
|
38
|
+
{
|
|
39
|
+
url: PARAKEET_ARCHIVE,
|
|
40
|
+
sha256: "17f945007b52ccd8b7200ffc7c5652e9e8e961dfdf479cefcabd06cf5703630b",
|
|
41
|
+
path: "parakeet.tar.bz2",
|
|
42
|
+
bytes: 104_337_827,
|
|
43
|
+
archive: {
|
|
44
|
+
members: [
|
|
45
|
+
{
|
|
46
|
+
name: `${PARAKEET_DIR}/model.int8.onnx`,
|
|
47
|
+
path: "model.int8.onnx",
|
|
48
|
+
sha256: "9177a9146cf32ee0cc8152276ef95116f312018d316be37ccf57f7efea81fc1a",
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
name: `${PARAKEET_DIR}/tokens.txt`,
|
|
52
|
+
path: "tokens.txt",
|
|
53
|
+
sha256: "450e56bd2f036fe5b6aa821865838cc5aa9d8b0106134ce9a9ba0664abe6cd10",
|
|
54
|
+
},
|
|
55
|
+
],
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
],
|
|
59
|
+
},
|
|
60
|
+
// OpenAI Whisper base (multilingual, about 99 languages), int8. Base rather
|
|
61
|
+
// than tiny: tiny is a third smaller but noticeably worse outside English,
|
|
62
|
+
// and base still runs well under real time on a laptop CPU (each 30 s
|
|
63
|
+
// window took about 1 s on 2 threads in testing). Whisper reads at most
|
|
64
|
+
// 30 s at a time, so audio is fed in pieces of at most 28 seconds.
|
|
65
|
+
multilingual: {
|
|
66
|
+
label: "All languages (Whisper base)",
|
|
67
|
+
license: "MIT",
|
|
68
|
+
attribution: "OpenAI Whisper base (https://github.com/openai/whisper), MIT, converted to ONNX int8 by the sherpa-onnx project",
|
|
69
|
+
sizeBytes: 160_609_290,
|
|
70
|
+
files: [
|
|
71
|
+
{
|
|
72
|
+
url: `${WHISPER_BASE}/base-encoder.int8.onnx`,
|
|
73
|
+
sha256: "0b8fb1304b6109976038efff5ace81720e00386f3ff6b54ee8c75291ca0a1e11",
|
|
74
|
+
path: "encoder.int8.onnx",
|
|
75
|
+
bytes: 29_120_534,
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
url: `${WHISPER_BASE}/base-decoder.int8.onnx`,
|
|
79
|
+
sha256: "9759d217388a01b3a4c7c15533201067b48ae819c4daafc8624e64b9409dc02d",
|
|
80
|
+
path: "decoder.int8.onnx",
|
|
81
|
+
bytes: 130_672_026,
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
url: `${WHISPER_BASE}/base-tokens.txt`,
|
|
85
|
+
sha256: "b34b360dbb493e781e479794586d661700670d65564001f23024971d1f2fa126",
|
|
86
|
+
path: "tokens.txt",
|
|
87
|
+
bytes: 816_730,
|
|
88
|
+
},
|
|
89
|
+
],
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
const MARKER = ".installed.json";
|
|
93
|
+
/** Platform cache folder for models: `~/.cache/clipy-local/models` on Linux. */
|
|
94
|
+
export function defaultModelDir() {
|
|
95
|
+
const home = homedir();
|
|
96
|
+
if (process.platform === "win32") {
|
|
97
|
+
const base = process.env.LOCALAPPDATA || join(home, "AppData", "Local");
|
|
98
|
+
return join(base, "clipy-local", "models");
|
|
99
|
+
}
|
|
100
|
+
if (process.platform === "darwin")
|
|
101
|
+
return join(home, "Library", "Caches", "clipy-local", "models");
|
|
102
|
+
const base = process.env.XDG_CACHE_HOME || join(home, ".cache");
|
|
103
|
+
return join(base, "clipy-local", "models");
|
|
104
|
+
}
|
|
105
|
+
/** Final paths of a model's files inside its folder. */
|
|
106
|
+
export function modelFilePaths(model, dir) {
|
|
107
|
+
const out = {};
|
|
108
|
+
for (const f of LOCAL_MODELS[model].files) {
|
|
109
|
+
if (f.archive)
|
|
110
|
+
for (const m of f.archive.members)
|
|
111
|
+
out[m.path] = join(dir, m.path);
|
|
112
|
+
else
|
|
113
|
+
out[f.path] = join(dir, f.path);
|
|
114
|
+
}
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
export function modelStatus(model, modelDir) {
|
|
118
|
+
if (!(model in LOCAL_MODELS))
|
|
119
|
+
throw new Error(`Unknown local model "${model}"`);
|
|
120
|
+
const dir = join(modelDir ?? defaultModelDir(), model);
|
|
121
|
+
let installed = false;
|
|
122
|
+
try {
|
|
123
|
+
const marker = JSON.parse(readFileSync(join(dir, MARKER), "utf8"));
|
|
124
|
+
installed = marker.version === MODEL_VERSIONS[model] && Object.values(modelFilePaths(model, dir)).every((p) => existsSync(p));
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
installed = false;
|
|
128
|
+
}
|
|
129
|
+
return { installed, dir };
|
|
130
|
+
}
|
|
131
|
+
export function formatBytes(n) {
|
|
132
|
+
return `${Math.round(n / 1_000_000)} MB`;
|
|
133
|
+
}
|
|
134
|
+
export class ChecksumError extends Error {
|
|
135
|
+
constructor(what) {
|
|
136
|
+
super(`Checksum mismatch for ${what}: the download is corrupt or was changed. Nothing was installed; try again.`);
|
|
137
|
+
this.name = "ChecksumError";
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function cancelled() {
|
|
141
|
+
const err = new Error("Model download was cancelled");
|
|
142
|
+
err.name = "AbortError";
|
|
143
|
+
return err;
|
|
144
|
+
}
|
|
145
|
+
export class DownloadTooLargeError extends Error {
|
|
146
|
+
constructor(what, maxBytes) {
|
|
147
|
+
super(`The download of ${what} is larger than the expected ${maxBytes} bytes, so it was stopped. Nothing was installed.`);
|
|
148
|
+
this.name = "DownloadTooLargeError";
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** A model download that receives nothing for this long is abandoned. */
|
|
152
|
+
export const DOWNLOAD_IDLE_TIMEOUT_MS = 60_000;
|
|
153
|
+
/**
|
|
154
|
+
* Stream `url` to `dest`, hashing as it goes. Throws ChecksumError on a
|
|
155
|
+
* mismatch. With `maxBytes` (the file's expected size), a server that sends
|
|
156
|
+
* more is cut off at that size instead of filling the disk.
|
|
157
|
+
*
|
|
158
|
+
* Redirects are followed: the model hosts serve from a CDN, and no key or
|
|
159
|
+
* other credential is sent with these requests.
|
|
160
|
+
*/
|
|
161
|
+
export async function downloadVerified(url, dest, sha256, label, signal, onBytes, maxBytes, idleMs = DOWNLOAD_IDLE_TIMEOUT_MS) {
|
|
162
|
+
// Abandon a connection that stops sending: the clock restarts on every chunk.
|
|
163
|
+
const idle = new AbortController();
|
|
164
|
+
let timer;
|
|
165
|
+
const bump = () => {
|
|
166
|
+
clearTimeout(timer);
|
|
167
|
+
timer = setTimeout(() => idle.abort(), idleMs);
|
|
168
|
+
};
|
|
169
|
+
const stalled = () => new Error(`Could not download ${label}: the connection stalled (nothing received for ${Math.round(idleMs / 1000)} s)`);
|
|
170
|
+
const combined = signal ? AbortSignal.any([signal, idle.signal]) : idle.signal;
|
|
171
|
+
bump();
|
|
172
|
+
try {
|
|
173
|
+
let res;
|
|
174
|
+
try {
|
|
175
|
+
res = await fetch(url, { signal: combined, redirect: "follow" });
|
|
176
|
+
}
|
|
177
|
+
catch (err) {
|
|
178
|
+
if (signal?.aborted)
|
|
179
|
+
throw cancelled();
|
|
180
|
+
if (idle.signal.aborted)
|
|
181
|
+
throw stalled();
|
|
182
|
+
const code = err.cause?.code;
|
|
183
|
+
throw new Error(`Could not download ${label}: ${code ? `network error (${code})` : "the server could not be reached"}`);
|
|
184
|
+
}
|
|
185
|
+
bump();
|
|
186
|
+
await saveVerified(res, dest, sha256, label, signal, onBytes, maxBytes, bump, () => idle.signal.aborted, stalled);
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
clearTimeout(timer);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async function saveVerified(res, dest, sha256, label, signal, onBytes, maxBytes, bump, isStalled, stalled) {
|
|
193
|
+
if (!res.ok || !res.body) {
|
|
194
|
+
await res.body?.cancel().catch(() => undefined);
|
|
195
|
+
throw new Error(`Could not download ${label} (HTTP ${res.status})`);
|
|
196
|
+
}
|
|
197
|
+
const declared = Number(res.headers.get("content-length"));
|
|
198
|
+
if (maxBytes !== undefined && Number.isFinite(declared) && declared > maxBytes) {
|
|
199
|
+
await res.body.cancel().catch(() => undefined);
|
|
200
|
+
throw new DownloadTooLargeError(label, maxBytes);
|
|
201
|
+
}
|
|
202
|
+
const hash = createHash("sha256");
|
|
203
|
+
const fh = await open(dest, "w");
|
|
204
|
+
let received = 0;
|
|
205
|
+
try {
|
|
206
|
+
const reader = res.body.getReader();
|
|
207
|
+
for (;;) {
|
|
208
|
+
const { done, value } = await reader.read();
|
|
209
|
+
if (done)
|
|
210
|
+
break;
|
|
211
|
+
bump();
|
|
212
|
+
received += value.byteLength;
|
|
213
|
+
if (maxBytes !== undefined && received > maxBytes) {
|
|
214
|
+
await reader.cancel().catch(() => undefined);
|
|
215
|
+
throw new DownloadTooLargeError(label, maxBytes);
|
|
216
|
+
}
|
|
217
|
+
hash.update(value);
|
|
218
|
+
await fh.write(value);
|
|
219
|
+
onBytes?.(value.byteLength);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
if (err instanceof DownloadTooLargeError)
|
|
224
|
+
throw err;
|
|
225
|
+
if (signal?.aborted)
|
|
226
|
+
throw cancelled();
|
|
227
|
+
if (isStalled())
|
|
228
|
+
throw stalled();
|
|
229
|
+
throw new Error(`Could not download ${label}: the connection dropped`);
|
|
230
|
+
}
|
|
231
|
+
finally {
|
|
232
|
+
await fh.close();
|
|
233
|
+
}
|
|
234
|
+
if (hash.digest("hex") !== sha256.toLowerCase())
|
|
235
|
+
throw new ChecksumError(label);
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Remove staging folders left by a download whose process died before it
|
|
239
|
+
* could clean up (killed, power loss). A folder whose process is still alive
|
|
240
|
+
* belongs to a download in progress and is left alone.
|
|
241
|
+
*/
|
|
242
|
+
async function removeAbandonedStages(root) {
|
|
243
|
+
let names;
|
|
244
|
+
try {
|
|
245
|
+
names = await readdir(root);
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
for (const name of names) {
|
|
251
|
+
const m = /^\..+\.partial-(\d+)-[0-9a-f]+$/.exec(name);
|
|
252
|
+
if (!m)
|
|
253
|
+
continue;
|
|
254
|
+
const pid = Number(m[1]);
|
|
255
|
+
if (pid === process.pid || processAlive(pid))
|
|
256
|
+
continue;
|
|
257
|
+
await rm(join(root, name), { recursive: true, force: true }).catch(() => undefined);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
function processAlive(pid) {
|
|
261
|
+
try {
|
|
262
|
+
process.kill(pid, 0);
|
|
263
|
+
return true;
|
|
264
|
+
}
|
|
265
|
+
catch (err) {
|
|
266
|
+
return err.code === "EPERM";
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
/** Decompress a .bz2 file on a worker thread so the event loop stays free. */
|
|
270
|
+
function bunzip2(path, signal) {
|
|
271
|
+
const bzipPath = createRequire(import.meta.url).resolve("seek-bzip");
|
|
272
|
+
const code = `
|
|
273
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
274
|
+
const fs = require("node:fs");
|
|
275
|
+
const Bunzip = require(workerData.bzipPath);
|
|
276
|
+
const out = Bunzip.decode(fs.readFileSync(workerData.path));
|
|
277
|
+
const ab = out.buffer.slice(out.byteOffset, out.byteOffset + out.length);
|
|
278
|
+
parentPort.postMessage(ab, [ab]);
|
|
279
|
+
`;
|
|
280
|
+
return new Promise((resolve, reject) => {
|
|
281
|
+
const worker = new Worker(code, { eval: true, workerData: { bzipPath, path } });
|
|
282
|
+
const onAbort = () => {
|
|
283
|
+
void worker.terminate();
|
|
284
|
+
reject(cancelled());
|
|
285
|
+
};
|
|
286
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
287
|
+
worker.once("message", (ab) => {
|
|
288
|
+
signal?.removeEventListener("abort", onAbort);
|
|
289
|
+
resolve(Buffer.from(ab));
|
|
290
|
+
});
|
|
291
|
+
worker.once("error", () => {
|
|
292
|
+
signal?.removeEventListener("abort", onAbort);
|
|
293
|
+
reject(new Error("The model archive could not be unpacked"));
|
|
294
|
+
});
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
function sha256Hex(buf) {
|
|
298
|
+
return createHash("sha256").update(buf).digest("hex");
|
|
299
|
+
}
|
|
300
|
+
/** Pull the listed members out of a verified archive, checking each one. */
|
|
301
|
+
export async function extractArchiveMembers(archivePath, members, outDir, label, signal) {
|
|
302
|
+
const tar = await bunzip2(archivePath, signal);
|
|
303
|
+
const wanted = new Map(members.map((m) => [m.name, m]));
|
|
304
|
+
const found = new Set();
|
|
305
|
+
for (const entry of readTar(tar)) {
|
|
306
|
+
const m = wanted.get(entry.name);
|
|
307
|
+
if (!m)
|
|
308
|
+
continue;
|
|
309
|
+
if (sha256Hex(entry.data) !== m.sha256.toLowerCase())
|
|
310
|
+
throw new ChecksumError(`${label} (${m.path})`);
|
|
311
|
+
const tmp = join(outDir, `.${m.path}.${randomBytes(4).toString("hex")}.tmp`);
|
|
312
|
+
await writeFile(tmp, entry.data);
|
|
313
|
+
await rename(tmp, join(outDir, m.path));
|
|
314
|
+
found.add(m.name);
|
|
315
|
+
}
|
|
316
|
+
const missing = members.filter((m) => !found.has(m.name));
|
|
317
|
+
if (missing.length)
|
|
318
|
+
throw new Error(`The ${label} archive is missing ${missing.map((m) => m.path).join(", ")}`);
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Download, verify and install a model. Returns its folder. Safe to call
|
|
322
|
+
* again: an installed model is returned as is.
|
|
323
|
+
*/
|
|
324
|
+
export async function downloadModel(model, options = {}) {
|
|
325
|
+
const spec = LOCAL_MODELS[model];
|
|
326
|
+
if (!spec)
|
|
327
|
+
throw new Error(`Unknown local model "${model}"`);
|
|
328
|
+
const root = options.modelDir ?? defaultModelDir();
|
|
329
|
+
const status = modelStatus(model, root);
|
|
330
|
+
if (status.installed) {
|
|
331
|
+
options.onProgress?.(1);
|
|
332
|
+
return status.dir;
|
|
333
|
+
}
|
|
334
|
+
await mkdir(root, { recursive: true });
|
|
335
|
+
await removeAbandonedStages(root);
|
|
336
|
+
const stage = join(root, `.${model}.partial-${process.pid}-${randomBytes(4).toString("hex")}`);
|
|
337
|
+
await mkdir(stage, { recursive: true });
|
|
338
|
+
const hasArchive = spec.files.some((f) => f.archive);
|
|
339
|
+
const total = spec.files.reduce((n, f) => n + (f.bytes ?? 0), 0) || spec.sizeBytes;
|
|
340
|
+
const downloadShare = hasArchive ? 0.85 : 1;
|
|
341
|
+
let done = 0;
|
|
342
|
+
const report = (n) => {
|
|
343
|
+
done += n;
|
|
344
|
+
options.onProgress?.(Math.min(downloadShare, (done / total) * downloadShare));
|
|
345
|
+
};
|
|
346
|
+
try {
|
|
347
|
+
options.onProgress?.(0);
|
|
348
|
+
for (const f of spec.files) {
|
|
349
|
+
const dest = join(stage, f.path);
|
|
350
|
+
await downloadVerified(f.url, dest, f.sha256, spec.label, options.signal, report, f.bytes);
|
|
351
|
+
if (f.archive) {
|
|
352
|
+
await extractArchiveMembers(dest, f.archive.members, stage, spec.label, options.signal);
|
|
353
|
+
await rm(dest, { force: true });
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
await writeFile(join(stage, MARKER), JSON.stringify({ model, version: MODEL_VERSIONS[model], installedAt: new Date().toISOString() }, null, 2));
|
|
357
|
+
const final = status.dir;
|
|
358
|
+
await rm(final, { recursive: true, force: true });
|
|
359
|
+
await rename(stage, final);
|
|
360
|
+
options.onProgress?.(1);
|
|
361
|
+
return final;
|
|
362
|
+
}
|
|
363
|
+
catch (err) {
|
|
364
|
+
await rm(stage, { recursive: true, force: true }).catch(() => undefined);
|
|
365
|
+
if (options.signal?.aborted)
|
|
366
|
+
throw cancelled();
|
|
367
|
+
throw err;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// GENERATED from oss/packages/transcribe/src/providers/assemblyai.ts by cli/scripts/sync-local.mjs. Do not edit here.
|
|
3
|
+
/** AssemblyAI: upload the audio, start a transcript job, poll until it finishes. */
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { joinUrl, ProviderError, requestJson, sleep } from "./http.js";
|
|
7
|
+
import { groupWordsIntoSegments, toTimeline } from "../chunking.js";
|
|
8
|
+
export const ASSEMBLYAI_BASE_URL = "https://api.assemblyai.com";
|
|
9
|
+
const Upload = z.object({ upload_url: z.string() });
|
|
10
|
+
const Job = z
|
|
11
|
+
.object({
|
|
12
|
+
id: z.string(),
|
|
13
|
+
status: z.string(),
|
|
14
|
+
language_code: z.string().nullish(),
|
|
15
|
+
words: z.array(z.object({ text: z.string(), start: z.number(), end: z.number() }).passthrough()).nullish(),
|
|
16
|
+
utterances: z.array(z.object({ text: z.string(), start: z.number(), end: z.number() }).passthrough()).nullish(),
|
|
17
|
+
})
|
|
18
|
+
.passthrough();
|
|
19
|
+
export async function transcribeAssemblyAI(input, config, limits = {}) {
|
|
20
|
+
const provider = "assemblyai";
|
|
21
|
+
const base = config.baseUrl || ASSEMBLYAI_BASE_URL;
|
|
22
|
+
const auth = { authorization: config.apiKey };
|
|
23
|
+
const pollMs = limits.pollIntervalMs ?? 3000;
|
|
24
|
+
const timeoutMs = limits.timeoutMs ?? 60 * 60 * 1000;
|
|
25
|
+
const audio = await readFile(input.wavPath);
|
|
26
|
+
const up = Upload.safeParse(await requestJson(provider, joinUrl(base, "v2/upload"), { method: "POST", headers: { ...auth, "Content-Type": "application/octet-stream" }, body: new Uint8Array(audio) }, input.signal));
|
|
27
|
+
if (!up.success)
|
|
28
|
+
throw new ProviderError(provider, 200, "upload answer had no upload_url");
|
|
29
|
+
input.onProgress?.(0.2);
|
|
30
|
+
const body = { audio_url: up.data.upload_url, language_detection: true };
|
|
31
|
+
if (config.model)
|
|
32
|
+
body.speech_models = [config.model];
|
|
33
|
+
const created = Job.safeParse(await requestJson(provider, joinUrl(base, "v2/transcript"), { method: "POST", headers: { ...auth, "Content-Type": "application/json" }, body: JSON.stringify(body) }, input.signal));
|
|
34
|
+
if (!created.success)
|
|
35
|
+
throw new ProviderError(provider, 200, "unexpected answer shape");
|
|
36
|
+
const started = Date.now();
|
|
37
|
+
let job = created.data;
|
|
38
|
+
while (job.status !== "completed") {
|
|
39
|
+
if (job.status === "error")
|
|
40
|
+
throw new ProviderError(provider, undefined, "the provider reported an error for this audio");
|
|
41
|
+
if (Date.now() - started > timeoutMs)
|
|
42
|
+
throw new ProviderError(provider, undefined, "timed out waiting for the transcript");
|
|
43
|
+
await sleep(pollMs, input.signal);
|
|
44
|
+
const next = Job.safeParse(await requestJson(provider, joinUrl(base, `v2/transcript/${encodeURIComponent(job.id)}`), { headers: auth }, input.signal));
|
|
45
|
+
if (!next.success)
|
|
46
|
+
throw new ProviderError(provider, 200, "unexpected answer shape");
|
|
47
|
+
job = next.data;
|
|
48
|
+
input.onProgress?.(Math.min(0.95, 0.2 + (Date.now() - started) / Math.max(60_000, input.info.durationSec * 300)));
|
|
49
|
+
}
|
|
50
|
+
// Times are milliseconds.
|
|
51
|
+
const segments = job.utterances && job.utterances.length > 0
|
|
52
|
+
? job.utterances.map((u) => ({ start: u.start / 1000, end: u.end / 1000, text: u.text }))
|
|
53
|
+
: groupWordsIntoSegments((job.words ?? []).map((w) => ({ start: w.start / 1000, end: w.end / 1000, text: w.text })));
|
|
54
|
+
input.onProgress?.(1);
|
|
55
|
+
return {
|
|
56
|
+
segments: toTimeline(segments),
|
|
57
|
+
language: job.language_code ?? undefined,
|
|
58
|
+
engine: `assemblyai${config.model ? `:${config.model}` : ""}`,
|
|
59
|
+
gaps: [],
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// GENERATED from oss/packages/transcribe/src/providers/common.ts by cli/scripts/sync-local.mjs. Do not edit here.
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { BYTES_PER_SECOND, detectSilences, measureMeanVolume, readWavSlice, silenceThresholds, throwIfAborted } from "../audio.js";
|
|
5
|
+
import { mergePieces, planChunks, speechSecIn, trimToSpeech } from "../chunking.js";
|
|
6
|
+
/**
|
|
7
|
+
* The AudioInput for an extracted WAV. Both silence lists are computed at
|
|
8
|
+
* most once, with thresholds that follow the recording's own loudness, so
|
|
9
|
+
* quiet speech is not taken for silence.
|
|
10
|
+
*/
|
|
11
|
+
export function audioInputFor(wavPath, info, signal, onProgress) {
|
|
12
|
+
let levels = null;
|
|
13
|
+
const thresholds = () => (levels ??= measureMeanVolume(wavPath, signal).then(silenceThresholds));
|
|
14
|
+
const at = (pick) => {
|
|
15
|
+
let spans = null;
|
|
16
|
+
return () => (spans ??= thresholds()
|
|
17
|
+
.then((t) => detectSilences(wavPath, signal, info.durationSec, pick(t)))
|
|
18
|
+
.then((list) => list.map((x) => ({ startSec: x.startSec, endSec: Math.min(x.endSec, info.durationSec) }))));
|
|
19
|
+
};
|
|
20
|
+
return {
|
|
21
|
+
wavPath,
|
|
22
|
+
info,
|
|
23
|
+
signal,
|
|
24
|
+
silences: at((t) => t.splitDb),
|
|
25
|
+
noSpeech: at((t) => t.skipDb),
|
|
26
|
+
quiet: () => thresholds().then((t) => t.quiet),
|
|
27
|
+
onProgress,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/** Longest WAV (header included) that fits in `maxBytes`. */
|
|
31
|
+
export function maxSecForBytes(maxBytes) {
|
|
32
|
+
return Math.floor((maxBytes - 44) / BYTES_PER_SECOND);
|
|
33
|
+
}
|
|
34
|
+
/** A piece with less speech than this (outside `noSpeech` spans) is not sent. */
|
|
35
|
+
export const MIN_SPEECH_SEC = 0.3;
|
|
36
|
+
export const NO_SPEECH_GAP_REASON = "no speech detected";
|
|
37
|
+
/**
|
|
38
|
+
* Of a multi-piece plan, the pieces with no speech, which are not sent.
|
|
39
|
+
*
|
|
40
|
+
* - "strict" (Parakeet, which says nothing over noise): only pieces that the
|
|
41
|
+
* strict `noSpeech` spans cover.
|
|
42
|
+
* - "invents" (Whisper and the hosted providers, which turn fan noise into
|
|
43
|
+
* "Thank you."): also pieces the ordinary `silences` cover, unless the
|
|
44
|
+
* recording is quiet, where those spans could hide speech.
|
|
45
|
+
*
|
|
46
|
+
* A recording that is one piece is always transcribed.
|
|
47
|
+
*/
|
|
48
|
+
export async function piecesWithoutSpeech(input, plan, engine) {
|
|
49
|
+
if (plan.length <= 1)
|
|
50
|
+
return new Set();
|
|
51
|
+
let spans = null;
|
|
52
|
+
if (engine === "invents" && !(await input.quiet?.()))
|
|
53
|
+
spans = await input.silences();
|
|
54
|
+
else if (input.noSpeech)
|
|
55
|
+
spans = await input.noSpeech();
|
|
56
|
+
if (!spans)
|
|
57
|
+
return new Set();
|
|
58
|
+
const quiet = spans;
|
|
59
|
+
return new Set(plan.filter((p) => speechSecIn(quiet, p.extractStartSec, p.extractStartSec + p.extractDurSec) < MIN_SPEECH_SEC).map((p) => p.index));
|
|
60
|
+
}
|
|
61
|
+
/** The part of the timeline a piece owns, as a gap. */
|
|
62
|
+
export function pieceGap(p, reason) {
|
|
63
|
+
const start = Math.max(p.keepStartSec, p.extractStartSec);
|
|
64
|
+
const end = Math.min(p.keepEndSec, p.extractStartSec + p.extractDurSec);
|
|
65
|
+
return { startMs: Math.round(start * 1000), endMs: Math.round(end * 1000), reason };
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Send the audio to a provider in pieces small enough for its upload limit,
|
|
69
|
+
* cut in silences, one piece at a time, and merge the results. A piece with
|
|
70
|
+
* no speech at all is not sent and is reported as a gap.
|
|
71
|
+
*/
|
|
72
|
+
export async function runInPieces(input, limits, run) {
|
|
73
|
+
const total = input.info.durationSec;
|
|
74
|
+
const silences = total > limits.maxSec ? await input.silences() : [];
|
|
75
|
+
const plan = planChunks(silences, total, { targetSec: limits.targetSec, maxSec: limits.maxSec, overlapSec: 0, minSec: Math.min(15, limits.targetSec / 2) });
|
|
76
|
+
const skip = await piecesWithoutSpeech(input, plan, "invents");
|
|
77
|
+
const pieces = [];
|
|
78
|
+
const gaps = [];
|
|
79
|
+
let language;
|
|
80
|
+
for (const [i, p] of plan.entries()) {
|
|
81
|
+
throwIfAborted(input.signal);
|
|
82
|
+
if (skip.has(p.index)) {
|
|
83
|
+
gaps.push(pieceGap(p, NO_SPEECH_GAP_REASON));
|
|
84
|
+
input.onProgress?.((i + 1) / plan.length);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const wav = plan.length === 1 ? await readFile(input.wavPath) : await readWavSlice(input.wavPath, input.info, p.extractStartSec, p.extractDurSec);
|
|
88
|
+
const out = await run(wav, p.extractDurSec);
|
|
89
|
+
language ??= out.language;
|
|
90
|
+
pieces.push({ plan: p, segments: out.segments });
|
|
91
|
+
input.onProgress?.((i + 1) / plan.length);
|
|
92
|
+
}
|
|
93
|
+
return { segments: mergePieces(pieces), language, gaps };
|
|
94
|
+
}
|
|
95
|
+
/** A provider that only returned plain text: one segment over the speech in the piece. */
|
|
96
|
+
export function wholePieceSegment(text, durSec, silences = []) {
|
|
97
|
+
const t = text.trim();
|
|
98
|
+
if (!t)
|
|
99
|
+
return [];
|
|
100
|
+
const span = trimToSpeech(silences, 0, durSec);
|
|
101
|
+
return [{ start: span.startSec, end: Math.max(span.endSec, span.startSec), text: t }];
|
|
102
|
+
}
|
|
103
|
+
export function finiteNumber(v) {
|
|
104
|
+
return typeof v === "number" && Number.isFinite(v) ? v : undefined;
|
|
105
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// GENERATED from oss/packages/transcribe/src/providers/deepgram.ts by cli/scripts/sync-local.mjs. Do not edit here.
|
|
3
|
+
/** Deepgram pre-recorded `/v1/listen`, with utterances for segment boundaries. */
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { joinUrl, ProviderError, requestJson } from "./http.js";
|
|
7
|
+
import { groupWordsIntoSegments, toTimeline } from "../chunking.js";
|
|
8
|
+
export const DEEPGRAM_BASE_URL = "https://api.deepgram.com";
|
|
9
|
+
export const DEEPGRAM_DEFAULT_MODEL = "nova-3";
|
|
10
|
+
const Word = z.object({ start: z.number(), end: z.number(), word: z.string(), punctuated_word: z.string().optional() }).passthrough();
|
|
11
|
+
const Answer = z.object({
|
|
12
|
+
results: z
|
|
13
|
+
.object({
|
|
14
|
+
utterances: z.array(z.object({ start: z.number(), end: z.number(), transcript: z.string() }).passthrough()).nullish(),
|
|
15
|
+
channels: z
|
|
16
|
+
.array(z
|
|
17
|
+
.object({
|
|
18
|
+
detected_language: z.string().optional(),
|
|
19
|
+
alternatives: z.array(z.object({ transcript: z.string().optional(), words: z.array(Word).optional() }).passthrough()).optional(),
|
|
20
|
+
})
|
|
21
|
+
.passthrough())
|
|
22
|
+
.optional(),
|
|
23
|
+
})
|
|
24
|
+
.passthrough(),
|
|
25
|
+
});
|
|
26
|
+
export async function transcribeDeepgram(input, config) {
|
|
27
|
+
const provider = "deepgram";
|
|
28
|
+
const model = config.model || DEEPGRAM_DEFAULT_MODEL;
|
|
29
|
+
const params = new URLSearchParams({
|
|
30
|
+
model,
|
|
31
|
+
smart_format: "true",
|
|
32
|
+
punctuate: "true",
|
|
33
|
+
utterances: "true",
|
|
34
|
+
detect_language: "true",
|
|
35
|
+
});
|
|
36
|
+
const url = `${joinUrl(config.baseUrl || DEEPGRAM_BASE_URL, "v1/listen")}?${params}`;
|
|
37
|
+
const audio = await readFile(input.wavPath);
|
|
38
|
+
const raw = await requestJson(provider, url, { method: "POST", headers: { Authorization: `Token ${config.apiKey}`, "Content-Type": "audio/wav" }, body: new Uint8Array(audio) }, input.signal);
|
|
39
|
+
const parsed = Answer.safeParse(raw);
|
|
40
|
+
if (!parsed.success)
|
|
41
|
+
throw new ProviderError(provider, 200, "unexpected answer shape");
|
|
42
|
+
const channel = parsed.data.results.channels?.[0];
|
|
43
|
+
let segments;
|
|
44
|
+
const utterances = parsed.data.results.utterances;
|
|
45
|
+
if (utterances && utterances.length > 0) {
|
|
46
|
+
segments = utterances.map((u) => ({ start: u.start, end: u.end, text: u.transcript }));
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
const words = channel?.alternatives?.[0]?.words ?? [];
|
|
50
|
+
segments = groupWordsIntoSegments(words.map((w) => ({ start: w.start, end: w.end, text: w.punctuated_word ?? w.word })));
|
|
51
|
+
}
|
|
52
|
+
input.onProgress?.(1);
|
|
53
|
+
return {
|
|
54
|
+
segments: toTimeline(segments),
|
|
55
|
+
language: channel?.detected_language,
|
|
56
|
+
engine: `deepgram:${model}`,
|
|
57
|
+
gaps: [],
|
|
58
|
+
};
|
|
59
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// GENERATED from oss/packages/transcribe/src/providers/elevenlabs.ts by cli/scripts/sync-local.mjs. Do not edit here.
|
|
3
|
+
/** ElevenLabs Scribe `/v1/speech-to-text`: word timestamps grouped into segments. */
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { joinUrl, ProviderError, requestJson } from "./http.js";
|
|
7
|
+
import { groupWordsIntoSegments, toTimeline } from "../chunking.js";
|
|
8
|
+
export const ELEVENLABS_BASE_URL = "https://api.elevenlabs.io";
|
|
9
|
+
export const ELEVENLABS_DEFAULT_MODEL = "scribe_v2";
|
|
10
|
+
const Answer = z
|
|
11
|
+
.object({
|
|
12
|
+
language_code: z.string().nullish(),
|
|
13
|
+
text: z.string().optional(),
|
|
14
|
+
words: z
|
|
15
|
+
.array(z.object({ text: z.string(), start: z.number().nullish(), end: z.number().nullish(), type: z.string().optional() }).passthrough())
|
|
16
|
+
.optional(),
|
|
17
|
+
})
|
|
18
|
+
.passthrough();
|
|
19
|
+
export async function transcribeElevenLabs(input, config) {
|
|
20
|
+
const provider = "elevenlabs";
|
|
21
|
+
const model = config.model || ELEVENLABS_DEFAULT_MODEL;
|
|
22
|
+
const audio = await readFile(input.wavPath);
|
|
23
|
+
const form = new FormData();
|
|
24
|
+
form.append("model_id", model);
|
|
25
|
+
form.append("file", new Blob([new Uint8Array(audio)], { type: "audio/wav" }), "audio.wav");
|
|
26
|
+
form.append("timestamps_granularity", "word");
|
|
27
|
+
form.append("tag_audio_events", "false");
|
|
28
|
+
const raw = await requestJson(provider, joinUrl(config.baseUrl || ELEVENLABS_BASE_URL, "v1/speech-to-text"), { method: "POST", headers: { "xi-api-key": config.apiKey }, body: form }, input.signal);
|
|
29
|
+
const parsed = Answer.safeParse(raw);
|
|
30
|
+
if (!parsed.success)
|
|
31
|
+
throw new ProviderError(provider, 200, "unexpected answer shape");
|
|
32
|
+
// Words come with "spacing" entries between them; keep only words, times in seconds.
|
|
33
|
+
const words = (parsed.data.words ?? [])
|
|
34
|
+
.filter((w) => (w.type ?? "word") === "word" && typeof w.start === "number" && typeof w.end === "number")
|
|
35
|
+
.map((w) => ({ start: w.start, end: w.end, text: w.text }));
|
|
36
|
+
input.onProgress?.(1);
|
|
37
|
+
return {
|
|
38
|
+
segments: toTimeline(groupWordsIntoSegments(words)),
|
|
39
|
+
language: parsed.data.language_code ?? undefined,
|
|
40
|
+
engine: `elevenlabs:${model}`,
|
|
41
|
+
gaps: [],
|
|
42
|
+
};
|
|
43
|
+
}
|