



'''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        lowerCAmelCase_(				SCREAMING_SNAKE_CASE_     ):
  '''simple docstring'''




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







def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """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    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





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



    """simple docstring"""





    return isinstance(UpperCamelCase							,    np.ndarray			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    return _is_numpy(UpperCamelCase			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    import torch

    return isinstance(UpperCamelCase							,    torch.Tensor			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    return False if not is_torch_available() else _is_torch(UpperCamelCase			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    import torch

    return isinstance(UpperCamelCase							,    torch.device			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    return False if not is_torch_available() else _is_torch_device(UpperCamelCase			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    import torch

    if isinstance(UpperCamelCase							,    UpperCamelCase			):
        if hasattr(UpperCamelCase							,    UpperCamelCase			):
            lowerCAmelCase__ :  Any							      =					getattr(UpperCamelCase							,    UpperCamelCase			)
        else:
            return False
    return isinstance(UpperCamelCase							,    torch.dtype			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    return False if not is_torch_available() else _is_torch_dtype(UpperCamelCase			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    import tensorflow as tf

    return isinstance(UpperCamelCase							,    tf.Tensor			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    return False if not is_tf_available() else _is_tensorflow(UpperCamelCase			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





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



    """simple docstring"""





    return False if not is_tf_available() else _is_tf_symbolic_tensor(UpperCamelCase			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    import jax.numpy as jnp  # noqa: F811

    return isinstance(UpperCamelCase							,    jnp.ndarray			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    return False if not is_flax_available() else _is_jax(UpperCamelCase			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





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



    """simple docstring"""





    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_(				SCREAMING_SNAKE_CASE_     ):
  '''simple docstring'''




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




  def __delitem__(    self  ,*__UpperCAmelCase  ,**__UpperCAmelCase      )    ->		Optional[Any]:
      raise Exception(F"""You cannot use ``__delitem__`` on a {self.__class__.__name__} instance."""      )




  def 							UpperCAmelCase_	(    self  ,*__UpperCAmelCase  ,**__UpperCAmelCase      )    ->		Tuple:
      raise Exception(F"""You cannot use ``setdefault`` on a {self.__class__.__name__} instance."""      )




  def 							UpperCAmelCase_	(    self  ,*__UpperCAmelCase  ,**__UpperCAmelCase      )    ->		Dict:
      raise Exception(F"""You cannot use ``pop`` on a {self.__class__.__name__} instance."""      )




  def 							UpperCAmelCase_	(    self  ,*__UpperCAmelCase  ,**__UpperCAmelCase      )    ->		Any:
      raise Exception(F"""You cannot use ``update`` on a {self.__class__.__name__} instance."""      )




  def __getitem__(    self  ,__UpperCAmelCase      )    ->		Dict:
      if isinstance(__UpperCAmelCase  ,__UpperCAmelCase      ):
          lowerCAmelCase__ :  List[str]							      =					dict(self.items()      )
          return inner_dict[k]
      else:
          return self.to_tuple()[k]




  def __setattr__(    self  ,__UpperCAmelCase  ,__UpperCAmelCase      )    ->		List[Any]:
      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      )    ->		Tuple:
      # Will raise a KeyException if needed
      super().__setitem__(__UpperCAmelCase  ,__UpperCAmelCase      )
      # Don't call self.__setattr__ to avoid recursion errors
      super().__setattr__(__UpperCAmelCase  ,__UpperCAmelCase      )






  def 							UpperCAmelCase_	(    self      )    ->		Tuple[Any]:
      return tuple(self[k] for k in self.keys()      )







class        lowerCAmelCase_(				SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_     ):
  '''simple docstring'''




  @classmethod
  def 							UpperCAmelCase_	(    cls  ,__UpperCAmelCase      )    ->		Optional[int]:
      raise ValueError(
          F"""{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()      )}"""      )







class        lowerCAmelCase_(				SCREAMING_SNAKE_CASE_     ):
  '''simple docstring'''




  __lowercase							:      Union[str, Any]				=      '''longest'''
  __lowercase							:      int				=      '''max_length'''
  __lowercase							:      Optional[int]				=      '''do_not_pad'''







class        lowerCAmelCase_(				SCREAMING_SNAKE_CASE_     ):
  '''simple docstring'''




  __lowercase							:      Optional[int]				=      '''pt'''
  __lowercase							:      Any				=      '''tf'''
  __lowercase							:      Any				=      '''np'''
  __lowercase							:      Any				=      '''jax'''







class        lowerCAmelCase_:
  '''simple docstring'''




  def __init__(    self  ,__UpperCAmelCase      )    ->		Tuple:
      lowerCAmelCase__ :  Union[str, Any]							      =					context_managers
      lowerCAmelCase__ :  int							      =					ExitStack()




  def __enter__(    self      )    ->		Optional[int]:
      for context_manager in self.context_managers:
          self.stack.enter_context(__UpperCAmelCase      )






  def __exit__(    self  ,*__UpperCAmelCase  ,**__UpperCAmelCase      )    ->		List[str]:
      self.stack.__exit__(*__UpperCAmelCase  ,**__UpperCAmelCase      )







def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    lowerCAmelCase__ :  Union[str, Any]							      =					infer_framework(UpperCamelCase			)
    if framework == "tf":
        lowerCAmelCase__ :  str							      =					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    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





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



    """simple docstring"""





    def _flatten_dict(UpperCamelCase							,    UpperCamelCase=""							,    UpperCamelCase="."			):
        for k, v in d.items():
            lowerCAmelCase__ :  str							      =					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    _SCREAMING_SNAKE_CASE  (       UpperCamelCase							,    UpperCamelCase = False			):



    """simple docstring"""





    if use_temp_dir:
        with tempfile.TemporaryDirectory() as tmp_dir:
            yield tmp_dir
    else:
        yield working_dir
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase							,    UpperCamelCase=None			):



    """simple docstring"""





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



    """simple docstring"""





    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    _SCREAMING_SNAKE_CASE  (       UpperCamelCase							,    UpperCamelCase=None			):



    """simple docstring"""





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



    """simple docstring"""





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



    """simple docstring"""





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



    """simple docstring"""





    for key, value in auto_map.items():
        if isinstance(UpperCamelCase							,    (tuple, list)			):
            lowerCAmelCase__ :  Union[str, 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__ :  List[str]							      =					f"""{repo_id}--{value}"""

    return auto_map




def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    for base_class in inspect.getmro(UpperCamelCase			):
        lowerCAmelCase__ :  Optional[Any]							      =					base_class.__module__
        lowerCAmelCase__ :  Dict							      =					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  (       UpperCamelCase = "The quick brown fox jumps over the lazy dog"							,    ):



    """simple docstring"""





    lowerCAmelCase__ :  str							      =					set()

    # Replace all the whitespace in our sentence
    lowerCAmelCase__ :  Tuple							      =					input_str.replace(""" """							,    """"""			)
    for alpha in input_str:
        if "a" <= alpha.lower() <= "z":
            frequency.add(alpha.lower()			)
    return len(UpperCamelCase			) == 26
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase = "The quick brown fox jumps over the lazy dog"							,    ):



    """simple docstring"""





    lowerCAmelCase__ :  Any							      =					[False] * 26
    for char in input_str:
        if char.islower():
            lowerCAmelCase__ :  Optional[Any]							      =					True
        elif char.isupper():
            lowerCAmelCase__ :  Any							      =					True
    return all(UpperCamelCase			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase = "The quick brown fox jumps over the lazy dog"							,    ):



    """simple docstring"""





    return len({char for char in input_str.lower() if char.isalpha()}			) == 26
def    _SCREAMING_SNAKE_CASE  (       ):



    """simple docstring"""





    from timeit import timeit

    lowerCAmelCase__ :  Union[str, Any]							      =					"""from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest"""
    print(timeit("""is_pangram()"""							,    setup=UpperCamelCase			)			)
    print(timeit("""is_pangram_faster()"""							,    setup=UpperCamelCase			)			)
    print(timeit("""is_pangram_fastest()"""							,    setup=UpperCamelCase			)			)
    # 5.348480500048026, 2.6477354579837993, 1.8470395830227062
    # 5.036091582966037, 2.644472333951853,  1.8869528750656173


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 benchmark()


