import os
import json
import shutil

def filter_single_circle_files(src_folder, dst_folder, img_exts=(".png", ".jpg", ".jpeg")):
    """
    ¸´ÖÆËùÓÐ½ö°üº¬Ò»¸ö label == 'circle' µÄ JSON ÎÄ¼þ¼°Æä¶ÔÓ¦Í¼Æ¬¡£
    Ô´ÎÄ¼þ¼Ð²»ÐÞ¸Ä£¬½á¹û±£´æµ½ÐÂÎÄ¼þ¼Ð¡£
    """
    os.makedirs(dst_folder, exist_ok=True)

    for filename in os.listdir(src_folder):
        if not filename.lower().endswith(".json"):
            continue

        json_path = os.path.join(src_folder, filename)
        try:
            with open(json_path, "r", encoding="utf-8") as f:
                data = json.load(f)
        except Exception as e:
            print(f"[ERROR] ÎÞ·¨¶ÁÈ¡ {filename}: {e}")
            continue

        shapes = data.get("shapes", [])
        circle_count = sum(1 for shape in shapes if shape.get("label") == "circle")

        # ? Ö»±£ÁôÇ¡ºÃÒ»¸ö circle µÄÎÄ¼þ
        if circle_count == 1:
            base = os.path.splitext(filename)[0]

            # ¸´ÖÆ json
            dst_json = os.path.join(dst_folder, filename)
            shutil.copy2(json_path, dst_json)

            # ²éÕÒ²¢¸´ÖÆÍ¬ÃûÍ¼Æ¬
            found_img = False
            for ext in img_exts:
                img_path = os.path.join(src_folder, base + ext)
                if os.path.exists(img_path):
                    shutil.copy2(img_path, os.path.join(dst_folder, base + ext))
                    found_img = True
                    break

            print(f"? Copied: {filename} ({circle_count} circle){' + image' if found_img else ''}")
        else:
            print(f"Skipped: {filename} ({circle_count} circles)")

if __name__ == "__main__":
    src_folder = "/data/share/zyh/master_dataset/circle/huayan_circle/251112_251111/total"  # Ô´ÎÄ¼þ¼Ð
    dst_folder = "/data/share/zyh/master_dataset/circle/huayan_circle/251112_251111/onecircle"  # Ä¿±êÎÄ¼þ¼Ð
    filter_single_circle_files(src_folder, dst_folder)
