-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_metadata.py
executable file
·279 lines (210 loc) · 8.09 KB
/
get_metadata.py
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import os
import re
import glob
import argparse
from collections import namedtuple
import shutil
import torchaudio
import pandas as pd
from omegaconf import OmegaConf
from sklearn.model_selection import train_test_split
Info = namedtuple("Info", ["length", "sample_rate", "channels"])
def get_audio_info(path: str) -> namedtuple:
"""
Get basic information related to number of frames,
sample rate and number of channels.
Params:
path: Audio path.
Returns:
Tuple
"""
info = torchaudio.info(path)
if hasattr(info, 'num_frames'):
return Info(info.num_frames, info.sample_rate, info.num_channels)
else:
siginfo = info[0]
return Info(siginfo.length // siginfo.channels, siginfo.rate, siginfo.channels)
def coraa_dataset(audio_paths, data_base_dir):
labels = []
os.makedirs(os.path.join(data_base_dir, 'dev'), exist_ok=True)
audio_paths = glob.glob(os.path.join(audio_paths, '**', '*.wav'), recursive=True)
for audio_path in audio_paths:
labels.append(audio_path.replace('.wav', '').split('_')[-1])
df = pd.DataFrame(list(zip(audio_paths, labels)), columns =['wav_file', 'label'])
train_df, dev_df = train_test_split(
df,
stratify=df['label'],
test_size=0.2,
random_state=42
)
for dev_audio_path in dev_df['wav_file'].values:
shutil.copy2(dev_audio_path, os.path.join(data_base_dir, 'dev', os.path.basename(dev_audio_path)))
return train_df, dev_df
def baved_dataset(audio_paths):
genders = []
emotions = []
labels = []
for idx, audio_path in enumerate(audio_paths):
gender = os.path.basename(audio_path).split('-')[1]
emotion = os.path.basename(audio_path).split('-')[4]
if emotion == '1':
emotion = 'neutral'
else:
emotion = 'non-neutral'
if gender=='m':
gender = 'male'
if gender == 'f':
gender = 'female'
if emotion == 'neutral':
label = 'neutral'
else:
label = emotion+'-'+gender
genders.append(gender)
emotions.append(emotion)
labels.append(label)
df = pd.DataFrame(list(zip(audio_paths, genders, emotions, labels)), columns =['wav_file', 'gender', 'emotion', 'label'])
return df
def emovo_dataset(audio_paths):
genders = []
emotions = []
labels = []
for idx, audio_path in enumerate(audio_paths):
gender = os.path.basename(audio_path).split('-')[1]
emotion = os.path.basename(audio_path).split('-')[0]
if emotion == 'neu':
emotion = 'neutral'
else:
emotion = 'non-neutral'
if gender.startswith('m'):
gender = 'male'
if gender.startswith('f'):
gender = 'female'
if emotion == 'neutral':
label = 'neutral'
else:
label = emotion+'-'+gender
genders.append(gender)
emotions.append(emotion)
labels.append(label)
df = pd.DataFrame(list(zip(audio_paths, genders, emotions, labels)), columns =['wav_file', 'gender', 'emotion', 'label'])
return df
def ravdess_dataset(audio_paths):
genders = []
emotions = []
labels = []
for idx, audio_path in enumerate(audio_paths):
gender = os.path.basename(audio_path).split('-')[-1].split('.')[0]
emotion = os.path.basename(audio_path).split('-')[2]
if emotion == '01':
emotion = 'neutral'
else:
emotion = 'non-neutral'
if int(gender)%2 == 0:
gender = 'female'
else:
gender = 'male'
if emotion == 'neutral':
label = 'neutral'
else:
label = emotion+'-'+gender
genders.append(gender)
emotions.append(emotion)
labels.append(label)
df = pd.DataFrame(list(zip(audio_paths, genders, emotions, labels)), columns =['wav_file', 'gender', 'emotion', 'label'])
return df
def iemocap_dataset(audio_paths, ie_base_dir):
iemocap_datas = []
genders = []
emotions = []
labels = []
paths = []
for audio_path in audio_paths:
audio_info = get_audio_info(audio_path)
audio_length = audio_info[0]/audio_info[1]
emotion_dict = {}
file_name = os.path.basename(audio_path).split('.')[0]
session_path = "Session"+str(int(file_name.split('_')[0][3:5]))
gender = file_name.split('_')[-1][0]
txt_name = os.path.basename(os.path.dirname(audio_path))
txt_path = os.path.join(ie_base_dir, session_path, 'dialog', 'EmoEvaluation', txt_name+'.txt')
assert os.path.isfile(txt_path)
with open(txt_path, 'r') as file:
string = file.read()
results = re.findall("\[.+\]\t(.+)\t(.+)\t\[.+\]", string)
for emo in results:
emotion_dict[emo[0]] = emo[1]
# Select good labels and filter by length
if emotion_dict[file_name]!="xxx" and audio_length<=15.0:
iemocap_datas.append((audio_path, emotion_dict[file_name], gender))
for iemocap_data in iemocap_datas:
gender = iemocap_data[-1]
emotion = iemocap_data[1]
path = iemocap_data[0]
if emotion == 'neu':
emotion = 'neutral'
else:
emotion = 'non-neutral'
if gender == 'F':
gender = 'female'
if gender == 'M':
gender = 'male'
if emotion == 'neutral':
label = 'neutral'
else:
label = emotion+'-'+gender
genders.append(gender)
emotions.append(emotion)
labels.append(label)
paths.append(path)
df = pd.DataFrame(list(zip(paths, genders, emotions, labels)), columns =['wav_file', 'gender', 'emotion', 'label'])
return df
def adapt_test_metadata_coraa(test_metadata_path: str):
df = pd.read_csv(test_metadata_path)
df = df[["wav_file", "label"]]
df["wav_file"] = "data/test/" + df["wav_file"].astype(str)
df.to_csv("metadata/test_ser_coraa.csv", index=False)
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--data_base_dir',
default='data',
help='Path to save metadata'
)
parser.add_argument(
'-mtd', '--metada_train_data_output_data',
default='metadata/ser_train_multiple_languages.csv',
help='Path to save metadata'
)
parser.add_argument(
'-mdd', '--metada_dev_data_output_data',
default='metadata/ser_dev_coraa.csv',
help='Path to save metadata'
)
args = parser.parse_args()
os.makedirs(os.path.dirname(args.metada_train_data_output_data), exist_ok=True)
os.makedirs(os.path.dirname(args.metada_dev_data_output_data), exist_ok=True)
coraa_ser_base_dir = os.path.join(args.data_base_dir, 'train', 'CORAA_SER')
baved_base_dir = os.path.join(args.data_base_dir, 'train', 'BAVED')
emovo_base_dir = os.path.join(args.data_base_dir, 'train', 'EMOVO')
ravdess_base_dir = os.path.join(args.data_base_dir, 'train', 'RAVDESS')
baved_audio_paths = glob.glob(os.path.join(baved_base_dir, '**', '*.wav'), recursive=True)
emovo_audio_paths = glob.glob(os.path.join(emovo_base_dir, '**', '*.wav'), recursive=True)
ravdess_audio_paths = glob.glob(os.path.join(ravdess_base_dir, '**', '*.wav'), recursive=True)
coraa_train_df, coraa_dev_df = coraa_dataset(coraa_ser_base_dir, args.data_base_dir)
baved_df = baved_dataset(baved_audio_paths)
emovo_df = emovo_dataset(emovo_audio_paths)
ravdess_df = ravdess_dataset(ravdess_audio_paths)
s_train = pd.concat(
[
coraa_train_df[['wav_file', 'label']],
baved_df[['wav_file', 'label']],
emovo_df[['wav_file', 'label']],
ravdess_df[['wav_file', 'label']]
]
)
assert s_train.shape[0] == coraa_train_df.shape[0] + baved_df.shape[0] + emovo_df.shape[0] + ravdess_df.shape[0]
s_train.to_csv(args.metada_train_data_output_data, index=False)
coraa_dev_df.to_csv(args.metada_dev_data_output_data, index=False)
adapt_test_metadata_coraa("metadata/test_ser_metadata.csv")
if __name__ == '__main__':
main()