"""14장 · 실전: rfdetr 패키지 (1) 도형 세상을 COCO 형식 데이터셋 폴더로 내보내기.

무엇을 하나
  1. 2장의 정규화 (cx, cy, w, h) 박스를 COCO 의 픽셀 [x, y, w, h] (왼쪽 위 모서리 기준) 로 바꾼다.
     본문의 손계산 예를 같은 함수로 다시 계산해 보인다.
  2. ShapesDataset 을 rfdetr 패키지가 읽는 폴더 구조로 저장한다.
         ch14_shapes_coco/train/_annotations.coco.json + 000000.png …   (seed 0, 1,000장)
         ch14_shapes_coco/valid/_annotations.coco.json + …             (seed 1,   200장)
         ch14_shapes_coco/test/_annotations.coco.json  + …             (seed 2,   200장)
     장면은 앞 장들과 같고(같은 시드), 그림만 96 대신 192 픽셀로 크게 그린다.
  3. 저장한 JSON 을 다시 읽어 정규화 (cx, cy, w, h) 로 되돌렸을 때 원래 정답과 같은지 확인한다 (check).
  4. 주석 하나를 그림 위에 그려 COCO bbox 네 숫자의 뜻을 보인다 (ch14-coco-bbox.png).

실행
  python ch14_make_coco.py            # 1,400장 내보내기 (CPU 15초 안팎)
  python ch14_make_coco.py --quick    # 60 + 20 + 20장만 (1초 남짓, ch14_shapes_coco_quick/ 에)
그림은 --fig-dir (기본 figures/) 에, 데이터셋은 --out (기본 ch14_shapes_coco) 에 저장된다.
필요한 패키지: torch · numpy · matplotlib · pillow (그림 파일 저장).
ch14_finetune.py · ch14_export.py 가 이 파일이 만든 폴더와 load_coco_split 을 쓴다.
"""

from __future__ import annotations

import argparse
import json
import os
import time

import numpy as np
import torch
from PIL import Image

from rf_shapes import CLASS_NAMES, ShapesDataset

SPLIT_SEEDS = {"train": 0, "valid": 1, "test": 2}  # 이 튜토리얼의 약속: 학습 0, 검증 1, 시험 2
ANNOTATION_FILE = "_annotations.coco.json"  # rfdetr 가 찾는 주석 파일 이름


# --8<-- [start:convert]
def cxcywh_norm_to_coco(box, width: int, height: int):
    """정규화 (cx, cy, w, h) → COCO bbox [x, y, w, h] (픽셀, (x, y) 는 왼쪽 위 모서리).

    x = (cx − w/2)·W,  y = (cy − h/2)·H,  너비 = w·W,  높이 = h·H
    """
    cx, cy, w, h = (float(v) for v in box)
    return [(cx - w / 2) * width, (cy - h / 2) * height, w * width, h * height]


def coco_to_cxcywh_norm(bbox, width: int, height: int):
    """COCO bbox [x, y, w, h] (픽셀) → 정규화 (cx, cy, w, h). 위 함수의 역변환."""
    x, y, w, h = (float(v) for v in bbox)
    return [(x + w / 2) / width, (y + h / 2) / height, w / width, h / height]
# --8<-- [end:convert]


# --8<-- [start:export]
def export_split(dataset: ShapesDataset, split_dir: str) -> dict:
    """데이터셋 하나를 COCO 형식 폴더 하나로 저장하고, 저장한 주석 사전을 돌려준다.

    COCO 주석 JSON 은 목록 세 개로 이루어진다.
      images:      그림마다 {"id", "file_name", "width", "height"}
      categories:  클래스마다 {"id", "name", "supercategory"} — COCO 의 관례대로 id 를 1 부터 매긴다.
      annotations: 객체마다 {"id", "image_id", "category_id", "bbox", "area", "iscrowd"}
    """
    os.makedirs(split_dir, exist_ok=True)
    size = dataset.size
    images, annotations = [], []
    for image_id, target in enumerate(dataset.targets):
        file_name = f"{image_id:06d}.png"
        pixels = dataset.images[image_id].permute(1, 2, 0).numpy()  # (3, S, S) uint8 → (S, S, 3)
        Image.fromarray(pixels).save(os.path.join(split_dir, file_name))  # PNG: 손실 없이 저장
        images.append({"id": image_id, "file_name": file_name, "width": size, "height": size})
        for box, label in zip(target["boxes"].tolist(), target["labels"].tolist()):
            bbox = cxcywh_norm_to_coco(box, size, size)
            annotations.append({
                "id": len(annotations) + 1,          # 주석 번호 (데이터셋 안에서 유일하면 된다)
                "image_id": image_id,                # 어느 그림의 객체인가
                "category_id": int(label) + 1,       # 우리 클래스 0, 1, 2 → COCO 범주 id 1, 2, 3
                "bbox": [round(v, 2) for v in bbox],  # [x, y, w, h] 픽셀
                "area": round(round(bbox[2], 2) * round(bbox[3], 2), 2),  # 넓이 (여기서는 박스 넓이 w·h)
                "iscrowd": 0,                        # 1 이면 "여럿이 뭉친 영역" — 학습 정답으로 쓰지 않는다
            })
    coco = {
        "info": {"description": "Shape World (RF-DETR tutorial, chapter 14)"},
        "licenses": [],
        "images": images,
        "categories": [{"id": k + 1, "name": name, "supercategory": "shape"} for k, name in enumerate(CLASS_NAMES)],
        "annotations": annotations,
    }
    with open(os.path.join(split_dir, ANNOTATION_FILE), "w", encoding="utf-8") as f:
        json.dump(coco, f)
    return coco
