



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


lowerCAmelCase__		:					Union[str, Any]							=logging.get_logger(__name__)

@add_end_docstrings(
    UpperCamelCase_   ,   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_  (       UpperCamelCase_	):

						'''simple docstring'''




						def 	_A     (   self				,							_A		):







													'''simple docstring'''

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






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.get_masked_index(_A		)
													__SCREAMING_SNAKE_CASE									= 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 	_A     (   self				,							_A		):







													'''simple docstring'''

													if isinstance(_A				,							_A		):
																				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(_A		)






						def 	_A     (   self				,							_A				,							_A=None				,							**_A		):







													'''simple docstring'''

													if return_tensors is None:
																				__SCREAMING_SNAKE_CASE									= self.framework
													__SCREAMING_SNAKE_CASE									= self.tokenizer(_A				,							return_tensors=_A		)
													self.ensure_exactly_one_mask_token(_A		)
													return model_inputs






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.model(**_A		)
													__SCREAMING_SNAKE_CASE									= model_inputs['input_ids']
													return model_outputs






						def 	_A     (   self				,							_A				,							_A=5				,							_A=None		):







													'''simple docstring'''

													if target_ids is not None and target_ids.shape[0] < top_k:
																				__SCREAMING_SNAKE_CASE									= target_ids.shape[0]
													__SCREAMING_SNAKE_CASE									= model_outputs['input_ids'][0]
													__SCREAMING_SNAKE_CASE									= model_outputs['logits']

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

																				__SCREAMING_SNAKE_CASE									= outputs.numpy()

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

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

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

																				__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE									= probs.topk(_A		)

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

																											__SCREAMING_SNAKE_CASE									= p
																											# Filter padding out:
																											__SCREAMING_SNAKE_CASE									= 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
																											__SCREAMING_SNAKE_CASE									= self.tokenizer.decode(_A				,							skip_special_tokens=_A		)
																											__SCREAMING_SNAKE_CASE									= {'score': v, 'token': p, 'token_str': self.tokenizer.decode([p]		), 'sequence': sequence}
																											row.append(_A		)
																				result.append(_A		)
													if single_mask:
																				return result[0]
													return result






						def 	_A     (   self				,							_A				,							_A=None		):







													'''simple docstring'''

													if isinstance(_A				,							_A		):
																				__SCREAMING_SNAKE_CASE									= [targets]
													try:
																				__SCREAMING_SNAKE_CASE									= self.tokenizer.get_vocab()
													except Exception:
																				__SCREAMING_SNAKE_CASE									= {}
													__SCREAMING_SNAKE_CASE									= []
													for target in targets:
																				__SCREAMING_SNAKE_CASE									= vocab.get(_A				,							_A		)
																				if id_ is None:
																											__SCREAMING_SNAKE_CASE									= self.tokenizer(
																											    _A				,							add_special_tokens=_A				,							return_attention_mask=_A				,							return_token_type_ids=_A				,							max_length=1				,							truncation=_A				,							)['input_ids']
																											if len(_A		) == 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
																											__SCREAMING_SNAKE_CASE									= 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_		)
													__SCREAMING_SNAKE_CASE									= list(set(_A		)		)
													if len(_A		) == 0:
																				raise ValueError('At least one target must be provided when passed.'		)
													__SCREAMING_SNAKE_CASE									= np.array(_A		)
													return target_ids






						def 	_A     (   self				,							_A=None				,							_A=None		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= {}

													if targets is not None:
																				__SCREAMING_SNAKE_CASE									= self.get_target_ids(_A				,							_A		)
																				__SCREAMING_SNAKE_CASE									= target_ids

													if top_k is not None:
																				__SCREAMING_SNAKE_CASE									= 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				,							_A				,							*_A				,							**_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= super().__call__(_A				,							**_A		)
													if isinstance(_A				,							_A		) and len(_A		) == 1:
																				return outputs[0]
													return outputs










import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin
from .feature_extraction_wavaveca import WavaVecaFeatureExtractor
from .tokenization_wavaveca import WavaVecaCTCTokenizer

class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						UpperCamelCase__      :			Union[str, Any]      =  '''Wav2Vec2FeatureExtractor'''
						UpperCamelCase__      :			Union[str, Any]      =  '''AutoTokenizer'''






						def __init__(   self				,							_A				,							_A		):







													'''simple docstring'''

													super().__init__(_A				,							_A		)
													__SCREAMING_SNAKE_CASE									= self.feature_extractor
													__SCREAMING_SNAKE_CASE									= False






						@classmethod
						def 	_A     (   cls				,							_A				,							**_A		):







													'''simple docstring'''

													try:
																				return super().from_pretrained(_A				,							**_A		)
													except OSError:
																				warnings.warn(
																				    f"""Loading a tokenizer inside {cls.__name__} from a config that does not"""
																				    ' include a `tokenizer_class` attribute is deprecated and will be '
																				    'removed in v5. Please add `\'tokenizer_class\': \'Wav2Vec2CTCTokenizer\'`'
																				    ' attribute to either your `config.json` or `tokenizer_config.json` '
																				    'file to suppress this warning: '				,							_A				,							)

																				__SCREAMING_SNAKE_CASE									= WavaVecaFeatureExtractor.from_pretrained(_A				,							**_A		)
																				__SCREAMING_SNAKE_CASE									= WavaVecaCTCTokenizer.from_pretrained(_A				,							**_A		)

																				return cls(feature_extractor=_A				,							tokenizer=_A		)






						def __call__(   self				,							*_A				,							**_A		):







													'''simple docstring'''

													if self._in_target_context_manager:
																				return self.current_processor(*_A				,							**_A		)

													if "raw_speech" in kwargs:
																				warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.'		)
																				__SCREAMING_SNAKE_CASE									= kwargs.pop('raw_speech'		)
													else:
																				__SCREAMING_SNAKE_CASE									= kwargs.pop('audio'				,							_A		)
													__SCREAMING_SNAKE_CASE									= kwargs.pop('sampling_rate'				,							_A		)
													__SCREAMING_SNAKE_CASE									= kwargs.pop('text'				,							_A		)
													if len(_A		) > 0:
																				__SCREAMING_SNAKE_CASE									= args[0]
																				__SCREAMING_SNAKE_CASE									= args[1:]

													if audio is None and text is None:
																				raise ValueError('You need to specify either an `audio` or `text` input to process.'		)

													if audio is not None:
																				__SCREAMING_SNAKE_CASE									= self.feature_extractor(_A				,							*_A				,							sampling_rate=_A				,							**_A		)
													if text is not None:
																				__SCREAMING_SNAKE_CASE									= self.tokenizer(_A				,							**_A		)

													if text is None:
																				return inputs
													elif audio is None:
																				return encodings
													else:
																				__SCREAMING_SNAKE_CASE									= encodings['input_ids']
																				return inputs






						def 	_A     (   self				,							*_A				,							**_A		):







													'''simple docstring'''

													if self._in_target_context_manager:
																				return self.current_processor.pad(*_A				,							**_A		)

													__SCREAMING_SNAKE_CASE									= kwargs.pop('input_features'				,							_A		)
													__SCREAMING_SNAKE_CASE									= kwargs.pop('labels'				,							_A		)
													if len(_A		) > 0:
																				__SCREAMING_SNAKE_CASE									= args[0]
																				__SCREAMING_SNAKE_CASE									= args[1:]

													if input_features is not None:
																				__SCREAMING_SNAKE_CASE									= self.feature_extractor.pad(_A				,							*_A				,							**_A		)
													if labels is not None:
																				__SCREAMING_SNAKE_CASE									= self.tokenizer.pad(_A				,							**_A		)

													if labels is None:
																				return input_features
													elif input_features is None:
																				return labels
													else:
																				__SCREAMING_SNAKE_CASE									= labels['input_ids']
																				return input_features






						def 	_A     (   self				,							*_A				,							**_A		):







													'''simple docstring'''

													return self.tokenizer.batch_decode(*_A				,							**_A		)






						def 	_A     (   self				,							*_A				,							**_A		):







													'''simple docstring'''

													return self.tokenizer.decode(*_A				,							**_A		)






						@contextmanager
						def 	_A     (   self		):







													'''simple docstring'''

													warnings.warn(
													    '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '
													    'labels by using the argument `text` of the regular `__call__` method (either in the same call as '
													    'your audio inputs, or in a separate call.'		)
													__SCREAMING_SNAKE_CASE									= True
													__SCREAMING_SNAKE_CASE									= self.tokenizer
													yield
													__SCREAMING_SNAKE_CASE									= self.feature_extractor
													__SCREAMING_SNAKE_CASE									= False






