


from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


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

lowerCAmelCase__    :int       =				'''\
The BLEU score has some undesirable properties when used for single
sentences, as it was designed to be a corpus measure. We therefore
use a slightly different score for our RL experiments which we call
the \'GLEU score\'. For the GLEU score, we record all sub-sequences of
1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then
compute a recall, which is the ratio of the number of matching n-grams
to the number of total n-grams in the target (ground truth) sequence,
and a precision, which is the ratio of the number of matching n-grams
to the number of total n-grams in the generated output sequence. Then
GLEU score is simply the minimum of recall and precision. This GLEU
score\'s range is always between 0 (no matches) and 1 (all match) and
it is symmetrical when switching output and target. According to
our experiments, GLEU score correlates quite well with the BLEU
metric on a corpus level but does not have its drawbacks for our per
sentence reward objective.
'''

lowerCAmelCase__    :Tuple       =				'''\
Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.
Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching
tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.

Args:
    predictions (list of str): list of translations to score.
        Each translation should be tokenized into a list of tokens.
    references (list of list of str): list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.
    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.

Returns:
    \'google_bleu\': google_bleu score

Examples:
    Example 1:
        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',
        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',
        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']
        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',
        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',
        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']

        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',
        ...         \'interested\', \'in\', \'world\', \'history\']
        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',
        ...          \'because\', \'he\', \'read\', \'the\', \'book\']

        >>> list_of_references = [[ref1a], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.44

    Example 2:
        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',
        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',
        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']
        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',
        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',
        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']
        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',
        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',
        ...          \'heed\', \'the\', \'cat\', \'commands\']
        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',
        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',
        ...          \'of\', \'the\', \'cat\']

        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',
        ...         \'interested\', \'in\', \'world\', \'history\']
        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',
        ...          \'because\', \'he\', \'read\', \'the\', \'book\']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.61

    Example 3:
        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',
        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',
        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']
        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',
        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',
        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']
        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',
        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',
        ...          \'heed\', \'the\', \'cat\', \'commands\']
        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',
        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',
        ...          \'of\', \'the\', \'cat\']

        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',
        ...         \'interested\', \'in\', \'world\', \'history\']
        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',
        ...          \'because\', \'he\', \'read\', \'the\', \'book\']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)
        >>> print(round(results[\"google_bleu\"], 2))
        0.53

    Example 4:
        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',
        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',
        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']
        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',
        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',
        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']
        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',
        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',
        ...          \'heed\', \'the\', \'cat\', \'commands\']
        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',
        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',
        ...          \'of\', \'the\', \'cat\']

        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',
        ...         \'interested\', \'in\', \'world\', \'history\']
        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',
        ...          \'because\', \'he\', \'read\', \'the\', \'book\']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)
        >>> print(round(results[\"google_bleu\"], 2))
        0.4
'''

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION       , _KWARGS_DESCRIPTION     )
class 						__a (							datasets.Metric     ):
		def       UpperCAmelCase__							(     self		)					->			List[str]:




									"""simple docstring"""





									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       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE = 1     ,       _SCREAMING_SNAKE_CASE = 4     ,       )					->			List[Any]:




									"""simple docstring"""





									return {
									    "google_bleu": gleu_score.corpus_gleu(
									        list_of_references=_SCREAMING_SNAKE_CASE     ,       hypotheses=_SCREAMING_SNAKE_CASE     ,       min_len=_SCREAMING_SNAKE_CASE     ,       max_len=_SCREAMING_SNAKE_CASE		)
									}



"""simple docstring"""

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

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


_UpperCamelCase		     =    logging.get_logger(__name__)

_UpperCamelCase		     =    """▁"""

