{"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\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport numpy as np # linear algebra\nimport scipy.io.wavfile\nimport os\nimport librosa as lb\nimport librosa.display\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense , Dropout , Activation , Flatten , Conv1D, Conv2D , MaxPooling1D, MaxPooling2D , ZeroPadding2D ,MaxPool1D\nfrom matplotlib import pyplot as plt\nfrom IPython.display import Audio\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.regularizers import l2\n\nimport os\n#for 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 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":"2021-10-02T21:54:46.645794Z","iopub.execute_input":"2021-10-02T21:54:46.646478Z","iopub.status.idle":"2021-10-02T21:54:54.226717Z","shell.execute_reply.started":"2021-10-02T21:54:46.646354Z","shell.execute_reply":"2021-10-02T21:54:54.225426Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndef melspectrogram_saving(df,start,dur,filepath,folder):\n    try:\n        \n        fig = plt.figure(figsize=[2.7,2.7])\n        filename = filepath.split('/')[-1].split('.')[0]\n        data, sr = librosa.load(filepath, sr=None, offset=start, duration=dur) \n        S = librosa.feature.melspectrogram(y=data, sr=sr)\n        librosa.display.specshow(librosa.power_to_db(S, ref=np.max))\n        if not os.path.exists(folder):\n            os.makedirs(folder )\n        plt.savefig((folder +filename +'.jpg'), bbox_inches='tight',pad_inches=0, facecolor='black')\n        print(len(S))\n        print(len(S[0]))\n        print(len(S[0][0]))\n        fig.clear()          \n        plt.close(fig)\n        plt.close()\n        plt.close('all')\n        plt.cla()\n        fig.clf()\n        plt.clf()\n        plt.close()\n    except:\n        print(\"error in audio file .\")      ","metadata":{"execution":{"iopub.status.busy":"2021-10-02T22:26:24.744777Z","iopub.execute_input":"2021-10-02T22:26:24.746554Z","iopub.status.idle":"2021-10-02T22:26:24.767001Z","shell.execute_reply.started":"2021-10-02T22:26:24.746447Z","shell.execute_reply":"2021-10-02T22:26:24.76574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_new='/kaggle/working/mels/train/' #new folder for saving training melspectrogram images\ntest_new='/kaggle/working/mels/test/'\nexample_new = '/kaggle/working/mels/exa_test/'\ntrain_dir = '../input/birdsong-recognition/train_audio/'#training data folder\ntrain_csv_dir = '../input/birdsong-recognition/train.csv'#csv folder\ntest_dir = '../input/birdsong-recognition/test_audio/'\ntest_csv_dir = '../input/birdsong-recognition/test.csv'\nexampletest_dir = '../input/birdsong-recognition/example_test_audio/'\nexampletest_csv_dir = '../input/birdsong-recognition/example_test_audio_summary.csv'\ntrain_df = pd.read_csv(train_csv_dir)\ntest_df = pd.read_csv(test_csv_dir)\nexampletest_df = pd.read_csv(exampletest_csv_dir)\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n#for x in train_df.values:\n    #x[2] is class (bird type)\n    #x[7] is filename\n    #x[6] is duration\n #   melspectrogram_saving(x, 0, x[6],filepath=(train_dir +x[2] +'/' +x[7]), folder=train_new)\nos.listdir(test_dir)\nfor x in test_df.values:\n    print(x[0])\n    if x[0]=='site_3' :\n   #     du=None\n  #      if(x[6]>25):\n #           du=25\n        melspectrogram_saving(x, 0, dur= None, filepath=(test_dir + x[3] +'.mp3'), folder=test_new)\n    else :\n        start = x[2] - 5\n        melspectrogram_saving(x, start=start, dur= 5, filepath=(test_dir + x[3] +'.mp3'), folder=test_new)\n        \nfor x in exampletest_df.values:\n    if pd.isna(x[1])==False :\n        start = x[3] - 5\n        melspectrogram_saving(x, start=start, dur= 5, filepath=exampletest_dir, folder=example_new)","metadata":{"execution":{"iopub.status.busy":"2021-10-02T22:33:09.634667Z","iopub.execute_input":"2021-10-02T22:33:09.635154Z","iopub.status.idle":"2021-10-02T22:33:10.537885Z","shell.execute_reply.started":"2021-10-02T22:33:09.635111Z","shell.execute_reply":"2021-10-02T22:33:10.535963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\n\nshutil.make_archive('train_compressed', 'zip', '/kaggle/working/mels')","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}