// `archilyzer tts setup` — install a text-to-speech engine (release 25 T1). // // For Kokoro (a `python-venv` engine, lib/ttsApps.ts) it builds, under // `/kokoro` (default ~/.local/share/archilyzer/tts/kokoro): // venv/ a python venv with the pinned package // (kokoro-onnx==0.6.1) — made by `uv venv --python // 3.12` when uv is on PATH, else `<--python> -m venv` // kokoro-v1.0.onnx the model files, downloaded ONCE from the // voices-v1.0.bin kokoro-onnx project's `model-files-v1.0` release // install.json what was installed, and when // // POLITE: one download at a time, one stream each, no retry loop — a failed // download is reported and the next run resumes nothing (it starts the file // again). Every file is verified by size and sha256 before it is moved into // place; a file already there and verified is never fetched again. `--from // ` takes the files from a directory that already holds them (hard // links where the filesystem allows, else copies), verified the same way — // for a machine that downloaded them once already. // // `--check` installs nothing: it lists what is missing (the venv, the package // at its pinned version — by importing it — each model file at its size) and // exits 1 when anything is. // // Orpheus (`--engine orpheus`) is the same shape: a venv with onnxruntime and // numpy (the SNAC decoder; no torch), and its GGUF, decoder and decoder config // from Hugging Face (unsloth/orpheus-3b-0.1-ft-GGUF, onnx-community/ // snac_24khz-ONNX) — 3.5 GB, so `--from` a directory that holds them already is // the polite way on a machine that has them. The llama-server it runs on is not // installed here (settings.tts.orpheus.serverBin, Ollama's bundled build by // default); setup and `--check` say when it is missing. // // espeak-ng (a `system` engine) has nothing to install: setup says whether it // is on PATH. // // Scratch (pip's build dirs) goes to `/.tmp`, never the OS temp // dir: it may be a small RAM tmpfs. import { createHash } from "node:crypto"; import { createReadStream, createWriteStream } from "node:fs"; import { copyFile, link, mkdir, rename, rm, stat } from "node:fs/promises"; import path from "node:path"; import { Readable } from "node:stream"; import { pipeline } from "node:stream/promises"; import { execa } from "execa"; import { getPaths } from "../lib/paths"; import { getSettings } from "../lib/settings"; import { DEFAULT_TTS_ENGINE_ID, getTtsEngine, ttsEngineIds, ttsInstallDir, ttsVenvPython, type TtsModelFile, } from "../lib/ttsApps"; import { findOnPath, ttsInstallState } from "../lib/ttsInstall"; import { resolveTtsHome } from "../lib/ttsSettings"; import { writeJsonAtomic } from "../lib/jsonFile-server"; export type TtsSetupOptions = { engine?: string; from?: string; python?: string; check?: boolean; // Injected by tests. home?: string; log?: (line: string) => void; fetch?: typeof fetch; envPath?: string; }; async function sha256File(file: string): Promise { const h = createHash("sha256"); await pipeline(createReadStream(file), h); return h.digest("hex"); } // "ok" when `file` is the pinned file (size, then sha256), else why not. export async function verifyModelFile(file: string, spec: TtsModelFile): Promise<"ok" | string> { const st = await stat(file).catch(() => null); if (!st?.isFile()) return "absent"; if (st.size !== spec.bytes) return `${st.size} bytes, expected ${spec.bytes}`; const sha = await sha256File(file); return sha === spec.sha256 ? "ok" : `sha256 ${sha.slice(0, 12)}…, expected ${spec.sha256.slice(0, 12)}…`; } function mb(n: number): string { return `${(n / 1_000_000).toFixed(1)} MB`; } // One stream to `.part`, verified, then renamed. No retries. export async function downloadModelFile( spec: TtsModelFile, target: string, log: (l: string) => void, doFetch: typeof fetch, ): Promise { const part = `${target}.part`; log(` downloading ${spec.url} (${mb(spec.bytes)})…`); const res = await doFetch(spec.url, { redirect: "follow" }); if (!res.ok || !res.body) throw new Error(`${spec.url} answered ${res.status}`); let got = 0; let nextReport = 0.25; const counted = Readable.fromWeb(res.body as import("node:stream/web").ReadableStream).on("data", (c: Buffer) => { got += c.length; if (got / spec.bytes >= nextReport) { log(` ${Math.round((got / spec.bytes) * 100)}%`); nextReport += 0.25; } }); try { await pipeline(counted, createWriteStream(part)); const v = await verifyModelFile(part, spec); if (v !== "ok") throw new Error(`${spec.name} downloaded but does not verify (${v})`); await rename(part, target); } catch (e) { await rm(part, { force: true }).catch(() => {}); throw e; } } // From `--from`: a hard link when the filesystem allows, else a copy. export async function adoptModelFile(src: string, target: string, spec: TtsModelFile, log: (l: string) => void): Promise { const v = await verifyModelFile(src, spec); if (v !== "ok") { log(` ${src}: ${v} — not used`); return false; } await rm(target, { force: true }); try { await link(src, target); log(` linked ${spec.name} from ${path.dirname(src)}`); } catch { const part = `${target}.part`; await copyFile(src, part); await rename(part, target); log(` copied ${spec.name} from ${path.dirname(src)}`); } return true; } // The pinned package's installed version, or null when it does not import. async function installedVersion(python: string, importName: string, dist: string): Promise { try { const { stdout } = await execa(python, [ "-c", `import ${importName}, importlib.metadata as m; print(m.version(${JSON.stringify(dist)}))`, ]); return stdout.trim() || null; } catch { return null; } } export async function main(opts: TtsSetupOptions = {}): Promise { const log = opts.log ?? ((l: string) => console.log(l)); const engineId = opts.engine ?? DEFAULT_TTS_ENGINE_ID; const engine = getTtsEngine(engineId); if (!engine) { log(`tts setup: no engine "${engineId}" — known: ${ttsEngineIds().join(", ")}`); return 2; } const paths = getPaths(); const envPath = opts.envPath ?? process.env.PATH; const setup = engine.setup; if (setup.kind === "system") { const found = findOnPath(paths[setup.bin], envPath); log(found ? `${engine.label}: ${found} — nothing to install` : `${engine.label}: ${paths[setup.bin]} is not on PATH — ${setup.hint}`); return found ? 0 : 1; } const tts = getSettings().tts; const home = opts.home ?? resolveTtsHome(tts, paths); const dir = ttsInstallDir(home, engine); const python = ttsVenvPython(dir); const [dist, pinned] = setup.packages[0].split("=="); if (opts.check) { const state = ttsInstallState(engine, { home, paths, envPath, tts }); const missing = [...state.missing]; if (!missing.some((m) => m.startsWith("the python venv"))) { const v = await installedVersion(python, setup.importName, dist); if (v !== pinned) missing.push(v ? `${dist} ${v} (pinned ${pinned})` : `${dist} does not import in the venv`); } if (missing.length === 0) { log(`${engine.label}: installed at ${dir} (${dist} ${pinned}, ${setup.files.map((f) => f.name).join(", ")})`); return 0; } log(`${engine.label} at ${dir} — missing:`); for (const m of missing) log(` - ${m}`); log(`Run \`archilyzer tts setup${engine.id === DEFAULT_TTS_ENGINE_ID ? "" : ` --engine ${engine.id}`}\` to install it.`); return 1; } log(`Installing ${engine.label} at ${dir}`); const scratch = path.join(dir, ".tmp"); await mkdir(scratch, { recursive: true }); const env = { TMPDIR: scratch, PIP_DISABLE_PIP_VERSION_CHECK: "1", NO_COLOR: "1" }; const uv = findOnPath("uv", envPath); const run = async (cmd: string, args: string[]) => { log(` $ ${[cmd, ...args].join(" ")}`); const child = execa(cmd, args, { env, all: true, buffer: false }); let pending = ""; child.all?.on("data", (c: Buffer) => { pending += c.toString("utf8"); const lines = pending.split("\n"); pending = lines.pop() ?? ""; for (const l of lines) if (l.trim()) log(` ${l.trimEnd()}`); }); await child; if (pending.trim()) log(` ${pending.trimEnd()}`); }; try { // 1. The venv. if ((await stat(python).catch(() => null)) === null) { const venv = path.join(dir, "venv"); if (opts.python) await run(opts.python, ["-m", "venv", venv]); else if (uv) await run(uv, ["venv", "--python", setup.python, venv]); else await run("python3", ["-m", "venv", venv]); } else { log(` venv present (${python})`); } // 2. The pinned package. const have = await installedVersion(python, setup.importName, dist); if (have === pinned) { log(` ${dist} ${pinned} present`); } else if (uv && !opts.python) { await run(uv, ["pip", "install", "--python", python, ...setup.packages]); } else { await run(python, ["-m", "pip", "install", ...setup.packages]); } // 3. The model files, one at a time. for (const spec of setup.files) { const target = path.join(dir, spec.name); if ((await verifyModelFile(target, spec)) === "ok") { log(` ${spec.name} present and verified`); continue; } if (opts.from && (await adoptModelFile(path.join(path.resolve(opts.from), spec.name), target, spec, log))) continue; await downloadModelFile(spec, target, log, opts.fetch ?? fetch); log(` ${spec.name} downloaded and verified`); } } catch (e) { log(`tts setup failed: ${(e as Error).message}`); return 1; } finally { await rm(scratch, { recursive: true, force: true }).catch(() => {}); } const version = await installedVersion(python, setup.importName, dist); if (version !== pinned) { log(`tts setup: ${dist} does not import at ${pinned} in ${python} (got ${version ?? "nothing"})`); return 1; } await writeJsonAtomic( path.join(dir, "install.json"), { engine: engine.id, model: engine.model, license: engine.license, packages: setup.packages, files: setup.files.map((f) => ({ name: f.name, bytes: f.bytes, sha256: f.sha256, url: f.url })), installedAt: new Date().toISOString(), }, { indent: 2 }, ); log(`${engine.label} installed: ${dir}`); // What setup cannot install: a server binary the engine runs on (Orpheus's // llama-server, settings.tts.orpheus.serverBin). const absent = (engine.requires?.(tts) ?? []).filter((r) => !findOnPath(r.path, envPath)); for (const r of absent) log(` but ${r.what} is not there: ${r.path} — install it, or point the setting at one`); return absent.length ? 1 : 0; }