





'''simple docstring'''






import inspect
import unittest

from transformers import ConvNextConfig
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_backbone_common import BackboneTesterMixin
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 ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
      from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor




class  UpperCAmelCase     :




      def __init__(			self			: str			,			__snake_case			: int			,			__snake_case			: Optional[Any]=13			,			__snake_case			: List[Any]=32			,			__snake_case			: int=3			,			__snake_case			: str=4			,			__snake_case			: Optional[int]=[10, 20, 30, 40]			,			__snake_case			: Optional[Any]=[2, 2, 3, 2]			,			__snake_case			: Optional[int]=True			,			__snake_case			: Optional[int]=True			,			__snake_case			: Optional[int]=37			,			__snake_case			: int="gelu"			,			__snake_case			: str=10			,			__snake_case			: Union[str, Any]=0.02			,			__snake_case			: List[Any]=["stage2", "stage3", "stage4"]			,			__snake_case			: Any=[2, 3, 4]			,			__snake_case			: Optional[Any]=None			,			)				->      int:
            _lowerCAmelCase							     =							parent
            _lowerCAmelCase							     =							batch_size
            _lowerCAmelCase							     =							image_size
            _lowerCAmelCase							     =							num_channels
            _lowerCAmelCase							     =							num_stages
            _lowerCAmelCase							     =							hidden_sizes
            _lowerCAmelCase							     =							depths
            _lowerCAmelCase							     =							is_training
            _lowerCAmelCase							     =							use_labels
            _lowerCAmelCase							     =							intermediate_size
            _lowerCAmelCase							     =							hidden_act
            _lowerCAmelCase							     =							num_labels
            _lowerCAmelCase							     =							initializer_range
            _lowerCAmelCase							     =							out_features
            _lowerCAmelCase							     =							out_indices
            _lowerCAmelCase							     =							scope




      def 				lowercase__    (			self			: str  )				->      Any:
            _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 				lowercase__    (			self			: List[str]  )				->      Union[str, Any]:
            return ConvNextConfig(
                num_channels=self.num_channels			,			hidden_sizes=self.hidden_sizes			,			depths=self.depths			,			num_stages=self.num_stages			,			hidden_act=self.hidden_act			,			is_decoder=_snake_case			,			initializer_range=self.initializer_range			,			out_features=self.out_features			,			out_indices=self.out_indices			,			num_labels=self.num_labels			,			)




      def 				lowercase__    (			self			: Dict			,			__snake_case			: List[Any]			,			__snake_case			: List[str]			,			__snake_case			: Optional[int]  )				->      List[str]:
            _lowerCAmelCase							     =							ConvNextModel(config=_snake_case  )
            model.to(_snake_case  )
            model.eval()
            _lowerCAmelCase							     =							model(_snake_case  )
            # expected last hidden states: B, C, H // 32, W // 32
            self.parent.assertEqual(
                result.last_hidden_state.shape			,			(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)			,			)




      def 				lowercase__    (			self			: int			,			__snake_case			: int			,			__snake_case			: Optional[int]			,			__snake_case			: Tuple  )				->      List[str]:
            _lowerCAmelCase							     =							ConvNextForImageClassification(_snake_case  )
            model.to(_snake_case  )
            model.eval()
            _lowerCAmelCase							     =							model(_snake_case			,			labels=_snake_case  )
            self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels)  )




      def 				lowercase__    (			self			: Union[str, Any]			,			__snake_case			: List[str]			,			__snake_case			: Optional[Any]			,			__snake_case			: Any  )				->      Union[str, Any]:
            _lowerCAmelCase							     =							ConvNextBackbone(config=_snake_case  )
            model.to(_snake_case  )
            model.eval()
            _lowerCAmelCase							     =							model(_snake_case  )

            # verify hidden states
            self.parent.assertEqual(len(result.feature_maps  )			,			len(config.out_features  )  )
            self.parent.assertListEqual(list(result.feature_maps[0].shape  )			,			[self.batch_size, self.hidden_sizes[1], 4, 4]  )

            # verify channels
            self.parent.assertEqual(len(model.channels  )			,			len(config.out_features  )  )
            self.parent.assertListEqual(model.channels			,			config.hidden_sizes[1:]  )

            # verify backbone works with out_features=None
            _lowerCAmelCase							     =							None
            _lowerCAmelCase							     =							ConvNextBackbone(config=_snake_case  )
            model.to(_snake_case  )
            model.eval()
            _lowerCAmelCase							     =							model(_snake_case  )

            # verify feature maps
            self.parent.assertEqual(len(result.feature_maps  )			,			1  )
            self.parent.assertListEqual(list(result.feature_maps[0].shape  )			,			[self.batch_size, self.hidden_sizes[-1], 1, 1]  )

            # verify channels
            self.parent.assertEqual(len(model.channels  )			,			1  )
            self.parent.assertListEqual(model.channels			,			[config.hidden_sizes[-1]]  )




      def 				lowercase__    (			self			: int  )				->      Any:
            _lowerCAmelCase							     =							self.prepare_config_and_inputs()
            _lowerCAmelCase							     =							config_and_inputs
            _lowerCAmelCase							     =							{'''pixel_values''': pixel_values}
            return config, inputs_dict




