
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   (						UpperCamelCase__   ):





   '''simple docstring'''


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

      """simple docstring"""
      # See docs.python.org/3/howto/descriptor.html#properties
      if obj is None:
         return self
      if self.fget is None:
         raise AttributeError('''unreadable attribute'''     )
      _A:  List[str]					=       """__cached_""" + self.fget.__name__
      _A:  Any					=       getattr(_a			,			_a			,			_a     )
      if cached is None:
         _A:  Dict					=       self.fget(_a     )
         setattr(_a			,			_a			,			_a     )
      return cached






def   lowerCamelCase__							(					a      )      ->   List[str]:
   _A:  Union[str, Any]					=       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__							(					a      )      ->   Optional[Any]:
   if is_torch_fx_proxy(snake_case_      ):
      return True
   if is_torch_available():
      import torch

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

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

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

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

   return isinstance(snake_case_		,		np.ndarray      )






def   lowerCamelCase__							(					a      )      ->   Optional[Any]:
   return isinstance(snake_case_		,		np.ndarray      )






def   lowerCamelCase__							(					a      )      ->   int:
   return _is_numpy(snake_case_      )






def   lowerCamelCase__							(					a      )      ->   Optional[Any]:
   import torch

   return isinstance(snake_case_		,		torch.Tensor      )






def   lowerCamelCase__							(					a      )      ->   List[str]:
   return False if not is_torch_available() else _is_torch(snake_case_      )






def   lowerCamelCase__							(					a      )      ->   List[Any]:
   import torch

   return isinstance(snake_case_		,		torch.device      )






def   lowerCamelCase__							(					a      )      ->   Optional[int]:
   return False if not is_torch_available() else _is_torch_device(snake_case_      )






def   lowerCamelCase__							(					a      )      ->   Optional[Any]:
   import torch

   if isinstance(snake_case_		,		snake_case_      ):
      if hasattr(snake_case_		,		snake_case_      ):
         _A:  Optional[int]					=       getattr(snake_case_		,		snake_case_      )
      else:
         return False
   return isinstance(snake_case_		,		torch.dtype      )






def   lowerCamelCase__							(					a      )      ->   Dict:
   return False if not is_torch_available() else _is_torch_dtype(snake_case_      )






def   lowerCamelCase__							(					a      )      ->   str:
   import tensorflow as tf

   return isinstance(snake_case_		,		tf.Tensor      )






def   lowerCamelCase__							(					a      )      ->   Dict:
   return False if not is_tf_available() else _is_tensorflow(snake_case_      )






def   lowerCamelCase__							(					a      )      ->   Optional[Any]:
   import tensorflow as tf

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






def   lowerCamelCase__							(					a      )      ->   Optional[Any]:
   return False if not is_tf_available() else _is_tf_symbolic_tensor(snake_case_      )






def   lowerCamelCase__							(					a      )      ->   Optional[Any]:
   import jax.numpy as jnp  # noqa: F811

   return isinstance(snake_case_		,		jnp.ndarray      )






def   lowerCamelCase__							(					a      )      ->   Tuple:
   return False if not is_flax_available() else _is_jax(snake_case_      )






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






def   lowerCamelCase__							(					a      )      ->   Dict:
   if isinstance(snake_case_		,		(dict, UserDict)      ):
      return {k: to_numpy(snake_case_      ) for k, v in obj.items()}
   elif isinstance(snake_case_		,		(list, tuple)      ):
      return np.array(snake_case_      )
   elif is_tf_tensor(snake_case_      ):
      return obj.numpy()
   elif is_torch_tensor(snake_case_      ):
      return obj.detach().cpu().numpy()
   elif is_jax_tensor(snake_case_      ):
      return np.asarray(snake_case_      )
   else:
      return obj






