



"""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_   ):

    def __get__(				self			:				Any ,  lowerCAmelCase_			:				Optional[int] ,  lowerCAmelCase_			:				Dict=None):







      """simple docstring"""







      if obj is None:
        return self
      if self.fget is None:
        raise AttributeError("""unreadable attribute""")
      lowercase_								= '__cached_' + self.fget.__name__
      lowercase_								= getattr(__a ,  __a ,  __a)
      if cached is None:
        lowercase_								= self.fget(__a)
        setattr(__a ,  __a ,  __a)
      return cached







def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Optional[int]:







  '''simple docstring'''


  lowercase_								= 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 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Union[str, Any]:







  '''simple docstring'''


  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 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Dict:







  '''simple docstring'''


  return isinstance(__lowerCAmelCase ,  np.ndarray							)


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Any:







  '''simple docstring'''


  return _is_numpy(__lowerCAmelCase							)


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Tuple:







  '''simple docstring'''


  import torch

  return isinstance(__lowerCAmelCase ,  torch.Tensor							)


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Union[str, Any]:







  '''simple docstring'''


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


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						str:







  '''simple docstring'''


  import torch

  return isinstance(__lowerCAmelCase ,  torch.device							)


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Optional[int]:







  '''simple docstring'''


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


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Any:







  '''simple docstring'''


  import torch

  if isinstance(__lowerCAmelCase ,  __lowerCAmelCase							):
    if hasattr(__lowerCAmelCase ,  __lowerCAmelCase							):
      lowercase_								= getattr(__lowerCAmelCase ,  __lowerCAmelCase							)
    else:
      return False
  return isinstance(__lowerCAmelCase ,  torch.dtype							)


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						List[str]:







  '''simple docstring'''


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


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Any:







  '''simple docstring'''


  import tensorflow as tf

  return isinstance(__lowerCAmelCase ,  tf.Tensor							)


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Optional[int]:







  '''simple docstring'''


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


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						int:







  '''simple docstring'''


  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 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Dict:







  '''simple docstring'''


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


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Any:







  '''simple docstring'''


  import jax.numpy as jnp  # noqa: F811

  return isinstance(__lowerCAmelCase ,  jnp.ndarray							)


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Union[str, Any]:







  '''simple docstring'''


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


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Union[str, Any]:







  '''simple docstring'''


  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 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Any:







  '''simple docstring'''


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

    def 					_UpperCAmelCase	(				self			:				Union[str, Any]):







      """simple docstring"""







      lowercase_								= 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.''')

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

    def __delitem__(				self			:				Tuple ,  *lowerCAmelCase_			:				List[str] ,  **lowerCAmelCase_			:				Dict):







      """simple docstring"""







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

    def 					_UpperCAmelCase	(				self			:				int ,  *lowerCAmelCase_			:				Union[str, Any] ,  **lowerCAmelCase_			:				List[str]):







      """simple docstring"""







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

    def 					_UpperCAmelCase	(				self			:				Dict ,  *lowerCAmelCase_			:				Any ,  **lowerCAmelCase_			:				List[Any]):







      """simple docstring"""







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

    def 					_UpperCAmelCase	(				self			:				List[Any] ,  *lowerCAmelCase_			:				int ,  **lowerCAmelCase_			:				Union[str, Any]):







      """simple docstring"""







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

    def __getitem__(				self			:				Optional[int] ,  lowerCAmelCase_			:				str):







      """simple docstring"""







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

    def __setattr__(				self			:				Dict ,  lowerCAmelCase_			:				Dict ,  lowerCAmelCase_			:				Dict):







      """simple docstring"""







      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			:				Any ,  lowerCAmelCase_			:				str ,  lowerCAmelCase_			:				Dict):







      """simple docstring"""







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




    def 					_UpperCAmelCase	(				self			:				str):







      """simple docstring"""







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







class    SCREAMING_SNAKE_CASE__ (							UpperCamelCase_      ,  UpperCamelCase_   ):

    @classmethod
    def 					_UpperCAmelCase	(				cls			:				Any ,  lowerCAmelCase_			:				Optional[Any]):







      """simple docstring"""







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







class    SCREAMING_SNAKE_CASE__ (							UpperCamelCase_   ):
    lowercase__      =   "longest"
    lowercase__      =   "max_length"
    lowercase__      =   "do_not_pad"







class    SCREAMING_SNAKE_CASE__ (							UpperCamelCase_   ):
    lowercase__      =   "pt"
    lowercase__      =   "tf"
    lowercase__      =   "np"
    lowercase__      =   "jax"







class    SCREAMING_SNAKE_CASE__ :

    def __init__(				self			:				List[Any] ,  lowerCAmelCase_			:				List[Any]):







      """simple docstring"""







      lowercase_								= context_managers
      lowercase_								= ExitStack()

    def __enter__(				self			:				List[str]):







      """simple docstring"""







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




    def __exit__(				self			:				int ,  *lowerCAmelCase_			:				List[str] ,  **lowerCAmelCase_			:				Tuple):







      """simple docstring"""







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







def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Tuple:







  '''simple docstring'''


  lowercase_								= infer_framework(__lowerCAmelCase							)
  if framework == "tf":
    lowercase_								= inspect.signature(model_class.call							)  # TensorFlow models
  elif framework == "pt":
    lowercase_								= inspect.signature(model_class.forward							)  # PyTorch models
  else:
    lowercase_								= 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 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						List[Any]:







  '''simple docstring'''


  lowercase_								= model_class.__name__
  lowercase_								= infer_framework(__lowerCAmelCase							)
  if framework == "tf":
    lowercase_								= inspect.signature(model_class.call							)  # TensorFlow models
  elif framework == "pt":
    lowercase_								= inspect.signature(model_class.forward							)  # PyTorch models
  else:
    lowercase_								= 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 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase = "" ,  __lowerCAmelCase = "."							) ->						Any:







  '''simple docstring'''


  def _flatten_dict(__lowerCAmelCase ,  __lowerCAmelCase="" ,  __lowerCAmelCase="."							):
    for k, v in d.items():
      lowercase_								= 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 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase = False							) ->						Union[str, Any]:







  '''simple docstring'''


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


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase=None							) ->						List[Any]:







  '''simple docstring'''


  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 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase							) ->						List[str]:







  '''simple docstring'''


  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 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase=None							) ->						Union[str, Any]:







  '''simple docstring'''


  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 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase							) ->						int:







  '''simple docstring'''


  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 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Optional[int]:







  '''simple docstring'''


  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 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase							) ->						Optional[Any]:







  '''simple docstring'''


  for key, value in auto_map.items():
    if isinstance(__lowerCAmelCase ,  (tuple, list)							):
      lowercase_								= [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:
      lowercase_								= F'''{repo_id}--{value}'''

  return auto_map


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Tuple:







  '''simple docstring'''


  for base_class in inspect.getmro(__lowerCAmelCase							):
    lowercase_								= base_class.__module__
    lowercase_								= 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 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase							) ->						int:







  '''simple docstring'''


  while a != 0:
    lowercase_					,    lowercase_								= b % a, a
  return b


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase							) ->						int:







  '''simple docstring'''


  if gcd(__lowerCAmelCase ,  __lowerCAmelCase							) != 1:
    lowercase_								= F'''mod inverse of {a!r} and {m!r} does not exist'''
    raise ValueError(__lowerCAmelCase							)
  lowercase_					,    lowercase_					,    lowercase_								= 1, 0, a
  lowercase_					,    lowercase_					,    lowercase_								= 0, 1, m
  while va != 0:
    lowercase_								= ua // va
    lowercase_					,    lowercase_					,    lowercase_					,    lowercase_					,    lowercase_					,    lowercase_								= (ua - q * va), (ua - q * va), (ua - q * va), va, va, va
  return ua % m

