

'''simple docstring'''



from math import ceil
from typing import List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor
from ...utils import TensorType, logging


_UpperCamelCase						:  Union[str, Any]							       =				logging.get_logger(__name__)



class 				_snake_case					(   __A			):
  SCREAMING_SNAKE_CASE			:       Dict				=     ['audio_values', 'audio_mask']

  def __init__(				self      , _SCREAMING_SNAKE_CASE=20_48      , _SCREAMING_SNAKE_CASE=1      , _SCREAMING_SNAKE_CASE=[16, 16]      , _SCREAMING_SNAKE_CASE=1_28      , _SCREAMING_SNAKE_CASE=4_41_00      , _SCREAMING_SNAKE_CASE=86      , _SCREAMING_SNAKE_CASE=20_48      , _SCREAMING_SNAKE_CASE=0.0      , **_SCREAMING_SNAKE_CASE      , ):





      '''simple docstring'''

      super().__init__(
          feature_size=snake_case_      , sampling_rate=snake_case_      , padding_value=snake_case_      , **snake_case_      , )

      lowerCAmelCase 						=							spectrogram_length
      lowerCAmelCase 						=							num_channels
      lowerCAmelCase 						=							patch_size
      lowerCAmelCase 						=							feature_size // self.patch_size[1]
      lowerCAmelCase 						=							n_fft
      lowerCAmelCase 						=							sampling_rate // hop_length_to_sampling_rate
      lowerCAmelCase 						=							sampling_rate
      lowerCAmelCase 						=							padding_value
      lowerCAmelCase 						=							mel_filter_bank(
          num_frequency_bins=1 + n_fft // 2      , num_mel_filters=snake_case_      , min_frequency=0.0      , max_frequency=2_20_50.0      , sampling_rate=snake_case_      , norm='slaney'      , mel_scale='slaney'      , ).T

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							spectrogram(
          snake_case_      , window_function(self.n_fft      , 'hann'	)      , frame_length=self.n_fft      , hop_length=self.hop_length      , power=2.0      , mel_filters=self.mel_filters.T      , log_mel='dB'      , db_range=80.0      , )
      lowerCAmelCase 						=							log_spec[:, :-1]
      lowerCAmelCase 						=							log_spec - 20.0
      lowerCAmelCase 						=							np.clip(log_spec / 40.0      , -2.0      , 0.0	) + 1.0
      return log_spec


  def __call__(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE = None      , _SCREAMING_SNAKE_CASE = True      , _SCREAMING_SNAKE_CASE = None      , _SCREAMING_SNAKE_CASE = False      , _SCREAMING_SNAKE_CASE = False      , **_SCREAMING_SNAKE_CASE      , ):





      '''simple docstring'''

      if sampling_rate is not None:
          if sampling_rate != self.sampling_rate:
              raise ValueError(
                  'This feature extractor is set to support sampling rate'
                  F' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled'
                  F' with {self.sampling_rate} and not {sampling_rate}.'	)
      else:
          logger.warning(
              'It is strongly recommended to pass the `sampling_rate` argument to this function. '
              'Failing to do so can result in silent errors that might be hard to debug.'	)

      lowerCAmelCase 						=							isinstance(snake_case_      , np.ndarray	) and len(raw_speech.shape	) > 1
      if is_batched_numpy and len(raw_speech.shape	) > 2:
          raise ValueError(F'Only mono-channel audio is supported for input to {self}'	)
      lowerCAmelCase 						=							is_batched_numpy or (
          isinstance(snake_case_      , (list, tuple)	) and (isinstance(raw_speech[0]      , (np.ndarray, tuple, list)	))
      )
      if is_batched:
          lowerCAmelCase 						=							[np.asarray([speech]      , dtype=np.floataa	).T for speech in raw_speech]
      elif not is_batched and not isinstance(snake_case_      , np.ndarray	):
          lowerCAmelCase 						=							np.asarray(snake_case_      , dtype=np.floataa	)
      elif isinstance(snake_case_      , np.ndarray	) and raw_speech.dtype is np.dtype(np.floataa	):
          lowerCAmelCase 						=							raw_speech.astype(np.floataa	)
      # always return batch
      if not is_batched:
          lowerCAmelCase 						=							[np.asarray([raw_speech]	).T]

      # Convert audio signals to log mel spectrograms, truncate by time axis
      lowerCAmelCase 						=							[
          self._np_extract_fbank_features(waveform.squeeze()	).T[: self.spectrogram_length] for waveform in raw_speech
      ]
      if isinstance(audio_features[0]      , snake_case_	):
          lowerCAmelCase 						=							[np.asarray(snake_case_      , dtype=np.floataa	) for feature in audio_features]

      # Create audio attention mask
      lowerCAmelCase 						=							max(
          [ceil(feature.shape[0] / self.patch_size[0]	) * self.freq_len for feature in audio_features]	)  # The maximum number of audio patches in a batch
      if return_attention_mask:
          lowerCAmelCase 						=							[
              (ceil(feature.shape[0] / self.patch_size[0]	) * self.freq_len) * [1]
              + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]	) * self.freq_len) * [0]
              for feature in audio_features
          ]
          lowerCAmelCase 						=							np.array(snake_case_	).astype(np.floataa	)

      # convert into correct format for padding
      lowerCAmelCase 						=							max_patch_len // self.freq_len * self.patch_size[0]  # The maximum audio size in a batch
      lowerCAmelCase 						=							np.ones([len(snake_case_	), 1, max_time_len, self.feature_size]	).astype(np.floataa	)
      lowerCAmelCase 						=							padded_audio_features * self.padding_value
      for i in range(len(snake_case_	)	):
          lowerCAmelCase 						=							audio_features[i]
          lowerCAmelCase 						=							feature

      # return as BatchFeature
      if return_attention_mask:
          lowerCAmelCase 						=							{"""audio_values""": padded_audio_features, """audio_mask""": audio_mask}
      else:
          lowerCAmelCase 						=							{"""audio_values""": padded_audio_features}

      lowerCAmelCase 						=							BatchFeature(data=snake_case_      , tensor_type=snake_case_	)
      return encoded_inputs






