File size: 16,624 Bytes
76f9cd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
"""
Integration tests for Speaker Embedding functionality
Tests the complete workflow of speaker unification in distributed transcription
"""

import pytest
import asyncio
import tempfile
import shutil
import json
import numpy as np
from pathlib import Path
from unittest.mock import Mock, patch, AsyncMock, MagicMock
import torch

from src.services.distributed_transcription_service import DistributedTranscriptionService
from src.services.speaker_embedding_service import SpeakerEmbeddingService, SpeakerIdentificationService
from src.utils.config import AudioProcessingConfig


class TestSpeakerEmbeddingIntegration:
    """Integration tests for speaker embedding with distributed transcription"""
    
    def setup_method(self):
        """Setup test environment"""
        self.temp_dir = tempfile.mkdtemp()
        self.service = DistributedTranscriptionService(cache_dir=self.temp_dir)
        
    def teardown_method(self):
        """Cleanup test environment"""
        shutil.rmtree(self.temp_dir, ignore_errors=True)
    
    @pytest.mark.asyncio
    @patch.dict('os.environ', {'HF_TOKEN': 'test_token'})
    async def test_merge_chunk_results_with_speaker_unification(self):
        """Test complete speaker unification workflow in merge_chunk_results"""
        
        # Create realistic chunk results with overlapping speakers
        chunk_results = [
            {
                "processing_status": "success",
                "chunk_start_time": 0.0,
                "audio_duration": 60.0,
                "language_detected": "en",
                "model_used": "turbo",
                "segments": [
                    {"start": 0.0, "end": 5.0, "text": "Hello everyone", "speaker": "SPEAKER_00"},
                    {"start": 5.0, "end": 10.0, "text": "How are you?", "speaker": "SPEAKER_01"},
                    {"start": 10.0, "end": 15.0, "text": "I'm doing well", "speaker": "SPEAKER_00"},
                ]
            },
            {
                "processing_status": "success",
                "chunk_start_time": 60.0,
                "audio_duration": 60.0,
                "language_detected": "en", 
                "model_used": "turbo",
                "segments": [
                    {"start": 0.0, "end": 5.0, "text": "Let's continue", "speaker": "SPEAKER_00"},  # Same as chunk 0 SPEAKER_00
                    {"start": 5.0, "end": 10.0, "text": "Great idea", "speaker": "SPEAKER_01"},    # Same as chunk 0 SPEAKER_01
                    {"start": 10.0, "end": 15.0, "text": "New person here", "speaker": "SPEAKER_02"}, # New speaker
                ]
            }
        ]
        
        with patch('src.services.speaker_embedding_service.SpeakerIdentificationService') as mock_service_class:
            # Configure the mock speaker service
            mock_service = Mock()
            mock_service.unify_distributed_speakers = AsyncMock()
            
            # Create a realistic speaker mapping
            mock_speaker_mapping = {
                "chunk_0_SPEAKER_00": "SPEAKER_GLOBAL_001",  # Person A
                "chunk_0_SPEAKER_01": "SPEAKER_GLOBAL_002",  # Person B
                "chunk_1_SPEAKER_00": "SPEAKER_GLOBAL_001",  # Person A (unified)
                "chunk_1_SPEAKER_01": "SPEAKER_GLOBAL_002",  # Person B (unified)
                "chunk_1_SPEAKER_02": "SPEAKER_GLOBAL_003",  # Person C (new)
            }
            
            mock_service.unify_distributed_speakers.return_value = mock_speaker_mapping
            mock_service_class.return_value = mock_service
            
            # Test the merge functionality
            result = await self.service.merge_chunk_results(
                chunk_results=chunk_results,
                output_format="srt",
                enable_speaker_diarization=True,
                audio_file_path="test_audio.wav"
            )
            
            # Verify the result
            assert result["processing_status"] == "success"
            assert result["speaker_diarization_enabled"] is True
            assert result["speaker_embedding_unified"] is True
            assert result["distributed_processing"] is True
            assert result["chunks_processed"] == 2
            assert result["chunks_failed"] == 0
            
            # Check speaker statistics
            assert result["global_speaker_count"] == 3  # Should be unified to 3 speakers
            expected_speakers = {"SPEAKER_GLOBAL_001", "SPEAKER_GLOBAL_002", "SPEAKER_GLOBAL_003"}
            assert set(result["speakers_detected"]) == expected_speakers
            
            # Check segments have unified speaker labels
            segments = result["segments"]
            assert len(segments) == 6  # Total segments across all chunks
            
            # Verify speaker mappings in segments
            for segment in segments:
                assert "speaker" in segment
                assert segment["speaker"] in expected_speakers
    
    @pytest.mark.asyncio
    async def test_merge_chunk_results_without_speaker_diarization(self):
        """Test merge_chunk_results when speaker diarization is disabled"""
        
        chunk_results = [
            {
                "processing_status": "success",
                "chunk_start_time": 0.0,
                "audio_duration": 60.0,
                "language_detected": "en",
                "model_used": "turbo",
                "segments": [
                    {"start": 0.0, "end": 5.0, "text": "Hello everyone"},
                    {"start": 5.0, "end": 10.0, "text": "How are you?"},
                ]
            }
        ]
        
        result = await self.service.merge_chunk_results(
            chunk_results=chunk_results,
            output_format="srt",
            enable_speaker_diarization=False,
            audio_file_path="test_audio.wav"
        )
        
        # Should not perform speaker unification
        assert result["processing_status"] == "success"
        assert result["speaker_diarization_enabled"] is False
        assert "speaker_embedding_unified" not in result or result["speaker_embedding_unified"] is False
        # Note: global_speaker_count may not be present when speaker diarization is disabled
    
    @pytest.mark.asyncio
    async def test_merge_chunk_results_speaker_unification_failure(self):
        """Test merge_chunk_results when speaker unification fails"""
        
        chunk_results = [
            {
                "processing_status": "success",
                "chunk_start_time": 0.0,
                "audio_duration": 60.0,
                "language_detected": "en",
                "model_used": "turbo",
                "segments": [
                    {"start": 0.0, "end": 5.0, "text": "Hello", "speaker": "SPEAKER_00"},
                ]
            }
        ]
        
        with patch('src.services.speaker_embedding_service.SpeakerIdentificationService') as mock_service_class:
            # Make the speaker service throw an exception
            mock_service = Mock()
            mock_service.unify_distributed_speakers = AsyncMock(side_effect=Exception("Model not available"))
            mock_service_class.return_value = mock_service
            
            result = await self.service.merge_chunk_results(
                chunk_results=chunk_results,
                output_format="srt",
                enable_speaker_diarization=True,
                audio_file_path="test_audio.wav"
            )
            
            # Should continue with original speaker labels
            assert result["processing_status"] == "success"
            assert result["speaker_diarization_enabled"] is True
            assert "speaker_embedding_unified" not in result or result["speaker_embedding_unified"] is False
            
            # Should have chunk-aware speaker labels when unification fails
            segments = result["segments"]
            assert len(segments) == 1
            assert segments[0]["speaker"] == "SPEAKER_CHUNK_0_SPEAKER_00"  # Chunk-aware label when unification fails

    @pytest.mark.asyncio
    async def test_merge_chunk_results_unknown_speaker_filtering(self):
        """Test that UNKNOWN speakers are properly filtered from output"""
        
        service = DistributedTranscriptionService()
        
        # Mock chunk results with mixed speaker types
        chunk_results = [
            {
                "processing_status": "success",
                "chunk_start_time": 0.0,
                "chunk_end_time": 30.0,
                "segments": [
                    {
                        "start": 0.0,
                        "end": 2.0,
                        "text": "Hello world",
                        "speaker": "SPEAKER_00"
                    },
                    {
                        "start": 2.0,
                        "end": 4.0,
                        "text": "This has no speaker",
                        # No speaker field - should become UNKNOWN
                    },
                    {
                        "start": 4.0,
                        "end": 6.0,
                        "text": "Another good segment",
                        "speaker": "SPEAKER_01"
                    }
                ]
            },
            {
                "processing_status": "success",
                "chunk_start_time": 30.0,
                "chunk_end_time": 60.0,
                "segments": [
                    {
                        "start": 0.0,
                        "end": 2.0,
                        "text": "",  # Empty text - should be filtered
                        "speaker": "SPEAKER_00"
                    },
                    {
                        "start": 2.0,
                        "end": 4.0,
                        "text": "Good segment from chunk 2",
                        "speaker": "SPEAKER_00"
                    }
                ]
            }
        ]
        
        # Mock speaker embedding service (not available)
        with patch('src.services.distributed_transcription_service.SpeakerIdentificationService', create=True) as mock_service_class:
            with patch('src.services.distributed_transcription_service.SpeakerEmbeddingService', create=True) as mock_manager_class:
                
                result = await service.merge_chunk_results(
                    chunk_results=chunk_results,
                    output_format="srt",
                    enable_speaker_diarization=False,  # Disable to focus on filtering logic
                    audio_file_path="test.wav"
                )
                
                # Verify basic result structure
                assert result["processing_status"] == "success"
                assert result["chunks_processed"] == 2
                assert result["chunks_failed"] == 0
                
                # Verify filtering statistics
                assert "total_segments_collected" in result
                assert "unknown_segments_filtered" in result
                assert result["total_segments_collected"] == 5  # Total segments before filtering (4 with data + 1 empty)
                assert result["unknown_segments_filtered"] == 1  # One segment with no speaker
                assert result["segment_count"] == 4  # Known speaker segments after first filtering (including empty text)
                
                # Verify segments content (this will be the final filtered segments)
                segments = result["segments"]
                assert len(segments) == 4  # Known speaker segments (including empty text ones)
                
                # Check that all segments have speakers (but may have empty text)
                for segment in segments:
                    assert "speaker" in segment
                    assert segment["speaker"] != "UNKNOWN"
                    # Note: segments array includes all known-speaker segments,
                    # but full_text and output files filter empty text
                
                # Verify text content (should not include UNKNOWN segment)
                full_text = result["text"]
                assert "This has no speaker" not in full_text  # UNKNOWN segment filtered
                assert "Hello world" in full_text
                assert "Another good segment" in full_text
                assert "Good segment from chunk 2" in full_text


