





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


snake_case 				=       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 				A_				(      UpperCAmelCase	):







       """simple docstring"""





       def    __UpperCAmelCase (    self	:	List[Any]						,__A	:	GenericTensor  )						->					np.ndarray:
         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=__A  )
         else:
           raise ValueError('Unsupported framework'  )
         return masked_index







       def    __UpperCAmelCase (    self	:	Optional[int]						,__A	:	GenericTensor  )						->					np.ndarray:
         _lowercase							= self.get_masked_index(__A  )
         _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    __UpperCAmelCase (    self	:	Tuple						,__A	:	GenericTensor  )						->					List[str]:
         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    __UpperCAmelCase (    self	:	Tuple						,__A	:	List[str]						,__A	:	Any=None						,**__A	:	Tuple  )						->					Dict[str, GenericTensor]:
         if return_tensors is None:
           _lowercase							= self.framework
         _lowercase							= self.tokenizer(__A						,return_tensors=__A  )
         self.ensure_exactly_one_mask_token(__A  )
         return model_inputs







       def    __UpperCAmelCase (    self	:	Tuple						,__A	:	Any  )						->					Tuple:
         _lowercase							= self.model(**__A  )
         _lowercase							= model_inputs['input_ids']
         return model_outputs







       def    __UpperCAmelCase (    self	:	Union[str, Any]						,__A	:	Tuple						,__A	:	Dict=5						,__A	:	str=None  )						->					Dict:
         # 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(__A						,axis=-1  )
           if target_ids is not None:
             _lowercase							= tf.gather_nd(tf.squeeze(__A						,0  )						,target_ids.reshape(-1						,1  )  )
             _lowercase							= tf.expand_dims(__A						,0  )

           _lowercase							= tf.math.top_k(__A						,k=__A  )
           _lowercase						,		_lowercase							= topk.values.numpy(), topk.indices.numpy()
         else:
           _lowercase							= torch.nonzero(input_ids == self.tokenizer.mask_token_id						,as_tuple=__A  ).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(__A  )

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







       def    __UpperCAmelCase (    self	:	Optional[int]						,__A	:	str=None						,__A	:	Any=None  )						->					Tuple:
         _lowercase							= {}

         if targets is not None:
           _lowercase							= self.get_target_ids(__A						,__A  )
           _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	:	int						,__A	:	List[str]						,*__A	:	Tuple						,**__A	:	int  )						->					Optional[Any]:
         _lowercase							= super().__call__(__A						,**__A  )
         if isinstance(__A						,__A  ) and len(__A  ) == 1:
           return outputs[0]
         return outputs






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tensorflow_text_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


snake_case 				=       {
    """configuration_bert""": ["""BERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BertConfig""", """BertOnnxConfig"""],
    """tokenization_bert""": ["""BasicTokenizer""", """BertTokenizer""", """WordpieceTokenizer"""],
}

try:
      if not is_tokenizers_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      snake_case 				=       ["""BertTokenizerFast"""]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      snake_case 				=       [
          """BERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """BertForMaskedLM""",
          """BertForMultipleChoice""",
          """BertForNextSentencePrediction""",
          """BertForPreTraining""",
          """BertForQuestionAnswering""",
          """BertForSequenceClassification""",
          """BertForTokenClassification""",
          """BertLayer""",
          """BertLMHeadModel""",
          """BertModel""",
          """BertPreTrainedModel""",
          """load_tf_weights_in_bert""",
      ]

try:
      if not is_tf_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      snake_case 				=       [
          """TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """TFBertEmbeddings""",
          """TFBertForMaskedLM""",
          """TFBertForMultipleChoice""",
          """TFBertForNextSentencePrediction""",
          """TFBertForPreTraining""",
          """TFBertForQuestionAnswering""",
          """TFBertForSequenceClassification""",
          """TFBertForTokenClassification""",
          """TFBertLMHeadModel""",
          """TFBertMainLayer""",
          """TFBertModel""",
          """TFBertPreTrainedModel""",
      ]
try:
      if not is_tensorflow_text_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      snake_case 				=       ["""TFBertTokenizer"""]

try:
      if not is_flax_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      snake_case 				=       [
          """FlaxBertForCausalLM""",
          """FlaxBertForMaskedLM""",
          """FlaxBertForMultipleChoice""",
          """FlaxBertForNextSentencePrediction""",
          """FlaxBertForPreTraining""",
          """FlaxBertForQuestionAnswering""",
          """FlaxBertForSequenceClassification""",
          """FlaxBertForTokenClassification""",
          """FlaxBertModel""",
          """FlaxBertPreTrainedModel""",
      ]

if TYPE_CHECKING:
      from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig
      from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer

      try:
            if not is_tokenizers_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_bert_fast import BertTokenizerFast

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_bert import (
                BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
                BertForMaskedLM,
                BertForMultipleChoice,
                BertForNextSentencePrediction,
                BertForPreTraining,
                BertForQuestionAnswering,
                BertForSequenceClassification,
                BertForTokenClassification,
                BertLayer,
                BertLMHeadModel,
                BertModel,
                BertPreTrainedModel,
                load_tf_weights_in_bert,
            )

      try:
            if not is_tf_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_tf_bert import (
                TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
                TFBertEmbeddings,
                TFBertForMaskedLM,
                TFBertForMultipleChoice,
                TFBertForNextSentencePrediction,
                TFBertForPreTraining,
                TFBertForQuestionAnswering,
                TFBertForSequenceClassification,
                TFBertForTokenClassification,
                TFBertLMHeadModel,
                TFBertMainLayer,
                TFBertModel,
                TFBertPreTrainedModel,
            )

      try:
            if not is_tensorflow_text_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_bert_tf import TFBertTokenizer

      try:
            if not is_flax_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_flax_bert import (
                FlaxBertForCausalLM,
                FlaxBertForMaskedLM,
                FlaxBertForMultipleChoice,
                FlaxBertForNextSentencePrediction,
                FlaxBertForPreTraining,
                FlaxBertForQuestionAnswering,
                FlaxBertForSequenceClassification,
                FlaxBertForTokenClassification,
                FlaxBertModel,
                FlaxBertPreTrainedModel,
            )

else:
      import sys

      snake_case 				=       _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)