"""Optional output clean-up for drama3-expressive-medium (numpy + soundfile). The fine-tuned model is about 3.5 dB louder than Drama 3 and leaves a little more room tone in the gaps between words. This script (1) loudness-matches a take: the speech level (95th percentile of 10 ms frame levels) goes to --target dBFS, peaks stay below -1 dBFS; and (2) with --gate, applies a smoothed downward expander to frames more than 30 dB below the speech level (1.5 dB per dB, at most 24 dB, 50 ms hold, 5 ms attack, 80 ms release), so the gaps fall toward silence while word tails are kept. python postprocess.py in.wav out.wav [--target -20] [--gate] """ import argparse import numpy as np import soundfile as sf def frame_db(w: np.ndarray, sr: int, hop: float = 0.01) -> np.ndarray: n = int(hop * sr) f = w[: len(w) // n * n].reshape(-1, n) return 20 * np.log10(np.sqrt((f ** 2).mean(1)) + 1e-9) def process(w: np.ndarray, sr: int, target: float = -20.0, gate: bool = False) -> np.ndarray: db = frame_db(w, sr) if not len(db): return w level = np.percentile(db, 95) out = w * 10 ** ((target - level) / 20) if gate: thr = level - 30.0 att = -np.clip((thr - db) * 1.5, 0.0, 24.0) hold = 5 near = np.convolve((db >= thr).astype(float), np.ones(2 * hold + 1), mode="same") > 0 att[near] = 0.0 sm, g = np.zeros_like(att), 0.0 for i, a in enumerate(att): g += (0.86 if a > g else 0.12) * (a - g) sm[i] = g n = int(0.01 * sr) gain = np.repeat(10 ** (sm / 20), n) gain = np.concatenate([gain, np.full(len(out) - len(gain), gain[-1] if len(gain) else 1.0)]) out = out * gain return out * min(1.0, 10 ** (-1 / 20) / max(float(np.abs(out).max()), 1e-9)) if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("src") ap.add_argument("dst") ap.add_argument("--target", type=float, default=-20.0) ap.add_argument("--gate", action="store_true") a = ap.parse_args() w, sr = sf.read(a.src, dtype="float32", always_2d=True) sf.write(a.dst, process(w.mean(1), sr, a.target, a.gate), sr)