File size: 4,997 Bytes
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41b4ddd
 
 
 
 
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Audio conversion and normalization module - Simplified without noisereduce
Author: Maaldeens
License: MIT
"""

import os
import numpy as np
import librosa
import soundfile as sf
from pydub import AudioSegment
from pathlib import Path
import tempfile
import logging
from typing import Optional
import uuid

logger = logging.getLogger(__name__)

class AudioConverter:
    """
    Converts audio to standard format for ASR processing
    Target: 16kHz mono WAV with normalized volume
    """
    
    def __init__(self, target_sr: int = 16000, target_channels: int = 1,
                 target_dbfs: int = -20, apply_noise_reduction: bool = False):  # Disabled by default
        self.target_sr = target_sr
        self.target_channels = target_channels
        self.target_dbfs = target_dbfs
        self.apply_noise_reduction = False  # Force disable
        self.temp_dir = Path(tempfile.gettempdir()) / "asr_temp"
        self.temp_dir.mkdir(exist_ok=True)
    
    def convert_to_wav(self, input_path: str, output_path: Optional[str] = None) -> str:
        """Convert any audio format to WAV using pydub"""
        if not output_path:
            output_path = str(self.temp_dir / f"{uuid.uuid4()}.wav")
        
        try:
            audio = AudioSegment.from_file(input_path)
            audio.export(output_path, format="wav")
            logger.info(f"Converted {input_path} to WAV: {output_path}")
            return output_path
        except Exception as e:
            logger.error(f"Conversion failed for {input_path}: {e}")
            raise
    
    def resample(self, input_path: str, target_sr: int = None) -> np.ndarray:
        """Resample audio to target sample rate"""
        target_sr = target_sr or self.target_sr
        
        try:
            audio, sr = librosa.load(input_path, sr=None, mono=False)
            if sr != target_sr:
                audio = librosa.resample(audio, orig_sr=sr, target_sr=target_sr)
                logger.info(f"Resampled from {sr}Hz to {target_sr}Hz")
            return audio
        except Exception as e:
            logger.error(f"Resampling failed: {e}")
            raise
    
    def convert_to_mono(self, audio: np.ndarray) -> np.ndarray:
        """Convert stereo to mono by averaging channels"""
        if audio.ndim > 1 and audio.shape[0] == 2:
            mono = np.mean(audio, axis=0)
            logger.info("Converted stereo to mono")
            return mono
        return audio
    
    def normalize_volume(self, audio: np.ndarray, sr: int, target_dbfs: int = None) -> np.ndarray:
        """Normalize audio volume to target dBFS"""
        target_dbfs = target_dbfs or self.target_dbfs
        
        # Simple peak normalization
        max_val = np.max(np.abs(audio))
        if max_val > 0:
            # Target max amplitude of 0.95 to avoid clipping
            target_amplitude = 0.95
            audio = audio * (target_amplitude / max_val)
            logger.info(f"Normalized volume (peak: {max_val:.3f} -> {target_amplitude:.3f})")
        
        return audio
    
    def preprocess(self, input_path: str, output_path: Optional[str] = None) -> str:
        """Complete preprocessing pipeline without noise reduction"""
        if not output_path:
            output_path = str(self.temp_dir / f"processed_{uuid.uuid4()}.wav")
        
        # Step 1: Convert to WAV if needed
        wav_path = self.convert_to_wav(input_path) if not input_path.lower().endswith('.wav') else input_path
        
        # Step 2: Load and resample
        audio = self.resample(wav_path)
        
        # Step 3: Convert to mono
        audio = self.convert_to_mono(audio)
        
        # Step 4: Normalize volume
        audio = self.normalize_volume(audio, self.target_sr)

        # Step 5: Trim leading/trailing silence — prevents Whisper from
        # hallucinating at the end when it encounters long silence.
        # top_db=20 was too aggressive and cut quiet speech at the edges
        # of phone recordings; 35 dB only removes genuine dead air.
        audio, kept = librosa.effects.trim(audio, top_db=35)
        # Seconds cut from the start. Timestamps are measured on the trimmed
        # audio, so the engine adds this back to line them up with the
        # original recording the user replays.
        self.last_trim_offset = float(kept[0]) / self.target_sr if len(kept) else 0.0

        # Step 6: Save processed audio
        sf.write(output_path, audio, self.target_sr)
        logger.info(f"Saved processed audio to {output_path}")
        
        # Cleanup temporary WAV if created
        if wav_path != input_path and Path(wav_path).exists():
            Path(wav_path).unlink()
        
        return output_path
    
    def cleanup(self):
        """Clean up temporary files"""
        for file in self.temp_dir.glob("*.wav"):
            try:
                file.unlink()
            except Exception as e:
                logger.warning(f"Failed to delete {file}: {e}")