"""simple docstring"""







import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer
from ...utils import logging


__SCREAMING_SNAKE_CASE								=logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE								="▁"

__SCREAMING_SNAKE_CASE								={"vocab_file": "sentencepiece.bpe.model"}

__SCREAMING_SNAKE_CASE								={
    "vocab_file": {
        "facebook/mbart-large-50-one-to-many-mmt": (
            "https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model"
        ),
    }
}

__SCREAMING_SNAKE_CASE								={
    "facebook/mbart-large-50-one-to-many-mmt": 1024,
}

# fmt: off
__SCREAMING_SNAKE_CASE								=["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN", "af_ZA", "az_AZ", "bn_IN", "fa_IR", "he_IL", "hr_HR", "id_ID", "ka_GE", "km_KH", "mk_MK", "ml_IN", "mn_MN", "mr_IN", "pl_PL", "ps_AF", "pt_XX", "sv_SE", "sw_KE", "ta_IN", "te_IN", "th_TH", "tl_XX", "uk_UA", "ur_PK", "xh_ZA", "gl_ES", "sl_SI"]







class  UpperCamelCase	(    lowercase_						):
   lowercase							=						VOCAB_FILES_NAMES
   lowercase							=						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   lowercase							=						PRETRAINED_VOCAB_FILES_MAP
   lowercase							=						['input_ids', 'attention_mask']

   lowercase							=						[]
   lowercase							=						[]
   def __init__(    self  ,__UpperCamelCase  ,__UpperCamelCase=None  ,__UpperCamelCase=None  ,__UpperCamelCase="</s>"  ,__UpperCamelCase="</s>"  ,__UpperCamelCase="<s>"  ,__UpperCamelCase="<unk>"  ,__UpperCamelCase="<pad>"  ,__UpperCamelCase="<mask>"  ,__UpperCamelCase = None  ,**__UpperCamelCase  ,)			->   None:


        '''simple docstring'''


        lowercase_			:       Union[str, Any]									=			AddedToken(__UpperCamelCase  ,lstrip=__UpperCamelCase  ,rstrip=__UpperCamelCase    ) if isinstance(__UpperCamelCase  ,__UpperCamelCase    ) else mask_token

        lowercase_			:       Dict									=			{} if sp_model_kwargs is None else sp_model_kwargs

        lowercase_			:       Union[str, Any]									=			kwargs.get('additional_special_tokens'  ,[]    )
        kwargs["additional_special_tokens"] += [
            code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"]
        ]

        super().__init__(
            src_lang=__UpperCamelCase  ,tgt_lang=__UpperCamelCase  ,eos_token=__UpperCamelCase  ,unk_token=__UpperCamelCase  ,sep_token=__UpperCamelCase  ,cls_token=__UpperCamelCase  ,pad_token=__UpperCamelCase  ,mask_token=__UpperCamelCase  ,sp_model_kwargs=self.sp_model_kwargs  ,**__UpperCamelCase  ,)

        lowercase_			:       Optional[Any]									=			spm.SentencePieceProcessor(**self.sp_model_kwargs    )
        self.sp_model.Load(str(__UpperCamelCase    )    )
        lowercase_			:       Tuple									=			vocab_file

        # Original fairseq vocab and spm vocab must be "aligned":
        # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
        # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
        # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
        # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

        # Mimic fairseq token-to-id alignment for the first 4 token
        lowercase_			:       Optional[Any]									=			{'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3}

        # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
        lowercase_			:       Any									=			1

        lowercase_			:       Union[str, Any]									=			len(self.sp_model    )
        lowercase_			:       Union[str, Any]									=			{
            code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__UpperCamelCase    )
        }
        lowercase_			:       Optional[int]									=			{v: k for k, v in self.lang_code_to_id.items()}
        lowercase_			:       Tuple									=			len(self.sp_model    ) + len(self.lang_code_to_id    ) + self.fairseq_offset

        self.fairseq_tokens_to_ids.update(self.lang_code_to_id    )
        lowercase_			:       Dict									=			{v: k for k, v in self.fairseq_tokens_to_ids.items()}

        lowercase_			:       Tuple									=			src_lang if src_lang is not None else 'en_XX'
        lowercase_			:       Tuple									=			self.lang_code_to_id[self._src_lang]
        lowercase_			:       Union[str, Any]									=			tgt_lang
        self.set_src_lang_special_tokens(self._src_lang    )
   @property
   def     _UpperCAmelCase     (    self    )			->   int:


        '''simple docstring'''


        return len(self.sp_model    ) + len(self.lang_code_to_id    ) + self.fairseq_offset + 1  # Plus 1 for the mask token
   @property
   def     _UpperCAmelCase     (    self    )			->   str:


        '''simple docstring'''


        return self._src_lang
   @src_lang.setter
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   None:


        '''simple docstring'''


        lowercase_			:       Tuple									=			new_src_lang
        self.set_src_lang_special_tokens(self._src_lang    )
   def __getstate__(    self    )			->   Dict:


        '''simple docstring'''


        lowercase_			:       Optional[int]									=			self.__dict__.copy()
        lowercase_			:       Optional[Any]									=			None
        return state
   def __setstate__(    self  ,__UpperCamelCase    )			->   None:


        '''simple docstring'''


        lowercase_			:       Optional[Any]									=			d

        # for backward compatibility
        if not hasattr(self  ,'sp_model_kwargs'    ):
             lowercase_			:       Optional[int]									=			{}

        lowercase_			:       Tuple									=			spm.SentencePieceProcessor(**self.sp_model_kwargs    )
        self.sp_model.Load(self.vocab_file    )
   def     _UpperCAmelCase     (    self    )			->   Dict:


        '''simple docstring'''


        lowercase_			:       List[Any]									=			{self.convert_ids_to_tokens(__UpperCamelCase    ): i for i in range(self.vocab_size    )}
        vocab.update(self.added_tokens_encoder    )
        return vocab
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   List[str]:


        '''simple docstring'''


        return self.sp_model.encode(__UpperCamelCase  ,out_type=__UpperCamelCase    )
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   int:


        '''simple docstring'''


        if token in self.fairseq_tokens_to_ids:
             return self.fairseq_tokens_to_ids[token]
        lowercase_			:       Optional[Any]									=			self.sp_model.PieceToId(__UpperCamelCase    )

        # Need to return unknown token if the SP model returned 0
        return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   str:


        '''simple docstring'''


        if index in self.fairseq_ids_to_tokens:
             return self.fairseq_ids_to_tokens[index]
        return self.sp_model.IdToPiece(index - self.fairseq_offset    )
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   int:


        '''simple docstring'''


        lowercase_			:       int									=			[]
        lowercase_			:       Union[str, Any]									=			''
        lowercase_			:       Optional[Any]									=			False
        for token in tokens:
             # make sure that special tokens are not decoded using sentencepiece model
             if token in self.all_special_tokens:
                  if not prev_is_special:
                       out_string += " "
                  out_string += self.sp_model.decode(__UpperCamelCase    ) + token
                  lowercase_			:       int									=			True
                  lowercase_			:       str									=			[]
             else:
                  current_sub_tokens.append(__UpperCamelCase    )
                  lowercase_			:       Optional[int]									=			False
        out_string += self.sp_model.decode(__UpperCamelCase    )
        return out_string.strip()
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase = None    )			->   Tuple[str]:


        '''simple docstring'''


        if not os.path.isdir(__UpperCamelCase    ):
             logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''    )
             return
        lowercase_			:       Any									=			os.path.join(
            __UpperCamelCase  ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']    )

        if os.path.abspath(self.vocab_file    ) != os.path.abspath(__UpperCamelCase    ) and os.path.isfile(self.vocab_file    ):
             copyfile(self.vocab_file  ,__UpperCamelCase    )
        elif not os.path.isfile(self.vocab_file    ):
             with open(__UpperCamelCase  ,'wb'    ) as fi:
                  lowercase_			:       Any									=			self.sp_model.serialized_model_proto()
                  fi.write(__UpperCamelCase    )

        return (out_vocab_file,)
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase = None  ,__UpperCamelCase = False    )			->   List[int]:


        '''simple docstring'''


        if already_has_special_tokens:
             return super().get_special_tokens_mask(
                 token_ids_a=__UpperCamelCase  ,token_ids_a=__UpperCamelCase  ,already_has_special_tokens=__UpperCamelCase    )

        lowercase_			:       Optional[int]									=			[1] * len(self.prefix_tokens    )
        lowercase_			:       int									=			[1] * len(self.suffix_tokens    )
        if token_ids_a is None:
             return prefix_ones + ([0] * len(__UpperCamelCase    )) + suffix_ones
        return prefix_ones + ([0] * len(__UpperCamelCase    )) + ([0] * len(__UpperCamelCase    )) + suffix_ones
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase = None    )			->   List[int]:


        '''simple docstring'''


        if token_ids_a is None:
             return self.prefix_tokens + token_ids_a + self.suffix_tokens
        # We don't expect to process pairs, but leave the pair logic for API consistency
        return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase  ,__UpperCamelCase  ,__UpperCamelCase  ,**__UpperCamelCase    )			->   List[str]:


        '''simple docstring'''


        if src_lang is None or tgt_lang is None:
             raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model'    )
        lowercase_			:       Optional[int]									=			src_lang
        lowercase_			:       str									=			self(__UpperCamelCase  ,add_special_tokens=__UpperCamelCase  ,return_tensors=__UpperCamelCase  ,**__UpperCamelCase    )
        lowercase_			:       int									=			self.convert_tokens_to_ids(__UpperCamelCase    )
        lowercase_			:       Union[str, Any]									=			tgt_lang_id
        return inputs
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase = "en_XX"  ,__UpperCamelCase = None  ,__UpperCamelCase = "ro_RO"  ,**__UpperCamelCase  ,)			->   BatchEncoding:


        '''simple docstring'''


        lowercase_			:       List[str]									=			src_lang
        lowercase_			:       List[str]									=			tgt_lang
        return super().prepare_seqaseq_batch(__UpperCamelCase  ,__UpperCamelCase  ,**__UpperCamelCase    )
   def     _UpperCAmelCase     (    self    )			->   Tuple:


        '''simple docstring'''


        return self.set_src_lang_special_tokens(self.src_lang    )
   def     _UpperCAmelCase     (    self    )			->   List[str]:


        '''simple docstring'''


        return self.set_tgt_lang_special_tokens(self.tgt_lang    )
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   None:


        '''simple docstring'''


        lowercase_			:       List[Any]									=			self.lang_code_to_id[src_lang]
        lowercase_			:       int									=			[self.cur_lang_code_id]
        lowercase_			:       List[str]									=			[self.eos_token_id]







   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   None:


        '''simple docstring'''


        lowercase_			:       List[str]									=			self.lang_code_to_id[tgt_lang]
        lowercase_			:       Union[str, Any]									=			[self.cur_lang_code_id]
        lowercase_			:       Union[str, Any]									=			[self.eos_token_id]


