{"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":"nvidiaTeslaT4","dataSources":[{"sourceType":"competition","sourceId":24800,"datasetId":1042002,"databundleVersionId":1831594},{"sourceType":"datasetVersion","sourceId":15094918,"datasetId":9664561,"databundleVersionId":15979687}],"dockerImageVersionId":31287,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip -q install pydicom pylibjpeg pylibjpeg-libjpeg pylibjpeg-openjpeg ultralytics albumentations\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:19:32.719843Z","iopub.execute_input":"2026-03-25T16:19:32.720482Z","iopub.status.idle":"2026-03-25T16:19:36.206061Z","shell.execute_reply.started":"2026-03-25T16:19:32.720452Z","shell.execute_reply":"2026-03-25T16:19:36.205066Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport cv2\nimport yaml\nimport time\nimport random\nimport numpy as np\nimport pandas as pd\nimport pydicom\nimport albumentations as A\n\nfrom collections import defaultdict\nfrom sklearn.model_selection import train_test_split\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:19:36.207788Z","iopub.execute_input":"2026-03-25T16:19:36.208445Z","iopub.status.idle":"2026-03-25T16:19:36.212877Z","shell.execute_reply.started":"2026-03-25T16:19:36.208415Z","shell.execute_reply":"2026-03-25T16:19:36.21229Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Config","metadata":{}},{"cell_type":"code","source":"# =========================\n# PATH CONFIG\n# =========================\nfrom pathlib import Path\n\nROOT = Path(\"/kaggle/input/competitions/vinbigdata-chest-xray-abnormalities-detection\")\n\nTRAIN_DIR = ROOT / \"train\"\nTRAIN_CSV = '/kaggle/input/datasets/benxelua/correct-label/annotations/annotations_train.csv'\n\n# output YOLO dataset\nOUT_ROOT = Path(\"/kaggle/working/yolo_vindr_multiclass\")\n\nPNG_DIR = OUT_ROOT / \"images\"\nLBL_DIR = OUT_ROOT / \"labels\"\n\nIMG_TRAIN_DIR = PNG_DIR / \"train\"\nIMG_VAL_DIR   = PNG_DIR / \"val\"\nLBL_TRAIN_DIR = LBL_DIR / \"train\"\nLBL_VAL_DIR   = LBL_DIR / \"val\"\n\nfor d in [IMG_TRAIN_DIR, IMG_VAL_DIR, LBL_TRAIN_DIR, LBL_VAL_DIR]:\n    d.mkdir(parents=True, exist_ok=True)\n\n# =========================\n# SUBSET CONFIG\n# =========================\nUSE_SMALL_SUBSET = False     # True = subset nhỏ, False = full dataset\nIMAGES_PER_CLASS = 10       # mỗi class lấy khoảng 10-15 ảnh, ví dụ 12\nSEED = 42\n\n# =========================\n# IMAGE CONFIG\n# =========================\nIMG_SIZE = 1024             # có thể đổi 640 cho nhanh hơn\nSAVE_AS_JPG = False         # True nhanh hơn PNG\nJPG_QUALITY = 95","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:19:36.213826Z","iopub.execute_input":"2026-03-25T16:19:36.214175Z","iopub.status.idle":"2026-03-25T16:19:36.227871Z","shell.execute_reply.started":"2026-03-25T16:19:36.214145Z","shell.execute_reply":"2026-03-25T16:19:36.227116Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Helper functions","metadata":{}},{"cell_type":"code","source":"def seed_everything(seed=42):\n    random.seed(seed)\n    np.random.seed(seed)\n\nseed_everything(SEED)\n\n\ndef list_dicom_files(folder: Path):\n    files = []\n    for p in sorted(folder.rglob(\"*\")):\n        if p.is_file() and p.suffix.lower() in {\".dicom\", \".dcm\"}:\n            files.append(p)\n    return files\n\n\nfrom pathlib import Path\nimport numpy as np\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_modality_lut\n\n# def read_dicom_to_uint8(path: Path):\n#     ds = pydicom.dcmread(str(path))\n\n#     # 1. Rescale / Modality LUT\n#     img = apply_modality_lut(ds.pixel_array, ds).astype(np.float32)\n\n#     # 2. Handle MONOCHROME1\n#     if getattr(ds, \"PhotometricInterpretation\", \"\") == \"MONOCHROME1\":\n#         img = img.max() - img\n\n#     # 3. Min-max normalization\n#     img_min = img.min()\n#     img_max = img.max()\n#     if img_max > img_min:\n#         img = (img - img_min) / (img_max - img_min)\n#     else:\n#         img = np.zeros_like(img)\n\n#     # 4. Convert to uint8\n#     return (img * 255.0).clip(0, 255).astype(np.uint8)\n\nfrom pathlib import Path\nimport numpy as np\nimport pydicom\n\ndef read_dicom_to_uint8(path: Path):\n    ds = pydicom.dcmread(str(path))\n    \n    # 1. Read raw pixel array only\n    img = ds.pixel_array.astype(np.float32)\n\n    # 2. Handle Photometric Interpretation\n    if getattr(ds, \"PhotometricInterpretation\", \"\") == \"MONOCHROME1\":\n        img = np.max(img) - img\n\n    # 3. Raw min-max normalization\n    img = img - np.min(img)\n    max_val = np.max(img)\n    if max_val > 0:\n        img = img / max_val\n\n    # 4. Convert to uint8\n    img = (img * 255.0).clip(0, 255).astype(np.uint8)\n    return img\n\ndef resize_image_keep_shape(img, size=1024):\n    h, w = img.shape[:2]\n    resized = cv2.resize(img, (size, size), interpolation=cv2.INTER_AREA)\n    return resized, w, h","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:19:36.229639Z","iopub.execute_input":"2026-03-25T16:19:36.229896Z","iopub.status.idle":"2026-03-25T16:19:36.238863Z","shell.execute_reply.started":"2026-03-25T16:19:36.229876Z","shell.execute_reply":"2026-03-25T16:19:36.238293Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Đọc CSV và chuẩn hóa annotation","metadata":{}},{"cell_type":"code","source":"df_full = pd.read_csv(TRAIN_CSV)\n\nprint(\"Full CSV shape:\", df_full.shape)\nprint(\"Columns:\", df_full.columns.tolist())\ndisplay(df_full.head())\n\n# Bỏ No finding\nif \"class_name\" in df_full.columns:\n    df_full = df_full[df_full[\"class_name\"].fillna(\"\").str.lower() != \"no finding\"].copy()\nelse:\n    raise ValueError(\"train.csv của bạn cần có cột class_name để làm multi-class dễ hơn.\")\n\n# Giữ bbox hợp lệ\nrequired_cols = [\"image_id\", \"class_name\", \"x_min\", \"y_min\", \"x_max\", \"y_max\"]\nfor c in required_cols:\n    if c not in df_full.columns:\n        raise ValueError(f\"Thiếu cột {c}\")\n\ndf_full = df_full.dropna(subset=required_cols).copy()\ndf_full = df_full[(df_full[\"x_max\"] > df_full[\"x_min\"]) & (df_full[\"y_max\"] > df_full[\"y_min\"])].copy()\n\n# Build class list\nCLASS_NAMES = sorted(df_full[\"class_name\"].unique().tolist())\nCLASS2ID = {name: i for i, name in enumerate(CLASS_NAMES)}\nID2CLASS = {i: name for name, i in CLASS2ID.items()}\n\nprint(\"Num classes:\", len(CLASS_NAMES))\nprint(\"CLASS_NAMES:\", CLASS_NAMES)\nprint(\"CLASS2ID:\", CLASS2ID)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:19:36.239674Z","iopub.execute_input":"2026-03-25T16:19:36.239886Z","iopub.status.idle":"2026-03-25T16:19:36.376286Z","shell.execute_reply.started":"2026-03-25T16:19:36.239867Z","shell.execute_reply":"2026-03-25T16:19:36.375699Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Chọn subset nhỏ theo từng class","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\n\nprint(\"Building subset from CSV only...\")\n\n# chỉ dùng annotation đã clean\ndf_work = df_full.copy()\n\n# group 1 lần\nclass_to_ids = (\n    df_work.groupby(\"class_name\")[\"image_id\"]\n    .unique()\n    .to_dict()\n)\n\ndef build_small_subset_by_class_fast(class_to_ids, images_per_class=12, seed=42):\n    rng = np.random.default_rng(seed)\n\n    selected_ids = set()\n    per_class_summary = []\n\n    for cls in sorted(class_to_ids.keys()):\n        cls_ids = list(class_to_ids[cls])\n        n_take = min(images_per_class, len(cls_ids))\n\n        if n_take > 0:\n            chosen = rng.choice(cls_ids, size=n_take, replace=False).tolist()\n        else:\n            chosen = []\n\n        selected_ids.update(chosen)\n\n        per_class_summary.append({\n            \"class_name\": cls,\n            \"available_images\": len(cls_ids),\n            \"selected_images\": len(chosen)\n        })\n\n    return selected_ids, pd.DataFrame(per_class_summary)\n\ndicom_files_all = list_dicom_files(TRAIN_DIR)\n\nall_file_ids = {p.stem for p in dicom_files_all}\n\nif USE_SMALL_SUBSET:\n    chosen_ids, subset_summary_df = build_small_subset_by_class_fast(\n        class_to_ids,\n        images_per_class=IMAGES_PER_CLASS,\n        seed=SEED\n    )\n    print(\"Using SMALL subset mode\")\n    print(\"Total selected unique images:\", len(chosen_ids))\n    display(subset_summary_df)\nelse:\n    chosen_ids = set(all_file_ids)\n    print(\"Using FULL dataset mode\")\n    print(\"Total selected unique images:\", len(chosen_ids))\n\n\nprint(\"Scanning DICOM files...\")\n\n# chỉ giữ file thuộc chosen_ids\ndicom_files_selected = [p for p in dicom_files_all if p.stem in chosen_ids]\n\nprint(\"Total DICOM files scanned:\", len(dicom_files_all))\nprint(\"Selected DICOM files:\", len(dicom_files_selected))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:19:36.377114Z","iopub.execute_input":"2026-03-25T16:19:36.37741Z","iopub.status.idle":"2026-03-25T16:19:41.307836Z","shell.execute_reply.started":"2026-03-25T16:19:36.377387Z","shell.execute_reply":"2026-03-25T16:19:41.307296Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dicom_files_selected = [p for p in dicom_files_all if p.stem in chosen_ids]\ndf = df_full[df_full[\"image_id\"].isin(chosen_ids)].copy()\n\nprint(\"Selected DICOM files:\", len(dicom_files_selected))\nprint(\"Selected annotation rows:\", len(df))\nprint(\"Selected unique image_id:\", df[\"image_id\"].nunique())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:19:41.308634Z","iopub.execute_input":"2026-03-25T16:19:41.308935Z","iopub.status.idle":"2026-03-25T16:19:41.324739Z","shell.execute_reply.started":"2026-03-25T16:19:41.308911Z","shell.execute_reply":"2026-03-25T16:19:41.32406Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Split train/val","metadata":{}},{"cell_type":"code","source":"from collections import defaultdict\nimport numpy as np\n\ndef build_multilabel_split(df, image_ids, val_ratio=0.2, seed=42):\n    rng = np.random.default_rng(seed)\n\n    image_ids = list(sorted(set(image_ids)))\n    class_to_images = {\n        cls: set(df.loc[df[\"class_name\"] == cls, \"image_id\"].unique()) & set(image_ids)\n        for cls in sorted(df[\"class_name\"].unique())\n    }\n\n    val_ids = set()\n\n    # Mỗi class cố gắng lấy ít nhất 1 ảnh vào val\n    for cls, ids in class_to_images.items():\n        ids = list(ids - val_ids)\n        if len(ids) > 0:\n            chosen = rng.choice(ids, size=1, replace=False)\n            val_ids.update(chosen.tolist())\n\n    # Bổ sung cho đủ tỷ lệ val mong muốn\n    target_val_size = max(1, int(len(image_ids) * val_ratio))\n    remaining = list(set(image_ids) - val_ids)\n\n    if len(val_ids) < target_val_size and len(remaining) > 0:\n        n_more = min(target_val_size - len(val_ids), len(remaining))\n        extra = rng.choice(remaining, size=n_more, replace=False)\n        val_ids.update(extra.tolist())\n\n    train_ids = set(image_ids) - val_ids\n    return train_ids, val_ids","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:19:41.32565Z","iopub.execute_input":"2026-03-25T16:19:41.325946Z","iopub.status.idle":"2026-03-25T16:19:41.338254Z","shell.execute_reply.started":"2026-03-25T16:19:41.325914Z","shell.execute_reply":"2026-03-25T16:19:41.337634Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"image_ids_selected = sorted([p.stem for p in dicom_files_selected])\n\ntrain_ids, val_ids = build_multilabel_split(\n    df=df,\n    image_ids=image_ids_selected,\n    val_ratio=0.2,\n    seed=SEED\n)\n\nprint(\"Train images:\", len(train_ids))\nprint(\"Val images:\", len(val_ids))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:19:41.33925Z","iopub.execute_input":"2026-03-25T16:19:41.339515Z","iopub.status.idle":"2026-03-25T16:19:41.363835Z","shell.execute_reply.started":"2026-03-25T16:19:41.339493Z","shell.execute_reply":"2026-03-25T16:19:41.363298Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Lưu metadata để lần sau dùng lại","metadata":{}},{"cell_type":"code","source":"import json\n\nmeta = {\n    \"use_small_subset\": USE_SMALL_SUBSET,\n    \"images_per_class\": IMAGES_PER_CLASS,\n    \"seed\": SEED,\n    \"img_size\": IMG_SIZE,\n    \"save_as_jpg\": SAVE_AS_JPG,\n    \"jpg_quality\": JPG_QUALITY,\n    \"num_classes\": len(CLASS_NAMES),\n    \"class_names\": CLASS_NAMES,\n    \"chosen_ids\": sorted(list(chosen_ids)),\n    \"train_ids\": sorted(list(train_ids)),\n    \"val_ids\": sorted(list(val_ids)),\n}\n\nwith open(OUT_ROOT / \"meta.json\", \"w\") as f:\n    json.dump(meta, f, indent=2)\n\nprint(\"Saved:\", OUT_ROOT / \"meta.json\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:19:41.365728Z","iopub.execute_input":"2026-03-25T16:19:41.365936Z","iopub.status.idle":"2026-03-25T16:19:41.371956Z","shell.execute_reply.started":"2026-03-25T16:19:41.365917Z","shell.execute_reply":"2026-03-25T16:19:41.371318Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Build annotation map nhanh","metadata":{}},{"cell_type":"code","source":"from collections import defaultdict\n\nann_map = defaultdict(list)\n\nfor r in df.itertuples(index=False):\n    class_id = CLASS2ID[r.class_name]\n    ann_map[r.image_id].append(\n        (r.x_min, r.y_min, r.x_max, r.y_max, class_id)\n    )\n\nsplit_map = {}\nfor x in train_ids:\n    split_map[x] = \"train\"\nfor x in val_ids:\n    split_map[x] = \"val\"\n\nprint(\"Images with annotations:\", len(ann_map))\nprint(\"Images in split map:\", len(split_map))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:19:41.372748Z","iopub.execute_input":"2026-03-25T16:19:41.373073Z","iopub.status.idle":"2026-03-25T16:19:41.391061Z","shell.execute_reply.started":"2026-03-25T16:19:41.373051Z","shell.execute_reply":"2026-03-25T16:19:41.390513Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Export ảnh + label nhanh, có track time","metadata":{}},{"cell_type":"code","source":"DICOM_TRAIN_AUG = A.Compose(\n    [\n        A.HorizontalFlip(p=0.5),\n        A.Sharpen(alpha=(0.1, 0.3), lightness=(0.9, 1.1), p=0.20),\n        A.GaussianBlur(blur_limit=(3, 5), sigma_limit=(0.1, 1.5), p=0.20),\n        A.CLAHE(clip_limit=2.0, tile_grid_size=(8, 8), p=0.20),\n        A.RandomBrightnessContrast(\n            brightness_limit=0.10,\n            contrast_limit=0.0,\n            p=0.20,\n        ),\n    ],\n    bbox_params=A.BboxParams(\n        format=\"pascal_voc\",\n        label_fields=[\"class_labels\"],\n        min_visibility=0.0,\n    ),\n)\n\n\ndef sanitize_pascal_voc_boxes(boxes, width, height):\n    sanitized = []\n    for (x1, y1, x2, y2, class_id) in boxes:\n        x1 = float(np.clip(x1, 0, width))\n        y1 = float(np.clip(y1, 0, height))\n        x2 = float(np.clip(x2, 0, width))\n        y2 = float(np.clip(y2, 0, height))\n\n        if x2 <= x1 or y2 <= y1:\n            continue\n\n        sanitized.append((x1, y1, x2, y2, class_id))\n\n    return sanitized\n\n\ndef apply_dicom_augmentation(img, boxes, split):\n    height, width = img.shape[:2]\n    boxes = sanitize_pascal_voc_boxes(boxes, width=width, height=height)\n\n    if split != \"train\" or len(boxes) == 0:\n        return img, boxes\n\n    bboxes = [(x1, y1, x2, y2) for (x1, y1, x2, y2, _) in boxes]\n    class_labels = [class_id for (_, _, _, _, class_id) in boxes]\n\n    transformed = DICOM_TRAIN_AUG(\n        image=img,\n        bboxes=bboxes,\n        class_labels=class_labels,\n    )\n\n    aug_boxes = [\n        (x1, y1, x2, y2, class_id)\n        for (x1, y1, x2, y2), class_id in zip(\n            transformed[\"bboxes\"],\n            transformed[\"class_labels\"],\n        )\n    ]\n    aug_boxes = sanitize_pascal_voc_boxes(aug_boxes, width=width, height=height)\n    return transformed[\"image\"], aug_boxes\n\n\ndef process_one_dicom(dicom_path: Path):\n    t0 = time.perf_counter()\n\n    image_id = dicom_path.stem\n    split = split_map.get(image_id)\n    if split is None:\n        return {\n            \"image_id\": image_id,\n            \"ok\": False,\n            \"reason\": \"not_in_split\",\n            \"elapsed\": 0.0\n        }\n\n    boxes = ann_map.get(image_id, [])\n\n    # Augment ngay trên ảnh lấy từ DICOM trước khi resize và export sang PNG/JPG.\n    img = read_dicom_to_uint8(dicom_path)\n    img, boxes = apply_dicom_augmentation(img, boxes, split)\n    img_resized, orig_w, orig_h = resize_image_keep_shape(img, size=IMG_SIZE)\n\n    ext = \".jpg\" if SAVE_AS_JPG else \".png\"\n\n    if split == \"train\":\n        img_out_path = IMG_TRAIN_DIR / f\"{image_id}{ext}\"\n        lbl_out_path = LBL_TRAIN_DIR / f\"{image_id}.txt\"\n    else:\n        img_out_path = IMG_VAL_DIR / f\"{image_id}{ext}\"\n        lbl_out_path = LBL_VAL_DIR / f\"{image_id}.txt\"\n\n    if SAVE_AS_JPG:\n        cv2.imwrite(\n            str(img_out_path),\n            img_resized,\n            [cv2.IMWRITE_JPEG_QUALITY, JPG_QUALITY]\n        )\n    else:\n        cv2.imwrite(\n            str(img_out_path),\n            img_resized,\n            [cv2.IMWRITE_PNG_COMPRESSION, 0]\n        )\n\n    yolo_lines = []\n\n    if len(boxes) > 0:\n        sx = IMG_SIZE / orig_w\n        sy = IMG_SIZE / orig_h\n\n        for (x1, y1, x2, y2, class_id) in boxes:\n            x1 *= sx\n            x2 *= sx\n            y1 *= sy\n            y2 *= sy\n\n            xc = ((x1 + x2) / 2.0) / IMG_SIZE\n            yc = ((y1 + y2) / 2.0) / IMG_SIZE\n            bw = (x2 - x1) / IMG_SIZE\n            bh = (y2 - y1) / IMG_SIZE\n\n            xc = min(max(xc, 0.0), 1.0)\n            yc = min(max(yc, 0.0), 1.0)\n            bw = min(max(bw, 0.0), 1.0)\n            bh = min(max(bh, 0.0), 1.0)\n\n            if bw > 0 and bh > 0:\n                yolo_lines.append(f\"{class_id} {xc:.6f} {yc:.6f} {bw:.6f} {bh:.6f}\")\n\n    with open(lbl_out_path, \"w\") as f:\n        f.write(\"\\n\".join(yolo_lines))\n\n    elapsed = time.perf_counter() - t0\n    return {\n        \"image_id\": image_id,\n        \"ok\": True,\n        \"reason\": \"done\",\n        \"elapsed\": elapsed\n    }\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:19:41.391916Z","iopub.execute_input":"2026-03-25T16:19:41.392165Z","iopub.status.idle":"2026-03-25T16:19:41.409981Z","shell.execute_reply.started":"2026-03-25T16:19:41.392145Z","shell.execute_reply":"2026-03-25T16:19:41.409272Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Chạy export song song + ETA","metadata":{}},{"cell_type":"code","source":"max_workers = min(8, os.cpu_count() or 4)\nprint(\"max_workers =\", max_workers)\n\ntotal_files = len(dicom_files_selected)\nstart_all = time.perf_counter()\n\ndone = 0\nok_count = 0\ntimes = []\n\nlog_every = 20\n\nwith ThreadPoolExecutor(max_workers=max_workers) as executor:\n    futures = [executor.submit(process_one_dicom, p) for p in dicom_files_selected]\n\n    for future in as_completed(futures):\n        result = future.result()\n        done += 1\n\n        if result[\"ok\"]:\n            ok_count += 1\n            times.append(result[\"elapsed\"])\n\n        if done % log_every == 0 or done == total_files:\n            elapsed_all = time.perf_counter() - start_all\n            avg_per_file = elapsed_all / done\n            speed = done / elapsed_all if elapsed_all > 0 else 0.0\n            remaining = total_files - done\n            eta_sec = remaining * avg_per_file\n\n            avg_worker = np.mean(times) if len(times) > 0 else 0.0\n            p50_worker = np.median(times) if len(times) > 0 else 0.0\n\n            print(\n                f\"[{done}/{total_files}] \"\n                f\"ok={ok_count} | \"\n                f\"wall={elapsed_all:.1f}s | \"\n                f\"speed={speed:.2f} img/s | \"\n                f\"avg_wall/file={avg_per_file:.3f}s | \"\n                f\"avg_worker={avg_worker:.3f}s | \"\n                f\"p50_worker={p50_worker:.3f}s | \"\n                f\"ETA={eta_sec:.1f}s\"\n            )\n\ntotal_elapsed = time.perf_counter() - start_all\nprint(\"\\nDONE\")\nprint(f\"Processed: {done}/{total_files}\")\nprint(f\"Success:   {ok_count}\")\nprint(f\"Total time: {total_elapsed:.2f}s\")\nprint(f\"Overall speed: {done / total_elapsed:.2f} img/s\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:19:41.410907Z","iopub.execute_input":"2026-03-25T16:19:41.411167Z","iopub.status.idle":"2026-03-25T16:21:19.780695Z","shell.execute_reply.started":"2026-03-25T16:19:41.411129Z","shell.execute_reply":"2026-03-25T16:21:19.780009Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_ext = \"*.jpg\" if SAVE_AS_JPG else \"*.png\"\n\nprint(\"Train images:\", len(list(IMG_TRAIN_DIR.glob(img_ext))))\nprint(\"Val images:\", len(list(IMG_VAL_DIR.glob(img_ext))))\nprint(\"Train labels:\", len(list(LBL_TRAIN_DIR.glob(\"*.txt\"))))\nprint(\"Val labels:\", len(list(LBL_VAL_DIR.glob(\"*.txt\"))))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:21:19.781615Z","iopub.execute_input":"2026-03-25T16:21:19.781863Z","iopub.status.idle":"2026-03-25T16:21:19.789874Z","shell.execute_reply.started":"2026-03-25T16:21:19.781841Z","shell.execute_reply":"2026-03-25T16:21:19.789306Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Tạo data.yaml","metadata":{}},{"cell_type":"code","source":"data_yaml = {\n    \"path\": str(OUT_ROOT),\n    \"train\": \"images/train\",\n    \"val\": \"images/val\",\n    \"names\": {i: name for i, name in enumerate(CLASS_NAMES)}\n}\n\nyaml_path = OUT_ROOT / \"data.yaml\"\nwith open(yaml_path, \"w\") as f:\n    yaml.dump(data_yaml, f, sort_keys=False)\n\nprint(\"Saved:\", yaml_path)\nprint(yaml_path.read_text())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:21:19.790711Z","iopub.execute_input":"2026-03-25T16:21:19.790989Z","iopub.status.idle":"2026-03-25T16:21:19.803764Z","shell.execute_reply.started":"2026-03-25T16:21:19.790959Z","shell.execute_reply":"2026-03-25T16:21:19.803115Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nfor i in range(10):\n    img_ext = \".jpg\" if SAVE_AS_JPG else \".png\"\n    sample_image_path = list(IMG_TRAIN_DIR.glob(f\"*{img_ext}\"))[i]\n    sample_label_path = LBL_TRAIN_DIR / f\"{sample_image_path.stem}.txt\"\n    \n    img = cv2.imread(str(sample_image_path))\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    \n    h, w = img.shape[:2]\n    \n    if sample_label_path.exists():\n        lines = sample_label_path.read_text().strip().splitlines()\n        for line in lines:\n            parts = line.strip().split()\n            if len(parts) != 5:\n                continue\n    \n            cls_id = int(float(parts[0]))\n            xc, yc, bw, bh = map(float, parts[1:])\n    \n            x1 = int((xc - bw/2) * w)\n            y1 = int((yc - bh/2) * h)\n            x2 = int((xc + bw/2) * w)\n            y2 = int((yc + bh/2) * h)\n    \n            cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 2)\n            cv2.putText(\n                img,\n                ID2CLASS[cls_id],\n                (x1, max(20, y1 - 5)),\n                cv2.FONT_HERSHEY_SIMPLEX,\n                0.6,\n                (255, 0, 0),\n                2\n            )\n    \n    plt.figure(figsize=(10, 10))\n    plt.imshow(img)\n    plt.title(sample_image_path.name)\n    plt.axis(\"off\")\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:21:19.804619Z","iopub.execute_input":"2026-03-25T16:21:19.804842Z","iopub.status.idle":"2026-03-25T16:21:22.878904Z","shell.execute_reply.started":"2026-03-25T16:21:19.804822Z","shell.execute_reply":"2026-03-25T16:21:22.878084Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_id = \"8573fa95ec3defbe2dec45d85a5093a1\"\ntmp = df_full[df_full[\"image_id\"] == img_id].copy()\nprint(tmp[[\"image_id\", \"class_name\", \"x_min\", \"y_min\", \"x_max\", \"y_max\"]])\nprint(\"Num rows:\", len(tmp))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:23:08.282637Z","iopub.execute_input":"2026-03-25T16:23:08.283395Z","iopub.status.idle":"2026-03-25T16:23:08.29469Z","shell.execute_reply.started":"2026-03-25T16:23:08.283361Z","shell.execute_reply":"2026-03-25T16:23:08.29389Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_id = \"0fca086ebe001f784d428aa9973ba691\"\n\nfor p in [LBL_TRAIN_DIR / f\"{img_id}.txt\", LBL_VAL_DIR / f\"{img_id}.txt\"]:\n    if p.exists():\n        print(\"FOUND:\", p)\n        print(p.read_text())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:21:22.893282Z","iopub.execute_input":"2026-03-25T16:21:22.893637Z","iopub.status.idle":"2026-03-25T16:21:22.905696Z","shell.execute_reply.started":"2026-03-25T16:21:22.893602Z","shell.execute_reply":"2026-03-25T16:21:22.904983Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# from pathlib import Path\nimport numpy as np\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_modality_lut\n\ndef read_dicom_rescale_minmax(path: Path):\n    ds = pydicom.dcmread(str(path))\n\n    # 1. Rescale / Modality LUT\n    img = apply_modality_lut(ds.pixel_array, ds).astype(np.float32)\n\n    # 2. Handle MONOCHROME1\n    if getattr(ds, \"PhotometricInterpretation\", \"\") == \"MONOCHROME1\":\n        img = img.max() - img\n\n    # 3. Min-max normalization\n    img_min = img.min()\n    img_max = img.max()\n    if img_max > img_min:\n        img = (img - img_min) / (img_max - img_min)\n    else:\n        img = np.zeros_like(img)\n\n    # 4. Convert to uint8\n    return (img * 255.0).clip(0, 255).astype(np.uint8)Train YOLO","metadata":{}},{"cell_type":"code","source":"# import torch\n# from ultralytics import YOLO\n\n# device = 0 if torch.cuda.is_available() else \"cpu\"\n# print(\"Device:\", device)\n\n# # model nhỏ để test nhanh\n# model = YOLO(\"yolov8n.pt\")\n\n# model.train(\n#     data=str(yaml_path),\n#     epochs=50,               # test nhanh, có thể đổi 1 / 3 / 10\n#     imgsz=IMG_SIZE,\n#     batch=8,                # nếu thiếu VRAM thì giảm xuống 4\n#     device=device,\n#     project=str(OUT_ROOT / \"runs\"),\n#     name=\"yolov8n_multiclass_test\",\n#     exist_ok=True\n# )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:21:22.906672Z","iopub.execute_input":"2026-03-25T16:21:22.906947Z","iopub.status.idle":"2026-03-25T16:21:22.919324Z","shell.execute_reply.started":"2026-03-25T16:21:22.906924Z","shell.execute_reply":"2026-03-25T16:21:22.918622Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from pathlib import Path\nimport torch\nfrom ultralytics import YOLO\n\n\ndevice = 0 if torch.cuda.is_available() else \"cpu\"\nprint(\"Device:\", device)\n\nMODEL_NAME = \"yolov8n.pt\"   # baseline\nINIT_LR = 1e-3              # bắt đầu từ 1e-3 đúng yêu cầu\nMIN_LR = 1e-5               # chặn dưới\nFACTOR = 0.1                # giảm còn 0.1 lần\nPLATEAU_PATIENCE = 2        # 2 lần loss không giảm thì giảm LR\nEARLY_STOPPING = 6          # early stopping = 6\n\n# =========================\n# REDUCE ON PLATEAU CALLBACK\n# =========================\nbest_loss = float(\"inf\")\nbad_epochs = 0\n\ndef reduce_lr_on_plateau(trainer):\n    \"\"\"\n    Giảm LR nếu train loss không giảm sau 2 epoch liên tiếp.\n    Theo yêu cầu:\n        1e-3 -> 1e-4 -> 1e-5\n    \"\"\"\n    global best_loss, bad_epochs\n\n    # trainer.tloss là tensor loss train hiện tại\n    current_loss = float(trainer.tloss.mean().item())\n\n    if current_loss < best_loss - 1e-8:\n        best_loss = current_loss\n        bad_epochs = 0\n    else:\n        bad_epochs += 1\n\n    if bad_epochs >= PLATEAU_PATIENCE:\n        for pg in trainer.optimizer.param_groups:\n            old_lr = pg[\"lr\"]\n            new_lr = max(old_lr * FACTOR, MIN_LR)\n            pg[\"lr\"] = new_lr\n\n        print(\n            f\"[ReduceLROnPlateau] Epoch {trainer.epoch + 1}: \"\n            f\"loss không giảm {PLATEAU_PATIENCE} lần -> giảm LR xuống {trainer.optimizer.param_groups[0]['lr']:.1e}\"\n        )\n        bad_epochs = 0\n\n# =========================\n# TRAIN\n# =========================\nmodel = YOLO(MODEL_NAME)\n\n# gắn callback vào cuối mỗi epoch train\nmodel.add_callback(\"on_train_epoch_end\", reduce_lr_on_plateau)\n\nresults = model.train(\n    data=str(yaml_path),\n    epochs=100,\n    imgsz=IMG_SIZE,\n    batch=8,\n    device=device,\n\n    # optimizer\n    optimizer=\"AdamW\",          # hoặc \"Adam\"\n\n    # learning rate\n    lr0=INIT_LR,                # 1e-3 lúc đầu\n    cos_lr=False,               # tắt cosine vì ông muốn plateau scheduler\n    lrf=1.0,                    # giữ scheduler mặc định không tự decay theo cosine\n\n    # warmup\n    warmup_epochs=3.0,          # Ultralytics warmup theo epoch, không phải 1000 iters trực tiếp\n    warmup_momentum=0.8,\n    warmup_bias_lr=0.1,\n\n    # early stopping\n    patience=EARLY_STOPPING,\n\n    # DICOM đã được augment trước khi export sang PNG/JPG nên tắt augment tương ứng ở đây.\n    fliplr=0.0,\n    flipud=0.0,\n    hsv_h=0.0,\n    hsv_s=0.0,\n    hsv_v=0.0,\n\n    # giữ baseline sạch\n    degrees=0.0,\n    translate=0.0,\n    scale=0.0,\n    shear=0.0,\n    perspective=0.0,\n    mosaic=0.0,\n    mixup=0.0,\n    cutmix=0.0,\n\n    # log/save\n    project=str(OUT_ROOT / \"runs\"),\n    name=\"yolov8n_baseline_reduce_on_plateau\",\n    exist_ok=True,\n    seed=42,\n    deterministic=True,\n    save=True,\n    amp=True\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T16:21:22.920106Z","iopub.execute_input":"2026-03-25T16:21:22.920902Z","iopub.status.idle":"2026-03-25T16:22:08.006078Z","shell.execute_reply.started":"2026-03-25T16:21:22.920881Z","shell.execute_reply":"2026-03-25T16:22:08.004447Z"}},"outputs":[],"execution_count":null}]}