"""StemDeck's processing service on a free Hugging Face ZeroGPU Space. The StemDeck website (frontend built with VITE_STEMDECK_BACKEND=hf, hosted as a static Space) keeps every visitor's songs in their own browser and calls this service only to do the GPU work: /split a song file + quality ("best" or "max") -> stems (FLAC), analysis, waveform peaks and chords /extract one stem + the names of the song's other stems + an extractor -> new stems and the rewritten stem It runs the same pipeline as the local app (backend/stemdeck, copied in by scripts/deploy_hf.py) on a temporary database and folder per job. Each visitor's GPU time comes from their own free Hugging Face daily quota. """ from __future__ import annotations import functools import json import logging import os import shutil import sys import threading import time from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parent WORK = Path("/tmp/stemdeck") os.environ.setdefault("STEMDECK_DATA_DIR", str(WORK / "data")) os.environ.setdefault("STEMDECK_DB_FILE", str(WORK / "app.db")) os.environ.setdefault("STEMDECK_MODELS_DIR", str(WORK / "models")) # downloaded again after a Space restart os.environ.setdefault("STEMDECK_CONFIG_FILE", str(ROOT / "config.hf.yaml")) os.environ.setdefault("STEMDECK_FLAC_SUBTYPE", "PCM_16") # every stem is downloaded to the visitor's browser os.environ.setdefault("STEMDECK_PUBLIC", "1") # messages written for visitors (no API server runs here) sys.path.insert(0, str(ROOT)) import gradio as gr # noqa: E402 import spaces # noqa: E402 log = logging.getLogger("stemdeck.space") logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") MAX_GPU_SECONDS = 170 # never ask ZeroGPU for more than this per call MAX_STEMS = 64 MAX_NAME_LENGTH = 64 GPU_OVERHEAD_SEC = 25.0 # model loading and start-up, on top of the per-second estimate ANALYSIS_RTF = 0.03 KEEP_JOB_FOLDERS_SEC = 3600.0 SONG_ID_LENGTH = 32 _prefetch_done = threading.Event() # ---------------------------------------------------------------------- start-up: models before the first request def _prefetch_models() -> None: """Download every model once at start-up (on CPU), so no visitor's GPU time is spent downloading.""" from audio_separator.separator import Separator from stemdeck import worker from stemdeck.pipeline import mega from stemdeck.settings import get_config, get_settings try: worker._prepare_environment() # model caches under the models folder, OS trust store for downloads cfg, settings = get_config(), get_settings() names = {s.model for q in cfg.qualities.values() for s in (q.vocals, q.karaoke, q.instruments)} names |= {e.model for e in cfg.extractors.values() if e.engine == "audio-separator"} separator = Separator(model_file_dir=str(settings.models_dir), log_level=logging.WARNING) for name in sorted(names): started = time.monotonic() separator.download_model_files(name) log.info("model %s ready (%.0f s)", name, time.monotonic() - started) for ext in cfg.extractors.values(): if ext.engine == "mega": mega.ensure_files(settings.models_dir / ext.model, list(ext.outputs), lambda _f: None) log.info("model %s ready", ext.model) from beat_this.inference import File2Beats File2Beats(checkpoint_path="final0", device="cpu", dbn=False) log.info("all models downloaded") except Exception: # noqa: BLE001 - jobs still work; they download what's missing themselves log.exception("model prefetch failed") finally: _prefetch_done.set() threading.Thread(target=_prefetch_models, name="prefetch", daemon=True).start() # ---------------------------------------------------------------------- helpers def _clean_old_jobs() -> None: songs = WORK / "data" / "songs" if not songs.is_dir(): return cutoff = time.time() - KEEP_JOB_FOLDERS_SEC for folder in songs.iterdir(): try: if folder.is_dir() and len(folder.name) == SONG_ID_LENGTH and folder.stat().st_mtime < cutoff: shutil.rmtree(folder, ignore_errors=True) except OSError: continue def _seconds(path: str) -> float: from stemdeck.audio_io import AudioError, probe_duration try: return probe_duration(Path(path)) except AudioError as exc: raise gr.Error(str(exc)) from exc def _check_song(path: str | None) -> float: from stemdeck.settings import get_config if not path: raise gr.Error("Choose a song file first.") seconds = _seconds(path) limit = get_config().max_duration_sec if seconds > limit: raise gr.Error(f"This song is {seconds / 60:.1f} min long; the limit here is {limit / 60:.0f} min.") return seconds def _split_gpu_seconds(path: str, quality: str) -> int: from stemdeck.settings import get_config profile = get_config().qualities.get(quality) rtf = (profile.vocals.rtf + profile.karaoke.rtf + profile.instruments.rtf) if profile else 0.6 return int(min(MAX_GPU_SECONDS, GPU_OVERHEAD_SEC + _seconds(path) * (rtf + ANALYSIS_RTF))) def _extract_gpu_seconds(path: str, source_name: str, existing: list[dict[str, Any]], extractor: str) -> int: from stemdeck.settings import get_config ext = get_config().extractors.get(extractor) rtf = ext.rtf if ext else 0.3 return int(min(MAX_GPU_SECONDS, GPU_OVERHEAD_SEC + _seconds(path) * rtf)) def _run_job(kind: str, audio_path: str, params: dict[str, Any], source_name: str | None = None, existing: list[dict[str, Any]] | None = None) -> dict[str, Any]: """Run one split or extraction through the local app's worker, on a fresh database connection (this runs in ZeroGPU's GPU process, so nothing opened in the parent process may be reused). Returns plain data.""" from sqlmodel import Session, select from stemdeck import db, worker from stemdeck.audio_io import probe_duration from stemdeck.models import Job, Song, Stem, utcnow from stemdeck.settings import get_settings db.get_engine.cache_clear() settings = get_settings() song = Song(title="job", owner="space", quality=str(params.get("quality", "best"))) song_id = song.id # read once: after a commit the object is expired and detached from its session folder = settings.songs_dir / song_id folder.mkdir(parents=True, exist_ok=True) song.duration_sec = round(probe_duration(Path(audio_path)), 3) with Session(db.get_engine()) as session: session.add(song) session.commit() if kind == "split": shutil.copyfile(audio_path, folder / f"original{Path(audio_path).suffix.lower() or '.wav'}") else: stems_dir = folder / "stems" stems_dir.mkdir(parents=True, exist_ok=True) source_file = stems_dir / f"{source_name}.flac" shutil.copyfile(audio_path, source_file) # The song's stems as the website has them (colours and places matter: new stems get free ones). for info in existing or []: is_source = info["name"] == source_name session.add(Stem(song_id=song_id, name=info["name"], label=info["label"], kind=info["kind"], color=info["color"], order=info["order"], experimental=info["experimental"], file_path=str(source_file) if is_source else "")) if not any(info["name"] == source_name for info in existing or []): session.add(Stem(song_id=song_id, name=str(source_name), label=str(source_name), kind="base", file_path=str(source_file))) job = Job(song_id=song_id, type=kind, params=params, status="running", started_at=utcnow()) session.add(job) session.commit() job_id = job.id worker.run(job_id) with Session(db.get_engine()) as session: job = session.get(Job, job_id) if job is None or job.status != "done": raise gr.Error((job.error if job else None) or "Processing failed. Please try again.") song = session.get(Song, song_id) duration_sec, null_test = (song.duration_sec, song.null_test_snr_db) if song else (None, None) rows = session.exec(select(Stem).where(Stem.song_id == song_id).order_by(Stem.order)).all() stems = [{"name": r.name, "label": r.label, "kind": r.kind, "detected": r.detected, "experimental": r.experimental, "color": r.color, "rms_db": r.rms_db, "order": r.order, "file": r.file_path} for r in rows if r.file_path and Path(r.file_path).is_file()] if kind == "extract": # only what changed: the new stems and the rewritten source stem unchanged = {info["name"] for info in existing or []} - {source_name} stems = [s for s in stems if s["name"] not in unchanged] result: dict[str, Any] = {"song": {"duration_sec": duration_sec, "null_test_snr_db": null_test}, "stems": stems, "analysis": None, "peaks": None} for key, name in (("analysis", "analysis.json"), ("peaks", "peaks.json")): path = folder / name if path.is_file(): result[key] = json.loads(path.read_text(encoding="utf-8")) return result @spaces.GPU(duration=_split_gpu_seconds) def _split_on_gpu(path: str, quality: str) -> dict[str, Any]: return _run_job("split", path, {"quality": quality}) @spaces.GPU(duration=_extract_gpu_seconds) def _extract_on_gpu(path: str, source_name: str, existing: list[dict[str, Any]], extractor: str) -> dict[str, Any]: return _run_job("extract", path, {"extractor": extractor, "source_stem": source_name}, source_name=source_name, existing=existing) def _chords(result: dict[str, Any]) -> list[dict[str, Any]]: """Chords per beat for the website's added instruments (CPU, after the GPU part).""" from stemdeck.pipeline.chords import song_chords beats = (result.get("analysis") or {}).get("beats") if not beats: return [] try: files = {s["name"]: Path(s["file"]) for s in result["stems"]} return [c.to_dict() for c in song_chords(files, beats)] except Exception: # noqa: BLE001 - chords are a nice-to-have log.exception("chord detection failed") return [] def _on_gpu(run: Any, *args: Any) -> dict[str, Any]: """Run a GPU job. Gradio's API hides the message of anything but gr.Error, so unexpected failures are turned into a readable gr.Error (quota errors from ZeroGPU already are gr.Error and pass through).""" try: return run(*args) except gr.Error: raise except Exception as exc: # noqa: BLE001 - logged in full here, summarised for the visitor log.exception("GPU job failed") raise gr.Error(f"Processing failed ({type(exc).__name__}). Please try again.") from exc def _response(result: dict[str, Any]) -> tuple[dict[str, Any], list[str]]: files = [s["file"] for s in result["stems"]] meta = {**result, "stems": [{**{k: v for k, v in s.items() if k != "file"}, "file": Path(s["file"]).name} for s in result["stems"]]} return meta, files def _reported(run: Any) -> Any: """Gradio's HTTP API sends every error as `data: null`, so the website could never say what went wrong. Endpoints therefore return failures as a normal result, {"error": ""} and no files.""" @functools.wraps(run) # keeps the signature: Gradio reads it for the API def endpoint(*args: Any) -> tuple[dict[str, Any], list[str]]: try: return run(*args) except gr.Error as exc: return {"error": str(getattr(exc, "message", "") or exc)}, [] except Exception: # noqa: BLE001 - logged in full here, summarised for the visitor log.exception("request failed") return {"error": "The GPU service could not process this song. Please try again."}, [] return endpoint # ---------------------------------------------------------------------- endpoints @_reported def split(audio: str | None, quality: str) -> tuple[dict[str, Any], list[str]]: from stemdeck.settings import get_config if quality not in get_config().qualities: raise gr.Error(f"Unknown quality '{quality}'.") _check_song(audio) _clean_old_jobs() _prefetch_done.wait() result = _on_gpu(_split_on_gpu, str(audio), quality) result["chords"] = _chords(result) return _response(result) @_reported def extract(audio: str | None, source_name: str, existing_names: str, extractor: str) -> tuple[dict[str, Any], list[str]]: from stemdeck.settings import get_config if extractor not in get_config().extractors: raise gr.Error(f"Unknown extractor '{extractor}'.") if not source_name or len(source_name) > MAX_NAME_LENGTH or not source_name.replace("_", "").isalnum(): raise gr.Error("Invalid source stem.") existing = _parse_stems(existing_names) _check_song(audio) _clean_old_jobs() _prefetch_done.wait() result = _on_gpu(_extract_on_gpu, str(audio), source_name, existing, extractor) return _response(result) def _parse_stems(raw: str) -> list[dict[str, Any]]: """The song's stems sent by the website: names (older pages) or {name, label, kind, color, order, ...}.""" try: items = json.loads(raw or "[]") except json.JSONDecodeError as exc: raise gr.Error("Invalid list of stems.") from exc if not isinstance(items, list): raise gr.Error("Invalid list of stems.") stems: list[dict[str, Any]] = [] for item in items[:MAX_STEMS]: info = item if isinstance(item, dict) else {"name": item} name = str(info.get("name", ""))[:MAX_NAME_LENGTH] if not name: continue color = str(info.get("color", "#94a3b8")) order = info.get("order", 0) stems.append({ "name": name, "label": str(info.get("label") or name)[:80], "kind": info.get("kind") if info.get("kind") in ("base", "extra") else "base", "color": color if len(color) <= 9 and color.startswith("#") else "#94a3b8", "order": order if isinstance(order, int) else 0, "experimental": bool(info.get("experimental", False)), }) return stems # ---------------------------------------------------------------------- YouTube links (CPU only: no GPU time) YOUTUBE_DIR = WORK / "youtube" # Optional: a cookies.txt export of a YouTube account, kept as a private secret of this Space. YouTube asks # servers like this one to "confirm you're not a bot"; a signed-in session gets past that. YOUTUBE_COOKIES_SECRET = "STEMDECK_YOUTUBE_COOKIES" YOUTUBE_BLOCKED = "youtube-blocked" # the website then gets the song through the visitor's own browser # A cap on downloads for the whole site: keeps anyone from using this Space as a free YouTube downloader, which # would also get its YouTube sign-in flagged. Past it, the website uses the visitor's own browser (the extension). YOUTUBE_DOWNLOADS_PER_HOUR = 60 _youtube_times: list[float] = [] _youtube_lock = threading.Lock() def _youtube_allowed(now: float) -> bool: with _youtube_lock: recent = [t for t in _youtube_times if now - t < 3600] allowed = len(recent) < YOUTUBE_DOWNLOADS_PER_HOUR _youtube_times[:] = recent + ([now] if allowed else []) return allowed def _load_youtube_sign_in() -> None: from stemdeck import youtube as yt from stemdeck.settings import get_settings raw = os.environ.pop(YOUTUBE_COOKIES_SECRET, "") # not left in the environment of anything started later if not raw.strip(): return settings = get_settings() settings.data_dir.mkdir(parents=True, exist_ok=True) try: log.info("YouTube sign-in loaded (%d youtube.com cookies)", yt.save_cookies(settings, raw.encode())) except yt.YouTubeError as exc: log.warning("YouTube sign-in not loaded: %s", exc) _load_youtube_sign_in() def _clean_old_downloads() -> None: if not YOUTUBE_DIR.is_dir(): return cutoff = time.time() - KEEP_JOB_FOLDERS_SEC for folder in YOUTUBE_DIR.iterdir(): try: if folder.is_dir() and folder.stat().st_mtime < cutoff: shutil.rmtree(folder, ignore_errors=True) except OSError: continue # yt-dlp's words for failures that the visitor's own (signed-in) browser may not have: YouTube distrusting this # server ("confirm you're not a bot", too many requests, or its newer "This content isn't available, try again # later"), an age check, or a player challenge / format problem on this server. A private or removed video fails # everywhere, so those stay final. _BROWSER_MAY_WORK = ("not a bot", "sign in to confirm", "http error 429", "too many requests", "content isn't available", "confirm your age", "age-restricted", "inappropriate for some users", "javascript runtime", "challenge solving failed", "n challenge", "signature solving failed", "requested format is not available") def _is_blocked(exc: BaseException) -> bool: """Whether the website should try the visitor's own browser (the extension) after this failure.""" text = str(exc.__cause__ or exc).lower().replace("’", "'") # yt-dlp's own message, not our summary of it return any(needle in text for needle in _BROWSER_MAY_WORK) def youtube(url: str) -> tuple[dict[str, Any], list[str]]: """A YouTube link -> the song's original audio (no GPU time). Failures come back as {"error", "reason"}.""" import uuid from stemdeck import youtube as yt from stemdeck.settings import get_config, get_settings cfg, settings = get_config(), get_settings() _clean_old_downloads() try: canonical = yt.canonical_url(url or "") if not _youtube_allowed(time.time()): log.warning("YouTube downloads: hourly limit reached") return {"error": "This site has fetched a lot of YouTube songs this hour. Try again later.", "reason": YOUTUBE_BLOCKED}, [] folder = YOUTUBE_DIR / uuid.uuid4().hex path, info = yt.download_song(canonical, folder, settings, cfg.max_duration_sec, cfg.max_upload_mb * 1024 * 1024, lambda _done, _text: None) except yt.YouTubeError as exc: detail = str(exc.__cause__ or exc)[:300] # yt-dlp's own words, for diagnosing (never cookie contents) log.warning("YouTube download failed: %s", detail) if _is_blocked(exc): return {"error": "YouTube is blocking downloads from this server right now.", "reason": YOUTUBE_BLOCKED, "detail": detail}, [] return {"error": str(exc), "detail": detail}, [] except Exception: # noqa: BLE001 - logged in full here, summarised for the visitor log.exception("YouTube download failed") return {"error": "Couldn't get this song from YouTube. Try again, or upload the file."}, [] log.info("YouTube song ready: %s (%.0f s, %.1f MB)", info.video_id, info.duration_sec or 0, path.stat().st_size / 1e6) return {"title": info.title, "artist": info.artist, "duration_sec": info.duration_sec, "url": canonical, "file": path.name}, [str(path)] def _qualities() -> list[str]: from stemdeck.settings import get_config return list(get_config().qualities) def _extractors() -> list[str]: from stemdeck.settings import get_config return list(get_config().extractors) # Gradio keeps a copy of every upload and returned stem: forget them after an hour (checked hourly). with gr.Blocks(title="StemDeck GPU service", delete_cache=(3600, 3600)) as demo: gr.Markdown("# StemDeck GPU service\nSplits songs into stems for the StemDeck website. " "You can also try it here: choose a song and a quality.") with gr.Row(): song = gr.File(type="filepath", label="Song") # as uploaded: gr.Audio may re-encode it quality = gr.Radio(_qualities(), value=_qualities()[0], label="Quality") run = gr.Button("Split into stems", variant="primary") meta_out = gr.JSON(label="Details") files_out = gr.File(file_count="multiple", label="Stems") run.click(split, [song, quality], [meta_out, files_out], api_name="split") with gr.Accordion("Extract more instruments from one stem (used by the website)", open=False): stem_in = gr.File(type="filepath", label="Stem") source_in = gr.Textbox(value="other", label="Stem name") existing_in = gr.Textbox(value="[]", label="Names of the song's other stems (JSON list)") extractor_in = gr.Dropdown(_extractors(), value=_extractors()[0] if _extractors() else None, label="Extractor") extract_btn = gr.Button("Extract") extract_meta = gr.JSON(label="Details") extract_files = gr.File(file_count="multiple", label="New stems") extract_btn.click(extract, [stem_in, source_in, existing_in, extractor_in], [extract_meta, extract_files], api_name="extract") with gr.Accordion("Get a song from a YouTube link (used by the website)", open=False): link_in = gr.Textbox(label="YouTube link", placeholder="https://www.youtube.com/watch?v=…") link_btn = gr.Button("Get the song") link_meta = gr.JSON(label="Details") link_files = gr.File(file_count="multiple", label="Song") # Its own queue lane: a download never waits behind a GPU job, and uses no GPU time. link_btn.click(youtube, [link_in], [link_meta, link_files], api_name="youtube", concurrency_limit=4, concurrency_id="youtube") demo.queue(default_concurrency_limit=1, max_size=20) if __name__ == "__main__": demo.launch(max_file_size="100mb", show_error=True)