# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/06_utils.ipynb (unless otherwise specified).

__all__ = ['load_json', 'load_yaml', 'xywh_to_xyxy', 'xyxy_to_xywh', 'replacenth']

# Cell
import json
import yaml
import numpy as np

def load_json(files):
    """Load a json file
    """
    with open(files, "r") as fp:
        file = json.load(fp)
    return file

def load_yaml(loc):
    with open(loc) as f:
        data = yaml.load(f)
    return data


def xywh_to_xyxy(xywh):
    """Convert [x1 y1 w h] box format to [x1 y1 x2 y2] format.
    copied from:
    https://github.com/facebookresearch/Detectron/blob/058768239b2d859c7350f633609fddb3a9094a91/detectron/utils/boxes.py#L74
    """
    if isinstance(xywh, (list, tuple)):
        # Single box given as a list of coordinates
        assert len(xywh) == 4
        x1, y1 = xywh[0], xywh[1]
        x2 = x1 + np.maximum(0.0, xywh[2] - 1.0)
        y2 = y1 + np.maximum(0.0, xywh[3] - 1.0)
        return (x1, y1, x2, y2)
    elif isinstance(xywh, np.ndarray):
        # Multiple boxes given as a 2D ndarray
        return np.hstack((xywh[:, 0:2], xywh[:, 0:2] + np.maximum(0, xywh[:, 2:4] - 1)))
    else:
        raise TypeError("Argument xywh must be a list, tuple, or numpy array.")


def xyxy_to_xywh(xyxy):
    """Convert [x1 y1 x2 y2] box format to [x1 y1 w h] format.
    copied from
    https://github.com/facebookresearch/Detectron/blob/058768239b2d859c7350f633609fddb3a9094a91/detectron/utils/boxes.py#L92
    """
    if isinstance(xyxy, (list, tuple)):
        # Single box given as a list of coordinates
        assert len(xyxy) == 4
        x1, y1 = xyxy[0], xyxy[1]
        w = xyxy[2] - x1 + 1
        h = xyxy[3] - y1 + 1
        return (x1, y1, w, h)
    elif isinstance(xyxy, np.ndarray):
        # Multiple boxes given as a 2D ndarray
        return np.hstack((xyxy[:, 0:2], xyxy[:, 2:4] - xyxy[:, 0:2] + 1))
    else:
        raise TypeError("Argument xyxy must be a list, tuple, or numpy array.")


def replacenth(string, sub, wanted, n):
    """
    replace nth occurence of a substring in a string
    """
    where = [m.start() for m in re.finditer(sub, string)][n-1]
    before = string[:where]
    after = string[where:]
    after = after.replace(sub, wanted, 1)
    newString = before + after
    return newString