{"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# !pip install resampy\n\nfrom matplotlib import pyplot as plt\nimport os\nimport json\nfrom pathlib import Path\nimport shutil\nfrom tqdm import tqdm\nimport pandas as pd\nimport re\nimport librosa\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n# from datetime import datetime, timedelta, date\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\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":"2023-04-03T19:01:13.443104Z","iopub.execute_input":"2023-04-03T19:01:13.443460Z","iopub.status.idle":"2023-04-03T19:01:13.451431Z","shell.execute_reply.started":"2023-04-03T19:01:13.443424Z","shell.execute_reply":"2023-04-03T19:01:13.450068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def normalize_db(db, max_db, min_db):\n    \"\"\"\n    Normalize dB-scaled spectrogram values to be in range of 0~1.\n    :param db: Decibel-scaled spectrogram.\n    :param max_db: Maximum dB.\n    :param min_db: Minimum dB.\n    :return: Normalized spectrogram.\n    \"\"\"\n    norm_db = np.clip((db - min_db) / (max_db - min_db), 0, 1)\n    return norm_db\n\ndef features_extractor(file_name):\n    audio, sample_rate = librosa.load(file_name) \n    mfccs_features = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=40)\n    mfccs_scaled_features = np.mean(mfccs_features.T,axis=0)\n    \n    return mfccs_scaled_features, sample_rate\n\ndef features_stft_extractor(file_path, window_length, hop_length, time_first=True):\n    y, sr = librosa.load(file_path, sr=22050)  # Load audio file with sampling rate of 44100\n    stft = np.abs(librosa.stft(y,  n_fft=window_length, hop_length=hop_length))  # Compute STFT\n    features = np.array([])\n    for i in range(stft.shape[1]):\n        feature = np.mean(stft[:, i])\n        features = np.append(features, feature)\n    return features","metadata":{"execution":{"iopub.status.busy":"2023-04-03T19:01:13.453637Z","iopub.execute_input":"2023-04-03T19:01:13.454522Z","iopub.status.idle":"2023-04-03T19:01:13.472822Z","shell.execute_reply.started":"2023-04-03T19:01:13.454480Z","shell.execute_reply":"2023-04-03T19:01:13.471262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"src_folder = Path(\"/kaggle/input/birdclef-2023/train_audio\")\ndf_train_metadata = pd.read_csv('/kaggle/input/birdclef-2023/train_metadata.csv', encoding='utf-8')\n\nresults = pd.DataFrame([], columns=[])\n\nfor index, row in tqdm(df_train_metadata.iterrows()):\n    filename = row[\"filename\"]\n    features, sample_rate = features_extractor(os.path.join(src_folder, filename))\n\n    data = {\n        \"class\": row[\"primary_label\"],\n        \"filename\": filename,\n        \"sample_rate\": sample_rate,\n        \"mel_feature_shape\" : len(features),\n    }\n    for i, name in enumerate(features):\n        data[\"mf_{}\".format(i)] = name\n\n    results = pd.concat([results, pd.DataFrame.from_records([data])], ignore_index = True)\n\nprint(results.shape)\nresults.to_csv(\"audio_mfcc_train.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2023-04-03T19:01:13.475519Z","iopub.execute_input":"2023-04-03T19:01:13.475895Z","iopub.status.idle":"2023-04-03T19:01:20.409178Z","shell.execute_reply.started":"2023-04-03T19:01:13.475857Z","shell.execute_reply":"2023-04-03T19:01:20.407455Z"},"trusted":true},"execution_count":null,"outputs":[]}]}