Spaces:
Sleeping
Sleeping
Update js/app.py
Browse files94 unmodified lines959697989910010110210310410510610761 unmodified lines16917017117217317417517617717817918018118218318418518618714 unmodified lines2022032042052062072082092102112122132142152162172182191 unmodified line22122222322422522622722822923023123240 unmodified lines2732742752762772782792802 unmodified lines28328428528628728828994 unmodified lines"""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 = True61 unmodified linesDecodes any audio format to a temporary stereo WAV file at the targetsample rate using FFmpeg, then loads it with torchaudio.Uses pcm_s16le (universally supported by every soundfile/torchaudiobuild) rather than pcm_f32le whose IEEE-float WAV header supportvaries across library versions on the HF Docker image."""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,"-i", str(input_path),"-vn","-acodec", "pcm_s16le", # universally supported 16-bit PCM"-ac", "2","-ar", str(target_sr),str(temp_wav)14 unmodified linesdef 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",str(mp3_path)]subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)1 unmodified linedef _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")40 unmodified lines# ββ 3. Separate (the expensive step) βββββββββββββββββββββββββββββββββββββββ# segment= is intentionally omitted: apply_model reads model.segment# (architecture-native chunk size) automatically.# overlap=0.1 (10 %) instead of the default 0.25 reduces the number of# chunks by ~20 % with negligible quality loss on normal music._N_THREADS = max(os.cpu_count() or 2, 2)with torch.no_grad():sources_norm = apply_model(2 unmodified linesdevice="cpu",progress=False,split=True,overlap=0.1, # reduced from 0.25 β 20 % fewer chunksnum_workers=0, # no subprocesses on HF Spaces)[0] # drop batch dim: (stems, 2, samples)del wav_norm94 unmodified lines959697989910010110210310410561 unmodified lines16716816917017117217317417517617717817918018118218318418514 unmodified lines2002012022032042052062072082092102112122132142151 unmodified line21721821922022122222322422522622722840 unmodified lines2692702712722732742752762 unmodified lines27928028128228328428594 unmodified lines"""global _modelif _model is None:# Cap PyTorch intra-op threads to 2 (matching the Hugging Face Spaces free CPU# tier core limit) to prevent CPU CFS scheduler throttling. Capping inter-op# threads to 1 avoids overhead. This prevents thrashing and speeds up inference.torch.set_num_threads(2)torch.set_num_interop_threads(1)# Force Intel oneDNN (MKL-DNN) fast-path math.torch.backends.mkldnn.enabled = True61 unmodified linesDecodes any audio format to a temporary stereo WAV file at the targetsample rate using FFmpeg, then loads it with torchaudio.Uses pcm_s24le (universally supported 24-bit integer PCM) to preservedynamic range, rather than pcm_f32le whose IEEE-float WAV header supportvaries across library versions on the HF Docker image."""temp_wav = input_path.with_suffix(".temp.wav")n_threads = "2"try:cmd = ["ffmpeg", "-y","-threads", n_threads,"-i", str(input_path),"-vn","-acodec", "pcm_s24le", # high-fidelity 24-bit PCM"-ac", "2","-ar", str(target_sr),str(temp_wav)14 unmodified linesdef encode_to_mp3(wav_path: Path, mp3_path: Path) -> None:"""Encodes a WAV file to a 320 kbps MP3 for high-quality browser preview.Runs with 1 thread because multiple encode tasks are parallelised in a threadpool across stems, preventing CPU scheduling contention and thrashing."""cmd = ["ffmpeg", "-y","-threads", "1","-i", str(wav_path),"-codec:a", "libmp3lame","-b:a", "320k",str(mp3_path)]subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)1 unmodified linedef _save_stem(name: str, tensor: torch.Tensor, out_dir: Path, samplerate: int) -> None:"""Helper run inside the ThreadPoolExecutor β saves 24-bit WAV then encodes320 kbps MP3 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, bits_per_sample=24)encode_to_mp3(wav_path, out_dir / f"{name}.mp3")40 unmodified lines# ββ 3. Separate (the expensive step) βββββββββββββββββββββββββββββββββββββββ# segment= is intentionally omitted: apply_model reads model.segment# (architecture-native chunk size) automatically.# overlap=0.25 (25 %) provides the default smooth segment crossfades for# optimal, studio-grade separation without boundary artifacts._N_THREADS = max(os.cpu_count() or 2, 2)with torch.no_grad():sources_norm = apply_model(2 unmodified linesdevice="cpu",progress=False,split=True,overlap=0.25, # default high-quality overlapnum_workers=0, # no subprocesses on HF Spaces)[0] # drop batch dim: (stems, 2, samples)del wav_norm
js/app.py+20-24