Datasets:
File size: 2,574 Bytes
cdc5412 |
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 |
import os
import warnings
from io import BytesIO
from typing import Dict, Optional, Union
import datasets
import numpy as np
class customized_features(datasets.features.Audio):
def decode_example(self, value):
"""Decode example audio file into audio data.
Args:
value: Audio file path.
Returns:
dict
"""
# TODO: backard compatibility for users without audio dependencies
array, sampling_rate = (
self._decode_example_with_torchaudio(value)
if value.endswith(".mp3")
else self._decode_example_with_librosa(value)
)
return {"path": value, "array": array, "sampling_rate": sampling_rate}
def _decode_example_with_librosa(self, value):
try:
import librosa
except ImportError as err:
raise ImportError("To support decoding audio files, please install 'librosa'.") from err
try:
with open(value, "rb") as f:
array, sampling_rate = librosa.load(f, sr=self.sampling_rate, mono=self.mono)
except Exception as e:
warnings.warn(f"Error while reading {value} using librosa: {e}")
array = np.empty(0)
sampling_rate = self.sampling_rate
return array, sampling_rate
def _decode_example_with_torchaudio(self, value):
try:
import torchaudio
import torchaudio.transforms as T
except ImportError as err:
raise ImportError("To support decoding 'mp3' audio files, please install 'torchaudio'.") from err
try:
torchaudio.set_audio_backend("sox_io")
except RuntimeError as err:
raise ImportError("To support decoding 'mp3' audio files, please install 'sox'.") from err
array, sampling_rate = torchaudio.load(value)
if self.sampling_rate and self.sampling_rate != sampling_rate:
if not hasattr(self, "_resampler"):
self._resampler = T.Resample(sampling_rate, self.sampling_rate)
array = self._resampler(array)
sampling_rate = self.sampling_rate
array = array.numpy()
if self.mono:
array = array.mean(axis=0)
return array, sampling_rate
def decode_batch(self, values):
decoded_batch = defaultdict(list)
for value in values:
decoded_example = self.decode_example(value)
for k, v in decoded_example.items():
decoded_batch[k].append(v)
return dict(decoded_batch) |