Spaces:
Sleeping
Sleeping
Delete app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313"""StemSplit Backend — FastAPI service that runs Demucs (htdemucs) foraudio source separation. Designed to run as a Hugging Face SpacesDocker 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 asyncioimport osimport shutilimport timeimport uuidfrom contextlib import asynccontextmanagerfrom enum import Enumfrom pathlib import Pathfrom typing import Optional
import torchimport torchaudiofrom demucs.apply import apply_modelfrom demucs.audio import save_audiofrom demucs.pretrained import get_modelfrom fastapi import FastAPI, File, HTTPException, UploadFilefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponsefrom pydantic import BaseModel
# --------------------------------------------------------------------------# Config# --------------------------------------------------------------------------
TMP_ROOT = Path("/tmp/stemsplit")TMP_ROOT.mkdir(parents=True, exist_ok=True)
MAX_UPLOAD_BYTES = 25 * 1024 * 1024 # 25 MB — keep CPU jobs short enough to finishALLOWED_EXTENSIONS = {".mp3", ".wav", ".m4a", ".flac", ".ogg"}JOB_TTL_SECONDS = 30 * 60 # delete job files/state 30 min after completionSWEEP_INTERVAL_SECONDS = 5 * 60
# Demucs model name. htdemucs is Meta's best general-purpose free model# and natively separates into 4 stems: vocals, drums, bass, other.# For "2-stem" mode we just sum drums+bass+other into "instrumental".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 -> JobJOBS: dict[str, Job] = {}# the actual asyncio queue of job_ids waiting to be processedQUEUE: asyncio.Queue[str] = asyncio.Queue()
# --------------------------------------------------------------------------# Model loading# --------------------------------------------------------------------------
def load_model(): """ Loads htdemucs once at startup. Loading takes a while on first call (downloads + initializes weights), which is why we do it once in a lifespan hook rather than per-request.
NOTE: in the Dockerfile we pre-download the model weights into the image at build time (see Dockerfile), so this call at runtime just reads them from the local torch hub cache instead of hitting the network on every cold start. """ global _model if _model is None: _model = get_model(MODEL_NAME) _model.eval() # CPU-only inference — Spaces free tier has no GPU. _model.to("cpu") return _model
@asynccontextmanagerasync def lifespan(app: FastAPI): load_model() worker_task = asyncio.create_task(job_worker()) sweeper_task = asyncio.create_task(job_sweeper()) yield worker_task.cancel() sweeper_task.cancel()
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 run_separation(job: Job, input_path: Path): """ Runs Demucs on the input file and writes stem WAVs to the job dir. This is CPU-bound and blocking, so it's always called via asyncio.to_thread from the worker loop — never directly in an async function. """ model = load_model() out_dir = job_dir(job.id) out_dir.mkdir(parents=True, exist_ok=True)
wav, sr = torchaudio.load(str(input_path))
# Demucs expects stereo; duplicate channel if the upload is mono. if wav.shape[0] == 1: wav = wav.repeat(2, 1)
# Resample to the model's expected sample rate if needed. if sr != model.samplerate: wav = torchaudio.functional.resample(wav, sr, model.samplerate)
job.status = JobStatus.PROCESSING job.progress = 10
def progress_callback(state): # apply_model calls this with a dict containing 'segment_offset' # and 'audio_length' we can use for a coarse progress estimate. try: frac = state.get("segment_offset", 0) / max(state.get("audio_length", 1), 1) job.progress = 10 + int(frac * 80) # 10-90% during inference except Exception: pass
with torch.no_grad(): sources = apply_model( model, wav[None], device="cpu", progress=False, callback=progress_callback, split=True, overlap=0.25, )[0] # sources shape: (stems, channels, samples) in model.sources order # htdemucs order is: drums, bass, other, vocals
stem_names = model.sources # ["drums", "bass", "other", "vocals"] stem_tensors = {name: sources[i] for i, name in enumerate(stem_names)}
job.progress = 92
if job.mode == "4stem": for name, tensor in stem_tensors.items(): save_audio(tensor, str(out_dir / f"{name}.wav"), model.samplerate) job.stems = stem_names else: # 2-stem: vocals vs everything else summed together vocals = stem_tensors["vocals"] instrumental = stem_tensors["drums"] + stem_tensors["bass"] + stem_tensors["other"] save_audio(vocals, str(out_dir / "vocals.wav"), model.samplerate) save_audio(instrumental, str(out_dir / "instrumental.wav"), model.samplerate) job.stems = ["vocals", "instrumental"]
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 = "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}.wav" 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/wav", filename=f"{stem}.wav", )app.pyDeleted-313