"""14장 · 실전: rfdetr 패키지 (2) 사전 학습 모델로 추론 → 도형 세상에 미세 조정 → 평가.

무엇을 하나
  1. COCO 로 학습된 RF-DETR Nano 를 내려받아 도형 세상 그림에 그대로 써 본다 (도형을 모른다는 것을 확인).
     predict 가 돌려주는 supervision.Detections 의 구조와, 입력 형태(경로 · PIL · numpy · 텐서 · 배치)를 확인한다.
  2. ch14_make_coco.py 가 만든 COCO 형식 폴더로 미세 조정한다: (a) 사전 학습 가중치에서 시작(5 에폭),
     (b) 같은 설정으로 무작위 초기화에서 시작(3 에폭). 에폭마다의 손실 · 검증 AP 를 metrics.csv 에서 읽어 표로 낸다.
  3. 시험 세트를 패키지의 evaluate() 와 3장의 evaluate_ap 로 각각 채점해 비교한다.
  4. 추론 설정(점수 문턱값 · num_select · 입력 해상도)을 바꿔 가며 결과가 어떻게 달라지는지 본다.
  5. 그림 4장: ch14-coco-model-on-shapes.png, ch14-finetune-curves.png, ch14-test-predictions.png,
     ch14-inference-knobs.png

실행
  python ch14_make_coco.py          # 먼저 데이터셋 폴더를 만든다
  python ch14_finetune.py           # 본 실행: 미세 조정 2회. 8GB 노트북 GPU 를 다른 작업과 나눠 쓰며 약 30분
                                    #   (학습 18.2분 + 8.5분, 나머지 단계 약 3분 반), GPU 메모리 최대 1.6 GiB
  python ch14_finetune.py --quick   # 학습 없이 1번(추론)만. 약 35초 (가중치 내려받는 시간 제외)
  python ch14_finetune.py --retrain # 저장된 학습 결과가 있어도 다시 학습
학습 결과는 ch14_out_pretrained/ · ch14_out_scratch/ 에, 요약은 ch14_finetune_results.json 에 저장된다.
이미 학습한 폴더가 있으면 학습을 건너뛰고 평가 · 그림만 다시 만든다.

필요한 패키지 (이 장에서만): pip install "rfdetr[train]"   (rfdetr 1.12.1 에서 확인. supervision · pillow 가 함께 설치된다)
ch14_export.py 가 이 파일의 detections_to_prediction · load_finetuned 와 ch14_out_pretrained/ 의 체크포인트를 쓴다.
"""

from __future__ import annotations

import argparse
import csv
import json
import os
import sys
import time
import warnings
from importlib.metadata import version

import numpy as np
import torch
from PIL import Image

from ch02_boxes import box_cxcywh_to_xyxy, box_xyxy_to_cxcywh
from ch03_metrics import evaluate_ap, match_detections
from ch14_make_coco import SPLIT_SEEDS, export_split, load_coco_split
from rf_shapes import CLASS_NAMES, NUM_CLASSES, ShapesDataset, draw_boxes

warnings.filterwarnings("ignore")  # 패키지 · Lightning 의 안내 경고가 많다. 본문에 필요한 것은 직접 출력한다.

# --8<-- [start:config]
# 미세 조정 설정. model.train(**TRAIN_KWARGS) 로 넘긴다. 적지 않은 것은 TrainConfig 의 기본값이다.
TRAIN_KWARGS = dict(
    epochs=5,              # 기본 100. 도형 세상은 쉬워서 몇 에폭이면 충분하다
    batch_size=2,          # 기본 4. 한 번에 GPU 에 올리는 그림 수 — 8GB GPU 를 나눠 쓰느라 작게 잡았다
    grad_accum_steps=4,    # 기본 1. 기울기를 4번 모아 한 번 갱신 → 실효 배치 크기 2 × 4 = 8
    lr=1e-4,               # 기본 1e-4 (디코더 쪽). 백본은 lr_encoder=1.5e-4 에 층별 감쇠 0.8 이 곱해진다
    num_workers=2,         # 기본 2. 데이터 로더 일꾼 수
    seed=0,
    tensorboard=False,     # 기본 True. 이 실습은 metrics.csv 만 읽는다 (wandb · mlflow 는 기본이 False)
    eval_base_model=True,  # 기본 False(EMA 가중치만 검증). EMA 와 일반 가중치를 둘 다 검증해 비교한다
    compact_train_metrics=False,  # 기본 True(보조 손실을 _aux 하나로 합쳐 기록). 층별 손실을 따로 본다
    progress_bar=None,
)
SCRATCH_EPOCHS = 3  # (b) 무작위 초기화는 3 에폭만 돌린다 (GPU 시간을 아끼려고). 그 밖의 설정은 (a) 와 같다
OUT_PRETRAINED = "ch14_out_pretrained"
OUT_SCRATCH = "ch14_out_scratch"
RESULTS_FILE = "ch14_finetune_results.json"
# --8<-- [end:config]


