

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   UpperCamelCase			(  SCREAMING_SNAKE_CASE ):

    def __get__(      self			:   Optional[int]				,     snake_case__			:   List[str]				,     snake_case__			:   int=None     ):

     """simple docstring"""






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


def 							__lowerCAmelCase     (							_UpperCamelCase		:	Dict						)		->				Dict:
 '''simple docstring'''


 SCREAMING_SNAKE_CASE		    =      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		:	str						)		->				Any:
 '''simple docstring'''


 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		:	List[Any]						)		->				Tuple:
 '''simple docstring'''


 return isinstance(_UpperCamelCase		,				np.ndarray						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	int						)		->				List[Any]:
 '''simple docstring'''


 return _is_numpy(_UpperCamelCase						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	str						)		->				Union[str, Any]:
 '''simple docstring'''


 import torch

 return isinstance(_UpperCamelCase		,				torch.Tensor						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	Optional[Any]						)		->				Optional[int]:
 '''simple docstring'''


 return False if not is_torch_available() else _is_torch(_UpperCamelCase						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	Optional[Any]						)		->				Dict:
 '''simple docstring'''


 import torch

 return isinstance(_UpperCamelCase		,				torch.device						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	Optional[Any]						)		->				str:
 '''simple docstring'''


 return False if not is_torch_available() else _is_torch_device(_UpperCamelCase						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	Optional[Any]						)		->				List[Any]:
 '''simple docstring'''


 import torch

 if isinstance(_UpperCamelCase		,				_UpperCamelCase						):
  if hasattr(_UpperCamelCase		,				_UpperCamelCase						):
   SCREAMING_SNAKE_CASE		    =      getattr(_UpperCamelCase		,				_UpperCamelCase						)
  else:
   return False
 return isinstance(_UpperCamelCase		,				torch.dtype						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	Tuple						)		->				List[Any]:
 '''simple docstring'''


 return False if not is_torch_available() else _is_torch_dtype(_UpperCamelCase						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	Union[str, Any]						)		->				Dict:
 '''simple docstring'''


 import tensorflow as tf

 return isinstance(_UpperCamelCase		,				tf.Tensor						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	str						)		->				Optional[int]:
 '''simple docstring'''


 return False if not is_tf_available() else _is_tensorflow(_UpperCamelCase						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	List[str]						)		->				Tuple:
 '''simple docstring'''


 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		:	Optional[int]						)		->				Optional[int]:
 '''simple docstring'''


 return False if not is_tf_available() else _is_tf_symbolic_tensor(_UpperCamelCase						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	Union[str, Any]						)		->				int:
 '''simple docstring'''


 import jax.numpy as jnp  # noqa: F811

 return isinstance(_UpperCamelCase		,				jnp.ndarray						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	str						)		->				Any:
 '''simple docstring'''


 return False if not is_flax_available() else _is_jax(_UpperCamelCase						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	int						)		->				Dict:
 '''simple docstring'''


 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[Any]						)		->				List[str]:
 '''simple docstring'''


 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   UpperCamelCase			(  SCREAMING_SNAKE_CASE ):

    def UpperCamelCase      (      self			:   int     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      fields(self     )

     # Safety and consistency checks
     if not len(snake_case__     ):
      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."""     )

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

     if other_fields_are_none and not is_tensor(snake_case__     ):
      if isinstance(snake_case__				,     snake_case__     ):
       SCREAMING_SNAKE_CASE		    =      first_field.items()
       SCREAMING_SNAKE_CASE		    =      True
      else:
       try:
        SCREAMING_SNAKE_CASE		    =      iter(snake_case__     )
        SCREAMING_SNAKE_CASE		    =      True
       except TypeError:
        SCREAMING_SNAKE_CASE		    =      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(snake_case__     ):
        if (
            not isinstance(snake_case__				,     (list, tuple)     )
            or not len(snake_case__     ) == 2
            or not isinstance(element[0]				,     snake_case__     )
        ):
         if idx == 0:
          # If we do not have an iterator of key/values, set it as attribute
          SCREAMING_SNAKE_CASE		    =      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:
         SCREAMING_SNAKE_CASE		    =      element[1]
      elif first_field is not None:
       SCREAMING_SNAKE_CASE		    =      first_field
     else:
      for field in class_fields:
       SCREAMING_SNAKE_CASE		    =      getattr(self				,     field.name     )
       if v is not None:
        SCREAMING_SNAKE_CASE		    =      v

    def __delitem__(      self			:   Tuple				,     *snake_case__			:   Optional[int]				,     **snake_case__			:   Any     ):

     """simple docstring"""






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

    def UpperCamelCase      (      self			:   Union[str, Any]				,     *snake_case__			:   Tuple				,     **snake_case__			:   Tuple     ):

     """simple docstring"""






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

    def UpperCamelCase      (      self			:   str				,     *snake_case__			:   Dict				,     **snake_case__			:   Optional[Any]     ):

     """simple docstring"""






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

    def UpperCamelCase      (      self			:   List[Any]				,     *snake_case__			:   Dict				,     **snake_case__			:   Dict     ):

     """simple docstring"""






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

    def __getitem__(      self			:   Optional[Any]				,     snake_case__			:   Union[str, Any]     ):

     """simple docstring"""






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

    def __setattr__(      self			:   Any				,     snake_case__			:   Dict				,     snake_case__			:   Optional[Any]     ):

     """simple docstring"""






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

    def __setitem__(      self			:   int				,     snake_case__			:   Union[str, Any]				,     snake_case__			:   Optional[int]     ):

     """simple docstring"""






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




    def UpperCamelCase      (      self			:   List[str]     ):

     """simple docstring"""






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




class   UpperCamelCase			(  SCREAMING_SNAKE_CASE						,      SCREAMING_SNAKE_CASE ):

    @classmethod
    def UpperCamelCase      (      cls			:   List[Any]				,     snake_case__			:   List[str]     ):

     """simple docstring"""






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




class   UpperCamelCase			(  SCREAMING_SNAKE_CASE ):
    __UpperCamelCase    ="longest"
    __UpperCamelCase    ="max_length"
    __UpperCamelCase    ="do_not_pad"




class   UpperCamelCase			(  SCREAMING_SNAKE_CASE ):
    __UpperCamelCase    ="pt"
    __UpperCamelCase    ="tf"
    __UpperCamelCase    ="np"
    __UpperCamelCase    ="jax"




class   UpperCamelCase			:

    def __init__(      self			:   List[Any]				,     snake_case__			:   List[ContextManager]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      context_managers
     SCREAMING_SNAKE_CASE		    =      ExitStack()

    def __enter__(      self			:   Optional[Any]     ):

     """simple docstring"""






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




    def __exit__(      self			:   Any				,     *snake_case__			:   Tuple				,     **snake_case__			:   List[str]     ):

     """simple docstring"""






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


def 							__lowerCAmelCase     (							_UpperCamelCase		:	List[str]						)		->				Union[str, Any]:
 '''simple docstring'''


 SCREAMING_SNAKE_CASE		    =      infer_framework(_UpperCamelCase						)
 if framework == "tf":
  SCREAMING_SNAKE_CASE		    =      inspect.signature(model_class.call						)  # TensorFlow models
 elif framework == "pt":
  SCREAMING_SNAKE_CASE		    =      inspect.signature(model_class.forward						)  # PyTorch models
 else:
  SCREAMING_SNAKE_CASE		    =      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		:	Optional[int]						)		->				Optional[Any]:
 '''simple docstring'''


 SCREAMING_SNAKE_CASE		    =      model_class.__name__
 SCREAMING_SNAKE_CASE		    =      infer_framework(_UpperCamelCase						)
 if framework == "tf":
  SCREAMING_SNAKE_CASE		    =      inspect.signature(model_class.call						)  # TensorFlow models
 elif framework == "pt":
  SCREAMING_SNAKE_CASE		    =      inspect.signature(model_class.forward						)  # PyTorch models
 else:
  SCREAMING_SNAKE_CASE		    =      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		:	MutableMapping		,				_UpperCamelCase		:	str = ""		,				_UpperCamelCase		:	str = "."						)		->				Tuple:
 '''simple docstring'''


 def _flatten_dict(_UpperCamelCase		:	List[Any]		,				_UpperCamelCase		:	Union[str, Any]=""		,				_UpperCamelCase		:	str="."						):
  for k, v in d.items():
   SCREAMING_SNAKE_CASE		    =      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		:	Tuple		,				_UpperCamelCase		:	bool = False						)		->				List[str]:
 '''simple docstring'''


 if use_temp_dir:
  with tempfile.TemporaryDirectory() as tmp_dir:
   yield tmp_dir
 else:
  yield working_dir


def 							__lowerCAmelCase     (							_UpperCamelCase		:	List[str]		,				_UpperCamelCase		:	List[Any]=None						)		->				str:
 '''simple docstring'''


 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		:	Any		,				_UpperCamelCase		:	Any						)		->				str:
 '''simple docstring'''


 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		:	List[Any]		,				_UpperCamelCase		:	Dict=None						)		->				Any:
 '''simple docstring'''


 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		:	Optional[Any]		,				_UpperCamelCase		:	str						)		->				str:
 '''simple docstring'''


 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		:	Optional[Any]						)		->				int:
 '''simple docstring'''


 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		:	int		,				_UpperCamelCase		:	str						)		->				int:
 '''simple docstring'''


 for key, value in auto_map.items():
  if isinstance(_UpperCamelCase		,				(tuple, list)						):
   SCREAMING_SNAKE_CASE		    =      [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:
   SCREAMING_SNAKE_CASE		    =      f"""{repo_id}--{value}"""

 return auto_map




def 							__lowerCAmelCase     (							_UpperCamelCase		:	str						)		->				List[str]:
 '''simple docstring'''


 for base_class in inspect.getmro(_UpperCamelCase						):
  SCREAMING_SNAKE_CASE		    =      base_class.__module__
  SCREAMING_SNAKE_CASE		    =      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}."""						)




