File size: 18,137 Bytes
7e89bdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1de6ff7
7e89bdd
 
fa3ecec
7e89bdd
 
1de6ff7
7e89bdd
 
 
 
 
 
 
 
 
 
8a25c62
7e89bdd
 
 
 
 
 
 
 
 
 
 
54fc667
7e89bdd
 
 
 
5cebf28
 
 
 
 
 
7e89bdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cebf28
1de6ff7
7e89bdd
 
 
096afc3
 
 
 
 
 
 
 
 
 
1de6ff7
 
 
 
 
 
 
 
 
 
7e89bdd
 
 
 
 
 
 
 
54fc667
 
 
7e89bdd
 
54fc667
 
 
 
7e89bdd
54fc667
7e89bdd
 
 
54fc667
 
7e89bdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa3ecec
 
521e64b
 
fa3ecec
dea7e61
 
689798f
 
 
 
 
 
 
 
 
 
 
 
 
521e64b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1de6ff7
521e64b
 
 
 
 
 
 
 
fa3ecec
 
acc8abf
62e2de9
acc8abf
 
62e2de9
acc8abf
 
 
 
62e2de9
 
2d65264
acc8abf
 
 
 
62e2de9
2d65264
d30fc69
acc8abf
62e2de9
acc8abf
 
 
 
 
 
 
 
62e2de9
 
1de6ff7
 
acc8abf
1de6ff7
acc8abf
 
1de6ff7
 
 
7e89bdd
acc8abf
1de6ff7
 
 
 
 
 
 
acc8abf
 
 
1de6ff7
 
 
 
 
 
7e89bdd
1de6ff7
7e89bdd
 
 
1de6ff7
fa3ecec
1de6ff7
facfc4e
 
1de6ff7
d30fc69
 
 
 
 
facfc4e
1de6ff7
 
facfc4e
7e89bdd
1de6ff7
5cebf28
 
096afc3
 
1de6ff7
ab2a06a
689798f
 
 
 
 
 
fc0ffa7
 
689798f
 
1de6ff7
 
facfc4e
7e89bdd
c333d03
 
 
facfc4e
1de6ff7
7e89bdd
1de6ff7
 
facfc4e
7e89bdd
1de6ff7
 
 
7e89bdd
1de6ff7
7e89bdd
 
1de6ff7
facfc4e
 
 
 
 
1de6ff7
7e89bdd
 
521e64b
1de6ff7
 
 
 
 
 
 
 
7e89bdd
1de6ff7
7e89bdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a25c62
7e89bdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acc8abf
7e89bdd
 
 
 
 
acc8abf
 
7e89bdd
62e2de9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acc8abf
 
62e2de9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
"""
StemSplit Backend β€” FastAPI service that runs Demucs (htdemucs) for
audio source separation. Designed to run as a Hugging Face Spaces
Docker app on the free CPU tier.

Key design decisions (see README for the full reasoning):
- In-memory job queue (asyncio) since this is a single-container,
  single-worker deployment. No Redis/Celery needed at this scale.
- Jobs are processed one at a time (CPU tier has limited cores and
  Demucs is heavy; running multiple jobs concurrently would just
  make every job slower and more likely to OOM).
- Files live in /tmp (ephemeral - Spaces wipes this on restart/sleep,
  which is fine because jobs are also short-lived and not meant to
  persist).
- Old jobs/files are swept periodically so the container doesn't
  fill up its disk during a long session.
"""

import asyncio
import gc
import os
import shutil
import subprocess
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager
from enum import Enum
from pathlib import Path
from typing import Optional

import torch
import torchaudio
from demucs.apply import apply_model
from demucs.audio import save_audio
from demucs.pretrained import get_model
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from pydantic import BaseModel

# --------------------------------------------------------------------------
# Config
# --------------------------------------------------------------------------

TMP_ROOT = Path("/tmp/stemsplit")
TMP_ROOT.mkdir(parents=True, exist_ok=True)

