#!/usr/bin/env python
"""
objects365_coco_fix.py
────────────────────────────────────────────────────────────
기존 Objects365 COCO JSON의 "file_name"이 상대경로만 가지고 있어
/data/ltb/ultralytics/objects365_mmyolo_coco/images/··· 로 못 찾는 문제를
절대경로로 일괄 수정해 train/val _fix.json 을 만들어 줍니다.
"""

import json
import os
from pathlib import Path

# ---------------------------------------------------------------------
# 1. 기본 경로 설정
# ---------------------------------------------------------------------
DATA_ROOT   = Path("/data/ltb/ultralytics/objects365_mmyolo_coco")
IMG_FOLDER  = "images"            # 실제 이미지가 들어있는 하위 폴더
SRC_FILES   = {
    "train": DATA_ROOT / "train_coco.json",
    "val"  : DATA_ROOT / "val_coco.json",
}

# ---------------------------------------------------------------------
# 2. JSON 수정 함수
# ---------------------------------------------------------------------
def fix_coco_json(src_path: Path, dst_path: Path):
    """src_path → dst_path 로 파일이름 절대경로화해서 저장"""
    with src_path.open("r", encoding="utf-8") as fp:
        coco = json.load(fp)

    changed = 0
    for img in coco.get("images", []):
        fname = img["file_name"]
        # 이미 절대경로라면 건너뜀
        if fname.startswith("/"):
            continue
        abs_path = (DATA_ROOT / IMG_FOLDER / fname).as_posix()
        img["file_name"] = abs_path
        changed += 1

    with dst_path.open("w", encoding="utf-8") as fp:
        json.dump(coco, fp, ensure_ascii=False, indent=2)

    print(f"[✓] {src_path.name} → {dst_path.name}  "
          f"(updated {changed:,} images)")

# ---------------------------------------------------------------------
# 3. 실행
# ---------------------------------------------------------------------
if __name__ == "__main__":
    for split, src in SRC_FILES.items():
        dst = src.with_name(f"{split}_coco_fix.json")
        if not src.is_file():
            raise FileNotFoundError(src)
        fix_coco_json(src, dst)
