





import sacrebleu as scb
from packaging import version

import datasets


UpperCamelCase__          ='\\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__          ='\\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__          ='\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			):






       '''simple docstring'''


       def 			UpperCamelCase_	(					self							)	->   Optional[Any]:
            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 			UpperCamelCase_	(					self			,  __lowerCamelCase			,  __lowerCamelCase			,  __lowerCamelCase="exp"			,  __lowerCamelCase=None			,  __lowerCamelCase=False			,  __lowerCamelCase=False			,  __lowerCamelCase=None			,  __lowerCamelCase=False			,  )	->   Union[str, Any]:
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							len(references[0]							)
            if any(len(__lowerCamelCase							) != references_per_prediction for refs in references							):
                 raise ValueError("Sacrebleu requires the same number of references for each prediction"							)
            _SCREAMING_SNAKE_CASE				:		List[str]  			=							[[refs[i] for refs in references] for i in range(__lowerCamelCase							)]
            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							scb.corpus_bleu(
                __lowerCamelCase			,  __lowerCamelCase			,  smooth_method=__lowerCamelCase			,  smooth_value=__lowerCamelCase			,  force=__lowerCamelCase			,  lowercase=__lowerCamelCase			,  use_effective_order=__lowerCamelCase			,  **({"tokenize": tokenize} if tokenize else {})			,  )
            _SCREAMING_SNAKE_CASE				:		Tuple  			=							{
                "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 json
import os
import random
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
       from PIL import Image

       from transformers import FlavaImageProcessor, FlavaProcessor
       from transformers.models.flava.image_processing_flava import (
           FLAVA_CODEBOOK_MEAN,
           FLAVA_CODEBOOK_STD,
           FLAVA_IMAGE_MEAN,
           FLAVA_IMAGE_STD,
       )





@require_vision
class 	lowerCAmelCase__(       unittest.TestCase			):






       '''simple docstring'''


       def 			UpperCamelCase_	(					self							)	->   str:
            _SCREAMING_SNAKE_CASE				:		str  			=							tempfile.mkdtemp()

            # fmt: off
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"]
            # fmt: on
            _SCREAMING_SNAKE_CASE				:		int  			=							os.path.join(self.tmpdirname			,  VOCAB_FILES_NAMES["vocab_file"]							)

            with open(self.vocab_file			,  "w"			,  encoding="utf-8"							) as fp:
                 fp.write("".join([x + "\n" for x in vocab_tokens]							)							)

            _SCREAMING_SNAKE_CASE				:		Any  			=							{
                "image_mean": FLAVA_IMAGE_MEAN,
                "image_std": FLAVA_IMAGE_STD,
                "do_normalize": True,
                "do_resize": True,
                "size": 2_2_4,
                "do_center_crop": True,
                "crop_size": 2_2_4,
                "input_size_patches": 1_4,
                "total_mask_patches": 7_5,
                "mask_group_max_patches": None,
                "mask_group_min_patches": 1_6,
                "mask_group_min_aspect_ratio": 0.3,
                "mask_group_max_aspect_ratio": None,
                "codebook_do_resize": True,
                "codebook_size": 1_1_2,
                "codebook_do_center_crop": True,
                "codebook_crop_size": 1_1_2,
                "codebook_do_map_pixels": True,
                "codebook_do_normalize": True,
                "codebook_image_mean": FLAVA_CODEBOOK_MEAN,
                "codebook_image_std": FLAVA_CODEBOOK_STD,
            }

            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							os.path.join(self.tmpdirname			,  __lowerCamelCase							)
            with open(self.image_processor_file			,  "w"			,  encoding="utf-8"							) as fp:
                 json.dump(__lowerCamelCase			,  __lowerCamelCase							)




       def 			UpperCamelCase_	(					self			,  **__lowerCamelCase							)	->   List[str]:
            return BertTokenizer.from_pretrained(self.tmpdirname			,  **__lowerCamelCase							)




       def 			UpperCamelCase_	(					self			,  **__lowerCamelCase							)	->   Optional[Any]:
            return BertTokenizerFast.from_pretrained(self.tmpdirname			,  **__lowerCamelCase							)




       def 			UpperCamelCase_	(					self			,  **__lowerCamelCase							)	->   Tuple:
            return FlavaImageProcessor.from_pretrained(self.tmpdirname			,  **__lowerCamelCase							)




       def 			UpperCamelCase_	(					self							)	->   int:
            shutil.rmtree(self.tmpdirname							)




       def 			UpperCamelCase_	(					self							)	->   Optional[int]:
            _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							[np.random.randint(2_5_5			,  size=(3, 3_0, 4_0_0)			,  dtype=np.uinta							)]

            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							[Image.fromarray(np.moveaxis(__lowerCamelCase			,  0			,  -1							)							) for x in image_inputs]

            return image_inputs




       def 			UpperCamelCase_	(					self							)	->   Any:
            _SCREAMING_SNAKE_CASE				:		Dict  			=							self.get_tokenizer()
            _SCREAMING_SNAKE_CASE				:		Any  			=							self.get_rust_tokenizer()
            _SCREAMING_SNAKE_CASE				:		Dict  			=							self.get_image_processor()

            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)
            processor_slow.save_pretrained(self.tmpdirname							)
            _SCREAMING_SNAKE_CASE				:		Tuple  			=							FlavaProcessor.from_pretrained(self.tmpdirname			,  use_fast=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)
            processor_fast.save_pretrained(self.tmpdirname							)
            _SCREAMING_SNAKE_CASE				:		int  			=							FlavaProcessor.from_pretrained(self.tmpdirname							)

            self.assertEqual(processor_slow.tokenizer.get_vocab()			,  tokenizer_slow.get_vocab()							)
            self.assertEqual(processor_fast.tokenizer.get_vocab()			,  tokenizer_fast.get_vocab()							)
            self.assertEqual(tokenizer_slow.get_vocab()			,  tokenizer_fast.get_vocab()							)
            self.assertIsInstance(processor_slow.tokenizer			,  __lowerCamelCase							)
            self.assertIsInstance(processor_fast.tokenizer			,  __lowerCamelCase							)

            self.assertEqual(processor_slow.image_processor.to_json_string()			,  image_processor.to_json_string()							)
            self.assertEqual(processor_fast.image_processor.to_json_string()			,  image_processor.to_json_string()							)
            self.assertIsInstance(processor_slow.image_processor			,  __lowerCamelCase							)
            self.assertIsInstance(processor_fast.image_processor			,  __lowerCamelCase							)




       def 			UpperCamelCase_	(					self							)	->   Optional[int]:
            _SCREAMING_SNAKE_CASE				:		Dict  			=							FlavaProcessor(tokenizer=self.get_tokenizer()			,  image_processor=self.get_image_processor()							)
            processor.save_pretrained(self.tmpdirname							)

            _SCREAMING_SNAKE_CASE				:		str  			=							self.get_tokenizer(bos_token="(BOS)"			,  eos_token="(EOS)"							)
            _SCREAMING_SNAKE_CASE				:		List[str]  			=							self.get_image_processor(do_normalize=__lowerCamelCase			,  padding_value=1.0							)

            _SCREAMING_SNAKE_CASE				:		Dict  			=							FlavaProcessor.from_pretrained(
                self.tmpdirname			,  bos_token="(BOS)"			,  eos_token="(EOS)"			,  do_normalize=__lowerCamelCase			,  padding_value=1.0							)

            self.assertEqual(processor.tokenizer.get_vocab()			,  tokenizer_add_kwargs.get_vocab()							)
            self.assertIsInstance(processor.tokenizer			,  __lowerCamelCase							)

            self.assertEqual(processor.image_processor.to_json_string()			,  image_processor_add_kwargs.to_json_string()							)
            self.assertIsInstance(processor.image_processor			,  __lowerCamelCase							)




       def 			UpperCamelCase_	(					self							)	->   Any:
            _SCREAMING_SNAKE_CASE				:		str  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		Any  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		int  			=							self.prepare_image_inputs()

            _SCREAMING_SNAKE_CASE				:		List[str]  			=							image_processor(__lowerCamelCase			,  return_tensors="np"							)
            _SCREAMING_SNAKE_CASE				:		str  			=							processor(images=__lowerCamelCase			,  return_tensors="np"							)

            for key in input_feat_extract.keys():
                 self.assertAlmostEqual(input_feat_extract[key].sum()			,  input_processor[key].sum()			,  delta=1E-2							)

            # With rest of the args
            random.seed(1_2_3_4							)
            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							image_processor(
                __lowerCamelCase			,  return_image_mask=__lowerCamelCase			,  return_codebook_pixels=__lowerCamelCase			,  return_tensors="np"							)
            random.seed(1_2_3_4							)
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							processor(
                images=__lowerCamelCase			,  return_image_mask=__lowerCamelCase			,  return_codebook_pixels=__lowerCamelCase			,  return_tensors="np"							)

            for key in input_feat_extract.keys():
                 self.assertAlmostEqual(input_feat_extract[key].sum()			,  input_processor[key].sum()			,  delta=1E-2							)




       def 			UpperCamelCase_	(					self							)	->   int:
            _SCREAMING_SNAKE_CASE				:		Any  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		int  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							"lower newer"

            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							processor(text=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		List[str]  			=							tokenizer(__lowerCamelCase							)

            for key in encoded_tok.keys():
                 self.assertListEqual(encoded_tok[key]			,  encoded_processor[key]							)




       def 			UpperCamelCase_	(					self							)	->   Tuple:
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Any  			=							"lower newer"
            _SCREAMING_SNAKE_CASE				:		Dict  			=							self.prepare_image_inputs()

            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							processor(text=__lowerCamelCase			,  images=__lowerCamelCase							)

            self.assertListEqual(list(inputs.keys()							)			,  ["input_ids", "token_type_ids", "attention_mask", "pixel_values"]							)

            # add extra args
            _SCREAMING_SNAKE_CASE				:		Tuple  			=							processor(text=__lowerCamelCase			,  images=__lowerCamelCase			,  return_codebook_pixels=__lowerCamelCase			,  return_image_mask=__lowerCamelCase							)

            self.assertListEqual(
                list(inputs.keys()							)			,  [
                    "input_ids",
                    "token_type_ids",
                    "attention_mask",
                    "pixel_values",
                    "codebook_pixel_values",
                    "bool_masked_pos",
                ]			,  )

            # test if it raises when no input is passed
            with pytest.raises(__lowerCamelCase							):
                 processor()




       def 			UpperCamelCase_	(					self							)	->   Dict:
            _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		str  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		int  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

            _SCREAMING_SNAKE_CASE				:		Dict  			=							processor.batch_decode(__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE				:		Any  			=							tokenizer.batch_decode(__lowerCamelCase							)

            self.assertListEqual(__lowerCamelCase			,  __lowerCamelCase							)







       def 			UpperCamelCase_	(					self							)	->   Any:
            _SCREAMING_SNAKE_CASE				:		int  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		Dict  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							"lower newer"
            _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							self.prepare_image_inputs()

            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							processor(text=__lowerCamelCase			,  images=__lowerCamelCase							)

            self.assertListEqual(list(inputs.keys()							)			,  processor.model_input_names							)