def pick_device() -> str:
    if torch.cuda.is_available():
        return "cuda"
    if torch.backends.mps.is_available():
        return "mps"
    return "cpu"


# --8<-- [start:to-prediction]
def detections_to_prediction(detections, num_classes: int | None = None) -> dict:
    """supervision.Detections 하나를 이 튜토리얼의 예측 형식으로 바꾼다.

    Detections 의 주요 필드 (객체 n 개):
      xyxy        (n, 4) float32 — 원본 그림의 픽셀 좌표 (x0, y0, x1, y1)
      confidence  (n,)   float32 — 점수 (시그모이드를 거친 값), 내림차순
      class_id    (n,)   int64   — 클래스 번호
      data["class_name"], data["source_shape"] (원본 그림의 (높이, 너비))
    돌려주는 값: {"boxes": (n, 4) 정규화 (cx, cy, w, h), "scores": (n,), "labels": (n,)} — 3장의 evaluate_ap 형식.
    num_classes 를 주면 class_id 가 그보다 작은 것만 남긴다 (미세 조정한 모델의 머리에는 클래스 수보다
    하나 많은 출력이 있고, 문턱값을 0 으로 두면 그 남는 칸의 예측도 딸려 나오기 때문이다).
    """
    xyxy = torch.from_numpy(np.asarray(detections.xyxy, dtype=np.float32)).reshape(-1, 4)
    scores = torch.from_numpy(np.asarray(detections.confidence, dtype=np.float32))
    labels = torch.from_numpy(np.asarray(detections.class_id, dtype=np.int64))
    if len(xyxy):
        height, width = (float(v) for v in detections.data["source_shape"][0])
        xyxy = xyxy / torch.tensor([width, height, width, height])  # 픽셀 → 0 – 1
    if num_classes is not None:
        keep = labels < num_classes
        xyxy, scores, labels = xyxy[keep], scores[keep], labels[keep]
    return {"boxes": box_xyxy_to_cxcywh(xyxy), "scores": scores, "labels": labels}
# --8<-- [end:to-prediction]


def predict_all(model, paths, threshold: float, batch: int = 8, num_classes: int | None = None, **kwargs):
    """그림 경로 목록 전체를 batch 장씩 predict 해서 예측 사전의 목록으로 돌려준다."""
    predictions = []
    for start in range(0, len(paths), batch):
        results = model.predict(paths[start:start + batch], threshold=threshold, include_source_image=False, **kwargs)
        predictions += [detections_to_prediction(d, num_classes) for d in results]
    return predictions


# --8<-- [start:coco-predict]
def try_pretrained(test_paths, fig_dir: str):
    """COCO 로 학습된 Nano 를 그대로 도형 세상에 써 본다."""
    from rfdetr import RFDETRNano
    from rfdetr.assets.coco_classes import COCO_CLASSES  # {1: "person", 2: "bicycle", …, 90: "toothbrush"}

    start = time.time()
    model = RFDETRNano()  # 처음 부르면 가중치 rf-detr-nano.pth 를 내려받는다 (~/.roboflow/models, 366 MB)
    cfg = model.model_config
    net = model.model.model  # 실제 nn.Module (클래스 이름 LWDETR)
    print(f"  모델 준비 {time.time() - start:.1f}초 | 매개변수 {sum(p.numel() for p in net.parameters()):,}개")
    print(f"  설정: resolution={cfg.resolution}, patch_size={cfg.patch_size}, num_windows={cfg.num_windows},"
          f" dec_layers={cfg.dec_layers}, num_queries={cfg.num_queries}, num_select={cfg.num_select},"
          f" group_detr={cfg.group_detr}, num_classes={cfg.num_classes}")
    print(f"  분류 머리: {net.class_embed}")
    print(f"  COCO_CLASSES: 이름 {len(COCO_CLASSES)}개, id 범위 {min(COCO_CLASSES)} – {max(COCO_CLASSES)},"
          f" 예: {COCO_CLASSES[1]!r}, {COCO_CLASSES[18]!r}")

    # (가) 입력 형태: 경로 · PIL · numpy (H, W, 3) uint8 RGB · 텐서 (3, H, W) 0 – 1 · 목록(배치)
    pil = Image.open(test_paths[0])
    array = np.asarray(pil)
    tensor = torch.from_numpy(array).permute(2, 0, 1).float() / 255.0
    low = 0.05  # 일부러 아주 낮은 문턱값 (기본은 0.5)
    outs = [model.predict(x, threshold=low) for x in (test_paths[0], pil, array, tensor)]
    batch = model.predict([test_paths[0], test_paths[1]], threshold=low)  # 목록을 주면 목록이 돌아온다
    reference = outs[0]
    diffs = [float(np.abs(o.xyxy - reference.xyxy).max()) if len(reference) else 0.0 for o in outs[1:] + batch[:1]]
    print(f"  입력 형태 check (경로 기준 박스 최대 차이, 픽셀): PIL {diffs[0]:.1e}, numpy {diffs[1]:.1e},"
          f" 텐서 {diffs[2]:.1e}, 배치 {diffs[3]:.1e}")
    print(f"  predict 가 돌려준 것: {type(reference).__module__}.{type(reference).__name__}, 객체 {len(reference)}개"
          f" (threshold={low})")
    for box, score, class_id in list(zip(reference.xyxy, reference.confidence, reference.class_id))[:4]:
        print(f"    xyxy {np.round(box, 1).tolist()}  confidence {score:.3f}  class_id {class_id}"
              f" → {COCO_CLASSES[int(class_id)]!r}")

    # (나) 시험 그림 50장(--quick 은 20장)에서 문턱값별로 몇 개나 "찾는지", 무엇이라고 부르는지
    results = []
    count = min(50, len(test_paths))
    for i in range(0, count, 10):
        results += model.predict(test_paths[i:i + 10], threshold=low)
    scores = np.concatenate([r.confidence for r in results])
    names = np.concatenate([r.data["class_name"] for r in results])
    for threshold in (0.5, 0.3, 0.1, low):
        print(f"  시험 그림 {count}장, threshold={threshold}: 탐지 {int((scores > threshold).sum())}개")
    unique, counts = np.unique(names[scores > 0.1], return_counts=True)
    top = sorted(zip(counts.tolist(), unique.tolist()), reverse=True)[:6]
    print("  threshold=0.1 에서 붙인 이름 (많은 순):", ", ".join(f"{name} {count}" for count, name in top))

    draw_pretrained_figure(test_paths, results, fig_dir)
    return model