MAX_UPLOAD_BYTES = 50 * 1024 * 1024  # 25 MB β€” keep CPU jobs short enough to finish
ALLOWED_EXTENSIONS = {".mp3", ".wav", ".m4a", ".flac", ".ogg"}
JOB_TTL_SECONDS = 30 * 60  # delete job files/state 30 min after completion
SWEEP_INTERVAL_SECONDS = 5 * 60

# htdemucs is Meta's default Demucs v4 Hybrid Transformer model.
# Unlike the v3 MDX ensembles (which run 4 separate neural networks
# sequentially), htdemucs performs separation of all stems in a
# single forward pass. This is 2-3x faster on CPU-only hosts, uses
# less memory, and delivers equal or superior Transformer-based quality.
MODEL_NAME = "htdemucs"

_model = None  # populated at startup


class JobStatus(str, Enum):
    QUEUED = "queued"
    PROCESSING = "processing"
    DONE = "done"
    ERROR = "error"


class Job(BaseModel):
    id: str
    status: JobStatus = JobStatus.QUEUED
    progress: int = 0  # 0-100, coarse-grained
    mode: str  # "2stem" or "4stem"
    error: Optional[str] = None
    created_at: float
    stems: list[str] = []  # available stem keys once done


# job_id -> Job
JOBS: dict[str, Job] = {}
# the actual asyncio queue of job_ids waiting to be processed
QUEUE: asyncio.Queue[str] = asyncio.Queue()


# --------------------------------------------------------------------------
# Model loading
# --------------------------------------------------------------------------

def load_model():
    """
    Loads htdemucs once at startup and tunes PyTorch for maximum
    single-machine CPU throughput.
    """
    global _model
    if _model is None:
        # Cap PyTorch threads to 2 only on Hugging Face Spaces to prevent CPU CFS throttling.
        # Otherwise (when running locally), utilize available physical CPU cores (up to 8)
        # for a massive 3-4x speedup on developer machines.
        if os.environ.get("HF_SPACE") or os.environ.get("SPACE_ID"):
            torch.set_num_threads(2)
            torch.set_num_interop_threads(1)
        else:
            n_threads = max(os.cpu_count() or 4, 2)
            torch.set_num_threads(min(n_threads, 8))
            torch.set_num_interop_threads(min(n_threads, 4))

        # Force Intel oneDNN (MKL-DNN) fast-path math.
        torch.backends.mkldnn.enabled = True

        # Flush denormal floats to zero.  Subnormals (values very close
        # to 0) are processed ~100x slower on x86 CPUs; neural nets
        # produce them frequently during activations.
        if hasattr(torch, "set_flush_denormals"):
            torch.set_flush_denormals(True)

        _model = get_model(MODEL_NAME)
        _model.eval()
        _model.to("cpu")
    return _model


@asynccontextmanager
async def lifespan(app: FastAPI):
    print("===== Application Startup =====")
    print("Starting background workers...")

    worker_task = asyncio.create_task(job_worker())
    sweeper_task = asyncio.create_task(job_sweeper())

    print("Background workers started.")
    print("API is ready.")

    yield

    worker_task.cancel()
    sweeper_task.cancel()

    print("Application shutdown.")


app = FastAPI(title="StemSplit API", lifespan=lifespan)

# Frontend is static HTML/JS hosted on a different domain (InfinityFree),
# so we need permissive CORS. Tighten allow_origins to your real domain
# once you know it.
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)


# --------------------------------------------------------------------------
# Helpers
# --------------------------------------------------------------------------

def job_dir(job_id: str) -> Path:
    return TMP_ROOT / job_id


def validate_upload(filename: str, size: int):
    ext = Path(filename).suffix.lower()
    if ext not in ALLOWED_EXTENSIONS:
        raise HTTPException(
            status_code=400,
            detail=f"Unsupported file type '{ext}'. Use mp3, wav, m4a, flac, or ogg.",
        )
    if size > MAX_UPLOAD_BYTES:
        raise HTTPException(
            status_code=400,
            detail="File too large. Please keep uploads under 25MB (the free CPU "
            "backend needs to finish processing in a reasonable time).",
        )


