narad commited on
Commit
79c4595
1 Parent(s): 5a839bf

Upload ravdess.py

Browse files
Files changed (1) hide show
  1. ravdess.py +191 -0
ravdess.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # Lint as: python3
17
+ """RAVDESS multimodal dataset for emotion recognition."""
18
+
19
+
20
+ import os
21
+ from pathlib import Path, PurePath, PurePosixPath
22
+ from collections import OrderedDict
23
+ import pandas as pd
24
+ import datasets
25
+
26
+
27
+ _CITATION = """\
28
+
29
+ """
30
+
31
+ _DESCRIPTION = """\
32
+
33
+ """
34
+
35
+ _URL = "https://zenodo.org/record/1188976/files/Audio_Speech_Actors_01-24.zip"
36
+ _HOMEPAGE = "https://smartlaboratory.org/ravdess/"
37
+
38
+ _CLASS_NAMES = [
39
+ 'neutral',
40
+ 'calm',
41
+ 'happy',
42
+ 'sad',
43
+ 'angry',
44
+ 'fearful',
45
+ 'disgust',
46
+ 'surprised'
47
+ ]
48
+
49
+
50
+
51
+ _FEAT_DICT = OrderedDict([
52
+ ('Modality', ['full-AV', 'video-only', 'audio-only']),
53
+ ('Vocal channel', ['speech', 'song']),
54
+ ('Emotion', ['neutral', 'calm', 'happy', 'sad', 'angry', 'fearful', 'disgust', 'surprised']),
55
+ ('Emotion intensity', ['normal', 'strong']),
56
+ ('Statement', ["Kids are talking by the door", "Dogs are sitting by the door"]),
57
+ ('Repetition', ["1st repetition", "2nd repetition"]),
58
+ ])
59
+
60
+
61
+ def filename2feats(filename):
62
+ codes = filename.stem.split('-')
63
+ d = {}
64
+ for i, k in enumerate(_FEAT_DICT.keys()):
65
+ d[k] = _FEAT_DICT[k][int(codes[i])-1]
66
+ d['Actor'] = codes[-1]
67
+ d['Gender'] = 'female' if int(codes[-1]) % 2 == 0 else 'male'
68
+ d['Path_to_Wav'] = str(filename)
69
+ return d
70
+
71
+
72
+ def preprocess(data_root_path):
73
+ output_dir = data_root_path / "RAVDESS_ser"
74
+ output_dir.mkdir(parents=True, exist_ok=True)
75
+
76
+ data = []
77
+ for actor_dir in data_root_path.iterdir():
78
+ if actor_dir.is_dir() and "Actor" in actor_dir.name:
79
+ for f in actor_dir.iterdir():
80
+ data.append(filename2feats(f))
81
+
82
+ df = pd.DataFrame(data, columns=list(_FEAT_DICT.keys()) + ['Actor', 'Gender', 'Path_to_Wav'])
83
+ df.to_csv(output_dir / 'data.csv')
84
+
85
+
86
+
87
+ class RAVDESSConfig(datasets.BuilderConfig):
88
+ """BuilderConfig for RAVDESS."""
89
+
90
+ def __init__(self, **kwargs):
91
+ """
92
+ Args:
93
+ data_dir: `string`, the path to the folder containing the files in the
94
+ downloaded .tar
95
+ citation: `string`, citation for the data set
96
+ url: `string`, url for information about the data set
97
+ **kwargs: keyword arguments forwarded to super.
98
+ """
99
+ super(RAVDESSConfig, self).__init__(version=datasets.Version("2.0.1", ""), **kwargs)
100
+
101
+
102
+ class RAVDESS(datasets.GeneratorBasedBuilder):
103
+ """RAVDESS dataset."""
104
+
105
+ BUILDER_CONFIGS = [] #RAVDESSConfig(name="clean", description="'Clean' speech.")]
106
+
107
+ def _info(self):
108
+ return datasets.DatasetInfo(
109
+ description=_DESCRIPTION,
110
+ features=datasets.Features(
111
+ {
112
+ "audio": datasets.Audio(sampling_rate=48000),
113
+ "text": datasets.Value("string"),
114
+ "labels": datasets.ClassLabel(names=_CLASS_NAMES),
115
+ "speaker_id": datasets.Value("string"),
116
+ "speaker_gender": datasets.Value("string")
117
+ # "id": datasets.Value("string"),
118
+ }
119
+ ),
120
+ homepage=_HOMEPAGE,
121
+ citation=_CITATION
122
+ )
123
+
124
+
125
+ def _split_generators(self, dl_manager):
126
+ archive_path = dl_manager.download_and_extract(_URL)
127
+ archive_path = Path(archive_path)
128
+ preprocess(archive_path)
129
+ csv_path = os.path.join(archive_path, "RAVDESS_ser/data.csv")
130
+
131
+
132
+ return [
133
+ datasets.SplitGenerator(name=datasets.Split.TRAIN,
134
+ gen_kwargs={"data_info_csv": csv_path}),
135
+ ]
136
+
137
+
138
+ def _generate_examples(self, data_info_csv):
139
+ print("\nGenerating an example")
140
+
141
+ # Read the data info to extract rows mentioning about non-converted audio only
142
+ data_info = pd.read_csv(open(data_info_csv, encoding="utf8"))
143
+
144
+ # Iterating the contents of the data to extract the relevant information
145
+ for audio_idx in range(data_info.shape[0]):
146
+ audio_data = data_info.iloc[audio_idx]
147
+
148
+ # subpath = str(audio_data["Path_to_Wav"])
149
+ # import pathlib
150
+ # subpath = subpath.replace('\\', '/')
151
+ # p2 = pathlib.PurePosixPath(subpath)
152
+ # wav_path = str(pathlib.PurePath(data_path) / p2)
153
+ # labels = audio_data["Emotion"] #.lower().split(',')
154
+
155
+ # labels = [l for l in labels if len(l) > 1]
156
+
157
+ example = {
158
+ "audio": audio_data['Path_to_Wav'], #wav_path,
159
+ "text": audio_data['Statement'],
160
+ "labels": audio_data['Emotion'],
161
+ "speaker_id": audio_data["Actor"],
162
+ "speaker_gender": audio_data["Gender"]
163
+ }
164
+
165
+ yield audio_idx, example
166
+
167
+
168
+
169
+
170
+
171
+
172
+
173
+
174
+
175
+
176
+
177
+
178
+
179
+
180
+
181
+ # def class_names(self):
182
+ # return _CLASS_NAMES
183
+
184
+
185
+
186
+
187
+
188
+ # transcript =
189
+ # # extract transcript
190
+ # with open(wav_path.replace(".WAV", ".TXT"), encoding="utf-8") as op:
191
+ # transcript = " ".join(op.readlines()[0].split()[2:]) # first two items are sample number