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.

fix(setup): try downloads again after temporary network failures (#190)

Taras Hevlich442a9a4cab15
diff --git a/CHANGELOG.md b/CHANGELOG.md
index caa51a1..59740eb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,9 @@
## Unreleased
+* **Setup and the installer builds try a download again after a temporary network failure** (a server error, a
+ dropped connection, a timeout): up to four attempts with growing waits, and one line in the log for each. A missing
+ file or a corrupt download still stops at once; a model download continues where the last attempt stopped.
* **Deleting a design take can no longer delete anything else:** a take id from a program (API, MCP) must be one the
app made; before, the id ".." deleted the whole data folder.
* **A setup step that cannot delete or move a file fails on its own** (a file in use on Windows, say) instead of
diff --git a/engine/tests/test_download_retries.py b/engine/tests/test_download_retries.py
new file mode 100644
index 0000000..e1ef9ed
--- /dev/null
+++ b/engine/tests/test_download_retries.py
@@ -0,0 +1,213 @@
+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()
+
+
+def serve():
+ servers = []
+
+ def start(*replies):
+ servers.append(Server(replies))
+ return servers[-1]
+
+ yield start
+ for server in servers:
+ server.close()
+
+
+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
diff --git a/engine/tests/test_setup_tool.py b/engine/tests/test_setup_tool.py
index 59f7808..43e51bd 100644
--- a/engine/tests/test_setup_tool.py
+++ b/engine/tests/test_setup_tool.py
@@ -165,7 +165,7 @@ class FakeUv:
def fake_uv(tmp_path, monkeypatch):
s = make(tmp_path / "data")
uv = FakeUv(s)
- monkeypatch.setattr(setup.Setup, "run", lambda self, command, cwd=None, extra_env=None: uv.run(command))
+ monkeypatch.setattr(setup.Setup, "run", lambda self, command, cwd=None, extra_env=None, retry="": uv.run(command))
monkeypatch.setattr(setup.Setup, "quiet", lambda self, command, cwd=None: uv.run(command))
monkeypatch.setattr(setup.Setup, "read", lambda self, command, cwd=None: uv.read(command))
s.engine_env()
diff --git a/scripts/build/build-linux.sh b/scripts/build/build-linux.sh
index 4f9fb0f..84d3bd6 100755
--- a/scripts/build/build-linux.sh
+++ b/scripts/build/build-linux.sh
@@ -65,8 +65,9 @@ if [[ ",$FORMATS," == *",appimage,"* ]]; then
apprun="${XDG_CACHE_HOME:-$HOME/.cache}/.cargo-packager/AppImage/AppRun-$(uname -m)"
if [ ! -f "$apprun" ]; then
mkdir -p "$(dirname "$apprun")"
- curl -fsSL -o "$apprun" \
+ curl -fsSL --retry 3 --retry-connrefused -o "$apprun.part" \
"https://github.com/tauri-apps/binary-releases/releases/download/apprun-old/AppRun-$(uname -m)"
+ mv "$apprun.part" "$apprun"
fi
chmod 755 "$apprun"
fi
diff --git a/scripts/build/inno.py b/scripts/build/inno.py
index 1101912..49d015a 100755
--- a/scripts/build/inno.py
+++ b/scripts/build/inno.py
@@ -11,9 +11,10 @@ import hashlib
import subprocess
import sys
import tempfile
-import urllib.request
from pathlib import Path
+from stage_resources import fetch
+
REPO = Path(__file__).resolve().parents[2]
ICON_PNG = REPO / "tools" / "release" / "icons" / "icon_512x512.png"
ICON_ICO = REPO / "tools" / "release" / "icons" / "icon.ico"
@@ -896,8 +897,7 @@ def ensure_iscc(cache: Path) -> Path:
installer = cache / f"innosetup-{INNO_VERSION}.exe"
if not installer.is_file():
print(f"[inno] Downloading Inno Setup {INNO_VERSION}...", flush=True)
- with urllib.request.urlopen(INNO_URL, timeout=300) as response:
- data = response.read()
+ data = fetch(INNO_URL)
if hashlib.sha256(data).hexdigest() != INNO_SHA256:
raise SystemExit(f"[inno] {INNO_URL}: checksum mismatch")
installer.write_bytes(data)
diff --git a/scripts/build/stage_resources.py b/scripts/build/stage_resources.py
index f02f849..2d975d9 100755
--- a/scripts/build/stage_resources.py
+++ b/scripts/build/stage_resources.py
@@ -5,15 +5,21 @@ 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]
@@ -39,9 +45,50 @@ IGNORE = shutil.ignore_patterns(
)
+# 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:
- with urllib.request.urlopen(url, timeout=120) as response: # noqa: S310 - a fixed https URL
- return response.read()
+ """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:
diff --git a/setup.cmd b/setup.cmd
index 6d4dc4c..7ec0f67 100644
--- a/setup.cmd
+++ b/setup.cmd
@@ -11,7 +11,7 @@ set UV_VERSION=0.12.18
cd /d "%~dp0"
where uv >nul 2>&1 && goto run
echo [setup] Installing uv %UV_VERSION%...
-powershell -NoProfile -ExecutionPolicy Bypass -Command "irm https://astral.sh/uv/%UV_VERSION%/install.ps1 | iex" || exit /b 1
+powershell -NoProfile -ExecutionPolicy Bypass -Command "$u = 'https://astral.sh/uv/%UV_VERSION%/install.ps1'; foreach ($w in 2, 8, 30, 0) { try { $s = Invoke-RestMethod $u; break } catch { $c = [int]$_.Exception.Response.StatusCode; if (-not $w -or $c -in 401, 403, 404) { throw }; Write-Host ('[setup] ' + $_ + '; trying again in ' + $w + ' s...'); Start-Sleep $w } }; Invoke-Expression $s" || exit /b 1
rem Where the installer put it: the first of its candidates, in its own order, that holds uv.exe.
set "UV_BIN="
if defined UV_INSTALL_DIR if exist "%UV_INSTALL_DIR%\uv.exe" set "UV_BIN=%UV_INSTALL_DIR%"
diff --git a/setup.sh b/setup.sh
index faa5e44..69564ee 100755
--- a/setup.sh
+++ b/setup.sh
@@ -10,9 +10,10 @@ cd "$(dirname "$0")"
if ! command -v uv >/dev/null 2>&1; then
echo "[setup] Installing uv $UV_VERSION..."
if command -v curl >/dev/null 2>&1; then
- curl -LsSf "https://astral.sh/uv/$UV_VERSION/install.sh" | sh
+ curl -LsSf --retry 3 --retry-connrefused "https://astral.sh/uv/$UV_VERSION/install.sh" | sh
else
- wget -qO- "https://astral.sh/uv/$UV_VERSION/install.sh" | sh
+ wget -qO- --tries=4 --waitretry=30 --retry-connrefused --retry-on-http-error=429,500,502,503,504 \
+ "https://astral.sh/uv/$UV_VERSION/install.sh" | sh
fi
# Where the installer put it: the first of its candidates, in its own order, that holds uv.
UV_BIN=""
diff --git a/tools/setup/setup.py b/tools/setup/setup.py
index 059007e..b2346db 100644
--- a/tools/setup/setup.py
+++ b/tools/setup/setup.py
@@ -5,12 +5,16 @@ from __future__ import annotations
import argparse
import contextlib
+import email.utils
import hashlib
+import http.client
+import io
import json
import os
import platform
import re
import shutil
+import ssl
import subprocess
import sys
import tarfile
@@ -23,6 +27,7 @@ import urllib.request
import zipfile
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass, field
+from datetime import UTC, datetime
from pathlib import Path
APP_DIR_NAME = "mimvox"
@@ -344,6 +349,7 @@ SPEECH_MODELS = ("omnivoice", "voxcpm", "chatterbox")
# Portable ffmpeg for Windows when Applio (which brings one) is not installed.
FFMPEG_WINDOWS_URL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-{}-gpl.zip"
UV_HTTP_TIMEOUT = "600"
+UV_HTTP_RETRIES = "5"
# Records the commit of a source tree that came as an archive (no git).
ARCHIVE_MARKER = ".mimvox-commit"
@@ -510,15 +516,107 @@ def expect_download(remaining_bytes: int | None) -> None:
StepMeter.current.expect(remaining_bytes)
+# 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
+NETWORK_ERRORS = (OSError, http.client.HTTPException)
+NETWORK_FAILURE = re.compile(
+ r"could not resolve host|temporary failure in name resolution|name or service not known|nodename nor servname"
+ r"|getaddrinfo failed|no such host is known|network is unreachable|connection (reset|refused|aborted|closed)"
+ r"|connectionreseterror|connectionrefusederror|connecterror|readerror|readtimeout|connecttimeout|timed ?out"
+ r"|early eof|rpc failed|unexpected disconnect|remote end hung up|empty reply from server|transfer closed"
+ r"|http/2 stream|ssl_read|ssl_error_syscall|gnutls recv error|schannel: failed|failed to connect"
+ r"|returned error: (5\d\d|408|429)|\b(5\d\d|408|429) (server|client) error|server error '5|too many requests"
+ r"|bad gateway|service unavailable|gateway time-?out|internal server error|incompleteread|chunkedencodingerror"
+ r"|remoteprotocolerror|server disconnected|peer closed connection",
+ re.IGNORECASE,
+)
+PERMANENT_FAILURE = re.compile(
+ r"\b40[134] (client error|forbidden|not found|unauthorized)|returned error: 40[134]|http error 40[134]"
+ r"|client error '40[134]|repositorynotfounderror|gatedrepoerror|revisionnotfounderror|entrynotfounderror"
+ r"|not our ref|couldn't find remote ref|authentication failed|repository not found|no module named",
+ re.IGNORECASE,
+)
+
+
+def retry_after(value: str | None) -> float | None:
+ """A Retry-After header (seconds or an HTTP date) in seconds, at most ``RETRY_AFTER_MAX``."""
+ if not value:
+ return None
+ value = value.strip()
+ if value.isdigit():
+ seconds = float(value)
+ else:
+ try:
+ when = email.utils.parsedate_to_datetime(value)
+ except (TypeError, ValueError):
+ return None
+ if when.tzinfo is None:
+ when = when.replace(tzinfo=UTC)
+ seconds = (when - datetime.now(UTC)).total_seconds()
+ return min(max(seconds, 0.0), RETRY_AFTER_MAX)
+
+
+def retry_wait(error: BaseException, 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 = retry_after(error.headers.get("Retry-After") if error.headers else None)
+ return RETRY_WAITS[attempt] if after is None else after
+ if isinstance(error, ssl.SSLCertVerificationError) or (
+ isinstance(error, urllib.error.URLError) and isinstance(error.reason, ssl.SSLCertVerificationError)
+ ):
+ return None
+ if isinstance(
+ error, (urllib.error.URLError, http.client.HTTPException, ConnectionError, TimeoutError, ssl.SSLError)
+ ):
+ return RETRY_WAITS[attempt]
+ return None
+
+
+def with_retries[T](label: str, action: Callable[[], T]) -> T:
+ """``action`` again after a temporary network failure, up to ``len(RETRY_WAITS)`` more times."""
+ attempt = 0
+ while True:
+ try:
+ return action()
+ except NETWORK_ERRORS as error:
+ wait = retry_wait(error, attempt) if attempt < len(RETRY_WAITS) else None
+ if wait is None:
+ raise
+ attempt += 1
+ say(f"{label}: {error}; trying again in {wait:.0f} s (attempt {attempt + 1} of {len(RETRY_WAITS) + 1})...")
+ time.sleep(wait)
+
+
+def check_complete(response: http.client.HTTPResponse, received: int) -> None:
+ """A body cut short is an error: urllib returns it as if it were complete."""
+ expected = int(response.headers.get("Content-Length") or 0)
+ if expected and received < expected:
+ raise http.client.IncompleteRead(b"", expected - received)
+
+
+def network_failure(output: str) -> bool:
+ """Whether a download command's output ends in an error that trying again can fix."""
+ return not PERMANENT_FAILURE.search(output) and bool(NETWORK_FAILURE.search(output))
+
+
def hf_bytes(repo: str, target: Path, files: Sequence[str] = (), revision: str = "main") -> int | None:
"""What a Hugging Face download still has to fetch into ``target`` (``files`` empty: the whole repo); ``None``
when the Hub cannot be asked."""
endpoint = os.environ.get("HF_ENDPOINT", "https://huggingface.co").rstrip("/")
url = f"{endpoint}/api/models/{repo}/tree/{urllib.parse.quote(revision, safe='')}?recursive=true"
- try:
+
+ def ask() -> object:
with urllib.request.urlopen(url, timeout=15) as response:
- listing = json.load(response)
- except (OSError, ValueError):
+ return json.load(response)
+
+ try:
+ listing = with_retries(f"Size of {repo}", ask)
+ except (*NETWORK_ERRORS, ValueError):
+ return None
+ if not isinstance(listing, list):
return None
sizes = {
e["path"]: int((e.get("lfs") or {}).get("size") or e.get("size") or 0)
@@ -530,10 +628,13 @@ def hf_bytes(repo: str, target: Path, files: Sequence[str] = (), revision: str =
def url_bytes(url: str) -> int | None:
- try:
+ def ask() -> int | None:
with urllib.request.urlopen(urllib.request.Request(url, method="HEAD"), timeout=15) as response:
return int(response.headers.get("Content-Length") or 0) or None
- except (OSError, ValueError):
+
+ try:
+ return with_retries(f"Size of {url}", ask)
+ except (*NETWORK_ERRORS, ValueError):
return None
@@ -931,6 +1032,7 @@ class Setup:
for name in ("VIRTUAL_ENV", "UV_PROJECT_ENVIRONMENT", "PYTHONHOME", "PYTHONPATH"):
env.pop(name, None)
env.setdefault("UV_HTTP_TIMEOUT", UV_HTTP_TIMEOUT)
+ env.setdefault("UV_HTTP_RETRIES", UV_HTTP_RETRIES)
env.setdefault("UV_CONCURRENT_DOWNLOADS", "4") # moderate: big wheels and source builds can exhaust RAM
env.setdefault("UV_CONCURRENT_BUILDS", "2")
env.setdefault("UV_CONCURRENT_INSTALLS", "4")
@@ -956,15 +1058,67 @@ class Setup:
return env
def run(
- self, command: Sequence[object], cwd: Path | None = None, extra_env: Mapping[str, str] | None = None
+ self,
+ command: Sequence[object],
+ cwd: Path | None = None,
+ extra_env: Mapping[str, str] | None = None,
+ retry: str = "",
) -> int:
- """Returns the exit code (127: program not found)."""
+ """Returns the exit code (127: program not found). With ``retry`` (the step's name) a download command runs
+ again after a failure its output shows to be a temporary network error."""
argv = [str(part) for part in command]
+ if retry:
+ return self._run_retried(argv, cwd, extra_env, retry)
try:
return subprocess.run(argv, cwd=cwd or self.root, env=self.env(extra_env), check=False).returncode
except OSError:
return 127
+ def _run_retried(self, argv: list[str], cwd: Path | None, extra_env: Mapping[str, str] | None, label: str) -> int:
+ attempt = 0
+ while True:
+ code, output = self._run_teed(argv, cwd, extra_env)
+ if code in (0, 127) or attempt == len(RETRY_WAITS) or not network_failure(output):
+ return code
+ wait = RETRY_WAITS[attempt]
+ attempt += 1
+ say(
+ f"{label}: a network error (exit {code}); trying again in {wait:.0f} s "
+ f"(attempt {attempt + 1} of {len(RETRY_WAITS) + 1})..."
+ )
+ time.sleep(wait)
+
+ def _run_teed(self, argv: list[str], cwd: Path | None, extra_env: Mapping[str, str] | None) -> tuple[int, str]:
+ """The exit code and the end of the output, which is still shown as it comes."""
+ try:
+ proc = subprocess.Popen(
+ argv, cwd=cwd or self.root, env=self.env(extra_env), stdout=subprocess.PIPE, stderr=subprocess.PIPE
+ )
+ except OSError:
+ return 127, ""
+ tail = bytearray()
+ lock = threading.Lock()
+
+ def pump(source: io.BufferedReader, sink: io.TextIOBase) -> None:
+ for chunk in iter(lambda: source.read1(1 << 16), b""):
+ sink.buffer.write(chunk)
+ sink.buffer.flush()
+ with lock:
+ tail.extend(chunk)
+ del tail[: max(len(tail) - (1 << 15), 0)]
+
+ sys.stdout.flush()
+ sys.stderr.flush()
+ pumps = [
+ threading.Thread(target=pump, args=(proc.stdout, sys.stdout), daemon=True),
+ threading.Thread(target=pump, args=(proc.stderr, sys.stderr), daemon=True),
+ ]
+ for thread in pumps:
+ thread.start()
+ for thread in pumps:
+ thread.join()
+ return proc.wait(), tail.decode("utf-8", "replace")
+
def quiet(self, command: Sequence[object], cwd: Path | None = None) -> int:
try:
return subprocess.run(
@@ -979,9 +1133,14 @@ class Setup:
return 127
def must(
- self, command: Sequence[object], what: str, cwd: Path | None = None, extra_env: Mapping[str, str] | None = None
+ self,
+ command: Sequence[object],
+ what: str,
+ cwd: Path | None = None,
+ extra_env: Mapping[str, str] | None = None,
+ retry: bool = False,
) -> None:
- code = self.run(command, cwd, extra_env)
+ code = self.run(command, cwd, extra_env, retry=what) if retry else self.run(command, cwd, extra_env)
if code != 0:
raise SetupError(f"{what} failed (exit {code}); the output above says why.")
@@ -1520,10 +1679,18 @@ class Setup:
@staticmethod
def _download(url: str, target: Path) -> None:
- try:
+ def attempt() -> None:
with urllib.request.urlopen(url, timeout=120) as response, target.open("wb") as handle:
- shutil.copyfileobj(response, handle)
- except OSError as error:
+ received = 0
+ for block in iter(lambda: response.read(1 << 20), b""):
+ handle.write(block)
+ received += len(block)
+ check_complete(response, received)
+
+ try:
+ with_retries(f"Downloading {url}", attempt)
+ except NETWORK_ERRORS as error:
+ target.unlink(missing_ok=True)
raise SetupError(f"Downloading {url} failed: {error}") from error
def ensure_repo(self, name: str, url: str, commit: str, dest: Path) -> None:
@@ -1546,9 +1713,12 @@ class Setup:
if not (dest / ".git").exists():
self.must(self.git("init", "--quiet", dest), f"git init for {name}")
self.must(self.git("remote", "add", "origin", url), f"git remote for {name}", cwd=dest)
- if self.run(self.git("fetch", "--quiet", "--depth", "1", "origin", commit), dest) != 0:
+ if (
+ self.run(self.git("fetch", "--quiet", "--depth", "1", "origin", commit), dest, retry=f"Fetching {name}")
+ != 0
+ ):
say(f"{name}: shallow fetch of the commit failed, fetching the full history...")
- self.must(self.git("fetch", "--quiet", "origin"), f"Fetching {name}", cwd=dest)
+ self.must(self.git("fetch", "--quiet", "origin"), f"Fetching {name}", cwd=dest, retry=True)
self.must(self.git("checkout", "--quiet", "--force", commit), f"Checking out {name}", cwd=dest)
say(f"{name}: checked out {commit[:9]}.")
@@ -1875,6 +2045,7 @@ class Setup:
code = self.run(
[py, "-I", "-m", "huggingface_hub.cli.hf", "download", NLLB_REPO, *NLLB_FILES, "--local-dir", nllb],
cwd=self.runtime,
+ retry=f"Downloading {NLLB_REPO}",
)
if code != 0:
script = (
@@ -1885,6 +2056,7 @@ class Setup:
[py, "-I", "-c", script, NLLB_REPO, nllb, *NLLB_FILES],
"Downloading the translation model",
cwd=self.runtime,
+ retry=True,
)
if not self._has(nllb, NLLB_REQUIRED):
raise SetupError("The translation model download finished but files are missing; run this again.")
@@ -1917,6 +2089,7 @@ class Setup:
code = self.run(
[py, "-I", "-m", "huggingface_hub.cli.hf", "download", NLLB_BIG_REPO, *NLLB_FILES, "--local-dir", target],
cwd=self.runtime,
+ retry=f"Downloading {NLLB_BIG_REPO}",
)
if code != 0:
script = (
@@ -1927,6 +2100,7 @@ class Setup:
[py, "-I", "-c", script, NLLB_BIG_REPO, target, *NLLB_FILES],
"Downloading the better translation model",
cwd=self.runtime,
+ retry=True,
)
if not self._has(
target, ("config.json", "pytorch_model.bin", "sentencepiece.bpe.model", "tokenizer_config.json")
@@ -2084,6 +2258,7 @@ class Setup:
],
cwd=self.runtime,
extra_env={"HF_HUB_DISABLE_XET": "1"},
+ retry=f"Downloading {repo}",
)
if code != 0:
script = (
@@ -2096,6 +2271,7 @@ class Setup:
f"Downloading {repo} for the zero-shot voice converter",
cwd=self.runtime,
extra_env={"HF_HUB_DISABLE_XET": "1"},
+ retry=True,
)
if not self._has(target, files):
raise SetupError(f"The {repo} download finished but files are missing; run this again.")
@@ -2173,7 +2349,7 @@ class Setup:
"ok = [nltk.download(name, download_dir=sys.argv[1], quiet=True) for name in sys.argv[2:]]\n"
"sys.exit(0 if all(ok) else 1)"
)
- if self.run([py, "-I", "-c", script, target, *missing], cwd=self.runtime) != 0:
+ if self.run([py, "-I", "-c", script, target, *missing], cwd=self.runtime, retry="NLTK's data") != 0:
warn(
"NLTK's data could not be downloaded (the next setup run tries again); until then the recording-text "
"analysis uses NLTK data found elsewhere or a simpler method."
@@ -2271,6 +2447,7 @@ class Setup:
f"Downloading {spec['repo']}",
cwd=self.runtime,
extra_env={"HF_HUB_DISABLE_XET": "1"},
+ retry=True,
)
if not self._has(target, spec["required"]):
raise SetupError(f"The {spec['repo']} download finished but files are missing; run this again.")
@@ -2320,6 +2497,7 @@ class Setup:
],
cwd=self.runtime,
extra_env={"HF_HUB_DISABLE_XET": "1"},
+ retry=f"Downloading {HOLOS_REPO}",
)
if code != 0:
script = (
@@ -2332,6 +2510,7 @@ class Setup:
f"Downloading {HOLOS_REPO}",
cwd=self.runtime,
extra_env={"HF_HUB_DISABLE_XET": "1"},
+ retry=True,
)
if not self._has(target, HOLOS_FILES):
raise SetupError("The HolosTTS download finished but files are missing; run this again.")
@@ -2344,6 +2523,7 @@ class Setup:
[py, "-I", "-c", script, stanza_dir, HOLOS_STANZA_PROCESSORS],
"Downloading Stanza's Ukrainian models",
cwd=self.runtime,
+ retry=True,
)
if not (stanza_dir / "resources.json").is_file() or not (stanza_dir / "uk" / "pos").is_dir():
raise SetupError("Stanza's Ukrainian models are incomplete; run this again.")
@@ -2365,6 +2545,7 @@ class Setup:
[py, "-I", "-m", "huggingface_hub.cli.hf", "download", OMNIVOICE_REPO, "--local-dir", target],
cwd=self.runtime,
extra_env={"HF_HUB_DISABLE_XET": "1"},
+ retry=f"Downloading {OMNIVOICE_REPO}",
)
if code != 0:
script = (
@@ -2376,6 +2557,7 @@ class Setup:
"Downloading the OmniVoice model",
cwd=self.runtime,
extra_env={"HF_HUB_DISABLE_XET": "1"},
+ retry=True,
)
if not self._has(target, OMNIVOICE_REQUIRED):
raise SetupError("The OmniVoice download finished but files are missing; run this again.")
@@ -2394,6 +2576,7 @@ class Setup:
[self.rvc_python(), "core.py", "prerequisites", "--pretraineds-hifigan", "--models", "--exe"],
"Downloading the Applio prerequisites",
cwd=self.applio,
+ retry=True,
)
if not self._has(self.applio, self.applio_required()):
raise SetupError("The Applio prerequisites finished but files are missing; run this again.")
@@ -2680,13 +2863,12 @@ def fetch_checked(url: str, target: Path, sha256: str, label: str) -> None:
rename."""
target.parent.mkdir(parents=True, exist_ok=True)
part = target.with_name(target.name + ".part")
- have = part.stat().st_size if part.is_file() else 0
- request = urllib.request.Request(url, headers={"Range": f"bytes={have}-"} if have else {})
- try:
- with urllib.request.urlopen(request, timeout=120) as response:
- if response.status == 416: # the .part is already complete
- pass
- else:
+
+ def attempt() -> None:
+ have = part.stat().st_size if part.is_file() else 0
+ request = urllib.request.Request(url, headers={"Range": f"bytes={have}-"} if have else {})
+ try:
+ with urllib.request.urlopen(request, timeout=120) as response:
resumed = have > 0 and response.status == 206
done = have if resumed else 0
total = done + int(response.headers.get("Content-Length") or 0)
@@ -2699,10 +2881,14 @@ def fetch_checked(url: str, target: Path, sha256: str, label: str) -> None:
if total and next_note <= done < total:
say(f" {100 * done // total}% of {total / 1e9:.1f} GB")
next_note = (done // step + 1) * step
- except urllib.error.HTTPError as error:
- if error.code != 416:
- raise SetupError(f"Downloading {label} failed ({error}); run setup again to resume.") from error
- except OSError as error:
+ check_complete(response, done - (have if resumed else 0))
+ except urllib.error.HTTPError as error:
+ if error.code != 416: # 416: the .part is already complete
+ raise
+
+ try:
+ with_retries(f"Downloading {label}", attempt)
+ except NETWORK_ERRORS as error:
raise SetupError(f"Downloading {label} failed ({error}); run setup again to resume.") from error
digest = hashlib.sha256()
with part.open("rb") as handle:
@@ -2729,29 +2915,32 @@ def fetch_demucs(models_dir: Path) -> Path:
folder.mkdir(parents=True, exist_ok=True)
target = folder / DEMUCS_FILE
part = folder / (DEMUCS_FILE + ".part")
- have = part.stat().st_size if part.is_file() else 0
- if have > DEMUCS_SIZE:
+ if part.is_file() and part.stat().st_size > DEMUCS_SIZE:
part.unlink()
- have = 0
- if have < DEMUCS_SIZE:
+
+ def attempt() -> None:
+ have = part.stat().st_size if part.is_file() else 0
+ if have >= DEMUCS_SIZE:
+ return
request = urllib.request.Request(DEMUCS_URL, headers={"Range": f"bytes={have}-"} if have else {})
- try:
- with urllib.request.urlopen(request, timeout=120) as response:
- resumed = have > 0 and response.status == 206
- done = have if resumed else 0
- step = DEMUCS_SIZE // 10
- next_note = (done // step + 1) * step
- with part.open("ab" if resumed else "wb") as handle:
- for block in iter(lambda: response.read(1 << 20), b""):
- handle.write(block)
- done += len(block)
- if done >= next_note and done < DEMUCS_SIZE:
- say(f" {100 * done // DEMUCS_SIZE}% of {DEMUCS_SIZE / 1e6:.0f} MB")
- next_note = (done // step + 1) * step
- except OSError as error:
- raise SetupError(
- f"Downloading the music-removal model failed ({error}); run setup again to resume."
- ) from error
+ with urllib.request.urlopen(request, timeout=120) as response:
+ resumed = have > 0 and response.status == 206
+ done = have if resumed else 0
+ step = DEMUCS_SIZE // 10
+ next_note = (done // step + 1) * step
+ with part.open("ab" if resumed else "wb") as handle:
+ for block in iter(lambda: response.read(1 << 20), b""):
+ handle.write(block)
+ done += len(block)
+ if done >= next_note and done < DEMUCS_SIZE:
+ say(f" {100 * done // DEMUCS_SIZE}% of {DEMUCS_SIZE / 1e6:.0f} MB")
+ next_note = (done // step + 1) * step
+ check_complete(response, done - (have if resumed else 0))
+
+ try:
+ with_retries("Downloading the music-removal model", attempt)
+ except NETWORK_ERRORS as error:
+ raise SetupError(f"Downloading the music-removal model failed ({error}); run setup again to resume.") from error
digest = hashlib.sha256()
with part.open("rb") as handle:
for block in iter(lambda: handle.read(1 << 20), b""):