Download backend/audio_denoise.py from localailb/assistant: direct link, hf CLI and curl.
- Browser
- Download file 7.19 kB
-
https://huggingface.co/spaces/localailb/assistant/resolve/main/backend/audio_denoise.py
- Command line
-
hf download hf://spaces/localailb/assistant/backend/audio_denoise.py
-
curl -L -o audio_denoise.py https://huggingface.co/spaces/localailb/assistant/resolve/main/backend/audio_denoise.py
7.19 kB
| """audio_denoise.py β Background-noise reduction for the STT tab. | |
| Self-contained spectral-gate denoiser (no new dependencies: numpy + scipy, | |
| both already part of the app's stack β scipy is a hard dependency of | |
| librosa, pinned in requirements.txt since this module imports it directly). | |
| Approach: estimate a stationary noise profile from the QUIETEST STFT frames | |
| (β speech pauses), then attenuate every frame's magnitude where it sits near | |
| that noise floor (spectral gating). The cleaned audio is written as 16-bit | |
| PCM WAV β the one format every STT backend (soundfile, whisper-server) reads, | |
| so the cleaned file drops straight into the existing transcribe/save/trim | |
| plumbing. | |
| The module is total: unusable input or a missing scipy degrades to a clean | |
| error, never a traceback. Every import is lazy so a broken optional wheel can | |
| never crash app startup. | |
| """ | |
| from __future__ import annotations | |
| from pathlib import Path | |
| # Named strength presets for the STT tab's noise-reduction picker. Each maps | |
| # to the gate's `strength` (how far the noise floor is pulled down, 0β1): | |
| # gentle (0.55) β light touch: keeps soft consonants / ambience | |
| # medium (0.75) β balanced (the previous default's neighborhood) | |
| # aggressive (0.9) β hard gate: silences pauses, may thin quiet speech | |
| DENOISE_STRENGTH_PRESETS = { | |
| "gentle": 0.55, | |
| "medium": 0.75, | |
| "aggressive": 0.9, | |
| } | |
| DEFAULT_DENOISE_STRENGTH = DENOISE_STRENGTH_PRESETS["aggressive"] | |
| def resolve_strength(value) -> float: | |
| """Map a preset name ('gentle' / 'medium' / 'aggressive') or a raw 0β1 | |
| number (int / float / numeric string) to a gate strength. Anything else | |
| falls back to the aggressive default β the endpoint can never crash on a | |
| bad pick, and the numeric form stays usable for advanced callers.""" | |
| if isinstance(value, str): | |
| v = value.strip().lower() | |
| if v in DENOISE_STRENGTH_PRESETS: | |
| return DENOISE_STRENGTH_PRESETS[v] | |
| try: | |
| num = float(v) | |
| except ValueError: | |
| return DEFAULT_DENOISE_STRENGTH | |
| return num if 0.0 <= num <= 1.0 else DEFAULT_DENOISE_STRENGTH | |
| # type() rather than isinstance(): bool is an int subclass, and a JSON | |
| # `true` silently meaning "max strength" is never intended β same | |
| # bool-rejection convention as the settings_save guards. | |
| if type(value) in (int, float): | |
| return value if 0.0 <= float(value) <= 1.0 else DEFAULT_DENOISE_STRENGTH | |
| return DEFAULT_DENOISE_STRENGTH | |
| def denoise_audio(input_path, output_path, *, strength: float = DEFAULT_DENOISE_STRENGTH, | |
| n_fft: int = 1024, hop_length: int = 256, | |
| noise_quantile: float = 0.1) -> str: | |
| """Reduce stationary background noise in *input_path* and write the | |
| cleaned 16-bit mono WAV to *output_path*. Returns the output path. | |
| `strength` β how aggressively the noise floor is pulled down (0β1). | |
| `noise_quantile` β fraction of lowest-energy frames used to estimate the | |
| noise profile (0.05β0.5). Raises RuntimeError on unusable input / a | |
| missing scipy β never a raw traceback. | |
| """ | |
| import numpy as np | |
| import soundfile as sf | |
| try: | |
| from scipy.ndimage import median_filter | |
| from scipy.signal import istft, stft | |
| except Exception as e: # pragma: no cover β scipy is pinned, defensive | |
| raise RuntimeError(f"Noise reduction unavailable (scipy missing): {e}") | |
| data, sr = sf.read(str(input_path), dtype="float32", always_2d=False) | |
| if data is None or len(data) == 0: | |
| raise RuntimeError("No audio samples to denoise.") | |
| if getattr(data, "ndim", 1) > 1: | |
| data = data.mean(axis=1) # mono β the STT backends transcribe mono anyway | |
| # A corrupt sample (NaN) must never flow through log10/exp/istft into the | |
| # WAV β silence it first so the module stays total. | |
| data = np.nan_to_num(np.asarray(data, dtype="float32"), nan=0.0, posinf=0.0, neginf=0.0) | |
| # Shorter than one FFT window there's nothing to gate β scipy would pad | |
| # it into near-silence instead of failing, which would be a lie. | |
| if len(data) < n_fft: | |
| raise RuntimeError("Audio too short to denoise.") | |
| # Clamp the noise-quantile so a pathological value can't empty the profile. | |
| nq = float(min(max(noise_quantile, 0.01), 0.5)) | |
| gain_floor = max(0.0, min(float(strength), 0.98)) | |
| f, t, Zxx = stft(data, fs=sr, nperseg=n_fft, noverlap=n_fft - hop_length, | |
| window="hann", boundary="zeros") | |
| mag = np.abs(Zxx) | |
| # Noise profile β mean magnitude of the quietest frames (speech pauses). | |
| n_noise = max(1, int(round(mag.shape[1] * nq))) | |
| quiet_idx = np.argsort(np.mean(mag, axis=0))[:n_noise] | |
| noise_floor = np.mean(mag[:, quiet_idx], axis=1, keepdims=True) | |
| # De-contaminate narrow tonal peaks: when the recording has no true pause | |
| # (a constant tone / droning fan in every frame), the quietest frames still | |
| # carry that tone, so the profile would read it as noise and the gate would | |
| # attenuate it away. The noise floor is broadband while tones/harmonics are | |
| # narrow, so replace each bin's estimate with the lower of itself and the | |
| # median of its neighbours across frequency (nearest-mode keeps the edges | |
| # honest). | |
| noise_floor = np.minimum( | |
| noise_floor, | |
| median_filter(noise_floor, size=(31, 1), mode="nearest"), | |
| ) | |
| # Spectral gate: keep signal, pull down what looks like the noise floor. | |
| # A sigmoid on the bin's dB EXCESS over the floor (a soft threshold ~10 dB | |
| # above the profile) β a linear 1 - gain*ratio gate let noise bins sitting | |
| # above the profile pass through almost untouched (~2x reduction); the | |
| # sigmoid clamps typical noise fluctuations (a few dB around the floor) | |
| # down hard while staying transparent for anything clearly above it. | |
| with np.errstate(divide="ignore", invalid="ignore", over="ignore"): | |
| excess_db = 20.0 * np.log10( | |
| np.maximum(mag, 1e-12) / np.maximum(noise_floor, 1e-12) | |
| ) | |
| # exp(+huge) for deep-sub-floor bins β inf β gate = floor. Guarded by | |
| # errstate(over="ignore") β the clip below still lands it exactly on | |
| # the floor, never amplifying. | |
| gate = 1.0 / (1.0 + np.exp(-2.0 * (excess_db - 10.0))) | |
| gate = (1.0 - gain_floor) + gain_floor * gate # strength scales the floor | |
| gate = np.clip(gate, 1.0 - gain_floor, 1.0) # never below the floor, never amplify | |
| cleaned = Zxx * gate | |
| # boundary='zeros' on both transforms keeps the pair invertible (NOLA | |
| # satisfied); the zero-padding edges are trimmed back to the input length. | |
| _, y = istft(cleaned, fs=sr, nperseg=n_fft, noverlap=n_fft - hop_length, | |
| window="hann", boundary="zeros") | |
| y = np.asarray(y, dtype=np.float32)[: len(data)] | |
| # Normalise to a safe peak so whisper never clips, then write 16-bit WAV. | |
| peak = float(np.max(np.abs(y))) if len(y) else 0.0 | |
| if peak > 0.999: | |
| y = y / peak * 0.95 | |
| out = Path(output_path) | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| sf.write(str(out), y, sr, subtype="PCM_16") | |
| return str(out) | |