# --8<-- [end:coco-predict]


# --8<-- [start:train]
def finetune(output_dir: str, dataset_dir: str, pretrained: bool, retrain: bool, **overrides) -> dict:
    """RF-DETR Nano 를 dataset_dir 로 미세 조정한다. 돌려주는 값: {"minutes": 걸린 시간, "peak_gib": GPU 메모리 최대}.

    학습을 마치면 같은 값을 output_dir/train_info.json 에 적어 두고, 다음에 부르면 학습을 건너뛰고 그것을 읽는다.

    pretrained=True : RFDETRNano() — COCO 까지 학습된 가중치(rf-detr-nano.pth)에서 시작.
    pretrained=False: RFDETRNano(pretrain_weights=None) — 가중치를 읽지 않는다. Nano 는 패치 16 · 위치 임베딩
                      24×24 라 DINOv2 원본(패치 14)도 읽을 수 없어, 백본까지 전부 무작위 초기화로 시작한다.
    """
    from rfdetr import RFDETRNano

    info_path = os.path.join(output_dir, "train_info.json")
    if os.path.exists(os.path.join(output_dir, "checkpoint_best_total.pth")) and os.path.exists(info_path) and not retrain:
        with open(info_path, encoding="utf-8") as f:
            info = json.load(f)
        print(f"  {output_dir}/ 에 학습 결과가 있어 건너뜀 (--retrain 으로 다시 학습).")
        print(f"  그때의 기록: {info['minutes']:.1f}분, GPU 메모리 최대 {info['peak_gib']:.2f} GiB (torch 가 할당한 양)")
        return info
    model = RFDETRNano() if pretrained else RFDETRNano(pretrain_weights=None)
    if torch.cuda.is_available():
        torch.cuda.reset_peak_memory_stats()
    start = time.time()
    # 클래스 수는 주지 않는다: train() 이 train/_annotations.coco.json 의 categories 를 세어
    # 분류 머리를 (클래스 수 + 1) 칸으로 다시 만든다 (이때 머리의 가중치는 새로 초기화된다).
    model.train(dataset_dir=dataset_dir, output_dir=output_dir, **{**TRAIN_KWARGS, **overrides})
    peak = torch.cuda.max_memory_allocated() / 2**30 if torch.cuda.is_available() else float("nan")
    info = {"minutes": round((time.time() - start) / 60, 1), "peak_gib": round(peak, 2)}
    with open(info_path, "w", encoding="utf-8") as f:
        json.dump(info, f)
    print(f"  학습 끝: {info['minutes']:.1f}분, GPU 메모리 최대 {info['peak_gib']:.2f} GiB (torch 가 할당한 양)")
    return info
# --8<-- [end:train]


