{"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":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# 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\n\ntrain_soundscape_files = []\nfor dirname, _, filenames in os.walk('/kaggle/input/birdclef-2021/train_soundscapes'):\n    for filename in filenames:\n        train_soundscape_files.append(filename)\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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-06-12T02:57:06.536052Z","iopub.execute_input":"2023-06-12T02:57:06.536625Z","iopub.status.idle":"2023-06-12T02:57:06.546218Z","shell.execute_reply.started":"2023-06-12T02:57:06.536579Z","shell.execute_reply":"2023-06-12T02:57:06.544757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import librosa\nimport librosa.display\nimport numpy as np\nfrom PIL import Image\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport csv\nfrom operator import length_hint","metadata":{"execution":{"iopub.status.busy":"2023-06-12T02:57:06.549071Z","iopub.execute_input":"2023-06-12T02:57:06.549544Z","iopub.status.idle":"2023-06-12T02:57:06.559153Z","shell.execute_reply.started":"2023-06-12T02:57:06.549502Z","shell.execute_reply":"2023-06-12T02:57:06.557897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_melspectrogram(audio_path, start_time, end_time, save_path):\n    # Load the audio file\n    audio, sr = librosa.load(audio_path, offset=start_time, duration=(end_time - start_time))\n\n    # Compute the Mel spectrogram\n    mel_spectrogram = librosa.feature.melspectrogram(y=audio, sr=sr)\n    mel_spectrogram_db = librosa.power_to_db(mel_spectrogram, ref=np.max)\n\n    # Normalize the spectrogram to the 0-255 range\n    mel_spectrogram_normalized = (mel_spectrogram_db - mel_spectrogram_db.min()) / (mel_spectrogram_db.max() - mel_spectrogram_db.min()) * 255\n    mel_spectrogram_normalized = mel_spectrogram_normalized.astype(np.uint8)\n\n    # Apply a colormap\n    colormap = cm.get_cmap('viridis')  # Choose a colormap (e.g., 'viridis', 'inferno', 'plasma', etc.)\n    mel_spectrogram_colored = colormap(mel_spectrogram_normalized)\n\n    # Convert the spectrogram to a PIL image\n    image = Image.fromarray((mel_spectrogram_colored[:, :, :3] * 255).astype(np.uint8))  # Keep only RGB channels\n\n    # Add colorbar\n    fig, ax = plt.subplots(figsize=(10, 4))\n    im = ax.imshow(mel_spectrogram_db, cmap='viridis', origin='lower')\n    norm = plt.Normalize(vmin=mel_spectrogram_db.min(), vmax=mel_spectrogram_db.max())\n    cmap = cm.get_cmap('viridis')\n    cb = fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax, format='%+2.0f dB')\n    \n    ax.set_xlabel('Time (s)')\n    ax.set_ylabel('Mel Frequencies (Hz)')\n    cb.set_label('Amplitude')\n    cb.ax.yaxis.set_label_position('left')\n    \n\n    # Save the image as a PNG file\n    plt.savefig(save_path, format='PNG')\n    plt.close()","metadata":{"execution":{"iopub.status.busy":"2023-06-12T02:57:06.561308Z","iopub.execute_input":"2023-06-12T02:57:06.562129Z","iopub.status.idle":"2023-06-12T02:57:06.574112Z","shell.execute_reply.started":"2023-06-12T02:57:06.56209Z","shell.execute_reply":"2023-06-12T02:57:06.573157Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"soundscapeCSV = '/kaggle/input/birdclef-2021/train_soundscape_labels.csv'\n\nwith open(soundscapeCSV, 'r') as inputFile:\n    soundscapeLabels = []\n    csvReader = csv.DictReader(inputFile)\n    for row in csvReader:\n        soundscapeLabels.append(dict(row))\n","metadata":{"execution":{"iopub.status.busy":"2023-06-12T02:57:06.57577Z","iopub.execute_input":"2023-06-12T02:57:06.576513Z","iopub.status.idle":"2023-06-12T02:57:06.606194Z","shell.execute_reply.started":"2023-06-12T02:57:06.576471Z","shell.execute_reply":"2023-06-12T02:57:06.604973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Example usage\nsoundscapesMelsDir = '/kaggle/working/train_soundscapes_mels'\nsoundscapesDir = '/kaggle/input/birdclef-2021/train_soundscapes'\n\n# os.makedirs(soundscapesMelsDir)\n\nfor row in soundscapeLabels:\n    for file in train_soundscape_files:\n        if row['audio_id'] in file:\n            audio_path = soundscapesDir + '/' + file\n            break\n    end_time = int(row['seconds']) \n    start_time = end_time - 5\n    save_path = soundscapesMelsDir + '/' + row['row_id'] + '.png'\n    create_melspectrogram(audio_path, start_time, end_time, save_path)","metadata":{"execution":{"iopub.status.busy":"2023-06-12T02:57:06.608635Z","iopub.execute_input":"2023-06-12T02:57:06.609346Z","iopub.status.idle":"2023-06-12T03:17:54.591464Z","shell.execute_reply.started":"2023-06-12T02:57:06.609309Z","shell.execute_reply":"2023-06-12T03:17:54.590398Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # Load the audio file\n# audio_path = '/kaggle/input/birdclef-2021/train_soundscapes/10534_SSW_20170429.ogg'\n# create_melspectrogram(audio_path, 0, 5, '/kaggle/working/test2.png')","metadata":{"execution":{"iopub.status.busy":"2023-06-12T03:17:54.592772Z","iopub.execute_input":"2023-06-12T03:17:54.5936Z","iopub.status.idle":"2023-06-12T03:17:54.598492Z","shell.execute_reply.started":"2023-06-12T03:17:54.593568Z","shell.execute_reply":"2023-06-12T03:17:54.597106Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(mel_spectrogram_db.min())","metadata":{"execution":{"iopub.status.busy":"2023-06-12T03:17:54.600267Z","iopub.execute_input":"2023-06-12T03:17:54.600726Z","iopub.status.idle":"2023-06-12T03:17:54.651421Z","shell.execute_reply.started":"2023-06-12T03:17:54.600693Z","shell.execute_reply":"2023-06-12T03:17:54.64975Z"},"trusted":true},"execution_count":null,"outputs":[]}]}