






import sacrebleu as scb
from packaging import version

import datasets


_UpperCAmelCase				:	Any    						=    '\\n@inproceedings{post-2018-call,\n    title = "A Call for Clarity in Reporting {BLEU} Scores",\n    author = "Post, Matt",\n    booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",\n    month = oct,\n    year = "2018",\n    address = "Belgium, Brussels",\n    publisher = "Association for Computational Linguistics",\n    url = "https://www.aclweb.org/anthology/W18-6319",\n    pages = "186--191",\n}\n'

_UpperCAmelCase				:	List[Any]    						=    '\\nSacreBLEU provides hassle-free computation of shareable, comparable, and reproducible BLEU scores.\nInspired by Rico Sennrich\'s `multi-bleu-detok.perl`, it produces the official WMT scores but works with plain text.\nIt also knows all the standard test sets and handles downloading, processing, and tokenization for you.\n\nSee the [README.md] file at https://github.com/mjpost/sacreBLEU for more information.\n'

_UpperCAmelCase				:	List[str]    						=    '\nProduces BLEU scores along with its sufficient statistics\nfrom a source against one or more references.\n\nArgs:\n    predictions (`list` of `str`): list of translations to score. Each translation should be tokenized into a list of tokens.\n    references (`list` of `list` of `str`): A list of lists of references. The contents of the first sub-list are the references for the first prediction, the contents of the second sub-list are for the second prediction, etc. Note that there must be the same number of references for each prediction (i.e. all sub-lists must be of the same length).\n    smooth_method (`str`): The smoothing method to use, defaults to `\'exp\'`. Possible values are:\n        - `\'none\'`: no smoothing\n        - `\'floor\'`: increment zero counts\n        - `\'add-k\'`: increment num/denom by k for n>1\n        - `\'exp\'`: exponential decay\n    smooth_value (`float`): The smoothing value. Only valid when `smooth_method=\'floor\'` (in which case `smooth_value` defaults to `0.1`) or `smooth_method=\'add-k\'` (in which case `smooth_value` defaults to `1`).\n    tokenize (`str`): Tokenization method to use for BLEU. If not provided, defaults to `\'zh\'` for Chinese, `\'ja-mecab\'` for Japanese and `\'13a\'` (mteval) otherwise. Possible values are:\n        - `\'none\'`: No tokenization.\n        - `\'zh\'`: Chinese tokenization.\n        - `\'13a\'`: mimics the `mteval-v13a` script from Moses.\n        - `\'intl\'`: International tokenization, mimics the `mteval-v14` script from Moses\n        - `\'char\'`: Language-agnostic character-level tokenization.\n        - `\'ja-mecab\'`: Japanese tokenization. Uses the [MeCab tokenizer](https://pypi.org/project/mecab-python3).\n    lowercase (`bool`): If `True`, lowercases the input, enabling case-insensitivity. Defaults to `False`.\n    force (`bool`): If `True`, insists that your tokenized input is actually detokenized. Defaults to `False`.\n    use_effective_order (`bool`): If `True`, stops including n-gram orders for which precision is 0. This should be `True`, if sentence-level BLEU will be computed. Defaults to `False`.\n\nReturns:\n    \'score\': BLEU score,\n    \'counts\': Counts,\n    \'totals\': Totals,\n    \'precisions\': Precisions,\n    \'bp\': Brevity penalty,\n    \'sys_len\': predictions length,\n    \'ref_len\': reference length,\n\nExamples:\n\n    Example 1:\n        >>> predictions = ["hello there general kenobi", "foo bar foobar"]\n        >>> references = [["hello there general kenobi", "hello there !"], ["foo bar foobar", "foo bar foobar"]]\n        >>> sacrebleu = datasets.load_metric("sacrebleu")\n        >>> results = sacrebleu.compute(predictions=predictions, references=references)\n        >>> print(list(results.keys()))\n        [\'score\', \'counts\', \'totals\', \'precisions\', \'bp\', \'sys_len\', \'ref_len\']\n        >>> print(round(results["score"], 1))\n        100.0\n\n    Example 2:\n        >>> predictions = ["hello there general kenobi",\n        ...                 "on our way to ankh morpork"]\n        >>> references = [["hello there general kenobi", "hello there !"],\n        ...                 ["goodbye ankh morpork", "ankh morpork"]]\n        >>> sacrebleu = datasets.load_metric("sacrebleu")\n        >>> results = sacrebleu.compute(predictions=predictions,\n        ...                             references=references)\n        >>> print(list(results.keys()))\n        [\'score\', \'counts\', \'totals\', \'precisions\', \'bp\', \'sys_len\', \'ref_len\']\n        >>> print(round(results["score"], 1))\n        39.8\n'


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





     def 	lowerCamelCase       (  self     )		->							Tuple:
        if version.parse(scb.__version__     ) < version.parse("""1.4.12"""     ):
           raise ImportWarning(
               """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"""
               """You can install it with `pip install \"sacrebleu>=1.4.12\"`."""     )
        return datasets.MetricInfo(
            description=_DESCRIPTION       ,   citation=_CITATION       ,   homepage="""https://github.com/mjpost/sacreBLEU"""       ,   inputs_description=_KWARGS_DESCRIPTION       ,   features=datasets.Features(
                {
                    """predictions""": datasets.Value("""string"""       ,   id="""sequence"""     ),
                    """references""": datasets.Sequence(datasets.Value("""string"""       ,   id="""sequence"""     )       ,   id="""references"""     ),
                }     )       ,   codebase_urls=["""https://github.com/mjpost/sacreBLEU"""]       ,   reference_urls=[
                """https://github.com/mjpost/sacreBLEU""",
                """https://en.wikipedia.org/wiki/BLEU""",
                """https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213""",
            ]       ,   )





     def 	lowerCamelCase       (  self       ,   _UpperCAmelCase       ,   _UpperCAmelCase       ,   _UpperCAmelCase="exp"       ,   _UpperCAmelCase=None       ,   _UpperCAmelCase=False       ,   _UpperCAmelCase=False       ,   _UpperCAmelCase=None       ,   _UpperCAmelCase=False       ,   )		->							Any:
        lowerCamelCase											=len(references[0]     )
        if any(len(_UpperCAmelCase     ) != references_per_prediction for refs in references     ):
           raise ValueError("""Sacrebleu requires the same number of references for each prediction"""     )
        lowerCamelCase											=[[refs[i] for refs in references] for i in range(_UpperCAmelCase     )]
        lowerCamelCase											=scb.corpus_bleu(
            _UpperCAmelCase       ,   _UpperCAmelCase       ,   smooth_method=_UpperCAmelCase       ,   smooth_value=_UpperCAmelCase       ,   force=_UpperCAmelCase       ,   lowercase=_UpperCAmelCase       ,   use_effective_order=_UpperCAmelCase       ,   **({"""tokenize""": tokenize} if tokenize else {})       ,   )
        lowerCamelCase											={
            """score""": output.score,
            """counts""": output.counts,
            """totals""": output.totals,
            """precisions""": output.precisions,
            """bp""": output.bp,
            """sys_len""": output.sys_len,
            """ref_len""": output.ref_len,
        }
        return output_dict







