






"""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_							(      snake_case_  ):







				def __get__(							self							:						List[str]						,    __lowerCamelCase							:						Any						,    __lowerCamelCase							:						List[Any]=None	)				->					str:
										# See docs.python.org/3/howto/descriptor.html#properties
										if obj is None:
																return self
										if self.fget is None:
																raise AttributeError("unreadable attribute"	)
										__magic_name__            =     "__cached_" + self.fget.__name__
										__magic_name__            =     getattr(__lowerCamelCase						,    __lowerCamelCase						,    __lowerCamelCase	)
										if cached is None:
																__magic_name__            =     self.fget(__lowerCamelCase	)
																setattr(__lowerCamelCase						,    __lowerCamelCase						,    __lowerCamelCase	)
										return cached






def _lowerCAmelCase	(  __lowerCamelCase:int   ):

						'''simple docstring'''






						__magic_name__            =     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	(  __lowerCamelCase:List[Any]   ):

						'''simple docstring'''






						if is_torch_fx_proxy(__lowerCamelCase   ):
												return True
						if is_torch_available():
												import torch

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

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

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

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

						return isinstance(__lowerCamelCase ,						np.ndarray   )






def _lowerCAmelCase	(  __lowerCamelCase:Union[str, Any]   ):

						'''simple docstring'''






						return isinstance(__lowerCamelCase ,						np.ndarray   )






def _lowerCAmelCase	(  __lowerCamelCase:Optional[int]   ):

						'''simple docstring'''






						return _is_numpy(__lowerCamelCase   )






def _lowerCAmelCase	(  __lowerCamelCase:Union[str, Any]   ):

						'''simple docstring'''






						import torch

						return isinstance(__lowerCamelCase ,						torch.Tensor   )






def _lowerCAmelCase	(  __lowerCamelCase:Any   ):

						'''simple docstring'''






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






def _lowerCAmelCase	(  __lowerCamelCase:List[str]   ):

						'''simple docstring'''






						import torch

						return isinstance(__lowerCamelCase ,						torch.device   )






def _lowerCAmelCase	(  __lowerCamelCase:Dict   ):

						'''simple docstring'''






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






def _lowerCAmelCase	(  __lowerCamelCase:int   ):

						'''simple docstring'''






						import torch

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






def _lowerCAmelCase	(  __lowerCamelCase:Optional[int]   ):

						'''simple docstring'''






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






def _lowerCAmelCase	(  __lowerCamelCase:int   ):

						'''simple docstring'''






						import tensorflow as tf

						return isinstance(__lowerCamelCase ,						tf.Tensor   )






def _lowerCAmelCase	(  __lowerCamelCase:Any   ):

						'''simple docstring'''






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






def _lowerCAmelCase	(  __lowerCamelCase:int   ):

						'''simple docstring'''






						import tensorflow as tf

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






def _lowerCAmelCase	(  __lowerCamelCase:Tuple   ):

						'''simple docstring'''






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






def _lowerCAmelCase	(  __lowerCamelCase:str   ):

						'''simple docstring'''






						import jax.numpy as jnp  # noqa: F811

						return isinstance(__lowerCamelCase ,						jnp.ndarray   )






def _lowerCAmelCase	(  __lowerCamelCase:List[str]   ):

						'''simple docstring'''






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






def _lowerCAmelCase	(  __lowerCamelCase:int   ):

						'''simple docstring'''






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






def _lowerCAmelCase	(  __lowerCamelCase:List[Any]   ):

						'''simple docstring'''






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

class 						A_							(      snake_case_  ):







				def     _snake_case					(							self							:						List[str]	)				->					Optional[int]:
										__magic_name__            =     fields(self	)

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

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

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







				def __delitem__(							self							:						Optional[Any]						,    *__lowerCamelCase							:						int						,    **__lowerCamelCase							:						List[str]	)				->					Union[str, Any]:
										raise Exception(f'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'''	)







				def     _snake_case					(							self							:						str						,    *__lowerCamelCase							:						str						,    **__lowerCamelCase							:						Tuple	)				->					List[str]:
										raise Exception(f'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''	)







				def     _snake_case					(							self							:						Tuple						,    *__lowerCamelCase							:						Tuple						,    **__lowerCamelCase							:						Tuple	)				->					List[str]:
										raise Exception(f'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''	)







				def     _snake_case					(							self							:						List[Any]						,    *__lowerCamelCase							:						Any						,    **__lowerCamelCase							:						Optional[int]	)				->					List[Any]:
										raise Exception(f'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''	)







				def __getitem__(							self							:						Optional[int]						,    __lowerCamelCase							:						int	)				->					Dict:
										if isinstance(__lowerCamelCase						,    __lowerCamelCase	):
																__magic_name__            =     dict(self.items()	)
																return inner_dict[k]
										else:
																return self.to_tuple()[k]







				def __setattr__(							self							:						Any						,    __lowerCamelCase							:						Any						,    __lowerCamelCase							:						List[Any]	)				->					Dict:
										if name in self.keys() and value is not None:
																# Don't call self.__setitem__ to avoid recursion errors
																super().__setitem__(__lowerCamelCase						,    __lowerCamelCase	)
										super().__setattr__(__lowerCamelCase						,    __lowerCamelCase	)







				def __setitem__(							self							:						List[str]						,    __lowerCamelCase							:						List[Any]						,    __lowerCamelCase							:						Optional[Any]	)				->					Tuple:
										# Will raise a KeyException if needed
										super().__setitem__(__lowerCamelCase						,    __lowerCamelCase	)
										# Don't call self.__setattr__ to avoid recursion errors
										super().__setattr__(__lowerCamelCase						,    __lowerCamelCase	)







				def     _snake_case					(							self							:						int	)				->					Tuple[Any]:
										return tuple(self[k] for k in self.keys()	)





class 						A_							(      snake_case_					,							snake_case_  ):







				@classmethod
				def     _snake_case					(							cls							:						Dict						,    __lowerCamelCase							:						List[Any]	)				->					str:
										raise ValueError(
										    f'''{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()	)}'''	)





class 						A_							(      snake_case_  ):
				UpperCAmelCase__        =				'''longest'''
				UpperCAmelCase__        =				'''max_length'''
				UpperCAmelCase__        =				'''do_not_pad'''





class 						A_							(      snake_case_  ):
				UpperCAmelCase__        =				'''pt'''
				UpperCAmelCase__        =				'''tf'''
				UpperCAmelCase__        =				'''np'''
				UpperCAmelCase__        =				'''jax'''





class 						A_							:







				def __init__(							self							:						Optional[Any]						,    __lowerCamelCase							:						List[ContextManager]	)				->					str:
										__magic_name__            =     context_managers
										__magic_name__            =     ExitStack()







				def __enter__(							self							:						List[str]	)				->					Optional[Any]:
										for context_manager in self.context_managers:
																self.stack.enter_context(__lowerCamelCase	)







				def __exit__(							self							:						Union[str, Any]						,    *__lowerCamelCase							:						List[Any]						,    **__lowerCamelCase							:						Any	)				->					int:
										self.stack.__exit__(*__lowerCamelCase						,    **__lowerCamelCase	)






def _lowerCAmelCase	(  __lowerCamelCase:Union[str, Any]   ):

						'''simple docstring'''






						__magic_name__            =     infer_framework(__lowerCamelCase   )
						if framework == "tf":
												__magic_name__            =     inspect.signature(model_class.call   )  # TensorFlow models
						elif framework == "pt":
												__magic_name__            =     inspect.signature(model_class.forward   )  # PyTorch models
						else:
												__magic_name__            =     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	(  __lowerCamelCase:Dict   ):

						'''simple docstring'''






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

						'''simple docstring'''






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

						return dict(_flatten_dict(__lowerCamelCase ,						__lowerCamelCase ,						__lowerCamelCase   )   )






@contextmanager
def _lowerCAmelCase	(  __lowerCamelCase:Dict ,						__lowerCamelCase:bool = False   ):

						'''simple docstring'''






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






def _lowerCAmelCase	(  __lowerCamelCase:str ,						__lowerCamelCase:Tuple=None   ):

						'''simple docstring'''






						if is_numpy_array(__lowerCamelCase   ):
												return np.transpose(__lowerCamelCase ,						axes=__lowerCamelCase   )
						elif is_torch_tensor(__lowerCamelCase   ):
												return array.T if axes is None else array.permute(*__lowerCamelCase   )
						elif is_tf_tensor(__lowerCamelCase   ):
												import tensorflow as tf

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






def _lowerCAmelCase	(  __lowerCamelCase:int ,						__lowerCamelCase:Any   ):

						'''simple docstring'''






						if is_numpy_array(__lowerCamelCase   ):
												return np.reshape(__lowerCamelCase ,						__lowerCamelCase   )
						elif is_torch_tensor(__lowerCamelCase   ):
												return array.reshape(*__lowerCamelCase   )
						elif is_tf_tensor(__lowerCamelCase   ):
												import tensorflow as tf

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






def _lowerCAmelCase	(  __lowerCamelCase:int ,						__lowerCamelCase:str=None   ):

						'''simple docstring'''






						if is_numpy_array(__lowerCamelCase   ):
												return np.squeeze(__lowerCamelCase ,						axis=__lowerCamelCase   )
						elif is_torch_tensor(__lowerCamelCase   ):
												return array.squeeze() if axis is None else array.squeeze(dim=__lowerCamelCase   )
						elif is_tf_tensor(__lowerCamelCase   ):
												import tensorflow as tf

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






def _lowerCAmelCase	(  __lowerCamelCase:str ,						__lowerCamelCase:Tuple   ):

						'''simple docstring'''






						if is_numpy_array(__lowerCamelCase   ):
												return np.expand_dims(__lowerCamelCase ,						__lowerCamelCase   )
						elif is_torch_tensor(__lowerCamelCase   ):
												return array.unsqueeze(dim=__lowerCamelCase   )
						elif is_tf_tensor(__lowerCamelCase   ):
												import tensorflow as tf

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






def _lowerCAmelCase	(  __lowerCamelCase:List[Any]   ):

						'''simple docstring'''






						if is_numpy_array(__lowerCamelCase   ):
												return np.size(__lowerCamelCase   )
						elif is_torch_tensor(__lowerCamelCase   ):
												return array.numel()
						elif is_tf_tensor(__lowerCamelCase   ):
												import tensorflow as tf

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






def _lowerCAmelCase	(  __lowerCamelCase:List[str] ,						__lowerCamelCase:int   ):

						'''simple docstring'''






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

						return auto_map






def _lowerCAmelCase	(  __lowerCamelCase:List[Any]   ):

						'''simple docstring'''






						for base_class in inspect.getmro(__lowerCamelCase   ):
												__magic_name__            =     base_class.__module__
												__magic_name__            =     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	(  __lowerCamelCase:int   ):

						'''simple docstring'''






						if number < 0:
												raise ValueError("number must not be negative"   )
						return number & (number - 1) == 0


if __name__ == "__main__":
			import doctest

			doctest.testmod()



