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.

8.9 KB
Raw Blame
import importlib.util
import sys
from pathlib import Path

import pytest
from mimvox_engine import backends, tts
from mimvox_engine.backends import clone
from mimvox_engine.redub import handlers
from mimvox_engine.registry import EngineError

TOOLS = Path(__file__).resolve().parents[2] / "tools" / "setup"


def _setup_module():
    spec = importlib.util.spec_from_file_location("mimvox_setup_models", TOOLS / "setup.py")
    module = importlib.util.module_from_spec(spec)
    sys.modules["mimvox_setup_models"] = module
    spec.loader.exec_module(module)
    return module


def install(tmp_path, *names):
    """A runtime.toml dict with the given clone models' interpreters and weights on disk."""
    runtime = {"python": {}, "paths": {}}
    for name in names:
        model = backends.by_name(name)
        py = tmp_path / name / "python"
        py.parent.mkdir(parents=True)
        py.write_bytes(b"")
        weights = tmp_path / "models" / name
        weights.mkdir(parents=True)
        for f in (*model.required, clone.STAMP):
            (weights / f).write_bytes(b"x")
        runtime["python"][name] = str(py)
        runtime["paths"][f"{name}_model"] = str(weights)
    return runtime


@pytest.fixture(autouse=True)
def fresh():
    for b in clone._ALL:
        b._status, b._runtime = "missing", {}
    yield
    for b in clone._ALL:
        b._status, b._runtime = "missing", {}


def probe(runtime):
    for b in clone._ALL:
        b.probe(runtime)


def test_a_named_model_speaks(tmp_path):
    probe(install(tmp_path, "voxcpm"))
    lang, backend = tts.speech_language({"language": "pl", "model": "voxcpm"})
    assert (lang, backend) == ("pl", clone.VOXCPM)
    tts.check_backend_ready(backend)  # "idle": it loads when it first speaks


def test_a_model_that_does_not_speak_the_language_is_refused(tmp_path):
    probe(install(tmp_path, "chatterbox"))
    with pytest.raises(EngineError) as e:
        tts.speech_language({"language": "uk", "model": "chatterbox"})
    assert e.value.code == "bad_request" and "Ukrainian" in e.value.message


def test_omnivoice_with_exact_stress_reads_ukrainian_with_holos(monkeypatch):
    holos = backends.by_name("holos")
    monkeypatch.setattr(holos, "available", lambda: True)
    assert tts.speech_language({"language": "uk", "model": "omnivoice"})[1] is holos
    assert tts.speech_language({"language": "uk", "model": "omnivoice", "exact_stress": False})[1] is not holos


def test_an_unknown_or_missing_model(tmp_path):
    probe(install(tmp_path))
    with pytest.raises(EngineError) as e:
        tts.speech_language({"language": "en", "model": "holos"})
    assert e.value.code == "bad_request"
    with pytest.raises(EngineError) as e:
        tts.speech_language({"language": "en", "model": "voxcpm"})
    assert e.value.code == "not_ready"


def test_auto_keeps_omnivoice_and_adds_the_languages_it_lacks(tmp_path):
    assert "he" not in backends.languages()
    with pytest.raises(EngineError):
        tts.speech_language({"language": "he"})
    probe(install(tmp_path, "voxcpm", "chatterbox"))
    assert tts.speech_language({"language": "en"})[1].name == "omnivoice"
    assert tts.speech_language({"language": "he"})[1] is clone.VOXCPM
    assert "he" in backends.languages()
    assert [b.name for b in backends.selectable()][-2:] == ["voxcpm", "chatterbox"]


def test_setup_installs_what_the_engine_looks_for():
    setup = _setup_module()
    for b in clone._ALL:
        spec = setup.CLONE_MODELS[b.name]
        assert set(spec["required"]) == set(b.required)
        assert setup.CLONE_STAMP == clone.STAMP
        assert b.name in setup.COMPONENTS
        assert spec["revision"] and len(spec["revision"]) == 40


@pytest.fixture
def no_omnivoice(monkeypatch):
    from mimvox_engine.backends.omnivoice import OMNIVOICE

    monkeypatch.setattr(OMNIVOICE, "_status", "missing")
    monkeypatch.setattr(OMNIVOICE, "_absent", True)


def test_without_omnivoice_another_model_speaks_its_own_languages(tmp_path, no_omnivoice):
    assert tts.speech_status() == "missing"
    probe(install(tmp_path, "chatterbox"))
    assert tts.speech_status() == "ready"
    assert backends.languages() == set(clone.CHATTERBOX.languages)
    assert tts.speech_language({"language": "en"}) == ("en", clone.CHATTERBOX)
    with pytest.raises(EngineError):
        tts.speech_language({"language": "uk"})


def test_the_last_voice_model_stays_on(tmp_path, no_omnivoice):
    import asyncio
    from types import SimpleNamespace

    from mimvox_engine import components

    probe(install(tmp_path, "chatterbox", "voxcpm"))
    ctx = SimpleNamespace(data_dir=tmp_path)
    asyncio.run(components.components_set(ctx, {"id": "voxcpm", "on": False}))
    with pytest.raises(EngineError) as e:
        asyncio.run(components.components_set(ctx, {"id": "chatterbox", "on": False}))
    assert e.value.code == "bad_request"


