forked from trav/lintunes
186 lines
6.7 KiB
Python
186 lines
6.7 KiB
Python
"""Instant vocals: Spleeter's 2-stem model, ~20× faster than Demucs here.
|
||
|
||
Demucs takes minutes a song on this laptop's CPU (Round 94); Spleeter took
|
||
11 s for a 4-minute song while Demucs was running beside it. It sounds
|
||
rougher (watery vocals, some bleed), so it's opt-in: Preferences › DJ has a
|
||
download button, and a deck can swap between the two splits of a song.
|
||
|
||
The original ``spleeter`` package needs TensorFlow and Python ≤3.11, so this
|
||
runs Spleeter's own weights as ONNX through **sherpa-onnx** (onnxruntime, a
|
||
~125 MB venv at ``paths.data_dir()/spleeter``, never a pip dependency
|
||
of LinTunes). The fp16 models (35 MB) come from sherpa-onnx's GitHub release
|
||
and are refused unless their SHA-256 is the one pinned here, the
|
||
``airplay/cli.py`` rule. The release's own checksum.txt is stale for this
|
||
file (it names a different hash), so this one was measured on download.
|
||
"""
|
||
|
||
import hashlib
|
||
import os
|
||
import shutil
|
||
import subprocess
|
||
import tarfile
|
||
import tempfile
|
||
import threading
|
||
import urllib.request
|
||
from pathlib import Path
|
||
|
||
from PyQt6.QtCore import QObject, pyqtSignal
|
||
|
||
from lintunes import paths
|
||
from lintunes.airplay import cli
|
||
from lintunes.dj import venv_tool
|
||
|
||
SHERPA_VERSION = "2.0.1"
|
||
MODEL_URL = ("https://github.com/k2-fsa/sherpa-onnx/releases/download/"
|
||
"source-separation-models/sherpa-onnx-spleeter-2stems-fp16.tar.bz2")
|
||
MODEL_SHA256 = "d54561979bd2e08a51e7dbd99ac36bb47564e089eefd403636dbca93e811bba2"
|
||
MODEL_FILES = ("vocals.fp16.onnx", "accompaniment.fp16.onnx")
|
||
DOWNLOAD_MB = 160 # the wheels (~125 MB installed) and the models
|
||
RUNNER = Path(__file__).with_name("_spleeter_run.py")
|
||
|
||
|
||
class Cancelled(Exception):
|
||
pass
|
||
|
||
|
||
def venv_dir() -> Path:
|
||
return paths.data_dir() / "spleeter"
|
||
|
||
|
||
def python() -> Path:
|
||
return venv_dir() / "bin" / "python"
|
||
|
||
|
||
def model_dir() -> Path:
|
||
return venv_dir() / "models"
|
||
|
||
|
||
def available() -> bool:
|
||
return python().is_file() and all((model_dir() / f).is_file() for f in MODEL_FILES)
|
||
|
||
|
||
def threads() -> int:
|
||
return os.cpu_count() or 4
|
||
|
||
|
||
def remove():
|
||
shutil.rmtree(venv_dir(), ignore_errors=True)
|
||
|
||
|
||
def _fetch(url: str) -> bytes:
|
||
with urllib.request.urlopen(url, timeout=120,
|
||
context=cli.https_context()) as response:
|
||
return response.read()
|
||
|
||
|
||
def install_models(fetch=None):
|
||
"""Download, check and unpack the models. Raises OSError."""
|
||
data = (fetch or _fetch)(MODEL_URL)
|
||
if hashlib.sha256(data).hexdigest() != MODEL_SHA256:
|
||
raise OSError("the downloaded Spleeter models didn't match their checksum")
|
||
target = model_dir()
|
||
target.mkdir(parents=True, exist_ok=True)
|
||
with tempfile.TemporaryDirectory(prefix="lintunes-spleeter-") as tmp:
|
||
archive = Path(tmp) / "models.tar.bz2"
|
||
archive.write_bytes(data)
|
||
with tarfile.open(archive) as tar:
|
||
for member in tar.getmembers():
|
||
name = Path(member.name).name
|
||
if name in MODEL_FILES and member.isfile():
|
||
source = tar.extractfile(member)
|
||
(target / name).write_bytes(source.read())
|
||
missing = [f for f in MODEL_FILES if not (target / f).is_file()]
|
||
if missing:
|
||
raise OSError(f"the Spleeter download had no {missing[0]}")
|
||
|
||
|
||
class InstantSetup(QObject):
|
||
"""Preferences' download button: makes the venv, installs sherpa-onnx,
|
||
fetches the models, on a daemon thread."""
|
||
|
||
progress = pyqtSignal(str)
|
||
finished = pyqtSignal()
|
||
failed = pyqtSignal(str)
|
||
|
||
def __init__(self, parent=None):
|
||
super().__init__(parent)
|
||
self._thread = None
|
||
|
||
def busy(self) -> bool:
|
||
return self._thread is not None and self._thread.is_alive()
|
||
|
||
def start(self):
|
||
self._thread = threading.Thread(target=self._run, daemon=True,
|
||
name="lintunes-spleeter-setup")
|
||
self._thread.start()
|
||
|
||
def _run(self):
|
||
try:
|
||
venv = venv_dir()
|
||
if venv_tool.uses_uv():
|
||
# A Mac (or the built app) has no Python to make a venv
|
||
# with; uv brings one (venv_tool's docstring).
|
||
self.progress.emit("Downloading a Python for it…")
|
||
venv_tool.ensure_uv()
|
||
env = venv_tool.run_env()
|
||
if not python().is_file():
|
||
self.progress.emit("Making its own Python environment…")
|
||
venv.parent.mkdir(parents=True, exist_ok=True)
|
||
self._call(venv_tool.create_command(venv), env)
|
||
self.progress.emit("Downloading sherpa-onnx…")
|
||
self._call(venv_tool.install_command(
|
||
venv, [f"sherpa-onnx=={SHERPA_VERSION}", "numpy"]), env)
|
||
self.progress.emit("Downloading the Spleeter models…")
|
||
install_models()
|
||
except (OSError, subprocess.SubprocessError) as e:
|
||
self.failed.emit(str(e) or type(e).__name__)
|
||
return
|
||
self.finished.emit()
|
||
|
||
@staticmethod
|
||
def _call(cmd, env=None):
|
||
done = subprocess.run(cmd, capture_output=True, text=True, timeout=1800,
|
||
env=env)
|
||
if done.returncode != 0:
|
||
lines = (done.stderr or done.stdout).strip().splitlines()
|
||
raise OSError(lines[-1] if lines else f"{cmd[2]} failed")
|
||
|
||
|
||
def split(path: str, out_dir: Path, progress=None,
|
||
cancel: threading.Event | None = None):
|
||
"""Write ``vocals.opus`` and ``no_vocals.opus`` for ``path`` into
|
||
``out_dir`` (blocking). Raises OSError, or Cancelled."""
|
||
if not available():
|
||
raise OSError("instant vocal splitting isn't set up on this computer")
|
||
if not RUNNER.is_file(): # a built app that left the helper out
|
||
raise OSError(f"LinTunes is missing {RUNNER.name}")
|
||
cmd, preexec = venv_tool.niced(
|
||
[str(python()), "-I", str(RUNNER), str(model_dir()), str(threads()), path, str(out_dir)],
|
||
5)
|
||
process = subprocess.Popen(
|
||
cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True,
|
||
env=venv_tool.child_env(), preexec_fn=preexec)
|
||
if cancel is not None:
|
||
def watch():
|
||
while process.poll() is None:
|
||
if cancel.wait(0.2):
|
||
process.kill()
|
||
return
|
||
threading.Thread(target=watch, daemon=True, name="lintunes-spleeter-watch").start()
|
||
tail = []
|
||
for line in process.stderr:
|
||
if line.startswith("LTPCT "):
|
||
if progress is not None:
|
||
try:
|
||
progress(int(line.split()[1]))
|
||
except ValueError:
|
||
pass
|
||
else:
|
||
tail = (tail + [line.strip()])[-20:]
|
||
code = process.wait()
|
||
if cancel is not None and cancel.is_set():
|
||
raise Cancelled()
|
||
if code != 0:
|
||
lines = [t for t in tail if t]
|
||
raise OSError(lines[-1] if lines else "Spleeter failed")
|