




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

      def __get__(   self      ,				__UpperCAmelCase      ,				__UpperCAmelCase=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'''		)
        lowerCAmelCase__				:  Dict		       =     '''__cached_''' + self.fget.__name__
        lowerCAmelCase__				:  Any		       =     getattr(__UpperCAmelCase      ,				__UpperCAmelCase      ,				__UpperCAmelCase		)
        if cached is None:
          lowerCAmelCase__				:  Any		       =     self.fget(__UpperCAmelCase		)
          setattr(__UpperCAmelCase      ,				__UpperCAmelCase      ,				__UpperCAmelCase		)
        return cached



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	Any:
  lowerCAmelCase__				:  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      __lowerCAmelCase			(					UpperCamelCase      )     ->	Optional[int]:
  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      __lowerCAmelCase			(					UpperCamelCase      )     ->	Union[str, Any]:
  return isinstance(UpperCamelCase	,      np.ndarray      )



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	Tuple:
  return _is_numpy(UpperCamelCase      )



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	Tuple:
  import torch

  return isinstance(UpperCamelCase	,      torch.Tensor      )



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	Union[str, Any]:
  return False if not is_torch_available() else _is_torch(UpperCamelCase      )



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	List[str]:
  import torch

  return isinstance(UpperCamelCase	,      torch.device      )



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	Optional[int]:
  return False if not is_torch_available() else _is_torch_device(UpperCamelCase      )



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	Tuple:
  import torch

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



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	Any:
  return False if not is_torch_available() else _is_torch_dtype(UpperCamelCase      )



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	Union[str, Any]:
  import tensorflow as tf

  return isinstance(UpperCamelCase	,      tf.Tensor      )



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	Optional[Any]:
  return False if not is_tf_available() else _is_tensorflow(UpperCamelCase      )



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



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	Dict:
  import jax.numpy as jnp  # noqa: F811

  return isinstance(UpperCamelCase	,      jnp.ndarray      )



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	Tuple:
  return False if not is_flax_available() else _is_jax(UpperCamelCase      )



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	Optional[int]:
  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      __lowerCAmelCase			(					UpperCamelCase      )     ->	Tuple:
  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  _lowerCAmelCase     (  _lowercase	):

      def 	__magic_name__(   self		):
        lowerCAmelCase__				:  List[Any]		       =     fields(self		)

        # Safety and consistency checks
        if not len(__UpperCAmelCase		):
          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__				:  int		       =     getattr(self      ,				class_fields[0].name		)
        lowerCAmelCase__				:  str		       =     all(getattr(self      ,				field.name		) is None for field in class_fields[1:]		)

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

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

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

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

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

      def __getitem__(   self      ,				__UpperCAmelCase		):
        if isinstance(__UpperCAmelCase      ,				__UpperCAmelCase		):
          lowerCAmelCase__				:  Union[str, Any]		       =     dict(self.items()		)
          return inner_dict[k]
        else:
          return self.to_tuple()[k]

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

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







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






class  _lowerCAmelCase     (  _lowercase    ,			_lowercase	):

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






class  _lowerCAmelCase     (  _lowercase	):
      A__		     =		'longest'
      A__		     =		'max_length'
      A__		     =		'do_not_pad'






class  _lowerCAmelCase     (  _lowercase	):
      A__		     =		'pt'
      A__		     =		'tf'
      A__		     =		'np'
      A__		     =		'jax'






class  _lowerCAmelCase     :

      def __init__(   self      ,				__UpperCAmelCase		):
        lowerCAmelCase__				:  Optional[Any]		       =     context_managers
        lowerCAmelCase__				:  List[Any]		       =     ExitStack()

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







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



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

  def _flatten_dict(UpperCamelCase	,      UpperCamelCase=""	,      UpperCamelCase="."      ):
    for k, v in d.items():
      lowerCAmelCase__				:  Optional[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      __lowerCAmelCase			(					UpperCamelCase	,      UpperCamelCase = False      )     ->	List[str]:
  if use_temp_dir:
    with tempfile.TemporaryDirectory() as tmp_dir:
      yield tmp_dir
  else:
    yield working_dir



def      __lowerCAmelCase			(					UpperCamelCase	,      UpperCamelCase=None      )     ->	Tuple:
  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      __lowerCAmelCase			(					UpperCamelCase	,      UpperCamelCase      )     ->	Any:
  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      __lowerCAmelCase			(					UpperCamelCase	,      UpperCamelCase=None      )     ->	Dict:
  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      __lowerCAmelCase			(					UpperCamelCase	,      UpperCamelCase      )     ->	List[str]:
  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      __lowerCAmelCase			(					UpperCamelCase      )     ->	int:
  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      __lowerCAmelCase			(					UpperCamelCase	,      UpperCamelCase      )     ->	List[str]:
  for key, value in auto_map.items():
    if isinstance(UpperCamelCase	,      (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      __lowerCAmelCase			(					UpperCamelCase      )     ->	Union[str, Any]:
  for base_class in inspect.getmro(UpperCamelCase      ):
    lowerCAmelCase__				:  Any		       =     base_class.__module__
    lowerCAmelCase__				:  Union[str, Any]		       =     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}."""      )







from __future__ import annotations



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	list[int]:  # This function is recursive
  lowerCAmelCase__				:  Tuple		       =     len(UpperCamelCase      )
  # If the array contains only one element, we return it (it's the stop condition of
  # recursion)
  if array_length <= 1:
    return array
    # Else
  lowerCAmelCase__				:  Optional[int]		       =     array[0]
  lowerCAmelCase__				:  Union[str, Any]		       =     False
  lowerCAmelCase__				:  List[str]		       =     1
  lowerCAmelCase__				:  list[int]		       =     []
  while not is_found and i < array_length:
    if array[i] < pivot:
      lowerCAmelCase__				:  List[Any]		       =     True
      lowerCAmelCase__				:  Optional[int]		       =     [element for element in array[i:] if element >= array[i]]
      lowerCAmelCase__				:  Any		       =     longest_subsequence(UpperCamelCase      )
      if len(UpperCamelCase      ) > len(UpperCamelCase      ):
        lowerCAmelCase__				:  Optional[int]		       =     temp_array
    else:
      i += 1

  lowerCAmelCase__				:  Optional[Any]		       =     [element for element in array[1:] if element >= pivot]
  lowerCAmelCase__				:  List[Any]		       =     [pivot, *longest_subsequence(UpperCamelCase      )]
  if len(UpperCamelCase      ) > len(UpperCamelCase      ):
    return temp_array
  else:
    return longest_subseq


if __name__ == "__main__":
     import doctest

     doctest.testmod()

