* refactor(launchpad): quieter, borderless design refresh The launchpad carried decoration from an earlier direction: icon chips, corner-hung count badges, a permanently visible filled arrow, uppercase mono card titles, and a dotted stipple divider — plus a frame that had been invisible since the app-wide border tokens were zeroed. Rework it around what the borderless direction actually implies: - Feature tiles get a whisper-faint surface instead of a dead frame, and read as three bands (bare glyph + count / title + arrow / description). `--card-hue` is spent sparingly — the glyph at rest, the surface, count and arrow only once raised. Titles move to sans sentence case; counts are plain tabular numerals. Lift softened 4px -> 2px, coloured glow -> neutral shadow, plus an explicit focus ring and a staggered entrance. - Hero drops the boxed "646" pill and the filled A/B-Compare button for quiet type, with a hairline standing in for the separation. - Section labels trade the dotted stipple for a single fading hairline; rows are transparent until hover and reveal "Open" on hover/focus (it stays in the DOM, so AT and keyboard always reach it). - Hero, tiles, recent files, callout and project lists now share one 1180px column — previously only the top half was capped, so lists ran edge-to-edge on a wide display while the deck stayed centred. Two bugs found and fixed while doing it: - Buttons that had `border border-solid border-transparent` removed fell back to the UA default border and rendered a visible 1px outline. They now carry `border-0` explicitly. - `.lp-animate` used `animation-fill-mode: both`, so after the entrance it kept owning `transform` — and animation-origin declarations outrank normal ones, which silently killed the card hover lift. Now `backwards`, which still holds the from-state through the stagger delay. Also drops CSS the page has not rendered since #904: the cursor-spotlight layer, the breath ring, and the per-card waveform strip. Verified with headless renders at 1600/1280/940 and the empty state. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(dictation): decode Wayland portal signals and show the capture pill The GlobalShortcuts portal declares Activated/Deactivated as (o session, s shortcut_id, t timestamp, a{sv} options). We decoded the timestamp as u32, so zbus rejected every signal with Signature mismatch: got `(osta{sv})`, expected `(osua{sv})` and the press was dropped as an invalid signal. Registration succeeded and the desktop even reported the bound chord back, so the hotkey looked wired up while doing nothing at all — on every Wayland compositor, for the whole life of the feature (#1490). Decode the 64-bit timestamp, and keep the 32-bit spelling as a fallback so a non-conforming portal degrades to working rather than to silence. With presses arriving, the second half of the failure showed: nothing had shown the widget window since it became a hidden recorder host, so a capture ran with no pill on screen — and a mic or Accessibility failure rendered into a window nobody could see. Add show_dictation_pill, which bottom-centres the capsule on the monitor under the pointer and shows it without taking focus (Windows keeps SW_SHOWNOACTIVATE so paste still lands in the user's document), and call it from the widget for every state but idle. Wayland denies clients their own placement, so the compositor picks the spot there; the pill still appears. dispatch_dictation_capture now logs whether a press was emitted or queued — a press that reaches Rust and produces nothing was otherwise indistinguishable from one the compositor never delivered. Tests: portal signals decode at both timestamp widths (the 64-bit case fails before this change with the exact production error); pill placement centres, respects a second monitor's origin, and clamps rather than going off-screen; the widget shows for a state needing the user, stays hidden while idle, and never shows for a press that arrives while dictation is disabled. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore: sync in-progress workspace changes Uncommitted work already in the tree, checkpointed so the branch matches the local machine: - Remote GPU workers: join-from-the-app flow, one-time secrets, QR join codes, a Compute control in the status bar, and the device-list Workers panel (#1516) - Model Catalogue workspace, with Settings pointing at it - Settings sidebar search and keyboard navigation - Demo assets for dubbing, dictation and voice design, plus the scripts that render them - Backend: validation-error handling, ASR request-path degradation, and the accompanying tests - CHANGELOG entries for the above and for the Wayland dictation fix Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(tests): follow Engines to the Model Catalogue, and green the sweep - test_supertonic3 asserted the license gate points at "Settings" while the engine now names Model Catalogue → Engines, which is where the accept button actually lives. The assertion follows the move; what it pins is unchanged — the hint must name a place the user can reach it. - Carries the CJK allowlist entries for the rendered dub bundle (#1517) and the regenerated route snapshot for /workers/agent (#1516), both of which this branch inherits from the workspace sync. - docs/install/linux.md: the dictation capsule is bottom-anchored everywhere except Wayland, where the protocol gives applications no say in their placement. Documented rather than left as a surprise (CodeRabbit). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * ci: stop a flaky dependency fetch from failing green runs en-core-web-sm resolves to a direct GitHub release URL, and github.com intermittently answers `http2 error: refused stream before processing any application logic`. uv's own three retries all land within the same few seconds and fail together, so the whole job dies on a dependency that has nothing to do with the change under test — it cost #1518 and #1517 an otherwise-green run tonight. Two changes: back off between whole `uv sync` attempts, which is what actually clears it, and pass --no-sync to the pytest steps. `uv run` re-resolves the environment before running, so every test step was a fresh chance to hit the same fetch even though the install step had already synced — that is exactly how #1518 failed, in the isolated backend/tests step, with all 5467 tests already passed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * ci: one retry seam for every uv sync, not just the job that failed last en-core-web-sm resolves to a direct GitHub *release* URL rather than a package index, and github.com intermittently answers `http2 error: refused stream before processing any application logic`. uv's own retries all land inside the same ~10 seconds and fail together, so a job dies on a dependency unrelated to the change under test. Tonight that cost four otherwise-green runs across #1515, #1517 and #1518 — and the first fix only covered the Tests job, so the next failure simply moved to Smoke (Linux), which syncs separately. The fetch is per-job, so the fix has to be per-job: scripts/uv-sync-retry.sh backs off between whole attempts (15s, 45s, 90s) and every workflow that syncs now goes through it — ci.yml (tests + the platform matrix), release.yml, security.yml, evals.yml. It still fails loudly after four attempts, so a genuinely broken lockfile is not disguised as a flake. The Tests job also lacked the UV_HTTP_TIMEOUT / UV_HTTP_RETRIES the smoke matrix has always set, which is part of why it was the one that kept dying; it has them now. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test(ci): pin the Intel-Mac contract by intent, not by command spelling test_ci_verifies_intel_mac_as_the_documented_remote_only_host asserted the literal line `run: uv sync --extra pockettts`, so routing every sync through scripts/uv-sync-retry.sh read as a broken Intel-Mac contract. The contract it exists to protect is that the pockettts extra installs ONLY on backend_supported legs — which the regex now pins, while leaving how the sync is invoked free to change. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * ci: keep every uv run out of the resolver, and bound the retry budget CodeRabbit, #1517: - `uv run` re-resolves before running, so the smoke suite, the worker-artifact tests, the release test run and the eval run were each a fresh chance to hit the flaky direct-URL fetch outside the retry loop. All of them pass --no-sync now; the environment is already synced by the step that owns the retries. security.yml's `uv run --with pip-audit` is deliberately left alone — it layers an ephemeral package rather than running the project's own tests. - The retry count multiplied uv's own budget (UV_HTTP_RETRIES=5 with a 120 s timeout on the smoke matrix). Three attempts and 60 s of total backoff outlast the refusals actually observed while staying well inside the jobs' timeout-minutes. - The Intel-Mac contract test pinned the smoke command literally too, so --no-sync tripped it exactly like the sync line did. Same fix: assert the contract (smoke runs only on backend_supported legs), not its spelling. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
568 lines
23 KiB
Python
568 lines
23 KiB
Python
"""First-run wizard endpoints — status, preflight, and warmup.
|
||
|
||
Extracted from the monolithic ``setup.py``.
|
||
|
||
- ``GET /setup/status`` — missing-model gate for boot screen
|
||
- ``GET /setup/preflight`` — system health check (OS, RAM, disk, GPU, network —
|
||
genuine user facts only; the media engine (ffmpeg/ffprobe/yt-dlp) is an
|
||
internal concern that self-heals via ``services.media_tools``)
|
||
- ``POST /setup/warmup`` — background model pre-load
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import logging
|
||
import os
|
||
import platform as _platform
|
||
import sys
|
||
|
||
from fastapi import APIRouter
|
||
|
||
from api.schemas import SetupStatusResponse, PreflightResponse
|
||
# MIN_FREE_GB + disk_free_bytes are single-sourced in ``.models`` (the lowest
|
||
# module in the setup import graph) so the wizard gate, the /models header, and
|
||
# the per-install disk guard can't drift apart.
|
||
from .models import REQUIRED_MODELS, hf_cache_dir, is_cached, MIN_FREE_GB, disk_free_bytes
|
||
|
||
logger = logging.getLogger("omnivoice.setup.wizard")
|
||
router = APIRouter()
|
||
|
||
|
||
def _disk_free_gb(path: str) -> float:
|
||
"""Free GB on the volume containing *path* (thin GB wrapper over the shared
|
||
``models.disk_free_bytes``, which walks up to the nearest existing ancestor
|
||
for a not-yet-created path)."""
|
||
return disk_free_bytes(path) / (1024 ** 3)
|
||
|
||
|
||
# ── Setup Status ───────────────────────────────────────────────────────────
|
||
|
||
@router.get("/setup/status", response_model=SetupStatusResponse)
|
||
def setup_status():
|
||
"""Snapshot the setup state so the client can pick its boot screen."""
|
||
missing = [
|
||
{"repo_id": rid, "label": label}
|
||
for (rid, label) in REQUIRED_MODELS
|
||
if not is_cached(rid)
|
||
]
|
||
cache = hf_cache_dir()
|
||
free_gb = _disk_free_gb(cache)
|
||
return {
|
||
"models_ready": len(missing) == 0,
|
||
"missing": missing,
|
||
"hf_cache_dir": cache,
|
||
"disk_free_gb": round(free_gb, 2),
|
||
"min_free_gb": MIN_FREE_GB,
|
||
"enough_disk": free_gb >= MIN_FREE_GB,
|
||
}
|
||
|
||
|
||
# ── Pre-flight System Check ───────────────────────────────────────────────
|
||
|
||
_MIN_NVIDIA_DRIVER = 555
|
||
_RAM_FAIL_GB = 8
|
||
_RAM_WARN_GB = 12
|
||
|
||
|
||
def _run_cmd(args: list[str], timeout: float = 2.0) -> tuple[int, str]:
|
||
"""Run a subprocess synchronously with a short timeout."""
|
||
import subprocess
|
||
try:
|
||
out = subprocess.run(
|
||
args, capture_output=True, text=True, timeout=timeout, check=False,
|
||
)
|
||
return out.returncode, out.stdout
|
||
except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
|
||
return -1, ""
|
||
|
||
|
||
def _detect_gpu() -> dict:
|
||
"""Best-effort detection of GPU vendor + driver + compute backend."""
|
||
info = {
|
||
"vendor": "none", "driver": None, "device_name": None,
|
||
"backend": "cpu", "available": False, "notes": [],
|
||
}
|
||
|
||
# Apple Silicon → MPS
|
||
if sys.platform == "darwin" and _platform.machine() == "arm64":
|
||
info["vendor"] = "apple"
|
||
info["backend"] = "mps"
|
||
info["device_name"] = "Apple Silicon GPU (Metal)"
|
||
try:
|
||
import torch
|
||
info["available"] = bool(torch.backends.mps.is_available())
|
||
except Exception:
|
||
info["available"] = False
|
||
return info
|
||
|
||
# NVIDIA
|
||
rc, out = _run_cmd([
|
||
"nvidia-smi",
|
||
"--query-gpu=driver_version,name",
|
||
"--format=csv,noheader",
|
||
])
|
||
if rc == 0 and out.strip():
|
||
line = out.strip().splitlines()[0]
|
||
parts = [p.strip() for p in line.split(",")]
|
||
driver = parts[0] if parts else None
|
||
name = parts[1] if len(parts) > 1 else None
|
||
info.update({"vendor": "nvidia", "driver": driver, "device_name": name})
|
||
try:
|
||
import torch
|
||
info["available"] = bool(torch.cuda.is_available())
|
||
info["backend"] = "cuda" if info["available"] else "cpu"
|
||
except Exception:
|
||
pass
|
||
try:
|
||
major = int((driver or "0").split(".")[0])
|
||
if major < _MIN_NVIDIA_DRIVER:
|
||
info["notes"].append(
|
||
f"NVIDIA driver {driver} below {_MIN_NVIDIA_DRIVER} required "
|
||
f"by the bundled CUDA 12.8 runtime — GPU will fail to launch "
|
||
f"kernels. Update drivers before dubbing."
|
||
)
|
||
info["available"] = False
|
||
except Exception:
|
||
pass
|
||
return info
|
||
|
||
# AMD
|
||
rc, out = _run_cmd(["rocm-smi", "--showproductname"])
|
||
if rc == 0 and out.strip():
|
||
info["vendor"] = "amd"
|
||
info["device_name"] = out.strip().splitlines()[0][:120]
|
||
try:
|
||
import torch
|
||
has_hip = getattr(torch.version, "hip", None) is not None
|
||
if has_hip and torch.cuda.is_available():
|
||
info["backend"] = "rocm"
|
||
info["available"] = True
|
||
else:
|
||
info["backend"] = "cpu"
|
||
info["notes"].append(
|
||
"AMD GPU detected but torch was installed with CUDA wheels. "
|
||
"Re-run `uv sync --index-url https://download.pytorch.org/whl/rocm6.1` "
|
||
"to enable ROCm acceleration."
|
||
)
|
||
except Exception:
|
||
info["notes"].append("AMD GPU detected but torch not importable.")
|
||
return info
|
||
|
||
# Fallback — no nvidia-smi/rocm-smi but torch might still see CUDA
|
||
# (common inside Docker containers with the NVIDIA runtime).
|
||
try:
|
||
import torch
|
||
if torch.cuda.is_available():
|
||
info["vendor"] = "unknown"
|
||
info["backend"] = "cuda"
|
||
info["available"] = True
|
||
try:
|
||
info["device_name"] = torch.cuda.get_device_name(0)
|
||
except Exception:
|
||
pass
|
||
info["notes"].append(
|
||
"torch.cuda.is_available() is True but no nvidia-smi/rocm-smi "
|
||
"found — running through WSL or virtual GPU?"
|
||
)
|
||
except Exception:
|
||
pass
|
||
return info
|
||
|
||
|
||
def _probe_network(host: str = "huggingface.co", port: int = 443, timeout: float = 2.0) -> bool:
|
||
"""Tiny TCP connect test."""
|
||
import socket
|
||
try:
|
||
with socket.create_connection((host, port), timeout=timeout):
|
||
return True
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
def _hf_endpoint_host() -> tuple[str, int]:
|
||
"""Host/port of the Hugging Face endpoint actually in effect.
|
||
|
||
Mirror-aware: restricted-network users (e.g. behind the Great Firewall)
|
||
point HF_ENDPOINT at a mirror via Model Catalogue → Models → Hugging Face
|
||
mirror. Probing hardcoded huggingface.co would fail them even when their
|
||
configured mirror works fine.
|
||
"""
|
||
try:
|
||
from core.failure import configured_hf_mirror
|
||
mirror = configured_hf_mirror()
|
||
except Exception:
|
||
logger.warning("Configured Hugging Face endpoint could not be read")
|
||
return "", 0
|
||
if mirror:
|
||
try:
|
||
from urllib.parse import urlsplit
|
||
u = urlsplit(mirror)
|
||
if u.hostname:
|
||
return u.hostname, u.port or (80 if u.scheme == "http" else 443)
|
||
except Exception:
|
||
logger.warning("Configured Hugging Face endpoint could not be parsed")
|
||
return "", 0
|
||
logger.warning("Configured Hugging Face endpoint has no host")
|
||
return "", 0
|
||
return "huggingface.co", 443
|
||
|
||
|
||
def _network_check() -> dict:
|
||
"""The preflight "network" check row — auto-race or explicit-endpoint probe.
|
||
|
||
Auto mode (nothing explicitly configured): force a fresh endpoint race —
|
||
preflight IS the connectivity health check, and the cached winner is what
|
||
model downloads will use. Manual mode: probe exactly the configured
|
||
endpoint (never auto-switch an explicit choice), keeping the mirror
|
||
quick-pick affordance when the official endpoint is blocked.
|
||
"""
|
||
auto_decision = None
|
||
try:
|
||
from services import endpoint_race
|
||
if endpoint_race.mode() == "auto":
|
||
auto_decision = endpoint_race.ensure_decision(force=True)
|
||
except Exception as exc: # the race must never break preflight
|
||
logger.warning("preflight endpoint race failed: %s", exc)
|
||
|
||
if auto_decision is not None:
|
||
from urllib.parse import urlsplit
|
||
from services.endpoint_race import CANONICAL_ENDPOINT
|
||
|
||
picked = auto_decision["endpoint"]
|
||
picked_host = urlsplit(picked).hostname or picked
|
||
latency = auto_decision.get("latency_ms")
|
||
latency_s = f" ({latency:.0f} ms)" if isinstance(latency, (int, float)) else ""
|
||
results = {r["endpoint"]: r for r in auto_decision.get("results", [])}
|
||
canonical_ok = bool(results.get(CANONICAL_ENDPOINT, {}).get("reachable"))
|
||
mirror_reachable = any(
|
||
r.get("reachable") for ep, r in results.items() if ep != CANONICAL_ENDPOINT
|
||
)
|
||
if auto_decision.get("reachable"):
|
||
if picked == CANONICAL_ENDPOINT:
|
||
detail = f"Reachable{latency_s}"
|
||
elif not canonical_ok:
|
||
detail = (
|
||
f"huggingface.co is unreachable on this network — using the "
|
||
f"community mirror {picked_host}{latency_s} for model "
|
||
"downloads. Downloads are checksum-verified by Hugging Face "
|
||
"regardless of endpoint; change anytime in Settings → "
|
||
"Models → Hugging Face mirror."
|
||
)
|
||
else:
|
||
detail = (
|
||
f"Both endpoints reachable — {picked_host}{latency_s} "
|
||
"selected (decisively faster here). Change anytime in "
|
||
"Settings → Models → Hugging Face mirror."
|
||
)
|
||
status, fix = "pass", None
|
||
else:
|
||
status = "warn"
|
||
detail = "No Hugging Face endpoint reachable"
|
||
fix = (
|
||
"Neither huggingface.co nor the hf-mirror.com community mirror "
|
||
"responded — check internet connection, VPN, or firewall. You "
|
||
"can continue — models already downloaded keep working "
|
||
"offline; a custom mirror can be configured below."
|
||
)
|
||
return {
|
||
"id": "network", "label": f"Network ({picked_host})",
|
||
"status": status, "detail": detail, "fix": fix,
|
||
# Frontend affordance hint: the wizard offers the mirror
|
||
# quick-pick when the check didn't pass (PreflightCheck allows
|
||
# extras). `endpoint` documents the auto pick for the UI.
|
||
"mirror_reachable": mirror_reachable,
|
||
"endpoint": picked,
|
||
}
|
||
|
||
# Manual mode (explicit endpoint) — probe exactly what the user chose.
|
||
net_host, net_port = _hf_endpoint_host()
|
||
if not net_host:
|
||
return {
|
||
"id": "network", "label": "Network (configured endpoint)",
|
||
"status": "warn",
|
||
"detail": "The configured Hugging Face endpoint could not be validated.",
|
||
"fix": "Review the endpoint in Model Catalogue → Models, then re-check.",
|
||
"mirror_reachable": False,
|
||
}
|
||
net_ok = _probe_network(net_host, net_port)
|
||
mirror_reachable = False
|
||
if not net_ok and net_host == "huggingface.co":
|
||
# Official endpoint blocked — if the community mirror is reachable,
|
||
# tell the user exactly which switch unblocks them.
|
||
mirror_reachable = _probe_network("hf-mirror.com")
|
||
if net_ok:
|
||
net_fix = None
|
||
elif mirror_reachable:
|
||
net_fix = (
|
||
"huggingface.co is blocked on this network, but the hf-mirror.com "
|
||
"community mirror is reachable — apply it below and re-check. "
|
||
"Model downloads will use the mirror immediately."
|
||
)
|
||
elif net_host != "huggingface.co":
|
||
net_fix = (
|
||
f"Your configured Hugging Face mirror ({net_host}) is unreachable "
|
||
"— it may be down or blocked. Pick another mirror or the official "
|
||
"endpoint below, or continue offline: models already downloaded "
|
||
"keep working."
|
||
)
|
||
else:
|
||
net_fix = (
|
||
"Check internet connection, VPN, or corporate firewall whitelist "
|
||
"for huggingface.co. You can continue — models already downloaded "
|
||
"keep working offline; new downloads need a connection or a "
|
||
"mirror (configurable below)."
|
||
)
|
||
return {
|
||
"id": "network", "label": f"Network ({net_host})",
|
||
"status": "pass" if net_ok else "warn",
|
||
"detail": "Reachable" if net_ok else f"Unreachable on port {net_port}",
|
||
"fix": net_fix,
|
||
# Frontend affordance hint: the wizard offers the mirror quick-pick
|
||
# when the endpoint is unreachable (PreflightCheck allows extras).
|
||
"mirror_reachable": mirror_reachable,
|
||
}
|
||
|
||
|
||
def _ram_gb() -> float:
|
||
try:
|
||
import psutil
|
||
return psutil.virtual_memory().total / (1024 ** 3)
|
||
except Exception:
|
||
return 0.0
|
||
|
||
|
||
@router.get("/setup/preflight", response_model=PreflightResponse)
|
||
def preflight():
|
||
"""One-shot system health check for the wizard."""
|
||
checks: list[dict] = []
|
||
|
||
# ── OS + arch
|
||
arch = _platform.machine()
|
||
os_ver = _platform.platform(terse=True)
|
||
checks.append({
|
||
"id": "os", "label": "Operating system", "status": "pass",
|
||
"detail": f"{os_ver} ({arch})", "fix": None,
|
||
})
|
||
|
||
# ── Python runtime
|
||
checks.append({
|
||
"id": "python", "label": "Python runtime", "status": "pass",
|
||
"detail": f"Python {sys.version.split()[0]}", "fix": None,
|
||
})
|
||
|
||
# ── RAM
|
||
ram = _ram_gb()
|
||
if ram == 0:
|
||
ram_status, ram_detail, ram_fix = (
|
||
"warn", "Could not detect system RAM.",
|
||
"Install psutil in the backend environment or ignore this warning.",
|
||
)
|
||
elif ram < _RAM_FAIL_GB:
|
||
ram_status, ram_detail, ram_fix = (
|
||
"fail", f"{ram:.1f} GB total (need ≥ {_RAM_FAIL_GB} GB)",
|
||
"The app will OOM on first dub. Close other apps or upgrade RAM.",
|
||
)
|
||
elif ram < _RAM_WARN_GB:
|
||
ram_status, ram_detail, ram_fix = (
|
||
"warn", f"{ram:.1f} GB total ({_RAM_WARN_GB}+ GB recommended)",
|
||
"Long videos may hit swap. Keep other apps closed during dubbing.",
|
||
)
|
||
else:
|
||
ram_status, ram_detail, ram_fix = ("pass", f"{ram:.1f} GB total", None)
|
||
checks.append({
|
||
"id": "ram", "label": "System RAM", "status": ram_status,
|
||
"detail": ram_detail, "fix": ram_fix,
|
||
})
|
||
|
||
# ── Disk free
|
||
cache = hf_cache_dir()
|
||
free = _disk_free_gb(cache)
|
||
if free < MIN_FREE_GB:
|
||
disk = {
|
||
"status": "fail",
|
||
"detail": f"{free:.1f} GB free at {cache} (need ≥ {MIN_FREE_GB} GB)",
|
||
"fix": f"Free up disk space or set HF_HOME to a larger partition.",
|
||
}
|
||
else:
|
||
disk = {"status": "pass", "detail": f"{free:.1f} GB free at {cache}", "fix": None}
|
||
checks.append({"id": "disk", **{"label": "Disk space", **disk}})
|
||
|
||
# ── HF cache writable
|
||
try:
|
||
os.makedirs(cache, exist_ok=True)
|
||
writable = os.access(cache, os.W_OK)
|
||
except Exception:
|
||
writable = False
|
||
checks.append({
|
||
"id": "hf_cache_writable", "label": "HuggingFace cache writable",
|
||
"status": "pass" if writable else "fail",
|
||
"detail": cache,
|
||
"fix": None if writable else
|
||
f"Fix write permissions on {cache} or point HF_HOME elsewhere.",
|
||
})
|
||
|
||
# ── Media engine (ffmpeg/ffprobe/yt-dlp) — deliberately NOT a check row.
|
||
# These are internal dependencies the app provisions for itself, not user
|
||
# facts: when the resolution chain has no tier at all, preflight kicks the
|
||
# bundled acquisition in the background and the wizard shows a quiet
|
||
# progress line (a failure card only if that fails — with Retry / use a
|
||
# system copy). yt-dlp is an importable locked module and never appears.
|
||
# Power users manage all three in Settings → Audio tools.
|
||
media_tools = None
|
||
try:
|
||
from services.media_tools import summary as _media_summary
|
||
media_tools = _media_summary(auto_acquire=True)
|
||
except Exception as exc: # never break preflight on the media engine
|
||
logger.warning("preflight media_tools summary failed: %s", exc)
|
||
|
||
# ── GPU
|
||
gpu = _detect_gpu()
|
||
if gpu["vendor"] == "apple" and gpu["available"]:
|
||
gpu_status, gpu_fix = "pass", None
|
||
gpu_detail = f"{gpu['device_name']} — Metal (MPS) ready"
|
||
elif gpu["vendor"] == "nvidia" and gpu["available"]:
|
||
gpu_status, gpu_fix = "pass", None
|
||
gpu_detail = f"{gpu['device_name']} (driver {gpu['driver']}) — CUDA ready"
|
||
elif gpu["vendor"] == "nvidia" and not gpu["available"]:
|
||
gpu_status = "fail"
|
||
gpu_detail = (
|
||
f"{gpu['device_name']} found but CUDA not usable "
|
||
f"(driver {gpu['driver']}). " + " ".join(gpu["notes"])
|
||
)
|
||
gpu_fix = (
|
||
f"Update NVIDIA drivers to ≥ R{_MIN_NVIDIA_DRIVER} "
|
||
"(https://www.nvidia.com/Download/index.aspx). Or run CPU-only "
|
||
"by continuing past this step — dubbing will be ~10× slower."
|
||
)
|
||
elif gpu["vendor"] == "amd":
|
||
gpu_status = "warn"
|
||
gpu_detail = (
|
||
f"{gpu['device_name']} — ROCm "
|
||
+ ("ready" if gpu["available"] else "not configured")
|
||
)
|
||
gpu_fix = (
|
||
None if gpu["available"] else
|
||
"AMD support is experimental. Re-run `uv sync --index-url "
|
||
"https://download.pytorch.org/whl/rocm6.1` to enable. App works "
|
||
"on CPU otherwise (slower)."
|
||
)
|
||
elif gpu["available"]:
|
||
# Fallback: torch.cuda works but nvidia-smi/rocm-smi absent (e.g. Docker)
|
||
gpu_status, gpu_fix = "pass", None
|
||
dev = gpu.get("device_name") or "GPU"
|
||
gpu_detail = f"{dev} — CUDA ready (detected via PyTorch)"
|
||
if gpu["notes"]:
|
||
gpu_detail += f". {' '.join(gpu['notes'])}"
|
||
else:
|
||
gpu_status = "warn"
|
||
gpu_detail = "No compatible GPU detected — running CPU-only."
|
||
gpu_fix = (
|
||
"Dubbing will work but ~10× slower than GPU. If you have an "
|
||
"NVIDIA/AMD card, check drivers are installed."
|
||
)
|
||
checks.append({
|
||
"id": "gpu", "label": "GPU acceleration",
|
||
"status": gpu_status, "detail": gpu_detail, "fix": gpu_fix,
|
||
})
|
||
|
||
# ── GPU routing for the ACTIVE TTS engine (#21 — no silent CPU fallback).
|
||
# Distinct from the hardware "gpu" check above: this asks "will the engine
|
||
# the user actually selected use that GPU on this host?" Built from the same
|
||
# canonical probe + resolver the Engine Compatibility Matrix uses.
|
||
try:
|
||
from services.tts_backend import gpu_routing_verdict
|
||
gpu_routing = gpu_routing_verdict()
|
||
except Exception as exc: # never break preflight on a routing hiccup
|
||
logger.warning("preflight gpu_routing failed: %s", exc)
|
||
gpu_routing = None
|
||
if gpu_routing:
|
||
_rs = gpu_routing.get("routing_status")
|
||
_eng = gpu_routing.get("engine") or "active engine"
|
||
_dev = gpu_routing.get("effective_device") or "?"
|
||
_why = gpu_routing.get("routing_reason")
|
||
if _rs == "accelerated" and not _why:
|
||
r_status, r_detail, r_fix = "pass", f"{_eng} → {_dev} (accelerated)", None
|
||
elif _rs == "accelerated": # driver/arch caveat
|
||
r_status, r_detail, r_fix = "warn", f"{_eng} → {_dev}: {_why}", (
|
||
"GPU selected but may fail at kernel launch — update drivers / "
|
||
"reinstall torch for this GPU architecture.")
|
||
elif _rs == "cpu_fallback":
|
||
r_status, r_detail, r_fix = "warn", (
|
||
f"{_eng} runs on CPU here: {_why or 'no GPU path for this host'}"), (
|
||
"Pick an engine that supports this host's GPU for a speedup, or "
|
||
"continue on CPU (slower).")
|
||
elif _rs == "cpu_only":
|
||
r_status, r_detail, r_fix = "pass", f"{_eng} → cpu (no accelerator on this host)", None
|
||
elif _rs == "unavailable":
|
||
r_status, r_detail, r_fix = "fail", (
|
||
f"{_eng} can't run on this host: {_why or 'needs a GPU this machine lacks'}"), (
|
||
"Select an engine with a CPU path in Model Catalogue → Engines.")
|
||
else: # "none" / unknown
|
||
r_status, r_detail, r_fix = "warn", "No active TTS engine resolved for routing.", (
|
||
"Pick an engine in Model Catalogue → Engines.")
|
||
checks.append({
|
||
"id": "gpu_routing", "label": "Active engine routing",
|
||
"status": r_status, "detail": r_detail, "fix": r_fix,
|
||
})
|
||
|
||
# ── Network — a dead network is a WARNING, not a blocker. The app is
|
||
# local-first: already-downloaded models work offline, and a hard fail
|
||
# here dead-ends restricted-network users (e.g. China, where
|
||
# huggingface.co is blocked) on the very first screen — before they can
|
||
# reach the mirror setting that fixes it. Model downloads surface their
|
||
# own actionable errors.
|
||
#
|
||
# With NO explicit endpoint configured, preflight runs the automatic
|
||
# endpoint race (services.endpoint_race): both the official endpoint and
|
||
# the community mirror are probed, the winner is cached for downloads,
|
||
# and the copy states the outcome honestly — so a blocked huggingface.co
|
||
# no longer needs the user to find the mirror setting at all. An explicit
|
||
# endpoint (Settings / HF_ENDPOINT / pref) keeps the single-endpoint
|
||
# probe: the user's choice is never auto-switched.
|
||
checks.append(_network_check())
|
||
|
||
# Aggregate
|
||
any_fail = any(c["status"] == "fail" for c in checks)
|
||
any_warn = any(c["status"] == "warn" for c in checks)
|
||
|
||
return {
|
||
"ok": not any_fail,
|
||
"has_warnings": any_warn,
|
||
"checks": checks,
|
||
"device": {
|
||
"os": sys.platform,
|
||
"arch": arch,
|
||
"gpu_vendor": gpu["vendor"],
|
||
"gpu_backend": gpu["backend"],
|
||
"gpu_available": gpu["available"],
|
||
"gpu_driver": gpu["driver"],
|
||
"gpu_device_name": gpu["device_name"],
|
||
# Canonical probe (distinguishes ROCm from CUDA):
|
||
"gpu_family": (gpu_routing or {}).get("host_family", "cpu"),
|
||
"vram_gb": (gpu_routing or {}).get("vram_gb", 0.0),
|
||
"ram_gb": round(ram, 1),
|
||
"disk_free_gb": round(free, 1),
|
||
},
|
||
"gpu_routing": gpu_routing,
|
||
"media_tools": media_tools,
|
||
}
|
||
|
||
|
||
# ── Warmup ─────────────────────────────────────────────────────────────────
|
||
|
||
@router.post("/setup/warmup")
|
||
async def setup_warmup():
|
||
"""Trigger a model load in the background so the first dub doesn't pay
|
||
the cold-start tax."""
|
||
loop = asyncio.get_running_loop()
|
||
|
||
async def _do_warmup():
|
||
try:
|
||
from services.model_manager import get_model
|
||
await get_model()
|
||
except Exception as e:
|
||
logger.warning("setup/warmup: model load failed: %s", e)
|
||
|
||
loop.create_task(_do_warmup())
|
||
return {"status": "warmup_started"}
|