





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	:				Optional[Any]    ,      a__	:				str    ,      a__	:				Optional[int]=None				):





         """simple docstring"""



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






def lowerCamelCase__   (							snake_case_     :  Optional[Any]	)				->    str:
   __snake_case								=       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__   (							snake_case_     :  Any	)				->    Tuple:
   if is_torch_fx_proxy(snake_case_	):
      return True
   if is_torch_available():
      import torch

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

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

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

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

   return isinstance(snake_case_	,				np.ndarray	)






def lowerCamelCase__   (							snake_case_     :  int	)				->    List[str]:
   return isinstance(snake_case_	,				np.ndarray	)






def lowerCamelCase__   (							snake_case_     :  Optional[int]	)				->    Optional[Any]:
   return _is_numpy(snake_case_	)






def lowerCamelCase__   (							snake_case_     :  Optional[int]	)				->    Optional[int]:
   import torch

   return isinstance(snake_case_	,				torch.Tensor	)






def lowerCamelCase__   (							snake_case_     :  int	)				->    Optional[Any]:
   return False if not is_torch_available() else _is_torch(snake_case_	)






def lowerCamelCase__   (							snake_case_     :  int	)				->    int:
   import torch

   return isinstance(snake_case_	,				torch.device	)






def lowerCamelCase__   (							snake_case_     :  Tuple	)				->    List[str]:
   return False if not is_torch_available() else _is_torch_device(snake_case_	)






def lowerCamelCase__   (							snake_case_     :  Optional[int]	)				->    Union[str, Any]:
   import torch

   if isinstance(snake_case_	,				snake_case_	):
      if hasattr(snake_case_	,				snake_case_	):
         __snake_case								=       getattr(snake_case_	,				snake_case_	)
      else:
         return False
   return isinstance(snake_case_	,				torch.dtype	)






def lowerCamelCase__   (							snake_case_     :  List[Any]	)				->    str:
   return False if not is_torch_available() else _is_torch_dtype(snake_case_	)






def lowerCamelCase__   (							snake_case_     :  List[str]	)				->    List[str]:
   import tensorflow as tf

   return isinstance(snake_case_	,				tf.Tensor	)






def lowerCamelCase__   (							snake_case_     :  Tuple	)				->    List[str]:
   return False if not is_tf_available() else _is_tensorflow(snake_case_	)






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

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






def lowerCamelCase__   (							snake_case_     :  Optional[int]	)				->    List[str]:
   return False if not is_tf_available() else _is_tf_symbolic_tensor(snake_case_	)






def lowerCamelCase__   (							snake_case_     :  Optional[int]	)				->    str:
   import jax.numpy as jnp  # noqa: F811

   return isinstance(snake_case_	,				jnp.ndarray	)






def lowerCamelCase__   (							snake_case_     :  Union[str, Any]	)				->    str:
   return False if not is_flax_available() else _is_jax(snake_case_	)






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






def lowerCamelCase__   (							snake_case_     :  Optional[Any]	)				->    Any:
   if isinstance(snake_case_	,				(dict, UserDict)	):
      return {k: to_numpy(snake_case_	) for k, v in obj.items()}
   elif isinstance(snake_case_	,				(list, tuple)	):
      return np.array(snake_case_	)
   elif is_tf_tensor(snake_case_	):
      return obj.numpy()
   elif is_torch_tensor(snake_case_	):
      return obj.detach().cpu().numpy()
   elif is_jax_tensor(snake_case_	):
      return np.asarray(snake_case_	)
   else:
      return obj

class 		SCREAMING_SNAKE_CASE__    (	_UpperCAmelCase  ):


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





         """simple docstring"""



         __snake_case								=       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."""				)

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


      def __delitem__(self	:				str    ,      *a__	:				Optional[Any]    ,      **a__	:				List[str]				):





         """simple docstring"""



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


      def        a			(self	:				List[Any]    ,      *a__	:				Dict    ,      **a__	:				Dict				):





         """simple docstring"""



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


      def        a			(self	:				Optional[Any]    ,      *a__	:				Tuple    ,      **a__	:				int				):





         """simple docstring"""



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


      def        a			(self	:				Union[str, Any]    ,      *a__	:				Any    ,      **a__	:				Optional[Any]				):





         """simple docstring"""



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


      def __getitem__(self	:				Any    ,      a__	:				Any				):





         """simple docstring"""



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


      def __setattr__(self	:				Optional[int]    ,      a__	:				str    ,      a__	:				Tuple				):





         """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	:				Optional[Any]    ,      a__	:				List[Any]    ,      a__	:				Tuple				):





         """simple docstring"""



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


      def        a			(self	:				str				):





         """simple docstring"""



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






