
'''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  (						SCREAMING_SNAKE_CASE__     ):





	def __get__(       self      :							List[Any]   ,				__magic_name__      :							Dict   ,				__magic_name__      :							Union[str, Any]=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(__magic_name__   ,				__magic_name__   ,				__magic_name__				)
				if cached is None:
							lowerCAmelCase__										=				self.fget(__magic_name__				)
							setattr(__magic_name__   ,				__magic_name__   ,				__magic_name__				)
				return cached







def 	A  (   UpperCamelCase_       :  List[str]   )       ->							str:







			'''simple docstring'''



			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 	A  (   UpperCamelCase_       :  List[Any]   )       ->							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 	A  (   UpperCamelCase_       :  Any   )       ->							Any:







			'''simple docstring'''



			return isinstance(UpperCamelCase_    ,						np.ndarray   )







def 	A  (   UpperCamelCase_       :  str   )       ->							Union[str, Any]:







			'''simple docstring'''



			return _is_numpy(UpperCamelCase_   )







def 	A  (   UpperCamelCase_       :  Union[str, Any]   )       ->							Dict:







			'''simple docstring'''



			import torch

			return isinstance(UpperCamelCase_    ,						torch.Tensor   )







def 	A  (   UpperCamelCase_       :  str   )       ->							Optional[Any]:







			'''simple docstring'''



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







def 	A  (   UpperCamelCase_       :  Union[str, Any]   )       ->							str:







			'''simple docstring'''



			import torch

			return isinstance(UpperCamelCase_    ,						torch.device   )







def 	A  (   UpperCamelCase_       :  Any   )       ->							str:







			'''simple docstring'''



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







def 	A  (   UpperCamelCase_       :  Optional[Any]   )       ->							List[str]:







			'''simple docstring'''



			import torch

			if isinstance(UpperCamelCase_    ,						UpperCamelCase_   ):
						if hasattr(UpperCamelCase_    ,						UpperCamelCase_   ):
									lowerCAmelCase__										=				getattr(UpperCamelCase_    ,						UpperCamelCase_   )
						else:
									return False
			return isinstance(UpperCamelCase_    ,						torch.dtype   )







def 	A  (   UpperCamelCase_       :  int   )       ->							Any:







			'''simple docstring'''



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







def 	A  (   UpperCamelCase_       :  str   )       ->							Tuple:







			'''simple docstring'''



			import tensorflow as tf

			return isinstance(UpperCamelCase_    ,						tf.Tensor   )







def 	A  (   UpperCamelCase_       :  Union[str, Any]   )       ->							List[str]:







			'''simple docstring'''



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







def 	A  (   UpperCamelCase_       :  Optional[int]   )       ->							str:







			'''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 	A  (   UpperCamelCase_       :  Optional[Any]   )       ->							Optional[Any]:







			'''simple docstring'''



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







def 	A  (   UpperCamelCase_       :  Optional[Any]   )       ->							Optional[Any]:







			'''simple docstring'''



			import jax.numpy as jnp  # noqa: F811

			return isinstance(UpperCamelCase_    ,						jnp.ndarray   )







def 	A  (   UpperCamelCase_       :  Union[str, Any]   )       ->							str:







			'''simple docstring'''



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







def 	A  (   UpperCamelCase_       :  List[str]   )       ->							Tuple:







			'''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 	A  (   UpperCamelCase_       :  Tuple   )       ->							Optional[Any]:







			'''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  A  (						SCREAMING_SNAKE_CASE__     ):





	def 				__SCREAMING_SNAKE_CASE	(       self      :							List[Any]				):


				"""simple docstring"""

				lowerCAmelCase__										=				fields(self				)

				# Safety and consistency checks
				if not len(__magic_name__				):
							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(__magic_name__				):
							if isinstance(__magic_name__   ,				__magic_name__				):
										lowerCAmelCase__										=				first_field.items()
										lowerCAmelCase__										=				True
							else:
										try:
													lowerCAmelCase__										=				iter(__magic_name__				)
													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(__magic_name__				):
													if (
													    not isinstance(__magic_name__   ,				(list, tuple)				)
													    or not len(__magic_name__				) == 2
													    or not isinstance(element[0]   ,				__magic_name__				)
													):
																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      :							Union[str, Any]   ,				*__magic_name__      :							Tuple   ,				**__magic_name__      :							Dict				):


				"""simple docstring"""

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





	def 				__SCREAMING_SNAKE_CASE	(       self      :							Tuple   ,				*__magic_name__      :							Tuple   ,				**__magic_name__      :							Dict				):


				"""simple docstring"""

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





	def 				__SCREAMING_SNAKE_CASE	(       self      :							int   ,				*__magic_name__      :							Union[str, Any]   ,				**__magic_name__      :							Union[str, Any]				):


				"""simple docstring"""

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





	def 				__SCREAMING_SNAKE_CASE	(       self      :							List[Any]   ,				*__magic_name__      :							List[Any]   ,				**__magic_name__      :							List[Any]				):


				"""simple docstring"""

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





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


				"""simple docstring"""

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





	def __setattr__(       self      :							int   ,				__magic_name__      :							Optional[Any]   ,				__magic_name__      :							Union[str, Any]				):


				"""simple docstring"""

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





	def __setitem__(       self      :							List[Any]   ,				__magic_name__      :							List[str]   ,				__magic_name__      :							List[Any]				):


				"""simple docstring"""

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







	def 				__SCREAMING_SNAKE_CASE	(       self      :							Tuple				):


				"""simple docstring"""

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






