{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":19596,"databundleVersionId":1292430,"sourceType":"competition"},{"sourceId":1262046,"sourceType":"datasetVersion","datasetId":726424},{"sourceId":1264575,"sourceType":"datasetVersion","datasetId":725893}],"dockerImageVersionId":30635,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import cv2 #image processing\nimport audioread #reading and processing audio files\nimport logging #record events and errors for debugging and monitoring\nimport os #file and directory manipulation\nimport random #shuffling data\nimport time #calculate time taken or introduce delays\nimport warnings #issuing warning messages about potential issues\n\nimport librosa\nimport numpy as np\nimport pandas as pd\nimport soundfile as sf #reading and writing audio files\nimport torch #core module of PyTorch\nimport torch.nn as nn #building and training neural networks\nimport torch.nn.functional as F #for element-wise functions\nimport torch.utils.data as data #for loading and batching data during training\n\nfrom contextlib import contextmanager #to ensure that resources are properly managed\nfrom pathlib import Path #for working with paths in a more object-oriented way\nfrom typing import Optional #type hint\n\nfrom fastprogress import progress_bar\nfrom sklearn.metrics import f1_score\nfrom torchvision import models #provides pre-trained models","metadata":{"execution":{"iopub.status.busy":"2024-01-11T12:12:43.070858Z","iopub.execute_input":"2024-01-11T12:12:43.071302Z","iopub.status.idle":"2024-01-11T12:12:43.080411Z","shell.execute_reply.started":"2024-01-11T12:12:43.071265Z","shell.execute_reply":"2024-01-11T12:12:43.078823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def set_seed(seed: int = 42):\n    # Sets random seed for different libraries\n    random.seed(seed)\n    np.random.seed(seed)\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)  # For hash functions\n    torch.manual_seed(seed)  # Random seed for PyTorch\n    torch.cuda.manual_seed(seed)  # Same but for GPU\n    torch.backends.cudnn.deterministic = True  # Deterministic mode\n    torch.backends.cudnn.benchmark = True  # Optimize performance\n\ndef get_logger(out_file=None):\n    logger = logging.getLogger()\n    formatter = logging.Formatter(\"%(asctime)s - %(levelname)s - %(message)s\")  # Timestamp, log level, message\n    logger.handlers = []  # Object that transfers log\n    logger.setLevel(logging.INFO)  # Capture only INFO level\n    handler = logging.StreamHandler()  # To the console\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\n    logger.info(\"Logger set up\")\n    return logger\n\n@contextmanager\ndef timer(name: str, logger: Optional[logging.Logger] = None):\n    t0 = time.time()  # Current time\n    msg = f\"[{name}] start\"\n    if logger is None:\n        print(msg)\n    else:\n        logger.info(msg)\n    yield\n    if logger is None:\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)\n","metadata":{"execution":{"iopub.status.busy":"2024-01-11T12:12:43.132995Z","iopub.execute_input":"2024-01-11T12:12:43.133427Z","iopub.status.idle":"2024-01-11T12:12:43.148015Z","shell.execute_reply.started":"2024-01-11T12:12:43.133391Z","shell.execute_reply":"2024-01-11T12:12:43.146458Z"},"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-11T12:12:43.157055Z","iopub.execute_input":"2024-01-11T12:12:43.157631Z","iopub.status.idle":"2024-01-11T12:12:43.170369Z","shell.execute_reply.started":"2024-01-11T12:12:43.157560Z","shell.execute_reply":"2024-01-11T12:12:43.169306Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"DATA LODING ","metadata":{}},{"cell_type":"code","source":"TARGET_SR=32000","metadata":{"execution":{"iopub.status.busy":"2024-01-11T12:12:43.177623Z","iopub.execute_input":"2024-01-11T12:12:43.178186Z","iopub.status.idle":"2024-01-11T12:12:43.185888Z","shell.execute_reply.started":"2024-01-11T12:12:43.178128Z","shell.execute_reply":"2024-01-11T12:12:43.184799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test=pd.read_csv(\"/kaggle/input/birdcall-check/test.csv\")\ntest_audio=(\"/kaggle/intput/birdcall-check/test_audio\")\ntest.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-11T12:12:43.198672Z","iopub.execute_input":"2024-01-11T12:12:43.199967Z","iopub.status.idle":"2024-01-11T12:12:43.222977Z","shell.execute_reply.started":"2024-01-11T12:12:43.199921Z","shell.execute_reply":"2024-01-11T12:12:43.220914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"DEFINE MODEL","metadata":{}},{"cell_type":"code","source":"class ResNet(nn.Module):\n    def __init__(self, base_model_name: str, pretrained=False, num_classes=264):\n        super(ResNet, self).__init__()  # Initializing the base class\n        base_model = getattr(models, base_model_name)(pretrained=pretrained)\n        layers = list(base_model.children())[:-2]  # Except pooling and dense layers\n        layers.append(nn.AdaptiveMaxPool2d(1))\n        self.encoder = nn.Sequential(*layers)\n\n        in_features = base_model.fc.in_features  # Number of input features\n\n        self.classifier = nn.Sequential(\n            nn.Linear(in_features, 1024),\n            nn.ReLU(),\n            nn.Dropout(p=0.2),\n            nn.Linear(1024, 1024),\n            nn.ReLU(),\n            nn.Dropout(p=0.2),\n            nn.Linear(1024, num_classes)\n        )\n\n    def forward(self, x):\n        batch_size = x.size(0)  # Input tensor\n        x = self.encoder(x).view(batch_size, -1)  # 1D tensor\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        }\n","metadata":{"execution":{"iopub.status.busy":"2024-01-11T12:12:43.226629Z","iopub.execute_input":"2024-01-11T12:12:43.227144Z","iopub.status.idle":"2024-01-11T12:12:43.241365Z","shell.execute_reply.started":"2024-01-11T12:12:43.227100Z","shell.execute_reply":"2024-01-11T12:12:43.240227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"PARAMETERS","metadata":{}},{"cell_type":"code","source":"model_config = {\n\"base_model_name\": \"resnet50\",\n\"pretrained\": False,\n\"num_classes\": 264\n}\nmelspectrogram_parameters = {\n\"n_mels\": 128, #number of Mel bins\n\"fmin\": 20,\n\"fmax\": 16000\n}\nweights_path = \"../input/birdcall-resnet50-init-weights/best.pth\"","metadata":{"execution":{"iopub.status.busy":"2024-01-11T12:12:43.243272Z","iopub.execute_input":"2024-01-11T12:12:43.244027Z","iopub.status.idle":"2024-01-11T12:12:43.263787Z","shell.execute_reply.started":"2024-01-11T12:12:43.243989Z","shell.execute_reply":"2024-01-11T12:12:43.262099Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\nimport pandas as pd\n\ndf = pd.read_csv(\"/kaggle/input/birdsong-recognition/train.csv\")\n\nunique_bird_names = df['ebird_code'].unique()\n\nlabel_encoder = LabelEncoder()\n\nencoded_labels = label_encoder.fit_transform(unique_bird_names)\n\nBIRD_CODE = dict(zip(unique_bird_names, encoded_labels))\n\n#for bird_name, label in BIRD_CODE.items(): \n #   print(f\"{bird_name}: {label}\")\n\nINV_BIRD_CODE = {v: k for k, v in BIRD_CODE.items()}\n# for bird_name, label in INV_BIRD_CODE.items():\n#     print(f\"{bird_name}: {label}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-01-11T12:12:43.279399Z","iopub.execute_input":"2024-01-11T12:12:43.279890Z","iopub.status.idle":"2024-01-11T12:12:43.699449Z","shell.execute_reply.started":"2024-01-11T12:12:43.279841Z","shell.execute_reply":"2024-01-11T12:12:43.697779Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def mono_to_color(X: np.ndarray,\n                  mean=None,\n                  std=None,\n                  norm_max=None,\n                  norm_min=None,\n                  eps=1e-6):\n    X = np.stack([X, X, X], axis=-1)\n\n    # Standardize\n    mean = mean or X.mean()\n    X = X - mean  # Corrected the missing operator\n    std = std or X.std()\n    Xstd = X / (std + eps)\n    _min, _max = Xstd.min(), Xstd.max()  # Corrected the missing underscore in \"_min\" and \"max\"\n\n    norm_max = norm_max or _max  # Corrected the missing assignment operator\n    norm_min = norm_min or _min  # Corrected the missing assignment operator\n\n    if (_max - _min) > eps:\n        # Normalize to [0, 255]\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)  # Corrected the missing operators\n        V = V.astype(np.uint8)\n    else:\n        V = np.zeros_like(Xstd, dtype=np.uint8)\n    return V\n","metadata":{"execution":{"iopub.status.busy":"2024-01-11T12:12:43.702162Z","iopub.execute_input":"2024-01-11T12:12:43.702563Z","iopub.status.idle":"2024-01-11T12:12:43.714341Z","shell.execute_reply.started":"2024-01-11T12:12:43.702529Z","shell.execute_reply":"2024-01-11T12:12:43.712661Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class TestDataset(data.Dataset):\n\n    def __init__(self, df: pd.DataFrame, clip: np.ndarray, 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)  # Number of samples\n\n    def __getitem__(self, idx: int):\n        SR = 32000\n\n        sample = self.df.loc[idx]  # Return row\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\n            images = []\n\n            while len_y > start:\n                y_batch = y[start:end].astype(np.float32)\n\n                if len(y_batch) != (SR * 5):\n                    break\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)  # Color channel axis to the first dimension\n                image = (image / 255.0).astype(np.float32)\n                images.append(image)\n\n                start = end\n                end += SR * 5\n\n            images = np.asarray(images)\n            return images, row_id, site\n\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            melspec = librosa.feature.melspectrogram(y, 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\n            return image, row_id, site\n","metadata":{"execution":{"iopub.status.busy":"2024-01-11T12:12:43.715923Z","iopub.execute_input":"2024-01-11T12:12:43.716353Z","iopub.status.idle":"2024-01-11T12:12:43.740104Z","shell.execute_reply.started":"2024-01-11T12:12:43.716319Z","shell.execute_reply":"2024-01-11T12:12:43.738515Z"},"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)  # Pretrained weights\n    model.load_state_dict(checkpoint[\"model_state_dict\"])  # Initializing learned parameters of the model\n    device = torch.device(\"cuda\")\n    model.to(device)\n    model.eval()\n    return model\n","metadata":{"execution":{"iopub.status.busy":"2024-01-11T12:12:43.742745Z","iopub.execute_input":"2024-01-11T12:12:43.743643Z","iopub.status.idle":"2024-01-11T12:12:43.763028Z","shell.execute_reply.started":"2024-01-11T12:12:43.743536Z","shell.execute_reply":"2024-01-11T12:12:43.761422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def prediction_for_clip(test_df: pd.DataFrame,\n                         clip: np.ndarray,\n                         model: ResNet,  # Update with your actual model class\n                         mel_params: dict,\n                         threshold=0.5):\n    dataset = TestDataset(df=test_df,\n                          clip=clip,\n                          img_size=224,\n                          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    model.eval()\n    prediction_dict = {}\n\n    for image, row_id, site in loader:\n        site = site[0]\n        row_id = row_id[0]\n\n        if site in (\"site_1\", \"site_2\"):\n            image = image.to(device)\n            with torch.no_grad():\n                prediction = model(image)\n            proba = prediction[\"multilabel_proba\"].detach().cpu().numpy().reshape(-1)\n            events = proba >= threshold\n            labels = np.argwhere(events).reshape(-1).tolist()\n\n        else:\n            image = image.squeeze(0)\n            batch_size = 16\n            whole_size = image.size(0)\n\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\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\n    return prediction_dict","metadata":{"execution":{"iopub.status.busy":"2024-01-11T12:12:43.766764Z","iopub.execute_input":"2024-01-11T12:12:43.767279Z","iopub.status.idle":"2024-01-11T12:12:43.786980Z","shell.execute_reply.started":"2024-01-11T12:12:43.767234Z","shell.execute_reply":"2024-01-11T12:12:43.785794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndef prediction(test_df: pd.DataFrame,\n               test_audio: Path,\n               model_config: dict,\n               mel_params: dict,\n               weights_path: str,\n               threshold=0.5):\n    model = get_model(model_config, weights_path)  # Assuming you have a 'get_model' function defined\n    unique_audio_id = test_df.audio_id.unique()\n    warnings.filterwarnings(\"ignore\")\n    prediction_dfs = []\n\n    for audio_id in unique_audio_id:\n        with timer(f\"Loading {audio_id}\", logger):  # Assuming 'timer' is defined\n            clip, _ = librosa.load(test_audio / (audio_id + \".mp3\"), sr=TARGET_SR, mono=True, res_type=\"kaiser_fast\")\n\n        test_df_for_audio_id = test_df.query(f\"audio_id == '{audio_id}'\").reset_index(drop=True)\n\n        with timer(f\"Prediction on {audio_id}\", logger):  # Assuming 'timer' is defined\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\n        row_id = list(prediction_dict.keys())\n        birds = list(prediction_dict.values())\n\n        prediction_df = pd.DataFrame({\"row_id\": row_id, \"birds\": birds})\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-11T12:12:43.788619Z","iopub.execute_input":"2024-01-11T12:12:43.789439Z","iopub.status.idle":"2024-01-11T12:12:43.806292Z","shell.execute_reply.started":"2024-01-11T12:12:43.789374Z","shell.execute_reply":"2024-01-11T12:12:43.805164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"PREDICTION","metadata":{}},{"cell_type":"code","source":"# Assuming prediction is a function that returns a DataFrame with the predictions\nsubmission = 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)\n\n# Save the DataFrame to a CSV file\nsubmission.to_csv(\"submission.csv\", index=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-01-11T12:12:43.807977Z","iopub.execute_input":"2024-01-11T12:12:43.808829Z","iopub.status.idle":"2024-01-11T12:12:44.564746Z","shell.execute_reply.started":"2024-01-11T12:12:43.808761Z","shell.execute_reply":"2024-01-11T12:12:44.562658Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"execution":{"iopub.status.busy":"2024-01-11T12:12:44.566300Z","iopub.status.idle":"2024-01-11T12:12:44.566827Z","shell.execute_reply.started":"2024-01-11T12:12:44.566561Z","shell.execute_reply":"2024-01-11T12:12:44.566601Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"raw","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\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\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\nimport os\nfor 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"}}]}