# --8<-- [start:read-metrics]
def read_metrics(output_dir: str) -> list[dict]:
    """output_dir/metrics.csv 를 에폭별 사전의 목록으로 읽는다.

    Lightning 의 CSV 기록은 에폭마다 두 줄(검증 지표 줄, 학습 손실 줄)을 쓰고 빈 칸은 비워 둔다.
    같은 에폭의 두 줄을 하나로 합친다. 열 이름은 "train/loss_ce", "val/mAP_50_95" 같은 식이다.
    """
    epochs: dict[int, dict] = {}
    with open(os.path.join(output_dir, "metrics.csv"), encoding="utf-8") as f:
        for row in csv.DictReader(f):
            merged = epochs.setdefault(int(row["epoch"]), {"epoch": int(row["epoch"])})
            for key, value in row.items():
                if key not in ("epoch", "step") and value not in ("", None):
                    merged[key] = float(value)
    return [epochs[k] for k in sorted(epochs)]
# --8<-- [end:read-metrics]


def print_metrics(rows: list[dict]):
    """에폭별 표: 손실 항목(마지막 디코더 층 · 보조 · 인코더 제안)과 검증 AP(일반 · EMA)."""
    loss_keys = sorted(k for k in rows[0] if k.startswith("train/loss"))
    print("  metrics.csv 의 손실 열:", ", ".join(k.removeprefix("train/") for k in loss_keys))
    print("  에폭 | loss    | loss_ce loss_bbox loss_giou | loss_ce_0 loss_ce_enc | val AP(일반) AP(EMA) AP50(EMA)")
    for r in rows:
        print(f"  {r['epoch'] + 1:4d} | {r['train/loss']:7.3f} | {r['train/loss_ce']:7.3f} {r['train/loss_bbox']:9.4f}"
              f" {r['train/loss_giou']:9.4f} | {r['train/loss_ce_0']:9.3f} {r['train/loss_ce_enc']:11.3f} |"
              f" {r['val/mAP_50_95']:11.4f} {r['val/ema_mAP_50_95']:7.4f} {r['val/ema_mAP_50']:9.4f}")
    first = rows[0]
    print("  첫 에폭의 손실 항목:", ", ".join(f"{k.removeprefix('train/')} {first[k]:.4f}" for k in loss_keys))
    print("  cardinality_error (에폭별):", ", ".join(f"{r['train/cardinality_error']:.2f}" for r in rows),
          "| lr_max", f"{max(r['train/lr_max'] for r in rows):.4g}", "lr_min", f"{min(r['train/lr_min'] for r in rows):.4g}")
    last = rows[-1]
    # 전체 손실이 "가중치 × 항목" 의 합인지 확인: 분류 1, L1 5, GIoU 2 (11장). 모든 층 · 인코더 제안에 같은 가중치.
    total = sum(last[k] * (5.0 if "bbox" in k else 2.0 if "giou" in k else 1.0) for k in loss_keys if k != "train/loss")
    print(f"  check: 1·Σloss_ce + 5·Σloss_bbox + 2·Σloss_giou = {total:.3f}  vs  기록된 loss = {last['train/loss']:.3f}")


# --8<-- [start:load]
def load_finetuned(output_dir: str = OUT_PRETRAINED):
    """학습이 남긴 checkpoint_best_total.pth 를 읽어 추론할 수 있는 모델을 돌려준다.

    rfdetr.from_checkpoint 는 체크포인트에 적힌 모델 종류 · 해상도 · 클래스 이름을 읽어 알맞은 클래스(RFDETRNano)를
    스스로 고른다. 검증 AP 가 가장 좋았던 가중치(일반과 EMA 가운데 나은 쪽)가 들어 있다.
    """
    import rfdetr

    return rfdetr.from_checkpoint(os.path.join(output_dir, "checkpoint_best_total.pth"))
# --8<-- [end:load]


# --8<-- [start:evaluate]
def evaluate_both(model, dataset_dir: str, test_paths, test_targets) -> dict:
    """같은 모델 · 같은 시험 세트를 (가) 패키지의 evaluate() 와 (나) 3장의 evaluate_ap 로 채점한다."""
    # (가) 패키지: COCO 방식 채점기로 mAP@[.50:.95], mAP@.50, mAP@.75, mAR 등을 돌려준다.
    package = model.evaluate(dataset_dir=dataset_dir, split="test", batch_size=2, num_workers=2, progress_bar=None)
    # (나) 우리 것: predict 로 예측을 모두 받아(문턱값 0 → 그림마다 num_select 개) 직접 채점.
    predictions = predict_all(model, test_paths, threshold=0.0, num_classes=NUM_CLASSES)
    ours = evaluate_ap(predictions, test_targets, NUM_CLASSES)                    # 그림당 상위 100개 (3장 기본값)
    ours_500 = evaluate_ap(predictions, test_targets, NUM_CLASSES, max_dets=500)  # 패키지처럼 500개까지
    return {"package": package, "ours": ours, "ours_500": ours_500, "predictions": predictions}
