





"""simple docstring"""





import inspect
import unittest

from transformers import EfficientNetConfig
from transformers.testing_utils import is_pipeline_test, 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 EfficientNetForImageClassification, EfficientNetModel
       from transformers.models.efficientnet.modeling_efficientnet import EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor

class 		lowercase :





      def __init__(	self				,						lowercase				,						lowercase=13				,						lowercase=32				,						lowercase=3				,						lowercase=[3, 3, 5]				,						lowercase=[32, 16, 24]				,						lowercase=[16, 24, 40]				,						lowercase=[1, 1, 2]				,						lowercase=[1, 1, 2]				,						lowercase=[1, 6, 6]				,						lowercase=True				,						lowercase=True				,						lowercase=37				,						lowercase="gelu"				,						lowercase=10				,						)		->					Tuple:
            lowerCAmelCase  						=	parent
            lowerCAmelCase  						=	batch_size
            lowerCAmelCase  						=	image_size
            lowerCAmelCase  						=	num_channels
            lowerCAmelCase  						=	kernel_sizes
            lowerCAmelCase  						=	in_channels
            lowerCAmelCase  						=	out_channels
            lowerCAmelCase  						=	strides
            lowerCAmelCase  						=	num_block_repeats
            lowerCAmelCase  						=	expand_ratios
            lowerCAmelCase  						=	is_training
            lowerCAmelCase  						=	hidden_act
            lowerCAmelCase  						=	num_labels
            lowerCAmelCase  						=	use_labels





      def    _snake_case      (	self			)		->					List[str]:
            lowerCAmelCase  						=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

            lowerCAmelCase  						=	None
            if self.use_labels:
                  lowerCAmelCase  						=	ids_tensor([self.batch_size]				,						self.num_labels			)

            lowerCAmelCase  						=	self.get_config()
            return config, pixel_values, labels





      def    _snake_case      (	self			)		->					List[Any]:
            return EfficientNetConfig(
                num_channels=self.num_channels				,						kernel_sizes=self.kernel_sizes				,						in_channels=self.in_channels				,						out_channels=self.out_channels				,						strides=self.strides				,						num_block_repeats=self.num_block_repeats				,						expand_ratios=self.expand_ratios				,						hidden_act=self.hidden_act				,						num_labels=self.num_labels				,						)





      def    _snake_case      (	self				,						lowercase				,						lowercase				,						lowercase			)		->					str:
            lowerCAmelCase  						=	EfficientNetModel(config=lowercase			)
            model.to(lowercase			)
            model.eval()
            lowerCAmelCase  						=	model(lowercase			)
            # expected last hidden states: B, C, H // 4, W // 4
            self.parent.assertEqual(
                result.last_hidden_state.shape				,						(self.batch_size, config.hidden_dim, self.image_size // 4, self.image_size // 4)				,						)





      def    _snake_case      (	self				,						lowercase				,						lowercase				,						lowercase			)		->					Optional[int]:
            lowerCAmelCase  						=	EfficientNetForImageClassification(lowercase			)
            model.to(lowercase			)
            model.eval()
            lowerCAmelCase  						=	model(lowercase				,						labels=lowercase			)
            self.parent.assertEqual(result.logits.shape				,						(self.batch_size, self.num_labels)			)





      def    _snake_case      (	self			)		->					Dict:
            lowerCAmelCase  						=	self.prepare_config_and_inputs()
            lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase  						=	config_and_inputs
            lowerCAmelCase  						=	{"""pixel_values""": pixel_values}
            return config, inputs_dict







@require_torch
class 		lowercase ( _UpperCAmelCase					,  _UpperCAmelCase					,  unittest.TestCase ):
      _SCREAMING_SNAKE_CASE         =				(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
      _SCREAMING_SNAKE_CASE         =				(
          {'feature-extraction': EfficientNetModel, 'image-classification': EfficientNetForImageClassification}
          if is_torch_available()
          else {}
      )

      _SCREAMING_SNAKE_CASE         =				False
      _SCREAMING_SNAKE_CASE         =				False
      _SCREAMING_SNAKE_CASE         =				False
      _SCREAMING_SNAKE_CASE         =				False
      _SCREAMING_SNAKE_CASE         =				False





      def    _snake_case      (	self			)		->					Any:
            lowerCAmelCase  						=	EfficientNetModelTester(self			)
            lowerCAmelCase  						=	ConfigTester(
                self				,						config_class=lowercase				,						has_text_modality=lowercase				,						hidden_size=37			)





      def    _snake_case      (	self			)		->					List[str]:
            self.create_and_test_config_common_properties()
            self.config_tester.create_and_test_config_to_json_string()
            self.config_tester.create_and_test_config_to_json_file()
            self.config_tester.create_and_test_config_from_and_save_pretrained()
            self.config_tester.create_and_test_config_with_num_labels()
            self.config_tester.check_config_can_be_init_without_params()
            self.config_tester.check_config_arguments_init()





      def    _snake_case      (	self			)		->					int:
            return





      @unittest.skip(reason="""EfficientNet does not use inputs_embeds"""			)
      def    _snake_case      (	self			)		->					List[str]:
            pass





      @unittest.skip(reason="""EfficientNet does not support input and output embeddings"""			)
      def    _snake_case      (	self			)		->					Optional[Any]:
            pass





      @unittest.skip(reason="""EfficientNet does not use feedforward chunking"""			)
      def    _snake_case      (	self			)		->					Tuple:
            pass





      def    _snake_case      (	self			)		->					Dict:
            lowerCAmelCase						,		lowerCAmelCase  						=	self.model_tester.prepare_config_and_inputs_for_common()

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

                  lowerCAmelCase  						=	["""pixel_values"""]
                  self.assertListEqual(arg_names[:1]				,						lowercase			)





      def    _snake_case      (	self			)		->					Optional[int]:
            lowerCAmelCase  						=	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*lowercase			)





      def    _snake_case      (	self			)		->					List[Any]:
            def check_hidden_states_output(lowercase				,						lowercase				,						lowercase			):
                  lowerCAmelCase  						=	model_class(lowercase			)
                  model.to(lowercase			)
                  model.eval()

                  with torch.no_grad():
                        lowerCAmelCase  						=	model(**self._prepare_for_class(lowercase				,						lowercase			)			)

                  lowerCAmelCase  						=	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
                  lowerCAmelCase  						=	sum(config.num_block_repeats			) * 4
                  self.assertEqual(len(lowercase			)				,						lowercase			)

                  # EfficientNet's feature maps are of shape (batch_size, num_channels, height, width)
                  self.assertListEqual(
                      list(hidden_states[0].shape[-2:]			)				,						[self.model_tester.image_size // 2, self.model_tester.image_size // 2]				,						)

            lowerCAmelCase						,		lowerCAmelCase  						=	self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  lowerCAmelCase  						=	True
                  check_hidden_states_output(lowercase				,						lowercase				,						lowercase			)

                  # check that output_hidden_states also work using config
                  del inputs_dict["output_hidden_states"]
                  lowerCAmelCase  						=	True

                  check_hidden_states_output(lowercase				,						lowercase				,						lowercase			)





      def    _snake_case      (	self			)		->					Optional[Any]:
            lowerCAmelCase  						=	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*lowercase			)





      @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""			)
      def    _snake_case      (	self			)		->					Optional[int]:
            pass





      @slow
      def    _snake_case      (	self			)		->					Union[str, Any]:
            for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  lowerCAmelCase  						=	EfficientNetModel.from_pretrained(lowercase			)
                  self.assertIsNotNone(lowercase			)





      @is_pipeline_test
      @require_vision
      @slow
      def    _snake_case      (	self			)		->					Dict:
            super().test_pipeline_image_classification()







def       UpperCAmelCase__							(  ):







      '''simple docstring'''




      lowerCAmelCase  						=	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
      return image






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





      @cached_property
      def    _snake_case      (	self			)		->					Tuple:
            return AutoImageProcessor.from_pretrained("""google/efficientnet-b7"""			) if is_vision_available() else None





      @slow
      def    _snake_case      (	self			)		->					Any:
            lowerCAmelCase  						=	EfficientNetForImageClassification.from_pretrained("""google/efficientnet-b7"""			).to(lowercase			)

            lowerCAmelCase  						=	self.default_image_processor
            lowerCAmelCase  						=	prepare_img()
            lowerCAmelCase  						=	image_processor(images=lowercase				,						return_tensors="""pt"""			).to(lowercase			)

            # forward pass
            with torch.no_grad():
                  lowerCAmelCase  						=	model(**lowercase			)

            # verify the logits
            lowerCAmelCase  						=	torch.Size((1, 1_000)			)
            self.assertEqual(outputs.logits.shape				,						lowercase			)

            lowerCAmelCase  						=	torch.tensor([0.0_001, 0.0_002, 0.0_002]			).to(lowercase			)
            self.assertTrue(torch.allclose(outputs.logits[0, :3]				,						lowercase				,						atol=1e-4			)			)













"""simple docstring"""





import sacrebleu as scb
from packaging import version

import datasets


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

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

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





      def    _snake_case      (	self			)		->					List[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"""				,						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    _snake_case      (	self				,						lowercase				,						lowercase				,						lowercase="exp"				,						lowercase=None				,						lowercase=False				,						lowercase=False				,						lowercase=None				,						lowercase=False				,						)		->					int:
            lowerCAmelCase  						=	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"""			)
            lowerCAmelCase  						=	[[refs[i] for refs in references] for i in range(lowercase			)]
            lowerCAmelCase  						=	scb.corpus_bleu(
                lowercase				,						lowercase				,						smooth_method=lowercase				,						smooth_value=lowercase				,						force=lowercase				,						lowercase=lowercase				,						use_effective_order=lowercase				,						**({"""tokenize""": tokenize} if tokenize else {})				,						)
            lowerCAmelCase  						=	{
                """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






