


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




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







def       _UpperCamelCase (						UpperCamelCase__   ):
			UpperCAmelCase__					:   Optional[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       _UpperCamelCase (						UpperCamelCase__   ):
			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       _UpperCamelCase (						UpperCamelCase__   ):
			return isinstance(UpperCamelCase__	, np.ndarray   )







def       _UpperCamelCase (						UpperCamelCase__   ):
			return _is_numpy(UpperCamelCase__   )







def       _UpperCamelCase (						UpperCamelCase__   ):
			import torch

			return isinstance(UpperCamelCase__	, torch.Tensor   )







def       _UpperCamelCase (						UpperCamelCase__   ):
			return False if not is_torch_available() else _is_torch(UpperCamelCase__   )







def       _UpperCamelCase (						UpperCamelCase__   ):
			import torch

			return isinstance(UpperCamelCase__	, torch.device   )







def       _UpperCamelCase (						UpperCamelCase__   ):
			return False if not is_torch_available() else _is_torch_device(UpperCamelCase__   )







def       _UpperCamelCase (						UpperCamelCase__   ):
			import torch

			if isinstance(UpperCamelCase__	, UpperCamelCase__   ):
						if hasattr(UpperCamelCase__	, UpperCamelCase__   ):
									UpperCAmelCase__					:   Union[str, Any]       				=       getattr(UpperCamelCase__	, UpperCamelCase__   )
						else:
									return False
			return isinstance(UpperCamelCase__	, torch.dtype   )







def       _UpperCamelCase (						UpperCamelCase__   ):
			return False if not is_torch_available() else _is_torch_dtype(UpperCamelCase__   )







def       _UpperCamelCase (						UpperCamelCase__   ):
			import tensorflow as tf

			return isinstance(UpperCamelCase__	, tf.Tensor   )







def       _UpperCamelCase (						UpperCamelCase__   ):
			return False if not is_tf_available() else _is_tensorflow(UpperCamelCase__   )







def       _UpperCamelCase (						UpperCamelCase__   ):
			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       _UpperCamelCase (						UpperCamelCase__   ):
			return False if not is_tf_available() else _is_tf_symbolic_tensor(UpperCamelCase__   )







def       _UpperCamelCase (						UpperCamelCase__   ):
			import jax.numpy as jnp  # noqa: F811

			return isinstance(UpperCamelCase__	, jnp.ndarray   )







def       _UpperCamelCase (						UpperCamelCase__   ):
			return False if not is_flax_available() else _is_jax(UpperCamelCase__   )







def       _UpperCamelCase (						UpperCamelCase__   ):
			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       _UpperCamelCase (						UpperCamelCase__   ):
			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 						_snake_case   (       a__		):




					def 			snake_case__  ( self):
								UpperCAmelCase__					:   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.''')

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




					def __delitem__( self							,							*_lowerCamelCase							,							**_lowerCamelCase):
								raise Exception(f'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.''')




					def 			snake_case__  ( self							,							*_lowerCamelCase							,							**_lowerCamelCase):
								raise Exception(f'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.''')




					def 			snake_case__  ( self							,							*_lowerCamelCase							,							**_lowerCamelCase):
								raise Exception(f'''You cannot use ``pop`` on a {self.__class__.__name__} instance.''')




					def 			snake_case__  ( self							,							*_lowerCamelCase							,							**_lowerCamelCase):
								raise Exception(f'''You cannot use ``update`` on a {self.__class__.__name__} instance.''')




					def __getitem__( self							,							_lowerCamelCase):
								if isinstance(_lowerCamelCase							,							_lowerCamelCase):
											UpperCAmelCase__					:   List[Any]       				=       dict(self.items())
											return inner_dict[k]
								else:
											return self.to_tuple()[k]




					def __setattr__( self							,							_lowerCamelCase							,							_lowerCamelCase):
								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							,							_lowerCamelCase							,							_lowerCamelCase):
								# 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):
								return tuple(self[k] for k in self.keys())


class 						_snake_case   (       a__    ,				a__		):




					@classmethod
					def 			snake_case__  ( cls							,							_lowerCamelCase):
								raise ValueError(
								    f'''{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys())}''')


class 						_snake_case   (       a__		):
					lowerCAmelCase :Union[str, Any]						=   '''longest'''
					lowerCAmelCase :Optional[Any]						=   '''max_length'''
					lowerCAmelCase :List[Any]						=   '''do_not_pad'''


class 						_snake_case   (       a__		):
					lowerCAmelCase :str						=   '''pt'''
					lowerCAmelCase :Optional[Any]						=   '''tf'''
					lowerCAmelCase :str						=   '''np'''
					lowerCAmelCase :Dict						=   '''jax'''


class 						_snake_case   :




					def __init__( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   int       				=       context_managers
								UpperCAmelCase__					:   str       				=       ExitStack()




					def __enter__( self):
								for context_manager in self.context_managers:
											self.stack.enter_context(_lowerCamelCase)




					def __exit__( self							,							*_lowerCamelCase							,							**_lowerCamelCase):
								self.stack.__exit__(*_lowerCamelCase							,							**_lowerCamelCase)







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

			def _flatten_dict(UpperCamelCase__	, UpperCamelCase__=""	, UpperCamelCase__="."   ):
						for k, v in d.items():
									UpperCAmelCase__					:   int       				=       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       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__ = False   ):
			if use_temp_dir:
						with tempfile.TemporaryDirectory() as tmp_dir:
									yield tmp_dir
			else:
						yield working_dir







def       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__=None   ):
			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       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__   ):
			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       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__=None   ):
			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       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__   ):
			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       _UpperCamelCase (						UpperCamelCase__   ):
			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       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__   ):
			for key, value in auto_map.items():
						if isinstance(UpperCamelCase__	, (tuple, list)   ):
									UpperCAmelCase__					:   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:
									UpperCAmelCase__					:   Optional[int]       				=       f'''{repo_id}--{value}'''

			return auto_map







def       _UpperCamelCase (						UpperCamelCase__   ):
			for base_class in inspect.getmro(UpperCamelCase__   ):
						UpperCAmelCase__					:   str       				=       base_class.__module__
						UpperCAmelCase__					:   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}.'''   )



'''simple docstring'''



def       _UpperCamelCase (						UpperCamelCase__ = 1_0	, UpperCamelCase__ = 2_2   ):
			UpperCAmelCase__					:   List[str]       				=       range(1	, UpperCamelCase__   )
			UpperCAmelCase__					:   int       				=       range(1	, UpperCamelCase__   )
			return sum(
			    1 for power in powers for base in bases if len(str(base**power   )   ) == power   )


if __name__ == "__main__":
		print(f"""{solution(10, 22) = }""")