

'''simple docstring'''

from __future__ import annotations

import inspect
import unittest

from transformers import MobileViTConfig
from transformers.file_utils import is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, slow

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 numpy as np
 import tensorflow as tf

 from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
 from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import MobileViTImageProcessor




class 			A_					(							_snake_case				):






     '''simple docstring'''



     def   UpperCAmelCase_			(						self					:	List[Any]			)		->      Optional[Any]:
      UpperCAmelCase			:      Tuple		   =					self.config_class(**self.inputs_dict			)
      self.parent.assertTrue(hasattr(lowercase_	,     'hidden_sizes'			)			)
      self.parent.assertTrue(hasattr(lowercase_	,     'neck_hidden_sizes'			)			)
      self.parent.assertTrue(hasattr(lowercase_	,     'num_attention_heads'			)			)




class 			A_					:






     '''simple docstring'''



     def __init__(						self					:	Tuple	,     lowercase_					:	List[str]	,     lowercase_					:	str=13	,     lowercase_					:	Dict=32	,     lowercase_					:	Union[str, Any]=2	,     lowercase_					:	Any=3	,     lowercase_					:	Optional[Any]=640	,     lowercase_					:	List[Any]=4	,     lowercase_					:	Dict="silu"	,     lowercase_					:	Optional[int]=3	,     lowercase_					:	Union[str, Any]=32	,     lowercase_					:	str=0.1	,     lowercase_					:	Optional[int]=0.1	,     lowercase_					:	List[Any]=0.1	,     lowercase_					:	Tuple=0.02	,     lowercase_					:	Union[str, Any]=True	,     lowercase_					:	Optional[Any]=True	,     lowercase_					:	Tuple=10	,     lowercase_					:	List[str]=None	,     )		->      Any:
      UpperCAmelCase			:      List[Any]		   =					parent
      UpperCAmelCase			:      int		   =					batch_size
      UpperCAmelCase			:      str		   =					image_size
      UpperCAmelCase			:      Union[str, Any]		   =					patch_size
      UpperCAmelCase			:      Optional[Any]		   =					num_channels
      UpperCAmelCase			:      Dict		   =					last_hidden_size
      UpperCAmelCase			:      List[Any]		   =					num_attention_heads
      UpperCAmelCase			:      Optional[int]		   =					hidden_act
      UpperCAmelCase			:      List[Any]		   =					conv_kernel_size
      UpperCAmelCase			:      Union[str, Any]		   =					output_stride
      UpperCAmelCase			:      int		   =					hidden_dropout_prob
      UpperCAmelCase			:      Optional[int]		   =					attention_probs_dropout_prob
      UpperCAmelCase			:      List[Any]		   =					classifier_dropout_prob
      UpperCAmelCase			:      Any		   =					use_labels
      UpperCAmelCase			:      Optional[int]		   =					is_training
      UpperCAmelCase			:      str		   =					num_labels
      UpperCAmelCase			:      Optional[int]		   =					initializer_range
      UpperCAmelCase			:      Optional[int]		   =					scope


     def   UpperCAmelCase_			(						self					:	Any			)		->      Tuple:
      UpperCAmelCase			:      Optional[Any]		   =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

      UpperCAmelCase			:      Union[str, Any]		   =					None
      UpperCAmelCase			:      int		   =					None
      if self.use_labels:
       UpperCAmelCase			:      str		   =					ids_tensor([self.batch_size]	,     self.num_labels			)
       UpperCAmelCase			:      List[str]		   =					ids_tensor([self.batch_size, self.image_size, self.image_size]	,     self.num_labels			)

      UpperCAmelCase			:      Any		   =					self.get_config()

      return config, pixel_values, labels, pixel_labels


     def   UpperCAmelCase_			(						self					:	Optional[int]			)		->      Tuple:
      return MobileViTConfig(
          image_size=self.image_size	,     patch_size=self.patch_size	,     num_channels=self.num_channels	,     num_attention_heads=self.num_attention_heads	,     hidden_act=self.hidden_act	,     conv_kernel_size=self.conv_kernel_size	,     output_stride=self.output_stride	,     hidden_dropout_prob=self.hidden_dropout_prob	,     attention_probs_dropout_prob=self.attention_probs_dropout_prob	,     classifier_dropout_prob=self.classifier_dropout_prob	,     initializer_range=self.initializer_range	,     )


     def   UpperCAmelCase_			(						self					:	Tuple	,     lowercase_					:	Tuple	,     lowercase_					:	List[str]	,     lowercase_					:	List[str]	,     lowercase_					:	List[str]			)		->      Optional[int]:
      UpperCAmelCase			:      Tuple		   =					TFMobileViTModel(config=lowercase_			)
      UpperCAmelCase			:      str		   =					model(lowercase_	,     training=lowercase_			)
      UpperCAmelCase			:      Tuple		   =					self.image_size // self.output_stride
      self.parent.assertEqual(
          result.last_hidden_state.shape	,     (self.batch_size, self.last_hidden_size, expected_height, expected_width)			)


     def   UpperCAmelCase_			(						self					:	Dict	,     lowercase_					:	Any	,     lowercase_					:	str	,     lowercase_					:	List[str]	,     lowercase_					:	List[Any]			)		->      int:
      UpperCAmelCase			:      Optional[int]		   =					self.num_labels
      UpperCAmelCase			:      Union[str, Any]		   =					TFMobileViTForImageClassification(lowercase_			)
      UpperCAmelCase			:      Optional[Any]		   =					model(lowercase_	,     labels=lowercase_	,     training=lowercase_			)
      self.parent.assertEqual(result.logits.shape	,     (self.batch_size, self.num_labels)			)


     def   UpperCAmelCase_			(						self					:	int	,     lowercase_					:	str	,     lowercase_					:	Union[str, Any]	,     lowercase_					:	Union[str, Any]	,     lowercase_					:	Tuple			)		->      Any:
      UpperCAmelCase			:      List[Any]		   =					self.num_labels
      UpperCAmelCase			:      Dict		   =					TFMobileViTForSemanticSegmentation(lowercase_			)
      UpperCAmelCase			:      Union[str, Any]		   =					self.image_size // self.output_stride

      UpperCAmelCase			:      Tuple		   =					model(lowercase_	,     training=lowercase_			)
      self.parent.assertEqual(
          result.logits.shape	,     (self.batch_size, self.num_labels, expected_height, expected_width)			)

      UpperCAmelCase			:      List[Any]		   =					model(lowercase_	,     labels=lowercase_	,     training=lowercase_			)
      self.parent.assertEqual(
          result.logits.shape	,     (self.batch_size, self.num_labels, expected_height, expected_width)			)




     def   UpperCAmelCase_			(						self					:	Optional[int]			)		->      Dict:
      UpperCAmelCase			:      Dict		   =					self.prepare_config_and_inputs()
      UpperCAmelCase   ,					UpperCAmelCase   ,					UpperCAmelCase   ,					UpperCAmelCase			:      Tuple		   =					config_and_inputs
      UpperCAmelCase			:      Any		   =					{'pixel_values': pixel_values}
      return config, inputs_dict




