'''simple docstring'''




import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
  import jax.numpy as jnp




class    a__				(       UpperCAmelCase__			):






     def __get__(			self		:		Union[str, Any]  ,    a		:		Optional[int]  ,    a		:		Optional[int]=None   ):





         """simple docstring"""



         if obj is None:
             return self
         if self.fget is None:
             raise AttributeError('''unreadable attribute'''   )
         __lowerCamelCase          =  '''__cached_''' + self.fget.__name__
         __lowerCamelCase          =  getattr(a  ,    a  ,    a   )
         if cached is None:
             __lowerCamelCase          =  self.fget(a   )
             setattr(a  ,    a  ,    a   )
         return cached






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   Optional[Any]:
    __lowerCamelCase          =  val.lower()
    if val in {"y", "yes", "t", "true", "on", "1"}:
        return 1
    if val in {"n", "no", "f", "false", "off", "0"}:
        return 0
    raise ValueError(f"""invalid truth value {val!r}"""    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   List[Any]:
    if is_torch_fx_proxy(UpperCamelCase__    ):
        return True
    if is_torch_available():
        import torch

        if isinstance(UpperCamelCase__    ,  torch.Tensor    ):
            return True
    if is_tf_available():
        import tensorflow as tf

        if isinstance(UpperCamelCase__    ,  tf.Tensor    ):
            return True

    if is_flax_available():
        import jax.numpy as jnp
        from jax.core import Tracer

        if isinstance(UpperCamelCase__    ,  (jnp.ndarray, Tracer)    ):
            return True

    return isinstance(UpperCamelCase__    ,  np.ndarray    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   Union[str, Any]:
    return isinstance(UpperCamelCase__    ,  np.ndarray    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   Optional[Any]:
    return _is_numpy(UpperCamelCase__    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   Any:
    import torch

    return isinstance(UpperCamelCase__    ,  torch.Tensor    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   str:
    return False if not is_torch_available() else _is_torch(UpperCamelCase__    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   int:
    import torch

    return isinstance(UpperCamelCase__    ,  torch.device    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   int:
    return False if not is_torch_available() else _is_torch_device(UpperCamelCase__    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   Tuple:
    import torch

    if isinstance(UpperCamelCase__    ,  UpperCamelCase__    ):
        if hasattr(UpperCamelCase__    ,  UpperCamelCase__    ):
            __lowerCamelCase          =  getattr(UpperCamelCase__    ,  UpperCamelCase__    )
        else:
            return False
    return isinstance(UpperCamelCase__    ,  torch.dtype    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   List[str]:
    return False if not is_torch_available() else _is_torch_dtype(UpperCamelCase__    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   Optional[Any]:
    import tensorflow as tf

    return isinstance(UpperCamelCase__    ,  tf.Tensor    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   Dict:
    return False if not is_tf_available() else _is_tensorflow(UpperCamelCase__    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   int:
    import tensorflow as tf

    # the `is_symbolic_tensor` predicate is only available starting with TF 2.14
    if hasattr(UpperCamelCase__    ,  '''is_symbolic_tensor'''    ):
        return tf.is_symbolic_tensor(UpperCamelCase__    )
    return type(UpperCamelCase__    ) == tf.Tensor






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   Any:
    return False if not is_tf_available() else _is_tf_symbolic_tensor(UpperCamelCase__    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   Optional[int]:
    import jax.numpy as jnp  # noqa: F811

    return isinstance(UpperCamelCase__    ,  jnp.ndarray    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   Optional[int]:
    return False if not is_flax_available() else _is_jax(UpperCamelCase__    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   int:
    if isinstance(UpperCamelCase__    ,  (dict, UserDict)    ):
        return {k: to_py_obj(UpperCamelCase__    ) for k, v in obj.items()}
    elif isinstance(UpperCamelCase__    ,  (list, tuple)    ):
        return [to_py_obj(UpperCamelCase__    ) for o in obj]
    elif is_tf_tensor(UpperCamelCase__    ):
        return obj.numpy().tolist()
    elif is_torch_tensor(UpperCamelCase__    ):
        return obj.detach().cpu().tolist()
    elif is_jax_tensor(UpperCamelCase__    ):
        return np.asarray(UpperCamelCase__    ).tolist()
    elif isinstance(UpperCamelCase__    ,  (np.ndarray, np.number)    ):  # tolist also works on 0d np arrays
        return obj.tolist()
    else:
        return obj






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   List[str]:
    if isinstance(UpperCamelCase__    ,  (dict, UserDict)    ):
        return {k: to_numpy(UpperCamelCase__    ) for k, v in obj.items()}
    elif isinstance(UpperCamelCase__    ,  (list, tuple)    ):
        return np.array(UpperCamelCase__    )
    elif is_tf_tensor(UpperCamelCase__    ):
        return obj.numpy()
    elif is_torch_tensor(UpperCamelCase__    ):
        return obj.detach().cpu().numpy()
    elif is_jax_tensor(UpperCamelCase__    ):
        return np.asarray(UpperCamelCase__    )
    else:
        return obj




class    a__				(       UpperCAmelCase__			):






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[str]   ):





         """simple docstring"""



         __lowerCamelCase          =  fields(self   )

         # Safety and consistency checks
         if not len(a   ):
             raise ValueError(f"""{self.__class__.__name__} has no fields."""   )
         if not all(field.default is None for field in class_fields[1:]   ):
             raise ValueError(f"""{self.__class__.__name__} should not have more than one required field."""   )

         __lowerCamelCase          =  getattr(self  ,    class_fields[0].name   )
         __lowerCamelCase          =  all(getattr(self  ,    field.name   ) is None for field in class_fields[1:]   )

         if other_fields_are_none and not is_tensor(a   ):
             if isinstance(a  ,    a   ):
                 __lowerCamelCase          =  first_field.items()
                 __lowerCamelCase          =  True
             else:
                 try:
                     __lowerCamelCase          =  iter(a   )
                     __lowerCamelCase          =  True
                 except TypeError:
                     __lowerCamelCase          =  False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
             if first_field_iterator:
                 for idx, element in enumerate(a   ):
                     if (
                         not isinstance(a  ,    (list, tuple)   )
                         or not len(a   ) == 2
                         or not isinstance(element[0]  ,    a   )
                     ):
                         if idx == 0:
                             # If we do not have an iterator of key/values, set it as attribute
                             __lowerCamelCase          =  first_field
                         else:
                             # If we have a mixed iterator, raise an error
                             raise ValueError(
                                 f"""Cannot set key/value for {element}. It needs to be a tuple (key, value)."""   )
                         break
                     setattr(self  ,    element[0]  ,    element[1]   )
                     if element[1] is not None:
                         __lowerCamelCase          =  element[1]
             elif first_field is not None:
                 __lowerCamelCase          =  first_field
         else:
             for field in class_fields:
                 __lowerCamelCase          =  getattr(self  ,    field.name   )
                 if v is not None:
                     __lowerCamelCase          =  v






     def __delitem__(			self		:		List[Any]  ,    *a		:		Optional[int]  ,    **a		:		Optional[Any]   ):





         """simple docstring"""



         raise Exception(f"""You cannot use ``__delitem__`` on a {self.__class__.__name__} instance."""   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Union[str, Any]  ,    *a		:		List[Any]  ,    **a		:		Dict   ):





         """simple docstring"""



         raise Exception(f"""You cannot use ``setdefault`` on a {self.__class__.__name__} instance."""   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[Any]  ,    *a		:		List[str]  ,    **a		:		str   ):





         """simple docstring"""



         raise Exception(f"""You cannot use ``pop`` on a {self.__class__.__name__} instance."""   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[Any]  ,    *a		:		Tuple  ,    **a		:		Union[str, Any]   ):





         """simple docstring"""



         raise Exception(f"""You cannot use ``update`` on a {self.__class__.__name__} instance."""   )






     def __getitem__(			self		:		List[str]  ,    a		:		List[str]   ):





         """simple docstring"""



         if isinstance(a  ,    a   ):
             __lowerCamelCase          =  dict(self.items()   )
             return inner_dict[k]
         else:
             return self.to_tuple()[k]






     def __setattr__(			self		:		List[Any]  ,    a		:		Union[str, Any]  ,    a		:		str   ):





         """simple docstring"""



         if name in self.keys() and value is not None:
             # Don't call self.__setitem__ to avoid recursion errors
             super().__setitem__(a  ,    a   )
         super().__setattr__(a  ,    a   )






     def __setitem__(			self		:		List[str]  ,    a		:		str  ,    a		:		Dict   ):





         """simple docstring"""



         super().__setitem__(a  ,    a   )
         # Don't call self.__setattr__ to avoid recursion errors
         super().__setattr__(a  ,    a   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]   ):





         """simple docstring"""



         return tuple(self[k] for k in self.keys()   )




class    a__				(       UpperCAmelCase__							,       UpperCAmelCase__			):






     @classmethod
     def        SCREAMING_SNAKE_CASE__       (			cls		:		int  ,    a		:		int   ):





         """simple docstring"""



         raise ValueError(
             f"""{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()   )}"""   )




class    a__				(       UpperCAmelCase__			):
     lowerCamelCase  :					Tuple							="longest"
     lowerCamelCase  :					Any							="max_length"
     lowerCamelCase  :					Tuple							="do_not_pad"




class    a__				(       UpperCAmelCase__			):
     lowerCamelCase  :					Dict							="pt"
     lowerCamelCase  :					Tuple							="tf"
     lowerCamelCase  :					Any							="np"
     lowerCamelCase  :					Any							="jax"




class    a__				:






     def __init__(			self		:		str  ,    a		:		List[ContextManager]   ):





         """simple docstring"""



         __lowerCamelCase          =  context_managers
         __lowerCamelCase          =  ExitStack()






     def __enter__(			self		:		Optional[int]   ):





         """simple docstring"""



         for context_manager in self.context_managers:
             self.stack.enter_context(a   )






     def __exit__(			self		:		List[Any]  ,    *a		:		Tuple  ,    **a		:		Optional[Any]   ):





         """simple docstring"""



         self.stack.__exit__(*a  ,    **a   )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   Tuple:
    __lowerCamelCase          =  infer_framework(UpperCamelCase__    )
    if framework == "tf":
        __lowerCamelCase          =  inspect.signature(model_class.call    )  # TensorFlow models
    elif framework == "pt":
        __lowerCamelCase          =  inspect.signature(model_class.forward    )  # PyTorch models
    else:
        __lowerCamelCase          =  inspect.signature(model_class.__call__    )  # Flax models

    for p in signature.parameters:
        if p == "return_loss" and signature.parameters[p].default is True:
            return True

    return False






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   int:
    __lowerCamelCase          =  model_class.__name__
    __lowerCamelCase          =  infer_framework(UpperCamelCase__    )
    if framework == "tf":
        __lowerCamelCase          =  inspect.signature(model_class.call    )  # TensorFlow models
    elif framework == "pt":
        __lowerCamelCase          =  inspect.signature(model_class.forward    )  # PyTorch models
    else:
        __lowerCamelCase          =  inspect.signature(model_class.__call__    )  # Flax models

    if "QuestionAnswering" in model_name:
        return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
    else:
        return [p for p in signature.parameters if "label" in p]






def __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__ = ""    ,  UpperCamelCase__ = "."    )     ->   Optional[Any]:

    def _flatten_dict(UpperCamelCase__    ,  UpperCamelCase__=""    ,  UpperCamelCase__="."    ):
        for k, v in d.items():
            __lowerCamelCase          =  str(UpperCamelCase__    ) + delimiter + str(UpperCamelCase__    ) if parent_key else k
            if v and isinstance(UpperCamelCase__    ,  UpperCamelCase__    ):
                yield from flatten_dict(UpperCamelCase__    ,  UpperCamelCase__    ,  delimiter=UpperCamelCase__    ).items()
            else:
                yield key, v

    return dict(_flatten_dict(UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    )    )






@contextmanager
def __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__ = False    )     ->   str:
    if use_temp_dir:
        with tempfile.TemporaryDirectory() as tmp_dir:
            yield tmp_dir
    else:
        yield working_dir






def __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__=None    )     ->   Any:
    if is_numpy_array(UpperCamelCase__    ):
        return np.transpose(UpperCamelCase__    ,  axes=UpperCamelCase__    )
    elif is_torch_tensor(UpperCamelCase__    ):
        return array.T if axes is None else array.permute(*UpperCamelCase__    )
    elif is_tf_tensor(UpperCamelCase__    ):
        import tensorflow as tf

        return tf.transpose(UpperCamelCase__    ,  perm=UpperCamelCase__    )
    elif is_jax_tensor(UpperCamelCase__    ):
        return jnp.transpose(UpperCamelCase__    ,  axes=UpperCamelCase__    )
    else:
        raise ValueError(f"""Type not supported for transpose: {type(UpperCamelCase__    )}."""    )






def __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__    )     ->   Any:
    if is_numpy_array(UpperCamelCase__    ):
        return np.reshape(UpperCamelCase__    ,  UpperCamelCase__    )
    elif is_torch_tensor(UpperCamelCase__    ):
        return array.reshape(*UpperCamelCase__    )
    elif is_tf_tensor(UpperCamelCase__    ):
        import tensorflow as tf

        return tf.reshape(UpperCamelCase__    ,  UpperCamelCase__    )
    elif is_jax_tensor(UpperCamelCase__    ):
        return jnp.reshape(UpperCamelCase__    ,  UpperCamelCase__    )
    else:
        raise ValueError(f"""Type not supported for reshape: {type(UpperCamelCase__    )}."""    )






def __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__=None    )     ->   Union[str, Any]:
    if is_numpy_array(UpperCamelCase__    ):
        return np.squeeze(UpperCamelCase__    ,  axis=UpperCamelCase__    )
    elif is_torch_tensor(UpperCamelCase__    ):
        return array.squeeze() if axis is None else array.squeeze(dim=UpperCamelCase__    )
    elif is_tf_tensor(UpperCamelCase__    ):
        import tensorflow as tf

        return tf.squeeze(UpperCamelCase__    ,  axis=UpperCamelCase__    )
    elif is_jax_tensor(UpperCamelCase__    ):
        return jnp.squeeze(UpperCamelCase__    ,  axis=UpperCamelCase__    )
    else:
        raise ValueError(f"""Type not supported for squeeze: {type(UpperCamelCase__    )}."""    )






def __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__    )     ->   List[Any]:
    if is_numpy_array(UpperCamelCase__    ):
        return np.expand_dims(UpperCamelCase__    ,  UpperCamelCase__    )
    elif is_torch_tensor(UpperCamelCase__    ):
        return array.unsqueeze(dim=UpperCamelCase__    )
    elif is_tf_tensor(UpperCamelCase__    ):
        import tensorflow as tf

        return tf.expand_dims(UpperCamelCase__    ,  axis=UpperCamelCase__    )
    elif is_jax_tensor(UpperCamelCase__    ):
        return jnp.expand_dims(UpperCamelCase__    ,  axis=UpperCamelCase__    )
    else:
        raise ValueError(f"""Type not supported for expand_dims: {type(UpperCamelCase__    )}."""    )






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   str:
    if is_numpy_array(UpperCamelCase__    ):
        return np.size(UpperCamelCase__    )
    elif is_torch_tensor(UpperCamelCase__    ):
        return array.numel()
    elif is_tf_tensor(UpperCamelCase__    ):
        import tensorflow as tf

        return tf.size(UpperCamelCase__    )
    elif is_jax_tensor(UpperCamelCase__    ):
        return array.size
    else:
        raise ValueError(f"""Type not supported for expand_dims: {type(UpperCamelCase__    )}."""    )






def __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__    )     ->   Optional[Any]:
    for key, value in auto_map.items():
        if isinstance(UpperCamelCase__    ,  (tuple, list)    ):
            __lowerCamelCase          =  [f"""{repo_id}--{v}""" if (v is not None and '''--''' not in v) else v for v in value]
        elif value is not None and "--" not in value:
            __lowerCamelCase          =  f"""{repo_id}--{value}"""

    return auto_map






def __lowerCAmelCase			(							UpperCamelCase__    )     ->   Any:
    for base_class in inspect.getmro(UpperCamelCase__    ):
        __lowerCamelCase          =  base_class.__module__
        __lowerCamelCase          =  base_class.__name__
        if module.startswith('''tensorflow'''    ) or module.startswith('''keras'''    ) or name == "TFPreTrainedModel":
            return "tf"
        elif module.startswith('''torch'''    ) or name == "PreTrainedModel":
            return "pt"
        elif module.startswith('''flax'''    ) or module.startswith('''jax'''    ) or name == "FlaxPreTrainedModel":
            return "flax"
    else:
        raise TypeError(f"""Could not infer framework from class {model_class}."""    )

'''simple docstring'''




def __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    )     ->   float:
    if principal <= 0:
        raise Exception('''Principal borrowed must be > 0'''    )
    if rate_per_annum < 0:
        raise Exception('''Rate of interest must be >= 0'''    )
    if years_to_repay <= 0 or not isinstance(UpperCamelCase__    ,  UpperCamelCase__    ):
        raise Exception('''Years to repay must be an integer > 0'''    )

    # Yearly rate is divided by 12 to get monthly rate
    __lowerCamelCase          =  rate_per_annum / 12

    # Years to repay is multiplied by 12 to get number of payments as payment is monthly
    __lowerCamelCase          =  years_to_repay * 12

    return (
        principal
        * rate_per_month
        * (1 + rate_per_month) ** number_of_payments
        / ((1 + rate_per_month) ** number_of_payments - 1)
    )


if __name__ == "__main__":
  import doctest

  doctest.testmod()
