Spaces:
Sleeping
Sleeping
Update js/app.py
Browse files51 unmodified lines5253545556555758596038 unmodified lines9910010110010110210310410510610710810911078 unmodified lines1891901911861921931941951961971981991922002012022035 unmodified lines2092102112122132142152162172182192202212222 unmodified lines2252262272122282292302312322332342352362372382392402152412422172432442452202212222232242462472482492502512522532542552562572262582592602292612622632642 unmodified lines26726826923823924024127027127227327427527627727827928024324424524624728128228328428528624925028728828929029151 unmodified lines# 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".# htdemucs_ft is the fine-tuned checkpoint of htdemucs β same speed,# measurably better separation quality on most music genres.MODEL_NAME = "htdemucs"MODEL_NAME = "htdemucs_ft"
_model = None # populated at startup
38 unmodified lines """ global _model if _model is None: # Optimize CPU threads for Hugging Face Spaces (2 vCPUs) torch.set_num_threads(2) # 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.78 unmodified lines
def encode_to_mp3(wav_path: Path, mp3_path: Path): """ Encodes a WAV file to a lightweight 128k MP3 file for fast browser preview. 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", "128k", "-b:a", "192k", str(mp3_path) ] subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)5 unmodified lines 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. """ model = load_model() out_dir = job_dir(job.id)2 unmodified lines wav = load_audio_via_ffmpeg(input_path, model.samplerate)
job.status = JobStatus.PROCESSING job.progress = 15 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,) ref_mean = ref.mean() ref_std = ref.std().clamp(min=1e-8) wav_norm = (wav - ref_mean) / ref_std
job.progress = 20
with torch.no_grad(): sources = apply_model( sources_norm = apply_model( model, wav[None], wav_norm[None], # add batch dim device="cpu", progress=False, split=True, overlap=0.25, )[0] # sources shape: (stems, channels, samples) in model.sources order # htdemucs order is: drums, bass, other, vocals 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
job.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 Γ N stem_names = 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)}
job.progress = 92 job.progress = 88
if job.mode == "4stem": for name, tensor in stem_tensors.items():2 unmodified lines encode_to_mp3(wav_path, out_dir / f"{name}.mp3") job.stems = stem_names else: # 2-stem: vocals vs everything else (original mix minus vocals) vocals = stem_tensors["vocals"] instrumental = wav - vocals # 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) 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") encode_to_mp3(inst_wav, out_dir / "instrumental.mp3")
job.stems = ["vocals", "instrumental"]
job.progress = 100js/app.py+64-26