'''simple docstring'''
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


lowercase__  :      Optional[int]        =					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 lowerCamelCase							(	lowerCamelCase					):




  '''simple docstring'''



  def  lowerCAmelCase__ (      self			:       Dict  ,							UpperCAmelCase__			:       GenericTensor  )				->np.ndarray:
        if self.framework == "tf":
              UpperCAmelCase_            =  tf.where(input_ids == self.tokenizer.mask_token_id  ).numpy()
        elif self.framework == "pt":
              UpperCAmelCase_            =  torch.nonzero(input_ids == self.tokenizer.mask_token_id  ,							as_tuple=UpperCAmelCase__  )
        else:
              raise ValueError('''Unsupported framework'''  )
        return masked_index






  def  lowerCAmelCase__ (      self			:       Any  ,							UpperCAmelCase__			:       GenericTensor  )				->np.ndarray:
        UpperCAmelCase_            =  self.get_masked_index(UpperCAmelCase__  )
        UpperCAmelCase_            =  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  lowerCAmelCase__ (      self			:       Tuple  ,							UpperCAmelCase__			:       GenericTensor  )				->Optional[Any]:
        if isinstance(UpperCAmelCase__  ,							UpperCAmelCase__  ):
              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(UpperCAmelCase__  )






  def  lowerCAmelCase__ (      self			:       List[Any]  ,							UpperCAmelCase__			:       List[str]  ,							UpperCAmelCase__			:       Optional[int]=None  ,							**UpperCAmelCase__			:       int  )				->Dict[str, GenericTensor]:
        if return_tensors is None:
              UpperCAmelCase_            =  self.framework
        UpperCAmelCase_            =  self.tokenizer(UpperCAmelCase__  ,							return_tensors=UpperCAmelCase__  )
        self.ensure_exactly_one_mask_token(UpperCAmelCase__  )
        return model_inputs






  def  lowerCAmelCase__ (      self			:       int  ,							UpperCAmelCase__			:       Optional[Any]  )				->Any:
        UpperCAmelCase_            =  self.model(**UpperCAmelCase__  )
        UpperCAmelCase_            =  model_inputs['''input_ids''']
        return model_outputs






  def  lowerCAmelCase__ (      self			:       Optional[Any]  ,							UpperCAmelCase__			:       Tuple  ,							UpperCAmelCase__			:       Union[str, Any]=5  ,							UpperCAmelCase__			:       Union[str, Any]=None  )				->List[str]:
        # Cap top_k if there are targets
        if target_ids is not None and target_ids.shape[0] < top_k:
              UpperCAmelCase_            =  target_ids.shape[0]
        UpperCAmelCase_            =  model_outputs['''input_ids'''][0]
        UpperCAmelCase_            =  model_outputs['''logits''']

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

              UpperCAmelCase_            =  outputs.numpy()

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

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

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

              UpperCAmelCase_      ,		UpperCAmelCase_            =  probs.topk(UpperCAmelCase__  )

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

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






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






  def  lowerCAmelCase__ (      self			:       Dict  ,							UpperCAmelCase__			:       List[str]=None  ,							UpperCAmelCase__			:       Optional[Any]=None  )				->Dict:
        UpperCAmelCase_            =  {}

        if targets is not None:
              UpperCAmelCase_            =  self.get_target_ids(UpperCAmelCase__  ,							UpperCAmelCase__  )
              UpperCAmelCase_            =  target_ids

        if top_k is not None:
              UpperCAmelCase_            =  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[str]  ,							UpperCAmelCase__			:       Union[str, Any]  ,							*UpperCAmelCase__			:       List[str]  ,							**UpperCAmelCase__			:       Tuple  )				->str:
        UpperCAmelCase_            =  super().__call__(UpperCAmelCase__  ,							**UpperCAmelCase__  )
        if isinstance(UpperCAmelCase__  ,							UpperCAmelCase__  ) and len(UpperCAmelCase__  ) == 1:
              return outputs[0]
        return outputs






'''simple docstring'''
from ...utils import logging
from ..ta.modeling_tf_ta import TFTaEncoderModel, TFTaForConditionalGeneration, TFTaModel
from .configuration_mta import MTaConfig


lowercase__  :      Dict        =					logging.get_logger(__name__)

lowercase__  :      List[Any]        =					"T5Config"







class lowerCamelCase							(	lowerCamelCase					):




  '''simple docstring'''



  lowerCAmelCase__										=	'''mt5'''
  lowerCAmelCase__										=	MTaConfig







class lowerCamelCase							(	lowerCamelCase					):




  '''simple docstring'''



  lowerCAmelCase__										=	'''mt5'''
  lowerCAmelCase__										=	MTaConfig







class lowerCamelCase							(	lowerCamelCase					):




  '''simple docstring'''



  lowerCAmelCase__										=	'''mt5'''
  lowerCAmelCase__										=	MTaConfig