class 		SCREAMING_SNAKE_CASE__    (	_UpperCAmelCase						,				_UpperCAmelCase  ):


      @classmethod
      def        a			(cls	:				List[str]    ,      a__	:				int				):





         """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  ):
      A_						:    Union[str, Any]							=   'longest'
      A_						:    int							=   'max_length'
      A_						:    List[Any]							=   'do_not_pad'






class 		SCREAMING_SNAKE_CASE__    (	_UpperCAmelCase  ):
      A_						:    Tuple							=   'pt'
      A_						:    Tuple							=   'tf'
      A_						:    Any							=   'np'
      A_						:    Union[str, Any]							=   'jax'






class 		SCREAMING_SNAKE_CASE__    :


      def __init__(self	:				Any    ,      a__	:				List[ContextManager]				):





         """simple docstring"""



         __snake_case								=       context_managers
         __snake_case								=       ExitStack()


      def __enter__(self	:				Optional[int]				):





         """simple docstring"""



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


      def __exit__(self	:				List[Any]    ,      *a__	:				Tuple    ,      **a__	:				Dict				):





         """simple docstring"""



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






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

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

   return dict(_flatten_dict(snake_case_	,				snake_case_	,				snake_case_	)	)






@contextmanager
def lowerCamelCase__   (							snake_case_     :  Optional[int]	,				snake_case_     :  bool = False	)				->    Optional[int]:
   if use_temp_dir:
      with tempfile.TemporaryDirectory() as tmp_dir:
         yield tmp_dir
   else:
      yield working_dir






def lowerCamelCase__   (							snake_case_     :  Dict	,				snake_case_     :  List[str]=None	)				->    List[str]:
   if is_numpy_array(snake_case_	):
      return np.transpose(snake_case_	,				axes=snake_case_	)
   elif is_torch_tensor(snake_case_	):
      return array.T if axes is None else array.permute(*snake_case_	)
   elif is_tf_tensor(snake_case_	):
      import tensorflow as tf

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






def lowerCamelCase__   (							snake_case_     :  List[str]	,				snake_case_     :  Optional[Any]	)				->    Optional[Any]:
   if is_numpy_array(snake_case_	):
      return np.reshape(snake_case_	,				snake_case_	)
   elif is_torch_tensor(snake_case_	):
      return array.reshape(*snake_case_	)
   elif is_tf_tensor(snake_case_	):
      import tensorflow as tf

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






def lowerCamelCase__   (							snake_case_     :  Optional[int]	,				snake_case_     :  Tuple=None	)				->    Optional[Any]:
   if is_numpy_array(snake_case_	):
      return np.squeeze(snake_case_	,				axis=snake_case_	)
   elif is_torch_tensor(snake_case_	):
      return array.squeeze() if axis is None else array.squeeze(dim=snake_case_	)
   elif is_tf_tensor(snake_case_	):
      import tensorflow as tf

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






def lowerCamelCase__   (							snake_case_     :  Tuple	,				snake_case_     :  Optional[Any]	)				->    str:
   if is_numpy_array(snake_case_	):
      return np.expand_dims(snake_case_	,				snake_case_	)
   elif is_torch_tensor(snake_case_	):
      return array.unsqueeze(dim=snake_case_	)
   elif is_tf_tensor(snake_case_	):
      import tensorflow as tf

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






def lowerCamelCase__   (							snake_case_     :  Tuple	)				->    List[str]:
   if is_numpy_array(snake_case_	):
      return np.size(snake_case_	)
   elif is_torch_tensor(snake_case_	):
      return array.numel()
   elif is_tf_tensor(snake_case_	):
      import tensorflow as tf

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






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

   return auto_map







def lowerCamelCase__   (							snake_case_     :  Dict	)				->    str:
   for base_class in inspect.getmro(snake_case_	):
      __snake_case								=       base_class.__module__
      __snake_case								=       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}."""	)








import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


snake_case_           =      logging.get_logger(__name__)

snake_case_           =      {
    'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json',
    # See all SEW-D models at https://huggingface.co/models?filter=sew-d
}

