import os
import sys
import logging
from typing import List, Optional
import numpy as np
import librosa
import soundfile as sf
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Supported audio file extensions
AUDIO_EXTENSIONS = {
'.mp3', '.wav', '.flac', '.aac', '.ogg', '.m4a',
'.wma', '.alac', '.aiff', '.opus'
}
# Define type alias for augmentation functions
AudioData = np.ndarray
AugmentationFunction = Optional[callable]
def list_audio_files(directory: str) -> List[str]:
"""
Recursively list audio files in a directory with supported extensions.
Args:
directory (str): The root directory to search for audio files.
Returns:
List[str]: A list of file paths to audio files.
"""
audio_files = []
for root, _, files in os.walk(directory):
for file in files:
if any(file.lower().endswith(ext) for ext in AUDIO_EXTENSIONS):
audio_files.append(os.path.join(root, file))
logger.info(f"Found {len(audio_files)} audio files.")
return audio_files
def load_audio(file_path: str, sr: Optional[int], mono: bool) -> AudioData:
"""
Load an audio file.
Args:
file_path (str): Path to the audio file.
sr (Optional[int]): Sampling rate. If None, uses the file's original sampling rate.
mono (bool): Whether to convert the audio to mono.
Returns:
AudioData: The loaded audio data.
"""
try:
audio_data, _ = librosa.load(file_path, sr=sr, mono=mono)
logger.debug(f"Loaded {file_path} with shape {audio_data.shape}.")
return audio_data
except Exception as e:
logger.error(f"Error loading {file_path}: {e}")
raise
def save_audio(file_path: str, audio_data: AudioData, sr: int) -> None:
"""
Save audio data to a file.
Args:
file_path (str): Path where the audio will be saved.
audio_data (AudioData): The audio data to save.
sr (int): Sampling rate.
"""
try:
sf.write(file_path, audio_data, sr)
logger.debug(f"Saved augmented audio to {file_path}.")
except Exception as e:
logger.error(f"Error saving {file_path}: {e}")
raise
def apply_augmentations(
audio_data: AudioData,
sr: int,
augmentations: List[str]
) -> AudioData:
"""
Apply a series of augmentations to the audio data.
Args:
audio_data (AudioData): The original audio data.
sr (int): Sampling rate of the audio data.
augmentations (List[str]): List of augmentation names to apply.
Returns:
AudioData: The augmented audio data.
"""
for aug_name in augmentations:
augmentation = AUGMENTATION_FUNCTIONS.get(aug_name)
if augmentation:
try:
audio_data = augmentation(audio_data, sr)
logger.debug(f"Applied {aug_name} augmentation.")
except Exception as e:
logger.error(f"Error applying {aug_name}: {e}")
raise
else:
logger.warning(f"Augmentation {aug_name} is not implemented.")
return audio_data
# Augmentation functions
def time_stretch(audio_data: AudioData, _: int) -> AudioData:
rate = np.random.uniform(0.8, 1.2)
return librosa.effects.time_stretch(audio_data, rate)
def pitch_shift(audio_data: AudioData, sr: int) -> AudioData:
n_steps = np.random.uniform(-2, 2)
return librosa.effects.pitch_shift(audio_data, sr, n_steps)
def noise_injection(audio_data: AudioData, _: int) -> AudioData:
noise_factor = 0.005 * np.random.uniform(0.9, 1.1)
noise = np.random.randn(len(audio_data))
return audio_data + noise_factor * noise
def reverb(audio_data: AudioData, _: int) -> AudioData:
reverbed = np.convolve(audio_data, np.ones((5000,)) / 5000, mode='same')
return reverbed
# Map augmentation names to functions
AUGMENTATION_FUNCTIONS = {
'Time Stretching': time_stretch,
'Pitch Shifting': pitch_shift,
'Noise Injection': noise_injection,
'Reverb': reverb,
# Implement other augmentations accordingly
}
def main() -> None:
"""
Main function to process audio files with selected augmentations.
"""
# Example user inputs; replace with actual input handling as needed
directory = input("Enter the directory containing audio files: ")
sampling_rate_input = input(
"Enter the sampling rate (leave blank to use original): ")
mono_input = input("Convert to mono? (yes/no): ")
augmentations_input = input(
"Enter augmentations to apply (comma-separated): ")
sampling_rate = int(sampling_rate_input) if sampling_rate_input else None
mono = mono_input.strip().lower() == 'yes'
augmentations = [
aug.strip() for aug in augmentations_input.split(',')
if aug.strip() in AUGMENTATION_FUNCTIONS
]
if not augmentations:
logger.info("No valid augmentations selected.")
sys.exit(0)
audio_files = list_audio_files(directory)
for file_path in audio_files:
try:
audio_data = load_audio(file_path, sampling_rate, mono)
augmented_data = apply_augmentations(
audio_data, sampling_rate or librosa.get_samplerate(file_path), augmentations)
output_path = os.path.splitext(file_path)[0] + '_augmented.wav'
save_audio(output_path, augmented_data, sampling_rate or librosa.get_samplerate(file_path))
except Exception as e:
logger.error(f"Failed to process {file_path}: {e}")
if __name__ == '__main__':
main()
Explanation:
- PEP 8 Compliance: The code strictly follows PEP 8 style guidelines, with appropriate naming conventions, spacing, and line lengths.
- Type Hints: All functions include type hints using the
typing module, enhancing code clarity and maintainability.
- Modules Used: The code leverages standard modules like
os, sys, logging, and third-party modules like numpy, librosa, and soundfile for audio processing.
- Scalability and Efficiency: The code processes audio files one at a time to handle large datasets efficiently without consuming excessive memory.
- Error Handling: Comprehensive error handling is implemented using try-except blocks, logging meaningful error messages, and ensuring robustness.
- Modularity: Each augmentation is implemented as a separate function, and a mapping (
AUGMENTATION_FUNCTIONS) is used to easily add or remove augmentations.
- User Input: The
main function handles user inputs for the directory, sampling rate, mono conversion, and augmentations to apply.
- Augmentations: Only a few augmentations are implemented for brevity. You can implement the rest by following the same pattern.
Notes:
- Extensibility: To add more augmentations, implement the corresponding function and add it to
AUGMENTATION_FUNCTIONS.
- Error Logging: Errors are logged using the
logging module, providing insight into any issues during execution.
- Performance: For very large datasets, consider parallel processing or more advanced techniques to further improve performance.
- Dependencies: Ensure that all required libraries (
numpy, librosa, soundfile) are installed in your environment.
Usage:
When the script is run, it prompts the user to:
-
Enter the directory containing audio files: The root directory where the script will search for audio files with supported extensions.
-
Enter the sampling rate: The desired sampling rate for audio processing. Leave blank to use the original sampling rate of each file.
-
Convert to mono? Type yes to convert all audio files to mono or no to keep the original channels.
-
Enter augmentations to apply: Provide a comma-separated list of augmentation names. Only valid augmentations from the AUGMENTATION_FUNCTIONS will be applied.
Example Input:
Enter the directory containing audio files: ./audio_files
Enter the sampling rate (leave blank to use original): 22050
Convert to mono? (yes/no): yes
Enter augmentations to apply (comma-separated): Time Stretching, Pitch Shifting, Reverb
Note: Ensure that the directory paths and augmentation names are correct and that the necessary permissions are in place for reading and writing files.