-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmfcc_extractor.py
205 lines (167 loc) · 5.8 KB
/
mfcc_extractor.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""MFCC extractor.
Extracts MFCC data from the ``GTZAN Dataset - Music Genre Classification``
dataset from Kaggle.
Example:
To just run the default settings, you can use the CLI.
$ python mfcc_extractor.py
Alternatively, you can see the different options you can change.
$ python mfcc_extractor.py --help
"""
from re import S
import pandas as pd
import librosa
from tqdm import tqdm
import logging
import argparse
import pickle
import os
import sys
from datetime import datetime
def time_series(data_all, sr_all, NUM_SLICES, SAMPLES_PER_SLICE, N_MFCC):
"""Default time series MFCC extractor.
Args:
data_all (list): Data from loading audio files.
sr_all (list): Sample rate of all the audio files.
Returns:
tuple: List of MFCC data and labels.
"""
mfcc_list = []
labels_list = []
for i in tqdm(range(len(data_all))):
for s in range(NUM_SLICES):
start_sample = SAMPLES_PER_SLICE * s
end_sample = start_sample + SAMPLES_PER_SLICE
song = data_all[i]
mfcc = librosa.feature.mfcc(
y=song[start_sample:end_sample], sr=sr_all[i], n_mfcc=N_MFCC
)
mfcc = mfcc.T
mfcc_list.append(mfcc.tolist())
labels_list.append(i)
return mfcc_list, labels_list
def htk(data_all, sr_all, NUM_SLICES, SAMPLES_PER_SLICE, N_MFCC):
"""Default time series MFCC extractor with htk enabled.
Args:
data_all (list): Data from loading audio files.
sr_all (list): Sample rate of all the audio files.
Returns:
tuple: List of MFCC data and labels.
"""
mfcc_list = []
labels_list = []
for i in tqdm(range(len(data_all))):
for s in range(NUM_SLICES):
start_sample = SAMPLES_PER_SLICE * s
end_sample = start_sample + SAMPLES_PER_SLICE
song = data_all[i]
mfcc = librosa.feature.mfcc(
y=song[start_sample:end_sample], sr=sr_all[i], n_mfcc=N_MFCC, htk=True
)
mfcc = mfcc.T
mfcc_list.append(mfcc.tolist())
labels_list.append(i)
return mfcc_list, labels_list
def main():
if not os.path.isdir("Preprocessed"):
os.mkdir("Preprocessed")
if not os.path.isdir("Logs/Preprocessed"):
os.mkdir("Logs/Preprocessed")
# Parser for CLI configs
parser = argparse.ArgumentParser(description="MFCC extraction.")
parser.add_argument(
"--features_path",
default="Data/features_30_sec.csv",
type=str,
help="Path for the features CSV. Default: 'Data/features_30_sec.csv'",
)
parser.add_argument(
"--folder",
default="Data/",
type=str,
help="Folder containing `genres_original` folder with music inside. Default: 'Data/'",
)
parser.add_argument(
"--mfcc_type",
default="time-series",
type=str,
help="The method used to extract MFCC. Default: time-series. Options: htk",
)
parser.add_argument(
"--total_samples",
default=29,
type=int,
help="Specify total samples. Default: 29.",
)
parser.add_argument(
"--num_slices",
default=10,
type=int,
help="Specify number of slices. Default: 10.",
)
parser.add_argument(
"--n_mfcc",
default=60,
type=int,
help="Specify number of MFCCs to extract. Default: 60.",
)
opt = parser.parse_args()
FEATURES_PATH = opt.features_path
FOLDER = opt.folder
MFCC_TYPE = opt.mfcc_type
sr = 22050
TOTAL_SAMPLES = opt.total_samples * sr
NUM_SLICES = opt.num_slices
SAMPLES_PER_SLICE = int(TOTAL_SAMPLES / NUM_SLICES)
N_MFCC = opt.n_mfcc
START_DATETIME = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
# Logger configs
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.FileHandler(f"Logs/Preprocessed/{START_DATETIME}_mfcc_list_{MFCC_TYPE}_{TOTAL_SAMPLES}_{NUM_SLICES}_{N_MFCC}.log"), logging.StreamHandler(sys.stdout)],
)
# Start
logging.info("Starting MFCC extraction...")
df = pd.read_csv(FEATURES_PATH)
logging.info("Processing csv file...")
df["path"] = "genres_original/" + df["label"] + "/" + df["filename"]
paths = df["path"].tolist()
data_all = []
sr_all = []
failed_load = []
# Loading audio files
logging.info("Loading music data...")
for i in tqdm(paths):
try:
data, sr = librosa.load(FOLDER + i)
data_all.append(data)
sr_all.append(sr)
except:
failed_load.append(i)
logging.warning(f"The file {i} was not loaded.")
# MFCC extraction
# ! Are there more options?
logging.info(f"Converting into MFCC using {MFCC_TYPE}...")
if MFCC_TYPE == "time-series":
mfcc_list, labels_list = time_series(
data_all, sr_all, NUM_SLICES, SAMPLES_PER_SLICE, N_MFCC
)
elif MFCC_TYPE == "htk":
mfcc_list, labels_list = time_series(
data_all, sr_all, NUM_SLICES, SAMPLES_PER_SLICE, N_MFCC
)
else:
logging.error("MFCC type not specified correctly.")
new_df = pd.DataFrame({"mfcc": mfcc_list, "labels": labels_list})
# Pickling
logging.info(f"Dumping into pickle file...")
if os.path.isfile(f"Preprocessed/mfcc_list_{MFCC_TYPE}_{TOTAL_SAMPLES}_{NUM_SLICES}_{N_MFCC}"):
os.remove(f"Preprocessed/mfcc_list_{MFCC_TYPE}_{TOTAL_SAMPLES}_{NUM_SLICES}_{N_MFCC}")
outfile = open(f"Preprocessed/mfcc_list_{MFCC_TYPE}_{TOTAL_SAMPLES}_{NUM_SLICES}_{N_MFCC}", "wb")
pickle.dump(new_df, outfile)
outfile.close()
logging.info("Done.")
if __name__ == "__main__":
main()