File size: 8,841 Bytes
98938e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
"""
Quick test script for OPTION A ensemble.

Tests:
1. Model loading
2. Single audio annotation
3. Batch processing
4. Performance benchmarking
"""

import sys
import logging
import time
import numpy as np
from pathlib import Path

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from ensemble_tts import EnsembleAnnotator

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def test_model_loading():
    """Test 1: Model Loading"""
    logger.info("=" * 60)
    logger.info("TEST 1: Model Loading")
    logger.info("=" * 60)

    try:
        annotator = EnsembleAnnotator(
            mode='quick',  # Start with quick mode for faster testing
            device='cpu',
            enable_events=False  # Disable events for faster testing
        )

        start = time.time()
        annotator.load_models()
        elapsed = time.time() - start

        logger.info(f"βœ… Models loaded successfully in {elapsed:.2f}s")
        return annotator, True
    except Exception as e:
        logger.error(f"❌ Model loading failed: {e}")
        return None, False


def test_single_annotation(annotator):
    """Test 2: Single Audio Annotation"""
    logger.info("\n" + "=" * 60)
    logger.info("TEST 2: Single Audio Annotation")
    logger.info("=" * 60)

    try:
        # Generate dummy audio (3 seconds)
        audio = np.random.randn(16000 * 3).astype(np.float32)

        start = time.time()
        result = annotator.annotate(audio, sample_rate=16000)
        elapsed = time.time() - start

        logger.info(f"\nπŸ“Š Annotation Result:")
        logger.info(f"  Emotion: {result['emotion']['label']}")
        logger.info(f"  Confidence: {result['emotion']['confidence']:.2%}")
        logger.info(f"  Agreement: {result['emotion']['agreement']:.2%}")
        logger.info(f"  Votes: {result['emotion']['votes']}")
        logger.info(f"  Time: {elapsed:.2f}s")

        # Validate result structure
        assert 'emotion' in result
        assert 'label' in result['emotion']
        assert 'confidence' in result['emotion']
        assert result['emotion']['confidence'] >= 0 and result['emotion']['confidence'] <= 1

        logger.info(f"\nβœ… Single annotation successful")
        return True
    except Exception as e:
        logger.error(f"❌ Single annotation failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_batch_processing(annotator):
    """Test 3: Batch Processing"""
    logger.info("\n" + "=" * 60)
    logger.info("TEST 3: Batch Processing")
    logger.info("=" * 60)

    try:
        # Generate 5 dummy audio samples
        batch_size = 5
        audios = [np.random.randn(16000 * (i + 1)).astype(np.float32) for i in range(batch_size)]

        start = time.time()
        results = annotator.annotate_batch(audios, sample_rates=[16000] * batch_size)
        elapsed = time.time() - start

        logger.info(f"\nπŸ“Š Batch Results:")
        for i, result in enumerate(results):
            logger.info(f"  Sample {i+1}: {result['emotion']['label']} ({result['emotion']['confidence']:.2%})")

        logger.info(f"\n  Total time: {elapsed:.2f}s")
        logger.info(f"  Average time per sample: {elapsed/batch_size:.2f}s")

        # Validate
        assert len(results) == batch_size

        logger.info(f"\nβœ… Batch processing successful")
        return True
    except Exception as e:
        logger.error(f"❌ Batch processing failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_balanced_mode():
    """Test 4: Balanced Mode (OPTION A)"""
    logger.info("\n" + "=" * 60)
    logger.info("TEST 4: Balanced Mode (OPTION A)")
    logger.info("=" * 60)

    try:
        annotator_balanced = EnsembleAnnotator(
            mode='balanced',  # 3 models
            device='cpu',
            enable_events=False
        )

        start = time.time()
        annotator_balanced.load_models()
        load_time = time.time() - start
        logger.info(f"  Load time: {load_time:.2f}s")

        # Test annotation
        audio = np.random.randn(16000 * 3).astype(np.float32)

        start = time.time()
        result = annotator_balanced.annotate(audio, sample_rate=16000)
        annotate_time = time.time() - start

        logger.info(f"\nπŸ“Š Balanced Mode Result:")
        logger.info(f"  Emotion: {result['emotion']['label']}")
        logger.info(f"  Confidence: {result['emotion']['confidence']:.2%}")
        logger.info(f"  Agreement: {result['emotion']['agreement']:.2%}")
        logger.info(f"  Number of predictions: {len(result['emotion']['predictions'])}")
        logger.info(f"  Annotation time: {annotate_time:.2f}s")

        # Should have 3 model predictions (OPTION A)
        assert len(result['emotion']['predictions']) == 3, \
            f"Expected 3 predictions, got {len(result['emotion']['predictions'])}"

        logger.info(f"\nβœ… Balanced mode (OPTION A) successful")
        return True
    except Exception as e:
        logger.error(f"❌ Balanced mode failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def benchmark_modes():
    """Test 5: Benchmark All Modes"""
    logger.info("\n" + "=" * 60)
    logger.info("TEST 5: Performance Benchmark")
    logger.info("=" * 60)

    modes = ['quick', 'balanced']
    audio = np.random.randn(16000 * 3).astype(np.float32)

    results = {}

    for mode in modes:
        logger.info(f"\nπŸ“Š Testing {mode.upper()} mode...")

        try:
            annotator = EnsembleAnnotator(
                mode=mode,
                device='cpu',
                enable_events=False
            )

            # Load time
            start = time.time()
            annotator.load_models()
            load_time = time.time() - start

            # Annotation time (average of 3 runs)
            times = []
            for _ in range(3):
                start = time.time()
                result = annotator.annotate(audio, sample_rate=16000)
                times.append(time.time() - start)

            avg_time = np.mean(times)

            results[mode] = {
                'load_time': load_time,
                'avg_annotation_time': avg_time,
                'num_models': len(result['emotion']['predictions'])
            }

            logger.info(f"  Load time: {load_time:.2f}s")
            logger.info(f"  Avg annotation time: {avg_time:.2f}s")
            logger.info(f"  Models: {results[mode]['num_models']}")

        except Exception as e:
            logger.error(f"  ❌ {mode} mode failed: {e}")
            results[mode] = {'error': str(e)}

    # Summary
    logger.info("\n" + "=" * 60)
    logger.info("BENCHMARK SUMMARY")
    logger.info("=" * 60)

    for mode, metrics in results.items():
        if 'error' not in metrics:
            logger.info(f"\n{mode.upper()} MODE:")
            logger.info(f"  Models: {metrics['num_models']}")
            logger.info(f"  Load: {metrics['load_time']:.2f}s")
            logger.info(f"  Annotation: {metrics['avg_annotation_time']:.2f}s/sample")

    return True


def main():
    """Run all tests"""
    logger.info("\n" + "=" * 60)
    logger.info("ENSEMBLE TTS ANNOTATION - QUICK TEST")
    logger.info("OPTION A - Balanced Mode (3 models)")
    logger.info("=" * 60)

    results = {
        'model_loading': False,
        'single_annotation': False,
        'batch_processing': False,
        'balanced_mode': False,
        'benchmark': False
    }

    # Test 1: Model Loading
    annotator, success = test_model_loading()
    results['model_loading'] = success

    if not success:
        logger.error("\n❌ Model loading failed. Cannot continue tests.")
        return False

    # Test 2: Single Annotation
    results['single_annotation'] = test_single_annotation(annotator)

    # Test 3: Batch Processing
    results['batch_processing'] = test_batch_processing(annotator)

    # Test 4: Balanced Mode
    results['balanced_mode'] = test_balanced_mode()

    # Test 5: Benchmark
    results['benchmark'] = benchmark_modes()

    # Summary
    logger.info("\n" + "=" * 60)
    logger.info("TEST SUMMARY")
    logger.info("=" * 60)

    for test_name, success in results.items():
        status = "βœ… PASS" if success else "❌ FAIL"
        logger.info(f"  {test_name}: {status}")

    all_passed = all(results.values())

    if all_passed:
        logger.info("\nπŸŽ‰ ALL TESTS PASSED!")
        logger.info("\nSystem is ready for production use.")
    else:
        logger.error("\n❌ SOME TESTS FAILED")
        logger.error("\nPlease check the logs above for details.")

    logger.info("\n" + "=" * 60)

    return all_passed


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)