def calculate(preds, targets, iou_threshold=0.5):
    """Compute mean of maximum IoU and F1-score.

    The TableBank datasets consists of images containing multiple tables, while the annotation only marks one table.
    The model outputs preds with multiple tables.
    Therefore, calculate mean of maximum IoU and F1-score.
    """
    preds_xyxy = cxcywh_to_xyxy(preds)
    targets_xyxy = cxcywh_to_xyxy(targets[:, None, :])

    inter_x1 = torch.maximum(preds_xyxy[..., 0], targets_xyxy[..., 0])
    inter_y1 = torch.maximum(preds_xyxy[..., 1], targets_xyxy[..., 1])
    inter_x2 = torch.minimum(preds_xyxy[..., 2], targets_xyxy[..., 2])
    inter_y2 = torch.minimum(preds_xyxy[..., 3], targets_xyxy[..., 3])

    inter_w = (inter_x2 - inter_x1).clamp(min=0)
    inter_h = (inter_y2 - inter_y1).clamp(min=0)
    inter_area = inter_w * inter_h

    preds_area = (preds_xyxy[..., 2] - preds_xyxy[..., 0]) * (preds_xyxy[..., 3] - preds_xyxy[..., 1])
    targets_area = (targets_xyxy[..., 2] - targets_xyxy[..., 0]) * (targets_xyxy[..., 3] - targets_xyxy[..., 1])

    union_area = preds_area + targets_area - inter_area
    iou = inter_area / union_area.clamp(min=1e-6)
    max_iou, _ = iou.max(dim=1)
    mean_iou = max_iou.mean().item()

    tp = (max_iou >= iou_threshold).sum().item()
    fp = (max_iou < iou_threshold).sum().item()
    fn = targets.shape[0] - tp

    precision = tp / (tp + fp + 1e-6)  # Avoid division by zero
    recall = tp / (tp + fn + 1e-6)
    f1_score = 2 * (precision * recall) / (precision + recall + 1e-6)

    return mean_iou, f1_score
Compute mean of maximum IoU and F1-score.

    The TableBank datasets consists of images containing multiple tables, while the annotation only marks one table.
    The model outputs preds with multiple tables.
    Therefore, calculate mean of maximum IoU and F1-score.
    
examples/table_transformer_detection/ttd.py