# --8<-- [end:evaluate]


# --8<-- [start:knobs]
def threshold_sweep(predictions, targets, thresholds, iou_threshold: float = 0.5):
    """점수 문턱값을 올리며 남는 예측 수 · 정밀도 · 재현율을 센다 (IoU 0.5 기준, 3장의 match_detections)."""
    num_gt = sum(len(t["labels"]) for t in targets)
    rows = []
    for threshold in thresholds:
        kept = tp = 0
        for pred, target in zip(predictions, targets):
            keep = pred["scores"] > threshold  # 패키지와 같이 "문턱값보다 큰 것" 만 남긴다
            boxes, scores, labels = box_cxcywh_to_xyxy(pred["boxes"][keep]), pred["scores"][keep], pred["labels"][keep]
            kept += int(keep.sum())
            for cls in range(NUM_CLASSES):
                gt = box_cxcywh_to_xyxy(target["boxes"][target["labels"] == cls])
                tp += int(match_detections(boxes[labels == cls], scores[labels == cls], gt, iou_threshold).sum())
        rows.append({"threshold": threshold, "kept": kept, "precision": tp / max(kept, 1), "recall": tp / num_gt})
    return rows


def resolution_sweep(model, paths, targets, sizes):
    """predict(shape=(H, W)) 로 추론 해상도만 바꿔 AP 를 잰다. H, W 는 patch_size × num_windows 의 배수여야 한다."""
    rows = []
    for size in sizes:
        start = time.time()
        predictions = predict_all(model, paths, threshold=0.0, num_classes=NUM_CLASSES, shape=(size, size))
        seconds = time.time() - start
        result = evaluate_ap(predictions, targets, NUM_CLASSES)
        rows.append({"size": size, "AP": result["AP"], "AP50": result["AP50"], "AP75": result["AP75"],
                     "ms_per_image": 1000 * seconds / len(paths)})
    return rows
# --8<-- [end:knobs]


def num_select_sweep(model, paths, targets, values):
    """후처리가 남기는 예측 수 num_select 를 바꿔 본다 (model.model.postprocess.num_select)."""
    rows = []
    original = model.model.postprocess.num_select
    for value in values:
        model.model.postprocess.num_select = value
        predictions = predict_all(model, paths, threshold=0.0, num_classes=NUM_CLASSES)
        result = evaluate_ap(predictions, targets, NUM_CLASSES)
        returned = float(np.mean([len(p["scores"]) for p in predictions]))
        rows.append({"num_select": value, "returned": returned, "AP": result["AP"], "AP50": result["AP50"]})
    model.model.postprocess.num_select = original
    return rows


# ─────────────────────────────────────── 그림 ───────────────────────────────────────

def _pyplot():
    import matplotlib

    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    return plt


def _load_image(path):
    return np.transpose(np.asarray(Image.open(path), dtype=np.float32) / 255.0, (2, 0, 1))  # (3, H, W) 0 – 1


def draw_pretrained_figure(test_paths, results, fig_dir: str):
    """COCO 모델이 도형 그림에 붙인 박스 (score > 0.1). 이름은 그림마다 점수가 가장 높은 하나만 제목에 적는다."""
    import matplotlib.patches as patches

    plt = _pyplot()
    fig, axes = plt.subplots(1, 6, figsize=(13.2, 2.75))
    for ax, path, det in zip(axes, test_paths, results):
        draw_boxes(ax, _load_image(path))
        keep = det.confidence > 0.1
        for x0, y0, x1, y1 in det.xyxy[keep]:
            ax.add_patch(patches.Rectangle((x0, y0), x1 - x0, y1 - y0, fill=False, edgecolor="#ff40ff", linewidth=1.4,
                                           linestyle="--"))
        if keep.any():  # confidence 는 내림차순이라 첫 번째가 최고 점수
            title = f"{int(keep.sum())} boxes, top: {det.data['class_name'][0]} {det.confidence[0]:.2f}"
        else:
            title = "0 boxes"
        ax.set_title(title, fontsize=8)
    fig.suptitle("COCO-pretrained RF-DETR Nano on Shape World, no fine-tuning (dashed: boxes with score > 0.1)",
                 fontsize=10)
    fig.tight_layout(pad=0.4)
    os.makedirs(fig_dir, exist_ok=True)
    path = os.path.join(fig_dir, "ch14-coco-model-on-shapes.png")
    fig.savefig(path, dpi=120)
    plt.close(fig)
    print(f"  그림 저장: {path}")


