"""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


_a     :     str= logging.get_logger(__name__)

@add_end_docstrings(
    lowerCamelCase__      ,	r"""\n        top_k (`int`, defaults to 5):\n            The number of predictions to return.\n        targets (`str` or `List[str]`, *optional*):\n            When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n            token will be used (with a warning, and that might be slower).\n\n    """      ,	)
class 		UpperCamelCase			(    lowerCamelCase__						):



				def 					_lowercase     (self				:      List[Any]	,  _A				:      GenericTensor)    ->	Union[str, Any]:
					if self.framework == "tf":
						__snake_case			:							Optional[Any]      		= tf.where(input_ids == self.tokenizer.mask_token_id).numpy()
					elif self.framework == "pt":
						__snake_case			:							Optional[int]      		= torch.nonzero(input_ids == self.tokenizer.mask_token_id	,  as_tuple=lowercase__)
					else:
						raise ValueError('Unsupported framework')
					return masked_index



				def 					_lowercase     (self				:      List[str]	,  _A				:      GenericTensor)    ->	Dict:
					__snake_case			:							int      		= self.get_masked_index(lowercase__)
					__snake_case			:							Optional[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 					_lowercase     (self				:      Any	,  _A				:      GenericTensor)    ->	int:
					if isinstance(lowercase__	,  lowercase__):
						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(lowercase__)



				def 					_lowercase     (self				:      Optional[Any]	,  _A				:      str	,  _A				:      Union[str, Any]=None	,  **_A				:      Any)    ->	Optional[int]:
					if return_tensors is None:
						__snake_case			:							Dict      		= self.framework
					__snake_case			:							List[str]      		= self.tokenizer(lowercase__	,  return_tensors=lowercase__)
					self.ensure_exactly_one_mask_token(lowercase__)
					return model_inputs



				def 					_lowercase     (self				:      Tuple	,  _A				:      int)    ->	Any:
					__snake_case			:							Tuple      		= self.model(**lowercase__)
					__snake_case			:							Tuple      		= model_inputs['input_ids']
					return model_outputs



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

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

						__snake_case			:							Optional[int]      		= outputs.numpy()

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

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

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

						__snake_case		,				__snake_case			:							int      		= probs.topk(lowercase__)

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

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



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



				def 					_lowercase     (self				:      List[str]	,  _A				:      int=None	,  _A				:      List[str]=None)    ->	Tuple:
					__snake_case			:							List[Any]      		= {}

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








'''simple docstring'''






import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowerCAmelCase__											=	logging.get_logger(__name__)

lowerCAmelCase__											=	{'''vocab_file''': '''spiece.model'''}

lowerCAmelCase__											=	{
    '''vocab_file''': {
        '''bert_for_seq_generation''': (
            '''https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model'''
        ),
    }
}

lowerCAmelCase__											=	{'''bert_for_seq_generation''': 512}






class 			lowercase_	(lowerCamelCase__      ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  List[Any]							=			VOCAB_FILES_NAMES
  SCREAMING_SNAKE_CASE    :  Dict							=			PRETRAINED_VOCAB_FILES_MAP
  SCREAMING_SNAKE_CASE    :  Optional[int]							=			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  SCREAMING_SNAKE_CASE    :  List[int]							=			[]
  SCREAMING_SNAKE_CASE    :  Any							=			['input_ids', 'attention_mask']






  def __init__(      self   :     Optional[Any]					,lowercase__   :     Tuple					,lowercase__   :     Tuple="<s>"					,lowercase__   :     Union[str, Any]="</s>"					,lowercase__   :     str="<unk>"					,lowercase__   :     Tuple="<pad>"					,lowercase__   :     Union[str, Any]="<::::>"					,lowercase__   :     Optional[Dict[str, Any]] = None					,**lowercase__   :     Any					,):
   __lowercase							  = {} if sp_model_kwargs is None else sp_model_kwargs

   # Add extra_ids to the special token list
   super().__init__(
       bos_token=lowercase__					,eos_token=lowercase__					,unk_token=lowercase__					,pad_token=lowercase__					,sep_token=lowercase__					,sp_model_kwargs=self.sp_model_kwargs					,**lowercase__					,)

   __lowercase							  = vocab_file

   __lowercase							  = spm.SentencePieceProcessor(**self.sp_model_kwargs			)
   self.sp_model.Load(lowercase__			)






  @property
  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[int]			):
   return self.sp_model.get_piece_size()






  def 					SCREAMING_SNAKE_CASE      (      self   :     Union[str, Any]			):
   __lowercase							  = {self.convert_ids_to_tokens(lowercase__			): i for i in range(self.vocab_size			)}
   vocab.update(self.added_tokens_encoder			)
   return vocab






  def __getstate__(      self   :     str			):
   __lowercase							  = self.__dict__.copy()
   __lowercase							  = None
   return state






  def __setstate__(      self   :     Optional[int]					,lowercase__   :     Optional[Any]			):
   __lowercase							  = d

   # for backward compatibility
   if not hasattr(self					,'''sp_model_kwargs'''			):
    __lowercase							  = {}

   __lowercase							  = spm.SentencePieceProcessor(**self.sp_model_kwargs			)
   self.sp_model.Load(self.vocab_file			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     str					,lowercase__   :     str			):
   return self.sp_model.encode(lowercase__					,out_type=lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Tuple					,lowercase__   :     Union[str, Any]			):
   return self.sp_model.piece_to_id(lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Any					,lowercase__   :     Tuple			):
   __lowercase							  = self.sp_model.IdToPiece(lowercase__			)
   return token






  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[int]					,lowercase__   :     int			):
   __lowercase							  = []
   __lowercase							  = ''''''
   for token in tokens:
    # make sure that special tokens are not decoded using sentencepiece model
    if token in self.all_special_tokens:
     out_string += self.sp_model.decode(lowercase__			) + token
     __lowercase							  = []
    else:
     current_sub_tokens.append(lowercase__			)
   out_string += self.sp_model.decode(lowercase__			)
   return out_string.strip()






  def 					SCREAMING_SNAKE_CASE      (      self   :     int					,lowercase__   :     str					,lowercase__   :     Optional[str] = None			):
   if not os.path.isdir(lowercase__			):
    logger.error(F"Vocabulary path ({save_directory}) should be a directory"			)
    return
   __lowercase							  = os.path.join(
       lowercase__					,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']			)

   if os.path.abspath(self.vocab_file			) != os.path.abspath(lowercase__			) and os.path.isfile(self.vocab_file			):
    copyfile(self.vocab_file					,lowercase__			)
   elif not os.path.isfile(self.vocab_file			):
    with open(lowercase__					,'''wb'''			) as fi:
     __lowercase							  = self.sp_model.serialized_model_proto()
     fi.write(lowercase__			)

   return (out_vocab_file,)

