


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


UpperCAmelCase__   	=							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):





     def      __A					(self		,     UpperCAmelCase       )     ->   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=UpperCAmelCase       )
      else:
       raise ValueError('''Unsupported framework'''       )
      return masked_index





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





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





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

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

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





     def      __A					(self		,     UpperCAmelCase=None		,     UpperCAmelCase=None       )     ->   List[str]:
      _lowercase							      ={}

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





from typing import Any
def 				UpperCAmelCase_					(							__snake_case     ,						__snake_case     ,						__snake_case     ,						__snake_case     ,						__snake_case     ,						)     ->			list:







 """simple docstring"""


 _validation(
     __snake_case     ,						__snake_case     ,						__snake_case     ,						__snake_case     ,						__snake_case     ,						)
 # Creates data structures and fill initial step
 _lowercase							      ={}
 _lowercase							      ={}
 for state in states_space:
  _lowercase							      =observations_space[0]
  _lowercase							      =(
      initial_probabilities[state] * emission_probabilities[state][observation]
  )
  _lowercase							      =None

 # Fills the data structure with the probabilities of
 # different transitions and pointers to previous states
 for o in range(1     ,						len(__snake_case						)						):
  _lowercase							      =observations_space[o]
  _lowercase							      =observations_space[o - 1]
  for state in states_space:
   # Calculates the argmax for probability function
   _lowercase							      =''''''
   _lowercase							      =-1
   for k_state in states_space:
    _lowercase							      =(
        probabilities[(k_state, prior_observation)]
        * transition_probabilities[k_state][state]
        * emission_probabilities[state][observation]
    )
    if probability > max_probability:
     _lowercase							      =probability
     _lowercase							      =k_state

            # Update probabilities and pointers dicts
   _lowercase							      =(
       probabilities[(arg_max, prior_observation)]
       * transition_probabilities[arg_max][state]
       * emission_probabilities[state][observation]
   )

   _lowercase							      =arg_max

    # The final observation
 _lowercase							      =observations_space[len(__snake_case						) - 1]

 # argmax for given final observation
 _lowercase							      =''''''
 _lowercase							      =-1
 for k_state in states_space:
  _lowercase							      =probabilities[(k_state, final_observation)]
  if probability > max_probability:
   _lowercase							      =probability
   _lowercase							      =k_state
 _lowercase							      =arg_max

 # Process pointers backwards
 _lowercase							      =last_state
 _lowercase							      =[]
 for o in range(len(__snake_case						) - 1     ,						-1     ,						-1						):
  result.append(__snake_case						)
  _lowercase							      =pointers[previous, observations_space[o]]
 result.reverse()

 return result
def 				UpperCAmelCase_					(							__snake_case     ,						__snake_case     ,						__snake_case     ,						__snake_case     ,						__snake_case     ,						)     ->			None:







 """simple docstring"""


 _validate_not_empty(
     __snake_case     ,						__snake_case     ,						__snake_case     ,						__snake_case     ,						__snake_case     ,						)
 _validate_lists(__snake_case     ,						__snake_case						)
 _validate_dicts(
     __snake_case     ,						__snake_case     ,						__snake_case						)
def 				UpperCAmelCase_					(							__snake_case     ,						__snake_case     ,						__snake_case     ,						__snake_case     ,						__snake_case     ,						)     ->			None:







 """simple docstring"""


 if not all(
     [
         observations_space,
         states_space,
         initial_probabilities,
         transition_probabilities,
         emission_probabilities,
     ]						):
  raise ValueError('''There\'s an empty parameter'''						)
def 				UpperCAmelCase_					(							__snake_case     ,						__snake_case						)     ->			None:







 """simple docstring"""


 _validate_list(__snake_case     ,						'''observations_space'''						)
 _validate_list(__snake_case     ,						'''states_space'''						)
def 				UpperCAmelCase_					(							__snake_case     ,						__snake_case						)     ->			None:







 """simple docstring"""


 if not isinstance(_object     ,						__snake_case						):
  _lowercase							      =F"{var_name} must be a list"
  raise ValueError(__snake_case						)
 else:
  for x in _object:
   if not isinstance(__snake_case     ,						__snake_case						):
    _lowercase							      =F"{var_name} must be a list of strings"
    raise ValueError(__snake_case						)
def 				UpperCAmelCase_					(							__snake_case     ,						__snake_case     ,						__snake_case     ,						)     ->			None:







 """simple docstring"""


 _validate_dict(__snake_case     ,						'''initial_probabilities'''     ,						__snake_case						)
 _validate_nested_dict(__snake_case     ,						'''transition_probabilities'''						)
 _validate_nested_dict(__snake_case     ,						'''emission_probabilities'''						)
def 				UpperCAmelCase_					(							__snake_case     ,						__snake_case						)     ->			None:







 """simple docstring"""


 _validate_dict(_object     ,						__snake_case     ,						__snake_case						)
 for x in _object.values():
  _validate_dict(__snake_case     ,						__snake_case     ,						__snake_case     ,						__snake_case						)
def 				UpperCAmelCase_					(							__snake_case     ,						__snake_case     ,						__snake_case     ,						__snake_case = False						)     ->			None:







 """simple docstring"""


 if not isinstance(_object     ,						__snake_case						):
  _lowercase							      =F"{var_name} must be a dict"
  raise ValueError(__snake_case						)
 if not all(isinstance(__snake_case     ,						__snake_case						) for x in _object						):
  _lowercase							      =F"{var_name} all keys must be strings"
  raise ValueError(__snake_case						)
 if not all(isinstance(__snake_case     ,						__snake_case						) for x in _object.values()						):
  _lowercase							      ='''nested dictionary ''' if nested else ''''''
  _lowercase							      =F"{var_name} {nested_text}all values must be {value_type.__name__}"
  raise ValueError(__snake_case						)


if __name__ == "__main__":
  from doctest import testmod

  testmod()

