{"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":"gpu","dataSources":[{"sourceId":99552,"databundleVersionId":13190393,"sourceType":"competition"}],"dockerImageVersionId":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import time\nimport os\nimport torch\nimport pandas as pd\nfrom skimage import io, transform\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\nimport torch.nn.functional as F\n\nfrom scipy import ndimage\nfrom glob import glob\nimport pandas as pd\nfrom pathlib import Path\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n# Ignore warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n#Innat https://www.kaggle.com/code/ipythonx/cervical-spine-fracture-detection-quick-eda\n\nfrom random import sample\nimport nibabel as nib\n\nplt.ion()   # interactive mode","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T22:06:31.549067Z","iopub.execute_input":"2025-08-04T22:06:31.549268Z","iopub.status.idle":"2025-08-04T22:06:40.839285Z","shell.execute_reply.started":"2025-08-04T22:06:31.54925Z","shell.execute_reply":"2025-08-04T22:06:40.838647Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install nnunet -q","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T22:06:40.839898Z","iopub.execute_input":"2025-08-04T22:06:40.840275Z","iopub.status.idle":"2025-08-04T22:08:12.271455Z","shell.execute_reply.started":"2025-08-04T22:06:40.840247Z","shell.execute_reply":"2025-08-04T22:08:12.270731Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Competition constants\nID_COL = 'SeriesInstanceUID'\nLABEL_COLS = [\n    'Left Infraclinoid Internal Carotid Artery',\n    'Right Infraclinoid Internal Carotid Artery',\n    'Left Supraclinoid Internal Carotid Artery',\n    'Right Supraclinoid Internal Carotid Artery',\n    'Left Middle Cerebral Artery',\n    'Right Middle Cerebral Artery',\n    'Anterior Communicating Artery',\n    'Left Anterior Cerebral Artery',\n    'Right Anterior Cerebral Artery',\n    'Left Posterior Communicating Artery',\n    'Right Posterior Communicating Artery',\n    'Basilar Tip',\n    'Other Posterior Circulation',\n    'Aneurysm Present',\n]\n\nDICOM_TAG_ALLOWLIST = [\n    'BitsAllocated', 'BitsStored', 'Columns', 'FrameOfReferenceUID', 'HighBit',\n    'ImageOrientationPatient', 'ImagePositionPatient', 'InstanceNumber', 'Modality',\n    'PatientID', 'PhotometricInterpretation', 'PixelRepresentation', 'PixelSpacing',\n    'PlanarConfiguration', 'RescaleIntercept', 'RescaleSlope', 'RescaleType', 'Rows',\n    'SOPClassUID', 'SOPInstanceUID', 'SamplesPerPixel', 'SliceThickness',\n    'SpacingBetweenSlices', 'StudyInstanceUID', 'TransferSyntaxUID',\n]\n\n# Model configuration\nTARGET_SIZE = (64, 64, 64)  # Reduced size for memory efficiency\nDEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T22:08:12.273557Z","iopub.execute_input":"2025-08-04T22:08:12.273801Z","iopub.status.idle":"2025-08-04T22:08:12.336283Z","shell.execute_reply.started":"2025-08-04T22:08:12.273779Z","shell.execute_reply":"2025-08-04T22:08:12.335736Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"TRAIN = True                     # ← set to True when you want to train\nRAW_DIR = Path(\"/kaggle/input/rsna-intracranial-aneurysm-detection\")\nCWD = Path('/kaggle/working/')\nPRETRAINED_DIR = Path(\"/kaggle/input/\")# used when TRAIN=False\nSERIES_DIR = RAW_DIR / \"series\"\nSEGMENTATIONS_DIR = RAW_DIR / \"segmentations\"\nEXPORT_DIR = Path(\"./\")                                    # artefacts will be saved here\n\nft_nnunet_dir = CWD / \"ft_nnunet\"\nRAW_DATA = ft_nnunet_dir / \"nnUNet/nnunet/nnUNet_raw_data_base/nnUNet_raw\"\nREPO_DIR = ft_nnunet_dir / \"nnUNet\"\n\ntask_id = 552\ntask_name = \"RSNAaneurysm\"\ntask_folder = f\"Dataset{task_id:03d}_{task_name}\"\n\n# We define all the necessary paths\nbase_dir = RAW_DATA / task_folder\nimagesTr = base_dir / 'imagesTr' # path to training images\nlabelsTr = base_dir / 'labelsTr' # path to training labels\ntest_dir = base_dir / 'imagesTs' # path to test images\nmain_dir =ft_nnunet_dir / 'nnUNet/nnunet' # path to main directory\ntrained_model_dir = main_dir / 'nnUNet_trained_models' # path to trained models\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T22:08:12.337296Z","iopub.execute_input":"2025-08-04T22:08:12.337892Z","iopub.status.idle":"2025-08-04T22:08:12.359871Z","shell.execute_reply.started":"2025-08-04T22:08:12.337863Z","shell.execute_reply":"2025-08-04T22:08:12.359204Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ft_nnunet_dir.mkdir(parents=True, exist_ok=True)\n%cd $ft_nnunet_dir\n!git clone https://github.com/MIC-DKFZ/nnUNet.git\n!git clone https://github.com/NVIDIA/apex\n\n# repository dir is the path of the github folder\n# respository_dir = nnunet_dir / 'nnUNet'\n%cd $REPO_DIR\n!pip install -e\n!pip install --upgrade git+https://github.com/nanohanno/hiddenlayer.git@bugfix/get_trace_graph#egg=hiddenlayer","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T22:08:12.360712Z","iopub.execute_input":"2025-08-04T22:08:12.360927Z","iopub.status.idle":"2025-08-04T22:08:21.454537Z","shell.execute_reply.started":"2025-08-04T22:08:12.36091Z","shell.execute_reply":"2025-08-04T22:08:21.45359Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"base_dir.mkdir(parents=True, exist_ok=True)\nimagesTr.mkdir(parents=True, exist_ok=True)\nlabelsTr.mkdir(parents=True, exist_ok=True)\ntest_dir.mkdir(parents=True, exist_ok=True)\ntrained_model_dir.mkdir(parents=True, exist_ok=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T22:08:21.455725Z","iopub.execute_input":"2025-08-04T22:08:21.456019Z","iopub.status.idle":"2025-08-04T22:08:21.461488Z","shell.execute_reply.started":"2025-08-04T22:08:21.45598Z","shell.execute_reply":"2025-08-04T22:08:21.460928Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nos.environ[\"nnUNet_raw\"] = \"/kaggle/working/ft_nnunet/nnUNet/nnunet/nnUNet_raw_data_base/nnUNet_raw\"\nos.environ[\"nnUNet_preprocessed\"] = \"/kaggle/working/ft_nnunet/nnUNet/nnunet/preprocessed\"\nos.environ[\"nnUNet_results\"] = \"/kaggle/working/ft_nnunet/nnUNet/nnunet/nnUNet_results\"\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T22:08:21.462195Z","iopub.execute_input":"2025-08-04T22:08:21.462384Z","iopub.status.idle":"2025-08-04T22:08:21.478352Z","shell.execute_reply.started":"2025-08-04T22:08:21.462369Z","shell.execute_reply":"2025-08-04T22:08:21.477416Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"FLIPPED_IDS = {\n    \"1.2.826.0.1.3680043.8.498.10035643165968342618460849823699311381\",\n    \"1.2.826.0.1.3680043.8.498.10540586847553109495238524904638776495\",\n    \"1.2.826.0.1.3680043.8.498.10557880026294057874761753231388788828\",\n    \"1.2.826.0.1.3680043.8.498.10759842474698331813589731619457567641\",\n    \"1.2.826.0.1.3680043.8.498.10865391592895615633871689438787039175\",\n    \"1.2.826.0.1.3680043.8.498.11140496970152788589837488009637704168\",\n    \"1.2.826.0.1.3680043.8.498.11641438607169452758239778414614826230\",\n    \"1.2.826.0.1.3680043.8.498.11924949819899884502738782576851659426\",\n    \"1.2.826.0.1.3680043.8.498.12283701604837916064212605259577798418\",\n    \"1.2.826.0.1.3680043.8.498.12780116426159918728945213894055885771\",\n    \"1.2.826.0.1.3680043.8.498.12873050136415197430227722045995986358\",\n    \"1.2.826.0.1.3680043.8.498.12896910506681881306246412668919668702\",\n    \"1.2.826.0.1.3680043.8.498.12898332622076283462996059479076432725\",\n    \"1.2.826.0.1.3680043.8.498.12904246053955178641505906243733756576\",\n    \"1.2.826.0.1.3680043.8.498.13789305723712362238118274295587312089\",\n    \"1.2.826.0.1.3680043.8.498.15111820005882064793593034423469604305\",\n    \"1.2.826.0.1.3680043.8.498.15412988336827906186857260013885503248\",\n    \"1.2.826.0.1.3680043.8.498.16386250344855221757144432829845114733\",\n    \"1.2.826.0.1.3680043.8.498.20627322154402566045565159680288078498\",\n    \"1.2.826.0.1.3680043.8.498.21260453249991608190728327379762807665\",\n    \"1.2.826.0.1.3680043.8.498.23047023542526806696555440426928375679\",\n    \"1.2.826.0.1.3680043.8.498.27693546360513068451517048347207987807\",\n    \"1.2.826.0.1.3680043.8.498.31897325247898403027455884342546675049\",\n    \"1.2.826.0.1.3680043.8.498.32250259987224176174516959348681094310\",\n    \"1.2.826.0.1.3680043.8.498.34439485184360273751379923196589017042\",\n    \"1.2.826.0.1.3680043.8.498.35327124657045713676192746001247576881\",\n    \"1.2.826.0.1.3680043.8.498.35378146560080702211693278243609271022\",\n    \"1.2.826.0.1.3680043.8.498.35633450896661854179640200212683653363\",\n    \"1.2.826.0.1.3680043.8.498.37086262716517957668471635372810376638\",\n    \"1.2.826.0.1.3680043.8.498.38904475631578710113273863766282479811\",\n    \"1.2.826.0.1.3680043.8.498.50275403170194436966991630938339966596\",\n    \"1.2.826.0.1.3680043.8.498.52363954882447190271251269039176558430\",\n    \"1.2.826.0.1.3680043.8.498.53901203212732811892702239112353256979\",\n    \"1.2.826.0.1.3680043.8.498.58839417089022860359638460482101293080\",\n    \"1.2.826.0.1.3680043.8.498.63610643988023140802787347827023957721\",\n    \"1.2.826.0.1.3680043.8.498.67357468192986203292275214887760889253\",\n    \"1.2.826.0.1.3680043.8.498.67364033194715249441864636235467322768\",\n    \"1.2.826.0.1.3680043.8.498.68356160898101066850726244725552676010\",\n    \"1.2.826.0.1.3680043.8.498.76127804295106714014266113869285421890\",\n    \"1.2.826.0.1.3680043.8.498.79099213587801933936080747802403048718\",\n    \"1.2.826.0.1.3680043.8.498.80114244849666367523293067199486077713\",\n    \"1.2.826.0.1.3680043.8.498.86037975393556827852769300088670915080\",\n    \"1.2.826.0.1.3680043.8.498.86867376272146805428455638150607288831\",\n    \"1.2.826.0.1.3680043.8.498.88739296218460643753583291722714541935\",\n    \"1.2.826.0.1.3680043.8.498.90015157820692758596783999454928886688\",\n    \"1.2.826.0.1.3680043.8.498.93009153822317083064844213344156801735\",\n    \"1.2.826.0.1.3680043.8.498.98123758735027035609698227781754927939\",\n}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T22:08:21.479345Z","iopub.execute_input":"2025-08-04T22:08:21.479706Z","iopub.status.idle":"2025-08-04T22:08:21.498223Z","shell.execute_reply.started":"2025-08-04T22:08:21.479654Z","shell.execute_reply":"2025-08-04T22:08:21.497362Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import shutil\nfrom pathlib import Path\nimport nibabel as nib\nfrom tqdm import tqdm \n\n\nfor seg_dir in SEGMENTATIONS_DIR.iterdir():\n    if not seg_dir.is_dir():\n        continue\n\n    nii_files = list(seg_dir.glob('*.nii'))\n    cowseg_files = [f for f in nii_files if f.name.endswith('_cowseg.nii')]\n    raw_files = [f for f in nii_files if not f.name.endswith('_cowseg.nii')]\n\n    if len(raw_files) != 1 or len(cowseg_files) != 1:\n        continue\n\n    raw_file = raw_files[0]\n    cowseg_file = cowseg_files[0]\n\n    case_id = raw_file.stem\n\n    # Load raw image and save as <case>_0000.nii.gz\n    raw_img = nib.load(raw_file)\n    seg_img = nib.load(cowseg_file)\n\n    if case_id in FLIPPED_IDS:\n        seg_data = seg_img.get_fdata()[..., ::-1]  # axis=2\n        seg_img = nib.Nifti1Image(seg_data, affine=seg_img.affine)\n\n\n    nib.save(raw_img, imagesTr / f\"{case_id}_0000.nii.gz\")\n    nib.save(seg_img, labelsTr / f\"{case_id}.nii.gz\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T22:08:21.500501Z","iopub.execute_input":"2025-08-04T22:08:21.500766Z","iopub.status.idle":"2025-08-04T22:29:32.974643Z","shell.execute_reply.started":"2025-08-04T22:08:21.500745Z","shell.execute_reply":"2025-08-04T22:29:32.97402Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import json\nfrom pathlib import Path\n\n# Change this if needed\ntask_id = 552\ntask_name = \"RSNAaneurysm\"\ntask_folder = f\"Dataset{task_id:03d}_{task_name}\"\ntask_path = Path(os.environ['nnUNet_raw']) / task_folder\n\n# Define modality and label information\ndataset_dict = {\n    \"name\": task_name,\n    \"description\": \"Intracranial Aneurysm Vascular Segmentation\",\n    \"tensorImageSize\": \"3D\",\n    \"reference\": \"RSNA Intracranial Aneurysm Detection Challenge\",\n    \"licence\": \"Kaggle Competition RSNA 2024\",\n    \"release\": \"1.0\",\n    \"channel_names\": {\n    \"0\": \"CT\"\n    },\n    \"file_ending\": \".nii.gz\",\n    \"labels\": {\n    \"background\": 0,\n    \"Other Posterior Circulation\": 1,\n    \"Basilar Tip\": 2,\n    \"Right PComm\": 3,\n    \"Left PComm\": 4,\n    \"Right ICA Infraclinoid\": 5,\n    \"Left ICA Infraclinoid\": 6,\n    \"Right ICA Supraclinoid\": 7,\n    \"Left ICA Supraclinoid\": 8,\n    \"Right MCA\": 9,\n    \"Left MCA\": 10,\n    \"Right ACA\": 11,\n    \"Left ACA\": 12,\n    \"AComm\": 13\n    },\n    \"numTraining\": 178,\n}\n\n# Save JSON\nwith open(task_path / \"dataset.json\", 'w') as f:\n    json.dump(dataset_dict, f, indent=4)\n\nprint(\"✅ dataset.json saved to\", task_path / \"dataset.json\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T22:29:32.975443Z","iopub.execute_input":"2025-08-04T22:29:32.975637Z","iopub.status.idle":"2025-08-04T22:29:32.983259Z","shell.execute_reply.started":"2025-08-04T22:29:32.975621Z","shell.execute_reply":"2025-08-04T22:29:32.982498Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"%cd $REPO_DIR \n!pip install -q --upgrade pip\n!pip install -q git+https://github.com/MIC-DKFZ/nnUNet.git","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T22:29:32.984133Z","iopub.execute_input":"2025-08-04T22:29:32.984389Z","iopub.status.idle":"2025-08-04T22:29:55.419945Z","shell.execute_reply.started":"2025-08-04T22:29:32.984363Z","shell.execute_reply":"2025-08-04T22:29:55.419195Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nos.environ[\"nnUNet_raw\"] = \"/kaggle/working/ft_nnunet/nnUNet/nnunet/nnUNet_raw_data_base/nnUNet_raw\"\nos.environ[\"nnUNet_preprocessed\"] = \"/kaggle/working/ft_nnunet/nnUNet/nnunet/preprocessed\"\nos.environ[\"nnUNet_results\"] = \"/kaggle/working/ft_nnunet/nnUNet/nnunet/nnUNet_results\"\nos.environ['nnUNet_def_n_proc'] = str(4)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T22:29:55.420971Z","iopub.execute_input":"2025-08-04T22:29:55.421229Z","iopub.status.idle":"2025-08-04T22:29:55.425848Z","shell.execute_reply.started":"2025-08-04T22:29:55.421193Z","shell.execute_reply":"2025-08-04T22:29:55.425142Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"os.environ[\"nnUNet_raw\"], os.environ[\"nnUNet_preprocessed\"], os.environ[\"nnUNet_results\"]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T22:29:55.426653Z","iopub.execute_input":"2025-08-04T22:29:55.426961Z","iopub.status.idle":"2025-08-04T22:29:55.450936Z","shell.execute_reply.started":"2025-08-04T22:29:55.426944Z","shell.execute_reply":"2025-08-04T22:29:55.450354Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"%cd $REPO_DIR \n!nnUNetv2_plan_and_preprocess -d 552 --verify_dataset_integrity -npfp 1 -np 1","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T22:29:55.451669Z","iopub.execute_input":"2025-08-04T22:29:55.451914Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# !nnUNetv2_train DATASET_NAME_OR_ID UNET_CONFIGURATION FOLD --val ","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!nnUNetv2_train DATASET_NAME_OR_ID 3d_lowres FOLD","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}