@require_tf
class 			A_					(							_snake_case			,  _snake_case			,  unittest.TestCase				):






     '''simple docstring'''



     UpperCAmelCase_		:      Dict    						=    (
         (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
         if is_tf_available()
         else ()
     )
     UpperCAmelCase_		:      Any    						=    (
         {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
         if is_tf_available()
         else {}
     )

     UpperCAmelCase_		:      Tuple    						=    False
     UpperCAmelCase_		:      Union[str, Any]    						=    False
     UpperCAmelCase_		:      Any    						=    False
     UpperCAmelCase_		:      Optional[Any]    						=    False
     UpperCAmelCase_		:      Union[str, Any]    						=    False


     def   UpperCAmelCase_			(						self					:	Any			)		->      Dict:
      UpperCAmelCase			:      Optional[int]		   =					TFMobileViTModelTester(self			)
      UpperCAmelCase			:      str		   =					TFMobileViTConfigTester(self	,     config_class=lowercase_	,     has_text_modality=lowercase_			)


     def   UpperCAmelCase_			(						self					:	int			)		->      Any:
      self.config_tester.run_common_tests()


     @unittest.skip(reason='MobileViT does not use inputs_embeds'			)
     def   UpperCAmelCase_			(						self					:	Union[str, Any]			)		->      Tuple:
      pass


     @unittest.skip(reason='MobileViT does not support input and output embeddings'			)
     def   UpperCAmelCase_			(						self					:	Any			)		->      int:
      pass


     @unittest.skip(reason='MobileViT does not output attentions'			)
     def   UpperCAmelCase_			(						self					:	int			)		->      Optional[int]:
      pass


     def   UpperCAmelCase_			(						self					:	str			)		->      Optional[Any]:
      UpperCAmelCase   ,					UpperCAmelCase			:      Any		   =					self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
       UpperCAmelCase			:      Any		   =					model_class(lowercase_			)
       UpperCAmelCase			:      List[str]		   =					inspect.signature(model.call			)
       # signature.parameters is an OrderedDict => so arg_names order is deterministic
       UpperCAmelCase			:      int		   =					[*signature.parameters.keys()]

       UpperCAmelCase			:      Dict		   =					['pixel_values']
       self.assertListEqual(arg_names[:1]	,     lowercase_			)


     def   UpperCAmelCase_			(						self					:	Optional[Any]			)		->      Tuple:
      UpperCAmelCase			:      Optional[Any]		   =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowercase_			)


     def   UpperCAmelCase_			(						self					:	List[str]			)		->      List[str]:
      def check_hidden_states_output(lowercase_					:	Dict	,     lowercase_					:	Optional[Any]	,     lowercase_					:	List[Any]			):
       UpperCAmelCase			:      Any		   =					model_class(lowercase_			)

       UpperCAmelCase			:      Any		   =					model(**self._prepare_for_class(lowercase_	,     lowercase_			)			)

       UpperCAmelCase			:      Dict		   =					outputs.hidden_states

       UpperCAmelCase			:      Dict		   =					5
       self.assertEqual(len(lowercase_			)	,     lowercase_			)

       # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
       # with the width and height being successively divided by 2.
       UpperCAmelCase			:      List[str]		   =					2
       for i in range(len(lowercase_			)			):
        self.assertListEqual(
            list(hidden_states[i].shape[-2:]			)	,     [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]	,     )
        divisor *= 2

       self.assertEqual(self.model_tester.output_stride	,     divisor // 2			)

      UpperCAmelCase   ,					UpperCAmelCase			:      Union[str, Any]		   =					self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
       UpperCAmelCase			:      Tuple		   =					True
       check_hidden_states_output(lowercase_	,     lowercase_	,     lowercase_			)

       # check that output_hidden_states also work using config
       del inputs_dict["output_hidden_states"]
       UpperCAmelCase			:      Any		   =					True

       check_hidden_states_output(lowercase_	,     lowercase_	,     lowercase_			)


     def   UpperCAmelCase_			(						self					:	List[str]			)		->      Any:
      UpperCAmelCase			:      Union[str, Any]		   =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*lowercase_			)


     def   UpperCAmelCase_			(						self					:	Optional[int]			)		->      int:
      UpperCAmelCase			:      int		   =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_semantic_segmentation(*lowercase_			)


     @unittest.skipIf(
         not is_tf_available() or len(tf.config.list_physical_devices('GPU'			)			) == 0	,     reason='TF does not support backprop for grouped convolutions on CPU.'	,     )
     def   UpperCAmelCase_			(						self					:	Any			)		->      str:
      super().test_dataset_conversion()


     def   UpperCAmelCase_			(						self					:	Optional[Any]	,     lowercase_					:	int	,     lowercase_					:	Any	,     lowercase_					:	Tuple=2E-1	,     lowercase_					:	Tuple=2E-1			)		->      Optional[Any]:
      self.assertTrue(np.allclose(lowercase_	,     lowercase_	,     atol=lowercase_	,     rtol=lowercase_			)			)


     @unittest.skipIf(
         not is_tf_available() or len(tf.config.list_physical_devices('GPU'			)			) == 0	,     reason='TF does not support backprop for grouped convolutions on CPU.'	,     )
     @slow
     def   UpperCAmelCase_			(						self					:	int			)		->      List[Any]:
      UpperCAmelCase   ,					UpperCAmelCase			:      Any		   =					self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
       # Since `TFMobileViTModel` cannot operate with the default `fit()` method.
       if model_class.__name__ != "TFMobileViTModel":
        UpperCAmelCase			:      Union[str, Any]		   =					model_class(lowercase_			)
        if getattr(lowercase_	,     'hf_compute_loss'	,     lowercase_			):
         super().test_keras_fit()


     def   UpperCAmelCase_			(						self					:	Tuple			)		->      Union[str, Any]:
      UpperCAmelCase   ,					UpperCAmelCase			:      str		   =					self.model_tester.prepare_config_and_inputs_for_common()
      for model_class in self.all_model_classes:
       # set an ignore index to correctly test the masked loss used in
       # `TFMobileViTForSemanticSegmentation`.
       if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
        UpperCAmelCase			:      int		   =					5

       UpperCAmelCase			:      Union[str, Any]		   =					model_class(lowercase_			)
       if getattr(lowercase_	,     'hf_compute_loss'	,     lowercase_			):
        # The number of elements in the loss should be the same as the number of elements in the label
        UpperCAmelCase			:      Tuple		   =					self._prepare_for_class(inputs_dict.copy()	,     lowercase_	,     return_labels=lowercase_			)
        UpperCAmelCase			:      List[str]		   =					prepared_for_class[
            sorted(prepared_for_class.keys() - inputs_dict.keys()	,     reverse=lowercase_			)[0]
        ]
        UpperCAmelCase			:      List[Any]		   =					added_label.shape.as_list()[:1]

        # Test that model correctly compute the loss with kwargs
        UpperCAmelCase			:      Dict		   =					self._prepare_for_class(inputs_dict.copy()	,     lowercase_	,     return_labels=lowercase_			)
        UpperCAmelCase			:      List[Any]		   =					{'input_ids', 'pixel_values', 'input_features'}
        UpperCAmelCase			:      int		   =					possible_input_names.intersection(set(lowercase_			)			).pop()
        UpperCAmelCase			:      Optional[int]		   =					prepared_for_class.pop(lowercase_			)

        UpperCAmelCase			:      List[Any]		   =					model(lowercase_	,     **lowercase_			)[0]
        self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)

        # Test that model correctly compute the loss when we mask some positions
        UpperCAmelCase			:      List[str]		   =					self._prepare_for_class(inputs_dict.copy()	,     lowercase_	,     return_labels=lowercase_			)
        UpperCAmelCase			:      List[Any]		   =					{'input_ids', 'pixel_values', 'input_features'}
        UpperCAmelCase			:      int		   =					possible_input_names.intersection(set(lowercase_			)			).pop()
        UpperCAmelCase			:      str		   =					prepared_for_class.pop(lowercase_			)
        if "labels" in prepared_for_class:
         UpperCAmelCase			:      Any		   =					prepared_for_class['labels'].numpy()
         if len(labels.shape			) > 1 and labels.shape[1] != 1:
          # labels[0] = -100
          UpperCAmelCase			:      Tuple		   =					tf.convert_to_tensor(lowercase_			)
          UpperCAmelCase			:      List[Any]		   =					model(lowercase_	,     **lowercase_			)[0]
          self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)
          self.assertTrue(not np.any(np.isnan(loss.numpy()			)			)			)

                # Test that model correctly compute the loss with a dict
        UpperCAmelCase			:      Optional[int]		   =					self._prepare_for_class(inputs_dict.copy()	,     lowercase_	,     return_labels=lowercase_			)
        UpperCAmelCase			:      Optional[int]		   =					model(lowercase_			)[0]
        self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)

        # Test that model correctly compute the loss with a tuple
        UpperCAmelCase			:      Union[str, Any]		   =					self._prepare_for_class(inputs_dict.copy()	,     lowercase_	,     return_labels=lowercase_			)

        # Get keys that were added with the _prepare_for_class function
        UpperCAmelCase			:      Tuple		   =					prepared_for_class.keys() - inputs_dict.keys()
        UpperCAmelCase			:      List[Any]		   =					inspect.signature(model.call			).parameters
        UpperCAmelCase			:      str		   =					list(signature.keys()			)

        # Create a dictionary holding the location of the tensors in the tuple
        UpperCAmelCase			:      Union[str, Any]		   =					{0: input_name}
        for label_key in label_keys:
         UpperCAmelCase			:      Optional[Any]		   =					signature_names.index(lowercase_			)
         UpperCAmelCase			:      str		   =					label_key
        UpperCAmelCase			:      Any		   =					sorted(tuple_index_mapping.items()			)
        # Initialize a list with their default values, update the values and convert to a tuple
        UpperCAmelCase			:      Any		   =					[]

        for name in signature_names:
         if name != "kwargs":
          list_input.append(signature[name].default			)

        for index, value in sorted_tuple_index_mapping:
         UpperCAmelCase			:      Dict		   =					prepared_for_class[value]

        UpperCAmelCase			:      Union[str, Any]		   =					tuple(lowercase_			)

        # Send to model
        UpperCAmelCase			:      Dict		   =					model(tuple_input[:-1]			)[0]

        self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)




     @slow
     def   UpperCAmelCase_			(						self					:	Optional[Any]			)		->      Optional[Any]:
      for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       UpperCAmelCase			:      Any		   =					TFMobileViTModel.from_pretrained(lowercase_			)
       self.assertIsNotNone(lowercase_			)




