{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport glob\nimport librosa\nimport librosa.display\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom ipywidgets import interact\nfrom ipywidgets import widgets\nfrom IPython.display import display","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_files = glob.glob( '../input/rfcx-species-audio-detection/train/*.flac' )\ndf = pd.read_csv('/kaggle/input/rfcx-species-audio-detection/train_tp.csv')\n\nSR = 48000\nCLIP_LENGTH = 7 # number of seconds to clip around the sound\nSTART_TIME = 1 # start 2 seconds before t_min\nN_CLASS = 24\n\n# fft params\nN_FFT = 1024\nHOP_LEN = 512","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Helper Functions"},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_full_path(recording_id):\n    return f'../input/rfcx-species-audio-detection/train/{recording_id}.flac'\n\ndef pad_truncate_sequence(x, max_len):\n    if len(x) < max_len:\n        return np.concatenate((x, np.zeros(max_len - len(x)))) # pad back\n    else:\n        return x[0 : max_len]\n\ndef cut_audio(audio, t_min, start_time=START_TIME):\n    start = max(0, t_min - start_time)\n    end = start + CLIP_LENGTH\n    snippet = audio[int(start*SR):int(end*SR)]\n    if t_min - start_time < 0:\n        return t_min, pad_truncate_sequence(snippet, CLIP_LENGTH*SR)\n    else:\n        return START_TIME, pad_truncate_sequence(snippet, CLIP_LENGTH*SR)\n\ndef load_audio(recording_id):\n    audio, _ = librosa.core.load(get_full_path(recording_id), sr=SR, mono=True)\n    return audio\n\ndef create_spectrogram_from_row(row):\n    recording_id = row.recording_id\n    t_min = row.t_min\n    t_max = row.t_max\n    f_min = row.f_min\n    f_max = row.f_max\n    \n    audio = load_audio(recording_id)\n    start, audio = cut_audio(audio, t_min)\n    stft = librosa.stft(audio, n_fft=N_FFT, hop_length=HOP_LEN, win_length=N_FFT)\n    S_db = librosa.amplitude_to_db(np.abs(stft), ref=np.max)\n    fig, ax = plt.subplots(figsize=(10,10))\n    ax.set(title=f'spectrogram of {recording_id} from time {t_min} to {t_max}')\n    img = librosa.display.specshow(S_db, hop_length=HOP_LEN, sr=SR, x_axis='time', y_axis='linear')\n    ax.add_patch(\n        patches.Rectangle(xy=(start, f_min), width=t_max-t_min, height=f_max-f_min, ec='#00ff00', fill=False)\n    )\n    fig.colorbar(img, ax=ax)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_slider = widgets.IntSlider(min=0, max=df[df.species_id == 0].shape[0], value=0)\nspecies_dropdown = widgets.Dropdown(options=list(range(N_CLASS)), value=0)\n\ndef update_x_range(*args):\n    image_slider.max = df[df.species_id == int(species_dropdown.value)].shape[0]\nimage_slider.observe(update_x_range, 'value')\n\ndef view_image(image_idx, species_id):\n    sub_df = df[df.species_id == int(species_id)]\n    create_spectrogram_from_row(sub_df.iloc[image_idx])\n\ninteract(view_image,image_idx=image_slider, species_id=species_dropdown)","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}