
'''simple docstring'''






from typing import List, Optional, Union

import numpy as np

from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging


UpperCAmelCase_							: str =							logging.get_logger(__name__)

class 			UpperCAmelCase__    (							A			):
    lowerCAmelCase_					     =		['input_features', 'attention_mask']



    def __init__(						self   :							Any,__A   :							List[Any]=8_0,__A   :							Dict=1_6_0_0_0,__A   :							Tuple=0.0,__A   :							Dict=1_0,__A   :							int=2_5,__A   :							Union[str, Any]="hamming_window",__A   :							List[str]=32768.0,__A   :							Union[str, Any]=0.97,__A   :							str=1.0,__A   :							Union[str, Any]=True,__A   :							Tuple=True,__A   :							Optional[Any]=False,**__A   :							Optional[Any],):
          super().__init__(feature_size=__A,sampling_rate=__A,padding_value=__A,**__A  )

          _lowerCamelCase					: Dict		    = feature_size
          _lowerCamelCase					: List[str]		    = sampling_rate
          _lowerCamelCase					: Any		    = padding_value
          _lowerCamelCase					: Dict		    = hop_length
          _lowerCamelCase					: Tuple		    = win_length
          _lowerCamelCase					: str		    = frame_signal_scale
          _lowerCamelCase					: List[str]		    = preemphasis_coeff
          _lowerCamelCase					: List[str]		    = mel_floor
          _lowerCamelCase					: str		    = normalize_means
          _lowerCamelCase					: Any		    = normalize_vars
          _lowerCamelCase					: List[str]		    = win_function
          _lowerCamelCase					: Tuple		    = return_attention_mask

          _lowerCamelCase					: List[Any]		    = win_length * sampling_rate // 1_0_0_0
          _lowerCamelCase					: List[Any]		    = hop_length * sampling_rate // 1_0_0_0

          _lowerCamelCase					: Any		    = optimal_fft_length(self.sample_size  )
          _lowerCamelCase					: Dict		    = (self.n_fft // 2) + 1



    def 	lowerCamelCase_	(						self   :							Any,__A   :							np.array  ):
          if self.win_function == "hamming_window":
                _lowerCamelCase					: Any		    = window_function(window_length=self.sample_size,name=self.win_function,periodic=__A  )
          else:
                _lowerCamelCase					: Optional[int]		    = window_function(window_length=self.sample_size,name=self.win_function  )

          _lowerCamelCase					: int		    = mel_filter_bank(
              num_frequency_bins=self.n_freqs,num_mel_filters=self.feature_size,min_frequency=0.0,max_frequency=self.sampling_rate / 2.0,sampling_rate=self.sampling_rate,)

          _lowerCamelCase					: List[str]		    = spectrogram(
              one_waveform * self.frame_signal_scale,window=__A,frame_length=self.sample_size,hop_length=self.sample_stride,fft_length=self.n_fft,center=__A,preemphasis=self.preemphasis_coeff,mel_filters=__A,mel_floor=self.mel_floor,log_mel="log",)
          return msfc_features.T



    def 	lowerCamelCase_	(						self   :							Optional[int],__A   :							List[str],__A   :							Dict,__A   :							int  ):
          # make sure we normalize float32 arrays
          if self.normalize_means:
                _lowerCamelCase					: Optional[Any]		    = x[:input_length].mean(axis=0  )
                _lowerCamelCase					: Optional[int]		    = np.subtract(__A,__A  )
          if self.normalize_vars:
                _lowerCamelCase					: int		    = x[:input_length].std(axis=0  )
                _lowerCamelCase					: Any		    = np.divide(__A,__A  )

          if input_length < x.shape[0]:
                _lowerCamelCase					: Tuple		    = padding_value

          # make sure array is in float32
          _lowerCamelCase					: Optional[int]		    = x.astype(np.floataa  )

          return x



    def 	lowerCamelCase_	(						self   :							Any,__A   :							List[np.ndarray],__A   :							Optional[np.ndarray] = None  ):
          _lowerCamelCase					: Optional[int]		    = attention_mask.sum(-1  ) if attention_mask is not None else [x.shape[0] for x in input_features]
          return [self._normalize_one(__A,__A,self.padding_value  ) for x, n in zip(__A,__A  )]



    def __call__(						self   :							Optional[Any],__A   :							Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]],__A   :							Union[bool, str, PaddingStrategy] = False,__A   :							Optional[int] = None,__A   :							bool = False,__A   :							Optional[int] = None,__A   :							Optional[bool] = None,__A   :							Optional[Union[str, TensorType]] = None,__A   :							Optional[int] = None,**__A   :							Optional[Any],):

          if sampling_rate is not None:
                if sampling_rate != self.sampling_rate:
                      raise ValueError(
                          f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of'
                          f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with'
                          f' {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					: List[str]		    = isinstance(__A,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					: List[str]		    = is_batched_numpy or (
              isinstance(__A,(list, tuple)  ) and (isinstance(raw_speech[0],(np.ndarray, tuple, list)  ))
          )

          if is_batched:
                _lowerCamelCase					: List[Any]		    = [np.asarray(__A,dtype=np.floataa  ) for speech in raw_speech]
          elif not is_batched and not isinstance(__A,np.ndarray  ):
                _lowerCamelCase					: Dict		    = np.asarray(__A,dtype=np.floataa  )
          elif isinstance(__A,np.ndarray  ) and raw_speech.dtype is np.dtype(np.floataa  ):
                _lowerCamelCase					: Tuple		    = raw_speech.astype(np.floataa  )

          # always return batch
          if not is_batched:
                _lowerCamelCase					: Tuple		    = [raw_speech]

          # extract fbank features
          _lowerCamelCase					: str		    = [self._extract_mfsc_features(__A  ) for one_waveform in raw_speech]

          # convert into correct format for padding
          _lowerCamelCase					: Union[str, Any]		    = BatchFeature({"input_features": features}  )

          _lowerCamelCase					: List[Any]		    = self.pad(
              __A,padding=__A,max_length=__A,truncation=__A,pad_to_multiple_of=__A,return_attention_mask=__A,**__A,)
          # make sure list is in array format
          _lowerCamelCase					: Optional[Any]		    = padded_inputs.get("input_features"  )
          if isinstance(input_features[0],__A  ):
                _lowerCamelCase					: int		    = [np.asarray(__A,dtype=np.floataa  ) for feature in input_features]

          _lowerCamelCase					: Dict		    = padded_inputs.get("attention_mask"  )
          if attention_mask is not None:
                _lowerCamelCase					: Dict		    = [np.asarray(__A,dtype=np.intaa  ) for array in attention_mask]

          if self.normalize_means or self.normalize_vars:
                _lowerCamelCase					: Dict		    = (
                    np.array(__A,dtype=np.intaa  )
                    if self._get_padding_strategies(__A,max_length=__A  ) is not PaddingStrategy.DO_NOT_PAD
                    and padding
                    else None
                )
                _lowerCamelCase					: Tuple		    = self.normalize(
                    padded_inputs["input_features"],attention_mask=__A  )

          if return_tensors is not None:
                _lowerCamelCase					: Dict		    = padded_inputs.convert_to_tensors(__A  )

          return padded_inputs

