



"""simple docstring"""





import datasets

from .nmt_bleu import compute_bleu  # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py


lowerCamelCase  			=		"""\
@INPROCEEDINGS{Papineni02bleu:a,
    author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},
    title = {BLEU: a Method for Automatic Evaluation of Machine Translation},
    booktitle = {},
    year = {2002},
    pages = {311--318}
}
@inproceedings{lin-och-2004-orange,
    title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\",
    author = \"Lin, Chin-Yew  and
      Och, Franz Josef\",
    booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\",
    month = \"aug 23{--}aug 27\",
    year = \"2004\",
    address = \"Geneva, Switzerland\",
    publisher = \"COLING\",
    url = \"https://www.aclweb.org/anthology/C04-1072\",
    pages = \"501--507\",
}
"""

lowerCamelCase  			=		"""\
BLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.
Quality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation,
the better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and
remains one of the most popular automated and inexpensive metrics.

Scores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.
Those scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness
are not taken into account[citation needed].

BLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1
representing more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the
reference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional
reference translations will increase the BLEU score.
"""

lowerCamelCase  			=		"""
Computes BLEU score of translated segments against one or more references.
Args:
    predictions: list of translations to score.
        Each translation should be tokenized into a list of tokens.
    references: list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    max_order: Maximum n-gram order to use when computing BLEU score.
    smooth: Whether or not to apply Lin et al. 2004 smoothing.
Returns:
    'bleu': bleu score,
    'precisions': geometric mean of n-gram precisions,
    'brevity_penalty': brevity penalty,
    'length_ratio': ratio of lengths,
    'translation_length': translation_length,
    'reference_length': reference_length
Examples:

    >>> predictions = [
    ...     [\"hello\", \"there\", \"general\", \"kenobi\"],                             # tokenized prediction of the first sample
    ...     [\"foo\", \"bar\", \"foobar\"]                                             # tokenized prediction of the second sample
    ... ]
    >>> references = [
    ...     [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]],  # tokenized references for the first sample (2 references)
    ...     [[\"foo\", \"bar\", \"foobar\"]]                                           # tokenized references for the second sample (1 reference)
    ... ]
    >>> bleu = datasets.load_metric(\"bleu\")
    >>> results = bleu.compute(predictions=predictions, references=references)
    >>> print(results[\"bleu\"])
    1.0
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,   _KWARGS_DESCRIPTION )
class  lowercase__  (       datasets.Metric ):







       '''simple docstring'''


       def 	lowercase__							(				self     :    List[str]       )					->		List[Any]:


             '''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"       ),
                     }       )						,							codebase_urls=["https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py"]						,							reference_urls=[
                     "https://en.wikipedia.org/wiki/BLEU",
                     "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213",
                 ]						,							)







       def 	lowercase__							(				self     :    Optional[int]						,							_UpperCAmelCase     :    List[str]						,							_UpperCAmelCase     :    Optional[Any]						,							_UpperCAmelCase     :    Optional[Any]=4						,							_UpperCAmelCase     :    Dict=False       )					->		List[str]:


             '''simple docstring'''




             UpperCAmelCase_     					=				compute_bleu(
                 reference_corpus=_UpperCAmelCase						,							translation_corpus=_UpperCAmelCase						,							max_order=_UpperCAmelCase						,							smooth=_UpperCAmelCase       )
             ((UpperCAmelCase_)					,       (UpperCAmelCase_)					,       (UpperCAmelCase_)					,       (UpperCAmelCase_)					,       (UpperCAmelCase_)					,       (UpperCAmelCase_))     					=				score
             return {
                 "bleu": bleu,
                 "precisions": precisions,
                 "brevity_penalty": bp,
                 "length_ratio": ratio,
                 "translation_length": translation_length,
                 "reference_length": reference_length,
             }









"""simple docstring"""







import inspect
import unittest

from transformers import MobileNetVaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
	from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import MobileNetVaImageProcessor







class 					A_(SCREAMING_SNAKE_CASE_      ):







			"""simple docstring"""



			def    _lowerCAmelCase		(	self							):
						_lowerCamelCase					:					Optional[int]	       =    self.config_class(**self.inputs_dict							)
						self.parent.assertTrue(hasattr(A				,   'tf_padding'							)							)
						self.parent.assertTrue(hasattr(A				,   'depth_multiplier'							)							)







class 					A_:







			"""simple docstring"""



			def __init__(	self				,   A				,   A=13				,   A=3				,   A=32				,   A=0.2_5				,   A=8				,   A=8				,   A=6				,   A=32				,   A=True				,   A=True				,   A=True				,   A="relu6"				,   A=1280				,   A=0.1				,   A=0.0_2				,   A=True				,   A=True				,   A=10				,   A=None				,   ):
						_lowerCamelCase					:					str	       =    parent
						_lowerCamelCase					:					Union[str, Any]	       =    batch_size
						_lowerCamelCase					:					List[str]	       =    num_channels
						_lowerCamelCase					:					int	       =    image_size
						_lowerCamelCase					:					str	       =    depth_multiplier
						_lowerCamelCase					:					Optional[int]	       =    depth_divisible_by
						_lowerCamelCase					:					Any	       =    min_depth
						_lowerCamelCase					:					Optional[Any]	       =    expand_ratio
						_lowerCamelCase					:					Tuple	       =    tf_padding
						_lowerCamelCase					:					Optional[Any]	       =    output_stride
						_lowerCamelCase					:					Optional[int]	       =    first_layer_is_expansion
						_lowerCamelCase					:					List[str]	       =    finegrained_output
						_lowerCamelCase					:					Any	       =    hidden_act
						_lowerCamelCase					:					Dict	       =    last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier							)
						_lowerCamelCase					:					Any	       =    classifier_dropout_prob
						_lowerCamelCase					:					Optional[Any]	       =    use_labels
						_lowerCamelCase					:					Any	       =    is_training
						_lowerCamelCase					:					List[str]	       =    num_labels
						_lowerCamelCase					:					int	       =    initializer_range
						_lowerCamelCase					:					Tuple	       =    scope
			def    _lowerCAmelCase		(	self							):
						_lowerCamelCase					:					Tuple	       =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

						_lowerCamelCase					:					Union[str, Any]	       =    None
						_lowerCamelCase					:					str	       =    None
						if self.use_labels:
									_lowerCamelCase					:					Dict	       =    ids_tensor([self.batch_size]				,   self.num_labels							)
									_lowerCamelCase					:					Dict	       =    ids_tensor([self.batch_size, self.image_size, self.image_size]				,   self.num_labels							)

						_lowerCamelCase					:					List[Any]	       =    self.get_config()

						return config, pixel_values, labels, pixel_labels
			def    _lowerCAmelCase		(	self							):
						return MobileNetVaConfig(
						    num_channels=self.num_channels				,   image_size=self.image_size				,   depth_multiplier=self.depth_multiplier				,   depth_divisible_by=self.depth_divisible_by				,   min_depth=self.min_depth				,   expand_ratio=self.expand_ratio				,   output_stride=self.output_stride				,   first_layer_is_expansion=self.first_layer_is_expansion				,   finegrained_output=self.finegrained_output				,   hidden_act=self.hidden_act				,   tf_padding=self.tf_padding				,   classifier_dropout_prob=self.classifier_dropout_prob				,   initializer_range=self.initializer_range				,   )
			def    _lowerCAmelCase		(	self				,   A				,   A				,   A				,   A							):
						_lowerCamelCase					:					int	       =    MobileNetVaModel(config=A							)
						model.to(A							)
						model.eval()
						_lowerCamelCase					:					str	       =    model(A							)
						self.parent.assertEqual(
						    result.last_hidden_state.shape				,   (
						        self.batch_size,
						        self.last_hidden_size,
						        self.image_size // self.output_stride,
						        self.image_size // self.output_stride,
						    )				,   )
						self.parent.assertEqual(
						    result.pooler_output.shape				,   (self.batch_size, self.last_hidden_size)				,   )
			def    _lowerCAmelCase		(	self				,   A				,   A				,   A				,   A							):
						_lowerCamelCase					:					List[Any]	       =    self.num_labels
						_lowerCamelCase					:					Tuple	       =    MobileNetVaForImageClassification(A							)
						model.to(A							)
						model.eval()
						_lowerCamelCase					:					List[str]	       =    model(A				,   labels=A							)
						self.parent.assertEqual(result.logits.shape				,   (self.batch_size, self.num_labels)							)
			def    _lowerCAmelCase		(	self				,   A				,   A				,   A				,   A							):
						_lowerCamelCase					:					int	       =    self.num_labels
						_lowerCamelCase					:					List[str]	       =    MobileNetVaForSemanticSegmentation(A							)
						model.to(A							)
						model.eval()
						_lowerCamelCase					:					Dict	       =    model(A							)
						self.parent.assertEqual(
						    result.logits.shape				,   (
						        self.batch_size,
						        self.num_labels,
						        self.image_size // self.output_stride,
						        self.image_size // self.output_stride,
						    )				,   )
						_lowerCamelCase					:					str	       =    model(A				,   labels=A							)
						self.parent.assertEqual(
						    result.logits.shape				,   (
						        self.batch_size,
						        self.num_labels,
						        self.image_size // self.output_stride,
						        self.image_size // self.output_stride,
						    )				,   )

			def    _lowerCAmelCase		(	self							):
						_lowerCamelCase					:					List[str]	       =    self.prepare_config_and_inputs()
						_lowerCamelCase       ,							_lowerCamelCase       ,							_lowerCamelCase       ,							_lowerCamelCase					:					List[Any]	       =    config_and_inputs
						_lowerCamelCase					:					Any	       =    {'pixel_values': pixel_values}
						return config, inputs_dict







@require_torch
class 					A_(SCREAMING_SNAKE_CASE_   ,   SCREAMING_SNAKE_CASE_   ,   unittest.TestCase      ):







			"""simple docstring"""



			a_       :			List[Any]												=			(
			    (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)
			a_       :			Optional[int]												=			(
			    {
			        """feature-extraction""": MobileNetVaModel,
			        """image-classification""": MobileNetVaForImageClassification,
			        """image-segmentation""": MobileNetVaForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			a_       :			List[Any]												=			False
			a_       :			Union[str, Any]												=			False
			a_       :			Union[str, Any]												=			False
			a_       :			str												=			False
			def    _lowerCAmelCase		(	self							):
						_lowerCamelCase					:					int	       =    MobileNetVaModelTester(self							)
						_lowerCamelCase					:					int	       =    MobileNetVaConfigTester(self				,   config_class=A				,   has_text_modality=A							)
			def    _lowerCAmelCase		(	self							):
						self.config_tester.run_common_tests()
			@unittest.skip(reason='MobileNetV2 does not use inputs_embeds'							)
			def    _lowerCAmelCase		(	self							):
						pass
			@unittest.skip(reason='MobileNetV2 does not support input and output embeddings'							)
			def    _lowerCAmelCase		(	self							):
						pass
			@unittest.skip(reason='MobileNetV2 does not output attentions'							)
			def    _lowerCAmelCase		(	self							):
						pass
			def    _lowerCAmelCase		(	self							):
						_lowerCamelCase       ,							_lowerCamelCase					:					List[Any]	       =    self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									_lowerCamelCase					:					int	       =    model_class(A							)
									_lowerCamelCase					:					Optional[Any]	       =    inspect.signature(model.forward							)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									_lowerCamelCase					:					Tuple	       =    [*signature.parameters.keys()]

									_lowerCamelCase					:					Tuple	       =    ['pixel_values']
									self.assertListEqual(arg_names[:1]				,   A							)
			def    _lowerCAmelCase		(	self							):
						_lowerCamelCase					:					Tuple	       =    self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*A							)
			def    _lowerCAmelCase		(	self							):
						def check_hidden_states_output(A				,   A				,   A							):
									_lowerCamelCase					:					Any	       =    model_class(A							)
									model.to(A							)
									model.eval()

									with torch.no_grad():
												_lowerCamelCase					:					Optional[int]	       =    model(**self._prepare_for_class(A				,   A							)							)

									_lowerCamelCase					:					int	       =    outputs.hidden_states

									_lowerCamelCase					:					Dict	       =    16
									self.assertEqual(len(A							)				,   A							)

						_lowerCamelCase       ,							_lowerCamelCase					:					Optional[int]	       =    self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									_lowerCamelCase					:					Optional[Any]	       =    True
									check_hidden_states_output(A				,   A				,   A							)

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

									check_hidden_states_output(A				,   A				,   A							)
			def    _lowerCAmelCase		(	self							):
						_lowerCamelCase					:					Union[str, Any]	       =    self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*A							)
			def    _lowerCAmelCase		(	self							):
						_lowerCamelCase					:					Any	       =    self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_semantic_segmentation(*A							)

			@slow
			def    _lowerCAmelCase		(	self							):
						for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									_lowerCamelCase					:					Any	       =    MobileNetVaModel.from_pretrained(A							)
									self.assertIsNotNone(A							)






def     UpperCAmelCase_					(				):




			'''simple docstring'''



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







@require_torch
@require_vision
class 					A_(unittest.TestCase      ):







			"""simple docstring"""



			@cached_property
			def    _lowerCAmelCase		(	self							):
						return (
						    MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v2_1.0_224'							) if is_vision_available() else None
						)
			@slow
			def    _lowerCAmelCase		(	self							):
						_lowerCamelCase					:					Optional[Any]	       =    MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v2_1.0_224'							).to(A							)

						_lowerCamelCase					:					int	       =    self.default_image_processor
						_lowerCamelCase					:					Tuple	       =    prepare_img()
						_lowerCamelCase					:					int	       =    image_processor(images=A				,   return_tensors='pt'							).to(A							)

						# forward pass
						with torch.no_grad():
									_lowerCamelCase					:					int	       =    model(**A							)

						# verify the logits
						_lowerCamelCase					:					Tuple	       =    torch.Size((1, 1001)							)
						self.assertEqual(outputs.logits.shape				,   A							)

						_lowerCamelCase					:					Union[str, Any]	       =    torch.tensor([0.2_4_4_5, -1.1_9_9_3, 0.1_9_0_5]							).to(A							)

						self.assertTrue(torch.allclose(outputs.logits[0, :3]				,   A				,   atol=1E-4							)							)

			@slow
			def    _lowerCAmelCase		(	self							):
						_lowerCamelCase					:					str	       =    MobileNetVaForSemanticSegmentation.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513'							)
						_lowerCamelCase					:					Tuple	       =    model.to(A							)

						_lowerCamelCase					:					Tuple	       =    MobileNetVaImageProcessor.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513'							)

						_lowerCamelCase					:					Any	       =    prepare_img()
						_lowerCamelCase					:					Any	       =    image_processor(images=A				,   return_tensors='pt'							).to(A							)

						# forward pass
						with torch.no_grad():
									_lowerCamelCase					:					Optional[Any]	       =    model(**A							)
						_lowerCamelCase					:					Optional[int]	       =    outputs.logits

						# verify the logits
						_lowerCamelCase					:					Tuple	       =    torch.Size((1, 21, 65, 65)							)
						self.assertEqual(logits.shape				,   A							)

						_lowerCamelCase					:					Optional[int]	       =    torch.tensor(
						    [
						        [[1_7.5_7_9_0, 1_7.7_5_8_1, 1_8.3_3_5_5], [1_8.3_2_5_7, 1_8.4_2_3_0, 1_8.8_9_7_3], [1_8.6_1_6_9, 1_8.8_6_5_0, 1_9.2_1_8_7]],
						        [[-2.1_5_9_5, -2.0_9_7_7, -2.3_7_4_1], [-2.4_2_2_6, -2.3_0_2_8, -2.6_8_3_5], [-2.7_8_1_9, -2.5_9_9_1, -2.7_7_0_6]],
						        [[4.2_0_5_8, 4.8_3_1_7, 4.7_6_3_8], [4.4_1_3_6, 5.0_3_6_1, 4.9_3_8_3], [4.5_0_2_8, 4.9_6_4_4, 4.8_7_3_4]],
						    ]				,   device=A				,   )

						self.assertTrue(torch.allclose(logits[0, :3, :3, :3]				,   A				,   atol=1E-4							)							)





