


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     _lowercase				(							lowercase__):


							"""simple docstring"""




							def __get__(     self							:    Union[str, Any]      ,   __lowerCamelCase							:    List[str]      ,   __lowerCamelCase							:    Any=None ):


													'''simple docstring'''



													if obj is None:
																			return self
													if self.fget is None:
																			raise AttributeError("unreadable attribute" )
													lowerCamelCase__	:       Optional[int]					=						"__cached_" + self.fget.__name__
													lowerCamelCase__	:       Optional[Any]					=						getattr(__lowerCamelCase      ,   __lowerCamelCase      ,   __lowerCamelCase )
													if cached is None:
																			lowerCamelCase__	:       List[Any]					=						self.fget(__lowerCamelCase )
																			setattr(__lowerCamelCase      ,   __lowerCamelCase      ,   __lowerCamelCase )
													return cached



def    lowercase_	(	_A    :					List[str]		):

						"""simple docstring"""




						lowerCamelCase__	:       List[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    lowercase_	(	_A    :					str		):

						"""simple docstring"""




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

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

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

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

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

						return isinstance(_A					,      np.ndarray		)

def    lowercase_	(	_A    :					int		):

						"""simple docstring"""




						return isinstance(_A					,      np.ndarray		)

def    lowercase_	(	_A    :					Dict		):

						"""simple docstring"""




						return _is_numpy(_A		)

def    lowercase_	(	_A    :					List[str]		):

						"""simple docstring"""




						import torch

						return isinstance(_A					,      torch.Tensor		)

def    lowercase_	(	_A    :					Any		):

						"""simple docstring"""




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

def    lowercase_	(	_A    :					str		):

						"""simple docstring"""




						import torch

						return isinstance(_A					,      torch.device		)

def    lowercase_	(	_A    :					Any		):

						"""simple docstring"""




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

def    lowercase_	(	_A    :					int		):

						"""simple docstring"""




						import torch

						if isinstance(_A					,      _A		):
												if hasattr(_A					,      _A		):
																		lowerCamelCase__	:       List[Any]					=						getattr(_A					,      _A		)
												else:
																		return False
						return isinstance(_A					,      torch.dtype		)

def    lowercase_	(	_A    :					Tuple		):

						"""simple docstring"""




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

def    lowercase_	(	_A    :					str		):

						"""simple docstring"""




						import tensorflow as tf

						return isinstance(_A					,      tf.Tensor		)

def    lowercase_	(	_A    :					Union[str, Any]		):

						"""simple docstring"""




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

def    lowercase_	(	_A    :					Dict		):

						"""simple docstring"""




						import tensorflow as tf

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

def    lowercase_	(	_A    :					Optional[Any]		):

						"""simple docstring"""




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

def    lowercase_	(	_A    :					Optional[int]		):

						"""simple docstring"""




						import jax.numpy as jnp  # noqa: F811

						return isinstance(_A					,      jnp.ndarray		)

def    lowercase_	(	_A    :					List[Any]		):

						"""simple docstring"""




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

def    lowercase_	(	_A    :					Any		):

						"""simple docstring"""




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

def    lowercase_	(	_A    :					List[Any]		):

						"""simple docstring"""




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







class     _lowercase				(							lowercase__):


							"""simple docstring"""




							def 		lowerCAmelCase  (     self							:    Tuple ):


													'''simple docstring'''



													lowerCamelCase__	:       Optional[int]					=						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." )

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





							def __delitem__(     self							:    Tuple      ,   *__lowerCamelCase							:    str      ,   **__lowerCamelCase							:    Union[str, Any] ):


													'''simple docstring'''



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





							def 		lowerCAmelCase  (     self							:    Optional[int]      ,   *__lowerCamelCase							:    Tuple      ,   **__lowerCamelCase							:    Optional[int] ):


													'''simple docstring'''



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





							def 		lowerCAmelCase  (     self							:    Optional[int]      ,   *__lowerCamelCase							:    Any      ,   **__lowerCamelCase							:    int ):


													'''simple docstring'''



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





							def 		lowerCAmelCase  (     self							:    str      ,   *__lowerCamelCase							:    Union[str, Any]      ,   **__lowerCamelCase							:    str ):


													'''simple docstring'''



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





							def __getitem__(     self							:    int      ,   __lowerCamelCase							:    Any ):


													'''simple docstring'''



													if isinstance(__lowerCamelCase      ,   __lowerCamelCase ):
																			lowerCamelCase__	:       List[str]					=						dict(self.items() )
																			return inner_dict[k]
													else:
																			return self.to_tuple()[k]





							def __setattr__(     self							:    List[str]      ,   __lowerCamelCase							:    Tuple      ,   __lowerCamelCase							:    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__(__lowerCamelCase      ,   __lowerCamelCase )
													super().__setattr__(__lowerCamelCase      ,   __lowerCamelCase )





							def __setitem__(     self							:    Tuple      ,   __lowerCamelCase							:    Tuple      ,   __lowerCamelCase							:    List[str] ):


													'''simple docstring'''



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





							def 		lowerCAmelCase  (     self							:    str ):


													'''simple docstring'''



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







class     _lowercase				(							lowercase__							,						lowercase__):


							"""simple docstring"""




							@classmethod
							def 		lowerCAmelCase  (     cls							:    List[Any]      ,   __lowerCamelCase							:    List[str] ):


													'''simple docstring'''



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







class     _lowercase				(							lowercase__):


							"""simple docstring"""




							A__      		=    "longest"
							A__      		=    "max_length"
							A__      		=    "do_not_pad"







class     _lowercase				(							lowercase__):


							"""simple docstring"""




							A__      		=    "pt"
							A__      		=    "tf"
							A__      		=    "np"
							A__      		=    "jax"







class     _lowercase				:


							"""simple docstring"""




							def __init__(     self							:    Tuple      ,   __lowerCamelCase							:    List[ContextManager] ):


													'''simple docstring'''



													lowerCamelCase__	:       Optional[int]					=						context_managers
													lowerCamelCase__	:       Dict					=						ExitStack()





							def __enter__(     self							:    Dict ):


													'''simple docstring'''



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





							def __exit__(     self							:    List[str]      ,   *__lowerCamelCase							:    Any      ,   **__lowerCamelCase							:    int ):


													'''simple docstring'''



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



def    lowercase_	(	_A    :					List[Any]		):

						"""simple docstring"""




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

						"""simple docstring"""




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

						"""simple docstring"""




						def _flatten_dict(_A    :					Optional[int]					,      _A    :					Any=""					,      _A    :					Any="."		):
												for k, v in d.items():
																		lowerCamelCase__	:       List[str]					=						str(_A		) + delimiter + str(_A		) if parent_key else k
																		if v and isinstance(_A					,      _A		):
																								yield from flatten_dict(_A					,      _A					,      delimiter=_A		).items()
																		else:
																								yield key, v

						return dict(_flatten_dict(_A					,      _A					,      _A		)		)

@contextmanager
def    lowercase_	(	_A    :					Dict					,      _A    :					bool = False		):

						"""simple docstring"""




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

def    lowercase_	(	_A    :					Optional[int]					,      _A    :					Optional[int]=None		):

						"""simple docstring"""




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

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

def    lowercase_	(	_A    :					Any					,      _A    :					Any		):

						"""simple docstring"""




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

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

def    lowercase_	(	_A    :					Dict					,      _A    :					int=None		):

						"""simple docstring"""




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

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

def    lowercase_	(	_A    :					Any					,      _A    :					Union[str, Any]		):

						"""simple docstring"""




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

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

def    lowercase_	(	_A    :					int		):

						"""simple docstring"""




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

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

def    lowercase_	(	_A    :					Tuple					,      _A    :					Tuple		):

						"""simple docstring"""




						for key, value in auto_map.items():
												if isinstance(_A					,      (tuple, list)		):
																		lowerCamelCase__	:       Optional[Any]					=						[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__	:       Tuple					=						F"{repo_id}--{value}"

						return auto_map


def    lowercase_	(	_A    :					Dict		):

						"""simple docstring"""




						for base_class in inspect.getmro(_A		):
												lowerCamelCase__	:       Optional[int]					=						base_class.__module__
												lowerCamelCase__	:       List[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}."		)






def    lowercase_	(	_A    :					int					,      _A    :					int		):

      """simple docstring"""




      if a < 0 or b < 0:
            raise ValueError("the value of both inputs must be positive"		)

      lowerCamelCase__	:       List[str]					=						str(bin(_A		)		)[2:]  # remove the leading "0b"
      lowerCamelCase__	:       List[Any]					=						str(bin(_A		)		)[2:]  # remove the leading "0b"

      lowerCamelCase__	:       List[Any]					=						max(len(_A		)					,      len(_A		)		)

      return "0b" + "".join(
          str(int(char_a != char_b		)		)
          for char_a, char_b in zip(a_binary.zfill(_A		)					,      b_binary.zfill(_A		)		)		)


if __name__ == "__main__":
    import doctest

    doctest.testmod()