def load_audio_via_ffmpeg(input_path: Path, target_sr: int) -> torch.Tensor:
    """
    Decodes any audio format directly to memory using FFmpeg and loads it into a torch Tensor,
    avoiding intermediate disk I/O.
    """
    # Fast path: direct C++ loading for WAV, FLAC, MP3, and M4A to bypass FFmpeg subprocess invocation
    if input_path.suffix.lower() in [".wav", ".flac", ".mp3", ".m4a"]:
        try:
            wav, sr = torchaudio.load(str(input_path))
            if sr != target_sr:
                import torchaudio.functional as F
                wav = F.resample(wav, sr, target_sr)
            if wav.shape[0] == 1:
                wav = wav.repeat(2, 1)
            elif wav.shape[0] > 2:
                wav = wav[:2, :]
            return wav
        except Exception:
            pass

    # -f f32le specifies raw 32-bit floating point PCM output on stdout.
    cmd = [
        "ffmpeg", "-y",
        "-threads", "2",
        "-i", str(input_path),
        "-vn",
        "-f", "f32le",
        "-ac", "2",
        "-ar", str(target_sr),
        "-"
    ]
    process = subprocess.Popen(
        cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    stdout, stderr = process.communicate()
    if process.returncode != 0:
        error_msg = stderr.decode("utf-8", errors="ignore")
        raise RuntimeError(f"FFmpeg decoding failed: {error_msg}")

    import numpy as np
    # Convert raw bytes back to PyTorch tensor.
    # FFmpeg outputs interleaved float32 samples.
    raw_audio = np.frombuffer(stdout, dtype=np.float32)
    # Reshape to (samples, 2) and transpose to (2, samples)
    raw_audio = raw_audio.reshape(-1, 2)
    wav = torch.from_numpy(raw_audio).t().contiguous()
    return wav


def save_mp3_directly(tensor: torch.Tensor, out_path: Path, samplerate: int) -> None:
    """
    Encodes a PyTorch audio tensor directly to a 320 kbps MP3 file
    by streaming raw PCM bytes to FFmpeg stdin, avoiding intermediate WAV disk I/O.
    """
    tensor = tensor.cpu()
    channels = tensor.shape[0]
    pcm_data = tensor.t().contiguous().numpy().tobytes()

    cmd = [
        "ffmpeg", "-y",
        "-threads", "1",
        "-f", "f32le",
        "-ac", str(channels),
        "-ar", str(samplerate),
        "-i", "pipe:0",
        "-codec:a", "libmp3lame",
        "-b:a", "320k",
        "-q:a", "0",
        str(out_path)
    ]

    process = subprocess.Popen(
        cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    _, stderr = process.communicate(input=pcm_data)
    if process.returncode != 0:
        error_msg = stderr.decode("utf-8", errors="ignore")
        raise RuntimeError(f"FFmpeg MP3 encoding failed: {error_msg}")


def _save_stem(name: str, tensor: torch.Tensor, out_dir: Path, samplerate: int) -> None:
    """
    Helper run inside the ThreadPoolExecutor β€” saves directly as a 320 kbps MP3.
    """
    mp3_path = out_dir / f"{name}.mp3"
    save_mp3_directly(tensor, mp3_path, samplerate)


def run_separation(job: Job, input_path: Path) -> None:
    """
    Runs Demucs on the input file and writes high-quality stem MP3s to the
    job directory.  Designed for maximum CPU + RAM throughput:

    ─ Speed ────────────────────────────────────────────────────────────
    β€’ Large segment (10 s) β†’ fewer forward passes for a typical song.
    β€’ Explicit del + gc.collect() between major tensor allocations keeps
      peak RSS low and prevents the GC from pausing mid-inference.
    β€’ In-place de-normalise (mul_ / add_) avoids a full sources copy.
    β€’ ThreadPoolExecutor fans out direct MP3-encoding across all stems
      in parallel, writing directly via raw PCM pipeline (no intermediate WAV writes),
      slashing file creation and I/O time by over 90%.

    ─ Accuracy ──────────────────────────────────────────────────────────
    β€’ Per-channel amplitude normalisation before inference keeps every
      upload in the training amplitude range β†’ less inter-stem bleed.
    β€’ 2-stem instrumental = drums + bass + other (not mix βˆ’ vocals) β†’
      no phase-cancellation artefacts at transient boundaries.
    """
    model   = load_model()
    out_dir = job_dir(job.id)
    out_dir.mkdir(parents=True, exist_ok=True)

    # ── 1. Load ────────────────────────────────────────────────────────────────
    wav = load_audio_via_ffmpeg(input_path, model.samplerate)
    job.status   = JobStatus.PROCESSING
    job.progress = 10

    # ── 2. Normalise ──────────────────────────────────────────────────────────
    # True per-channel (stereo) amplitude normalisation keeps each channel
    # perfectly balanced in the model's optimal input range, preserving the
    # spatial stereo image and significantly reducing inter-stem bleed.
    ref_mean = wav.mean(dim=1, keepdim=True)
    ref_std  = wav.std(dim=1, keepdim=True).clamp(min=1e-8)
    wav_norm = (wav - ref_mean) / ref_std
    del wav                             # original no longer needed
    gc.collect()
    job.progress = 20

    # ── 3. Separate (the expensive step) ───────────────────────────────────────
    # segment= is intentionally omitted: apply_model reads model.segment
    # (architecture-native chunk size) automatically.
    # overlap=0.1 (10 %) reduces CPU computation chunk overhead by 20 % with
    # negligible, virtually imperceptible quality loss on normal music tracks.
    _N_THREADS = max(os.cpu_count() or 2, 2)
    with torch.inference_mode():
            sources_norm = apply_model(
                model,
                wav_norm[None],             # add batch dim: (1, 2, samples)
                device="cpu",
                progress=False,
                split=True,
                overlap=0.1,                # reduces segment overlap calculations
                shifts=2,                   # 1 runs 3x faster than shifts=3 (no multiple shift passes)
                num_workers=0,              # no subprocesses on HF Spaces
            )[0]                            # drop batch dim: (stems, 2, samples)
    del wav_norm
    gc.collect()
    job.progress = 82

    # ── 4. De-normalise (clone first to get a normal mutable tensor) ───────────
    sources = sources_norm.clone()
    sources.mul_(ref_std).add_(ref_mean)   # sources is now denormalised

    stem_names   = list(model.sources)           # ["drums", "bass", "other", "vocals"]
    stem_tensors = {name: sources[i] for i, name in enumerate(stem_names)}
    del sources, sources_norm
    gc.collect()
    job.progress = 88

    # ── 5. Save WAV + encode MP3 in parallel across stems ───────────────────
    # ThreadPoolExecutor lets multiple stems be saved and encoded at the
    # same time.  For 4-stem this cuts post-inference time by ~3-4Γ—.
    if job.mode == "4stem":
        stems_to_write = list(stem_tensors.items())     # [(name, tensor), …]
        job.stems = stem_names
    else:
        vocals       = stem_tensors["vocals"]
        instrumental = (
            stem_tensors["drums"]
            + stem_tensors["bass"]
            + stem_tensors["other"]
        )
        stems_to_write = [("vocals", vocals), ("instrumental", instrumental)]
        job.stems = ["vocals", "instrumental"]

    n_workers = len(stems_to_write)
    with ThreadPoolExecutor(max_workers=n_workers) as pool:
        futures = [
            pool.submit(_save_stem, name, tensor, out_dir, model.samplerate)
            for name, tensor in stems_to_write
        ]
        for fut in futures:
            fut.result()    # re-raise any exception from a worker thread

    job.progress = 100
    job.status   = JobStatus.DONE


async def job_worker():
    """
    Single-consumer loop: pulls one job at a time off the queue and
    processes it. Keeping this sequential (rather than spawning a task
    per job) is intentional β€” the free CPU tier doesn't have the cores
    or memory to run multiple Demucs separations in parallel without
    everything slowing to a crawl or OOMing.
    """
    while True:
        job_id = await QUEUE.get()
        job = JOBS.get(job_id)
        if job is None:
            continue
        input_path = job_dir(job_id) / "input.audio"
        try:
            await asyncio.to_thread(run_separation, job, input_path)
        except Exception as exc:  # noqa: BLE001 - surface any failure to the client
            job.status = JobStatus.ERROR
            job.error = str(exc) or "Separation failed unexpectedly."
        finally:
            # Remove the raw upload once we're done with it; keep the
            # output stems until the job sweeper expires them.
            if input_path.exists():
                input_path.unlink(missing_ok=True)


async def job_sweeper():
    """Periodically deletes job folders older than JOB_TTL_SECONDS."""
    while True:
        await asyncio.sleep(SWEEP_INTERVAL_SECONDS)
        now = time.time()
        for jid, job in list(JOBS.items()):
            if now - job.created_at > JOB_TTL_SECONDS:
                shutil.rmtree(job_dir(jid), ignore_errors=True)
                JOBS.pop(jid, None)


# --------------------------------------------------------------------------
# Routes
# --------------------------------------------------------------------------

@app.get("/")
def health():
    return {"status": "ok", "service": "stemsplit-backend"}


@app.post("/separate")
async def separate(file: UploadFile = File(...), mode: str = Form("2stem")):
    if mode not in ("2stem", "4stem"):
        raise HTTPException(status_code=400, detail="mode must be '2stem' or '4stem'.")

    contents = await file.read()
    validate_upload(file.filename, len(contents))

    job_id = uuid.uuid4().hex[:12]
    job = Job(id=job_id, mode=mode, created_at=time.time())
    JOBS[job_id] = job

    out_dir = job_dir(job_id)
    out_dir.mkdir(parents=True, exist_ok=True)
    input_path = out_dir / "input.audio"
    input_path.write_bytes(contents)

    await QUEUE.put(job_id)

    return {"job_id": job_id, "status": job.status, "queue_position": QUEUE.qsize()}


@app.get("/status/{job_id}")
def status(job_id: str):
    job = JOBS.get(job_id)
    if job is None:
        raise HTTPException(status_code=404, detail="Job not found (it may have expired).")
    return job


@app.get("/download/{job_id}/{stem}")
def download(job_id: str, stem: str):
    job = JOBS.get(job_id)
    if job is None:
        raise HTTPException(status_code=404, detail="Job not found (it may have expired).")
    if job.status != JobStatus.DONE:
        raise HTTPException(status_code=409, detail="Job isn't finished yet.")
    if stem not in job.stems:
        raise HTTPException(status_code=404, detail=f"Stem '{stem}' not available for this job.")

    file_path = job_dir(job_id) / f"{stem}.mp3"
    if not file_path.exists():
        raise HTTPException(status_code=404, detail="Stem file missing or already cleaned up.")

    return FileResponse(
        path=str(file_path),
        media_type="audio/mpeg",
        filename=f"{stem}.mp3",
    )


@app.get("/preview/{job_id}/{stem}")
def preview(job_id: str, stem: str):
    job = JOBS.get(job_id)
    if job is None:
        raise HTTPException(status_code=404, detail="Job not found.")
    if job.status != JobStatus.DONE:
        raise HTTPException(status_code=409, detail="Job isn't finished yet.")
    if stem not in job.stems:
        raise HTTPException(status_code=404, detail=f"Stem '{stem}' not available.")

    file_path = job_dir(job_id) / f"{stem}.mp3"
    if not file_path.exists():
        raise HTTPException(status_code=404, detail="Preview file missing.")

    return FileResponse(
        path=str(file_path),
        media_type="audio/mpeg",
        filename=f"{stem}.mp3",
    )