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

import numpy as np
import torch

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


UpperCamelCase     					=      logging.get_logger(__name__)


class _a  (			lowerCAmelCase__   ):

	'''simple docstring'''



	lowerCamelCase_       :     Tuple          =			["input_features", "is_longer"]

	def __init__(  self				,					__UpperCAmelCase=64				,					__UpperCAmelCase=48_000				,					__UpperCAmelCase=480				,					__UpperCAmelCase=10				,					__UpperCAmelCase=1_024				,					__UpperCAmelCase=0.0				,					__UpperCAmelCase=False				,					__UpperCAmelCase = 0				,					__UpperCAmelCase = 14_000				,					__UpperCAmelCase = None				,					__UpperCAmelCase = "fusion"				,					__UpperCAmelCase = "repeatpad"				,					**__UpperCAmelCase				,					):
			super().__init__(
			    feature_size=__UpperCAmelCase				,					sampling_rate=__UpperCAmelCase				,					padding_value=__UpperCAmelCase				,					return_attention_mask=__UpperCAmelCase				,					**__UpperCAmelCase				,					)
			__A				:       Any			    = top_db
			__A				:       Dict			    = truncation
			__A				:       Optional[int]			    = padding
			__A				:       Optional[Any]			    = fft_window_size
			__A				:       List[Any]			    = (fft_window_size >> 1) + 1
			__A				:       int			    = hop_length
			__A				:       Any			    = max_length_s
			__A				:       Tuple			    = max_length_s * sampling_rate
			__A				:       Any			    = sampling_rate
			__A				:       List[Any]			    = frequency_min
			__A				:       Optional[Any]			    = frequency_max
			__A				:       str			    = mel_filter_bank(
			    num_frequency_bins=self.nb_frequency_bins				,					num_mel_filters=__UpperCAmelCase				,					min_frequency=__UpperCAmelCase				,					max_frequency=__UpperCAmelCase				,					sampling_rate=__UpperCAmelCase				,					norm=__UpperCAmelCase				,					mel_scale="htk"				,					)
			__A				:       List[Any]			    = mel_filter_bank(
			    num_frequency_bins=self.nb_frequency_bins				,					num_mel_filters=__UpperCAmelCase				,					min_frequency=__UpperCAmelCase				,					max_frequency=__UpperCAmelCase				,					sampling_rate=__UpperCAmelCase				,					norm="slaney"				,					mel_scale="slaney"				,					)

	def 	__UpperCAmelCase(  self       ):
			__A				:       int			    = copy.deepcopy(self.__dict__       )
			__A				:       str			    = self.__class__.__name__
			if "mel_filters" in output:
					del output["mel_filters"]
			if "mel_filters_slaney" in output:
					del output["mel_filters_slaney"]
			return output

	def 	__UpperCAmelCase(  self				,					__UpperCAmelCase				,					__UpperCAmelCase = None       ):
			__A				:       Any			    = spectrogram(
			    __UpperCAmelCase				,					window_function(self.fft_window_size				,					"hann"       )				,					frame_length=self.fft_window_size				,					hop_length=self.hop_length				,					power=2.0				,					mel_filters=__UpperCAmelCase				,					log_mel="dB"				,					)
			return log_mel_spectrogram.T

	def 	__UpperCAmelCase(  self				,					__UpperCAmelCase				,					__UpperCAmelCase				,					__UpperCAmelCase       ):
			__A				:       Tuple			    = np.array_split(list(range(0				,					total_frames - chunk_frames + 1       )       )				,					3       )
			if len(ranges[1]       ) == 0:
					# if the audio is too short, we just use the first chunk
					__A				:       Union[str, Any]			    = [0]
			if len(ranges[2]       ) == 0:
					# if the audio is too short, we just use the first chunk
					__A				:       Union[str, Any]			    = [0]
			# randomly choose index for each part
			__A				:       Tuple			    = np.random.choice(ranges[0]       )
			__A				:       List[str]			    = np.random.choice(ranges[1]       )
			__A				:       List[Any]			    = np.random.choice(ranges[2]       )

			__A				:       List[str]			    = mel[idx_front : idx_front + chunk_frames, :]
			__A				:       int			    = mel[idx_middle : idx_middle + chunk_frames, :]
			__A				:       Union[str, Any]			    = mel[idx_back : idx_back + chunk_frames, :]

			__A				:       List[Any]			    = torch.tensor(mel[None, None, :]       )
			__A				:       Dict			    = torch.nn.functional.interpolate(
			    __UpperCAmelCase				,					size=[chunk_frames, 64]				,					mode="bilinear"				,					align_corners=__UpperCAmelCase       )
			__A				:       Union[str, Any]			    = mel_shrink[0][0].numpy()
			__A				:       Any			    = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back]				,					axis=0       )
			return mel_fusion

	def 	__UpperCAmelCase(  self				,					__UpperCAmelCase				,					__UpperCAmelCase				,					__UpperCAmelCase				,					__UpperCAmelCase       ):

			if waveform.shape[0] > max_length:
					if truncation == "rand_trunc":
							__A				:       Tuple			    = True
							# random crop to max_length (for compatibility) -> this should be handled by self.pad
							__A				:       Any			    = len(__UpperCAmelCase       ) - max_length
							__A				:       Optional[Any]			    = np.random.randint(0				,					overflow + 1       )
							__A				:       Optional[int]			    = waveform[idx : idx + max_length]
							__A				:       Any			    = self._np_extract_fbank_features(__UpperCAmelCase				,					self.mel_filters_slaney       )[None, :]
					elif truncation == "fusion":
							__A				:       Optional[int]			    = self._np_extract_fbank_features(__UpperCAmelCase				,					self.mel_filters       )
							__A				:       Optional[Any]			    = max_length // self.hop_length + 1  # the +1 related to how the spectrogram is computed
							__A				:       Union[str, Any]			    = mel.shape[0]
							if chunk_frames == total_frames:
									# there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
									# In this case, we just use the whole audio.
									__A				:       str			    = np.stack([mel, mel, mel, mel]				,					axis=0       )
									__A				:       Optional[Any]			    = False
							else:
									__A				:       Tuple			    = self._random_mel_fusion(__UpperCAmelCase				,					__UpperCAmelCase				,					__UpperCAmelCase       )
									__A				:       Optional[int]			    = True
					else:
							raise NotImplementedError(F"data_truncating {truncation} not implemented"       )

			else:
					__A				:       Optional[int]			    = False
					# only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
					if waveform.shape[0] < max_length:
							if padding == "repeat":
									__A				:       Union[str, Any]			    = int(max_length / len(__UpperCAmelCase       )       )
									__A				:       Optional[Any]			    = np.stack(np.tile(__UpperCAmelCase				,					n_repeat + 1       )       )[:max_length]
							if padding == "repeatpad":
									__A				:       List[Any]			    = int(max_length / len(__UpperCAmelCase       )       )
									__A				:       List[str]			    = np.stack(np.tile(__UpperCAmelCase				,					__UpperCAmelCase       )       )
							__A				:       Optional[int]			    = np.pad(__UpperCAmelCase				,					(0, max_length - waveform.shape[0])				,					mode="constant"				,					constant_values=0       )

					if truncation == "fusion":
							__A				:       List[Any]			    = self._np_extract_fbank_features(__UpperCAmelCase				,					self.mel_filters       )
							__A				:       List[str]			    = np.stack([input_mel, input_mel, input_mel, input_mel]				,					axis=0       )
					else:
							__A				:       Optional[int]			    = self._np_extract_fbank_features(__UpperCAmelCase				,					self.mel_filters_slaney       )[None, :]

			return input_mel, longer







	def __call__(  self				,					__UpperCAmelCase				,					__UpperCAmelCase = None				,					__UpperCAmelCase = None				,					__UpperCAmelCase = None				,					__UpperCAmelCase = None				,					__UpperCAmelCase = None				,					**__UpperCAmelCase				,					):
			__A				:       Tuple			    = truncation if truncation is not None else self.truncation
			__A				:       Any			    = padding if padding else self.padding

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

			__A				:       Optional[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}"       )
			__A				:       str			    = is_batched_numpy or (
			    isinstance(__UpperCAmelCase				,					(list, tuple)       ) and (isinstance(raw_speech[0]				,					(np.ndarray, tuple, list)       ))
			)

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

			# always return batch
			if not is_batched:
					__A				:       List[str]			    = [np.asarray(__UpperCAmelCase       )]

			# convert to mel spectrogram, truncate and pad if needed.
			__A				:       Dict			    = [
			    self._get_input_mel(__UpperCAmelCase				,					max_length if max_length else self.nb_max_samples				,					__UpperCAmelCase				,					__UpperCAmelCase       )
			    for waveform in raw_speech
			]

			__A				:       List[str]			    = []
			__A				:       List[Any]			    = []
			for mel, longer in padded_inputs:
					input_mel.append(__UpperCAmelCase       )
					is_longer.append(__UpperCAmelCase       )

			if truncation == "fusion" and sum(__UpperCAmelCase       ) == 0:
					# if no audio is longer than 10s, then randomly select one audio to be longer
					__A				:       int			    = np.random.randint(0				,					len(__UpperCAmelCase       )       )
					__A				:       List[str]			    = True

			if isinstance(input_mel[0]				,					__UpperCAmelCase       ):
					__A				:       Any			    = [np.asarray(__UpperCAmelCase				,					dtype=np.floataa       ) for feature in input_mel]

			# is_longer is a list of bool
			__A				:       Optional[Any]			    = [[longer] for longer in is_longer]

			__A				:       Optional[Any]			    = {"input_features": input_mel, "is_longer": is_longer}
			__A				:       int			    = BatchFeature(__UpperCAmelCase       )

			if return_tensors is not None:
					__A				:       str			    = input_features.convert_to_tensors(__UpperCAmelCase       )

			return input_features










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