class  A  (						SCREAMING_SNAKE_CASE__	,   SCREAMING_SNAKE_CASE__     ):





	@classmethod
	def 				__SCREAMING_SNAKE_CASE	(       cls      :							int   ,				__magic_name__      :							Optional[int]				):


				"""simple docstring"""

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






class  A  (						SCREAMING_SNAKE_CASE__     ):
	snake_case__   :int   =  'longest'
	snake_case__   :Optional[Any]   =  'max_length'
	snake_case__   :str   =  'do_not_pad'






class  A  (						SCREAMING_SNAKE_CASE__     ):
	snake_case__   :Any   =  'pt'
	snake_case__   :Union[str, Any]   =  'tf'
	snake_case__   :Any   =  'np'
	snake_case__   :List[str]   =  'jax'






class  A  :





	def __init__(       self      :							Dict   ,				__magic_name__      :							List[ContextManager]				):


				"""simple docstring"""

				lowerCAmelCase__										=				context_managers
				lowerCAmelCase__										=				ExitStack()





	def __enter__(       self      :							str				):


				"""simple docstring"""

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







	def __exit__(       self      :							Dict   ,				*__magic_name__      :							Dict   ,				**__magic_name__      :							int				):


				"""simple docstring"""

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







def 	A  (   UpperCamelCase_       :  Dict   )       ->							List[str]:







			'''simple docstring'''



			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 	A  (   UpperCamelCase_       :  int   )       ->							int:







			'''simple docstring'''



			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 	A  (   UpperCamelCase_       :  MutableMapping    ,						UpperCamelCase_       :  str = ""    ,						UpperCamelCase_       :  str = "."   )       ->							List[Any]:







			'''simple docstring'''



			def _flatten_dict(UpperCamelCase_       :  Dict    ,						UpperCamelCase_       :  Optional[int]=""    ,						UpperCamelCase_       :  Any="."   ):
						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 	A  (   UpperCamelCase_       :  List[Any]    ,						UpperCamelCase_       :  bool = False   )       ->							Any:







			'''simple docstring'''



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







def 	A  (   UpperCamelCase_       :  Optional[int]    ,						UpperCamelCase_       :  Union[str, Any]=None   )       ->							Tuple:







			'''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 	A  (   UpperCamelCase_       :  str    ,						UpperCamelCase_       :  int   )       ->							Dict:







			'''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 	A  (   UpperCamelCase_       :  Union[str, Any]    ,						UpperCamelCase_       :  List[str]=None   )       ->							Optional[int]:







			'''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 	A  (   UpperCamelCase_       :  Optional[int]    ,						UpperCamelCase_       :  Tuple   )       ->							List[Any]:







			'''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 	A  (   UpperCamelCase_       :  List[str]   )       ->							Dict:







			'''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 	A  (   UpperCamelCase_       :  Union[str, Any]    ,						UpperCamelCase_       :  List[str]   )       ->							Dict:







			'''simple docstring'''



			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 	A  (   UpperCamelCase_       :  str   )       ->							Any:







			'''simple docstring'''



			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}."""   )










def 	SCREAMING_SNAKE_CASE_							(	_snake_case	:list				)  ->     bool:
   if not isinstance(_snake_case	,   _snake_case				):
      raise ValueError('''Input series is not valid, valid series - [2, 4, 6]'''				)
   if len(_snake_case				) == 0:
      raise ValueError('''Input list must be a non empty list'''				)
   if len(_snake_case				) == 1:
      return True
   _A      =       series[1] - series[0]
   for index in range(len(_snake_case				) - 1				):
      if series[index + 1] - series[index] != common_diff:
         return False
   return True

def 	SCREAMING_SNAKE_CASE_							(	_snake_case	:list				)  ->     float:
   if not isinstance(_snake_case	,   _snake_case				):
      raise ValueError('''Input series is not valid, valid series - [2, 4, 6]'''				)
   if len(_snake_case				) == 0:
      raise ValueError('''Input list must be a non empty list'''				)
   _A      =       0
   for val in series:
      answer += val
   return answer / len(_snake_case				)


if __name__ == "__main__":
   import doctest

   doctest.testmod()



