


'''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, MobileNetVaModel
      from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import MobileNetVaImageProcessor



class 			a       (	_a ):


     """simple docstring"""






     def 				lowerCamelCase__				(       self  :	Optional[Any]    )		->							Tuple:
          __UpperCAmelCase			:				Tuple													=    self.config_class(**self.inputs_dict    )
          self.parent.assertTrue(hasattr(snake_case							,				'''tf_padding'''    )    )
          self.parent.assertTrue(hasattr(snake_case							,				'''depth_multiplier'''    )    )



class 			a       :


     """simple docstring"""






     def __init__(       self  :	Union[str, Any]							,				snake_case  :	List[str]							,				snake_case  :	List[Any]=13							,				snake_case  :	int=3							,				snake_case  :	List[Any]=32							,				snake_case  :	int=0.25							,				snake_case  :	Dict=8							,				snake_case  :	Any=True							,				snake_case  :	Dict=1024							,				snake_case  :	Union[str, Any]=32							,				snake_case  :	int="relu6"							,				snake_case  :	Any=0.1							,				snake_case  :	str=0.02							,				snake_case  :	Optional[int]=True							,				snake_case  :	List[Any]=True							,				snake_case  :	Union[str, Any]=10							,				snake_case  :	Any=None							,				)		->							List[Any]:
          __UpperCAmelCase			:				Tuple													=    parent
          __UpperCAmelCase			:				Any													=    batch_size
          __UpperCAmelCase			:				List[str]													=    num_channels
          __UpperCAmelCase			:				int													=    image_size
          __UpperCAmelCase			:				Dict													=    depth_multiplier
          __UpperCAmelCase			:				Optional[Any]													=    min_depth
          __UpperCAmelCase			:				Dict													=    tf_padding
          __UpperCAmelCase			:				Union[str, Any]													=    int(last_hidden_size * depth_multiplier    )
          __UpperCAmelCase			:				List[Any]													=    output_stride
          __UpperCAmelCase			:				Tuple													=    hidden_act
          __UpperCAmelCase			:				Dict													=    classifier_dropout_prob
          __UpperCAmelCase			:				Optional[int]													=    use_labels
          __UpperCAmelCase			:				int													=    is_training
          __UpperCAmelCase			:				Dict													=    num_labels
          __UpperCAmelCase			:				List[str]													=    initializer_range
          __UpperCAmelCase			:				List[str]													=    scope

     def 				lowerCamelCase__				(       self  :	str    )		->							Dict:
          __UpperCAmelCase			:				List[Any]													=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

          __UpperCAmelCase			:				Optional[int]													=    self.get_config()

          return config, pixel_values, labels, pixel_labels

     def 				lowerCamelCase__				(       self  :	List[str]    )		->							Optional[Any]:
          return MobileNetVaConfig(
              num_channels=self.num_channels							,				image_size=self.image_size							,				depth_multiplier=self.depth_multiplier							,				min_depth=self.min_depth							,				tf_padding=self.tf_padding							,				hidden_act=self.hidden_act							,				classifier_dropout_prob=self.classifier_dropout_prob							,				initializer_range=self.initializer_range							,				)

     def 				lowerCamelCase__				(       self  :	Optional[int]							,				snake_case  :	str							,				snake_case  :	Dict							,				snake_case  :	str							,				snake_case  :	Dict    )		->							Dict:
          __UpperCAmelCase			:				Optional[int]													=    MobileNetVaModel(config=snake_case    )
          model.to(snake_case    )
          model.eval()
          __UpperCAmelCase			:				str													=    model(snake_case    )
          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,
              )							,				)

     def 				lowerCamelCase__				(       self  :	Tuple							,				snake_case  :	Union[str, Any]							,				snake_case  :	List[str]							,				snake_case  :	List[Any]							,				snake_case  :	List[str]    )		->							Dict:
          __UpperCAmelCase			:				int													=    self.num_labels
          __UpperCAmelCase			:				Optional[int]													=    MobileNetVaForImageClassification(snake_case    )
          model.to(snake_case    )
          model.eval()
          __UpperCAmelCase			:				str													=    model(snake_case							,				labels=snake_case    )
          self.parent.assertEqual(result.logits.shape							,				(self.batch_size, self.num_labels)    )






     def 				lowerCamelCase__				(       self  :	str    )		->							Union[str, Any]:
          __UpperCAmelCase			:				Optional[Any]													=    self.prepare_config_and_inputs()
          __UpperCAmelCase							,     __UpperCAmelCase							,     __UpperCAmelCase							,     __UpperCAmelCase			:				List[str]													=    config_and_inputs
          __UpperCAmelCase			:				int													=    {'''pixel_values''': pixel_values}
          return config, inputs_dict



@require_torch
class 			a       (	_a			,						_a			,						unittest.TestCase ):


     """simple docstring"""






     SCREAMING_SNAKE_CASE :				List[str]							     =     (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
     SCREAMING_SNAKE_CASE :				List[str]							     =     (
         {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification}
         if is_torch_available()
         else {}
     )

     SCREAMING_SNAKE_CASE :				Optional[int]							     =     False
     SCREAMING_SNAKE_CASE :				List[str]							     =     False
     SCREAMING_SNAKE_CASE :				Union[str, Any]							     =     False
     SCREAMING_SNAKE_CASE :				str							     =     False

     def 				lowerCamelCase__				(       self  :	List[str]    )		->							Any:
          __UpperCAmelCase			:				Tuple													=    MobileNetVaModelTester(self    )
          __UpperCAmelCase			:				Tuple													=    MobileNetVaConfigTester(self							,				config_class=snake_case							,				has_text_modality=snake_case    )

     def 				lowerCamelCase__				(       self  :	int    )		->							Dict:
          self.config_tester.run_common_tests()

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

     @unittest.skip(reason='''MobileNetV1 does not support input and output embeddings'''    )
     def 				lowerCamelCase__				(       self  :	Dict    )		->							List[Any]:
          pass

     @unittest.skip(reason='''MobileNetV1 does not output attentions'''    )
     def 				lowerCamelCase__				(       self  :	Union[str, Any]    )		->							Any:
          pass

     def 				lowerCamelCase__				(       self  :	Union[str, Any]    )		->							int:
          __UpperCAmelCase							,     __UpperCAmelCase			:				Any													=    self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __UpperCAmelCase			:				str													=    model_class(snake_case    )
               __UpperCAmelCase			:				str													=    inspect.signature(model.forward    )
               # signature.parameters is an OrderedDict => so arg_names order is deterministic
               __UpperCAmelCase			:				str													=    [*signature.parameters.keys()]

               __UpperCAmelCase			:				List[Any]													=    ['''pixel_values''']
               self.assertListEqual(arg_names[:1]							,				snake_case    )

     def 				lowerCamelCase__				(       self  :	int    )		->							List[str]:
          __UpperCAmelCase			:				Optional[int]													=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*snake_case    )

     def 				lowerCamelCase__				(       self  :	Any    )		->							str:
          def check_hidden_states_output(snake_case  :	Optional[int]							,				snake_case  :	Optional[Any]							,				snake_case  :	Optional[Any]    ):
               __UpperCAmelCase			:				Optional[Any]													=    model_class(snake_case    )
               model.to(snake_case    )
               model.eval()

               with torch.no_grad():
                    __UpperCAmelCase			:				Any													=    model(**self._prepare_for_class(snake_case							,				snake_case    )    )

               __UpperCAmelCase			:				str													=    outputs.hidden_states

               __UpperCAmelCase			:				Optional[int]													=    26
               self.assertEqual(len(snake_case    )							,				snake_case    )

          __UpperCAmelCase							,     __UpperCAmelCase			:				Optional[Any]													=    self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __UpperCAmelCase			:				str													=    True
               check_hidden_states_output(snake_case							,				snake_case							,				snake_case    )

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

               check_hidden_states_output(snake_case							,				snake_case							,				snake_case    )

     def 				lowerCamelCase__				(       self  :	int    )		->							int:
          __UpperCAmelCase			:				str													=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*snake_case    )






     @slow
     def 				lowerCamelCase__				(       self  :	Optional[Any]    )		->							Union[str, Any]:
          for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __UpperCAmelCase			:				List[Any]													=    MobileNetVaModel.from_pretrained(snake_case    )
               self.assertIsNotNone(snake_case    )




def 			_a			(		):





     '''simple docstring'''






     __UpperCAmelCase			:				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  :	Union[str, Any]    )		->							Dict:
          return (
              MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v1_1.0_224'''    ) if is_vision_available() else None
          )






     @slow
     def 				lowerCamelCase__				(       self  :	str    )		->							Dict:
          __UpperCAmelCase			:				Union[str, Any]													=    MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v1_1.0_224'''    ).to(snake_case    )

          __UpperCAmelCase			:				Tuple													=    self.default_image_processor
          __UpperCAmelCase			:				str													=    prepare_img()
          __UpperCAmelCase			:				Union[str, Any]													=    image_processor(images=snake_case							,				return_tensors='''pt'''    ).to(snake_case    )

          # forward pass
          with torch.no_grad():
               __UpperCAmelCase			:				List[str]													=    model(**snake_case    )

          # verify the logits
          __UpperCAmelCase			:				Optional[int]													=    torch.Size((1, 1001)    )
          self.assertEqual(outputs.logits.shape							,				snake_case    )

          __UpperCAmelCase			:				List[Any]													=    torch.tensor([-4.1_739, -1.1_233, 3.1_205]    ).to(snake_case    )

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



'''simple docstring'''



import sacrebleu as scb
from packaging import version
from sacrebleu import CHRF

import datasets


__UpperCAmelCase    :str				       =     "\\n@inproceedings{popovic-2015-chrf,\n    title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n    author = \"Popovi{\'c}, Maja\",\n    booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n    month = sep,\n    year = \"2015\",\n    address = \"Lisbon, Portugal\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://aclanthology.org/W15-3049\",\n    doi = \"10.18653/v1/W15-3049\",\n    pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n    title = \"chr{F}++: words helping character n-grams\",\n    author = \"Popovi{\'c}, Maja\",\n    booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n    month = sep,\n    year = \"2017\",\n    address = \"Copenhagen, Denmark\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://aclanthology.org/W17-4770\",\n    doi = \"10.18653/v1/W17-4770\",\n    pages = \"612--618\",\n}\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    :Tuple				       =     "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n"

__UpperCAmelCase    :List[Any]				       =     "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n    predictions (list of str): The predicted sentences.\n    references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n    char_order (int): Character n-gram order. Defaults to `6`.\n    word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n    beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n    lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n    whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n    eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n    to reference chrF++.py, NLTK and Moses implementations. If `False`,\n    it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n    'score' (float): The chrF (chrF++) score,\n    'char_order' (int): The character n-gram order,\n    'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n    'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n    Example 1--a simple example of calculating chrF:\n        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction, references=reference)\n        >>> print(results)\n        {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n    Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction,\n        ...                         references=reference,\n        ...                         word_order=2)\n        >>> print(results)\n        {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n    Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction,\n        ...                         references=reference,\n        ...                         word_order=2,\n        ...                         lowercase=True)\n        >>> print(results)\n        {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n"



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


     """simple docstring"""






     def 				lowerCamelCase__				(       self  :	Dict    )		->							str:
          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#chrf--chrf'''							,				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#chrf--chrf''']							,				reference_urls=[
                  '''https://github.com/m-popovic/chrF''',
              ]							,				)






     def 				lowerCamelCase__				(       self  :	Any							,				snake_case  :	str							,				snake_case  :	int							,				snake_case  :	int = CHRF.CHAR_ORDER							,				snake_case  :	int = CHRF.WORD_ORDER							,				snake_case  :	int = CHRF.BETA							,				snake_case  :	bool = False							,				snake_case  :	bool = False							,				snake_case  :	bool = False							,				)		->							Optional[int]:
          __UpperCAmelCase			:				Any													=    len(references[0]    )
          if any(len(snake_case    ) != references_per_prediction for refs in references    ):
               raise ValueError('''Sacrebleu requires the same number of references for each prediction'''    )
          __UpperCAmelCase			:				int													=    [[refs[i] for refs in references] for i in range(snake_case    )]

          __UpperCAmelCase			:				int													=    CHRF(snake_case							,				snake_case							,				snake_case							,				snake_case							,				snake_case							,				snake_case    )
          __UpperCAmelCase			:				Dict													=    sb_chrf.corpus_score(snake_case							,				snake_case    )

          return {
              "score": output.score,
              "char_order": output.char_order,
              "word_order": output.word_order,
              "beta": output.beta,
          }