// `archilyzer voice setup` — install a voice engine (release 39), for `pnpm ops // voice-enhance` / `voice-convert`. bin/tts-setup.ts's twin. // // Under `/` (default // ~/.local/share/archilyzer/voice/): // deepfilternet deep-filter DeepFilterNet's static binary // (v0.5.6, x86_64 musl; 36 MB) // openvoice venv/ python 3.12 (uv), torch 2.4.0 CPU, // torchaudio, librosa, soundfile // code/ myshell-ai/OpenVoice at a pinned commit // converter/ the v2 converter's checkpoint and // config (Hugging Face, 131 MB) // seed-vc venv/ python 3.12 (uv), torch 2.4.0 CPU, // transformers 4.46.3, librosa, … // code/ Plachtaa/seed-vc at a pinned commit // … the DiT (440 MB), whisper-small (967 // MB), BigVGAN v2 (449 MB), CAM++ (28 MB) // … (--with f0) OPTIONAL: the f0-conditioned 44.1 kHz // DiT (821 MB), its BigVGAN (489 MB) and // RMVPE (181 MB) — what `pitch: source | // contour` runs on; an install without // them converts at the target's pitch // install.json what was installed, and when // rnnoise has nothing to install (ffmpeg, and the model in the repo): setup // says whether ffmpeg has `arnndn`. // // IT SAYS WHAT IT WILL FETCH FIRST — each file, its source and its size, the // packages and the checkout — then fetches; `--dry-run` stops after saying. // POLITE, as tts setup is: one download at a time, one stream each, no retry // loop; every file verified by size and sha256 before it is moved into place; // a file already there and verified is never fetched again. `--from ` // takes files from a directory that holds them already (`/`, the // names as the install dir has them — `whisper-small/model.safetensors`), // hard-linked where it can. The checkout is `git fetch --depth 1 // `: the commit pins the code. // // `--check` installs nothing: it lists what is missing (the venv, the package // importing, the checkout at its commit, each file at its size) and exits 1 // when anything is. An optional group that is not there is SAID (with the // command that fetches it) and does not fail the check, unless it was asked // for (`--check --with f0`). // // Scratch (pip's build dirs) goes to `/.tmp`, never the OS temp // dir: it may be a small RAM tmpfs. import { chmod, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { execa } from "execa"; import { getPaths } from "../lib/paths"; import { getSettings } from "../lib/settings"; import { getVoiceEngine, voiceCodeDir, voiceEngineIds, voiceInstallDir, voiceVenvPython, type VoiceEngine, type VoiceFileGroup, } from "../lib/voiceApps"; import { VOICE_CODE_MARKER, voiceInstallState } from "../lib/voiceInstall"; import { DEFAULT_VOICE_SETTINGS, resolveVoiceHome } from "../lib/voiceSettings"; import { findOnPath } from "../lib/ttsInstall"; import { writeJsonAtomic } from "../lib/jsonFile-server"; import { adoptModelFile, downloadModelFile, verifyModelFile } from "./tts-setup"; export type VoiceSetupOptions = { engine?: string; from?: string; // Optional file groups to install too (seed-vc: "f0"). with?: string[]; python?: string; check?: boolean; dryRun?: boolean; // Injected by tests. home?: string; log?: (line: string) => void; fetch?: typeof fetch; envPath?: string; ffmpegBin?: string; // Runs git/uv/pip; default execa. run?: (cmd: string, args: string[], env: Record) => Promise; }; function mb(n: number): string { if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)} GB`; return n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)} MB` : `${(n / 1000).toFixed(1)} kB`; } /** The engine's optional groups by these ids, or the ids it does not have. */ export function pickVoiceGroups(engine: VoiceEngine, ids: readonly string[]): { groups: VoiceFileGroup[]; unknown: string[]; known: string[] } { const all = engine.setup.kind === "python-venv" ? engine.setup.optional ?? [] : []; return { groups: all.filter((g) => ids.includes(g.id)), unknown: ids.filter((id) => !all.some((g) => g.id === id)), known: all.map((g) => g.id), }; } /** * What setup fetches for an engine, in words: one line each, then the total. * The optional groups asked for (`withGroups`) are fetched and counted; the * others are listed after, as what `--with ` would add. */ export function voiceSetupPlan(engine: VoiceEngine, withGroups: readonly string[] = []): string[] { const s = engine.setup; if (s.kind === "bundled") return [`${engine.label}: nothing to download (${s.hint})`]; const lines: string[] = []; if (s.kind === "python-venv") { lines.push(` a python ${s.python} venv (uv), with: ${s.packages.join(" ")}${s.indexUrl ? ` (torch from ${s.indexUrl})` : ""}`); lines.push(` the code: ${s.code.repo} at ${s.code.commit}`); } let total = 0; for (const f of s.files) { lines.push(` ${f.name} — ${mb(f.bytes)} from ${f.url}`); total += f.bytes; } const optional = s.kind === "python-venv" ? s.optional ?? [] : []; for (const g of optional.filter((x) => withGroups.includes(x.id))) { lines.push(` with ${g.id} — ${g.label}:`); for (const f of g.files) { lines.push(` ${f.name} — ${mb(f.bytes)} from ${f.url}`); total += f.bytes; } } lines.push(` files: ${mb(total)}${s.kind === "python-venv" ? " (plus the packages: torch's CPU wheels are ~200 MB)" : ""}`); for (const g of optional.filter((x) => !withGroups.includes(x.id))) { lines.push(` optional, not fetched without \`--with ${g.id}\` — ${g.label}:`); for (const f of g.files) lines.push(` ${f.name} — ${mb(f.bytes)} from ${f.url}`); lines.push(` ${mb(g.files.reduce((n, f) => n + f.bytes, 0))} more`); } return lines; } async function importsAt(python: string, importName: string): Promise { try { const { stdout } = await execa(python, ["-c", `import ${importName}; print(${importName}.__version__)`]); return String(stdout).trim() || "?"; } catch { return null; } } async function hasArnndn(ffmpeg: string): Promise { try { const { stdout } = await execa(ffmpeg, ["-hide_banner", "-filters"]); return /\barnndn\b/.test(String(stdout)); } catch { return false; } } export async function main(opts: VoiceSetupOptions = {}): Promise { const log = opts.log ?? ((l: string) => console.log(l)); const engine = getVoiceEngine(opts.engine); if (!engine) { log(`voice setup: --engine is one of ${voiceEngineIds().join(", ")}${opts.engine ? ` (got "${opts.engine}")` : ""}`); return 2; } const paths = getPaths(); const voice = getSettings().voice ?? DEFAULT_VOICE_SETTINGS; const home = opts.home ?? resolveVoiceHome(voice, paths); const setup = engine.setup; const envPath = opts.envPath ?? process.env.PATH; const ffmpeg = opts.ffmpegBin ?? paths.ffmpegBin; if (setup.kind === "bundled") { const state = voiceInstallState(engine, { home, voiceModelsDir: paths.voiceModelsDir }); const arnndn = await hasArnndn(ffmpeg); if (state.installed && arnndn) { log(`${engine.label}: nothing to install — ${ffmpeg} has arnndn, the model is ${path.join(paths.voiceModelsDir, "sh.rnnn")}`); return 0; } log(`${engine.label}: ${[...state.missing, ...(arnndn ? [] : [`${ffmpeg} has no arnndn filter — ${setup.hint}`])].join("; ")}`); return 1; } const dir = voiceInstallDir(home, engine); const picked = pickVoiceGroups(engine, opts.with ?? []); if (picked.unknown.length) { log(`voice setup: ${engine.id} has no optional group "${picked.unknown.join('", "')}" — ${picked.known.length ? `--with is one of ${picked.known.join(", ")}` : "it has none"}`); return 2; } const withIds = picked.groups.map((g) => g.id); if (opts.check) { const state = voiceInstallState(engine, { home, voiceModelsDir: paths.voiceModelsDir }); const missing = [...state.missing]; if (setup.kind === "python-venv" && !missing.some((m) => m.startsWith("the python venv"))) { if ((await importsAt(voiceVenvPython(dir), setup.importName)) === null) missing.push(`${setup.importName} does not import in the venv`); } // A group asked for is part of the check; one not asked for is only said. for (const g of state.optional) if (withIds.includes(g.id)) missing.push(...g.missing); const said = () => { for (const g of state.optional) { if (g.installed) log(` with ${g.id} (${g.label}): installed`); else if (!withIds.includes(g.id)) { log(` optional ${g.id} (${g.label}): not installed — \`archilyzer voice setup --engine ${engine.id} --with ${g.id}\` fetches it`); } } }; const withArg = withIds.map((id) => ` --with ${id}`).join(""); if (missing.length === 0) { log(`${engine.label}: installed at ${dir}`); said(); return 0; } log(`${engine.label} at ${dir} — missing:`); for (const m of missing) log(` - ${m}`); said(); log(`Run \`archilyzer voice setup --engine ${engine.id}${withArg}\` to install it.`); return 1; } log(`${opts.dryRun ? "Would install" : "Installing"} ${engine.label} (${engine.license}) at ${dir}:`); for (const l of voiceSetupPlan(engine, withIds)) log(l); if (opts.dryRun) return 0; const scratch = path.join(dir, ".tmp"); await mkdir(scratch, { recursive: true }); const env: Record = { TMPDIR: scratch, PIP_DISABLE_PIP_VERSION_CHECK: "1", NO_COLOR: "1", GIT_TERMINAL_PROMPT: "0" }; const run = opts.run ?? (async (cmd: string, args: string[], e: Record) => { log(` $ ${[cmd, ...args].join(" ")}`); const child = execa(cmd, args, { env: e, 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 { if (setup.kind === "python-venv") { const python = voiceVenvPython(dir); const uv = findOnPath("uv", envPath); // 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], env); else if (uv) await run(uv, ["venv", "--python", setup.python, venv], env); else await run("python3", ["-m", "venv", venv], env); } else { log(` venv present (${python})`); } // 2. The pinned packages (pip and uv both skip what is already there). const index = setup.indexUrl ? ["--index-url", setup.indexUrl, "--extra-index-url", "https://pypi.org/simple"] : []; if (uv && !opts.python) { await run(uv, ["pip", "install", "--python", python, ...index, ...(index.length ? ["--index-strategy", "unsafe-best-match"] : []), ...setup.packages], env); } else { await run(python, ["-m", "pip", "install", ...index, ...setup.packages], env); } // 3. The code, at its commit. const code = voiceCodeDir(dir); const marker = path.join(code, VOICE_CODE_MARKER); const at = await readFile(marker, "utf8").then((s) => s.trim(), () => null); if (at === setup.code.commit) { log(` ${setup.code.repo} at ${setup.code.commit.slice(0, 10)} present`); } else { await rm(code, { recursive: true, force: true }); await mkdir(code, { recursive: true }); await run("git", ["-C", code, "init", "-q"], env); await run("git", ["-C", code, "fetch", "-q", "--depth", "1", setup.code.repo, setup.code.commit], env); await run("git", ["-C", code, "checkout", "-q", "FETCH_HEAD"], env); const { stdout } = await execa("git", ["-C", code, "rev-parse", "HEAD"]); if (String(stdout).trim() !== setup.code.commit) throw new Error(`the checkout is at ${String(stdout).trim()}, not ${setup.code.commit}`); await writeFile(marker, `${setup.code.commit}\n`); } } // 4. The files, one at a time. for (const spec of [...setup.files, ...picked.groups.flatMap((g) => g.files)]) { const target = path.join(dir, spec.name); await mkdir(path.dirname(target), { recursive: true }); if ((await verifyModelFile(target, spec)) === "ok") { log(` ${spec.name} present and verified`); } else if (!(opts.from && (await adoptModelFile(path.join(path.resolve(opts.from), spec.name), target, spec, log)))) { await downloadModelFile(spec, target, log, opts.fetch ?? fetch); log(` ${spec.name} downloaded and verified`); } if (spec.executable) await chmod(target, 0o755); } } catch (e) { log(`voice setup failed: ${(e as Error).message}`); return 1; } finally { await rm(scratch, { recursive: true, force: true }).catch(() => {}); } if (setup.kind === "python-venv" && (await importsAt(voiceVenvPython(dir), setup.importName)) === null) { log(`voice setup: ${setup.importName} does not import in ${voiceVenvPython(dir)}`); return 1; } const state = voiceInstallState(engine, { home, voiceModelsDir: paths.voiceModelsDir }); const stillMissing = [...state.missing, ...state.optional.filter((g) => withIds.includes(g.id)).flatMap((g) => g.missing)]; if (stillMissing.length) { log(`voice setup: still missing ${stillMissing.join("; ")}`); return 1; } // What is there now, whichever run fetched it. const groupsThere = picked.known.filter((id) => state.optional.find((g) => g.id === id)?.installed); const optionalGroups = pickVoiceGroups(engine, groupsThere).groups; await writeJsonAtomic( path.join(dir, "install.json"), { engine: engine.id, model: engine.model, license: engine.license, ...(setup.kind === "python-venv" ? { packages: setup.packages, code: setup.code } : {}), files: setup.files.map((f) => ({ name: f.name, bytes: f.bytes, sha256: f.sha256, url: f.url })), ...(optionalGroups.length ? { optional: optionalGroups.map((g) => ({ id: g.id, files: g.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}${optionalGroups.length ? ` (with ${optionalGroups.map((g) => g.id).join(", ")})` : ""}`); return 0; }