File size: 8,902 Bytes
b77cba7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#!/usr/bin/env python3
"""
Benchmark script for VAD + Speaker Diarization
Tests performance on various audio conditions
"""

import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))

import time
import json
import numpy as np
from typing import Dict, List
import argparse

from src.vad import SileroVAD
from src.pipeline import VADDiarizationPipeline
from src.utils import create_test_audio


class Benchmark:
    """Benchmark suite for VAD + Diarization."""
    
    def __init__(self, use_auth_token: str = None):
        """Initialize benchmark."""
        self.use_auth_token = use_auth_token
        self.results = {}
    
    def benchmark_vad_latency(self, durations: List[float] = [1, 5, 10, 30, 60]):
        """Benchmark VAD latency across different audio durations."""
        print("\n" + "="*60)
        print("VAD LATENCY BENCHMARK")
        print("="*60)
        
        vad = SileroVAD(threshold=0.5)
        results = []
        
        for duration in durations:
            print(f"\nTesting {duration}s audio...")
            metrics = vad.benchmark_latency(duration_seconds=duration)
            
            result = {
                'duration_s': duration,
                'processing_time_ms': metrics['total_processing_time_ms'],
                'latency_per_second_ms': metrics['latency_per_second_ms'],
                'real_time_factor': metrics['real_time_factor']
            }
            results.append(result)
            
            print(f"  Processing time: {result['processing_time_ms']:.2f}ms")
            print(f"  Latency/second: {result['latency_per_second_ms']:.2f}ms")
            print(f"  Real-time factor: {result['real_time_factor']:.4f}x")
            
            # Check target
            if result['latency_per_second_ms'] < 100:
                print("  ✅ Target achieved (<100ms)")
            else:
                print("  ⚠️  Above target (>100ms)")
        
        self.results['vad_latency'] = results
        
        # Summary
        avg_latency = np.mean([r['latency_per_second_ms'] for r in results])
        print(f"\n📊 Average latency: {avg_latency:.2f}ms per second")
        
        return results
    
    def benchmark_vad_thresholds(self, thresholds: List[float] = [0.3, 0.5, 0.7]):
        """Benchmark VAD with different sensitivity thresholds."""
        print("\n" + "="*60)
        print("VAD THRESHOLD BENCHMARK")
        print("="*60)
        
        # Create test audio
        test_audio = create_test_audio("test_threshold.wav", duration=10.0)
        results = []
        
        for threshold in thresholds:
            print(f"\nTesting threshold {threshold}...")
            vad = SileroVAD(threshold=threshold)
            
            timestamps, processing_time = vad.process_file(test_audio)
            
            result = {
                'threshold': threshold,
                'num_segments': len(timestamps),
                'processing_time_ms': processing_time,
                'total_speech_time_s': sum(ts['end'] - ts['start'] for ts in timestamps)
            }
            results.append(result)
            
            print(f"  Segments detected: {result['num_segments']}")
            print(f"  Total speech time: {result['total_speech_time_s']:.2f}s")
            print(f"  Processing time: {result['processing_time_ms']:.2f}ms")
        
        self.results['vad_thresholds'] = results
        
        # Cleanup
        Path(test_audio).unlink(missing_ok=True)
        
        return results
    
    def benchmark_full_pipeline(self):
        """Benchmark full VAD + Diarization pipeline."""
        print("\n" + "="*60)
        print("FULL PIPELINE BENCHMARK")
        print("="*60)
        
        if not self.use_auth_token:
            print("⚠️  No HF_TOKEN provided, skipping full pipeline benchmark")
            return None
        
        try:
            # Initialize pipeline
            print("\nInitializing pipeline...")
            pipeline = VADDiarizationPipeline(
                use_auth_token=self.use_auth_token,
                vad_threshold=0.5
            )
            
            # Create test audio
            test_audio = create_test_audio("test_pipeline.wav", duration=30.0)
            
            # Process
            print(f"\nProcessing {test_audio}...")
            result = pipeline.process_file(test_audio)
            
            benchmark_result = {
                'audio_duration_s': 30.0,
                'vad_time_ms': result['processing_time']['vad_ms'],
                'diarization_time_ms': result['processing_time']['diarization_ms'],
                'total_time_ms': result['processing_time']['total_ms'],
                'num_speakers': result['metadata']['num_speakers'],
                'num_segments': result['metadata']['num_segments']
            }
            
            print(f"\n📊 Results:")
            print(f"  VAD time: {benchmark_result['vad_time_ms']:.2f}ms")
            print(f"  Diarization time: {benchmark_result['diarization_time_ms']:.2f}ms")
            print(f"  Total time: {benchmark_result['total_time_ms']:.2f}ms")
            print(f"  Speakers: {benchmark_result['num_speakers']}")
            print(f"  Segments: {benchmark_result['num_segments']}")
            
            self.results['full_pipeline'] = benchmark_result
            
            # Cleanup
            Path(test_audio).unlink(missing_ok=True)
            
            return benchmark_result
            
        except Exception as e:
            print(f"❌ Error: {e}")
            return None
    
    def benchmark_memory_usage(self):
        """Benchmark memory usage."""
        print("\n" + "="*60)
        print("MEMORY USAGE BENCHMARK")
        print("="*60)
        
        import psutil
        import torch
        
        process = psutil.Process()
        
        # Initial memory
        initial_mem = process.memory_info().rss / 1024 / 1024  # MB
        print(f"\nInitial memory: {initial_mem:.2f} MB")
        
        # Load VAD
        print("\nLoading VAD...")
        vad = SileroVAD()
        vad_mem = process.memory_info().rss / 1024 / 1024
        print(f"After VAD: {vad_mem:.2f} MB (+{vad_mem - initial_mem:.2f} MB)")
        
        # GPU memory (if available)
        if torch.cuda.is_available():
            gpu_mem = torch.cuda.memory_allocated() / 1024 / 1024
            print(f"GPU memory: {gpu_mem:.2f} MB")
        
        result = {
            'initial_memory_mb': initial_mem,
            'vad_memory_mb': vad_mem,
            'vad_increase_mb': vad_mem - initial_mem
        }
        
        if torch.cuda.is_available():
            result['gpu_memory_mb'] = gpu_mem
        
        self.results['memory_usage'] = result
        
        return result
    
    def save_results(self, output_path: str = "benchmark_results.json"):
        """Save benchmark results to file."""
        output_file = Path(__file__).parent / output_path
        
        with open(output_file, 'w') as f:
            json.dump(self.results, f, indent=2)
        
        print(f"\n✓ Results saved to: {output_file}")
    
    def run_all(self):
        """Run all benchmarks."""
        print("\n" + "="*60)
        print("RUNNING ALL BENCHMARKS")
        print("="*60)
        
        # VAD latency
        self.benchmark_vad_latency()
        
        # VAD thresholds
        self.benchmark_vad_thresholds()
        
        # Memory usage
        self.benchmark_memory_usage()
        
        # Full pipeline (if token available)
        if self.use_auth_token:
            self.benchmark_full_pipeline()
        
        # Save results
        self.save_results()
        
        print("\n" + "="*60)
        print("✅ ALL BENCHMARKS COMPLETE")
        print("="*60)


def main():
    """Main benchmark runner."""
    parser = argparse.ArgumentParser(description="Run VAD + Diarization benchmarks")
    parser.add_argument(
        '--token',
        type=str,
        default=None,
        help='Hugging Face token for full pipeline benchmark'
    )
    parser.add_argument(
        '--output',
        type=str,
        default='benchmark_results.json',
        help='Output file for results'
    )
    parser.add_argument(
        '--quick',
        action='store_true',
        help='Run quick benchmark (VAD only)'
    )
    
    args = parser.parse_args()
    
    # Get token from args or environment
    token = args.token or os.environ.get('HF_TOKEN')
    
    # Initialize benchmark
    benchmark = Benchmark(use_auth_token=token)
    
    if args.quick:
        # Quick benchmark (VAD only)
        benchmark.benchmark_vad_latency(durations=[1, 5, 10])
        benchmark.save_results(args.output)
    else:
        # Full benchmark suite
        benchmark.run_all()


if __name__ == "__main__":
    import os
    main()