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 hashlib
import importlib.util
import sys
import threading
import urllib.error
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import pytest
REPO = Path(__file__).resolve().parents[2]
def _load(name, path):
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
return module
setup = _load("mimvox_setup_retries", REPO / "tools" / "setup" / "setup.py")
stage = _load("stage_resources", REPO / "scripts" / "build" / "stage_resources.py")
BODY = b"model weights " * 1000
SHA = hashlib.sha256(BODY).hexdigest()
class Server:
"""Answers each request with the next scripted reply: (status, headers, body), or "short" for a body cut off
after its first 100 bytes, or "resume" for a 206 with the rest of BODY from the requested range."""
def __init__(self, replies):
self.replies = list(replies)
self.requests = []
server = self
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
server.requests.append(self.headers.get("Range"))
reply = server.replies.pop(0) if len(server.replies) > 1 else server.replies[0]
if reply == "short":
self.send_response(200)
self.send_header("Content-Length", str(len(BODY)))
self.end_headers()
self.wfile.write(BODY[:100])
self.wfile.flush()
self.close_connection = True
return
if reply == "resume":
start = int(self.headers["Range"].removeprefix("bytes=").rstrip("-"))
reply = (206, {}, BODY[start:])
status, headers, body = reply
self.send_response(status)
for key, value in {"Content-Length": str(len(body)), **headers}.items():
self.send_header(key, value)
self.end_headers()
self.wfile.write(body)
def log_message(self, *_):
pass
self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self.url = f"http://127.0.0.1:{self.httpd.server_address[1]}/file.bin"
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
def close(self):
self.httpd.shutdown()
self.httpd.server_close()
@pytest.fixture
def serve():
servers = []
def start(*replies):
servers.append(Server(replies))
return servers[-1]
yield start
for server in servers:
server.close()
@pytest.fixture
def sleeps(monkeypatch):
waits = []
monkeypatch.setattr(setup.time, "sleep", waits.append)
return waits
def test_a_server_error_then_success_downloads_the_file(tmp_path, serve, sleeps):
server = serve((500, {}, b"oops"), (200, {}, BODY))
target = tmp_path / "model.bin"
setup.fetch_checked(server.url, target, SHA, "the model")
assert target.read_bytes() == BODY
assert not (tmp_path / "model.bin.part").exists()
assert sleeps == [2.0]
def test_not_found_fails_at_once(tmp_path, serve, sleeps):
server = serve((404, {}, b"no"))
with pytest.raises(setup.SetupError, match="404"):
setup.fetch_checked(server.url, tmp_path / "model.bin", SHA, "the model")
assert len(server.requests) == 1
assert sleeps == []
def test_too_many_requests_waits_as_long_as_retry_after_says(tmp_path, serve, sleeps):
server = serve((429, {"Retry-After": "7"}, b"slow down"), (200, {}, BODY))
setup.fetch_checked(server.url, tmp_path / "model.bin", SHA, "the model")
assert sleeps == [7.0]
def test_a_checksum_mismatch_is_not_tried_again(tmp_path, serve, sleeps):
server = serve((200, {}, BODY))
with pytest.raises(setup.SetupError, match="checksum"):
setup.fetch_checked(server.url, tmp_path / "model.bin", "0" * 64, "the model")
assert len(server.requests) == 1
assert sleeps == []
assert not (tmp_path / "model.bin.part").exists()
def test_the_attempts_are_bounded(tmp_path, serve, sleeps):
server = serve((503, {}, b"down"))
with pytest.raises(setup.SetupError, match="503"):
setup.fetch_checked(server.url, tmp_path / "model.bin", SHA, "the model")
assert len(server.requests) == len(setup.RETRY_WAITS) + 1
assert sleeps == list(setup.RETRY_WAITS)
def test_a_body_cut_short_resumes_from_where_it_stopped(tmp_path, serve, sleeps):
server = serve("short", "resume")
target = tmp_path / "model.bin"
setup.fetch_checked(server.url, target, SHA, "the model")
assert target.read_bytes() == BODY
assert server.requests == [None, "bytes=100-"]
assert sleeps == [2.0]
def test_a_plain_download_leaves_no_half_file_when_it_gives_up(tmp_path, serve, sleeps):
server = serve("short")
target = tmp_path / "archive.zip"
with pytest.raises(setup.SetupError):
setup.Setup._download(server.url, target)
assert not target.exists()
assert len(server.requests) == len(setup.RETRY_WAITS) + 1
def test_the_size_probe_asks_again_after_a_server_error(tmp_path, serve, sleeps, monkeypatch):
server = serve((502, {}, b""), (200, {}, b'[{"type": "file", "path": "a.bin", "size": 5}]'))
monkeypatch.setenv("HF_ENDPOINT", server.url.removesuffix("/file.bin"))
assert setup.hf_bytes("a/b", tmp_path) == 5
assert len(server.requests) == 2
assert sleeps == [2.0]
def test_retry_after_takes_seconds_or_a_date_and_is_capped():
assert setup.retry_after("12") == 12.0
assert setup.retry_after("Wed, 21 Oct 2015 07:28:00 GMT") == 0.0
assert setup.retry_after("99999") == setup.RETRY_AFTER_MAX
assert setup.retry_after("soon") is None
def _command(tmp_path, *outputs):
"""A command that prints the next of ``outputs`` to stderr and fails, then succeeds once they are used up."""
counter = tmp_path / "runs"
script = (
"import sys, pathlib\n"
"p = pathlib.Path(sys.argv[1]); n = int(p.read_text()) if p.exists() else 0; p.write_text(str(n + 1))\n"
"outputs = sys.argv[2:]\n"
"if n < len(outputs): sys.stderr.write(outputs[n] + '\\n'); sys.exit(1)\n"
)
return [sys.executable, "-c", script, counter, *outputs], counter
def test_a_download_command_runs_again_after_a_network_error(tmp_path, sleeps):
s = setup.Setup(root=tmp_path, plat="linux", arch="x86_64", data_dir=tmp_path / "data", uv_path="uv")
command, counter = _command(tmp_path, "fatal: unable to access: Could not resolve host: github.com")
assert s.run(command, tmp_path, retry="Fetching Applio") == 0
assert counter.read_text() == "2"
assert sleeps == [2.0]
def test_a_download_command_is_not_run_again_for_a_missing_file(tmp_path, sleeps):
s = setup.Setup(root=tmp_path, plat="linux", arch="x86_64", data_dir=tmp_path / "data", uv_path="uv")
command, counter = _command(tmp_path, "huggingface_hub.errors.EntryNotFoundError: 404 Client Error.")
assert s.run(command, tmp_path, retry="Downloading a/b") == 1
assert counter.read_text() == "1"
assert sleeps == []
def test_a_download_command_gives_up_after_the_last_attempt(tmp_path, sleeps):
s = setup.Setup(root=tmp_path, plat="linux", arch="x86_64", data_dir=tmp_path / "data", uv_path="uv")
command, counter = _command(tmp_path, *["503 Server Error: Service Unavailable"] * 9)
assert s.run(command, tmp_path, retry="Downloading a/b") == 1
assert counter.read_text() == str(len(setup.RETRY_WAITS) + 1)
def test_the_build_fetch_survives_a_server_error(serve, monkeypatch):
waits = []
monkeypatch.setattr(stage.time, "sleep", waits.append)
server = serve((500, {}, b"Internal Server Error"), (200, {}, BODY))
assert stage.fetch(server.url) == BODY
assert waits == [2.0]
def test_the_build_fetch_stops_at_not_found(serve, monkeypatch):
monkeypatch.setattr(stage.time, "sleep", lambda _: pytest.fail("waited"))
server = serve((404, {}, b"no"))
with pytest.raises(urllib.error.HTTPError):
stage.fetch(server.url)
assert len(server.requests) == 1