import unittest

from transformers import ErnieMTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


_UpperCAmelCase				:	Any    						=    get_tests_dir('fixtures/spiece.model')


@require_sentencepiece
@require_tokenizers
class 		lowerCAmelCase_							(     UpperCamelCase							,    unittest.TestCase   ):
     __lowerCamelCase					:						List[Any]     =    ErnieMTokenizer
     __lowerCamelCase					:						Optional[Any]     =    False
     __lowerCamelCase					:						Optional[int]     =    True
     __lowerCamelCase					:						str     =    False
     __lowerCamelCase					:						Any     =    False





     def 	lowerCamelCase       (  self     )		->							Any:
        super().setUp()

        # We have a SentencePiece fixture for testing
        lowerCamelCase											=ErnieMTokenizer(_UpperCAmelCase       ,   unk_token="""<unk>"""       ,   pad_token="""<pad>"""     )
        tokenizer.save_pretrained(self.tmpdirname     )





     def 	lowerCamelCase       (  self       ,   _UpperCAmelCase     )		->							Union[str, Any]:
        lowerCamelCase											="""this is a test"""
        lowerCamelCase											="""this is a test"""
        return input_text, output_text





     def 	lowerCamelCase       (  self     )		->							List[Any]:
        lowerCamelCase											="""<pad>"""
        lowerCamelCase											=0

        self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCAmelCase     )       ,   _UpperCAmelCase     )
        self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCAmelCase     )       ,   _UpperCAmelCase     )





     def 	lowerCamelCase       (  self     )		->							List[str]:
        lowerCamelCase											=list(self.get_tokenizer().get_vocab().keys()     )

        self.assertEqual(vocab_keys[0]       ,   """<pad>"""     )
        self.assertEqual(vocab_keys[1]       ,   """<unk>"""     )
        self.assertEqual(vocab_keys[-1]       ,   """▁eloquent"""     )
        self.assertEqual(len(_UpperCAmelCase     )       ,   30000     )





     def 	lowerCamelCase       (  self     )		->							Any:
        self.assertEqual(self.get_tokenizer().vocab_size       ,   30000     )





     def 	lowerCamelCase       (  self     )		->							Any:
        if not self.test_rust_tokenizer:
           return

        lowerCamelCase											=self.get_tokenizer()
        lowerCamelCase											=self.get_rust_tokenizer()

        lowerCamelCase											="""I was born in 92000, and this is falsé."""

        lowerCamelCase											=tokenizer.tokenize(_UpperCAmelCase     )
        lowerCamelCase											=rust_tokenizer.tokenize(_UpperCAmelCase     )
        self.assertListEqual(_UpperCAmelCase       ,   _UpperCAmelCase     )

        lowerCamelCase											=tokenizer.encode(_UpperCAmelCase       ,   add_special_tokens=_UpperCAmelCase     )
        lowerCamelCase											=rust_tokenizer.encode(_UpperCAmelCase       ,   add_special_tokens=_UpperCAmelCase     )
        self.assertListEqual(_UpperCAmelCase       ,   _UpperCAmelCase     )

        lowerCamelCase											=self.get_rust_tokenizer()
        lowerCamelCase											=tokenizer.encode(_UpperCAmelCase     )
        lowerCamelCase											=rust_tokenizer.encode(_UpperCAmelCase     )
        self.assertListEqual(_UpperCAmelCase       ,   _UpperCAmelCase     )





     def 	lowerCamelCase       (  self     )		->							Union[str, Any]:
        lowerCamelCase											=ErnieMTokenizer(_UpperCAmelCase       ,   do_lower_case=_UpperCAmelCase       ,   unk_token="""<unk>"""       ,   pad_token="""<pad>"""     )

        lowerCamelCase											=tokenizer.tokenize("""This is a test"""     )
        self.assertListEqual(_UpperCAmelCase       ,   ["""▁this""", """▁is""", """▁a""", """▁test"""]     )

        self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase     )       ,   [48, 25, 21, 1289]     )

        lowerCamelCase											=tokenizer.tokenize("""I was born in 92000, and this is falsé."""     )
        # ErnieMTokenizer(paddlenlp implementation) outputs '9' instead of '_9' so to mimic that '_9' is changed to '9'
        self.assertListEqual(
            _UpperCAmelCase       ,   ["""▁i""", """▁was""", """▁born""", """▁in""", """9""", """2000""", """,""", """▁and""", """▁this""", """▁is""", """▁fal""", """s""", """é""", """."""]     )
        lowerCamelCase											=tokenizer.convert_tokens_to_ids(_UpperCAmelCase     )
        self.assertListEqual(_UpperCAmelCase       ,   [31, 23, 386, 19, 518, 3050, 15, 17, 48, 25, 8256, 18, 1, 9]     )

        lowerCamelCase											=tokenizer.convert_ids_to_tokens(_UpperCAmelCase     )
        self.assertListEqual(
            _UpperCAmelCase       ,   ["""▁i""", """▁was""", """▁born""", """▁in""", """9""", """2000""", """,""", """▁and""", """▁this""", """▁is""", """▁fal""", """s""", """<unk>""", """."""]       ,   )





     def 	lowerCamelCase       (  self     )		->							List[str]:
        lowerCamelCase											=ErnieMTokenizer(_UpperCAmelCase       ,   unk_token="""<unk>"""       ,   pad_token="""<pad>"""     )

        lowerCamelCase											=tokenizer.encode("""sequence builders"""     )
        lowerCamelCase											=tokenizer.encode("""multi-sequence build"""     )

        lowerCamelCase											=tokenizer.build_inputs_with_special_tokens(_UpperCAmelCase     )
        lowerCamelCase											=tokenizer.build_inputs_with_special_tokens(_UpperCAmelCase       ,   _UpperCAmelCase     )

        assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
        assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + [
            tokenizer.sep_token_id
        ] + text_a + [tokenizer.sep_token_id]





     @slow
     def 	lowerCamelCase       (  self     )		->							Dict:
        # fmt: off
        lowerCamelCase											={"""input_ids""": [[0, 11062, 82772, 7, 15, 82772, 538, 51529, 237, 17198, 1290, 206, 9, 215175, 1314, 136, 17198, 1290, 206, 9, 56359, 42, 122009, 9, 16466, 16, 87344, 4537, 9, 4717, 78381, 6, 159958, 7, 15, 24480, 618, 4, 527, 22693, 9, 304, 4, 2777, 24480, 9874, 4, 43523, 594, 4, 803, 18392, 33189, 18, 4, 43523, 24447, 5, 5, 5, 16, 100, 24955, 83658, 9626, 144057, 15, 839, 22335, 16, 136, 24955, 83658, 83479, 15, 39102, 724, 16, 678, 645, 6460, 1328, 4589, 42, 122009, 115774, 23, 3559, 1328, 46876, 7, 136, 53894, 1940, 42227, 41159, 17721, 823, 425, 4, 27512, 98722, 206, 136, 5531, 4970, 919, 17336, 5, 2], [0, 20080, 618, 83, 82775, 47, 479, 9, 1517, 73, 53894, 333, 80581, 110117, 18811, 5256, 1295, 51, 152526, 297, 7986, 390, 124416, 538, 35431, 214, 98, 15044, 25737, 136, 7108, 43701, 23, 756, 135355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 581, 63773, 119455, 6, 147797, 88203, 7, 645, 70, 21, 3285, 10269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}
        # fmt: on

        self.tokenizer_integration_test_util(
            expected_encoding=_UpperCAmelCase       ,   model_name="""susnato/ernie-m-base_pytorch"""       ,   sequences=[
                """Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides """
                """general-purpose architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet...) for Natural """
                """Language Understanding (NLU) and Natural Language Generation (NLG) with over32+ pretrained """
                """models in100+ languages and deep interoperability between Jax, PyTorch and TensorFlow.""",
                """BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly """
                """conditioning on both left and right context in all layers.""",
                """The quick brown fox jumps over the lazy dog.""",
            ]       ,   )