"""Speech clean-up before transcription and speaker detection. Levels off the audio as converted (16 kHz mono, peak-normalised) light DC offset removed, low rumble cut (80 Hz high-pass), speech brought to a steady level so quiet and loud voices sit closer together, peaks limited instead of clipped full light, plus noise reduction when the recording measures as noisy The noise reduction is deliberately gentle (a floor on how much any part of the spectrum is turned down, gains smoothed across time and frequency): heavy denoising leaves artefacts that make Whisper drop or invent words. Everything is numpy/scipy so it runs the same on Modal and the HF Space. """ import warnings from dataclasses import dataclass, asdict from typing import Dict, Tuple import numpy as np from scipy import signal from scipy.ndimage import uniform_filter1d LEVELS = ("off", "light", "full") TARGET_SPEECH_DBFS = -20.0 # level speech is brought to MAX_BOOST_DB = 12.0 # quietest speakers are lifted at most this much MAX_CUT_DB = 6.0 # loudest speakers are lowered at most this much LIMIT_AT = 0.89 # about -1 dBFS; above this peaks are softened DENOISE_BELOW_SNR_DB = 25.0 # cleaner recordings are left alone DENOISE_FLOOR_DB = -12.0 # never turn any time-frequency cell down more than this DENOISE_OVERSUBTRACT = 1.5 # The 15th percentile of a noise band's power sits at about 0.16 of its mean # (power of random noise is exponentially distributed): scale it back up. NOISE_BIAS = 1 / 0.1625 @dataclass class EnhanceReport: level: str snr_db: float noise_floor_dbfs: float speech_dbfs: float denoised: bool boost_db_max: float def _frame_db(x: np.ndarray, sr: int, frame_s: float = 0.02) -> np.ndarray: n = max(1, int(sr * frame_s)) usable = len(x) // n * n if usable == 0: return np.array([-120.0]) frames = x[:usable].reshape(-1, n) rms = np.sqrt(np.mean(frames ** 2, axis=1) + 1e-12) return 20 * np.log10(rms + 1e-12) def measure(x: np.ndarray, sr: int) -> Tuple[float, float, float]: """(snr_db, noise_floor_dbfs, speech_dbfs) from the spread of 20 ms frame levels.""" db = _frame_db(x, sr) db = db[db > -100] if db.size < 10: return 0.0, -100.0, -100.0 noise = float(np.percentile(db, 10)) speech = float(np.percentile(db, 90)) return speech - noise, noise, speech def _highpass(x: np.ndarray, sr: int, hz: float = 80.0) -> np.ndarray: sos = signal.butter(2, hz, btype="highpass", fs=sr, output="sos") return signal.sosfilt(sos, x).astype(np.float32) def _denoise(x: np.ndarray, sr: int) -> np.ndarray: """Spectral gating against a slowly moving noise estimate (non-stationary: a fan that starts or a generator in the next room is followed).""" n_fft, hop = 512, 128 _, _, Z = signal.stft(x, fs=sr, nperseg=n_fft, noverlap=n_fft - hop, boundary="zeros", padded=True) power = np.abs(Z) ** 2 frames_per_s = sr / hop # Noise estimate per frequency: a low percentile over ~3 s blocks, then # interpolated across time, so speech pauses anywhere nearby define the floor. block = max(8, int(3.0 * frames_per_s)) n_frames = power.shape[1] centres, floors = [], [] for start in range(0, n_frames, block // 2): seg = power[:, start:start + block] if seg.shape[1] < 4: continue centres.append(start + seg.shape[1] / 2) floors.append(np.percentile(seg, 15, axis=1) * NOISE_BIAS) if not floors: return x floors = np.stack(floors, axis=1) if floors.shape[1] == 1: noise = np.repeat(floors, n_frames, axis=1) else: idx = np.arange(n_frames) noise = np.vstack([np.interp(idx, centres, floors[k]) for k in range(floors.shape[0])]) gain = 1.0 - DENOISE_OVERSUBTRACT * noise / (power + 1e-12) floor = 10 ** (DENOISE_FLOOR_DB / 20) gain = np.clip(gain, floor ** 2, 1.0) ** 0.5 # Smooth gains over ~3 bins and ~40 ms to avoid "musical" artefacts. gain = uniform_filter1d(gain, size=3, axis=0) gain = uniform_filter1d(gain, size=max(3, int(0.04 * frames_per_s)), axis=1) _, y = signal.istft(Z * gain, fs=sr, nperseg=n_fft, noverlap=n_fft - hop, boundary=True) return y[: len(x)].astype(np.float32) def _level(x: np.ndarray, sr: int, noise_dbfs: float) -> Tuple[np.ndarray, float]: """Slow gain riding so each stretch of speech sits near TARGET_SPEECH_DBFS. Gain is decided from speech frames only and held through pauses, so background noise between sentences is not pumped up.""" frame_s = 0.02 db = _frame_db(x, sr, frame_s) speechy = db > noise_dbfs + 6 if speechy.sum() < 10: return x, 0.0 # Speech level over ~1.5 s, carried across pauses. level = np.where(speechy, db, np.nan) win = int(1.5 / frame_s) pad = np.pad(level, (win // 2, win - win // 2 - 1), constant_values=np.nan) windows = np.lib.stride_tricks.sliding_window_view(pad, win) with np.errstate(all="ignore"), warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) local = np.nanpercentile(windows, 75, axis=1) known = ~np.isnan(local) idx = np.arange(len(local)) local = np.interp(idx, idx[known], local[known]) gain_db = np.clip(TARGET_SPEECH_DBFS - local, -MAX_CUT_DB, MAX_BOOST_DB) gain_db = uniform_filter1d(gain_db, size=int(0.5 / frame_s)) n = int(sr * frame_s) curve = np.interp(np.arange(len(x)), np.arange(len(gain_db)) * n + n / 2, gain_db) return (x * 10 ** (curve / 20)).astype(np.float32), float(gain_db.max()) def _limit(x: np.ndarray) -> np.ndarray: """Soft-knee limiter: untouched below LIMIT_AT, smoothly squeezed above.""" a = np.abs(x) over = a > LIMIT_AT if not over.any(): return x head = 1.0 - LIMIT_AT y = x.copy() y[over] = np.sign(x[over]) * (LIMIT_AT + head * np.tanh((a[over] - LIMIT_AT) / head)) return y def enhance(x: np.ndarray, sr: int, level: str = "light") -> Tuple[np.ndarray, EnhanceReport]: """Return the cleaned-up audio (same length and sample rate) and what was done.""" x = np.asarray(x, dtype=np.float32) if x.ndim > 1: x = x.mean(axis=1 if x.shape[1] < x.shape[0] else 0) snr, noise, speech = measure(x, sr) if level not in LEVELS: raise ValueError(f"Unknown enhancement level {level!r}; use one of {LEVELS}") if level == "off" or x.size < sr // 2: return x, EnhanceReport("off", round(snr, 1), round(noise, 1), round(speech, 1), False, 0.0) y = x - float(np.mean(x)) y = _highpass(y, sr) # Measured again once DC offset and rumble are gone: they inflate the noise # floor, which would hide quiet speakers from the levelling below. snr, noise, speech = measure(y, sr) denoised = False if level == "full" and snr < DENOISE_BELOW_SNR_DB: y = _denoise(y, sr) denoised = True _, noise, _ = measure(y, sr) y, boost = _level(y, sr, noise) y = _limit(y) return y, EnhanceReport(level, round(snr, 1), round(noise, 1), round(speech, 1), denoised, round(boost, 1)) def report_dict(r: EnhanceReport) -> Dict: return asdict(r)