from typing import List
import torch
from typing import Tuple


def scale_coords(
    img_size: List[int], coords: torch.Tensor, img0_size: Tuple[int, int]
) -> torch.Tensor:
    """Rescales bounding box coordinates (x1, y1, x2, y2) from `img_size` to
    `img0_size`.

    Args:
        img_size (List[int]): Model input size (w x h).
        coords (torch.Tensor): Bounding box coordinates.
        img0_size (Tuple[int, int]): Size of original video frame (h x w).

    Returns:
        (torch.Tensor): Bounding boxes with resized coordinates.
    """
    # gain = old / new
    gain = min(float(img_size[0]) / img0_size[1], float(img_size[1]) / img0_size[0])
    pad_x = (img_size[0] - img0_size[1] * gain) / 2  # width padding
    pad_y = (img_size[1] - img0_size[0] * gain) / 2  # height padding
    coords[:, [0, 2]] -= pad_x
    coords[:, [1, 3]] -= pad_y
    coords[:, :4] /= gain
    coords[:, :4] = torch.clamp(coords[:, :4], min=0)
    return coords