def draw_curves(runs: dict, fig_dir: str):
    """왼쪽: 에폭별 검증 AP (사전 학습 vs 무작위 초기화, 일반 vs EMA). 오른쪽: 학습 손실 항목 (사전 학습)."""
    plt = _pyplot()
    fig, axes = plt.subplots(1, 2, figsize=(11.5, 4.0))
    styles = {"pretrained": ("#0072b2", "COCO-pretrained start"), "scratch": ("#d55e00", "random init")}
    for name, rows in runs.items():
        color, label = styles[name]
        x = [r["epoch"] + 1 for r in rows]
        axes[0].plot(x, [r["val/ema_mAP_50_95"] for r in rows], "-o", color=color, label=f"{label} (EMA weights)")
        axes[0].plot(x, [r["val/mAP_50_95"] for r in rows], "--s", color=color, alpha=0.6, markersize=4,
                     label=f"{label} (regular weights)")
    axes[0].set_xlabel("epoch")
    axes[0].set_ylabel("validation mAP@[.50:.95]")
    axes[0].set_ylim(-0.03, 1.03)
    axes[0].set_xticks(range(1, max(len(rows) for rows in runs.values()) + 1))
    axes[0].grid(alpha=0.3)
    axes[0].legend(fontsize=8, loc="center right")
    axes[0].set_title("Validation AP per epoch (200 images)", fontsize=10)

    rows = runs["pretrained"]
    x = [r["epoch"] + 1 for r in rows]
    for key, style, label in [
        ("train/loss_ce", "-o", "loss_ce (last decoder layer)"),
        ("train/loss_ce_0", "--s", "loss_ce_0 (decoder layer 1)"),
        ("train/loss_ce_enc", ":^", "loss_ce_enc (encoder proposals)"),
        ("train/loss_giou", "-D", "loss_giou (last decoder layer)"),
        ("train/loss_bbox", "-v", "loss_bbox (last decoder layer)"),
    ]:
        axes[1].plot(x, [r[key] for r in rows], style, label=label, markersize=4)
    axes[1].set_yscale("log")
    axes[1].set_xlabel("epoch")
    axes[1].set_ylabel("training loss term (epoch mean, unweighted)")
    axes[1].set_xticks(x)
    axes[1].grid(alpha=0.3, which="both")
    axes[1].legend(fontsize=8)
    axes[1].set_title("Loss terms, COCO-pretrained start", fontsize=10)
    fig.tight_layout()
    path = os.path.join(fig_dir, "ch14-finetune-curves.png")
    fig.savefig(path, dpi=120)
    plt.close(fig)
    print(f"  그림 저장: {path}")


def draw_test_predictions(test_paths, test_targets, predictions: dict, fig_dir: str, count: int = 6):
    """시험 그림 위에 정답(흰 점선)과 두 모델의 예측(score > 0.5)."""
    plt = _pyplot()
    names = list(predictions)
    titles = {"pretrained": "COCO-pretrained start", "scratch": "random init"}
    fig, axes = plt.subplots(len(names), count, figsize=(2.2 * count, 2.35 * len(names)), squeeze=False)
    for row, name in enumerate(names):
        for col in range(count):
            ax = axes[row, col]
            image = _load_image(test_paths[col])
            pred = predictions[name][col]
            keep = pred["scores"] > 0.5
            draw_boxes(ax, image, test_targets[col]["boxes"], color="white", linestyle=":", linewidth=1.2)
            draw_boxes(ax, image, pred["boxes"][keep], pred["labels"][keep], pred["scores"][keep], fontsize=6.5)
            if col == 0:
                ax.set_ylabel(titles[name], fontsize=9)
    fig.suptitle("Test images: ground truth (white dotted) and predictions with score > 0.5 (green)", fontsize=10)
    fig.tight_layout(pad=0.4)
    path = os.path.join(fig_dir, "ch14-test-predictions.png")
    fig.savefig(path, dpi=120)
    plt.close(fig)
    print(f"  그림 저장: {path}")