def test_the_runtime_folder_is_found_without_applio_or_omnivoice(tmp_path):
    from mimvox_engine import config

    py = tmp_path / "runtime" / "engine" / ".venv" / "bin" / "python"
    assert config.runtime_root({"python": {"engine": str(py)}, "paths": {}}) == tmp_path / "runtime"


def test_a_model_that_does_not_fit_on_the_gpu_moves_to_the_processor(tmp_path, monkeypatch):
    import asyncio

    from mimvox_engine.workerproc import WorkerError

    b = clone.CHATTERBOX
    runtime = install(tmp_path, "chatterbox")
    runtime["device"] = {"backend": "cuda"}
    b.probe(runtime)
    monkeypatch.setattr(b, "_cpu", False)
    monkeypatch.setattr(b, "_client", None)
    made = []

    class Client:
        def __init__(self, device):
            self.device, self.calls = device, []

        async def call(self, op, params, **kw):
            self.calls.append(op)
            if self.device == "cuda":
                raise WorkerError("no_vram", "no room")
            return {"op": op}

        async def stop(self):
            pass

    def ensure(self):
        if self._client is None:
            self._client = Client(self._device())
            made.append(self._client)
        return self._client

    async def nothing_to_stop(_client):
        return []

    monkeypatch.setattr(clone.WorkerBackend, "_ensure_client", ensure)
    monkeypatch.setattr(clone, "stop_idle", nothing_to_stop)
    assert asyncio.run(b._call("synth", {})) == {"op": "synth"}
    assert [c.device for c in made] == ["cuda", "cpu"]
    assert made[1].calls == ["load", "synth"]


def test_a_small_card_keeps_less_vram_free(monkeypatch):
    from mimvox_engine import worker_kit

    monkeypatch.delenv("MIMVOX_VRAM_RESERVE_GB", raising=False)
    assert worker_kit.vram_reserve_gb(4 * 2**30) == worker_kit.SMALL_CARD_RESERVE_GB
    assert worker_kit.vram_reserve_gb(12 * 2**30) == worker_kit.VRAM_RESERVE_GB


def redub_voice(model):
    voice = handlers._Voice.__new__(handlers._Voice)
    voice.model = model
    return voice


def test_redub_speaks_with_the_model_picked(tmp_path):
    probe(install(tmp_path, "voxcpm", "chatterbox"))
    assert handlers._model({"model": "chatterbox"}) == "chatterbox"
    assert redub_voice("voxcpm").backend("pl") is clone.VOXCPM
    with pytest.raises(EngineError) as e:
        redub_voice("chatterbox").backend("uk")
    assert e.value.code == "bad_request"
    assert redub_voice("auto").backend("pl") is backends.for_language("pl")


def test_redub_refuses_an_unknown_or_missing_model(tmp_path):
    probe(install(tmp_path, "chatterbox"))
    with pytest.raises(EngineError) as e:
        handlers._model({"model": "voxcpm"})
    assert e.value.code == "not_ready"
    with pytest.raises(EngineError) as e:
        handlers._model({"model": "holos"})
    assert e.value.code == "bad_request"


def test_every_speech_environment_pins_transformers_and_the_hub():
    setup = _setup_module()
    for packages in (setup.ENGINE_PACKAGES, setup.CLONE_MODELS["voxcpm"]["packages"]):
        names = {p.split("==")[0] for p in packages if "==" in p}
        assert {"transformers", "huggingface-hub"} <= names, packages


def test_workers_run_without_hub_kernels(monkeypatch):
    from mimvox_engine import workerproc

    monkeypatch.setenv("USE_HUB_KERNELS", "1")
    assert workerproc.child_env()["USE_HUB_KERNELS"] == "0"


def test_every_environment_has_a_lock_that_agrees_with_setup():
    setup = _setup_module()
    envs = {
        "engine": (*setup.ENGINE_TORCH, *setup.ENGINE_PACKAGES, *setup.ENGINE_NO_DEPS, *setup.SEEDVC_PACKAGES),
        "holos": (*setup.ENGINE_TORCH, *setup.HOLOS_PACKAGES, *setup.HOLOS_NO_DEPS),
        "applio": (),
        **{name: (*setup.ENGINE_TORCH, *spec["packages"]) for name, spec in setup.CLONE_MODELS.items()},
    }
    for env, packages in envs.items():
        lines = (setup.LOCKS / f"{env}.txt").read_text(encoding="utf-8").splitlines()
        locked = dict(line.split("==", 1) for line in lines)
        assert list(locked) == sorted(locked) and all("==" in line for line in lines), env
        for pin in (p for p in packages if "==" in p):
            name, version = pin.split("==", 1)
            assert locked.get(name.lower().replace("_", "-")) == version, (env, pin)