@require_torch
class  UpperCAmelCase     (			A_							,		A_							,		unittest.TestCase   ):
      _lowercase:			Optional[Any]						     =   (
          (
              ConvNextModel,
              ConvNextForImageClassification,
              ConvNextBackbone,
          )
          if is_torch_available()
          else ()
      )
      _lowercase:			Union[str, Any]						     =   (
          {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
          if is_torch_available()
          else {}
      )

      _lowercase:			Optional[Any]						     =   True
      _lowercase:			Optional[Any]						     =   False
      _lowercase:			Optional[Any]						     =   False
      _lowercase:			Optional[Any]						     =   False
      _lowercase:			Dict						     =   False




      def 				lowercase__    (			self			: int  )				->      Any:
            _lowerCAmelCase							     =							ConvNextModelTester(self  )
            _lowerCAmelCase							     =							ConfigTester(self			,			config_class=_snake_case			,			has_text_modality=_snake_case			,			hidden_size=37  )




      def 				lowercase__    (			self			: List[Any]  )				->      Optional[int]:
            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 				lowercase__    (			self			: List[Any]  )				->      int:
            return




      @unittest.skip(reason="""ConvNext does not use inputs_embeds"""  )
      def 				lowercase__    (			self			: Union[str, Any]  )				->      List[Any]:
            pass




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




      @unittest.skip(reason="""ConvNext does not use feedforward chunking"""  )
      def 				lowercase__    (			self			: Union[str, Any]  )				->      List[str]:
            pass




      def 				lowercase__    (			self			: Union[str, Any]  )				->      List[Any]:
            _lowerCAmelCase							     =							self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  _lowerCAmelCase							     =							model_class(_snake_case  )
                  _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]			,			_snake_case  )




      def 				lowercase__    (			self			: str  )				->      Tuple:
            _lowerCAmelCase							     =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*_snake_case  )




      def 				lowercase__    (			self			: Union[str, Any]  )				->      List[str]:
            _lowerCAmelCase							     =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_backbone(*_snake_case  )




      def 				lowercase__    (			self			: Union[str, Any]  )				->      int:



            def check_hidden_states_output(__snake_case			: Union[str, Any]			,			__snake_case			: List[str]			,			__snake_case			: Union[str, Any]  ):
                  _lowerCAmelCase							     =							model_class(_snake_case  )
                  model.to(_snake_case  )
                  model.eval()

                  with torch.no_grad():
                        _lowerCAmelCase							     =							model(**self._prepare_for_class(_snake_case			,			_snake_case  )  )

                  _lowerCAmelCase							     =							outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                  _lowerCAmelCase							     =							self.model_tester.num_stages
                  self.assertEqual(len(_snake_case  )			,			expected_num_stages + 1  )

                  # ConvNext'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 // 4, self.model_tester.image_size // 4]			,			)

            _lowerCAmelCase							     =							self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  _lowerCAmelCase							     =							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"]
                  _lowerCAmelCase							     =							True

                  check_hidden_states_output(_snake_case			,			_snake_case			,			_snake_case  )




      def 				lowercase__    (			self			: int  )				->      List[Any]:
            _lowerCAmelCase							     =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*_snake_case  )




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



            for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  _lowerCAmelCase							     =							ConvNextModel.from_pretrained(_snake_case  )
                  self.assertIsNotNone(_snake_case  )




