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
"outputs": [],
|
8 |
+
"source": [
|
9 |
+
"from dataclasses import dataclass\n",
|
10 |
+
"from typing import Any, Dict, List, Union\n",
|
11 |
+
"import torch\n",
|
12 |
+
"import torchaudio\n",
|
13 |
+
"import random\n",
|
14 |
+
"\n",
|
15 |
+
"@dataclass\n",
|
16 |
+
"class DataCollatorSpeechSeq2SeqWithPadding:\n",
|
17 |
+
" processor: Any\n",
|
18 |
+
" decoder_start_token_id: int\n",
|
19 |
+
" apply_augmentation: bool = False\n",
|
20 |
+
" n_fft_choices: List[int] = (400, 800, 1024)\n",
|
21 |
+
" hop_length_choices: List[int] = (160, 320, 512)\n",
|
22 |
+
" apply_noise_injection: bool = False # Toggle for noise injection\n",
|
23 |
+
" noise_profiles: List[str] = ('white', 'pink', 'environmental') # Example noise profiles\n",
|
24 |
+
"\n",
|
25 |
+
" def add_adaptive_noise(self, audio, noise_type='white', base_intensity=0.005):\n",
|
26 |
+
" amplitude = audio.abs().mean()\n",
|
27 |
+
" noise_intensity = base_intensity * amplitude # Scale noise intensity based on amplitude\n",
|
28 |
+
"\n",
|
29 |
+
" noise = torch.randn_like(audio) * noise_intensity\n",
|
30 |
+
" if noise_type == 'pink':\n",
|
31 |
+
" noise = torchaudio.functional.highpass_biquad(noise, sample_rate=16000, cutoff_freq=200)\n",
|
32 |
+
" elif noise_type == 'environmental':\n",
|
33 |
+
" # Load an example environmental noise file\n",
|
34 |
+
" noise, _ = torchaudio.load('environmental_noise.wav')\n",
|
35 |
+
" noise = torch.nn.functional.interpolate(noise.unsqueeze(0), size=audio.size()).squeeze() * noise_intensity\n",
|
36 |
+
" return audio + noise\n",
|
37 |
+
"\n",
|
38 |
+
" def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:\n",
|
39 |
+
" input_features = []\n",
|
40 |
+
" labels_list = []\n",
|
41 |
+
" dec_input_features = []\n",
|
42 |
+
" \n",
|
43 |
+
" for feature in features:\n",
|
44 |
+
" audio = feature[\"input_features\"]\n",
|
45 |
+
" if self.apply_augmentation:\n",
|
46 |
+
" # Randomly select n_fft and hop_length for augmentation\n",
|
47 |
+
" n_fft = random.choice(self.n_fft_choices)\n",
|
48 |
+
" hop_length = random.choice(self.hop_length_choices)\n",
|
49 |
+
" if self.apply_noise_injection:\n",
|
50 |
+
" noise_type = random.choice(self.noise_profiles)\n",
|
51 |
+
" audio = self.add_adaptive_noise(audio, noise_type=noise_type)\n",
|
52 |
+
" else:\n",
|
53 |
+
" # Use default values if augmentation is not applied\n",
|
54 |
+
" n_fft = 1024\n",
|
55 |
+
" hop_length = 512\n",
|
56 |
+
"\n",
|
57 |
+
" # Apply MelSpectrogram transformation with the selected parameters\n",
|
58 |
+
" mel_spectrogram = torchaudio.transforms.MelSpectrogram(\n",
|
59 |
+
" sample_rate=16000, # Sample rate is assumed; update if necessary\n",
|
60 |
+
" n_fft=n_fft,\n",
|
61 |
+
" hop_length=hop_length,\n",
|
62 |
+
" n_mels=80\n",
|
63 |
+
" )(torch.tensor(audio))\n",
|
64 |
+
"\n",
|
65 |
+
" log_mel_spectrogram = torch.log(mel_spectrogram + 1e-9)\n",
|
66 |
+
" input_features.append({\"input_features\": log_mel_spectrogram})\n",
|
67 |
+
" \n",
|
68 |
+
" label = feature[\"labels\"]\n",
|
69 |
+
" label_tokens = [self.processor.tokenizer.bos_token_id] + self.processor.tokenizer.encode(label) + [self.processor.tokenizer.eos_token_id]\n",
|
70 |
+
" dec_input_feature = label_tokens[:-1]\n",
|
71 |
+
" label = label_tokens[1:]\n",
|
72 |
+
" \n",
|
73 |
+
" labels_list.append({\"input_ids\": label})\n",
|
74 |
+
" dec_input_features.append({\"input_ids\": dec_input_feature})\n",
|
75 |
+
" \n",
|
76 |
+
" batch = self.processor.feature_extractor.pad(input_features, return_tensors=\"pt\")\n",
|
77 |
+
" labels_batch = self.processor.tokenizer.pad(labels_list, return_tensors=\"pt\")\n",
|
78 |
+
" dec_input_batch = self.processor.tokenizer.pad(dec_input_features, return_tensors=\"pt\")\n",
|
79 |
+
"\n",
|
80 |
+
" labels = labels_batch[\"input_ids\"].masked_fill(labels_batch.attention_mask.ne(1), -100)\n",
|
81 |
+
" if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():\n",
|
82 |
+
" labels = labels[:, 1:]\n",
|
83 |
+
" batch[\"labels\"] = labels\n",
|
84 |
+
"\n",
|
85 |
+
" dec_input_features = dec_input_batch[\"input_ids\"]\n",
|
86 |
+
" if (dec_input_features[:, 0] == self.decoder_start_token_id).all().cpu().item():\n",
|
87 |
+
" dec_input_features = dec_input_features[:, 1:]\n",
|
88 |
+
" batch[\"dec_input_features\"] = dec_input_features\n",
|
89 |
+
"\n",
|
90 |
+
" return batch\n",
|
91 |
+
"\n",
|
92 |
+
"# Example usage\n",
|
93 |
+
"data_collator = DataCollatorSpeechSeq2SeqWithPadding(\n",
|
94 |
+
" processor=processor,\n",
|
95 |
+
" decoder_start_token_id=model.config.decoder_start_token_id,\n",
|
96 |
+
" apply_augmentation=True, # Enable augmentation\n",
|
97 |
+
" apply_noise_injection=True # Enable adaptive noise injection\n",
|
98 |
+
")\n"
|
99 |
+
]
|
100 |
+
},
|
101 |
+
{
|
102 |
+
"cell_type": "code",
|
103 |
+
"execution_count": null,
|
104 |
+
"metadata": {},
|
105 |
+
"outputs": [],
|
106 |
+
"source": [
|
107 |
+
"from dataclasses import dataclass\n",
|
108 |
+
"from typing import Any, Dict, List, Union\n",
|
109 |
+
"import torch\n",
|
110 |
+
"import torchaudio\n",
|
111 |
+
"import random\n",
|
112 |
+
"\n",
|
113 |
+
"\n",
|
114 |
+
"def add_adaptive_noise(audio, noise_type='white', base_intensity=0.005):\n",
|
115 |
+
" amplitude = audio.abs().mean()\n",
|
116 |
+
" noise_intensity = base_intensity * amplitude # Scale noise intensity based on amplitude\n",
|
117 |
+
" \n",
|
118 |
+
" noise = torch.randn_like(audio) * noise_intensity\n",
|
119 |
+
" if noise_type == 'pink':\n",
|
120 |
+
" noise = torchaudio.functional.highpass_biquad(noise, sample_rate=16000, cutoff_freq=200)\n",
|
121 |
+
" elif noise_type == 'environmental':\n",
|
122 |
+
" # Load an example environmental noise file\n",
|
123 |
+
" noise, _ = torchaudio.load('environmental_noise.wav')\n",
|
124 |
+
" noise = torch.nn.functional.interpolate(noise.unsqueeze(0), size=audio.size()).squeeze() * noise_intensity\n",
|
125 |
+
" return audio + noise\n",
|
126 |
+
"\n",
|
127 |
+
"def collate_fn(batch, apply_augmentation_flag=True, apply_noise_injection_flag=False):\n",
|
128 |
+
" n_fft_choices = [400, 800, 1024]\n",
|
129 |
+
" hop_length_choices = [160, 320, 512]\n",
|
130 |
+
" noise_profiles = ['white', 'pink', 'environmental']\n",
|
131 |
+
"\n",
|
132 |
+
" input_features, labels, dec_input_features = [], [], []\n",
|
133 |
+
" \n",
|
134 |
+
" for f in batch:\n",
|
135 |
+
" audio = whisper.pad_or_trim(f[\"audio\"].flatten())\n",
|
136 |
+
" \n",
|
137 |
+
" if apply_augmentation_flag:\n",
|
138 |
+
" n_fft = random.choice(n_fft_choices)\n",
|
139 |
+
" hop_length = random.choice(hop_length_choices)\n",
|
140 |
+
" if apply_noise_injection_flag:\n",
|
141 |
+
" noise_type = random.choice(noise_profiles)\n",
|
142 |
+
" audio = add_adaptive_noise(audio, noise_type=noise_type)\n",
|
143 |
+
" else:\n",
|
144 |
+
" n_fft = 1024\n",
|
145 |
+
" hop_length = 512\n",
|
146 |
+
"\n",
|
147 |
+
" mel_spectrogram = torchaudio.transforms.MelSpectrogram(\n",
|
148 |
+
" sample_rate=16000, # Assuming a sample rate of 16000\n",
|
149 |
+
" n_fft=n_fft,\n",
|
150 |
+
" hop_length=hop_length,\n",
|
151 |
+
" n_mels=80\n",
|
152 |
+
" )(audio)\n",
|
153 |
+
"\n",
|
154 |
+
" input_feature = torch.log(mel_spectrogram + 1e-9)\n",
|
155 |
+
"\n",
|
156 |
+
" label = f[\"label\"]\n",
|
157 |
+
" label_tokens = [tokenizer.bos_token_id] + tokenizer.encode(label) + [tokenizer.eos_token_id]\n",
|
158 |
+
" dec_input_feature = label_tokens[:-1]\n",
|
159 |
+
" label = label_tokens[1:]\n",
|
160 |
+
"\n",
|
161 |
+
" input_features.append(input_feature)\n",
|
162 |
+
" labels.append(label)\n",
|
163 |
+
" dec_input_features.append(dec_input_feature)\n",
|
164 |
+
"\n",
|
165 |
+
" input_features = torch.stack(input_features)\n",
|
166 |
+
"\n",
|
167 |
+
" max_label_len = max(len(l) for l in labels)\n",
|
168 |
+
" max_dec_input_len = max(len(d) for d in dec_input_features)\n",
|
169 |
+
" max_len = max(max_label_len, max_dec_input_len)\n",
|
170 |
+
"\n",
|
171 |
+
" labels = [np.pad(l, (0, max_len - len(l)), 'constant', constant_values=-100) for l in labels]\n",
|
172 |
+
" dec_input_features = [np.pad(d, (0, max_len - len(d)), 'constant', constant_values=tokenizer.pad_token_id) for d in dec_input_features]\n",
|
173 |
+
"\n",
|
174 |
+
" labels = np.array(labels)\n",
|
175 |
+
" dec_input_features = np.array(dec_input_features)\n",
|
176 |
+
"\n",
|
177 |
+
" labels = torch.tensor(labels, dtype=torch.long)\n",
|
178 |
+
" dec_input_features = torch.tensor(dec_input_features, dtype=torch.long)\n",
|
179 |
+
"\n",
|
180 |
+
" batch = {\n",
|
181 |
+
" \"input_features\": input_features,\n",
|
182 |
+
" \"labels\": labels,\n",
|
183 |
+
" \"dec_input_features\": dec_input_features\n",
|
184 |
+
" }\n",
|
185 |
+
" return batch\n",
|
186 |
+
"\n"
|
187 |
+
]
|
188 |
+
},
|
189 |
+
{
|
190 |
+
"cell_type": "code",
|
191 |
+
"execution_count": null,
|
192 |
+
"metadata": {},
|
193 |
+
"outputs": [],
|
194 |
+
"source": [
|
195 |
+
"from dataclasses import dataclass\n",
|
196 |
+
"from typing import Any, Dict, List, Union\n",
|
197 |
+
"import torch\n",
|
198 |
+
"import torchaudio\n",
|
199 |
+
"import random\n",
|
200 |
+
"\n",
|
201 |
+
"@dataclass\n",
|
202 |
+
"class DataCollatorSpeechSeq2SeqWithPadding:\n",
|
203 |
+
" processor: Any\n",
|
204 |
+
" decoder_start_token_id: int\n",
|
205 |
+
" apply_augmentation: bool = False\n",
|
206 |
+
" n_fft_choices: List[int] = (400, 800, 1024)\n",
|
207 |
+
" hop_length_choices: List[int] = (160, 320, 512)\n",
|
208 |
+
"\n",
|
209 |
+
" def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:\n",
|
210 |
+
" input_features = []\n",
|
211 |
+
" labels_list = []\n",
|
212 |
+
" dec_input_features = []\n",
|
213 |
+
" \n",
|
214 |
+
" for feature in features:\n",
|
215 |
+
" audio = feature[\"input_features\"]\n",
|
216 |
+
" if self.apply_augmentation:\n",
|
217 |
+
" # Randomly select n_fft and hop_length for augmentation\n",
|
218 |
+
" n_fft = random.choice(self.n_fft_choices)\n",
|
219 |
+
" hop_length = random.choice(self.hop_length_choices)\n",
|
220 |
+
" else:\n",
|
221 |
+
" # Use default values if augmentation is not applied\n",
|
222 |
+
" n_fft = 1024\n",
|
223 |
+
" hop_length = 512\n",
|
224 |
+
"\n",
|
225 |
+
" # Apply MelSpectrogram transformation with the selected parameters\n",
|
226 |
+
" mel_spectrogram = torchaudio.transforms.MelSpectrogram(\n",
|
227 |
+
" sample_rate=16000, # Sample rate is assumed; update if necessary\n",
|
228 |
+
" n_fft=n_fft,\n",
|
229 |
+
" hop_length=hop_length,\n",
|
230 |
+
" n_mels=80\n",
|
231 |
+
" )(torch.tensor(audio))\n",
|
232 |
+
"\n",
|
233 |
+
" log_mel_spectrogram = torch.log(mel_spectrogram + 1e-9)\n",
|
234 |
+
" input_features.append({\"input_features\": log_mel_spectrogram})\n",
|
235 |
+
" \n",
|
236 |
+
" label = feature[\"labels\"]\n",
|
237 |
+
" label_tokens = [self.processor.tokenizer.bos_token_id] + self.processor.tokenizer.encode(label) + [self.processor.tokenizer.eos_token_id]\n",
|
238 |
+
" dec_input_feature = label_tokens[:-1]\n",
|
239 |
+
" label = label_tokens[1:]\n",
|
240 |
+
" \n",
|
241 |
+
" labels_list.append({\"input_ids\": label})\n",
|
242 |
+
" dec_input_features.append({\"input_ids\": dec_input_feature})\n",
|
243 |
+
" \n",
|
244 |
+
" batch = self.processor.feature_extractor.pad(input_features, return_tensors=\"pt\")\n",
|
245 |
+
" labels_batch = self.processor.tokenizer.pad(labels_list, return_tensors=\"pt\")\n",
|
246 |
+
" dec_input_batch = self.processor.tokenizer.pad(dec_input_features, return_tensors=\"pt\")\n",
|
247 |
+
"\n",
|
248 |
+
" labels = labels_batch[\"input_ids\"].masked_fill(labels_batch.attention_mask.ne(1), -100)\n",
|
249 |
+
" if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():\n",
|
250 |
+
" labels = labels[:, 1:]\n",
|
251 |
+
" batch[\"labels\"] = labels\n",
|
252 |
+
"\n",
|
253 |
+
" dec_input_features = dec_input_batch[\"input_ids\"]\n",
|
254 |
+
" if (dec_input_features[:, 0] == self.decoder_start_token_id).all().cpu().item():\n",
|
255 |
+
" dec_input_features = dec_input_features[:, 1:]\n",
|
256 |
+
" batch[\"dec_input_features\"] = dec_input_features\n",
|
257 |
+
"\n",
|
258 |
+
" return batch\n",
|
259 |
+
"\n",
|
260 |
+
"# Example usage\n",
|
261 |
+
"data_collator = DataCollatorSpeechSeq2SeqWithPadding(\n",
|
262 |
+
" processor=processor,\n",
|
263 |
+
" decoder_start_token_id=model.config.decoder_start_token_id,\n",
|
264 |
+
" apply_augmentation=True # Set to False to disable augmentation\n",
|
265 |
+
")\n"
|
266 |
+
]
|
267 |
+
},
|
268 |
+
{
|
269 |
+
"cell_type": "code",
|
270 |
+
"execution_count": null,
|
271 |
+
"metadata": {},
|
272 |
+
"outputs": [],
|
273 |
+
"source": [
|
274 |
+
"@dataclass\n",
|
275 |
+
"class DataCollatorSpeechSeq2SeqWithPadding:\n",
|
276 |
+
" processor: Any\n",
|
277 |
+
" decoder_start_token_id: int\n",
|
278 |
+
" apply_augmentation: bool = False\n",
|
279 |
+
" n_fft_choices: List[int] = (400, 800, 1024)\n",
|
280 |
+
" hop_length_choices: List[int] = (160, 320, 512)\n",
|
281 |
+
" apply_noise_injection: bool = False # Toggle for noise injection\n",
|
282 |
+
" noise_profiles: List[str] = ('white', 'pink', 'environmental') # Example noise profiles\n",
|
283 |
+
"\n",
|
284 |
+
" def add_noise(self, audio, noise_type='white', intensity=0.005):\n",
|
285 |
+
" noise = torch.randn_like(audio) * intensity\n",
|
286 |
+
" if noise_type == 'pink':\n",
|
287 |
+
" noise = torchaudio.functional.highpass_biquad(noise, sample_rate=16000, cutoff_freq=200)\n",
|
288 |
+
" elif noise_type == 'environmental':\n",
|
289 |
+
" # Load an example environmental noise file\n",
|
290 |
+
" noise, _ = torchaudio.load('environmental_noise.wav')\n",
|
291 |
+
" noise = torch.nn.functional.interpolate(noise.unsqueeze(0), size=audio.size()).squeeze() * intensity\n",
|
292 |
+
" return audio + noise\n",
|
293 |
+
"\n",
|
294 |
+
" def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:\n",
|
295 |
+
" input_features = []\n",
|
296 |
+
" labels_list = []\n",
|
297 |
+
" dec_input_features = []\n",
|
298 |
+
" \n",
|
299 |
+
" for feature in features:\n",
|
300 |
+
" audio = feature[\"input_features\"]\n",
|
301 |
+
" if self.apply_augmentation:\n",
|
302 |
+
" n_fft = random.choice(self.n_fft_choices)\n",
|
303 |
+
" hop_length = random.choice(self.hop_length_choices)\n",
|
304 |
+
" if self.apply_noise_injection:\n",
|
305 |
+
" noise_type = random.choice(self.noise_profiles)\n",
|
306 |
+
" audio = self.add_noise(audio, noise_type=noise_type)\n",
|
307 |
+
" else:\n",
|
308 |
+
" n_fft = 1024\n",
|
309 |
+
" hop_length = 512\n",
|
310 |
+
"\n",
|
311 |
+
" mel_spectrogram = torchaudio.transforms.MelSpectrogram(\n",
|
312 |
+
" sample_rate=16000, # Sample rate is assumed; update if necessary\n",
|
313 |
+
" n_fft=n_fft,\n",
|
314 |
+
" hop_length=hop_length,\n",
|
315 |
+
" n_mels=80\n",
|
316 |
+
" )(torch.tensor(audio))\n",
|
317 |
+
"\n",
|
318 |
+
" log_mel_spectrogram = torch.log(mel_spectrogram + 1e-9)\n",
|
319 |
+
" input_features.append({\"input_features\": log_mel_spectrogram})\n",
|
320 |
+
" \n",
|
321 |
+
" label = feature[\"labels\"]\n",
|
322 |
+
" label_tokens = [self.processor.tokenizer.bos_token_id] + self.processor.tokenizer.encode(label) + [self.processor.tokenizer.eos_token_id]\n",
|
323 |
+
" dec_input_feature = label_tokens[:-1]\n",
|
324 |
+
" label = label_tokens[1:]\n",
|
325 |
+
" \n",
|
326 |
+
" labels_list.append({\"input_ids\": label})\n",
|
327 |
+
" dec_input_features.append({\"input_ids\": dec_input_feature})\n",
|
328 |
+
" \n",
|
329 |
+
" batch = self.processor.feature_extractor.pad(input_features, return_tensors=\"pt\")\n",
|
330 |
+
" labels_batch = self.processor.tokenizer.pad(labels_list, return_tensors=\"pt\")\n",
|
331 |
+
" dec_input_batch = self.processor.tokenizer.pad(dec_input_features, return_tensors=\"pt\")\n",
|
332 |
+
"\n",
|
333 |
+
" labels = labels_batch[\"input_ids\"].masked_fill(labels_batch.attention_mask.ne(1), -100)\n",
|
334 |
+
" if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():\n",
|
335 |
+
" labels = labels[:, 1:]\n",
|
336 |
+
" batch[\"labels\"] = labels\n",
|
337 |
+
"\n",
|
338 |
+
" dec_input_features = dec_input_batch[\"input_ids\"]\n",
|
339 |
+
" if (dec_input_features[:, 0] == self.decoder_start_token_id).all().cpu().item():\n",
|
340 |
+
" dec_input_features = dec_input_features[:, 1:]\n",
|
341 |
+
" batch[\"dec_input_features\"] = dec_input_features\n",
|
342 |
+
"\n",
|
343 |
+
" return batch\n",
|
344 |
+
"\n",
|
345 |
+
"data_collator = DataCollatorSpeechSeq2SeqWithPadding(\n",
|
346 |
+
" processor=processor,\n",
|
347 |
+
" decoder_start_token_id=model.config.decoder_start_token_id,\n",
|
348 |
+
" apply_augmentation=True, # Set to True to enable augmentation\n",
|
349 |
+
" apply_noise_injection=True # Set to True to enable noise injection\n",
|
350 |
+
")\n",
|
351 |
+
"\n",
|
352 |
+
"dataloader = torch.utils.data.DataLoader(dataset, batch_size=2, shuffle=True, collate_fn=data_collator)\n",
|
353 |
+
"\n",
|
354 |
+
"for batch in dataloader:\n",
|
355 |
+
" # Pass the batch to your model\n",
|
356 |
+
" outputs = model(batch)\n"
|
357 |
+
]
|
358 |
+
},
|
359 |
+
{
|
360 |
+
"cell_type": "code",
|
361 |
+
"execution_count": null,
|
362 |
+
"metadata": {},
|
363 |
+
"outputs": [],
|
364 |
+
"source": [
|
365 |
+
"import torch\n",
|
366 |
+
"import torchaudio\n",
|
367 |
+
"import random\n",
|
368 |
+
"import numpy as np\n",
|
369 |
+
"\n",
|
370 |
+
"def add_noise(audio, noise_type='white', intensity=0.005):\n",
|
371 |
+
" noise = torch.randn_like(audio) * intensity\n",
|
372 |
+
" if noise_type == 'pink':\n",
|
373 |
+
" noise = torchaudio.functional.highpass_biquad(noise, sample_rate=16000, cutoff_freq=200)\n",
|
374 |
+
" elif noise_type == 'environmental':\n",
|
375 |
+
" # Load an example environmental noise file\n",
|
376 |
+
" noise, _ = torchaudio.load('environmental_noise.wav')\n",
|
377 |
+
" noise = torch.nn.functional.interpolate(noise.unsqueeze(0), size=audio.size()).squeeze() * intensity\n",
|
378 |
+
" return audio + noise\n",
|
379 |
+
"\n",
|
380 |
+
"def collate_fn(batch, apply_augmentation_flag=True, apply_noise_injection_flag=False):\n",
|
381 |
+
" n_fft_choices = [400, 800, 1024]\n",
|
382 |
+
" hop_length_choices = [160, 320, 512]\n",
|
383 |
+
" noise_profiles = ['white', 'pink', 'environmental']\n",
|
384 |
+
"\n",
|
385 |
+
" input_features, labels, dec_input_features = [], [], []\n",
|
386 |
+
" \n",
|
387 |
+
" for f in batch:\n",
|
388 |
+
" # Convert audio to features here\n",
|
389 |
+
" audio = whisper.pad_or_trim(f[\"audio\"].flatten())\n",
|
390 |
+
" \n",
|
391 |
+
" if apply_augmentation_flag:\n",
|
392 |
+
" n_fft = random.choice(n_fft_choices)\n",
|
393 |
+
" hop_length = random.choice(hop_length_choices)\n",
|
394 |
+
" if apply_noise_injection_flag:\n",
|
395 |
+
" noise_type = random.choice(noise_profiles)\n",
|
396 |
+
" audio = add_noise(audio, noise_type=noise_type)\n",
|
397 |
+
" else:\n",
|
398 |
+
" n_fft = 1024\n",
|
399 |
+
" hop_length = 512\n",
|
400 |
+
"\n",
|
401 |
+
" # Apply MelSpectrogram transformation with the selected parameters\n",
|
402 |
+
" mel_spectrogram = torchaudio.transforms.MelSpectrogram(\n",
|
403 |
+
" sample_rate=16000, # Assuming a sample rate of 16000\n",
|
404 |
+
" n_fft=n_fft,\n",
|
405 |
+
" hop_length=hop_length,\n",
|
406 |
+
" n_mels=80\n",
|
407 |
+
" )(audio)\n",
|
408 |
+
"\n",
|
409 |
+
" # Apply logarithm for log-Mel spectrogram\n",
|
410 |
+
" input_feature = torch.log(mel_spectrogram + 1e-9)\n",
|
411 |
+
"\n",
|
412 |
+
" label = f[\"label\"]\n",
|
413 |
+
" label_tokens = [tokenizer.bos_token_id] + tokenizer.encode(label) + [tokenizer.eos_token_id]\n",
|
414 |
+
" dec_input_feature = label_tokens[:-1]\n",
|
415 |
+
" label = label_tokens[1:]\n",
|
416 |
+
"\n",
|
417 |
+
" input_features.append(input_feature)\n",
|
418 |
+
" labels.append(label)\n",
|
419 |
+
" dec_input_features.append(dec_input_feature)\n",
|
420 |
+
"\n",
|
421 |
+
" input_features = torch.stack(input_features)\n",
|
422 |
+
"\n",
|
423 |
+
" max_label_len = max(len(l) for l in labels)\n",
|
424 |
+
" max_dec_input_len = max(len(d) for d in dec_input_features)\n",
|
425 |
+
" max_len = max(max_label_len, max_dec_input_len)\n",
|
426 |
+
"\n",
|
427 |
+
" labels = [np.pad(l, (0, max_len - len(l)), 'constant', constant_values=-100) for l in labels]\n",
|
428 |
+
" dec_input_features = [np.pad(d, (0, max_len - len(d)), 'constant', constant_values=tokenizer.pad_token_id) for d in dec_input_features]\n",
|
429 |
+
"\n",
|
430 |
+
" # Convert the lists of numpy arrays to numpy arrays before creating tensors\n",
|
431 |
+
" labels = np.array(labels)\n",
|
432 |
+
" dec_input_features = np.array(dec_input_features)\n",
|
433 |
+
"\n",
|
434 |
+
" labels = torch.tensor(labels, dtype=torch.long)\n",
|
435 |
+
" dec_input_features = torch.tensor(dec_input_features, dtype=torch.long)\n",
|
436 |
+
"\n",
|
437 |
+
" batch = {\n",
|
438 |
+
" \"input_features\": input_features,\n",
|
439 |
+
" \"labels\": labels,\n",
|
440 |
+
" \"dec_input_features\": dec_input_features\n",
|
441 |
+
" }\n",
|
442 |
+
" return batch\n"
|
443 |
+
]
|
444 |
+
},
|
445 |
+
{
|
446 |
+
"cell_type": "code",
|
447 |
+
"execution_count": null,
|
448 |
+
"metadata": {},
|
449 |
+
"outputs": [],
|
450 |
+
"source": [
|
451 |
+
"# Flag to apply augmentation\n",
|
452 |
+
"apply_augmentation_flag = True\n",
|
453 |
+
"apply_noise_injection_flag = True\n",
|
454 |
+
"\n",
|
455 |
+
"# Create dataset and dataloader with augmentation and noise injection based on the flags\n",
|
456 |
+
"collate_fn_with_flags = partial(collate_fn, apply_augmentation_flag=apply_augmentation_flag, apply_noise_injection_flag=apply_noise_injection_flag)\n",
|
457 |
+
"dataloader = torch.utils.data.DataLoader(dataset, batch_size=2, shuffle=True, collate_fn=collate_fn_with_flags)\n",
|
458 |
+
"\n",
|
459 |
+
"for batch in dataloader:\n",
|
460 |
+
" # Pass the batch to your model\n",
|
461 |
+
" outputs = model(batch)\n"
|
462 |
+
]
|
463 |
+
}
|
464 |
+
],
|
465 |
+
"metadata": {
|
466 |
+
"language_info": {
|
467 |
+
"name": "python"
|
468 |
+
}
|
469 |
+
},
|
470 |
+
"nbformat": 4,
|
471 |
+
"nbformat_minor": 2
|
472 |
+
}
|