class UpperCAmelCase   (						UpperCamelCase__   ):





   '''simple docstring'''


   def  __magic_name__				(					self     :							Optional[Any]     ):

      """simple docstring"""
      _A:  int					=       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."""     )

      _A:  str					=       getattr(self			,			class_fields[0].name     )
      _A:  str					=       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     ):
            _A:  int					=       first_field.items()
            _A:  Dict					=       True
         else:
            try:
               _A:  List[Any]					=       iter(_a     )
               _A:  List[Any]					=       True
            except TypeError:
               _A:  Dict					=       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
                     _A:  Dict					=       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:
                  _A:  Any					=       element[1]
         elif first_field is not None:
            _A:  List[str]					=       first_field
      else:
         for field in class_fields:
            _A:  Any					=       getattr(self			,			field.name     )
            if v is not None:
               _A:  int					=       v


   def __delitem__(					self     :							Any			,			*lowerCAmelCase_     :							Any			,			**lowerCAmelCase_     :							str     ):

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


   def  __magic_name__				(					self     :							List[str]			,			*lowerCAmelCase_     :							int			,			**lowerCAmelCase_     :							List[str]     ):

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


   def  __magic_name__				(					self     :							int			,			*lowerCAmelCase_     :							int			,			**lowerCAmelCase_     :							Tuple     ):

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


   def  __magic_name__				(					self     :							int			,			*lowerCAmelCase_     :							List[str]			,			**lowerCAmelCase_     :							Optional[Any]     ):

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


   def __getitem__(					self     :							Dict			,			lowerCAmelCase_     :							List[Any]     ):

      """simple docstring"""
      if isinstance(_a			,			_a     ):
         _A:  str					=       dict(self.items()     )
         return inner_dict[k]
      else:
         return self.to_tuple()[k]


   def __setattr__(					self     :							Optional[Any]			,			lowerCAmelCase_     :							Dict			,			lowerCAmelCase_     :							List[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     :							int			,			lowerCAmelCase_     :							Any			,			lowerCAmelCase_     :							Any     ):

      """simple docstring"""
      # Will raise a KeyException if needed
      super().__setitem__(_a			,			_a     )
      # Don't call self.__setattr__ to avoid recursion errors
      super().__setattr__(_a			,			_a     )


   def  __magic_name__				(					self     :							str     ):

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






class UpperCAmelCase   (						UpperCamelCase__							,							UpperCamelCase__   ):





   '''simple docstring'''


   @classmethod
   def  __magic_name__				(					cls     :							List[Any]			,			lowerCAmelCase_     :							int     ):

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






class UpperCAmelCase   (						UpperCamelCase__   ):





   '''simple docstring'''
   __UpperCamelCase		:    Dict 				=    '''longest'''
   __UpperCamelCase		:    Dict 				=    '''max_length'''
   __UpperCamelCase		:    List[Any] 				=    '''do_not_pad'''






class UpperCAmelCase   (						UpperCamelCase__   ):





   '''simple docstring'''
   __UpperCamelCase		:    Dict 				=    '''pt'''
   __UpperCamelCase		:    int 				=    '''tf'''
   __UpperCamelCase		:    Union[str, Any] 				=    '''np'''
   __UpperCamelCase		:    str 				=    '''jax'''






class UpperCAmelCase   :





   '''simple docstring'''


   def __init__(					self     :							int			,			lowerCAmelCase_     :							Union[str, Any]     ):

      """simple docstring"""
      _A:  List[Any]					=       context_managers
      _A:  List[Any]					=       ExitStack()


   def __enter__(					self     :							int     ):

      """simple docstring"""
      for context_manager in self.context_managers:
         self.stack.enter_context(_a     )


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

      """simple docstring"""
      self.stack.__exit__(*_a			,			**_a     )






def   lowerCamelCase__							(					a      )      ->   Union[str, Any]:
   _A:  List[Any]					=       infer_framework(snake_case_      )
   if framework == "tf":
      _A:  str					=       inspect.signature(model_class.call      )  # TensorFlow models
   elif framework == "pt":
      _A:  Union[str, Any]					=       inspect.signature(model_class.forward      )  # PyTorch models
   else:
      _A:  int					=       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__							(					a      )      ->   Optional[Any]:
   _A:  Dict					=       model_class.__name__
   _A:  Optional[Any]					=       infer_framework(snake_case_      )
   if framework == "tf":
      _A:  Any					=       inspect.signature(model_class.call      )  # TensorFlow models
   elif framework == "pt":
      _A:  Optional[Any]					=       inspect.signature(model_class.forward      )  # PyTorch models
   else:
      _A:  Optional[Any]					=       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__							(					a		,		a = ""		,		a = "."      )      ->   Any:

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

   return dict(_flatten_dict(snake_case_		,		snake_case_		,		snake_case_      )      )






@contextmanager
def   lowerCamelCase__							(					a		,		a = False      )      ->   Optional[Any]:
   if use_temp_dir:
      with tempfile.TemporaryDirectory() as tmp_dir:
         yield tmp_dir
   else:
      yield working_dir






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

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






def   lowerCamelCase__							(					a		,		a      )      ->   Dict:
   if is_numpy_array(snake_case_      ):
      return np.reshape(snake_case_		,		snake_case_      )
   elif is_torch_tensor(snake_case_      ):
      return array.reshape(*snake_case_      )
   elif is_tf_tensor(snake_case_      ):
      import tensorflow as tf

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






def   lowerCamelCase__							(					a		,		a=None      )      ->   Optional[int]:
   if is_numpy_array(snake_case_      ):
      return np.squeeze(snake_case_		,		axis=snake_case_      )
   elif is_torch_tensor(snake_case_      ):
      return array.squeeze() if axis is None else array.squeeze(dim=snake_case_      )
   elif is_tf_tensor(snake_case_      ):
      import tensorflow as tf

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






def   lowerCamelCase__							(					a		,		a      )      ->   Tuple:
   if is_numpy_array(snake_case_      ):
      return np.expand_dims(snake_case_		,		snake_case_      )
   elif is_torch_tensor(snake_case_      ):
      return array.unsqueeze(dim=snake_case_      )
   elif is_tf_tensor(snake_case_      ):
      import tensorflow as tf

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






def   lowerCamelCase__							(					a      )      ->   List[str]:
   if is_numpy_array(snake_case_      ):
      return np.size(snake_case_      )
   elif is_torch_tensor(snake_case_      ):
      return array.numel()
   elif is_tf_tensor(snake_case_      ):
      import tensorflow as tf

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






def   lowerCamelCase__							(					a		,		a      )      ->   Tuple:
   for key, value in auto_map.items():
      if isinstance(snake_case_		,		(tuple, list)      ):
         _A:  int					=       [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:
         _A:  List[str]					=       f"""{repo_id}--{value}"""

   return auto_map






def   lowerCamelCase__							(					a      )      ->   List[str]:
   for base_class in inspect.getmro(snake_case_      ):
      _A:  Optional[Any]					=       base_class.__module__
      _A:  Tuple					=       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}."""      )









def 				lowerCAmelCase_	(     snake_case_,snake_case_     ):
      while b:
            _A			,   _A							:     List[str]			=						b, a % b
      return a







def 				lowerCAmelCase_	(     snake_case_,snake_case_     ):
      return a if b == 0 else euclidean_gcd_recursive(snake_case_,a % b     )







def 				lowerCAmelCase_	(     ):
      print(f'''euclidean_gcd(3, 5) = {euclidean_gcd(3,5     )}'''     )
      print(f'''euclidean_gcd(5, 3) = {euclidean_gcd(5,3     )}'''     )
      print(f'''euclidean_gcd(1, 3) = {euclidean_gcd(1,3     )}'''     )
      print(f'''euclidean_gcd(3, 6) = {euclidean_gcd(3,6     )}'''     )
      print(f'''euclidean_gcd(6, 3) = {euclidean_gcd(6,3     )}'''     )

      print(f'''euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3,5     )}'''     )
      print(f'''euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5,3     )}'''     )
      print(f'''euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1,3     )}'''     )
      print(f'''euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3,6     )}'''     )
      print(f'''euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6,3     )}'''     )


if __name__ == "__main__":
  main()

