File size: 4,047 Bytes
2b894fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b58f25
2b894fd
 
 
 
 
 
 
 
 
 
 
 
 
dbfa6ca
2b894fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03ec4f6
2b894fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# coding=utf-8

"""CREMA-D dataset."""


import os
import textwrap
import datasets
import itertools
import typing as tp
from pathlib import Path
from sklearn.model_selection import train_test_split

SAMPLE_RATE = 16_000

_COMPRESSED_FILENAME = 'crema-d.zip'

CREMAD_EMOTIONS_MAPPING = {
    'ANG': 'anger', 
    'DIS': 'disgust', 
    'FEA': 'fear', 
    'HAP': 'happy', 
    'NEU': 'neutral', 
    'SAD': 'sad', 
}
CLASSES = list(sorted(CREMAD_EMOTIONS_MAPPING.values()))


class CremaDConfig(datasets.BuilderConfig):
    """BuilderConfig for CREMA-D."""
    
    def __init__(self, features, **kwargs):
        super(CremaDConfig, self).__init__(version=datasets.Version("0.0.1", ""), **kwargs)
        self.features = features


class CREMAD(datasets.GeneratorBasedBuilder):

    BUILDER_CONFIGS = [
        CremaDConfig(
            features=datasets.Features(
                {
                    "file": datasets.Value("string"),
                    "audio": datasets.Audio(sampling_rate=SAMPLE_RATE),
                    "emotion": datasets.Value("string"),
                    "label": datasets.ClassLabel(names=CLASSES),
                }
            ),
            name="crema-d", 
            description='',
        ), 
    ]

    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."""
        archive_path = dl_manager.extract(_COMPRESSED_FILENAME)
        extensions = ['.wav']
        _, _walker = fast_scandir(archive_path, extensions, recursive=True)

        train_walker, val_test_walker = train_test_split(
            _walker, test_size=0.3, random_state=914, stratify=[default_find_classes(f) for f in _walker]
        )
        val_walker, test_walker = train_test_split(
            val_test_walker, test_size=0.5, random_state=914, stratify=[default_find_classes(f) for f in val_test_walker]
        )
        
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN, gen_kwargs={"audio_paths": train_walker, "split": "train"}
            ), 
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION, gen_kwargs={"audio_paths": val_walker, "split": "validation"}
            ), 
            datasets.SplitGenerator(
                name=datasets.Split.TEST, gen_kwargs={"audio_paths": test_walker, "split": "test"}
            ), 
        ]

    def _generate_examples(self, audio_paths, split=None):
        for guid, audio_path in enumerate(audio_paths):
            yield guid, {
                "id": str(guid),
                "file": audio_path, 
                "audio": audio_path, 
                "emotion": default_find_classes(audio_path), 
                "label": default_find_classes(audio_path), 
            }


def default_find_classes(audio_path):
    return CREMAD_EMOTIONS_MAPPING.get(Path(audio_path).name.split('_')[2])


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