{"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":"import numpy as np\nimport librosa as lb\nimport soundfile as sf\nimport pandas as pd\nfrom pathlib import Path\n\nimport torch\nfrom  torch.utils.data import Dataset\n\nfrom tqdm.notebook import tqdm\n\nfrom torchvision.models import efficientnet_b0","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-11-03T18:58:14.313534Z","iopub.execute_input":"2023-11-03T18:58:14.313904Z","iopub.status.idle":"2023-11-03T18:58:19.684307Z","shell.execute_reply.started":"2023-11-03T18:58:14.313872Z","shell.execute_reply":"2023-11-03T18:58:19.683432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"NUM_CLASSES = 397\nSR = 32_000\nDURATION = 5\nTHRESH = 0.4\n\n\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(\"DEVICE:\", DEVICE)\n\nTEST_AUDIO_ROOT = Path(\"../input/birdclef-2021/test_soundscapes\")\nSAMPLE_SUB_PATH = \"../input/birdclef-2021/sample_submission.csv\"\nTARGET_PATH = None\n    \nif not len(list(TEST_AUDIO_ROOT.glob(\"*.ogg\"))):\n    TEST_AUDIO_ROOT = Path(\"../input/birdclef-2021/train_soundscapes\")\n    SAMPLE_SUB_PATH = None\n    TARGET_PATH = Path(\"../input/birdclef-2021/train_soundscape_labels.csv\")","metadata":{"execution":{"iopub.status.busy":"2023-11-03T18:58:19.686029Z","iopub.execute_input":"2023-11-03T18:58:19.686999Z","iopub.status.idle":"2023-11-03T18:58:19.705006Z","shell.execute_reply.started":"2023-11-03T18:58:19.686966Z","shell.execute_reply":"2023-11-03T18:58:19.703781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class MelSpecComputer:\n    def __init__(self, sr, n_mels, fmin, fmax, **kwargs):\n        self.sr = sr\n        self.n_mels = n_mels\n        self.fmin = fmin\n        self.fmax = fmax\n        kwargs[\"n_fft\"] = kwargs.get(\"n_fft\", self.sr//10)\n        kwargs[\"hop_length\"] = kwargs.get(\"hop_length\", self.sr//(10*4))\n        self.kwargs = kwargs\n\n    def __call__(self, y):\n\n        melspec = lb.feature.melspectrogram(y=y, sr=self.sr, n_mels=self.n_mels, fmin=self.fmin, fmax=self.fmax, **self.kwargs,)\n\n        melspec = lb.power_to_db(melspec).astype(np.float32)\n        return melspec","metadata":{"execution":{"iopub.status.busy":"2023-11-03T18:58:19.706468Z","iopub.execute_input":"2023-11-03T18:58:19.706831Z","iopub.status.idle":"2023-11-03T18:58:19.715898Z","shell.execute_reply.started":"2023-11-03T18:58:19.706797Z","shell.execute_reply":"2023-11-03T18:58:19.714621Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def mono_to_color(X, eps=1e-6, mean=None, std=None):\n    mean = mean or X.mean()\n    std = std or X.std()\n    X = (X - mean) / (std + eps)\n    \n    _min, _max = X.min(), X.max()\n\n    if (_max - _min) > eps:\n        V = np.clip(X, _min, _max)\n        V = 255 * (V - _min) / (_max - _min)\n        V = V.astype(np.uint8)\n    else:\n        V = np.zeros_like(X, dtype=np.uint8)\n\n    return V","metadata":{"execution":{"iopub.status.busy":"2023-11-03T18:58:19.718652Z","iopub.execute_input":"2023-11-03T18:58:19.719030Z","iopub.status.idle":"2023-11-03T18:58:19.728658Z","shell.execute_reply.started":"2023-11-03T18:58:19.719000Z","shell.execute_reply":"2023-11-03T18:58:19.727711Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class BirdCLEFDataset(Dataset):\n    def __init__(self, data, sr=SR, n_mels=128, fmin=0, fmax=None, duration=DURATION, step=None, res_type=\"kaiser_fast\", resample=True):\n        \n        self.data = data\n        \n        self.sr = sr\n        self.n_mels = n_mels\n        self.fmin = fmin\n        self.fmax = fmax or self.sr//2\n\n        self.duration = duration\n        self.audio_length = self.duration*self.sr\n        self.step = step or self.audio_length\n        \n        self.res_type = res_type\n        self.resample = resample\n\n        self.mel_spec_computer = MelSpecComputer(sr=self.sr, n_mels=self.n_mels, fmin=self.fmin,\n                                                 fmax=self.fmax)\n    def __len__(self):\n        return len(self.data)\n    \n    @staticmethod\n    def normalize(image):\n        image = image.astype(\"float32\", copy=False) / 255.0\n        image = np.stack([image, image, image])\n        return image\n    \n    def audio_to_image(self, audio):\n        melspec = self.mel_spec_computer(audio) \n        image = mono_to_color(melspec)\n        image = self.normalize(image)\n        return image\n\n    def read_file(self, filepath):\n        audio, orig_sr = sf.read(filepath, dtype=\"float32\")\n\n        if self.resample and orig_sr != self.sr:\n            audio = lb.resample(audio, orig_sr, self.sr, res_type=self.res_type)\n          \n        audios = []\n        for i in range(self.audio_length, len(audio) + self.step, self.step):\n            start = max(0, i - self.audio_length)\n            end = start + self.audio_length\n            audios.append(audio[start:end])\n            \n        if len(audios[-1]) < self.audio_length:\n            audios = audios[:-1]\n            \n        images = [self.audio_to_image(audio) for audio in audios]\n        images = np.stack(images)\n        \n        return images\n    \n        \n    def __getitem__(self, idx):\n        return self.read_file(self.data.loc[idx, \"filepath\"])","metadata":{"execution":{"iopub.status.busy":"2023-11-03T18:58:19.730095Z","iopub.execute_input":"2023-11-03T18:58:19.730441Z","iopub.status.idle":"2023-11-03T18:58:19.749215Z","shell.execute_reply.started":"2023-11-03T18:58:19.730413Z","shell.execute_reply":"2023-11-03T18:58:19.748216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = pd.DataFrame(\n     [(path.stem, *path.stem.split(\"_\"), path) for path in Path(TEST_AUDIO_ROOT).glob(\"*.ogg\")],\n    columns = [\"filename\", \"id\", \"site\", \"date\", \"filepath\"]\n)","metadata":{"execution":{"iopub.status.busy":"2023-11-03T18:58:19.750644Z","iopub.execute_input":"2023-11-03T18:58:19.752057Z","iopub.status.idle":"2023-11-03T18:58:19.804239Z","shell.execute_reply.started":"2023-11-03T18:58:19.752016Z","shell.execute_reply":"2023-11-03T18:58:19.803404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = pd.read_csv(\"../input/birdclef-2021/train_metadata.csv\")\n\nLABEL_IDS = {label: label_id for label_id,label in enumerate(sorted(df_train[\"primary_label\"].unique()))}\nINV_LABEL_IDS = {val: key for key,val in LABEL_IDS.items()}\n\ntest_data = BirdCLEFDataset(data=data)\n","metadata":{"execution":{"iopub.status.busy":"2023-11-03T18:58:19.805596Z","iopub.execute_input":"2023-11-03T18:58:19.806632Z","iopub.status.idle":"2023-11-03T18:58:20.397234Z","shell.execute_reply.started":"2023-11-03T18:58:19.806591Z","shell.execute_reply":"2023-11-03T18:58:20.396277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_net(checkpoint_path, num_classes=NUM_CLASSES):\n    net = efficientnet_b0(pretrained=False)\n    net.classifier[1] = torch.nn.Linear(1280, NUM_CLASSES)\n    dummy_device = torch.device(\"cpu\")\n    d = torch.load(checkpoint_path, map_location=dummy_device)\n    for key in list(d.keys()):\n        d[key.replace(\"model.\", \"\")] = d.pop(key)\n    net.load_state_dict(d)\n    net = net.to(DEVICE)\n    net = net.eval()\n    return net","metadata":{"execution":{"iopub.status.busy":"2023-11-03T18:58:40.072728Z","iopub.execute_input":"2023-11-03T18:58:40.073749Z","iopub.status.idle":"2023-11-03T18:58:40.083121Z","shell.execute_reply.started":"2023-11-03T18:58:40.073708Z","shell.execute_reply":"2023-11-03T18:58:40.081648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\ncheckpoint_paths = [\n    Path(\"../input/models-final/model0.pt\"),\n    Path(\"../input/models-final/model1.pt\"),\n    Path(\"../input/models-final/model2.pt\"),\n    Path(\"../input/models-final/model3.pt\"),\n    Path(\"../input/models-final/model4.pt\"),\n]\n\nnets = [\n        load_net(checkpoint_path.as_posix()) for checkpoint_path in checkpoint_paths\n]\n\n","metadata":{"execution":{"iopub.status.busy":"2023-11-03T18:58:40.093040Z","iopub.execute_input":"2023-11-03T18:58:40.096817Z","iopub.status.idle":"2023-11-03T18:58:40.742706Z","shell.execute_reply.started":"2023-11-03T18:58:40.096766Z","shell.execute_reply":"2023-11-03T18:58:40.741528Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"@torch.no_grad()\ndef get_thresh_preds(out, thresh=None):\n    thresh = thresh or THRESH\n    o = (-out).argsort(1)\n    npreds = (out > thresh).sum(1)\n    preds = []\n    for oo, npred in zip(o, npreds):\n        preds.append(oo[:npred].cpu().numpy().tolist())\n    return preds","metadata":{"execution":{"iopub.status.busy":"2023-11-03T18:58:40.745729Z","iopub.execute_input":"2023-11-03T18:58:40.746458Z","iopub.status.idle":"2023-11-03T18:58:40.754485Z","shell.execute_reply.started":"2023-11-03T18:58:40.746424Z","shell.execute_reply":"2023-11-03T18:58:40.753086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_bird_names(preds):\n    bird_names = []\n    for pred in preds:\n        if not pred:\n            bird_names.append(\"nocall\")\n        else:\n            bird_names.append(\" \".join([INV_LABEL_IDS[bird_id] for bird_id in pred]))\n    return bird_names","metadata":{"execution":{"iopub.status.busy":"2023-11-03T18:58:40.758368Z","iopub.execute_input":"2023-11-03T18:58:40.760475Z","iopub.status.idle":"2023-11-03T18:58:40.796171Z","shell.execute_reply.started":"2023-11-03T18:58:40.760439Z","shell.execute_reply":"2023-11-03T18:58:40.795140Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def predict(nets, test_data, names=True):\n    preds = []\n    with torch.no_grad():\n        for idx in  tqdm(list(range(len(test_data)))):\n            xb = torch.from_numpy(test_data[idx]).to(DEVICE)\n            pred = 0.\n            for net in nets:\n                o = net(xb)\n                o = torch.nn.functional.softmax(o, dim=1)\n                pred += o\n\n            pred /= len(nets)\n            \n            if names:\n                pred = get_bird_names(get_thresh_preds(pred))\n\n            preds.append(pred)\n    return preds\n\n","metadata":{"execution":{"iopub.status.busy":"2023-11-03T18:58:40.797174Z","iopub.execute_input":"2023-11-03T18:58:40.797504Z","iopub.status.idle":"2023-11-03T18:58:40.809100Z","shell.execute_reply.started":"2023-11-03T18:58:40.797465Z","shell.execute_reply":"2023-11-03T18:58:40.807569Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_probas = predict(nets, test_data, names=False)\npreds = [get_bird_names(get_thresh_preds(pred, thresh=THRESH)) for pred in pred_probas]","metadata":{"execution":{"iopub.status.busy":"2023-11-03T18:58:40.811124Z","iopub.execute_input":"2023-11-03T18:58:40.811963Z","iopub.status.idle":"2023-11-03T19:01:38.031699Z","shell.execute_reply.started":"2023-11-03T18:58:40.811924Z","shell.execute_reply":"2023-11-03T19:01:38.030847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def preds_as_df(data, preds):\n    sub = {\n        \"row_id\": [],\n        \"birds\": [],\n    }\n    \n    for row, pred in zip(data.itertuples(False), preds):\n        row_id = [f\"{row.id}_{row.site}_{5*i}\" for i in range(1, len(pred)+1)]\n        sub[\"birds\"] += pred\n        sub[\"row_id\"] += row_id\n        \n    sub = pd.DataFrame(sub)\n    \n    if SAMPLE_SUB_PATH:\n        sample_sub = pd.read_csv(SAMPLE_SUB_PATH, usecols=[\"row_id\"])\n        sub = sample_sub.merge(sub, on=\"row_id\", how=\"left\")\n        sub[\"birds\"] = sub[\"birds\"].fillna(\"nocall\")\n    return sub","metadata":{"execution":{"iopub.status.busy":"2023-11-03T19:04:18.247747Z","iopub.execute_input":"2023-11-03T19:04:18.248142Z","iopub.status.idle":"2023-11-03T19:04:18.256218Z","shell.execute_reply.started":"2023-11-03T19:04:18.248114Z","shell.execute_reply":"2023-11-03T19:04:18.255136Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = preds_as_df(data, preds)\nsub.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2023-11-03T19:04:19.674188Z","iopub.execute_input":"2023-11-03T19:04:19.674744Z","iopub.status.idle":"2023-11-03T19:04:19.698276Z","shell.execute_reply.started":"2023-11-03T19:04:19.674682Z","shell.execute_reply":"2023-11-03T19:04:19.696799Z"},"trusted":true},"execution_count":null,"outputs":[]}]}