
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        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







  def __get__( self			: Union[str, Any]			,							UpperCamelCase__			: List[Any]			,							UpperCamelCase__			: Any=None    )			->	str:







    """simple docstring"""






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







def a__    (       A_					):






  '''simple docstring'''





  __magic_name__				     =       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 a__    (       A_					):






  '''simple docstring'''





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

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

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

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

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

  return isinstance(A_,     np.ndarray					)

def a__    (       A_					):






  '''simple docstring'''





  return isinstance(A_,     np.ndarray					)

def a__    (       A_					):






  '''simple docstring'''





  return _is_numpy(A_					)

def a__    (       A_					):






  '''simple docstring'''





  import torch

  return isinstance(A_,     torch.Tensor					)

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





  import torch

  return isinstance(A_,     torch.device					)

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





  import torch

  if isinstance(A_,     A_					):
    if hasattr(A_,     A_					):
      __magic_name__				     =       getattr(A_,     A_					)
    else:
      return False
  return isinstance(A_,     torch.dtype					)

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





  import tensorflow as tf

  return isinstance(A_,     tf.Tensor					)

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





  import tensorflow as tf

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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





  import jax.numpy as jnp  # noqa: F811

  return isinstance(A_,     jnp.ndarray					)

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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




class        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







  def 							_lowercase							( self			: List[Any]    )			->	str:







    """simple docstring"""






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

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







    """simple docstring"""






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







    """simple docstring"""






    raise Exception(F'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''    )
  def 							_lowercase							( self			: Any			,							*UpperCamelCase__			: List[str]			,							**UpperCamelCase__			: Optional[Any]    )			->	Optional[int]:







    """simple docstring"""






    raise Exception(F'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''    )
  def 							_lowercase							( self			: List[str]			,							*UpperCamelCase__			: Dict			,							**UpperCamelCase__			: Optional[int]    )			->	Tuple:







    """simple docstring"""






    raise Exception(F'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''    )
  def __getitem__( self			: Any			,							UpperCamelCase__			: Optional[Any]    )			->	Any:







    """simple docstring"""






    if isinstance(UpperCamelCase__			,							UpperCamelCase__    ):
      __magic_name__				     =       dict(self.items()    )
      return inner_dict[k]
    else:
      return self.to_tuple()[k]
  def __setattr__( self			: Optional[int]			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: str    )			->	Optional[Any]:







    """simple docstring"""






    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			: List[Any]			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: int    )			->	int:







    """simple docstring"""






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





  def 							_lowercase							( self			: str    )			->	Tuple[Any]:







    """simple docstring"""






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







class        UpperCAmelCase_			( _A  ,       _A     ):


  '''simple docstring'''







  @classmethod
  def 							_lowercase							( cls			: Union[str, Any]			,							UpperCamelCase__			: Optional[int]    )			->	Optional[int]:







    """simple docstring"""






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







class        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







  a__           =		"""longest"""
  a__           =		"""max_length"""
  a__           =		"""do_not_pad"""







class        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







  a__           =		"""pt"""
  a__           =		"""tf"""
  a__           =		"""np"""
  a__           =		"""jax"""







class        UpperCAmelCase_			:


  '''simple docstring'''







  def __init__( self			: Dict			,							UpperCamelCase__			: List[ContextManager]    )			->	Any:







    """simple docstring"""






    __magic_name__				     =       context_managers
    __magic_name__				     =       ExitStack()
  def __enter__( self			: Optional[int]    )			->	int:







    """simple docstring"""






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





  def __exit__( self			: Dict			,							*UpperCamelCase__			: str			,							**UpperCamelCase__			: Optional[int]    )			->	str:







    """simple docstring"""






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







def a__    (       A_					):






  '''simple docstring'''





  __magic_name__				     =       infer_framework(A_					)
  if framework == "tf":
    __magic_name__				     =       inspect.signature(model_class.call					)  # TensorFlow models
  elif framework == "pt":
    __magic_name__				     =       inspect.signature(model_class.forward					)  # PyTorch models
  else:
    __magic_name__				     =       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 a__    (       A_					):






  '''simple docstring'''





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






  '''simple docstring'''





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

  return dict(_flatten_dict(A_,     A_,     A_					)					)

@contextmanager
def a__    (       A_,     A_ = False					):






  '''simple docstring'''





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

def a__    (       A_,     A_=None					):






  '''simple docstring'''





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

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

def a__    (       A_,     A_					):






  '''simple docstring'''





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

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

def a__    (       A_,     A_=None					):






  '''simple docstring'''





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

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

def a__    (       A_,     A_					):






  '''simple docstring'''





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

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

def a__    (       A_					):






  '''simple docstring'''





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

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

def a__    (       A_,     A_					):






  '''simple docstring'''





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

  return auto_map





def a__    (       A_					):






  '''simple docstring'''





  for base_class in inspect.getmro(A_					):
    __magic_name__				     =       base_class.__module__
    __magic_name__				     =       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 typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available


lowerCAmelCase__      		= {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    lowerCAmelCase__      		= ['SpeechEncoderDecoderModel']

try:
    if not is_flax_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    lowerCAmelCase__      		= ['FlaxSpeechEncoderDecoderModel']

if TYPE_CHECKING:
    from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel

    try:
        if not is_flax_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel

else:
    import sys

    lowerCAmelCase__      		= _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
