


from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


_lowerCamelCase			:	int							 =     """\\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"""

_lowerCamelCase			:	Optional[int]							 =     """\\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"""

_lowerCamelCase			:	Tuple							 =     """\\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        UpperCamelCase_					(				datasets.Metric  ):

    '''simple docstring'''






    def  SCREAMING_SNAKE_CASE							(    self   :			int)		->MetricInfo:





           '''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  SCREAMING_SNAKE_CASE							(    self   :			List[Any]      ,				UpperCAmelCase__   :			Dict      ,				UpperCAmelCase__   :			Dict      ,				UpperCAmelCase__   :			Optional[int] = 1      ,				UpperCAmelCase__   :			Union[str, Any] = 4      ,				)		->Dict[str, float]:





           '''simple docstring'''

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








from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import TFViTForImageClassification, TFViTModel


if is_vision_available():
  from PIL import Image

  from transformers import ViTImageProcessor


class        UpperCamelCase_					:

    '''simple docstring'''






    def __init__(    self   :			Dict      ,				UpperCAmelCase__   :			Optional[Any]      ,				UpperCAmelCase__   :			str=13      ,				UpperCAmelCase__   :			Union[str, Any]=30      ,				UpperCAmelCase__   :			List[str]=2      ,				UpperCAmelCase__   :			List[Any]=3      ,				UpperCAmelCase__   :			int=True      ,				UpperCAmelCase__   :			Tuple=True      ,				UpperCAmelCase__   :			Optional[int]=32      ,				UpperCAmelCase__   :			Tuple=2      ,				UpperCAmelCase__   :			Optional[Any]=4      ,				UpperCAmelCase__   :			Any=37      ,				UpperCAmelCase__   :			List[Any]="gelu"      ,				UpperCAmelCase__   :			Dict=0.1      ,				UpperCAmelCase__   :			List[Any]=0.1      ,				UpperCAmelCase__   :			Union[str, Any]=10      ,				UpperCAmelCase__   :			int=0.02      ,				UpperCAmelCase__   :			Optional[Any]=3      ,				UpperCAmelCase__   :			List[Any]=None      ,				)		->Dict:





           '''simple docstring'''

           A__   				=					parent
           A__   				=					batch_size
           A__   				=					image_size
           A__   				=					patch_size
           A__   				=					num_channels
           A__   				=					is_training
           A__   				=					use_labels
           A__   				=					hidden_size
           A__   				=					num_hidden_layers
           A__   				=					num_attention_heads
           A__   				=					intermediate_size
           A__   				=					hidden_act
           A__   				=					hidden_dropout_prob
           A__   				=					attention_probs_dropout_prob
           A__   				=					type_sequence_label_size
           A__   				=					initializer_range
           A__   				=					scope

           # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
           A__   				=					(image_size // patch_size) ** 2
           A__   				=					num_patches + 1


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





           '''simple docstring'''

           A__   				=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

           A__   				=					None
           if self.use_labels:
                  A__   				=					ids_tensor([self.batch_size]      ,				self.type_sequence_label_size)

           A__   				=					self.get_config()

           return config, pixel_values, labels


    def  SCREAMING_SNAKE_CASE							(    self   :			Optional[Any])		->Optional[int]:





           '''simple docstring'''

           return ViTConfig(
               image_size=self.image_size      ,				patch_size=self.patch_size      ,				num_channels=self.num_channels      ,				hidden_size=self.hidden_size      ,				num_hidden_layers=self.num_hidden_layers      ,				num_attention_heads=self.num_attention_heads      ,				intermediate_size=self.intermediate_size      ,				hidden_act=self.hidden_act      ,				hidden_dropout_prob=self.hidden_dropout_prob      ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,				is_decoder=UpperCAmelCase__      ,				initializer_range=self.initializer_range      ,				)


    def  SCREAMING_SNAKE_CASE							(    self   :			List[Any]      ,				UpperCAmelCase__   :			List[str]      ,				UpperCAmelCase__   :			Any      ,				UpperCAmelCase__   :			str)		->Tuple:





           '''simple docstring'''

           A__   				=					TFViTModel(config=UpperCAmelCase__)
           A__   				=					model(UpperCAmelCase__      ,				training=UpperCAmelCase__)
           self.parent.assertEqual(result.last_hidden_state.shape      ,				(self.batch_size, self.seq_length, self.hidden_size))

           # Test with an image with different size than the one specified in config.
           A__   				=					self.image_size // 2
           A__   				=					pixel_values[:, :, :image_size, :image_size]
           A__   				=					model(UpperCAmelCase__      ,				interpolate_pos_encoding=UpperCAmelCase__      ,				training=UpperCAmelCase__)
           A__   				=					(image_size // self.patch_size) ** 2 + 1
           self.parent.assertEqual(result.last_hidden_state.shape      ,				(self.batch_size, seq_length, self.hidden_size))


    def  SCREAMING_SNAKE_CASE							(    self   :			Any      ,				UpperCAmelCase__   :			Tuple      ,				UpperCAmelCase__   :			List[Any]      ,				UpperCAmelCase__   :			List[str])		->List[str]:





           '''simple docstring'''

           A__   				=					self.type_sequence_label_size
           A__   				=					TFViTForImageClassification(UpperCAmelCase__)
           A__   				=					model(UpperCAmelCase__      ,				labels=UpperCAmelCase__      ,				training=UpperCAmelCase__)
           self.parent.assertEqual(result.logits.shape      ,				(self.batch_size, self.type_sequence_label_size))

           # Test with an image with different size than the one specified in config.
           A__   				=					self.image_size // 2
           A__   				=					pixel_values[:, :, :image_size, :image_size]
           A__   				=					model(UpperCAmelCase__      ,				interpolate_pos_encoding=UpperCAmelCase__      ,				training=UpperCAmelCase__)
           self.parent.assertEqual(result.logits.shape      ,				(self.batch_size, self.type_sequence_label_size))

           # test greyscale images
           A__   				=					1
           A__   				=					TFViTForImageClassification(UpperCAmelCase__)
           A__   				=					floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
           A__   				=					model(UpperCAmelCase__)
           self.parent.assertEqual(result.logits.shape      ,				(self.batch_size, self.type_sequence_label_size))





    def  SCREAMING_SNAKE_CASE							(    self   :			List[Any])		->int:





           '''simple docstring'''

           A__   				=					self.prepare_config_and_inputs()
           A__				,							A__				,							A__   				=					config_and_inputs
           A__   				=					{'''pixel_values''': pixel_values}
           return config, inputs_dict


@require_tf
class        UpperCamelCase_					(				UpperCAmelCase__	,      UpperCAmelCase__	,      unittest.TestCase  ):

    '''simple docstring'''






    UpperCAmelCase__													=   (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
    UpperCAmelCase__													=   (
        {'''feature-extraction''': TFViTModel, '''image-classification''': TFViTForImageClassification}
        if is_tf_available()
        else {}
    )

    UpperCAmelCase__													=   False
    UpperCAmelCase__													=   False
    UpperCAmelCase__													=   False


    def  SCREAMING_SNAKE_CASE							(    self   :			int)		->Optional[int]:





           '''simple docstring'''

           A__   				=					TFViTModelTester(self)
           A__   				=					ConfigTester(self      ,				config_class=UpperCAmelCase__      ,				has_text_modality=UpperCAmelCase__      ,				hidden_size=37)


    def  SCREAMING_SNAKE_CASE							(    self   :			str)		->List[str]:





           '''simple docstring'''

           self.config_tester.run_common_tests()


    @unittest.skip(reason='''ViT does not use inputs_embeds''')
    def  SCREAMING_SNAKE_CASE							(    self   :			List[Any])		->Tuple:





           '''simple docstring'''

           pass


    @unittest.skip(reason='''ViT does not use inputs_embeds''')
    def  SCREAMING_SNAKE_CASE							(    self   :			int)		->Optional[Any]:





           '''simple docstring'''

           pass


    def  SCREAMING_SNAKE_CASE							(    self   :			int)		->List[Any]:





           '''simple docstring'''

           A__				,							A__   				=					self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  A__   				=					model_class(UpperCAmelCase__)
                  self.assertIsInstance(model.get_input_embeddings()      ,				(tf.keras.layers.Layer))
                  A__   				=					model.get_output_embeddings()
                  self.assertTrue(x is None or isinstance(UpperCAmelCase__      ,				tf.keras.layers.Layer))


    def  SCREAMING_SNAKE_CASE							(    self   :			int)		->Any:





           '''simple docstring'''

           A__				,							A__   				=					self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  A__   				=					model_class(UpperCAmelCase__)
                  A__   				=					inspect.signature(model.call)
                  # signature.parameters is an OrderedDict => so arg_names order is deterministic
                  A__   				=					[*signature.parameters.keys()]

                  A__   				=					['''pixel_values''']
                  self.assertListEqual(arg_names[:1]      ,				UpperCAmelCase__)


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





           '''simple docstring'''

           A__   				=					self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCAmelCase__)


    def  SCREAMING_SNAKE_CASE							(    self   :			Dict)		->Optional[Any]:





           '''simple docstring'''

           A__   				=					self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__)





    @slow
    def  SCREAMING_SNAKE_CASE							(    self   :			Optional[int])		->List[Any]:





           '''simple docstring'''

           A__   				=					TFViTModel.from_pretrained('''google/vit-base-patch16-224''')
           self.assertIsNotNone(UpperCAmelCase__)







def SCREAMING_SNAKE_CASE       ( )     -> int:



       """simple docstring"""

       A__   				=					Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
       return image


@require_tf
@require_vision
class        UpperCamelCase_					(				unittest.TestCase  ):

    '''simple docstring'''






    @cached_property
    def  SCREAMING_SNAKE_CASE							(    self   :			Dict)		->Optional[Any]:





           '''simple docstring'''

           return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224''') if is_vision_available() else None





    @slow
    def  SCREAMING_SNAKE_CASE							(    self   :			Any)		->int:





           '''simple docstring'''

           A__   				=					TFViTForImageClassification.from_pretrained('''google/vit-base-patch16-224''')

           A__   				=					self.default_image_processor
           A__   				=					prepare_img()
           A__   				=					image_processor(images=UpperCAmelCase__      ,				return_tensors='''tf''')

           # forward pass
           A__   				=					model(**UpperCAmelCase__)

           # verify the logits
           A__   				=					tf.TensorShape((1, 1_000))
           self.assertEqual(outputs.logits.shape      ,				UpperCAmelCase__)

           A__   				=					tf.constant([-0.2744, 0.8215, -0.0836])

           tf.debugging.assert_near(outputs.logits[0, :3]      ,				UpperCAmelCase__      ,				atol=1e-4)