# --8<-- [end:export]


# --8<-- [start:load]
def load_coco_split(split_dir: str):
    """COCO 형식 폴더를 읽어 (그림 경로 목록, 정답 목록) 을 돌려준다.

    정답은 이 튜토리얼의 형식: {"boxes": (n, 4) 정규화 (cx, cy, w, h), "labels": (n,) 0 부터의 클래스 번호}.
    범주 id 를 작은 것부터 0, 1, 2 … 로 다시 매긴다 — rfdetr 패키지가 학습할 때 하는 일과 같다.
    """
    with open(os.path.join(split_dir, ANNOTATION_FILE), encoding="utf-8") as f:
        coco = json.load(f)
    cat_to_label = {cat_id: k for k, cat_id in enumerate(sorted(c["id"] for c in coco["categories"]))}
    by_image = {image["id"]: [] for image in coco["images"]}
    for ann in coco["annotations"]:
        by_image[ann["image_id"]].append(ann)
    paths, targets = [], []
    for image in coco["images"]:
        anns = by_image[image["id"]]
        boxes = [coco_to_cxcywh_norm(a["bbox"], image["width"], image["height"]) for a in anns]
        paths.append(os.path.join(split_dir, image["file_name"]))
        targets.append({
            "boxes": torch.tensor(boxes, dtype=torch.float32).reshape(-1, 4),
            "labels": torch.tensor([cat_to_label[a["category_id"]] for a in anns], dtype=torch.int64),
        })
    return paths, targets
# --8<-- [end:load]


# --8<-- [start:check]
def check_roundtrip(dataset: ShapesDataset, split_dir: str) -> float:
    """저장한 폴더를 다시 읽어 원래 정답과 비교한다. 돌려주는 값: 박스 좌표의 최대 차이 (정규화 단위)."""
    paths, targets = load_coco_split(split_dir)
    assert len(paths) == len(dataset)
    worst = 0.0
    for original, loaded in zip(dataset.targets, targets):
        assert original["labels"].tolist() == loaded["labels"].tolist()
        if len(original["boxes"]):
            worst = max(worst, float((original["boxes"] - loaded["boxes"]).abs().max()))
    first = np.asarray(Image.open(paths[0]))  # 그림도 한 장 읽어 픽셀이 그대로인지 본다
    assert np.array_equal(first, dataset.images[0].permute(1, 2, 0).numpy())
    return worst
# --8<-- [end:check]


def hand_example():
    """본문의 손계산: 96×96 그림과 192×192 그림에서 같은 정규화 박스가 어떤 COCO bbox 가 되는가."""
    box = (0.5, 0.375, 0.25, 0.5)
    print("[1] 손계산 예: 정규화 (cx, cy, w, h) =", box)
    for size in (96, 192):
        bbox = cxcywh_norm_to_coco(box, size, size)
        back = coco_to_cxcywh_norm(bbox, size, size)
        print(f"  {size}×{size} 그림 → COCO bbox [x, y, w, h] = {[round(v, 2) for v in bbox]}"
              f"  (넓이 {bbox[2] * bbox[3]:.0f})  → 되돌리면 {tuple(round(v, 4) for v in back)}")


