Skip to content

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.

5.5 KB
Raw Blame
"""Write tools/setup/locks/<environment>.txt from a working runtime.

Each lock holds every package of that environment at the version the runtime runs, plus the packages that only
Windows or macOS install, at the versions they resolve to under those pins. Setup installs with ``-c`` each lock.

    uv run --no-project python tools/setup/lock.py <runtime folder>
"""

from __future__ import annotations

import importlib.util
import os
import re
import subprocess
import sys
import tempfile
import types
from pathlib import Path

HERE = Path(__file__).resolve().parent
LOCKS = HERE / "locks"
PLATFORMS = ("x86_64-manylinux_2_28", "x86_64-pc-windows-msvc", "aarch64-apple-darwin")
# crates/desktop/Packager.toml minimum-system-version, then the first one an environment's own pins have wheels for.
MACOS = ("13.0", "14.0")
LINE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9._-]*)==([^\s;+]+)")
# Each torch build (CUDA, ROCm, CPU) pins its own GPU packages exactly.
BUILD = re.compile(r"^(nvidia-|cuda-|triton$|pytorch-triton)")


def setup_module() -> types.ModuleType:
    spec = importlib.util.spec_from_file_location("mimvox_setup_lock", HERE / "setup.py")
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    return module


def canonical(name: str) -> str:
    return re.sub(r"[-_.]+", "-", name).lower()


def pins(text: str) -> dict[str, str]:
    found = {}
    for line in text.splitlines():
        match = LINE.match(line.strip())
        if match and not BUILD.match(canonical(match.group(1))):
            found[canonical(match.group(1))] = match.group(2)
    return found


class UvError(Exception):
    pass


def uv(*args: object, cwd: Path | None = None, env: dict[str, str] | None = None) -> str:
    done = subprocess.run(
        ["uv", *map(str, args)], capture_output=True, text=True, cwd=cwd, check=False, env={**os.environ, **(env or {})}
    )
    if done.returncode != 0:
        raise UvError(f"uv {' '.join(map(str, args[:3]))} failed:\n{done.stderr.strip()}")
    return done.stdout


def environments(s: types.ModuleType, runtime: Path) -> dict[str, tuple[Path, str, list[str], Path | None]]:
    """Each environment: its venv, Python version, requirements and the folder they are read in."""
    torch = list(s.ENGINE_TORCH)
    envs = {
        "engine": (
            runtime / s.ENGINE_DIR / ".venv",
            s.ENGINE_PYTHON,
            [*torch, *s.ENGINE_PACKAGES, *s.SEEDVC_PACKAGES],
            None,
        ),
        "holos": (runtime / s.HOLOS_DIR / ".venv", s.HOLOS_PYTHON, [*torch, *s.HOLOS_PACKAGES], None),
        "applio": (runtime / "applio" / ".venv", s.APPLIO_PYTHON, ["-r", "requirements.txt"], runtime / "applio"),
    }
    for name, spec in s.CLONE_MODELS.items():
        envs[name] = (runtime / name / ".venv", s.ENGINE_PYTHON, [*torch, *spec["packages"]], None)
    return envs


def lock(name: str, venv: Path, python: str, requirements: list[str], cwd: Path | None) -> dict[str, str]:
    py = venv / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
    if not py.exists():
        raise SystemExit(f"{name}: no environment at {venv}")
    locked = pins(uv("pip", "freeze", "--python", py))
    with tempfile.TemporaryDirectory() as tmp:
        constraints = Path(tmp) / "constraints.txt"
        constraints.write_text("".join(f"{n}=={v}\n" for n, v in sorted(locked.items())), encoding="utf-8")
        for target in PLATFORMS:
            for macos in MACOS if "apple" in target else MACOS[:1]:
                try:
                    out = compile_for(
                        target, python, constraints, requirements, cwd, {"MACOSX_DEPLOYMENT_TARGET": macos}
                    )
                except UvError:
                    if macos == MACOS[-1] or "apple" not in target:
                        raise
                    continue
                if "apple" in target and macos != MACOS[0]:
                    print(f"{name}: needs macOS {macos} or later")
                break
            for n, v in pins(out).items():
                locked.setdefault(n, v)
    return locked


def compile_for(
    target: str, python: str, constraints: Path, requirements: list[str], cwd: Path | None, env: dict[str, str]
) -> str:
    with tempfile.TemporaryDirectory() as tmp:
        inputs = Path(tmp) / "requirements.in"
        if requirements[:1] == ["-r"]:
            inputs = (cwd or Path.cwd()) / requirements[1]
        else:
            inputs.write_text("".join(f"{r}\n" for r in requirements), encoding="utf-8")
        return uv(
            "pip",
            "compile",
            "--quiet",
            "--no-header",
            "--no-annotate",
            "--python-version",
            python,
            "--python-platform",
            target,
            "-c",
            constraints,
            inputs,
            cwd=cwd,
            env=env,
        )


def main() -> int:
    if len(sys.argv) != 2:
        print(__doc__.strip(), file=sys.stderr)
        return 2
    runtime = Path(sys.argv[1]).expanduser().resolve()
    s = setup_module()
    LOCKS.mkdir(exist_ok=True)
    for name, (venv, python, requirements, cwd) in environments(s, runtime).items():
        try:
            locked = lock(name, venv, python, requirements, cwd)
        except UvError as exc:
            raise SystemExit(f"{name}: {exc}") from None
        (LOCKS / f"{name}.txt").write_text("".join(f"{n}=={v}\n" for n, v in sorted(locked.items())), "utf-8")
        print(f"{name}: {len(locked)} packages")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())