import os
import logging
from typing import List, Tuple, Optional
import numpy as np
import pandas as pd
import librosa
from transformers import AutoTokenizer
import torch
from torch.utils.data import Dataset, DataLoader
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def load_and_augment_audio(audio_path: str, augment: bool = True) -> Optional[np.ndarray]:
"""
Load an audio file and perform augmentation.
Args:
audio_path (str): Path to the audio file.
augment (bool): Whether to perform augmentation.
Returns:
Optional[np.ndarray]: Audio time series data, or None if loading fails.
"""
try:
audio, sr = librosa.load(audio_path, sr=None)
if augment:
audio = augment_audio(audio, sr)
return audio
except Exception as e:
logger.error(f"Error loading audio file {audio_path}: {e}")
return None
def augment_audio(audio: np.ndarray, sr: int) -> np.ndarray:
"""
Perform audio augmentation.
Args:
audio (np.ndarray): Audio time series data.
sr (int): Sampling rate.
Returns:
np.ndarray: Augmented audio data.
"""
audio_aug = audio.copy()
# Add random noise
noise = np.random.randn(len(audio_aug))
audio_aug = audio_aug + 0.005 * noise
# Pitch shift
n_steps = np.random.uniform(-2, 2)
audio_aug = librosa.effects.pitch_shift(audio_aug, sr, n_steps)
# Time stretch
rate = np.random.uniform(0.9, 1.1)
audio_aug = librosa.effects.time_stretch(audio_aug, rate)
return audio_aug
def tokenize_text(text: str, tokenizer) -> List[int]:
"""
Tokenize text into tokens suitable for the language model.
Args:
text (str): Input text.
tokenizer: Tokenizer instance from transformers library.
Returns:
List[int]: Token IDs.
"""
try:
tokens = tokenizer.encode(text, add_special_tokens=True)
return tokens
except Exception as e:
logger.error(f"Error tokenizing text: {e}")
return []
def process_data(csv_file: str, tokenizer) -> List[Tuple[np.ndarray, List[int]]]:
"""
Process the data from the CSV file.
Args:
csv_file (str): Path to the CSV file.
tokenizer: Tokenizer instance from transformers library.
Returns:
List[Tuple[np.ndarray, List[int]]]: List of tuples containing audio data and tokenized text.
"""
try:
df = pd.read_csv(csv_file)
except Exception as e:
logger.error(f"Error reading CSV file {csv_file}: {e}")
return []
data = []
for index, row in df.iterrows():
audio_path = row['Path of Audio(Audio)']
text = row['details description of text in great detail']
if not os.path.exists(audio_path):
logger.error(f"Audio file does not exist: {audio_path}")
continue
audio_data = load_and_augment_audio(audio_path)
if audio_data is None:
continue
tokenized_text = tokenize_text(text, tokenizer)
if not tokenized_text:
continue
data.append((audio_data, tokenized_text))
return data
class AudioTextDataset(Dataset):
"""
Dataset for audio and text data.
"""
def __init__(self, data: List[Tuple[np.ndarray, List[int]]]):
self.data = data
def __len__(self) -> int:
return len(self.data)
def __getitem__(self, idx: int) -> Tuple[torch.Tensor, torch.Tensor]:
audio_data, tokenized_text = self.data[idx]
# Convert audio data to tensor
audio_tensor = torch.tensor(audio_data, dtype=torch.float32)
# Convert tokenized text to tensor
text_tensor = torch.tensor(tokenized_text, dtype=torch.long)
return audio_tensor, text_tensor
def collate_fn(batch: List[Tuple[torch.Tensor, torch.Tensor]]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Collate function to batch variable-length sequences.
Args:
batch (List[Tuple[torch.Tensor, torch.Tensor]]): List of (audio_tensor, text_tensor).
Returns:
Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
- Padded audio tensors
- Audio lengths
- Padded text tensors
- Text lengths
"""
audio_tensors = [item[0] for item in batch]
text_tensors = [item[1] for item in batch]
# Pad audio sequences
audio_lengths = torch.tensor([len(a) for a in audio_tensors], dtype=torch.long)
padded_audio = torch.nn.utils.rnn.pad_sequence(audio_tensors, batch_first=True)
# Pad text sequences
text_lengths = torch.tensor([len(t) for t in text_tensors], dtype=torch.long)
padded_text = torch.nn.utils.rnn.pad_sequence(text_tensors, batch_first=True)
return padded_audio, audio_lengths, padded_text, text_lengths
if __name__ == '__main__':
# Replace 'bert-base-uncased' with the appropriate tokenizer for your language model
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
csv_file = 'path_to_csv_file.csv' # Replace with your CSV file path
data = process_data(csv_file, tokenizer)
dataset = AudioTextDataset(data)
dataloader = DataLoader(dataset, batch_size=32, shuffle=True, collate_fn=collate_fn)
for batch in dataloader:
audio_batch, audio_lengths, text_batch, text_lengths = batch
# Now feed this batch to your model
This script performs the following tasks:
- Data Loading: Reads a CSV file containing paths to audio files and their detailed textual descriptions.
- Audio Processing: Loads each audio file, applies augmentations such as adding noise, pitch shifting, and time stretching.
- Text Tokenization: Tokenizes the text descriptions using a tokenizer from the Hugging Face Transformers library.
- Dataset Preparation: Creates a custom
Dataset class to handle audio and text data.
- Batching: Implements a
collate_fn to handle variable-length sequences when batching data for model input.
- Error Handling: Includes comprehensive error handling with meaningful logging messages.
- Performance Optimization: Utilizes efficient data structures and batching to handle large datasets effectively.
- Code Quality: Adheres strictly to PEP-8 standards, includes type hints, and is structured for readability and maintainability.
Instructions for Use:
-
Install Dependencies:
pip install pandas numpy librosa transformers torch
-
Replace Placeholder Paths:
- Update
'path_to_csv_file.csv' with the actual path to your CSV file.
- If using a different tokenizer or model, replace
'bert-base-uncased' with the appropriate model name.
-
Run the Script:
python script_name.py
Replace script_name.py with the name you've given to the script file.
-
Integrate with Your Model:
- In the loop over
dataloader, replace the comment with code to feed the batch to your audio language model.
Notes:
- Audio Augmentation: The
augment_audio function applies random noise addition, pitch shifting, and time stretching. Adjust the parameters as needed for your use case.
- Tokenization: Ensure that the tokenizer aligns with the language model you intend to use.
- Variable-Length Handling: The
collate_fn function pads sequences to the length of the longest sequence in the batch, which is essential for batch processing in models.
- Logging: The script uses the
logging module to provide informative messages, aiding in debugging and monitoring.
Feel free to modify and extend this script to suit your specific requirements.