import string


def 							__lowerCAmelCase     (							_UpperCamelCase		:	str						)		->				str:
 '''simple docstring'''


 SCREAMING_SNAKE_CASE		    =      ''
 for i in sequence:
  SCREAMING_SNAKE_CASE		    =      ord(_UpperCamelCase						)
  if 65 <= extract <= 90:
   output += chr(1_55 - extract						)
  elif 97 <= extract <= 1_22:
   output += chr(2_19 - extract						)
  else:
   output += i
 return output


def 							__lowerCAmelCase     (							_UpperCamelCase		:	str						)		->				str:
 '''simple docstring'''


 SCREAMING_SNAKE_CASE		    =      string.ascii_letters
 SCREAMING_SNAKE_CASE		    =      string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1]
 return "".join(
     letters_reversed[letters.index(_UpperCamelCase						)] if c in letters else c for c in sequence						)


def 							__lowerCAmelCase     (							)		->				None:
 '''simple docstring'''


 from timeit import timeit

 print('Running performance benchmarks...'						)
 SCREAMING_SNAKE_CASE		    =      'from string import printable ; from __main__ import atbash, atbash_slow'
 print(f"""> atbash_slow(): {timeit('atbash_slow(printable)'		,				setup=_UpperCamelCase						)} seconds"""						)
 print(f""">      atbash(): {timeit('atbash(printable)'		,				setup=_UpperCamelCase						)} seconds"""						)


if __name__ == "__main__":
      for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"):
            print(F"""{example} encrypted in atbash: {atbash(example)}""")
      benchmark()

