{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.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":71549,"databundleVersionId":8561470,"sourceType":"competition"},{"sourceId":9235934,"sourceType":"datasetVersion","datasetId":5586514},{"sourceId":9238129,"sourceType":"datasetVersion","datasetId":5587999},{"sourceId":9238150,"sourceType":"datasetVersion","datasetId":5588015},{"sourceId":9409759,"sourceType":"datasetVersion","datasetId":5577143},{"sourceId":192715298,"sourceType":"kernelVersion"},{"sourceId":193161758,"sourceType":"kernelVersion"},{"sourceId":193298353,"sourceType":"kernelVersion"},{"sourceId":193335312,"sourceType":"kernelVersion"},{"sourceId":193338638,"sourceType":"kernelVersion"},{"sourceId":193417638,"sourceType":"kernelVersion"}],"dockerImageVersionId":30747,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install -q --no-index --find-links /kaggle/input/ultralytics ultralytics","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T04:17:05.242676Z","iopub.execute_input":"2024-11-19T04:17:05.243077Z","iopub.status.idle":"2024-11-19T04:17:15.500925Z","shell.execute_reply.started":"2024-11-19T04:17:05.243045Z","shell.execute_reply":"2024-11-19T04:17:15.499736Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pydicom\nfrom PIL import Image\nimport numpy as np\nfrom multiprocessing import Pool, cpu_count\n\nimport sklearn.metrics\nimport torch\nimport cv2\nimport numpy as np \nimport pandas as pd \nfrom tqdm.auto import tqdm","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-11-19T04:17:15.502949Z","iopub.execute_input":"2024-11-19T04:17:15.503217Z","iopub.status.idle":"2024-11-19T04:17:19.92016Z","shell.execute_reply.started":"2024-11-19T04:17:15.503194Z","shell.execute_reply":"2024-11-19T04:17:19.91946Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"EVAL = False # Change to True to compute the validation score\nIMG_DIR = '/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/lsdc-train-yolo-scs/lsdc_yolov8/train/weights/best.pt']\n\nSS_WEIGHTS = ['/kaggle/input/lsdc-train-yolo-ss/lsdc_yolov8/train/weights/best.pt',\n             '/kaggle/input/lsdc-yolo-ssv3/best.pt']\n\nNFN_WEIGHTS = ['/kaggle/input/lsdc-train-yolo-nfn/lsdc_yolov8/train/weights/best.pt',\n              '/kaggle/input/lsdc-yolo-nfnv3/best.pt']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T04:17:19.92127Z","iopub.execute_input":"2024-11-19T04:17:19.922017Z","iopub.status.idle":"2024-11-19T04:17:19.927161Z","shell.execute_reply.started":"2024-11-19T04:17:19.921975Z","shell.execute_reply":"2024-11-19T04:17:19.926242Z"}},"outputs":[],"execution_count":null},{"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":{"iopub.status.busy":"2024-11-19T04:17:19.92876Z","iopub.execute_input":"2024-11-19T04:17:19.92898Z","iopub.status.idle":"2024-11-19T04:17:19.9399Z","shell.execute_reply.started":"2024-11-19T04:17:19.928961Z","shell.execute_reply":"2024-11-19T04:17:19.939268Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_val_df = pd.read_csv('/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T04:17:19.940733Z","iopub.execute_input":"2024-11-19T04:17:19.94095Z","iopub.status.idle":"2024-11-19T04:17:19.974914Z","shell.execute_reply.started":"2024-11-19T04:17:19.940931Z","shell.execute_reply":"2024-11-19T04:17:19.974262Z"}},"outputs":[],"execution_count":null},{"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":{"iopub.status.busy":"2024-11-19T04:17:19.975768Z","iopub.execute_input":"2024-11-19T04:17:19.975969Z","iopub.status.idle":"2024-11-19T04:17:19.983103Z","shell.execute_reply.started":"2024-11-19T04:17:19.975952Z","shell.execute_reply":"2024-11-19T04:17:19.982462Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"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":{"iopub.status.busy":"2024-11-19T04:17:19.984076Z","iopub.execute_input":"2024-11-19T04:17:19.984324Z","iopub.status.idle":"2024-11-19T04:17:19.992139Z","shell.execute_reply.started":"2024-11-19T04:17:19.984306Z","shell.execute_reply":"2024-11-19T04:17:19.991212Z"}},"outputs":[],"execution_count":null},{"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/input/lsdc-get-all-images/images.zip\n        print('Done unziping data')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T04:17:19.993293Z","iopub.execute_input":"2024-11-19T04:17:19.993635Z","iopub.status.idle":"2024-11-19T04:17:20.952053Z","shell.execute_reply.started":"2024-11-19T04:17:19.993606Z","shell.execute_reply":"2024-11-19T04:17:20.951086Z"}},"outputs":[],"execution_count":null},{"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]\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":{"iopub.status.busy":"2024-11-19T04:17:20.953314Z","iopub.execute_input":"2024-11-19T04:17:20.953895Z","iopub.status.idle":"2024-11-19T04:17:20.973212Z","shell.execute_reply.started":"2024-11-19T04:17:20.95387Z","shell.execute_reply":"2024-11-19T04:17:20.972586Z"}},"outputs":[],"execution_count":null},{"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":{"iopub.status.busy":"2024-11-19T04:17:20.975718Z","iopub.execute_input":"2024-11-19T04:17:20.976001Z","iopub.status.idle":"2024-11-19T04:17:20.981337Z","shell.execute_reply.started":"2024-11-19T04:17:20.975982Z","shell.execute_reply":"2024-11-19T04:17:20.980509Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from ultralytics import YOLO\n\n# Load YOLO Model\nscs_models = []\nfor weight in SCS_WEIGHTS:\n    scs_models.append(YOLO(weight))\n    \nss_models = []\nfor weight in SS_WEIGHTS:\n    ss_models.append(YOLO(weight))\n    \nnfn_models = []\nfor weight in NFN_WEIGHTS:\n    nfn_models.append(YOLO(weight))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T04:17:20.982235Z","iopub.execute_input":"2024-11-19T04:17:20.982461Z","iopub.status.idle":"2024-11-19T04:17:24.75418Z","shell.execute_reply.started":"2024-11-19T04:17:20.98243Z","shell.execute_reply":"2024-11-19T04:17:24.753338Z"}},"outputs":[],"execution_count":null},{"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":{"iopub.status.busy":"2024-11-19T04:17:24.755282Z","iopub.execute_input":"2024-11-19T04:17:24.755607Z","iopub.status.idle":"2024-11-19T04:17:24.760725Z","shell.execute_reply.started":"2024-11-19T04:17:24.755579Z","shell.execute_reply":"2024-11-19T04:17:24.75975Z"}},"outputs":[],"execution_count":null},{"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":{"iopub.status.busy":"2024-11-19T04:17:24.762188Z","iopub.execute_input":"2024-11-19T04:17:24.762458Z","iopub.status.idle":"2024-11-19T04:17:24.774174Z","shell.execute_reply.started":"2024-11-19T04:17:24.76242Z","shell.execute_reply":"2024-11-19T04:17:24.77346Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from collections import defaultdict","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T04:17:24.775059Z","iopub.execute_input":"2024-11-19T04:17:24.775284Z","iopub.status.idle":"2024-11-19T04:17:24.785639Z","shell.execute_reply.started":"2024-11-19T04:17:24.775265Z","shell.execute_reply":"2024-11-19T04:17:24.784858Z"}},"outputs":[],"execution_count":null},{"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, conf=thresh, verbose=False)\n                for res in results:\n                    for pred_class, conf in zip(res.boxes.cls, res.boxes.conf):\n                        pred_class = pred_class.item()\n                        conf = conf.item()\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:\n            res_dict = {'row_id': f'{study_id}_{condition}' }\n\n            score_vec = []\n            for severity in SEVERITIES:\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            # normalize score to sum to 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)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T04:17:24.78685Z","iopub.execute_input":"2024-11-19T04:17:24.78709Z","iopub.status.idle":"2024-11-19T04:17:30.48735Z","shell.execute_reply.started":"2024-11-19T04:17:24.787071Z","shell.execute_reply":"2024-11-19T04:17:30.486443Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pred_df = pd.DataFrame(pred_rows)\npred_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T04:17:30.488318Z","iopub.execute_input":"2024-11-19T04:17:30.48868Z","iopub.status.idle":"2024-11-19T04:17:30.505135Z","shell.execute_reply.started":"2024-11-19T04:17:30.488659Z","shell.execute_reply":"2024-11-19T04:17:30.504374Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pred_df.to_csv('submission.csv', index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T04:17:30.50604Z","iopub.execute_input":"2024-11-19T04:17:30.506284Z","iopub.status.idle":"2024-11-19T04:17:30.54328Z","shell.execute_reply.started":"2024-11-19T04:17:30.506257Z","shell.execute_reply":"2024-11-19T04:17:30.542161Z"}},"outputs":[],"execution_count":null},{"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":{"iopub.status.busy":"2024-11-19T04:17:30.544321Z","iopub.execute_input":"2024-11-19T04:17:30.544576Z","iopub.status.idle":"2024-11-19T04:17:30.549597Z","shell.execute_reply.started":"2024-11-19T04:17:30.544555Z","shell.execute_reply":"2024-11-19T04:17:30.548766Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n    # Prepare ground truth DataFrame\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    # Merge with predictions\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    # Print mismatches\n    mismatches_gt = gt_df1[(gt_df1['pred_cls'] != pred_df1['pred_cls'])]\n    mismatches_pred = pred_df1[(gt_df1['pred_cls'] != pred_df1['pred_cls'])]\n\n    print('Mismatched Ground Truth Labels:\\n', mismatches_gt)\n    print('Mismatched Predictions:\\n', mismatches_pred)\n\n    # Print label counts and accuracy\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    # Calculate and print the loss\n    target_levels = ['normal_mild', 'moderate', 'severe']\n    loss = lsdc_scoring(\n        gt_df1.drop(['pred_cls'], axis=1), \n        pred_df1.drop(['pred_cls'], axis=1), \n        row_id_column_name='row_id', \n        any_severe_scalar=1\n    )\n    print('Total weighted log loss:', loss)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T04:17:53.112804Z","iopub.execute_input":"2024-11-19T04:17:53.113675Z","iopub.status.idle":"2024-11-19T04:17:53.852008Z","shell.execute_reply.started":"2024-11-19T04:17:53.11364Z","shell.execute_reply":"2024-11-19T04:17:53.85082Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T04:17:30.567475Z","iopub.execute_input":"2024-11-19T04:17:30.567701Z","iopub.status.idle":"2024-11-19T04:17:31.606346Z","shell.execute_reply.started":"2024-11-19T04:17:30.567683Z","shell.execute_reply":"2024-11-19T04:17:31.605187Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}