_UpperCamelCase		     =    {"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""}

_UpperCamelCase		     =    {
    """vocab_file""": {
        """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""",
    },
    """monolingual_vocab_file""": {
        """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""",
    },
}

_UpperCamelCase		     =    {"""vinai/bartpho-syllable""": 1_0_2_4}






class 			__a					(						__magic_name__       ):





       """simple docstring"""


       __UpperCamelCase					:      int    =						VOCAB_FILES_NAMES
       __UpperCamelCase					:      List[str]    =						PRETRAINED_VOCAB_FILES_MAP
       __UpperCamelCase					:      List[Any]    =						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       __UpperCamelCase					:      int    =						['input_ids', 'attention_mask']






       def __init__(   self			,					snake_case			,					snake_case			,					snake_case="<s>"			,					snake_case="</s>"			,					snake_case="</s>"			,					snake_case="<s>"			,					snake_case="<unk>"			,					snake_case="<pad>"			,					snake_case="<mask>"			,					snake_case = None			,					**snake_case			,					):





        """simple docstring"""

        lowerCAmelCase__   :				Union[str, Any] 			=				AddedToken(snake_case			,					lstrip=snake_case			,					rstrip=snake_case   ) if isinstance(snake_case			,					snake_case   ) else mask_token

        lowerCAmelCase__   :				Union[str, Any] 			=				{} if sp_model_kwargs is None else sp_model_kwargs

        super().__init__(
            bos_token=snake_case			,					eos_token=snake_case			,					unk_token=snake_case			,					sep_token=snake_case			,					cls_token=snake_case			,					pad_token=snake_case			,					mask_token=snake_case			,					sp_model_kwargs=self.sp_model_kwargs			,					**snake_case			,					)

        lowerCAmelCase__   :				Union[str, Any] 			=				vocab_file
        lowerCAmelCase__   :				Optional[Any] 			=				monolingual_vocab_file
        lowerCAmelCase__   :				Optional[Any] 			=				spm.SentencePieceProcessor(**self.sp_model_kwargs   )
        self.sp_model.Load(str(snake_case   )   )

        # Load the reduced vocab

        # Keep order of special tokens for backward compatibility
        lowerCAmelCase__   :				Optional[int] 			=				{}
        lowerCAmelCase__   :				int 			=				0
        for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]:
         if str(snake_case   ) not in self.fairseq_tokens_to_ids:
          lowerCAmelCase__   :				Optional[int] 			=				cnt
          cnt += 1
        with open(snake_case			,					"r"			,					encoding="utf-8"   ) as f:
         for line in f.readlines():
          lowerCAmelCase__   :				Union[str, Any] 			=				line.strip().split()[0]
          lowerCAmelCase__   :				List[str] 			=				len(self.fairseq_tokens_to_ids   )
        if str(snake_case   ) not in self.fairseq_tokens_to_ids:
         lowerCAmelCase__   :				int 			=				len(self.fairseq_tokens_to_ids   )

        lowerCAmelCase__   :				Union[str, Any] 			=				{v: k for k, v in self.fairseq_tokens_to_ids.items()}






       def __getstate__(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[Any] 			=				self.__dict__.copy()
        lowerCAmelCase__   :				str 			=				None
        lowerCAmelCase__   :				Union[str, Any] 			=				self.sp_model.serialized_model_proto()
        return state






       def __setstate__(   self			,					snake_case   ):





        """simple docstring"""

        lowerCAmelCase__   :				Any 			=				d

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

        lowerCAmelCase__   :				Dict 			=				spm.SentencePieceProcessor(**self.sp_model_kwargs   )
        self.sp_model.LoadFromSerializedProto(self.sp_model_proto   )






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case = None   ):





        """simple docstring"""

        if token_ids_a is None:
         return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
        lowerCAmelCase__   :				Any 			=				[self.cls_token_id]
        lowerCAmelCase__   :				Dict 			=				[self.sep_token_id]
        return cls + token_ids_a + sep + sep + token_ids_a + sep






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case = None			,					snake_case = False   ):





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

        if token_ids_a is None:
         return [1] + ([0] * len(snake_case   )) + [1]
        return [1] + ([0] * len(snake_case   )) + [1, 1] + ([0] * len(snake_case   )) + [1]






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case = None   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[Any] 			=				[self.sep_token_id]
        lowerCAmelCase__   :				Optional[int] 			=				[self.cls_token_id]

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






       @property
       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        return len(self.fairseq_ids_to_tokens   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[str] 			=				{self.convert_ids_to_tokens(snake_case   ): i for i in range(self.vocab_size   )}
        vocab.update(self.added_tokens_encoder   )
        return vocab






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case   ):





        """simple docstring"""

        return self.sp_model.encode(snake_case			,					out_type=snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case   ):





        """simple docstring"""

        if token in self.fairseq_tokens_to_ids:
         return self.fairseq_tokens_to_ids[token]
        else:
         return self.unk_token_id






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case   ):





        """simple docstring"""

        return self.fairseq_ids_to_tokens[index]






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[str] 			=				"".join(snake_case   ).replace(snake_case			,					" "   ).strip()
        return out_string






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case = None   ):





        """simple docstring"""

        if not os.path.isdir(snake_case   ):
         logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""   )
         return
        lowerCAmelCase__   :				List[str] 			=				os.path.join(
            snake_case			,					(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]   )
        lowerCAmelCase__   :				Optional[Any] 			=				os.path.join(
            snake_case			,					(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["monolingual_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:
          lowerCAmelCase__   :				str 			=				self.sp_model.serialized_model_proto()
          fi.write(snake_case   )

        if os.path.abspath(self.monolingual_vocab_file   ) != os.path.abspath(
            snake_case   ) and os.path.isfile(self.monolingual_vocab_file   ):
         copyfile(self.monolingual_vocab_file			,					snake_case   )
        elif not os.path.isfile(self.monolingual_vocab_file   ):
         with open(snake_case			,					"w"			,					encoding="utf-8"   ) as fp:
          for token in self.fairseq_tokens_to_ids:
           if token not in self.all_special_tokens:
            fp.write(F"""{str(snake_case   )} \n"""   )

        return out_vocab_file, out_monolingual_vocab_file