def  UpperCamelCase(	):
 UpperCAmelCase			:      List[Any]		   =					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
 return image




@require_tf
class 			A_					(							unittest.TestCase				):






     '''simple docstring'''



     @slow
     def   UpperCAmelCase_			(						self					:	Tuple			)		->      str:
      UpperCAmelCase			:      int		   =					TFMobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'			)

      UpperCAmelCase			:      Optional[Any]		   =					MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small'			)
      UpperCAmelCase			:      str		   =					prepare_img()
      UpperCAmelCase			:      str		   =					image_processor(images=lowercase_	,     return_tensors='tf'			)

      # forward pass
      UpperCAmelCase			:      List[str]		   =					model(**lowercase_	,     training=lowercase_			)

      # verify the logits
      UpperCAmelCase			:      Optional[int]		   =					tf.TensorShape((1, 1_000)			)
      self.assertEqual(outputs.logits.shape	,     lowercase_			)

      UpperCAmelCase			:      Dict		   =					tf.constant([-1.9364, -1.2327, -0.4653]			)

      tf.debugging.assert_near(outputs.logits[0, :3]	,     lowercase_	,     atol=1E-4	,     rtol=1E-04			)




     @slow
     def   UpperCAmelCase_			(						self					:	Dict			)		->      Optional[int]:
      # `from_pt` will be removed
      UpperCAmelCase			:      Optional[Any]		   =					TFMobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'			)

      UpperCAmelCase			:      Tuple		   =					MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small'			)

      UpperCAmelCase			:      Optional[Any]		   =					prepare_img()
      UpperCAmelCase			:      Optional[int]		   =					image_processor(images=lowercase_	,     return_tensors='tf'			)

      # forward pass
      UpperCAmelCase			:      Union[str, Any]		   =					model(inputs.pixel_values	,     training=lowercase_			)
      UpperCAmelCase			:      Optional[int]		   =					outputs.logits

      # verify the logits
      UpperCAmelCase			:      Optional[Any]		   =					tf.TensorShape((1, 21, 32, 32)			)
      self.assertEqual(logits.shape	,     lowercase_			)

      UpperCAmelCase			:      List[str]		   =					tf.constant(
          [
              [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
              [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
              [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
          ]			)

      tf.debugging.assert_near(logits[0, :3, :3, :3]	,     lowercase_	,     rtol=1E-4	,     atol=1E-4			)







'''simple docstring'''

import sacrebleu as scb
from packaging import version

import datasets


lowercase__            =     "\\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"

lowercase__            =     "\\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"

lowercase__            =     "\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 			A_					(							datasets.Metric				):






     '''simple docstring'''



     def   UpperCAmelCase_			(						self					:	Tuple			)		->      Union[str, 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					:	Union[str, Any]	,     lowercase_					:	Union[str, Any]	,     lowercase_					:	int	,     lowercase_					:	List[Any]="exp"	,     lowercase_					:	Optional[int]=None	,     lowercase_					:	List[str]=False	,     lowercase_					:	Tuple=False	,     lowercase_					:	int=None	,     lowercase_					:	str=False	,     )		->      Dict:
      UpperCAmelCase			:      Union[str, Any]		   =					len(references[0]			)
      if any(len(lowercase_			) != references_per_prediction for refs in references			):
       raise ValueError('Sacrebleu requires the same number of references for each prediction'			)
      UpperCAmelCase			:      Optional[Any]		   =					[[refs[i] for refs in references] for i in range(lowercase_			)]
      UpperCAmelCase			:      List[Any]		   =					scb.corpus_bleu(
          lowercase_	,     lowercase_	,     smooth_method=lowercase_	,     smooth_value=lowercase_	,     force=lowercase_	,     lowercase=lowercase_	,     use_effective_order=lowercase_	,     **({'tokenize': tokenize} if tokenize else {})	,     )
      UpperCAmelCase			:      Union[str, Any]		   =					{
          '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




