




"""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


a_	   =    logging.get_logger(__name__)

class    UpperCAmelCase_  (       lowerCAmelCase_						):
		UpperCamelCase						 =["input_features", "attention_mask"]
		def __init__(		self							,		UpperCamelCase_=80							,		UpperCamelCase_=1_60_00							,		UpperCamelCase_=0.0							,		UpperCamelCase_=10							,		UpperCamelCase_=25							,		UpperCamelCase_="hamming_window"							,		UpperCamelCase_=3_27_68.0							,		UpperCamelCase_=0.9_7							,		UpperCamelCase_=1.0							,		UpperCamelCase_=True							,		UpperCamelCase_=True							,		UpperCamelCase_=False							,		**UpperCamelCase_							,		)		->    Optional[int]:
					super().__init__(feature_size=UpperCamelCase_							,		sampling_rate=UpperCamelCase_							,		padding_value=UpperCamelCase_							,		**UpperCamelCase_    )

					__lowercase       :   Dict        =    feature_size
					__lowercase       :   int        =    sampling_rate
					__lowercase       :   Optional[int]        =    padding_value
					__lowercase       :   Dict        =    hop_length
					__lowercase       :   Tuple        =    win_length
					__lowercase       :   Tuple        =    frame_signal_scale
					__lowercase       :   int        =    preemphasis_coeff
					__lowercase       :   int        =    mel_floor
					__lowercase       :   List[Any]        =    normalize_means
					__lowercase       :   Union[str, Any]        =    normalize_vars
					__lowercase       :   Optional[int]        =    win_function
					__lowercase       :   str        =    return_attention_mask

					__lowercase       :   str        =    win_length * sampling_rate // 10_00
					__lowercase       :   Dict        =    hop_length * sampling_rate // 10_00

					__lowercase       :   Dict        =    optimal_fft_length(self.sample_size    )
					__lowercase       :   List[Any]        =    (self.n_fft // 2) + 1
		def      _lowerCamelCase				(		self							,		UpperCamelCase_    )		->    np.ndarray:
					if self.win_function == "hamming_window":
								__lowercase       :   List[Any]        =    window_function(window_length=self.sample_size							,		name=self.win_function							,		periodic=UpperCamelCase_    )
					else:
								__lowercase       :   int        =    window_function(window_length=self.sample_size							,		name=self.win_function    )

					__lowercase       :   Dict        =    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							,		)

					__lowercase       :   Dict        =    spectrogram(
					    one_waveform * self.frame_signal_scale							,		window=UpperCamelCase_							,		frame_length=self.sample_size							,		hop_length=self.sample_stride							,		fft_length=self.n_fft							,		center=UpperCamelCase_							,		preemphasis=self.preemphasis_coeff							,		mel_filters=UpperCamelCase_							,		mel_floor=self.mel_floor							,		log_mel='''log'''							,		)
					return msfc_features.T
		def      _lowerCamelCase				(		self							,		UpperCamelCase_							,		UpperCamelCase_							,		UpperCamelCase_    )		->    List[Any]:
					# make sure we normalize float32 arrays
					if self.normalize_means:
								__lowercase       :   Union[str, Any]        =    x[:input_length].mean(axis=0    )
								__lowercase       :   Any        =    np.subtract(UpperCamelCase_							,		UpperCamelCase_    )
					if self.normalize_vars:
								__lowercase       :   List[Any]        =    x[:input_length].std(axis=0    )
								__lowercase       :   Optional[int]        =    np.divide(UpperCamelCase_							,		UpperCamelCase_    )

					if input_length < x.shape[0]:
								__lowercase       :   Optional[Any]        =    padding_value

					# make sure array is in float32
					__lowercase       :   Union[str, Any]        =    x.astype(np.floataa    )

					return x
		def      _lowerCamelCase				(		self							,		UpperCamelCase_							,		UpperCamelCase_ = None    )		->    List[np.ndarray]:
					__lowercase       :   Union[str, Any]        =    attention_mask.sum(-1    ) if attention_mask is not None else [x.shape[0] for x in input_features]
					return [self._normalize_one(UpperCamelCase_							,		UpperCamelCase_							,		self.padding_value    ) for x, n in zip(UpperCamelCase_							,		UpperCamelCase_    )]
		def __call__(		self							,		UpperCamelCase_							,		UpperCamelCase_ = False							,		UpperCamelCase_ = None							,		UpperCamelCase_ = False							,		UpperCamelCase_ = None							,		UpperCamelCase_ = None							,		UpperCamelCase_ = None							,		UpperCamelCase_ = None							,		**UpperCamelCase_							,		)		->    BatchFeature:

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

					__lowercase       :   Any        =    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       :   Optional[int]        =    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(UpperCamelCase_							,		dtype=np.floataa    ) for speech in raw_speech]
					elif not is_batched and not isinstance(UpperCamelCase_							,		np.ndarray    ):
								__lowercase       :   str        =    np.asarray(UpperCamelCase_							,		dtype=np.floataa    )
					elif isinstance(UpperCamelCase_							,		np.ndarray    ) and raw_speech.dtype is np.dtype(np.floataa    ):
								__lowercase       :   List[str]        =    raw_speech.astype(np.floataa    )

					# always return batch
					if not is_batched:
								__lowercase       :   Dict        =    [raw_speech]

					# extract fbank features
					__lowercase       :   Dict        =    [self._extract_mfsc_features(UpperCamelCase_    ) for one_waveform in raw_speech]

					# convert into correct format for padding
					__lowercase       :   List[str]        =    BatchFeature({'''input_features''': features}    )

					__lowercase       :   Dict        =    self.pad(
					    UpperCamelCase_							,		padding=UpperCamelCase_							,		max_length=UpperCamelCase_							,		truncation=UpperCamelCase_							,		pad_to_multiple_of=UpperCamelCase_							,		return_attention_mask=UpperCamelCase_							,		**UpperCamelCase_							,		)
					# make sure list is in array format
					__lowercase       :   Dict        =    padded_inputs.get('''input_features'''    )
					if isinstance(input_features[0]							,		UpperCamelCase_    ):
								__lowercase       :   Tuple        =    [np.asarray(UpperCamelCase_							,		dtype=np.floataa    ) for feature in input_features]

					__lowercase       :   Tuple        =    padded_inputs.get('''attention_mask'''    )
					if attention_mask is not None:
								__lowercase       :   str        =    [np.asarray(UpperCamelCase_							,		dtype=np.intaa    ) for array in attention_mask]

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

					if return_tensors is not None:
								__lowercase       :   Dict        =    padded_inputs.convert_to_tensors(UpperCamelCase_    )

					return padded_inputs








"""simple docstring"""






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

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_lowercase : Optional[int]      						=						"▁"

_lowercase : Optional[Any]      						=						{"vocab_file": "spiece.model"}

_lowercase : Optional[Any]      						=						{
    "vocab_file": {"google/pegasus-xsum": "https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model"}
}

_lowercase : Tuple      						=						{
    "google/pegasus-xsum": 5_1_2,
}


_lowercase : Optional[int]      						=						logging.get_logger(__name__)

class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					_a   			=							VOCAB_FILES_NAMES

					_a   			=							VOCAB_FILES_NAMES
					_a   			=							PRETRAINED_VOCAB_FILES_MAP
					_a   			=							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					_a   			=							['input_ids', 'attention_mask']



					def __init__(       self							:  Any,  lowerCamelCase							:  Optional[Any],  lowerCamelCase							:  Any="<pad>",  lowerCamelCase							:  Optional[Any]="</s>",  lowerCamelCase							:  Any="<unk>",  lowerCamelCase							:  Tuple="<mask_2>",  lowerCamelCase							:  int="<mask_1>",  lowerCamelCase							:  Optional[Any]=None,  lowerCamelCase							:  Dict=103,  lowerCamelCase							:  Optional[Dict[str, Any]] = None,  **lowerCamelCase							:  Optional[int],  )->					None:
								lowerCamelCase__		:		Union[str, Any]			=offset
								if additional_special_tokens is not None:
											if not isinstance(lowerCamelCase,  lowerCamelCase     ):
														raise TypeError(
														    F'''additional_special_tokens should be of type {type(lowerCamelCase     )}, but is'''
														    F''' {type(lowerCamelCase     )}'''     )

											lowerCamelCase__		:		Any			=(
											    ([mask_token_sent] + additional_special_tokens)
											    if mask_token_sent not in additional_special_tokens and mask_token_sent is not None
											    else additional_special_tokens
											)
											# fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken
											additional_special_tokens_extended += [
											    F'''<unk_{i}>''' for i in range(len(lowerCamelCase     ),  self.offset - 1     )
											]

											if len(set(lowerCamelCase     )     ) != len(lowerCamelCase     ):
														raise ValueError(
														    '''Please make sure that the provided additional_special_tokens do not contain an incorrectly'''
														    F''' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.'''     )
											lowerCamelCase__		:		Optional[Any]			=additional_special_tokens_extended
								else:
											lowerCamelCase__		:		Tuple			=[mask_token_sent] if mask_token_sent is not None else []
											additional_special_tokens += [F'''<unk_{i}>''' for i in range(2,  self.offset     )]

								lowerCamelCase__		:		Tuple			={} if sp_model_kwargs is None else sp_model_kwargs

								super().__init__(
								    eos_token=lowerCamelCase,  unk_token=lowerCamelCase,  mask_token=lowerCamelCase,  pad_token=lowerCamelCase,  mask_token_sent=lowerCamelCase,  offset=lowerCamelCase,  additional_special_tokens=lowerCamelCase,  sp_model_kwargs=self.sp_model_kwargs,  **lowerCamelCase,  )
								lowerCamelCase__		:		Optional[int]			=mask_token_sent
								lowerCamelCase__		:		Optional[Any]			=vocab_file
								lowerCamelCase__		:		List[str]			=spm.SentencePieceProcessor(**self.sp_model_kwargs     )
								self.sp_model.Load(lowerCamelCase     )

								# add special tokens to encoder dict
								lowerCamelCase__		:		Dict[int, str]			={
								    0: self.pad_token,
								    1: self.eos_token,
								}

								if self.mask_token_sent is not None:
											self.encoder.update(
											    {
											        2: self.mask_token_sent,
											        3: self.mask_token,
											    }     )

								if self.offset > 0:
											# entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102
											# mask_token_sent is already added to list -> so start at 1
											self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1,  self.offset - 1     )}     )

								lowerCamelCase__		:		Dict[str, int]			={v: k for k, v in self.encoder.items()}



					@property
					def 		snake_case       (       self							:  Union[str, Any]     )->					int:
								return len(self.sp_model     ) + self.offset



					def 		snake_case       (       self							:  Optional[Any]     )->					Dict[str, int]:
								lowerCamelCase__		:		List[Any]			={self.convert_ids_to_tokens(lowerCamelCase     ): i for i in range(self.vocab_size     )}
								vocab.update(self.added_tokens_encoder     )
								return vocab



					def __getstate__(       self							:  str     )->					List[Any]:
								lowerCamelCase__		:		Optional[Any]			=self.__dict__.copy()
								lowerCamelCase__		:		Optional[int]			=None
								return state



					def __setstate__(       self							:  Dict,  lowerCamelCase							:  int     )->					Optional[Any]:
								lowerCamelCase__		:		Optional[int]			=d

								# for backward compatibility
								if not hasattr(self,  '''sp_model_kwargs'''     ):
											lowerCamelCase__		:		str			={}

								lowerCamelCase__		:		Union[str, Any]			=spm.SentencePieceProcessor(**self.sp_model_kwargs     )
								self.sp_model.Load(self.vocab_file     )



					def 		snake_case       (       self							:  Any,  lowerCamelCase							:  str     )->					List[str]:
								return self.sp_model.encode(lowerCamelCase,  out_type=lowerCamelCase     )



					def 		snake_case       (       self							:  int,  lowerCamelCase							:  str     )->					int:
								if token in self.decoder:
											return self.decoder[token]
								elif token in self.added_tokens_decoder:
											return self.added_tokens_decoder[token]
								lowerCamelCase__		:		Any			=self.sp_model.piece_to_id(lowerCamelCase     )
								return sp_id + self.offset



					def 		snake_case       (       self							:  Tuple,  lowerCamelCase							:  int     )->					str:
								if index in self.encoder:
											return self.encoder[index]
								elif index in self.added_tokens_encoder:
											return self.added_tokens_encoder[index]
								else:
											lowerCamelCase__		:		Any			=self.sp_model.IdToPiece(index - self.offset     )
								return token



					def 		snake_case       (       self							:  List[Any],  lowerCamelCase							:  Optional[int]     )->					Any:
								lowerCamelCase__		:		Optional[int]			=[]
								lowerCamelCase__		:		Tuple			=''''''
								for token in tokens:
											# make sure that special tokens are not decoded using sentencepiece model
											if token in self.all_special_tokens:
														out_string += self.sp_model.decode(lowerCamelCase     ) + token
														lowerCamelCase__		:		str			=[]
											else:
														current_sub_tokens.append(lowerCamelCase     )
								out_string += self.sp_model.decode(lowerCamelCase     )
								return out_string.strip()



					def 		snake_case       (       self							:  Union[str, Any],  lowerCamelCase							:  Union[str, Any]=False     )->					List[str]:
								return 1



					def 		snake_case       (       self							:  Tuple,  lowerCamelCase							:  Optional[int]     )->					Tuple:
								lowerCamelCase__		:		Tuple			=set(self.all_special_ids     )  # call it once instead of inside list comp
								all_special_ids.remove(self.unk_token_id     )  # <unk> is only sometimes special

								return [1 if x in all_special_ids else 0 for x in seq]



					def 		snake_case       (       self							:  Any,  lowerCamelCase							:  List,  lowerCamelCase							:  Optional[List] = None,  lowerCamelCase							:  bool = False     )->					List[int]:
								if already_has_special_tokens:
											return self._special_token_mask(lowerCamelCase     )
								elif token_ids_a is None:
											return self._special_token_mask(lowerCamelCase     ) + [1]
								else:
											return self._special_token_mask(token_ids_a + token_ids_a     ) + [1]



					def 		snake_case       (       self							:  Optional[Any],  lowerCamelCase							:  List[str],  lowerCamelCase							:  Optional[int]=None     )->					List[int]:
								if token_ids_a is None:
											return token_ids_a + [self.eos_token_id]
								# We don't expect to process pairs, but leave the pair logic for API consistency
								return token_ids_a + token_ids_a + [self.eos_token_id]




					def 		snake_case       (       self							:  Optional[int],  lowerCamelCase							:  str,  lowerCamelCase							:  Optional[str] = None     )->					Tuple[str]:
								if not os.path.isdir(lowerCamelCase     ):
											logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''     )
											return
								lowerCamelCase__		:		List[str]			=os.path.join(
								    lowerCamelCase,  (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']     )

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

								return (out_vocab_file,)




