CoolFace
Apppublic

AnimalMonk/audio-mastering-suite

sourceHugging Facemitupdated 6mo agoView on Hugging Face
3likes
visualization.py126 linesDownload Raw Back to root
1"""Before/after waveform and spectrum comparison plots."""2 3import numpy as np4import matplotlib5matplotlib.use("Agg")6import matplotlib.pyplot as plt7 8 9def _to_mono(audio):10    """Collapse to mono for plotting."""11    if audio.ndim > 1 and audio.shape[1] > 1:12        return audio.mean(axis=1)13    return audio.ravel()14 15 16def _downsample_for_plot(signal, time, max_points=500_000):17    """Reduce sample count so matplotlib stays responsive."""18    if len(signal) > max_points:19        step = len(signal) // max_points20        return signal[::step], time[::step]21    return signal, time22 23 24def plot_waveform_comparison(original, mastered, sample_rate):25    """Create a stacked before/after waveform plot.26 27    Returns a matplotlib Figure.28    """29    fig, axes = plt.subplots(2, 1, figsize=(8, 4), sharex=True)30 31    duration = len(original) / sample_rate32    time_o = np.linspace(0, duration, len(original))33    time_m = np.linspace(0, duration, len(mastered))34 35    orig_mono = _to_mono(original)36    mast_mono = _to_mono(mastered)37 38    orig_mono, time_o = _downsample_for_plot(orig_mono, time_o)39    mast_mono, time_m = _downsample_for_plot(mast_mono, time_m)40 41    axes[0].plot(time_o, orig_mono, color="#4a90d9", linewidth=0.3)42    axes[0].set_ylabel("Amplitude")43    axes[0].set_title("Original")44    axes[0].set_ylim(-1.05, 1.05)45 46    axes[1].plot(time_m, mast_mono, color="#d94a4a", linewidth=0.3)47    axes[1].set_ylabel("Amplitude")48    axes[1].set_title("Mastered")49    axes[1].set_xlabel("Time (seconds)")50    axes[1].set_ylim(-1.05, 1.05)51 52    plt.tight_layout()53    return fig54 55 56def plot_spectrum_comparison(original, mastered, sample_rate):57    """Create a frequency spectrum comparison with shape-normalized overlay58    and a difference trace showing the processing's spectral impact.59 60    The mastered spectrum is level-aligned to the original so the plot61    compares spectral *shape*, not overall loudness (LUFS stats handle that).62 63    Returns a matplotlib Figure.64    """65    fig, (ax_spec, ax_diff) = plt.subplots(66        2, 1, figsize=(8, 5), height_ratios=[3, 1], sharex=True,67    )68 69    orig_mono = _to_mono(original)70    mast_mono = _to_mono(mastered)71 72    n_fft = 819273 74    def avg_spectrum(signal, n_fft, sr):75        hop = n_fft // 276        n_windows = max(1, (len(signal) - n_fft) // hop)77        spectra = []78        for i in range(min(n_windows, 100)):79            start = i * hop80            window = signal[start : start + n_fft] * np.hanning(n_fft)81            spectrum = np.abs(np.fft.rfft(window))82            spectra.append(spectrum)83        avg = np.mean(spectra, axis=0)84        freqs = np.fft.rfftfreq(n_fft, 1.0 / sr)85        avg_db = 20.0 * np.log10(avg + 1e-10)86        return freqs, avg_db87 88    freqs_o, spec_o = avg_spectrum(orig_mono, n_fft, sample_rate)89    freqs_m, spec_m = avg_spectrum(mast_mono, n_fft, sample_rate)90 91    # --- Level-align mastered to original (remove overall loudness diff) ---92    # Use only the passband (100 Hz – 10 kHz) for alignment so the HPF/LPF93    # roll-offs at the extremes don't skew the offset.94    passband = (freqs_o >= 100) & (freqs_o <= 10000)95    level_offset = np.mean(spec_o[passband]) - np.mean(spec_m[passband])96    spec_m_aligned = spec_m + level_offset97 98    # --- Top: overlaid spectra (shape comparison) ---99    ax_spec.plot(freqs_o, spec_o, color="#4a90d9", alpha=0.7, linewidth=1,100                 label="Original")101    ax_spec.plot(freqs_m, spec_m_aligned, color="#d94a4a", alpha=0.7,102                 linewidth=1, label="Mastered (level-aligned)")103    ax_spec.set_ylabel("Magnitude (dB)")104    ax_spec.set_title("Spectral Shape Comparison")105    ax_spec.legend(loc="upper right", fontsize=8)106    ax_spec.grid(True, alpha=0.3)107 108    # --- Bottom: difference (mastered − original) ---109    diff = spec_m_aligned - spec_o110    ax_diff.plot(freqs_o, diff, color="#2ca02c", linewidth=1)111    ax_diff.axhline(0, color="gray", linewidth=0.5, linestyle="--")112    ax_diff.set_ylabel("Δ dB")113    ax_diff.set_xlabel("Frequency")114    ax_diff.set_title("Processing Difference (Mastered − Original)", fontsize=9)115    ax_diff.set_ylim(-6, 6)116    ax_diff.grid(True, alpha=0.3)117 118    # Shared x-axis settings119    ax_diff.set_xscale("log")120    ax_diff.set_xlim(20, sample_rate / 2)121    ax_diff.set_xticks([10, 100, 1000, 10000])122    ax_diff.set_xticklabels(["10 Hz", "100 Hz", "1 kHz", "10 kHz"])123 124    plt.tight_layout()125    return fig126