{"cells":[{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"!pip uninstall fastai torch torchaudio fastcore torchvision -y ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"!pip install ../input/packages/packages/packages/colorednoise-1.1.1/colorednoise-1.1.1 --find-links ../input/packages/packages --no-index --use-feature=2020-resolver","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"!pip install ../input/packages/fastaudio-0.0.post0.dev143gc7a2b85.dirty-py2.py3-none-any.whl --find-links ../input/packages/packages/packages --no-index --verbose --upgrade --use-feature=2020-resolver","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport matplotlib.image as mpimg\nfrom matplotlib.offsetbox import AnnotationBbox, OffsetImage\n\n# Map 1 library\nimport plotly.express as px\n\n# Map 2 libraries\nimport descartes\nimport geopandas as gpd\nfrom shapely.geometry import Point, Polygon\n\n# Librosa Libraries\nimport librosa\nimport librosa.display\nimport IPython.display as ipd\n\nimport sklearn\n\nimport warnings\nwarnings.filterwarnings('ignore')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import soundfile as sf","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### resample all audio files to 32 khz"},{"metadata":{"trusted":true},"cell_type":"code","source":"#import ffmpy","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#new_path = Path(\"data/train_audio_resample\")\n#old_path = Path(\"data/train_audio\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#new_path.mkdir()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#for subfolder in old_path.ls():\n#    Path(str(subfolder).replace(\"/train_audio/\", \"/train_audio_resample/\")).mkdir()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#audio_files = get_files(old_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#from fastprogress import progress_bar","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#for file in progress_bar(audio_files):\n#    new_file = Path(str(file).replace(\"/train_audio/\", \"/train_audio_resample/\").replace(\".mp3\", \".wav\"))\n#    new_file.parent.mkdir(exist_ok=True)\n#    ff = ffmpy.FFmpeg(inputs={str(file):None}, outputs={str(new_file): \"-ar 32000 -ac 1\"})\n#    ff.run()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#resampled_audio_files = get_files(new_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#len(resampled_audio_files)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#len(audio_files)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Import data\ntrain_csv = pd.read_csv(\"../input/birdsong-recognition/train.csv\")\ntest_csv = pd.read_csv(\"../input/birdsong-recognition/test.csv\")\n\n# Create some time features\ntrain_csv['year'] = train_csv['date'].apply(lambda x: x.split('-')[0])\ntrain_csv['month'] = train_csv['date'].apply(lambda x: x.split('-')[1])\ntrain_csv['day_of_month'] = train_csv['date'].apply(lambda x: x.split('-')[2])\n\nprint(\"There are {:,} unique bird species in the dataset.\".format(len(train_csv['species'].unique())))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_csv[\"file_path\"] = train_csv[[\"ebird_code\", \"filename\"]].agg(\"/\".join, axis=1)\ntrain_csv[\"file_path\"] = train_csv[\"file_path\"]#.apply(lambda x: x.split(\".\")[0] + \".wav\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from fastai.vision.all import *\nfrom fastaudio.core.all import *\nfrom fastaudio.augment.all import *","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cfg = AudioConfig.BasicMelSpectrogram(n_fft=512)\na2s = AudioToSpec.from_cfg(cfg)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path = Path(\"../input/birdsong-resampled-train-audio-00/\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_csv['file_path'] = train_csv['file_path'].str.replace('.mp3','.wav')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dataset_mapping = {\n    'a': Path('../input/birdsong-resampled-train-audio-00'),\n    'b': Path('../input/birdsong-resampled-train-audio-00'),\n    'c': Path('../input/birdsong-resampled-train-audio-01'),\n    'd': Path('../input/birdsong-resampled-train-audio-01'),\n    'e': Path('../input/birdsong-resampled-train-audio-01'),\n    'f': Path('../input/birdsong-resampled-train-audio-01'),\n    'g': Path('../input/birdsong-resampled-train-audio-02'),\n    'h': Path('../input/birdsong-resampled-train-audio-02'),\n    'i': Path('../input/birdsong-resampled-train-audio-02'),\n    'j': Path('../input/birdsong-resampled-train-audio-02'),\n    'k': Path('../input/birdsong-resampled-train-audio-02'),\n    'l': Path('../input/birdsong-resampled-train-audio-02'),\n    'm': Path('../input/birdsong-resampled-train-audio-02'),\n    'n': Path('../input/birdsong-resampled-train-audio-03'),\n    'o': Path('../input/birdsong-resampled-train-audio-03'),\n    'p': Path('../input/birdsong-resampled-train-audio-03'),\n    'q': Path('../input/birdsong-resampled-train-audio-03'),\n    'r': Path('../input/birdsong-resampled-train-audio-03'),\n    's': Path('../input/birdsong-resampled-train-audio-04'),\n    't': Path('../input/birdsong-resampled-train-audio-04'),\n    'u': Path('../input/birdsong-resampled-train-audio-04'),\n    'v': Path('../input/birdsong-resampled-train-audio-04'),\n    'w': Path('../input/birdsong-resampled-train-audio-04'),\n    'x': Path('../input/birdsong-resampled-train-audio-04'),\n    'y': Path('../input/birdsong-resampled-train-audio-04'),\n}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"BIRD_CODE = {\n    'aldfly': 0, 'ameavo': 1, 'amebit': 2, 'amecro': 3, 'amegfi': 4,\n    'amekes': 5, 'amepip': 6, 'amered': 7, 'amerob': 8, 'amewig': 9,\n    'amewoo': 10, 'amtspa': 11, 'annhum': 12, 'astfly': 13, 'baisan': 14,\n    'baleag': 15, 'balori': 16, 'banswa': 17, 'barswa': 18, 'bawwar': 19,\n    'belkin1': 20, 'belspa2': 21, 'bewwre': 22, 'bkbcuc': 23, 'bkbmag1': 24,\n    'bkbwar': 25, 'bkcchi': 26, 'bkchum': 27, 'bkhgro': 28, 'bkpwar': 29,\n    'bktspa': 30, 'blkpho': 31, 'blugrb1': 32, 'blujay': 33, 'bnhcow': 34,\n    'boboli': 35, 'bongul': 36, 'brdowl': 37, 'brebla': 38, 'brespa': 39,\n    'brncre': 40, 'brnthr': 41, 'brthum': 42, 'brwhaw': 43, 'btbwar': 44,\n    'btnwar': 45, 'btywar': 46, 'buffle': 47, 'buggna': 48, 'buhvir': 49,\n    'bulori': 50, 'bushti': 51, 'buwtea': 52, 'buwwar': 53, 'cacwre': 54,\n    'calgul': 55, 'calqua': 56, 'camwar': 57, 'cangoo': 58, 'canwar': 59,\n    'canwre': 60, 'carwre': 61, 'casfin': 62, 'caster1': 63, 'casvir': 64,\n    'cedwax': 65, 'chispa': 66, 'chiswi': 67, 'chswar': 68, 'chukar': 69,\n    'clanut': 70, 'cliswa': 71, 'comgol': 72, 'comgra': 73, 'comloo': 74,\n    'commer': 75, 'comnig': 76, 'comrav': 77, 'comred': 78, 'comter': 79,\n    'comyel': 80, 'coohaw': 81, 'coshum': 82, 'cowscj1': 83, 'daejun': 84,\n    'doccor': 85, 'dowwoo': 86, 'dusfly': 87, 'eargre': 88, 'easblu': 89,\n    'easkin': 90, 'easmea': 91, 'easpho': 92, 'eastow': 93, 'eawpew': 94,\n    'eucdov': 95, 'eursta': 96, 'evegro': 97, 'fiespa': 98, 'fiscro': 99,\n    'foxspa': 100, 'gadwal': 101, 'gcrfin': 102, 'gnttow': 103, 'gnwtea': 104,\n    'gockin': 105, 'gocspa': 106, 'goleag': 107, 'grbher3': 108, 'grcfly': 109,\n    'greegr': 110, 'greroa': 111, 'greyel': 112, 'grhowl': 113, 'grnher': 114,\n    'grtgra': 115, 'grycat': 116, 'gryfly': 117, 'haiwoo': 118, 'hamfly': 119,\n    'hergul': 120, 'herthr': 121, 'hoomer': 122, 'hoowar': 123, 'horgre': 124,\n    'horlar': 125, 'houfin': 126, 'houspa': 127, 'houwre': 128, 'indbun': 129,\n    'juntit1': 130, 'killde': 131, 'labwoo': 132, 'larspa': 133, 'lazbun': 134,\n    'leabit': 135, 'leafly': 136, 'leasan': 137, 'lecthr': 138, 'lesgol': 139,\n    'lesnig': 140, 'lesyel': 141, 'lewwoo': 142, 'linspa': 143, 'lobcur': 144,\n    'lobdow': 145, 'logshr': 146, 'lotduc': 147, 'louwat': 148, 'macwar': 149,\n    'magwar': 150, 'mallar3': 151, 'marwre': 152, 'merlin': 153, 'moublu': 154,\n    'mouchi': 155, 'moudov': 156, 'norcar': 157, 'norfli': 158, 'norhar2': 159,\n    'normoc': 160, 'norpar': 161, 'norpin': 162, 'norsho': 163, 'norwat': 164,\n    'nrwswa': 165, 'nutwoo': 166, 'olsfly': 167, 'orcwar': 168, 'osprey': 169,\n    'ovenbi1': 170, 'palwar': 171, 'pasfly': 172, 'pecsan': 173, 'perfal': 174,\n    'phaino': 175, 'pibgre': 176, 'pilwoo': 177, 'pingro': 178, 'pinjay': 179,\n    'pinsis': 180, 'pinwar': 181, 'plsvir': 182, 'prawar': 183, 'purfin': 184,\n    'pygnut': 185, 'rebmer': 186, 'rebnut': 187, 'rebsap': 188, 'rebwoo': 189,\n    'redcro': 190, 'redhea': 191, 'reevir1': 192, 'renpha': 193, 'reshaw': 194,\n    'rethaw': 195, 'rewbla': 196, 'ribgul': 197, 'rinduc': 198, 'robgro': 199,\n    'rocpig': 200, 'rocwre': 201, 'rthhum': 202, 'ruckin': 203, 'rudduc': 204,\n    'rufgro': 205, 'rufhum': 206, 'rusbla': 207, 'sagspa1': 208, 'sagthr': 209,\n    'savspa': 210, 'saypho': 211, 'scatan': 212, 'scoori': 213, 'semplo': 214,\n    'semsan': 215, 'sheowl': 216, 'shshaw': 217, 'snobun': 218, 'snogoo': 219,\n    'solsan': 220, 'sonspa': 221, 'sora': 222, 'sposan': 223, 'spotow': 224,\n    'stejay': 225, 'swahaw': 226, 'swaspa': 227, 'swathr': 228, 'treswa': 229,\n    'truswa': 230, 'tuftit': 231, 'tunswa': 232, 'veery': 233, 'vesspa': 234,\n    'vigswa': 235, 'warvir': 236, 'wesblu': 237, 'wesgre': 238, 'weskin': 239,\n    'wesmea': 240, 'wessan': 241, 'westan': 242, 'wewpew': 243, 'whbnut': 244,\n    'whcspa': 245, 'whfibi': 246, 'whtspa': 247, 'whtswi': 248, 'wilfly': 249,\n    'wilsni1': 250, 'wiltur': 251, 'winwre3': 252, 'wlswar': 253, 'wooduc': 254,\n    'wooscj2': 255, 'woothr': 256, 'y00475': 257, 'yebfly': 258, 'yebsap': 259,\n    'yehbla': 260, 'yelwar': 261, 'yerwar': 262, 'yetvir': 263\n}\n\nINV_BIRD_CODE = {v: k for k, v in BIRD_CODE.items()}\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_x(x):\n    fp = x['file_path']\n    path = dataset_mapping[fp[0]]\n    return path/fp","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"birds = L(BIRD_CODE.keys())[:20]\nbird_code = {k:BIRD_CODE[k] for k in birds}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"subset = train_csv['ebird_code'].map(lambda x: x in birds)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_y(x): \n    return [x['ebird_code']]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"auds = DataBlock(blocks=(AudioBlock(sample_rate=32000,crop_signal_to=5000), MultiCategoryBlock(vocab=BIRD_CODE)),  \n                 get_x=get_x,\n                 item_tfms=[AddNoise(color=NoiseColor.Pink)],\n                 batch_tfms = [AddNoise(noise_level=0.1),ChangeVolume(),a2s],\n#                  batch_tfms = [a2s],\n                 get_y=get_y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Path('/kaggle/input/birdsong-resampled-train-audio-04/snobun/')\nPath('kaggle/input/birdsong-resampled-train-audio-04/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dbunch = auds.dataloaders(train_csv, bs=64)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dbunch.show_batch(figsize=(10, 5),max_n=10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn = cnn_learner(dbunch, \n            xresnet50, \n            config=cnn_config(n_in=1), #<- Only audio specific modification here\n            metrics=[F1ScoreMulti(thresh=0.5)])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# learn.lr_find()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fine_tune(20,freeze_epochs=3, base_lr=4e-2, pct_start=0.3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.export()","execution_count":null,"outputs":[]},{"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}