Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

preprocess_data.py 9.3 KB

You have to be logged in to leave a comment. Sign In
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
  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. import glob
  4. import os
  5. import sys
  6. import scipy.io.wavfile as wavf
  7. import scipy.signal
  8. import h5py
  9. import json
  10. import librosa
  11. import multiprocessing
  12. import argparse
  13. def preprocess_data(src, dst, src_meta, n_processes=15):
  14. """
  15. Calls for distibuted preprocessing of the data.
  16. Parameters:
  17. -----------
  18. src: string
  19. Path to data directory.
  20. dst: string
  21. Path to directory where preprocessed data shall be stored.
  22. stc_meta: string
  23. Path to meta_information file.
  24. n_processes: int
  25. number of simultaneous processes to use for data preprocessing.
  26. """
  27. folders = []
  28. for folder in os.listdir(src):
  29. # only process folders
  30. if not os.path.isdir(os.path.join(src, folder)):
  31. continue
  32. folders.append(folder)
  33. pool=multiprocessing.Pool(processes=n_processes)
  34. _=pool.map(_preprocess_data, [(os.path.join(src, folder),
  35. os.path.join(dst, folder),
  36. src_meta) for folder in sorted(folders)])
  37. def _preprocess_data(src_dst_meta):
  38. """
  39. Preprocessing for all data files in given directory.
  40. Preprocessing includes:
  41. AlexNet: resampling to 8000 Hz,
  42. embedding in zero vector,
  43. transformation to amplitute spectrogram representation in dB.
  44. AudioNet: resampling to 8000 Hz,
  45. embedding in zero vector,
  46. normalization at 95th percentile.
  47. Preprocessed data will be stored in hdf5 files with one datum per file.
  48. In terms of I/O, this is not very efficient but it allows to easily change
  49. training, validation, and test sets without re-preprocessing or redundant
  50. storage of preprocessed files.
  51. Parameters:
  52. -----------
  53. src_dst_meta: tuple of 3 strings
  54. Tuple (path to data directory, path to destination directory, path
  55. to meta file)
  56. """
  57. src, dst, src_meta = src_dst_meta
  58. print("processing {}".format(src))
  59. metaData = json.load(open(src_meta))
  60. # create folder for hdf5 files
  61. if not os.path.exists(dst):
  62. os.makedirs(dst)
  63. # loop over recordings
  64. for filepath in sorted(glob.glob(os.path.join(src, "*.wav"))):
  65. # infer sample info from name
  66. dig, vp, rep = filepath.rstrip(".wav").split("/")[-1].split("_")
  67. # read data
  68. fs, data = wavf.read(filepath)
  69. # resample
  70. data = librosa.core.resample(y=data.astype(np.float32), orig_sr=fs, target_sr=8000, res_type="scipy")
  71. # zero padding
  72. if len(data) > 8000:
  73. raise ValueError("data length cannot exceed padding length.")
  74. elif len(data) < 8000:
  75. embedded_data = np.zeros(8000)
  76. offset = np.random.randint(low = 0, high = 8000 - len(data))
  77. embedded_data[offset:offset+len(data)] = data
  78. elif len(data) == 8000:
  79. # nothing to do here
  80. embedded_data = data
  81. pass
  82. ##### AlexNet #####
  83. # stft, with seleced parameters, spectrogram will have shape (228,230)
  84. f, t, Zxx = scipy.signal.stft(embedded_data, 8000, nperseg = 455, noverlap = 420, window='hann')
  85. # get amplitude
  86. Zxx = np.abs(Zxx[0:227, 2:-1])
  87. Zxx = np.atleast_3d(Zxx).transpose(2,0,1)
  88. # convert to decibel
  89. Zxx = librosa.amplitude_to_db(Zxx, ref = np.max)
  90. # save as hdf5 file
  91. with h5py.File(os.path.join(dst, "AlexNet_{}_{}_{}.hdf5".format(dig, vp, rep)), "w") as f:
  92. tmp_X = np.zeros([1, 1, 227, 227])
  93. tmp_X[0, 0] = Zxx
  94. f['data'] = tmp_X
  95. f['label'] = np.array([[int(dig), 0 if metaData[vp]["gender"] == "male" else 1]])
  96. ##### AudioNet #####
  97. embedded_data /= (np.percentile(embedded_data, 95) + 0.001)
  98. with h5py.File(os.path.join(dst, "AudioNet_{}_{}_{}.hdf5".format(dig, vp, rep)), "w") as f:
  99. tmp_X = np.zeros([1, 1, 1, 8000])
  100. tmp_X[0, 0, 0] = embedded_data
  101. f['data'] = tmp_X
  102. f['label'] = np.array([[int(dig), 0 if metaData[vp]["gender"] == "male" else 1]])
  103. return
  104. def create_splits(src, dst):
  105. """
  106. Creation of text files specifying which files training, validation and test
  107. set consist of for each cross-validation split.
  108. Parameters:
  109. -----------
  110. src: string
  111. Path to directory containing the directories for each subject that
  112. hold the preprocessed data in hdf5 format.
  113. dst: string
  114. Destination where to store the text files specifying training,
  115. validation and test splits.
  116. """
  117. print("creating splits")
  118. splits={"digit":{ "train":[ set([28, 56, 7, 19, 35, 1, 6, 16, 23, 34, 46, 53, 36, 57, 9, 24, 37, 2, \
  119. 8, 17, 29, 39, 48, 54, 43, 58, 14, 25, 38, 3, 10, 20, 30, 40, 49, 55]),
  120. set([36, 57, 9, 24, 37, 2, 8, 17, 29, 39, 48, 54, 43, 58, 14, 25, 38, 3, \
  121. 10, 20, 30, 40, 49, 55, 12, 47, 59, 15, 27, 41, 4, 11, 21, 31, 44, 50]),
  122. set([43, 58, 14, 25, 38, 3, 10, 20, 30, 40, 49, 55, 12, 47, 59, 15, 27, 41, \
  123. 4, 11, 21, 31, 44, 50, 26, 52, 60, 18, 32, 42, 5, 13, 22, 33, 45, 51]),
  124. set([12, 47, 59, 15, 27, 41, 4, 11, 21, 31, 44, 50, 26, 52, 60, 18, 32, 42, \
  125. 5, 13, 22, 33, 45, 51, 28, 56, 7, 19, 35, 1, 6, 16, 23, 34, 46, 53]),
  126. set([26, 52, 60, 18, 32, 42, 5, 13, 22, 33, 45, 51, 28, 56, 7, 19, 35, 1, \
  127. 6, 16, 23, 34, 46, 53, 36, 57, 9, 24, 37, 2, 8, 17, 29, 39, 48, 54])],
  128. "validate":[set([12, 47, 59, 15, 27, 41, 4, 11, 21, 31, 44, 50]),
  129. set([26, 52, 60, 18, 32, 42, 5, 13, 22, 33, 45, 51]),
  130. set([28, 56, 7, 19, 35, 1, 6, 16, 23, 34, 46, 53]),
  131. set([36, 57, 9, 24, 37, 2, 8, 17, 29, 39, 48, 54]),
  132. set([43, 58, 14, 25, 38, 3, 10, 20, 30, 40, 49, 55])],
  133. "test":[ set([26, 52, 60, 18, 32, 42, 5, 13, 22, 33, 45, 51]),
  134. set([28, 56, 7, 19, 35, 1, 6, 16, 23, 34, 46, 53]),
  135. set([36, 57, 9, 24, 37, 2, 8, 17, 29, 39, 48, 54]),
  136. set([43, 58, 14, 25, 38, 3, 10, 20, 30, 40, 49, 55]),
  137. set([12, 47, 59, 15, 27, 41, 4, 11, 21, 31, 44, 50])]},
  138. "gender":{ "train":[ set([36, 47, 56, 26, 12, 57, 2, 44, 50, 25, 37, 45]),
  139. set([26, 12, 57, 43, 28, 52, 25, 37, 45, 48, 53, 41]),
  140. set([43, 28, 52, 58, 59, 60, 48, 53, 41, 7, 23, 38]),
  141. set([58, 59, 60, 36, 47, 56, 7, 23, 38, 2, 44, 50])],
  142. "validate":[set([43, 28, 52, 48, 53, 41]),
  143. set([58, 59, 60, 7, 23, 38]),
  144. set([36, 47, 56, 2, 44, 50]),
  145. set([26, 12, 57, 25, 37, 45])],
  146. "test":[ set([58, 59, 60, 7, 23, 38]),
  147. set([36, 47, 56, 2, 44, 50]),
  148. set([26, 12, 57, 25, 37, 45]),
  149. set([43, 28, 52, 48, 53, 41])]}}
  150. for split in range(5):
  151. for modus in ["train", "validate", "test"]:
  152. for task in ["digit", "gender"]:
  153. if task == "gender" and split > 3:
  154. continue
  155. with open(os.path.join(dst, "AlexNet_{}_{}_{}.txt".format(task, split, modus)), mode = "w") as txt_file:
  156. for vp in splits[task][modus][split]:
  157. for filepath in glob.glob(os.path.join(src, "{:02d}".format(vp), "AlexNet*.hdf5")):
  158. txt_file.write(filepath+"\n")
  159. with open(os.path.join(dst, "AudioNet_{}_{}_{}.txt".format(task, split, modus)), mode = "w") as txt_file:
  160. for vp in splits[task][modus][split]:
  161. for filepath in glob.glob(os.path.join(src, "{:02d}".format(vp), "AudioNet*.hdf5")):
  162. txt_file.write(filepath+"\n")
  163. if __name__ == "__main__":
  164. parser = argparse.ArgumentParser()
  165. parser.add_argument('--source', '-src', default=os.path.join(os.getcwd(), "data"), help="Path to folder containing each participant's data directory.")
  166. parser.add_argument('--destination', '-dst', default=os.path.join(os.getcwd(), "preprocessed_data"), help="Destination where preprocessed data shall be stored.")
  167. parser.add_argument('--meta', '-m', default=os.path.join(os.getcwd(), "data", "audioMNIST_meta.txt"), help="Path to meta_information json file.")
  168. args = parser.parse_args()
  169. # preprocessing
  170. preprocess_data(src=args.source, dst=args.destination, src_meta=args.meta)
  171. # create training, validation and test sets
  172. create_splits(src=args.destination, dst=args.destination)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...