{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":117682,"databundleVersionId":14443416,"sourceType":"competition"}],"dockerImageVersionId":31192,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","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","trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:42:35.160966Z","iopub.execute_input":"2025-11-16T13:42:35.161308Z","iopub.status.idle":"2025-11-16T13:42:40.772973Z","shell.execute_reply.started":"2025-11-16T13:42:35.161273Z","shell.execute_reply":"2025-11-16T13:42:40.771671Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport gc\nimport cv2\nimport math\nimport time\nimport glob\nimport random\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom pathlib import Path\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.cuda.amp import autocast, GradScaler\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:43:52.73171Z","iopub.execute_input":"2025-11-16T13:43:52.73236Z","iopub.status.idle":"2025-11-16T13:43:52.739072Z","shell.execute_reply.started":"2025-11-16T13:43:52.732328Z","shell.execute_reply":"2025-11-16T13:43:52.737505Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"CONFIG = {\n    \"image_path\": \"/kaggle/input/vesuvius-challenge-surface-detection/train_images/\",\n    \"label_path\": \"/kaggle/input/vesuvius-challenge-surface-detection/train_labels/\",\n    \"train_csv\": \"/kaggle/input/vesuvius-challenge-surface-detection/train.csv\",\n    \"patch_size\": 64,\n    \"batch_size\": 4,\n    \"epochs\": 3,\n    \"lr\": 1e-4,\n    \"num_workers\": 2,\n}\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:43:58.440717Z","iopub.execute_input":"2025-11-16T13:43:58.441058Z","iopub.status.idle":"2025-11-16T13:43:58.446157Z","shell.execute_reply.started":"2025-11-16T13:43:58.441029Z","shell.execute_reply":"2025-11-16T13:43:58.445198Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def set_seed(seed=42):\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n\nset_seed()\n\ndef load_volume(path):\n    return cv2.imread(path, cv2.IMREAD_UNCHANGED)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:44:02.709828Z","iopub.execute_input":"2025-11-16T13:44:02.710323Z","iopub.status.idle":"2025-11-16T13:44:02.723062Z","shell.execute_reply.started":"2025-11-16T13:44:02.71029Z","shell.execute_reply":"2025-11-16T13:44:02.721781Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class PapyrusDataset(Dataset):\n    def __init__(self, df, cfg):\n        self.df = df\n        self.cfg = cfg\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        row = self.df.iloc[idx]\n        img = np.load(row['image_path'])\n        mask = np.load(row['mask_path'])\n\n        img = torch.tensor(img).float().unsqueeze(0)\n        mask = torch.tensor(mask).float().unsqueeze(0)\n\n        return img, mask\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:44:14.150455Z","iopub.execute_input":"2025-11-16T13:44:14.150817Z","iopub.status.idle":"2025-11-16T13:44:14.157989Z","shell.execute_reply.started":"2025-11-16T13:44:14.15079Z","shell.execute_reply":"2025-11-16T13:44:14.156382Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class ConvBlock(nn.Module):\n    def __init__(self, in_c, out_c):\n        super().__init__()\n        self.net = nn.Sequential(\n            nn.Conv3d(in_c, out_c, 3, padding=1),\n            nn.ReLU(),\n            nn.Conv3d(out_c, out_c, 3, padding=1),\n            nn.ReLU(),\n        )\n\n    def forward(self, x):\n        return self.net(x)\n\n\nclass SimpleUNet(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.enc1 = ConvBlock(1, 16)\n        self.enc2 = ConvBlock(16, 32)\n        self.dec1 = ConvBlock(32, 16)\n        self.final = nn.Conv3d(16, 1, 1)\n\n    def forward(self, x):\n        x1 = self.enc1(x)\n        x2 = F.max_pool3d(x1, 2)\n        x2 = self.enc2(x2)\n        x = F.interpolate(x2, scale_factor=2)\n        x = self.dec1(x)\n        return torch.sigmoid(self.final(x))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:44:19.280407Z","iopub.execute_input":"2025-11-16T13:44:19.280727Z","iopub.status.idle":"2025-11-16T13:44:19.290419Z","shell.execute_reply.started":"2025-11-16T13:44:19.280703Z","shell.execute_reply":"2025-11-16T13:44:19.289257Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def dice_loss(pred, target):\n    smooth = 1e-5\n    pred = pred.view(-1)\n    target = target.view(-1)\n    inter = (pred * target).sum()\n    return 1 - (2 * inter + smooth) / (pred.sum() + target.sum() + smooth)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:44:44.759916Z","iopub.execute_input":"2025-11-16T13:44:44.760305Z","iopub.status.idle":"2025-11-16T13:44:44.766306Z","shell.execute_reply.started":"2025-11-16T13:44:44.76028Z","shell.execute_reply":"2025-11-16T13:44:44.765294Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def train_loop(model, loader, optimizer, scaler):\n    model.train()\n    losses = []\n\n    for imgs, masks in tqdm(loader):\n        imgs = imgs.cuda()\n        masks = masks.cuda()\n\n        optimizer.zero_grad()\n\n        with autocast():\n            preds = model(imgs)\n            loss = dice_loss(preds, masks)\n\n        scaler.scale(loss).backward()\n        scaler.step(optimizer)\n        scaler.update()\n\n        losses.append(loss.item())\n\n    return np.mean(losses)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:44:53.352056Z","iopub.execute_input":"2025-11-16T13:44:53.352442Z","iopub.status.idle":"2025-11-16T13:44:53.359917Z","shell.execute_reply.started":"2025-11-16T13:44:53.352416Z","shell.execute_reply":"2025-11-16T13:44:53.358615Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df = pd.read_csv(CONFIG[\"train_csv\"])\n\n# FIX: dataset uses .tif files, NOT .npy files\ntrain_df['image_path'] = train_df['id'].apply(\n    lambda x: f\"/kaggle/input/vesuvius-challenge-surface-detection/train_images/{x}.tif\"\n)\ntrain_df['mask_path'] = train_df['id'].apply(\n    lambda x: f\"/kaggle/input/vesuvius-challenge-surface-detection/train_labels/{x}.tif\"\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:45:12.170654Z","iopub.execute_input":"2025-11-16T13:45:12.171011Z","iopub.status.idle":"2025-11-16T13:45:12.184486Z","shell.execute_reply.started":"2025-11-16T13:45:12.170978Z","shell.execute_reply":"2025-11-16T13:45:12.183063Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tifffile\n\nclass PapyrusDataset(Dataset):\n    def __init__(self, df, cfg):\n        self.df = df\n        self.cfg = cfg\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        row = self.df.iloc[idx]\n\n        # Read .tif files\n        img = tifffile.imread(row['image_path'])\n        mask = tifffile.imread(row['mask_path'])\n\n        # Convert to torch tensors\n        img = torch.tensor(img).float().unsqueeze(0)      # (1,H,W)\n        mask = torch.tensor(mask).float().unsqueeze(0)    # (1,H,W)\n\n        return img, mask\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:45:15.030535Z","iopub.execute_input":"2025-11-16T13:45:15.030854Z","iopub.status.idle":"2025-11-16T13:45:15.264872Z","shell.execute_reply.started":"2025-11-16T13:45:15.030834Z","shell.execute_reply":"2025-11-16T13:45:15.263614Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_dataset = PapyrusDataset(train_df, CONFIG)\ntrain_loader = DataLoader(\n    train_dataset,\n    batch_size=CONFIG['batch_size'],\n    shuffle=True,\n    num_workers=CONFIG['num_workers']\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:45:26.730722Z","iopub.execute_input":"2025-11-16T13:45:26.731067Z","iopub.status.idle":"2025-11-16T13:45:26.736451Z","shell.execute_reply.started":"2025-11-16T13:45:26.73104Z","shell.execute_reply":"2025-11-16T13:45:26.735345Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = SimpleUNet().cuda()\noptimizer = torch.optim.Adam(model.parameters(), lr=CONFIG['lr'])\nscaler = GradScaler()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:45:29.620008Z","iopub.execute_input":"2025-11-16T13:45:29.620378Z","iopub.status.idle":"2025-11-16T13:45:29.707928Z","shell.execute_reply.started":"2025-11-16T13:45:29.620355Z","shell.execute_reply":"2025-11-16T13:45:29.706199Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport tifffile\nimport torch\nimport torch.nn.functional as F\n\nPATCH_SIZE = 256    # patch height/width\nSTRIDE = 256        # non-overlapping patches (fastest)\nDEVICE = \"cuda\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:45:44.981108Z","iopub.execute_input":"2025-11-16T13:45:44.981492Z","iopub.status.idle":"2025-11-16T13:45:44.988194Z","shell.execute_reply.started":"2025-11-16T13:45:44.981466Z","shell.execute_reply":"2025-11-16T13:45:44.987088Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def predict_patch(model, patch):\n    patch = torch.tensor(patch).float().unsqueeze(0).unsqueeze(0).to(DEVICE)\n    with torch.no_grad():\n        pred = model(patch)\n        pred = torch.sigmoid(pred)        # probability\n    return pred.squeeze().cpu().numpy()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:45:49.770943Z","iopub.execute_input":"2025-11-16T13:45:49.771705Z","iopub.status.idle":"2025-11-16T13:45:49.777687Z","shell.execute_reply.started":"2025-11-16T13:45:49.771672Z","shell.execute_reply":"2025-11-16T13:45:49.776046Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def predict_full_image(model, image_path):\n    img = tifffile.imread(image_path)     # shape: H x W\n\n    H, W = img.shape\n    full_pred = np.zeros((H, W), dtype=np.float32)\n    count = np.zeros((H, W), dtype=np.float32)\n\n    for y in range(0, H, STRIDE):\n        for x in range(0, W, STRIDE):\n\n            patch = img[y:y+PATCH_SIZE, x:x+PATCH_SIZE]\n\n            # Skip incomplete boundary patches\n            if patch.shape != (PATCH_SIZE, PATCH_SIZE):\n                continue\n\n            pred = predict_patch(model, patch)\n\n            full_pred[y:y+PATCH_SIZE, x:x+PATCH_SIZE] += pred\n            count[y:y+PATCH_SIZE, x:x+PATCH_SIZE] += 1\n\n    full_pred /= np.maximum(count, 1)\n    return full_pred\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:45:55.942335Z","iopub.execute_input":"2025-11-16T13:45:55.942651Z","iopub.status.idle":"2025-11-16T13:45:55.950681Z","shell.execute_reply.started":"2025-11-16T13:45:55.942628Z","shell.execute_reply":"2025-11-16T13:45:55.94938Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def mask_to_rle(mask):\n    flat = (mask.flatten() > 0.5).astype(np.uint8)\n    runs = []\n    last = 0\n\n    for i, val in enumerate(flat, 1):\n        if val and not last:\n            start = i\n        if not val and last:\n            end = i - 1\n            runs.append(f\"{start} {end-start+1}\")\n        last = val\n\n    if last:\n        runs.append(f\"{start} {len(flat)-start+1}\")\n\n    return \" \".join(runs)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:46:00.081827Z","iopub.execute_input":"2025-11-16T13:46:00.082291Z","iopub.status.idle":"2025-11-16T13:46:00.090787Z","shell.execute_reply.started":"2025-11-16T13:46:00.082256Z","shell.execute_reply":"2025-11-16T13:46:00.08924Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_dir = \"/kaggle/input/vesuvius-challenge-surface-detection/test_images\"\n\ntest_files = sorted([f for f in os.listdir(test_dir) if f.endswith(\".tif\")])\n\nresults = []\nfor f in test_files:\n    print(\"Processing:\", f)\n    path = os.path.join(test_dir, f)\n\n    pred = predict_full_image(model, path)\n\n    rle = mask_to_rle(pred)\n\n    img_id = f.replace(\".tif\", \"\")\n    results.append([img_id, rle])\n\nsubmission = pd.DataFrame(results, columns=[\"id\", \"crop\"])\nsubmission.to_csv(\"submission.csv\", index=False)\n\nprint(\"Saved REAL submission.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T13:46:03.764528Z","iopub.execute_input":"2025-11-16T13:46:03.764909Z","iopub.status.idle":"2025-11-16T13:46:03.785275Z","shell.execute_reply.started":"2025-11-16T13:46:03.764883Z","shell.execute_reply":"2025-11-16T13:46:03.783102Z"}},"outputs":[],"execution_count":null}]}