Download training/dataset.py from devmm03/vs: direct link, hf CLI and curl.
- Browser
- Download file 6.61 kB
-
https://huggingface.co/spaces/devmm03/vs/resolve/main/training/dataset.py
- Command line
-
hf download hf://spaces/devmm03/vs/training/dataset.py
-
curl -L -o dataset.py https://huggingface.co/spaces/devmm03/vs/resolve/main/training/dataset.py
6.61 kB
| """ | |
| 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() | |