{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":129601,"databundleVersionId":15542776,"sourceType":"competition"}],"dockerImageVersionId":31259,"isInternetEnabled":true,"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":"2026-02-02T13:03:19.078135Z","iopub.execute_input":"2026-02-02T13:03:19.078402Z","iopub.status.idle":"2026-02-02T13:03:31.276820Z","shell.execute_reply.started":"2026-02-02T13:03:19.078376Z","shell.execute_reply":"2026-02-02T13:03:31.276007Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport os\nimport nibabel as nib\n\n# 1. CORRECT PATHS (As seen in your file list)\nBASE_PATH = '/kaggle/input/instant-odc-ai-hackathon'\nSAMPLE_SUB_PATH = os.path.join(BASE_PATH, 'sample_submission.csv')\nTEST_DATA_DIR = os.path.join(BASE_PATH, 'test')\n\n# 2. LOAD SAMPLE SUBMISSION\ntry:\n    sample_sub = pd.read_csv(SAMPLE_SUB_PATH)\n    print(f\"Loaded sample_submission.csv. Found {len(sample_sub)} rows.\")\nexcept FileNotFoundError:\n    print(\"Error: Could not find sample_submission.csv. Please verify the path.\")\n\n# 3. EXTRACT UNIQUE PATIENT IDs\n# IDs look like 'BraTS2021_01333_1', we need 'BraTS2021_01333'\npatient_ids = sample_sub['id'].apply(lambda x: \"_\".join(x.split('_')[:-1])).unique()\n\n# 4. ROBUST RLE ENCODER\ndef rle_encode(mask):\n    \"\"\"Converts a binary mask into RLE format (Fortran order).\"\"\"\n    pixels = mask.flatten(order='F')\n    pixels = np.concatenate([[0], pixels, [0]])\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n    runs[1::2] -= runs[::2]\n    return ' '.join(str(x) for x in runs)\n\n# 5. PREDICTION & SUBMISSION LOOP\nsubmission_data = []\n\nprint(f\"Processing {len(patient_ids)} test patients...\")\n\nfor p_id in patient_ids:\n    # Build path to the patient's folder\n    patient_folder = os.path.join(TEST_DATA_DIR, p_id)\n    \n    # Check if folder exists (prevents crashes if IDs don't match folder names)\n    if os.path.exists(patient_folder):\n        # Example: Load the FLAIR modality to get the volume shape\n        # flair_img = nib.load(os.path.join(patient_folder, f'{p_id}_flair.nii'))\n        # shape = flair_img.shape\n        \n        # --- PLACEHOLDER: YOUR MODEL INFERENCE HERE ---\n        # Your model should output a mask of shape (240, 240, 155)\n        # with labels: 1 (Necrotic), 2 (Edema), 4 (Enhancing)\n        dummy_mask = np.zeros((240, 240, 155), dtype=np.uint8) \n    else:\n        # Fallback if folder is missing\n        dummy_mask = np.zeros((240, 240, 155), dtype=np.uint8)\n\n    # Encode each class required by the competition\n    for label in [1, 2, 4]:\n        binary_mask = (dummy_mask == label).astype(np.uint8)\n        rle_str = rle_encode(binary_mask)\n        \n        # If no tumor detected, use \"1 1\" (standard placeholder) or empty string\n        # depending on leaderboard requirements. \"1 0\" or \"\" are common.\n        submission_data.append({\n            'id': f\"{p_id}_{label}\",\n            'rle': rle_str if rle_str else \"\"\n        })\n\n# 6. SAVE FINAL CSV\nsubmission_df = pd.DataFrame(submission_data)\nsubmission_df.to_csv('submission.csv', index=False)\nprint(\"Success! 'submission.csv' is ready for upload.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-02T13:05:42.147902Z","iopub.execute_input":"2026-02-02T13:05:42.148274Z","iopub.status.idle":"2026-02-02T13:06:44.195312Z","shell.execute_reply.started":"2026-02-02T13:05:42.148245Z","shell.execute_reply":"2026-02-02T13:06:44.194373Z"}},"outputs":[],"execution_count":null}]}