def draw_knobs(sweep_rows, resolution_rows, fig_dir: str):
    """왼쪽: 문턱값에 따른 정밀도 · 재현율. 오른쪽: 추론 해상도에 따른 AP."""
    plt = _pyplot()
    fig, axes = plt.subplots(1, 2, figsize=(11.0, 3.8))
    x = [r["threshold"] for r in sweep_rows]
    axes[0].plot(x, [r["precision"] for r in sweep_rows], "-o", color="#0072b2", label="precision (IoU 0.5)")
    axes[0].plot(x, [r["recall"] for r in sweep_rows], "--s", color="#d55e00", label="recall (IoU 0.5)")
    axes[0].set_xlabel("score threshold")
    axes[0].set_ylabel("precision / recall")
    axes[0].set_ylim(-0.03, 1.03)
    axes[0].grid(alpha=0.3)
    axes[0].legend(fontsize=8, loc="lower center")
    axes[0].set_title("Score threshold sweep (fine-tuned Nano, test set)", fontsize=10)
    sizes = [r["size"] for r in resolution_rows]
    axes[1].plot(sizes, [r["AP"] for r in resolution_rows], "-o", color="#0072b2", label="AP@[.50:.95]")
    axes[1].plot(sizes, [r["AP75"] for r in resolution_rows], "--s", color="#009e73", label="AP75")
    axes[1].plot(sizes, [r["AP50"] for r in resolution_rows], ":^", color="#d55e00", label="AP50")
    axes[1].axvline(384, color="gray", linewidth=1, linestyle="--")
    axes[1].text(384, 0.05, " trained at 384", fontsize=8, color="gray")
    axes[1].set_xticks(sizes)
    axes[1].set_xlabel("inference resolution: predict(shape=(S, S))")
    axes[1].set_ylabel("test AP")
    axes[1].set_ylim(-0.03, 1.03)
    axes[1].grid(alpha=0.3)
    axes[1].legend(fontsize=8, loc="lower right")
    axes[1].set_title("Inference resolution sweep (same weights)", fontsize=10)
    fig.tight_layout()
    path = os.path.join(fig_dir, "ch14-inference-knobs.png")
    fig.savefig(path, dpi=120)
    plt.close(fig)
    print(f"  그림 저장: {path}")


# ─────────────────────────────────────── 본 실행 ───────────────────────────────────────