def draw_figure(dataset: ShapesDataset, coco: dict, fig_dir: str):
    """첫 그림의 주석을 COCO 좌표 그대로 그린다: (x, y) 모서리 점과 w, h 화살표."""
    import matplotlib

    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle

    size = dataset.size
    image_id = next(i for i, t in enumerate(dataset.targets) if len(t["labels"]) == 3)
    anns = [a for a in coco["annotations"] if a["image_id"] == image_id]
    fig, (ax, side) = plt.subplots(1, 2, figsize=(9.2, 4.6), gridspec_kw={"width_ratios": [1.0, 0.95]})
    ax.imshow(dataset.images[image_id].permute(1, 2, 0).numpy(), extent=(0, size, size, 0), interpolation="nearest")
    lines = []
    for k, ann in enumerate(anns):
        x, y, w, h = ann["bbox"]
        ax.add_patch(Rectangle((x, y), w, h, fill=False, edgecolor="#39ff14", linewidth=1.8))
        ax.plot([x], [y], marker="o", color="#ff40ff", markersize=8)  # (x, y) = 왼쪽 위 모서리
        ax.text(x + 5, y + 13, "ABCDEFG"[k], color="white", fontsize=10, fontweight="bold",
                bbox={"facecolor": "black", "alpha": 0.6, "pad": 1.5, "edgecolor": "none"})
        name = coco["categories"][ann["category_id"] - 1]["name"]
        lines.append(f"{'ABCDEFG'[k]}: category_id {ann['category_id']} ({name})\n"
                     f"    bbox = [{x:.2f}, {y:.2f}, {w:.2f}, {h:.2f}]\n"
                     f"    corner (x, y) = ({x:.0f}, {y:.0f}), w = {w:.0f}, h = {h:.0f}")
    ax.set_xlabel("x (pixels), origin at the top-left corner")
    ax.set_ylabel("y (pixels), grows downward")
    ax.set_xticks(range(0, size + 1, 48))
    ax.set_yticks(range(0, size + 1, 48))
    side.axis("off")
    side.text(0.0, 0.98, f"COCO bbox = [x, y, w, h] in pixels\n({size}x{size} image, magenta dot = (x, y))\n\n"
              + "\n\n".join(lines), va="top", ha="left", fontsize=9, family="monospace")
    fig.tight_layout()
    os.makedirs(fig_dir, exist_ok=True)
    path = os.path.join(fig_dir, "ch14-coco-bbox.png")
    fig.savefig(path, dpi=120)
    plt.close(fig)
    print(f"  그림 저장: {path}")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--quick", action="store_true", help="60 + 20 + 20장만 내보낸다")
    parser.add_argument("--out", default=None, help="데이터셋 폴더 (기본 ch14_shapes_coco)")
    parser.add_argument("--size", type=int, default=192, help="그림 한 변의 픽셀 수")
    parser.add_argument("--n-train", type=int, default=1000)
    parser.add_argument("--n-valid", type=int, default=200)
    parser.add_argument("--n-test", type=int, default=200)
    parser.add_argument("--fig-dir", default="figures")
    parser.add_argument("--seed", type=int, default=0, help="쓰지 않음 (분할마다 시드가 정해져 있다: 0, 1, 2)")
    args = parser.parse_args()
    counts = {"train": args.n_train, "valid": args.n_valid, "test": args.n_test}
    if args.quick:
        counts = {"train": 60, "valid": 20, "test": 20}
    out = args.out or ("ch14_shapes_coco_quick" if args.quick else "ch14_shapes_coco")

    hand_example()

    print(f"[2] 도형 세상을 COCO 형식으로 내보내기 → {out}/  (그림 {args.size}×{args.size})")
    start = time.time()
    first = None
    for split, n in counts.items():
        dataset = ShapesDataset(n, size=args.size, seed=SPLIT_SEEDS[split])
        coco = export_split(dataset, os.path.join(out, split))
        worst = check_roundtrip(dataset, os.path.join(out, split))
        per_class = np.bincount([a["category_id"] for a in coco["annotations"]], minlength=4)[1:]
        print(f"  {split:5s}: 그림 {len(coco['images']):5d}장, 객체 {len(coco['annotations']):5d}개"
              f" (circle {per_class[0]}, rectangle {per_class[1]}, triangle {per_class[2]})"
              f" | 되읽기 check: 박스 최대 차이 {worst:.1e}")
        if first is None:
            first = (dataset, coco)
    print(f"  걸린 시간 {time.time() - start:.1f}초")

    dataset, coco = first
    print("[3] 주석 파일 들여다보기 (train/_annotations.coco.json)")
    print("  images[0]      =", json.dumps(coco["images"][0]))
    print("  categories     =", json.dumps(coco["categories"]))
    print("  annotations[0] =", json.dumps(coco["annotations"][0]))
    print("  2장 형식의 같은 박스 (cx, cy, w, h) =", [round(v, 4) for v in dataset.targets[0]["boxes"][0].tolist()])
    draw_figure(dataset, coco, args.fig_dir)


if __name__ == "__main__":
    main()
