{"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)\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\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 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":"\n!pip install librosa -U --quiet\n!pip install torchaudio --quiet","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import warnings\nwarnings.simplefilter('ignore')\n\nimport os\nimport sys\nimport cv2\nimport glob\nimport math\nimport random\nimport librosa\nimport zipfile\nimport numpy as np\nimport pandas as pd\nfrom librosa import display as libdisplay\nfrom tqdm.notebook import tqdm\nfrom sklearn.model_selection import train_test_split, StratifiedKFold\nfrom sklearn.metrics import log_loss\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchaudio\nfrom torchaudio import transforms\nfrom torchvision import models\nfrom keras.utils import to_categorical\nimport IPython.display as ipd\nfrom matplotlib import pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import random\nimport numpy as np\nseed = 2020\n\nrandom.seed(seed)\nnp.random.seed(seed)\ntorch.manual_seed(seed)\n\nif torch.cuda.is_available(): \n    torch.cuda.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n#will store our models here\nos.makedirs('MODELS/', exist_ok=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Placeholder for the training and test spectogram's images\n#It is going to store the spec, we will shortly generate.\nos.makedirs('Imgs/Train/', exist_ok=True)\nos.makedirs('Imgs/Test/', exist_ok=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\ndef melspectogram_dB(file_path, cst=5, top_db=80.):\n  row_sound, sr = librosa.load(file_path)\n  sound = np.zeros((cst*sr,))\n\n  if row_sound.shape[0] < cst*sr:\n    sound[:row_sound.shape[0]] = row_sound[:]\n  else:\n    sound[:] = row_sound[:cst*sr]\n\n  spec = librosa.feature.melspectrogram(sound, sr)\n  spec_db = librosa.power_to_db(spec, top_db=top_db)\n\n  return spec_db\n\ndef spec_to_image(spec, eps=1e-6):\n  mean = spec.mean()\n  std = spec.std()\n  spec_norm = (spec - mean) / (std + eps)\n  spec_min, spec_max = spec_norm.min(), spec_norm.max()\n  spec_img = 255 * (spec_norm - spec_min) / (spec_max - spec_min)\n  \n  return spec_img.astype(np.uint8)\n\ndef save_spec_image(spec_img, fname):\n  cv2.imwrite(fname, spec_img)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/birdsong-recognition/train.csv')\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = pd.read_csv('../input/birdsong-recognition/sample_submission.csv')\nsub.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv('../input/birdsong-recognition/test.csv')\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\n# Add file names\ntrain['spec_name'] = '../input/output/Imgs/Train/'+str(train['filename'])+'.png'\nsub['spec_name'] = '../input/output/Imgs/Test/'+sub['row_id']+'.png'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#we will save just 5 rows to save time","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train=train.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Training specs\nfor row in tqdm(train.values):\n  sound_path = '../input/birdsong-recognition/train_audio/'+str(row[2])+'/'+str(row[7]) #this corresponds to 'file_name'\n  spec_name = row[-1] #this corresponds to 'spec_name'\n\n  spec = melspectogram_dB(sound_path, 15)\n  spec = spec_to_image(spec)\n  save_spec_image(spec, spec_name)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"spec","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(spec)","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}