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
#!/usr/bin/env python3
"""Stage the runtime resources the installers bundle into crates/desktop/target/bundle-resources/ (the layout the app
looks for at runtime, see crates/desktop/Packager.toml)."""
from __future__ import annotations
import argparse
import email.utils
import hashlib
import http.client
import io
import shutil
import ssl
import subprocess
import sys
import tarfile
import tempfile
import time
import urllib.error
import urllib.request
import zipfile
from datetime import UTC, datetime
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
STAGE = REPO / "crates" / "desktop" / "target" / "bundle-resources"
REQUIRED_DIRS = ["engine/src", "presets", "tools/setup", "contract"]
OPTIONAL_FILES = ["DISCLAIMER.md", "THIRD_PARTY_NOTICES.md", "LICENSE", "LICENSE.md"]
# The uv the installers carry (keep it equal to UV_VERSION in setup.sh / setup.cmd).
UV_VERSION = "0.12.18"
UV_RELEASES = f"https://github.com/astral-sh/uv/releases/download/{UV_VERSION}"
IGNORE = shutil.ignore_patterns(
"__pycache__",
"*.pyc",
"*.pyo",
".venv",
"venv",
".pytest_cache",
".ruff_cache",
".mypy_cache",
"*.egg-info",
".DS_Store",
"Thumbs.db",
)
# 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
def retry_wait(error: Exception, 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 = (error.headers.get("Retry-After") or "").strip() if error.headers else ""
if after.isdigit():
return min(float(after), RETRY_AFTER_MAX)
try:
when = email.utils.parsedate_to_datetime(after)
except (TypeError, ValueError):
return RETRY_WAITS[attempt]
when = when if when.tzinfo else when.replace(tzinfo=UTC)
return min(max((when - datetime.now(UTC)).total_seconds(), 0.0), RETRY_AFTER_MAX)
if isinstance(error, urllib.error.URLError) and isinstance(error.reason, ssl.SSLCertVerificationError):
return None
if isinstance(error, (urllib.error.URLError, http.client.HTTPException, ConnectionError, TimeoutError)):
return RETRY_WAITS[attempt]
return None
def fetch(url: str) -> bytes:
"""Tried again after a temporary network failure (HTTP 5xx or 429, a dropped connection, a timeout)."""
attempt = 0
while True:
try:
with urllib.request.urlopen(url, timeout=120) as response: # noqa: S310 - a fixed https URL
return response.read()
except (OSError, http.client.HTTPException) as error:
wait = retry_wait(error, attempt) if attempt < len(RETRY_WAITS) else None
if wait is None:
raise
attempt += 1
print(
f"[stage] {url}: {error}; trying again in {wait:.0f} s "
f"(attempt {attempt + 1} of {len(RETRY_WAITS) + 1})",
flush=True,
)
time.sleep(wait)
def uv_binary(target: str) -> bytes:
"""The uv executable from the pinned release for ``target``, checked against the release's SHA-256."""
archive = f"uv-{target}.zip" if "windows" in target else f"uv-{target}.tar.gz"
data = fetch(f"{UV_RELEASES}/{archive}")
expected = fetch(f"{UV_RELEASES}/{archive}.sha256").decode().split()[0]
if hashlib.sha256(data).hexdigest() != expected:
raise SystemExit(f"[stage] {archive}: checksum mismatch")
name = "uv.exe" if "windows" in target else "uv"
if archive.endswith(".zip"):
with zipfile.ZipFile(io.BytesIO(data)) as z:
member = next(m for m in z.namelist() if m.rsplit("/", 1)[-1] == name)
return z.read(member)
with tarfile.open(fileobj=io.BytesIO(data)) as t:
member = next(m for m in t.getmembers() if m.name.rsplit("/", 1)[-1] == name and m.isfile())
extracted = t.extractfile(member)
assert extracted is not None
return extracted.read()
def stage_uv(targets: list[str]) -> None:
"""``bin/uv`` for one target, or a universal macOS binary (lipo) for two."""
out_dir = STAGE / "bin"
out_dir.mkdir(parents=True, exist_ok=True)
name = "uv.exe" if any("windows" in t for t in targets) else "uv"
out = out_dir / name
if any("linux" in t for t in targets):
# The AppImage tool (linuxdeploy) rewrites every ELF file in the AppDir and breaks the static uv, so Linux
# gets it gzipped; the app unpacks it on first use (crates/desktop/src/ui/setuprun.rs, uv_path).
import gzip
packed = out_dir / "uv.gz"
packed.write_bytes(gzip.compress(uv_binary(targets[0]), compresslevel=9))
print(f"[stage] uv {UV_VERSION} ({targets[0]}) -> {packed}")
return
if len(targets) == 1:
out.write_bytes(uv_binary(targets[0]))
else:
with tempfile.TemporaryDirectory() as tmp:
parts = []
for t in targets:
part = Path(tmp) / t
part.write_bytes(uv_binary(t))
parts.append(str(part))
subprocess.run(["lipo", "-create", "-output", str(out), *parts], check=True)
out.chmod(0o755)
print(f"[stage] uv {UV_VERSION} ({', '.join(targets)}) -> {out}")
def main() -> int:
parser = argparse.ArgumentParser(description="Stage the installers' bundled resources.")
parser.add_argument(
"--uv",
metavar="TARGET[,TARGET]",
help="also bundle uv for this target (e.g. x86_64-unknown-linux-musl); two comma-separated "
"targets make a macOS universal binary",
)
args = parser.parse_args()
missing = [d for d in REQUIRED_DIRS if not (REPO / d).is_dir()]
if missing:
print(f"[stage] missing required folders in {REPO}: {', '.join(missing)}", file=sys.stderr)
print("[stage] these are produced by other parts of the repo; check out a complete tree.", file=sys.stderr)
return 1
if not (REPO / "engine/src/mimvox_engine").is_dir():
print("[stage] engine/src/mimvox_engine is missing.", file=sys.stderr)
return 1
if STAGE.exists():
shutil.rmtree(STAGE)
STAGE.mkdir(parents=True)
count = 0
for rel in REQUIRED_DIRS:
shutil.copytree(REPO / rel, STAGE / rel, ignore=IGNORE)
for rel in OPTIONAL_FILES:
src = REPO / rel
if src.is_file():
shutil.copy2(src, STAGE / rel)
if args.uv:
stage_uv([t.strip() for t in args.uv.split(",") if t.strip()])
for path in STAGE.rglob("*"):
count += path.is_file()
print(f"[stage] {count} files staged in {STAGE}")
return 0
if __name__ == "__main__":
raise SystemExit(main())