Sin2pi commited on
Commit
657e19a
·
verified ·
1 Parent(s): 339e2f4

Delete newcollators.ipynb

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