Spaces:
Sleeping
Sleeping
Update js/app.py
Browse files51 unmodified lines5253545556575838 unmodified lines97989910010110210310478 unmodified lines1831841851861871881891901911921931941955 unmodified lines2012022032042052062 unmodified lines2092102112122132142152162172182192202212222232242252262272282292302312322 unmodified lines23523623723823924024124224324424524624724824925025125225351 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".MODEL_NAME = "htdemucs"_model = None # populated at startup38 unmodified lines"""global _modelif _model is None:# Optimize CPU threads for Hugging Face Spaces (2 vCPUs)torch.set_num_threads(2)_model = get_model(MODEL_NAME)_model.eval()# CPU-only inference β Spaces free tier has no GPU.78 unmodified linesdef encode_to_mp3(wav_path: Path, mp3_path: Path):"""Encodes a WAV file to a lightweight 128k MP3 file for fast browser preview."""cmd = ["ffmpeg", "-y","-i", str(wav_path),"-codec:a", "libmp3lame","-b:a", "128k",str(mp3_path)]subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)5 unmodified linesThis is CPU-bound and blocking, so it's always called viaasyncio.to_thread from the worker loop β never directly in anasync function."""model = load_model()out_dir = job_dir(job.id)2 unmodified lineswav = load_audio_via_ffmpeg(input_path, model.samplerate)job.status = JobStatus.PROCESSINGjob.progress = 15with torch.no_grad():sources = apply_model(model,wav[None],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, vocalsstem_names = model.sources # ["drums", "bass", "other", "vocals"]stem_tensors = {name: sources[i] for i, name in enumerate(stem_names)}job.progress = 92if job.mode == "4stem":for name, tensor in stem_tensors.items():2 unmodified linesencode_to_mp3(wav_path, out_dir / f"{name}.mp3")job.stems = stem_nameselse:# 2-stem: vocals vs everything else (original mix minus vocals)vocals = stem_tensors["vocals"]instrumental = wav - vocalsvocals_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 = 10051 unmodified lines52535455565758596038 unmodified lines9910010110210310410510610710810911078 unmodified lines1891901911921931941951961971981992002012022035 unmodified lines2092102112122132142152162172182192202212222 unmodified lines2252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642 unmodified lines26726826927027127227327427527627727827928028128228328428528628728828929029151 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_ft"_model = None # populated at startup38 unmodified lines"""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.78 unmodified linesdef 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",str(mp3_path)]subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)5 unmodified linesThis 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)2 unmodified lineswav = 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():2 unmodified linesencode_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 = 100
js/app.py+64-26