| """Evaluate bgβfg models on the hidingsound CLAP metrics: |
| 1. clap_sim(bg, mix) β lower = better (fg makes mix diverge from bg) |
| 2. clap_sim(mix, prompt_text) β higher = better (mix carries fg semantics) |
| |
| LUFS protocol: bg β -30 LUFS, mix β -23 LUFS (matches ymdou's pipeline). |
| Both audios are forced to 16 kHz mono before CLAP, so SA (44.1 kHz stereo) |
| and Frieren (16 kHz mono) outputs are compared on equal footing. |
| """ |
| import json, os, sys |
| from pathlib import Path |
| import numpy as np |
| import torch |
| import torchaudio |
| import pyloudnorm as pyln |
|
|
| |
| sys.path.insert(0, '/nfs/turbo/coe-ahowens-nobackup/dingqy/AudioLDM-training-finetuning') |
| from audioldm_train.conditional_models import CLAPAudioEmbeddingClassifierFreev2 |
|
|
| CLAP_CKPT = "/nfs/turbo/coe-ahowens-nobackup/dingqy/AudioLDM-training-finetuning/data/checkpoints/clap_music_speech_audioset_epoch_15_esc_89.98.pt" |
| SR = 16000 |
| TARGET_BG_LUFS = -30.0 |
| TARGET_MIX_LUFS = -23.0 |
|
|
| DEMO_ROOT = Path("/home/dingqy/inference_demo") |
| PAIRS_FILE = "/nfs/turbo/coe-ahowens-nobackup/dingqy/inference_val_pairs.json" |
| MANIFEST = "/nfs/turbo/coe-ahowens-nobackup/ymdou/hidingsound/data/noise_guidance_out_latent/manifest.json" |
| DATA_ROOT = "/scratch/ahowens_root/ahowens2/ymdou/hiding_sound_noise_guidance_output_scratch/" |
|
|
|
|
| def load_mono_16k(path): |
| w, sr = torchaudio.load(str(path)) |
| if w.shape[0] > 1: w = w.mean(0, keepdim=True) |
| if sr != SR: w = torchaudio.functional.resample(w, sr, SR) |
| return w.squeeze(0).numpy().astype(np.float32) |
|
|
|
|
| def lufs_normalize(wav, target_lufs, sr=SR): |
| """Apply gain so wav reaches target LUFS. wav is 1D float.""" |
| meter = pyln.Meter(sr) |
| cur = meter.integrated_loudness(wav) |
| if not np.isfinite(cur): |
| return wav |
| return pyln.normalize.loudness(wav, cur, target_lufs).astype(np.float32) |
|
|
|
|
| def cos_sim(a, b): |
| a = a.flatten(); b = b.flatten() |
| return float((a @ b) / (a.norm() * b.norm() + 1e-8)) |
|
|
|
|
| def main(): |
| pairs = json.load(open(PAIRS_FILE)) |
| |
| prompts = [] |
| for p in pairs: |
| cfg_path = Path(DATA_ROOT) / Path(p["rel_path"]).parent / "config.json" |
| try: |
| d = json.load(open(cfg_path)) |
| prompts.append(d["generations"][0]["prompt"]) |
| except Exception: |
| prompts.append("") |
| print(f"loaded {len(pairs)} pairs + prompts") |
|
|
| |
| |
| |
| print("loading CLAP...", flush=True) |
| clap = CLAPAudioEmbeddingClassifierFreev2( |
| pretrained_path=CLAP_CKPT, |
| sampling_rate=SR, |
| embed_mode="audio", |
| amodel="HTSAT-base", |
| ).cuda().eval() |
|
|
| print(f"\n{'pair':35s} {'clap(bg,mix) β':>14s} {'clap(mix,txt) β':>16s} (model)") |
|
|
| results = {"sa": [], "frieren": []} |
| for model_name, sub_dir in [("sa", "sa"), ("frieren", "frieren")]: |
| d = DEMO_ROOT / sub_dir |
| for pair, prompt in zip(pairs, prompts): |
| sid = pair["sample_id"] |
| tag = f"val_{sid}" |
| bg_p = d / f"{tag}_bg.wav" |
| fg_p = d / f"{tag}_fg_pred.wav" |
| if not (bg_p.exists() and fg_p.exists()): |
| continue |
| bg = load_mono_16k(bg_p) |
| fg = load_mono_16k(fg_p) |
| T = min(len(bg), len(fg)) |
| bg, fg = bg[:T], fg[:T] |
| |
| bg_norm = lufs_normalize(bg, TARGET_BG_LUFS) |
| |
| mix_raw = bg_norm + fg |
| mix_norm = lufs_normalize(mix_raw, TARGET_MIX_LUFS) |
| |
| with torch.no_grad(): |
| |
| |
| |
| target_len = 11 * SR |
| def pad_to(x): |
| if len(x) >= target_len: return x[:target_len] |
| return np.pad(x, (0, target_len - len(x))) |
| bg_t = torch.from_numpy(pad_to(bg_norm)).view(1, 1, -1).cuda() |
| mix_t = torch.from_numpy(pad_to(mix_norm)).view(1, 1, -1).cuda() |
| clap.embed_mode = "audio" |
| emb_bg = clap(bg_t).squeeze() |
| emb_mix = clap(mix_t).squeeze() |
| if prompt: |
| clap.embed_mode = "text" |
| emb_txt = clap([prompt]).squeeze() |
| else: |
| emb_txt = None |
| sim_bg_mix = cos_sim(emb_bg, emb_mix) |
| sim_mix_txt = cos_sim(emb_mix, emb_txt) if emb_txt is not None else float("nan") |
| results[model_name].append((sid, sim_bg_mix, sim_mix_txt)) |
| print(f"{tag[:35]:35s} {sim_bg_mix:>14.4f} {sim_mix_txt:>16.4f} ({model_name})") |
|
|
| print(f"\n=== summary (5 val pairs) ===") |
| print(f"{'model':10s} {'mean clap(bg,mix) β':>22s} {'mean clap(mix,txt) β':>22s}") |
| for m, rows in results.items(): |
| if not rows: continue |
| bm = np.mean([r[1] for r in rows]) |
| mt = np.mean([r[2] for r in rows if not np.isnan(r[2])]) |
| print(f"{m:10s} {bm:>22.4f} {mt:>22.4f}") |
|
|
| |
| with open("/home/dingqy/inference_demo/clap_eval.json", "w") as f: |
| json.dump({m: [{"sid": r[0], "clap_bg_mix": r[1], "clap_mix_txt": r[2]} for r in rows] |
| for m, rows in results.items()}, f, indent=2) |
| print("\nsaved β /home/dingqy/inference_demo/clap_eval.json") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|