{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":99552,"databundleVersionId":13190393,"sourceType":"competition"}],"dockerImageVersionId":31091,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Import necessary libraries\n!pip install polars -q\n!pip install pydicom -q\nimport kaggle_evaluation.rsna_inference_server\nfrom collections import defaultdict\nimport pydicom\nimport shutil\nimport os\nimport pandas as pd\nimport polars as pl\nimport numpy as np\nfrom sklearn import *\n\n# Define paths and read CSV files\ndata_path = '/kaggle/input/rsna-intracranial-aneurysm-detection/'\ntrain_data = pd.read_csv(os.path.join(data_path, 'train.csv'))\ntrain_localizers = pd.read_csv(os.path.join(data_path, 'train_localizers.csv'))\n\n# Define column names\nID_COL = 'SeriesInstanceUID'\n\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\n# Define allowed DICOM tags\nDICOM_TAG_ALLOWLIST = [\n    'BitsAllocated',\n    'BitsStored',\n    'Columns',\n    'FrameOfReferenceUID',\n    'HighBit',\n    'ImageOrientationPatient',\n    'ImagePositionPatient',\n    'InstanceNumber',\n    'Modality',\n    'PatientID',\n    'PhotometricInterpretation',\n    'PixelRepresentation',\n    'PixelSpacing',\n    'PlanarConfiguration',\n    'RescaleIntercept',\n    'RescaleSlope',\n    'RescaleType',\n    'Rows',\n    'SOPClassUID',\n    'SOPInstanceUID',\n    'SamplesPerPixel',\n    'SliceThickness',\n    'SpacingBetweenSlices',\n    'StudyInstanceUID',\n    'TransferSyntaxUID',\n]\n\n# Calculate means of label columns\nmeans = train_data[LABEL_COLS].mean().to_dict()\n\ndef predict(series_path: str):\n    # Extract series ID from the path\n    series_id = os.path.basename(series_path)\n\n    # Create a DataFrame with predictions\n    predictions = pl.DataFrame(\n        data=[[series_id] + [means[k] for k in LABEL_COLS]],\n        schema=[ID_COL, *LABEL_COLS],\n        orient='row'\n    )\n\n    # Validate the predictions DataFrame\n    if isinstance(predictions, pl.DataFrame):\n        assert predictions.columns == [ID_COL, *LABEL_COLS]\n    elif isinstance(predictions, pd.DataFrame):\n        assert (predictions.columns == [ID_COL, *LABEL_COLS]).all()\n    else:\n        raise TypeError('The predict function must return a DataFrame')\n\n    # Clean up the shared directory\n    shutil.rmtree('/kaggle/shared', ignore_errors=True)\n\n    # Return predictions without the ID column\n    return predictions.drop(ID_COL)\n\n# Initialize the inference server\ninference_server = kaggle_evaluation.rsna_inference_server.RSNAInferenceServer(predict)\n\n# Check if the environment variable is set to run the server or locally\nif os.getenv('KAGGLE_IS_COMPETITION_RERUN'):\n    inference_server.serve()\nelse:\n    inference_server.run_local_gateway()\n    # Display the submission parquet file\n    display(pl.read_parquet('/kaggle/working/submission.parquet'))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-04T07:31:12.117922Z","iopub.execute_input":"2025-08-04T07:31:12.118171Z","iopub.status.idle":"2025-08-04T07:31:26.209737Z","shell.execute_reply.started":"2025-08-04T07:31:12.118149Z","shell.execute_reply":"2025-08-04T07:31:26.208949Z"}},"outputs":[],"execution_count":null}]}