





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






   '''simple docstring'''





   def __get__(							self	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE=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"""       )
    snake_case__     :					List[Any]    =  """__cached_""" + self.fget.__name__
    snake_case__     :					str    =  getattr(__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       )
    if cached is None:
     snake_case__     :					Optional[Any]    =  self.fget(__SCREAMING_SNAKE_CASE       )
     setattr(__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       )
    return cached



def        UpperCamelCase__		(						__magic_name__  :   List[Any]      )				->			str:
 '''simple docstring'''






 snake_case__     :					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        UpperCamelCase__		(						__magic_name__  :   Optional[int]      )				->			str:
 '''simple docstring'''






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

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

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

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

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

 return isinstance(__magic_name__		,       np.ndarray      )



def        UpperCamelCase__		(						__magic_name__  :   List[str]      )				->			List[str]:
 '''simple docstring'''






 return isinstance(__magic_name__		,       np.ndarray      )



def        UpperCamelCase__		(						__magic_name__  :   Optional[int]      )				->			List[Any]:
 '''simple docstring'''






 return _is_numpy(__magic_name__      )



def        UpperCamelCase__		(						__magic_name__  :   Tuple      )				->			List[Any]:
 '''simple docstring'''






 import torch

 return isinstance(__magic_name__		,       torch.Tensor      )



def        UpperCamelCase__		(						__magic_name__  :   List[str]      )				->			Union[str, Any]:
 '''simple docstring'''






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



def        UpperCamelCase__		(						__magic_name__  :   Dict      )				->			Union[str, Any]:
 '''simple docstring'''






 import torch

 return isinstance(__magic_name__		,       torch.device      )



def        UpperCamelCase__		(						__magic_name__  :   str      )				->			Dict:
 '''simple docstring'''






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



def        UpperCamelCase__		(						__magic_name__  :   Optional[Any]      )				->			int:
 '''simple docstring'''






 import torch

 if isinstance(__magic_name__		,       __magic_name__      ):
  if hasattr(__magic_name__		,       __magic_name__      ):
   snake_case__     :					Optional[Any]    =  getattr(__magic_name__		,       __magic_name__      )
  else:
   return False
 return isinstance(__magic_name__		,       torch.dtype      )



def        UpperCamelCase__		(						__magic_name__  :   Union[str, Any]      )				->			List[str]:
 '''simple docstring'''






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



def        UpperCamelCase__		(						__magic_name__  :   Union[str, Any]      )				->			List[Any]:
 '''simple docstring'''






 import tensorflow as tf

 return isinstance(__magic_name__		,       tf.Tensor      )



def        UpperCamelCase__		(						__magic_name__  :   List[str]      )				->			Union[str, Any]:
 '''simple docstring'''






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



def        UpperCamelCase__		(						__magic_name__  :   Optional[Any]      )				->			Optional[Any]:
 '''simple docstring'''






 import tensorflow as tf

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



def        UpperCamelCase__		(						__magic_name__  :   List[str]      )				->			int:
 '''simple docstring'''






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



def        UpperCamelCase__		(						__magic_name__  :   Union[str, Any]      )				->			Optional[Any]:
 '''simple docstring'''






 import jax.numpy as jnp  # noqa: F811

 return isinstance(__magic_name__		,       jnp.ndarray      )



def        UpperCamelCase__		(						__magic_name__  :   List[str]      )				->			List[str]:
 '''simple docstring'''






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



def        UpperCamelCase__		(						__magic_name__  :   str      )				->			str:
 '''simple docstring'''






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



def        UpperCamelCase__		(						__magic_name__  :   List[Any]      )				->			Union[str, Any]:
 '''simple docstring'''






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






   '''simple docstring'''





   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					List[Any]    =  fields(self       )

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

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

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

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

   def 		__UpperCamelCase						(							self	,		*__SCREAMING_SNAKE_CASE	,		**__SCREAMING_SNAKE_CASE       ):
    raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance."       )

   def 		__UpperCamelCase						(							self	,		*__SCREAMING_SNAKE_CASE	,		**__SCREAMING_SNAKE_CASE       ):
    raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance."       )

   def 		__UpperCamelCase						(							self	,		*__SCREAMING_SNAKE_CASE	,		**__SCREAMING_SNAKE_CASE       ):
    raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance."       )

   def __getitem__(							self	,		__SCREAMING_SNAKE_CASE       ):
    if isinstance(__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       ):
     snake_case__     :					Optional[Any]    =  dict(self.items()       )
     return inner_dict[k]
    else:
     return self.to_tuple()[k]

   def __setattr__(							self	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       ):
    if name in self.keys() and value is not None:
     # Don't call self.__setitem__ to avoid recursion errors
     super().__setitem__(__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       )
    super().__setattr__(__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       )

   def __setitem__(							self	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       ):
    # Will raise a KeyException if needed
    super().__setitem__(__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       )
    # Don't call self.__setattr__ to avoid recursion errors
    super().__setattr__(__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       )


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



class 					__snake_case  (					__SCREAMING_SNAKE_CASE		,				__SCREAMING_SNAKE_CASE							):






   '''simple docstring'''





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



class 					__snake_case  (					__SCREAMING_SNAKE_CASE							):






   '''simple docstring'''





   lowerCamelCase__    							=      '''longest'''
   lowerCamelCase__    							=      '''max_length'''
   lowerCamelCase__    							=      '''do_not_pad'''



class 					__snake_case  (					__SCREAMING_SNAKE_CASE							):






   '''simple docstring'''





   lowerCamelCase__    							=      '''pt'''
   lowerCamelCase__    							=      '''tf'''
   lowerCamelCase__    							=      '''np'''
   lowerCamelCase__    							=      '''jax'''



class 					__snake_case  :






   '''simple docstring'''





   def __init__(							self	,		__SCREAMING_SNAKE_CASE       ):
    snake_case__     :					Union[str, Any]    =  context_managers
    snake_case__     :					str    =  ExitStack()

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


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



def        UpperCamelCase__		(						__magic_name__  :   Optional[int]      )				->			Union[str, Any]:
 '''simple docstring'''






 snake_case__     :					Dict    =  infer_framework(__magic_name__      )
 if framework == "tf":
  snake_case__     :					Union[str, Any]    =  inspect.signature(model_class.call      )  # TensorFlow models
 elif framework == "pt":
  snake_case__     :					int    =  inspect.signature(model_class.forward      )  # PyTorch models
 else:
  snake_case__     :					Optional[int]    =  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__		(						__magic_name__  :   Any      )				->			List[str]:
 '''simple docstring'''






 snake_case__     :					List[Any]    =  model_class.__name__
 snake_case__     :					Union[str, Any]    =  infer_framework(__magic_name__      )
 if framework == "tf":
  snake_case__     :					int    =  inspect.signature(model_class.call      )  # TensorFlow models
 elif framework == "pt":
  snake_case__     :					Dict    =  inspect.signature(model_class.forward      )  # PyTorch models
 else:
  snake_case__     :					List[str]    =  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__		(						__magic_name__  :   MutableMapping		,       __magic_name__  :   str = ""		,       __magic_name__  :   str = "."      )				->			Dict:
 '''simple docstring'''






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

 return dict(_flatten_dict(__magic_name__		,       __magic_name__		,       __magic_name__      )      )



@contextmanager
def        UpperCamelCase__		(						__magic_name__  :   Union[str, Any]		,       __magic_name__  :   bool = False      )				->			List[str]:
 '''simple docstring'''






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



def        UpperCamelCase__		(						__magic_name__  :   Tuple		,       __magic_name__  :   Any=None      )				->			Dict:
 '''simple docstring'''






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

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



def        UpperCamelCase__		(						__magic_name__  :   int		,       __magic_name__  :   Optional[Any]      )				->			List[Any]:
 '''simple docstring'''






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

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



def        UpperCamelCase__		(						__magic_name__  :   List[Any]		,       __magic_name__  :   Optional[Any]=None      )				->			Dict:
 '''simple docstring'''






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

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



def        UpperCamelCase__		(						__magic_name__  :   str		,       __magic_name__  :   int      )				->			List[Any]:
 '''simple docstring'''






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

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



def        UpperCamelCase__		(						__magic_name__  :   List[str]      )				->			Optional[Any]:
 '''simple docstring'''






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

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



def        UpperCamelCase__		(						__magic_name__  :   Dict		,       __magic_name__  :   Optional[Any]      )				->			Optional[Any]:
 '''simple docstring'''






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

 return auto_map





def        UpperCamelCase__		(						__magic_name__  :   str      )				->			Tuple:
 '''simple docstring'''






 for base_class in inspect.getmro(__magic_name__      ):
  snake_case__     :					List[Any]    =  base_class.__module__
  snake_case__     :					Tuple    =  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 			a_	(				_lowerCAmelCase			) -> int:

  if not isinstance(_lowerCAmelCase			,_lowerCAmelCase			):
    raise TypeError('only integers accepted as input'			)
  else:
    __lowerCamelCase			:			Any       			=					str(abs(_lowerCAmelCase			)			)
    __lowerCamelCase			:			Tuple       			=					[list(_lowerCAmelCase			) for char in range(len(_lowerCAmelCase			)			)]
    for index in range(len(_lowerCAmelCase			)			):
      num_transpositions[index].pop(_lowerCAmelCase			)
    return max(
        int(''.join(list(_lowerCAmelCase			)			)			) for transposition in num_transpositions			)


if __name__ == "__main__":
   __import__('doctest').testmod()