class 		SCREAMING_SNAKE_CASE__    (	_UpperCAmelCase  ):
      A_						:    str							=   'sew-d'


      def __init__(self	:				str    ,      a__	:				List[Any]=32    ,      a__	:				Optional[int]=768    ,      a__	:				Union[str, Any]=12    ,      a__	:				Tuple=12    ,      a__	:				int=3072    ,      a__	:				List[Any]=2    ,      a__	:				Dict=512    ,      a__	:				Dict=256    ,      a__	:				List[str]=True    ,      a__	:				List[str]=True    ,      a__	:				str=("p2c", "c2p")    ,      a__	:				str="layer_norm"    ,      a__	:				str="gelu_python"    ,      a__	:				List[Any]=0.1    ,      a__	:				Dict=0.1    ,      a__	:				Optional[Any]=0.1    ,      a__	:				Union[str, Any]=0.0    ,      a__	:				Dict=0.1    ,      a__	:				int=0.0_2    ,      a__	:				str=1E-7    ,      a__	:				Union[str, Any]=1E-5    ,      a__	:				Union[str, Any]="group"    ,      a__	:				Optional[Any]="gelu"    ,      a__	:				List[Any]=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)    ,      a__	:				Union[str, Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)    ,      a__	:				Optional[int]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)    ,      a__	:				List[str]=False    ,      a__	:				Optional[Any]=128    ,      a__	:				Union[str, Any]=16    ,      a__	:				Optional[Any]=True    ,      a__	:				List[Any]=0.0_5    ,      a__	:				Tuple=10    ,      a__	:				str=2    ,      a__	:				int=0.0    ,      a__	:				Optional[Any]=10    ,      a__	:				List[Any]=0    ,      a__	:				Optional[int]="mean"    ,      a__	:				List[str]=False    ,      a__	:				Tuple=False    ,      a__	:				Optional[int]=256    ,      a__	:				str=0    ,      a__	:				List[Any]=1    ,      a__	:				int=2    ,      **a__	:				List[str]    ,      ):





         """simple docstring"""



         super().__init__(**a__    ,      pad_token_id=a__    ,      bos_token_id=a__    ,      eos_token_id=a__				)
         __snake_case								=       hidden_size
         __snake_case								=       feat_extract_norm
         __snake_case								=       feat_extract_activation
         __snake_case								=       list(a__				)
         __snake_case								=       list(a__				)
         __snake_case								=       list(a__				)
         __snake_case								=       conv_bias
         __snake_case								=       num_conv_pos_embeddings
         __snake_case								=       num_conv_pos_embedding_groups
         __snake_case								=       len(self.conv_dim				)
         __snake_case								=       num_hidden_layers
         __snake_case								=       intermediate_size
         __snake_case								=       squeeze_factor
         __snake_case								=       max_position_embeddings
         __snake_case								=       position_buckets
         __snake_case								=       share_att_key
         __snake_case								=       relative_attention
         __snake_case								=       norm_rel_ebd
         __snake_case								=       list(a__				)
         __snake_case								=       hidden_act
         __snake_case								=       num_attention_heads
         __snake_case								=       hidden_dropout
         __snake_case								=       attention_dropout
         __snake_case								=       activation_dropout
         __snake_case								=       feat_proj_dropout
         __snake_case								=       final_dropout
         __snake_case								=       layer_norm_eps
         __snake_case								=       feature_layer_norm_eps
         __snake_case								=       initializer_range
         __snake_case								=       vocab_size

         if (
             (len(self.conv_stride				) != self.num_feat_extract_layers)
             or (len(self.conv_kernel				) != self.num_feat_extract_layers)
             or (len(self.conv_dim				) != self.num_feat_extract_layers)
         ):
            raise ValueError(
                '''Configuration for convolutional layers is incorrect.'''
                '''It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,'''
                f"""but is `len(config.conv_dim) = {len(self.conv_dim				)}`, `len(config.conv_stride)"""
                f"""= {len(self.conv_stride				)}`, `len(config.conv_kernel) = {len(self.conv_kernel				)}`."""				)

         # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
         __snake_case								=       apply_spec_augment
         __snake_case								=       mask_time_prob
         __snake_case								=       mask_time_length
         __snake_case								=       mask_time_min_masks
         __snake_case								=       mask_feature_prob
         __snake_case								=       mask_feature_length
         __snake_case								=       mask_feature_min_masks

         # ctc loss
         __snake_case								=       ctc_loss_reduction
         __snake_case								=       ctc_zero_infinity

         # sequence classification
         __snake_case								=       use_weighted_layer_sum
         __snake_case								=       classifier_proj_size


      @property
      def        a			(self	:				List[Any]				):





         """simple docstring"""



         return functools.reduce(operator.mul    ,      self.conv_stride    ,      1				)

