Spaces:
Sleeping
Sleeping
Update js/app.py
Browse files16 unmodified lines1718192021222324252627282960 unmodified lines90919291929394959697989394959697102103104989910010110210310410510610710810911011111211311411511611011711811947 unmodified lines1671681691641651701711721731741751761771781791801811821831841731851861871881891781901911921931941951821961971981991 unmodified line2012022031902042052061931942072082092102112122132142152162172 unmodified lines22022122222322422522622722822923023123223320623423520820921021121221321421521621721821923623723823924024124224324424524624724824925025125222125325425525625725822622725926026123023123223326226326426526626726826923727027127227327427527627727827928028124328228328424624724824925028528628728828929029129229325325425529429529629725725829829926030030130230330430530630726426526626730830931027027127227331131231331431531627928028128228328428528628728831731831932032132232332432532632732832929233033133233316 unmodified lines"""
import asyncioimport gcimport osimport shutilimport subprocessimport timeimport uuidfrom concurrent.futures import ThreadPoolExecutorfrom contextlib import asynccontextmanagerfrom enum import Enumfrom pathlib import Path60 unmodified lines
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. Loads htdemucs_ft once at startup and tunes PyTorch for maximum single-machine CPU throughput. """ global _model if _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)
# 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() # CPU-only inference β Spaces free tier has no GPU. _model.to("cpu") return _model
47 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 target sample rate using the system FFmpeg CLI, then loads it with torchaudio using the soundfile backend. This avoids torchaudio shared library issues. sample rate using FFmpeg, then loads it with torchaudio.
pcm_f32le (32-bit float PCM) is used instead of pcm_s16le so that the data arrives in memory already as float32 β this skips the per-sample int16 β float normalisation step that soundfile/torchaudio would 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_s16le", "-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) 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 wav finally:1 unmodified line temp_wav.unlink()
def encode_to_mp3(wav_path: Path, mp3_path: Path):def encode_to_mp3(wav_path: Path, mp3_path: Path) -> None: """ 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. Runs with multiple ffmpeg threads so each encode completes as quickly as possible (encodes are also parallelised across stems in 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 lines subprocess.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 encodes MP3 for a single stem. Each stem goes to its own file so these calls 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):def run_separation(job: Job, input_path: Path) -> None: """ 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.
Accuracy improvements over the naive approach: 1. Per-channel amplitude normalisation before inference β puts every upload in the amplitude range the model was trained on, which reduces 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 artefacts that waveform subtraction introduces at transient boundaries. Runs Demucs on the input file and writes stem WAVs + 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 WAV-save + MP3-encode across all stems in parallel, cutting post-inference time by up to 4Γ on 4-stem.
β 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() 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.status = JobStatus.PROCESSING job.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,) # ββ 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 downmix wav_norm = (wav - ref_mean) / ref_std
del wav # original no longer needed gc.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 wav_norm[None], # add batch dim: (1, 2, samples) device="cpu", progress=False, split=True, # chunk-process to bound peak memory overlap=0.25, # 25 % chunk overlap β good accuracy/speed balance num_workers=0, # no subprocess workers on HF Spaces )[0] # remove batch dim
split=True, overlap=0.25, # 25 % overlap β accuracy/speed sweet-spot segment=model.samplerate * 10, # 10-second chunks num_workers=0, # no subprocesses on HF Spaces )[0] # drop batch dim: (stems, 2, samples) del wav_norm gc.collect() job.progress = 82
# ββ De-normalise βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ # Recover the original amplitude scale before saving. sources = sources_norm * ref_std + ref_mean # ββ 4. De-normalise (in-place to avoid a full-tensor copy) ββββββββββββββββ sources_norm.mul_(ref_std).add_(ref_mean) # sources_norm is now denormalised sources = sources_norm # rename for clarity
# sources shape: (n_stems, channels, samples) e.g. 4 Γ 2 Γ N stem_names = list(model.sources) # ["drums", "bass", "other", "vocals"] 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": 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") stems_to_write = list(stem_tensors.items()) # [(name, tensor), β¦] job.stems = stem_names else: # 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"] 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")
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 thread
job.progress = 100 job.status = JobStatus.DONE job.status = JobStatus.DONE
async def job_worker():js/app.py+110-72