ckpt / code /eval_clap_hiding.py
AE-W's picture
archive loose scripts/configs
219f052 verified
Raw
History Blame Contribute Delete
5.95 kB
"""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
# Use AudioLDM's CLAP wrapper (already cached locally)
sys.path.insert(0, '/nfs/turbo/coe-ahowens-nobackup/dingqy/AudioLDM-training-finetuning')
from audioldm_train.conditional_models import CLAPAudioEmbeddingClassifierFreev2 # noqa
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 # silent input
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))
# Pull prompts from per-clip config.json
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")
# CLAP model: AudioLDM's wrapper exposes .get_audio_embedding(wav_tensor) and
# .get_text_embedding(list_of_str). Initializing with embed_mode='audio' but
# both modalities work after init.
print("loading CLAP...", flush=True)
clap = CLAPAudioEmbeddingClassifierFreev2(
pretrained_path=CLAP_CKPT,
sampling_rate=SR, # 16 kHz; wrapper resamples internally to 48k
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]
# 1. LUFS-normalize bg to -30
bg_norm = lufs_normalize(bg, TARGET_BG_LUFS)
# 2. mix = bg_norm + fg, then LUFS-normalize mix to -23
mix_raw = bg_norm + fg
mix_norm = lufs_normalize(mix_raw, TARGET_MIX_LUFS)
# 3. CLAP embeddings (CLAP expects 48 kHz; the wrapper handles resample)
with torch.no_grad():
# Wrapper expects [bs, 1, T] at self.sampling_rate, internally
# resamples to 48k then asserts audio.size(-1) > 480000 β€” so
# pad to 11s @ 16k (= 528000 β†’ 528000*3 = 1584000 @ 48k > 480k).
target_len = 11 * SR # 11 s headroom past CLAP's 10 s window
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}")
# Save
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()