{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"<center><h1 style = \"font-size:50px;font-family: Comic Sans MS\" >🦜 BirdCLEF 2021 </h1></center>","metadata":{}},{"cell_type":"markdown","source":"📌[Audio Feature Extraction Notebook](https://www.kaggle.com/shreyasajal/birdclef-2021-librosa-audio-feature-extraction)","metadata":{}},{"cell_type":"markdown","source":"\n<h1 style = \"font-size:45px;font-family: Comic Sans MS;text-align: center;background-color:#800000;color:#FFFFFF\">Audio Albumentations</h1>\n\n<h3 style=\"font-family:Comic Sans MS\">The importance of albumentations in computer vision to improve performance is well known. Similar is the case when we are working with audio data.Augmentations and audio transforms play an imporatant role here also.In this notebook,I have tried to cover nearly all the possible albumentations that can be applied to audio data.The purpose is to provide the basic intuition of the audio albumentations,by listening the change in the audio for yourself and visualizing the waveform difference.<br>\nI have used both torchaudio transforms and the audiomentations library for covering all the albumentations.<br><br>\n    I hope you like this and it helps you with this competition\n","metadata":{}},{"cell_type":"code","source":"!pip install audiomentations","metadata":{"_kg_hide-output":true,"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-23T00:38:13.207796Z","iopub.execute_input":"2022-02-23T00:38:13.208288Z","iopub.status.idle":"2022-02-23T00:38:22.587089Z","shell.execute_reply.started":"2022-02-23T00:38:13.208166Z","shell.execute_reply":"2022-02-23T00:38:22.586028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport pandas as pd\nimport numpy\nimport torch\nimport math\nimport torchaudio\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport plotly.express as px\nimport descartes\nimport geopandas as gpd\nfrom shapely.geometry import Point, Polygon\nimport librosa\nimport librosa.display\nimport IPython.display as ipd\nfrom IPython.display import Audio, display\nimport sklearn\nimport warnings\nimport gc \nimport torchaudio.functional as F\nimport torchaudio.transforms as T\nwarnings.filterwarnings('ignore')\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")","metadata":{"_kg_hide-output":true,"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-23T00:38:52.911486Z","iopub.execute_input":"2022-02-23T00:38:52.911849Z","iopub.status.idle":"2022-02-23T00:38:56.694118Z","shell.execute_reply.started":"2022-02-23T00:38:52.911817Z","shell.execute_reply":"2022-02-23T00:38:56.692763Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n\n<h1 style = \"font-family: Comic Sans MS\">Some functions we will use</h1>","metadata":{}},{"cell_type":"code","source":"def play_audio(waveform, sample_rate):\n    if type(waveform)!=numpy.ndarray:\n        waveform = waveform.numpy()\n    num_channels, num_frames = waveform.shape\n    if num_channels == 1:\n        display(Audio(waveform[0], rate=sample_rate))\n    elif num_channels == 2:\n        display(Audio((waveform[0], waveform[1]), rate=sample_rate))\n    else: \n        raise ValueError(\"Waveform with more than 2 channels are not supported.\")\n        \ndef print_stats(waveform, sample_rate=None, src=None):\n    if src:\n        print(\"-\" * 10)\n        print(\"Source:\", src)\n        print(\"-\" * 10)\n    if sample_rate:\n        print(\"Sample Rate:\", sample_rate)\n        print(\"Shape:\", tuple(waveform.shape))\n        print(\"Dtype:\", waveform.dtype)\n        print(f\" - Max:     {waveform.max().item():6.3f}\")\n        print(f\" - Min:     {waveform.min().item():6.3f}\")\n        print(f\" - Mean:    {waveform.mean().item():6.3f}\")\n        print(f\" - Std Dev: {waveform.std().item():6.3f}\")\n        print()\n        print(waveform)\n        print()\ndef plot_waveform(waveform, sample_rate, title=\"Waveform\", xlim=None, ylim=None):\n    if type(waveform)!=numpy.ndarray:\n        waveform = waveform.numpy()\n    num_channels, num_frames = waveform.shape\n    time_axis = torch.arange(0, num_frames) / sample_rate\n    figure, axes = plt.subplots(num_channels, figsize=(12,6))\n    if num_channels == 1:\n        axes = [axes]\n    for c in range(num_channels):\n        axes[c].plot(time_axis, waveform[c], linewidth=1,color = \"#A300F9\")\n        axes[c].grid(True)\n        if num_channels > 1:\n            axes[c].set_ylabel(f'Channel {c+1}')\n        if xlim:\n            axes[c].set_xlim(xlim)\n        if ylim:\n            axes[c].set_ylim(ylim)\n    figure.suptitle(title)\n    plt.show(block=False)\ndef plot_specgram(waveform, sample_rate, title=\"Spectrogram\", xlim=None):\n    waveform = waveform.numpy()\n\n    num_channels, num_frames = waveform.shape\n    time_axis = torch.arange(0, num_frames) / sample_rate\n\n    figure, axes = plt.subplots(num_channels, 1, figsize=(12,6))\n    if num_channels == 1:\n        axes = [axes]\n    for c in range(num_channels):\n        axes[c].specgram(waveform[c], Fs=sample_rate)\n        if num_channels > 1:\n            axes[c].set_ylabel(f'Channel {c+1}')\n        if xlim:\n            axes[c].set_xlim(xlim)\n    figure.suptitle(title)\n    plt.show(block=False)\ndef plot_spectrogram(spec, title=None, ylabel='freq_bin', aspect='auto', xmax=None):\n    fig, axs = plt.subplots(1, 1)\n    axs.set_title(title or 'Spectrogram (db)')\n    axs.set_ylabel(ylabel)\n    axs.set_xlabel('frame')\n    im = axs.imshow(librosa.power_to_db(spec), origin='lower', aspect=aspect)\n    if xmax:\n        axs.set_xlim((0, xmax))\n    fig.colorbar(im, ax=axs)\n    plt.show(block=False)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-23T00:38:56.696366Z","iopub.execute_input":"2022-02-23T00:38:56.696709Z","iopub.status.idle":"2022-02-23T00:38:56.717877Z","shell.execute_reply.started":"2022-02-23T00:38:56.696678Z","shell.execute_reply":"2022-02-23T00:38:56.716627Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h1 style = \"font-family: Comic Sans MS\">Load The Data</h1>","metadata":{}},{"cell_type":"code","source":"train_csv=pd.read_csv('../input/birdclef-2021/train_metadata.csv')\ntrain_csv.head()","metadata":{"execution":{"iopub.status.busy":"2022-02-23T00:39:00.902568Z","iopub.execute_input":"2022-02-23T00:39:00.902958Z","iopub.status.idle":"2022-02-23T00:39:01.459223Z","shell.execute_reply.started":"2022-02-23T00:39:00.902922Z","shell.execute_reply":"2022-02-23T00:39:01.458244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h1 style = \"font-family: Comic Sans MS\">GETTING A FEW SAMPLES</h1>","metadata":{}},{"cell_type":"code","source":"# Create Full Path so we can access data more easily\nbase_dir = '../input/birdclef-2021/train_short_audio'\ntrain_csv['full_path'] = base_dir+ '/' + train_csv['primary_label'] + '/' + train_csv['filename']\n\n# Now let's sample a fiew audio files\nastfly = train_csv[train_csv['primary_label'] == \"astfly\"].sample(1, random_state = 33)['full_path'].values[0]\ncasvir = train_csv[train_csv['primary_label'] == 'casvir'].sample(1, random_state = 33)['full_path'].values[0]\nsubfly = train_csv[train_csv['primary_label'] == \"subfly\"].sample(1, random_state = 33)['full_path'].values[0]\nwilfly = train_csv[train_csv['primary_label'] == 'wilfly'].sample(1, random_state = 33)['full_path'].values[0]\nverdin = train_csv[train_csv['primary_label'] == 'verdin'].sample(1, random_state = 33)['full_path'].values[0]\nsolsan = train_csv[train_csv['primary_label'] == 'solsan'].sample(1, random_state = 33)['full_path'].values[0]\n\n\nbirds= [\"astfly\", \"casvir\", \"subfly\", \"wilfly\", \"verdin\",'solsan']","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-23T00:39:04.179749Z","iopub.execute_input":"2022-02-23T00:39:04.180144Z","iopub.status.idle":"2022-02-23T00:39:04.344751Z","shell.execute_reply.started":"2022-02-23T00:39:04.180107Z","shell.execute_reply":"2022-02-23T00:39:04.343725Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"  # Loading audio data into Tensor","metadata":{}},{"cell_type":"code","source":"waveform, sample_rate = torchaudio.load(astfly)\nwaveform.to(device)\nprint_stats(waveform, sample_rate=sample_rate)\nplay_audio(waveform, sample_rate)","metadata":{"execution":{"iopub.status.busy":"2022-02-23T00:39:07.175285Z","iopub.execute_input":"2022-02-23T00:39:07.175677Z","iopub.status.idle":"2022-02-23T00:39:07.352026Z","shell.execute_reply.started":"2022-02-23T00:39:07.175646Z","shell.execute_reply":"2022-02-23T00:39:07.350958Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# SAVING AUDIO TO FILE","metadata":{}},{"cell_type":"markdown","source":"Saved the astfly audio (ogg format) that we loaded above in mp3 format ","metadata":{}},{"cell_type":"code","source":"path = \"./audio.mp3\"\ntorchaudio.save(path, waveform, sample_rate)","metadata":{"execution":{"iopub.status.busy":"2022-02-23T00:39:10.705937Z","iopub.execute_input":"2022-02-23T00:39:10.706328Z","iopub.status.idle":"2022-02-23T00:39:10.783811Z","shell.execute_reply.started":"2022-02-23T00:39:10.706289Z","shell.execute_reply":"2022-02-23T00:39:10.782642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"waveform, sample_rate = torchaudio.load(astfly)\nwaveform.shape","metadata":{"execution":{"iopub.status.busy":"2022-02-23T00:39:11.607740Z","iopub.execute_input":"2022-02-23T00:39:11.608140Z","iopub.status.idle":"2022-02-23T00:39:11.632629Z","shell.execute_reply.started":"2022-02-23T00:39:11.608092Z","shell.execute_reply":"2022-02-23T00:39:11.631227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h1 style = \"font-size:30px;font-family: Comic Sans MS;text-align:center\">RESAMPLE</h1>","metadata":{}},{"cell_type":"code","source":"new_sample_rate = sample_rate/10\ntransformed = torchaudio.transforms.Resample(sample_rate, new_sample_rate)(waveform)\nprint(\"Shape of transformed waveform: {}\".format(transformed.size()))\nplot_waveform(waveform,sample_rate,title='Original')\nplot_waveform(transformed,new_sample_rate,title='resampled')","metadata":{"execution":{"iopub.status.busy":"2022-02-23T00:39:14.870047Z","iopub.execute_input":"2022-02-23T00:39:14.870654Z","iopub.status.idle":"2022-02-23T00:39:19.118380Z","shell.execute_reply.started":"2022-02-23T00:39:14.870616Z","shell.execute_reply":"2022-02-23T00:39:19.117204Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h1 style = \"font-size:30px;font-family: Comic Sans MS;text-align: center\"> APPLYING EFFECTS(SOX)</h1>\n<h3 style=\"font-family:Comic Sans MS\">\n1. Speed changing<br>\n2. Reverberation","metadata":{}},{"cell_type":"code","source":"waveform1,sample_rate1=torchaudio.load(astfly)\nwaveform1.to(device)\neffects = [\n  [\"speed\", \"1.2\"],  # increase the speed\n                     # This only changes sample rate, so it is necessary to\n                     # add `rate` effect with original sample rate after this.\n  [\"rate\", f\"{sample_rate1}\"],\n  [\"reverb\", \"-w\"],  # Reverbration gives some dramatic feeling\n]\nwaveform2, sample_rate2 = torchaudio.sox_effects.apply_effects_tensor(waveform1, sample_rate1, effects)\nwaveform2.to(device)\nplot_waveform(waveform1, sample_rate1, title=\"Original\", xlim=(-.1, 3.2))\nplot_waveform(waveform2, sample_rate2, title=\"Effects Applied\", xlim=(-.1, 3.2))\nprint_stats(waveform1, sample_rate=sample_rate1, src=\"Original\")\nprint_stats(waveform2, sample_rate=sample_rate2, src=\"Effects Applied\")\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2021-05-22T13:45:52.561846Z","iopub.execute_input":"2021-05-22T13:45:52.562425Z","iopub.status.idle":"2021-05-22T13:46:01.837450Z","shell.execute_reply.started":"2021-05-22T13:45:52.562380Z","shell.execute_reply":"2021-05-22T13:46:01.836268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<h3 style=\"font-family:Comic Sans MS\">See the effect for yourself","metadata":{}},{"cell_type":"code","source":"play_audio(waveform1, sample_rate1)\nplay_audio(waveform2, sample_rate2)","metadata":{"execution":{"iopub.status.busy":"2021-05-22T13:46:01.839114Z","iopub.execute_input":"2021-05-22T13:46:01.839560Z","iopub.status.idle":"2021-05-22T13:46:01.917730Z","shell.execute_reply.started":"2021-05-22T13:46:01.839499Z","shell.execute_reply":"2021-05-22T13:46:01.916389Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h1 style = \"font-size:30px;font-family: Comic Sans MS;text-align: center\">Adding background noise</h1>","metadata":{}},{"cell_type":"markdown","source":"<h3 style=\"font-family:Comic Sans MS\">To add background noise to audio data, you can simply add audio Tensor and noise Tensor. A commonly used way to adjust the intensity of noise is to change Signal-to-Noise Ratio (SNR).","metadata":{}},{"cell_type":"code","source":"def _get_sample(path, resample=None):\n    effects = [\n      [\"remix\", \"1\"]\n    ]\n    if resample:\n        effects.append([\"rate\", f'{resample}'])\n    return torchaudio.sox_effects.apply_effects_file(path, effects=effects)\n\ndef get_noise_sample(*, resample=None):\n    return _get_sample(casvir, resample=resample)\n\ndef get_speech_sample(*, resample=None):\n    return _get_sample(casvir, resample=resample)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-05-22T13:46:01.919171Z","iopub.execute_input":"2021-05-22T13:46:01.919558Z","iopub.status.idle":"2021-05-22T13:46:01.927749Z","shell.execute_reply.started":"2021-05-22T13:46:01.919507Z","shell.execute_reply":"2021-05-22T13:46:01.926504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_rate = 6000\nspeech, _ = get_speech_sample(resample=sample_rate)\nspeech.to(device)\nnoise, _ = get_noise_sample(resample=sample_rate)\nnoise.to(device)\nnoise = noise[:, :speech.shape[1]]\nplot_waveform(noise, sample_rate, title=\"Background noise\")\nplot_specgram(noise, sample_rate, title=\"Background noise\")\nplay_audio(noise, sample_rate)\nspeech_power = speech.norm(p=2)\nnoise_power = noise.norm(p=2)\nfor snr_db in [20]:\n    snr = math.exp(snr_db / 10)\n    scale = snr * noise_power / speech_power\n    noisy_speech = (scale * speech + noise) / 2\n    plot_waveform(noisy_speech, sample_rate1, title=f\"SNR: {snr_db} [dB]\")\n    play_audio(noisy_speech, sample_rate1)\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2021-05-22T13:46:01.929613Z","iopub.execute_input":"2021-05-22T13:46:01.930084Z","iopub.status.idle":"2021-05-22T13:46:26.575202Z","shell.execute_reply.started":"2021-05-22T13:46:01.930035Z","shell.execute_reply":"2021-05-22T13:46:26.574153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h1 style = \"font-size:30px;font-family: Comic Sans MS\">SpecAugment</h1>\n<h4 style=\"font-family:Comic Sans MS\">SpecAugment is a popular augmentation technique applied on spectrogram.Torchaudio implements TimeStrech, TimeMasking and FrequencyMasking.","metadata":{}},{"cell_type":"markdown","source":"# <h1 style = \"font-size:30px;font-family: Comic Sans MS;text-align: center\">Time Masking</h1>","metadata":{}},{"cell_type":"code","source":"waveform, sample_rate = torchaudio.load(subfly)\nwaveform.to(device)\ntorch.random.manual_seed(4)\nn_fft = 2048\nwin_length = None\nhop_length = 400\n\nspectrogram = T.Spectrogram(\n    n_fft=n_fft,\n    win_length=win_length,\n    hop_length=hop_length\n)\n# Perform transformation\nspec = spectrogram(waveform)\nplot_spectrogram(spec[0], title=\"Original\")\nmasking = T.TimeMasking(time_mask_param=1300)\nspec = masking(spec)\ngriffin_lim = T.GriffinLim(\n    n_fft=n_fft,\n    win_length=win_length,\n    hop_length=hop_length,\n)\nwaveform_n=griffin_lim(spec)\nwaveform.to(device)\nplot_spectrogram(spec[0], title=\"Masked along time axis\")\n\nplay_audio(waveform, sample_rate)\nplay_audio(waveform_n, sample_rate)\n","metadata":{"execution":{"iopub.status.busy":"2021-05-22T13:46:26.576516Z","iopub.execute_input":"2021-05-22T13:46:26.576848Z","iopub.status.idle":"2021-05-22T13:47:00.120953Z","shell.execute_reply.started":"2021-05-22T13:46:26.576818Z","shell.execute_reply":"2021-05-22T13:47:00.120022Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h1 style = \"font-size:30px;font-family: Comic Sans MS;text-align: center\">Frequency Masking</h1>","metadata":{}},{"cell_type":"code","source":"torch.random.manual_seed(4)\nwaveform, sample_rate = torchaudio.load(subfly)\nwaveform.to(device)\nn_fft = 2048\nwin_length = None\nhop_length = 400\n\nspectrogram = T.Spectrogram(\n    n_fft=n_fft,\n    win_length=win_length,\n    hop_length=hop_length\n)\n# Perform transformation\nspec = spectrogram(waveform)\nplot_spectrogram(spec[0], title=\"Original\")\nmasking = T.FrequencyMasking(freq_mask_param=1000)\nspec = masking(spec)\ngriffin_lim = T.GriffinLim(\n    n_fft=n_fft,\n    win_length=win_length,\n    hop_length=hop_length,\n)\nwaveform_n=griffin_lim(spec)\nwaveform.to(device)\nplot_spectrogram(spec[0], title=\"Masked along frequency axis\")\nplay_audio(waveform, sample_rate)\nplay_audio(waveform_n, sample_rate)\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2021-05-22T13:47:00.122056Z","iopub.execute_input":"2021-05-22T13:47:00.122490Z","iopub.status.idle":"2021-05-22T13:47:34.101401Z","shell.execute_reply.started":"2021-05-22T13:47:00.122458Z","shell.execute_reply":"2021-05-22T13:47:34.100565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h1 style = \"font-size:30px;font-family: Comic Sans MS;text-align: center\">FADE</h1>","metadata":{}},{"cell_type":"code","source":"fade=T.Fade(fade_in_len=200, fade_out_len=100, fade_shape='linear')\nwaveform, sample_rate = torchaudio.load(astfly)\nplot_waveform(waveform, sample_rate, title='original')\nplay_audio(waveform, sample_rate)\nwaveform1=fade(waveform)\nplot_waveform(waveform1, sample_rate, title='fade')\nplay_audio(waveform1, sample_rate)\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2021-05-22T13:47:34.102491Z","iopub.execute_input":"2021-05-22T13:47:34.103057Z","iopub.status.idle":"2021-05-22T13:47:41.172668Z","shell.execute_reply.started":"2021-05-22T13:47:34.103017Z","shell.execute_reply":"2021-05-22T13:47:41.171639Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h1 style = \"font-size:30px;font-family: Comic Sans MS;text-align: center\">VOLUME TRANSFORM</h1>","metadata":{}},{"cell_type":"code","source":"vol=T.Vol(gain=29, gain_type='db')\nwaveform, sample_rate = torchaudio.load(subfly)\nplay_audio(waveform, sample_rate)\nwaveform1=vol(waveform)\nplay_audio(waveform1, sample_rate)\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2021-05-22T13:47:41.174014Z","iopub.execute_input":"2021-05-22T13:47:41.174419Z","iopub.status.idle":"2021-05-22T13:47:41.943409Z","shell.execute_reply.started":"2021-05-22T13:47:41.174378Z","shell.execute_reply":"2021-05-22T13:47:41.942194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n# <h1 style = \"font-size:30px;font-family: Comic Sans MS\"> AUDIOMENTATIONS</h1>","metadata":{}},{"cell_type":"markdown","source":"# <h1 style = \"font-size:30px;font-family: Comic Sans MS;text-align: center\">Time Stretch & Clipping</h1>","metadata":{}},{"cell_type":"code","source":"from audiomentations import TimeStretch\nfrom audiomentations import Compose,ClippingDistortion\naugmenter = Compose(\n            [\n                ClippingDistortion(\n                    min_percentile_threshold=20, max_percentile_threshold=40, p=1.0\n                ),TimeStretch(min_rate=0.8, max_rate=0.9, leave_length_unchanged=False, p=1.0)\n            ]\n        )\nwaveform, sample_rate = torchaudio.load(subfly)\nplay_audio(waveform, sample_rate)\nwaveform1 = augmenter(samples=waveform.numpy(), sample_rate=sample_rate)\nwaveform1=torch.from_numpy(waveform1)\nplay_audio(waveform1, sample_rate)","metadata":{"execution":{"iopub.status.busy":"2022-02-23T00:39:19.207444Z","iopub.execute_input":"2022-02-23T00:39:19.207815Z","iopub.status.idle":"2022-02-23T00:39:23.173592Z","shell.execute_reply.started":"2022-02-23T00:39:19.207779Z","shell.execute_reply":"2022-02-23T00:39:23.171060Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h1 style = \"font-size:30px;font-family: Comic Sans MS;text-align: center\">PITCH SHIFT & POLARITY INVERSION</h1>","metadata":{}},{"cell_type":"code","source":"from audiomentations import PitchShift,PolarityInversion\naugmenter = Compose([PitchShift(min_semitones=-2, max_semitones=-1, p=1.0),PolarityInversion(p=1.0)])\nwaveform, sample_rate = torchaudio.load(subfly)\nplay_audio(waveform, sample_rate)\nwaveform1 = augmenter(samples=waveform.numpy(), sample_rate=sample_rate)\nwaveform1=torch.from_numpy(waveform1)\nplay_audio(waveform1, sample_rate)\nplot_waveform(waveform, sample_rate, title='original')\nplot_waveform(waveform1, sample_rate, title='Augmented')","metadata":{"execution":{"iopub.status.busy":"2021-05-22T13:47:45.527608Z","iopub.execute_input":"2021-05-22T13:47:45.528152Z","iopub.status.idle":"2021-05-22T13:48:46.659339Z","shell.execute_reply.started":"2021-05-22T13:47:45.528111Z","shell.execute_reply":"2021-05-22T13:48:46.658571Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h1 style = \"font-size:30px;font-family: Comic Sans MS;text-align: center\">FORWARD SHIFT</h1>","metadata":{}},{"cell_type":"code","source":"from audiomentations import Shift\nforward_augmenter = Compose([Shift(min_fraction=0.5, max_fraction=0.5, p=1.0)])\nwaveform, sample_rate = torchaudio.load(subfly)\nplay_audio(waveform, sample_rate)\nwaveform1 = forward_augmenter(samples=waveform.numpy(), sample_rate=sample_rate)\nwaveform1=torch.from_numpy(waveform1)\nplay_audio(waveform1, sample_rate)\nplot_waveform(waveform, sample_rate, title='original')\nplot_waveform(waveform1, sample_rate, title='Forward Shift')","metadata":{"execution":{"iopub.status.busy":"2021-05-22T13:48:46.660434Z","iopub.execute_input":"2021-05-22T13:48:46.661036Z","iopub.status.idle":"2021-05-22T13:49:41.137968Z","shell.execute_reply.started":"2021-05-22T13:48:46.660998Z","shell.execute_reply":"2021-05-22T13:49:41.136741Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h1 style = \"font-size:30px;font-family: Comic Sans MS;text-align: center\">BACKWARD SHIFT</h1>","metadata":{}},{"cell_type":"code","source":"backward_augmenter = Compose([Shift(min_fraction=-0.25, max_fraction=-0.25, p=1.0)])\nwaveform, sample_rate = torchaudio.load(subfly)\nplay_audio(waveform, sample_rate)\nwaveform1 = backward_augmenter(samples=waveform.numpy(), sample_rate=sample_rate)\nwaveform1=torch.from_numpy(waveform1)\nplay_audio(waveform1, sample_rate)\nplot_waveform(waveform, sample_rate, title='original')\nplot_waveform(waveform1, sample_rate, title='Backward Shift')","metadata":{"execution":{"iopub.status.busy":"2021-05-22T13:49:41.139110Z","iopub.execute_input":"2021-05-22T13:49:41.139547Z","iopub.status.idle":"2021-05-22T13:50:35.140143Z","shell.execute_reply.started":"2021-05-22T13:49:41.139504Z","shell.execute_reply":"2021-05-22T13:50:35.139288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"![Upvote!](https://img.shields.io/badge/Upvote-If%20you%20like%20my%20work-07b3c8?style=for-the-badge&logo=kaggle)","metadata":{}}]}