"""simple docstring"""







import copy
from typing import Any, Dict, List, Optional, Union

import numpy as np

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


__SCREAMING_SNAKE_CASE								=logging.get_logger(__name__)







class  UpperCamelCase	(    lowercase_						):
   lowercase							=						['input_features']
   def __init__(    self  ,__UpperCamelCase=80  ,__UpperCamelCase=1_6000  ,__UpperCamelCase=160  ,__UpperCamelCase=30  ,__UpperCamelCase=400  ,__UpperCamelCase=0.0  ,__UpperCamelCase=False  ,**__UpperCamelCase  ,)			->   Any:


        '''simple docstring'''


        super().__init__(
            feature_size=__UpperCamelCase  ,sampling_rate=__UpperCamelCase  ,padding_value=__UpperCamelCase  ,return_attention_mask=__UpperCamelCase  ,**__UpperCamelCase  ,)
        lowercase_			:       Dict									=			n_fft
        lowercase_			:       Optional[Any]									=			hop_length
        lowercase_			:       Optional[int]									=			chunk_length
        lowercase_			:       Optional[Any]									=			chunk_length * sampling_rate
        lowercase_			:       Tuple									=			self.n_samples // hop_length
        lowercase_			:       int									=			sampling_rate
        lowercase_			:       int									=			mel_filter_bank(
            num_frequency_bins=1 + n_fft // 2  ,num_mel_filters=__UpperCamelCase  ,min_frequency=0.0  ,max_frequency=8000.0  ,sampling_rate=__UpperCamelCase  ,norm='slaney'  ,mel_scale='slaney'  ,)
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   np.ndarray:


        '''simple docstring'''


        lowercase_			:       Union[str, Any]									=			spectrogram(
            __UpperCamelCase  ,window_function(self.n_fft  ,'hann'    )  ,frame_length=self.n_fft  ,hop_length=self.hop_length  ,power=2.0  ,mel_filters=self.mel_filters  ,log_mel='log10'  ,)
        lowercase_			:       Optional[Any]									=			log_spec[:, :-1]
        lowercase_			:       int									=			np.maximum(__UpperCamelCase  ,log_spec.max() - 8.0    )
        lowercase_			:       List[Any]									=			(log_spec + 4.0) / 4.0
        return log_spec
   @staticmethod
   # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
   def     _UpperCAmelCase     (    __UpperCamelCase  ,__UpperCamelCase  ,__UpperCamelCase = 0.0    )			->   List[np.ndarray]:


        '''simple docstring'''


        if attention_mask is not None:
             lowercase_			:       Optional[int]									=			np.array(__UpperCamelCase  ,np.intaa    )
             lowercase_			:       Optional[Any]									=			[]

             for vector, length in zip(__UpperCamelCase  ,attention_mask.sum(-1    )    ):
                  lowercase_			:       Union[str, Any]									=			(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7    )
                  if length < normed_slice.shape[0]:
                       lowercase_			:       Any									=			padding_value

                  normed_input_values.append(__UpperCamelCase    )
        else:
             lowercase_			:       Optional[int]									=			[(x - x.mean()) / np.sqrt(x.var() + 1e-7    ) for x in input_values]

        return normed_input_values
   def __call__(    self  ,__UpperCamelCase  ,__UpperCamelCase = True  ,__UpperCamelCase = None  ,__UpperCamelCase = None  ,__UpperCamelCase = None  ,__UpperCamelCase = "max_length"  ,__UpperCamelCase = None  ,__UpperCamelCase = None  ,__UpperCamelCase = None  ,**__UpperCamelCase  ,)			->   BatchFeature:


        '''simple docstring'''


        if sampling_rate is not None:
             if sampling_rate != self.sampling_rate:
                  raise ValueError(
                      f'''The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a'''
                      f''' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input'''
                      f''' was sampled 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.'    )

        lowercase_			:       Optional[int]									=			isinstance(__UpperCamelCase  ,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}'''    )
        lowercase_			:       Union[str, Any]									=			is_batched_numpy or (
            isinstance(__UpperCamelCase  ,(list, tuple)    ) and (isinstance(raw_speech[0]  ,(np.ndarray, tuple, list)    ))
        )

        if is_batched:
             lowercase_			:       Union[str, Any]									=			[np.asarray([speech]  ,dtype=np.floataa    ).T for speech in raw_speech]
        elif not is_batched and not isinstance(__UpperCamelCase  ,np.ndarray    ):
             lowercase_			:       Dict									=			np.asarray(__UpperCamelCase  ,dtype=np.floataa    )
        elif isinstance(__UpperCamelCase  ,np.ndarray    ) and raw_speech.dtype is np.dtype(np.floataa    ):
             lowercase_			:       Dict									=			raw_speech.astype(np.floataa    )

        # always return batch
        if not is_batched:
             lowercase_			:       List[Any]									=			[np.asarray([raw_speech]    ).T]

        lowercase_			:       str									=			BatchFeature({'input_features': raw_speech}    )

        # convert into correct format for padding

        lowercase_			:       str									=			self.pad(
            __UpperCamelCase  ,padding=__UpperCamelCase  ,max_length=max_length if max_length else self.n_samples  ,truncation=__UpperCamelCase  ,pad_to_multiple_of=__UpperCamelCase  ,return_attention_mask=return_attention_mask or do_normalize  ,)

        # zero-mean and unit-variance normalization
        if do_normalize:
             lowercase_			:       int									=			self.zero_mean_unit_var_norm(
                 padded_inputs['input_features']  ,attention_mask=padded_inputs['attention_mask']  ,padding_value=self.padding_value  ,)
             lowercase_			:       Tuple									=			np.stack(padded_inputs['input_features']  ,axis=0    )

        # make sure list is in array format
        lowercase_			:       Dict									=			padded_inputs.get('input_features'    ).transpose(2  ,0  ,1    )

        lowercase_			:       List[str]									=			[self._np_extract_fbank_features(__UpperCamelCase    ) for waveform in input_features[0]]

        if isinstance(input_features[0]  ,__UpperCamelCase    ):
             lowercase_			:       Optional[Any]									=			[np.asarray(__UpperCamelCase  ,dtype=np.floataa    ) for feature in input_features]
        else:
             lowercase_			:       str									=			input_features

        if return_attention_mask:
             # rescale from sample (48000) to feature (3000)
             lowercase_			:       str									=			padded_inputs['attention_mask'][:, :: self.hop_length]

        if return_tensors is not None:
             lowercase_			:       Union[str, Any]									=			padded_inputs.convert_to_tensors(__UpperCamelCase    )

        return padded_inputs







   def     _UpperCAmelCase     (    self    )			->   Dict[str, Any]:


        '''simple docstring'''


        lowercase_			:       Dict									=			copy.deepcopy(self.__dict__    )
        lowercase_			:       Union[str, Any]									=			self.__class__.__name__
        if "mel_filters" in output:
             del output["mel_filters"]
        return output

