File size: 14,452 Bytes
92e075b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import torchaudio
import numpy as np
import logging
import tempfile
import os
import threading
from typing import List, Tuple, Dict, Optional, Any
import silero_vad
import soundfile as sf
import librosa

logger = logging.getLogger(__name__)

TARGET_CHUNK_DURATION = 30.0
MIN_CHUNK_DURATION = 5.0
SAMPLE_RATE = 16000


class AudioChunker:
    """

    Handles audio chunking with different strategies:

    - 'none': Single chunk (no chunking)

    - 'vad': VAD-based intelligent chunking

    - 'static': Fixed-duration time-based chunking

    """

    _instance = None
    _instance_lock = threading.Lock()
    vad_model: Optional[Any]

    def __new__(cls):
        if cls._instance is None:
            with cls._instance_lock:
                # Check again after acquiring lock as the value could have been set
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
                    # Only load VAD model here since this only runs once
                    cls._instance.vad_model = cls.load_vad_model()
        return cls._instance

    @staticmethod
    def load_vad_model():
        """Load silero VAD model with error handling."""
        try:
            logger.info("Loading Silero VAD model...")
            vad_model = silero_vad.load_silero_vad()
            logger.info("✓ VAD model loaded successfully")
            return vad_model
        except Exception as e:
            logger.error(f"Failed to load VAD model: {e}")
            logger.warning("VAD chunking will fall back to time-based chunking")
            return None

    @torch.inference_mode()
    def chunk_audio(self, audio_tensor: torch.Tensor, sample_rate: int = SAMPLE_RATE, mode: str = "vad", chunk_duration: float = 30.0) -> List[Dict]:
        """

        Chunk audio tensor using specified strategy.



        Args:

            audio_tensor: Audio tensor (1D waveform)

            sample_rate: Sample rate of the audio tensor

            mode: Chunking mode - 'none', 'vad', or 'static'

            chunk_duration: Target duration for static chunking (seconds)



        Returns:

            List of chunk info dicts with uniform format:

            - start_time: Start time in seconds

            - end_time: End time in seconds

            - duration: Duration in seconds

            - audio_data: Audio tensor for this chunk

            - sample_rate: Sample rate

            - chunk_index: Index of this chunk

        """
        logger.info(f"Chunking audio tensor: {audio_tensor.shape} at {sample_rate}Hz (mode: {mode})")

        try:
            # Assert tensor is already 1D (should be preprocessed by MediaTranscriptionProcessor)
            assert len(audio_tensor.shape) == 1, f"Expected 1D audio tensor, got shape {audio_tensor.shape}"

            # Assert sample rate is already 16kHz (should be preprocessed by MediaTranscriptionProcessor)
            assert sample_rate == SAMPLE_RATE, f"Expected {SAMPLE_RATE}Hz sample rate, got {sample_rate}Hz"

            # Route to appropriate chunking strategy
            if mode == "none":
                return self._create_single_chunk(audio_tensor, sample_rate)
            elif mode == "vad":
                if self.vad_model is not None:
                    return self._chunk_with_vad(audio_tensor)
                else:
                    logger.warning("VAD model not available, falling back to static chunking")
                    return self._chunk_static(audio_tensor, chunk_duration)
            elif mode == "static":
                return self._chunk_static(audio_tensor, chunk_duration)
            else:
                raise ValueError(f"Unknown chunking mode: {mode}")

        except Exception as e:
            logger.error(f"Error chunking audio tensor: {e}")
            # Ultimate fallback to single chunk
            return self._create_single_chunk(audio_tensor, sample_rate)

    def _create_single_chunk(self, waveform: torch.Tensor, sample_rate: int = SAMPLE_RATE) -> List[Dict]:
        """Create a single chunk containing the entire audio."""
        duration = len(waveform) / sample_rate

        return [{
            "start_time": 0.0,
            "end_time": duration,
            "duration": duration,
            "audio_data": waveform,
            "sample_rate": sample_rate,
            "chunk_index": 0,
        }]

    def _chunk_static(self, waveform: torch.Tensor, chunk_duration: float) -> List[Dict]:
        """Create fixed-duration chunks."""
        chunks = []
        total_samples = len(waveform)
        target_samples = int(chunk_duration * SAMPLE_RATE)

        start_sample = 0
        chunk_idx = 0

        while start_sample < total_samples:
            end_sample = min(start_sample + target_samples, total_samples)
            chunk_audio = waveform[start_sample:end_sample]
            duration = len(chunk_audio) / SAMPLE_RATE

            # Only add chunk if it meets minimum duration
            if duration >= MIN_CHUNK_DURATION:
                chunks.append({
                    "start_time": start_sample / SAMPLE_RATE,
                    "end_time": end_sample / SAMPLE_RATE,
                    "duration": duration,
                    "audio_data": chunk_audio,
                    "sample_rate": SAMPLE_RATE,
                    "chunk_index": chunk_idx,
                })
                chunk_idx += 1

            start_sample = end_sample

        logger.info(f"Created {len(chunks)} static chunks of ~{chunk_duration}s each")
        return chunks

    def _chunk_fallback(self, audio_path: str) -> List[Dict]:
        """Ultimate fallback - create single chunk using librosa (for file-based legacy method)."""
        try:
            logger.warning("Using librosa fallback for chunking")
            data, sr = librosa.load(audio_path, sr=SAMPLE_RATE)
            waveform = torch.from_numpy(data)
            return self._create_single_chunk(waveform, SAMPLE_RATE)
        except Exception as e:
            logger.error(f"All chunking methods failed: {e}")
            return []
    def _chunk_with_vad(self, waveform: torch.Tensor) -> List[Dict]:
        """Chunk audio using VAD for speech detection with uniform return format."""
        try:
            # VAD model expects tensor on CPU
            vad_waveform = waveform.cpu() if waveform.is_cuda else waveform

            # Get speech timestamps using VAD
            speech_timestamps = silero_vad.get_speech_timestamps(
                vad_waveform,
                self.vad_model,
                sampling_rate=SAMPLE_RATE,
                min_speech_duration_ms=500,  # Minimum speech segment
                min_silence_duration_ms=300,  # Minimum silence to split
                window_size_samples=1536,
                speech_pad_ms=100,  # Padding around speech
            )

            logger.info(f"Found {len(speech_timestamps)} speech segments")

            # Create chunks based on speech segments and target duration
            # Pass original waveform (with device preserved) to chunk creation
            chunks = self._create_chunks_from_speech_segments(
                waveform, speech_timestamps
            )

            logger.info(f"Created {len(chunks)} audio chunks using VAD")
            return chunks

        except Exception as e:
            logger.error(f"VAD chunking failed: {e}")
            return self._chunk_static(waveform, TARGET_CHUNK_DURATION)
    def _create_chunks_from_speech_segments(

        self, waveform: torch.Tensor, speech_segments: List[Dict]

    ) -> List[Dict]:
        """Create chunks that respect speech boundaries and target duration with uniform format."""
        if not speech_segments:
            logger.warning(
                "No speech segments found, falling back to static chunking"
            )
            return self._chunk_static(waveform, TARGET_CHUNK_DURATION)

        chunks = []
        current_chunk_start = 0
        target_samples = int(TARGET_CHUNK_DURATION * SAMPLE_RATE)
        total_samples = len(waveform)
        chunk_idx = 0

        while current_chunk_start < total_samples:
            # Calculate target end for this chunk
            target_chunk_end = current_chunk_start + target_samples

            # If this would be the last chunk or close to it, just take the rest
            if target_chunk_end >= total_samples or (
                total_samples - target_chunk_end
            ) < (target_samples * 0.3):
                chunk_end = total_samples
            else:
                # Find the best place to end this chunk using VAD, but ensure continuous coverage
                chunk_end = self._find_best_chunk_end_continuous(
                    speech_segments,
                    current_chunk_start,
                    target_chunk_end,
                    total_samples,
                )

            # Create chunk with uniform format
            chunk_audio = waveform[current_chunk_start:chunk_end]
            duration = len(chunk_audio) / SAMPLE_RATE

            chunks.append({
                "start_time": current_chunk_start / SAMPLE_RATE,
                "end_time": chunk_end / SAMPLE_RATE,
                "duration": duration,
                "audio_data": chunk_audio,
                "sample_rate": SAMPLE_RATE,
                "chunk_index": chunk_idx,
            })

            logger.info(
                f"Created chunk {chunk_idx + 1}: {current_chunk_start/SAMPLE_RATE:.2f}s - {chunk_end/SAMPLE_RATE:.2f}s ({duration:.2f}s)"
            )
            chunk_idx += 1

            # Move to next chunk - IMPORTANT: start exactly where this chunk ended
            current_chunk_start = chunk_end

        # Verify total coverage
        total_audio_duration = len(waveform) / SAMPLE_RATE
        total_chunks_duration = sum(chunk["duration"] for chunk in chunks)
        logger.info(
            f"Audio chunking complete: {len(chunks)} chunks covering {total_chunks_duration:.2f}s of {total_audio_duration:.2f}s total audio"
        )

        if (
            abs(total_chunks_duration - total_audio_duration) > 0.01
        ):  # Allow 10ms tolerance
            logger.error(
                f"Duration mismatch: chunks={total_chunks_duration:.2f}s, original={total_audio_duration:.2f}s"
            )
        else:
            logger.info("✓ Perfect audio coverage achieved")

        return chunks

    def _find_best_chunk_end_continuous(

        self,

        speech_segments: List[Dict],

        chunk_start: int,

        target_end: int,

        total_samples: int,

    ) -> int:
        """Find the best place to end a chunk while ensuring continuous coverage."""

        # Don't go beyond the audio
        target_end = min(target_end, total_samples)

        # Look for a good break point within a reasonable window around target
        search_window = int(SAMPLE_RATE * 3)  # 3 second window
        search_start = max(chunk_start, target_end - search_window)
        search_end = min(total_samples, target_end + search_window)

        best_end = target_end
        best_score = 0

        # Look for speech segment boundaries within the search window
        for segment in speech_segments:
            segment_start = segment["start"]
            segment_end = segment["end"]

            # Check if segment end is in our search window
            if search_start <= segment_end <= search_end:
                # Score based on how close to target and if it's a good break point
                distance_score = 1.0 - abs(segment_end - target_end) / search_window

                # Prefer segment ends (natural pauses)
                boundary_score = 1.0

                total_score = distance_score * boundary_score

                if total_score > best_score:
                    best_score = total_score
                    best_end = segment_end

        # Ensure we don't go beyond audio bounds
        best_end = min(int(best_end), total_samples)

        # Ensure we make progress (don't end before we started)
        if best_end <= chunk_start:
            best_end = min(target_end, total_samples)

        return best_end

    def _find_best_chunk_end(

        self,

        speech_segments: List[Dict],

        start_idx: int,

        chunk_start: int,

        target_end: int,

    ) -> int:
        """Find the best place to end a chunk (at silence, near target duration)."""

        best_end = target_end

        # Look for speech segments that could provide good break points
        for i in range(start_idx, len(speech_segments)):
            segment = speech_segments[i]
            segment_start = segment["start"]
            segment_end = segment["end"]

            # If segment starts after our target end, use the gap before it
            if segment_start > target_end:
                best_end = min(target_end, segment_start)
                break

            # If segment ends near our target, use the end of the segment
            if abs(segment_end - target_end) < SAMPLE_RATE * 5:  # Within 5 seconds
                best_end = segment_end
                break

            # If segment extends way past target, look for a good break point
            if segment_end > target_end + SAMPLE_RATE * 10:  # 10+ seconds past
                # Try to find a silence gap within the segment or use target
                best_end = target_end
                break

        return int(best_end)

    def save_chunk_to_file(self, chunk: Dict, output_path: str) -> str:
        """Save a chunk to a temporary audio file."""
        try:
            # Convert tensor to numpy if needed
            audio_data = chunk["audio_data"]
            if isinstance(audio_data, torch.Tensor):
                # Move to CPU first if on GPU, then convert to numpy
                audio_data = audio_data.cpu().numpy()

            # Save to file
            sf.write(output_path, audio_data, chunk["sample_rate"])
            return output_path

        except Exception as e:
            logger.error(f"Failed to save chunk to file: {e}")
            raise