| """Re-render mel-spectrogram PNGs from existing bg/fg_gt/fg_pred wav triplets. |
| |
| Style: librosa.display.specshow with time/Hz axes + colorbar + title (matches |
| audioldm_train sample callback look). Reusable any time inference output exists |
| under <root>/{sa,frieren,...}/val_<sid>_{bg,fg_gt,fg_pred}.wav. |
| |
| Usage: |
| python render_specs.py # default: /home/dingqy/inference_demo |
| python render_specs.py --root /path/to/dir # any dir of {sa,frieren} subdirs |
| python render_specs.py --subdir sa # only one subdir |
| """ |
| import argparse, re, sys |
| from pathlib import Path |
| import numpy as np |
| import torch |
| import torchaudio |
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| import librosa.display as ld |
| from librosa.filters import mel as librosa_mel_fn |
|
|
| |
| SUBDIR_DEFAULTS = { |
| "sa": {"sr": 44100, "n_fft": 2048, "hop_length": 512, "n_mels": 128, "fmax": 22050}, |
| "frieren": {"sr": 16000, "n_fft": 1024, "hop_length": 256, "n_mels": 80, "fmax": 8000}, |
| } |
|
|
|
|
| def log_mel(wav_ct, sr, n_fft, hop_length, n_mels, fmax): |
| """[C,T] tensor → log-mel [n_mels, T_mel] (channel-mean).""" |
| w = wav_ct.mean(0, keepdim=True).float() if wav_ct.dim() == 2 else wav_ct.float().unsqueeze(0) |
| mb = torch.from_numpy(librosa_mel_fn(sr=sr, n_fft=n_fft, n_mels=n_mels, |
| fmin=0, fmax=fmax)).float() |
| win = torch.hann_window(n_fft) |
| spec = torch.stft(w, n_fft=n_fft, hop_length=hop_length, win_length=n_fft, |
| window=win, center=True, return_complex=True).abs() |
| return (mb @ spec[0]).clamp(min=1e-5).log10().numpy() * 20.0 |
|
|
|
|
| def render_panels(panels, title, out_path, sr, hop_length, fmax): |
| """panels: list of (label, mel) tuples. Renders one row per panel with |
| shared vmin/vmax + colorbar.""" |
| n = len(panels) |
| fig, axes = plt.subplots(n, 1, figsize=(10, 2.5 * n), dpi=110, sharex=True) |
| if n == 1: |
| axes = [axes] |
| vmin = min(m.min() for _, m in panels) |
| vmax = max(m.max() for _, m in panels) |
| last_img = None |
| for ax, (label, m) in zip(axes, panels): |
| last_img = ld.specshow(m, x_axis="time", y_axis="mel", |
| sr=sr, hop_length=hop_length, fmax=fmax, |
| cmap="magma", ax=ax, vmin=vmin, vmax=vmax) |
| ax.set_ylabel(f"{label}\nmel (Hz)", fontsize=9) |
| axes[0].set_title(title, fontsize=11) |
| axes[-1].set_xlabel("time (s)") |
| fig.colorbar(last_img, ax=axes, format="%+.1f", label="log-mel (dB)", |
| shrink=0.9, pad=0.02) |
| fig.savefig(out_path, bbox_inches="tight") |
| plt.close(fig) |
|
|
|
|
| |
| def render_triplet(bg_mel, fg_gt_mel, fg_pred_mel, title, out_path, |
| sr, hop_length, fmax): |
| render_panels([("bg", bg_mel), ("fg_gt", fg_gt_mel), ("fg_pred", fg_pred_mel)], |
| title, out_path, sr, hop_length, fmax) |
|
|
|
|
| |
| PANEL_ORDER = ["bg", "fg_gt", "fg_pred", "mixture"] |
|
|
|
|
| def discover_pairs(subdir): |
| """Find {sample_id: {kind: path}} for each val_<sid>_<kind>.wav under subdir. |
| Always require bg + fg_pred; fg_gt and mixture are optional.""" |
| found = {} |
| pat = re.compile(r"^val_(.+)_(bg|fg_gt|fg_pred|mixture)\.wav$") |
| for p in Path(subdir).iterdir(): |
| m = pat.match(p.name) |
| if not m: continue |
| sid, kind = m.group(1), m.group(2) |
| found.setdefault(sid, {})[kind] = p |
| out = [] |
| for sid, d in sorted(found.items()): |
| if "bg" in d and "fg_pred" in d: |
| out.append((sid, d)) |
| return out |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--root", default="/home/dingqy/inference_demo", |
| help="dir containing model subdirs (e.g., sa/, frieren/)") |
| ap.add_argument("--subdir", action="append", |
| help="restrict to specific subdir(s) (default: all known)") |
| args = ap.parse_args() |
|
|
| root = Path(args.root) |
| if not root.exists(): |
| sys.exit(f"root not found: {root}") |
| subdirs = args.subdir if args.subdir else list(SUBDIR_DEFAULTS.keys()) |
|
|
| for sub in subdirs: |
| d = root / sub |
| if not d.exists(): |
| print(f"[skip] {d} does not exist") |
| continue |
| cfg = SUBDIR_DEFAULTS.get(sub) |
| if cfg is None: |
| print(f"[skip] {sub}: unknown subdir; add an entry to SUBDIR_DEFAULTS") |
| continue |
| pairs = discover_pairs(d) |
| print(f"[{sub}] {len(pairs)} val groups under {d}") |
| for sid, kind_to_path in pairs: |
| panels = [] |
| for kind in PANEL_ORDER: |
| if kind not in kind_to_path: continue |
| w, sr_w = torchaudio.load(str(kind_to_path[kind])) |
| if sr_w != cfg["sr"]: |
| w = torchaudio.functional.resample(w, sr_w, cfg["sr"]) |
| m = log_mel(w, cfg["sr"], cfg["n_fft"], cfg["hop_length"], |
| cfg["n_mels"], cfg["fmax"]) |
| panels.append((kind, m)) |
| out_path = d / f"val_{sid}_spec.png" |
| render_panels(panels, |
| title=f"[{sub}] {sid}", |
| out_path=str(out_path), |
| sr=cfg["sr"], hop_length=cfg["hop_length"], |
| fmax=cfg["fmax"]) |
| kinds = [k for k, _ in panels] |
| print(f" rendered {out_path.name} ({'+'.join(kinds)})") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|