import torch


def eval_iou(target_boxes, predicted_boxes):
    """
    Evaluates Predicted box location relative to Ground Truth box
    based on Intersection over Union metric to score high matching.

    Params
    ------
    target_boxes : (torch.tensor)
        midpoint format boxes {cx, cy, w, h} of shape --> (N, 4) 
    predicted_boxes : (torch.tensor)
        {cx, cy, w, h} of shape --> (N, 4) 
    
    Return
    ------
    iou_scores : (torch.tensor)
        iou scores of shape --> (N, 1)
    """
    # gboxes = change_boxes_format(target_boxes)
    # pboxes = change_boxes_format(predicted_boxes)
    g_x1, g_y1, g_x2, g_y2  = target_boxes.split(1, dim=-1)
    p_x1, p_y1, p_x2, p_y2 = predicted_boxes.split(1, dim=-1)
    # intersection corners estimation
    inter_x1 = torch.max(g_x1, p_x1)
    inter_y1 = torch.max(g_y1, p_y1)
    inter_x2 = torch.min(g_x2, p_x2)
    inter_y2 = torch.min(g_y2, p_y2)
    # iou evaluation
    inter_area = (inter_x2-inter_x1).clamp(0) * (inter_y2-inter_y1).clamp(0)
    g_area = torch.abs((g_x2 - g_x1) * (g_y2 - g_y1))
    p_area = torch.abs((p_x2 - p_x1) * (p_y2 - p_y1))
    union_area = g_area + p_area - inter_area
    iou_scores = inter_area / union_area
    return iou_scores + 1e-6