



"""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        __A       :







		'''simple docstring'''





		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:






				"""simple docstring"""



				lowercase__   :    List[str]				=			parent
				lowercase__   :    str				=			batch_size
				lowercase__   :    List[Any]				=			image_size
				lowercase__   :    Dict				=			num_channels
				lowercase__   :    Union[str, Any]				=			num_stages
				lowercase__   :    Optional[Any]				=			hidden_sizes
				lowercase__   :    Union[str, Any]				=			depths
				lowercase__   :    List[str]				=			is_training
				lowercase__   :    Dict				=			use_labels
				lowercase__   :    Any				=			intermediate_size
				lowercase__   :    List[Any]				=			hidden_act
				lowercase__   :    Any				=			num_labels
				lowercase__   :    Optional[int]				=			initializer_range
				lowercase__   :    str				=			out_features
				lowercase__   :    Union[str, Any]				=			out_indices
				lowercase__   :    int				=			scope







		def 					UpperCAmelCase    (	self						:  str						)					->		Any:






				"""simple docstring"""



				lowercase__   :    Union[str, Any]				=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

				lowercase__   :    Any				=			None
				if self.use_labels:
						lowercase__   :    str				=			ids_tensor([self.batch_size]			,self.num_labels						)

				lowercase__   :    Tuple				=			self.get_config()
				return config, pixel_values, labels







		def 					UpperCAmelCase    (	self						:  List[str]						)					->		Union[str, Any]:






				"""simple docstring"""



				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 					UpperCAmelCase    (	self						:  Dict			,_snake_case						:  List[Any]			,_snake_case						:  List[str]			,_snake_case						:  Optional[int]						)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    Union[str, Any]				=			ConvNextModel(config=_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    Union[str, Any]				=			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 					UpperCAmelCase    (	self						:  int			,_snake_case						:  int			,_snake_case						:  Optional[int]			,_snake_case						:  Tuple						)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    Dict				=			ConvNextForImageClassification(_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    str				=			model(_snake_case			,labels=_snake_case						)
				self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.num_labels)						)







		def 					UpperCAmelCase    (	self						:  Union[str, Any]			,_snake_case						:  List[str]			,_snake_case						:  Optional[Any]			,_snake_case						:  Any						)					->		Union[str, Any]:






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			ConvNextBackbone(config=_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    int				=			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
				lowercase__   :    List[str]				=			None
				lowercase__   :    List[Any]				=			ConvNextBackbone(config=_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    Tuple				=			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 					UpperCAmelCase    (	self						:  int						)					->		Any:






				"""simple docstring"""



				lowercase__   :    str				=			self.prepare_config_and_inputs()
				lowercase__		,			lowercase__		,			lowercase__   :    str				=			config_and_inputs
				lowercase__   :    int				=			{'''pixel_values''': pixel_values}
				return config, inputs_dict





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







		'''simple docstring'''





		lowerCAmelCase			:					Optional[Any]   	=				(
		    (
		        ConvNextModel,
		        ConvNextForImageClassification,
		        ConvNextBackbone,
		    )
		    if is_torch_available()
		    else ()
		)
		lowerCAmelCase			:					Union[str, Any]   	=				(
		    {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
		    if is_torch_available()
		    else {}
		)

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







		def 					UpperCAmelCase    (	self						:  int						)					->		Any:






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			ConvNextModelTester(self						)
				lowercase__   :    Any				=			ConfigTester(self			,config_class=_snake_case			,has_text_modality=_snake_case			,hidden_size=37						)







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






				"""simple docstring"""



				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 					UpperCAmelCase    (	self						:  List[Any]						)					->		int:






				"""simple docstring"""



				return







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






				"""simple docstring"""



				pass







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






				"""simple docstring"""



				pass







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






				"""simple docstring"""



				pass







		def 					UpperCAmelCase    (	self						:  Union[str, Any]						)					->		List[Any]:






				"""simple docstring"""



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

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

						lowercase__   :    str				=			['''pixel_values''']
						self.assertListEqual(arg_names[:1]			,_snake_case						)







		def 					UpperCAmelCase    (	self						:  str						)					->		Tuple:






				"""simple docstring"""



				lowercase__   :    List[str]				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*_snake_case						)







		def 					UpperCAmelCase    (	self						:  Union[str, Any]						)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    str				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_backbone(*_snake_case						)







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






				"""simple docstring"""



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

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

						lowercase__   :    Any				=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

						lowercase__   :    int				=			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]			,)

				lowercase__		,			lowercase__   :    List[str]				=			self.model_tester.prepare_config_and_inputs_for_common()

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

						check_hidden_states_output(_snake_case			,_snake_case			,_snake_case						)







		def 					UpperCAmelCase    (	self						:  int						)					->		List[Any]:






				"""simple docstring"""



				lowercase__   :    List[str]				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*_snake_case						)







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






				"""simple docstring"""



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





def      __UpperCAmelCase      (    )							->      Optional[int]:
		lowercase__   :    Optional[int]				=			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
		return image
@require_torch
@require_vision
class        __A       (	unittest.TestCase    ):







		'''simple docstring'''





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






				"""simple docstring"""



				return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''						) if is_vision_available() else None







		@slow
		def 					UpperCAmelCase    (	self						:  Dict						)					->		Dict:






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''						).to(_snake_case						)

				lowercase__   :    Optional[Any]				=			self.default_image_processor
				lowercase__   :    Dict				=			prepare_img()
				lowercase__   :    List[str]				=			image_processor(images=_snake_case			,return_tensors='''pt'''						).to(_snake_case						)

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

				# verify the logits
				lowercase__   :    List[Any]				=			torch.Size((1, 1_000)						)
				self.assertEqual(outputs.logits.shape			,_snake_case						)

				lowercase__   :    int				=			torch.tensor([-0.0260, -0.4739, 0.1911]						).to(_snake_case						)

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





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







		'''simple docstring'''





		lowerCAmelCase			:					str   	=				(ConvNextBackbone,) if is_torch_available() else ()
		lowerCAmelCase			:					int   	=				ConvNextConfig

		lowerCAmelCase			:					List[str]   	=				False







		def 					UpperCAmelCase    (	self						:  Dict						)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    int				=			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						)}