"""simple docstring"""






import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_funnel import FunnelTokenizer


__SCREAMING_SNAKE_CASE							=     logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE							=     {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'}

__SCREAMING_SNAKE_CASE							=     [
    'small',
    'small-base',
    'medium',
    'medium-base',
    'intermediate',
    'intermediate-base',
    'large',
    'large-base',
    'xlarge',
    'xlarge-base',
]

__SCREAMING_SNAKE_CASE							=     {
    'vocab_file': {
        'funnel-transformer/small': 'https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt',
        'funnel-transformer/small-base': 'https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt',
        'funnel-transformer/medium': 'https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt',
        'funnel-transformer/medium-base': (
            'https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt'
        ),
        'funnel-transformer/intermediate': (
            'https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt'
        ),
        'funnel-transformer/intermediate-base': (
            'https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt'
        ),
        'funnel-transformer/large': 'https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt',
        'funnel-transformer/large-base': 'https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt',
        'funnel-transformer/xlarge': 'https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt',
        'funnel-transformer/xlarge-base': (
            'https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt'
        ),
    },
    'tokenizer_file': {
        'funnel-transformer/small': 'https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json',
        'funnel-transformer/small-base': (
            'https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json'
        ),
        'funnel-transformer/medium': 'https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json',
        'funnel-transformer/medium-base': (
            'https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json'
        ),
        'funnel-transformer/intermediate': (
            'https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json'
        ),
        'funnel-transformer/intermediate-base': (
            'https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json'
        ),
        'funnel-transformer/large': 'https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json',
        'funnel-transformer/large-base': (
            'https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json'
        ),
        'funnel-transformer/xlarge': 'https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json',
        'funnel-transformer/xlarge-base': (
            'https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json'
        ),
    },
}
__SCREAMING_SNAKE_CASE							=     {F"""funnel-transformer/{name}""": 512 for name in _model_names}
__SCREAMING_SNAKE_CASE							=     {F"""funnel-transformer/{name}""": {'do_lower_case': True} for name in _model_names}





class 				a__					(						A__       ):
     UpperCAmelCase__         =      VOCAB_FILES_NAMES
     UpperCAmelCase__         =      PRETRAINED_VOCAB_FILES_MAP
     UpperCAmelCase__         =      PRETRAINED_INIT_CONFIGURATION
     UpperCAmelCase__         =      FunnelTokenizer
     UpperCAmelCase__         =      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     UpperCAmelCase__         =      2



     def __init__(							self :str      ,  _lowerCamelCase :int=None      ,  _lowerCamelCase :List[Any]=None      ,  _lowerCamelCase :Dict=True      ,  _lowerCamelCase :Optional[Any]="<unk>"      ,  _lowerCamelCase :Optional[Any]="<sep>"      ,  _lowerCamelCase :List[Any]="<pad>"      ,  _lowerCamelCase :List[Any]="<cls>"      ,  _lowerCamelCase :Union[str, Any]="<mask>"      ,  _lowerCamelCase :Any="<s>"      ,  _lowerCamelCase :Union[str, Any]="</s>"      ,  _lowerCamelCase :str=True      ,  _lowerCamelCase :Dict=True      ,  _lowerCamelCase :Tuple=None      ,  _lowerCamelCase :Tuple="##"      ,  **_lowerCamelCase :int      ,  ):







      '''simple docstring'''



      super().__init__(
          _lowerCamelCase      ,  tokenizer_file=_lowerCamelCase      ,  do_lower_case=_lowerCamelCase      ,  unk_token=_lowerCamelCase      ,  sep_token=_lowerCamelCase      ,  pad_token=_lowerCamelCase      ,  cls_token=_lowerCamelCase      ,  mask_token=_lowerCamelCase      ,  bos_token=_lowerCamelCase      ,  eos_token=_lowerCamelCase      ,  clean_text=_lowerCamelCase      ,  tokenize_chinese_chars=_lowerCamelCase      ,  strip_accents=_lowerCamelCase      ,  wordpieces_prefix=_lowerCamelCase      ,  **_lowerCamelCase      ,  )

      UpperCamelCase_     :					str   	=json.loads(self.backend_tokenizer.normalizer.__getstate__()   )
      if (
          normalizer_state.get('lowercase'      ,  _lowerCamelCase   ) != do_lower_case
          or normalizer_state.get('strip_accents'      ,  _lowerCamelCase   ) != strip_accents
          or normalizer_state.get('handle_chinese_chars'      ,  _lowerCamelCase   ) != tokenize_chinese_chars
      ):
       UpperCamelCase_     :					int   	=getattr(_lowerCamelCase      ,  normalizer_state.pop('type'   )   )
       UpperCamelCase_     :					Dict   	=do_lower_case
       UpperCamelCase_     :					Tuple   	=strip_accents
       UpperCamelCase_     :					int   	=tokenize_chinese_chars
       UpperCamelCase_     :					Tuple   	=normalizer_class(**_lowerCamelCase   )

      UpperCamelCase_     :					Dict   	=do_lower_case



     def  lowerCamelCase_						(							self :Optional[int]      ,  _lowerCamelCase :str      ,  _lowerCamelCase :Optional[int]=None   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[Any]   	=[self.cls_token_id] + token_ids_a + [self.sep_token_id]

      if token_ids_a:
       output += token_ids_a + [self.sep_token_id]

      return output



     def  lowerCamelCase_						(							self :List[Any]      ,  _lowerCamelCase :List[int]      ,  _lowerCamelCase :Optional[List[int]] = None   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[int]   	=[self.sep_token_id]
      UpperCamelCase_     :					List[Any]   	=[self.cls_token_id]
      if token_ids_a is None:
       return len(cls   ) * [self.cls_token_type_id] + len(token_ids_a + sep   ) * [0]
      return len(cls   ) * [self.cls_token_type_id] + len(token_ids_a + sep   ) * [0] + len(token_ids_a + sep   ) * [1]




     def  lowerCamelCase_						(							self :Optional[Any]      ,  _lowerCamelCase :str      ,  _lowerCamelCase :Optional[str] = None   ):







      '''simple docstring'''



      UpperCamelCase_     :					int   	=self._tokenizer.model.save(_lowerCamelCase      ,  name=_lowerCamelCase   )
      return tuple(_lowerCamelCase   )