def ensure_dataset(dataset_dir: str, quick: bool):
    """데이터셋 폴더가 없으면 --quick 에서만 작은 것을 바로 만든다 (본 실행은 ch14_make_coco.py 를 먼저 돌린다)."""
    if os.path.exists(os.path.join(dataset_dir, "train", "_annotations.coco.json")):
        return
    if not quick:
        raise SystemExit(f"{dataset_dir}/ 가 없습니다. 먼저 `python ch14_make_coco.py` 를 실행하세요.")
    for split, n in {"train": 60, "valid": 20, "test": 20}.items():
        export_split(ShapesDataset(n, size=192, seed=SPLIT_SEEDS[split]), os.path.join(dataset_dir, split))
    print(f"  {dataset_dir}/ 를 새로 만들었습니다 (60 + 20 + 20장)")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--quick", action="store_true", help="학습 없이 사전 학습 모델 추론만")
    parser.add_argument("--retrain", action="store_true", help="저장된 학습 결과가 있어도 다시 학습")
    parser.add_argument("--data", default=None, help="COCO 형식 데이터셋 폴더 (기본 ch14_shapes_coco)")
    parser.add_argument("--fig-dir", default="figures")
    parser.add_argument("--seed", type=int, default=0)
    args = parser.parse_args()
    dataset_dir = args.data or ("ch14_shapes_coco_quick" if args.quick else "ch14_shapes_coco")
    TRAIN_KWARGS["seed"] = args.seed
    torch.manual_seed(args.seed)
    sys.stdout.reconfigure(line_buffering=True)  # 패키지의 로그(stderr)와 우리 출력의 순서가 섞이지 않게

    device = pick_device()
    gpu = torch.cuda.get_device_name(0) if device == "cuda" else device
    print(f"[0] 환경: rfdetr {version('rfdetr')}, torch {torch.__version__}, supervision {version('supervision')},"
          f" 장치 {gpu}")
    ensure_dataset(dataset_dir, args.quick)
    test_paths, test_targets = load_coco_split(os.path.join(dataset_dir, "test"))

    print("[1] COCO 로 사전 학습된 RF-DETR Nano 를 도형 세상에 그대로 써 보기")
    model = try_pretrained(test_paths, args.fig_dir)
    del model
    if args.quick:
        print("--quick: 학습은 건너뜁니다.")
        return

    print(f"[2] 미세 조정 (a) 사전 학습 가중치에서 시작 → {OUT_PRETRAINED}/")
    print("  설정:", ", ".join(f"{k}={v}" for k, v in TRAIN_KWARGS.items()))
    info = {"pretrained": finetune(OUT_PRETRAINED, dataset_dir, pretrained=True, retrain=args.retrain)}
    runs = {"pretrained": read_metrics(OUT_PRETRAINED)}
    print_metrics(runs["pretrained"])
    print("  출력 폴더:", ", ".join(f"{name} ({os.path.getsize(os.path.join(OUT_PRETRAINED, name)) / 1e6:.0f} MB)"
                                 if name.endswith((".pth", ".ckpt")) else name
                                 for name in sorted(os.listdir(OUT_PRETRAINED))))

    print(f"[3] 미세 조정 (b) 무작위 초기화에서 시작 (epochs={SCRATCH_EPOCHS}, 나머지 설정은 같음) → {OUT_SCRATCH}/")
    info["scratch"] = finetune(OUT_SCRATCH, dataset_dir, pretrained=False, retrain=args.retrain, epochs=SCRATCH_EPOCHS)
    runs["scratch"] = read_metrics(OUT_SCRATCH)
    print_metrics(runs["scratch"])

    print("[4] 시험 세트 채점: 패키지의 evaluate() 와 3장의 evaluate_ap")
    summary, predictions = {}, {}
    for name, output_dir in (("pretrained", OUT_PRETRAINED), ("scratch", OUT_SCRATCH)):
        model = load_finetuned(output_dir)
        if name == "pretrained":
            print(f"  from_checkpoint → {type(model).__name__}, class_names={model.class_names},"
                  f" 분류 머리 {model.model.model.class_embed}")
        result = evaluate_both(model, dataset_dir, test_paths, test_targets)
        package, ours, ours_500 = result["package"], result["ours"], result["ours_500"]
        predictions[name] = result["predictions"]
        print(f"  ({name}) 패키지 evaluate(): mAP50:95 {package['test/mAP_50_95']:.4f}, mAP50 {package['test/mAP_50']:.4f},"
              f" mAP75 {package['test/mAP_75']:.4f}, mAR {package['test/mAR']:.4f}")
        print(f"  ({name}) 우리 evaluate_ap : AP      {ours['AP']:.4f}, AP50  {ours['AP50']:.4f}, AP75  {ours['AP75']:.4f}"
              f"  | max_dets=500 이면 AP {ours_500['AP']:.4f}"
              f"  | 클래스별 AP {', '.join(f'{n} {v:.3f}' for n, v in zip(CLASS_NAMES, ours['per_class']))}")
        summary[name] = {"package": package, "ours": {k: ours[k] for k in ("AP", "AP50", "AP75")},
                         "ours_500": ours_500["AP"]}
        if name == "pretrained":
            finetuned = model
            pred = predictions[name][0]
            print(f"  예측 예 (시험 그림 0, 점수 상위 4개 / 돌려받은 {len(pred['scores'])}개):")
            for box, score, label in list(zip(pred["boxes"], pred["scores"], pred["labels"]))[:4]:
                print(f"    {CLASS_NAMES[int(label)]:9s} 점수 {score:.3f}  (cx, cy, w, h) = {[round(v, 3) for v in box.tolist()]}")
            print(f"    정답: {[CLASS_NAMES[int(c)] for c in test_targets[0]['labels']]}"
                  f" {[[round(v, 3) for v in b] for b in test_targets[0]['boxes'].tolist()]}")
        else:
            del model

    print("[5] 추론 설정 바꿔 보기 (미세 조정한 모델 (a), 시험 세트 200장)")
    sweep = threshold_sweep(predictions["pretrained"], test_targets, [0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95])
    print("  문턱값 | 남는 예측 수 | 정밀도 | 재현율   (IoU 0.5 기준, 정답 %d개)" % sum(len(t["labels"]) for t in test_targets))
    for r in sweep:
        print(f"  {r['threshold']:6.2f} | {r['kept']:12d} | {r['precision']:.4f} | {r['recall']:.4f}")
    selects = num_select_sweep(finetuned, test_paths, test_targets, [300, 100, 20, 5, 2])
    print("  num_select | 그림당 돌려받은 예측 수(평균) | AP     | AP50")
    for r in selects:
        print(f"  {r['num_select']:10d} | {r['returned']:28.1f} | {r['AP']:.4f} | {r['AP50']:.4f}")
    resolutions = resolution_sweep(finetuned, test_paths, test_targets, [128, 192, 256, 320, 384, 448, 512, 640])
    print("  predict(shape=(S, S)) | AP     | AP50   | AP75   | 그림당 시간(ms, 파일 읽기 포함 · 참고용)")
    for r in resolutions:
        print(f"  {r['size']:21d} | {r['AP']:.4f} | {r['AP50']:.4f} | {r['AP75']:.4f} | {r['ms_per_image']:.1f}")
    try:
        finetuned.predict(test_paths[0], shape=(400, 400))
    except ValueError as error:
        print("  shape=(400, 400) 은 거절된다:", str(error))

    print("[6] 그림")
    draw_curves(runs, args.fig_dir)
    draw_test_predictions(test_paths, test_targets, predictions, args.fig_dir)
    draw_knobs(sweep, resolutions, args.fig_dir)
    with open(RESULTS_FILE, "w", encoding="utf-8") as f:
        json.dump({"train_info": info, "runs": runs, "test": summary, "threshold_sweep": sweep,
                   "num_select": selects, "resolution": resolutions}, f, indent=1)
    print(f"  요약 저장: {RESULTS_FILE}")


if __name__ == "__main__":
    main()
