



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







	"""simple docstring"""






	def __get__(		self    :  Optional[int]	,    __snake_case    :  Any	,    __snake_case    :  int=None	)    ->	int:






								if obj is None:
															return self
								if self.fget is None:
															raise AttributeError('''unreadable attribute'''	)
								UpperCAmelCase				: List[Any]											=	'__cached_' + self.fget.__name__
								UpperCAmelCase				: Tuple											=	getattr(__a	,    __a	,    __a	)
								if cached is None:
															UpperCAmelCase				: List[Any]											=	self.fget(__a	)
															setattr(__a	,    __a	,    __a	)
								return cached


def 				snake_case_  (      _lowerCAmelCase						:		Optional[int]						)   ->     Optional[int]:
							UpperCAmelCase				: Dict											=	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 				snake_case_  (      _lowerCAmelCase						:		str						)   ->     Union[str, Any]:
							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 				snake_case_  (      _lowerCAmelCase						:		Union[str, Any]						)   ->     Dict:
							return isinstance(_lowerCAmelCase     ,   np.ndarray						)


def 				snake_case_  (      _lowerCAmelCase						:		str						)   ->     Any:
							return _is_numpy(_lowerCAmelCase						)


def 				snake_case_  (      _lowerCAmelCase						:		Optional[Any]						)   ->     Tuple:
							import torch

							return isinstance(_lowerCAmelCase     ,   torch.Tensor						)


def 				snake_case_  (      _lowerCAmelCase						:		Dict						)   ->     Union[str, Any]:
							return False if not is_torch_available() else _is_torch(_lowerCAmelCase						)


def 				snake_case_  (      _lowerCAmelCase						:		Any						)   ->     str:
							import torch

							return isinstance(_lowerCAmelCase     ,   torch.device						)


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


def 				snake_case_  (      _lowerCAmelCase						:		Optional[Any]						)   ->     Any:
							import torch

							if isinstance(_lowerCAmelCase     ,   _lowerCAmelCase						):
														if hasattr(_lowerCAmelCase     ,   _lowerCAmelCase						):
																					UpperCAmelCase				: List[str]											=	getattr(_lowerCAmelCase     ,   _lowerCAmelCase						)
														else:
																					return False
							return isinstance(_lowerCAmelCase     ,   torch.dtype						)


def 				snake_case_  (      _lowerCAmelCase						:		Optional[Any]						)   ->     List[str]:
							return False if not is_torch_available() else _is_torch_dtype(_lowerCAmelCase						)


def 				snake_case_  (      _lowerCAmelCase						:		Dict						)   ->     Any:
							import tensorflow as tf

							return isinstance(_lowerCAmelCase     ,   tf.Tensor						)


def 				snake_case_  (      _lowerCAmelCase						:		Dict						)   ->     Optional[int]:
							return False if not is_tf_available() else _is_tensorflow(_lowerCAmelCase						)


def 				snake_case_  (      _lowerCAmelCase						:		Tuple						)   ->     int:
							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 				snake_case_  (      _lowerCAmelCase						:		List[str]						)   ->     Dict:
							return False if not is_tf_available() else _is_tf_symbolic_tensor(_lowerCAmelCase						)


def 				snake_case_  (      _lowerCAmelCase						:		List[str]						)   ->     Any:
							import jax.numpy as jnp  # noqa: F811

							return isinstance(_lowerCAmelCase     ,   jnp.ndarray						)


def 				snake_case_  (      _lowerCAmelCase						:		Optional[Any]						)   ->     Union[str, Any]:
							return False if not is_flax_available() else _is_jax(_lowerCAmelCase						)


