{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":19596,"databundleVersionId":1292430,"sourceType":"competition"},{"sourceId":1262046,"sourceType":"datasetVersion","datasetId":726424},{"sourceId":1264575,"sourceType":"datasetVersion","datasetId":725893}],"dockerImageVersionId":29956,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import cv2\nimport audioread\nimport logging\nimport os\nimport random\nimport time\nimport warnings\nimport librosa\nimport numpy as np\nimport pandas as pd\nimport soundfile as sf\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data as data\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Optional\nfrom sklearn.preprocessing import LabelEncoder\nfrom fastprogress import progress_bar\nfrom sklearn.metrics import f1_score\nfrom torchvision import models","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-01-11T16:29:21.808443Z","iopub.execute_input":"2024-01-11T16:29:21.808716Z","iopub.status.idle":"2024-01-11T16:29:25.230930Z","shell.execute_reply.started":"2024-01-11T16:29:21.808688Z","shell.execute_reply":"2024-01-11T16:29:25.230172Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def set_seed(seed: int = 42):\n    random.seed(seed)\n    np.random.seed(seed)\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True \n    torch.backends.cudnn.benchmark = True  \n    \ndef get_logger(out_file=None):\n    logger = logging.getLogger()\n    formatter = logging.Formatter(\"%(asctime)s - %(levelname)s - %(message)s\")\n    logger.handlers = []\n    logger.setLevel(logging.INFO)\n\n    handler = logging.StreamHandler()\n    handler.setFormatter(formatter)\n    handler.setLevel(logging.INFO)\n    logger.addHandler(handler)\n\n    if out_file is not None:\n        fh = logging.FileHandler(out_file)\n        fh.setFormatter(formatter)\n        fh.setLevel(logging.INFO)\n        logger.addHandler(fh)\n    logger.info(\"logger set up\")\n    return logger\n@contextmanager\ndef timer(name: str, logger: Optional[logging.Logger] = None):\n    t0 = time.time()\n    msg = f\"[{name}] start\"\n    if logger is None:\n        print(msg)\n    else:\n        logger.info(msg)\n    yield\n\n    msg = f\"[{name}] done in {time.time() - t0:.2f} s\"\n    if logger is None:\n        print(msg)\n    else:\n        logger.info(msg)","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:29:35.056280Z","iopub.execute_input":"2024-01-11T16:29:35.056605Z","iopub.status.idle":"2024-01-11T16:29:35.070024Z","shell.execute_reply.started":"2024-01-11T16:29:35.056576Z","shell.execute_reply":"2024-01-11T16:29:35.068964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"logger = get_logger(\"main.log\")\nset_seed(1213)","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:29:37.170384Z","iopub.execute_input":"2024-01-11T16:29:37.170708Z","iopub.status.idle":"2024-01-11T16:29:37.179581Z","shell.execute_reply.started":"2024-01-11T16:29:37.170677Z","shell.execute_reply":"2024-01-11T16:29:37.178626Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TARGET_SR = 32000\nTEST = Path(\"../input/birdsong-recognition/test_audio\").exists()","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:29:42.427355Z","iopub.execute_input":"2024-01-11T16:29:42.427892Z","iopub.status.idle":"2024-01-11T16:29:42.434263Z","shell.execute_reply.started":"2024-01-11T16:29:42.427834Z","shell.execute_reply":"2024-01-11T16:29:42.433106Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if TEST:\n    DATA_DIR = Path(\"../input/birdsong-recognition/\")\nelse:\n    DATA_DIR = Path(\"../input/birdcall-check/\")\ntest = pd.read_csv(DATA_DIR / \"test.csv\")\ntest_audio = DATA_DIR / \"test_audio\"\ntest.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:29:44.881920Z","iopub.execute_input":"2024-01-11T16:29:44.882278Z","iopub.status.idle":"2024-01-11T16:29:44.919486Z","shell.execute_reply.started":"2024-01-11T16:29:44.882243Z","shell.execute_reply":"2024-01-11T16:29:44.918686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.read_csv(\"../input/birdsong-recognition/sample_submission.csv\")\nsub.to_csv(\"submission.csv\", index=False)  ","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:29:46.428546Z","iopub.execute_input":"2024-01-11T16:29:46.428907Z","iopub.status.idle":"2024-01-11T16:29:46.753348Z","shell.execute_reply.started":"2024-01-11T16:29:46.428875Z","shell.execute_reply":"2024-01-11T16:29:46.752598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ResNet(nn.Module):\n    def __init__(self, base_model_name: str, pretrained=False, num_classes=264):\n        super().__init__()\n        base_model = models.__getattribute__(base_model_name)(pretrained=pretrained)\n        layers = list(base_model.children())[:-2]\n        layers.append(nn.AdaptiveMaxPool2d(1))\n        self.encoder = nn.Sequential(*layers)\n\n        in_features = base_model.fc.in_features\n\n        self.classifier = nn.Sequential(\n            nn.Linear(in_features, 1024), nn.ReLU(), nn.Dropout(p=0.2),\n            nn.Linear(1024, 1024), nn.ReLU(), nn.Dropout(p=0.2),\n            nn.Linear(1024, num_classes))\n\n    def forward(self, x):\n        batch_size = x.size(0)\n        x = self.encoder(x).view(batch_size, -1)\n        x = self.classifier(x)\n        multiclass_proba = F.softmax(x, dim=1)\n        multilabel_proba = F.sigmoid(x)\n        return {\n            \"logits\": x,\n            \"multiclass_proba\": multiclass_proba,\n            \"multilabel_proba\": multilabel_proba\n        }","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:29:48.072718Z","iopub.execute_input":"2024-01-11T16:29:48.073076Z","iopub.status.idle":"2024-01-11T16:29:48.086154Z","shell.execute_reply.started":"2024-01-11T16:29:48.073045Z","shell.execute_reply":"2024-01-11T16:29:48.085125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_config = {\n    \"base_model_name\": \"resnet50\",\n    \"pretrained\": False,\n    \"num_classes\": 264\n}\n\nmelspectrogram_parameters = {\n    \"n_mels\": 128,\n    \"fmin\": 20,\n    \"fmax\": 16000\n}\n\nweights_path = \"../input/birdcall-resnet50-init-weights/best.pth\"","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:29:50.045083Z","iopub.execute_input":"2024-01-11T16:29:50.045438Z","iopub.status.idle":"2024-01-11T16:29:50.050765Z","shell.execute_reply.started":"2024-01-11T16:29:50.045407Z","shell.execute_reply":"2024-01-11T16:29:50.049867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv(\"/kaggle/input/birdsong-recognition/train.csv\")\nuniq = df['ebird_code'].unique()\n\nle = LabelEncoder()\nencoded_labels = le.fit_transform(uniq)\nBIRD_CODE = dict(zip(uniq,encoded_labels))\nINV_BIRD_CODE = {v: k for k, v in BIRD_CODE.items()}","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:29:51.919525Z","iopub.execute_input":"2024-01-11T16:29:51.919889Z","iopub.status.idle":"2024-01-11T16:29:52.300436Z","shell.execute_reply.started":"2024-01-11T16:29:51.919853Z","shell.execute_reply":"2024-01-11T16:29:52.299379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def mono_to_color(X: np.ndarray, mean=None,std=None,norm_max=None,norm_min=None,eps=1e-6):\n    X = np.stack([X, X, X], axis=-1)\n    mean = mean or X.mean()\n    X = X - mean\n    std = std or X.std()\n    Xstd = X / (std + eps)\n    _min, _max = Xstd.min(), Xstd.max()\n    norm_max = norm_max or _max\n    norm_min = norm_min or _min\n    if (_max - _min) > eps:\n        V = Xstd\n        V[V < norm_min] = norm_min\n        V[V > norm_max] = norm_max\n        V = 255 * (V - norm_min) / (norm_max - norm_min)\n        V = V.astype(np.uint8)\n    else:\n        V = np.zeros_like(Xstd, dtype=np.uint8)\n    return V\nclass TestDataset(data.Dataset):\n    def __init__(self, df: pd.DataFrame, clip: np.ndarray,\n                 img_size=224, melspectrogram_parameters={}):\n        self.df = df\n        self.clip = clip\n        self.img_size = img_size\n        self.melspectrogram_parameters = melspectrogram_parameters\n        \n    def __len__(self):\n        return len(self.df)\n    \n    def __getitem__(self, idx: int):\n        SR = 32000\n        sample = self.df.loc[idx, :]\n        site = sample.site\n        row_id = sample.row_id\n        \n        if site == \"site_3\":\n            y = self.clip.astype(np.float32)\n            len_y = len(y)\n            start = 0\n            end = SR * 5\n            images = []\n            while len_y > start:\n                y_batch = y[start:end].astype(np.float32)\n                if len(y_batch) != (SR * 5):\n                    break\n                start = end\n                end = end + SR * 5\n                \n                melspec = librosa.feature.melspectrogram(y_batch,sr=SR,**self.melspectrogram_parameters)\n                melspec = librosa.power_to_db(melspec).astype(np.float32)\n                image = mono_to_color(melspec)\n                height, width, _ = image.shape\n                image = cv2.resize(image, (int(width * self.img_size / height), self.img_size))\n                image = np.moveaxis(image, 2, 0)\n                image = (image / 255.0).astype(np.float32)\n                images.append(image)\n            images = np.asarray(images)\n            return images, row_id, site\n        else:\n            end_seconds = int(sample.seconds)\n            start_seconds = int(end_seconds - 5)\n            \n            start_index = SR * start_seconds\n            end_index = SR * end_seconds\n            \n            y = self.clip[start_index:end_index].astype(np.float32)\n\n            melspec = librosa.feature.melspectrogram(y, sr=SR, **self.melspectrogram_parameters)\n            melspec = librosa.power_to_db(melspec).astype(np.float32)\n\n            image = mono_to_color(melspec)\n            height, width, _ = image.shape\n            image = cv2.resize(image, (int(width * self.img_size / height), self.img_size))\n            image = np.moveaxis(image, 2, 0)\n            image = (image / 255.0).astype(np.float32)\n\n            return image, row_id, site","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:29:53.714126Z","iopub.execute_input":"2024-01-11T16:29:53.714463Z","iopub.status.idle":"2024-01-11T16:29:53.743442Z","shell.execute_reply.started":"2024-01-11T16:29:53.714433Z","shell.execute_reply":"2024-01-11T16:29:53.742575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_model(config: dict, weights_path: str):\n    model = ResNet(**config)\n    checkpoint = torch.load(weights_path)\n    model.load_state_dict(checkpoint[\"model_state_dict\"])\n    device = torch.device(\"cuda\")\n    model.to(device)\n    model.eval()\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:29:58.948233Z","iopub.execute_input":"2024-01-11T16:29:58.948697Z","iopub.status.idle":"2024-01-11T16:29:58.958017Z","shell.execute_reply.started":"2024-01-11T16:29:58.948655Z","shell.execute_reply":"2024-01-11T16:29:58.956752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def prediction_for_clip(test_df: pd.DataFrame,clip: np.ndarray, model: ResNet, mel_params: dict, threshold=0.5):\n\n    dataset = TestDataset(df=test_df, clip=clip,img_size=224,melspectrogram_parameters=mel_params)\n    loader = data.DataLoader(dataset, batch_size=1, shuffle=False)\n    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n    \n    model.eval()\n    prediction_dict = {}\n    for image, row_id, site in progress_bar(loader):\n        site = site[0]\n        row_id = row_id[0]\n        if site in {\"site_1\", \"site_2\"}:\n            image = image.to(device)\n\n            with torch.no_grad():\n                prediction = model(image)\n                proba = prediction[\"multilabel_proba\"].detach().cpu().numpy().reshape(-1)\n\n            events = proba >= threshold\n            labels = np.argwhere(events).reshape(-1).tolist()\n\n        else:\n            # to avoid prediction on large batch\n            image = image.squeeze(0)\n            batch_size = 16\n            whole_size = image.size(0)\n            if whole_size % batch_size == 0:\n                n_iter = whole_size // batch_size\n            else:\n                n_iter = whole_size // batch_size + 1\n                \n            all_events = set()\n            for batch_i in range(n_iter):\n                batch = image[batch_i * batch_size:(batch_i + 1) * batch_size]\n                if batch.ndim == 3:\n                    batch = batch.unsqueeze(0)\n\n                batch = batch.to(device)\n                with torch.no_grad():\n                    prediction = model(batch)\n                    proba = prediction[\"multilabel_proba\"].detach().cpu().numpy()\n                    \n                events = proba >= threshold\n                for i in range(len(events)):\n                    event = events[i, :]\n                    labels = np.argwhere(event).reshape(-1).tolist()\n                    for label in labels:\n                        all_events.add(label)\n                        \n            labels = list(all_events)\n        if len(labels) == 0:\n            prediction_dict[row_id] = \"nocall\"\n        else:\n            labels_str_list = list(map(lambda x: INV_BIRD_CODE[x], labels))\n            label_string = \" \".join(labels_str_list)\n            prediction_dict[row_id] = label_string\n    return prediction_dict","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:30:00.982208Z","iopub.execute_input":"2024-01-11T16:30:00.982552Z","iopub.status.idle":"2024-01-11T16:30:01.003066Z","shell.execute_reply.started":"2024-01-11T16:30:00.982521Z","shell.execute_reply":"2024-01-11T16:30:01.002106Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def prediction(test_df: pd.DataFrame,test_audio: Path, model_config: dict,mel_params: dict,weights_path: str,threshold=0.5):\n    model = get_model(model_config, weights_path)\n    unique_audio_id = test_df.audio_id.unique()\n\n    warnings.filterwarnings(\"ignore\")\n    prediction_dfs = []\n    for audio_id in unique_audio_id:\n        with timer(f\"Loading {audio_id}\", logger):\n            clip, _ = librosa.load(test_audio / (audio_id + \".mp3\"),\n                                   sr=TARGET_SR,\n                                   mono=True,\n                                   res_type=\"kaiser_fast\")\n        \n        test_df_for_audio_id = test_df.query(\n            f\"audio_id == '{audio_id}'\").reset_index(drop=True)\n        with timer(f\"Prediction on {audio_id}\", logger):\n            prediction_dict = prediction_for_clip(test_df_for_audio_id,\n                                                  clip=clip,\n                                                  model=model,\n                                                  mel_params=mel_params,\n                                                  threshold=threshold)\n        row_id = list(prediction_dict.keys())\n        birds = list(prediction_dict.values())\n        prediction_df = pd.DataFrame({\n            \"row_id\": row_id,\n            \"birds\": birds\n        })\n        prediction_dfs.append(prediction_df)\n    \n    prediction_df = pd.concat(prediction_dfs, axis=0, sort=False).reset_index(drop=True)\n    return prediction_df","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:30:03.188243Z","iopub.execute_input":"2024-01-11T16:30:03.188595Z","iopub.status.idle":"2024-01-11T16:30:03.200398Z","shell.execute_reply.started":"2024-01-11T16:30:03.188561Z","shell.execute_reply":"2024-01-11T16:30:03.199430Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = prediction(test_df=test,\n                        test_audio=test_audio,\n                        model_config=model_config,\n                        mel_params=melspectrogram_parameters,\n                        weights_path=weights_path,\n                        threshold=0.8)\nsubmission.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:30:05.259436Z","iopub.execute_input":"2024-01-11T16:30:05.259809Z","iopub.status.idle":"2024-01-11T16:30:32.175834Z","shell.execute_reply.started":"2024-01-11T16:30:05.259770Z","shell.execute_reply":"2024-01-11T16:30:32.174996Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:30:59.418664Z","iopub.execute_input":"2024-01-11T16:30:59.419072Z","iopub.status.idle":"2024-01-11T16:30:59.432353Z","shell.execute_reply.started":"2024-01-11T16:30:59.419035Z","shell.execute_reply":"2024-01-11T16:30:59.431506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission1 = submission\nsubmission1['row_id'] = submission['row_id'].apply(lambda x:(str(x)[:39]))\nsubmission1","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:37:18.753116Z","iopub.execute_input":"2024-01-11T16:37:18.753465Z","iopub.status.idle":"2024-01-11T16:37:18.766990Z","shell.execute_reply.started":"2024-01-11T16:37:18.753436Z","shell.execute_reply":"2024-01-11T16:37:18.766156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission1['row_id'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:38:06.561052Z","iopub.execute_input":"2024-01-11T16:38:06.561413Z","iopub.status.idle":"2024-01-11T16:38:06.569626Z","shell.execute_reply.started":"2024-01-11T16:38:06.561369Z","shell.execute_reply":"2024-01-11T16:38:06.568820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission1['birds'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-01-11T16:40:11.819571Z","iopub.execute_input":"2024-01-11T16:40:11.819940Z","iopub.status.idle":"2024-01-11T16:40:11.828253Z","shell.execute_reply.started":"2024-01-11T16:40:11.819908Z","shell.execute_reply":"2024-01-11T16:40:11.827426Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}