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
import asyncio
import types
from pathlib import Path
import numpy as np
import pytest
import soundfile as sf
from mimvox_engine import design, server, tts
from mimvox_engine.backends import clone
from mimvox_engine.backends.omnivoice import OMNIVOICE
from mimvox_engine.registry import EngineError
from test_speech_models import install, probe
@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 test_whisper_hears_only_the_start_of_a_take(tmp_path, monkeypatch):
take = tmp_path / "voice.wav"
sf.write(take, np.zeros(24000 * 40, np.float32), 24000)
seen = []
async def inspect(ref, detect=True):
seen.append(sf.info(ref).duration)
(tmp_path / "heard.omnivoice.json").write_text('{"text": "hi"}')
monkeypatch.setattr(OMNIVOICE, "inspect", inspect)
monkeypatch.setattr(design.reflang, "read_sidecar", lambda p: {"text": "hi"})
assert asyncio.run(_real_hear(take)) == "hi"
assert seen == [design.HEAR_S]
assert sorted(p.name for p in tmp_path.iterdir()) == ["voice.wav"]
_real_hear = design._hear
@pytest.fixture(autouse=True)
def hears_the_text(monkeypatch):
heard = {}
async def hear(path):
return heard.get("next", heard.get("all", "")) if heard else _last_text[0]
monkeypatch.setattr(design, "_hear", hear)
return heard
_last_text = [""]
@pytest.fixture
def ctx(tmp_path):
return types.SimpleNamespace(data_dir=str(tmp_path / "data"), runtime={})
def run(ctx, **params):
_last_text[0] = params.get("text", "")
return asyncio.run(design.voices_design(ctx, params))
def fake_design(calls):
async def make(text, lang, description, out_path):
calls.append((text, lang, description))
sf.write(out_path, np.zeros(24000, np.float32), 24000)
return str(out_path)
return make
def test_the_models_say_which_of_them_design(tmp_path, monkeypatch):
monkeypatch.setattr(OMNIVOICE, "probe", lambda runtime: None)
probe(install(tmp_path, "voxcpm", "chatterbox"))
flags = {m["id"]: m["design"] for m in server.speech_models(types.SimpleNamespace(runtime={}))}
assert flags == {"omnivoice": True, "voxcpm": True, "chatterbox": False}
def test_a_clip_in_a_designed_voice(tmp_path, ctx, monkeypatch):
probe(install(tmp_path, "voxcpm"))
calls = []
monkeypatch.setattr(clone.VOXCPM, "design", fake_design(calls))
res = run(ctx, model="voxcpm", language="PL", text=" Dzień dobry. ", description=" A calm,\n deep voice ")
assert calls == [("Dzień dobry.", "pl", "A calm, deep voice")]
assert res["model"] == "voxcpm" and res["language"] == "pl" and res["duration_s"] == 1.0
assert res["path"] == res["reference"] and res["path"].endswith("voice.wav")
assert res["description"] == "A calm, deep voice" and res["exact_stress"] is False
takes = design.voices_design_takes(ctx, {})["takes"]
assert [t["id"] for t in takes] == [res["id"]]
day, clock = takes[0]["when"].split(" ")
assert len(day) == 10 and len(clock) == 8 and res["id"].startswith(day.replace("-", ""))
def test_omnivoice_gets_its_own_terms(tmp_path, monkeypatch):
sent = []
class Client:
async def call(self, op, params, **kw):
sent.append((op, params))
return {"out": params["out"]}
monkeypatch.setattr(OMNIVOICE, "_client", Client())
monkeypatch.setattr(OMNIVOICE, "_status", "ready")
out = asyncio.run(OMNIVOICE.design("Привіт", "uk", "female, elderly", tmp_path / "a.wav"))
assert out == str(tmp_path / "a.wav")
op, params = sent[0]
assert op == "design" and params["instruct"] == "female, elderly" and params["lang"] == "uk"
assert "ref" not in params
@pytest.mark.parametrize(
("params", "code"),
[
({"model": "chatterbox", "language": "en", "text": "Hi"}, "bad_request"),
({"model": "voxcpm", "language": "uk", "text": "Привіт"}, "bad_request"),
({"model": "voxcpm", "language": "en", "text": " "}, "bad_request"),
({"model": "voxcpm", "language": "", "text": "Hi"}, "bad_request"),
({"model": "voxcpm", "language": "en", "text": "Hi", "description": "x" * 401}, "bad_request"),
({"model": "holos", "language": "uk", "text": "Привіт"}, "bad_request"),
({"model": "voxcpm", "language": "en", "text": "Hi", "loudness": -5}, "bad_request"),
({"model": "voxcpm", "language": "en", "text": "Hi", "loudness": "loud"}, "bad_request"),
],
)
def test_refusals(tmp_path, ctx, params, code):
probe(install(tmp_path, "voxcpm", "chatterbox"))
with pytest.raises(EngineError) as e:
run(ctx, **params)
assert e.value.code == code
def test_a_model_that_is_not_installed(tmp_path, ctx):
probe(install(tmp_path))
with pytest.raises(EngineError) as e:
run(ctx, model="voxcpm", language="en", text="Hi")
assert e.value.code == "not_ready"
def test_it_waits_for_no_other_generation(tmp_path, ctx, monkeypatch):
probe(install(tmp_path, "voxcpm"))
monkeypatch.setattr(tts, "_ACTIVE", ["job-1"])
with pytest.raises(EngineError) as e:
run(ctx, model="voxcpm", language="en", text="Hi")
assert e.value.code == "busy"
def test_it_holds_the_generation_slot_while_it_works(tmp_path, ctx, monkeypatch):
probe(install(tmp_path, "voxcpm"))
seen = []
async def design_while_busy(text, lang, description, out_path):
seen.append((tts.is_busy(), tts.busy_message("x")))
with pytest.raises(EngineError) as e, tts.holding("other"):
pass
seen.append(e.value.code)
sf.write(out_path, np.zeros(2400, np.float32), 24000)
return str(out_path)
monkeypatch.setattr(clone.VOXCPM, "design", design_while_busy)
run(ctx, model="voxcpm", language="en", text="Hi")
assert seen[0][0] is True and "Design" in seen[0][1] and seen[1] == "busy"
assert not tts.is_busy()
def test_ukrainian_is_read_again_by_holos(tmp_path, ctx, monkeypatch):
from mimvox_engine.backends.holos import HOLOS
said = []
async def holos_says(text, lang, reference, params):
said.append((text, lang, reference))
sf.write(params.out_path, np.zeros(48000, np.float32), 24000)
return str(params.out_path)
monkeypatch.setattr(OMNIVOICE, "_status", "ready")
monkeypatch.setattr(OMNIVOICE, "design", fake_design([]))
monkeypatch.setattr(HOLOS, "_status", "ready")
monkeypatch.setattr(HOLOS, "synthesize", holos_says)
res = run(ctx, model="omnivoice", language="uk", text="Привіт", description="male")
assert res["exact_stress"] is True and res["duration_s"] == 2.0
assert res["path"].endswith("speech.wav") and res["reference"].endswith("voice.wav")
assert said == [("Привіт", "uk", res["reference"])]
plain = run(ctx, model="omnivoice", language="uk", text="Привіт", exact_stress=False)
assert plain["exact_stress"] is False and plain["path"] == plain["reference"]
def test_only_the_last_takes_are_kept(tmp_path, ctx, monkeypatch):
probe(install(tmp_path, "voxcpm"))
monkeypatch.setattr(clone.VOXCPM, "design", fake_design([]))
monkeypatch.setattr(design, "KEEP", 2)
ids = [run(ctx, model="voxcpm", language="en", text=f"Take {i}")["id"] for i in range(3)]
kept = [t["id"] for t in design.voices_design_takes(ctx, {})["takes"]]
assert kept == ids[:0:-1]
def test_a_failed_take_leaves_nothing(tmp_path, ctx, monkeypatch):
probe(install(tmp_path, "voxcpm"))
async def fails(*_a):
raise EngineError("internal", "boom")
monkeypatch.setattr(clone.VOXCPM, "design", fails)
with pytest.raises(EngineError):
run(ctx, model="voxcpm", language="en", text="Hi")
assert design.voices_design_takes(ctx, {})["takes"] == []
def test_takes_are_deleted_one_by_one_or_all(tmp_path, ctx, monkeypatch):
probe(install(tmp_path, "voxcpm"))
monkeypatch.setattr(clone.VOXCPM, "design", fake_design([]))
ids = [run(ctx, model="voxcpm", language="en", text=f"Take {i}")["id"] for i in range(3)]
left = design.voices_design_delete(ctx, {"id": ids[1]})["takes"]
assert [t["id"] for t in left] == [ids[2], ids[0]]
keep = Path(ctx.data_dir) / "voices" / "mine.txt"
keep.parent.mkdir(parents=True, exist_ok=True)
keep.write_text("x")
for bad in ("../voices", "..", ".", "", None, "nope", f"{ids[0]}/.."):
with pytest.raises(EngineError) as e:
design.voices_design_delete(ctx, {"id": bad})
assert e.value.code == "not_found"
assert design.voices_design_delete(ctx, {"all": True})["takes"] == []
assert keep.is_file()
def test_an_omnivoice_take_nobody_can_hear_is_made_again(tmp_path, ctx, monkeypatch, hears_the_text):
calls = []
monkeypatch.setattr(OMNIVOICE, "_status", "ready")
monkeypatch.setattr(OMNIVOICE, "design", fake_design(calls))
answers = iter(["Thank you.", "", "Hello there, my friend"])
async def hear(path):
return next(answers)
monkeypatch.setattr(design, "_hear", hear)
res = run(ctx, model="omnivoice", language="en", text="Hello there, my friend")
assert len(calls) == 3 and res["clear"] is True
answers = iter(["Thank you."] * 3)
res = run(ctx, model="omnivoice", language="en", text="Hello there, my friend")
assert len(calls) == 6 and res["clear"] is False
def test_voxcpm_takes_are_not_heard(tmp_path, ctx, monkeypatch):
probe(install(tmp_path, "voxcpm"))
calls = []
monkeypatch.setattr(clone.VOXCPM, "design", fake_design(calls))
async def hear(path):
raise AssertionError("Whisper ran")
monkeypatch.setattr(design, "_hear", hear)
res = run(ctx, model="voxcpm", language="en", text="Hello there")
assert len(calls) == 1 and res["clear"] is None
def test_what_counts_as_heard():
assert design.said("Привіт! Це мій голос.", "привіт це мій голос") == 1.0
assert design.said("I will kill you!", "Thank you.") < design.CLEAR
assert design.said("Hi", "") == 0.0
long = "When you picture mountain climbers scaling Mount Everest, what comes to mind are teams of climbers. " * 5
assert design.said(long, "what comes to mind are teams of climbers") >= design.CLEAR
assert design.said(long, "Mount") < design.CLEAR
assert design.said(long, "Thank you for watching, see you next time") < design.CLEAR
def test_cancel_stops_the_take_and_leaves_nothing(tmp_path, ctx, monkeypatch):
probe(install(tmp_path, "voxcpm"))
started = asyncio.Event()
async def slow(text, lang, description, out_path):
out_path.parent.mkdir(parents=True, exist_ok=True)
started.set()
await asyncio.sleep(30)
monkeypatch.setattr(clone.VOXCPM, "design", slow)
async def scenario():
making = asyncio.ensure_future(design.voices_design(ctx, {"model": "voxcpm", "language": "en", "text": "Hi"}))
await started.wait()
assert await design.voices_design_cancel(ctx, {}) == {"cancelled": True}
with pytest.raises(EngineError) as err:
await making
return err.value.code
assert asyncio.run(scenario()) == "cancelled"
assert design.voices_design_takes(ctx, {})["takes"] == []
assert tts._ACTIVE == [None]
assert asyncio.run(design.voices_design_cancel(ctx, {})) == {"cancelled": False}
def test_without_a_model_the_first_installed_designer_speaks(tmp_path, ctx, monkeypatch):
probe(install(tmp_path, "voxcpm"))
calls = []
monkeypatch.setattr(clone.VOXCPM, "design", fake_design(calls))
monkeypatch.setattr(OMNIVOICE, "status", lambda: "missing")
assert run(ctx, language="de", text="Guten Tag.")["model"] == "voxcpm"
clone.VOXCPM._status = "missing"
with pytest.raises(EngineError) as err:
run(ctx, model="auto", language="de", text="Guten Tag.")
assert err.value.code == "not_ready"
def test_clearing_every_take_spares_the_one_being_made(ctx):
making = design.folder(design.config.data_dir(ctx)) / "20990101-000000-1"
making.mkdir(parents=True)
assert design.voices_design_delete(ctx, {"all": True}) == {"takes": []}
assert making.is_dir()
def _tone(path, amplitude, sr=48000):
t = np.arange(sr * 4) / sr
sf.write(path, (amplitude * np.sin(2 * np.pi * 220 * t)).astype(np.float32), sr)
def test_a_quiet_take_is_brought_to_the_loudness_asked(tmp_path):
clip = tmp_path / "voice.wav"
_tone(clip, 0.02)
before = design.level(clip, -23.0)
y, sr = sf.read(clip, dtype="float32")
assert before < -35
assert design.dubmix.lufs(y, sr) == pytest.approx(-23.0, abs=0.1)
assert sf.info(clip).subtype == "PCM_16"
def test_levelling_stops_short_of_clipping(tmp_path):
clip = tmp_path / "voice.wav"
t = np.arange(48000 * 4) / 48000
y = (0.01 * np.sin(2 * np.pi * 220 * t)).astype(np.float32)
y[1000] = 0.5
sf.write(clip, y, 48000)
design.level(clip, -23.0)
y, _ = sf.read(clip, dtype="float32")
assert 20 * np.log10(np.max(np.abs(y))) == pytest.approx(design.PEAK_DBFS, abs=0.05)
def test_silence_is_left_as_it_is(tmp_path):
clip = tmp_path / "voice.wav"
sf.write(clip, np.zeros(48000, np.float32), 48000)
assert design.level(clip, -23.0) is None
def _speech_with_pauses(sr, hum=None):
rng = np.random.default_rng(1)
t = np.arange(sr * 12) / sr
speech = rng.normal(0, 0.1, len(t)).astype(np.float32) * (np.sin(2 * np.pi * 0.25 * t) > 0)
noise = rng.normal(0, 0.0005, len(t)).astype(np.float32)
if hum is not None:
noise += 0.003 * np.sin(2 * np.pi * hum * t).astype(np.float32)
return speech + noise
def test_a_voxcpm_hum_stands_out_of_the_pauses(tmp_path):
clean, humming = tmp_path / "clean.wav", tmp_path / "hum.wav"
sf.write(clean, _speech_with_pauses(48000), 48000)
sf.write(humming, _speech_with_pauses(48000, hum=800.0), 48000)
assert design.hum_db(clean) < design.HUM_DB <= design.hum_db(humming)
def test_a_voice_can_be_made_in_any_language_a_speech_model_speaks(tmp_path, monkeypatch):
from mimvox_engine import backends, voices
from mimvox_engine.registry import EngineError
class Ctx:
data_dir = str(tmp_path)
monkeypatch.setattr(backends, "languages", lambda: {"en", "it", "uk"})
made = voices.voices_create(Ctx(), {"name": "Narratore", "language": "it"})["voice"]
assert voices.read_meta(voices.config.data_dir(Ctx()), made["id"])["language"] == "it"
voices.voices_rename(Ctx(), {"id": made["id"], "language": "en"})
assert voices.read_meta(voices.config.data_dir(Ctx()), made["id"])["language"] == "en"
voices.voices_rename(Ctx(), {"id": made["id"], "book_role": "men"})
meta = voices.read_meta(voices.config.data_dir(Ctx()), made["id"])
assert meta["book_role"] == "men" and meta["name"] == "Narratore"
with pytest.raises(EngineError):
voices.voices_rename(Ctx(), {"id": made["id"], "book_role": "children"})
with pytest.raises(EngineError):
voices.voices_create(Ctx(), {"name": "Nobody", "language": "xx"})
def test_a_voice_made_anew_keeps_its_id(tmp_path):
import numpy as np
import soundfile as sf
from mimvox_engine import voices
class Ctx:
data_dir = str(tmp_path)
clip = tmp_path / "a.wav"
sf.write(clip, np.zeros(16000, dtype=np.float32), 16000)
made = voices.import_voice(Ctx(), {"name": "Book · men", "reference_path": str(clip)})["voice"]
data = voices.config.data_dir(Ctx())
(data.voice(made["id"]) / "reference.omnivoice.json").write_text("{}")
sf.write(clip, np.ones(8000, dtype=np.float32) * 0.1, 16000)
again = voices.import_voice(Ctx(), {"name": "Book · men", "reference_path": str(clip), "into": made["id"]})["voice"]
assert again["id"] == made["id"]
assert len(sf.read(data.reference(made["id"]))[0]) == 8000
assert not (data.voice(made["id"]) / "reference.omnivoice.json").exists()
assert len(list((tmp_path / "voices").iterdir())) == 1
def test_a_voice_made_for_a_book_remembers_the_book_and_role(tmp_path):
from mimvox_engine import voices
class Ctx:
data_dir = str(tmp_path)
ref = tmp_path / "take.wav"
t = np.linspace(0, 3.0, 72000, endpoint=False)
sf.write(ref, (0.2 * np.sin(2 * np.pi * 180 * t)).astype(np.float32), 24000)
made = voices.voices_import(
Ctx(),
{
"name": "Мартін Іден · men",
"reference_path": str(ref),
"language": "uk",
"book": "Мартін Іден",
"book_role": "men",
},
)["voice"]
assert (made["book"], made["book_role"]) == ("Мартін Іден", "men")
plain = voices.voices_import(Ctx(), {"name": "Mine", "reference_path": str(ref), "language": "uk"})["voice"]
assert plain["book"] is None