import fiftyone as fo
import fiftyone.zoo as foz
import os
import shutil

# Create folders
os.makedirs("../data/images/val", exist_ok=True)
os.makedirs("../data/labels/val", exist_ok=True)

# Download small COCO 2017 validation subset
dataset = foz.load_zoo_dataset(
    "coco-2017",
    split="validation",
    label_types=["detections"],
    classes=["person","car"],
    max_samples=50
)

# Save images and YOLO labels
for sample in dataset:
    img_path = os.path.join("../data/images/val", sample.filepath.split("\\")[-1])
    # Save image
    shutil.copy(sample.filepath, img_path)
    
    # Save YOLO label
    label_path = os.path.join("../data/labels/val", sample.filepath.split("\\")[-1].replace(".jpg", ".txt"))
    with open(label_path, "w") as f:
        for detection in sample.ground_truth.detections:
            cls_id = 0 if detection.label == "person" else 1
            bbox = detection.bounding_box  # [x,y,width,height] normalized
            f.write(f"{cls_id} {bbox[0]+bbox[2]/2} {bbox[1]+bbox[3]/2} {bbox[2]} {bbox[3]}\n")

print("Small COCO subset downloaded and YOLO labels created!")
