{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Audio -> Denoised Melspectrogram Image"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session\n\n!pip install noisereduce","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom scipy import signal\nfrom scipy.io import wavfile as wav\nimport numpy as np\nfrom numpy.lib import stride_tricks\n\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport librosa\nimport librosa.display\nimport noisereduce as nr\n\nimport IPython.display as ipd\n\nfrom glob import glob\nfrom tqdm import tqdm\n\nimport tensorflow as tf\nfrom tensorflow.python.keras import Sequential\nfrom tensorflow.python.keras.layers import Input, Dense\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Load Train Set Metadata"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_fp = pd.read_csv('../input/rfcx-species-audio-detection/train_fp.csv')\ntrain_fp_noise = train_fp.groupby('recording_id')['t_min'].min().reset_index()\n\nprint('We have %d training samples' % (train_fp.shape[0]))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Reading, Denoising and Converting Audio to Spectrograms"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reading the audio file and applying some transformations (trimming, padding...) and denoising to \"clean\" the sound file\ndef read_audio(conf, pathname, t_min, trim_long_data):\n    y, sr = librosa.load(pathname, sr=conf.sampling_rate)\n    \n    # Denoise\n    audio_data, sampling_rate = librosa.load(pathname)\n    noise_interval = [0, int(sr * t_min)]\n    noisy_part = y[noise_interval[0]:noise_interval[1]]\n    reduced_noise = nr.reduce_noise(audio_clip=y, noise_clip=noisy_part)\n    trimmed, index = librosa.effects.trim(reduced_noise, top_db=20, frame_length=512, hop_length=64)\n    \n    # trim silence\n    if 0 < len(trimmed): # workaround: 0 length causes error\n        trimmed, _ = librosa.effects.trim(trimmed) # trim, top_db=default(60)\n    # make it unified length to conf.samples\n    if len(trimmed) > conf.samples: # long enough\n        if trim_long_data:\n            trimmed = trimmed[0:0+conf.samples]\n    else: # pad blank\n        padding = conf.samples - len(trimmed)    # add padding at both ends\n        offset = padding // 2\n        trimmed = np.pad(trimmed, (offset, conf.samples - len(trimmed) - offset), 'constant')\n    return trimmed\n\n# Generating the Melspectrogram using Librosa\ndef audio_to_melspectrogram(conf, audio):\n    spectrogram = librosa.feature.melspectrogram(audio, \n                                                 sr=conf.sampling_rate,\n                                                 n_mels=conf.n_mels,\n                                                 hop_length=conf.hop_length,\n                                                 n_fft=conf.n_fft,\n                                                 fmin=conf.fmin,\n                                                 fmax=conf.fmax)\n    spectrogram = librosa.power_to_db(spectrogram)\n    spectrogram = spectrogram.astype(np.float32)\n    return spectrogram\n\n# Adding both previous function together\ndef read_as_melspectrogram(conf, pathname, t_min, trim_long_data, debug_display=False):\n    x = read_audio(conf, pathname, t_min, trim_long_data)\n    mels = audio_to_melspectrogram(conf, x)\n    return mels\n\n# A set of settings that you can adapt to fit your audio files (frequency, average duration, number of Fourier transforms...)\nclass conf:\n    # Preprocessing settings\n    sampling_rate = 44100\n    duration = 2\n    hop_length = 347*duration # to make time steps 128\n    fmin = 20\n    fmax = sampling_rate // 2\n    n_mels = 128\n    n_fft = n_mels * 20\n    samples = sampling_rate * duration","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def mono_to_color(X, mean=None, std=None, norm_max=None, norm_min=None, eps=1e-6):\n    # Stack X as [X,X,X]\n    X = np.stack([X, X, X], axis=-1)\n\n    # Standardize\n    mean = mean or X.mean()\n    std = std or X.std()\n    Xstd = (X - mean) / (std + eps)\n    _min, _max = Xstd.min(), Xstd.max()\n    norm_max = norm_max or _max\n    norm_min = norm_min or _min\n    if (_max - _min) > eps:\n        # Scale to [0, 255]\n        V = Xstd\n        V[V < norm_min] = norm_min\n        V[V > norm_max] = norm_max\n        V = 255 * (V - norm_min) / (norm_max - norm_min)\n        V = V.astype(np.uint8)\n    else:\n        # Just zero\n        V = np.zeros_like(Xstd, dtype=np.uint8)\n    return V","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Remove .flac and add .jpg\n\ndef rename_file(img_name):\n    img_name = img_name.split(\"/\")[4]\n    img_name = img_name[:-5]\n    img_name += \".jpg\"\n    return img_name","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import gc\n\ndef save_image_from_sound(img_path, t_min):\n    filename = rename_file(img_path)\n    x = read_as_melspectrogram(conf, img_path, t_min, trim_long_data=False, debug_display=True)\n    #x_color = mono_to_color(x)\n    \n    plt.imshow(x, interpolation='nearest', aspect='auto')\n    plt.axis('off')\n    figure = plt.gcf()\n    figure.set_size_inches(4, 2)\n    plt.savefig(filename, bbox_inches='tight', pad_inches=0, dpi=100)\n    plt.show()\n    \n    plt.close()\n    del x\n    gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Loop over 10 files and convert them to images\nfor index, row in tqdm(train_fp_noise.iloc[:10].iterrows()):\n    # Get the Noise Interval\n    recording_id = row['recording_id']\n    t_min = row['t_min']\n    \n    # Load the train file\n    fn = '%s.flac' % (recording_id)\n    path = '../input/rfcx-species-audio-detection/train/' + fn\n    save_image_from_sound(path, t_min)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Future Work\n\n\nNow I have denoised and converted the audio into images, the next step is to train the CNNs. After this I will test the CNN on the test set, and consider how to (possibly) denoise the test set samples.\n\nInteresting Links:\n- https://www.tensorflow.org/tutorials/images/cnn\n- https://towardsdatascience.com/building-a-convolutional-neural-network-cnn-in-keras-329fbbadc5f5\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}