{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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)\nimport seaborn as sns \nimport matplotlib.pyplot as plt\nimport plotly as pl\n\nimport plotly.graph_objects as go\n\nimport librosa\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\n# import os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n        \npd.set_option(\"display.max_rows\", 999, \"display.max_columns\", 999)\n\n# You can write up to 5GB 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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_file = pd.read_csv('/kaggle/input/birdsong-recognition/train.csv')\ntest_file = pd.read_csv('/kaggle/input/birdsong-recognition/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_file","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_file.info()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Lets Get the basic stats arounf the train dataset","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_file.nunique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_file.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x = train_file['ebird_code'].unique()\n\nprint(\"Total Birds in the data set: \", len(x))\n\nx","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Lets View the actual bird and dont forget to checkout the sound!","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import requests \n\nBird_name = input('Type the bird name: ')\nprint(Bird_name)\n\nlink = \"https://ebird.org/species/{0}#\".format(Bird_name)\nfrom IPython.display import IFrame\nIFrame(link, width=1000, height=700) ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Duration of the recording","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import plotly.express as px\nfig = px.histogram(train_file, x=\"duration\")\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Average Duration of recordings for each species","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = px.histogram(train_file, x=\"duration\", y=\"species\", histfunc= 'avg').update_yaxes(categoryorder=\"total descending\")\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Month of recording","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def dateprocessing(row):\n    year = row.split('-')[0]\n    month = row.split('-')[1]\n    date = row.split('-')[2]\n    return year, month, date","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#train_file = train_file['date'].apply(dateprocessing)\ntrain_file['year'],  train_file['month'], train_file['day'] = zip(*train_file['date'].apply(dateprocessing))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import plotly.express as px\nfig = px.histogram(train_file, x=\"month\")\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import plotly.express as px\nfig = px.histogram(train_file, x=\"day\")\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_file","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Pitch Distributed ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"pitch= train_file[\"pitch\"].value_counts().sort_values()\n\npitch.plot.barh()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"## Top 30 birds with low number of recordings\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"x = train_file['species'].value_counts()[train_file['species'].value_counts() < 100]\nfig = go.FigureWidget(data=go.Bar(y=x))\nfig","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_file[\"species\"].value_counts(ascending= True)[:30].sort_values()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Lets Load the audio data","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"44.1 kHz\nFor most music applications, \n44.1 kHz is the best sample rate to go for. 48 kHz is common when creating music or other audio for video. \nHigher sample rates can have advantages for professional music and audio production work, but many professionals work at 44.1 kHz.\n\nSource: Google","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# Get the ramdom files from the bird choosen","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import random \nimport os\n\n\npath ='/kaggle/input/birdsong-recognition/train_audio/{0}/'.format(Bird_name)\nfiles = os.listdir(path)\nindex = random.randrange(0, len(files))\nrndm_file = files[index]\n\n\ninput_audio = '/kaggle/input/birdsong-recognition/train_audio/{0}/{1}'.format(Bird_name,rndm_file)\ndata, sr = librosa.load(input_audio, sr = 44100) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Audio loaded: ', data, sr)\n\nprint('\\nlength of the numpy array,' , len(data))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#data = librosa.effects.trim(data)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plot audio over time","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"time = np.arange(0, len(data))/ sr\ntime","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import IPython.display as ipd\nipd.Audio(input_audio)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Audio Amplitude graph","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots()\nax.plot(time, data)\nax.set(xlabel='Time', ylabel = 'Amplitude')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Audio Waveplot","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import librosa.display\nplt.figure(figsize=(30, 4))\nlibrosa.display.waveplot(data, sr=sr)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Spectrum","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"X = librosa.stft(data,)\nXdb = librosa.amplitude_to_db(abs(X))\nplt.figure(figsize=(14, 5))\nlibrosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='hz')\nplt.colorbar()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(14, 5))\nlibrosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='log')\nplt.colorbar()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Get the Audio Features ","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"1. Spectral Centroid\n\nThe spectral centroid indicates at which frequency the energy of a spectrum is centered upon or in other words It indicates where the ” center of mass” for a sound is located. This is like a weighted mean:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import sklearn\nspectral_centroids = librosa.feature.spectral_centroid(data, sr=sr)[0]\nspectral_centroids.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12, 4))\nframes = range(len(spectral_centroids))\nt = librosa.frames_to_time(frames)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def normalize(x, axis=0):\n    return sklearn.preprocessing.minmax_scale(x, axis=axis)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12, 4))\nlibrosa.display.waveplot(data, sr=sr, alpha=0.4)\nplt.plot(t, normalize(spectral_centroids), color='b')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"#### This is work in Progress notebook. Please feel free to leave a comment/ upvote if you find anything useful. Thanks for reading","execution_count":null},{"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}