{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":71549,"databundleVersionId":8561470,"sourceType":"competition"},{"sourceId":9409759,"sourceType":"datasetVersion","datasetId":5577143},{"sourceId":9414254,"sourceType":"datasetVersion","datasetId":5716000},{"sourceId":9414402,"sourceType":"datasetVersion","datasetId":5716011},{"sourceId":192715298,"sourceType":"kernelVersion"},{"sourceId":193161758,"sourceType":"kernelVersion"},{"sourceId":196765686,"sourceType":"kernelVersion"},{"sourceId":196825307,"sourceType":"kernelVersion"},{"sourceId":196828698,"sourceType":"kernelVersion"}],"dockerImageVersionId":30762,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"from IPython.display import clear_output\n\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/pycocotools-2.0.6-cp310-cp310-linux_x86_64.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/torch-1.12.1cu116-cp310-cp310-linux_x86_64.whl \n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/torchvision-0.13.0cu116-cp310-cp310-linux_x86_64.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/mmcv-2.0.1-cp310-cp310-manylinux1_x86_64.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/openmim-0.3.9-py2.py3-none-any.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/mmengine-0.8.3-py3-none-any.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/addict-2.4.0-py3-none-any.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/yapf-0.40.1-py3-none-any.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/terminaltables-3.1.10-py2.py3-none-any.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/setuptools-69.5.1-py3-none-any.whl\n\n# mmpretrain\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/einops-0.8.0-py3-none-any.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/mat4py-0.6.0-py2.py3-none-any.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/ordered_set-4.1.0-py3-none-any.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/model_index-0.1.11-py3-none-any.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/modelindex-0.0.2-py3-none-any.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetection-wheel/mmpretrain-1.2.0-py2.py3-none-any.whl\nclear_output()","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-09-17T02:44:42.195103Z","iopub.execute_input":"2024-09-17T02:44:42.195447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Helper Function","metadata":{}},{"cell_type":"code","source":"def read_dcm(src_path):\n    dicom_data = pydicom.dcmread(src_path)\n    image = dicom_data.pixel_array\n    image = (image - image.min()) / (image.max() - image.min() +1e-6) * 255\n    return image\n\ndef convert_dcm_to_jpg(file_path):\n    try:\n        # Read the DICOM file\n        image_array = read_dcm(file_path)\n        \n        # Define the output path\n        relative_path = os.path.relpath(file_path, start=input_directory)\n        output_path = os.path.join(output_directory, relative_path)\n        output_path = output_path.replace('.dcm', '.jpg')\n                \n        # Create the output directory if it doesn't exist\n        os.makedirs(os.path.dirname(output_path), exist_ok=True)\n        \n        # Save the image as a JPEG file\n        cv2.imwrite(output_path, image_array)\n        \n        return output_path\n    except Exception as e:\n        print(f\"Error processing file {file_path}: {e}\")\n        return None\n\ndef process_files(dcm_files):\n    with Pool(cpu_count()) as pool:\n        # Wrap pool.map with tqdm to show the progress bar\n        list(tqdm(pool.imap(convert_dcm_to_jpg, dcm_files), total=len(dcm_files)))\n\ndef get_dcm_files(directory):\n    dcm_files = []\n    for root, dirs, files in os.walk(directory):\n        for file in files:\n            if file.endswith('.dcm'):\n                dcm_files.append(os.path.join(root, file))\n    return dcm_files","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Move mmdetection to output dir","metadata":{}},{"cell_type":"code","source":"import os\nimport shutil\n\ninput_path = \"/kaggle/input/mmdetection-3-3-0\"\noutput_path = \"/kaggle/working/mmdetection\"\n\nshutil.copytree(input_path, output_path)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%cd /kaggle/working/mmdetection\n!pip install -v -e .\nclear_output()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Check Pytorch installation\nimport torch, torchvision\nprint(\"torch version:\",torch.__version__, \"cuda:\",torch.cuda.is_available())\n\n# Check MMDetection installation\nimport mmdet\nprint(\"mmdetection:\",mmdet.__version__)\n\n# Check mmcv installation\nimport mmcv\nprint(\"mmcv:\",mmcv.__version__)\n\n# Check mmengine installation\nimport mmengine\nprint(\"mmengine:\",mmengine.__version__)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%cd ..","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Importing the required pakages","metadata":{}},{"cell_type":"code","source":"from tqdm.notebook import tqdm\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nfrom glob import glob\nimport matplotlib.pyplot as plt\n\nfrom mmdet.apis import init_detector, inference_detector, DetInferencer\nimport mmcv\n\nimport cv2\nimport pydicom\nfrom PIL import Image\nimport numpy as np\nfrom multiprocessing import Pool, cpu_count\nimport os\nimport torch","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EVAL = False # Change to True to compute the validation score\nIMG_DIR = '/kaggle/working/images'\nFOLD = 0\nSAMPLE = False # True for quick debugging\nSEVERITIES = ['Normal/Mild', 'Moderate', 'Severe']\nLEVELS = ['l1_l2', 'l2_l3', 'l3_l4', 'l4_l5', 'l5_s1']\n\nSCS_WEIGHTS = ['/kaggle/input/mmdetection-convnext-cascadercn-scs-train/model_output/best_coco_bbox_mAP_50_epoch_14.pth']\nSCS_CONFIG = ['/kaggle/input/mmdetection-convnext-cascadercn-scs-train/model_output/custom_config.py']\n\nSS_WEIGHTS = ['/kaggle/input/mmdetection-convnext-cascadercn-ss-train/model_output/best_coco_bbox_mAP_50_epoch_9.pth']\nSS_CONFIG = ['/kaggle/input/mmdetection-convnext-cascadercn-ss-train/model_output/custom_config.py']\n\nNFN_WEIGHTS = ['/kaggle/input/mmdetection-convnext-cascadercn-nfn-train/model_output/best_coco_bbox_mAP_50_epoch_15.pth']\nNFN_CONFIG = ['/kaggle/input/mmdetection-convnext-cascadercn-nfn-train/model_output/custom_config.py']\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if EVAL:\n    import sys\n    sys.path.append('/kaggle/input/lsdc-utils')\n    from metrics import score as lsdc_scoring","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_val_df = pd.read_csv('/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train.csv')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if EVAL:\n    train_xy = pd.read_csv('/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_label_coordinates.csv')\n    des = pd.read_csv('/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_series_descriptions.csv')\nelse:    \n    des = pd.read_csv('/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/test_series_descriptions.csv')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Replace these with your input and output directories\nif not EVAL:\n    input_directory = '/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/test_images'\n\n    output_directory = IMG_DIR\n\n    # Get all .dcm files in the input directory\n    dcm_files = get_dcm_files(input_directory)\n\n    # Process the files using multiprocessing\n    process_files(dcm_files)\n\n    print(f\"Conversion completed. Images saved to {output_directory}\")\nelse:\n    if not os.path.exists(IMG_DIR):\n        print('Unziping data..')\n        !unzip -q -d /kaggle/working /kaggle/input/lsdc-get-all-images/images.zip\n        print('Done unziping data')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def gen_label_map(CONDITIONS):\n    label2id = {}\n    id2label = {}\n    i = 0\n    for cond in CONDITIONS:\n        for level in LEVELS:\n            for severity in SEVERITIES:\n                cls_ = f\"{cond.lower().replace(' ', '_')}_{level}_{severity.lower()}\"\n                label2id[cls_] = i\n                id2label[i] = cls_\n                i+=1\n    return label2id, id2label\n                \nscs_label2id, scs_id2label = gen_label_map(['Spinal Canal Stenosis'])\nss_label2id, ss_id2label = gen_label_map(['Left Subarticular Stenosis', 'Right Subarticular Stenosis'])\nnfn_label2id, nfn_id2label = gen_label_map(['Left Neural Foraminal Narrowing', 'Right Neural Foraminal Narrowing'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if EVAL:\n    fold_df = pd.read_csv('/kaggle/input/lsdc-fold-split/5folds.csv')\n    test_df = fold_df[fold_df.fold == FOLD].sample(100, random_state = 42).sort_values(by='study_id').reset_index(drop=True)\n    \nelse:\n    test_df = os.listdir('/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/test_images')\n    test_df = pd.DataFrame(test_df, columns=['study_id'])\n    test_df['study_id'] = test_df['study_id'].astype(int)\n    \ntest_df = test_df.merge(des, on=['study_id'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load Model\ndevice = 'cuda:0'\nscs_models = []\nscs_config = []\nfor weight, config in zip(SCS_WEIGHTS, SCS_CONFIG):\n    scs_models.append(DetInferencer(config, weight, device=device, show_progress=False))\n    \nss_models = []\nss_config = []\nfor weight, config in zip(SS_WEIGHTS, SS_CONFIG):\n    ss_models.append(DetInferencer(config, weight, device=device, show_progress=False))\n    \nnfn_models = []\nnfn_config = []\nfor weight, config in zip(NFN_WEIGHTS, NFN_CONFIG):\n    nfn_models.append(DetInferencer(config, weight, device=device, show_progress=False))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_label_set = train_val_df.iloc[0, 1:].index.tolist()\nscs_label_set = all_label_set[:5]\nnfn_label_set = all_label_set[5:15]\nss_label_set = all_label_set[15:]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"settings = [\n    ( 'Sagittal T2/STIR', scs_models, scs_id2label, scs_label_set, 0.01),\n    ( 'Axial T2', ss_models, ss_id2label, ss_label_set, 0.01),\n    ( 'Sagittal T1', nfn_models, nfn_id2label, nfn_label_set, 0.1)\n]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from collections import defaultdict","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_rows = []\n\nfor modality, models, id2label, label_set, thresh in settings:\n    mod_df = test_df[test_df.series_description == modality]\n    \n    if SAMPLE:\n        mod_df = mod_df.sample(20, random_state=610)\n    \n    # for each study, at each level and condition, get the maximum probability score\n    for study_id, group in tqdm(mod_df.groupby('study_id')):\n        predictions = defaultdict(list)\n        for i, row in group.iterrows():\n            # predict on all images from all the series\n            series_dir = os.path.join(IMG_DIR, str(row['study_id']), str(row['series_id']))\n            for model in models:\n                results = model(series_dir, batch_size=8, pred_score_thr=thresh)\n                results_predictions = results['predictions']\n                for res in results_predictions:\n                    for pred_class, conf in zip(res['labels'], res['scores']):\n                        _class = id2label[pred_class]\n                        predictions[_class].append(conf)\n                        \n        # aggregate the result on images to obtain study-level prediction\n        for condition in label_set: # label_set: left/right + condition + level\n            res_dict = {'row_id': f'{study_id}_{condition}' }\n\n            score_vec = []\n            for severity in SEVERITIES: # SEVERITIES : 'Normal/Mild', 'Moderate', 'Severe' \n                severity = severity.lower()\n                key = f'{condition}_{severity}'\n                if len(predictions[key]) > 0:\n                    score = np.max(predictions[key])\n                else:\n                    score = thresh\n                score_vec.append(score)\n                \n            # 将三个分数的和标准化为1\n            score_vec = torch.tensor(score_vec)\n            score_vec = score_vec / score_vec.sum()\n\n            for idx, severity in enumerate(SEVERITIES):\n                res_dict[severity.replace('/', '_').lower()] = score_vec[idx].item()\n\n            pred_rows.append(res_dict)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_df = pd.DataFrame(pred_rows)\npred_df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_df.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def sample_weight(row):\n    if row['normal_mild'] == 1:\n        return 1\n    if row['moderate'] == 1:\n        return 2\n    if row['severe'] == 1:\n        return 4\n    raise ValueError('No such value')\n    \ndef get_class(row):\n    return np.argmax([row['normal_mild'], row['moderate'], row['severe']])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if EVAL:\n    gt_df = train_val_df.dropna().melt(id_vars=['study_id'], value_vars=all_label_set)\n    gt_df['row_id'] = gt_df['study_id'].astype(str) + '_' + gt_df['variable']\n    gt_df= gt_df[['row_id', 'value']]\n    gt_df = pd.get_dummies(gt_df, columns=['value'], dtype=int)\n    gt_df.columns = ['row_id', 'moderate', 'normal_mild', 'severe']\n    gt_df = gt_df[['row_id', 'normal_mild', 'moderate', 'severe']]\n    gt_df['sample_weight'] = gt_df.apply(sample_weight, axis=1)\n\n    gt_df1 = gt_df.merge(pred_df['row_id'], how='inner', on='row_id').sort_values('row_id').reset_index(drop=True)\n    pred_df1 = pred_df.merge(gt_df1['row_id'], how='inner', on='row_id').sort_values('row_id').reset_index(drop=True)\n    gt_df1['pred_cls'] = gt_df1.apply(get_class, axis=1)\n    pred_df1['pred_cls'] = pred_df1.apply(get_class, axis=1)\n\n    gt_df1[(gt_df1['pred_cls'] != pred_df1['pred_cls'])]\n    pred_df1[(gt_df1['pred_cls'] != pred_df1['pred_cls'])]\n    print('Label count:\\n', gt_df1['pred_cls'].value_counts(normalize=True))\n    print('Prediction accuracy:', (gt_df1['pred_cls'] == pred_df1['pred_cls']).mean())\n    print()\n\n    target_levels = ['normal_mild', 'moderate', 'severe']\n    loss = lsdc_scoring(gt_df1.drop(['pred_cls'], axis=1), pred_df1.drop(['pred_cls'], axis=1), row_id_column_name='row_id', any_severe_scalar=1)\n    print('Total weighted log loss:', loss)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!rm -rf /kaggle/working/mmdetection","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!rm -rf /kaggle/working/images","metadata":{},"execution_count":null,"outputs":[]}]}