emovo / emovo.py
yangwang825's picture
Update emovo.py
fa4f20d verified
# coding=utf-8
"""EMOVO dataset."""
import os
import re
import gdown
import textwrap
import datasets
import itertools
import typing as tp
from pathlib import Path
VERSION = "0.0.1"
SAMPLE_RATE = 48_000
_DATASET_GOOGLE_DRIVE_ID = '1SUtaKeA-LYnKaD3qv87Y5wYgihJiNJAo'
EMOTIONS = [
'dis', 'gio', 'neu', 'pau', 'rab', 'sor', 'tri'
]
# Cache location
DEFAULT_XDG_CACHE_HOME = "~/.cache"
XDG_CACHE_HOME = os.getenv("XDG_CACHE_HOME", DEFAULT_XDG_CACHE_HOME)
DEFAULT_HF_CACHE_HOME = os.path.join(XDG_CACHE_HOME, "huggingface")
HF_CACHE_HOME = os.path.expanduser(os.getenv("HF_HOME", DEFAULT_HF_CACHE_HOME))
DEFAULT_HF_DATASETS_CACHE = os.path.join(HF_CACHE_HOME, "datasets")
HF_DATASETS_CACHE = Path(os.getenv("HF_DATASETS_CACHE", DEFAULT_HF_DATASETS_CACHE))
class EMOVOConfig(datasets.BuilderConfig):
"""BuilderConfig for EMOVO."""
def __init__(self, features, **kwargs):
super(EMOVOConfig, self).__init__(version=datasets.Version("0.0.1", ""), **kwargs)
self.features = features
class EMOVO(datasets.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
EMOVOConfig(
features=datasets.Features(
{
"file": datasets.Value("string"),
"audio": datasets.Audio(sampling_rate=SAMPLE_RATE),
"emotion": datasets.Value("string"),
"label": datasets.ClassLabel(names=EMOTIONS),
}
),
name=f"fold{i}",
description=textwrap.dedent(
"""\
"""
),
)
for i in range(1, 6+1)
]
def _info(self):
return datasets.DatasetInfo(
description="",
features=self.config.features,
supervised_keys=None,
homepage="",
citation="""
""",
task_templates=None,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
refine_url = f'http://drive.google.com/uc?id={_DATASET_GOOGLE_DRIVE_ID}&confirm=t'
output_filepath = os.path.join(HF_DATASETS_CACHE, 'confit___emovo', 'emovo.zip')
if not os.path.exists(output_filepath):
gdown.download(refine_url, output_filepath, quiet=True)
archive_path = dl_manager.extract(output_filepath)
extensions = ['.wav']
_, _walker = fast_scandir(archive_path, extensions, recursive=True)
if self.config.name == 'fold1':
speaker = 'f1'
elif self.config.name == 'fold2':
speaker = 'f2'
elif self.config.name == 'fold3':
speaker = 'f3'
elif self.config.name == 'fold4':
speaker = 'm1'
elif self.config.name == 'fold5':
speaker = 'm2'
elif self.config.name == 'fold6':
speaker = 'm3'
_test_walker = [fileid for fileid in _walker if Path(fileid).parent.stem == speaker]
_train_walker = [fileid for fileid in _walker if fileid not in _test_walker]
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN, gen_kwargs={"audio_filepaths": _train_walker, "split": "train"}
),
datasets.SplitGenerator(
name=datasets.Split.TEST, gen_kwargs={"audio_filepaths": _test_walker, "split": "test"}
),
]
def _generate_examples(self, audio_filepaths, split=None):
for guid, audio_path in enumerate(audio_filepaths):
yield guid, {
"id": str(guid),
"file": audio_path,
"audio": audio_path,
"emotion": Path(audio_path).name.split('-')[0],
"label": Path(audio_path).name.split('-')[0]
}
def fast_scandir(path: str, exts: tp.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 exts:
files.append(f.path)
except Exception:
pass
except Exception:
pass
if recursive:
for path in list(subfolders):
sf, f = fast_scandir(path, exts, recursive=recursive)
subfolders.extend(sf)
files.extend(f) # type: ignore
return subfolders, files