import sentencepiece as spm

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


a__   :					Optional[int] 						=      logging.get_logger(__name__)
a__   :					Dict 						=      {"vocab_file": "spiece.model"}

a__   :					str 						=      {
    "vocab_file": {
        "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model",
        "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model",
        "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model",
        "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model",
        "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model",
        "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model",
        "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model",
        "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model",
    }
}

a__   :					Union[str, Any] 						=      {
    "albert-base-v1": 5_12,
    "albert-large-v1": 5_12,
    "albert-xlarge-v1": 5_12,
    "albert-xxlarge-v1": 5_12,
    "albert-base-v2": 5_12,
    "albert-large-v2": 5_12,
    "albert-xlarge-v2": 5_12,
    "albert-xxlarge-v2": 5_12,
}

a__   :					Optional[int] 						=      "▁"



class    UpperCAmelCase__(				lowerCamelCase						):

   '''simple docstring'''




   A     :	Tuple												=     VOCAB_FILES_NAMES
   A     :	Dict												=     PRETRAINED_VOCAB_FILES_MAP
   A     :	str												=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES


   def __init__(    self	:      List[str]      ,					lowerCAmelCase	:      Tuple      ,					lowerCAmelCase	:      Optional[int]=True      ,					lowerCAmelCase	:      List[Any]=True      ,					lowerCAmelCase	:      str=False      ,					lowerCAmelCase	:      str="[CLS]"      ,					lowerCAmelCase	:      Optional[int]="[SEP]"      ,					lowerCAmelCase	:      int="<unk>"      ,					lowerCAmelCase	:      str="[SEP]"      ,					lowerCAmelCase	:      Dict="<pad>"      ,					lowerCAmelCase	:      int="[CLS]"      ,					lowerCAmelCase	:      Tuple="[MASK]"      ,					lowerCAmelCase	:      Optional[Dict[str, Any]] = None      ,					**lowerCAmelCase	:      List[str]      ,					)						->					None:




         """simple docstring"""

         lowercase__  =	(
             AddedToken(lowerCAmelCase      ,					lstrip=lowerCAmelCase      ,					rstrip=lowerCAmelCase      ,					normalized=lowerCAmelCase)
             if isinstance(lowerCAmelCase      ,					lowerCAmelCase)
             else mask_token
         )

         lowercase__  =	{} if sp_model_kwargs is None else sp_model_kwargs

         super().__init__(
             do_lower_case=lowerCAmelCase      ,					remove_space=lowerCAmelCase      ,					keep_accents=lowerCAmelCase      ,					bos_token=lowerCAmelCase      ,					eos_token=lowerCAmelCase      ,					unk_token=lowerCAmelCase      ,					sep_token=lowerCAmelCase      ,					pad_token=lowerCAmelCase      ,					cls_token=lowerCAmelCase      ,					mask_token=lowerCAmelCase      ,					sp_model_kwargs=self.sp_model_kwargs      ,					**lowerCAmelCase      ,					)

         lowercase__  =	do_lower_case
         lowercase__  =	remove_space
         lowercase__  =	keep_accents
         lowercase__  =	vocab_file

         lowercase__  =	spm.SentencePieceProcessor(**self.sp_model_kwargs)
         self.sp_model.Load(lowerCAmelCase)


   @property
   def       UpperCAmelCase		(    self	:      Any)						->					Optional[int]:




         """simple docstring"""

         return len(self.sp_model)


   def       UpperCAmelCase		(    self	:      Optional[int])						->					Any:




         """simple docstring"""

         lowercase__  =	{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	:      int)						->					List[str]:




         """simple docstring"""

         lowercase__  =	self.__dict__.copy()
         lowercase__  =	None
         return state


   def __setstate__(    self	:      int      ,					lowerCAmelCase	:      str)						->					Any:




         """simple docstring"""

         lowercase__  =	d

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

         lowercase__  =	spm.SentencePieceProcessor(**self.sp_model_kwargs)
         self.sp_model.Load(self.vocab_file)


   def       UpperCAmelCase		(    self	:      Dict      ,					lowerCAmelCase	:      int)						->					List[str]:




         """simple docstring"""

         if self.remove_space:
               lowercase__  =	' '.join(inputs.strip().split())
         else:
               lowercase__  =	inputs
         lowercase__  =	outputs.replace('``'      ,					'"').replace('\'\''      ,					'"')

         if not self.keep_accents:
               lowercase__  =	unicodedata.normalize('NFKD'      ,					lowerCAmelCase)
               lowercase__  =	''.join([c for c in outputs if not unicodedata.combining(lowerCAmelCase)])
         if self.do_lower_case:
               lowercase__  =	outputs.lower()

         return outputs


   def       UpperCAmelCase		(    self	:      Any      ,					lowerCAmelCase	:      str)						->					List[str]:




         """simple docstring"""

         lowercase__  =	self.preprocess_text(lowerCAmelCase)
         lowercase__  =	self.sp_model.encode(lowerCAmelCase      ,					out_type=lowerCAmelCase)
         lowercase__  =	[]
         for piece in pieces:
               if len(lowerCAmelCase) > 1 and piece[-1] == str(',') and piece[-2].isdigit():
                     lowercase__  =	self.sp_model.EncodeAsPieces(piece[:-1].replace(lowerCAmelCase      ,					''))
                     if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
                           if len(cur_pieces[0]) == 1:
                                 lowercase__  =	cur_pieces[1:]
                           else:
                                 lowercase__  =	cur_pieces[0][1:]
                     cur_pieces.append(piece[-1])
                     new_pieces.extend(lowerCAmelCase)
               else:
                     new_pieces.append(lowerCAmelCase)

         return new_pieces


   def       UpperCAmelCase		(    self	:      Any      ,					lowerCAmelCase	:      int)						->					int:




         """simple docstring"""

         return self.sp_model.PieceToId(lowerCAmelCase)


   def       UpperCAmelCase		(    self	:      List[str]      ,					lowerCAmelCase	:      Any)						->					Tuple:




         """simple docstring"""

         return self.sp_model.IdToPiece(lowerCAmelCase)


   def       UpperCAmelCase		(    self	:      Tuple      ,					lowerCAmelCase	:      Optional[Any])						->					List[Any]:




         """simple docstring"""

         lowercase__  =	[]
         lowercase__  =	''
         lowercase__  =	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(lowerCAmelCase) + token
                     lowercase__  =	True
                     lowercase__  =	[]
               else:
                     current_sub_tokens.append(lowerCAmelCase)
                     lowercase__  =	False
         out_string += self.sp_model.decode(lowerCAmelCase)
         return out_string.strip()


   def       UpperCAmelCase		(    self	:      Union[str, Any]      ,					lowerCAmelCase	:      List[int]      ,					lowerCAmelCase	:      Optional[List[int]] = None)						->					List[int]:




         """simple docstring"""

         lowercase__  =	[self.sep_token_id]
         lowercase__  =	[self.cls_token_id]
         if token_ids_a is None:
               return cls + token_ids_a + sep
         return cls + token_ids_a + sep + token_ids_a + sep


   def       UpperCAmelCase		(    self	:      int      ,					lowerCAmelCase	:      List[int]      ,					lowerCAmelCase	:      Optional[List[int]] = None      ,					lowerCAmelCase	:      bool = False)						->					List[int]:




         """simple docstring"""

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

         if token_ids_a is not None:
               return [1] + ([0] * len(lowerCAmelCase)) + [1] + ([0] * len(lowerCAmelCase)) + [1]
         return [1] + ([0] * len(lowerCAmelCase)) + [1]


   def       UpperCAmelCase		(    self	:      Union[str, Any]      ,					lowerCAmelCase	:      List[int]      ,					lowerCAmelCase	:      Optional[List[int]] = None)						->					List[int]:




         """simple docstring"""

         lowercase__  =	[self.sep_token_id]
         lowercase__  =	[self.cls_token_id]

         if token_ids_a is None:
               return len(cls + token_ids_a + sep) * [0]
         return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1]



   def       UpperCAmelCase		(    self	:      Dict      ,					lowerCAmelCase	:      str      ,					lowerCAmelCase	:      Optional[str] = None)						->					Tuple[str]:




         """simple docstring"""

         if not os.path.isdir(lowerCAmelCase):
               logger.error(f'''Vocabulary path ({save_directory}) should be a directory''')
               return
         lowercase__  =	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:
                     lowercase__  =	self.sp_model.serialized_model_proto()
                     fi.write(lowerCAmelCase)

         return (out_vocab_file,)
