Skill Tracer
Skills › HyperFrames › media-use › transcribe.mjs

transcribe.mjs

194 lines · skills/media-use/scripts/transcribe.mjs at a595755

1#!/usr/bin/env node
2
3import { execFileSync } from "node:child_process";
4import {
5 existsSync,
6 readFileSync,
7 writeFileSync,
8 copyFileSync,
9 renameSync,
10 mkdtempSync,
11 rmSync,
12} from "node:fs";
13import { homedir, tmpdir } from "node:os";
14import { basename, extname, join, resolve } from "node:path";
15import { parseArgs, stripVTControlCharacters } from "node:util";
16import { mergeTokensToWords } from "./lib/parakeet-words.mjs";
17import { track } from "./lib/telemetry.mjs";
18import { resolveNpxInvocation } from "./lib/npx-sync.mjs";
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.
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});
44if (args.help) {
45 console.log(`media-use transcribe: better-than-whisper local ASR (Parakeet), whisper.cpp fallback
47Usage:
48 node transcribe.mjs --input audio.wav [--out audio.transcribe.json] [--engine auto|parakeet|whisper]
50Parakeet (default) beats whisper.cpp on accuracy + speed for English/European
51languages; whisper.cpp (99 languages) is the fallback. Install Parakeet once:
52 npx hyperframes models install parakeet (macOS, Windows, Linux with glibc 2.32+)
53 uv venv ~/.venvs/parakeet && VIRTUAL_ENV=~/.venvs/parakeet uv pip install parakeet-mlx (Apple Silicon)`);
54 process.exit(0);
57if (!args.input) {
58 console.error("error: --input is required");
59 process.exit(2);
61const inputPath = resolve(args.input);
62if (!existsSync(inputPath)) {
63 console.error(`error: input not found: ${inputPath}`);
64 process.exit(2);
66const outPath = resolve(
67 args.out || `${inputPath.slice(0, -extname(inputPath).length)}.transcribe.json`,
68);
70// Locate the parakeet-mlx runner the same way the CLI does: env override, then
71// the documented ~/.venvs/parakeet install, then PATH. Checking the venv (not
72// just PATH) is what keeps a user who followed the install docs verbatim from
73// silently falling through to whisper. Returns the runner path, or null.
74function resolveParakeet() {
75 for (const p of [
76 process.env.HYPERFRAMES_PARAKEET,
77 join(homedir(), ".venvs", "parakeet", "bin", "parakeet-mlx"),
78 ]) {
79 if (p && existsSync(p)) return p;
80 }
81 try {
82 execFileSync("parakeet-mlx", ["--help"], {
83 stdio: ["ignore", "ignore", "ignore"],
84 timeout: 20000,
85 });
86 return "parakeet-mlx";
87 } catch {
88 return null;
89 }
92// Write via a sibling temp + atomic rename so a SIGKILL mid-write can't leave a
93// truncated transcript at outPath (downstream reads it as valid JSON).
94function atomicWrite(target, data) {
95 const tmp = `${target}.tmp-${process.pid}`;
96 writeFileSync(tmp, data);
97 renameSync(tmp, target);
100function report(engine, wordCount) {
101 if (args.json) console.log(JSON.stringify({ ok: true, out: outPath, engine, words: wordCount }));
102 else
103 console.log(
104 `transcribed ${basename(inputPath)} -> ${outPath}${wordCount != null ? ` (${wordCount} words,` : " ("}${engine})`,
105 );
108function runParakeet(runner) {
109 const workDir = mkdtempSync(join(tmpdir(), "media-use-asr-"));
110 try {
111 execFileSync(
112 runner,
113 [inputPath, "--model", args.model, "--output-format", "json", "--output-dir", workDir],
114 { stdio: ["ignore", "pipe", "pipe"], timeout: 1_800_000 },
115 );
116 const jsonPath = join(workDir, `${basename(inputPath, extname(inputPath))}.json`);
117 if (!existsSync(jsonPath)) throw new Error("parakeet produced no JSON");
118 const merged = mergeTokensToWords(JSON.parse(readFileSync(jsonPath, "utf8")));
119 atomicWrite(outPath, JSON.stringify(merged, null, 2));
120 report("parakeet", merged.words.length);
121 } finally {
122 rmSync(workDir, { recursive: true, force: true });
123 }
126// The hyperframes CLI (its Parakeet, else whisper.cpp built on first use — see
127// SKILL.md): writes transcript.json into --dir; relocate to --out.
128function runCli(cliEngine) {
129 const workDir = mkdtempSync(join(tmpdir(), "media-use-whisper-"));
130 try {
131 // On Windows a bare "npx" is npx.cmd, which execFileSync cannot exec
132 // (spawnSync npx ENOENT) — resolveNpxInvocation reroutes it through
133 // node + npx-cli.js (and throws actionably when it can't), same
134 // mechanism as the audio engine's TTS spawns.
135 // Under auto or parakeet the CLI may run its own Parakeet; --json says which engine ran.
136 const resolved = resolveNpxInvocation(
137 ["hyperframes", "transcribe", inputPath, "--dir", workDir, "--engine", cliEngine, "--json"],
138 { stdio: ["ignore", "pipe", "pipe"], timeout: 1_800_000 },
139 );
140 let stdout;
141 try {
142 stdout = String(execFileSync(resolved.cmd, resolved.args, resolved.opts));
143 } catch (e) {
144 // stderr holds spinner redraws and --json prints the reason on stdout, so keep the last lines.
145 const tail = stripVTControlCharacters(`${e.stderr ?? ""}\n${e.stdout ?? ""}`)
146 .split(/[\r\n]+/)
147 .map((l) => l.trim())
148 .filter((l) => l && l !== "│")
149 .slice(-3)
150 .join("\n");
151 throw new Error(
152 `hyperframes transcribe failed (exit ${e.status ?? e.code})${tail ? `:\n${tail}` : ""}`,
153 );
154 }
155 const produced = join(workDir, "transcript.json");
156 if (!existsSync(produced))
157 throw new Error("hyperframes transcribe produced no transcript.json");
158 const tmp = `${outPath}.tmp-${process.pid}`;
159 copyFileSync(produced, tmp);
160 renameSync(tmp, outPath); // atomic publish
161 let words;
162 try {
163 const t = JSON.parse(readFileSync(outPath, "utf8"));
164 // The CLI writes a flat word array, not { words }.
165 words = Array.isArray(t) ? t.length : undefined;
166 } catch {
167 /* leave undefined */
168 }
169 let ran = "whisper";
170 try {
171 ran = JSON.parse(stdout.trim().split("\n").at(-1)).engine === "parakeet" ? "parakeet" : ran;
172 } catch {
173 /* no JSON line: keep whisper */
174 }
175 report(ran, words);
176 return ran;
177 } finally {
178 rmSync(workDir, { recursive: true, force: true });
179 }
182try {
183 const parakeetBin = resolveParakeet();
184 const asked = args.engine === "parakeet" || args.engine === "whisper" ? args.engine : "auto";
185 // Without parakeet-mlx, the CLI's own Parakeet (any OS, `hyperframes models install parakeet`).
186 let engine = "parakeet";
187 if (asked !== "whisper" && parakeetBin) runParakeet(parakeetBin);
188 else engine = runCli(asked);
189 await track("media_use_transcribe", { engine });
190} catch (err) {
191 if (args.json) console.log(JSON.stringify({ ok: false, error: err.message }));
192 else console.error(`error: transcription failed: ${err.message}`);
193 process.exit(1);