| |
| """ |
| Temporal Dynamics Score Calculator for Audio Evaluation |
| |
| Calculates temporal dynamics similarity scores between ground truth and output audio files |
| based on normalized temporal differences of magnitude spectrograms. |
| |
| The metric: |
| 1. Converts audio to magnitude spectrogram M(f, t) via STFT |
| 2. Takes temporal differences ΔM(f, t) = M(f, t+1) - M(f, t) |
| 3. L2-normalizes each frequency bin's time-difference vector |
| 4. Computes cosine similarity between normalized pred and target |
| 5. Returns cosine similarity (1 = perfect alignment, -1 = opposite) |
| |
| Usage: |
| python calculate_temporal_dynamics.py [--input-dir INPUT_DIR] [--n-fft N_FFT] [--hop-length HOP_LENGTH] |
| """ |
|
|
| import os |
| import sys |
| import argparse |
| import logging |
| from pathlib import Path |
| from typing import List, Tuple, Dict, Optional |
| import warnings |
|
|
| import torch |
| import torchaudio |
| import numpy as np |
| import pandas as pd |
| from tqdm import tqdm |
| import matplotlib.pyplot as plt |
| import matplotlib.gridspec as gridspec |
|
|
| |
| logging.basicConfig( |
| level=logging.INFO, |
| format='%(asctime)s - %(levelname)s - %(message)s' |
| ) |
| logger = logging.getLogger(__name__) |
|
|
| |
| warnings.filterwarnings('ignore') |
|
|
|
|
| class AudioProcessor: |
| """Handles audio loading and preprocessing for temporal dynamics calculation.""" |
| |
| def __init__(self, target_sample_rate: int = 16000, n_fft: int = 1024, |
| hop_length: int = 512, eps: float = 1e-8): |
| """ |
| Initialize audio processor. |
| |
| Args: |
| target_sample_rate: Sample rate to resample audio to |
| n_fft: FFT window size for STFT |
| hop_length: Hop length for STFT |
| eps: Epsilon for numerical stability in normalization |
| """ |
| self.target_sample_rate = target_sample_rate |
| self.n_fft = n_fft |
| self.hop_length = hop_length |
| self.eps = eps |
| self.resampler = None |
| self._last_sr = None |
| |
| def load_audio(self, audio_path: str) -> torch.Tensor: |
| """ |
| Load audio file and resample to target sample rate. |
| |
| Args: |
| audio_path: Path to the audio file |
| |
| Returns: |
| Audio tensor at target sample rate, shape (channels, time) |
| """ |
| try: |
| |
| waveform, sample_rate = torchaudio.load(audio_path) |
| |
| |
| if sample_rate != self.target_sample_rate: |
| if self.resampler is None or self._last_sr != sample_rate: |
| self.resampler = torchaudio.transforms.Resample( |
| orig_freq=sample_rate, |
| new_freq=self.target_sample_rate |
| ) |
| self._last_sr = sample_rate |
| waveform = self.resampler(waveform) |
| |
| return waveform |
| |
| except Exception as e: |
| logger.error(f"Error loading audio {audio_path}: {e}") |
| raise |
| |
| def compute_magnitude_spectrogram(self, waveform: torch.Tensor) -> torch.Tensor: |
| """ |
| Compute magnitude spectrogram using STFT. |
| |
| Args: |
| waveform: Audio tensor, shape (channels, time) |
| |
| Returns: |
| Magnitude spectrogram, shape (channels, freq_bins, time_frames) |
| """ |
| |
| if waveform.shape[0] > 1: |
| waveform = torch.mean(waveform, dim=0, keepdim=True) |
| |
| |
| stft = torch.stft( |
| waveform.squeeze(0), |
| n_fft=self.n_fft, |
| hop_length=self.hop_length, |
| window=torch.hann_window(self.n_fft), |
| return_complex=True |
| ) |
| |
| |
| magnitude = torch.abs(stft) |
| |
| return magnitude |
| |
| def compute_temporal_differences(self, magnitude: torch.Tensor) -> torch.Tensor: |
| """ |
| Compute frame-to-frame temporal differences. |
| |
| Args: |
| magnitude: Magnitude spectrogram, shape (freq_bins, time_frames) |
| |
| Returns: |
| Temporal differences ΔM(f, t) = M(f, t+1) - M(f, t), shape (freq_bins, time_frames-1) |
| """ |
| |
| delta_m = magnitude[:, 1:] - magnitude[:, :-1] |
| |
| return delta_m |
| |
| def normalize_frequency_bins(self, delta_m: torch.Tensor) -> torch.Tensor: |
| """ |
| L2-normalize each frequency bin's temporal difference vector. |
| |
| Args: |
| delta_m: Temporal differences, shape (freq_bins, time_frames) |
| |
| Returns: |
| Normalized temporal differences, shape (freq_bins, time_frames) |
| """ |
| |
| |
| norms = torch.sqrt(torch.sum(delta_m ** 2, dim=1, keepdim=True)) |
| |
| |
| norms = torch.clamp(norms, min=self.eps) |
| |
| |
| delta_m_normalized = delta_m / norms |
| |
| return delta_m_normalized |
| |
| def compute_temporal_dynamics_score(self, pred_path: str, target_path: str) -> float: |
| """ |
| Compute temporal dynamics similarity score between prediction and target. |
| |
| Args: |
| pred_path: Path to predicted audio file |
| target_path: Path to target (ground truth) audio file |
| |
| Returns: |
| Cosine similarity score (1 = perfect alignment, -1 = opposite) |
| """ |
| |
| pred_waveform = self.load_audio(pred_path) |
| target_waveform = self.load_audio(target_path) |
| |
| |
| pred_mag = self.compute_magnitude_spectrogram(pred_waveform) |
| target_mag = self.compute_magnitude_spectrogram(target_waveform) |
| |
| |
| min_time = min(pred_mag.shape[1], target_mag.shape[1]) |
| pred_mag = pred_mag[:, :min_time] |
| target_mag = target_mag[:, :min_time] |
| |
| |
| pred_delta = self.compute_temporal_differences(pred_mag) |
| target_delta = self.compute_temporal_differences(target_mag) |
| |
| |
| pred_delta_norm = self.normalize_frequency_bins(pred_delta) |
| target_delta_norm = self.normalize_frequency_bins(target_delta) |
| |
| |
| pred_vector = pred_delta_norm.flatten() |
| target_vector = target_delta_norm.flatten() |
| |
| |
| cosine_sim = torch.nn.functional.cosine_similarity( |
| pred_vector.unsqueeze(0), |
| target_vector.unsqueeze(0), |
| dim=1 |
| ).item() |
| |
| return cosine_sim |
|
|
|
|
| class FilePairMatcher: |
| """Matches ground truth and output audio files.""" |
| |
| @staticmethod |
| def find_audio_pairs(directory: Path) -> List[Tuple[str, str]]: |
| """ |
| Find matching gt_*.wav and output_*.wav pairs in a directory. |
| Pairs all gt files with all output files in the same directory. |
| |
| Args: |
| directory: Directory to search for audio pairs |
| |
| Returns: |
| List of tuples (gt_file, output_file) |
| """ |
| pairs = [] |
| |
| |
| gt_files = sorted(directory.glob("gt_*.wav")) |
| output_files = sorted(directory.glob("output_*.wav")) |
| |
| if not gt_files or not output_files: |
| return pairs |
| |
| |
| |
| for output_file in output_files: |
| for gt_file in gt_files: |
| pairs.append((str(gt_file), str(output_file))) |
| |
| return pairs |
|
|
|
|
| def calculate_temporal_dynamics_scores( |
| input_dir: str, |
| sample_rate: int = 16000, |
| n_fft: int = 1024, |
| hop_length: int = 512, |
| eps: float = 1e-8 |
| ) -> pd.DataFrame: |
| """ |
| Calculate temporal dynamics scores for all audio pairs in subdirectories. |
| |
| Args: |
| input_dir: Path to eval_outputs directory |
| sample_rate: Target sample rate for audio processing |
| n_fft: FFT window size for STFT |
| hop_length: Hop length for STFT |
| eps: Epsilon for numerical stability |
| |
| Returns: |
| DataFrame with columns: subdirectory, gt_file, output_file, temporal_dynamics_score |
| """ |
| input_path = Path(input_dir) |
| if not input_path.exists(): |
| raise ValueError(f"Input directory does not exist: {input_dir}") |
| |
| |
| audio_processor = AudioProcessor( |
| target_sample_rate=sample_rate, |
| n_fft=n_fft, |
| hop_length=hop_length, |
| eps=eps |
| ) |
| file_matcher = FilePairMatcher() |
| |
| |
| subdirs = sorted([d for d in input_path.iterdir() if d.is_dir()]) |
| logger.info(f"Found {len(subdirs)} subdirectories to process") |
| logger.info(f"STFT parameters: n_fft={n_fft}, hop_length={hop_length}, sample_rate={sample_rate}") |
| |
| |
| results = [] |
| |
| |
| for subdir in tqdm(subdirs, desc="Processing directories"): |
| subdir_name = subdir.name |
| |
| |
| pairs = file_matcher.find_audio_pairs(subdir) |
| |
| if not pairs: |
| logger.warning(f"No audio pairs found in {subdir_name}") |
| continue |
| |
| |
| for gt_file, output_file in pairs: |
| try: |
| |
| td_score = audio_processor.compute_temporal_dynamics_score( |
| pred_path=output_file, |
| target_path=gt_file |
| ) |
| |
| |
| result = { |
| 'subdirectory': subdir_name, |
| 'gt_file': Path(gt_file).name, |
| 'output_file': Path(output_file).name, |
| 'temporal_dynamics_score': td_score |
| } |
| |
| results.append(result) |
| |
| except Exception as e: |
| logger.error( |
| f"Error processing pair in {subdir_name}: " |
| f"{Path(gt_file).name} vs {Path(output_file).name}: {e}" |
| ) |
| continue |
| |
| |
| df = pd.DataFrame(results) |
| logger.info(f"Processed {len(results)} audio pairs successfully") |
| |
| return df |
|
|
|
|
| def generate_visualization_plot( |
| df: pd.DataFrame, |
| input_dir: str, |
| audio_processor: AudioProcessor, |
| output_path: str |
| ) -> None: |
| """ |
| Generate a visualization plot showing 5 examples (one from each score range). |
| |
| Args: |
| df: DataFrame with temporal dynamics scores |
| input_dir: Path to eval_outputs directory |
| audio_processor: AudioProcessor instance for computing spectrograms |
| output_path: Path to save the plot |
| """ |
| |
| score_ranges = [ |
| (0.0, 0.2, "[0.0-0.2)"), |
| (0.2, 0.4, "[0.2-0.4)"), |
| (0.4, 0.6, "[0.4-0.6)"), |
| (0.6, 0.8, "[0.6-0.8)"), |
| (0.8, 1.0, "[0.8-1.0]") |
| ] |
| |
| |
| examples = [] |
| for min_score, max_score, label in score_ranges: |
| if max_score == 1.0: |
| mask = (df['temporal_dynamics_score'] >= min_score) & (df['temporal_dynamics_score'] <= max_score) |
| else: |
| mask = (df['temporal_dynamics_score'] >= min_score) & (df['temporal_dynamics_score'] < max_score) |
| |
| candidates = df[mask] |
| if len(candidates) > 0: |
| |
| target_score = (min_score + max_score) / 2 |
| idx = (candidates['temporal_dynamics_score'] - target_score).abs().idxmin() |
| example = candidates.loc[idx] |
| examples.append((example, label)) |
| else: |
| logger.warning(f"No examples found in range {label}") |
| |
| if not examples: |
| logger.warning("No examples found for visualization") |
| return |
| |
| |
| n_examples = len(examples) |
| fig = plt.figure(figsize=(20, 4 * n_examples)) |
| gs = gridspec.GridSpec(n_examples, 4, figure=fig, hspace=0.4, wspace=0.3) |
| |
| input_path = Path(input_dir) |
| |
| for idx, (example, range_label) in enumerate(examples): |
| score = example['temporal_dynamics_score'] |
| subdir = example['subdirectory'] |
| gt_file = example['gt_file'] |
| output_file = example['output_file'] |
| |
| |
| gt_path = str(input_path / subdir / gt_file) |
| output_path_full = str(input_path / subdir / output_file) |
| |
| try: |
| |
| gt_waveform = audio_processor.load_audio(gt_path) |
| output_waveform = audio_processor.load_audio(output_path_full) |
| |
| |
| gt_mag = audio_processor.compute_magnitude_spectrogram(gt_waveform) |
| output_mag = audio_processor.compute_magnitude_spectrogram(output_waveform) |
| |
| |
| min_time = min(gt_mag.shape[1], output_mag.shape[1]) |
| gt_mag = gt_mag[:, :min_time] |
| output_mag = output_mag[:, :min_time] |
| |
| |
| gt_delta = audio_processor.compute_temporal_differences(gt_mag) |
| output_delta = audio_processor.compute_temporal_differences(output_mag) |
| |
| |
| gt_delta_norm = audio_processor.normalize_frequency_bins(gt_delta) |
| output_delta_norm = audio_processor.normalize_frequency_bins(output_delta) |
| |
| |
| gt_mag_np = gt_mag.numpy() |
| output_mag_np = output_mag.numpy() |
| gt_delta_norm_np = gt_delta_norm.numpy() |
| output_delta_norm_np = output_delta_norm.numpy() |
| |
| |
| ax1 = fig.add_subplot(gs[idx, 0]) |
| im1 = ax1.imshow( |
| 20 * np.log10(gt_mag_np + 1e-8), |
| aspect='auto', |
| origin='lower', |
| cmap='viridis', |
| interpolation='nearest' |
| ) |
| ax1.set_title(f'GT Magnitude Spectrogram\n{subdir}', fontsize=10) |
| ax1.set_ylabel('Frequency Bin') |
| ax1.set_xlabel('Time Frame') |
| plt.colorbar(im1, ax=ax1, label='dB') |
| |
| |
| ax2 = fig.add_subplot(gs[idx, 1]) |
| im2 = ax2.imshow( |
| 20 * np.log10(output_mag_np + 1e-8), |
| aspect='auto', |
| origin='lower', |
| cmap='viridis', |
| interpolation='nearest' |
| ) |
| ax2.set_title(f'Output Magnitude Spectrogram\n{output_file}', fontsize=10) |
| ax2.set_ylabel('Frequency Bin') |
| ax2.set_xlabel('Time Frame') |
| plt.colorbar(im2, ax=ax2, label='dB') |
| |
| |
| ax3 = fig.add_subplot(gs[idx, 2]) |
| vmax = max(np.abs(gt_delta_norm_np).max(), 0.1) |
| im3 = ax3.imshow( |
| gt_delta_norm_np, |
| aspect='auto', |
| origin='lower', |
| cmap='RdBu_r', |
| vmin=-vmax, |
| vmax=vmax, |
| interpolation='nearest' |
| ) |
| ax3.set_title('GT Normalized Temporal Δ', fontsize=10) |
| ax3.set_ylabel('Frequency Bin') |
| ax3.set_xlabel('Time Frame') |
| plt.colorbar(im3, ax=ax3, label='Normalized Δ') |
| |
| |
| ax4 = fig.add_subplot(gs[idx, 3]) |
| vmax = max(np.abs(output_delta_norm_np).max(), 0.1) |
| im4 = ax4.imshow( |
| output_delta_norm_np, |
| aspect='auto', |
| origin='lower', |
| cmap='RdBu_r', |
| vmin=-vmax, |
| vmax=vmax, |
| interpolation='nearest' |
| ) |
| ax4.set_title(f'Output Normalized Temporal Δ\nScore: {score:.4f} {range_label}', fontsize=10) |
| ax4.set_ylabel('Frequency Bin') |
| ax4.set_xlabel('Time Frame') |
| plt.colorbar(im4, ax=ax4, label='Normalized Δ') |
| |
| except Exception as e: |
| logger.error(f"Error processing example {subdir}/{output_file}: {e}") |
| continue |
| |
| plt.suptitle('Temporal Dynamics Metric Visualization\n(Red=energy increase, Blue=energy decrease)', |
| fontsize=14, fontweight='bold', y=0.995) |
| |
| |
| plt.savefig(output_path, dpi=150, bbox_inches='tight') |
| plt.close() |
| logger.info(f"Saved visualization plot to: {output_path}") |
|
|
|
|
| def generate_summary_statistics(df: pd.DataFrame) -> str: |
| """ |
| Generate summary statistics from temporal dynamics scores. |
| |
| Args: |
| df: DataFrame with temporal dynamics scores |
| |
| Returns: |
| Formatted summary statistics string |
| """ |
| summary = [] |
| summary.append("=" * 70) |
| summary.append("TEMPORAL DYNAMICS SCORE SUMMARY STATISTICS") |
| summary.append("=" * 70) |
| summary.append("") |
| summary.append(f"Total Comparisons: {len(df)}") |
| summary.append("") |
| |
| if 'temporal_dynamics_score' in df.columns: |
| scores = df['temporal_dynamics_score'].values |
| summary.append("─" * 70) |
| summary.append("Temporal Dynamics Score (1 = perfect, -1 = opposite):") |
| summary.append("─" * 70) |
| summary.append(f" Mean: {np.mean(scores):.6f}") |
| summary.append(f" Median: {np.median(scores):.6f}") |
| summary.append(f" Std Dev: {np.std(scores):.6f}") |
| summary.append(f" Min: {np.min(scores):.6f}") |
| summary.append(f" Max: {np.max(scores):.6f}") |
| summary.append("") |
| summary.append(" Quartiles:") |
| summary.append(f" Q1 (25%): {np.percentile(scores, 25):.6f}") |
| summary.append(f" Q2 (50%): {np.percentile(scores, 50):.6f}") |
| summary.append(f" Q3 (75%): {np.percentile(scores, 75):.6f}") |
| summary.append("") |
| summary.append(" Distribution:") |
| summary.append(f" [-1.0-0.0): {np.sum((scores >= -1.0) & (scores < 0.0))} samples") |
| summary.append(f" [0.0-0.2): {np.sum((scores >= 0.0) & (scores < 0.2))} samples") |
| summary.append(f" [0.2-0.4): {np.sum((scores >= 0.2) & (scores < 0.4))} samples") |
| summary.append(f" [0.4-0.6): {np.sum((scores >= 0.4) & (scores < 0.6))} samples") |
| summary.append(f" [0.6-0.8): {np.sum((scores >= 0.6) & (scores < 0.8))} samples") |
| summary.append(f" [0.8-1.0]: {np.sum((scores >= 0.8) & (scores <= 1.0))} samples") |
| summary.append("") |
| |
| summary.append("=" * 70) |
| |
| return "\n".join(summary) |
|
|
|
|
| def main(): |
| """Main function to run temporal dynamics score calculation.""" |
| parser = argparse.ArgumentParser( |
| description="Calculate temporal dynamics scores for audio evaluation" |
| ) |
| parser.add_argument( |
| '--input-dir', |
| type=str, |
| default='/home/karan/sda_link/GitHub/EMMA2/EMMA2_text_conditioning_contextual/eval_outputs', |
| help='Input directory containing subdirectories with audio files' |
| ) |
| parser.add_argument( |
| '--sample-rate', |
| type=int, |
| default=16000, |
| help='Target sample rate for audio processing (default: 16000)' |
| ) |
| parser.add_argument( |
| '--n-fft', |
| type=int, |
| default=1024, |
| help='FFT window size for STFT (default: 1024)' |
| ) |
| parser.add_argument( |
| '--hop-length', |
| type=int, |
| default=256, |
| help='Hop length for STFT (default: 512)' |
| ) |
| parser.add_argument( |
| '--eps', |
| type=float, |
| default=1e-8, |
| help='Epsilon for numerical stability in normalization (default: 1e-8)' |
| ) |
| |
| args = parser.parse_args() |
| |
| logger.info("Starting temporal dynamics score calculation...") |
| logger.info(f"Input directory: {args.input_dir}") |
| logger.info(f"STFT parameters: n_fft={args.n_fft}, hop_length={args.hop_length}") |
| logger.info(f"Sample rate: {args.sample_rate} Hz") |
| logger.info(f"Epsilon: {args.eps}") |
| |
| |
| audio_processor = AudioProcessor( |
| target_sample_rate=args.sample_rate, |
| n_fft=args.n_fft, |
| hop_length=args.hop_length, |
| eps=args.eps |
| ) |
| |
| |
| df = calculate_temporal_dynamics_scores( |
| args.input_dir, |
| sample_rate=args.sample_rate, |
| n_fft=args.n_fft, |
| hop_length=args.hop_length, |
| eps=args.eps |
| ) |
| |
| if df.empty: |
| logger.error("No results generated. Please check your input directory.") |
| return |
| |
| |
| csv_path = Path(args.input_dir) / "temporal_dynamics_scores.csv" |
| df.to_csv(csv_path, index=False) |
| logger.info(f"Saved CSV results to: {csv_path}") |
| |
| |
| summary = generate_summary_statistics(df) |
| summary_path = Path(args.input_dir) / "temporal_dynamics_summary.txt" |
| with open(summary_path, 'w') as f: |
| f.write(summary) |
| logger.info(f"Saved summary statistics to: {summary_path}") |
| |
| |
| print("\n" + summary) |
| |
| |
| logger.info("Generating visualization plot...") |
| plot_path = Path(args.input_dir) / "temporal_dynamics_visualization.png" |
| generate_visualization_plot(df, args.input_dir, audio_processor, str(plot_path)) |
| |
| logger.info("Temporal dynamics score calculation completed successfully!") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|