"""simple docstring"""



import functools
import operator

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


_UpperCamelCase								=		logging.get_logger(__name__)

_UpperCamelCase								=		{
    "asapp/sew-tiny-100k": "https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json",
    # See all SEW models at https://huggingface.co/models?filter=sew
}
class 						__UpperCAmelCase    (__A     ):







			'''simple docstring'''
			_UpperCamelCase  :						Dict					     =				'sew'





			def __init__(			self   ,      snake_case_=32   ,      snake_case_=768   ,      snake_case_=12   ,      snake_case_=12   ,      snake_case_=3_072   ,      snake_case_=2   ,      snake_case_="gelu"   ,      snake_case_=0.1   ,      snake_case_=0.1   ,      snake_case_=0.1   ,      snake_case_=0.0   ,      snake_case_=0.1   ,      snake_case_=0.1   ,      snake_case_=0.02   ,      snake_case_=1E-5   ,      snake_case_="group"   ,      snake_case_="gelu"   ,      snake_case_=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)   ,      snake_case_=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)   ,      snake_case_=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)   ,      snake_case_=False   ,      snake_case_=128   ,      snake_case_=16   ,      snake_case_=True   ,      snake_case_=0.05   ,      snake_case_=10   ,      snake_case_=2   ,      snake_case_=0.0   ,      snake_case_=10   ,      snake_case_=0   ,      snake_case_="mean"   ,      snake_case_=False   ,      snake_case_=False   ,      snake_case_=256   ,      snake_case_=0   ,      snake_case_=1   ,      snake_case_=2   ,      **snake_case_   ,      ):







										'''simple docstring'''


										super().__init__(**snake_case_   ,      pad_token_id=snake_case_   ,      bos_token_id=snake_case_   ,      eos_token_id=snake_case_							)
										A__       :     Dict								=			hidden_size
										A__       :     Dict								=			feat_extract_norm
										A__       :     str								=			feat_extract_activation
										A__       :     Optional[Any]								=			list(snake_case_							)
										A__       :     str								=			list(snake_case_							)
										A__       :     Any								=			list(snake_case_							)
										A__       :     Any								=			conv_bias
										A__       :     Any								=			num_conv_pos_embeddings
										A__       :     Any								=			num_conv_pos_embedding_groups
										A__       :     str								=			len(self.conv_dim							)
										A__       :     Tuple								=			num_hidden_layers
										A__       :     int								=			intermediate_size
										A__       :     Union[str, Any]								=			squeeze_factor
										A__       :     Union[str, Any]								=			hidden_act
										A__       :     List[str]								=			num_attention_heads
										A__       :     List[str]								=			hidden_dropout
										A__       :     Dict								=			attention_dropout
										A__       :     Tuple								=			activation_dropout
										A__       :     Optional[int]								=			feat_proj_dropout
										A__       :     Optional[Any]								=			final_dropout
										A__       :     int								=			layerdrop
										A__       :     List[Any]								=			layer_norm_eps
										A__       :     int								=			initializer_range
										A__       :     Dict								=			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
										A__       :     Optional[Any]								=			apply_spec_augment
										A__       :     int								=			mask_time_prob
										A__       :     Tuple								=			mask_time_length
										A__       :     Optional[Any]								=			mask_time_min_masks
										A__       :     Any								=			mask_feature_prob
										A__       :     List[Any]								=			mask_feature_length
										A__       :     Any								=			mask_feature_min_masks

										# ctc loss
										A__       :     str								=			ctc_loss_reduction
										A__       :     List[Any]								=			ctc_zero_infinity

										# sequence classification
										A__       :     Union[str, Any]								=			use_weighted_layer_sum
										A__       :     str								=			classifier_proj_size





			@property
			def 		lowerCamelCase					(			self							):







										'''simple docstring'''


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





