Free, open-source real-time voice changer for Windows: 20 live voices, local AI voice conversion (Seed-VC on ONNX Runtime), soundboard, virtual mic, hotkeys.
Web installer: AI voice pack downloaded during setup or on demand
skya5b57266feeb
diff --git a/README.md b/README.mdindex 4b2bd7b..2457849 100644--- a/README.md+++ b/README.md@@ -16,10 +16,11 @@ telemetry.## Download-Get **`VoxShift-Setup-<version>.exe`** from-[Releases](../../releases/latest) and run it.+Get **`VoxShift-Setup-<version>.exe`** (about 60 MB) from+[Releases](../../releases/latest) and run it. It's a web installer:* **Per-user install.** It goes into `%LOCALAPPDATA%\Programs\VoxShift`, with shortcuts and an uninstaller. The app itself needs no admin rights.+* **AI voices.** Leave **"Download AI voices now"** checked to fetch the 820 MB AI voice pack during setup. It comes in 25 MB pieces, and each one is SHA-256 checked. If you skip it, the app offers the download the first time you use an AI voice, and it resumes if interrupted.* **Virtual microphone.** Leave **"Install the virtual microphone"** checked. Setup downloads the free [VB-CABLE](https://vb-audio.com/Cable/) driver from vb-audio.com and only runs it if VB-Audio's code signature checks out. Approve the two Windows prompts (admin + driver), once.* In Discord, OBS or your game, choose **CABLE Output (VB-Audio Virtual Cable)** as the microphone.@@ -121,10 +122,15 @@ python -m venv .venv.venv\Scripts\python -m pip install torch torchaudio --index-url https://download.pytorch.org/whl/cu128.venv\Scripts\python -m pip install -r requirements.txt pyinstaller pystray pillow sv-ttk.venv\Scripts\python -m voxshift export-onnx # downloads the open weights, writes models/onnx (~1.2 GB)-.venv\Scripts\python packaging/build.py # build/dist/VoxShift + installer (needs Inno Setup 6)-.venv\Scripts\python -m pytest # 43 tests+.venv\Scripts\python packaging/build.py # app + web installer + AI voice pack chunks (needs Inno Setup 6)+.venv\Scripts\python -m pytest # 46 tests```+`build.py --bundle-models` makes an offline installer (about 880 MB)+instead. `packaging/publish.py --models` and `--app` upload the voice pack+and installer to GitHub releases. They go one file at a time with retries,+and files already uploaded are skipped.+The developer install can also run the AI voices in PyTorch with a CUDA-graphsolver (`ai-whisper-small`, `ai-realtime`). These have lower latency onNVIDIA GPUs.diff --git a/packaging/build.py b/packaging/build.pyindex 28b1fa6..27f7cb8 100644--- a/packaging/build.py+++ b/packaging/build.py@@ -2,6 +2,7 @@python packaging/build.py # -> build/dist/VoxShift/ (+ build/VoxShift-Setup-<ver>.exe)python packaging/build.py --no-installer+ python packaging/build.py --bundle-models # offline installer (~880 MB) instead of the web installerRequires the dev environment once, to export the AI model to ONNX(`python -m voxshift export-onnx`); the resulting app needs no Python,@@ -34,6 +35,7 @@ def version() -> str:def main():ap = argparse.ArgumentParser()ap.add_argument("--no-installer", action="store_true")+ ap.add_argument("--bundle-models", action="store_true", help="offline installer with the AI model inside")args = ap.parse_args()missing = [f for f in MODEL_FILES if not (MODEL / f).is_file()]@@ -46,15 +48,21 @@ def main():subprocess.run([sys.executable, "-m", "PyInstaller", str(ROOT / "packaging" / "voxshift.spec"), "--noconfirm","--distpath", str(BUILD / "dist"), "--workpath", str(BUILD / "work")], check=True)- print("== AI model")- dest = DIST / "models" / "onnx" / MODEL.name- dest.mkdir(parents=True, exist_ok=True)- for f in MODEL_FILES:- shutil.copy2(MODEL / f, dest / f)+ shutil.rmtree(DIST / "models", ignore_errors=True)+ iscc_defines = []+ if args.bundle_models:+ print("== AI model (bundled: offline installer)")+ dest = DIST / "models" / "onnx" / MODEL.name+ dest.mkdir(parents=True, exist_ok=True)+ for f in MODEL_FILES:+ shutil.copy2(MODEL / f, dest / f)+ else:+ print("== AI voice pack (web installer: downloaded during setup or from the app)")+ iscc_defines.append(f"/DModelInclude={write_model_pack()}")for doc in ("LICENSE", "THIRD_PARTY_NOTICES.md"): # licence texts travel with the binariesshutil.copy2(ROOT / doc, DIST / doc)size = sum(p.stat().st_size for p in DIST.rglob("*") if p.is_file())- print(f"app folder: {DIST} ({size / 2**30:.2f} GB)")+ print(f"app folder: {DIST} ({size / 2**20:.0f} MB)")if args.no_installer:return@@ -64,7 +72,28 @@ def main():returnprint("== Inno Setup")subprocess.run([str(iscc), f"/DAppVersion={version()}", f"/DDistDir={DIST}", f"/DOutDir={BUILD}",- str(ROOT / "packaging" / "voxshift.iss")], check=True)+ *iscc_defines, str(ROOT / "packaging" / "voxshift.iss")], check=True)+++def write_model_pack() -> Path:+ """Chunk the model into build/model-pack (what gets published as the models release) and+ emit the Pascal include that makes the installer download exactly those chunks."""+ sys.path.insert(0, str(ROOT))+ from voxshift.ai import model_pack++ pack_dir = BUILD / "model-pack"+ shutil.rmtree(pack_dir, ignore_errors=True)+ manifest = model_pack.pack(MODEL, pack_dir)+ lines = ["procedure AddModelDownloads;", "begin",+ f" AddChunk('{model_pack.BASE_URL}manifest.json', 'manifest.json', "+ f"'{model_pack._sha256(pack_dir / 'manifest.json')}');"]+ lines += [f" AddChunk('{c['url']}', '{c['name']}', '{c['sha256']}');" for c in manifest["chunks"]]+ lines += ["end;", ""]+ inc = BUILD / "model_downloads.iss"+ inc.write_text("\n".join(lines), encoding="utf-8")+ print(f"{len(manifest['chunks'])} chunks ({manifest['total_size'] / 2**20:.0f} MB) in {pack_dir}; "+ f"publish them as release '{model_pack.PACK_TAG}' (python packaging/publish.py --models)")+ return incif __name__ == "__main__":diff --git a/packaging/publish.py b/packaging/publish.pynew file mode 100644index 0000000..2f34d81--- /dev/null+++ b/packaging/publish.py@@ -0,0 +1,83 @@+"""Publish build outputs to GitHub releases, one file at a time with retries.++ python packaging/publish.py --models # build/model-pack -> release models-v1 (not "latest")+ python packaging/publish.py --app # build/VoxShift-Setup-<ver>.exe -> release v<ver> (latest)++Files already on the release with the right size are skipped, so re-running+after a network failure only uploads what is missing. Needs the GitHub CLI.+"""+from __future__ import annotations++import argparse+import json+import subprocess+import sys+import time+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+BUILD = ROOT / "build"+sys.path.insert(0, str(ROOT))+from voxshift.ai.model_pack import PACK_TAG, REPO # noqa: E402+++def gh(*args, check=True) -> str:+ r = subprocess.run(["gh", *args], capture_output=True, text=True)+ if check and r.returncode:+ raise RuntimeError(f"gh {' '.join(args[:3])}: {r.stderr.strip()}")+ return r.stdout+++def ensure_release(tag: str, title: str, notes: str, latest: bool) -> int:+ if subprocess.run(["gh", "release", "view", tag, "--repo", REPO], capture_output=True).returncode:+ gh("release", "create", tag, "--repo", REPO, "--title", title, "--notes", notes,+ f"--latest={'true' if latest else 'false'}")+ return json.loads(gh("api", f"repos/{REPO}/releases/tags/{tag}"))["id"]+++def assets(release_id: int) -> dict[str, dict]:+ return {a["name"]: a for a in json.loads(gh("api", f"repos/{REPO}/releases/{release_id}/assets?per_page=100"))}+++def upload(tag: str, release_id: int, files: list[Path], tries: int = 6) -> None:+ for i, f in enumerate(files, 1):+ for attempt in range(1, tries + 1):+ have = assets(release_id).get(f.name)+ if have and have["state"] == "uploaded" and have["size"] == f.stat().st_size:+ print(f"[{i}/{len(files)}] {f.name}: ok")+ break+ if have: # partial / stale upload: remove before retrying+ gh("api", "-X", "DELETE", f"repos/{REPO}/releases/assets/{have['id']}", check=False)+ print(f"[{i}/{len(files)}] {f.name}: uploading ({f.stat().st_size / 2**20:.1f} MB, try {attempt})")+ subprocess.run(["gh", "release", "upload", tag, str(f), "--repo", REPO, "--clobber"],+ capture_output=True)+ time.sleep(1)+ else:+ raise SystemExit(f"{f.name}: still failing after {tries} attempts; re-run to resume")+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--models", action="store_true")+ ap.add_argument("--app", action="store_true")+ ap.add_argument("--notes", type=Path, help="release notes file for --app")+ a = ap.parse_args()+ if a.models:+ pack = BUILD / "model-pack"+ files = [pack / "manifest.json", *sorted(pack.glob("*.part*"))]+ rid = ensure_release(PACK_TAG, "AI voice pack v1",+ "Model chunks downloaded by the VoxShift installer and app. "+ "You don't need to download these by hand.", latest=False)+ upload(PACK_TAG, rid, files)+ if a.app:+ ns: dict = {}+ exec((ROOT / "voxshift" / "__init__.py").read_text(), ns)+ ver = ns["__version__"]+ exe = BUILD / f"VoxShift-Setup-{ver}.exe"+ notes = a.notes.read_text(encoding="utf-8") if a.notes else f"VoxShift {ver}"+ rid = ensure_release(f"v{ver}", f"VoxShift {ver}", notes, latest=True)+ upload(f"v{ver}", rid, [exe])+++if __name__ == "__main__":+ main()diff --git a/packaging/voxshift.iss b/packaging/voxshift.issindex 9003187..92bfd1b 100644--- a/packaging/voxshift.iss+++ b/packaging/voxshift.iss@@ -1,5 +1,6 @@; VoxShift installer (Inno Setup 6).-; Built by packaging/build.py, which passes AppVersion / DistDir / OutDir.+; Built by packaging/build.py, which passes AppVersion / DistDir / OutDir and, for the web installer,+; ModelInclude (generated Pascal that lists the AI voice pack chunks with their SHA-256).; Per-user install (%LOCALAPPDATA%\Programs), so the app itself needs no admin rights;; only the optional virtual-microphone driver asks for elevation.@@ -19,6 +20,7 @@ AppName=VoxShiftAppVersion={#AppVersion}AppVerName=VoxShift {#AppVersion}AppPublisher=VoxShift+AppPublisherURL=https://github.com/Metrix187/voxshiftDefaultDirName={localappdata}\Programs\VoxShiftDefaultGroupName=VoxShiftDisableProgramGroupPage=yes@@ -31,13 +33,15 @@ SetupIconFile=..\voxshift\assets\voxshift.icoUninstallDisplayIcon={app}\VoxShift.exeUninstallDisplayName=VoxShiftWizardStyle=modern-; model weights are already dense; fast LZMA keeps build time sane for ~1 GB-Compression=lzma2/fast-SolidCompression=no+Compression=lzma2/ultra64+SolidCompression=yesCloseApplications=yesRestartApplications=no[Tasks]+#ifdef ModelInclude+Name: "aivoices"; Description: "Download AI voices now (about 820 MB; you can also do this later in the app)"; Check: not ModelInstalled+#endifName: "vbcable"; Description: "Install the virtual microphone (free VB-CABLE driver from vb-audio.com; Windows will ask for permission)"; Check: not CableInstalledName: "desktopicon"; Description: "Create a desktop shortcut"Name: "autostart"; Description: "Start VoxShift with Windows (in the tray)"; Flags: unchecked@@ -53,6 +57,10 @@ Name: "{autodesktop}\VoxShift"; Filename: "{app}\VoxShift.exe"; Tasks: desktopicRoot: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: string; ValueName: "VoxShift"; ValueData: """{app}\VoxShift.exe"" --minimized"; Flags: uninsdeletevalue; Tasks: autostart[Run]+#ifdef ModelInclude+; the chunks were downloaded and hash-checked on the "Preparing" page; rebuild + verify the model files+Filename: "{app}\voxshift-cli.exe"; Parameters: "models assemble --chunks ""{tmp}"""; StatusMsg: "Installing AI voices..."; Flags: runhidden waituntilterminated; Tasks: aivoices+#endif; 1) download the official VB-CABLE pack and refuse it unless its Authenticode signature is VB-Audio's;; 2) Setup itself runs the verified driver setup elevated (-i -h = install, hidden UI). Requesting elevation; from this visible wizard keeps the UAC prompt in front; Windows also asks for driver consent once.@@ -63,6 +71,8 @@ Filename: "{app}\VoxShift.exe"; Description: "Launch VoxShift"; Flags: nowait po[UninstallDelete]Type: filesandordirs; Name: "{app}\_internal"Type: filesandordirs; Name: "{app}\vbcable"+; downloaded AI voice pack (settings and your own voices in %APPDATA%\VoxShift are kept)+Type: filesandordirs; Name: "{localappdata}\VoxShift\models"[Code]function VBCableDownloaded: Boolean;@@ -75,3 +85,66 @@ begin{ The driver runs from the DriverStore, so look for its service, not a file in System32\drivers. }Result := RegKeyExists(HKLM, 'SYSTEM\CurrentControlSet\Services\VBAudioVACMME');end;++function ModelInstalled: Boolean;+begin+ Result := FileExists(ExpandConstant('{localappdata}\VoxShift\models\onnx\whisper-small-bigvgan\config.json'));+end;++#ifdef ModelInclude+var+ DownloadPage: TDownloadWizardPage;++{ Queue a file unless an earlier attempt already left a verified copy in Setup's temp folder,+ so pressing Install again after a network error only fetches what is still missing. }+procedure AddChunk(const Url, Name, Sha: String);+var+ Path: String;+begin+ Path := ExpandConstant('{tmp}\' + Name);+ if FileExists(Path) and (GetSHA256OfFile(Path) = Sha) then+ Log('already have ' + Name)+ else+ DownloadPage.Add(Url, Name, Sha);+end;++#include ModelInclude++function OnDownloadProgress(const Url, FileName: String; const Progress, ProgressMax: Int64): Boolean;+begin+ Result := True;+end;++procedure InitializeWizard;+begin+ DownloadPage := CreateDownloadPage('Downloading AI voices',+ 'VoxShift is downloading its AI voice pack (about 820 MB). Every piece is checked before use.',+ @OnDownloadProgress);+end;++function NextButtonClick(CurPageID: Integer): Boolean;+begin+ Result := True;+ if (CurPageID = wpReady) and WizardIsTaskSelected('aivoices') then begin+ DownloadPage.Clear;+ AddModelDownloads;+ DownloadPage.Show;+ try+ try+ DownloadPage.Download;+ except+ if DownloadPage.AbortedByUser then+ Log('AI voice download aborted by user.')+ else+ { (no line may start with '#': the preprocessor would read it as a directive) }+ SuppressibleMsgBox('The AI voice download was interrupted: ' + GetExceptionMessage + #13#10#13#10 ++ 'Click Install to resume, or untick "Download AI voices" to skip it ' ++ '(VoxShift can download them later).', mbError, MB_OK, IDOK);+ Result := False;+ end;+ finally+ DownloadPage.Hide;+ end;+ end;+end;+#endifdiff --git a/tests/test_model_pack.py b/tests/test_model_pack.pynew file mode 100644index 0000000..f40a6d2--- /dev/null+++ b/tests/test_model_pack.py@@ -0,0 +1,86 @@+"""AI voice pack: pack -> serve -> resumable download -> verified reassembly."""+import http.server+import json+import threading+from pathlib import Path++import pytest++from voxshift.ai import model_pack as mp+++def model(tmp_path):+ d = tmp_path / "src" / "tiny-model"+ d.mkdir(parents=True)+ rng = __import__("random").Random(0)+ for name, size in (("a.onnx", 70_000), ("b.onnx", 5), ("config.json", 300), ("c.npz", 123_457)):+ (d / name).write_bytes(bytes(rng.getrandbits(8) for _ in range(size)))+ return d+++def serve(root: Path, flaky: dict):+ """Static server honouring Range; drops chosen chunks halfway the first time."""++ class H(http.server.SimpleHTTPRequestHandler):+ def __init__(self, *a, **k):+ super().__init__(*a, directory=str(root), **k)++ def log_message(self, *a):+ pass++ def do_GET(self):+ p = root / self.path.lstrip("/")+ data = p.read_bytes()+ start = int(self.headers["Range"].split("=")[1].split("-")[0]) if self.headers.get("Range") else 0+ body = data[start:]+ self.send_response(206 if start else 200)+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ if flaky.pop(p.name, False): # send half, then hang up+ self.wfile.write(body[: len(body) // 2])+ self.wfile.flush()+ self.connection.close()+ return+ self.wfile.write(body)++ srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ return srv+++def test_pack_and_assemble_roundtrip(model, tmp_path):+ m = mp.pack(model, tmp_path / "pack", chunk_size=40_000, base_url="x/")+ assert len(m["chunks"]) == 5 and m["total_size"] == 193_762+ out = mp.assemble(json.loads((tmp_path / "pack" / "manifest.json").read_text()), tmp_path / "pack",+ tmp_path / "dest")+ for f in model.iterdir():+ assert (out / f.name).read_bytes() == f.read_bytes()+++def test_download_resumes_after_dropped_connection(model, tmp_path, monkeypatch):+ monkeypatch.setattr(mp.time, "sleep", lambda s: None)+ pack_dir = tmp_path / "pack"+ pack_dir.mkdir()+ flaky = {"tiny-model.part003": True} # this chunk's first request is cut off halfway+ srv = serve(pack_dir, flaky)+ base = f"http://127.0.0.1:{srv.server_address[1]}/"+ m = mp.pack(model, pack_dir, chunk_size=40_000, base_url=base)+ seen = []+ out = mp.download(progress=lambda d, t: seen.append((d, t)), base_url=base, dest_root=tmp_path / "dest")+ srv.shutdown()+ assert not flaky, "the flaky chunk was requested"+ assert seen[-1] == (m["total_size"], m["total_size"])+ for f in model.iterdir():+ assert (out / f.name).read_bytes() == f.read_bytes()+ assert not (tmp_path / "dest" / ".download").exists()+++def test_corrupt_chunk_is_rejected(model, tmp_path):+ m = mp.pack(model, tmp_path / "pack", chunk_size=40_000, base_url="x/")+ p = tmp_path / "pack" / m["chunks"][1]["name"]+ b = bytearray(p.read_bytes())+ b[100] ^= 0xFF+ p.write_bytes(bytes(b))+ with pytest.raises(ValueError, match="corrupt"):+ mp.assemble(m, tmp_path / "pack", tmp_path / "dest")diff --git a/voxshift/ai/model_pack.py b/voxshift/ai/model_pack.pynew file mode 100644index 0000000..6d7ae01--- /dev/null+++ b/voxshift/ai/model_pack.py@@ -0,0 +1,187 @@+"""AI voice pack: split / download / reassemble the ONNX model.++The 820 MB model is published once as a GitHub release (``models-v1``) cut+into 25 MB chunks plus a ``manifest.json`` with SHA-256 for every chunk and+every reassembled file. Small chunks make both publishing and downloading+robust: a failed chunk is retried on its own, an interrupted download+resumes, and nothing is trusted until its hash matches.++ pack() dev: model dir -> chunks + manifest (for upload)+ download() app/installer: manifest + chunks -> verified model dir+ assemble() chunks already on disk (e.g. fetched by the installer) -> model dir+"""+from __future__ import annotations++import hashlib+import json+import os+import shutil+import threading+import time+import urllib.request+from pathlib import Path+from typing import Callable++from ..paths import install_dir, user_models_dir++REPO = "Metrix187/voxshift"+PACK_TAG = "models-v1"+MODEL_NAME = "whisper-small-bigvgan"+BASE_URL = os.environ.get("VOXSHIFT_PACK_URL", f"https://github.com/{REPO}/releases/download/{PACK_TAG}/")+CHUNK = 25 * 2**20+_BUF = 2**20++Progress = Callable[[int, int], None] # (bytes_done, bytes_total)+++def _sha256(path: Path) -> str:+ h = hashlib.sha256()+ with open(path, "rb") as f:+ for block in iter(lambda: f.read(_BUF), b""):+ h.update(block)+ return h.hexdigest()+++def find_model(name: str = MODEL_NAME) -> Path | None:+ """Installed model folder: bundled next to the app / repo, else downloaded."""+ for root in (install_dir() / "models", user_models_dir()):+ d = root / "onnx" / name+ if (d / "config.json").is_file():+ return d+ return None+++# ------------------------------------------------------------------ publishing+def pack(model_dir: Path, out_dir: Path, chunk_size: int = CHUNK, base_url: str = BASE_URL) -> dict:+ """Concatenate the model files and cut the stream into fixed-size chunks."""+ model_dir, out_dir = Path(model_dir), Path(out_dir)+ out_dir.mkdir(parents=True, exist_ok=True)+ files = sorted(p for p in model_dir.iterdir() if p.is_file())+ manifest = {"name": model_dir.name, "pack": PACK_TAG, "files": [], "chunks": []}+ chunk_idx, chunk_fill, out = 0, 0, None+ chunk_hash = None++ def close_chunk():+ nonlocal out+ if out:+ out.close()+ manifest["chunks"][-1]["sha256"] = chunk_hash.hexdigest()+ out = None++ for p in files:+ manifest["files"].append({"path": p.name, "size": p.stat().st_size, "sha256": _sha256(p)})+ with open(p, "rb") as f:+ while block := f.read(_BUF):+ while block:+ if out is None:+ chunk_idx += 1+ name = f"{model_dir.name}.part{chunk_idx:03d}"+ manifest["chunks"].append({"name": name, "url": base_url + name})+ out, chunk_fill, chunk_hash = open(out_dir / name, "wb"), 0, hashlib.sha256()+ take = min(len(block), chunk_size - chunk_fill)+ out.write(block[:take])+ chunk_hash.update(block[:take])+ chunk_fill += take+ block = block[take:]+ if chunk_fill == chunk_size:+ manifest["chunks"][-1]["size"] = chunk_fill+ close_chunk()+ if out is not None:+ manifest["chunks"][-1]["size"] = chunk_fill+ close_chunk()+ manifest["total_size"] = sum(c["size"] for c in manifest["chunks"])+ (out_dir / "manifest.json").write_text(json.dumps(manifest, indent=1))+ return manifest+++# ------------------------------------------------------------------ installing+def assemble(manifest: dict, chunk_dir: Path, dest_root: Path | None = None) -> Path:+ """Verify chunks, rebuild the files, verify them, then move into place atomically."""+ chunk_dir = Path(chunk_dir)+ for c in manifest["chunks"]:+ p = chunk_dir / c["name"]+ if not p.is_file() or p.stat().st_size != c["size"] or _sha256(p) != c["sha256"]:+ raise ValueError(f"chunk {c['name']} is missing or corrupt")+ dest = (Path(dest_root) if dest_root else user_models_dir()) / "onnx" / manifest["name"]+ staging = dest.with_name(dest.name + ".staging")+ shutil.rmtree(staging, ignore_errors=True)+ staging.mkdir(parents=True)+ chunks = iter(manifest["chunks"])+ src, left_in_chunk = None, 0+ for f in manifest["files"]:+ h, remaining = hashlib.sha256(), f["size"]+ with open(staging / f["path"], "wb") as out:+ while remaining:+ if left_in_chunk == 0:+ if src:+ src.close()+ c = next(chunks)+ src, left_in_chunk = open(chunk_dir / c["name"], "rb"), c["size"]+ block = src.read(min(_BUF, remaining, left_in_chunk))+ out.write(block)+ h.update(block)+ remaining -= len(block)+ left_in_chunk -= len(block)+ if h.hexdigest() != f["sha256"]:+ raise ValueError(f"{f['path']} failed verification after reassembly")+ if src:+ src.close()+ if dest.exists():+ shutil.rmtree(dest)+ staging.rename(dest)+ return dest+++def _fetch(url: str, path: Path, size: int, sha: str, cancel: threading.Event | None,+ on_bytes: Callable[[int], None], retries: int = 5) -> None:+ """Download one chunk with resume (HTTP Range) and retries; verify its hash."""+ for attempt in range(1, retries + 1):+ have = path.stat().st_size if path.exists() else 0+ if have > size:+ path.unlink()+ have = 0+ try:+ if have < size:+ req = urllib.request.Request(url, headers={"User-Agent": "VoxShift", "Range": f"bytes={have}-"})+ with urllib.request.urlopen(req, timeout=30) as r, open(path, "ab" if r.status == 206 else "wb") as f:+ if r.status != 206:+ on_bytes(-have) # server ignored Range: restart this chunk+ while block := r.read(_BUF):+ if cancel and cancel.is_set():+ raise InterruptedError("download cancelled")+ f.write(block)+ on_bytes(len(block))+ if _sha256(path) == sha:+ return+ on_bytes(-path.stat().st_size)+ path.unlink()+ except InterruptedError:+ raise+ except OSError:+ if attempt == retries:+ raise+ time.sleep(min(2 ** attempt, 15))+ raise ValueError(f"{path.name}: checksum mismatch after {retries} attempts")+++def download(progress: Progress | None = None, cancel: threading.Event | None = None,+ base_url: str = BASE_URL, dest_root: Path | None = None) -> Path:+ """Fetch the AI voice pack (resumable) and install it. Returns the model dir."""+ req = urllib.request.Request(base_url + "manifest.json", headers={"User-Agent": "VoxShift"})+ with urllib.request.urlopen(req, timeout=30) as r:+ manifest = json.loads(r.read())+ cache = (Path(dest_root) if dest_root else user_models_dir()) / ".download"+ cache.mkdir(parents=True, exist_ok=True)+ total = manifest["total_size"]+ done = [sum((cache / c["name"]).stat().st_size for c in manifest["chunks"] if (cache / c["name"]).exists())]++ def on_bytes(n):+ done[0] = max(0, done[0] + n)+ if progress:+ progress(min(done[0], total), total)++ for c in manifest["chunks"]: # chunks live next to the manifest (works for mirrors too)+ _fetch(base_url + c["name"], cache / c["name"], c["size"], c["sha256"], cancel, on_bytes)+ model = assemble(manifest, cache, dest_root)+ shutil.rmtree(cache, ignore_errors=True)+ return modeldiff --git a/voxshift/ai/onnx_backend.py b/voxshift/ai/onnx_backend.pyindex 6f28525..524957c 100644--- a/voxshift/ai/onnx_backend.py+++ b/voxshift/ai/onnx_backend.py@@ -44,8 +44,9 @@ class OnnxSeedVCModel:def __init__(self, onnx_dir: str, providers: list[str] | None = None):d = Path(onnx_dir)- if not d.is_absolute(): # "models/onnx/<name>" relative to the install / repo root- d = install_dir() / d+ if not d.is_absolute(): # "models/onnx/<name>": bundled, or the downloaded voice pack+ from .model_pack import find_model+ d = find_model(d.name) or install_dir() / dif not (d / "config.json").is_file():raise FileNotFoundError(f"{d} has no exported model; run `python -m voxshift export-onnx` first")self.dir = ddiff --git a/voxshift/cli.py b/voxshift/cli.pyindex ecc3e32..7d9ad26 100644--- a/voxshift/cli.py+++ b/voxshift/cli.py@@ -91,6 +91,33 @@ def cmd_cable(a):print(f" note: {c.caveat}")+def cmd_models(a):+ import json+ from pathlib import Path++ from .ai import model_pack as mp+ if a.action == "status":+ d = mp.find_model()+ print(f"AI voice pack: {'installed at ' + str(d) if d else 'not installed'}")+ elif a.action == "download":+ last = [0.0]++ def progress(done, total):+ import time+ if time.monotonic() - last[0] > 0.5 or done == total:+ last[0] = time.monotonic()+ print(f"\r {done / 2**20:7.1f} / {total / 2**20:.1f} MB ({100 * done / total:5.1f} %)",+ end="", flush=True)+ print(f"downloading the AI voice pack from {mp.BASE_URL}")+ print(f"\ninstalled: {mp.download(progress)}")+ elif a.action == "pack":+ m = mp.pack(Path(a.model or mp.find_model()), Path(a.out))+ print(f"{len(m['chunks'])} chunks, {m['total_size'] / 2**20:.1f} MB -> {a.out}")+ elif a.action == "assemble":+ manifest = json.loads((Path(a.chunks) / "manifest.json").read_text())+ print(f"installed: {mp.assemble(manifest, Path(a.chunks))}")++def cmd_live(a):import sounddevice as sd@@ -187,6 +214,13 @@ def build_parser() -> argparse.ArgumentParser:s.add_argument("--hostapi")s.set_defaults(fn=cmd_cable)+ s = sub.add_parser("models", help="AI voice pack: status / download / pack / assemble")+ s.add_argument("action", choices=["status", "download", "pack", "assemble"])+ s.add_argument("--model", help="pack: model folder (default: the installed one)")+ s.add_argument("--out", default="build/model-pack", help="pack: output folder")+ s.add_argument("--chunks", help="assemble: folder with manifest.json + downloaded chunks")+ s.set_defaults(fn=cmd_models)+s = sub.add_parser("gui", help="open the desktop app")s.add_argument("--minimized", action="store_true", help="start in the system tray")s.set_defaults(fn=cmd_gui)diff --git a/voxshift/gui.py b/voxshift/gui.pyindex 6008890..1abbbf0 100644--- a/voxshift/gui.py+++ b/voxshift/gui.py@@ -20,7 +20,8 @@ from . import __version__, winsysfrom .audio.cable import find_cables, install_vbcablefrom .audio.engine import AudioEngine, NoVirtualCable, default_hostapi, list_devicesfrom .paths import FROZEN, log_dir-from .presets import build_processor, create_ai_voice, delete_user_voice, is_ai, list_presets+from .presets import (NEEDS_DOWNLOAD, build_processor, create_ai_voice, delete_user_voice, is_ai, list_presets,+ unavailable_reason)from .settings import SettingsSR = 48000@@ -254,6 +255,15 @@ class App:self.banner_btn = ttk.Button(self.banner, text="Set up virtual microphone", command=self.install_cable)self.banner_btn.pack(side="right")+ # AI voice pack download bar (shown while downloading)+ self.dl_bar = ttk.Frame(r, padding=(14, 4))+ self.dl_label = ttk.Label(self.dl_bar, text="")+ self.dl_label.pack(side="left")+ ttk.Button(self.dl_bar, text="Cancel", command=self._cancel_download).pack(side="right")+ self.dl_progress = ttk.Progressbar(self.dl_bar, mode="determinate", length=320, maximum=1000)+ self.dl_progress.pack(side="right", padx=10)+ self._dl_cancel = None+self.status = tk.StringVar(value="Starting…") # packed before the body so it always gets spacettk.Label(r, textvariable=self.status, padding=(14, 6), foreground="#aaa").pack(fill="x", side="bottom")body = ttk.Frame(r, padding=(14, 4))@@ -265,7 +275,7 @@ class App:ttk.Label(left, text="Search voices", foreground="#999").pack(anchor="w")ttk.Entry(left, textvariable=self.search, width=32).pack(fill="x")ttk.Button(left, text="+ New AI voice", style="Accent.TButton",- command=lambda: NewAIVoiceDialog(self)).pack(fill="x", side="bottom")+ command=lambda: self.ensure_ai_pack(lambda: NewAIVoiceDialog(self))).pack(fill="x", side="bottom")self.tree = ttk.Treeview(left, show="tree", selectmode="browse", height=12)self.tree.column("#0", width=290)self.tree.pack(fill="both", expand=True, pady=6)@@ -346,6 +356,9 @@ class App:def _load_processor(self, spec):if not self.engine:return+ if unavailable_reason(spec) == NEEDS_DOWNLOAD:+ self.ensure_ai_pack(lambda: self._load_processor(spec))+ returnself._load_token += 1token = self._load_tokenif not is_ai(spec):@@ -494,6 +507,64 @@ class App:messagebox.showinfo("Virtual microphone", f"{cables[0].label}: {'working' if ok else 'NOT passing audio'} "f"({ratio:.0f} dB tone-to-noise)")+ # -------------------------------------------------------------- AI voice pack+ def ensure_ai_pack(self, then):+ """Run ``then`` now if the AI voice pack is installed, else offer to download it first."""+ from .ai.model_pack import find_model+ if find_model():+ then()+ return+ if self._dl_cancel is not None:+ self.status.set("The AI voice pack is still downloading…")+ return+ if messagebox.askyesno("AI voices", "AI voices need a one-time download of about 820 MB.\n\n"+ "Download them now? You can keep using VoxShift meanwhile, and an "+ "interrupted download resumes where it stopped."):+ self.download_ai_pack(then)++ def download_ai_pack(self, then=None):+ from .ai import model_pack+ cancel = self._dl_cancel = threading.Event()+ self.dl_progress["value"] = 0+ self.dl_label.config(text="Downloading AI voices…")+ self.dl_bar.pack(fill="x", after=self.root.winfo_children()[0])+ last = [0.0]++ def progress(done, total):+ import time+ if time.monotonic() - last[0] > 0.2 or done >= total:+ last[0] = time.monotonic()+ self.call_soon(lambda: self._dl_update(done, total))++ def run():+ try:+ model_pack.download(progress, cancel)+ msg, ok = "AI voices installed.", True+ except InterruptedError:+ msg, ok = "AI voice download paused — it resumes next time.", False+ except Exception as e:+ log.exception("AI voice pack download failed")+ msg, ok = f"AI voice download failed: {e} (it resumes next time)", False+ self.call_soon(lambda: self._dl_finished(msg, ok, then))+ threading.Thread(target=run, name="ai-pack-download", daemon=True).start()++ def _dl_update(self, done, total):+ self.dl_progress["value"] = 1000 * done / max(total, 1)+ self.dl_label.config(text=f"Downloading AI voices… {done / 2**20:.0f} / {total / 2**20:.0f} MB")++ def _dl_finished(self, msg, ok, then):+ self._dl_cancel = None+ self.dl_bar.pack_forget()+ self.status.set(msg)+ if ok:+ self.refresh_voices(select=self.current_key)+ if then:+ then()++ def _cancel_download(self):+ if self._dl_cancel:+ self._dl_cancel.set()+def _first_run(self):if self.s.first_run_done:returndiff --git a/voxshift/paths.py b/voxshift/paths.pyindex c556f57..5ce15dc 100644--- a/voxshift/paths.py+++ b/voxshift/paths.py@@ -31,6 +31,14 @@ def data_dir() -> Path:return d+def user_models_dir() -> Path:+ """Downloaded AI voice packs (%LOCALAPPDATA%/VoxShift/models); survives app updates."""+ base = os.environ.get("LOCALAPPDATA") or str(Path.home() / ".cache")+ d = Path(base) / APP_NAME / "models"+ d.mkdir(parents=True, exist_ok=True)+ return d++def user_voices_dir() -> Path:d = data_dir() / "voices"d.mkdir(parents=True, exist_ok=True)diff --git a/voxshift/presets.py b/voxshift/presets.pyindex 7c366c3..83a891a 100644--- a/voxshift/presets.py+++ b/voxshift/presets.py@@ -8,10 +8,11 @@ import shutilfrom pathlib import Pathfrom .dsp.graph import Voice-from .paths import models_dir, references_dir, user_voices_dir+from .paths import references_dir, user_voices_dirBUILTIN_DIR = Path(__file__).resolve().parent / "voices"ONNX_MODEL = "whisper-small-bigvgan"+NEEDS_DOWNLOAD = "AI voices need a one-time download (about 820 MB)"def preset_dirs() -> list[Path]:@@ -27,8 +28,8 @@ def unavailable_reason(spec: dict) -> str | None:if not is_ai(spec):return Noneif spec.get("backend") == "onnx":- d = models_dir() / "onnx" / spec.get("model", ONNX_MODEL)- return None if (d / "config.json").is_file() else "AI model files are not installed"+ from .ai.model_pack import find_model+ return None if find_model(spec.get("model", ONNX_MODEL)) else NEEDS_DOWNLOADif importlib.util.find_spec("torch") is None:return "needs the PyTorch developer setup"return None@@ -46,7 +47,7 @@ def list_presets(include_unavailable: bool = False) -> dict[str, dict]:continuespec["_path"] = str(p)spec["_user"] = d != BUILTIN_DIR- if include_unavailable or unavailable_reason(spec) is None:+ if include_unavailable or unavailable_reason(spec) in (None, NEEDS_DOWNLOAD):found[p.stem] = specreturn found