from typing import List
from typing import Dict
import codecs


def load_dict(dict_path: str,
              required: List[str] = ["<sos>", "<eos>"],
              reverse: bool = False) -> Dict:
    """
    Load the dictionary object
    Args:
        dict_path: path of the vocabulary dictionary
        required: required units in the dict
        reverse: return int:str if true, else str:int
    """
    with codecs.open(dict_path, encoding="utf-8") as f:
        vocab = {}
        for line in f:
            tok, idx = line.split()
            if reverse:
                vocab[int(idx)] = tok
            else:
                if tok in vocab:
                    raise RuntimeError(
                        f"Duplicated token in {dict_path}: {tok}")
                vocab[tok] = int(idx)
    if not reverse:
        for token in required:
            if token not in vocab:
                raise ValueError(f"Miss token: {token} in {dict_path}")
    return vocab