{"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 time\nnb_start = time.time()\n\nprint(\"\\n... installing libraries ...\\n\")\n\n!pip install -q \"/kaggle/input/pycocotools/pycocotools-2.0-cp37-cp37m-linux_x86_64.whl\"\n!pip install -q \"/kaggle/input/hpapytorchzoozip/pytorch_zoo-master\"\n!pip install -q \"../input/slidingwindow/slidingwindow\"\n!pip install -q \"../input/timm-pytorch-image-models/pytorch-image-models-master\"\n!pip install -q \"../input/hpacellsegmentatorraman/HPA-Cell-Segmentation\"\n\nlib_install = time.time() - nb_start\nprint(f\"Library install time:  {lib_install/60} minutes\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# global params\nnum_cpu = 2\n\n\nimport pandas as pd\n\npublic_test_df = pd.read_csv(\"../input/hpa-sample-submission-with-extra-metadata/updated_sample_submission.csv\")\npublic_test_df = public_test_df[[\"ID\", \"ImageWidth\", \"ImageHeight\", \"PredictionString\"]] #[:550]\n\nfull_test_df = pd.read_csv('../input/hpa-single-cell-image-classification/sample_submission.csv')\n\nsub_public_only = False\n\nif len(full_test_df) == 559:\n    commit_df = full_test_df[:5]\n    commit_df.to_csv('./sample_submission.csv', index=False)\n\nelse:\n    if sub_public_only:\n        df_public = public_test_df.copy()\n        df_public.to_csv('./sample_submission.csv', index=False)\n\n    else:\n        df_all = full_test_df.merge(public_test_df.drop_duplicates(), on=[\"ID\", \"ImageWidth\", \"ImageHeight\", \"PredictionString\"], \n                       how='left', indicator=True)\n\n        df_private = df_all[df_all['_merge'] == 'left_only']\n        df_private = df_private[[\"ID\", \"ImageWidth\", \"ImageHeight\", \"PredictionString\"]]\n\n        df_private.to_csv('./sample_submission.csv', index=False)\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Create Mask (deoxy)","metadata":{}},{"cell_type":"code","source":"%%writefile faster_hpa_cell_segment.py\n\n#mask_start = time.time()\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport numpy as np\nimport pandas as pd\nimport os\nfrom tqdm import tqdm\nimport imageio\n\nfrom hpacellseg.cellsegmentator import *\n\n\nclass CellSegmentator(object):\n    \"\"\"Uses pretrained DPN-Unet models to segment cells from images.\"\"\"\n\n    def __init__(\n        self,\n        nuclei_model=\"../input/hpacellsegmentatormodelweights/dpn_unet_nuclei_v1.pth\",\n        cell_model=\"../input/hpacellsegmentatormodelweights/dpn_unet_cell_3ch_v1.pth\",\n        scale_factor=1.0,\n        device=\"cuda\",\n        padding=False,\n        multi_channel_model=True,\n    ):\n        \"\"\"Class for segmenting nuclei and whole cells from confocal microscopy images.\n        It takes lists of images and returns the raw output from the\n        specified segmentation model. Models can be automatically\n        downloaded if they are not already available on the system.\n        When working with images from the Huan Protein Cell atlas, the\n        outputs from this class' methods are well combined with the\n        label functions in the utils module.\n        Note that for cell segmentation, there are two possible models\n        available. One that works with 2 channeled images and one that\n        takes 3 channels.\n        Keyword arguments:\n        nuclei_model -- A loaded torch nuclei segmentation model or the\n                        path to a file which contains such a model.\n                        If the argument is a path that points to a non-existant file,\n                        a pretrained nuclei_model is going to get downloaded to the\n                        specified path (default: './nuclei_model.pth').\n        cell_model -- A loaded torch cell segmentation model or the\n                      path to a file which contains such a model.\n                      The cell_model argument can be None if only nuclei\n                      are to be segmented (default: './cell_model.pth').\n        scale_factor -- How much to scale images before they are fed to\n                        segmentation models. Segmentations will be scaled back\n                        up by 1/scale_factor to match the original image\n                        (default: 0.25).\n        device -- The device on which to run the models.\n                  This should either be 'cpu' or 'cuda' or pointed cuda\n                  device like 'cuda:0' (default: 'cuda').\n        padding -- Whether to add padding to the images before feeding the\n                   images to the network. (default: False).\n        multi_channel_model -- Control whether to use the 3-channel cell model or not.\n                               If True, use the 3-channel model, otherwise use the\n                               2-channel version (default: True).\n        \"\"\"\n        if device != \"cuda\" and device != \"cpu\" and \"cuda\" not in device:\n            raise ValueError(f\"{device} is not a valid device (cuda/cpu)\")\n        if device != \"cpu\":\n            try:\n                assert torch.cuda.is_available()\n            except AssertionError:\n                print(\"No GPU found, using CPU.\", file=sys.stderr)\n                device = \"cpu\"\n        self.device = device\n\n        if isinstance(nuclei_model, str):\n            if not os.path.exists(nuclei_model):\n                print(\n                    f\"Could not find {nuclei_model}. Downloading it now\",\n                    file=sys.stderr,\n                )\n                download_with_url(NUCLEI_MODEL_URL, nuclei_model)\n            nuclei_model = torch.load(\n                nuclei_model, map_location=torch.device(self.device)\n            )\n        if isinstance(nuclei_model, torch.nn.DataParallel) and device == \"cpu\":\n            nuclei_model = nuclei_model.module\n\n        self.nuclei_model = nuclei_model.to(self.device).eval()\n\n        self.multi_channel_model = multi_channel_model\n        if isinstance(cell_model, str):\n            if not os.path.exists(cell_model):\n                print(\n                    f\"Could not find {cell_model}. Downloading it now\", file=sys.stderr\n                )\n                if self.multi_channel_model:\n                    download_with_url(MULTI_CHANNEL_CELL_MODEL_URL, cell_model)\n                else:\n                    download_with_url(TWO_CHANNEL_CELL_MODEL_URL, cell_model)\n            cell_model = torch.load(cell_model, map_location=torch.device(self.device))\n        self.cell_model = cell_model.to(self.device).eval()\n        self.scale_factor = scale_factor\n        self.padding = padding\n\n    def _image_conversion(self, images):\n        \"\"\"Convert/Format images to RGB image arrays list for cell predictions.\n        Intended for internal use only.\n        Keyword arguments:\n        images -- list of lists of image paths/arrays. It should following the\n                 pattern if with er channel input,\n                 [\n                     [microtubule_path0/image_array0, microtubule_path1/image_array1, ...],\n                     [er_path0/image_array0, er_path1/image_array1, ...],\n                     [nuclei_path0/image_array0, nuclei_path1/image_array1, ...]\n                 ]\n                 or if without er input,\n                 [\n                     [microtubule_path0/image_array0, microtubule_path1/image_array1, ...],\n                     None,\n                     [nuclei_path0/image_array0, nuclei_path1/image_array1, ...]\n                 ]\n        \"\"\"\n        microtubule_imgs, er_imgs, nuclei_imgs = images\n        if self.multi_channel_model:\n            if not isinstance(er_imgs, list):\n                raise ValueError(\"Please speicify the image path(s) for er channels!\")\n        else:\n            if not er_imgs is None:\n                raise ValueError(\n                    \"second channel should be None for two channel model predition!\"\n                )\n\n        if not isinstance(microtubule_imgs, list):\n            raise ValueError(\"The microtubule images should be a list\")\n        if not isinstance(nuclei_imgs, list):\n            raise ValueError(\"The microtubule images should be a list\")\n\n        if er_imgs:\n            if not len(microtubule_imgs) == len(er_imgs) == len(nuclei_imgs):\n                raise ValueError(\"The lists of images needs to be the same length\")\n        else:\n            if not len(microtubule_imgs) == len(nuclei_imgs):\n                raise ValueError(\"The lists of images needs to be the same length\")\n\n        if not all(isinstance(item, np.ndarray) for item in microtubule_imgs):\n            microtubule_imgs = [\n                os.path.expanduser(item) for _, item in enumerate(microtubule_imgs)\n            ]\n            nuclei_imgs = [\n                os.path.expanduser(item) for _, item in enumerate(nuclei_imgs)\n            ]\n\n            microtubule_imgs = list(\n                map(lambda item: imageio.imread(item), microtubule_imgs)\n            )\n            nuclei_imgs = list(map(lambda item: imageio.imread(item), nuclei_imgs))\n            if er_imgs:\n                er_imgs = [os.path.expanduser(item) for _, item in enumerate(er_imgs)]\n                er_imgs = list(map(lambda item: imageio.imread(item), er_imgs))\n\n        if not er_imgs:\n            er_imgs = [\n                np.zeros(item.shape, dtype=item.dtype)\n                for _, item in enumerate(microtubule_imgs)\n            ]\n        cell_imgs = list(\n            map(\n                lambda item: np.dstack((item[0], item[1], item[2])),\n                list(zip(microtubule_imgs, er_imgs, nuclei_imgs)),\n            )\n        )\n\n        return cell_imgs\n\n    def pred_nuclei(self, images):\n        \"\"\"Predict the nuclei segmentation.\n        Keyword arguments:\n        images -- A list of image arrays or a list of paths to images.\n                  If as a list of image arrays, the images could be 2d images\n                  of nuclei data array only, or must have the nuclei data in\n                  the blue channel; If as a list of file paths, the images\n                  could be RGB image files or gray scale nuclei image file\n                  paths.\n        Returns:\n        predictions -- A list of predictions of nuclei segmentation for each nuclei image.\n        \"\"\"\n\n        def _preprocess(image):\n            if isinstance(image, str):\n                image = imageio.imread(image)\n            self.target_shape = image.shape\n            if len(image.shape) == 2:\n                image = np.dstack((image, image, image))\n            image = transform.rescale(image, self.scale_factor, multichannel=True)\n            nuc_image = np.dstack((image[..., 2], image[..., 2], image[..., 2]))\n            if self.padding:\n                rows, cols = nuc_image.shape[:2]\n                self.scaled_shape = rows, cols\n                nuc_image = cv2.copyMakeBorder(\n                    nuc_image,\n                    32,\n                    (32 - rows % 32),\n                    32,\n                    (32 - cols % 32),\n                    cv2.BORDER_REFLECT,\n                )\n            nuc_image = nuc_image.transpose([2, 0, 1])\n            return nuc_image\n\n        def _segment_helper(imgs):\n            with torch.no_grad():\n                mean = torch.as_tensor(NORMALIZE[\"mean\"], device=self.device)\n                std = torch.as_tensor(NORMALIZE[\"std\"], device=self.device)\n                imgs = torch.tensor(imgs).float()\n                imgs = imgs.to(self.device)\n                imgs = imgs.sub_(mean[:, None, None]).div_(std[:, None, None])\n\n                imgs = self.nuclei_model(imgs)\n                imgs = F.softmax(imgs, dim=1)\n                return imgs\n\n        preprocessed_imgs = list(map(_preprocess, images))\n        bs = 24\n        predictions = []\n        for i in range(0, len(preprocessed_imgs), bs):\n            start = i\n            end = min(len(preprocessed_imgs), i+bs)\n            x = preprocessed_imgs[start:end]\n            pred = _segment_helper(x).cpu().numpy()\n            predictions.append(pred)\n        predictions = list(np.concatenate(predictions, axis=0))\n        predictions = map(util.img_as_ubyte, predictions)\n        predictions = list(map(self._restore_scaling_padding, predictions))\n        return predictions\n\n    def _restore_scaling_padding(self, n_prediction):\n        \"\"\"Restore an image from scaling and padding.\n        This method is intended for internal use.\n        It takes the output from the nuclei model as input.\n        \"\"\"\n        n_prediction = n_prediction.transpose([1, 2, 0])\n        if self.padding:\n            n_prediction = n_prediction[\n                32 : 32 + self.scaled_shape[0], 32 : 32 + self.scaled_shape[1], ...\n            ]\n        if not self.scale_factor == 1:\n            n_prediction[..., 0] = 0\n            n_prediction = cv2.resize(\n                n_prediction,\n                (self.target_shape[0], self.target_shape[1]),\n                interpolation=cv2.INTER_AREA,\n            )\n        return n_prediction\n\n    def pred_cells(self, images, precombined=False):\n        \"\"\"Predict the cell segmentation for a list of images.\n        Keyword arguments:\n        images -- list of lists of image paths/arrays. It should following the\n                  pattern if with er channel input,\n                  [\n                      [microtubule_path0/image_array0, microtubule_path1/image_array1, ...],\n                      [er_path0/image_array0, er_path1/image_array1, ...],\n                      [nuclei_path0/image_array0, nuclei_path1/image_array1, ...]\n                  ]\n                  or if without er input,\n                  [\n                      [microtubule_path0/image_array0, microtubule_path1/image_array1, ...],\n                      None,\n                      [nuclei_path0/image_array0, nuclei_path1/image_array1, ...]\n                  ]\n                  The ER channel is required when multichannel is True\n                  and required to be None when multichannel is False.\n                  The images needs to be of the same size.\n        precombined -- If precombined is True, the list of images is instead supposed to be\n                       a list of RGB numpy arrays (default: False).\n        Returns:\n        predictions -- a list of predictions of cell segmentations.\n        \"\"\"\n\n        def _preprocess(image):\n            self.target_shape = image.shape\n            if not len(image.shape) == 3:\n                raise ValueError(\"image should has 3 channels\")\n            cell_image = transform.rescale(image, self.scale_factor, multichannel=True)\n            if self.padding:\n                rows, cols = cell_image.shape[:2]\n                self.scaled_shape = rows, cols\n                cell_image = cv2.copyMakeBorder(\n                    cell_image,\n                    32,\n                    (32 - rows % 32),\n                    32,\n                    (32 - cols % 32),\n                    cv2.BORDER_REFLECT,\n                )\n            cell_image = cell_image.transpose([2, 0, 1])\n            return cell_image\n\n        def _segment_helper(imgs):\n            with torch.no_grad():\n                mean = torch.as_tensor(NORMALIZE[\"mean\"], device=self.device)\n                std = torch.as_tensor(NORMALIZE[\"std\"], device=self.device)\n                imgs = torch.tensor(imgs).float()\n                imgs = imgs.to(self.device)\n                imgs = imgs.sub_(mean[:, None, None]).div_(std[:, None, None])\n\n                imgs = self.cell_model(imgs)\n                imgs = F.softmax(imgs, dim=1)\n                return imgs\n\n        if not precombined:\n            images = self._image_conversion(images)\n        preprocessed_imgs = list(map(_preprocess, images))\n        bs = 24\n        predictions = []\n        for i in range(0, len(preprocessed_imgs), bs):\n            start = i\n            end = min(len(preprocessed_imgs), i+bs)\n            x = preprocessed_imgs[start:end]\n            pred = _segment_helper(x).cpu().numpy()\n            predictions.append(pred)\n        predictions = list(np.concatenate(predictions, axis=0))\n        predictions = map(self._restore_scaling_padding, predictions)\n        predictions = list(map(util.img_as_ubyte, predictions))\n\n        return predictions\n    \n    \nimport os.path\nimport urllib\nimport zipfile\n\nimport numpy as np\nimport scipy.ndimage as ndi\nfrom skimage import transform\nfrom skimage import filters, measure, segmentation\nfrom skimage.morphology import (binary_erosion, closing, disk,\n                                remove_small_holes, remove_small_objects)\n\nHIGH_THRESHOLD = 0.4\nLOW_THRESHOLD = HIGH_THRESHOLD - 0.25\n\n\ndef download_with_url(url_string, file_path, unzip=False):\n    \"\"\"Download file with a link.\"\"\"\n    with urllib.request.urlopen(url_string) as response, open(\n        file_path, \"wb\"\n    ) as out_file:\n        data = response.read()  # a `bytes` object\n        out_file.write(data)\n\n    if unzip:\n        with zipfile.ZipFile(file_path, \"r\") as zip_ref:\n            zip_ref.extractall(os.path.dirname(file_path))\n\n\ndef __fill_holes(image):\n    \"\"\"Fill_holes for labelled image, with a unique number.\"\"\"\n    boundaries = segmentation.find_boundaries(image)\n    image = np.multiply(image, np.invert(boundaries))\n    image = ndi.binary_fill_holes(image > 0)\n    image = ndi.label(image)[0]\n    return image\n\n\n\n\n\ndef label_cell(nuclei_pred, cell_pred):\n    \"\"\"Label the cells and the nuclei.\n    Keyword arguments:\n    nuclei_pred -- a 3D numpy array of a prediction from a nuclei image.\n    cell_pred -- a 3D numpy array of a prediction from a cell image.\n    Returns:\n    A tuple containing:\n    nuclei-label -- A nuclei mask data array.\n    cell-label  -- A cell mask data array.\n    0's in the data arrays indicate background while a continous\n    strech of a specific number indicates the area for a specific\n    cell.\n    The same value in cell mask and nuclei mask refers to the identical cell.\n    NOTE: The nuclei labeling from this function will be sligthly\n    different from the values in :func:`label_nuclei` as this version\n    will use information from the cell-predictions to make better\n    estimates.\n    \"\"\"\n    def __wsh(\n        mask_img,\n        threshold,\n        border_img,\n        seeds,\n        threshold_adjustment=0.35,\n        small_object_size_cutoff=10,\n    ):\n        img_copy = np.copy(mask_img)\n        m = seeds * border_img  # * dt\n        img_copy[m <= threshold + threshold_adjustment] = 0\n        img_copy[m > threshold + threshold_adjustment] = 1\n        img_copy = img_copy.astype(np.bool)\n        img_copy = remove_small_objects(img_copy, small_object_size_cutoff).astype(\n            np.uint8\n        )\n\n        mask_img[mask_img <= threshold] = 0\n        mask_img[mask_img > threshold] = 1\n        mask_img = mask_img.astype(np.bool)\n        mask_img = remove_small_holes(mask_img, 63)\n        mask_img = remove_small_objects(mask_img, 1).astype(np.uint8)\n        markers = ndi.label(img_copy, output=np.uint32)[0]\n        labeled_array = segmentation.watershed(\n            mask_img, markers, mask=mask_img, watershed_line=True\n        )\n        return labeled_array\n\n    nuclei_label = __wsh(\n        nuclei_pred[..., 2] / 255.0,\n        0.4,\n        1 - (nuclei_pred[..., 1] + cell_pred[..., 1]) / 255.0 > 0.05,\n        nuclei_pred[..., 2] / 255,\n        threshold_adjustment=-0.25,\n        small_object_size_cutoff=32,\n    )\n\n    # for hpa_image, to remove the small pseduo nuclei\n    nuclei_label = remove_small_objects(nuclei_label, 157)\n    nuclei_label = measure.label(nuclei_label)\n    # this is to remove the cell borders' signal from cell mask.\n    # could use np.logical_and with some revision, to replace this func.\n    # Tuned for segmentation hpa images\n    threshold_value = max(0.22, filters.threshold_otsu(cell_pred[..., 2] / 255) * 0.5)\n    # exclude the green area first\n    cell_region = np.multiply(\n        cell_pred[..., 2] / 255 > threshold_value,\n        np.invert(np.asarray(cell_pred[..., 1] / 255 > 0.05, dtype=np.int8)),\n    )\n    sk = np.asarray(cell_region, dtype=np.int8)\n    distance = np.clip(cell_pred[..., 2], 255 * threshold_value, cell_pred[..., 2])\n    cell_label = segmentation.watershed(-distance, nuclei_label, mask=sk)\n    cell_label = remove_small_objects(cell_label, 344).astype(np.uint8)\n    selem = disk(2)\n    cell_label = closing(cell_label, selem)\n    cell_label = __fill_holes(cell_label)\n    # this part is to use green channel, and extend cell label to green channel\n    # benefit is to exclude cells clear on border but without nucleus\n    sk = np.asarray(\n        np.add(\n            np.asarray(cell_label > 0, dtype=np.int8),\n            np.asarray(cell_pred[..., 1] / 255 > 0.05, dtype=np.int8),\n        )\n        > 0,\n        dtype=np.int8,\n    )\n    cell_label = segmentation.watershed(-distance, cell_label, mask=sk)\n    cell_label = __fill_holes(cell_label)\n    cell_label = np.asarray(cell_label > 0, dtype=np.uint8)\n    cell_label = measure.label(cell_label)\n    cell_label = remove_small_objects(cell_label, 344)\n    cell_label = measure.label(cell_label)\n    cell_label = np.asarray(cell_label, dtype=np.uint16)\n    nuclei_label = np.multiply(cell_label > 0, nuclei_label) > 0\n    nuclei_label = measure.label(nuclei_label)\n    nuclei_label = remove_small_objects(nuclei_label, 157)\n    nuclei_label = np.multiply(cell_label, nuclei_label > 0)\n\n    return nuclei_label, cell_label\n\n\ncellsegmentor = CellSegmentator()\n\ndata_df = pd.read_csv('./sample_submission.csv')\ndata_size = len(data_df)\nbs = 240\n\ndef load_images(df : pd.DataFrame, root='../input/hpa-single-cell-image-classification/test/'):\n    gray = []\n    rgb = []\n    for i, row in tqdm(df.iterrows(), total=len(df)):\n        r = os.path.join(root, f'{row.ID}_red.png')\n        y = os.path.join(root, f'{row.ID}_yellow.png')\n        b = os.path.join(root, f'{row.ID}_blue.png')\n        r = cv2.imread(r, 0)\n        y = cv2.imread(y, 0)\n        b = cv2.imread(b, 0)\n        gray_image = cv2.resize(b, (512, 512))\n        rgb_image = cv2.resize(np.stack((r, y, b), axis=2), (512, 512))\n        gray.append(gray_image)\n        rgb.append(rgb_image)\n    return gray, rgb\n        \n    \nfor i in range(0, data_size, bs):\n    print('!!!!', i, '!!!!')\n    start = i\n    end = min(len(data_df), start + bs)\n    test_df = data_df[start:end]\n    print(len(test_df))\n    print('---- start load images ----')\n    gray, rgb = load_images(test_df)\n    print(len(gray))\n    print('---- finish load images ----')\n    print('---- start pred nuclei ----')\n    nuc_segmentations = cellsegmentor.pred_nuclei(gray)\n    print('---- finish pred nucrei ----')\n    print('---- start pred cells ----')\n    cell_segmentations = cellsegmentor.pred_cells(rgb, precombined=True)\n    print('---- finish pred cells ----')\n\n\n    #root = '/temp/hpa_test_mask/'\n    root = '/kaggle/working/hpa_test_mask'\n    os.makedirs(root, exist_ok=True)\n    \n\n    print('---- start mask write ----')\n    for data_id, nuc_seg, cell_seg in zip(test_df.ID.to_list(), nuc_segmentations, cell_segmentations):\n        nuc, cell = label_cell(nuc_seg, cell_seg)\n        #np.save(os.path.join(root, f'{data_id}_nuc.npy'), nuc)\n        #np.save(os.path.join(root, f'{data_id}_cell.npy'), cell)\n        imageio.imwrite(os.path.join(root, f'{data_id}_predictedmask.png'), cell)\n        \n        \n        #_, cell = utils.label_cell(nuc_seg, cell_seg)\n        #save_fn = data_id.replace('red.png','predictedmask.png')\n        #imageio.imwrite(os.path.join(output_dir, save_fn), cell)\n        \n    print('---- finish mask write ----')\n    \n#mask_gen = time.time() - mask_start\n#print(f\"Mask generation time:  {mask_gen/60} minutes\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nmask_start = time.time()\n!python faster_hpa_cell_segment.py\nmask_gen = time.time() - mask_start","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Inference - PuzzleCam","metadata":{}},{"cell_type":"code","source":"import sys\nsys.path.append('/kaggle/input/hpasrc/src')\nimport copy\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch.utils.data import DataLoader\nfrom core.networks import *\nfrom tools.general.io_utils import *\nfrom tools.general.time_utils import *\nfrom tools.ai.demo_utils import *\nfrom tools.ai.torch_utils import *\nfrom tools.ai.augment_utils import *\nfrom tools.ai.randaugment import *\n\nimport timm\nimport pandas as pd\nfrom albumentations import Compose\nimport slidingwindow as sw\nfrom tqdm import tqdm\nfrom multiprocessing import Pool\n\ndevice = ('cuda' if torch.cuda.is_available() else 'cpu')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"###############################################################################\n# hpa dataset\n###############################################################################\n\nclass HPADataset(torch.utils.data.Dataset):\n    def __init__(self, root_dir, ids, labels, resize=None, transforms=None):\n        self.root_dir = root_dir\n        self.ids = ids\n        self.resize = resize\n        self.transforms = transforms\n        self.labels = labels\n\n    def __len__(self):\n        return len(self.ids)\n\n    def __getitem__(self, item):\n        _ids = self.ids[item]\n        colors = ['red', 'green', 'blue']\n        img = [cv2.imread(os.path.join(self.root_dir, args.domain, f'{_ids}_{color}.png'), cv2.IMREAD_GRAYSCALE)\n               for color in colors]\n        image = np.dstack(img)\n\n        if self.resize:\n            image = cv2.resize(image, (self.resize, self.resize))\n\n        # setting the target to one hot encoded form\n        if args.domain == \"train\":\n            y = self.labels[item]\n            y = y.split('|')\n            y = list(map(int, y))\n            return image, y, _ids\n\n        elif args.domain == \"test\":\n            return image, [-1], _ids\n        \n###################################################################################\n# Network\n###################################################################################\n\nclass Classifier(nn.Module, ABC_Model):\n    def __init__(self, model_name, num_classes=20, mode='fix'):\n        super().__init__()\n\n        if model_name == 'densenet121':\n            num_features = 1024\n        elif model_name == 'resnest101e':\n            num_features = 2048\n        elif model_name == 'resnest26d':\n            num_features = 2048\n        elif model_name == 'nf_regnet_b1':\n            num_features = 960\n        elif model_name == 'xception':\n            num_features = 2048\n            \n        self.num_classes = num_classes\n        self.model = timm.create_model(model_name, pretrained=False, num_classes=0, global_pool='')\n        self.classifierr = nn.Conv2d(num_features, num_classes, 1, bias=False)\n        self.initialize([self.classifierr])\n\n    def forward(self, x, with_cam=False, with_cam_prob=False):\n        x = self.model(x)\n        if with_cam:\n            features = self.classifierr(x)\n            logits = self.global_average_pooling_2d(features)\n            return logits, features\n\n        elif with_cam_prob:\n            features = self.classifierr(x)\n            x = self.global_average_pooling_2d(x, keepdims=True)\n            logits = self.classifierr(x).view(-1, self.num_classes)\n            return logits, features\n\n        else:\n            x = self.global_average_pooling_2d(x, keepdims=True)\n            logits = self.classifierr(x).view(-1, self.num_classes)\n            return logits","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#################################################################################################\n# prediction\n#################################################################################################\n\ndef get_cam(models, ori_image, scale, ori_w, ori_h):\n    # preprocessing\n    image = copy.deepcopy(ori_image)\n    image = cv2.resize(image, (round(ori_w * scale), round(ori_h * scale)), interpolation=cv2.INTER_AREA)\n    image = image.transpose((2, 0, 1))\n\n    image = torch.from_numpy(image)\n    flipped_image = image.flip(-1)\n    flipped_image2 = image.flip(-2)\n\n    images = torch.stack([image, flipped_image, flipped_image2])\n    images = images.to(device, dtype=torch.float)\n\n    # inferenece\n    output_list = []\n    cams_list = []\n    for model in models:\n        output, features = model(images, with_cam_prob=True)\n        output = (output[0] + output[1] + output[2]) / 3\n        output = torch.sigmoid(output)\n        output_list.append(output)\n\n        # postprocessing\n        cams = F.relu(features)\n        cams = (cams[0] + cams[1].flip(-1) + cams[2].flip(-2)) / 3\n        cams_list.append(cams)\n        \n    output = torch.mean(torch.stack(output_list), dim=0)\n    cams = torch.mean(torch.stack(cams_list), dim=0)\n\n    return cams, output\n\n\n\ndef run_prediction(models, dataset, pred_dir):\n    \n    scales = [float(scale) for scale in args.scales.split(',')]\n\n    with torch.no_grad():\n        length = len(dataset)\n        tk1 = tqdm(dataset, total=int(len(dataset)))\n        for (ori_image, label, image_id) in tk1:\n            _ori_w, _ori_h = ori_image.shape[0], ori_image.shape[1]\n\n            ##########################\n            image = ori_image.copy()\n            tmp = image  # for drawing a rectangle\n            windows = sw.generate(image, sw.DimOrder.HeightWidthChannel, args.crop_size, args.sw_overlap)\n\n            sourceWidth = image.shape[sw.DimOrder.HeightWidthChannel.index('w')]\n            sourceHeight = image.shape[sw.DimOrder.HeightWidthChannel.index('h')]\n            sums = np.zeros((args.CLASS, sourceHeight, sourceWidth), dtype=np.float)\n            counts = np.zeros((sourceHeight, sourceWidth), dtype=np.uint32)\n\n            # Do stuff with the generated windows\n            image_probs = []\n            for windowNum, window in enumerate(windows):\n                subset = image[window.indices()]\n\n                ori_w, ori_h = subset.shape[0], subset.shape[1]\n\n                strided_size = get_strided_size((ori_h, ori_w), 4)\n                strided_up_size = get_strided_up_size((ori_h, ori_w), 16)\n\n                cams_list = []\n                probs_list = []\n                for scale in scales:\n                    cams , probs = get_cam(models, subset, scale,  ori_w, ori_h)\n                    cams_list.append(cams)\n                    probs_list.append(probs)\n\n                hr_cams_list = [resize_for_tensors(cams.unsqueeze(0), strided_up_size)[0] for cams in cams_list]\n                hr_cams = torch.sum(torch.stack(hr_cams_list), dim=0)[:, :ori_h, :ori_w]\n                hc = hr_cams.cpu().numpy()\n\n                out_prob,_ = torch.max(torch.stack(probs_list), dim=0)\n                image_probs.append(out_prob)\n\n                x = window.x\n                y = window.y\n                w = window.w\n                h = window.h\n\n                windowIndices = window.indices(False)\n                sumsView = sums[:,  y:y+h, x:x+w,]\n                countsView = counts[windowIndices]\n\n                sumsView[:] += hc\n                countsView[:] += 1\n\n            # Use the sums and the counts to compute the mean values\n            for dim in range(0, args.CLASS):\n                sums[dim, :, :] /= counts\n\n            img_prob, _ = torch.max(torch.stack(image_probs), dim=0)\n            img_prob = img_prob.cpu().numpy()\n            ############################################################################################################\n\n            ori_image_vis = ori_image.astype(np.uint8)\n            label_cams = []\n            save_img = False\n            save_npy = True\n\n            for i, label_cam in enumerate(sums):\n                # normalize cam\n                norm_label_cam = (label_cam - np.min(label_cam)) / (200 - np.min(label_cam))\n                norm_label_cam *= img_prob[i]\n\n                if save_img:\n                    img = np.stack((norm_label_cam,) * 3, -1) * 255.\n                    img = img.astype(np.uint8)\n                    img = cv2.applyColorMap(img, cv2.COLORMAP_JET)\n\n                    image = cv2.addWeighted(ori_image_vis, 0.5, img, 0.5, 0)\n\n                    if i in label:\n                        cv2.imwrite(f'{pred_dir}{image_id}-{i}-true-{label}-prob{img_prob[i]:0.4f}.png', image)\n                    else:\n                        cv2.imwrite(f'{pred_dir}{image_id}-{i}-noLabel-prob{img_prob[i]:0.4f}.png', image)\n\n                if save_npy:\n                    norm_label_cam = cv2.resize(norm_label_cam, (256, 256))\n                    norm_label_cam = norm_label_cam.astype(np.float16)\n                    label_cams.append(norm_label_cam)\n\n            if save_npy:\n                np.save(f'{pred_dir}{image_id}.npy', label_cams)\n\n    ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_dir = '/kaggle/input/hpa-single-cell-image-classification'\nmask_dir = '/kaggle/working/hpa_test_mask'\n\ndf_sub_org = pd.read_csv('./sample_submission.csv')\ndf_sub = pd.read_csv('./sample_submission.csv')\ndf_sub[\"Label\"] = -1\n\nlabels = df_sub[\"Label\"].tolist()\nids = df_sub[\"ID\"].tolist()\n\nAUGMENTATIONS_TEST = Compose([], p=1)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_model(architecture, tag):\n    \n    model_path = '/kaggle/input/puzzleweights/' + f'{tag}.pth'\n    \n    # load model\n    model = Classifier(architecture, args.CLASS, mode=args.mode)\n    model = model.cuda()\n    model.eval()\n    model.load_state_dict(torch.load(model_path))\n    print('[i] Architecture is {}'.format(architecture))\n    \n    return model","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred1_start = time.time()\n\nclass args:\n    num_workers = num_cpu\n    mode = 'normal'\n    scales = '0.75,1.0,1.5'\n    domain = 'test'\n    CLASS = 19\n    img_size = 1280\n    crop_size = 1024\n    sw_overlap = 0.25\n\n\nmodels1024 = []\n\npred_dir = create_directory(f'/kaggle/working/predictions/models1024/')\ndataset = HPADataset(data_dir, ids, labels, args.img_size, AUGMENTATIONS_TEST)\n\narchitecture = 'xception'\ntag = 'xceptionPuzzle1024crops1280resizeadamwmllcombinedbs6_best_ep10'\nmodel = load_model(architecture, tag)\nmodels1024.append(model)\n\nrun_prediction(models1024, dataset, pred_dir)\n\npred1_gen = time.time() - pred1_start\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#################################################################################################\n# generate submission\n#################################################################################################\nimport base64\nimport os\nimport typing as t\nimport zlib\nfrom itertools import groupby\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom pycocotools import _mask as coco_mask\nfrom pycocotools import mask as mutils\nfrom tqdm import tqdm\n\n#################################################################################################\n\ndef coco_rle_encode(mask):\n    rle = {'counts': [], 'size': list(mask.shape)}\n    counts = rle.get('counts')\n    for i, (value, elements) in enumerate(groupby(mask.ravel(order='F'))):\n        if i == 0 and value == 1:\n            counts.append(0)\n        counts.append(len(list(elements)))\n    return rle\n\n\ndef encode_binary_mask(mask: np.ndarray) -> t.Text:\n    \"\"\"Converts a binary mask into OID challenge encoding ascii text.\"\"\"\n\n    # check input mask --\n    if mask.dtype != np.bool:\n        raise ValueError(\n            \"encode_binary_mask expects a binary mask, received dtype == %s\" %\n            mask.dtype)\n\n    mask = np.squeeze(mask)\n    if len(mask.shape) != 2:\n        raise ValueError(\n            \"encode_binary_mask expects a 2d mask, received shape == %s\" %\n            mask.shape)\n\n    # convert input mask to expected COCO API input --\n    mask_to_encode = mask.reshape(mask.shape[0], mask.shape[1], 1)\n    mask_to_encode = mask_to_encode.astype(np.uint8)\n    mask_to_encode = np.asfortranarray(mask_to_encode)\n\n    # RLE encode mask --\n    encoded_mask = coco_mask.encode(mask_to_encode)[0][\"counts\"]\n\n    # compress and base64 encoding --\n    binary_str = zlib.compress(encoded_mask, zlib.Z_BEST_COMPRESSION)\n    base64_str = base64.b64encode(binary_str)\n    return str(base64_str, 'utf-8')\n\n\ndef get_rles_from_mask(mask):\n    rle_list = []\n    sub_rle_list = []\n    mask_ids = np.unique(mask)\n    for val in mask_ids:\n        if val == 0:\n            continue\n        binary_mask = np.where(mask == val, 1, 0).astype(bool)\n        rle = coco_rle_encode(binary_mask)\n        rle_list.append(rle)\n\n        sub_rle = encode_binary_mask(binary_mask)\n        sub_rle_list.append(sub_rle)\n\n    return sub_rle_list, rle_list, mask.shape[0], mask.shape[1]\n\n\n\ndef mask_labelling(idx):\n    image_id = df_sub.iloc[idx].ID\n    img_w = df_sub.iloc[idx].ImageWidth\n    img_h = df_sub.iloc[idx].ImageHeight\n    \n    colors = ['red', 'green', 'blue']\n    img = [cv2.imread(os.path.join('../input/hpa-single-cell-image-classification/test/', f'{image_id}_{color}.png'), cv2.IMREAD_GRAYSCALE)\n           for color in colors]\n    img = np.dstack(img)\n\n    \n    CAMs = np.zeros((19, 256, 256))       \n    try:\n        cam1024 = np.load(f'./predictions/models1024/{image_id}.npy').astype(np.float32)\n        cam1024[np.isnan(cam1024)] = 0\n        CAMs = cam1024\n\n    except Exception as e:\n        print(e)\n        CAMs = np.zeros((19, 256, 256))\n\n    ###########################################\n    # load segmentation mask\n    ###########################################\n    try:\n        mask_path = mask_dir + \"/\" + image_id + '_predictedmask.png'\n        cell_mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)\n        cell_mask = cv2.resize(cell_mask, (img_w, img_h), interpolation=cv2.INTER_NEAREST)\n    except Exception as e:\n        print(e)\n        cell_mask = np.zeros((img_w, img_h))\n    \n    ############################################\n    # iterate for each predicted box \n    # over every segmented box\n    ############################################\n    if cell_mask.max() != 0:\n        pred_seg_ids = []\n        pred_seg_clss = []\n        pred_seg_confs = []\n        pred_seg_rles = []\n        cell_idxs = []\n        coco_seg_rles = []\n\n        sub_rles, seg_coco_rles, seg_height, seg_width = get_rles_from_mask(cell_mask)\n\n        crop_imgs = []\n        crop_probas = []\n        for class_id in range(args.CLASS):\n            for cell_idx in range(1, cell_mask.max() + 1):\n                cls_cam = CAMs[class_id, ...].astype(np.float32)\n                cls_cam = cv2.resize(cls_cam, (cell_mask.shape[0], cell_mask.shape[1]))\n                result = cls_cam * (cell_mask == cell_idx)\n\n                pred_seg_id = image_id\n                pred_seg_cls = class_id\n                pred_seg_conf = np.max(result)\n                pred_seg_rle = sub_rles[cell_idx-1]\n                coco_seg_rle = seg_coco_rles[cell_idx - 1]\n\n                pred_seg_ids.append(pred_seg_id)\n                pred_seg_clss.append(pred_seg_cls)\n                pred_seg_confs.append(pred_seg_conf)\n                pred_seg_rles.append(pred_seg_rle)\n                cell_idxs.append(cell_idx)\n                coco_seg_rles.append(coco_seg_rle)\n\n\n        df = pd.DataFrame()\n        df['ID'] = pred_seg_ids\n        df['cls'] = pred_seg_clss\n        df['conf'] = pred_seg_confs\n        df['rles'] = pred_seg_rles\n        df['cell_num'] = cell_idxs\n        \n        return df\n\n\n    else: \n        df = pd.DataFrame()\n        df['ID'] = image_id\n        df['cls'] = 0\n        df['conf'] = 0\n        df['rles'] = ''\n        df['cell_num'] = 0\n\n        return df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_start = time.time()\n\nix = np.arange(0, len(df_sub))\nix = ix.tolist()\n\nseg_boxes = []\nfor i in tqdm(ix, total=len(ix)):\n    x = mask_labelling(i)\n    seg_boxes.append(x)\n\nappended_data = pd.concat(seg_boxes)\nprint('prediction complete..')\n\nsub_gen = time.time() - sub_start","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Format predictions","metadata":{}},{"cell_type":"code","source":"def combine(r):\n    cls = r['cls']\n    conf = r['conf']\n    enc = r['rles']\n    classes = [str(cls) + ' ' + str(conf) + ' ' + enc]\n    return ' '.join(classes)\n\nappended_data['pred'] = appended_data[['cls', 'conf', 'rles']].apply(combine, axis=1)\n\nsubm = appended_data.groupby(['ID'])['pred'].apply(lambda x: ' '.join(x)).reset_index()\n\nsub = pd.merge(\n    full_test_df,\n    subm,\n    how=\"left\",\n    left_on='ID',\n    right_on='ID',\n)\n\n\nsub.head(20)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def isNaN(num):\n    return num != num\n\n\nfor i, row in sub.iterrows():\n    if isNaN(row['pred']): continue\n    sub.PredictionString.loc[i] = row['pred']\n\nsub = sub[df_sub_org.columns]\n\nsub.head(20)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub.to_csv(f'submission.csv', index=False)\nprint('Submission formatting complete !')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Clean working dir","metadata":{}},{"cell_type":"code","source":"######################################################################\nimport shutil\n\npred_dir_path = './predictions'\nmask_dir_path = './hpa_test_mask'\n\ntry:\n    shutil.rmtree(pred_dir_path)\n    shutil.rmtree(mask_dir_path)\nexcept OSError as e:\n    print(e)\n\n\n######################################################################\nprint(f\"Library install time:  {lib_install/60} minutes\")\nprint(f\"Mask generation time:  {mask_gen/60} minutes\")\nprint(f\"Prediction time (1):   {pred1_gen/60} minutes\")\nprint(f\"Submission time:       {sub_gen/60} minutes\")\nprint(f\"Total Notebook time:   {(time.time() - nb_start)/60} minutes\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}