{"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":"markdown","source":"# Install Libraries 🛠","metadata":{"papermill":{"duration":0.062037,"end_time":"2022-03-08T03:15:20.082763","exception":false,"start_time":"2022-03-08T03:15:20.020726","status":"completed"},"tags":[]}},{"cell_type":"code","source":"import sys, os\nsys.path.append('/kaggle/input/efficientnet-keras-dataset/efficientnet_kaggle')\n!pip install -q /kaggle/input/tensorflow-extra-lib-ds/tensorflow_extra-1.0.2-py3-none-any.whl --no-deps","metadata":{"execution":{"iopub.status.busy":"2023-03-18T17:27:29.665218Z","iopub.execute_input":"2023-03-18T17:27:29.66564Z","iopub.status.idle":"2023-03-18T17:27:52.48405Z","shell.execute_reply.started":"2023-03-18T17:27:29.665601Z","shell.execute_reply":"2023-03-18T17:27:52.482583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Import Libraries 📚","metadata":{"papermill":{"duration":0.065343,"end_time":"2022-03-08T03:18:11.885586","exception":false,"start_time":"2022-03-08T03:18:11.820243","status":"completed"},"tags":[]}},{"cell_type":"code","source":"import tensorflow as tf\ntf.get_logger().setLevel('ERROR')\ntf.autograph.set_verbosity(0)\nimport os\nimport pandas as pd\nimport numpy as np\nimport random\nfrom glob import glob\nfrom tqdm import tqdm\ntqdm.pandas()\nimport gc\nimport librosa\nimport sklearn\nimport time\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport librosa.display as lid\nimport IPython.display as ipd\n\nimport tensorflow as tf\ntf.config.optimizer.set_jit(True) # enable xla for speed up\nimport tensorflow_io as tfio\nimport tensorflow.keras.backend as K\n\nimport efficientnet.tfkeras as efn\nimport tensorflow_extra as tfe","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","papermill":{"duration":2.632068,"end_time":"2022-03-08T03:18:14.585094","exception":false,"start_time":"2022-03-08T03:18:11.953026","status":"completed"},"tags":[],"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-03-18T17:27:52.489131Z","iopub.execute_input":"2023-03-18T17:27:52.489531Z","iopub.status.idle":"2023-03-18T17:28:03.569845Z","shell.execute_reply.started":"2023-03-18T17:27:52.48948Z","shell.execute_reply":"2023-03-18T17:28:03.568492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Configuration ⚙️","metadata":{"papermill":{"duration":0.066353,"end_time":"2022-03-08T03:18:18.099835","exception":false,"start_time":"2022-03-08T03:18:18.033482","status":"completed"},"tags":[]}},{"cell_type":"code","source":"class CFG:\n    debug = False\n    verbose = 0\n    \n    device = 'CPU'\n    seed = 41 #42\n    \n    # Input image size and batch size\n    img_size = [128, 384]\n    batch_size = 16\n    infer_bs = 2\n    tta = 1\n    drop_remainder = True\n    \n    # STFT parameters\n    duration = 5 # duration for test\n    train_duration = 10\n    sample_rate = 32000\n    downsample = 1\n    audio_len = duration*sample_rate\n    nfft = 2028\n    window = 2048\n    hop_length = train_duration*32000 // (img_size[1] - 1)\n    fmin = 20\n    fmax = 16000\n    normalize = True\n\n    # Data Preprocessing Settings\n    class_names = sorted(os.listdir('/kaggle/input/birdclef-2023/train_audio/'))\n    num_classes = len(class_names)\n    class_labels = list(range(num_classes))\n    label2name = dict(zip(class_labels, class_names))\n    name2label = {v:k for k,v in label2name.items()}\n    \n    target_col = ['target']\n    tab_cols = ['filename','common_name','rate']","metadata":{"papermill":{"duration":0.156464,"end_time":"2022-03-08T03:18:18.322809","exception":false,"start_time":"2022-03-08T03:18:18.166345","status":"completed"},"tags":[],"_kg_hide-input":false,"execution":{"iopub.status.busy":"2023-03-18T17:28:03.584694Z","iopub.execute_input":"2023-03-18T17:28:03.585434Z","iopub.status.idle":"2023-03-18T17:28:03.62018Z","shell.execute_reply.started":"2023-03-18T17:28:03.585395Z","shell.execute_reply":"2023-03-18T17:28:03.619085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.keras.utils.set_random_seed(CFG.seed)","metadata":{"papermill":{"duration":0.153451,"end_time":"2022-03-08T03:18:18.685056","exception":false,"start_time":"2022-03-08T03:18:18.531605","status":"completed"},"tags":[],"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-03-18T17:28:03.621449Z","iopub.execute_input":"2023-03-18T17:28:03.621779Z","iopub.status.idle":"2023-03-18T17:28:03.626466Z","shell.execute_reply.started":"2023-03-18T17:28:03.621748Z","shell.execute_reply":"2023-03-18T17:28:03.625564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_device():\n    \"Detect and intializes GPU/TPU automatically\"\n    # Check TPU category\n    tpu = 'local' if CFG.device=='TPU-VM' else None\n    try:\n        # Connect to TPU\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect(tpu=tpu) \n        # Set TPU strategy\n        strategy = tf.distribute.TPUStrategy(tpu)\n        print(f'> Running on {CFG.device} ', tpu.master(), end=' | ')\n        print('Num of TPUs: ', strategy.num_replicas_in_sync)\n        device=CFG.device\n    except:\n        # If TPU is not available, detect GPUs\n        gpus = tf.config.list_logical_devices('GPU')\n        ngpu = len(gpus)\n         # Check number of GPUs\n        if ngpu:\n            # Set GPU strategy\n            strategy = tf.distribute.MirroredStrategy(gpus) # single-GPU or multi-GPU\n            # Print GPU details\n            print(\"> Running on GPU\", end=' | ')\n            print(\"Num of GPUs: \", ngpu)\n            device='GPU'\n        else:\n            # If no GPUs are available, use CPU\n            print(\"> Running on CPU\")\n            strategy = tf.distribute.get_strategy()\n            device='CPU'\n    return strategy, device, tpu","metadata":{"_kg_hide-input":true,"papermill":{"duration":7.941725,"end_time":"2022-03-08T03:18:26.826553","exception":false,"start_time":"2022-03-08T03:18:18.884828","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-03-18T17:28:03.627736Z","iopub.execute_input":"2023-03-18T17:28:03.628881Z","iopub.status.idle":"2023-03-18T17:28:03.63909Z","shell.execute_reply.started":"2023-03-18T17:28:03.62884Z","shell.execute_reply":"2023-03-18T17:28:03.637962Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Initialize GPU/TPU/TPU-VM\nstrategy, CFG.device, tpu = get_device()\nCFG.replicas = strategy.num_replicas_in_sync","metadata":{"execution":{"iopub.status.busy":"2023-03-18T17:28:03.640601Z","iopub.execute_input":"2023-03-18T17:28:03.641055Z","iopub.status.idle":"2023-03-18T17:28:03.675269Z","shell.execute_reply.started":"2023-03-18T17:28:03.641008Z","shell.execute_reply":"2023-03-18T17:28:03.673863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BASE_PATH = '/kaggle/input/birdclef-2023'\nGCS_PATH = BASE_PATH","metadata":{"execution":{"iopub.status.busy":"2023-03-18T17:28:03.676934Z","iopub.execute_input":"2023-03-18T17:28:03.677278Z","iopub.status.idle":"2023-03-18T17:28:03.683029Z","shell.execute_reply.started":"2023-03-18T17:28:03.677246Z","shell.execute_reply":"2023-03-18T17:28:03.681577Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_paths = glob('/kaggle/input/birdclef-2023/test_soundscapes/*ogg')\ntest_df = pd.DataFrame(test_paths, columns=['filepath'])\ntest_df['filename'] = test_df.filepath.map(lambda x: x.split('/')[-1].replace('.ogg',''))\ntest_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-03-18T17:28:03.68495Z","iopub.execute_input":"2023-03-18T17:28:03.685703Z","iopub.status.idle":"2023-03-18T17:28:03.71941Z","shell.execute_reply.started":"2023-03-18T17:28:03.685653Z","shell.execute_reply":"2023-03-18T17:28:03.718561Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.io.gfile.exists(test_df.filepath.iloc[0])","metadata":{"papermill":{"duration":0.244976,"end_time":"2022-03-08T03:18:33.994955","exception":false,"start_time":"2022-03-08T03:18:33.749979","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-03-18T17:28:03.722421Z","iopub.execute_input":"2023-03-18T17:28:03.72299Z","iopub.status.idle":"2023-03-18T17:28:03.730038Z","shell.execute_reply.started":"2023-03-18T17:28:03.722955Z","shell.execute_reply":"2023-03-18T17:28:03.728768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_audio(filepath, sr=32000, normalize=True):\n    audio, orig_sr = librosa.load(filepath, sr=None)\n    if sr!=orig_sr:\n        audio = librosa.resample(y, orig_sr, sr)\n    audio = audio.astype('float32').ravel()\n    audio = tf.convert_to_tensor(audio)\n    return audio\n\n@tf.function(jit_compile=True)\ndef MakeFrame(audio, duration=5, sr=32000):\n    frame_length = int(duration * sr)\n    frame_step = int(duration * sr)\n    chunks = tf.signal.frame(audio, frame_length, frame_step, pad_end=True)\n    return chunks","metadata":{"_kg_hide-input":true,"papermill":{"duration":0.251393,"end_time":"2022-03-08T03:18:36.833376","exception":false,"start_time":"2022-03-08T03:18:36.581983","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-03-18T17:28:03.731759Z","iopub.execute_input":"2023-03-18T17:28:03.732289Z","iopub.status.idle":"2023-03-18T17:28:03.742874Z","shell.execute_reply.started":"2023-03-18T17:28:03.732242Z","shell.execute_reply":"2023-03-18T17:28:03.741725Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# EDA 🎨","metadata":{"papermill":{"duration":0.091062,"end_time":"2022-03-08T03:18:37.019504","exception":false,"start_time":"2022-03-08T03:18:36.928442","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"## Utility","metadata":{}},{"cell_type":"code","source":"def display_audio(row):\n    # Caption for viz\n    caption = f'Id: {row.filename}'\n    # Read audio file\n    audio = load_audio(row.filepath)\n    # Keep fixed length audio\n    audio = audio[:CFG.audio_len]\n    # Display audio\n    print(\"# Audio:\")\n    display(ipd.Audio(audio.numpy(), rate=CFG.sample_rate))\n    print('# Visualization:')\n    plt.figure(figsize=(12, 3))\n    plt.title(caption)\n    # Waveplot\n    lid.waveshow(audio.numpy(),\n                 sr=CFG.sample_rate,)\n                 \n    plt.xlabel('');\n    plt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-03-18T17:28:03.745105Z","iopub.execute_input":"2023-03-18T17:28:03.745633Z","iopub.status.idle":"2023-03-18T17:28:03.757021Z","shell.execute_reply.started":"2023-03-18T17:28:03.745583Z","shell.execute_reply":"2023-03-18T17:28:03.755949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Check","metadata":{}},{"cell_type":"code","source":"display_audio(test_df.iloc[0])","metadata":{"execution":{"iopub.status.busy":"2023-03-18T17:28:03.75872Z","iopub.execute_input":"2023-03-18T17:28:03.759131Z","iopub.status.idle":"2023-03-18T17:28:16.816782Z","shell.execute_reply.started":"2023-03-18T17:28:03.759085Z","shell.execute_reply":"2023-03-18T17:28:16.815427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Inference Configs 🔧","metadata":{}},{"cell_type":"code","source":"# Directory of checkpoint\nCKPT_DIR = '/kaggle/input/birdclef23-pretraining-is-all-you-need-train-ds'\n# Get file paths of all trained models in the directory\nCKPT_PATHS = sorted([x for x in glob(f'{CKPT_DIR}/fold-*h5')])\nprint(\"Checkpoints: \", CKPT_PATHS)\n# Load all the models in memory to speed up\nCKPTS = [tf.keras.models.load_model(x, compile=False) for x in tqdm(CKPT_PATHS, desc=\"Loading ckpts \")]\n# Num of ckpt to use\nNUM_CKPTS = 1\n\n# Submit or Interactive mode\nSUBMIT = pd.read_csv('/kaggle/input/birdclef-2023/sample_submission.csv').shape[0] != 3","metadata":{"execution":{"iopub.status.busy":"2023-03-18T17:32:27.80418Z","iopub.execute_input":"2023-03-18T17:32:27.80521Z","iopub.status.idle":"2023-03-18T17:32:32.239775Z","shell.execute_reply.started":"2023-03-18T17:32:27.805163Z","shell.execute_reply":"2023-03-18T17:32:32.238583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Inference 🧪","metadata":{"papermill":{"duration":0.151237,"end_time":"2022-03-08T03:18:47.959873","exception":false,"start_time":"2022-03-08T03:18:47.808636","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# Start stopwatch\ntick = time.time()\n\n# Initialize empty list to store ids\nids = []\n# Initialize empty array to store predictions\npreds = np.empty(shape=(0, 264), dtype='float32')\n\n# Iterate over each audio file in the test dataset\nfor filepath in tqdm(test_df.filepath.tolist(), 'test '):\n    # Extract the filename without the extension\n    filename = filepath.split('/')[-1].replace('.ogg','')\n    \n    # Load audio from file and create audio frames, each recording will be a batch input\n    audio = load_audio(filepath)\n    chunks = MakeFrame(audio)\n    \n    # Predict bird species for all frames in a recording using all trained models\n    chunk_preds = np.zeros(shape=(len(chunks), 264), dtype=np.float32)\n    for model in CKPTS[:NUM_CKPTS]:\n        # Get the model's predictions for the current audio frames\n        rec_preds = model(chunks, training=False).numpy()\n        # Ensemble all prediction with average\n        chunk_preds += rec_preds/len(CKPTS)\n    \n    # Create a ID for each frame in a recording using the filename and frame number\n    rec_ids = [f'{filename}_{(frame_id+1)*5}' for frame_id in range(len(chunks))]\n    \n    # Concatenate the ids\n    ids += rec_ids\n    # Concatenate the predictions\n    preds = np.concatenate([preds, chunk_preds], axis=0)\n    \n# Stop stopwatch\ntock = time.time()","metadata":{"execution":{"iopub.status.busy":"2023-03-18T17:32:35.135629Z","iopub.execute_input":"2023-03-18T17:32:35.136027Z","iopub.status.idle":"2023-03-18T17:33:05.851578Z","shell.execute_reply.started":"2023-03-18T17:32:35.135993Z","shell.execute_reply":"2023-03-18T17:33:05.850703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission 📮","metadata":{}},{"cell_type":"code","source":"# Submit prediction\npred_df = pd.DataFrame(ids, columns=['row_id'])\npred_df.loc[:, CFG.class_names] = preds\npred_df.to_csv('submission.csv',index=False)\npred_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-03-18T17:29:00.095867Z","iopub.execute_input":"2023-03-18T17:29:00.096436Z","iopub.status.idle":"2023-03-18T17:29:00.227741Z","shell.execute_reply.started":"2023-03-18T17:29:00.096387Z","shell.execute_reply":"2023-03-18T17:29:00.226486Z"},"trusted":true},"execution_count":null,"outputs":[]}]}