





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			       =      logging.get_logger(__name__)







@add_end_docstrings(
    lowerCamelCase__ ,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 			__A       (      lowerCamelCase__  ):




      """simple docstring"""







      def 				__snake_case			(		self      ,							a__):



             """simple docstring"""





             if self.framework == "tf":
                    _lowerCamelCase							:     List[Any]	=		tf.where(input_ids == self.tokenizer.mask_token_id).numpy()
             elif self.framework == "pt":
                    _lowerCamelCase							:     List[Any]	=		torch.nonzero(input_ids == self.tokenizer.mask_token_id      ,							as_tuple=a__)
             else:
                    raise ValueError('''Unsupported framework''')
             return masked_index


      def 				__snake_case			(		self      ,							a__):



             """simple docstring"""





             _lowerCamelCase							:     List[str]	=		self.get_masked_index(a__)
             _lowerCamelCase							:     Union[str, Any]	=		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 				__snake_case			(		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 				__snake_case			(		self      ,							a__      ,							a__=None      ,							**a__):



             """simple docstring"""





             if return_tensors is None:
                    _lowerCamelCase							:     Union[str, Any]	=		self.framework
             _lowerCamelCase							:     Optional[Any]	=		self.tokenizer(a__      ,							return_tensors=a__)
             self.ensure_exactly_one_mask_token(a__)
             return model_inputs


      def 				__snake_case			(		self      ,							a__):



             """simple docstring"""





             _lowerCamelCase							:     Dict	=		self.model(**a__)
             _lowerCamelCase							:     Dict	=		model_inputs['''input_ids''']
             return model_outputs


      def 				__snake_case			(		self      ,							a__      ,							a__=5      ,							a__=None):



             """simple docstring"""





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

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

                    _lowerCamelCase							:     Tuple	=		outputs.numpy()

                    _lowerCamelCase							:     Optional[Any]	=		outputs[0, masked_index, :]
                    _lowerCamelCase							:     Optional[int]	=		stable_softmax(a__      ,							axis=-1)
                    if target_ids is not None:
                           _lowerCamelCase							:     List[str]	=		tf.gather_nd(tf.squeeze(a__      ,							0)      ,							target_ids.reshape(-1      ,							1))
                           _lowerCamelCase							:     Any	=		tf.expand_dims(a__      ,							0)

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

                    _lowerCamelCase							:     Dict	=		outputs[0, masked_index, :]
                    _lowerCamelCase							:     Union[str, Any]	=		logits.softmax(dim=-1)
                    if target_ids is not None:
                           _lowerCamelCase							:     List[Any]	=		probs[..., target_ids]

                    _lowerCamelCase,  _lowerCamelCase							:     Any	=		probs.topk(a__)

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

                           _lowerCamelCase							:     int	=		p
                           # Filter padding out:
                           _lowerCamelCase							:     List[Any]	=		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
                           _lowerCamelCase							:     str	=		self.tokenizer.decode(a__      ,							skip_special_tokens=a__)
                           _lowerCamelCase							:     List[str]	=		{'''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 				__snake_case			(		self      ,							a__      ,							a__=None):



             """simple docstring"""





             if isinstance(a__      ,							a__):
                    _lowerCamelCase							:     int	=		[targets]
             try:
                    _lowerCamelCase							:     Tuple	=		self.tokenizer.get_vocab()
             except Exception:
                    _lowerCamelCase							:     Union[str, Any]	=		{}
             _lowerCamelCase							:     List[Any]	=		[]
             for target in targets:
                    _lowerCamelCase							:     List[Any]	=		vocab.get(a__      ,							a__)
                    if id_ is None:
                           _lowerCamelCase							:     Optional[Any]	=		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
                           _lowerCamelCase							:     List[str]	=		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_)
             _lowerCamelCase							:     Tuple	=		list(set(a__))
             if len(a__) == 0:
                    raise ValueError('''At least one target must be provided when passed.''')
             _lowerCamelCase							:     Any	=		np.array(a__)
             return target_ids


      def 				__snake_case			(		self      ,							a__=None      ,							a__=None):



             """simple docstring"""





             _lowerCamelCase							:     List[Any]	=		{}

             if targets is not None:
                    _lowerCamelCase							:     List[Any]	=		self.get_target_ids(a__      ,							a__)
                    _lowerCamelCase							:     Optional[int]	=		target_ids

             if top_k is not None:
                    _lowerCamelCase							:     Any	=		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"""





             _lowerCamelCase							:     Optional[int]	=		super().__call__(a__      ,							**a__)
             if isinstance(a__      ,							a__) and len(a__) == 1:
                    return outputs[0]
             return outputs








import pytest

import datasets


# Import fixture modules as plugins
_lowerCamelCase			       =      ['tests.fixtures.files', 'tests.fixtures.hub', 'tests.fixtures.fsspec']




def    __UpperCAmelCase(      lowercase_ ,    lowercase_      ):
       # Mark tests as "unit" by default if not marked as "integration" (or already marked as "unit")
       for item in items:
              if any(marker in item.keywords for marker in ['''integration''', '''unit''']      ):
                     continue
              item.add_marker(pytest.mark.unit      )




def    __UpperCAmelCase(      lowercase_      ):
       config.addinivalue_line('''markers''' ,    '''torchaudio_latest: mark test to run with torchaudio>=0.12'''      )




@pytest.fixture(autouse=lowercase_      )
def    __UpperCAmelCase(      lowercase_ ,    lowercase_      ):
       # test_hf_cache_home = tmp_path_factory.mktemp("cache")  # TODO: why a cache dir per test function does not work?
       _lowerCamelCase							:     Optional[Any]	=		tmp_path_factory.getbasetemp() / '''cache'''
       _lowerCamelCase							:     Optional[Any]	=		test_hf_cache_home / '''datasets'''
       _lowerCamelCase							:     Union[str, Any]	=		test_hf_cache_home / '''metrics'''
       _lowerCamelCase							:     Dict	=		test_hf_cache_home / '''modules'''
       monkeypatch.setattr('''datasets.config.HF_DATASETS_CACHE''' ,    str(lowercase_      )      )
       monkeypatch.setattr('''datasets.config.HF_METRICS_CACHE''' ,    str(lowercase_      )      )
       monkeypatch.setattr('''datasets.config.HF_MODULES_CACHE''' ,    str(lowercase_      )      )
       _lowerCamelCase							:     str	=		test_hf_datasets_cache / '''downloads'''
       monkeypatch.setattr('''datasets.config.DOWNLOADED_DATASETS_PATH''' ,    str(lowercase_      )      )
       _lowerCamelCase							:     Optional[int]	=		test_hf_datasets_cache / '''downloads''' / '''extracted'''
       monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''' ,    str(lowercase_      )      )




@pytest.fixture(autouse=lowercase_ ,    scope='''session'''      )
def    __UpperCAmelCase(      ):
       datasets.disable_progress_bar()




@pytest.fixture(autouse=lowercase_      )
def    __UpperCAmelCase(      lowercase_      ):
       # don't take tests into account when counting downloads
       monkeypatch.setattr('''datasets.config.HF_UPDATE_DOWNLOAD_COUNTS''' ,    lowercase_      )




@pytest.fixture
def    __UpperCAmelCase(      lowercase_      ):
       # Required to suppress RemovedIn20Warning when feature(s) are not compatible with SQLAlchemy 2.0
       # To be removed once SQLAlchemy 2.0 supported
       monkeypatch.setattr('''sqlalchemy.util.deprecations.SILENCE_UBER_WARNING''' ,    lowercase_      )

