Spaces:
Sleeping
Sleeping
Update js/app.py
Browse files16 unmodified lines171819202122232425262760 unmodified lines88899091929394959697989910010110210310410510610710810911011111211347 unmodified lines1611621631641651661671681691701711721731741751761771781791801811821831841851 unmodified line1871881891901911921931941951961971981992002 unmodified lines20320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429516 unmodified lines"""import asyncioimport osimport shutilimport subprocessimport timeimport uuidfrom contextlib import asynccontextmanagerfrom enum import Enumfrom pathlib import Path60 unmodified linesdef 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 alifespan hook rather than per-request.NOTE: in the Dockerfile we pre-download the model weights into theimage at build time (see Dockerfile), so this call at runtime justreads them from the local torch hub cache instead of hitting thenetwork on every cold start."""global _modelif _model is None:# Use all available logical CPUs β on HF Spaces free tier this is# typically 2β4 vCPUs, so letting PyTorch use them all is a free# speed-up with no code complexity cost.n_threads = max(os.cpu_count() or 2, 2)torch.set_num_threads(n_threads)torch.set_num_interop_threads(min(n_threads, 4))_model = get_model(MODEL_NAME)_model.eval()# CPU-only inference β Spaces free tier has no GPU._model.to("cpu")return _model47 unmodified linesdef load_audio_via_ffmpeg(input_path: Path, target_sr: int) -> torch.Tensor:"""Decodes any audio format to a temporary stereo WAV file at the targetsample rate using the system FFmpeg CLI, then loads it with torchaudiousing the soundfile backend. This avoids torchaudio shared library issues."""temp_wav = input_path.with_suffix(".temp.wav")try:cmd = ["ffmpeg", "-y","-i", str(input_path),"-vn","-acodec", "pcm_s16le","-ac", "2","-ar", str(target_sr),str(temp_wav)]result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)if result.returncode != 0:error_msg = result.stderr.decode("utf-8", errors="ignore")raise RuntimeError(f"FFmpeg conversion failed: {error_msg}")wav, _ = torchaudio.load(str(temp_wav))return wavfinally:1 unmodified linetemp_wav.unlink()def encode_to_mp3(wav_path: Path, mp3_path: Path):"""Encodes a WAV file to a 192 kbps MP3 for browser preview.192 k is the sweet-spot: transparent quality for most listeners,roughly half the file size of lossless, and encodes fast on CPU."""cmd = ["ffmpeg", "-y","-i", str(wav_path),"-codec:a", "libmp3lame","-b:a", "192k",2 unmodified linessubprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)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 viaasyncio.to_thread from the worker loop β never directly in anasync function.Accuracy improvements over the naive approach:1. Per-channel amplitude normalisation before inference β puts everyupload in the amplitude range the model was trained on, whichreduces bleeding between stems on very quiet or very loud tracks.2. 2-stem instrumental = drums + bass + other instead of mix - vocals.Summing individual stems avoids the phase-cancellation artefactsthat waveform subtraction introduces at transient boundaries."""model = load_model()out_dir = job_dir(job.id)out_dir.mkdir(parents=True, exist_ok=True)wav = load_audio_via_ffmpeg(input_path, model.samplerate)job.status = JobStatus.PROCESSINGjob.progress = 10# ββ Normalise ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Compute per-channel mean/std on the mono downmix as a stable reference# so that the normalisation doesn't flip phase on multi-channel files.ref = wav.mean(0) # (samples,)ref_mean = ref.mean()ref_std = ref.std().clamp(min=1e-8)wav_norm = (wav - ref_mean) / ref_stdjob.progress = 20with torch.no_grad():sources_norm = apply_model(model,wav_norm[None], # add batch dimdevice="cpu",progress=False,split=True, # chunk-process to bound peak memoryoverlap=0.25, # 25 % chunk overlap β good accuracy/speed balancenum_workers=0, # no subprocess workers on HF Spaces)[0] # remove batch dimjob.progress = 82# ββ De-normalise βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Recover the original amplitude scale before saving.sources = sources_norm * ref_std + ref_mean# sources shape: (n_stems, channels, samples) e.g. 4 Γ 2 Γ Nstem_names = list(model.sources) # ["drums", "bass", "other", "vocals"]stem_tensors = {name: sources[i] for i, name in enumerate(stem_names)}job.progress = 88if job.mode == "4stem":for name, tensor in stem_tensors.items():wav_path = out_dir / f"{name}.wav"save_audio(tensor, str(wav_path), model.samplerate)encode_to_mp3(wav_path, out_dir / f"{name}.mp3")job.stems = stem_nameselse:# 2-stem: sum the three non-vocal stems instead of subtracting# vocals from the mix β avoids phase-cancellation artefacts at# transient boundaries (kick hits, consonants, etc.).vocals = stem_tensors["vocals"]instrumental = (stem_tensors["drums"]+ stem_tensors["bass"]+ stem_tensors["other"])vocals_wav = out_dir / "vocals.wav"inst_wav = out_dir / "instrumental.wav"save_audio(vocals, str(vocals_wav), model.samplerate)save_audio(instrumental, str(inst_wav), model.samplerate)encode_to_mp3(vocals_wav, out_dir / "vocals.mp3")encode_to_mp3(inst_wav, out_dir / "instrumental.mp3")job.stems = ["vocals", "instrumental"]job.progress = 100job.status = JobStatus.DONEasync def job_worker():16 unmodified lines1718192021222324252627282960 unmodified lines9091929394959697989910010110210310410510610710810911011111211311411511611711811947 unmodified lines1671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981991 unmodified line2012022032042052062072082092102112122132142152162172 unmodified lines22022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233316 unmodified lines"""import asyncioimport gcimport osimport shutilimport subprocessimport timeimport uuidfrom concurrent.futures import ThreadPoolExecutorfrom contextlib import asynccontextmanagerfrom enum import Enumfrom pathlib import Path60 unmodified linesdef load_model():"""Loads htdemucs_ft once at startup and tunes PyTorch for maximumsingle-machine CPU throughput."""global _modelif _model is None:n_threads = max(os.cpu_count() or 2, 2)# Give PyTorch every logical CPU for intra-op parallelism# (matrix muls, convolutions) and cap inter-op at 4 so we# don't over-subscribe the scheduler.torch.set_num_threads(n_threads)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 _model47 unmodified linesdef load_audio_via_ffmpeg(input_path: Path, target_sr: int) -> torch.Tensor:"""Decodes any audio format to a temporary stereo WAV file at the targetsample rate using FFmpeg, then loads it with torchaudio.pcm_f32le (32-bit float PCM) is used instead of pcm_s16le so thatthe data arrives in memory already as float32 β this skips theper-sample int16 β float normalisation step that soundfile/torchaudiowould otherwise perform in Python."""temp_wav = input_path.with_suffix(".temp.wav")n_threads = str(max(os.cpu_count() or 2, 2))try:cmd = ["ffmpeg", "-y","-threads", n_threads, # parallel demux / decode"-i", str(input_path),"-vn","-acodec", "pcm_f32le", # 32-bit float β no intβfloat step later"-ac", "2","-ar", str(target_sr),str(temp_wav)]result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)if result.returncode != 0:error_msg = result.stderr.decode("utf-8", errors="ignore")raise RuntimeError(f"FFmpeg conversion failed: {error_msg}")wav, _ = torchaudio.load(str(temp_wav))return wavfinally:1 unmodified linetemp_wav.unlink()def encode_to_mp3(wav_path: Path, mp3_path: Path) -> None:"""Encodes a WAV file to a 192 kbps MP3 for browser preview.Runs with multiple ffmpeg threads so each encode completes asquickly as possible (encodes are also parallelised across stemsin run_separation via ThreadPoolExecutor)."""n_threads = str(max(os.cpu_count() or 2, 2))cmd = ["ffmpeg", "-y","-threads", n_threads,"-i", str(wav_path),"-codec:a", "libmp3lame","-b:a", "192k",2 unmodified linessubprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)def _save_stem(name: str, tensor: torch.Tensor, out_dir: Path, samplerate: int) -> None:"""Helper run inside the ThreadPoolExecutor β saves WAV then encodesMP3 for a single stem. Each stem goes to its own file so thesecalls are fully independent and safe to parallelise."""wav_path = out_dir / f"{name}.wav"save_audio(tensor, str(wav_path), samplerate)encode_to_mp3(wav_path, out_dir / f"{name}.mp3")def run_separation(job: Job, input_path: Path) -> None:"""Runs Demucs on the input file and writes stem WAVs + MP3s to thejob 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 keepspeak RSS low and prevents the GC from pausing mid-inference.β’ In-place de-normalise (mul_ / add_) avoids a full sources copy.β’ ThreadPoolExecutor fans out WAV-save + MP3-encode across all stemsin parallel, cutting post-inference time by up to 4Γ on 4-stem.β Accuracy βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ’ Per-channel amplitude normalisation before inference keeps everyupload 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.PROCESSINGjob.progress = 10# ββ 2. Normalise ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Mono downmix as a stable amplitude reference; clamped std prevents# division-by-zero on near-silent clips.ref = wav.mean(0)ref_mean = ref.mean()ref_std = ref.std().clamp(min=1e-8)del ref # free the mono downmixwav_norm = (wav - ref_mean) / ref_stddel wav # original no longer neededgc.collect()job.progress = 20# ββ 3. Separate (the expensive step) βββββββββββββββββββββββββββββββββββββββ# segment=441000 β 10 s chunks at 44100 Hz. Larger chunks mean# fewer FFT boundary transitions and fewer forward passes overall# while still bounding peak memory to ~2 GB for a 25 MB upload._N_THREADS = max(os.cpu_count() or 2, 2)with torch.no_grad():sources_norm = apply_model(model,wav_norm[None], # add batch dim: (1, 2, samples)device="cpu",progress=False,split=True,overlap=0.25, # 25 % overlap β accuracy/speed sweet-spotsegment=model.samplerate * 10, # 10-second chunksnum_workers=0, # no subprocesses on HF Spaces)[0] # drop batch dim: (stems, 2, samples)del wav_normgc.collect()job.progress = 82# ββ 4. De-normalise (in-place to avoid a full-tensor copy) ββββββββββββββββsources_norm.mul_(ref_std).add_(ref_mean) # sources_norm is now denormalisedsources = sources_norm # rename for claritystem_names = list(model.sources) # ["drums", "bass", "other", "vocals"]stem_tensors = {name: sources[i] for i, name in enumerate(stem_names)}del sources, sources_normgc.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_nameselse: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 = min(len(stems_to_write), _N_THREADS)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 threadjob.progress = 100job.status = JobStatus.DONEasync def job_worker():
js/app.py+110-72