





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(
    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        _lowerCAmelCase    (			UpperCAmelCase_							):


  '''simple docstring'''







  def UpperCamelCase_ (      self      :					Tuple      ,				UpperCamelCase      :					GenericTensor							):


    '''simple docstring'''





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







  def UpperCamelCase_ (      self      :					List[str]      ,				UpperCamelCase      :					GenericTensor							):


    '''simple docstring'''





    _snake_case   :				int														=	self.get_masked_index(UpperCamelCase							)
    _snake_case   :				int														=	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      :					List[Any]      ,				UpperCamelCase      :					GenericTensor							):


    '''simple docstring'''





    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 UpperCamelCase_ (      self      :					Optional[Any]      ,				UpperCamelCase      :					Optional[Any]      ,				UpperCamelCase      :					Dict=None      ,				**UpperCamelCase      :					Union[str, Any]							):


    '''simple docstring'''





    if return_tensors is None:
      _snake_case   :				int														=	self.framework
    _snake_case   :				Optional[int]														=	self.tokenizer(UpperCamelCase      ,				return_tensors=UpperCamelCase							)
    self.ensure_exactly_one_mask_token(UpperCamelCase							)
    return model_inputs







  def UpperCamelCase_ (      self      :					List[Any]      ,				UpperCamelCase      :					Union[str, Any]							):


    '''simple docstring'''





    _snake_case   :				str														=	self.model(**UpperCamelCase							)
    _snake_case   :				int														=	model_inputs['input_ids']
    return model_outputs







  def UpperCamelCase_ (      self      :					Union[str, Any]      ,				UpperCamelCase      :					Union[str, Any]      ,				UpperCamelCase      :					List[str]=5      ,				UpperCamelCase      :					Any=None							):


    '''simple docstring'''





    if target_ids is not None and target_ids.shape[0] < top_k:
      _snake_case   :				Optional[Any]														=	target_ids.shape[0]
    _snake_case   :				Any														=	model_outputs['input_ids'][0]
    _snake_case   :				Optional[int]														=	model_outputs['logits']

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

      _snake_case   :				List[Any]														=	outputs.numpy()

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

      _snake_case   :				List[str]														=	tf.math.top_k(UpperCamelCase      ,				k=UpperCamelCase							)
      _snake_case							,					_snake_case   :				Dict														=	topk.values.numpy(), topk.indices.numpy()
    else:
      _snake_case   :				Optional[Any]														=	torch.nonzero(input_ids == self.tokenizer.mask_token_id      ,				as_tuple=UpperCamelCase							).squeeze(-1							)
      # Fill mask pipeline supports only one ${mask_token} per sample

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

      _snake_case							,					_snake_case   :				int														=	probs.topk(UpperCamelCase							)

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

        _snake_case   :				Tuple														=	p
        # Filter padding out:
        _snake_case   :				Union[str, 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
        _snake_case   :				Optional[int]														=	self.tokenizer.decode(UpperCamelCase      ,				skip_special_tokens=UpperCamelCase							)
        _snake_case   :				str														=	{'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 UpperCamelCase_ (      self      :					int      ,				UpperCamelCase      :					List[Any]      ,				UpperCamelCase      :					str=None							):


    '''simple docstring'''





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







  def UpperCamelCase_ (      self      :					Any      ,				UpperCamelCase      :					str=None      ,				UpperCamelCase      :					Any=None							):


    '''simple docstring'''





    _snake_case   :				Union[str, Any]														=	{}

    if targets is not None:
      _snake_case   :				Tuple														=	self.get_target_ids(UpperCamelCase      ,				UpperCamelCase							)
      _snake_case   :				Dict														=	target_ids

    if top_k is not None:
      _snake_case   :				Union[str, 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      :					Tuple      ,				UpperCamelCase      :					Dict      ,				*UpperCamelCase      :					str      ,				**UpperCamelCase      :					Union[str, Any]							):


    '''simple docstring'''





    _snake_case   :				str														=	super().__call__(UpperCamelCase      ,				**UpperCamelCase							)
    if isinstance(UpperCamelCase      ,				UpperCamelCase							) and len(UpperCamelCase							) == 1:
      return outputs[0]
    return outputs











import copy
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Optional, Union



@dataclass
class        _lowerCAmelCase    :


  '''simple docstring'''
  a_							:       Optional[Union[str, Path]]      					=None
  a_							:       bool      					=False
  a_							:       bool      					=False
  a_							:       bool      					=False
  a_							:       Optional[Dict]      					=None
  a_							:       Optional[str]      					=None
  a_							:       bool      					=False
  a_							:       bool      					=False
  a_							:       bool      					=False
  a_							:       bool      					=True
  a_							:       Optional[int]      					=None
  a_							:       int      					=1
  a_							:       Optional[Union[str, bool]]      					=None
  a_							:       bool      					=False
  a_							:       Optional[Dict]      					=None
  a_							:       Optional[str]      					=None







  def UpperCamelCase_ (      self      :					Dict							):


    '''simple docstring'''





    return self.__class__(**{k: copy.deepcopy(UpperCamelCase							) for k, v in self.__dict__.items()}							)




