{"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":9195731,"sourceType":"datasetVersion","datasetId":5559249},{"sourceId":193161758,"sourceType":"kernelVersion"},{"sourceId":193336580,"sourceType":"kernelVersion"}],"dockerImageVersionId":30747,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport pandas as pd\nimport numpy as np\nimport pydicom\nfrom tqdm.auto import tqdm\nimport matplotlib.pyplot as plt\nimport cv2\nimport glob","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-08-20T16:33:05.361432Z","iopub.execute_input":"2024-08-20T16:33:05.361764Z","iopub.status.idle":"2024-08-20T16:33:06.164716Z","shell.execute_reply.started":"2024-08-20T16:33:05.361738Z","shell.execute_reply":"2024-08-20T16:33:06.163885Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip -q /kaggle/input/lsdc-gen-yolo-data-nfn/data_fold0.zip","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:06.166367Z","iopub.execute_input":"2024-08-20T16:33:06.166794Z","iopub.status.idle":"2024-08-20T16:33:15.364074Z","shell.execute_reply.started":"2024-08-20T16:33:06.166769Z","shell.execute_reply":"2024-08-20T16:33:15.362901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ls","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:15.365434Z","iopub.execute_input":"2024-08-20T16:33:15.365714Z","iopub.status.idle":"2024-08-20T16:33:16.358347Z","shell.execute_reply.started":"2024-08-20T16:33:15.365691Z","shell.execute_reply":"2024-08-20T16:33:16.357413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMG_DIR = \"/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_images\"","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:16.359887Z","iopub.execute_input":"2024-08-20T16:33:16.360257Z","iopub.status.idle":"2024-08-20T16:33:16.366708Z","shell.execute_reply.started":"2024-08-20T16:33:16.360223Z","shell.execute_reply":"2024-08-20T16:33:16.365819Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"FOLD = 0\nOD_INPUT_SIZE = 384\nSTD_BOX_SIZE = 20\nBATCH_SIZE = 64\nEPOCHS = 40\n\nSAMPLE = None\nCONDITIONS = ['Left Neural Foraminal Narrowing', 'Right Neural Foraminal Narrowing']\nSEVERITIES = ['Normal/Mild', 'Moderate', 'Severe']\nLEVELS = ['l1_l2', 'l2_l3', 'l3_l4', 'l4_l5', 'l5_s1']\n\nDATA_DIR = f'data_fold{FOLD}'\n\n","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:16.369296Z","iopub.execute_input":"2024-08-20T16:33:16.369643Z","iopub.status.idle":"2024-08-20T16:33:16.375699Z","shell.execute_reply.started":"2024-08-20T16:33:16.369620Z","shell.execute_reply":"2024-08-20T16:33:16.374798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# rm -rf val_fold0","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:16.376731Z","iopub.execute_input":"2024-08-20T16:33:16.376984Z","iopub.status.idle":"2024-08-20T16:33:16.385543Z","shell.execute_reply.started":"2024-08-20T16:33:16.376962Z","shell.execute_reply":"2024-08-20T16:33:16.384700Z"},"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')\ntrain_xy = pd.read_csv('/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_label_coordinates.csv')\ntrain_des = pd.read_csv('/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_series_descriptions.csv')","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:16.386664Z","iopub.execute_input":"2024-08-20T16:33:16.386910Z","iopub.status.idle":"2024-08-20T16:33:16.537782Z","shell.execute_reply.started":"2024-08-20T16:33:16.386888Z","shell.execute_reply":"2024-08-20T16:33:16.536739Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if SAMPLE:\n    train_val_df = train_val_df.sample(SAMPLE, random_state=2698)","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:16.539151Z","iopub.execute_input":"2024-08-20T16:33:16.539543Z","iopub.status.idle":"2024-08-20T16:33:16.544367Z","shell.execute_reply.started":"2024-08-20T16:33:16.539509Z","shell.execute_reply":"2024-08-20T16:33:16.543369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fold_df = pd.read_csv('/kaggle/input/lsdc-fold-split/5folds.csv')","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:16.545544Z","iopub.execute_input":"2024-08-20T16:33:16.545831Z","iopub.status.idle":"2024-08-20T16:33:16.559693Z","shell.execute_reply.started":"2024-08-20T16:33:16.545801Z","shell.execute_reply":"2024-08-20T16:33:16.558910Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_xy.head(3)","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:16.560915Z","iopub.execute_input":"2024-08-20T16:33:16.561898Z","iopub.status.idle":"2024-08-20T16:33:16.583485Z","shell.execute_reply.started":"2024-08-20T16:33:16.561865Z","shell.execute_reply":"2024-08-20T16:33:16.582650Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_level(text):\n    for lev in ['l1_l2', 'l2_l3', 'l3_l4', 'l4_l5', 'l5_s1']:\n        if lev in text:\n            split = lev.split('_')\n            split[0] = split[0].capitalize()\n            split[1] = split[1].capitalize()\n            return '/'.join(split)\n    raise ValueError('Level not found '+ lev)\n    \ndef get_condition(text):\n    split = text.split('_')\n    for i in range(len(split)):\n        split[i] = split[i].capitalize()\n    split = split[:-2]\n    return ' '.join(split)\n#     raise ValueError('Condition not found '+ lev)","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:16.584467Z","iopub.execute_input":"2024-08-20T16:33:16.584726Z","iopub.status.idle":"2024-08-20T16:33:16.591252Z","shell.execute_reply.started":"2024-08-20T16:33:16.584704Z","shell.execute_reply":"2024-08-20T16:33:16.590355Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_xy['condition'].unique()","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:16.592584Z","iopub.execute_input":"2024-08-20T16:33:16.592843Z","iopub.status.idle":"2024-08-20T16:33:16.608731Z","shell.execute_reply.started":"2024-08-20T16:33:16.592821Z","shell.execute_reply":"2024-08-20T16:33:16.607804Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# train_df = train_df.dropna()","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:16.609831Z","iopub.execute_input":"2024-08-20T16:33:16.610082Z","iopub.status.idle":"2024-08-20T16:33:16.614429Z","shell.execute_reply.started":"2024-08-20T16:33:16.610061Z","shell.execute_reply":"2024-08-20T16:33:16.613530Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label_df = {'study_id':[], 'condition': [], 'level':[], 'label':[]}\n\nfor i, row in train_val_df.iterrows():\n    study_id = row['study_id']\n    for k, label in row.iloc[1:].to_dict().items():\n        level = get_level(k)\n        condition = get_condition(k)\n        label_df['study_id'].append(study_id)\n        label_df['condition'].append(condition)\n        label_df['level'].append(level)\n        label_df['label'].append(label)\n#         break\n#     break\n\nlabel_df = pd.DataFrame(label_df)\nlabel_df = label_df.merge(fold_df, on='study_id')","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:16.619780Z","iopub.execute_input":"2024-08-20T16:33:16.620022Z","iopub.status.idle":"2024-08-20T16:33:17.208333Z","shell.execute_reply.started":"2024-08-20T16:33:16.620002Z","shell.execute_reply":"2024-08-20T16:33:17.207346Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_xy = train_xy.merge(train_des, how='inner', on=['study_id', 'series_id'])\nlabel_df = label_df.merge(train_xy, how='inner', on=['study_id', 'condition', 'level'])","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:17.209496Z","iopub.execute_input":"2024-08-20T16:33:17.209800Z","iopub.status.idle":"2024-08-20T16:33:17.294585Z","shell.execute_reply.started":"2024-08-20T16:33:17.209759Z","shell.execute_reply":"2024-08-20T16:33:17.293751Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def query_train_xy_row(study_id, series_id=None, instance_num=None):\n    if series_id is not None and instance_num is not None:\n        return label_df[(label_df.study_id==study_id) & (label_df.series_id==series_id) &\n            (label_df.instance_number==instance_num)]\n    elif series_id is None and instance_num is None:\n        return label_df[(label_df.study_id==study_id)]\n    else:\n        return label_df[(train_xy.study_id==study_id) & (label_df.series_id==series_id)]","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:17.295799Z","iopub.execute_input":"2024-08-20T16:33:17.296107Z","iopub.status.idle":"2024-08-20T16:33:17.302842Z","shell.execute_reply.started":"2024-08-20T16:33:17.296081Z","shell.execute_reply":"2024-08-20T16:33:17.301688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    image = np.stack([image]*3, axis=-1).astype('uint8')\n    return image\n\ndef get_accronym(text):\n    split = text.split(' ')\n    return ''.join([x[0] for x in split])","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:17.304478Z","iopub.execute_input":"2024-08-20T16:33:17.304769Z","iopub.status.idle":"2024-08-20T16:33:17.312165Z","shell.execute_reply.started":"2024-08-20T16:33:17.304745Z","shell.execute_reply":"2024-08-20T16:33:17.311439Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# study_id = 4003253 \n# series_id = 2448190387\n# instance_num = 28\n\nex = label_df.sample(1).iloc[0]\nstudy_id = ex.study_id\nseries_id = ex.series_id\ninstance_num = ex.instance_number\n\nWIDTH = 10\n\npath = os.path.join(IMG_DIR, str(study_id), str(series_id), f'{instance_num}.dcm')","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:17.313156Z","iopub.execute_input":"2024-08-20T16:33:17.313454Z","iopub.status.idle":"2024-08-20T16:33:17.325695Z","shell.execute_reply.started":"2024-08-20T16:33:17.313427Z","shell.execute_reply":"2024-08-20T16:33:17.324894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img = read_dcm(path)\n\ntmp_df = query_train_xy_row(study_id, series_id, instance_num)\nfor i, row in tmp_df.iterrows():\n    lbl = f\"{get_accronym(row['condition'])}_{row['level']}\"\n    x, y = row['x'], row['y']\n    x1 = int(x - WIDTH)\n    x2 = int(x + WIDTH)\n    y1 = int(y - WIDTH)\n    y2 = int(y + WIDTH)\n    color = None\n    if row['label'] == 'Normal/Mild':\n        color =  (0, 255, 0)\n    elif row['label'] == 'Moderate':\n        color = (255,255,0) \n    elif row['label'] == 'Severe':\n        color = (255,0,0)\n        \n    fontFace = cv2.FONT_HERSHEY_SIMPLEX\n    fontScale = 0.5\n    thickness = 1\n    cv2.rectangle(img, (x1,y1), (x2,y2), color, 2)\n    cv2.putText(img, lbl, (x1,y1), fontFace, fontScale, color, thickness, cv2.LINE_AA)\n\ntmp_df","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:17.326967Z","iopub.execute_input":"2024-08-20T16:33:17.327632Z","iopub.status.idle":"2024-08-20T16:33:17.377454Z","shell.execute_reply.started":"2024-08-20T16:33:17.327599Z","shell.execute_reply":"2024-08-20T16:33:17.376540Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(img)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:17.378695Z","iopub.execute_input":"2024-08-20T16:33:17.378983Z","iopub.status.idle":"2024-08-20T16:33:17.718165Z","shell.execute_reply.started":"2024-08-20T16:33:17.378959Z","shell.execute_reply":"2024-08-20T16:33:17.717181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# label_df[['study_id', 'series_id']].drop_duplicates()","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:17.719377Z","iopub.execute_input":"2024-08-20T16:33:17.719688Z","iopub.status.idle":"2024-08-20T16:33:17.724702Z","shell.execute_reply.started":"2024-08-20T16:33:17.719663Z","shell.execute_reply":"2024-08-20T16:33:17.723635Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    image = np.stack([image]*3, axis=-1).astype('uint8')\n    return image","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:17.725892Z","iopub.execute_input":"2024-08-20T16:33:17.726224Z","iopub.status.idle":"2024-08-20T16:33:17.737908Z","shell.execute_reply.started":"2024-08-20T16:33:17.726192Z","shell.execute_reply":"2024-08-20T16:33:17.735964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filtered_df = label_df[label_df.condition.map(lambda x: x in CONDITIONS)]","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:17.739431Z","iopub.execute_input":"2024-08-20T16:33:17.739762Z","iopub.status.idle":"2024-08-20T16:33:17.919520Z","shell.execute_reply.started":"2024-08-20T16:33:17.739732Z","shell.execute_reply":"2024-08-20T16:33:17.918697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label2id = {}\nid2label = {}\ni = 0\nfor 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","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:17.920756Z","iopub.execute_input":"2024-08-20T16:33:17.921068Z","iopub.status.idle":"2024-08-20T16:33:17.969603Z","shell.execute_reply.started":"2024-08-20T16:33:17.921042Z","shell.execute_reply":"2024-08-20T16:33:17.968449Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"id2label","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:17.970907Z","iopub.execute_input":"2024-08-20T16:33:17.971188Z","iopub.status.idle":"2024-08-20T16:33:17.984160Z","shell.execute_reply.started":"2024-08-20T16:33:17.971164Z","shell.execute_reply":"2024-08-20T16:33:17.983137Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = filtered_df[filtered_df.fold != FOLD]\nval_df = filtered_df[filtered_df.fold == FOLD]","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:17.986141Z","iopub.execute_input":"2024-08-20T16:33:17.986886Z","iopub.status.idle":"2024-08-20T16:33:17.997896Z","shell.execute_reply.started":"2024-08-20T16:33:17.986844Z","shell.execute_reply":"2024-08-20T16:33:17.996801Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # test generated annotations\n\n_IM_DIR = f'{DATA_DIR}/images/train'\n_ANN_DIR = f'{DATA_DIR}/labels/train'\nname = np.random.choice(os.listdir(_IM_DIR))[:-4]\n\nim = plt.imread(os.path.join(_IM_DIR, name+'.jpg')).copy()\nH,W = im.shape[:2]\nanns = np.loadtxt(os.path.join(_ANN_DIR, name+'.txt')).reshape(-1, 5)\n\nfor _cls, x,y,w,h in anns.tolist():\n    x *= W\n    y *= H\n    w *= W\n    h *= H\n    x1 = int(x-w/2)\n    x2 = int(x+w/2)\n    y1 = int(y-h/2)\n    y2 = int(y+h/2)\n    label = id2label[_cls]\n    \n#     if _cls == 0:\n#         c = (255,0,0)\n#     elif _cls == 1:\n#         c = (0,255,0)\n#     else:\n#         c = (255,255,0)\n    c = (0,255,255)\n\n    im = cv2.rectangle(im, (x1,y1), (x2,y2), c, 2)\n    cv2.putText(im, label, (x1,y1), fontFace, 0.3, c, 1, cv2.LINE_AA)\n\n\nplt.imshow(im)","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:17.999668Z","iopub.execute_input":"2024-08-20T16:33:18.000056Z","iopub.status.idle":"2024-08-20T16:33:18.350707Z","shell.execute_reply.started":"2024-08-20T16:33:18.000029Z","shell.execute_reply":"2024-08-20T16:33:18.349774Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ls data_fold0/labels/val","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:18.352137Z","iopub.execute_input":"2024-08-20T16:33:18.352497Z","iopub.status.idle":"2024-08-20T16:33:18.356668Z","shell.execute_reply.started":"2024-08-20T16:33:18.352465Z","shell.execute_reply":"2024-08-20T16:33:18.355826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# os.path.join(_ANN_DIR, name+'.txt')","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:18.357826Z","iopub.execute_input":"2024-08-20T16:33:18.358152Z","iopub.status.idle":"2024-08-20T16:33:18.366325Z","shell.execute_reply.started":"2024-08-20T16:33:18.358120Z","shell.execute_reply":"2024-08-20T16:33:18.365567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# cat 'train_fold0/labels/404602713_1230697721_12.txt'","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:18.367645Z","iopub.execute_input":"2024-08-20T16:33:18.367975Z","iopub.status.idle":"2024-08-20T16:33:18.376041Z","shell.execute_reply.started":"2024-08-20T16:33:18.367946Z","shell.execute_reply":"2024-08-20T16:33:18.375181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Install the ultralytics package from GitHub\n!pip install git+https://github.com/ultralytics/ultralytics.git@main","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:18.377269Z","iopub.execute_input":"2024-08-20T16:33:18.377575Z","iopub.status.idle":"2024-08-20T16:33:49.078865Z","shell.execute_reply.started":"2024-08-20T16:33:18.377550Z","shell.execute_reply":"2024-08-20T16:33:49.077703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for k, v in id2label.items():\n    print(f'{k}: {v}')","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:49.080488Z","iopub.execute_input":"2024-08-20T16:33:49.080805Z","iopub.status.idle":"2024-08-20T16:33:49.086758Z","shell.execute_reply.started":"2024-08-20T16:33:49.080778Z","shell.execute_reply":"2024-08-20T16:33:49.085824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ls","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:49.088624Z","iopub.execute_input":"2024-08-20T16:33:49.089380Z","iopub.status.idle":"2024-08-20T16:33:50.244502Z","shell.execute_reply.started":"2024-08-20T16:33:49.089306Z","shell.execute_reply":"2024-08-20T16:33:50.243317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%writefile yolo_scs.yaml\npath: /kaggle/working/data_fold0 # dataset root dir\ntrain: images/train  \nval: images/val \ntest: images/val \n\n# Classes\nnames:\n    0: left_neural_foraminal_narrowing_l1_l2_normal/mild\n    1: left_neural_foraminal_narrowing_l1_l2_moderate\n    2: left_neural_foraminal_narrowing_l1_l2_severe\n    3: left_neural_foraminal_narrowing_l2_l3_normal/mild\n    4: left_neural_foraminal_narrowing_l2_l3_moderate\n    5: left_neural_foraminal_narrowing_l2_l3_severe\n    6: left_neural_foraminal_narrowing_l3_l4_normal/mild\n    7: left_neural_foraminal_narrowing_l3_l4_moderate\n    8: left_neural_foraminal_narrowing_l3_l4_severe\n    9: left_neural_foraminal_narrowing_l4_l5_normal/mild\n    10: left_neural_foraminal_narrowing_l4_l5_moderate\n    11: left_neural_foraminal_narrowing_l4_l5_severe\n    12: left_neural_foraminal_narrowing_l5_s1_normal/mild\n    13: left_neural_foraminal_narrowing_l5_s1_moderate\n    14: left_neural_foraminal_narrowing_l5_s1_severe\n    15: right_neural_foraminal_narrowing_l1_l2_normal/mild\n    16: right_neural_foraminal_narrowing_l1_l2_moderate\n    17: right_neural_foraminal_narrowing_l1_l2_severe\n    18: right_neural_foraminal_narrowing_l2_l3_normal/mild\n    19: right_neural_foraminal_narrowing_l2_l3_moderate\n    20: right_neural_foraminal_narrowing_l2_l3_severe\n    21: right_neural_foraminal_narrowing_l3_l4_normal/mild\n    22: right_neural_foraminal_narrowing_l3_l4_moderate\n    23: right_neural_foraminal_narrowing_l3_l4_severe\n    24: right_neural_foraminal_narrowing_l4_l5_normal/mild\n    25: right_neural_foraminal_narrowing_l4_l5_moderate\n    26: right_neural_foraminal_narrowing_l4_l5_severe\n    27: right_neural_foraminal_narrowing_l5_s1_normal/mild\n    28: right_neural_foraminal_narrowing_l5_s1_moderate\n    29: right_neural_foraminal_narrowing_l5_s1_severe","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:50.245954Z","iopub.execute_input":"2024-08-20T16:33:50.246255Z","iopub.status.idle":"2024-08-20T16:33:50.254428Z","shell.execute_reply.started":"2024-08-20T16:33:50.246229Z","shell.execute_reply":"2024-08-20T16:33:50.253427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import wandb\nfrom wandb.integration.ultralytics import add_wandb_callback\n\nfrom kaggle_secrets import UserSecretsClient\nuser_secrets = UserSecretsClient()\nsecret_value_0 = user_secrets.get_secret(\"wandbkey\")\nwandb.login(key=secret_value_0)","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:50.255621Z","iopub.execute_input":"2024-08-20T16:33:50.255880Z","iopub.status.idle":"2024-08-20T16:33:57.057617Z","shell.execute_reply.started":"2024-08-20T16:33:50.255858Z","shell.execute_reply":"2024-08-20T16:33:57.056690Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Initialize W&B run\nwandb.init(\n    project=\"lsdc_yolov8\",\n#     name=f\"Demo_fold0\",\n#     tags=[\"baseline\", \"search-lr\", ],\n    group=\";\".join(CONDITIONS),\n#     config={\n#         \"lr\": LR,\n#         \"model-name\":\"xtremedistill-trim\",\n#         \"dataset\": [\n#             \"raw_compettion\",\n#             \"MPWare\",\n#             \"Nicholas\"\n#         ]\n#     }\n)","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:33:57.058835Z","iopub.execute_input":"2024-08-20T16:33:57.059294Z","iopub.status.idle":"2024-08-20T16:34:14.224625Z","shell.execute_reply.started":"2024-08-20T16:33:57.059268Z","shell.execute_reply":"2024-08-20T16:34:14.223694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from ultralytics import YOLO\n\n\n# Initialize YOLO Model\nmodel = YOLO(\"yolov8s.pt\")\n\n# Add W&B callback for Ultralytics\nadd_wandb_callback(model, enable_model_checkpointing=True)\n\n# Train/fine-tune your model\n# At the end of each epoch, predictions on validation batches are logged\n# to a W&B table with insightful and interactive overlays for\n# computer vision tasks\nmodel.train(project=\"lsdc_yolov8\", data=\"yolo_scs.yaml\", \n            epochs=EPOCHS, imgsz=OD_INPUT_SIZE, batch=BATCH_SIZE)\n\n# Finish the W&B run\nwandb.finish()","metadata":{"execution":{"iopub.status.busy":"2024-08-20T16:34:14.225826Z","iopub.execute_input":"2024-08-20T16:34:14.226149Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # test generated annotations\n\n_IM_DIR = f'{DATA_DIR}/images/val'\n_ANN_DIR = f'{DATA_DIR}/labels/val'\nname = np.random.choice(os.listdir(_IM_DIR))[:-4]\n\npath = os.path.join(_IM_DIR, name+'.jpg')\n\nim = plt.imread(path).copy()\nH,W = im.shape[:2]\nanns = np.loadtxt(os.path.join(_ANN_DIR, name+'.txt')).reshape(-1, 5)\n\nfor _cls, x,y,w,h in anns.tolist():\n    x *= W\n    y *= H\n    w *= W\n    h *= H\n    x1 = int(x-w/2)\n    x2 = int(x+w/2)\n    y1 = int(y-h/2)\n    y2 = int(y+h/2)\n    label = id2label[_cls]\n    print(label)\n    \n#     if _cls == 0:\n#         c = (255,0,0)\n#     elif _cls == 1:\n#         c = (0,255,0)\n#     else:\n#         c = (255,255,0)\n    c = (0,255,255)\n\n    im = cv2.rectangle(im, (x1,y1), (x2,y2), c, 2)\n    cv2.putText(im, label, (x1,y1), fontFace, 0.3, c, 1, cv2.LINE_AA)\n\n\nplt.imshow(im)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Initialize YOLO Model\nmodel = YOLO(glob.glob(\"lsdc_yolov8/*/weights/best.pt\")[0])\n\n# Add W&B callback for Ultralytics\n# add_wandb_callback(model, enable_model_checkpointing=True)\n\n# Perform prediction which automatically logs to a W&B Table\n# with interactive overlays for bounding boxes, segmentation masks\nout = model.predict([path], save=True, conf=0.2)\n\n# Finish the W&B run\nwandb.finish()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"im = plt.imread(glob.glob(f'{out[0].save_dir}/*.jpg')[0])\nplt.imshow(im)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}