class TestSpeakerEmbeddingWorkflow:
    """Test complete workflow scenarios"""
    
    def setup_method(self):
        """Setup test environment"""
        self.temp_dir = tempfile.mkdtemp()
        
    def teardown_method(self):
        """Cleanup test environment"""
        shutil.rmtree(self.temp_dir, ignore_errors=True)
    
    @pytest.mark.asyncio
    @patch.dict('os.environ', {'HF_TOKEN': 'test_token'})
    async def test_end_to_end_speaker_unification(self):
        """Test complete end-to-end speaker unification workflow"""
        
        # Setup services
        embedding_service = SpeakerEmbeddingService(
            storage_path=str(Path(self.temp_dir) / "speakers.json")
        )
        speaker_service = SpeakerIdentificationService(embedding_service)
        
        # Mock the models
        speaker_service.embedding_model = Mock()
        
        # Create test chunk results representing a conversation between 2 people
        # but each chunk detects them as different local speakers
        chunk_results = [
            {
                "processing_status": "success",
                "chunk_start_time": 0,
                "segments": [
                    {"start": 0, "end": 3, "text": "Hi there", "speaker": "SPEAKER_00"},
                    {"start": 3, "end": 6, "text": "Hello", "speaker": "SPEAKER_01"},
                ]
            },
            {
                "processing_status": "success",
                "chunk_start_time": 60,
                "segments": [
                    {"start": 0, "end": 3, "text": "How are things?", "speaker": "SPEAKER_00"},  # Same person as chunk 0 SPEAKER_00
                    {"start": 3, "end": 6, "text": "Going well", "speaker": "SPEAKER_01"},      # Same person as chunk 0 SPEAKER_01
                ]
            }
        ]
        
        # Create consistent embeddings for same speakers
        person_a_base = np.zeros(512)
        person_a_base[0] = 1.0  # Person A concentrated at index 0
        
        person_b_base = np.zeros(512)
        person_b_base[256] = 1.0  # Person B concentrated at index 256
        
        def mock_crop_side_effect(waveform, segment):
            # Return consistent embeddings for same speakers across chunks
            segment_start = float(segment.start)
            if segment_start < 3 or (segment_start >= 60 and segment_start < 63):
                # Person A in both chunks
                return torch.tensor(person_a_base + np.random.normal(0, 0.005, 512))
            else:
                # Person B in both chunks  
                return torch.tensor(person_b_base + np.random.normal(0, 0.005, 512))
        
        mock_inference = Mock()
        mock_inference.crop.side_effect = mock_crop_side_effect
        mock_waveform = torch.rand(1, 96000)  # 6 seconds at 16kHz
        
        with patch('torchaudio.load', return_value=(mock_waveform, 16000)), \
             patch('pyannote.audio.core.inference.Inference', return_value=mock_inference):
            
            # Perform speaker unification
            mapping = await speaker_service.unify_distributed_speakers(
                chunk_results, "test_audio.wav"
            )
            
            # Verify mapping results
            assert len(mapping) == 4  # 2 speakers × 2 chunks
            
            # Same speakers should map to same global IDs
            chunk_0_speaker_00 = mapping["chunk_0_SPEAKER_00"]
            chunk_1_speaker_00 = mapping["chunk_1_SPEAKER_00"]
            chunk_0_speaker_01 = mapping["chunk_0_SPEAKER_01"]
            chunk_1_speaker_01 = mapping["chunk_1_SPEAKER_01"]
            
            # Verify unification worked
            assert chunk_0_speaker_00 == chunk_1_speaker_00  # Same person A
            assert chunk_0_speaker_01 == chunk_1_speaker_01  # Same person B
            assert chunk_0_speaker_00 != chunk_0_speaker_01  # Different people
            
            # Verify global speaker IDs are properly formatted
            assert chunk_0_speaker_00.startswith("SPEAKER_GLOBAL_")
            assert chunk_0_speaker_01.startswith("SPEAKER_GLOBAL_")


if __name__ == "__main__":
    pytest.main([__file__, "-v"])