| |
| """ |
| Audio Similarity Evaluation using Spatial CLAP Model |
| |
| This script evaluates the similarity between ground truth and output audio files |
| using the Spatial CLAP model. It processes stereo audio files, extracts embeddings, |
| and calculates cosine similarity scores. |
| |
| Usage: |
| python evaluate_similarity.py /path/to/audio/directory [options] |
| |
| Expected directory structure: |
| data_directory/ |
| ├── 000/ |
| │ ├── gt.wav |
| │ ├── mixture.wav |
| │ └── output.wav |
| ├── 001/ |
| │ ├── gt.wav |
| │ ├── mixture.wav |
| │ └── output.wav |
| └── ... |
| |
| Requirements: |
| - torch>=1.9.0 |
| - torchaudio>=0.9.0 |
| - numpy>=1.21.0 |
| - tqdm>=4.62.0 |
| - transformers>=4.20.0 |
| |
| Author: AI Assistant |
| Date: 2024 |
| """ |
|
|
| import os |
| import sys |
| import torch |
| import torchaudio |
| import numpy as np |
| from pathlib import Path |
| from tqdm import tqdm |
| import argparse |
| from typing import List, Tuple, Dict |
| import warnings |
|
|
| |
| warnings.filterwarnings("ignore") |
|
|
| |
| sys.path.append(os.path.dirname(os.path.abspath(__file__))) |
|
|
| try: |
| from model import CLAPEncoder |
| except ImportError as e: |
| print(f"Error importing Spatial CLAP model: {e}") |
| print("Make sure you're running this script from the SpatialCLAP directory") |
| print("and that all required dependencies are installed:") |
| print("pip install torch torchaudio numpy tqdm transformers") |
| sys.exit(1) |
|
|
|
|
| def load_and_resample_audio(file_path: str, target_sr: int = 16000) -> torch.Tensor: |
| """ |
| Load audio file and resample to target sample rate. |
| |
| Args: |
| file_path: Path to audio file |
| target_sr: Target sample rate (default: 16000 Hz) |
| |
| Returns: |
| Audio tensor of shape (2, time) - stereo audio |
| """ |
| try: |
| waveform, sr = torchaudio.load(file_path) |
| |
| |
| if sr != target_sr: |
| resampler = torchaudio.transforms.Resample(orig_freq=sr, new_freq=target_sr) |
| waveform = resampler(waveform) |
| |
| |
| if waveform.shape[0] == 1: |
| |
| waveform = waveform.repeat(2, 1) |
| elif waveform.shape[0] > 2: |
| |
| waveform = waveform[:2, :] |
| |
| return waveform |
| |
| except Exception as e: |
| raise RuntimeError(f"Error loading audio file {file_path}: {str(e)}") |
|
|
|
|
| def calculate_cosine_similarity(embedding1: torch.Tensor, embedding2: torch.Tensor) -> float: |
| """ |
| Calculate cosine similarity between two embeddings. |
| |
| Args: |
| embedding1: First embedding tensor |
| embedding2: Second embedding tensor |
| |
| Returns: |
| Cosine similarity score (0-1) |
| """ |
| |
| embedding1 = torch.nn.functional.normalize(embedding1, dim=-1) |
| embedding2 = torch.nn.functional.normalize(embedding2, dim=-1) |
| |
| |
| similarity = torch.cosine_similarity(embedding1, embedding2, dim=-1) |
| return similarity.item() |
|
|
|
|
| def process_directory(data_dir: str, model: CLAPEncoder, device: str, batch_size: int = 8) -> List[Dict]: |
| """ |
| Process all subdirectories in the data directory and calculate similarities. |
| |
| Args: |
| data_dir: Path to directory containing subdirectories with audio files |
| model: Loaded Spatial CLAP model |
| device: Device to run inference on |
| batch_size: Number of audio pairs to process in each batch |
| |
| Returns: |
| List of dictionaries containing results for each subdirectory |
| """ |
| results = [] |
| data_path = Path(data_dir) |
| |
| |
| subdirs = [d for d in data_path.iterdir() if d.is_dir()] |
| subdirs.sort() |
| |
| print(f"Found {len(subdirs)} subdirectories to process") |
| |
| if len(subdirs) == 0: |
| print("No subdirectories found in the specified path") |
| return results |
| |
| |
| valid_subdirs = [] |
| for subdir in subdirs: |
| gt_path = subdir / "gt.wav" |
| output_path = subdir / "output.wav" |
| if gt_path.exists() and output_path.exists(): |
| valid_subdirs.append(subdir) |
| else: |
| print(f"Warning: Missing files in {subdir.name} (skipping)") |
| |
| print(f"Processing {len(valid_subdirs)} valid directories in batches of {batch_size}") |
| |
| |
| for batch_start in tqdm(range(0, len(valid_subdirs), batch_size), desc="Processing batches"): |
| batch_end = min(batch_start + batch_size, len(valid_subdirs)) |
| batch_subdirs = valid_subdirs[batch_start:batch_end] |
| |
| try: |
| |
| gt_audios = [] |
| output_audios = [] |
| batch_info = [] |
| |
| for subdir in batch_subdirs: |
| gt_path = subdir / "gt.wav" |
| output_path = subdir / "output.wav" |
| |
| |
| gt_audio = load_and_resample_audio(str(gt_path)) |
| output_audio = load_and_resample_audio(str(output_path)) |
| |
| |
| max_len = max(gt_audio.shape[1], output_audio.shape[1]) |
| |
| if gt_audio.shape[1] < max_len: |
| gt_audio = torch.nn.functional.pad(gt_audio, (0, max_len - gt_audio.shape[1])) |
| if output_audio.shape[1] < max_len: |
| output_audio = torch.nn.functional.pad(output_audio, (0, max_len - output_audio.shape[1])) |
| |
| gt_audios.append(gt_audio) |
| output_audios.append(output_audio) |
| batch_info.append({ |
| 'directory': subdir.name, |
| 'gt_path': str(gt_path), |
| 'output_path': str(output_path) |
| }) |
| |
| |
| gt_batch = torch.stack(gt_audios).to(device) |
| output_batch = torch.stack(output_audios).to(device) |
| |
| |
| with torch.no_grad(): |
| gt_embeddings = model.embed_audio(gt_batch) |
| output_embeddings = model.embed_audio(output_batch) |
| |
| |
| for i, info in enumerate(batch_info): |
| similarity = calculate_cosine_similarity(gt_embeddings[i], output_embeddings[i]) |
| |
| result = { |
| 'directory': info['directory'], |
| 'similarity': similarity, |
| 'gt_path': info['gt_path'], |
| 'output_path': info['output_path'] |
| } |
| results.append(result) |
| |
| except Exception as e: |
| print(f"Error processing batch {batch_start}-{batch_end}: {str(e)}") |
| |
| for subdir in batch_subdirs: |
| try: |
| gt_path = subdir / "gt.wav" |
| output_path = subdir / "output.wav" |
| |
| gt_audio = load_and_resample_audio(str(gt_path)) |
| output_audio = load_and_resample_audio(str(output_path)) |
| |
| |
| max_len = max(gt_audio.shape[1], output_audio.shape[1]) |
| |
| if gt_audio.shape[1] < max_len: |
| gt_audio = torch.nn.functional.pad(gt_audio, (0, max_len - gt_audio.shape[1])) |
| if output_audio.shape[1] < max_len: |
| output_audio = torch.nn.functional.pad(output_audio, (0, max_len - output_audio.shape[1])) |
| |
| |
| gt_audio = gt_audio.unsqueeze(0).to(device) |
| output_audio = output_audio.unsqueeze(0).to(device) |
| |
| |
| with torch.no_grad(): |
| gt_embedding = model.embed_audio(gt_audio) |
| output_embedding = model.embed_audio(output_audio) |
| |
| |
| similarity = calculate_cosine_similarity(gt_embedding, output_embedding) |
| |
| |
| result = { |
| 'directory': subdir.name, |
| 'similarity': similarity, |
| 'gt_path': str(gt_path), |
| 'output_path': str(output_path) |
| } |
| results.append(result) |
| |
| except Exception as individual_error: |
| print(f"Error processing {subdir.name}: {str(individual_error)}") |
| continue |
| |
| return results |
|
|
|
|
| def save_results(results: List[Dict], output_file: str): |
| """ |
| Save results to a text file. |
| |
| Args: |
| results: List of result dictionaries |
| output_file: Path to output file |
| """ |
| try: |
| with open(output_file, 'w') as f: |
| f.write("Directory\tSimilarity\tGT_Path\tOutput_Path\n") |
| for result in results: |
| f.write(f"{result['directory']}\t{result['similarity']:.6f}\t{result['gt_path']}\t{result['output_path']}\n") |
| print(f"Results saved to: {output_file}") |
| except Exception as e: |
| print(f"Error saving results: {str(e)}") |
|
|
|
|
| def print_summary(results: List[Dict]): |
| """ |
| Print summary statistics. |
| |
| Args: |
| results: List of result dictionaries |
| """ |
| if not results: |
| print("No results to summarize") |
| return |
| |
| similarities = [r['similarity'] for r in results] |
| |
| print(f"\n" + "="*60) |
| print(f"SUMMARY STATISTICS") |
| print(f"="*60) |
| print(f"Total processed: {len(results)}") |
| print(f"Mean similarity: {np.mean(similarities):.6f}") |
| print(f"Std similarity: {np.std(similarities):.6f}") |
| print(f"Min similarity: {np.min(similarities):.6f}") |
| print(f"Max similarity: {np.max(similarities):.6f}") |
| print(f"Median similarity: {np.median(similarities):.6f}") |
| print(f"="*60) |
| |
| |
| print(f"\nFirst 10 results:") |
| print(f"{'#':<3} {'Directory':<12} {'Similarity':<12}") |
| print(f"{'-'*3} {'-'*12} {'-'*12}") |
| for i, result in enumerate(results[:10]): |
| print(f"{i+1:<3} {result['directory']:<12} {result['similarity']:.6f}") |
| |
| if len(results) > 10: |
| print(f"... and {len(results) - 10} more results") |
|
|
|
|
| def check_dependencies(): |
| """Check if all required dependencies are available.""" |
| required_modules = ['torch', 'torchaudio', 'numpy', 'tqdm', 'transformers'] |
| missing_modules = [] |
| |
| for module in required_modules: |
| try: |
| __import__(module) |
| except ImportError: |
| missing_modules.append(module) |
| |
| if missing_modules: |
| print("❌ Missing required dependencies:") |
| for module in missing_modules: |
| print(f" - {module}") |
| print("\nPlease install missing dependencies:") |
| print("pip install torch torchaudio numpy tqdm transformers") |
| return False |
| |
| return True |
|
|
|
|
| def main(): |
| """Main function to run the audio similarity evaluation.""" |
| |
| parser = argparse.ArgumentParser( |
| description="Evaluate audio similarity using Spatial CLAP model", |
| formatter_class=argparse.RawDescriptionHelpFormatter, |
| epilog=""" |
| Examples: |
| python evaluate_similarity.py /path/to/audio/directory |
| python evaluate_similarity.py /path/to/audio/directory --output results.txt |
| python evaluate_similarity.py /path/to/audio/directory --device cuda --batch_size 16 |
| python evaluate_similarity.py /path/to/audio/directory --batch_size 4 --device cpu |
| """ |
| ) |
| |
| parser.add_argument( |
| "data_dir", |
| type=str, |
| help="Path to directory containing subdirectories with gt.wav, mixture.wav, output.wav files" |
| ) |
| parser.add_argument( |
| "--output", |
| type=str, |
| default=None, |
| help="Output file for results (default: similarity_results.txt in the data directory)" |
| ) |
| parser.add_argument( |
| "--device", |
| type=str, |
| default="auto", |
| choices=["auto", "cpu", "cuda"], |
| help="Device to use (default: auto)" |
| ) |
| parser.add_argument( |
| "--batch_size", |
| type=int, |
| default=8, |
| help="Batch size for processing (default: 8)" |
| ) |
| parser.add_argument( |
| "--verbose", |
| action="store_true", |
| help="Enable verbose output" |
| ) |
| |
| args = parser.parse_args() |
| |
| |
| print("🎵 Spatial CLAP Audio Similarity Evaluation") |
| print("=" * 50) |
| |
| |
| if not check_dependencies(): |
| sys.exit(1) |
| |
| |
| if args.device == "auto": |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| else: |
| device = args.device |
| |
| print(f"Using device: {device}") |
| |
| |
| if not os.path.exists(args.data_dir): |
| print(f"❌ Error: Data directory {args.data_dir} does not exist") |
| sys.exit(1) |
| |
| |
| if args.output is None: |
| args.output = os.path.join(args.data_dir, "similarity_results.txt") |
| |
| |
| print("🔄 Loading Spatial CLAP model...") |
| try: |
| model = CLAPEncoder() |
| model.load_pretrained() |
| model.to(device) |
| model.eval() |
| print("✅ Model loaded successfully") |
| except Exception as e: |
| print(f"❌ Error loading model: {str(e)}") |
| print("Make sure you're running from the SpatialCLAP directory") |
| sys.exit(1) |
| |
| |
| print(f"🔄 Processing audio files in: {args.data_dir}") |
| print(f"Using batch size: {args.batch_size}") |
| results = process_directory(args.data_dir, model, device, args.batch_size) |
| |
| if not results: |
| print("❌ No results generated") |
| print("Check that your directory structure contains subdirectories with gt.wav and output.wav files") |
| sys.exit(1) |
| |
| |
| save_results(results, args.output) |
| |
| |
| print_summary(results) |
| |
| print(f"\n✅ Evaluation completed successfully!") |
| print(f"📊 Results saved to: {args.output}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |