



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


UpperCAmelCase__   =       logging.get_logger(__name__)

UpperCAmelCase__   =       {"vocab_file": "spiece.model"}

UpperCAmelCase__   =       {
    "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
UpperCAmelCase__   =       {
    "t5-small": 512,
    "t5-base": 512,
    "t5-large": 512,
    "t5-3b": 512,
    "t5-11b": 512,
}

UpperCAmelCase__   =       "▁"







class 			__lowerCAmelCase    (			lowerCAmelCase_						):
			UpperCamelCase   					=     VOCAB_FILES_NAMES
			UpperCamelCase   					=     PRETRAINED_VOCAB_FILES_MAP
			UpperCamelCase   					=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			UpperCamelCase   					=     ['''input_ids''', '''attention_mask''']



			def __init__(						self   :  Dict ,		A   :  List[Any] ,		A   :  str="</s>" ,		A   :  List[Any]="<unk>" ,		A   :  Union[str, Any]="<pad>" ,		A   :  List[Any]=1_00 ,		A   :  str=None ,		A   :  Optional[Dict[str, Any]] = None ,		A   :  Optional[Any]=True ,		**A   :  List[str] ,		)   ->    None:



						"""simple docstring"""






						if extra_ids > 0 and additional_special_tokens is None:
									_UpperCAmelCase		       =   [F"<extra_id_{i}>" for i in range(_snake_case)]
						elif extra_ids > 0 and additional_special_tokens is not None:
									# Check that we have the right number of extra_id special tokens
									_UpperCAmelCase		       =   len(set(filter(lambda A: bool('extra_id' in str(_snake_case)) ,		_snake_case)))
									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')

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

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

						_UpperCAmelCase		       =   vocab_file
						_UpperCAmelCase		       =   extra_ids

						_UpperCAmelCase		       =   spm.SentencePieceProcessor(**self.sp_model_kwargs)
						self.sp_model.Load(_snake_case)



			@staticmethod
			def     _lowerCamelCase       (						A   :  Optional[int] ,		A   :  Optional[int] ,		A   :  List[Any])   ->    Tuple:



						"""simple docstring"""






						if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes:
									_UpperCAmelCase		       =   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.' ,		_snake_case ,		)

						return max_model_length



			@property
			def     _lowerCamelCase       (						self   :  Optional[Any])   ->    Tuple:



						"""simple docstring"""






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



			def     _lowerCamelCase       (						self   :  Optional[Any])   ->    List[Any]:



						"""simple docstring"""






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



			def     _lowerCamelCase       (						self   :  List[Any] ,		A   :  List[int] ,		A   :  Optional[List[int]] = None ,		A   :  bool = False)   ->    List[int]:



						"""simple docstring"""






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

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



			def     _lowerCamelCase       (						self   :  Tuple)   ->    Union[str, Any]:



						"""simple docstring"""






						return list(
						    set(filter(lambda A: bool(re.search(R'<extra_id_\d+>' ,		_snake_case)) is not None ,		self.additional_special_tokens)))



			def     _lowerCamelCase       (						self   :  Any)   ->    str:



						"""simple docstring"""






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



			def     _lowerCamelCase       (						self   :  Dict ,		A   :  List[int])   ->    List[int]:



						"""simple docstring"""






						if len(_snake_case) > 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   :  Optional[Any] ,		A   :  List[int] ,		A   :  Optional[List[int]] = None)   ->    List[int]:



						"""simple docstring"""






						_UpperCAmelCase		       =   [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   :  int ,		A   :  List[int] ,		A   :  Optional[List[int]] = None)   ->    List[int]:



						"""simple docstring"""






						_UpperCAmelCase		       =   self._add_eos_if_not_present(_snake_case)
						if token_ids_a is None:
									return token_ids_a
						else:
									_UpperCAmelCase		       =   self._add_eos_if_not_present(_snake_case)
									return token_ids_a + token_ids_a



			def __getstate__(						self   :  Optional[Any])   ->    Union[str, Any]:



						"""simple docstring"""






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



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



						"""simple docstring"""






						_UpperCAmelCase		       =   d

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

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



			def     _lowerCamelCase       (						self   :  Tuple ,		A   :  "TextInput" ,		**A   :  Union[str, Any])   ->    List[str]:



						"""simple docstring"""






						if not self.legacy:
									_UpperCAmelCase		       =   SPIECE_UNDERLINE + text.replace(_snake_case ,		' ')
						return super().tokenize(_snake_case ,		**_snake_case)



			def     _lowerCamelCase       (						self   :  int ,		A   :  Optional[Any] ,		**A   :  Optional[Any])   ->    int:



						"""simple docstring"""






						if not self.legacy:
									_UpperCAmelCase		       =   text.startswith(_snake_case)
									if is_first:
												_UpperCAmelCase		       =   text[1:]

						_UpperCAmelCase		       =   self.sp_model.encode(_snake_case ,		out_type=_snake_case)

						if not self.legacy and not is_first and not text.startswith(' ') and tokens[0].startswith(_snake_case):
									_UpperCAmelCase		       =   ([tokens[0][1:]] if len(tokens[0]) > 1 else []) + tokens[1:]
						return tokens



			def     _lowerCamelCase       (						self   :  Union[str, Any] ,		A   :  List[Any])   ->    int:



						"""simple docstring"""






						if token.startswith('<extra_id_'):
									_UpperCAmelCase		       =   re.match(R'<extra_id_(\d+)>' ,		_snake_case)
									_UpperCAmelCase		       =   int(match.group(1))
									return self.vocab_size - num - 1
						return self.sp_model.piece_to_id(_snake_case)



			def     _lowerCamelCase       (						self   :  int ,		A   :  int)   ->    int:



						"""simple docstring"""






						if index < self.sp_model.get_piece_size():
									_UpperCAmelCase		       =   self.sp_model.IdToPiece(_snake_case)
						else:
									_UpperCAmelCase		       =   F"<extra_id_{self.vocab_size - 1 - index}>"
						return token



			def     _lowerCamelCase       (						self   :  Optional[Any] ,		A   :  Union[str, Any])   ->    Optional[int]:



						"""simple docstring"""






						_UpperCAmelCase		       =   []
						_UpperCAmelCase		       =   ''
						_UpperCAmelCase		       =   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(_snake_case) + token
												_UpperCAmelCase		       =   True
												_UpperCAmelCase		       =   []
									else:
												current_sub_tokens.append(_snake_case)
												_UpperCAmelCase		       =   False
						out_string += self.sp_model.decode(_snake_case)
						return out_string.strip()



			def     _lowerCamelCase       (						self   :  int ,		A   :  str ,		A   :  Optional[str] = None)   ->    Tuple[str]:



						"""simple docstring"""






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

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

						return (out_vocab_file,)





from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


a_   :Any        =      "\\n@misc{wu2016googles,\n      title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n              and Jeffrey Dean},\n      year={2016},\n      eprint={1609.08144},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL}\n}\n"

a_   :List[str]        =      "\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe 'GLEU score'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore's range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n"

a_   :List[str]        =      "\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n    predictions (list of str): list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references (list of list of str): list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n    'google_bleu': google_bleu score\n\nExamples:\n    Example 1:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.44\n\n    Example 2:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.61\n\n    Example 3:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.53\n\n    Example 4:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.4\n"




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION				,     _KWARGS_DESCRIPTION     )
class 					snake_case__						(       datasets.Metric     ):






     """simple docstring"""


     def    lowercase_   (       self  :  str					)   ->MetricInfo:
            return datasets.MetricInfo(
                description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features(
                    {
                        'predictions': datasets.Sequence(datasets.Value('string', id='token'					), id='sequence'					),
                        'references': datasets.Sequence(
                            datasets.Sequence(datasets.Value('string', id='token'					), id='sequence'					), id='references'					),
                    }					), )






     def    lowercase_   (       self  :  str, _snake_case  :  List[List[List[str]]], _snake_case  :  List[List[str]], _snake_case  :  int = 1, _snake_case  :  int = 4, )   ->Dict[str, float]:
            return {
                "google_bleu": gleu_score.corpus_gleu(
                    list_of_references=_snake_case, hypotheses=_snake_case, min_len=_snake_case, max_len=_snake_case					)
            }