def 				snake_case_  (      _lowerCAmelCase						:		List[Any]						)   ->     Union[str, Any]:
							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 				snake_case_  (      _lowerCAmelCase						:		List[str]						)   ->     Any:
							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        SCREAMING_SNAKE_CASE(							UpperCamelCase_    ):







	"""simple docstring"""






	def   A			(		self    :  int	)    ->	Optional[Any]:
								UpperCAmelCase				: Dict											=	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."""	)

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







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







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







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







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







	def __getitem__(		self    :  Dict	,    __snake_case    :  int	)    ->	Optional[Any]:






								if isinstance(__a	,    __a	):
															UpperCAmelCase				: Tuple											=	dict(self.items()	)
															return inner_dict[k]
								else:
															return self.to_tuple()[k]







	def __setattr__(		self    :  Union[str, Any]	,    __snake_case    :  str	,    __snake_case    :  Tuple	)    ->	Optional[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    :  Union[str, Any]	,    __snake_case    :  Optional[int]	,    __snake_case    :  str	)    ->	Dict:
								super().__setitem__(__a	,    __a	)
								# Don't call self.__setattr__ to avoid recursion errors
								super().__setattr__(__a	,    __a	)







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

class        SCREAMING_SNAKE_CASE(							UpperCamelCase_							,	UpperCamelCase_    ):







	"""simple docstring"""






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

class        SCREAMING_SNAKE_CASE(							UpperCamelCase_    ):







	"""simple docstring"""






	lowerCamelCase__    				= """longest"""
	lowerCamelCase__    				= """max_length"""
	lowerCamelCase__    				= """do_not_pad"""

class        SCREAMING_SNAKE_CASE(							UpperCamelCase_    ):







	"""simple docstring"""






	lowerCamelCase__    				= """pt"""
	lowerCamelCase__    				= """tf"""
	lowerCamelCase__    				= """np"""
	lowerCamelCase__    				= """jax"""

class        SCREAMING_SNAKE_CASE:







	"""simple docstring"""






	def __init__(		self    :  Optional[int]	,    __snake_case    :  Any	)    ->	Union[str, Any]:
								UpperCAmelCase				: Union[str, Any]											=	context_managers
								UpperCAmelCase				: Tuple											=	ExitStack()







	def __enter__(		self    :  int	)    ->	Any:






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







	def __exit__(		self    :  str	,    *__snake_case    :  Optional[int]	,    **__snake_case    :  str	)    ->	int:
								self.stack.__exit__(*__a	,    **__a	)


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

							def _flatten_dict(_lowerCAmelCase						:		int     ,   _lowerCAmelCase						:		Union[str, Any]=""     ,   _lowerCAmelCase						:		List[str]="."						):
														for k, v in d.items():
																					UpperCAmelCase				: Dict											=	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 				snake_case_  (      _lowerCAmelCase						:		Optional[int]     ,   _lowerCAmelCase						:		bool = False						)   ->     Union[str, Any]:
							if use_temp_dir:
														with tempfile.TemporaryDirectory() as tmp_dir:
																					yield tmp_dir
							else:
														yield working_dir


def 				snake_case_  (      _lowerCAmelCase						:		Dict     ,   _lowerCAmelCase						:		Optional[int]=None						)   ->     List[Any]:
							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 				snake_case_  (      _lowerCAmelCase						:		str     ,   _lowerCAmelCase						:		List[Any]						)   ->     List[str]:
							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 				snake_case_  (      _lowerCAmelCase						:		Any     ,   _lowerCAmelCase						:		List[Any]=None						)   ->     Union[str, Any]:
							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 				snake_case_  (      _lowerCAmelCase						:		Dict     ,   _lowerCAmelCase						:		Optional[int]						)   ->     int:
							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 				snake_case_  (      _lowerCAmelCase						:		List[Any]						)   ->     Optional[int]:
							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 				snake_case_  (      _lowerCAmelCase						:		int     ,   _lowerCAmelCase						:		Dict						)   ->     Optional[Any]:
							for key, value in auto_map.items():
														if isinstance(_lowerCAmelCase     ,   (tuple, list)						):
																					UpperCAmelCase				: 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:
																					UpperCAmelCase				: Union[str, Any]											=	f"""{repo_id}--{value}"""

							return auto_map




def 				snake_case_  (      _lowerCAmelCase						:		Optional[Any]						)   ->     Tuple:
							for base_class in inspect.getmro(_lowerCAmelCase						):
														UpperCAmelCase				: Union[str, Any]											=	base_class.__module__
														UpperCAmelCase				: str											=	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'''






import warnings

from ...utils import logging
from .image_processing_beit import BeitImageProcessor


UpperCamelCase__:     Dict										=    logging.get_logger(__name__)

class        SCREAMING_SNAKE_CASE(							A__    ):







	"""simple docstring"""






	def __init__(		self    :  Optional[Any]	,    *__snake_case    :  List[str]	,    **__snake_case    :  str	)    ->	None:
								warnings.warn(
								    '''The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'''
								    ''' use BeitImageProcessor instead.'''	,    __snake_case	,    )
								super().__init__(*__snake_case	,    **__snake_case	)





