| """ |
| Run mono speech enhancement baselines (MetricGAN+, MossFormer2) on binaural eval outputs. |
| |
| Each ear channel is processed independently, then recombined to binaural. |
| Computes SI-SNR improvement, SNR improvement, delta_ITD, delta_ILD. |
| |
| Usage: |
| python run_baselines.py \ |
| --input_dir experiments/TSDL_old_mixtures/eval_outputs_removeall_old \ |
| --model metricganplus \ |
| --output_dir experiments/metricganplus_baseline/eval_outputs_removeall_old \ |
| --use_cuda |
| """ |
|
|
| import argparse |
| import glob |
| import json |
| import os |
| import shutil |
| import tempfile |
|
|
| import numpy as np |
| import pandas as pd |
| import soundfile as sf |
| import torch |
| import torchaudio |
| from scipy import signal as scipy_signal |
| from torchmetrics.functional import ( |
| scale_invariant_signal_noise_ratio as si_snr, |
| signal_noise_ratio as snr, |
| ) |
| from tqdm import tqdm |
|
|
| SR = 44100 |
|
|
|
|
| |
| |
| |
|
|
| def compute_itd(s_left, s_right, sr, t_max=None): |
| corr = scipy_signal.correlate(s_left, s_right) |
| corr /= np.max(np.abs(corr)) + 1e-12 |
| mid = len(corr) // 2 + 1 |
| cc = np.concatenate((corr[-mid:], corr[:mid])) |
| if t_max is not None: |
| cc = np.concatenate([cc[-t_max + 1:], cc[:t_max + 1]]) |
| else: |
| t_max = mid |
| tau = np.argmax(np.abs(cc)) |
| tau -= t_max |
| return tau / sr * 1e6 |
|
|
|
|
| def compute_ild(s_left, s_right): |
| sum_sq_left = np.sum(s_left ** 2, axis=-1) |
| sum_sq_right = np.sum(s_right ** 2, axis=-1) |
| return 10 * np.log10((sum_sq_left + 1e-12) / (sum_sq_right + 1e-12)) |
|
|
|
|
| def itd_diff(s_est, s_gt, sr): |
| TMAX = int(round(1e-3 * sr)) |
| itd_est = compute_itd(s_est[0], s_est[1], sr, TMAX) |
| itd_gt = compute_itd(s_gt[0], s_gt[1], sr, TMAX) |
| return np.abs(itd_est - itd_gt) |
|
|
|
|
| def ild_diff(s_est, s_gt): |
| ild_est = compute_ild(s_est[0], s_est[1]) |
| ild_gt = compute_ild(s_gt[0], s_gt[1]) |
| return np.abs(ild_est - ild_gt) |
|
|
|
|
| |
| |
| |
|
|
| def load_metricganplus(device): |
| from speechbrain.inference.enhancement import SpectralMaskEnhancement |
| model = SpectralMaskEnhancement.from_hparams( |
| source="speechbrain/metricgan-plus-voicebank", |
| savedir="pretrained_models/metricgan-plus-voicebank", |
| run_opts={"device": str(device)}, |
| ) |
| return model |
|
|
|
|
| def load_mossformer2(): |
| from clearvoice import ClearVoice |
| model = ClearVoice( |
| task='speech_enhancement', |
| model_names=['MossFormer2_SE_48K'], |
| ) |
| return model |
|
|
|
|
| |
| |
| |
|
|
| def enhance_metricganplus(model, mixture_wav, device): |
| """ |
| Enhance binaural audio with MetricGAN+ (16kHz mono). |
| mixture_wav: numpy array [2, T] at 44100Hz |
| Returns: numpy array [2, T] at 44100Hz |
| """ |
| resampler_down = torchaudio.transforms.Resample(SR, 16000) |
| resampler_up = torchaudio.transforms.Resample(16000, SR) |
|
|
| enhanced_channels = [] |
| for ch in range(2): |
| mono = torch.from_numpy(mixture_wav[ch]).float() |
| mono_16k = resampler_down(mono.unsqueeze(0)).squeeze(0) |
| mono_16k_batch = mono_16k.unsqueeze(0).to(device) |
| lengths = torch.tensor([1.0]).to(device) |
| enhanced = model.enhance_batch(mono_16k_batch, lengths) |
| enhanced = enhanced.squeeze(0).cpu() |
| enhanced_44k = resampler_up(enhanced.unsqueeze(0)).squeeze(0) |
| enhanced_channels.append(enhanced_44k.numpy()) |
|
|
| |
| min_len = min(enhanced_channels[0].shape[-1], enhanced_channels[1].shape[-1], |
| mixture_wav.shape[-1]) |
| output = np.stack([enhanced_channels[0][:min_len], |
| enhanced_channels[1][:min_len]], axis=0) |
| return output |
|
|
|
|
| def enhance_mossformer2(model, mixture_wav): |
| """ |
| Enhance binaural audio with MossFormer2 (48kHz mono). |
| mixture_wav: numpy array [2, T] at 44100Hz |
| Returns: numpy array [2, T] at 44100Hz |
| """ |
| resampler_down = torchaudio.transforms.Resample(SR, 48000) |
| resampler_up = torchaudio.transforms.Resample(48000, SR) |
|
|
| enhanced_channels = [] |
| for ch in range(2): |
| mono = torch.from_numpy(mixture_wav[ch:ch+1]).float() |
| mono_48k = resampler_down(mono) |
|
|
| |
| with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp_in, \ |
| tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp_out: |
| tmp_in_path = tmp_in.name |
| tmp_out_path = tmp_out.name |
|
|
| try: |
| sf.write(tmp_in_path, mono_48k.numpy()[0], 48000) |
| output_wav = model(input_path=tmp_in_path, online_write=False) |
| |
| if isinstance(output_wav, dict): |
| output_wav = list(output_wav.values())[0] |
| if isinstance(output_wav, torch.Tensor): |
| output_wav = output_wav.numpy() |
| if isinstance(output_wav, np.ndarray): |
| if output_wav.ndim == 1: |
| output_wav = output_wav[np.newaxis, :] |
| elif output_wav.ndim == 2 and output_wav.shape[0] > output_wav.shape[1]: |
| output_wav = output_wav.T |
| enhanced_48k = torch.from_numpy(output_wav).float() |
| if enhanced_48k.ndim == 1: |
| enhanced_48k = enhanced_48k.unsqueeze(0) |
| enhanced_44k = resampler_up(enhanced_48k) |
| enhanced_channels.append(enhanced_44k.numpy()) |
| finally: |
| if os.path.exists(tmp_in_path): |
| os.unlink(tmp_in_path) |
| if os.path.exists(tmp_out_path): |
| os.unlink(tmp_out_path) |
|
|
| min_len = min(enhanced_channels[0].shape[-1], enhanced_channels[1].shape[-1], |
| mixture_wav.shape[-1]) |
| output = np.stack([enhanced_channels[0][0, :min_len], |
| enhanced_channels[1][0, :min_len]], axis=0) |
| return output |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Run mono SE baselines on binaural eval outputs") |
| parser.add_argument('--input_dir', type=str, required=True, |
| help="Path to eval_outputs_removeall_old dir") |
| parser.add_argument('--model', type=str, required=True, |
| choices=['metricganplus', 'mossformer2'], |
| help="Baseline model to run") |
| parser.add_argument('--output_dir', type=str, required=True, |
| help="Output directory for baseline results") |
| parser.add_argument('--use_cuda', action='store_true', |
| help="Use CUDA if available") |
| args = parser.parse_args() |
|
|
| device = torch.device('cuda' if args.use_cuda and torch.cuda.is_available() else 'cpu') |
| print(f"Using device: {device}") |
|
|
| |
| print(f"Loading {args.model}...") |
| if args.model == 'metricganplus': |
| model = load_metricganplus(device) |
| else: |
| model = load_mossformer2() |
| print("Model loaded.") |
|
|
| |
| samples_dir = os.path.join(args.input_dir, 'outputs') |
| sample_dirs = sorted([ |
| d for d in os.listdir(samples_dir) |
| if os.path.isdir(os.path.join(samples_dir, d)) |
| ]) |
| print(f"Found {len(sample_dirs)} samples") |
|
|
| |
| out_audio_dir = os.path.join(args.output_dir, 'outputs') |
| os.makedirs(out_audio_dir, exist_ok=True) |
|
|
| all_results = [] |
|
|
| for sample_name in tqdm(sample_dirs, desc=f"Running {args.model}"): |
| sample_path = os.path.join(samples_dir, sample_name) |
|
|
| |
| mix_files = glob.glob(os.path.join(sample_path, 'mixture_*.wav')) |
| if not mix_files: |
| print(f" Skipping {sample_name}: no mixture file found") |
| continue |
| mix_path = mix_files[0] |
|
|
| |
| gt_path = os.path.join(sample_path, 'gt_speech.wav') |
| if not os.path.exists(gt_path): |
| print(f" Skipping {sample_name}: no gt_speech.wav found") |
| continue |
|
|
| mixture, sr_mix = sf.read(mix_path) |
| gt, sr_gt = sf.read(gt_path) |
| mixture = mixture.T |
| gt = gt.T |
|
|
| |
| min_len = min(mixture.shape[-1], gt.shape[-1]) |
| mixture = mixture[:, :min_len] |
| gt = gt[:, :min_len] |
|
|
| |
| if args.model == 'metricganplus': |
| enhanced = enhance_metricganplus(model, mixture, device) |
| else: |
| enhanced = enhance_mossformer2(model, mixture) |
|
|
| |
| min_len = min(enhanced.shape[-1], mixture.shape[-1], gt.shape[-1]) |
| enhanced = enhanced[:, :min_len] |
| mixture_trimmed = mixture[:, :min_len] |
| gt_trimmed = gt[:, :min_len] |
|
|
| |
| out_sample_dir = os.path.join(out_audio_dir, sample_name) |
| os.makedirs(out_sample_dir, exist_ok=True) |
| out_wav_name = f'output_{args.model}.wav' |
| sf.write(os.path.join(out_sample_dir, out_wav_name), |
| enhanced.T, SR) |
|
|
| |
| meta_src = os.path.join(sample_path, 'metadata.json') |
| if os.path.exists(meta_src): |
| shutil.copy2(meta_src, os.path.join(out_sample_dir, 'metadata.json')) |
|
|
| |
| mix_t = torch.from_numpy(mixture_trimmed).float() |
| enh_t = torch.from_numpy(enhanced).float() |
| gt_t = torch.from_numpy(gt_trimmed).float() |
|
|
| si_snr_imp = (torch.mean(si_snr(enh_t, gt_t)) - torch.mean(si_snr(mix_t, gt_t))).item() |
| snr_imp = (torch.mean(snr(enh_t, gt_t)) - torch.mean(snr(mix_t, gt_t))).item() |
| d_itd = itd_diff(enhanced, gt_trimmed, SR) |
| d_ild = ild_diff(enhanced, gt_trimmed) |
| abs_si_snr = torch.mean(si_snr(enh_t, gt_t)).item() |
|
|
| |
| meta = {} |
| if os.path.exists(meta_src): |
| with open(meta_src) as f: |
| meta = json.load(f) |
|
|
| result = { |
| 'scale_invariant_signal_noise_ratio': [si_snr_imp], |
| 'signal_noise_ratio': [snr_imp], |
| 'delta_ITD': [d_itd], |
| 'delta_ILD': [d_ild], |
| 'si_snr': [abs_si_snr], |
| 'metadata': [{ |
| 'mixture_id': meta.get('mixture_id', sample_name), |
| 'mixture_file': meta.get('audio_file', ''), |
| 'command_variant': meta.get('command_variant', {}), |
| }], |
| } |
| all_results.append(result) |
|
|
| |
| results_pth_path = os.path.join(args.output_dir, 'results.eval.pth') |
| torch.save(all_results, results_pth_path) |
| print(f"Saved {results_pth_path}") |
|
|
| |
| rows = [] |
| for r in all_results: |
| row = { |
| 'mixture_id': r['metadata'][0].get('mixture_id', ''), |
| 'mixture_file': r['metadata'][0].get('mixture_file', ''), |
| 'command_type': r['metadata'][0].get('command_variant', {}).get('command_type', ''), |
| 'user_input': r['metadata'][0].get('command_variant', {}).get('user_input', ''), |
| 'target_sources': ', '.join(r['metadata'][0].get('command_variant', {}).get('target_sources', [])), |
| 'scale_invariant_signal_noise_ratio': r['scale_invariant_signal_noise_ratio'][0], |
| 'signal_noise_ratio': r['signal_noise_ratio'][0], |
| 'delta_ITD': r['delta_ITD'][0], |
| 'delta_ILD': r['delta_ILD'][0], |
| 'si_snr': r['si_snr'][0], |
| } |
| rows.append(row) |
| csv_path = os.path.join(args.output_dir, 'results.eval.csv') |
| pd.DataFrame(rows).to_csv(csv_path, index=False) |
| print(f"Saved {csv_path}") |
|
|
| |
| print("\n=== Summary ===") |
| df = pd.DataFrame(rows) |
| for col in ['scale_invariant_signal_noise_ratio', 'signal_noise_ratio', |
| 'delta_ITD', 'delta_ILD', 'si_snr']: |
| vals = df[col].values |
| print(f" {col}: {np.mean(vals):.4f} +/- {np.std(vals):.4f}") |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|