voxceleb / voxceleb.py
yangwang825's picture
Update voxceleb.py
c351777 verified
# coding=utf-8
"""VoxCeleb dataset."""
import os
from typing import List
from pathlib import Path
import librosa
import datasets
from rich import print
DATA_DIR_STRUCTURE = """
test/
└── wav
β”œβ”€β”€ id10270
...
└── id10309
β”œβ”€β”€ A3ZvNuG8_oM
...
└── UbApEUoPvzY
β”œβ”€β”€ 00001.wav
...
└── 00005.wav
"""
SAMPLING_RATE = 16_000
class VoxCelebConfig(datasets.BuilderConfig):
"""BuilderConfig for VoxCeleb."""
def __init__(self, features, **kwargs):
super(VoxCelebConfig, self).__init__(version=datasets.Version("0.0.1", ""), **kwargs)
self.features = features
class VoxCeleb(datasets.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
VoxCelebConfig(
features=datasets.Features(
{
"audio": datasets.Audio(sampling_rate=SAMPLING_RATE),
"speaker": datasets.Value("string"),
# "duration": datasets.Value("int32"),
}
),
name="verification",
description="",
),
]
DEFAULT_CONFIG_NAME = "verification"
def _info(self):
return datasets.DatasetInfo(
description="VoxCeleb for verification",
features=self.config.features,
)
@property
def manual_download_instructions(self):
return (
"To use VoxCeleb you have to download it manually. "
"The tree structure of the downloaded data looks like: \n"
f"{DATA_DIR_STRUCTURE}"
)
def _split_generators(self, dl_manager):
data_dir = os.path.abspath(os.path.expanduser(dl_manager.manual_dir))
if not os.path.exists(data_dir):
raise FileNotFoundError(
f"{data_dir} does not exist. "
f"Manual download instructions: \n{self.manual_download_instructions}"
)
dev_archive_path = os.path.join(data_dir, 'dev', 'wav')
test_archive_path = os.path.join(data_dir, 'test', 'wav')
for path in [dev_archive_path, test_archive_path]:
if not os.path.isdir(path):
raise FileExistsError(f"{path} does not exist. Make sure you have converted m4a to wav format.")
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"split": "train", "archive_path": dev_archive_path}),
datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"split": "test", "archive_path": test_archive_path}),
]
def _generate_examples(self, split, archive_path):
"""Generate examples from VoxCeleb"""
# Iterating the contents of the data to extract the relevant information
extensions = ['.wav']
_, wav_paths = fast_scandir(archive_path, extensions, recursive=True)
for guid, wav_path in enumerate(wav_paths):
fileid = Path(wav_path).name
speaker = Path(wav_path).parent.parent.name
# duration = librosa.get_duration(path=wav_path)
# if duration <= 0:
# continue
try:
yield guid, {
"id": str(guid),
"audio": wav_path,
"speaker": speaker,
# "duration": duration
}
except:
continue
def fast_scandir(path: str, extensions: List[str], recursive: bool = False):
# Scan files recursively faster than glob
# From github.com/drscotthawley/aeiou/blob/main/aeiou/core.py
subfolders, files = [], []
try: # hope to avoid 'permission denied' by this try
for f in os.scandir(path):
try: # 'hope to avoid too many levels of symbolic links' error
if f.is_dir():
subfolders.append(f.path)
elif f.is_file():
if os.path.splitext(f.name)[1].lower() in extensions:
files.append(f.path)
except Exception:
pass
except Exception:
pass
if recursive:
for path in list(subfolders):
sf, f = fast_scandir(path, extensions, recursive=recursive)
subfolders.extend(sf)
files.extend(f) # type: ignore
return subfolders, files