{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from dataclasses import dataclass\n", "from typing import Any, Dict, List, Union\n", "import torch\n", "import torchaudio\n", "import random\n", "\n", "@dataclass\n", "class DataCollatorSpeechSeq2SeqWithPadding:\n", " processor: Any\n", " decoder_start_token_id: int\n", " apply_augmentation: bool = False\n", " n_fft_choices: List[int] = (400, 800, 1024)\n", " hop_length_choices: List[int] = (160, 320, 512)\n", " apply_noise_injection: bool = False # Toggle for noise injection\n", " noise_profiles: List[str] = ('white', 'pink', 'environmental') # Example noise profiles\n", "\n", " def add_adaptive_noise(self, audio, noise_type='white', base_intensity=0.005):\n", " amplitude = audio.abs().mean()\n", " noise_intensity = base_intensity * amplitude # Scale noise intensity based on amplitude\n", "\n", " noise = torch.randn_like(audio) * noise_intensity\n", " if noise_type == 'pink':\n", " noise = torchaudio.functional.highpass_biquad(noise, sample_rate=16000, cutoff_freq=200)\n", " elif noise_type == 'environmental':\n", " # Load an example environmental noise file\n", " noise, _ = torchaudio.load('environmental_noise.wav')\n", " noise = torch.nn.functional.interpolate(noise.unsqueeze(0), size=audio.size()).squeeze() * noise_intensity\n", " return audio + noise\n", "\n", " def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:\n", " input_features = []\n", " labels_list = []\n", " dec_input_features = []\n", " \n", " for feature in features:\n", " audio = feature[\"input_features\"]\n", " if self.apply_augmentation:\n", " # Randomly select n_fft and hop_length for augmentation\n", " n_fft = random.choice(self.n_fft_choices)\n", " hop_length = random.choice(self.hop_length_choices)\n", " if self.apply_noise_injection:\n", " noise_type = random.choice(self.noise_profiles)\n", " audio = self.add_adaptive_noise(audio, noise_type=noise_type)\n", " else:\n", " # Use default values if augmentation is not applied\n", " n_fft = 1024\n", " hop_length = 512\n", "\n", " # Apply MelSpectrogram transformation with the selected parameters\n", " mel_spectrogram = torchaudio.transforms.MelSpectrogram(\n", " sample_rate=16000, # Sample rate is assumed; update if necessary\n", " n_fft=n_fft,\n", " hop_length=hop_length,\n", " n_mels=80\n", " )(torch.tensor(audio))\n", "\n", " log_mel_spectrogram = torch.log(mel_spectrogram + 1e-9)\n", " input_features.append({\"input_features\": log_mel_spectrogram})\n", " \n", " label = feature[\"labels\"]\n", " label_tokens = [self.processor.tokenizer.bos_token_id] + self.processor.tokenizer.encode(label) + [self.processor.tokenizer.eos_token_id]\n", " dec_input_feature = label_tokens[:-1]\n", " label = label_tokens[1:]\n", " \n", " labels_list.append({\"input_ids\": label})\n", " dec_input_features.append({\"input_ids\": dec_input_feature})\n", " \n", " batch = self.processor.feature_extractor.pad(input_features, return_tensors=\"pt\")\n", " labels_batch = self.processor.tokenizer.pad(labels_list, return_tensors=\"pt\")\n", " dec_input_batch = self.processor.tokenizer.pad(dec_input_features, return_tensors=\"pt\")\n", "\n", " labels = labels_batch[\"input_ids\"].masked_fill(labels_batch.attention_mask.ne(1), -100)\n", " if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():\n", " labels = labels[:, 1:]\n", " batch[\"labels\"] = labels\n", "\n", " dec_input_features = dec_input_batch[\"input_ids\"]\n", " if (dec_input_features[:, 0] == self.decoder_start_token_id).all().cpu().item():\n", " dec_input_features = dec_input_features[:, 1:]\n", " batch[\"dec_input_features\"] = dec_input_features\n", "\n", " return batch\n", "\n", "# Example usage\n", "data_collator = DataCollatorSpeechSeq2SeqWithPadding(\n", " processor=processor,\n", " decoder_start_token_id=model.config.decoder_start_token_id,\n", " apply_augmentation=True, # Enable augmentation\n", " apply_noise_injection=True # Enable adaptive noise injection\n", ")\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from dataclasses import dataclass\n", "from typing import Any, Dict, List, Union\n", "import torch\n", "import torchaudio\n", "import random\n", "\n", "\n", "def add_adaptive_noise(audio, noise_type='white', base_intensity=0.005):\n", " amplitude = audio.abs().mean()\n", " noise_intensity = base_intensity * amplitude # Scale noise intensity based on amplitude\n", " \n", " noise = torch.randn_like(audio) * noise_intensity\n", " if noise_type == 'pink':\n", " noise = torchaudio.functional.highpass_biquad(noise, sample_rate=16000, cutoff_freq=200)\n", " elif noise_type == 'environmental':\n", " # Load an example environmental noise file\n", " noise, _ = torchaudio.load('environmental_noise.wav')\n", " noise = torch.nn.functional.interpolate(noise.unsqueeze(0), size=audio.size()).squeeze() * noise_intensity\n", " return audio + noise\n", "\n", "def collate_fn(batch, apply_augmentation_flag=True, apply_noise_injection_flag=False):\n", " n_fft_choices = [400, 800, 1024]\n", " hop_length_choices = [160, 320, 512]\n", " noise_profiles = ['white', 'pink', 'environmental']\n", "\n", " input_features, labels, dec_input_features = [], [], []\n", " \n", " for f in batch:\n", " audio = whisper.pad_or_trim(f[\"audio\"].flatten())\n", " \n", " if apply_augmentation_flag:\n", " n_fft = random.choice(n_fft_choices)\n", " hop_length = random.choice(hop_length_choices)\n", " if apply_noise_injection_flag:\n", " noise_type = random.choice(noise_profiles)\n", " audio = add_adaptive_noise(audio, noise_type=noise_type)\n", " else:\n", " n_fft = 1024\n", " hop_length = 512\n", "\n", " mel_spectrogram = torchaudio.transforms.MelSpectrogram(\n", " sample_rate=16000, # Assuming a sample rate of 16000\n", " n_fft=n_fft,\n", " hop_length=hop_length,\n", " n_mels=80\n", " )(audio)\n", "\n", " input_feature = torch.log(mel_spectrogram + 1e-9)\n", "\n", " label = f[\"label\"]\n", " label_tokens = [tokenizer.bos_token_id] + tokenizer.encode(label) + [tokenizer.eos_token_id]\n", " dec_input_feature = label_tokens[:-1]\n", " label = label_tokens[1:]\n", "\n", " input_features.append(input_feature)\n", " labels.append(label)\n", " dec_input_features.append(dec_input_feature)\n", "\n", " input_features = torch.stack(input_features)\n", "\n", " max_label_len = max(len(l) for l in labels)\n", " max_dec_input_len = max(len(d) for d in dec_input_features)\n", " max_len = max(max_label_len, max_dec_input_len)\n", "\n", " labels = [np.pad(l, (0, max_len - len(l)), 'constant', constant_values=-100) for l in labels]\n", " 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", "\n", " labels = np.array(labels)\n", " dec_input_features = np.array(dec_input_features)\n", "\n", " labels = torch.tensor(labels, dtype=torch.long)\n", " dec_input_features = torch.tensor(dec_input_features, dtype=torch.long)\n", "\n", " batch = {\n", " \"input_features\": input_features,\n", " \"labels\": labels,\n", " \"dec_input_features\": dec_input_features\n", " }\n", " return batch\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from dataclasses import dataclass\n", "from typing import Any, Dict, List, Union\n", "import torch\n", "import torchaudio\n", "import random\n", "\n", "@dataclass\n", "class DataCollatorSpeechSeq2SeqWithPadding:\n", " processor: Any\n", " decoder_start_token_id: int\n", " apply_augmentation: bool = False\n", " n_fft_choices: List[int] = (400, 800, 1024)\n", " hop_length_choices: List[int] = (160, 320, 512)\n", "\n", " def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:\n", " input_features = []\n", " labels_list = []\n", " dec_input_features = []\n", " \n", " for feature in features:\n", " audio = feature[\"input_features\"]\n", " if self.apply_augmentation:\n", " # Randomly select n_fft and hop_length for augmentation\n", " n_fft = random.choice(self.n_fft_choices)\n", " hop_length = random.choice(self.hop_length_choices)\n", " else:\n", " # Use default values if augmentation is not applied\n", " n_fft = 1024\n", " hop_length = 512\n", "\n", " # Apply MelSpectrogram transformation with the selected parameters\n", " mel_spectrogram = torchaudio.transforms.MelSpectrogram(\n", " sample_rate=16000, # Sample rate is assumed; update if necessary\n", " n_fft=n_fft,\n", " hop_length=hop_length,\n", " n_mels=80\n", " )(torch.tensor(audio))\n", "\n", " log_mel_spectrogram = torch.log(mel_spectrogram + 1e-9)\n", " input_features.append({\"input_features\": log_mel_spectrogram})\n", " \n", " label = feature[\"labels\"]\n", " label_tokens = [self.processor.tokenizer.bos_token_id] + self.processor.tokenizer.encode(label) + [self.processor.tokenizer.eos_token_id]\n", " dec_input_feature = label_tokens[:-1]\n", " label = label_tokens[1:]\n", " \n", " labels_list.append({\"input_ids\": label})\n", " dec_input_features.append({\"input_ids\": dec_input_feature})\n", " \n", " batch = self.processor.feature_extractor.pad(input_features, return_tensors=\"pt\")\n", " labels_batch = self.processor.tokenizer.pad(labels_list, return_tensors=\"pt\")\n", " dec_input_batch = self.processor.tokenizer.pad(dec_input_features, return_tensors=\"pt\")\n", "\n", " labels = labels_batch[\"input_ids\"].masked_fill(labels_batch.attention_mask.ne(1), -100)\n", " if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():\n", " labels = labels[:, 1:]\n", " batch[\"labels\"] = labels\n", "\n", " dec_input_features = dec_input_batch[\"input_ids\"]\n", " if (dec_input_features[:, 0] == self.decoder_start_token_id).all().cpu().item():\n", " dec_input_features = dec_input_features[:, 1:]\n", " batch[\"dec_input_features\"] = dec_input_features\n", "\n", " return batch\n", "\n", "# Example usage\n", "data_collator = DataCollatorSpeechSeq2SeqWithPadding(\n", " processor=processor,\n", " decoder_start_token_id=model.config.decoder_start_token_id,\n", " apply_augmentation=True # Set to False to disable augmentation\n", ")\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "@dataclass\n", "class DataCollatorSpeechSeq2SeqWithPadding:\n", " processor: Any\n", " decoder_start_token_id: int\n", " apply_augmentation: bool = False\n", " n_fft_choices: List[int] = (400, 800, 1024)\n", " hop_length_choices: List[int] = (160, 320, 512)\n", " apply_noise_injection: bool = False # Toggle for noise injection\n", " noise_profiles: List[str] = ('white', 'pink', 'environmental') # Example noise profiles\n", "\n", " def add_noise(self, audio, noise_type='white', intensity=0.005):\n", " noise = torch.randn_like(audio) * intensity\n", " if noise_type == 'pink':\n", " noise = torchaudio.functional.highpass_biquad(noise, sample_rate=16000, cutoff_freq=200)\n", " elif noise_type == 'environmental':\n", " # Load an example environmental noise file\n", " noise, _ = torchaudio.load('environmental_noise.wav')\n", " noise = torch.nn.functional.interpolate(noise.unsqueeze(0), size=audio.size()).squeeze() * intensity\n", " return audio + noise\n", "\n", " def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:\n", " input_features = []\n", " labels_list = []\n", " dec_input_features = []\n", " \n", " for feature in features:\n", " audio = feature[\"input_features\"]\n", " if self.apply_augmentation:\n", " n_fft = random.choice(self.n_fft_choices)\n", " hop_length = random.choice(self.hop_length_choices)\n", " if self.apply_noise_injection:\n", " noise_type = random.choice(self.noise_profiles)\n", " audio = self.add_noise(audio, noise_type=noise_type)\n", " else:\n", " n_fft = 1024\n", " hop_length = 512\n", "\n", " mel_spectrogram = torchaudio.transforms.MelSpectrogram(\n", " sample_rate=16000, # Sample rate is assumed; update if necessary\n", " n_fft=n_fft,\n", " hop_length=hop_length,\n", " n_mels=80\n", " )(torch.tensor(audio))\n", "\n", " log_mel_spectrogram = torch.log(mel_spectrogram + 1e-9)\n", " input_features.append({\"input_features\": log_mel_spectrogram})\n", " \n", " label = feature[\"labels\"]\n", " label_tokens = [self.processor.tokenizer.bos_token_id] + self.processor.tokenizer.encode(label) + [self.processor.tokenizer.eos_token_id]\n", " dec_input_feature = label_tokens[:-1]\n", " label = label_tokens[1:]\n", " \n", " labels_list.append({\"input_ids\": label})\n", " dec_input_features.append({\"input_ids\": dec_input_feature})\n", " \n", " batch = self.processor.feature_extractor.pad(input_features, return_tensors=\"pt\")\n", " labels_batch = self.processor.tokenizer.pad(labels_list, return_tensors=\"pt\")\n", " dec_input_batch = self.processor.tokenizer.pad(dec_input_features, return_tensors=\"pt\")\n", "\n", " labels = labels_batch[\"input_ids\"].masked_fill(labels_batch.attention_mask.ne(1), -100)\n", " if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():\n", " labels = labels[:, 1:]\n", " batch[\"labels\"] = labels\n", "\n", " dec_input_features = dec_input_batch[\"input_ids\"]\n", " if (dec_input_features[:, 0] == self.decoder_start_token_id).all().cpu().item():\n", " dec_input_features = dec_input_features[:, 1:]\n", " batch[\"dec_input_features\"] = dec_input_features\n", "\n", " return batch\n", "\n", "data_collator = DataCollatorSpeechSeq2SeqWithPadding(\n", " processor=processor,\n", " decoder_start_token_id=model.config.decoder_start_token_id,\n", " apply_augmentation=True, # Set to True to enable augmentation\n", " apply_noise_injection=True # Set to True to enable noise injection\n", ")\n", "\n", "dataloader = torch.utils.data.DataLoader(dataset, batch_size=2, shuffle=True, collate_fn=data_collator)\n", "\n", "for batch in dataloader:\n", " # Pass the batch to your model\n", " outputs = model(batch)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torch\n", "import torchaudio\n", "import random\n", "import numpy as np\n", "\n", "def add_noise(audio, noise_type='white', intensity=0.005):\n", " noise = torch.randn_like(audio) * intensity\n", " if noise_type == 'pink':\n", " noise = torchaudio.functional.highpass_biquad(noise, sample_rate=16000, cutoff_freq=200)\n", " elif noise_type == 'environmental':\n", " # Load an example environmental noise file\n", " noise, _ = torchaudio.load('environmental_noise.wav')\n", " noise = torch.nn.functional.interpolate(noise.unsqueeze(0), size=audio.size()).squeeze() * intensity\n", " return audio + noise\n", "\n", "def collate_fn(batch, apply_augmentation_flag=True, apply_noise_injection_flag=False):\n", " n_fft_choices = [400, 800, 1024]\n", " hop_length_choices = [160, 320, 512]\n", " noise_profiles = ['white', 'pink', 'environmental']\n", "\n", " input_features, labels, dec_input_features = [], [], []\n", " \n", " for f in batch:\n", " # Convert audio to features here\n", " audio = whisper.pad_or_trim(f[\"audio\"].flatten())\n", " \n", " if apply_augmentation_flag:\n", " n_fft = random.choice(n_fft_choices)\n", " hop_length = random.choice(hop_length_choices)\n", " if apply_noise_injection_flag:\n", " noise_type = random.choice(noise_profiles)\n", " audio = add_noise(audio, noise_type=noise_type)\n", " else:\n", " n_fft = 1024\n", " hop_length = 512\n", "\n", " # Apply MelSpectrogram transformation with the selected parameters\n", " mel_spectrogram = torchaudio.transforms.MelSpectrogram(\n", " sample_rate=16000, # Assuming a sample rate of 16000\n", " n_fft=n_fft,\n", " hop_length=hop_length,\n", " n_mels=80\n", " )(audio)\n", "\n", " # Apply logarithm for log-Mel spectrogram\n", " input_feature = torch.log(mel_spectrogram + 1e-9)\n", "\n", " label = f[\"label\"]\n", " label_tokens = [tokenizer.bos_token_id] + tokenizer.encode(label) + [tokenizer.eos_token_id]\n", " dec_input_feature = label_tokens[:-1]\n", " label = label_tokens[1:]\n", "\n", " input_features.append(input_feature)\n", " labels.append(label)\n", " dec_input_features.append(dec_input_feature)\n", "\n", " input_features = torch.stack(input_features)\n", "\n", " max_label_len = max(len(l) for l in labels)\n", " max_dec_input_len = max(len(d) for d in dec_input_features)\n", " max_len = max(max_label_len, max_dec_input_len)\n", "\n", " labels = [np.pad(l, (0, max_len - len(l)), 'constant', constant_values=-100) for l in labels]\n", " 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", "\n", " # Convert the lists of numpy arrays to numpy arrays before creating tensors\n", " labels = np.array(labels)\n", " dec_input_features = np.array(dec_input_features)\n", "\n", " labels = torch.tensor(labels, dtype=torch.long)\n", " dec_input_features = torch.tensor(dec_input_features, dtype=torch.long)\n", "\n", " batch = {\n", " \"input_features\": input_features,\n", " \"labels\": labels,\n", " \"dec_input_features\": dec_input_features\n", " }\n", " return batch\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Flag to apply augmentation\n", "apply_augmentation_flag = True\n", "apply_noise_injection_flag = True\n", "\n", "# Create dataset and dataloader with augmentation and noise injection based on the flags\n", "collate_fn_with_flags = partial(collate_fn, apply_augmentation_flag=apply_augmentation_flag, apply_noise_injection_flag=apply_noise_injection_flag)\n", "dataloader = torch.utils.data.DataLoader(dataset, batch_size=2, shuffle=True, collate_fn=collate_fn_with_flags)\n", "\n", "for batch in dataloader:\n", " # Pass the batch to your model\n", " outputs = model(batch)\n" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 }