




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




							'''simple docstring'''



							def __get__(					self       :	List[str]       ,     a       :	str       ,     a       :	Tuple=None			)			->					List[Any]:
										# See docs.python.org/3/howto/descriptor.html#properties
										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(a       ,     a       ,     a			)
										if cached is None:
													SCREAMING_SNAKE_CASE           =					self.fget(a			)
													setattr(a       ,     a       ,     a			)
										return cached





def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''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_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			if is_torch_fx_proxy(SCREAMING_SNAKE_CASE   ):
						return True
			if is_torch_available():
						import torch

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

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

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

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

			return isinstance(SCREAMING_SNAKE_CASE					,	np.ndarray   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			return isinstance(SCREAMING_SNAKE_CASE					,	np.ndarray   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			return _is_numpy(SCREAMING_SNAKE_CASE   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			import torch

			return isinstance(SCREAMING_SNAKE_CASE					,	torch.Tensor   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			return False if not is_torch_available() else _is_torch(SCREAMING_SNAKE_CASE   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			import torch

			return isinstance(SCREAMING_SNAKE_CASE					,	torch.device   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			return False if not is_torch_available() else _is_torch_device(SCREAMING_SNAKE_CASE   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			import torch

			if isinstance(SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   ):
						if hasattr(SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   ):
									SCREAMING_SNAKE_CASE           =					getattr(SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   )
						else:
									return False
			return isinstance(SCREAMING_SNAKE_CASE					,	torch.dtype   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			return False if not is_torch_available() else _is_torch_dtype(SCREAMING_SNAKE_CASE   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			import tensorflow as tf

			return isinstance(SCREAMING_SNAKE_CASE					,	tf.Tensor   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			return False if not is_tf_available() else _is_tensorflow(SCREAMING_SNAKE_CASE   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			import tensorflow as tf

			# the `is_symbolic_tensor` predicate is only available starting with TF 2.14
			if hasattr(SCREAMING_SNAKE_CASE					,	"""is_symbolic_tensor"""   ):
						return tf.is_symbolic_tensor(SCREAMING_SNAKE_CASE   )
			return type(SCREAMING_SNAKE_CASE   ) == tf.Tensor
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			return False if not is_tf_available() else _is_tf_symbolic_tensor(SCREAMING_SNAKE_CASE   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			import jax.numpy as jnp  # noqa: F811

			return isinstance(SCREAMING_SNAKE_CASE					,	jnp.ndarray   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			return False if not is_flax_available() else _is_jax(SCREAMING_SNAKE_CASE   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			if isinstance(SCREAMING_SNAKE_CASE					,	(dict, UserDict)   ):
						return {k: to_py_obj(SCREAMING_SNAKE_CASE   ) for k, v in obj.items()}
			elif isinstance(SCREAMING_SNAKE_CASE					,	(list, tuple)   ):
						return [to_py_obj(SCREAMING_SNAKE_CASE   ) for o in obj]
			elif is_tf_tensor(SCREAMING_SNAKE_CASE   ):
						return obj.numpy().tolist()
			elif is_torch_tensor(SCREAMING_SNAKE_CASE   ):
						return obj.detach().cpu().tolist()
			elif is_jax_tensor(SCREAMING_SNAKE_CASE   ):
						return np.asarray(SCREAMING_SNAKE_CASE   ).tolist()
			elif isinstance(SCREAMING_SNAKE_CASE					,	(np.ndarray, np.number)   ):  # tolist also works on 0d np arrays
						return obj.tolist()
			else:
						return obj
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			if isinstance(SCREAMING_SNAKE_CASE					,	(dict, UserDict)   ):
						return {k: to_numpy(SCREAMING_SNAKE_CASE   ) for k, v in obj.items()}
			elif isinstance(SCREAMING_SNAKE_CASE					,	(list, tuple)   ):
						return np.array(SCREAMING_SNAKE_CASE   )
			elif is_tf_tensor(SCREAMING_SNAKE_CASE   ):
						return obj.numpy()
			elif is_torch_tensor(SCREAMING_SNAKE_CASE   ):
						return obj.detach().cpu().numpy()
			elif is_jax_tensor(SCREAMING_SNAKE_CASE   ):
						return np.asarray(SCREAMING_SNAKE_CASE   )
			else:
						return obj




class 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							def    _UpperCAmelCase     (					self       :	Tuple			)			->					int:
										SCREAMING_SNAKE_CASE           =					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."""			)

										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(a			):
													if isinstance(a       ,     a			):
																SCREAMING_SNAKE_CASE           =					first_field.items()
																SCREAMING_SNAKE_CASE           =					True
													else:
																try:
																			SCREAMING_SNAKE_CASE           =					iter(a			)
																			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(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
																									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       :	Optional[int]       ,     *a       :	Union[str, Any]       ,     **a       :	Dict			)			->					Any:
										raise Exception(f"""You cannot use ``__delitem__`` on a {self.__class__.__name__} instance."""			)





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





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





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





							def __getitem__(					self       :	List[Any]       ,     a       :	Dict			)			->					Any:
										if isinstance(a       ,     a			):
													SCREAMING_SNAKE_CASE           =					dict(self.items()			)
													return inner_dict[k]
										else:
													return self.to_tuple()[k]





							def __setattr__(					self       :	List[str]       ,     a       :	Optional[Any]       ,     a       :	Union[str, Any]			)			->					Any:
										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       :	Optional[int]       ,     a       :	str       ,     a       :	str			)			->					List[str]:
										# Will raise a KeyException if needed
										super().__setitem__(a       ,     a			)
										# Don't call self.__setattr__ to avoid recursion errors
										super().__setattr__(a       ,     a			)







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





class 			UpperCAmelCase_      (   A		,      A       ):




							'''simple docstring'''



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





class 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							a__						  =     '''longest'''
							a__						  =     '''max_length'''
							a__						  =     '''do_not_pad'''





class 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							a__						  =     '''pt'''
							a__						  =     '''tf'''
							a__						  =     '''np'''
							a__						  =     '''jax'''





class 			UpperCAmelCase_      :




							'''simple docstring'''



							def __init__(					self       :	Optional[int]       ,     a       :	List[ContextManager]			)			->					Any:
										SCREAMING_SNAKE_CASE           =					context_managers
										SCREAMING_SNAKE_CASE           =					ExitStack()





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







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





def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			SCREAMING_SNAKE_CASE           =					infer_framework(SCREAMING_SNAKE_CASE   )
			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_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			SCREAMING_SNAKE_CASE           =					model_class.__name__
			SCREAMING_SNAKE_CASE           =					infer_framework(SCREAMING_SNAKE_CASE   )
			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_    (    SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE = ""					,	SCREAMING_SNAKE_CASE = "."   ):
			'''simple docstring'''

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

			return dict(_flatten_dict(SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   )   )
@contextmanager
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE = False   ):
			'''simple docstring'''
			if use_temp_dir:
						with tempfile.TemporaryDirectory() as tmp_dir:
									yield tmp_dir
			else:
						yield working_dir
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE=None   ):
			'''simple docstring'''
			if is_numpy_array(SCREAMING_SNAKE_CASE   ):
						return np.transpose(SCREAMING_SNAKE_CASE					,	axes=SCREAMING_SNAKE_CASE   )
			elif is_torch_tensor(SCREAMING_SNAKE_CASE   ):
						return array.T if axes is None else array.permute(*SCREAMING_SNAKE_CASE   )
			elif is_tf_tensor(SCREAMING_SNAKE_CASE   ):
						import tensorflow as tf

						return tf.transpose(SCREAMING_SNAKE_CASE					,	perm=SCREAMING_SNAKE_CASE   )
			elif is_jax_tensor(SCREAMING_SNAKE_CASE   ):
						return jnp.transpose(SCREAMING_SNAKE_CASE					,	axes=SCREAMING_SNAKE_CASE   )
			else:
						raise ValueError(f"""Type not supported for transpose: {type(SCREAMING_SNAKE_CASE   )}."""   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			if is_numpy_array(SCREAMING_SNAKE_CASE   ):
						return np.reshape(SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   )
			elif is_torch_tensor(SCREAMING_SNAKE_CASE   ):
						return array.reshape(*SCREAMING_SNAKE_CASE   )
			elif is_tf_tensor(SCREAMING_SNAKE_CASE   ):
						import tensorflow as tf

						return tf.reshape(SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   )
			elif is_jax_tensor(SCREAMING_SNAKE_CASE   ):
						return jnp.reshape(SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   )
			else:
						raise ValueError(f"""Type not supported for reshape: {type(SCREAMING_SNAKE_CASE   )}."""   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE=None   ):
			'''simple docstring'''
			if is_numpy_array(SCREAMING_SNAKE_CASE   ):
						return np.squeeze(SCREAMING_SNAKE_CASE					,	axis=SCREAMING_SNAKE_CASE   )
			elif is_torch_tensor(SCREAMING_SNAKE_CASE   ):
						return array.squeeze() if axis is None else array.squeeze(dim=SCREAMING_SNAKE_CASE   )
			elif is_tf_tensor(SCREAMING_SNAKE_CASE   ):
						import tensorflow as tf

						return tf.squeeze(SCREAMING_SNAKE_CASE					,	axis=SCREAMING_SNAKE_CASE   )
			elif is_jax_tensor(SCREAMING_SNAKE_CASE   ):
						return jnp.squeeze(SCREAMING_SNAKE_CASE					,	axis=SCREAMING_SNAKE_CASE   )
			else:
						raise ValueError(f"""Type not supported for squeeze: {type(SCREAMING_SNAKE_CASE   )}."""   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			if is_numpy_array(SCREAMING_SNAKE_CASE   ):
						return np.expand_dims(SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   )
			elif is_torch_tensor(SCREAMING_SNAKE_CASE   ):
						return array.unsqueeze(dim=SCREAMING_SNAKE_CASE   )
			elif is_tf_tensor(SCREAMING_SNAKE_CASE   ):
						import tensorflow as tf

						return tf.expand_dims(SCREAMING_SNAKE_CASE					,	axis=SCREAMING_SNAKE_CASE   )
			elif is_jax_tensor(SCREAMING_SNAKE_CASE   ):
						return jnp.expand_dims(SCREAMING_SNAKE_CASE					,	axis=SCREAMING_SNAKE_CASE   )
			else:
						raise ValueError(f"""Type not supported for expand_dims: {type(SCREAMING_SNAKE_CASE   )}."""   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			if is_numpy_array(SCREAMING_SNAKE_CASE   ):
						return np.size(SCREAMING_SNAKE_CASE   )
			elif is_torch_tensor(SCREAMING_SNAKE_CASE   ):
						return array.numel()
			elif is_tf_tensor(SCREAMING_SNAKE_CASE   ):
						import tensorflow as tf

						return tf.size(SCREAMING_SNAKE_CASE   )
			elif is_jax_tensor(SCREAMING_SNAKE_CASE   ):
						return array.size
			else:
						raise ValueError(f"""Type not supported for expand_dims: {type(SCREAMING_SNAKE_CASE   )}."""   )
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			for key, value in auto_map.items():
						if isinstance(SCREAMING_SNAKE_CASE					,	(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_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			for base_class in inspect.getmro(SCREAMING_SNAKE_CASE   ):
						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}."""   )












def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			if not all(char in """01""" for char in bin_string   ):
						raise ValueError("""Non-binary value was passed to the function"""   )
			if not bin_string:
						raise ValueError("""Empty string was passed to the function"""   )
			SCREAMING_SNAKE_CASE           =					""""""
			while len(SCREAMING_SNAKE_CASE   ) % 3 != 0:
						SCREAMING_SNAKE_CASE           =					"""0""" + bin_string
			SCREAMING_SNAKE_CASE           =					[
			    bin_string[index : index + 3]
			    for index in range(len(SCREAMING_SNAKE_CASE   )   )
			    if index % 3 == 0
			]
			for bin_group in bin_string_in_3_list:
						SCREAMING_SNAKE_CASE           =					0
						for index, val in enumerate(SCREAMING_SNAKE_CASE   ):
									oct_val += int(2 ** (2 - index) * int(SCREAMING_SNAKE_CASE   )   )
						oct_string += str(SCREAMING_SNAKE_CASE   )
			return oct_string


if __name__ == "__main__":
		from doctest import testmod

		testmod()






