transformers endpoints_compatible region:us
---
library_name: transformers
---
class AudioDataset(Dataset):
    def __init__(self, data, tokenizer, max_len):
        self.data = data
        self.tokenizer = tokenizer
        self.max_len = max_len

    def __getitem__(self, index):
        audio_path = self.data['audio'][index]
        label = self.data['label'][index]

        # Read the audio file and convert it to a spectrogram
        audio, _ = librosa.load(audio_path)
        spectrogram = librosa.feature.melspectrogram(audio, n_mels=128)

        # Pad the spectrogram to have the same length for all samples
        spectrogram = torch.tensor(spectrogram).unsqueeze(0).expand(-1, self.max_len - spectrogram.shape[1])

        # Convert the label to a tensor
        label = torch.tensor(label)

        # Return the spectrogram and label as a dataset tuple
        return spectrogram, label

    def __len__(self):
        return len(self.data['audio'])