




'''simple docstring'''





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

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer


if TYPE_CHECKING:
		from ...tokenization_utils_base import TextInput
from ...utils import logging


_SCREAMING_SNAKE_CASE							:   Tuple      		= logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE							:   List[str]      		= {'vocab_file': 'spiece.model'}

_SCREAMING_SNAKE_CASE							:   Any      		= {
    'vocab_file': {
        't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model',
        't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model',
        't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model',
        't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model',
        't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model',
    }
}


# TODO(PVP) - this should be removed in Transformers v5
_SCREAMING_SNAKE_CASE							:   Optional[Any]      		= {
    't5-small': 512,
    't5-base': 512,
    't5-large': 512,
    't5-3b': 512,
    't5-11b': 512,
}

_SCREAMING_SNAKE_CASE							:   List[str]      		= '▁'




class  _snake_case		(	A__							):
			lowerCAmelCase_     :      str						       =    VOCAB_FILES_NAMES
			lowerCAmelCase_     :      int						       =    PRETRAINED_VOCAB_FILES_MAP
			lowerCAmelCase_     :      List[Any]						       =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			lowerCAmelCase_     :      str						       =    ["input_ids", "attention_mask"]




			def __init__(					self				,							a__				,							a__="</s>"				,							a__="<unk>"				,							a__="<pad>"				,							a__=100				,							a__=None				,							a__ = None				,							a__=True				,							**a__				,							)				->				Optional[Any]:

										'''simple docstring'''




										if extra_ids > 0 and additional_special_tokens is None:
																	snake_case_						=      [F'<extra_id_{i}>' for i in range(a__							)]
										elif extra_ids > 0 and additional_special_tokens is not None:
																	# Check that we have the right number of extra_id special tokens
																	snake_case_						=      len(set(filter(lambda a__							: bool("extra_id" in str(a__							)							)				,							a__							)							)							)
																	if extra_tokens != extra_ids:
																								raise ValueError(
																								    F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are'
																								    " provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids"
																								    " tokens"							)
										if legacy:
																	logger.warning_once(
																	    F'You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'
																	    " read the related pull request available at https://github.com/huggingface/transformers/pull/24565"							)

										snake_case_						=      legacy
										snake_case_						=      {} if sp_model_kwargs is None else sp_model_kwargs

										super().__init__(
										    eos_token=a__				,							unk_token=a__				,							pad_token=a__				,							extra_ids=a__				,							additional_special_tokens=a__				,							sp_model_kwargs=self.sp_model_kwargs				,							legacy=a__				,							**a__				,							)

										snake_case_						=      vocab_file
										snake_case_						=      extra_ids

										snake_case_						=      spm.SentencePieceProcessor(**self.sp_model_kwargs							)
										self.sp_model.Load(a__							)




			@staticmethod
			def    lowerCAmelCase__				(					a__				,							a__				,							a__							)				->				str:

										'''simple docstring'''




										if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes:
																	snake_case_						=      TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path]
																	if init_max_model_length is not None and init_max_model_length != max_model_length:
																								return init_max_model_length
																	elif init_max_model_length is None:
																								warnings.warn(
																								    "This tokenizer was incorrectly instantiated with a model max length of"
																								    F' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this'
																								    " behavior is kept to avoid breaking backwards compatibility when padding/encoding with"
																								    " `truncation is True`.\n- Be aware that you SHOULD NOT rely on"
																								    F' {pretrained_model_name_or_path} automatically truncating your input to'
																								    F' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences'
																								    F' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with'
																								    " `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please"
																								    " instantiate this tokenizer with `model_max_length` set to your preferred value."				,							a__				,							)

										return max_model_length




			@property
			def    lowerCAmelCase__				(					self							)				->				List[str]:

										'''simple docstring'''




										return self.sp_model.get_piece_size() + self._extra_ids




			def    lowerCAmelCase__				(					self							)				->				str:

										'''simple docstring'''




										snake_case_						=      {self.convert_ids_to_tokens(a__							): i for i in range(self.vocab_size							)}
										vocab.update(self.added_tokens_encoder							)
										return vocab




			def    lowerCAmelCase__				(					self				,							a__				,							a__ = None				,							a__ = False							)				->				Dict:

										'''simple docstring'''




										if already_has_special_tokens:
																	return super().get_special_tokens_mask(
																	    token_ids_a=a__				,							token_ids_a=a__				,							already_has_special_tokens=a__							)

										# normal case: some special tokens
										if token_ids_a is None:
																	return ([0] * len(a__							)) + [1]
										return ([0] * len(a__							)) + [1] + ([0] * len(a__							)) + [1]




			def    lowerCAmelCase__				(					self							)				->				Dict:

										'''simple docstring'''




										return list(
										    set(filter(lambda a__							: bool(re.search(r"<extra_id_\d+>"				,							a__							)							) is not None				,							self.additional_special_tokens							)							)							)




			def    lowerCAmelCase__				(					self							)				->				str:

										'''simple docstring'''




										return [self._convert_token_to_id(a__							) for token in self.get_sentinel_tokens()]




			def    lowerCAmelCase__				(					self				,							a__							)				->				Optional[int]:

										'''simple docstring'''




										if len(a__							) > 0 and token_ids[-1] == self.eos_token_id:
																	warnings.warn(
																	    F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated'
																	    " eos tokens being added."							)
																	return token_ids
										else:
																	return token_ids + [self.eos_token_id]




			def    lowerCAmelCase__				(					self				,							a__				,							a__ = None							)				->				Tuple:

										'''simple docstring'''




										snake_case_						=      [self.eos_token_id]

										if token_ids_a is None:
																	return len(token_ids_a + eos							) * [0]
										return len(token_ids_a + eos + token_ids_a + eos							) * [0]




			def    lowerCAmelCase__				(					self				,							a__				,							a__ = None							)				->				Tuple:

										'''simple docstring'''




										snake_case_						=      self._add_eos_if_not_present(a__							)
										if token_ids_a is None:
																	return token_ids_a
										else:
																	snake_case_						=      self._add_eos_if_not_present(a__							)
																	return token_ids_a + token_ids_a




			def __getstate__(					self							)				->				List[Any]:

										'''simple docstring'''




										snake_case_						=      self.__dict__.copy()
										snake_case_						=      None
										return state




			def __setstate__(					self				,							a__							)				->				Optional[int]:

										'''simple docstring'''




										snake_case_						=      d

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

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




			def    lowerCAmelCase__				(					self				,							a__				,							**a__							)				->				Optional[int]:

										'''simple docstring'''




										if not self.legacy:
																	snake_case_						=      SPIECE_UNDERLINE + text.replace(a__				,							" "							)
										return super().tokenize(a__				,							**a__							)




			def    lowerCAmelCase__				(					self				,							a__				,							**a__							)				->				int:

										'''simple docstring'''




										if not self.legacy:
																	snake_case_						=      text.startswith(a__							)
																	if is_first:
																								snake_case_						=      text[1:]

										snake_case_						=      self.sp_model.encode(a__				,							out_type=a__							)

										if not self.legacy and not is_first and not text.startswith(" "							) and tokens[0].startswith(a__							):
																	snake_case_						=      ([tokens[0][1:]] if len(tokens[0]							) > 1 else []) + tokens[1:]
										return tokens




			def    lowerCAmelCase__				(					self				,							a__							)				->				Optional[Any]:

										'''simple docstring'''




										if token.startswith("<extra_id_"							):
																	snake_case_						=      re.match(r"<extra_id_(\d+)>"				,							a__							)
																	snake_case_						=      int(match.group(1							)							)
																	return self.vocab_size - num - 1
										return self.sp_model.piece_to_id(a__							)




			def    lowerCAmelCase__				(					self				,							a__							)				->				Tuple:

										'''simple docstring'''




										if index < self.sp_model.get_piece_size():
																	snake_case_						=      self.sp_model.IdToPiece(a__							)
										else:
																	snake_case_						=      F'<extra_id_{self.vocab_size - 1 - index}>'
										return token




			def    lowerCAmelCase__				(					self				,							a__							)				->				Tuple:

										'''simple docstring'''




										snake_case_						=      []
										snake_case_						=      ""
										snake_case_						=      False
										for token in tokens:
																	# make sure that special tokens are not decoded using sentencepiece model
																	if token in self.all_special_tokens:
																								if not prev_is_special:
																															out_string += " "
																								out_string += self.sp_model.decode(a__							) + token
																								snake_case_						=      True
																								snake_case_						=      []
																	else:
																								current_sub_tokens.append(a__							)
																								snake_case_						=      False
										out_string += self.sp_model.decode(a__							)
										return out_string.strip()




			def    lowerCAmelCase__				(					self				,							a__				,							a__ = None							)				->				Optional[int]:

										'''simple docstring'''




										if not os.path.isdir(a__							):
																	logger.error(F'Vocabulary path ({save_directory}) should be a directory'							)
																	return
										snake_case_						=      os.path.join(
										    a__				,							(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]							)

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

										return (out_vocab_file,)












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__	:			Dict			   = logging.get_logger(__name__)
@add_end_docstrings(
    A__		,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       _UpperCAmelCase					(       A__	):

				"""simple docstring"""




				def 				lowercase__   (     self						:    Optional[int],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								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=lowerCamelCase  )
								else:
												raise ValueError('''Unsupported framework'''  )
								return masked_index




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								lowercase__    =			self.get_masked_index(lowerCamelCase  )
								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 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								if isinstance(lowerCamelCase,  lowerCamelCase  ):
												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(lowerCamelCase  )




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    Union[str, Any],  lowerCamelCase						:    Optional[int]=None,  **lowerCamelCase						:    Dict  ):

								'''simple docstring'''
								if return_tensors is None:
												lowercase__    =			self.framework
								lowercase__    =			self.tokenizer(lowerCamelCase,  return_tensors=lowerCamelCase  )
								self.ensure_exactly_one_mask_token(lowerCamelCase  )
								return model_inputs




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    int  ):

								'''simple docstring'''
								lowercase__    =			self.model(**lowerCamelCase  )
								lowercase__    =			model_inputs['''input_ids''']
								return model_outputs




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    List[str],  lowerCamelCase						:    Tuple=5,  lowerCamelCase						:    List[Any]=None  ):

								'''simple docstring'''
								# 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(lowerCamelCase,  axis=-1  )
												if target_ids is not None:
																lowercase__    =			tf.gather_nd(tf.squeeze(lowerCamelCase,  0  ),  target_ids.reshape(-1,  1  )  )
																lowercase__    =			tf.expand_dims(lowerCamelCase,  0  )

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

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




				def 				lowercase__   (     self						:    int,  lowerCamelCase						:    Optional[int],  lowerCamelCase						:    Dict=None  ):

								'''simple docstring'''
								if isinstance(lowerCamelCase,  lowerCamelCase  ):
												lowercase__    =			[targets]
								try:
												lowercase__    =			self.tokenizer.get_vocab()
								except Exception:
												lowercase__    =			{}
								lowercase__    =			[]
								for target in targets:
												lowercase__    =			vocab.get(lowerCamelCase,  lowerCamelCase  )
												if id_ is None:
																lowercase__    =			self.tokenizer(
																    lowerCamelCase,  add_special_tokens=lowerCamelCase,  return_attention_mask=lowerCamelCase,  return_token_type_ids=lowerCamelCase,  max_length=1,  truncation=lowerCamelCase,  )['''input_ids''']
																if len(lowerCamelCase  ) == 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(lowerCamelCase  )  )
								if len(lowerCamelCase  ) == 0:
												raise ValueError('''At least one target must be provided when passed.'''  )
								lowercase__    =			np.array(lowerCamelCase  )
								return target_ids




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    int=None,  lowerCamelCase						:    Any=None  ):

								'''simple docstring'''
								lowercase__    =			{}

								if targets is not None:
												lowercase__    =			self.get_target_ids(lowerCamelCase,  lowerCamelCase  )
												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						:    List[Any],  lowerCamelCase						:    Optional[Any],  *lowerCamelCase						:    Optional[Any],  **lowerCamelCase						:    Optional[Any]  ):

								'''simple docstring'''
								lowercase__    =			super().__call__(lowerCamelCase,  **lowerCamelCase  )
								if isinstance(lowerCamelCase,  lowerCamelCase  ) and len(lowerCamelCase  ) == 1:
												return outputs[0]
								return outputs




