mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
More stem engine implementation
# Conflicts: # backend/konduktor/schemas.py
This commit is contained in:
1 parent
27471a82cd
commit
e805635383
13 files changed
+1242
-1
No files matched your search
@@ -336,6 +336,22 @@ Two independent apps that talk over HTTP:
|
|||||||
the view's, so browsing elsewhere cannot point it at endpoints that do not
|
the view's, so browsing elsewhere cannot point it at endpoints that do not
|
||||||
know the track. `trackAudioUrl`/`trackCuesFor` in `api.ts` are the one place
|
know the track. `trackAudioUrl`/`trackCuesFor` in `api.ts` are the one place
|
||||||
that choice is made.
|
that choice is made.
|
||||||
|
- `stems/` — Convert to Stems around the file itself. `engine_manager.py`:
|
||||||
|
the engine version THIS build needs (`engine.json`) and the pinned weights
|
||||||
|
(`weights.json`, a copy of `engine/weights.json` a test keeps equal).
|
||||||
|
Installs under app-data (Windows: a SHORT `%LOCALAPPDATA%\Konduktor\engine`
|
||||||
|
for the 260-char limit); an install counts only after every part's hash,
|
||||||
|
the archive's, AND the unpacked engine starting and naming the expected
|
||||||
|
version (`probe`) — `installed.json` is written last. One engine at a time;
|
||||||
|
CUDA offered only for driver r580+ and capability 7.5+ (`nvidia-smi`).
|
||||||
|
Side-loading (offline) verifies against the release manifest, cached once
|
||||||
|
seen. `download.py`: resumable (`Range`, restarts if ignored), SHA-verified,
|
||||||
|
certifi TLS (a frozen macOS Python has no CA store). `engine_process.py`:
|
||||||
|
one `serve` per batch — progress, cancel-by-message, crash reported with
|
||||||
|
the engine's stderr tail, raw work files deleted as read, a Windows Job
|
||||||
|
Object and `keep_awake` (caffeinate / SetThreadExecutionState). Routes:
|
||||||
|
`GET /api/stems/engine`, `POST .../install` (a `stem-engine-install` job in
|
||||||
|
bytes, engine + weights), `POST .../sideload`, `DELETE`.
|
||||||
- `app_state.py` — the one loaded library, and the **version-history commit**.
|
- `app_state.py` — the one loaded library, and the **version-history commit**.
|
||||||
**`discard()`** (`POST /api/discard`, SaveBar's "Discard changes…", the
|
**`discard()`** (`POST /api/discard`, SaveBar's "Discard changes…", the
|
||||||
quit prompt's Discard) drops every unsaved edit through the adapter's own
|
quit prompt's Discard) drops every unsaved edit through the adapter's own
|
||||||
@@ -724,6 +740,14 @@ serialization path.** It enforces:
|
|||||||
save round-trip; anchor-before-0 moves a whole beat with its companion, a
|
save round-trip; anchor-before-0 moves a whole beat with its companion, a
|
||||||
hotcue clamps and is reported; "add" appends, keeps the original, joins a
|
hotcue clamps and is reported; "add" appends, keeps the original, joins a
|
||||||
playlist, carries pending tag fields; clashes refused with nothing changed.
|
playlist, carries pending tag fields; clashes refused with nothing changed.
|
||||||
|
- `test_engine_manager.py` — the engine manager and process against a LOCAL
|
||||||
|
Range-aware server and a FAKE engine script (no network, no torch): resume,
|
||||||
|
restart when Range is ignored, checksum refusal, cancel keeps the `.part`;
|
||||||
|
install from split parts with byte progress and a probe; a wrong-version
|
||||||
|
engine or corrupt part leaves nothing installed; side-load and weights
|
||||||
|
verified; the CUDA offer's driver/capability floors; the process relays
|
||||||
|
progress, cancels without dying, reports a crash with its reason, keeps the
|
||||||
|
Mac awake; the routes (install job in bytes, 409 while one runs, remove).
|
||||||
- `test_traktor_adapter.py` — the **generic layer**: one parse per open, the
|
- `test_traktor_adapter.py` — the **generic layer**: one parse per open, the
|
||||||
projection refreshing after every command family, cue-type translation,
|
projection refreshing after every command family, cue-type translation,
|
||||||
capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity`
|
capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity`
|
||||||
|
|||||||
@@ -48,6 +48,12 @@ datas += [
|
|||||||
("fixtures/rekordbox/device/export.pdb", "fixtures/rekordbox/device"),
|
("fixtures/rekordbox/device/export.pdb", "fixtures/rekordbox/device"),
|
||||||
("fixtures/rekordbox/device/exportExt.pdb", "fixtures/rekordbox/device"),
|
("fixtures/rekordbox/device/exportExt.pdb", "fixtures/rekordbox/device"),
|
||||||
]
|
]
|
||||||
|
# Which stem engine this build needs, and the pinned weights (read at import by
|
||||||
|
# konduktor/stems/engine_manager.py).
|
||||||
|
datas += [
|
||||||
|
("konduktor/stems/engine.json", "konduktor/stems"),
|
||||||
|
("konduktor/stems/weights.json", "konduktor/stems"),
|
||||||
|
]
|
||||||
|
|
||||||
a = Analysis(
|
a = Analysis(
|
||||||
["sidecar.py"],
|
["sidecar.py"],
|
||||||
|
|||||||
@@ -96,6 +96,8 @@ from .schemas import (
|
|||||||
Track,
|
Track,
|
||||||
TrackCues,
|
TrackCues,
|
||||||
TrackPage,
|
TrackPage,
|
||||||
|
StemEngineInstall,
|
||||||
|
StemSideLoad,
|
||||||
)
|
)
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
@@ -731,6 +733,100 @@ def state() -> EditState:
|
|||||||
return EditState(dirty=require_adapter().dirty, library=_library_info())
|
return EditState(dirty=require_adapter().dirty, library=_library_info())
|
||||||
|
|
||||||
|
|
||||||
|
# ---- stem engine (download / side-load / remove) --------------------------
|
||||||
|
# The engine and its weights live outside the app (see stems/engine_manager.py).
|
||||||
|
ENGINE_JOB = "stem-engine-install"
|
||||||
|
STEM_JOB = "stem-conversion"
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/stems/engine")
|
||||||
|
def stem_engine_status() -> dict:
|
||||||
|
"""What is installed, what this computer can run, and what a download costs."""
|
||||||
|
from .stems import engine_manager as em
|
||||||
|
|
||||||
|
mgr = em.default_manager()
|
||||||
|
running = JOBS.active(ENGINE_JOB)
|
||||||
|
return {**mgr.status(), "device": prefs.load_prefs().get("stemDevice", "auto"),
|
||||||
|
"install_job": running[0].id if running else None}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/stems/engine/install", response_model=JobStatus)
|
||||||
|
def install_stem_engine(body: StemEngineInstall) -> JobStatus:
|
||||||
|
"""Download the engine (and the weights) as a job, in bytes."""
|
||||||
|
from .jobs import JobCancelled
|
||||||
|
from .stems import download
|
||||||
|
from .stems import engine_manager as em
|
||||||
|
|
||||||
|
mgr = em.default_manager()
|
||||||
|
if mgr.base_target is None:
|
||||||
|
raise HTTPException(422, "There is no stem engine for this computer")
|
||||||
|
target = body.target or mgr.base_target
|
||||||
|
if target not in mgr.status(network=False)["offered_targets"]:
|
||||||
|
raise HTTPException(400, f"The {target} engine is not offered on this computer")
|
||||||
|
|
||||||
|
def run(handle):
|
||||||
|
info = mgr.target_info(target)
|
||||||
|
if info is None:
|
||||||
|
raise em.EngineError("Could not reach the engine download — check the internet connection")
|
||||||
|
installed = mgr.installed()
|
||||||
|
need_engine = not (installed and installed["target"] == target)
|
||||||
|
need_weights = body.weights and not mgr.weights_installed()
|
||||||
|
total = (info["size"] if need_engine else 0) + (mgr.weights_size() if need_weights else 0)
|
||||||
|
handle.progress(done=0, total=total, unit="bytes", message="Downloading the stem engine…")
|
||||||
|
done = [0]
|
||||||
|
|
||||||
|
def on_bytes(n: int) -> None:
|
||||||
|
done[0] += n
|
||||||
|
handle.progress(done=done[0])
|
||||||
|
|
||||||
|
try:
|
||||||
|
if need_engine:
|
||||||
|
mgr.install_engine(target, on_bytes=on_bytes, cancelled=lambda: handle.cancelled)
|
||||||
|
if need_weights:
|
||||||
|
handle.progress(message="Downloading the separation model…")
|
||||||
|
mgr.install_weights(on_bytes=on_bytes, cancelled=lambda: handle.cancelled)
|
||||||
|
except download.DownloadCancelled:
|
||||||
|
raise JobCancelled()
|
||||||
|
return {"target": target, "ready": mgr.ready()}
|
||||||
|
|
||||||
|
try:
|
||||||
|
job = JOBS.submit(ENGINE_JOB, run, exclusive_with=(ENGINE_JOB, STEM_JOB))
|
||||||
|
except JobBusy:
|
||||||
|
raise HTTPException(409, "The stem engine is already downloading, or a conversion is running")
|
||||||
|
return JobStatus(**job.as_dict())
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/stems/engine/sideload")
|
||||||
|
def side_load_stem_engine(body: StemSideLoad) -> dict:
|
||||||
|
"""Install the engine or the weights from files the user already has."""
|
||||||
|
from .stems import engine_manager as em
|
||||||
|
|
||||||
|
if JOBS.active(ENGINE_JOB) or JOBS.active(STEM_JOB):
|
||||||
|
raise HTTPException(409, "Wait for the running download or conversion to finish")
|
||||||
|
mgr = em.default_manager()
|
||||||
|
path = Path(body.path).expanduser()
|
||||||
|
if not path.exists():
|
||||||
|
raise HTTPException(400, f"Not found: {path}")
|
||||||
|
try:
|
||||||
|
if body.kind == "engine":
|
||||||
|
mgr.side_load_engine(path)
|
||||||
|
else:
|
||||||
|
mgr.side_load_weights(path)
|
||||||
|
except em.EngineError as ex:
|
||||||
|
raise HTTPException(400, str(ex))
|
||||||
|
return stem_engine_status()
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/stems/engine")
|
||||||
|
def remove_stem_engine() -> dict:
|
||||||
|
from .stems import engine_manager as em
|
||||||
|
|
||||||
|
if JOBS.active(ENGINE_JOB) or JOBS.active(STEM_JOB):
|
||||||
|
raise HTTPException(409, "Wait for the running download or conversion to finish")
|
||||||
|
em.default_manager().remove()
|
||||||
|
return stem_engine_status()
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/discard", response_model=EditState)
|
@app.post("/api/discard", response_model=EditState)
|
||||||
def discard_changes() -> EditState:
|
def discard_changes() -> EditState:
|
||||||
"""Drop every unsaved edit — the library re-reads itself from disk.
|
"""Drop every unsaved edit — the library re-reads itself from disk.
|
||||||
|
|||||||
@@ -152,6 +152,18 @@ class SetCueColor(BaseModel):
|
|||||||
color: str | None = None # a capabilities.cues.palette entry; None = uncoloured
|
color: str | None = None # a capabilities.cues.palette entry; None = uncoloured
|
||||||
|
|
||||||
|
|
||||||
|
class StemEngineInstall(BaseModel):
|
||||||
|
# None = this computer's default engine; "windows-x64-cuda" to take the GPU one.
|
||||||
|
target: str | None = None
|
||||||
|
# Also fetch the model weights (the engine is useless without them).
|
||||||
|
weights: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
class StemSideLoad(BaseModel):
|
||||||
|
path: str
|
||||||
|
kind: Literal["engine", "weights"]
|
||||||
|
|
||||||
|
|
||||||
class EditState(BaseModel):
|
class EditState(BaseModel):
|
||||||
dirty: bool # unsaved in-memory changes exist
|
dirty: bool # unsaved in-memory changes exist
|
||||||
library: LibraryInfo
|
library: LibraryInfo
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
"""Convert to Stems: everything outside the stem FILE itself.
|
||||||
|
|
||||||
|
`core/stem_file.py` writes a stem file from a separation callback; the Traktor
|
||||||
|
adapter swaps it into the collection (`apply_stem_swaps`). This package is what
|
||||||
|
sits around them: the downloadable engine and weights (`engine_manager`), the
|
||||||
|
engine process (`engine_process`), and — next — the batch and the parked-
|
||||||
|
originals lifecycle.
|
||||||
|
"""
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
"""A resumable, verified download — the engine's parts and the weights.
|
||||||
|
|
||||||
|
Big files over home connections get interrupted, so a download resumes from
|
||||||
|
its `.part` file with an HTTP `Range` request (and starts over if the server
|
||||||
|
ignores it), and a file only takes its final name once its SHA-256 matches.
|
||||||
|
GitHub release assets and Hugging Face files both redirect to a CDN; urllib
|
||||||
|
carries the `Range` header across the redirect.
|
||||||
|
|
||||||
|
TLS uses certifi's bundle: a frozen Python on macOS has no system CA store of
|
||||||
|
its own, so the default context would reject every HTTPS certificate.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
CHUNK = 1 << 20
|
||||||
|
_UA = "Konduktor (stem engine download)"
|
||||||
|
|
||||||
|
|
||||||
|
class DownloadError(Exception):
|
||||||
|
"""User-facing."""
|
||||||
|
|
||||||
|
|
||||||
|
class DownloadCancelled(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def ssl_context() -> ssl.SSLContext:
|
||||||
|
try:
|
||||||
|
import certifi
|
||||||
|
|
||||||
|
return ssl.create_default_context(cafile=certifi.where())
|
||||||
|
except Exception: # noqa: BLE001 — fall back to the platform's own store
|
||||||
|
return ssl.create_default_context()
|
||||||
|
|
||||||
|
|
||||||
|
def sha256_file(path: Path) -> str:
|
||||||
|
h = hashlib.sha256()
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
for chunk in iter(lambda: f.read(CHUNK), b""):
|
||||||
|
h.update(chunk)
|
||||||
|
return h.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def fetch(url: str, dest: Path, *, sha256: str, size: int | None = None,
|
||||||
|
on_bytes: Callable[[int], None] = lambda n: None,
|
||||||
|
cancelled: Callable[[], bool] = lambda: False,
|
||||||
|
context: ssl.SSLContext | None = None, timeout: float = 60) -> None:
|
||||||
|
"""Download `url` to `dest`, resuming a previous `.part`, verified.
|
||||||
|
|
||||||
|
`on_bytes` is told about every chunk INCLUDING what an earlier attempt
|
||||||
|
already fetched (once, up front), so a progress bar resumes where it was.
|
||||||
|
"""
|
||||||
|
dest = Path(dest)
|
||||||
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
if dest.exists() and (size is None or dest.stat().st_size == size) and sha256_file(dest) == sha256:
|
||||||
|
on_bytes(dest.stat().st_size)
|
||||||
|
return
|
||||||
|
partial = dest.with_name(dest.name + ".part")
|
||||||
|
have = partial.stat().st_size if partial.exists() else 0
|
||||||
|
if size is not None and have > size:
|
||||||
|
partial.unlink()
|
||||||
|
have = 0
|
||||||
|
if have:
|
||||||
|
on_bytes(have)
|
||||||
|
if size is None or have < size:
|
||||||
|
headers = {"User-Agent": _UA}
|
||||||
|
if have:
|
||||||
|
headers["Range"] = f"bytes={have}-"
|
||||||
|
req = urllib.request.Request(url, headers=headers)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=timeout, context=context) as r:
|
||||||
|
if have and r.status != 206:
|
||||||
|
# The server ignored the range: start over, and un-count it.
|
||||||
|
on_bytes(-have)
|
||||||
|
have = 0
|
||||||
|
with open(partial, "ab" if have else "wb") as f:
|
||||||
|
while True:
|
||||||
|
if cancelled():
|
||||||
|
raise DownloadCancelled()
|
||||||
|
chunk = r.read(CHUNK)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
f.write(chunk)
|
||||||
|
on_bytes(len(chunk))
|
||||||
|
except DownloadCancelled:
|
||||||
|
raise
|
||||||
|
except OSError as ex: # URLError, timeouts, connection resets
|
||||||
|
raise DownloadError(f"Could not download {dest.name}: {ex}") from ex
|
||||||
|
got = sha256_file(partial)
|
||||||
|
if got != sha256:
|
||||||
|
partial.unlink(missing_ok=True)
|
||||||
|
raise DownloadError(f"{dest.name} did not arrive intact (checksum mismatch); try again")
|
||||||
|
os.replace(partial, dest)
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"comment": "The stem engine THIS app build needs. Engines are released on their own channel (engine-v<version>, .github/workflows/engine.yml); the manifest lists each target's archive parts and hashes. `cuda` is the CUDA engine's floor, used to decide whether to OFFER it; the engine's own `info` confirms the card once installed.",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"manifest_url": "https://github.com/MrPatben8/konduktor/releases/download/engine-v{version}/engine-manifest.json",
|
||||||
|
"asset_url": "https://github.com/MrPatben8/konduktor/releases/download/engine-v{version}/{name}",
|
||||||
|
"cuda": {"min_driver": 580, "min_capability": 7.5}
|
||||||
|
}
|
||||||
@@ -0,0 +1,375 @@
|
|||||||
|
"""The stem engine and its weights on THIS machine: what is installed, getting
|
||||||
|
it, getting rid of it.
|
||||||
|
|
||||||
|
The engine is a separate frozen program, released on its own channel
|
||||||
|
(`engine-v<version>`; see `engine/` and `.github/workflows/engine.yml`) and
|
||||||
|
named by `engine.json` — the version this app build needs. The weights are
|
||||||
|
pinned by revision and SHA-256 in `weights.json` (a copy of
|
||||||
|
`engine/weights.json`; a test keeps them equal) and fetched from Hugging Face,
|
||||||
|
never re-hosted.
|
||||||
|
|
||||||
|
Layout under `root` — app-data on macOS; on Windows a SHORT root,
|
||||||
|
`%LOCALAPPDATA%\\Konduktor\\engine`, because torch's tree is deep and Windows
|
||||||
|
paths stop at 260 characters:
|
||||||
|
|
||||||
|
<root>/<version>/<target>/konduktor-engine/konduktor-engine[.exe]
|
||||||
|
<root>/installed.json what is installed, written LAST
|
||||||
|
<root>/weights/<revision>/... the four .safetensors + htdemucs_ft.yaml
|
||||||
|
<root>/downloads/ resumable .part files
|
||||||
|
|
||||||
|
An install is verified three times before it counts: each part's SHA-256, the
|
||||||
|
whole archive's, and — once unpacked into a temporary folder — the engine
|
||||||
|
actually starting and reporting the expected version. Only then is it moved
|
||||||
|
into place and `installed.json` written, so a half-finished or corrupt install
|
||||||
|
can never look like a working one. One engine is installed at a time (on
|
||||||
|
Windows the CUDA engine also runs on the CPU, so it replaces the CPU one).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import platform
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tarfile
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from .. import paths
|
||||||
|
from . import download
|
||||||
|
|
||||||
|
_HERE = Path(__file__).resolve().parent
|
||||||
|
CONFIG = json.loads((_HERE / "engine.json").read_text())
|
||||||
|
WEIGHTS = json.loads((_HERE / "weights.json").read_text())
|
||||||
|
|
||||||
|
TARGETS = ("macos-arm64", "windows-x64-cpu", "windows-x64-cuda")
|
||||||
|
|
||||||
|
|
||||||
|
class EngineError(Exception):
|
||||||
|
"""User-facing."""
|
||||||
|
|
||||||
|
|
||||||
|
def default_root() -> Path:
|
||||||
|
override = os.environ.get("KONDUKTOR_DATA_DIR")
|
||||||
|
if override:
|
||||||
|
return Path(override) / "engine"
|
||||||
|
if sys.platform == "win32" and os.environ.get("LOCALAPPDATA"):
|
||||||
|
return Path(os.environ["LOCALAPPDATA"]) / "Konduktor" / "engine"
|
||||||
|
return paths.app_data_dir() / "engine"
|
||||||
|
|
||||||
|
|
||||||
|
def base_target() -> str | None:
|
||||||
|
"""The engine this computer can run at all; None = no engine for it
|
||||||
|
(Intel Macs, Linux)."""
|
||||||
|
machine = platform.machine().lower()
|
||||||
|
if sys.platform == "darwin" and machine in ("arm64", "aarch64"):
|
||||||
|
return "macos-arm64"
|
||||||
|
if sys.platform == "win32" and machine in ("amd64", "x86_64"):
|
||||||
|
return "windows-x64-cpu"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class NvidiaGpu:
|
||||||
|
name: str
|
||||||
|
driver: str
|
||||||
|
capability: float
|
||||||
|
|
||||||
|
|
||||||
|
def detect_nvidia() -> list[NvidiaGpu]:
|
||||||
|
"""NVIDIA cards per `nvidia-smi` (installed with the driver). Empty when
|
||||||
|
there is none, or no driver — the case for every Mac."""
|
||||||
|
if sys.platform != "win32":
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
out = subprocess.run(
|
||||||
|
["nvidia-smi", "--query-gpu=name,driver_version,compute_cap", "--format=csv,noheader"],
|
||||||
|
capture_output=True, text=True, timeout=10,
|
||||||
|
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||||
|
).stdout
|
||||||
|
except (OSError, subprocess.SubprocessError):
|
||||||
|
return []
|
||||||
|
gpus = []
|
||||||
|
for line in out.splitlines():
|
||||||
|
parts = [p.strip() for p in line.split(",")]
|
||||||
|
if len(parts) == 3:
|
||||||
|
try:
|
||||||
|
gpus.append(NvidiaGpu(parts[0], parts[1], float(parts[2])))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return gpus
|
||||||
|
|
||||||
|
|
||||||
|
def cuda_suitable(gpus: list[NvidiaGpu], config: dict = CONFIG) -> NvidiaGpu | None:
|
||||||
|
"""The first card the CUDA engine can use: a new enough driver and compute
|
||||||
|
capability. Offering it to anyone else would be offering gigabytes for an
|
||||||
|
engine that falls back to the CPU."""
|
||||||
|
floor = config.get("cuda", {})
|
||||||
|
for g in gpus:
|
||||||
|
try:
|
||||||
|
major = int(g.driver.split(".")[0])
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if major >= floor.get("min_driver", 0) and g.capability >= floor.get("min_capability", 0):
|
||||||
|
return g
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class EngineManager:
|
||||||
|
def __init__(self, root: Path | None = None, config: dict | None = None,
|
||||||
|
weights: dict | None = None, target: str | None = "auto") -> None:
|
||||||
|
self.root = Path(root) if root else default_root()
|
||||||
|
self.config = config or CONFIG
|
||||||
|
self.weights = weights or WEIGHTS
|
||||||
|
self._base_target = base_target() if target == "auto" else target
|
||||||
|
self._manifest: dict | None = None
|
||||||
|
|
||||||
|
# ---- where things are --------------------------------------------------
|
||||||
|
@property
|
||||||
|
def version(self) -> str:
|
||||||
|
return self.config["version"]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def base_target(self) -> str | None:
|
||||||
|
return self._base_target
|
||||||
|
|
||||||
|
def _installed_record(self) -> dict | None:
|
||||||
|
return paths.read_json(self.root / "installed.json", None)
|
||||||
|
|
||||||
|
def installed(self) -> dict | None:
|
||||||
|
"""The installed engine, if it is this app's version and still there."""
|
||||||
|
rec = self._installed_record()
|
||||||
|
if not rec or rec.get("version") != self.version:
|
||||||
|
return None
|
||||||
|
exe = Path(rec.get("executable", ""))
|
||||||
|
return rec if exe.is_file() else None
|
||||||
|
|
||||||
|
def executable(self) -> Path | None:
|
||||||
|
rec = self.installed()
|
||||||
|
return Path(rec["executable"]) if rec else None
|
||||||
|
|
||||||
|
def weights_dir(self) -> Path:
|
||||||
|
return self.root / "weights" / self.weights["revision"]
|
||||||
|
|
||||||
|
def weights_installed(self) -> bool:
|
||||||
|
"""Present at the right sizes. (Hashes were checked when they arrived;
|
||||||
|
re-hashing 337 MB on every status call is not worth it.)"""
|
||||||
|
d = self.weights_dir()
|
||||||
|
return all((d / f["name"]).is_file() and (d / f["name"]).stat().st_size == f["size"]
|
||||||
|
for f in self.weights["files"])
|
||||||
|
|
||||||
|
def weights_size(self) -> int:
|
||||||
|
return sum(f["size"] for f in self.weights["files"])
|
||||||
|
|
||||||
|
# ---- manifest ------------------------------------------------------------
|
||||||
|
def manifest(self, *, fetch: bool = True) -> dict | None:
|
||||||
|
"""The release's manifest (each target's parts and hashes). Cached on
|
||||||
|
disk: once fetched, an install or side-load needs no network for it."""
|
||||||
|
if self._manifest is not None:
|
||||||
|
return self._manifest
|
||||||
|
cached = self.root / f"manifest-{self.version}.json"
|
||||||
|
data = paths.read_json(cached, None)
|
||||||
|
if data is None and fetch:
|
||||||
|
url = self.config["manifest_url"].format(version=self.version)
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
try:
|
||||||
|
req = urllib.request.Request(url, headers={"User-Agent": "Konduktor"})
|
||||||
|
with urllib.request.urlopen(req, timeout=20, context=download.ssl_context()) as r:
|
||||||
|
data = json.loads(r.read())
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return None
|
||||||
|
if data.get("version") != self.version:
|
||||||
|
return None
|
||||||
|
self.root.mkdir(parents=True, exist_ok=True)
|
||||||
|
paths.write_json(cached, data)
|
||||||
|
self._manifest = data
|
||||||
|
return data
|
||||||
|
|
||||||
|
def target_info(self, target: str) -> dict | None:
|
||||||
|
m = self.manifest()
|
||||||
|
return (m or {}).get("targets", {}).get(target)
|
||||||
|
|
||||||
|
# ---- status ----------------------------------------------------------------
|
||||||
|
def status(self, *, network: bool = True) -> dict:
|
||||||
|
installed = self.installed()
|
||||||
|
gpus = detect_nvidia()
|
||||||
|
cuda = cuda_suitable(gpus, self.config)
|
||||||
|
offered = [self.base_target] if self.base_target else []
|
||||||
|
if self.base_target == "windows-x64-cpu" and cuda is not None:
|
||||||
|
offered.append("windows-x64-cuda")
|
||||||
|
manifest = self.manifest(fetch=network) if offered else None
|
||||||
|
sizes = {t: (manifest or {}).get("targets", {}).get(t, {}).get("size") for t in offered}
|
||||||
|
return {
|
||||||
|
"supported": self.base_target is not None,
|
||||||
|
"required_version": self.version,
|
||||||
|
"installed": ({k: installed[k] for k in ("version", "target", "size")} if installed else None),
|
||||||
|
"offered_targets": offered,
|
||||||
|
"download_sizes": sizes,
|
||||||
|
"manifest_available": manifest is not None,
|
||||||
|
"nvidia": ({"name": cuda.name, "driver": cuda.driver, "capability": cuda.capability} if cuda else None),
|
||||||
|
"weights": {"installed": self.weights_installed(), "size": self.weights_size(),
|
||||||
|
"revision": self.weights["revision"]},
|
||||||
|
"root": str(self.root),
|
||||||
|
}
|
||||||
|
|
||||||
|
def ready(self) -> bool:
|
||||||
|
return self.executable() is not None and self.weights_installed()
|
||||||
|
|
||||||
|
# ---- installing the engine ---------------------------------------------------
|
||||||
|
def install_engine(self, target: str | None = None, *,
|
||||||
|
on_bytes: Callable[[int], None] = lambda n: None,
|
||||||
|
cancelled: Callable[[], bool] = lambda: False) -> dict:
|
||||||
|
target = target or self.base_target
|
||||||
|
if target is None or target not in TARGETS:
|
||||||
|
raise EngineError("There is no stem engine for this computer")
|
||||||
|
info = self.target_info(target)
|
||||||
|
if info is None:
|
||||||
|
raise EngineError("Could not reach the engine download — check the internet connection")
|
||||||
|
downloads = self.root / "downloads"
|
||||||
|
ctx = download.ssl_context()
|
||||||
|
for part in info["parts"]:
|
||||||
|
url = self.config["asset_url"].format(version=self.version, name=part["name"])
|
||||||
|
download.fetch(url, downloads / part["name"], sha256=part["sha256"], size=part["size"],
|
||||||
|
on_bytes=on_bytes, cancelled=cancelled, context=ctx)
|
||||||
|
archive = self._join_parts(info, downloads)
|
||||||
|
rec = self._install_archive(archive, target, info)
|
||||||
|
for part in info["parts"]:
|
||||||
|
(downloads / part["name"]).unlink(missing_ok=True)
|
||||||
|
archive.unlink(missing_ok=True)
|
||||||
|
return rec
|
||||||
|
|
||||||
|
def _join_parts(self, info: dict, folder: Path) -> Path:
|
||||||
|
parts = [folder / p["name"] for p in info["parts"]]
|
||||||
|
if len(parts) == 1:
|
||||||
|
archive = parts[0]
|
||||||
|
else:
|
||||||
|
archive = folder / info["archive"]
|
||||||
|
with open(archive, "wb") as out:
|
||||||
|
for p in parts:
|
||||||
|
with open(p, "rb") as f:
|
||||||
|
shutil.copyfileobj(f, out, 1 << 20)
|
||||||
|
if download.sha256_file(archive) != info["sha256"]:
|
||||||
|
raise EngineError("The engine download is damaged (checksum mismatch); try again")
|
||||||
|
return archive
|
||||||
|
|
||||||
|
def _install_archive(self, archive: Path, target: str, info: dict) -> dict:
|
||||||
|
"""Unpack, prove the engine starts, THEN move it into place."""
|
||||||
|
final = self.root / self.version / target
|
||||||
|
staging = self.root / self.version / f".{target}.installing"
|
||||||
|
shutil.rmtree(staging, ignore_errors=True)
|
||||||
|
staging.mkdir(parents=True)
|
||||||
|
try:
|
||||||
|
with tarfile.open(archive, "r:gz") as tar:
|
||||||
|
tar.extractall(staging, filter="tar")
|
||||||
|
exe = staging / "konduktor-engine" / ("konduktor-engine.exe" if sys.platform == "win32" else "konduktor-engine")
|
||||||
|
if not exe.is_file():
|
||||||
|
raise EngineError("The engine archive does not contain the engine")
|
||||||
|
reported = probe(exe)
|
||||||
|
if reported.get("version") != self.version:
|
||||||
|
raise EngineError(f"The engine reports version {reported.get('version')!r}, "
|
||||||
|
f"this app needs {self.version}")
|
||||||
|
shutil.rmtree(final, ignore_errors=True)
|
||||||
|
os.replace(staging, final)
|
||||||
|
except BaseException:
|
||||||
|
shutil.rmtree(staging, ignore_errors=True)
|
||||||
|
raise
|
||||||
|
rec = {"version": self.version, "target": target, "size": info.get("unpacked_size"),
|
||||||
|
"executable": str(final / "konduktor-engine" / exe.name), "info": reported}
|
||||||
|
paths.write_json(self.root / "installed.json", rec)
|
||||||
|
self._remove_others(keep=final)
|
||||||
|
return rec
|
||||||
|
|
||||||
|
def _remove_others(self, keep: Path) -> None:
|
||||||
|
"""One engine at a time: other targets and older versions go."""
|
||||||
|
for version_dir in self.root.iterdir():
|
||||||
|
if not version_dir.is_dir() or version_dir.name in ("weights", "downloads"):
|
||||||
|
continue
|
||||||
|
for target_dir in version_dir.iterdir():
|
||||||
|
if target_dir != keep and target_dir.is_dir():
|
||||||
|
shutil.rmtree(target_dir, ignore_errors=True)
|
||||||
|
if not any(version_dir.iterdir()):
|
||||||
|
version_dir.rmdir()
|
||||||
|
|
||||||
|
# ---- installing the weights ------------------------------------------------------
|
||||||
|
def install_weights(self, *, on_bytes: Callable[[int], None] = lambda n: None,
|
||||||
|
cancelled: Callable[[], bool] = lambda: False) -> None:
|
||||||
|
folder = self.weights_dir()
|
||||||
|
ctx = download.ssl_context()
|
||||||
|
for f in self.weights["files"]:
|
||||||
|
url = self.weights["url"].format(repo=self.weights["repo"], revision=self.weights["revision"],
|
||||||
|
name=f["name"])
|
||||||
|
download.fetch(url, folder / f["name"], sha256=f["sha256"], size=f["size"],
|
||||||
|
on_bytes=on_bytes, cancelled=cancelled, context=ctx)
|
||||||
|
|
||||||
|
# ---- side-loading (offline machines) ------------------------------------------
|
||||||
|
def side_load_engine(self, path: Path | str, target: str | None = None) -> dict:
|
||||||
|
"""Install from an engine archive the user already has — the `.tar.gz`,
|
||||||
|
or a folder holding all of its parts. Its hash must match the release
|
||||||
|
manifest (fetched now, or cached from an earlier look)."""
|
||||||
|
target = target or self.base_target
|
||||||
|
info = self.target_info(target) if target else None
|
||||||
|
if info is None:
|
||||||
|
raise EngineError("The engine's checksums are not known yet — connect once, or open the "
|
||||||
|
"Stems panel while online, so the file can be verified")
|
||||||
|
src = Path(path)
|
||||||
|
if src.is_dir():
|
||||||
|
archive = self._join_parts(info, src)
|
||||||
|
else:
|
||||||
|
if download.sha256_file(src) != info["sha256"]:
|
||||||
|
raise EngineError("That file is not the engine this app needs (checksum mismatch)")
|
||||||
|
archive = src
|
||||||
|
return self._install_archive(archive, target, info)
|
||||||
|
|
||||||
|
def side_load_weights(self, folder: Path | str) -> None:
|
||||||
|
"""Copy the weights from a folder the user supplies, each file verified."""
|
||||||
|
src = Path(folder)
|
||||||
|
dest = self.weights_dir()
|
||||||
|
dest.mkdir(parents=True, exist_ok=True)
|
||||||
|
for f in self.weights["files"]:
|
||||||
|
p = src / f["name"]
|
||||||
|
if not p.is_file() or download.sha256_file(p) != f["sha256"]:
|
||||||
|
raise EngineError(f"{f['name']} is missing from that folder or is not the right file")
|
||||||
|
for f in self.weights["files"]:
|
||||||
|
shutil.copy2(src / f["name"], dest / f["name"])
|
||||||
|
|
||||||
|
# ---- removal -------------------------------------------------------------------
|
||||||
|
def remove(self) -> None:
|
||||||
|
"""The engine, its weights and any unfinished downloads."""
|
||||||
|
(self.root / "installed.json").unlink(missing_ok=True)
|
||||||
|
if self.root.exists():
|
||||||
|
for child in self.root.iterdir():
|
||||||
|
if child.is_dir():
|
||||||
|
shutil.rmtree(child, ignore_errors=True)
|
||||||
|
elif child.name != "installed.json":
|
||||||
|
child.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
_DEFAULT: "EngineManager | None" = None
|
||||||
|
|
||||||
|
|
||||||
|
def default_manager() -> EngineManager:
|
||||||
|
"""The app's one manager (the routes and the batch share it)."""
|
||||||
|
global _DEFAULT
|
||||||
|
if _DEFAULT is None:
|
||||||
|
_DEFAULT = EngineManager()
|
||||||
|
return _DEFAULT
|
||||||
|
|
||||||
|
|
||||||
|
def probe(executable: Path, timeout: float = 120) -> dict:
|
||||||
|
"""Run `engine info` — proves the unpacked engine actually starts."""
|
||||||
|
try:
|
||||||
|
out = subprocess.run([str(executable), "info"], capture_output=True, text=True, timeout=timeout,
|
||||||
|
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||||
|
except (OSError, subprocess.SubprocessError) as ex:
|
||||||
|
raise EngineError(f"The engine would not start: {ex}") from ex
|
||||||
|
for line in out.stdout.splitlines():
|
||||||
|
try:
|
||||||
|
msg = json.loads(line)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if msg.get("event") == "info":
|
||||||
|
return msg
|
||||||
|
raise EngineError("The engine started but did not identify itself")
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
"""Driving the stem engine: one `serve` process per batch.
|
||||||
|
|
||||||
|
The engine's protocol is documented in `engine/konduktor_engine/serve.py`.
|
||||||
|
Audio crosses as raw planar float32 files in a work folder.
|
||||||
|
|
||||||
|
Lifetime is the part that must not go wrong — a batch can run for hours:
|
||||||
|
* The engine ends itself when its stdin closes, so if this backend dies the
|
||||||
|
engine follows. On Windows it is ALSO put in a Job Object that kills it
|
||||||
|
when the last handle closes, which covers a hard kill of the backend.
|
||||||
|
* Cancel is a message (the model stays loaded); `close()` ends the process.
|
||||||
|
* The machine is kept awake for the batch — macOS `caffeinate` tied to the
|
||||||
|
engine's pid, Windows `SetThreadExecutionState` on the calling thread —
|
||||||
|
or a laptop sleeping at 1 am stops a 4-hour conversion at track 30.
|
||||||
|
* stderr is drained on a thread (a full pipe would block the engine) and its
|
||||||
|
tail kept, so an engine crash can be reported with its reason.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import collections
|
||||||
|
import json
|
||||||
|
import queue
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from .engine_manager import EngineError
|
||||||
|
|
||||||
|
SOURCES = ("drums", "bass", "other", "vocals")
|
||||||
|
|
||||||
|
|
||||||
|
class EngineCancelled(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _job_object_kill_on_close(pid_handle) -> object | None:
|
||||||
|
"""Windows: a Job Object with KILL_ON_JOB_CLOSE holding the engine. The
|
||||||
|
returned handle must stay referenced for as long as the engine may live."""
|
||||||
|
if sys.platform != "win32":
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
import ctypes
|
||||||
|
from ctypes import wintypes
|
||||||
|
|
||||||
|
k32 = ctypes.windll.kernel32
|
||||||
|
|
||||||
|
class IO_COUNTERS(ctypes.Structure):
|
||||||
|
_fields_ = [(n, ctypes.c_ulonglong) for n in (
|
||||||
|
"ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
|
||||||
|
"ReadTransferCount", "WriteTransferCount", "OtherTransferCount")]
|
||||||
|
|
||||||
|
class BASIC(ctypes.Structure):
|
||||||
|
_fields_ = [("PerProcessUserTimeLimit", ctypes.c_int64), ("PerJobUserTimeLimit", ctypes.c_int64),
|
||||||
|
("LimitFlags", wintypes.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t),
|
||||||
|
("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wintypes.DWORD),
|
||||||
|
("Affinity", ctypes.c_size_t), ("PriorityClass", wintypes.DWORD),
|
||||||
|
("SchedulingClass", wintypes.DWORD)]
|
||||||
|
|
||||||
|
class EXTENDED(ctypes.Structure):
|
||||||
|
_fields_ = [("BasicLimitInformation", BASIC), ("IoInfo", IO_COUNTERS),
|
||||||
|
("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t),
|
||||||
|
("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)]
|
||||||
|
|
||||||
|
job = k32.CreateJobObjectW(None, None)
|
||||||
|
info = EXTENDED()
|
||||||
|
info.BasicLimitInformation.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||||
|
k32.SetInformationJobObject(job, 9, ctypes.byref(info), ctypes.sizeof(info)) # ExtendedLimitInformation
|
||||||
|
k32.AssignProcessToJobObject(job, int(pid_handle))
|
||||||
|
return job
|
||||||
|
except Exception: # noqa: BLE001 — the stdin watchdog still covers the common case
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def keep_awake(pid: int | None = None):
|
||||||
|
"""Stop the computer sleeping while a batch runs (not the display)."""
|
||||||
|
proc = None
|
||||||
|
if sys.platform == "darwin" and pid:
|
||||||
|
try:
|
||||||
|
proc = subprocess.Popen(["caffeinate", "-i", "-w", str(pid)],
|
||||||
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||||
|
except OSError:
|
||||||
|
proc = None
|
||||||
|
elif sys.platform == "win32":
|
||||||
|
try:
|
||||||
|
import ctypes
|
||||||
|
|
||||||
|
ES_CONTINUOUS, ES_SYSTEM_REQUIRED = 0x80000000, 0x00000001
|
||||||
|
ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
if proc is not None:
|
||||||
|
proc.terminate()
|
||||||
|
if sys.platform == "win32":
|
||||||
|
try:
|
||||||
|
import ctypes
|
||||||
|
|
||||||
|
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class EngineProcess:
|
||||||
|
"""One running `serve`. Not thread-safe: one batch drives it."""
|
||||||
|
|
||||||
|
def __init__(self, executable: Path | str, weights: Path | str, *, device: str = "auto",
|
||||||
|
ready_timeout: float = 180) -> None:
|
||||||
|
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
||||||
|
self.proc = subprocess.Popen(
|
||||||
|
[str(executable), "serve", "--weights", str(weights), "--device", device],
|
||||||
|
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||||
|
text=True, bufsize=1, creationflags=flags,
|
||||||
|
)
|
||||||
|
self._job = _job_object_kill_on_close(getattr(self.proc, "_handle", 0))
|
||||||
|
self._messages: "queue.Queue[dict | None]" = queue.Queue()
|
||||||
|
self._stderr: collections.deque[str] = collections.deque(maxlen=40)
|
||||||
|
threading.Thread(target=self._read_stdout, daemon=True, name="engine-stdout").start()
|
||||||
|
threading.Thread(target=self._read_stderr, daemon=True, name="engine-stderr").start()
|
||||||
|
self.device = device
|
||||||
|
msg = self._next(ready_timeout)
|
||||||
|
if msg is None or msg.get("event") != "ready":
|
||||||
|
self.close()
|
||||||
|
raise EngineError(f"The stem engine did not start: {self._reason(msg)}")
|
||||||
|
self.device = msg.get("device", device)
|
||||||
|
self._n = 0
|
||||||
|
|
||||||
|
# ---- plumbing ---------------------------------------------------------------
|
||||||
|
def _read_stdout(self) -> None:
|
||||||
|
for line in self.proc.stdout:
|
||||||
|
try:
|
||||||
|
self._messages.put(json.loads(line))
|
||||||
|
except ValueError:
|
||||||
|
self._stderr.append(line.rstrip())
|
||||||
|
self._messages.put(None) # the engine closed its output: it has exited
|
||||||
|
|
||||||
|
def _read_stderr(self) -> None:
|
||||||
|
for line in self.proc.stderr:
|
||||||
|
self._stderr.append(line.rstrip())
|
||||||
|
|
||||||
|
def _next(self, timeout: float | None) -> dict | None:
|
||||||
|
try:
|
||||||
|
return self._messages.get(timeout=timeout)
|
||||||
|
except queue.Empty:
|
||||||
|
return {"event": "timeout"}
|
||||||
|
|
||||||
|
def _reason(self, msg: dict | None) -> str:
|
||||||
|
if msg and msg.get("message"):
|
||||||
|
return msg["message"]
|
||||||
|
tail = [l for l in self._stderr if l.strip()][-3:]
|
||||||
|
return " / ".join(tail) or "no reason given"
|
||||||
|
|
||||||
|
def _send(self, **msg) -> None:
|
||||||
|
try:
|
||||||
|
self.proc.stdin.write(json.dumps(msg) + "\n")
|
||||||
|
self.proc.stdin.flush()
|
||||||
|
except (BrokenPipeError, OSError, ValueError) as ex:
|
||||||
|
raise EngineError(f"The stem engine has stopped: {self._reason(None)}") from ex
|
||||||
|
|
||||||
|
# ---- the one command ------------------------------------------------------------
|
||||||
|
def separate(self, pcm: np.ndarray, work: Path | str, *, seed: int = 0,
|
||||||
|
on_progress: Callable[[float], None] = lambda f: None,
|
||||||
|
cancelled: Callable[[], bool] = lambda: False) -> list[np.ndarray]:
|
||||||
|
"""Four stems in `SOURCES` order, each shaped like `pcm` (2, n)."""
|
||||||
|
work = Path(work)
|
||||||
|
work.mkdir(parents=True, exist_ok=True)
|
||||||
|
self._n += 1
|
||||||
|
rid = f"t{self._n}"
|
||||||
|
mix = work / f"{rid}.f32"
|
||||||
|
np.ascontiguousarray(pcm, dtype=np.float32).tofile(mix)
|
||||||
|
out = work / rid
|
||||||
|
self._send(cmd="separate", id=rid, input=str(mix), samples=int(pcm.shape[1]),
|
||||||
|
output_dir=str(out), seed=seed)
|
||||||
|
asked_to_stop = False
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
if cancelled() and not asked_to_stop:
|
||||||
|
self._send(cmd="cancel", id=rid)
|
||||||
|
asked_to_stop = True
|
||||||
|
msg = self._next(0.5)
|
||||||
|
if msg is None:
|
||||||
|
raise EngineError(f"The stem engine stopped: {self._reason(None)}")
|
||||||
|
if msg.get("event") == "timeout" or msg.get("id") not in (rid, None):
|
||||||
|
continue
|
||||||
|
event = msg.get("event")
|
||||||
|
if event == "progress":
|
||||||
|
on_progress(float(msg.get("fraction", 0.0)))
|
||||||
|
elif event == "done":
|
||||||
|
stems = [np.fromfile(out / f"{name}.f32", dtype=np.float32).reshape(2, -1)
|
||||||
|
for name in SOURCES]
|
||||||
|
# ~100 MB of raw float per minute of audio: never leave it.
|
||||||
|
shutil.rmtree(out, ignore_errors=True)
|
||||||
|
return stems
|
||||||
|
elif event == "cancelled":
|
||||||
|
raise EngineCancelled()
|
||||||
|
elif event == "error":
|
||||||
|
raise EngineError(f"Separation failed: {self._reason(msg)}")
|
||||||
|
finally:
|
||||||
|
mix.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
try:
|
||||||
|
if self.proc.stdin:
|
||||||
|
self.proc.stdin.close() # the engine ends itself on EOF
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
self.proc.wait(timeout=5)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
self.proc.kill()
|
||||||
|
self.proc.wait(timeout=5)
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *exc):
|
||||||
|
self.close()
|
||||||
|
|
||||||
|
|
||||||
|
def wait_until(predicate: Callable[[], bool], timeout: float) -> bool:
|
||||||
|
end = time.time() + timeout
|
||||||
|
while time.time() < end:
|
||||||
|
if predicate():
|
||||||
|
return True
|
||||||
|
time.sleep(0.02)
|
||||||
|
return predicate()
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"comment": "The htdemucs_ft weights, pinned. Fetched from the official Hugging Face repo on each machine and verified here; never re-hosted (their licence is ambiguous — see the stem-conversion discussion log). Konduktor's engine manager and CI both read this file.",
|
||||||
|
"repo": "adefossez/HTDemucs-ft",
|
||||||
|
"revision": "d74ac89c3a1e874fc78f152555cf4d8533f06cd4",
|
||||||
|
"url": "https://huggingface.co/{repo}/resolve/{revision}/{name}",
|
||||||
|
"files": [
|
||||||
|
{"name": "htdemucs_ft.yaml", "size": 149, "sha256": "69470b8c1bbd674437b51bc9fb491327a10ab0396b702c93389b9cf750016346"},
|
||||||
|
{"name": "f7e0c4bc.safetensors", "size": 84025440, "sha256": "2c85ab3c62dd6edd8e0b965e38b16fd1cdde357cc25de6b6bc9ce7c83f60925f"},
|
||||||
|
{"name": "d12395a8.safetensors", "size": 84025440, "sha256": "5b01a97567ae9a3178a6236fb520251045c03eb8834bc8c24a4eec11d6c8fb56"},
|
||||||
|
{"name": "92cfc3b6.safetensors", "size": 84025440, "sha256": "a241863551f30d01c42bd7b97da40839922ead3acb0f1fcab25682f55b4eeb59"},
|
||||||
|
{"name": "04573f0d.safetensors", "size": 84025440, "sha256": "68854b0d7c2b3274723b5761f6fd9f5aec5f1bcd3f0de7c1669546fdb7871b7c"}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -31,3 +31,6 @@ traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
|
|||||||
# deprecated alias and is removed in 0.6.0, so the Rekordbox adapter keeps
|
# deprecated alias and is removed in 0.6.0, so the Rekordbox adapter keeps
|
||||||
# running as-is — but that rename is the thing to fix before taking 0.6.
|
# running as-is — but that rename is the thing to fix before taking 0.6.
|
||||||
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
|
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
|
||||||
|
# The stem engine and its weights are downloaded over HTTPS by the sidecar; a
|
||||||
|
# frozen Python on macOS has no system CA bundle of its own.
|
||||||
|
certifi>=2024.7
|
||||||
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
|||||||
source .venv/bin/activate
|
source .venv/bin/activate
|
||||||
|
|
||||||
fail=0
|
fail=0
|
||||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
|
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
|
||||||
echo "──────────────────────────────────────────"
|
echo "──────────────────────────────────────────"
|
||||||
echo "▶ $t"
|
echo "▶ $t"
|
||||||
echo "──────────────────────────────────────────"
|
echo "──────────────────────────────────────────"
|
||||||
|
|||||||
@@ -0,0 +1,364 @@
|
|||||||
|
"""The stem engine manager and process, against a LOCAL server and a FAKE engine.
|
||||||
|
|
||||||
|
No network, no torch: a tiny HTTP server (Range-aware, and able to ignore Range)
|
||||||
|
serves a fake engine archive split into parts plus fake weights, and the fake
|
||||||
|
engine is a script speaking the real protocol. Pins what fails silently:
|
||||||
|
|
||||||
|
* a download resumes from its `.part`, restarts if the server ignores the
|
||||||
|
range, and never keeps a file whose checksum is wrong;
|
||||||
|
* an install counts only once parts, archive AND a started engine all check
|
||||||
|
out — a corrupt part or a wrong-version engine leaves nothing installed;
|
||||||
|
* side-loading verifies against the release manifest; weights are verified;
|
||||||
|
* the process driver relays progress, cancels without killing the engine,
|
||||||
|
reports a crash WITH its reason, and ends the engine on close;
|
||||||
|
* the CUDA engine is offered only for a new enough driver and card.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import http.server
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import stat
|
||||||
|
import sys
|
||||||
|
import tarfile
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import warnings
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
warnings.filterwarnings("ignore")
|
||||||
|
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-enginemgr-appdata-")
|
||||||
|
|
||||||
|
import numpy as np # noqa: E402
|
||||||
|
|
||||||
|
from konduktor.stems import download, engine_manager as em # noqa: E402
|
||||||
|
from konduktor.stems.engine_process import EngineCancelled, EngineProcess, keep_awake # noqa: E402
|
||||||
|
|
||||||
|
failed = False
|
||||||
|
|
||||||
|
|
||||||
|
def check(label, cond, detail=""):
|
||||||
|
global failed
|
||||||
|
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||||
|
if not cond:
|
||||||
|
failed = True
|
||||||
|
|
||||||
|
|
||||||
|
FAKE_ENGINE = r'''#!{python}
|
||||||
|
import json, os, queue, sys, threading, time
|
||||||
|
import numpy as np
|
||||||
|
if sys.argv[1] == "info":
|
||||||
|
print(json.dumps({{"event": "info", "version": "{version}", "devices": ["cpu"]}}))
|
||||||
|
sys.exit(0)
|
||||||
|
print(json.dumps({{"event": "ready", "device": "cpu"}}), flush=True)
|
||||||
|
cancel, Q = set(), queue.Queue()
|
||||||
|
def reader():
|
||||||
|
for line in sys.stdin:
|
||||||
|
m = json.loads(line)
|
||||||
|
(cancel.add(m["id"]) if m.get("cmd") == "cancel" else Q.put(m))
|
||||||
|
os._exit(0)
|
||||||
|
threading.Thread(target=reader, daemon=True).start()
|
||||||
|
while True:
|
||||||
|
m = Q.get()
|
||||||
|
rid = m["id"]
|
||||||
|
x = np.fromfile(m["input"], dtype=np.float32).reshape(2, -1)
|
||||||
|
if os.environ.get("FAKE_CRASH"):
|
||||||
|
print("boom: out of cheese", file=sys.stderr, flush=True); os._exit(3)
|
||||||
|
if os.environ.get("FAKE_ERROR"):
|
||||||
|
print(json.dumps({{"id": rid, "event": "error", "message": "bad input"}}), flush=True); continue
|
||||||
|
stopped = False
|
||||||
|
for i in range(10):
|
||||||
|
time.sleep(float(os.environ.get("FAKE_DELAY", "0.005")))
|
||||||
|
if rid in cancel:
|
||||||
|
print(json.dumps({{"id": rid, "event": "cancelled"}}), flush=True); stopped = True; break
|
||||||
|
print(json.dumps({{"id": rid, "event": "progress", "fraction": (i + 1) / 10}}), flush=True)
|
||||||
|
if stopped:
|
||||||
|
continue
|
||||||
|
os.makedirs(m["output_dir"], exist_ok=True)
|
||||||
|
for k, g in zip(("drums", "bass", "other", "vocals"), (0.5, 0.25, -0.2, 0.1)):
|
||||||
|
(x * g).astype(np.float32).tofile(os.path.join(m["output_dir"], k + ".f32"))
|
||||||
|
print(json.dumps({{"id": rid, "event": "done", "device": "cpu"}}), flush=True)
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
class Handler(http.server.BaseHTTPRequestHandler):
|
||||||
|
root: Path
|
||||||
|
ignore_range = False
|
||||||
|
requests: list = []
|
||||||
|
|
||||||
|
def log_message(self, *a):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
path = self.root / self.path.lstrip("/")
|
||||||
|
type(self).requests.append((self.path, self.headers.get("Range")))
|
||||||
|
if not path.is_file():
|
||||||
|
self.send_error(404)
|
||||||
|
return
|
||||||
|
data = path.read_bytes()
|
||||||
|
rng = self.headers.get("Range")
|
||||||
|
if rng and not type(self).ignore_range:
|
||||||
|
start = int(rng.split("=")[1].split("-")[0])
|
||||||
|
body = data[start:]
|
||||||
|
self.send_response(206)
|
||||||
|
self.send_header("Content-Range", f"bytes {start}-{len(data) - 1}/{len(data)}")
|
||||||
|
else:
|
||||||
|
body = data
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
try:
|
||||||
|
self.wfile.write(body)
|
||||||
|
except (BrokenPipeError, ConnectionResetError):
|
||||||
|
pass # the cancel test hangs up mid-download, on purpose
|
||||||
|
|
||||||
|
|
||||||
|
def sha(b: bytes) -> str:
|
||||||
|
return hashlib.sha256(b).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
tmp = Path(tempfile.mkdtemp(prefix="konduktor-enginemgr-"))
|
||||||
|
site = tmp / "site"
|
||||||
|
site.mkdir()
|
||||||
|
Handler.root = site
|
||||||
|
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||||
|
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||||
|
BASE = f"http://127.0.0.1:{server.server_address[1]}"
|
||||||
|
|
||||||
|
print("== the weights manifest ==")
|
||||||
|
repo_copy = json.loads((Path(__file__).resolve().parents[1] / "engine" / "weights.json").read_text())
|
||||||
|
check("the backend's weights.json is the engine's (no drift)", em.WEIGHTS == repo_copy)
|
||||||
|
|
||||||
|
print("== download: resume, restart, verify, cancel ==")
|
||||||
|
blob = os.urandom(3_000_000)
|
||||||
|
(site / "blob.bin").write_bytes(blob)
|
||||||
|
dest = tmp / "dl" / "blob.bin"
|
||||||
|
dest.parent.mkdir()
|
||||||
|
(dest.parent / "blob.bin.part").write_bytes(blob[:1_000_000])
|
||||||
|
seen = []
|
||||||
|
Handler.requests.clear()
|
||||||
|
download.fetch(f"{BASE}/blob.bin", dest, sha256=sha(blob), size=len(blob), on_bytes=seen.append)
|
||||||
|
check("a download resumes from its .part with a Range request",
|
||||||
|
Handler.requests[-1][1] == "bytes=1000000-" and dest.read_bytes() == blob, str(Handler.requests[-1]))
|
||||||
|
check("…and progress counts the resumed bytes once", sum(seen) == len(blob), str(sum(seen)))
|
||||||
|
dest.unlink()
|
||||||
|
(dest.parent / "blob.bin.part").write_bytes(blob[:1_000_000])
|
||||||
|
Handler.ignore_range = True
|
||||||
|
seen.clear()
|
||||||
|
download.fetch(f"{BASE}/blob.bin", dest, sha256=sha(blob), size=len(blob), on_bytes=seen.append)
|
||||||
|
Handler.ignore_range = False
|
||||||
|
check("a server that ignores Range makes it start over, correctly", dest.read_bytes() == blob and sum(seen) == len(blob))
|
||||||
|
dest.unlink()
|
||||||
|
try:
|
||||||
|
download.fetch(f"{BASE}/blob.bin", dest, sha256="0" * 64, size=len(blob))
|
||||||
|
check("a checksum mismatch is refused", False, "kept it")
|
||||||
|
except download.DownloadError:
|
||||||
|
check("a checksum mismatch is refused, and nothing is kept",
|
||||||
|
not dest.exists() and not (dest.parent / "blob.bin.part").exists())
|
||||||
|
calls = {"n": 0}
|
||||||
|
|
||||||
|
|
||||||
|
def cancel_soon():
|
||||||
|
calls["n"] += 1
|
||||||
|
return calls["n"] > 1
|
||||||
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
download.fetch(f"{BASE}/blob.bin", dest, sha256=sha(blob), size=len(blob), cancelled=cancel_soon)
|
||||||
|
check("a cancelled download stops", False, "finished")
|
||||||
|
except download.DownloadCancelled:
|
||||||
|
check("a cancelled download stops, keeping its .part to resume", (dest.parent / "blob.bin.part").exists()
|
||||||
|
and not dest.exists())
|
||||||
|
|
||||||
|
print("== engine install ==")
|
||||||
|
VERSION = em.CONFIG["version"]
|
||||||
|
|
||||||
|
|
||||||
|
def make_release(version_reported: str, name: str, parts: int = 2) -> dict:
|
||||||
|
"""A fake engine archive, split into `parts`, plus its manifest entry."""
|
||||||
|
src = tmp / f"build-{name}"
|
||||||
|
exe = src / "konduktor-engine" / "konduktor-engine"
|
||||||
|
exe.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
exe.write_text(FAKE_ENGINE.format(python=sys.executable, version=version_reported))
|
||||||
|
exe.chmod(exe.stat().st_mode | stat.S_IEXEC)
|
||||||
|
archive = tmp / f"{name}.tar.gz"
|
||||||
|
with tarfile.open(archive, "w:gz") as tar:
|
||||||
|
tar.add(src / "konduktor-engine", arcname="konduktor-engine")
|
||||||
|
data = archive.read_bytes()
|
||||||
|
size = -(-len(data) // parts)
|
||||||
|
entry = {"archive": archive.name, "size": len(data), "sha256": sha(data), "unpacked_size": 1234, "parts": []}
|
||||||
|
for i in range(parts):
|
||||||
|
chunk = data[i * size:(i + 1) * size]
|
||||||
|
part = f"{name}.tar.gz.part{i:02d}"
|
||||||
|
(site / part).write_bytes(chunk)
|
||||||
|
entry["parts"].append({"name": part, "size": len(chunk), "sha256": sha(chunk)})
|
||||||
|
return entry, archive
|
||||||
|
|
||||||
|
|
||||||
|
good, good_archive = make_release(VERSION, "good")
|
||||||
|
wrong, _ = make_release("0.0.1", "wrong")
|
||||||
|
config = dict(em.CONFIG, manifest_url=f"{BASE}/manifest-{{version}}.json", asset_url=f"{BASE}/{{name}}")
|
||||||
|
(site / f"manifest-{VERSION}.json").write_text(json.dumps(
|
||||||
|
{"version": VERSION, "targets": {"macos-arm64": good, "windows-x64-cpu": wrong}}))
|
||||||
|
|
||||||
|
root = tmp / "root"
|
||||||
|
mgr = em.EngineManager(root=root, config=config, target="macos-arm64")
|
||||||
|
check("nothing is installed to begin with", mgr.installed() is None and not mgr.ready())
|
||||||
|
status = mgr.status()
|
||||||
|
check("status offers this computer's engine, with its download size",
|
||||||
|
status["offered_targets"] == ["macos-arm64"] and status["download_sizes"]["macos-arm64"] == good["size"], str(status))
|
||||||
|
got = []
|
||||||
|
rec = mgr.install_engine(on_bytes=got.append)
|
||||||
|
check("the engine installs from its parts", mgr.installed() is not None and Path(rec["executable"]).is_file())
|
||||||
|
check("…with byte progress for the whole download", sum(got) == good["size"], str(sum(got)))
|
||||||
|
check("…and the installed engine was PROBED (it started and named its version)", rec["info"]["version"] == VERSION)
|
||||||
|
check("the downloaded parts are cleaned up", not any((root / "downloads").glob("*")))
|
||||||
|
|
||||||
|
mgr2 = em.EngineManager(root=tmp / "root2", config=config, target="windows-x64-cpu")
|
||||||
|
try:
|
||||||
|
mgr2.install_engine()
|
||||||
|
check("an engine reporting the wrong version is refused", False, "installed")
|
||||||
|
except em.EngineError as ex:
|
||||||
|
check("an engine reporting the wrong version is refused, and nothing is installed",
|
||||||
|
mgr2.installed() is None and not any((tmp / "root2" / VERSION).glob("*")), str(ex))
|
||||||
|
|
||||||
|
(site / good["parts"][1]["name"]).write_bytes(b"corrupt")
|
||||||
|
mgr3 = em.EngineManager(root=tmp / "root3", config=config, target="macos-arm64")
|
||||||
|
try:
|
||||||
|
mgr3.install_engine()
|
||||||
|
check("a corrupt part is refused", False, "installed")
|
||||||
|
except (download.DownloadError, em.EngineError):
|
||||||
|
check("a corrupt part is refused, and nothing is installed", mgr3.installed() is None)
|
||||||
|
|
||||||
|
print("== side-loading ==")
|
||||||
|
mgr4 = em.EngineManager(root=tmp / "root4", config=config, target="macos-arm64")
|
||||||
|
mgr4.side_load_engine(good_archive)
|
||||||
|
check("an engine archive the user has is installed after its hash checks out", mgr4.installed() is not None)
|
||||||
|
bogus = tmp / "bogus.tar.gz"
|
||||||
|
bogus.write_bytes(b"not an engine")
|
||||||
|
try:
|
||||||
|
em.EngineManager(root=tmp / "root5", config=config, target="macos-arm64").side_load_engine(bogus)
|
||||||
|
check("a file that is not the engine is refused", False, "installed")
|
||||||
|
except em.EngineError:
|
||||||
|
check("a file that is not the engine is refused", True)
|
||||||
|
|
||||||
|
print("== weights ==")
|
||||||
|
files = [("htdemucs_ft.yaml", b"models: [a]\n"), ("a.safetensors", os.urandom(200_000))]
|
||||||
|
for name, data in files:
|
||||||
|
(site / "w" / "rev1").mkdir(parents=True, exist_ok=True)
|
||||||
|
(site / "w" / "rev1" / name).write_bytes(data)
|
||||||
|
wmanifest = {"repo": "x/y", "revision": "rev1", "url": f"{BASE}/w/{{revision}}/{{name}}",
|
||||||
|
"files": [{"name": n, "size": len(d), "sha256": sha(d)} for n, d in files]}
|
||||||
|
wm = em.EngineManager(root=tmp / "root6", config=config, weights=wmanifest, target="macos-arm64")
|
||||||
|
check("weights are not installed to begin with", not wm.weights_installed())
|
||||||
|
wm.install_weights()
|
||||||
|
check("the weights install, verified", wm.weights_installed())
|
||||||
|
side = tmp / "side-weights"
|
||||||
|
side.mkdir()
|
||||||
|
for name, data in files:
|
||||||
|
(side / name).write_bytes(data)
|
||||||
|
wm2 = em.EngineManager(root=tmp / "root7", config=config, weights=wmanifest, target="macos-arm64")
|
||||||
|
wm2.side_load_weights(side)
|
||||||
|
check("weights from a folder the user supplies are accepted when they verify", wm2.weights_installed())
|
||||||
|
(side / "a.safetensors").write_bytes(b"tampered")
|
||||||
|
try:
|
||||||
|
em.EngineManager(root=tmp / "root8", config=config, weights=wmanifest, target="macos-arm64").side_load_weights(side)
|
||||||
|
check("tampered weights are refused", False, "accepted")
|
||||||
|
except em.EngineError:
|
||||||
|
check("tampered weights are refused", True)
|
||||||
|
mgr.remove()
|
||||||
|
check("remove takes the engine away", mgr.installed() is None and not (root / VERSION).exists())
|
||||||
|
|
||||||
|
print("== CUDA is offered only where it will run ==")
|
||||||
|
G = em.NvidiaGpu
|
||||||
|
check("RTX 40-series, current driver: offered", em.cuda_suitable([G("RTX 4070", "581.08", 8.9)]) is not None)
|
||||||
|
check("an old driver: not offered", em.cuda_suitable([G("RTX 4070", "552.22", 8.9)]) is None)
|
||||||
|
check("a GTX 1060 (Pascal, 6.1): not offered", em.cuda_suitable([G("GTX 1060", "581.08", 6.1)]) is None)
|
||||||
|
check("no card: not offered", em.cuda_suitable([]) is None)
|
||||||
|
|
||||||
|
print("== the engine process ==")
|
||||||
|
exe = Path(mgr4.executable())
|
||||||
|
pcm = np.random.default_rng(0).uniform(-0.5, 0.5, (2, 44100)).astype(np.float32)
|
||||||
|
work = tmp / "work"
|
||||||
|
with EngineProcess(exe, tmp, device="cpu") as eng:
|
||||||
|
prog = []
|
||||||
|
stems = eng.separate(pcm, work, on_progress=prog.append)
|
||||||
|
check("separate returns four stems in drums/bass/other/vocals order",
|
||||||
|
len(stems) == 4 and np.allclose(stems[0], pcm * 0.5) and np.allclose(stems[3], pcm * 0.1))
|
||||||
|
check("…relaying progress", prog and prog[-1] == 1.0, str(prog))
|
||||||
|
check("…and leaves no work files behind", not any(work.rglob("*.f32")), str(list(work.rglob("*"))))
|
||||||
|
os.environ["FAKE_DELAY"] = "0.05"
|
||||||
|
try:
|
||||||
|
eng.separate(pcm, work, cancelled=lambda: True)
|
||||||
|
check("a cancel stops the track", False, "finished")
|
||||||
|
except EngineCancelled:
|
||||||
|
check("a cancel stops the track", True)
|
||||||
|
os.environ.pop("FAKE_DELAY")
|
||||||
|
check("…and the engine is still usable", len(eng.separate(pcm, work)) == 4)
|
||||||
|
proc = eng.proc
|
||||||
|
check("closing ends the engine process", proc.poll() is not None)
|
||||||
|
os.environ["FAKE_ERROR"] = "1"
|
||||||
|
with EngineProcess(exe, tmp) as eng:
|
||||||
|
try:
|
||||||
|
eng.separate(pcm, work)
|
||||||
|
check("an engine error is reported", False)
|
||||||
|
except em.EngineError as ex:
|
||||||
|
check("an engine error is reported with its message", "bad input" in str(ex), str(ex))
|
||||||
|
os.environ.pop("FAKE_ERROR")
|
||||||
|
os.environ["FAKE_CRASH"] = "1"
|
||||||
|
with EngineProcess(exe, tmp) as eng:
|
||||||
|
try:
|
||||||
|
eng.separate(pcm, work)
|
||||||
|
check("an engine crash is reported", False)
|
||||||
|
except em.EngineError as ex:
|
||||||
|
check("an engine crash is reported WITH its reason", "out of cheese" in str(ex), str(ex))
|
||||||
|
os.environ.pop("FAKE_CRASH")
|
||||||
|
if sys.platform == "darwin":
|
||||||
|
import subprocess
|
||||||
|
with EngineProcess(exe, tmp) as eng, keep_awake(eng.proc.pid):
|
||||||
|
running = subprocess.run(["pgrep", "-f", f"caffeinate -i -w {eng.proc.pid}"], capture_output=True).returncode == 0
|
||||||
|
check("the machine is kept awake while the engine runs (caffeinate)", running)
|
||||||
|
|
||||||
|
print("== the routes ==")
|
||||||
|
from fastapi.testclient import TestClient # noqa: E402
|
||||||
|
import time as _time # noqa: E402
|
||||||
|
|
||||||
|
import konduktor.main as main # noqa: E402
|
||||||
|
|
||||||
|
# A fresh, uncorrupted release for the routes (an earlier check corrupted `good`).
|
||||||
|
fresh, _ = make_release(VERSION, "fresh")
|
||||||
|
(site / f"manifest-{VERSION}.json").write_text(json.dumps({"version": VERSION, "targets": {"macos-arm64": fresh}}))
|
||||||
|
em._DEFAULT = em.EngineManager(root=tmp / "root-routes", config=config, weights=wmanifest, target="macos-arm64")
|
||||||
|
with TestClient(main.app) as c:
|
||||||
|
st = c.get("/api/stems/engine").json()
|
||||||
|
check("status: supported, nothing installed, a download size known",
|
||||||
|
st["supported"] and st["installed"] is None and st["download_sizes"]["macos-arm64"] == fresh["size"], str(st)[:300])
|
||||||
|
os.environ["FAKE_DELAY"] = "0"
|
||||||
|
gate = threading.Event()
|
||||||
|
blocker = main.JOBS.submit(main.ENGINE_JOB, lambda h: gate.wait(10))
|
||||||
|
second = c.post("/api/stems/engine/install", json={})
|
||||||
|
gate.set()
|
||||||
|
main.JOBS.wait(blocker.id, 10)
|
||||||
|
job = c.post("/api/stems/engine/install", json={}).json()
|
||||||
|
end = _time.time() + 30
|
||||||
|
while _time.time() < end:
|
||||||
|
j = c.get(f"/api/jobs/{job['id']}").json()
|
||||||
|
if j["state"] != "running":
|
||||||
|
break
|
||||||
|
_time.sleep(0.05)
|
||||||
|
check("install runs as a job counting BYTES (engine + weights)",
|
||||||
|
j["state"] == "done" and j["unit"] == "bytes"
|
||||||
|
and j["total"] == fresh["size"] + sum(f["size"] for f in wmanifest["files"]), str(j)[:300])
|
||||||
|
check("…that ends ready to convert", j["result"] == {"target": "macos-arm64", "ready": True}, str(j["result"]))
|
||||||
|
check("an install while another runs is refused (409)", second.status_code == 409, str(second.status_code))
|
||||||
|
st = c.get("/api/stems/engine").json()
|
||||||
|
check("status now shows the engine and the weights", st["installed"] is not None and st["weights"]["installed"])
|
||||||
|
r = c.post("/api/stems/engine/sideload", json={"path": str(bogus), "kind": "engine"})
|
||||||
|
check("side-loading a file that is not the engine is refused (400)", r.status_code == 400, r.text[:200])
|
||||||
|
r = c.delete("/api/stems/engine")
|
||||||
|
check("remove answers with nothing installed", r.status_code == 200 and r.json()["installed"] is None)
|
||||||
|
|
||||||
|
server.shutdown()
|
||||||
|
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||||
|
sys.exit(1 if failed else 0)
|
||||||
Reference in new issue
Block a user