






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__	:			List[str]			   = logging.get_logger(__name__)
class       _UpperCAmelCase					(       A__	):

				"""simple docstring"""




				lowercase__											=       ["""input_features""", """attention_mask"""]




				def __init__(     self						:    int,  lowerCamelCase						:    Optional[Any]=80,  lowerCamelCase						:    str=16_000,  lowerCamelCase						:    str=0.0,  lowerCamelCase						:    str=10,  lowerCamelCase						:    List[Any]=25,  lowerCamelCase						:    Dict="hamming_window",  lowerCamelCase						:    List[str]=32768.0,  lowerCamelCase						:    List[str]=0.97,  lowerCamelCase						:    str=1.0,  lowerCamelCase						:    Union[str, Any]=True,  lowerCamelCase						:    Optional[int]=True,  lowerCamelCase						:    Union[str, Any]=False,  **lowerCamelCase						:    Optional[int],  ):

								'''simple docstring'''
								super().__init__(feature_size=lowerCamelCase,  sampling_rate=lowerCamelCase,  padding_value=lowerCamelCase,  **lowerCamelCase  )

								lowercase__    =			feature_size
								lowercase__    =			sampling_rate
								lowercase__    =			padding_value
								lowercase__    =			hop_length
								lowercase__    =			win_length
								lowercase__    =			frame_signal_scale
								lowercase__    =			preemphasis_coeff
								lowercase__    =			mel_floor
								lowercase__    =			normalize_means
								lowercase__    =			normalize_vars
								lowercase__    =			win_function
								lowercase__    =			return_attention_mask

								lowercase__    =			win_length * sampling_rate // 1_000
								lowercase__    =			hop_length * sampling_rate // 1_000

								lowercase__    =			optimal_fft_length(self.sample_size  )
								lowercase__    =			(self.n_fft // 2) + 1




				def 				lowercase__   (     self						:    Optional[int],  lowerCamelCase						:    np.array  ):

								'''simple docstring'''
								if self.win_function == "hamming_window":
												lowercase__    =			window_function(window_length=self.sample_size,  name=self.win_function,  periodic=lowerCamelCase  )
								else:
												lowercase__    =			window_function(window_length=self.sample_size,  name=self.win_function  )

								lowercase__    =			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__    =			spectrogram(
								    one_waveform * self.frame_signal_scale,  window=lowerCamelCase,  frame_length=self.sample_size,  hop_length=self.sample_stride,  fft_length=self.n_fft,  center=lowerCamelCase,  preemphasis=self.preemphasis_coeff,  mel_filters=lowerCamelCase,  mel_floor=self.mel_floor,  log_mel='''log''',  )
								return msfc_features.T




				def 				lowercase__   (     self						:    Dict,  lowerCamelCase						:    Any,  lowerCamelCase						:    Optional[int],  lowerCamelCase						:    Any  ):

								'''simple docstring'''
								# make sure we normalize float32 arrays
								if self.normalize_means:
												lowercase__    =			x[:input_length].mean(axis=0  )
												lowercase__    =			np.subtract(lowerCamelCase,  lowerCamelCase  )
								if self.normalize_vars:
												lowercase__    =			x[:input_length].std(axis=0  )
												lowercase__    =			np.divide(lowerCamelCase,  lowerCamelCase  )

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

								# make sure array is in float32
								lowercase__    =			x.astype(np.floataa  )

								return x




				def 				lowercase__   (     self						:    Tuple,  lowerCamelCase						:    List[np.ndarray],  lowerCamelCase						:    Optional[np.ndarray] = None  ):

								'''simple docstring'''
								lowercase__    =			attention_mask.sum(-1  ) if attention_mask is not None else [x.shape[0] for x in input_features]
								return [self._normalize_one(lowerCamelCase,  lowerCamelCase,  self.padding_value  ) for x, n in zip(lowerCamelCase,  lowerCamelCase  )]




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

								'''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} 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__    =			isinstance(lowerCamelCase,  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__    =			is_batched_numpy or (
								    isinstance(lowerCamelCase,  (list, tuple)  ) and (isinstance(raw_speech[0],  (np.ndarray, tuple, list)  ))
								)

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

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

								# extract fbank features
								lowercase__    =			[self._extract_mfsc_features(lowerCamelCase  ) for one_waveform in raw_speech]

								# convert into correct format for padding
								lowercase__    =			BatchFeature({'''input_features''': features}  )

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

								lowercase__    =			padded_inputs.get('''attention_mask'''  )
								if attention_mask is not None:
												lowercase__    =			[np.asarray(lowerCamelCase,  dtype=np.intaa  ) for array in attention_mask]

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

								if return_tensors is not None:
												lowercase__    =			padded_inputs.convert_to_tensors(lowerCamelCase  )

								return padded_inputs












from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
							import tensorflow as tf

							from ..tf_utils import stable_softmax


if is_torch_available():
							import torch


A__	:			Dict			   = logging.get_logger(__name__)
@add_end_docstrings(
    A__		,r"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """		,)
class       _UpperCAmelCase					(       A__	):

				"""simple docstring"""




				def 				lowercase__   (     self						:    Optional[int],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								if self.framework == "tf":
												lowercase__    =			tf.where(input_ids == self.tokenizer.mask_token_id  ).numpy()
								elif self.framework == "pt":
												lowercase__    =			torch.nonzero(input_ids == self.tokenizer.mask_token_id,  as_tuple=lowerCamelCase  )
								else:
												raise ValueError('''Unsupported framework'''  )
								return masked_index




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								lowercase__    =			self.get_masked_index(lowerCamelCase  )
								lowercase__    =			np.prod(masked_index.shape  )
								if numel < 1:
												raise PipelineException(
												    '''fill-mask''',  self.model.base_model_prefix,  F"""No mask_token ({self.tokenizer.mask_token}) found on the input""",  )




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								if isinstance(lowerCamelCase,  lowerCamelCase  ):
												for model_input in model_inputs:
																self._ensure_exactly_one_mask_token(model_input['''input_ids'''][0]  )
								else:
												for input_ids in model_inputs["input_ids"]:
																self._ensure_exactly_one_mask_token(lowerCamelCase  )




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    Union[str, Any],  lowerCamelCase						:    Optional[int]=None,  **lowerCamelCase						:    Dict  ):

								'''simple docstring'''
								if return_tensors is None:
												lowercase__    =			self.framework
								lowercase__    =			self.tokenizer(lowerCamelCase,  return_tensors=lowerCamelCase  )
								self.ensure_exactly_one_mask_token(lowerCamelCase  )
								return model_inputs




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    int  ):

								'''simple docstring'''
								lowercase__    =			self.model(**lowerCamelCase  )
								lowercase__    =			model_inputs['''input_ids''']
								return model_outputs




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    List[str],  lowerCamelCase						:    Tuple=5,  lowerCamelCase						:    List[Any]=None  ):

								'''simple docstring'''
								# Cap top_k if there are targets
								if target_ids is not None and target_ids.shape[0] < top_k:
												lowercase__    =			target_ids.shape[0]
								lowercase__    =			model_outputs['''input_ids'''][0]
								lowercase__    =			model_outputs['''logits''']

								if self.framework == "tf":
												lowercase__    =			tf.where(input_ids == self.tokenizer.mask_token_id  ).numpy()[:, 0]

												lowercase__    =			outputs.numpy()

												lowercase__    =			outputs[0, masked_index, :]
												lowercase__    =			stable_softmax(lowerCamelCase,  axis=-1  )
												if target_ids is not None:
																lowercase__    =			tf.gather_nd(tf.squeeze(lowerCamelCase,  0  ),  target_ids.reshape(-1,  1  )  )
																lowercase__    =			tf.expand_dims(lowerCamelCase,  0  )

												lowercase__    =			tf.math.top_k(lowerCamelCase,  k=lowerCamelCase  )
												lowercase__ ,						lowercase__    =			topk.values.numpy(), topk.indices.numpy()
								else:
												lowercase__    =			torch.nonzero(input_ids == self.tokenizer.mask_token_id,  as_tuple=lowerCamelCase  ).squeeze(-1  )
												# Fill mask pipeline supports only one ${mask_token} per sample

												lowercase__    =			outputs[0, masked_index, :]
												lowercase__    =			logits.softmax(dim=-1  )
												if target_ids is not None:
																lowercase__    =			probs[..., target_ids]

												lowercase__ ,						lowercase__    =			probs.topk(lowerCamelCase  )

								lowercase__    =			[]
								lowercase__    =			values.shape[0] == 1
								for i, (_values, _predictions) in enumerate(zip(values.tolist(),  predictions.tolist()  )  ):
												lowercase__    =			[]
												for v, p in zip(_values,  _predictions  ):
																# Copy is important since we're going to modify this array in place
																lowercase__    =			input_ids.numpy().copy()
																if target_ids is not None:
																				lowercase__    =			target_ids[p].tolist()

																lowercase__    =			p
																# Filter padding out:
																lowercase__    =			tokens[np.where(tokens != self.tokenizer.pad_token_id  )]
																# Originally we skip special tokens to give readable output.
																# For multi masks though, the other [MASK] would be removed otherwise
																# making the output look odd, so we add them back
																lowercase__    =			self.tokenizer.decode(lowerCamelCase,  skip_special_tokens=lowerCamelCase  )
																lowercase__    =			{'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p]  ), '''sequence''': sequence}
																row.append(lowerCamelCase  )
												result.append(lowerCamelCase  )
								if single_mask:
												return result[0]
								return result




				def 				lowercase__   (     self						:    int,  lowerCamelCase						:    Optional[int],  lowerCamelCase						:    Dict=None  ):

								'''simple docstring'''
								if isinstance(lowerCamelCase,  lowerCamelCase  ):
												lowercase__    =			[targets]
								try:
												lowercase__    =			self.tokenizer.get_vocab()
								except Exception:
												lowercase__    =			{}
								lowercase__    =			[]
								for target in targets:
												lowercase__    =			vocab.get(lowerCamelCase,  lowerCamelCase  )
												if id_ is None:
																lowercase__    =			self.tokenizer(
																    lowerCamelCase,  add_special_tokens=lowerCamelCase,  return_attention_mask=lowerCamelCase,  return_token_type_ids=lowerCamelCase,  max_length=1,  truncation=lowerCamelCase,  )['''input_ids''']
																if len(lowerCamelCase  ) == 0:
																				logger.warning(
																				    F"""The specified target token `{target}` does not exist in the model vocabulary. """
																				    '''We cannot replace it with anything meaningful, ignoring it'''  )
																				continue
																lowercase__    =			input_ids[0]
																# XXX: If users encounter this pass
																# it becomes pretty slow, so let's make sure
																# The warning enables them to fix the input to
																# get faster performance.
																logger.warning(
																    F"""The specified target token `{target}` does not exist in the model vocabulary. """
																    F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_  )}`."""  )
												target_ids.append(id_  )
								lowercase__    =			list(set(lowerCamelCase  )  )
								if len(lowerCamelCase  ) == 0:
												raise ValueError('''At least one target must be provided when passed.'''  )
								lowercase__    =			np.array(lowerCamelCase  )
								return target_ids




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    int=None,  lowerCamelCase						:    Any=None  ):

								'''simple docstring'''
								lowercase__    =			{}

								if targets is not None:
												lowercase__    =			self.get_target_ids(lowerCamelCase,  lowerCamelCase  )
												lowercase__    =			target_ids

								if top_k is not None:
												lowercase__    =			top_k

								if self.tokenizer.mask_token_id is None:
												raise PipelineException(
												    '''fill-mask''',  self.model.base_model_prefix,  '''The tokenizer does not define a `mask_token`.'''  )
								return {}, {}, postprocess_params




				def __call__(     self						:    List[Any],  lowerCamelCase						:    Optional[Any],  *lowerCamelCase						:    Optional[Any],  **lowerCamelCase						:    Optional[Any]  ):

								'''simple docstring'''
								lowercase__    =			super().__call__(lowerCamelCase,  **lowerCamelCase  )
								if isinstance(lowerCamelCase,  lowerCamelCase  ) and len(lowerCamelCase  ) == 1:
												return outputs[0]
								return outputs




