Files
raea/sdk/cloud/server/words.ts
shane d873402ac5 raea goal is the loop, raea make the asset tools (#269)
One loop, raea goal: every rule in TypeScript, held at edit, render, publish and done (goal check, tasks, judge, seen, gates, next); the brief's contract is goal: (one goal or a list, a workflow inline), and its plan is plan:. raea make is making a finished asset: character, clothes, motion, solid, wear, splat, physics, bake, sounds, component, the kit pipeline and shots. Instruments (check, judge, ask, world, scene faults, light check) stay top-level. With it: the montage pack (MK48-MK51), JavaScriptCore fixes raea goal needs (CommonJS named exports, reserved words too, dynamic import of file URLs, process.exit from a promise, stdin for -), raea-cli-goal and raea-cli-refused split out of raea-cli, and skills at raea-skills 105aede.
2026-11-29 18:43:09 -08:00

118 lines
5.6 KiB
TypeScript

// `raea words` on a raea cloud box: what a take or an export says, word by word. raea's own transcriber is parakeet-mlx
// (Mac only), so a box had none: agents guessed `raea transcribe` and cut on guessed frames (11-25). raea goal check's
// words, say, never and CTA packs hear through this on a box (sdk/goal media.ts).
//
// raea words FILE [-o OUT.words.json] [--language en]
// FILE's sound heard by Whisper large-v3 (the farm's POST /v1/words, the model raea cloud's library index uses)
// into FILE's words.json beside it ([{text, start_ms, end_ms}], what `raea cut`, captions and --words read)
//
// The sound goes as 16 kHz mono MP3 in 10-minute pieces (`raea media ffmpeg`), to RAEA_CLOUD_GPU_URL with its token.
import { spawnSync } from "node:child_process"
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
const REAL = process.env.RAEA_REAL ?? "/opt/raea/bin/raea"
const PIECE_S = 600
export type Word = { text: string; start: number; end: number }
function ffmpeg(args: string[]) {
const r = spawnSync(REAL, ["media", "ffmpeg", ...args], { encoding: "utf8" })
if (r.status !== 0) {
const r2 = spawnSync("ffmpeg", args, { encoding: "utf8" })
if (r2.status !== 0) throw new Error(`ffmpeg ${args.join(" ")}: ${(r.stderr || r2.stderr || "").slice(-400)}`)
}
}
function seconds(file: string): number {
const r = spawnSync(REAL, ["media", "ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file], { encoding: "utf8" })
const s = Number.parseFloat(r.stdout)
if (Number.isFinite(s)) return s
const r2 = spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file], { encoding: "utf8" })
const s2 = Number.parseFloat(r2.stdout)
if (!Number.isFinite(s2)) throw new Error(`${file}: no length (is it a video or sound file?)`)
return s2
}
/** what FILE says, by the farm's Whisper */
export async function hear(file: string, language?: string, f: typeof fetch = fetch): Promise<Word[]> {
const url = process.env.RAEA_CLOUD_GPU_URL
const token = process.env.RAEA_CLOUD_GPU_TOKEN ?? ""
if (!url) throw new Error("raea words needs the farm (RAEA_CLOUD_GPU_URL), which hears it with Whisper; this box has none set")
const len = seconds(file)
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-words-"))
try {
const out: Word[] = []
for (let at = 0; at < len; at += PIECE_S) {
const mp3 = path.join(dir, `p${at}.mp3`)
ffmpeg(["-v", "error", "-y", "-ss", String(at), "-t", String(PIECE_S), "-i", file, "-vn", "-ac", "1", "-ar", "16000", "-b:a", "32k", mp3])
if (!existsSync(mp3)) throw new Error(`${file} has no sound to hear`)
let r: Response | undefined
let why = ""
for (let k = 0; k < 4; k++) {
r = await f(`${url.replace(/\/$/, "")}/v1/words${language ? `?language=${encodeURIComponent(language)}` : ""}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "audio/mpeg" }, body: readFileSync(mp3), signal: AbortSignal.timeout(330_000) })
if (r.ok) break
why = `${r.status} ${(await r.text()).slice(0, 300)}`
if (r.status < 500) break
await new Promise((ok) => setTimeout(ok, 1000 * 2 ** k))
}
if (!r?.ok) throw new Error(`the farm couldn't hear ${path.basename(file)}: ${why}`)
const b = (await r.json()) as { words: Word[] }
out.push(...split(b.words).map((w) => ({ text: w.text, start: at + w.start, end: at + w.end })))
}
return out
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
/** Whisper sometimes hands back two words as one ("for $60"): one word each, sharing its time by their lengths */
export function split(ws: Word[]): Word[] {
return ws.flatMap((w) => {
const parts = w.text.split(/\s+/).filter(Boolean)
if (parts.length < 2) return [w]
const total = parts.reduce((n, p) => n + p.length, 0)
let t = w.start
return parts.map((p) => {
const d = ((w.end - w.start) * p.length) / total
const x = { text: p, start: t, end: t + d }
t += d
return x
})
})
}
const wordsPath = (file: string) => `${file.slice(0, file.length - path.extname(file).length)}.words.json`
const asRaea = (ws: Word[]) => ws.map((w) => ({ text: w.text, start_ms: Math.round(w.start * 1000), end_ms: Math.round(w.end * 1000) }))
function flag(args: string[], name: string): string | undefined {
const i = args.indexOf(name)
return i >= 0 ? args[i + 1] : undefined
}
export async function main(args: string[]): Promise<number> {
const language = flag(args, "--language")
const file = args.find((a, i) => !a.startsWith("-") && args[i - 1] !== "-o" && args[i - 1] !== "--language")
if (!file || !existsSync(file)) {
console.error("usage: raea words FILE [-o OUT.words.json] [--language en] (a cut held to its lines: raea goal check CUT.mp4, with CUT.lines.txt beside it)")
return 2
}
const heard = await hear(file, language)
const o = flag(args, "-o") ?? wordsPath(file)
writeFileSync(o, `${JSON.stringify(asRaea(heard))}\n`)
console.log(`${o}: ${heard.length} words, ${heard.length ? heard[heard.length - 1].end.toFixed(1) : 0} s`)
console.log(heard.map((w) => w.text).join(" "))
return 0
}
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
// `raea transcribe` is the name agents reach for: the same thing
const a = process.argv.slice(2)
main(a[0] === "words" || a[0] === "transcribe" ? a.slice(1) : a).then(
(c) => process.exit(c),
(e) => (console.error(`raea words: ${(e as Error).message}`), process.exit(1)),
)
}