Setting the file. One moment. Transcribe · Media Use · heygen-com/hyperframes · Skills Docs⋯
scripts/11 files
scripts/transcribe.mjs
JavaScript·180 lines·7 KB
"node:os"
;
14import { basename, extname, join, resolve } from "node:path";
15import { parseArgs } from "node:util";
16import { mergeTokensToWords } from "./lib/parakeet-words.mjs";
17import { track } from "./lib/telemetry.mjs";
18import { resolveNpxInvocation } from "./lib/npx-sync.mjs";
19
20// The DEFAULT local transcription path. Prefers NVIDIA Parakeet-TDT via
21// parakeet-mlx, which beats whisper.cpp on the Open ASR Leaderboard (~6.05% vs
22// 7.44% avg WER, and 4.73% vs 5.96% on noisy test-other) and is 5-10x faster
23// with native punctuation. Emits { text, words:[{text,start,end}] } (word
24// timestamps merged from Parakeet's sub-word tokens) for transcript-cut /
25// captions / the audio engine.
26//
27// Parakeet v3 covers English + 25 European languages. For other languages, or
28// when parakeet-mlx is not installed, it falls back to whisper.cpp via
29// `hyperframes transcribe` (99 languages; the CLI resolves/builds whisper.cpp
30// on first use — it is not bundled). `--engine` forces one.
31
32const { values: args } = parseArgs({
33 options: {
34 input: { type: "string", short: "i" },
35 out: { type: "string", short: "o" },
36 engine: { type: "string", default: "auto" }, // auto | parakeet | whisper
37 model: { type: "string", default: "mlx-community/parakeet-tdt-0.6b-v3" },
38 json: { type: "boolean", default: false },
39 help: { type: "boolean", short: "h", default: false },
40 },
41 strict: true,
42});
43
44if (args.help) {
45 console.log(`media-use transcribe: better-than-whisper local ASR (Parakeet), whisper.cpp fallback
46
47Usage:
48 node transcribe.mjs --input audio.wav [--out audio.transcribe.json] [--engine auto|parakeet|whisper]
49
50Parakeet (default) beats whisper.cpp on accuracy + speed for English/European
51languages; whisper.cpp (99 languages) is the fallback. Install Parakeet once:
52 uv venv ~/.venvs/parakeet && VIRTUAL_ENV=~/.venvs/parakeet uv pip install parakeet-mlx`);
53 process.exit(0);
54}
55
56if (!args.input) {
57 console.error("error: --input is required");
58 process.exit(2);
59}
60const inputPath = resolve(args.input);
61if (!existsSync(inputPath)) {
62 console.error(`error: input not found: ${inputPath}`);
63 process.exit(2);
64}
65const outPath = resolve(
66 args.out || `${inputPath.slice(0, -extname(inputPath).length)}.transcribe.json`,
67);
68
69// Locate the parakeet-mlx runner the same way the CLI does: env override, then
70// the documented ~/.venvs/parakeet install, then PATH. Checking the venv (not
71// just PATH) is what keeps a user who followed the install docs verbatim from
72// silently falling through to whisper. Returns the runner path, or null.
73function resolveParakeet() {
74 for (const p of [
75 process.env.HYPERFRAMES_PARAKEET,
76 join(homedir(), ".venvs", "parakeet", "bin", "parakeet-mlx"),
77 ]) {
78 if (p && existsSync(p)) return p;
79 }
80 try {
81 execFileSync("parakeet-mlx", ["--help"], {
82 stdio: ["ignore", "ignore", "ignore"],
83 timeout: 20000,
84 });
85 return "parakeet-mlx";
86 } catch {
87 return null;
88 }
89}
90
91// Write via a sibling temp + atomic rename so a SIGKILL mid-write can't leave a
92// truncated transcript at outPath (downstream reads it as valid JSON).
93function atomicWrite(target, data) {
94 const tmp = `${target}.tmp-${process.pid}`;
95 writeFileSync(tmp, data);
96 renameSync(tmp, target);
97}
98
99function report(engine, wordCount) {
100 if (args.json) console.log(JSON.stringify({ ok: true, out: outPath, engine, words: wordCount }));
101 else
102 console.log(
103 `transcribed ${basename(inputPath)} -> ${outPath}${wordCount != null ? ` (${wordCount} words,` : " ("}${engine})`,
104 );
105}
106
107function runParakeet(runner) {
108 const workDir = mkdtempSync(join(tmpdir(), "media-use-asr-"));
109 try {
110 execFileSync(
111 runner,
112 [inputPath, "--model", args.model, "--output-format", "json", "--output-dir", workDir],
113 { stdio: ["ignore", "pipe", "pipe"], timeout: 1_800_000 },
114 );
115 const jsonPath = join(workDir, `${basename(inputPath, extname(inputPath))}.json`);
116 if (!existsSync(jsonPath)) throw new Error("parakeet produced no JSON");
117 const merged = mergeTokensToWords(JSON.parse(readFileSync(jsonPath, "utf8")));
118 atomicWrite(outPath, JSON.stringify(merged, null, 2));
119 report("parakeet", merged.words.length);
120 } finally {
121 rmSync(workDir, { recursive: true, force: true });
122 }
123}
124
125// whisper.cpp via the hyperframes CLI (fetched/built on first use — see
126// SKILL.md): writes transcript.json into --dir; relocate to --out.
127function runWhisper() {
128 const workDir = mkdtempSync(join(tmpdir(), "media-use-whisper-"));
129 try {
130 // On Windows a bare "npx" is npx.cmd, which execFileSync cannot exec
131 // (spawnSync npx ENOENT) — resolveNpxInvocation reroutes it through
132 // node + npx-cli.js (and throws actionably when it can't), same
133 // mechanism as the audio engine's TTS spawns.
134 const resolved = resolveNpxInvocation(
135 ["hyperframes", "transcribe", inputPath, "--dir", workDir],
136 { stdio: ["ignore", "pipe", "pipe"], timeout: 1_800_000 },
137 );
138 execFileSync(resolved.cmd, resolved.args, resolved.opts);
139 const produced = join(workDir, "transcript.json");
140 if (!existsSync(produced)) throw new Error("whisper produced no transcript.json");
141 const tmp = `${outPath}.tmp-${process.pid}`;
142 copyFileSync(produced, tmp);
143 renameSync(tmp, outPath); // atomic publish
144 let words;
145 try {
146 const t = JSON.parse(readFileSync(outPath, "utf8"));
147 words = Array.isArray(t?.words) ? t.words.length : undefined;
148 } catch {
149 /* leave undefined */
150 }
151 report("whisper", words);
152 } finally {
153 rmSync(workDir, { recursive: true, force: true });
154 }
155}
156
157try {
158 const parakeetBin = resolveParakeet();
159 const engine =
160 args.engine === "parakeet" || args.engine === "whisper"
161 ? args.engine
162 : parakeetBin
163 ? "parakeet"
164 : "whisper";
165 if (engine === "parakeet") {
166 if (!parakeetBin) {
167 throw new Error(
168 "parakeet-mlx not found (checked $HYPERFRAMES_PARAKEET, ~/.venvs/parakeet, and PATH). Install: uv venv ~/.venvs/parakeet && VIRTUAL_ENV=~/.venvs/parakeet uv pip install parakeet-mlx (or use --engine whisper)",
169 );
170 }
171 runParakeet(parakeetBin);
172 } else {
173 runWhisper();
174 }
175 await track("media_use_transcribe", { engine });
176} catch (err) {
177 if (args.json) console.log(JSON.stringify({ ok: false, error: err.message }));
178 else console.error(`error: transcription failed: ${err.message}`);
179 process.exit(1);
180}