def    UpperCamelCase__      (		):





      """simple docstring"""


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




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




      @cached_property
      def 				lowercase__    (			self			: int  )				->      Optional[int]:
            return AutoImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""  ) if is_vision_available() else None




      @slow
      def 				lowercase__    (			self			: Dict  )				->      Dict:
            _lowerCAmelCase							     =							ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""  ).to(_snake_case  )

            _lowerCAmelCase							     =							self.default_image_processor
            _lowerCAmelCase							     =							prepare_img()
            _lowerCAmelCase							     =							image_processor(images=_snake_case			,			return_tensors="""pt"""  ).to(_snake_case  )

            # forward pass
            with torch.no_grad():
                  _lowerCAmelCase							     =							model(**_snake_case  )

            # verify the logits
            _lowerCAmelCase							     =							torch.Size((1, 10_00)  )
            self.assertEqual(outputs.logits.shape			,			_snake_case  )

            _lowerCAmelCase							     =							torch.tensor([-0.02_60, -0.47_39, 0.19_11]  ).to(_snake_case  )

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




@require_torch
class  UpperCAmelCase     (			unittest.TestCase							,		A_   ):
      _lowercase:			str						     =   (ConvNextBackbone,) if is_torch_available() else ()
      _lowercase:			int						     =   ConvNextConfig

      _lowercase:			List[str]						     =   False




      def 				lowercase__    (			self			: Dict  )				->      List[str]:
            _lowerCAmelCase							     =							ConvNextModelTester(self  )











"""simple docstring"""







import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


lowerCAmelCase_   						=   version.parse(importlib_metadata.version('nltk'))
if NLTK_VERSION >= version.Version('3.6.4'):
							from nltk import word_tokenize


lowerCAmelCase_   						=   '\\n@inproceedings{banarjee2005,\n  title     = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n  author    = {Banerjee, Satanjeev  and Lavie, Alon},\n  booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n  month     = jun,\n  year      = {2005},\n  address   = {Ann Arbor, Michigan},\n  publisher = {Association for Computational Linguistics},\n  url       = {https://www.aclweb.org/anthology/W05-0909},\n  pages     = {65--72},\n}\n'

lowerCAmelCase_   						=   '\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n'

lowerCAmelCase_   						=   '\nComputes METEOR score of translated segments against one or more references.\nArgs:\n    predictions: list of predictions to score. Each prediction\n        should be a string with tokens separated by spaces.\n    references: list of reference for each prediction. Each\n        reference should be a string with tokens separated by spaces.\n    alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n    beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n    gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n    \'meteor\': meteor score.\nExamples:\n\n    >>> meteor = datasets.load_metric(\'meteor\')\n    >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"]\n    >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"]\n    >>> results = meteor.compute(predictions=predictions, references=references)\n    >>> print(round(results["meteor"], 4))\n    0.6944\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,_KWARGS_DESCRIPTION    )
class        __A       (	datasets.Metric    ):







		'''simple docstring'''





		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		str:






				"""simple docstring"""



				return datasets.MetricInfo(
				    description=_DESCRIPTION			,citation=_CITATION			,inputs_description=_KWARGS_DESCRIPTION			,features=datasets.Features(
				        {
				            '''predictions''': datasets.Value('''string'''			,id='''sequence'''						),
				            '''references''': datasets.Value('''string'''			,id='''sequence'''						),
				        }						)			,codebase_urls=['''https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py''']			,reference_urls=[
				        '''https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score''',
				        '''https://en.wikipedia.org/wiki/METEOR''',
				    ]			,)







		def 					UpperCAmelCase    (	self						:  str			,_snake_case						:  Dict						)					->		Dict:






				"""simple docstring"""



				import nltk

				nltk.download('''wordnet'''						)
				if NLTK_VERSION >= version.Version('''3.6.5'''						):
						nltk.download('''punkt'''						)
				if NLTK_VERSION >= version.Version('''3.6.6'''						):
						nltk.download('''omw-1.4'''						)







		def 					UpperCAmelCase    (	self						:  Dict			,_snake_case						:  Dict			,_snake_case						:  List[str]			,_snake_case						:  Tuple=0.9			,_snake_case						:  Optional[int]=3			,_snake_case						:  Union[str, Any]=0.5						)					->		List[str]:






				"""simple docstring"""



				if NLTK_VERSION >= version.Version('''3.6.5'''						):
						lowercase__   :    int				=			[
						    meteor_score.single_meteor_score(
						        word_tokenize(_snake_case						)			,word_tokenize(_snake_case						)			,alpha=_snake_case			,beta=_snake_case			,gamma=_snake_case						)
						    for ref, pred in zip(_snake_case			,_snake_case						)
						]
				else:
						lowercase__   :    Tuple				=			[
						    meteor_score.single_meteor_score(_snake_case			,_snake_case			,alpha=_snake_case			,beta=_snake_case			,gamma=_snake_case						)
						    for ref, pred in zip(_snake_case			,_snake_case						)
						]

				return {"meteor": np.mean(_snake_case						)}
