import subprocess import sys from pathlib import Path import numpy as np import soundfile as sf from scipy.signal import istft, stft class ToneMatcher: RATE = 48000 NPER = 2048 HOP = 512 def __init__(self, target_path, limit_db=3.0): self.target = np.load(target_path) self.limit_db = limit_db def spectrum(self, x): f, _, z = stft(x, fs=self.RATE, nperseg=self.NPER, noverlap=self.NPER - self.HOP) power = np.abs(z) ** 2 level = 10 * np.log10(power.sum(axis=0) + 1e-12) speech = level > np.percentile(level, 50) return f, z, 10 * np.log10(power[:, speech].mean(axis=1) + 1e-12) @staticmethod def smooth(f, curve, fraction=3): out = np.empty_like(curve) for i, hz in enumerate(f): lo, hi = hz / 2 ** (0.5 / fraction), hz * 2 ** (0.5 / fraction) band = (f >= lo) & (f <= max(hi, lo + 30)) out[i] = curve[band].mean() return out def gains(self, x): f, z, curve = self.spectrum(x) top = min(0.92 * float(f[np.where(curve > curve.max() - 60)[0].max()]), 14000.0) speech_band = (f >= 300) & (f <= 3000) gain = np.clip(self.target - self.smooth(f, curve - curve[speech_band].mean()), -self.limit_db, self.limit_db) taper = np.clip((f - 60.0) / 60.0, 0, 1) * np.clip((top - f) / (0.12 * top), 0, 1) gain = self.smooth(f, gain * taper) gain -= gain[speech_band].mean() return f, z, gain def apply(self, x): _, z, gain = self.gains(x) _, y = istft(z * (10 ** (gain / 20))[:, None], fs=self.RATE, nperseg=self.NPER, noverlap=self.NPER - self.HOP) return y[: len(x)].astype(np.float32) def entries(self, x, points=96): f, _, gain = self.gains(x) grid = np.geomspace(40.0, 20000.0, points) return [(float(hz), float(np.interp(hz, f, gain))) for hz in grid] def filter(self, x): body = ";".join("entry(%.1f,%.2f)" % point for point in [(0.0, 0.0)] + self.entries(x) + [(24000.0, 0.0)]) delay = 960 return "firequalizer=gain_entry='%s':delay=0.02:accuracy=5,atrim=start_sample=%d:end_sample=%d,asetpts=PTS-STARTPTS" % (body, delay, delay + len(x)) if __name__ == "__main__": target_path, source, target = sys.argv[1:4] mode = sys.argv[4] if len(sys.argv) > 4 else "numpy" matcher = ToneMatcher(target_path) audio, rate = sf.read(source, dtype="float32") mono = audio.mean(axis=1) if audio.ndim == 2 else audio if mode == "ffmpeg": subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", source, "-af", matcher.filter(mono), "-c:a", "pcm_f32le", target], check=True) else: out = np.stack([matcher.apply(audio[:, c]) for c in range(audio.shape[1])], axis=1) if audio.ndim == 2 else matcher.apply(audio) sf.write(target, np.clip(out, -1, 1), rate, subtype="FLOAT") print(Path(target).name, "written")