from urllib.parse import urlparse
from PIL import Image
import os

def get_image_path(img_info, image_dir):
    """Parse local image path from COCO URL"""
    url_path = urlparse(img_info['coco_url']).path
    file_name = url_path.split('/')[-1]
    return os.path.join(image_dir, file_name)

def bbox_to_xyxy(bbox):
    """Convert [x,y,w,h] to [x1,y1,x2,y2]"""
    x, y, w, h = bbox
    return [x, y, x + w, y + h]

def load_and_crop_image(img_path, bbox):
    """Load image and crop ROI"""
    try:
        image = Image.open(img_path).convert("RGB")
        return image.crop(bbox)
    except Exception as e:
        raise ValueError(f"Failed to process image {img_path}: {str(e)}")
