Clone your own voice on your own computer: speak any text in 60+ languages and dub videos into another language in your voice. Fully local. Early version.
Rust chatterboxdesktopdubbingmobilemultilingualofflineomnivoicerustrvcspeech-synthesisspeech-to-textstttext-to-speechttsvoice-cloningvoxcpm2whisper
"""Set Mimvox up fully on Linux, macOS and Windows (``./setup.sh`` or ``setup.cmd``). Standard library only: it runs
before anything else is installed."""
from __future__ import annotations
import argparse
import contextlib
import email.utils
import hashlib
import http.client
import io
import json
import os
import platform
import re
import shutil
import ssl
import subprocess
import sys
import tarfile
import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import zipfile
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathlib import Path
APP_DIR_NAME = "mimvox"
LOCKS = Path(__file__).with_name("locks") # written by lock.py from a working runtime
def lock_args(env: str) -> list[str]:
"""Every package of that environment at the version it was tested with."""
return ["-c", str(LOCKS / f"{env}.txt")]
def canonical_name(name: str) -> str:
return re.sub(r"[-_.]+", "-", name).lower()
def lock_stamp(env: str) -> str:
return hashlib.sha256((LOCKS / f"{env}.txt").read_bytes()).hexdigest()[:12]
def runtime_version() -> int:
"""The app reads the same file."""
path = Path(__file__).with_name("runtime_version.txt")
try:
lines = [line.strip() for line in path.read_text(encoding="utf-8").splitlines()]
return int(next(line for line in lines if line and not line.startswith("#")))
except (OSError, StopIteration, ValueError):
return 1
DATA_ENV = "MIMVOX_DATA"
LOCATION_FILE = "location.toml"
UV_ENV = "MIMVOX_UV"
BIN_NAME = "mimvox"
# Pinned upstream revisions: bump deliberately.
APPLIO_URL = "https://github.com/IAHispano/Applio.git"
APPLIO_COMMIT = "6d5d9511b7e719b1f613362bc767e841ad72fa72"
TORCH_CUDA_INDEX = "https://download.pytorch.org/whl/cu128"
TORCH_ROCM_INDEX = "https://download.pytorch.org/whl/rocm7.2"
AMD_PCI_VENDOR = "0x1002"
# Integrated Radeon GPUs report a small VRAM carve-out; below this the card is not used.
AMD_MIN_VRAM_GB = 4.0
APPLIO_PYTHON = "3.12"
# Files that prove a download finished (relative to the repo they belong to).
APPLIO_REQUIRED = (
"rvc/models/predictors/rmvpe.pt",
"rvc/models/embedders/contentvec/pytorch_model.bin",
"rvc/models/embedders/contentvec/config.json",
"rvc/models/pretraineds/hifi-gan/f0G40k.pth",
"rvc/models/pretraineds/hifi-gan/f0D40k.pth",
)
# Windows only: Applio's `prerequisites --exe` puts these in the Applio folder; the engine uses them for every audio
# and video format (Linux and macOS use the system ffmpeg and ffprobe).
APPLIO_WINDOWS_REQUIRED = ("ffmpeg.exe", "ffprobe.exe")
# Redub models, under <data>/runtime/models (the speech worker loads them from there, never from the user's cache).
NLLB_REPO = "facebook/nllb-200-distilled-600M"
NLLB_DIR = "nllb-200-distilled-600M"
NLLB_FILES = (
"config.json",
"generation_config.json",
"pytorch_model.bin",
"sentencepiece.bpe.model",
"special_tokens_map.json",
"tokenizer.json",
"tokenizer_config.json",
)
NLLB_REQUIRED = ("config.json", "pytorch_model.bin", "sentencepiece.bpe.model", "tokenizer_config.json")
# "Better translation" (optional; a default with a GPU): NLLB-200 distilled 1.3B. The repo only has fp32
# weights (pytorch_model.bin, 5.5 GB), so they are downloaded, stored as fp16 safetensors (2.7 GB) and the .bin deleted.
NLLB_BIG_REPO = "facebook/nllb-200-distilled-1.3B"
NLLB_BIG_DIR = "nllb-200-distilled-1.3B"
NLLB_BIG_REQUIRED = ("config.json", "model.safetensors", "sentencepiece.bpe.model", "tokenizer_config.json")
NLLB_BIG_DOWNLOAD_GB = 5.5
# fp32 checkpoint -> fp16 model.safetensors in another folder (the tied embeddings are stored once). Engine interpreter.
NLLB_FP16_SCRIPT = (
"import sys, torch, transformers\n"
"from transformers import AutoModelForSeq2SeqLM\n"
"key = 'dtype' if int(transformers.__version__.split('.')[0]) >= 5 else 'torch_dtype'\n"
"model = AutoModelForSeq2SeqLM.from_pretrained(sys.argv[1], local_files_only=True, low_cpu_mem_usage=True,\n"
" **{key: torch.float16})\n"
"model.save_pretrained(sys.argv[2], max_shard_size='20GB')\n"
)
# Seed-VC (GPL-3.0) for the native accent of untrained voices: a separately downloaded runtime component, never part
# of this repository.
SEEDVC_URL = "https://github.com/Plachtaa/seed-vc.git"
SEEDVC_COMMIT = "51383efd921027683c89e5348211d93ff12ac2a8"
SEEDVC_DIR = "seed-vc" # <runtime>/seed-vc (code) and <runtime>/models/seed-vc (weights)
SEEDVC_PACKAGES = ("munch==4.0.0", "einops==0.8.0")
SEEDVC_MODELS = ( # (subfolder, Hugging Face repo, revision, files)
(
"dit",
"Plachta/Seed-VC",
"257283f9f41585055e8f858fba4fd044e5caed6e",
(
"DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth",
"config_dit_mel_seed_uvit_whisper_small_wavenet.yml",
),
),
(
"bigvgan",
"nvidia/bigvgan_v2_22khz_80band_256x",
"633ff708ed5b74903e86ff1298cf4a98e921c513",
("config.json", "bigvgan_generator.pt"),
),
(
"whisper-small",
"openai/whisper-small",
"973afd24965f72e36ca33b3055d56a652f456b4d",
("config.json", "preprocessor_config.json", "model.safetensors"),
),
)
SEEDVC_STAMP = ".mimvox-setup-ok" # in the weights folder: the engine uses the converter only once it is there
ZERO_SHOT_GB = 2.0 # Seed-VC checkout (~0.1 GB) + weights (1.8 GB: DiT 0.44, BigVGAN 0.45, Whisper-small 0.97)
# HolosTTS (MIT): Ukrainian with exact word stress, in its own venv because its ukrainian-word-stress fork has the
# package name of the lang-uk one the engine venv uses for OmniVoice's stress hints.
HOLOS_DIR = "holos" # <runtime>/holos/.venv and <runtime>/models/holos
HOLOS_PYTHON = "3.14"
HOLOS_PACKAGES = (
"holos-tts==0.4",
"stanza==1.15.1",
"transformers==5.23.0",
"huggingface-hub==2.4.0",
"marisa-trie==1.4.1",
"librosa==0.11.0",
"soundfile==0.14.0",
"numpy==2.4.6",
"scipy==1.17.1",
"num2words==0.5.14",
# archives at pinned commits, not git: setup works without git (and its certificate setup)
"ipa-uk @ https://github.com/patriotyk/ipa-uk/archive/3faf05ec50fd4880965b6c76f8e479a4f82117f5.zip",
(
"ukrainian-accentor @ https://github.com/egorsmkv/ukrainian-accentor/archive/"
"3dff5ecd2ac91e879086c0e2a7f1ce079603c9f1.zip"
),
)
# --no-deps: its metadata asks for ukrainian-accentor from git (installed above from the same commit's archive).
HOLOS_NO_DEPS = (
(
"ukrainian-word-stress @ https://github.com/patriotyk/ukrainian-word-stress/archive/"
"d5b37ea0abe9711930d9c3b0b13edec5a0675512.zip"
),
)
HOLOS_REPO = "patriotyk/HolosTTS"
HOLOS_REVISION = "main"
HOLOS_FILES = ("holos.pt", "voice_encoder.pt", "voices.pt")
HOLOS_STANZA = "stanza" # <runtime>/models/holos/stanza: STANZA_RESOURCES_DIR of the worker
HOLOS_STANZA_PROCESSORS = "tokenize,pos,mwt"
HOLOS_STAMP = ".mimvox-setup-ok" # in <runtime>/models/holos: the engine uses HolosTTS only once it is there
UKRAINIAN_GB = 1.5 # weights 0.9 GB + the packages the engine venv does not share (Stanza, ipa-uk, ...)
# Chatterbox's watermarker imports pkg_resources, which setuptools 82 drops.
CLONE_MODELS = {
"voxcpm": {
"label": "VoxCPM2",
"packages": ("voxcpm==2.0.3", "transformers==5.24.1", "huggingface-hub==2.5.0", "num2words==0.5.14"),
"repo": "openbmb/VoxCPM2",
"revision": "7936080b41163874f38610f46f438e2c0757f9fd",
"files": (),
"required": ("model.safetensors", "audiovae.pth", "config.json"),
"download_gb": 4.7,
},
"chatterbox": {
"label": "Chatterbox",
"packages": ("chatterbox-tts==0.1.7", "num2words==0.5.14", "setuptools==81.0.0"),
"repo": "ResembleAI/chatterbox",
"revision": "5bb1f6ee58e50c3b8d408bc82a6d3740c2db6e18",
"files": (
"ve.pt",
"t3_mtl23ls_v2.safetensors",
"s3gen.pt",
"grapheme_mtl_merged_expanded_v1.json",
"conds.pt",
"Cangjie5_TC.json",
),
"required": ("t3_mtl23ls_v2.safetensors", "s3gen.pt", "ve.pt", "conds.pt"),
"download_gb": 3.0,
"after": "from spacy_pkuseg import pkuseg; pkuseg()",
},
}
CLONE_STAMP = ".mimvox-setup-ok"
WHISPER_MODEL = "turbo"
# The checkpoint openai-whisper downloads for "turbo" (whisper._MODELS; the SHA-256 is part of the URL). Fetched by
# setup directly: importing whisper only to download it loaded torch and numba (LLVM) for nothing.
WHISPER_FILE = "large-v3-turbo.pt"
WHISPER_SHA256 = "aff26ae408abcba5fbf8813c21e62b0941638c5f6eebfb145be0c9839262a19a"
WHISPER_URL = f"https://openaipublic.azureedge.net/main/whisper/models/{WHISPER_SHA256}/{WHISPER_FILE}"
# torchaudio's HDEMUCS_HIGH_MUSDB_PLUS weights (the file that bundle downloads); the speech worker loads them from
# <data>/runtime/models/demucs.
DEMUCS_URL = "https://download.pytorch.org/torchaudio/models/hdemucs_high_trained.pt"
# fastText's language identification model: Design warns when the text is in another language than the one picked.
LID_URL = "https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.ftz"
LID_SHA256 = "8f3472cfe8738a7b6099e8e999c3cbfae0dcd15696aac7d7738a8039db603e83"
LID_DIR, LID_FILE = "lid", "lid.176.ftz"
DEMUCS_DIR = "demucs"
DEMUCS_FILE = "hdemucs_high_trained.pt"
DEMUCS_SIZE = 334_697_255
DEMUCS_SHA256 = "a004b2790d73ffeaa535db458a1a79b539dfdbafbccc31f275d07e632ebd7816"
# llama.cpp's prebuilt llama-server (MIT) for Character voices: (archive, its SHA-256) per platform, GPU and
# architecture; the CUDA builds use the CUDA runtime and cuBLAS that come with the engine's torch.
LLAMA_RELEASE = "b12818"
LLAMA_URL = "https://github.com/ggml-org/llama.cpp/releases/download/{release}/{name}"
LLAMA_BUILDS = {
("linux", "x64", "cuda"): (
"llama-b12818-bin-ubuntu-cuda-12.8-x64.tar.gz",
"15357a570be29f2698d6d0a1e4e0a891f50adf7eb67a81b12b6ea1159ebdabf8",
),
("linux", "x64", "vulkan"): (
"llama-b12818-bin-ubuntu-vulkan-x64.tar.gz",
"d9eb24826e4fd20ca3ca22feb2087faae21184606fd595602ca8704510b78317",
),
("linux", "arm64", "vulkan"): (
"llama-b12818-bin-ubuntu-vulkan-arm64.tar.gz",
"e007a8c3fd71f8da5f7cfc654094460e581b59a813b86bc5e6b81b5586ef441e",
),
("windows", "x64", "cuda"): (
"llama-b12818-bin-win-cuda-12.4-x64.zip",
"3966a614a31b695c13f80649b393e32e0f5b65e5a3d57a58be2afa1f9ddd8265",
),
("windows", "x64", "vulkan"): (
"llama-b12818-bin-win-vulkan-x64.zip",
"b4ae261e98b2d74a2fa2167175d5f5441a3219fb2592228d207223cb5e961982",
),
("windows", "arm64", "vulkan"): (
"llama-b12818-bin-win-vulkan-arm64.zip",
"225bd3d1611fa55842c146d11923a1cc55bab17a587673eac8bdfe1c4c554bc9",
),
("macos", "arm64", "metal"): (
"llama-b12818-bin-macos-arm64.tar.gz",
"b05fc72e0ed39d343f7e955d3fc67087ea56e161dc0cfb462f5f0163af372234",
),
("macos", "x64", "metal"): (
"llama-b12818-bin-macos-x64.tar.gz",
"fb387c67db69f9b40ff920a54353f235b8c112744a662350a3f129940dfaf85a",
),
}
LLAMA_DIR = "llama" # <runtime>/llama, also in engine/src/mimvox_engine/cast.py
LLAMA_STAMP = ".mimvox-llama"
# Gemma 4 12B instruct (Apache-2.0), Q4_K_M: who speaks each line of a book (engine cast.py).
CAST_REPO = "unsloth/gemma-4-12b-it-GGUF"
CAST_REVISION = "fc034cfff751157913579611efad8462ac1be606"
CAST_FILE = "gemma-4-12b-it-Q4_K_M.gguf"
CAST_SIZE = 7_121_861_440
CAST_SHA256 = "0a270ec9fe6b34f4a0d33992b6135117b484ebc4766ab76b51d4ae8c457e4c42"
CAST_DIR = "llm"
CAST_OLD_DIR = "lyrics" # where the dropped Sing feature kept the same file
CAST_GB = 7.4
CAST_MIN_VRAM_GB = 10.0 # 7.7 GB on the GPU while it reads, plus the desktop's share
ENGINE_DIR = "engine"
UV_PYTHON_DIR = "python" # <runtime>/python, also in move_runtime.fix_venv_paths and crates/desktop/src/ui/setuprun.rs
ENGINE_PYTHON = "3.14"
PIN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*==[^\s;@]+$") # a `uv pip freeze` line of a registry package
ENGINE_TORCH = ("torch==2.11.0", "torchaudio==2.11.0")
# pypdf (BSD-3-Clause, pure Python): PDF books; every other book format is read with the standard library.
ENGINE_PACKAGES = (
"omnivoice==0.2.1",
"transformers==5.24.1",
"huggingface-hub==2.5.0",
"openai-whisper==20250625",
"num2words==0.5.14",
"sentencepiece",
"g2p_en==2.1.0",
"soundfile",
"librosa",
"scipy",
"numpy",
"marisa-trie==1.4.1",
"pypdf==6.21.4",
)
# --no-deps: its Stanza dependency (and the ~500 MB of models Stanza downloads) is only needed for the context mode,
# which is not used; the dictionary-only mode works offline.
ENGINE_NO_DEPS = ("ukrainian-word-stress==2.1.0",)
NLTK_DIR = "nltk_data" # in the engine venv
# g2p_en's import looks for the first two (else downloads them); NLTK 3.9+ tags with the third.
NLTK_PACKAGES = (
("corpora", "cmudict"),
("taggers", "averaged_perceptron_tagger"),
("taggers", "averaged_perceptron_tagger_eng"),
)
OMNIVOICE_REPO = "k2-fsa/OmniVoice"
OMNIVOICE_DIR = "omnivoice" # <runtime>/models/omnivoice
OMNIVOICE_REQUIRED = (
"config.json",
"model.safetensors",
"tokenizer.json",
"tokenizer_config.json",
"audio_tokenizer/config.json",
"audio_tokenizer/model.safetensors",
"audio_tokenizer/preprocessor_config.json",
)
MIN_RUST = (1, 97)
RUNTIME_GB = 30
OMNIVOICE_GB = 3.3
APPLIO_GB = 12
SPEECH_GB = 4.5 # Whisper turbo (1.6 GB) + the NLLB-200 translation model (2.5 GB) for Redub
BETTER_TRANSLATION_GB = 2.7 # NLLB-200 1.3B in fp16 (a 5.5 GB download), with a GPU or --better-translation yes
SEPARATION_GB = 0.3 # Hybrid Demucs (335 MB) for "Remove background music"
LEGACY_INDEXTTS_DIR = "index-tts" # the IndexTTS-2.5 runtime of earlier versions (about 19 GB), no longer used
DISK_NEEDED_GB = 34
# "speech" is always installed; the rest are chosen in the app (or --components / --add) and recorded in runtime.toml.
# Sizes on disk in GB, also in COMPONENTS in crates/desktop/src/ui/setuprun.rs.
COMPONENTS = {
"speech": 9.3, # engine venv (7.7) + Whisper turbo (1.6)
"omnivoice": OMNIVOICE_GB,
"training": APPLIO_GB, # Applio/RVC: Train, voice match for trained voices, Redub's Convert voice
"translation": 2.5, # NLLB-200 600M: Redub's Translate & dub
"better_translation": BETTER_TRANSLATION_GB, # NLLB-200 1.3B (a 5.5 GB download)
"native_accent": ZERO_SHOT_GB, # Seed-VC: the native accent of voices that are not trained
"music_removal": SEPARATION_GB, # Hybrid Demucs: background music out of media files
"ukrainian": UKRAINIAN_GB, # HolosTTS: Ukrainian with exact word stress
"voxcpm": 6.0,
"chatterbox": 4.3,
"cast": CAST_GB, # Gemma 4 12B and llama.cpp: Book mode reads each character's lines in a man's or woman's voice
}
SPEECH_MODELS = ("omnivoice", "voxcpm", "chatterbox")
# Portable ffmpeg for Windows when Applio (which brings one) is not installed.
FFMPEG_WINDOWS_URL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-{}-gpl.zip"
UV_HTTP_TIMEOUT = "600"
UV_HTTP_RETRIES = "5"
# Records the commit of a source tree that came as an archive (no git).
ARCHIVE_MARKER = ".mimvox-commit"
# Linux packages: a C/C++ toolchain and the libraries Rune (wgpu, winit, cpal, fontconfig) builds and runs against,
# plus ffmpeg and libsndfile for the Python side. Keys are the package managers' names.
LINUX_PACKAGES = {
"apt-get": [
"build-essential",
"pkg-config",
"git",
"curl",
"ca-certificates",
"ffmpeg",
"libsndfile1",
"libasound2-dev",
"libxkbcommon-dev",
"libxkbcommon-x11-0",
"libwayland-dev",
"libx11-dev",
"libfontconfig1-dev",
"libvulkan1",
"mesa-vulkan-drivers",
"libportaudio2",
],
"dnf": [
"gcc",
"gcc-c++",
"make",
"pkgconf-pkg-config",
"git",
"curl",
"ffmpeg-free",
"libsndfile",
"alsa-lib-devel",
"libxkbcommon-devel",
"libxkbcommon-x11",
"wayland-devel",
"libX11-devel",
"fontconfig-devel",
"vulkan-loader",
"mesa-vulkan-drivers",
"portaudio",
],
"pacman": [
"base-devel",
"pkgconf",
"git",
"curl",
"ffmpeg",
"libsndfile",
"alsa-lib",
"libxkbcommon",
"libxkbcommon-x11",
"wayland",
"libx11",
"fontconfig",
"vulkan-icd-loader",
"vulkan-mesa-layers",
"portaudio",
],
"zypper": [
"gcc",
"gcc-c++",
"make",
"pkg-config",
"git",
"curl",
"ffmpeg",
"libsndfile1",
"alsa-devel",
"libxkbcommon-devel",
"libxkbcommon-x11-0",
"wayland-devel",
"libX11-devel",
"fontconfig-devel",
"libvulkan1",
"portaudio",
],
}
LINUX_INSTALL = {
"apt-get": ["apt-get", "install", "-y"],
"dnf": ["dnf", "install", "-y"],
"pacman": ["pacman", "-S", "--needed", "--noconfirm"],
"zypper": ["zypper", "--non-interactive", "install"],
}
WINGET = ["winget", "install", "--exact", "--accept-source-agreements", "--accept-package-agreements", "--id"]
WINGET_BUILD_TOOLS = "Microsoft.VisualStudio.2022.BuildTools"
BUILD_TOOLS_OVERRIDE = "--quiet --wait --norestart --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"
VC_COMPONENT = "Microsoft.VisualStudio.Component.VC.Tools.x86.x64"
XCODE_WAIT_SECONDS = 30 * 60
XCODE_POLL_SECONDS = 10
class SetupError(RuntimeError):
"""A step could not complete; the message is the one line the user sees."""
# Run by the app (--gui): progress goes out as "@@mimvox {json}" lines next to the readable ones (see event()).
GUI = False
def say(line: str) -> None:
print(f"[setup] {line}", flush=True)
def event(**fields: object) -> None:
"""Only with --gui: ``plan`` (the steps that will run), ``step`` (one starts, succeeds or fails), ``progress``
(how far the running step is) and ``done``."""
if GUI:
print("@@mimvox " + json.dumps(fields), flush=True)
class StepMeter:
"""Sends ``progress`` events for a running step from how much the data drive filled against the step's size."""
current: StepMeter | None = None
def __init__(self, folder: Path, step: str, gb: float) -> None:
self.folder, self.step, self.expected = folder, step, max(gb, 0.05) * 1e9
self.start = self._used()
self.peak = 0.0
self._stop = threading.Event()
self._thread = threading.Thread(target=self._watch, daemon=True)
StepMeter.current = self
self._thread.start()
def expect(self, remaining_bytes: int) -> None:
"""The step's size is what it wrote so far plus ``remaining_bytes`` still to download."""
self.expected = max(self.written_gb() * 1e9 + remaining_bytes, 0.05e9)
event(event="size", id=self.step, gb=round(self.expected / 1e9, 3))
def _used(self) -> int:
folder = self.folder
while not folder.exists() and folder != folder.parent:
folder = folder.parent
try:
return shutil.disk_usage(folder).used
except OSError:
return 0
def written_gb(self) -> float:
"""The most the step had on the drive at once: a download converted and deleted still counts."""
self.peak = max(self.peak, max(0, self._used() - self.start) / 1e9)
return self.peak
def _watch(self) -> None:
sent = 0.0
while not self._stop.wait(1.0):
done = min(self.written_gb() * 1e9 / self.expected, 0.97)
if done - sent >= 0.005:
sent = done
event(event="progress", id=self.step, done=round(done, 3), gb=round(self.written_gb(), 3))
def stop(self) -> float:
self._stop.set()
self._thread.join()
if StepMeter.current is self:
StepMeter.current = None
return self.written_gb()
def expect_download(remaining_bytes: int | None) -> None:
if remaining_bytes is not None and StepMeter.current is not None:
StepMeter.current.expect(remaining_bytes)
# Seconds to wait before the second, third and fourth attempt of a download.
RETRY_WAITS = (2.0, 8.0, 30.0)
RETRY_AFTER_MAX = 300.0
NETWORK_ERRORS = (OSError, http.client.HTTPException)
NETWORK_FAILURE = re.compile(
r"could not resolve host|temporary failure in name resolution|name or service not known|nodename nor servname"
r"|getaddrinfo failed|no such host is known|network is unreachable|connection (reset|refused|aborted|closed)"
r"|connectionreseterror|connectionrefusederror|connecterror|readerror|readtimeout|connecttimeout|timed ?out"
r"|early eof|rpc failed|unexpected disconnect|remote end hung up|empty reply from server|transfer closed"
r"|http/2 stream|ssl_read|ssl_error_syscall|gnutls recv error|schannel: failed|failed to connect"
r"|returned error: (5\d\d|408|429)|\b(5\d\d|408|429) (server|client) error|server error '5|too many requests"
r"|bad gateway|service unavailable|gateway time-?out|internal server error|incompleteread|chunkedencodingerror"
r"|remoteprotocolerror|server disconnected|peer closed connection",
re.IGNORECASE,
)
PERMANENT_FAILURE = re.compile(
r"\b40[134] (client error|forbidden|not found|unauthorized)|returned error: 40[134]|http error 40[134]"
r"|client error '40[134]|repositorynotfounderror|gatedrepoerror|revisionnotfounderror|entrynotfounderror"
r"|not our ref|couldn't find remote ref|authentication failed|repository not found|no module named",
re.IGNORECASE,
)
def retry_after(value: str | None) -> float | None:
"""A Retry-After header (seconds or an HTTP date) in seconds, at most ``RETRY_AFTER_MAX``."""
if not value:
return None
value = value.strip()
if value.isdigit():
seconds = float(value)
else:
try:
when = email.utils.parsedate_to_datetime(value)
except (TypeError, ValueError):
return None
if when.tzinfo is None:
when = when.replace(tzinfo=UTC)
seconds = (when - datetime.now(UTC)).total_seconds()
return min(max(seconds, 0.0), RETRY_AFTER_MAX)
def retry_wait(error: BaseException, attempt: int) -> float | None:
"""How long to wait before trying again after ``error``; ``None`` when trying again cannot help."""
if isinstance(error, urllib.error.HTTPError):
if error.code not in (408, 429) and error.code < 500:
return None
after = retry_after(error.headers.get("Retry-After") if error.headers else None)
return RETRY_WAITS[attempt] if after is None else after
if isinstance(error, ssl.SSLCertVerificationError) or (
isinstance(error, urllib.error.URLError) and isinstance(error.reason, ssl.SSLCertVerificationError)
):
return None
if isinstance(
error, (urllib.error.URLError, http.client.HTTPException, ConnectionError, TimeoutError, ssl.SSLError)
):
return RETRY_WAITS[attempt]
return None
def with_retries[T](label: str, action: Callable[[], T]) -> T:
"""``action`` again after a temporary network failure, up to ``len(RETRY_WAITS)`` more times."""
attempt = 0
while True:
try:
return action()
except NETWORK_ERRORS as error:
wait = retry_wait(error, attempt) if attempt < len(RETRY_WAITS) else None
if wait is None:
raise
attempt += 1
say(f"{label}: {error}; trying again in {wait:.0f} s (attempt {attempt + 1} of {len(RETRY_WAITS) + 1})...")
time.sleep(wait)
def check_complete(response: http.client.HTTPResponse, received: int) -> None:
"""A body cut short is an error: urllib returns it as if it were complete."""
expected = int(response.headers.get("Content-Length") or 0)
if expected and received < expected:
raise http.client.IncompleteRead(b"", expected - received)
def network_failure(output: str) -> bool:
"""Whether a download command's output ends in an error that trying again can fix."""
return not PERMANENT_FAILURE.search(output) and bool(NETWORK_FAILURE.search(output))
def hf_bytes(repo: str, target: Path, files: Sequence[str] = (), revision: str = "main") -> int | None:
"""What a Hugging Face download still has to fetch into ``target`` (``files`` empty: the whole repo); ``None``
when the Hub cannot be asked."""
endpoint = os.environ.get("HF_ENDPOINT", "https://huggingface.co").rstrip("/")
url = f"{endpoint}/api/models/{repo}/tree/{urllib.parse.quote(revision, safe='')}?recursive=true"
def ask() -> object:
with urllib.request.urlopen(url, timeout=15) as response:
return json.load(response)
try:
listing = with_retries(f"Size of {repo}", ask)
except (*NETWORK_ERRORS, ValueError):
return None
if not isinstance(listing, list):
return None
sizes = {
e["path"]: int((e.get("lfs") or {}).get("size") or e.get("size") or 0)
for e in listing
if isinstance(e, dict) and e.get("type") == "file" and "path" in e
}
wanted = [p for p in sizes if not files or p in files]
return sum(sizes[p] for p in wanted if not ((target / p).is_file() and (target / p).stat().st_size == sizes[p]))
def url_bytes(url: str) -> int | None:
def ask() -> int | None:
with urllib.request.urlopen(urllib.request.Request(url, method="HEAD"), timeout=15) as response:
return int(response.headers.get("Content-Length") or 0) or None
try:
return with_retries(f"Size of {url}", ask)
except (*NETWORK_ERRORS, ValueError):
return None
def warn(line: str) -> None:
print(f"[setup] WARNING: {line}", flush=True)
def host_platform() -> str:
if sys.platform.startswith("win"):
return "windows"
return "macos" if sys.platform == "darwin" else "linux"
def host_arch() -> str:
machine = platform.machine().lower()
if machine in ("amd64", "x86_64", "x64"):
return "x86_64"
if machine in ("arm64", "aarch64"):
return "arm64"
return machine
def platform_data_dir(plat: str) -> Path:
"""On Windows the *local* app data: the runtime is about 28 GB and the roaming profile can be synced or copied."""
home = Path.home()
if plat == "windows":
return Path(os.environ.get("LOCALAPPDATA") or home / "AppData" / "Local")
if plat == "macos":
return home / "Library" / "Application Support"
return Path(os.environ.get("XDG_DATA_HOME") or home / ".local" / "share")
def default_data_dir(plat: str) -> Path:
return platform_data_dir(plat) / APP_DIR_NAME
def config_dir(plat: str) -> Path:
"""Fixed per-user folder of the pointer file ``location.toml`` (the app looks here for a custom data dir)."""
home = Path.home()
if plat == "windows":
return Path(os.environ.get("LOCALAPPDATA") or home / "AppData" / "Local") / APP_DIR_NAME
if plat == "macos":
return home / "Library" / "Application Support" / APP_DIR_NAME
return Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config") / APP_DIR_NAME
def location_file(plat: str) -> Path:
return config_dir(plat) / LOCATION_FILE
def read_location(plat: str) -> Path | None:
try:
import tomllib
value = tomllib.loads(location_file(plat).read_text(encoding="utf-8")).get("data_dir")
except (OSError, ValueError, ImportError):
return None
return Path(value) if isinstance(value, str) and value.strip() else None
def previous_components(data_dir: Path) -> set[str] | None:
"""runtime.toml ``[setup] components``; None before there were any."""
import tomllib
try:
found = (
tomllib.loads((data_dir / "runtime.toml").read_text(encoding="utf-8")).get("setup", {}).get("components")
)
except (OSError, ValueError):
return None
return {c for c in found if c in COMPONENTS} if isinstance(found, list) else None
def recorded_gpu(data_dir: Path) -> Gpu | None:
"""runtime.toml ``[device]`` of an earlier run; None before there was one."""
import tomllib
try:
device = tomllib.loads((data_dir / "runtime.toml").read_text(encoding="utf-8")).get("device", {})
backend = str(device["backend"]).lower()
return Gpu(
backend, str(device.get("name", "")), float(device.get("vram_gb", 0.0)), str(device.get("vendor", ""))
)
except (OSError, ValueError, KeyError, TypeError, AttributeError):
return None
def has_runtime(data_dir: Path) -> bool:
return (
(data_dir / "runtime.toml").is_file()
or (data_dir / "runtime" / ENGINE_DIR).is_dir()
or (data_dir / "runtime" / LEGACY_INDEXTTS_DIR).is_dir()
)
def _drive_exists(root: str) -> bool:
try:
return Path(root).exists()
except OSError:
return False
def volumes(plat: str) -> list[tuple[str, float]]:
"""``(mount point or drive, free GB)`` of the volumes worth offering for the install."""
roots: list[str] = []
if plat == "windows":
roots = [f"{c}:\\" for c in "CDEFGHIJKLMNOPQRSTUVWXYZ" if _drive_exists(f"{c}:\\")]
else:
roots = ["/", str(Path.home())]
for base in ("/mnt", "/media", "/run/media", "/Volumes"):
try:
for entry in sorted(Path(base).iterdir()):
if entry.is_dir():
roots.append(str(entry))
except OSError:
continue
seen: set[tuple[int, int]] = set()
out: list[tuple[str, float]] = []
for root in roots:
try:
usage = shutil.disk_usage(root)
dev = Path(root).stat().st_dev
except OSError:
continue
key = (dev, usage.total)
if key in seen:
continue
seen.add(key)
out.append((root, usage.free / 1e9))
return out
def venv_python(venv: Path, plat: str) -> Path:
return venv / ("Scripts/python.exe" if plat == "windows" else "bin/python")
def venv_home(venv: Path) -> Path | None:
"""pyvenv.cfg ``home``: the folder of the Python the venv was made from."""
try:
lines = (venv / "pyvenv.cfg").read_text(encoding="utf-8").splitlines()
except OSError:
return None
for line in lines:
key, sep, value = line.partition("=")
if sep and key.strip() == "home":
return Path(value.strip())
return None
def venv_version(venv: Path) -> str | None:
"""pyvenv.cfg ``version_info`` as ``major.minor``."""
try:
lines = (venv / "pyvenv.cfg").read_text(encoding="utf-8").splitlines()
except OSError:
return None
for line in lines:
key, sep, value = line.partition("=")
if sep and key.strip() == "version_info":
return ".".join(value.strip().split(".")[:2])
return None
def _is_junction(path: Path) -> bool:
return getattr(path, "is_junction", lambda: False)()
def _inside(child: Path, parent: Path) -> bool:
c, p = os.path.normcase(str(child)), os.path.normcase(str(parent)).rstrip("\\/")
return c == p or c.startswith(p + os.sep)
def swap_venv(venv: Path, new: Path) -> None:
old = venv.with_name(venv.name + ".old")
if old.exists():
_rmtree(old)
venv.rename(old)
try:
new.rename(venv)
except OSError:
old.rename(venv)
raise
restore_swapped(venv)
def restore_swapped(venv: Path) -> None:
"""Puts the old venv back after an interrupted swap_venv, then deletes the leftovers."""
old, new = venv.with_name(venv.name + ".old"), venv.with_name(venv.name + ".new")
try:
if old.exists() and not venv.exists():
old.rename(venv)
for leftover in (old, new):
if leftover.exists():
_rmtree(leftover)
except OSError as error:
warn(f"Could not clean up next to {venv} ({error}); the next setup run tries again.")
def toml_str(value: object) -> str:
"""A TOML basic string (JSON string escapes are valid TOML)."""
return json.dumps(str(value), ensure_ascii=False)
@dataclass
class Gpu:
backend: str # cuda | mps | cpu; an AMD GPU is "cuda" too, because ROCm torch uses the torch.cuda API
name: str = ""
vram_gb: float = 0.0
vendor: str = "" # nvidia | amd, for a cuda backend
@property
def build(self) -> str:
return "rocm" if self.vendor == "amd" else self.backend
def amd_gpu() -> Gpu | None:
"""The AMD GPU with the most VRAM, from sysfs (no ROCm install needed: the torch wheels bring their own)."""
best: tuple[float, Path] | None = None
for dev in Path("/sys/class/drm").glob("card[0-9]*/device"):
try:
if (dev / "vendor").read_text().strip() != AMD_PCI_VENDOR:
continue
vram = int((dev / "mem_info_vram_total").read_text()) / 2**30
except (OSError, ValueError):
continue
if vram >= AMD_MIN_VRAM_GB and (best is None or vram > best[0]):
best = (vram, dev)
if best is None:
return None
return Gpu("cuda", amd_gpu_name(best[1]), round(best[0], 1), "amd")
def amd_gpu_name(dev: Path) -> str:
rocminfo = shutil.which("rocminfo") or "/opt/rocm/bin/rocminfo"
try:
out = subprocess.run([rocminfo], capture_output=True, text=True, timeout=10, check=False).stdout
names = re.findall(r"Marketing Name:\s*(.*(?:Radeon|Instinct).*)", out)
if names:
return names[0].strip()
except (OSError, subprocess.SubprocessError):
pass
try:
slot = dev.resolve().name
out = subprocess.run(
["lspci", "-mm", "-s", slot], capture_output=True, text=True, timeout=10, check=False
).stdout
fields = re.findall(r'"([^"]*)"', out)
match = re.search(r"\[(.+)\]", fields[2]) if len(fields) > 2 else None
if match:
return f"AMD {match.group(1)}"
except (OSError, subprocess.SubprocessError):
pass
return "AMD GPU"
@dataclass
class Setup:
"""The setup steps. ``root`` is the checkout, ``data_dir`` the user's data directory."""
root: Path
plat: str
arch: str
data_dir: Path
skip_toolchain: bool = False
skip_models: bool = False
force_cpu: bool = False
force_gpu: bool = False
assume_yes: bool = False
force: bool = False
gpu: Gpu = field(default_factory=lambda: Gpu("cpu"))
uv_path: str = ""
components: set[str] = field(default_factory=lambda: set(COMPONENTS))
@property
def zero_shot_vc(self) -> bool:
return "native_accent" in self.components
@property
def runtime(self) -> Path:
return self.data_dir / "runtime"
@property
def python_dir(self) -> Path:
"""Uv's Pythons (UV_PYTHON_INSTALL_DIR), which the venvs are made from."""
return self.runtime / UV_PYTHON_DIR
@property
def legacy_indextts(self) -> Path:
return self.runtime / LEGACY_INDEXTTS_DIR
@property
def applio(self) -> Path:
return self.runtime / "applio"
@property
def runtime_toml(self) -> Path:
return self.data_dir / "runtime.toml"
@property
def engine_venv(self) -> Path:
return self.runtime / ENGINE_DIR / ".venv"
@property
def omnivoice_model(self) -> Path:
return self.runtime / "models" / OMNIVOICE_DIR
@property
def seed_vc(self) -> Path:
return self.runtime / SEEDVC_DIR
@property
def seed_vc_models(self) -> Path:
return self.runtime / "models" / SEEDVC_DIR
@property
def holos_venv(self) -> Path:
return self.runtime / HOLOS_DIR / ".venv"
@property
def holos_models(self) -> Path:
return self.runtime / "models" / HOLOS_DIR
def clone_venv(self, name: str) -> Path:
return self.runtime / name / ".venv"
def clone_models_dir(self, name: str) -> Path:
return self.runtime / "models" / name
def clone_python(self, name: str) -> Path:
return venv_python(self.clone_venv(name), self.plat)
def holos_python(self) -> Path:
return venv_python(self.holos_venv, self.plat)
def engine_python(self) -> Path:
return venv_python(self.engine_venv, self.plat)
def rvc_python(self) -> Path:
return venv_python(self.applio / ".venv", self.plat)
def step_gb(self, step: str) -> float:
big = self.gpu.backend == "cuda"
sizes = {
"toolchain": 0.5,
"applio_source": 0.1,
"engine_env": 7.7 if big else 2.0,
"omnivoice": OMNIVOICE_GB,
"whisper": 1.6,
"speech_models": 2.5,
"better_translation": NLLB_BIG_DOWNLOAD_GB,
"separation": SEPARATION_GB,
"cast_runtime": 0.3,
"cast_model": CAST_SIZE / 1e9,
"zero_shot_vc": ZERO_SHOT_GB,
"holos_env": UKRAINIAN_GB - 0.9,
"holos_models": 0.9,
"applio_env": 8.0 if big else 3.0,
"applio_models": 4.0,
}
for name, spec in CLONE_MODELS.items():
sizes[f"{name}_env"] = COMPONENTS[name] - float(spec["download_gb"])
sizes[f"{name}_models"] = float(spec["download_gb"])
return sizes.get(step, 0.0)
def step_present(self, step: str) -> bool:
"""What a step would find in place, checked before the run so the app's progress leaves it out."""
models = self.models_dir
checks: dict[str, Callable[[], bool]] = {
"toolchain": lambda: True,
"applio_source": (self.applio / ".git").exists,
"engine_env": lambda: self.engine_python().exists(),
"omnivoice": lambda: self._has(self.omnivoice_model, OMNIVOICE_REQUIRED),
"whisper": (models / "whisper" / WHISPER_FILE).is_file,
"speech_models": lambda: self._has(models / NLLB_DIR, NLLB_REQUIRED),
"better_translation": self.has_better_translation,
"separation": (models / DEMUCS_DIR / DEMUCS_FILE).is_file,
"cast_runtime": self.has_llama,
"cast_model": (models / CAST_DIR / CAST_FILE).is_file,
"zero_shot_vc": self.has_zero_shot_vc,
"holos_env": lambda: self.holos_python().exists(),
"holos_models": (self.holos_models / HOLOS_STAMP).is_file,
"applio_env": lambda: self.rvc_python().exists(),
"applio_models": lambda: self._has(self.applio, self.applio_required()),
}
for name in CLONE_MODELS:
checks[f"{name}_env"] = lambda n=name: self.clone_python(n).exists()
checks[f"{name}_models"] = lambda n=name: (self.clone_models_dir(n) / CLONE_STAMP).is_file()
check = checks.get(step)
try:
return bool(check and check())
except OSError:
return False
def env(self, extra: Mapping[str, str] | None = None) -> dict[str, str]:
env = dict(os.environ)
for name in ("VIRTUAL_ENV", "UV_PROJECT_ENVIRONMENT", "PYTHONHOME", "PYTHONPATH"):
env.pop(name, None)
env.setdefault("UV_HTTP_TIMEOUT", UV_HTTP_TIMEOUT)
env.setdefault("UV_HTTP_RETRIES", UV_HTTP_RETRIES)
env.setdefault("UV_CONCURRENT_DOWNLOADS", "4") # moderate: big wheels and source builds can exhaust RAM
env.setdefault("UV_CONCURRENT_BUILDS", "2")
env.setdefault("UV_CONCURRENT_INSTALLS", "4")
env.setdefault("GIT_TERMINAL_PROMPT", "0")
env.setdefault("GCM_INTERACTIVE", "never")
env.setdefault("HF_HUB_DISABLE_SYMLINKS_WARNING", "1")
env.setdefault("PYTHONUTF8", "1")
env.setdefault("PYTHONIOENCODING", "utf-8")
# Temporary files on the install drive, not /tmp: /tmp is often a small RAM disk with a per-user quota (Arch,
# Fedora), and the Python packages unpack and compile there ("Disk quota exceeded").
for name in ("TMPDIR", "TEMP", "TMP"):
env[name] = str(self.temp_dir())
# uv's package cache next to the environments: on the same drive uv hard-links the packages into them
# instead of copying (PyTorch is several GB), and deleting the data folder removes everything setup wrote.
env.setdefault("UV_CACHE_DIR", str(self.data_dir / "cache" / "uv"))
env.setdefault("UV_PYTHON_INSTALL_DIR", str(self.python_dir))
env.setdefault("HF_HOME", str(self.data_dir / "cache" / "huggingface")) # the hf CLI's own state, not models
if GUI: # plain text for the app's log
env["NO_COLOR"] = "1"
env["TERM"] = "dumb"
if extra:
env.update(extra)
return env
def run(
self,
command: Sequence[object],
cwd: Path | None = None,
extra_env: Mapping[str, str] | None = None,
retry: str = "",
) -> int:
"""Returns the exit code (127: program not found). With ``retry`` (the step's name) a download command runs
again after a failure its output shows to be a temporary network error."""
argv = [str(part) for part in command]
if retry:
return self._run_retried(argv, cwd, extra_env, retry)
try:
return subprocess.run(argv, cwd=cwd or self.root, env=self.env(extra_env), check=False).returncode
except OSError:
return 127
def _run_retried(self, argv: list[str], cwd: Path | None, extra_env: Mapping[str, str] | None, label: str) -> int:
attempt = 0
while True:
code, output = self._run_teed(argv, cwd, extra_env)
if code in (0, 127) or attempt == len(RETRY_WAITS) or not network_failure(output):
return code
wait = RETRY_WAITS[attempt]
attempt += 1
say(
f"{label}: a network error (exit {code}); trying again in {wait:.0f} s "
f"(attempt {attempt + 1} of {len(RETRY_WAITS) + 1})..."
)
time.sleep(wait)
def _run_teed(self, argv: list[str], cwd: Path | None, extra_env: Mapping[str, str] | None) -> tuple[int, str]:
"""The exit code and the end of the output, which is still shown as it comes."""
try:
proc = subprocess.Popen(
argv, cwd=cwd or self.root, env=self.env(extra_env), stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
except OSError:
return 127, ""
tail = bytearray()
lock = threading.Lock()
def pump(source: io.BufferedReader, sink: io.TextIOBase) -> None:
for chunk in iter(lambda: source.read1(1 << 16), b""):
sink.buffer.write(chunk)
sink.buffer.flush()
with lock:
tail.extend(chunk)
del tail[: max(len(tail) - (1 << 15), 0)]
sys.stdout.flush()
sys.stderr.flush()
pumps = [
threading.Thread(target=pump, args=(proc.stdout, sys.stdout), daemon=True),
threading.Thread(target=pump, args=(proc.stderr, sys.stderr), daemon=True),
]
for thread in pumps:
thread.start()
for thread in pumps:
thread.join()
return proc.wait(), tail.decode("utf-8", "replace")
def quiet(self, command: Sequence[object], cwd: Path | None = None) -> int:
try:
return subprocess.run(
[str(p) for p in command],
cwd=cwd or self.root,
env=self.env(),
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
).returncode
except OSError:
return 127
def must(
self,
command: Sequence[object],
what: str,
cwd: Path | None = None,
extra_env: Mapping[str, str] | None = None,
retry: bool = False,
) -> None:
code = self.run(command, cwd, extra_env, retry=what) if retry else self.run(command, cwd, extra_env)
if code != 0:
raise SetupError(f"{what} failed (exit {code}); the output above says why.")
def read(self, command: Sequence[object], cwd: Path | None = None) -> str:
"""A command's stdout, or '' when it failed or is missing."""
try:
done = subprocess.run(
[str(p) for p in command],
cwd=cwd or self.root,
env=self.env(),
check=False,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
except OSError:
return ""
return done.stdout if done.returncode == 0 else ""
def git(self, *args: object) -> list[str]:
"""A git command line with the quirks pinned: LF checkouts, long paths, schannel TLS on Windows."""
config = ["-c", "core.autocrlf=false", "-c", "core.longpaths=true", "-c", "advice.detachedHead=false"]
if self.plat == "windows":
config += ["-c", "http.sslBackend=schannel"] # MinGit ships without a CA bundle the default backend finds
return ["git", *config, *[str(a) for a in args]]
def uv(self, *args: object) -> list[str]:
return [self.uv_path, *[str(a) for a in args]]
def detect(self) -> None:
say(f"Platform: {self.plat} {self.arch} ({platform.platform()})")
self.gpu, cpu_chosen = self._choose_gpu()
if self.gpu.build == "rocm":
say(f"GPU backend: rocm ({self.gpu.name}, {self.gpu.vram_gb:.0f} GB; AMD support is new, see the README)")
if not os.access("/dev/kfd", os.R_OK | os.W_OK):
warn(
"/dev/kfd is not accessible, so PyTorch cannot use the AMD GPU. Add your user to the 'render' "
"and 'video' groups (sudo usermod -aG render,video $USER), log in again and run setup again."
)
elif self.gpu.backend == "cuda":
say(
f"GPU backend: cuda ({self.gpu.name}, {self.gpu.vram_gb:.0f} GB)"
if self.gpu.name
else "GPU backend: cuda"
)
elif self.gpu.backend == "mps":
say("GPU backend: mps (Apple Silicon; best effort, parts of the engine may fall back to the CPU)")
else:
if self.plat == "macos":
warn(
"Intel Macs are not supported: PyTorch 2.11 (OmniVoice) has no wheels for them; expect the "
"install to fail."
)
if cpu_chosen:
say("GPU backend: cpu")
else:
warn(
"No supported GPU found: the runtime is set up for the CPU. Training a voice will be very slow "
"and speech generation several times slower than real time."
)
@staticmethod
def _existing_parent(path: Path) -> Path:
while not path.exists() and path != path.parent:
path = path.parent
return path
def _choose_gpu(self) -> tuple[Gpu, bool]:
"""--cpu, else the backend runtime.toml records (unless --gpu), else this machine's GPU. True: the CPU was
chosen rather than the only one there."""
if self.force_cpu:
say("--cpu given: using the CPU backend.")
return Gpu("cpu"), True
found = self._detect_gpu()
recorded = None if self.force_gpu else recorded_gpu(self.data_dir)
if recorded is None or recorded.build == found.build:
return found, False
if found.backend == "cpu":
say(
f"Keeping the {recorded.build} backend this runtime was set up for, although no GPU was found now "
"(--cpu switches to the CPU)."
)
else:
say(
f"Keeping the {recorded.build} backend this runtime was set up for ({found.name or found.build} found; "
"--gpu switches to it)."
)
return recorded, recorded.backend == "cpu"
def _detect_gpu(self) -> Gpu:
if self.plat == "macos":
return Gpu("mps") if self.arch == "arm64" else Gpu("cpu")
smi = shutil.which("nvidia-smi")
if smi:
out = self.read([smi, "--query-gpu=name,memory.total", "--format=csv,noheader,nounits"]).strip()
if out:
first = out.splitlines()[0].split(",")
try:
vram = float(first[1]) / 1024
except (IndexError, ValueError):
vram = 0.0
return Gpu("cuda", first[0].strip(), vram, "nvidia")
if self.plat == "linux":
return amd_gpu() or Gpu("cpu")
return Gpu("cpu")
def free_gb(self) -> float:
return shutil.disk_usage(self._existing_parent(self.data_dir)).free / 1e9
def resolve_components(self, args: argparse.Namespace) -> None:
"""``--components``, else what an earlier run installed, else everything (better_translation only with a CUDA /
ROCm GPU); then ``--add``, ``--better-translation`` and ``--no-zero-shot-vc``. ``speech`` is always in."""
def parse(value: str) -> set[str]:
items = {x.strip() for x in value.split(",") if x.strip()}
unknown = items - set(COMPONENTS)
if unknown:
raise SetupError(
f"Unknown component(s): {', '.join(sorted(unknown))} (known: {', '.join(COMPONENTS)})."
)
return items
previous = previous_components(self.data_dir)
if args.components:
chosen = parse(args.components)
elif previous is not None:
# an older setup (after a downgrade) drops the components it does not know from runtime.toml
chosen = set(previous) | {n for n in CLONE_MODELS if (self.clone_models_dir(n) / CLONE_STAMP).is_file()}
else:
chosen = set(COMPONENTS)
if (
"better_translation" in chosen
and self.gpu.backend != "cuda"
and args.better_translation != "yes"
and not (previous and "better_translation" in previous)
):
chosen.discard("better_translation")
say(
"Better translation left out: it runs on an NVIDIA or AMD GPU (--add better_translation installs it "
"anyway)."
)
if (
"cast" in chosen
and not args.components
and not (previous and "cast" in previous)
and not (self.gpu.backend == "mps" or (self.gpu.backend == "cuda" and self.gpu.vram_gb >= CAST_MIN_VRAM_GB))
):
chosen.discard("cast")
say(
f"Character voices left out: they need a GPU with {CAST_MIN_VRAM_GB:g} GB of memory or a Mac "
"(--add cast installs them anyway)."
)
if args.add:
chosen |= parse(args.add)
if args.better_translation == "yes":
chosen.add("better_translation")
elif args.better_translation == "no":
chosen.discard("better_translation")
if args.no_zero_shot_vc:
chosen.discard("native_accent")
if previous is not None and self._has(self.omnivoice_model, OMNIVOICE_REQUIRED):
chosen.add("omnivoice")
if not chosen & set(SPEECH_MODELS):
chosen.add("omnivoice")
chosen.add("speech")
self.components = chosen
say("Components: " + ", ".join(c for c in COMPONENTS if c in chosen))
def install_gb(self) -> float:
return sum(gb for c, gb in COMPONENTS.items() if c in self.components)
def announce(self) -> bool:
"""True when a big download is ahead (False: a runtime already exists here)."""
existing = has_runtime(self.data_dir)
free = self.free_gb()
say("=" * 78)
say(f"Install location : {self.data_dir}")
say(f"Free space there : {free:.0f} GB")
if existing:
say("Existing runtime found, nothing big to download (setup only fills in what is missing).")
if (
"translation" in self.components
and not self._has(self.models_dir / NLLB_DIR, NLLB_REQUIRED)
and not self.skip_models
):
say(f"The translation model for Redub will be downloaded now (about {COMPONENTS['translation']} GB).")
if "training" in self.components and not self.rvc_python().exists():
say(f"Voice training (Applio/RVC, about {APPLIO_GB} GB) will be installed now.")
if self.wants_better_translation() and not self.has_better_translation() and not self.skip_models:
say(
f"The better translation model (NLLB-200 1.3B) will be downloaded now: about "
f"{NLLB_BIG_DOWNLOAD_GB} GB, kept as {BETTER_TRANSLATION_GB} GB."
)
if (
"music_removal" in self.components
and not (self.models_dir / DEMUCS_DIR / DEMUCS_FILE).is_file()
and not self.skip_models
):
say(f"The music-removal model will be downloaded now (about {SEPARATION_GB} GB: Hybrid Demucs).")
if (
"ukrainian" in self.components
and not (self.holos_models / HOLOS_STAMP).is_file()
and not self.skip_models
):
say(f"Ukrainian speech (HolosTTS, exact word stress, about {UKRAINIAN_GB} GB) will be installed now.")
for name, spec in CLONE_MODELS.items():
if (
name in self.components
and not (self.clone_models_dir(name) / CLONE_STAMP).is_file()
and not self.skip_models
):
say(
f"The {spec['label']} voice-cloning model (about {COMPONENTS[name]:g} GB) will be "
"installed now."
)
if self.zero_shot_vc and not self.has_zero_shot_vc() and not self.skip_models:
say(
f"The zero-shot voice converter (Seed-VC, GPL-3.0, about {ZERO_SHOT_GB:.0f} GB) will be installed "
"now: the native accent for voices that are not trained (--no-zero-shot-vc leaves it out)."
)
if (
"omnivoice" in self.components
and not self._has(self.omnivoice_model, OMNIVOICE_REQUIRED)
and not self.skip_models
):
say(f"The OmniVoice voice-cloning model (about {OMNIVOICE_GB} GB) will be installed now.")
if self.legacy_indextts.is_dir():
say(
f"{self.legacy_indextts} (IndexTTS-2.5, about 19 GB) is no longer used; setup offers to delete it "
"at the end."
)
else:
labels = {
"speech": "speech engine and Whisper",
"omnivoice": "OmniVoice voice cloning",
"training": "voice training (Applio/RVC)",
"translation": "translation for Redub",
"better_translation": "better translation",
"native_accent": "native accent (Seed-VC, GPL-3.0)",
"music_removal": "music removal",
"ukrainian": "Ukrainian speech (HolosTTS)",
"voxcpm": "VoxCPM2 voice cloning",
"chatterbox": "Chatterbox voice cloning",
"cast": "character voices for books (Gemma 4 12B)",
}
chosen = [c for c in COMPONENTS if c in self.components]
parts = ", ".join(f"{labels[c]} ~{COMPONENTS[c]:g} GB" for c in chosen)
say(f"This will download and install about {self.install_gb():.0f} GB ({parts}) plus ~0.1 GB per voice.")
left = [labels[c] for c in COMPONENTS if c not in self.components]
if left:
say(f"Left out for now (can be added later): {', '.join(left)}.")
if self.skip_models:
say("--skip-models: the model files (most of that size) are left out for now.")
say("=" * 78)
needed = round(self.install_gb() + 4 + (NLLB_BIG_DOWNLOAD_GB if self.wants_better_translation() else 0))
if not existing and free < needed:
if self.force:
warn(f"Only {free:.0f} GB free, less than the {needed} GB needed; continuing because of --force.")
else:
raise SetupError(
f"Only {free:.0f} GB free in {self.data_dir}; at least {needed} GB are needed. "
f"Free up space, choose another place with --data-dir, or pass --force."
)
return not existing
def confirm(self) -> None:
"""Interactive: confirm or type another path; with ``--yes`` (or without a terminal) it only checks the free
space."""
interactive = not self.assume_yes and sys.stdin.isatty()
while True:
try:
self.announce()
except SetupError as error:
if not interactive:
raise SystemExit(f"[setup] {error}") from None
say(f"{error}")
answer = "n"
else:
if not interactive:
return
try:
answer = input("[setup] Continue? [Y/n, or type another folder] ").strip().strip('"')
except EOFError:
raise SystemExit("[setup] Cancelled.") from None
if answer.lower() in ("", "y", "yes"):
return
if answer.lower() in ("n", "no"):
try:
answer = input("[setup] Install into which folder (empty to cancel)? ").strip().strip('"')
except EOFError:
answer = ""
if not answer:
raise SystemExit("[setup] Cancelled.")
path = Path(answer).expanduser()
if not path.is_absolute():
say("Please give a full path (for example D:\\Voice or /data/voice).")
continue
self.data_dir = path.resolve()
def toolchains(self) -> None:
if self.skip_toolchain:
# No system packages (no sudo): git is optional (the sources come as archives without it) and ffmpeg
# comes as a portable copy where the system has none.
say("Skipping the toolchain install (--skip-toolchain).")
self._portable_ffmpeg()
return
failed: list[str] = []
for step in (self._git, self._compiler, self._rust, self._ffmpeg):
try:
step()
except SetupError as error:
say(f"Failed: {error}")
failed.append(str(error))
if failed and not shutil.which("git"):
raise SetupError("git is missing: " + "; ".join(failed))
if failed:
raise SetupError("; ".join(failed))
def _git(self) -> None:
if shutil.which("git"):
return
if self.plat == "windows":
say("Installing Git for Windows with winget...")
self.run([*WINGET, "Git.Git"])
for candidate in (r"C:\Program Files\Git\cmd", r"C:\Program Files (x86)\Git\cmd"):
if Path(candidate, "git.exe").exists():
os.environ["PATH"] = candidate + os.pathsep + os.environ["PATH"]
elif self.plat == "linux":
self._linux_install() # the package set holds git
if not shutil.which("git"):
raise SetupError("git could not be installed; install it and run this again.")
def _compiler(self) -> None:
if self.plat == "windows":
self._windows_build_tools()
elif self.plat == "macos":
self._xcode_tools()
else:
self._linux_install()
def _linux_manager(self) -> str:
found = next((name for name in LINUX_PACKAGES if shutil.which(name)), None)
if found is None:
raise SetupError(
"No known package manager (apt-get, dnf, pacman, zypper): install a C/C++ compiler, "
"pkg-config and the ALSA, xkbcommon, wayland, X11, fontconfig and Vulkan "
"development libraries by hand."
)
return found
def _dpkg_installed(self, package: str) -> bool:
return "install ok installed" in self.read(["dpkg-query", "-W", "-f=${Status}", package])
def _linux_missing(self, manager: str) -> list[str]:
packages = LINUX_PACKAGES[manager]
if manager == "apt-get":
return [p for p in packages if not self._dpkg_installed(p)]
query = ["rpm", "-q"] if manager in ("dnf", "zypper") else ["pacman", "-Qq"]
return [p for p in packages if not self.read([*query, p]).strip()]
def _linux_install(self) -> None:
manager = self._linux_manager()
missing = self._linux_missing(manager)
if not missing:
say("System packages: all present.")
return
say(f"Missing system packages: {' '.join(missing)}")
sudo = [] if hasattr(os, "geteuid") and os.geteuid() == 0 else ["sudo"]
if sudo:
say("Installing them needs administrator rights: sudo may ask for your password.")
if manager == "apt-get":
self.run([*sudo, "apt-get", "update"])
if self.run([*sudo, *LINUX_INSTALL[manager], *missing]) != 0:
raise SetupError(f"Installing the system packages failed; install them by hand: {' '.join(missing)}")
def _windows_build_tools(self) -> None:
vswhere = Path(os.environ.get("PROGRAMFILES(X86)", r"C:\Program Files (x86)")) / (
"Microsoft Visual Studio/Installer/vswhere.exe"
)
query = [vswhere, "-latest", "-products", "*", "-requires", VC_COMPONENT, "-property", "installationPath"]
if self.read(query).strip():
say("Visual Studio Build Tools (C++): present.")
return
if not shutil.which("winget"):
raise SetupError(
"winget is missing: install the Visual Studio Build Tools with the "
"'Desktop development with C++' workload by hand "
"(https://visualstudio.microsoft.com/visual-cpp-build-tools/)."
)
say("Installing the Visual Studio Build Tools with the C++ workload (about 3 GB; this takes a while)...")
self.run([*WINGET, WINGET_BUILD_TOOLS, "--override", BUILD_TOOLS_OVERRIDE])
if not self.read(query).strip(): # winget's exit code is unreliable (reboot pending, already installed)
raise SetupError("The Visual Studio Build Tools are still missing; install them with the C++ workload.")
def _xcode_tools(self) -> None:
if self.quiet(["xcode-select", "-p"]) == 0:
say("Xcode Command Line Tools: present.")
return
say("Installing Xcode's Command Line Tools: confirm the dialog that opens; this waits for it...")
self.run(["xcode-select", "--install"])
for _ in range(XCODE_WAIT_SECONDS // XCODE_POLL_SECONDS):
time.sleep(XCODE_POLL_SECONDS)
if self.quiet(["xcode-select", "-p"]) == 0:
return
raise SetupError("Xcode's Command Line Tools are still missing; finish their installer and run this again.")
def _ffmpeg(self) -> None:
"""Linux gets ffmpeg with the system packages, macOS through Homebrew when it is installed, Windows uses
Applio's copies."""
if self.plat == "windows":
return
if shutil.which("ffmpeg") and shutil.which("ffprobe"):
say("ffmpeg: present.")
return
if self.plat == "macos" and shutil.which("brew"):
say("Installing ffmpeg with Homebrew...")
self.run(["brew", "install", "ffmpeg"])
elif self.plat == "linux":
self._linux_install()
if not (shutil.which("ffmpeg") and shutil.which("ffprobe")):
how = "brew install ffmpeg" if self.plat == "macos" else "your package manager (package: ffmpeg)"
raise SetupError(f"ffmpeg and ffprobe are needed for audio and video files; install them with {how}.")
say("ffmpeg: installed.")
def temp_dir(self) -> Path:
path = self.data_dir / "tmp" / "setup"
path.mkdir(parents=True, exist_ok=True)
return path
def ffmpeg_dir(self) -> Path:
"""The engine looks here too (media._find)."""
return self.runtime / "ffmpeg"
def _portable_ffmpeg(self) -> None:
"""On PATH or in the runtime, else a static build on Linux, Homebrew's on macOS when Homebrew is there."""
exe = ".exe" if self.plat == "windows" else ""
if self.plat == "windows" and "training" in self.components:
return # Applio's prerequisites bring ffmpeg.exe / ffprobe.exe
if shutil.which("ffmpeg") and shutil.which("ffprobe"):
return
if all((self.ffmpeg_dir() / f"{name}{exe}").is_file() for name in ("ffmpeg", "ffprobe")):
say("ffmpeg: present (portable).")
return
if self.plat == "windows":
url = FFMPEG_WINDOWS_URL.format("winarm64" if self.arch == "arm64" else "win64")
say(f"ffmpeg: downloading a portable build ({url})...")
with tempfile.TemporaryDirectory() as tmp:
archive = Path(tmp) / "ffmpeg.zip"
self._download(url, archive)
self.ffmpeg_dir().mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(archive) as z:
for member in z.namelist():
name = member.rsplit("/", 1)[-1]
if name in ("ffmpeg.exe", "ffprobe.exe"):
(self.ffmpeg_dir() / name).write_bytes(z.read(member))
if not (self.ffmpeg_dir() / "ffmpeg.exe").is_file():
raise SetupError("The portable ffmpeg could not be unpacked.")
say(f"ffmpeg: installed in {self.ffmpeg_dir()}.")
return
if self.plat == "macos":
if shutil.which("brew"):
say("Installing ffmpeg with Homebrew...")
self.run(["brew", "install", "ffmpeg"])
if not shutil.which("ffmpeg"):
warn(
"ffmpeg is missing: video files and some audio formats cannot be opened. Install Homebrew "
"(https://brew.sh), run 'brew install ffmpeg', then run setup again."
)
return
arch = "arm64" if self.arch == "arm64" else "amd64"
url = f"https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-{arch}-static.tar.xz"
say(f"ffmpeg: downloading a portable build ({url})...")
with tempfile.TemporaryDirectory() as tmp:
archive = Path(tmp) / "ffmpeg.tar.xz"
self._download(url, archive)
self.ffmpeg_dir().mkdir(parents=True, exist_ok=True)
with tarfile.open(archive) as tar:
for member in tar.getmembers():
name = Path(member.name).name
if member.isfile() and name in ("ffmpeg", "ffprobe"):
source = tar.extractfile(member)
if source is None:
continue
target = self.ffmpeg_dir() / name
with source, target.open("wb") as out:
shutil.copyfileobj(source, out)
target.chmod(0o755)
if not (self.ffmpeg_dir() / "ffmpeg").is_file():
raise SetupError("The portable ffmpeg could not be unpacked; install ffmpeg with your package manager.")
say(f"ffmpeg: installed in {self.ffmpeg_dir()}.")
def _cargo(self) -> str | None:
found = shutil.which("cargo")
if found:
return found
candidate = Path.home() / ".cargo" / "bin" / ("cargo.exe" if self.plat == "windows" else "cargo")
if candidate.exists():
os.environ["PATH"] = str(candidate.parent) + os.pathsep + os.environ["PATH"]
return str(candidate)
return None
def _rust_version(self) -> tuple[int, int] | None:
match = re.search(r"cargo (\d+)\.(\d+)", self.read(["cargo", "--version"]))
return (int(match.group(1)), int(match.group(2))) if match else None
def _rust(self) -> None:
if not (self.root / "crates" / "desktop" / "Cargo.toml").is_file():
return # an installed app (no sources to build): Rust is not needed
if self._cargo():
version = self._rust_version()
if version and version >= MIN_RUST:
say(f"Rust: cargo {version[0]}.{version[1]} present.")
return
if shutil.which("rustup"):
say("Updating Rust (rustup)...")
self.must(["rustup", "update", "stable"], "Updating Rust")
self.run(["rustup", "default", "stable"])
return
raise SetupError(f"Rust is older than {MIN_RUST[0]}.{MIN_RUST[1]} and rustup is missing; update it.")
say("Installing Rust with rustup...")
with tempfile.TemporaryDirectory() as tmp:
if self.plat == "windows":
target = "aarch64" if self.arch == "arm64" else "x86_64"
installer = Path(tmp) / "rustup-init.exe"
self._download(f"https://win.rustup.rs/{target}", installer)
command: list[object] = [installer, "-y", "--profile", "minimal", "--default-toolchain", "stable"]
else:
installer = Path(tmp) / "rustup-init.sh"
self._download("https://sh.rustup.rs", installer)
command = ["sh", installer, "-y", "--profile", "minimal", "--default-toolchain", "stable"]
self.must(command, "Installing Rust")
if not self._cargo():
raise SetupError("Rust was installed but cargo was not found; open a new terminal and run this again.")
say("Rust installed (new terminals find cargo by themselves).")
@staticmethod
def _download(url: str, target: Path) -> None:
def attempt() -> None:
with urllib.request.urlopen(url, timeout=120) as response, target.open("wb") as handle:
received = 0
for block in iter(lambda: response.read(1 << 20), b""):
handle.write(block)
received += len(block)
check_complete(response, received)
try:
with_retries(f"Downloading {url}", attempt)
except NETWORK_ERRORS as error:
target.unlink(missing_ok=True)
raise SetupError(f"Downloading {url} failed: {error}") from error
def ensure_repo(self, name: str, url: str, commit: str, dest: Path) -> None:
"""Shallow, resumable checkout of ``commit``; without git it comes as a GitHub archive instead."""
marker = dest / ARCHIVE_MARKER
if (dest / ".git").exists() and shutil.which("git"):
head = self.read(self.git("rev-parse", "HEAD"), dest).strip()
else:
head = marker.read_text(encoding="utf-8").strip() if marker.is_file() else ""
if head == commit:
say(f"{name}: at the pinned commit {commit[:9]}.")
return
if not shutil.which("git") or marker.is_file():
self._fetch_archive(name, url, commit, dest)
return
if dest.exists() and not (dest / ".git").exists() and any(dest.iterdir()):
raise SetupError(f"{dest} exists and is not a git checkout; move it away.")
say(f"{name}: fetching {url} @ {commit[:9]}...")
dest.mkdir(parents=True, exist_ok=True)
if not (dest / ".git").exists():
self.must(self.git("init", "--quiet", dest), f"git init for {name}")
self.must(self.git("remote", "add", "origin", url), f"git remote for {name}", cwd=dest)
if (
self.run(self.git("fetch", "--quiet", "--depth", "1", "origin", commit), dest, retry=f"Fetching {name}")
!= 0
):
say(f"{name}: shallow fetch of the commit failed, fetching the full history...")
self.must(self.git("fetch", "--quiet", "origin"), f"Fetching {name}", cwd=dest, retry=True)
self.must(self.git("checkout", "--quiet", "--force", commit), f"Checking out {name}", cwd=dest)
say(f"{name}: checked out {commit[:9]}.")
def _fetch_archive(self, name: str, url: str, commit: str, dest: Path) -> None:
"""Unpacked over ``dest``: files it already has (a venv, downloaded models) stay."""
if dest.exists() and any(dest.iterdir()) and not (dest / ARCHIVE_MARKER).is_file():
raise SetupError(f"{dest} exists and holds something else; move it away.")
repo = url.removeprefix("https://github.com/").removesuffix(".git")
archive_url = f"https://codeload.github.com/{repo}/tar.gz/{commit}"
say(f"{name}: downloading {repo} @ {commit[:9]} (no git needed)...")
dest.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory() as tmp:
archive = Path(tmp) / "source.tar.gz"
self._download(archive_url, archive)
with tarfile.open(archive) as tar:
for member in tar.getmembers():
parts = Path(member.name).parts[1:] # drop the "<repo>-<commit>/" folder
if not parts or member.issym() or member.islnk():
continue
target = dest.joinpath(*parts)
if not target.resolve().is_relative_to(dest.resolve()):
raise SetupError(f"The {name} archive holds a path outside its folder: {member.name}")
if member.isdir():
target.mkdir(parents=True, exist_ok=True)
elif member.isfile():
target.parent.mkdir(parents=True, exist_ok=True)
source = tar.extractfile(member)
if source is None:
continue
with source, target.open("wb") as out:
shutil.copyfileobj(source, out)
if member.mode & 0o111:
target.chmod(0o755)
(dest / ARCHIVE_MARKER).write_text(commit, encoding="utf-8")
say(f"{name}: unpacked {commit[:9]}.")
def _stamp(self, venv_dir: Path) -> Path:
return venv_dir / ".mimvox-setup-ok"
def _stamp_value(self, commit: str) -> str:
return f"{commit} {self.gpu.build} {self.plat}"
def _build_note(self) -> str:
return {"cuda": "CUDA 12.8 build; a few GB", "rocm": "ROCm build; a few GB"}.get(self.gpu.build, "")
def _torch_args(self) -> list[str]:
"""unsafe-best-match: the PyTorch index also lists older copies of other packages (requests, numpy). The
reinstall replaces a torch of another build: torch==2.11.0 also matches an installed 2.11.0+cpu."""
args = ["--reinstall-package", "torch", "--reinstall-package", "torchaudio"]
if self.gpu.build in ("cuda", "rocm"):
index = TORCH_ROCM_INDEX if self.gpu.build == "rocm" else TORCH_CUDA_INDEX
return [*args, "--extra-index-url", index, "--index-strategy", "unsafe-best-match"]
if self.gpu.backend == "cpu" and self.plat != "macos":
return [*args, "--torch-backend", "cpu"]
return args
def _stamped(self, venv: Path, value: str) -> bool:
stamp = self._stamp(venv)
return (
venv_python(venv, self.plat).exists()
and stamp.is_file()
and stamp.read_text(encoding="utf-8").strip() == value
)
def _new_venv(self, version: str, venv: Path, *extra: str) -> list[str]:
return self.uv("venv", "--python", version, "--managed-python", "--allow-existing", *extra, venv)
def refresh_venv_launchers(self) -> list[Path]:
"""Uv's ``python.exe`` in a Windows venv holds the absolute path of its base Python; making the venv again
over itself writes new launchers and keeps the packages. Returns the venvs where that failed."""
failed = []
for venv in sorted(self.runtime.glob("*/.venv")):
version = venv_version(venv)
if version is None:
continue
cfg = (venv / "pyvenv.cfg").read_text(encoding="utf-8")
extra = ("--relocatable",) if re.search(r"^relocatable\s*=\s*true", cfg, re.MULTILINE) else ()
if self.quiet(self._new_venv(version, venv, *extra, "--offline")) != 0:
failed.append(venv)
return failed
def on_runtime_python(self, venv: Path) -> bool:
"""Whether the venv's base Python (pyvenv.cfg ``home``) is one of <runtime>/python; runtimes set up before
those were there use uv's default folder, which deleting the data folder leaves behind."""
home = venv_home(venv)
return home is None or _inside(home.resolve(), self.python_dir.resolve())
def _venv_step(
self,
label: str,
venv: Path,
version: str,
stamp_value: str,
install: Callable[[Path, Sequence[str]], bool],
cwd: Path,
) -> None:
"""Ready, made again on a Python in <runtime>/python (see _rebuild), or installed in place."""
restore_swapped(venv)
py = venv_python(venv, self.plat)
stamped = self._stamped(venv, stamp_value)
why = self._rebuild_reason(venv, version) if py.exists() else None
if why:
self._rebuild(label, venv, version, stamp_value, stamped, install, cwd, why)
return
if stamped:
say(f"{label}: ready.")
return
if not py.exists():
say(f"{label}: creating the Python {version} venv...")
venv.parent.mkdir(parents=True, exist_ok=True)
self.must(self._new_venv(version, venv), f"{label}: creating the venv", cwd=cwd)
if install(py, []):
self._stamp(venv).write_text(stamp_value, encoding="utf-8")
def remove_unused_pythons(self) -> None:
"""Pythons in <runtime>/python that no environment and not this setup run on (one an engine venv left when it
moved to a newer Python)."""
if not self.python_dir.is_dir():
return
keep = {f"{sys.version_info.major}.{sys.version_info.minor}"}
for venv in (self.engine_venv, self.holos_venv, self.applio / ".venv", *map(self.clone_venv, CLONE_MODELS)):
if (venv / "pyvenv.cfg").is_file():
version = venv_version(venv)
if version is None:
return
keep.add(version)
found: dict[str, list[Path]] = {}
for entry in self.python_dir.iterdir():
match = re.match(r"cpython-(\d+\.\d+)[.-]", entry.name)
if match and match.group(1) not in keep:
found.setdefault(match.group(1), []).append(entry)
for version, entries in sorted(found.items()):
say(f"Removing Python {version} from {self.python_dir}: no environment uses it any more.")
try:
for entry in sorted(entries, key=lambda p: not (p.is_symlink() or _is_junction(p))):
if entry.is_symlink() or _is_junction(entry):
entry.rmdir() if self.plat == "windows" else entry.unlink()
elif entry.is_dir():
_rmtree(entry)
except OSError as error:
warn(f"Python {version} could not be removed ({error}); it only takes some disk space.")
def _rebuild_reason(self, venv: Path, version: str) -> str | None:
if not self.on_runtime_python(venv):
return f"made from {venv_home(venv)}, outside {self.python_dir}"
old = venv_version(venv)
if old is not None and old != version:
return f"on Python {old}, needs {version}"
return None
def _rebuild(
self,
label: str,
venv: Path,
version: str,
stamp_value: str,
keep: bool,
install: Callable[[Path, Sequence[str]], bool],
cwd: Path,
why: str,
) -> None:
"""Builds the venv again next to it, from the cache first (``keep``: pinned to the packages it has), and swaps
it in only once that worked: the old venv stays otherwise."""
lock = LOCKS / f"{venv.parent.name}.txt"
locked = (
{re.split(r"==", line)[0] for line in lock.read_text(encoding="utf-8").split()} if lock.is_file() else set()
)
pins = [p for p in self._frozen(venv) if canonical_name(p.split("==")[0]) not in locked] if keep else []
constraints = self.temp_dir() / f"{venv.parent.name}-constraints.txt"
constraints.write_text("".join(f"{line}\n" for line in pins), encoding="utf-8")
say(
f"{label}: {why}; making it again on Python {version} in {self.python_dir}"
f"{', with the same packages' if pins else ''}..."
)
new = venv.with_name(venv.name + ".new")
if not (
self._runtime_python(label, version, cwd)
and self._build_from_cache(label, new, version, install, ["-c", str(constraints)] if pins else [], cwd)
):
if new.exists():
_rmtree(new)
if not keep:
raise SetupError(f"{label}: making it again on Python {version} in {self.python_dir} failed.")
warn(
f"{label}: could not be made again on Python {version} in {self.python_dir}; the old environment is "
"kept and still works (the next setup run tries again)."
)
return
if pins:
now = {line.split("==")[0] for line in self._frozen(new)}
dropped = [line for line in pins if line.split("==")[0] not in now]
if dropped:
say(f"{label}: no longer installed: {', '.join(dropped)}.")
self._stamp(new).write_text(stamp_value, encoding="utf-8")
try:
swap_venv(venv, new)
except OSError as error:
if new.exists():
_rmtree(new)
raise SetupError(
f"{label}: the new environment could not replace the old one ({error}); the old one is "
"kept. Close Mimvox and run setup again."
) from None
say(f"{label}: ready, on {venv_home(venv)}.")
def _runtime_python(self, label: str, version: str, cwd: Path) -> bool:
"""Python ``version`` in <runtime>/python, downloaded first when it is not there: an offline ``uv venv`` cannot
fetch it."""
if (
self.quiet(
self.uv("python", "find", "--managed-python", "--system", "--no-python-downloads", version), cwd=cwd
)
== 0
):
return True
say(f"{label}: downloading Python {version} into {self.python_dir}...")
if self.run(self.uv("python", "install", "--no-bin", "--no-registry", version), cwd=cwd) == 0:
return True
say(f"{label}: Python {version} could not be downloaded.")
return False
def _build_from_cache(
self,
label: str,
new: Path,
version: str,
install: Callable[[Path, Sequence[str]], bool],
args: Sequence[str],
cwd: Path,
) -> bool:
"""The venv at ``new`` from the package cache (hard links, offline); the packages it lacks are downloaded only
when that fails."""
for extra in (["--offline"], []):
if new.exists():
_rmtree(new)
try:
built = self.run(self._new_venv(version, new, "--relocatable", "--offline"), cwd=cwd) == 0 and install(
venv_python(new, self.plat), [*extra, *args]
)
except SetupError:
built = False
if built:
return True
if extra:
say(
f"{label}: not every package is in the cache ({self.data_dir / 'cache' / 'uv'}); downloading the "
"missing ones..."
)
return False
def _frozen(self, venv: Path) -> list[str]:
"""Its registry packages, as ``name==version`` lines."""
out = self.read(self.uv("pip", "freeze", "--python", venv_python(venv, self.plat)), cwd=self.runtime)
return [line for line in out.splitlines() if PIN.match(line)]
def _applio_install(self, py: Path, extra: Sequence[str]) -> bool:
note = self._build_note()
say(f"Applio environment: installing requirements (torch 2.11{' ' + note if note else ''})...")
command = self.uv("pip", "install", "--python", py, "-r", "requirements.txt", *lock_args("applio"), *extra)
command += self._torch_args()
self.must(command, "Installing the Applio requirements", cwd=self.applio)
return True
def applio_venv(self) -> None:
self._venv_step(
"Applio environment",
self.applio / ".venv",
APPLIO_PYTHON,
f"{self._stamp_value(APPLIO_COMMIT)} {lock_stamp('applio')}",
self._applio_install,
self.applio,
)
def _has(self, repo: Path, files: Sequence[str]) -> bool:
return all((repo / f).is_file() and (repo / f).stat().st_size > 0 for f in files)
@property
def models_dir(self) -> Path:
return self.runtime / "models"
def component_paths(self, component: str) -> list[Path]:
"""What ``--remove`` deletes for an optional component."""
return {
"training": [self.applio],
"omnivoice": [self.omnivoice_model],
"translation": [self.models_dir / NLLB_DIR],
"better_translation": [self.models_dir / NLLB_BIG_DIR],
"native_accent": [self.seed_vc, self.seed_vc_models],
"music_removal": [self.models_dir / DEMUCS_DIR],
"ukrainian": [self.holos_venv.parent, self.holos_models],
"cast": [self.llama_dir, self.models_dir / CAST_DIR],
**{name: [self.clone_venv(name).parent, self.clone_models_dir(name)] for name in CLONE_MODELS},
}[component]
def whisper_model(self) -> None:
py = self.engine_python()
if not py.exists():
raise SetupError("The engine environment is missing, so Whisper cannot be fetched.")
whisper_dir = self.models_dir / "whisper"
if (whisper_dir / WHISPER_FILE).is_file():
say("Whisper turbo checkpoint: present.")
else:
say("Whisper turbo checkpoint: downloading (about 1.6 GB, resumable)...")
expect_download(url_bytes(WHISPER_URL))
fetch_checked(WHISPER_URL, whisper_dir / WHISPER_FILE, WHISPER_SHA256, "the Whisper checkpoint")
lid = self.models_dir / LID_DIR / LID_FILE
if not lid.is_file():
say("Language identification model (fastText lid.176): downloading (about 1 MB)...")
fetch_checked(LID_URL, lid, LID_SHA256, "the language identification model")
def speech_models(self) -> None:
py = self.engine_python()
if not py.exists():
raise SetupError("The engine environment is missing, so the translation model cannot be fetched.")
nllb = self.models_dir / NLLB_DIR
if self._has(nllb, NLLB_REQUIRED):
say("Translation model (NLLB-200 distilled 600M): present.")
else:
say(f"Translation model: downloading {NLLB_REPO} (about 2.5 GB, resumable)...")
nllb.mkdir(parents=True, exist_ok=True)
expect_download(hf_bytes(NLLB_REPO, nllb, NLLB_FILES))
# `hf download` through the interpreter (the venv's hf.exe stub breaks when the runtime was moved);
# an older huggingface_hub without that CLI falls back to snapshot_download.
code = self.run(
[py, "-I", "-m", "huggingface_hub.cli.hf", "download", NLLB_REPO, *NLLB_FILES, "--local-dir", nllb],
cwd=self.runtime,
retry=f"Downloading {NLLB_REPO}",
)
if code != 0:
script = (
"import sys; from huggingface_hub import snapshot_download; "
"snapshot_download(sys.argv[1], local_dir=sys.argv[2], allow_patterns=sys.argv[3:])"
)
self.must(
[py, "-I", "-c", script, NLLB_REPO, nllb, *NLLB_FILES],
"Downloading the translation model",
cwd=self.runtime,
retry=True,
)
if not self._has(nllb, NLLB_REQUIRED):
raise SetupError("The translation model download finished but files are missing; run this again.")
def wants_better_translation(self) -> bool:
"""By default only with a CUDA or ROCm GPU: without one the 600M is about 3x faster on a CPU."""
return "better_translation" in self.components
def has_better_translation(self) -> bool:
return self._has(self.models_dir / NLLB_BIG_DIR, NLLB_BIG_REQUIRED)
def better_translation_model(self) -> None:
target = self.models_dir / NLLB_BIG_DIR
fp32 = target / "pytorch_model.bin"
if self.has_better_translation():
if fp32.is_file(): # a conversion that was interrupted after the new file was in place
fp32.unlink()
say("Better translation model (NLLB-200 distilled 1.3B): present.")
return
py = self.engine_python()
if not py.exists():
raise SetupError("The engine environment is missing, so the better translation model cannot be fetched.")
say(
f"Better translation model: downloading {NLLB_BIG_REPO} (about {NLLB_BIG_DOWNLOAD_GB} GB, resumable; "
f"kept as {BETTER_TRANSLATION_GB} GB)..."
)
target.mkdir(parents=True, exist_ok=True)
fetch = hf_bytes(NLLB_BIG_REPO, target, NLLB_FILES)
expect_download(None if fetch is None else fetch + int(BETTER_TRANSLATION_GB * 1e9))
code = self.run(
[py, "-I", "-m", "huggingface_hub.cli.hf", "download", NLLB_BIG_REPO, *NLLB_FILES, "--local-dir", target],
cwd=self.runtime,
retry=f"Downloading {NLLB_BIG_REPO}",
)
if code != 0:
script = (
"import sys; from huggingface_hub import snapshot_download; "
"snapshot_download(sys.argv[1], local_dir=sys.argv[2], allow_patterns=sys.argv[3:])"
)
self.must(
[py, "-I", "-c", script, NLLB_BIG_REPO, target, *NLLB_FILES],
"Downloading the better translation model",
cwd=self.runtime,
retry=True,
)
if not self._has(
target, ("config.json", "pytorch_model.bin", "sentencepiece.bpe.model", "tokenizer_config.json")
):
raise SetupError("The better translation model download finished but files are missing; run this again.")
say("Better translation model: storing it in fp16 (about a minute)...")
tmp = target / ".fp16"
shutil.rmtree(tmp, ignore_errors=True)
self.must(
[py, "-I", "-c", NLLB_FP16_SCRIPT, target, tmp],
"Converting the better translation model",
cwd=self.runtime,
extra_env={"HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1", "USE_HUB_KERNELS": "0"},
)
if not (tmp / "model.safetensors").is_file():
raise SetupError(f"Converting the better translation model wrote no model.safetensors in {tmp}.")
(tmp / "model.safetensors").replace(target / "model.safetensors")
shutil.rmtree(tmp, ignore_errors=True)
fp32.unlink(missing_ok=True)
if not self.has_better_translation():
raise SetupError("The better translation model is incomplete; run this again.")
size = (target / "model.safetensors").stat().st_size / 1e9
say(f"Better translation model: ready ({size:.1f} GB).")
@property
def llama_dir(self) -> Path:
return self.runtime / LLAMA_DIR
def llama_build(self) -> tuple[str, str]:
"""The llama.cpp archive for this machine: CUDA with an NVIDIA GPU, Metal on a Mac, Vulkan otherwise (it also
runs on the CPU)."""
arch = "arm64" if self.arch == "arm64" else "x64"
if self.plat == "macos":
kind = "metal"
elif self.gpu.vendor == "nvidia" and arch == "x64":
kind = "cuda"
else:
kind = "vulkan"
build = LLAMA_BUILDS.get((self.plat, arch, kind))
if build is None:
raise SetupError(f"llama.cpp has no prebuilt server for {self.plat} on {arch}.")
return build
def has_llama(self) -> bool:
exe = "llama-server.exe" if self.plat == "windows" else "llama-server"
stamp = self.llama_dir / LLAMA_STAMP
try:
return (self.llama_dir / exe).is_file() and stamp.read_text().strip() == self.llama_build()[0]
except (OSError, SetupError):
return False
def cast_runtime(self) -> None:
if self.has_llama():
say("Character voices runtime (llama.cpp): present.")
return
name, sha256 = self.llama_build()
say(f"Character voices runtime: downloading llama.cpp {LLAMA_RELEASE} ({name})...")
url = LLAMA_URL.format(release=LLAMA_RELEASE, name=name)
expect_download(url_bytes(url))
archive = self.temp_dir() / name
fetch_checked(url, archive, sha256, "llama.cpp")
unpack = self.temp_dir() / "llama-unpack"
_rmtree(unpack)
unpack.mkdir(parents=True)
if name.endswith(".zip"):
with zipfile.ZipFile(archive) as z:
z.extractall(unpack) # noqa: S202 - zipfile drops absolute paths and ".." from member names
else:
with tarfile.open(archive) as tar:
tar.extractall(unpack, filter="data")
entries = list(unpack.iterdir())
root = entries[0] if len(entries) == 1 and entries[0].is_dir() else unpack
_rmtree(self.llama_dir)
shutil.move(str(root), str(self.llama_dir))
_rmtree(unpack)
archive.unlink(missing_ok=True)
(self.llama_dir / LLAMA_STAMP).write_text(name + "\n")
if not self.has_llama():
raise SetupError(f"llama-server is missing from {name}.")
say(f"Character voices runtime: installed in {self.llama_dir}.")
def cast_model(self) -> None:
target = self.models_dir / CAST_DIR / CAST_FILE
if target.is_file():
say("Character voices model (Gemma 4 12B): present.")
return
old = self.models_dir / CAST_OLD_DIR / CAST_FILE
if old.is_file() and old.stat().st_size == CAST_SIZE and sha256_of(old) == CAST_SHA256:
target.parent.mkdir(parents=True, exist_ok=True)
old.replace(target)
with contextlib.suppress(OSError):
old.parent.rmdir()
say("Character voices model (Gemma 4 12B): moved from the earlier lyrics folder.")
return
say(f"Character voices model: downloading Gemma 4 12B (about {CAST_SIZE / 1e9:.1f} GB, resumable)...")
expect_download(CAST_SIZE)
url = f"https://huggingface.co/{CAST_REPO}/resolve/{CAST_REVISION}/{CAST_FILE}"
fetch_checked(url, target, CAST_SHA256, "the character voices model")
def separation_model(self) -> None:
target = self.models_dir / DEMUCS_DIR / DEMUCS_FILE
if target.is_file() and target.stat().st_size == DEMUCS_SIZE:
say("Music-removal model (Hybrid Demucs): present.")
return
say(f"Music-removal model: downloading Hybrid Demucs (about {DEMUCS_SIZE / 1e6:.0f} MB, resumable)...")
expect_download(DEMUCS_SIZE)
fetch_demucs(self.models_dir)
def has_zero_shot_vc(self) -> bool:
"""Checkout, weights and the stamp, as the engine's ``zsvc.installed`` checks."""
files = [f"{sub}/{name}" for sub, _repo, _rev, names in SEEDVC_MODELS for name in names]
return (
(self.seed_vc / "modules" / "commons.py").is_file()
and self._has(self.seed_vc, ("campplus_cn_common.bin",))
and self._has(self.seed_vc_models, (*files, SEEDVC_STAMP))
)
def zero_shot_vc_runtime(self) -> None:
py = self.engine_python()
if not py.exists():
raise SetupError("The engine environment is missing, so the zero-shot voice converter cannot be installed.")
stamp = self.seed_vc_models / SEEDVC_STAMP
revisions = " ".join(rev for _s, _r, rev, _f in SEEDVC_MODELS)
stamp_value = f"{SEEDVC_COMMIT} {' '.join(SEEDVC_PACKAGES)} {revisions}"
if self.has_zero_shot_vc() and stamp.read_text(encoding="utf-8").strip() == stamp_value:
say("Zero-shot voice converter (Seed-VC): present.")
return
self.ensure_repo("Seed-VC", SEEDVC_URL, SEEDVC_COMMIT, self.seed_vc)
if self.quiet([py, "-I", "-c", "import munch, einops"], cwd=self.runtime) != 0:
say("Zero-shot voice converter: adding munch and einops to the engine environment...")
self._seedvc_install(py, [])
if self.skip_models:
return
sizes = [hf_bytes(repo, self.seed_vc_models / sub, files, rev) for sub, repo, rev, files in SEEDVC_MODELS]
expect_download(None if None in sizes else sum(s or 0 for s in sizes))
for sub, repo, rev, files in SEEDVC_MODELS:
target = self.seed_vc_models / sub
if self._has(target, files):
continue
say(f"Zero-shot voice converter: downloading {repo} ({', '.join(files)}, resumable)...")
target.mkdir(parents=True, exist_ok=True)
code = self.run(
[
py,
"-I",
"-m",
"huggingface_hub.cli.hf",
"download",
repo,
*files,
"--revision",
rev,
"--local-dir",
target,
],
cwd=self.runtime,
extra_env={"HF_HUB_DISABLE_XET": "1"},
retry=f"Downloading {repo}",
)
if code != 0:
script = (
"import sys; from huggingface_hub import hf_hub_download\n"
"for f in sys.argv[4:]:\n"
" hf_hub_download(sys.argv[1], f, revision=sys.argv[2], local_dir=sys.argv[3])"
)
self.must(
[py, "-I", "-c", script, repo, rev, target, *files],
f"Downloading {repo} for the zero-shot voice converter",
cwd=self.runtime,
extra_env={"HF_HUB_DISABLE_XET": "1"},
retry=True,
)
if not self._has(target, files):
raise SetupError(f"The {repo} download finished but files are missing; run this again.")
stamp.write_text(stamp_value, encoding="utf-8")
if not self.has_zero_shot_vc():
raise SetupError("The zero-shot voice converter is incomplete; run this again.")
say("Zero-shot voice converter (Seed-VC): ready.")
def _engine_install(self, py: Path, extra: Sequence[str]) -> bool:
"""False when only the Ukrainian stress dictionary is missing."""
note = self._build_note()
say(f"Engine environment: installing torch 2.11{f' ({note})' if note else ''}, OmniVoice, Whisper...")
command = self.uv(
"pip",
"install",
"--python",
py,
"--compile-bytecode",
*ENGINE_TORCH,
*ENGINE_PACKAGES,
*lock_args("engine"),
*extra,
)
command += self._torch_args()
self.must(command, "Installing the engine environment", cwd=self.runtime)
if (
self.run(
self.uv("pip", "install", "--python", py, "--no-deps", *ENGINE_NO_DEPS, *lock_args("engine"), *extra),
cwd=self.runtime,
)
!= 0
):
warn(
"The Ukrainian stress dictionary could not be installed (the next setup run tries again); Ukrainian "
"speech works without automatic stress."
)
return False
return True
def _seedvc_install(self, py: Path, extra: Sequence[str]) -> None:
self.must(
self.uv("pip", "install", "--python", py, *SEEDVC_PACKAGES, *lock_args("engine"), *extra),
"Installing the zero-shot voice converter's packages",
cwd=self.runtime,
)
def engine_env(self) -> None:
stamp_value = (
f"{' '.join(ENGINE_TORCH)} {' '.join(ENGINE_PACKAGES)} {' '.join(ENGINE_NO_DEPS)} "
f"{self.gpu.build} {self.plat} {lock_stamp('engine')}"
)
def install(py: Path, extra: Sequence[str]) -> bool:
done = self._engine_install(py, extra)
if self.zero_shot_vc and py != self.engine_python(): # a rebuild: keep Seed-VC's packages too
self._seedvc_install(py, extra)
return done
self._venv_step("Engine environment", self.engine_venv, ENGINE_PYTHON, stamp_value, install, self.runtime)
self.nltk_data()
def nltk_data(self) -> None:
r"""g2p_en's NLTK data into <venv>/nltk_data, which NLTK searches (sys.prefix) on every OS. Its import fetches
the data only when NLTK finds none, also in the shared %APPDATA%\\nltk_data or ~/nltk_data."""
target = self.engine_venv / NLTK_DIR
missing = [
name for kind, name in NLTK_PACKAGES if not any((target / kind / f).exists() for f in (name, f"{name}.zip"))
]
py = self.engine_python()
if not missing or not py.exists():
return
say(f"Engine environment: downloading NLTK's {', '.join(missing)} (a few MB) to {target}...")
script = (
"import sys, nltk\n"
"ok = [nltk.download(name, download_dir=sys.argv[1], quiet=True) for name in sys.argv[2:]]\n"
"sys.exit(0 if all(ok) else 1)"
)
if self.run([py, "-I", "-c", script, target, *missing], cwd=self.runtime, retry="NLTK's data") != 0:
warn(
"NLTK's data could not be downloaded (the next setup run tries again); until then the recording-text "
"analysis uses NLTK data found elsewhere or a simpler method."
)
def holos_env(self) -> None:
stamp_value = (
f"{' '.join(ENGINE_TORCH)} {' '.join(HOLOS_PACKAGES)} {' '.join(HOLOS_NO_DEPS)} "
f"{self.gpu.build} {self.plat} {lock_stamp('holos')}"
)
self._venv_step(
"Ukrainian speech environment",
self.holos_venv,
HOLOS_PYTHON,
stamp_value,
self._holos_install,
self.runtime,
)
def _holos_install(self, py: Path, extra: Sequence[str]) -> bool:
note = self._build_note()
say(f"Ukrainian speech environment: installing torch 2.11{f' ({note})' if note else ''}, HolosTTS, Stanza...")
command = self.uv(
"pip",
"install",
"--python",
py,
"--compile-bytecode",
*ENGINE_TORCH,
*HOLOS_PACKAGES,
*lock_args("holos"),
*extra,
)
command += self._torch_args()
self.must(command, "Installing the Ukrainian speech environment", cwd=self.runtime)
self.must(
self.uv("pip", "install", "--python", py, "--no-deps", *HOLOS_NO_DEPS, *lock_args("holos"), *extra),
"Installing the Ukrainian stress dictionary",
cwd=self.runtime,
)
return True
def clone_env(self, name: str) -> None:
spec = CLONE_MODELS[name]
label = f"{spec['label']} environment"
stamp_value = (
f"{' '.join(ENGINE_TORCH)} {' '.join(spec['packages'])} {self.gpu.build} {self.plat} {lock_stamp(name)}"
)
def install(py: Path, extra: Sequence[str]) -> bool:
note = self._build_note()
say(f"{label}: installing torch 2.11{f' ({note})' if note else ''} and {spec['packages'][0]}...")
command = self.uv(
"pip",
"install",
"--python",
py,
"--compile-bytecode",
*ENGINE_TORCH,
*spec["packages"],
*lock_args(name),
*extra,
)
command += self._torch_args()
self.must(command, f"Installing the {label}", cwd=self.runtime)
return True
self._venv_step(label, self.clone_venv(name), ENGINE_PYTHON, stamp_value, install, self.runtime)
def clone_models_step(self, name: str) -> None:
spec = CLONE_MODELS[name]
py = self.clone_python(name)
if not py.exists():
raise SetupError(f"The {spec['label']} environment is missing, so its model cannot be fetched.")
target = self.clone_models_dir(name)
stamp = target / CLONE_STAMP
stamp_value = f"{spec['repo']}@{spec['revision']}{' + ' + spec['after'] if spec.get('after') else ''}"
if (
self._has(target, spec["required"])
and stamp.is_file()
and stamp.read_text(encoding="utf-8").strip() == stamp_value
):
say(f"{spec['label']} model: present.")
return
target.mkdir(parents=True, exist_ok=True)
say(f"{spec['label']}: downloading {spec['repo']} (about {spec['download_gb']} GB, resumable)...")
expect_download(hf_bytes(spec["repo"], target, spec["files"], spec["revision"]))
script = (
"import sys; from huggingface_hub import snapshot_download\n"
"snapshot_download(sys.argv[1], revision=sys.argv[2], local_dir=sys.argv[3], "
"allow_patterns=sys.argv[4:] or None)"
)
self.must(
[py, "-I", "-c", script, spec["repo"], spec["revision"], target, *spec["files"]],
f"Downloading {spec['repo']}",
cwd=self.runtime,
extra_env={"HF_HUB_DISABLE_XET": "1"},
retry=True,
)
if not self._has(target, spec["required"]):
raise SetupError(f"The {spec['repo']} download finished but files are missing; run this again.")
if spec.get("after"):
self.must(
[py, "-I", "-c", spec["after"]],
f"Preparing {spec['label']}",
cwd=self.runtime,
extra_env={"PKUSEG_HOME": str(target / "pkuseg"), "HF_HOME": str(target / "hf-home")},
)
stamp.write_text(stamp_value, encoding="utf-8")
say(f"{spec['label']}: ready.")
def holos_models_step(self) -> None:
py = self.holos_python()
if not py.exists():
raise SetupError("The Ukrainian speech environment is missing, so its models cannot be fetched.")
target = self.holos_models
stamp = target / HOLOS_STAMP
stanza_dir = target / HOLOS_STANZA
stamp_value = f"{HOLOS_REPO}@{HOLOS_REVISION} stanza {HOLOS_STANZA_PROCESSORS}"
if (
self._has(target, HOLOS_FILES)
and stamp.is_file()
and stamp.read_text(encoding="utf-8").strip() == stamp_value
):
say("Ukrainian speech models: present.")
return
target.mkdir(parents=True, exist_ok=True)
if not self._has(target, HOLOS_FILES):
say(f"Ukrainian speech: downloading {HOLOS_REPO} (about 0.7 GB, resumable)...")
fetch = hf_bytes(HOLOS_REPO, target, HOLOS_FILES, HOLOS_REVISION)
expect_download(None if fetch is None else fetch + 200_000_000)
code = self.run(
[
py,
"-I",
"-m",
"huggingface_hub.cli.hf",
"download",
HOLOS_REPO,
*HOLOS_FILES,
"--revision",
HOLOS_REVISION,
"--local-dir",
target,
],
cwd=self.runtime,
extra_env={"HF_HUB_DISABLE_XET": "1"},
retry=f"Downloading {HOLOS_REPO}",
)
if code != 0:
script = (
"import sys; from huggingface_hub import hf_hub_download\n"
"for f in sys.argv[4:]:\n"
" hf_hub_download(sys.argv[1], f, revision=sys.argv[2], local_dir=sys.argv[3])"
)
self.must(
[py, "-I", "-c", script, HOLOS_REPO, HOLOS_REVISION, target, *HOLOS_FILES],
f"Downloading {HOLOS_REPO}",
cwd=self.runtime,
extra_env={"HF_HUB_DISABLE_XET": "1"},
retry=True,
)
if not self._has(target, HOLOS_FILES):
raise SetupError("The HolosTTS download finished but files are missing; run this again.")
say("Ukrainian speech: downloading Stanza's Ukrainian models (about 0.2 GB)...")
script = (
"import sys, stanza; stanza.download('uk', model_dir=sys.argv[1], processors=sys.argv[2], "
"logging_level='WARN')"
)
self.must(
[py, "-I", "-c", script, stanza_dir, HOLOS_STANZA_PROCESSORS],
"Downloading Stanza's Ukrainian models",
cwd=self.runtime,
retry=True,
)
if not (stanza_dir / "resources.json").is_file() or not (stanza_dir / "uk" / "pos").is_dir():
raise SetupError("Stanza's Ukrainian models are incomplete; run this again.")
stamp.write_text(stamp_value, encoding="utf-8")
say("Ukrainian speech (HolosTTS): ready.")
def omnivoice_models(self) -> None:
py = self.engine_python()
if not py.exists():
raise SetupError("The engine environment is missing, so the OmniVoice model cannot be fetched.")
target = self.omnivoice_model
if self._has(target, OMNIVOICE_REQUIRED):
say("OmniVoice model: present.")
else:
say(f"OmniVoice model: downloading {OMNIVOICE_REPO} (about 3.3 GB, resumable)...")
target.mkdir(parents=True, exist_ok=True)
expect_download(hf_bytes(OMNIVOICE_REPO, target))
code = self.run(
[py, "-I", "-m", "huggingface_hub.cli.hf", "download", OMNIVOICE_REPO, "--local-dir", target],
cwd=self.runtime,
extra_env={"HF_HUB_DISABLE_XET": "1"},
retry=f"Downloading {OMNIVOICE_REPO}",
)
if code != 0:
script = (
"import sys; from huggingface_hub import snapshot_download; "
"snapshot_download(sys.argv[1], local_dir=sys.argv[2])"
)
self.must(
[py, "-I", "-c", script, OMNIVOICE_REPO, target],
"Downloading the OmniVoice model",
cwd=self.runtime,
extra_env={"HF_HUB_DISABLE_XET": "1"},
retry=True,
)
if not self._has(target, OMNIVOICE_REQUIRED):
raise SetupError("The OmniVoice download finished but files are missing; run this again.")
def applio_required(self) -> tuple[str, ...]:
return APPLIO_REQUIRED + (APPLIO_WINDOWS_REQUIRED if self.plat == "windows" else ())
def applio_models(self) -> None:
if not self.rvc_python().exists():
raise SetupError("The Applio environment is missing, so its models cannot be fetched.")
if self._has(self.applio, self.applio_required()):
say("Applio prerequisites: present.")
return
say("Applio prerequisites: downloading pretrained HiFi-GAN, rmvpe, contentvec (about 1.5 GB)...")
self.must(
[self.rvc_python(), "core.py", "prerequisites", "--pretraineds-hifigan", "--models", "--exe"],
"Downloading the Applio prerequisites",
cwd=self.applio,
retry=True,
)
if not self._has(self.applio, self.applio_required()):
raise SetupError("The Applio prerequisites finished but files are missing; run this again.")
def write_runtime_toml(self) -> None:
if not self.engine_python().exists():
raise SetupError(f"runtime.toml not written: the engine interpreter {self.engine_python()} does not exist.")
training = "training" in self.components and self.rvc_python().exists()
ukrainian = "ukrainian" in self.components and self.holos_python().exists()
clones = [n for n in CLONE_MODELS if n in self.components and self.clone_python(n).exists()]
if "training" in self.components and not training:
warn(f"Voice training is not ready (no {self.rvc_python()}): runtime.toml leaves it out; run setup again.")
text = (
"# Written by tools/setup/setup.py; setup rewrites it on every run.\n"
"[python]\n"
f"engine = {toml_str(self.engine_python())}\n"
+ (f"rvc = {toml_str(self.rvc_python())}\n" if training else "")
+ (f"holos = {toml_str(self.holos_python())}\n" if ukrainian else "")
+ "".join(f"{n} = {toml_str(self.clone_python(n))}\n" for n in clones)
+ "\n[paths]\n"
+ (f"applio = {toml_str(self.applio)}\n" if training else "")
+ (f"omnivoice_model = {toml_str(self.omnivoice_model)}\n" if "omnivoice" in self.components else "")
+ f"seed_vc = {toml_str(self.seed_vc)}\n"
f"seed_vc_models = {toml_str(self.seed_vc_models)}\n"
+ (f"holos_model = {toml_str(self.holos_models)}\n" if ukrainian else "")
+ "".join(f"{n}_model = {toml_str(self.clone_models_dir(n))}\n" for n in clones)
+ "\n[device]\n"
f'backend = "{self.gpu.backend}"\n'
)
if self.gpu.vendor:
text += f'vendor = "{self.gpu.vendor}"\n'
if self.gpu.vendor == "amd":
text += f"name = {toml_str(self.gpu.name)}\nvram_gb = {self.gpu.vram_gb}\n"
# What this runtime was set up for: the app asks for setup again when it needs a newer one.
chosen = ", ".join(f'"{c}"' for c in COMPONENTS if c in self.components)
text += f"\n[setup]\nruntime_version = {runtime_version()}\ncomponents = [{chosen}]\n"
self.data_dir.mkdir(parents=True, exist_ok=True)
tmp = self.runtime_toml.with_suffix(".toml.tmp")
tmp.write_text(text, encoding="utf-8", newline="\n")
tmp.replace(self.runtime_toml)
say(f"Wrote {self.runtime_toml}")
self.write_location()
def write_location(self) -> None:
"""``location.toml`` names the data dir only when it is not the default one; a stale pointer is removed."""
path = location_file(self.plat)
if self.data_dir == default_data_dir(self.plat).resolve():
try:
path.unlink()
say(f"Removed {path} (the data directory is the default again).")
except OSError:
pass
return
try:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".toml.tmp")
tmp.write_text(f"data_dir = {toml_str(self.data_dir)}\n", encoding="utf-8", newline="\n")
tmp.replace(path)
say(f"Wrote {path} (tells the app where the data directory is).")
except OSError as error:
warn(f"could not write {path}: {error}. Set {DATA_ENV} to {self.data_dir} before starting the app.")
def offer_legacy_removal(self, confirmed: bool) -> None:
"""``runtime/index-tts`` (~19 GB) is deleted only on ``--remove-indextts`` or "y" at the prompt, never
automatically."""
legacy = self.legacy_indextts
if not legacy.is_dir():
return
if not confirmed:
if self.assume_yes or not sys.stdin.isatty():
say(
f"{legacy} (IndexTTS-2.5, about 19 GB) is no longer used. Delete it yourself, or run setup with "
"--remove-indextts."
)
return
try:
answer = input(f"[setup] {legacy} (IndexTTS-2.5, about 19 GB) is no longer used. Delete it now? [y/N] ")
except EOFError:
answer = ""
if answer.strip().lower() not in ("y", "yes"):
say("Kept it. Run setup with --remove-indextts to delete it later.")
return
say(f"Deleting {legacy}...")
shutil.rmtree(legacy, ignore_errors=True)
if legacy.exists():
warn(f"Could not delete everything in {legacy} (a file in use?); delete the rest by hand.")
else:
say("Deleted.")
def quick_check(self) -> list[str]:
"""Verify an existing setup without loading a model: files, interpreters, torch and the GPU, for the
components it has."""
problems: list[str] = []
training = "training" in self.components
pythons = [("engine", "Engine", self.engine_python())]
if training:
pythons.append(("rvc", "Applio", self.rvc_python()))
if "ukrainian" in self.components:
pythons.append(("holos", "Ukrainian speech", self.holos_python()))
for name, spec in CLONE_MODELS.items():
if name in self.components:
pythons.append((name, spec["label"], self.clone_python(name)))
if not self.runtime_toml.is_file():
problems.append(f"{self.runtime_toml} is missing.")
else:
say(f"runtime.toml: {self.runtime_toml}")
text = self.runtime_toml.read_text(encoding="utf-8")
for key, _label, path in pythons:
if toml_str(path) not in text:
problems.append(f"runtime.toml does not point [python] {key} at {path}.")
if training:
if (self.applio / ".git").exists() and shutil.which("git"):
head = self.read(self.git("rev-parse", "HEAD"), self.applio).strip()
else:
marker = self.applio / ARCHIVE_MARKER
head = marker.read_text(encoding="utf-8").strip() if marker.is_file() else ""
if head == APPLIO_COMMIT:
say(f"Applio: pinned commit {APPLIO_COMMIT[:9]}.")
else:
problems.append(
f"Applio is not at the pinned commit {APPLIO_COMMIT[:9]} (found {head[:9] or 'nothing'})."
)
checks = (
[("OmniVoice model", self.omnivoice_model, OMNIVOICE_REQUIRED)] if "omnivoice" in self.components else []
)
if training:
checks.insert(0, ("Applio prerequisites", self.applio, self.applio_required()))
if "ukrainian" in self.components:
checks.append(("Ukrainian speech models", self.holos_models, (*HOLOS_FILES, HOLOS_STAMP)))
for name, spec in CLONE_MODELS.items():
if name in self.components:
checks.append((f"{spec['label']} model", self.clone_models_dir(name), (*spec["required"], CLONE_STAMP)))
for label, folder, files in checks:
missing = [f for f in files if not (folder / f).is_file()]
if missing:
problems.append(f"{label}: missing {', '.join(missing)} in {folder}")
else:
say(f"{label}: all files present.")
for _key, label, py in pythons:
problems += self._check_torch(label, py)
if self.engine_python().exists():
out = (
self.read(
[
self.engine_python(),
"-I",
"-c",
"import omnivoice, num2words, transformers; print(transformers.__version__)",
]
)
.strip()
.splitlines()
)
if out:
say(f"Engine environment: OmniVoice + num2words, transformers {out[-1]}.")
else:
problems.append("The engine environment cannot import omnivoice / num2words / transformers.")
if self.legacy_indextts.is_dir():
say(
f"Note: {self.legacy_indextts} (IndexTTS-2.5, about 19 GB) is no longer used and can be deleted "
"(setup --remove-indextts)."
)
problems += self._check_media()
return problems
def _check_media(self) -> list[str]:
problems: list[str] = []
has = self.components.__contains__
exe = ".exe" if self.plat == "windows" else ""
portable = all((self.ffmpeg_dir() / f"{name}{exe}").is_file() for name in ("ffmpeg", "ffprobe"))
if self.plat == "windows":
found = portable or all((self.applio / name).is_file() for name in APPLIO_WINDOWS_REQUIRED)
else:
found = portable or bool(shutil.which("ffmpeg") and shutil.which("ffprobe"))
if found:
say("ffmpeg and ffprobe: present.")
else:
where = ("the Applio folder" if self.plat == "windows" else "PATH") + f" or {self.ffmpeg_dir()}"
problems.append(f"ffmpeg / ffprobe not found in {where}: audio and video files cannot be read or exported.")
py = self.engine_python()
if py.exists():
out = self.read([py, "-c", "import whisper; print(whisper.__version__)"]).strip().splitlines()
if out:
say(f"openai-whisper {out[-1]} (Redub transcription).")
else:
problems.append("openai-whisper is missing from the engine environment (Redub transcription).")
if has("translation"):
out = (
self.read([py, "-c", "import transformers, sentencepiece; print(transformers.__version__)"])
.strip()
.splitlines()
)
if out:
say(f"transformers {out[-1]} + sentencepiece (Redub translation).")
else:
problems.append(
"transformers or sentencepiece is missing from the engine environment (Redub translation)."
)
if has("translation"):
nllb = self.models_dir / NLLB_DIR
missing = [f for f in NLLB_REQUIRED if not (nllb / f).is_file()]
if missing:
problems.append(f"Translation model: missing {', '.join(missing)} in {nllb}")
else:
say("Translation model (NLLB-200 distilled 600M): all files present.")
if self.has_better_translation():
say("Better translation model (NLLB-200 distilled 1.3B): all files present.")
elif self.wants_better_translation():
say(
"Better translation model (NLLB-200 distilled 1.3B): not downloaded (optional; run setup to add it, "
"Redub uses the 600M meanwhile)."
)
if not (self.models_dir / "whisper" / WHISPER_FILE).is_file():
say("Whisper turbo checkpoint: not downloaded yet (setup fetches it; otherwise the first Redub does).")
if has("music_removal"):
demucs = self.models_dir / DEMUCS_DIR / DEMUCS_FILE
if demucs.is_file() and demucs.stat().st_size == DEMUCS_SIZE:
say("Music-removal model (Hybrid Demucs): present.")
else:
say(
f"Music-removal model: not downloaded yet ({demucs}); media files are used with their music until "
"setup fetches it."
)
if has("native_accent"):
if self.has_zero_shot_vc():
say("Zero-shot voice converter (Seed-VC): present.")
else:
say(
"Zero-shot voice converter (Seed-VC): not installed (untrained voices have no native accent until "
"setup installs it)."
)
return problems
def _check_torch(self, label: str, py: Path) -> list[str]:
if not py.exists():
return [f"{label} interpreter missing: {py}"]
script = (
"import json, torch\n"
"cuda = torch.cuda.is_available()\n"
"mps = bool(getattr(torch.backends, 'mps', None) and torch.backends.mps.is_available())\n"
"name = torch.cuda.get_device_name(0) if cuda else ''\n"
"hip = bool(getattr(torch.version, 'hip', None))\n"
"print(json.dumps({'torch': torch.__version__, 'cuda': cuda, 'mps': mps, 'name': name, 'hip': hip}))\n"
)
out = self.read([py, "-c", script]).strip().splitlines()
if not out:
return [f"{label}: importing torch failed with {py}."]
info = json.loads(out[-1])
wanted = {"cuda": info["cuda"], "mps": info["mps"], "cpu": True}[self.gpu.backend]
detail = info["name"] if info["cuda"] else ("mps" if info["mps"] else "cpu")
say(f"{label}: torch {info['torch']}, device {detail}.")
if self.gpu.build == "rocm" and not info["hip"]:
return [f"{label}: torch {info['torch']} is not the ROCm build; run setup again to reinstall it."]
if not wanted and self.gpu.build == "rocm":
return [
(
f"{label}: the ROCm build of torch cannot use {self.gpu.name}. The card may be too old for these "
"ROCm wheels, or /dev/kfd may be inaccessible; run setup with --cpu to use the CPU."
)
]
if not wanted:
return [f"{label}: torch {info['torch']} cannot use the {self.gpu.backend} backend."]
return []
def ready_lines(self) -> list[str]:
binary = self.root / "target" / "release" / (BIN_NAME + (".exe" if self.plat == "windows" else ""))
lines = ["Start the app with:"]
if self.data_dir != default_data_dir(self.plat).resolve():
lines.insert(0, f"The app finds the data directory {self.data_dir} through {location_file(self.plat)}.")
app = self.root / "crates" / "desktop"
if not (app / "Cargo.toml").is_file():
return [*lines[:-1], "Go back to the Mimvox window: it notices the finished setup by itself."]
if binary.exists():
lines.append(f" {binary}")
elif self.plat == "windows":
lines.append(f' cd /d "{app}" && cargo run --release')
else:
lines.append(f" cd {shlex_quote(str(app))} && cargo run --release")
return lines
def fetch_checked(url: str, target: Path, sha256: str, label: str) -> None:
"""Through a ``.part`` file a later run continues (an HTTP range request), checked against ``sha256`` before the
rename."""
target.parent.mkdir(parents=True, exist_ok=True)
part = target.with_name(target.name + ".part")
def attempt() -> None:
have = part.stat().st_size if part.is_file() else 0
request = urllib.request.Request(url, headers={"Range": f"bytes={have}-"} if have else {})
try:
with urllib.request.urlopen(request, timeout=120) as response:
resumed = have > 0 and response.status == 206
done = have if resumed else 0
total = done + int(response.headers.get("Content-Length") or 0)
step = max(total // 10, 1)
next_note = (done // step + 1) * step
with part.open("ab" if resumed else "wb") as handle:
for block in iter(lambda: response.read(1 << 20), b""):
handle.write(block)
done += len(block)
if total and next_note <= done < total:
say(f" {100 * done // total}% of {total / 1e9:.1f} GB")
next_note = (done // step + 1) * step
check_complete(response, done - (have if resumed else 0))
except urllib.error.HTTPError as error:
if error.code != 416: # 416: the .part is already complete
raise
try:
with_retries(f"Downloading {label}", attempt)
except NETWORK_ERRORS as error:
raise SetupError(f"Downloading {label} failed ({error}); run setup again to resume.") from error
digest = hashlib.sha256()
with part.open("rb") as handle:
for block in iter(lambda: handle.read(1 << 20), b""):
digest.update(block)
if digest.hexdigest() != sha256:
part.unlink()
raise SetupError(f"The download of {label} is corrupt (checksum mismatch); run setup again.")
part.replace(target)
say(f"Saved {target}.")
def sha256_of(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for block in iter(lambda: handle.read(1 << 20), b""):
digest.update(block)
return digest.hexdigest()
def fetch_demucs(models_dir: Path) -> Path:
"""Resumable through a ``.part`` file, checked against the pinned SHA-256."""
folder = models_dir / DEMUCS_DIR
folder.mkdir(parents=True, exist_ok=True)
target = folder / DEMUCS_FILE
part = folder / (DEMUCS_FILE + ".part")
if part.is_file() and part.stat().st_size > DEMUCS_SIZE:
part.unlink()
def attempt() -> None:
have = part.stat().st_size if part.is_file() else 0
if have >= DEMUCS_SIZE:
return
request = urllib.request.Request(DEMUCS_URL, headers={"Range": f"bytes={have}-"} if have else {})
with urllib.request.urlopen(request, timeout=120) as response:
resumed = have > 0 and response.status == 206
done = have if resumed else 0
step = DEMUCS_SIZE // 10
next_note = (done // step + 1) * step
with part.open("ab" if resumed else "wb") as handle:
for block in iter(lambda: response.read(1 << 20), b""):
handle.write(block)
done += len(block)
if done >= next_note and done < DEMUCS_SIZE:
say(f" {100 * done // DEMUCS_SIZE}% of {DEMUCS_SIZE / 1e6:.0f} MB")
next_note = (done // step + 1) * step
check_complete(response, done - (have if resumed else 0))
try:
with_retries("Downloading the music-removal model", attempt)
except NETWORK_ERRORS as error:
raise SetupError(f"Downloading the music-removal model failed ({error}); run setup again to resume.") from error
digest = hashlib.sha256()
with part.open("rb") as handle:
for block in iter(lambda: handle.read(1 << 20), b""):
digest.update(block)
if digest.hexdigest() != DEMUCS_SHA256:
part.unlink()
raise SetupError("The music-removal model download is corrupt (checksum mismatch); run setup again.")
part.replace(target)
say(f"Music-removal model: saved to {target}.")
return target
def shlex_quote(text: str) -> str:
import shlex
return shlex.quote(text)
def parse_args(argv: Sequence[str] | None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
prog="setup", description="Full setup of Mimvox: toolchains, runtime, models, runtime.toml."
)
parser.add_argument(
"--data-dir",
metavar="DIR",
help=f"data directory (default: ${DATA_ENV}, else asked for; the default is the local app data "
f"dir + {APP_DIR_NAME}, or the one in location.toml)",
)
parser.add_argument(
"--skip-toolchain", action="store_true", help="do not install Rust / compilers / system packages"
)
parser.add_argument(
"--components",
metavar="LIST",
help=f"what to install, comma separated ({', '.join(COMPONENTS)}; speech is always included). "
"Default: what an earlier run installed, else everything (better_translation only with a "
"GPU)",
)
parser.add_argument("--add", metavar="LIST", help="install these components in addition to the installed ones")
parser.add_argument(
"--remove",
metavar="LIST",
help="delete these optional components from the runtime and leave the rest as it is (speech and the last "
"voice-cloning model cannot be removed)",
)
parser.add_argument(
"--gui",
action="store_true",
help="run by the app: no questions and no system packages (no sudo; implies --yes and "
"--skip-toolchain), plus '@@mimvox {json}' progress lines for its setup screen",
)
parser.add_argument("--skip-models", action="store_true", help="set the environments up but download no models")
backend = parser.add_mutually_exclusive_group()
backend.add_argument(
"--cpu", action="store_true", help="ignore any GPU and set up the CPU backend; later runs keep it until --gpu"
)
backend.add_argument(
"--gpu",
action="store_true",
help="use this machine's GPU also when the runtime was set up with --cpu (default: keep the "
"backend runtime.toml records, else detect the GPU)",
)
parser.add_argument(
"--yes",
"-y",
action="store_true",
help="do not ask for confirmation (then --data-dir is required: no silent default)",
)
parser.add_argument(
"--force", action="store_true", help=f"continue even when the drive has less than {DISK_NEEDED_GB} GB free"
)
parser.add_argument(
"--quick-check",
action="store_true",
help="verify an existing setup (files, interpreters, torch on the GPU) and download nothing",
)
parser.add_argument(
"--runtime-toml-only",
action="store_true",
help="only (re)write runtime.toml for a runtime that already exists in the data directory",
)
parser.add_argument(
"--move-to",
metavar="DIR",
help="move the installed data directory (from --data-dir, location.toml or the default) to "
"DIR: renames on the same volume, else copies with '[move] 37%% 11.4/31.0 GB' progress "
"lines, fixes the paths inside the virtual environments, rewrites runtime.toml and "
"location.toml, checks the result and only then deletes the old copy",
)
parser.add_argument("--no-check", action="store_true", help="with --move-to: skip the quick check (testing)")
parser.add_argument(
"--better-translation",
choices=("auto", "yes", "no"),
default="auto",
help="the optional better translation model for Redub (NLLB-200 1.3B, a 5.5 GB download kept "
"as 2.7 GB): auto = only with a CUDA or ROCm GPU (default), yes = also without one, "
"no = never",
)
parser.add_argument(
"--no-zero-shot-vc",
action="store_true",
help="leave out Seed-VC (GPL-3.0, about 2 GB), the zero-shot voice converter that gives voices "
"that are not trained a native accent",
)
parser.add_argument(
"--remove-indextts",
action="store_true",
help="delete <data>/runtime/index-tts (the IndexTTS-2.5 runtime of earlier versions, about "
"19 GB) without asking; without this flag setup only offers it in an interactive terminal",
)
return parser.parse_args(argv)
def find_uv() -> str:
installed = os.environ.get(UV_ENV)
if installed and Path(installed).exists():
return installed
found = shutil.which("uv")
if found:
return found
raise SetupError("uv was not found; run setup.sh / setup.cmd, which installs it.")
def choose_data_dir(args: argparse.Namespace, plat: str) -> Path:
"""``--data-dir`` > ``$MIMVOX_DATA`` > ask: a full setup never picks a place silently. Only ``--quick-check`` and
``--runtime-toml-only`` fall back to location.toml or the default directory."""
explicit = args.data_dir or os.environ.get(DATA_ENV)
default = (read_location(plat) or default_data_dir(plat)).expanduser().resolve()
if explicit:
chosen = Path(explicit).expanduser().resolve()
elif args.quick_check or args.runtime_toml_only or args.remove:
chosen = default
elif not args.yes and sys.stdin.isatty():
chosen = ask_data_dir(plat, default)
else:
raise SetupError(
"no install location given: pass --data-dir DIR (a full setup needs about "
f"{RUNTIME_GB} GB, so the place is never chosen silently), or run it in a terminal "
"without --yes to be asked."
)
return chosen
def ask_data_dir(plat: str, default: Path) -> Path:
say(f"Where should the voice runtime go? It needs about {RUNTIME_GB} GB (models and two Python environments).")
say("Free space per volume:")
for root, free in volumes(plat):
say(f" {root:<28} {free:7.0f} GB free")
say(f"Default: {default}")
while True:
try:
answer = input("[setup] Data directory (Enter for the default): ").strip().strip('"')
except EOFError:
raise SetupError("no install location chosen (no input)") from None
chosen = Path(answer).expanduser() if answer else default
if not chosen.is_absolute():
say("Please give a full path (for example D:\\Voice or /data/voice).")
continue
return chosen.resolve()
def _rmtree(path: Path) -> None:
"""Deletes a folder; a symlink or junction is removed as a link and its target stays."""
if path.is_symlink():
path.unlink()
return
if path.is_junction():
path.rmdir()
return
def writable(func, target, exc) -> None: # noqa: ANN001 - shutil's callback
if isinstance(exc, FileNotFoundError):
return
# Windows refuses to delete read-only files (git objects, some wheels).
Path(target).chmod(0o700)
func(target)
shutil.rmtree(path, onexc=writable)
def remove_components(setup: Setup, value: str) -> int:
"""``--remove``: deletes the components' folders and rewrites runtime.toml without them."""
items = [x.strip() for x in value.split(",") if x.strip()]
unknown = [x for x in items if x not in COMPONENTS]
if unknown or "speech" in items:
say(
f"Failed: cannot remove {', '.join(unknown or ['speech'])} (optional components: "
f"{', '.join(c for c in COMPONENTS if c != 'speech')})."
)
return 1
if not (setup.components & set(SPEECH_MODELS)) - set(items):
say("Failed: at least one voice-cloning model (OmniVoice, VoxCPM2 or Chatterbox) has to stay installed.")
return 1
labels = {
"training": "Voice training",
"omnivoice": "OmniVoice voice cloning",
"translation": "Translation",
"better_translation": "Better translation",
"native_accent": "Native accent",
"music_removal": "Music removal",
"ukrainian": "Ukrainian speech",
"cast": "Character voices",
**{name: f"{spec['label']} voice cloning" for name, spec in CLONE_MODELS.items()},
}
plan = [(f"remove_{c}", f"Removing {labels[c].lower()}") for c in items] + [("runtime_toml", "Finishing")]
event(event="plan", steps=[{"id": i, "label": label} for i, label in plan])
failed: list[str] = []
for component in items:
step = f"remove_{component}"
event(event="step", id=step, state="run")
try:
for path in setup.component_paths(component):
if path.exists():
say(f"Deleting {path}")
if path.is_dir():
_rmtree(path)
else:
path.unlink()
except OSError as error:
message = f"{labels[component]}: {error}"
say(f"Failed: {message}")
failed.append(message)
event(event="step", id=step, state="fail", message=message)
continue
setup.components.discard(component)
event(event="step", id=step, state="ok")
event(event="step", id="runtime_toml", state="run")
try:
setup.write_runtime_toml()
event(event="step", id="runtime_toml", state="ok")
except SetupError as error:
failed.append(str(error))
event(event="step", id="runtime_toml", state="fail", message=str(error))
event(event="done", ok=not failed, **({"failed": failed} if failed else {}))
return 1 if failed else 0
def build_setup(args: argparse.Namespace) -> Setup:
global GUI
if args.gui:
GUI = True
args.yes = True
args.skip_toolchain = True
plat = host_platform()
root = Path(__file__).resolve().parents[2]
data_dir = choose_data_dir(args, plat)
return Setup(
root=root,
plat=plat,
arch=host_arch(),
data_dir=data_dir,
skip_toolchain=args.skip_toolchain,
skip_models=args.skip_models,
force_cpu=args.cpu,
force_gpu=args.gpu,
assume_yes=args.yes,
force=args.force,
uv_path=find_uv(),
)
def run_move(args: argparse.Namespace) -> int:
"""``--move-to`` (move_runtime.py); exit code 0 only when everything went through."""
import move_runtime as mv
plat = host_platform()
windows = plat == "windows"
explicit = args.data_dir or os.environ.get(DATA_ENV)
current = Path(explicit).expanduser() if explicit else (read_location(plat) or default_data_dir(plat))
new = Path(args.move_to).expanduser().resolve()
try:
old, resume, same = mv.prepare(current.resolve(), new, windows, args.force)
mv.move_files(old, new, resume, same, args.force)
fixer = mv.fix_venv_paths(new, old, windows)
mv.out(f"Updated {len(fixer.fixed)} file(s) that held the old path")
gpu = recorded_gpu(new) or Gpu("cuda")
setup = Setup(
root=Path(__file__).resolve().parents[2],
plat=plat,
arch=host_arch(),
data_dir=new,
gpu=gpu,
components=previous_components(new) or set(COMPONENTS),
uv_path=find_uv() if windows else "",
)
if windows:
for venv in setup.refresh_venv_launchers():
mv.out(f"warning: could not make the launchers of {venv} again")
setup.write_runtime_toml() # also writes (or removes) location.toml
mv.out("Rewrote runtime.toml and the location pointer")
if not args.no_check:
problems = setup.quick_check()
if problems:
kept = ", the old copy was kept" if old.exists() else ""
raise mv.MoveError(f"the moved runtime failed the quick check{kept}: " + "; ".join(problems))
mv.out("Quick check passed")
(new / mv.MARKER).unlink(missing_ok=True)
if old.exists():
mv.out(f"Deleting the old copy {old}")
mv.remove_tree(old)
setup.write_location() # the old folder may have held location.toml (the default dir is the config dir too)
mv.out("done")
return 0
except mv.MoveError as error:
mv.out(f"failed: {error}")
return 1
except OSError as error:
mv.out(f"failed: {error}. Run the same command again to resume.")
return 1
def main(argv: Sequence[str] | None = None) -> int:
args = parse_args(argv)
if args.move_to:
return run_move(args)
try:
setup = build_setup(args)
except SetupError as error:
say(f"Failed: {error}")
return 1
setup.detect()
try:
setup.resolve_components(args)
except SetupError as error:
say(f"Failed: {error}")
return 1
if args.quick_check:
problems = setup.quick_check()
if problems:
say(f"Quick check found {len(problems)} problem(s):")
for line in problems:
say(f" - {line}")
say("Run setup again (without --quick-check) to fix them.")
return 1
say("Quick check passed.")
return 0
if args.remove:
return remove_components(setup, args.remove)
if args.runtime_toml_only:
try:
setup.write_runtime_toml()
except SetupError as error:
say(f"Failed: {error}")
return 1
return 0
setup.confirm()
# This process's own temporary files (downloaded archives) go there too.
tempfile.tempdir = str(setup.temp_dir())
failed: list[str] = []
models = not args.skip_models
has = setup.components.__contains__
better = models and has("better_translation")
zero_shot = has("native_accent")
training = has("training")
plan = [("toolchain", "System tools")]
if training:
plan.append(("applio_source", "Voice training: source"))
plan.append(("engine_env", "Speech engine"))
if models:
if has("omnivoice"):
plan.append(("omnivoice", "OmniVoice: model"))
plan.append(("whisper", "Speech recognition (Whisper)"))
if has("translation"):
plan.append(("speech_models", "Translation model"))
if better:
plan.append(("better_translation", "Better translation model"))
if has("music_removal"):
plan.append(("separation", "Music removal model"))
if has("cast"):
plan.append(("cast_runtime", "Character voices: runtime"))
if models:
plan.append(("cast_model", "Character voices: model"))
if zero_shot:
plan.append(("zero_shot_vc", "Native accent converter"))
ukrainian = has("ukrainian")
if ukrainian:
plan.append(("holos_env", "Ukrainian speech: environment"))
if models:
plan.append(("holos_models", "Ukrainian speech: models"))
clones = [name for name in CLONE_MODELS if has(name)]
for name in clones:
plan.append((f"{name}_env", f"{CLONE_MODELS[name]['label']}: environment"))
if models:
plan.append((f"{name}_models", f"{CLONE_MODELS[name]['label']}: model"))
if training:
plan.append(("applio_env", "Voice training: environment"))
if models:
plan.append(("applio_models", "Voice training: models"))
plan.append(("runtime_toml", "Finishing"))
labels = dict(plan)
event(
event="plan",
steps=[
{"id": i, "label": label, "gb": 0.0 if setup.step_present(i) else round(setup.step_gb(i), 2)}
for i, label in plan
],
)
def attempt(step_id: str, step) -> bool: # noqa: ANN001 - a bound method
event(event="step", id=step_id, state="run")
say(f"== {labels.get(step_id, step_id)} ==")
meter = StepMeter(setup.data_dir, step_id, setup.step_gb(step_id)) if GUI else None
try:
step()
except (SetupError, OSError) as error:
say(f"Failed: {error}")
failed.append(str(error))
event(event="step", id=step_id, state="fail", message=str(error))
return False
finally:
wrote = meter.stop() if meter else 0.0
# A step that found everything in place wrote nothing: the app leaves it out of the progress.
event(event="step", id=step_id, state="ok", work=wrote >= 0.05, gb=round(wrote, 3))
return True
def skipped(*step_ids: str) -> None:
for step_id in step_ids:
if step_id in labels:
event(event="step", id=step_id, state="skip")
attempt("toolchain", setup.toolchains)
applio_cloned = training and attempt(
"applio_source", lambda: setup.ensure_repo("Applio", APPLIO_URL, APPLIO_COMMIT, setup.applio)
)
if attempt("engine_env", setup.engine_env):
if models:
if has("omnivoice"):
attempt("omnivoice", setup.omnivoice_models)
attempt("whisper", setup.whisper_model)
if has("translation"):
attempt("speech_models", setup.speech_models)
if better:
attempt("better_translation", setup.better_translation_model)
if has("music_removal"):
attempt("separation", setup.separation_model)
else:
skipped("omnivoice", "whisper", "speech_models", "better_translation", "separation")
if has("cast") and attempt("cast_runtime", setup.cast_runtime):
if models:
attempt("cast_model", setup.cast_model)
else:
skipped("cast_model")
if zero_shot and setup.engine_python().exists():
attempt("zero_shot_vc", setup.zero_shot_vc_runtime)
else:
skipped("zero_shot_vc")
if ukrainian and attempt("holos_env", setup.holos_env):
if models:
attempt("holos_models", setup.holos_models_step)
else:
skipped("holos_models")
for name in clones:
if attempt(f"{name}_env", lambda n=name: setup.clone_env(n)):
if models:
attempt(f"{name}_models", lambda n=name: setup.clone_models_step(n))
else:
skipped(f"{name}_models")
if applio_cloned and attempt("applio_env", setup.applio_venv):
if models:
attempt("applio_models", setup.applio_models)
else:
if training and not applio_cloned:
skipped("applio_env")
skipped("applio_models")
attempt("runtime_toml", setup.write_runtime_toml)
if not failed:
setup.remove_unused_pythons()
setup.offer_legacy_removal(args.remove_indextts)
if args.skip_models:
warn("--skip-models: no model files were downloaded; run setup again without it before using the app.")
if failed:
say(f"Setup finished with {len(failed)} step(s) failed; fix them and run it again (it resumes):")
for line in failed:
say(f" - {line}")
event(event="done", ok=False, failed=failed)
return 1
event(event="done", ok=True)
if GUI:
return 0
for line in setup.ready_lines():
say(line)
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
say("Interrupted. Run it again to resume where it stopped.")
sys.exit(130)