{"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":"# pip install librosa","metadata":{"execution":{"iopub.status.busy":"2023-04-27T11:12:48.110646Z","iopub.execute_input":"2023-04-27T11:12:48.11157Z","iopub.status.idle":"2023-04-27T11:12:48.117449Z","shell.execute_reply.started":"2023-04-27T11:12:48.111519Z","shell.execute_reply":"2023-04-27T11:12:48.116151Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from pydub import AudioSegment\nimport os\nfrom pydub.effects import low_pass_filter, normalize, high_pass_filter\nfrom pydub import AudioSegment\nimport pydub\nfrom torch.utils.data import Dataset\nimport torch\nimport librosa\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport io\nfrom PIL import Image\nimport glob\nimport pandas as pd\nimport torch.nn as nn\nfrom torch import Tensor\nfrom collections import OrderedDict\nfrom functools import partial\nfrom typing import Callable, Optional\nimport cv2\nfrom torchvision import transforms\nimport sys\nimport torchaudio\nfrom pydub import AudioSegment\nimport numpy as np\nfrom scipy import signal\nimport shutil","metadata":{"execution":{"iopub.status.busy":"2023-04-27T11:12:48.119631Z","iopub.execute_input":"2023-04-27T11:12:48.12002Z","iopub.status.idle":"2023-04-27T11:12:48.131907Z","shell.execute_reply.started":"2023-04-27T11:12:48.119985Z","shell.execute_reply":"2023-04-27T11:12:48.130898Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"matplotlib.use(\"Agg\")","metadata":{"execution":{"iopub.status.busy":"2023-04-27T11:12:48.13358Z","iopub.execute_input":"2023-04-27T11:12:48.134108Z","iopub.status.idle":"2023-04-27T11:12:48.146601Z","shell.execute_reply.started":"2023-04-27T11:12:48.134055Z","shell.execute_reply":"2023-04-27T11:12:48.145655Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def crop_audio(audio_path, save_path, segment_duration=6000):\n    if os.path.exists(save_path) is False:\n        os.mkdir(save_path)\n    name_dir = os.listdir(audio_path)\n    for classes_name in name_dir:        \n        format = classes_name.split('.')[-1]\n        audio_path = os .path.join(audio_path, classes_name)\n        audio = AudioSegment.from_file(audio_path, format=format,duration=18)\n        \n        # get the total duration of the audio in milliseconds\n        audio_duration = len(audio)\n        # initialize the start and end time of each segment\n        start_time = 0\n        end_time = segment_duration\n        # create a list to store the segmented audio files\n        segments = []\n        # iterate over the audio file and segment it\n        while end_time <= audio_duration:\n            # extract the segment and append it to the list\n            segment = audio[start_time:end_time]\n            segments.append(segment)\n            # update the start and end time for the next segment\n            start_time = end_time\n            end_time += segment_duration\n        # segments = segments[:3]\n        # save each segment to a new audio file\n        k = 5\n        for i, segment in enumerate(segments):\n            name = classes_name.split('.')[0]\n            segment.export(save_path + \"/{}_{}.{}\".format(name, k, format))\n            k += 5\n","metadata":{"execution":{"iopub.status.busy":"2023-04-27T11:12:48.149072Z","iopub.execute_input":"2023-04-27T11:12:48.150599Z","iopub.status.idle":"2023-04-27T11:12:48.162652Z","shell.execute_reply.started":"2023-04-27T11:12:48.150538Z","shell.execute_reply":"2023-04-27T11:12:48.160926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def acquire2_melspectrogram(original_file_path, save_file_path):\n    if not os.path.exists(save_file_path):\n        os.mkdir(save_file_path)        \n    with torch.no_grad():\n        for file in os.listdir(original_file_path):\n            file_path = os.path.join(original_file_path, file)\n            audio = AudioSegment.from_file(file_path)\n            audio = audio[:5000]  # Get the first 5 seconds\n            samples = np.array(audio.get_array_of_samples())\n            sample_rate = audio.frame_rate\n\n            # Compute the spectrogram using the Short-Time Fourier Transform (STFT)\n            f, t, Sxx = signal.spectrogram(samples, sample_rate, nfft=1024, nperseg=1024, noverlap=512)\n\n            # Convert the spectrogram to decibels\n            m_db = 10 * np.log10(Sxx)\n\n            fig, ax = plt.subplots(figsize=(6, 6))\n            img = ax.pcolormesh(t, f, m_db)\n\n            fig.canvas.draw()  \n\n            buffer = io.BytesIO()  \n            fig.savefig(buffer, format=\"jpg\")  \n\n            data = buffer.getvalue()  \n\n            img = Image.open(io.BytesIO(data))  \n            img = np.asarray(img)\n            img_name = file.split('.')[0]\n            cv2.imwrite(save_file_path + \"/{}.jpg\".format(img_name), img)\n            plt.clf()  \n            buffer.close()  \n            plt.cla()\n            plt.close('all')\n","metadata":{"execution":{"iopub.status.busy":"2023-04-27T11:12:48.164337Z","iopub.execute_input":"2023-04-27T11:12:48.16482Z","iopub.status.idle":"2023-04-27T11:12:48.179493Z","shell.execute_reply.started":"2023-04-27T11:12:48.16475Z","shell.execute_reply":"2023-04-27T11:12:48.178192Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class MyDataSet(Dataset):\n\n\n    def __init__(self, images_path: list, images_class: list, transform=None):\n        self.images_path = images_path\n        self.images_class = images_class\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.images_path)\n\n    def __getitem__(self, item):\n        img = Image.open(self.images_path[item])\n\n        if img.mode != 'RGB':\n            raise ValueError(\"image: {} isn't RGB mode.\".format(self.images_path[item]))\n        label = self.images_class[item]\n\n        if self.transform is not None:\n            img = self.transform(img)\n        return img, label\n\n    @staticmethod\n    def collate_fn(batch):\n        images, labels = tuple(zip(*batch))\n        images = torch.stack(images, dim=0)\n        labels = torch.as_tensor(labels)\n        return images, labels","metadata":{"execution":{"iopub.status.busy":"2023-04-27T11:12:48.181322Z","iopub.execute_input":"2023-04-27T11:12:48.18214Z","iopub.status.idle":"2023-04-27T11:12:48.196668Z","shell.execute_reply.started":"2023-04-27T11:12:48.182085Z","shell.execute_reply":"2023-04-27T11:12:48.195176Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def drop_path(x, drop_prob: float = 0., training: bool = False):\n    \"\"\"\n    Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).\n    \"Deep Networks with Stochastic Depth\", https://arxiv.org/pdf/1603.09382.pdf\n\n    This function is taken from the rwightman.\n    It can be seen here:\n    https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py#L140\n    \"\"\"\n    if drop_prob == 0. or not training:\n        return x\n    keep_prob = 1 - drop_prob\n    shape = (x.shape[0],) + (1,) * (x.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets\n    random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)\n    random_tensor.floor_()  # binarize\n    output = x.div(keep_prob) * random_tensor\n    return output\n\n\nclass DropPath(nn.Module):\n    \"\"\"\n    Drop paths (Stochastic Depth) per sample  (when applied in main path of residual blocks).\n    \"Deep Networks with Stochastic Depth\", https://arxiv.org/pdf/1603.09382.pdf\n    \"\"\"\n    def __init__(self, drop_prob=None):\n        super(DropPath, self).__init__()\n        self.drop_prob = drop_prob\n\n    def forward(self, x):\n        return drop_path(x, self.drop_prob, self.training)\n\n\nclass ConvBNAct(nn.Module):\n    def __init__(self,\n                 in_planes: int,\n                 out_planes: int,\n                 kernel_size: int = 3,\n                 stride: int = 1,\n                 groups: int = 1,\n                 norm_layer: Optional[Callable[..., nn.Module]] = None,\n                 activation_layer: Optional[Callable[..., nn.Module]] = None):\n        super(ConvBNAct, self).__init__()\n\n        padding = (kernel_size - 1) // 2\n        if norm_layer is None:\n            norm_layer = nn.BatchNorm2d\n        if activation_layer is None:\n            activation_layer = nn.SiLU  # alias Swish  (torch>=1.7)\n\n        self.conv = nn.Conv2d(in_channels=in_planes,\n                              out_channels=out_planes,\n                              kernel_size=kernel_size,\n                              stride=stride,\n                              padding=padding,\n                              groups=groups,\n                              bias=False)\n\n        self.bn = norm_layer(out_planes)\n        self.act = activation_layer()\n\n    def forward(self, x):\n        result = self.conv(x)\n        result = self.bn(result)\n        result = self.act(result)\n\n        return result\n\n\nclass SqueezeExcite(nn.Module):\n    def __init__(self,\n                 input_c: int,   # block input channel\n                 expand_c: int,  # block expand channel\n                 se_ratio: float = 0.25):\n        super(SqueezeExcite, self).__init__()\n        squeeze_c = int(input_c * se_ratio)\n        self.conv_reduce = nn.Conv2d(expand_c, squeeze_c, 1)\n        self.act1 = nn.SiLU()  # alias Swish\n        self.conv_expand = nn.Conv2d(squeeze_c, expand_c, 1)\n        self.act2 = nn.Sigmoid()\n\n    def forward(self, x: Tensor) -> Tensor:\n        scale = x.mean((2, 3), keepdim=True)\n        scale = self.conv_reduce(scale)\n        scale = self.act1(scale)\n        scale = self.conv_expand(scale)\n        scale = self.act2(scale)\n        return scale * x\n\n\nclass MBConv(nn.Module):\n    def __init__(self,\n                 kernel_size: int,\n                 input_c: int,\n                 out_c: int,\n                 expand_ratio: int,\n                 stride: int,\n                 se_ratio: float,\n                 drop_rate: float,\n                 norm_layer: Callable[..., nn.Module]):\n        super(MBConv, self).__init__()\n\n        if stride not in [1, 2]:\n            raise ValueError(\"illegal stride value.\")\n\n        self.has_shortcut = (stride == 1 and input_c == out_c)\n\n        activation_layer = nn.SiLU  # alias Swish\n        expanded_c = input_c * expand_ratio\n\n\n        assert expand_ratio != 1\n        # Point-wise expansion\n        self.expand_conv = ConvBNAct(input_c,\n                                     expanded_c,\n                                     kernel_size=1,\n                                     norm_layer=norm_layer,\n                                     activation_layer=activation_layer)\n\n        # Depth-wise convolution\n        self.dwconv = ConvBNAct(expanded_c,\n                                expanded_c,\n                                kernel_size=kernel_size,\n                                stride=stride,\n                                groups=expanded_c,\n                                norm_layer=norm_layer,\n                                activation_layer=activation_layer)\n\n        self.se = SqueezeExcite(input_c, expanded_c, se_ratio) if se_ratio > 0 else nn.Identity()\n\n\n        self.project_conv = ConvBNAct(expanded_c,\n                                      out_planes=out_c,\n                                      kernel_size=1,\n                                      norm_layer=norm_layer,\n                                      activation_layer=nn.Identity)  # 注意这里没有激活函数，所有传入Identity\n\n        self.out_channels = out_c\n\n\n        self.drop_rate = drop_rate\n        if self.has_shortcut and drop_rate > 0:\n            self.dropout = DropPath(drop_rate)\n\n    def forward(self, x: Tensor) -> Tensor:\n        result = self.expand_conv(x)\n        result = self.dwconv(result)\n        result = self.se(result)\n        result = self.project_conv(result)\n\n        if self.has_shortcut:\n            if self.drop_rate > 0:\n                result = self.dropout(result)\n            result += x\n\n        return result\n\n\nclass FusedMBConv(nn.Module):\n    def __init__(self,\n                 kernel_size: int,\n                 input_c: int,\n                 out_c: int,\n                 expand_ratio: int,\n                 stride: int,\n                 se_ratio: float,\n                 drop_rate: float,\n                 norm_layer: Callable[..., nn.Module]):\n        super(FusedMBConv, self).__init__()\n\n        assert stride in [1, 2]\n        assert se_ratio == 0\n\n        self.has_shortcut = stride == 1 and input_c == out_c\n        self.drop_rate = drop_rate\n\n        self.has_expansion = expand_ratio != 1\n\n        activation_layer = nn.SiLU  # alias Swish\n        expanded_c = input_c * expand_ratio\n\n        # 只有当expand ratio不等于1时才有expand conv\n        if self.has_expansion:\n            # Expansion convolution\n            self.expand_conv = ConvBNAct(input_c,\n                                         expanded_c,\n                                         kernel_size=kernel_size,\n                                         stride=stride,\n                                         norm_layer=norm_layer,\n                                         activation_layer=activation_layer)\n\n            self.project_conv = ConvBNAct(expanded_c,\n                                          out_c,\n                                          kernel_size=1,\n                                          norm_layer=norm_layer,\n                                          activation_layer=nn.Identity)  # 注意没有激活函数\n        else:\n\n            self.project_conv = ConvBNAct(input_c,\n                                          out_c,\n                                          kernel_size=kernel_size,\n                                          stride=stride,\n                                          norm_layer=norm_layer,\n                                          activation_layer=activation_layer)  # 注意有激活函数\n\n        self.out_channels = out_c\n\n\n        self.drop_rate = drop_rate\n        if self.has_shortcut and drop_rate > 0:\n            self.dropout = DropPath(drop_rate)\n\n    def forward(self, x: Tensor) -> Tensor:\n        if self.has_expansion:\n            result = self.expand_conv(x)\n            result = self.project_conv(result)\n        else:\n            result = self.project_conv(x)\n\n        if self.has_shortcut:\n            if self.drop_rate > 0:\n                result = self.dropout(result)\n\n            result += x\n\n        return result\n\n\nclass EfficientNetV2(nn.Module):\n    def __init__(self,\n                 model_cnf: list,\n                 num_classes: int = 1000,\n                 num_features: int = 1280,\n                 dropout_rate: float = 0.3,\n                 drop_connect_rate: float = 0.3):\n        super(EfficientNetV2, self).__init__()\n\n        for cnf in model_cnf:\n            assert len(cnf) == 8\n\n        norm_layer = partial(nn.BatchNorm2d, eps=1e-3, momentum=0.1)\n\n        stem_filter_num = model_cnf[0][4]\n\n        self.stem = ConvBNAct(3,\n                              stem_filter_num,\n                              kernel_size=3,\n                              stride=2,\n                              norm_layer=norm_layer)  # 激活函数默认是SiLU\n\n        total_blocks = sum([i[0] for i in model_cnf])\n        block_id = 0\n        blocks = []\n        for cnf in model_cnf:\n            repeats = cnf[0]\n            op = FusedMBConv if cnf[-2] == 0 else MBConv\n            for i in range(repeats):\n                blocks.append(op(kernel_size=cnf[1],\n                                 input_c=cnf[4] if i == 0 else cnf[5],\n                                 out_c=cnf[5],\n                                 expand_ratio=cnf[3],\n                                 stride=cnf[2]if i == 0 else 1,\n                                 se_ratio=cnf[-1],\n                                 drop_rate=drop_connect_rate * block_id / total_blocks,\n                                 norm_layer=norm_layer))\n                block_id += 1\n        self.blocks = nn.Sequential(*blocks)\n\n        head_input_c = model_cnf[-1][-3]\n        head = OrderedDict()\n\n        head.update({\"project_conv\": ConvBNAct(head_input_c,\n                                               num_features,\n                                               kernel_size=1,\n                                               norm_layer=norm_layer)})  # 激活函数默认是SiLU\n\n        head.update({\"avgpool\": nn.AdaptiveAvgPool2d(1)})\n        head.update({\"flatten\": nn.Flatten()})\n\n        if dropout_rate > 0:\n            head.update({\"dropout\": nn.Dropout(p=dropout_rate, inplace=True)})\n        head.update({\"classifier\": nn.Linear(num_features, num_classes)})\n\n        self.head = nn.Sequential(head)\n\n        # initial weights\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                nn.init.kaiming_normal_(m.weight, mode=\"fan_out\")\n                if m.bias is not None:\n                    nn.init.zeros_(m.bias)\n            elif isinstance(m, nn.BatchNorm2d):\n                nn.init.ones_(m.weight)\n                nn.init.zeros_(m.bias)\n            elif isinstance(m, nn.Linear):\n                nn.init.normal_(m.weight, 0, 0.01)\n                nn.init.zeros_(m.bias)\n\n    def forward(self, x: Tensor) -> Tensor:\n        x = self.stem(x)\n        x = self.blocks(x)\n        x = self.head(x)\n\n        return x\n\n\ndef efficientnetv2_s(num_classes: int = 1000):\n    \"\"\"\n    EfficientNetV2\n    https://arxiv.org/abs/2104.00298\n    \"\"\"\n    # train_size: 300, eval_size: 384\n\n    # repeat, kernel, stride, expansion, in_c, out_c, operator, se_ratio\n    model_config = [[2, 3, 1, 1, 24, 24, 0, 0],\n                    [4, 3, 2, 4, 24, 48, 0, 0],\n                    [4, 3, 2, 4, 48, 64, 0, 0],\n                    [6, 3, 2, 4, 64, 128, 1, 0.25],\n                    [9, 3, 1, 6, 128, 160, 1, 0.25],\n                    [15, 3, 2, 6, 160, 256, 1, 0.25]]\n                    #[15, 3, 2, 6, 256, 512, 1, 0.25],\n                    #[15, 3, 1, 8, 512, 1024, 1, 0.25]]\n\n    model = EfficientNetV2(model_cnf=model_config,\n                           num_classes=num_classes,\n                           dropout_rate=0.2)\n    return model\n\n\ndef efficientnetv2_m(num_classes: int = 1000):\n    \"\"\"\n    EfficientNetV2\n    https://arxiv.org/abs/2104.00298\n    \"\"\"\n    # train_size: 384, eval_size: 480\n\n    # repeat, kernel, stride, expansion, in_c, out_c, operator, se_ratio\n    model_config = [[3, 3, 1, 1, 24, 24, 0, 0],\n                    [5, 3, 2, 4, 24, 48, 0, 0],\n                    [5, 3, 2, 4, 48, 80, 0, 0],\n                    [7, 3, 2, 4, 80, 160, 1, 0.25],\n                    [14, 3, 1, 6, 160, 176, 1, 0.25],\n                    [18, 3, 2, 6, 176, 304, 1, 0.25],\n                    [5, 3, 1, 6, 304, 512, 1, 0.25]]\n\n    model = EfficientNetV2(model_cnf=model_config,\n                           num_classes=num_classes,\n                           dropout_rate=0)\n    return model\n\n\ndef efficientnetv2_l(num_classes: int = 1000):\n    \"\"\"\n    EfficientNetV2\n    https://arxiv.org/abs/2104.00298\n    \"\"\"\n    # train_size: 384, eval_size: 480\n\n    # repeat, kernel, stride, expansion, in_c, out_c, operator, se_ratio\n    model_config = [[4, 3, 1, 1, 32, 32, 0, 0],\n                    [7, 3, 2, 4, 32, 64, 0, 0],\n                    [7, 3, 2, 4, 64, 96, 0, 0],\n                    [10, 3, 2, 4, 96, 192, 1, 0.25],\n                    [19, 3, 1, 6, 192, 224, 1, 0.25],\n                    [25, 3, 2, 6, 224, 384, 1, 0.25],\n                    [7, 3, 1, 6, 384, 640, 1, 0.25]]\n\n    model = EfficientNetV2(model_cnf=model_config,\n                           num_classes=num_classes,\n                           dropout_rate=0.4)\n    return model\n","metadata":{"execution":{"iopub.status.busy":"2023-04-27T11:12:48.226974Z","iopub.execute_input":"2023-04-27T11:12:48.227776Z","iopub.status.idle":"2023-04-27T11:12:48.283564Z","shell.execute_reply.started":"2023-04-27T11:12:48.227734Z","shell.execute_reply":"2023-04-27T11:12:48.282339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"init_file = '/kaggle/input/birdclef-2023/test_soundscapes/'\nsave_path = '/kaggle/temp/temporary_audio'\ntemp_path = '/kaggle/temp/'\nif not os.path.exists('/kaggle/temp/'):\n    os.mkdir('/kaggle/temp/')\ncrop_audio(init_file, save_path,)\nos.listdir('/kaggle/temp/temporary_audio')","metadata":{"execution":{"iopub.status.busy":"2023-04-27T11:12:48.286473Z","iopub.execute_input":"2023-04-27T11:12:48.287021Z","iopub.status.idle":"2023-04-27T11:12:48.936864Z","shell.execute_reply.started":"2023-04-27T11:12:48.286968Z","shell.execute_reply":"2023-04-27T11:12:48.935297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"save_img_path = '/kaggle/temp/temporary_img/'\nacquire2_melspectrogram(save_path, save_img_path)\n# shutil.rmtree(save_path)","metadata":{"execution":{"iopub.status.busy":"2023-04-27T11:12:48.939446Z","iopub.execute_input":"2023-04-27T11:12:48.940018Z","iopub.status.idle":"2023-04-27T11:12:50.862455Z","shell.execute_reply.started":"2023-04-27T11:12:48.93995Z","shell.execute_reply":"2023-04-27T11:12:50.860836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndef detect(img_path):\n    device = torch.device(\"cpu\" if torch.cuda.is_available() else \"cpu\")\n\n    img_size = {\"s\": [300, 300],  # train_size, val_size\n                \"m\": [224, 224],\n                \"l\": [384, 480]}\n    num_model = \"m\"\n\n    data_transform = transforms.Compose(\n        [transforms.Resize(img_size[num_model][1]),\n         transforms.CenterCrop(img_size[num_model][1]),\n         transforms.ToTensor(),\n         transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])\n\n    # load image\n    assert os.path.exists(img_path), \"file: '{}' dose not exist.\".format(img_path)\n    name = os.path.splitext(os.path.basename(img_path))[0]\n    img = Image.open(img_path)\n#    plt.imshow(img)\n    # [N, C, H, W]\n    img = data_transform(img)\n    # expand batch dimension\n    img = torch.unsqueeze(img, dim=0)\n\n\n\n    # create model\n    model = efficientnetv2_s(num_classes=264).to(device)\n    # load model weights\n    model_weight_path = \"/kaggle/input/weight/model-best.pth\"\n    model.load_state_dict(torch.load(model_weight_path, map_location=device))\n    model.eval()\n    with torch.no_grad():\n        # predict class\n        output = torch.squeeze(model(img.to(device))).to(device)\n        predict = torch.softmax(output, dim=0)\n    return predict, name\n\nwith open(f\"submission_df.csv\", \"w\") as f:\n    imgfold = save_img_path   \n    df = pd.read_csv('/kaggle/input/birdsong/list.csv', usecols=['label'])\n    img_dir_all = os.listdir(imgfold)\n    labels = ['row_id']\n    for label in df['label']:\n        labels.append(label)\n    labels_str = ', '.join(map(str, labels))\n    f.write(f\"{labels_str}\\n\")\n\n    for img_name in img_dir_all:\n        img_path = os.path.join(imgfold, img_name)\n        res, name = detect(img_path)\n        res = np.array(res)\n\n        \n        res_str = ', '.join(map(str, res))\n        f.write(f\"{name}, {res_str}\\n\")\n        f.flush()\nshutil.rmtree(temp_path)\n# if os.path.exists('/kaggle/temp/state.db'):\n  #   os.remove('/kaggle/temp/state.db')","metadata":{"execution":{"iopub.status.busy":"2023-04-27T11:12:50.864877Z","iopub.execute_input":"2023-04-27T11:12:50.865306Z","iopub.status.idle":"2023-04-27T11:12:52.860638Z","shell.execute_reply.started":"2023-04-27T11:12:50.865262Z","shell.execute_reply":"2023-04-27T11:12:52.859183Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/working/submission_df.csv')\ndf.head()\n","metadata":{"execution":{"iopub.status.busy":"2023-04-27T11:12:52.865262Z","iopub.execute_input":"2023-04-27T11:12:52.866429Z","iopub.status.idle":"2023-04-27T11:12:52.907638Z","shell.execute_reply.started":"2023-04-27T11:12:52.866368Z","shell.execute_reply":"2023-04-27T11:12:52.906477Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv(\"submission.csv\", index=False)\n'/kaggle/working/submission.csv'\nif os.path.exists('/kaggle/working/submission_df.csv'):\n    os.remove('/kaggle/working/submission_df.csv')","metadata":{"execution":{"iopub.status.busy":"2023-04-27T11:12:52.909372Z","iopub.execute_input":"2023-04-27T11:12:52.909726Z","iopub.status.idle":"2023-04-27T11:12:52.919831Z","shell.execute_reply.started":"2023-04-27T11:12:52.909693Z","shell.execute_reply":"2023-04-27T11:12:52.918361Z"},"trusted":true},"execution_count":null,"outputs":[]}]}