File size: 6,608 Bytes
0468ff5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Dataset Loader for VocalSense Training
Loads audio files from data/real and data/fake folders.
"""
import numpy as np
from pathlib import Path
from typing import Tuple, List, Dict, Optional
from sklearn.model_selection import train_test_split
from tqdm import tqdm
import warnings
warnings.filterwarnings('ignore')

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

from config import DATA_DIR, SAMPLE_RATE
from utils.audio import load_audio, preprocess_audio
from features.spectral import extract_spectral_features
from features.mfcc import extract_mfcc_features
from features.prosody import extract_prosodic_features


class AudioDataset:
    """
    Dataset loader for real/fake audio classification.
    
    Loads audio from:
    - data/real/ -> label 0 (human)
    - data/fake/ -> label 1 (AI/TTS)
    """
    
    AUDIO_EXTENSIONS = {'.wav', '.mp3', '.flac', '.ogg', '.m4a'}
    
    def __init__(
        self,
        data_dir: Optional[Path] = None,
        test_size: float = 0.1,
        val_size: float = 0.1,
        random_state: int = 42
    ):
        """
        Initialize dataset.
        
        Args:
            data_dir: Path to data directory (default: config.DATA_DIR)
            test_size: Fraction for test set
            val_size: Fraction for validation set
            random_state: Random seed for reproducibility
        """
        self.data_dir = Path(data_dir) if data_dir else DATA_DIR
        self.real_dir = self.data_dir / "real"
        self.fake_dir = self.data_dir / "fake"
        self.test_size = test_size
        self.val_size = val_size
        self.random_state = random_state
        
        # Check directories exist
        if not self.real_dir.exists():
            raise FileNotFoundError(f"Real audio directory not found: {self.real_dir}")
        if not self.fake_dir.exists():
            raise FileNotFoundError(f"Fake audio directory not found: {self.fake_dir}")
    
    def _get_audio_files(self, directory: Path) -> List[Path]:
        """Get all audio files in a directory."""
        files = []
        for ext in self.AUDIO_EXTENSIONS:
            files.extend(directory.glob(f"*{ext}"))
            files.extend(directory.glob(f"*{ext.upper()}"))
        return sorted(files)
    
    def _extract_features(self, audio_path: Path) -> Optional[np.ndarray]:
        """Extract all features from an audio file."""
        try:
            # Load and preprocess
            audio, sr = load_audio(str(audio_path), sr=SAMPLE_RATE)
            if audio is None or len(audio) < sr:  # Skip very short files
                return None
            
            audio = preprocess_audio(audio, sr)
            
            # Extract features
            spectral = extract_spectral_features(audio, sr)
            mfcc = extract_mfcc_features(audio, sr)
            prosody = extract_prosodic_features(audio, sr)
            
            # Combine into single vector
            all_features = {}
            all_features.update(spectral)
            all_features.update(mfcc)
            all_features.update(prosody)
            
            return np.array(list(all_features.values()))
            
        except Exception as e:
            print(f"  Warning: Could not process {audio_path.name}: {e}")
            return None
    
    def load_data(self) -> Tuple[np.ndarray, np.ndarray]:
        """
        Load all audio files and extract features.
        
        Returns:
            Tuple of (features, labels)
        """
        features_list = []
        labels_list = []
        
        # Load real (human) audio - label 0
        real_files = self._get_audio_files(self.real_dir)
        print(f"\nLoading {len(real_files)} real/human audio files...")
        for audio_path in tqdm(real_files, desc="Real audio"):
            features = self._extract_features(audio_path)
            if features is not None:
                features_list.append(features)
                labels_list.append(0)
        
        # Load fake (AI/TTS) audio - label 1
        fake_files = self._get_audio_files(self.fake_dir)
        print(f"\nLoading {len(fake_files)} fake/AI audio files...")
        for audio_path in tqdm(fake_files, desc="Fake audio"):
            features = self._extract_features(audio_path)
            if features is not None:
                features_list.append(features)
                labels_list.append(1)
        
        if len(features_list) == 0:
            raise ValueError("No audio files found or processed successfully!")
        
        features = np.array(features_list)
        labels = np.array(labels_list)
        
        print(f"\nLoaded {len(labels)} samples total:")
        print(f"  - Real/Human: {np.sum(labels == 0)}")
        print(f"  - Fake/AI: {np.sum(labels == 1)}")
        
        return features, labels
    
    def get_splits(self) -> Dict[str, Tuple[np.ndarray, np.ndarray]]:
        """
        Load data and split into train/val/test sets.
        
        Returns:
            Dictionary with 'train', 'val', 'test' keys,
            each containing (features, labels) tuple
        """
        features, labels = self.load_data()
        
        # First split: separate test set
        X_temp, X_test, y_temp, y_test = train_test_split(
            features, labels,
            test_size=self.test_size,
            random_state=self.random_state,
            stratify=labels
        )
        
        # Second split: separate validation from training
        val_ratio = self.val_size / (1 - self.test_size)
        X_train, X_val, y_train, y_val = train_test_split(
            X_temp, y_temp,
            test_size=val_ratio,
            random_state=self.random_state,
            stratify=y_temp
        )
        
        print(f"\nData splits:")
        print(f"  - Train: {len(y_train)} samples")
        print(f"  - Val: {len(y_val)} samples")
        print(f"  - Test: {len(y_test)} samples")
        
        return {
            'train': (X_train, y_train),
            'val': (X_val, y_val),
            'test': (X_test, y_test)
        }


def quick_test():
    """Quick test to verify dataset loading."""
    print("Testing AudioDataset...")
    try:
        dataset = AudioDataset()
        real_files = dataset._get_audio_files(dataset.real_dir)
        fake_files = dataset._get_audio_files(dataset.fake_dir)
        print(f"Found {len(real_files)} real files, {len(fake_files)} fake files")
        return True
    except Exception as e:
        print(f"Error: {e}")
        return False


if __name__ == "__main__":
    quick_test()