

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					,					lowercase					,					lowercase=13					,					lowercase=32					,					lowercase=3					,					lowercase=4					,					lowercase=[10, 20, 30, 40]					,					lowercase=[2, 2, 3, 2]					,					lowercase=True					,					lowercase=True					,					lowercase=37					,					lowercase="gelu"					,					lowercase=10					,					lowercase=0.02					,					lowercase=["stage2", "stage3", "stage4"]					,					lowercase=[2, 3, 4]					,					lowercase=None					,					)     ->  List[str]:
							'''simple docstring'''






							A__						=	parent
							A__						=	batch_size
							A__						=	image_size
							A__						=	num_channels
							A__						=	num_stages
							A__						=	hidden_sizes
							A__						=	depths
							A__						=	is_training
							A__						=	use_labels
							A__						=	intermediate_size
							A__						=	hidden_act
							A__						=	num_labels
							A__						=	initializer_range
							A__						=	out_features
							A__						=	out_indices
							A__						=	scope


			def    UpperCamelCase						(			self				)     ->  Dict:
							'''simple docstring'''






							A__						=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

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


			def    UpperCamelCase						(			self				)     ->  List[str]:
							'''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=lowercase					,					initializer_range=self.initializer_range					,					out_features=self.out_features					,					out_indices=self.out_indices					,					num_labels=self.num_labels					,					)


			def    UpperCamelCase						(			self					,					lowercase					,					lowercase					,					lowercase				)     ->  Union[str, Any]:
							'''simple docstring'''






							A__						=	ConvNextModel(config=lowercase				)
							model.to(lowercase				)
							model.eval()
							A__						=	model(lowercase				)
							# 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					,					lowercase					,					lowercase					,					lowercase				)     ->  Optional[int]:
							'''simple docstring'''






							A__						=	ConvNextForImageClassification(lowercase				)
							model.to(lowercase				)
							model.eval()
							A__						=	model(lowercase					,					labels=lowercase				)
							self.parent.assertEqual(result.logits.shape					,					(self.batch_size, self.num_labels)				)


			def    UpperCamelCase						(			self					,					lowercase					,					lowercase					,					lowercase				)     ->  Dict:
							'''simple docstring'''






							A__						=	ConvNextBackbone(config=lowercase				)
							model.to(lowercase				)
							model.eval()
							A__						=	model(lowercase				)

							# 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
							A__						=	None
							A__						=	ConvNextBackbone(config=lowercase				)
							model.to(lowercase				)
							model.eval()
							A__						=	model(lowercase				)

							# 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:
							'''simple docstring'''






							A__						=	self.prepare_config_and_inputs()
							A__			, A__			, A__						=	config_and_inputs
							A__						=	{"pixel_values": pixel_values}
							return config, inputs_dict

@require_torch
class     a__  (    snake_case							,		snake_case							,		unittest.TestCase	):
			"""simple docstring"""







			__lowerCamelCase       				=				(
			    (
			        ConvNextModel,
			        ConvNextForImageClassification,
			        ConvNextBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			__lowerCamelCase       				=				(
			    {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification}
			    if is_torch_available()
			    else {}
			)

			__lowerCamelCase       				=				True
			__lowerCamelCase       				=				False
			__lowerCamelCase       				=				False
			__lowerCamelCase       				=				False
			__lowerCamelCase       				=				False


			def    UpperCamelCase						(			self				)     ->  Union[str, Any]:
							'''simple docstring'''






							A__						=	ConvNextModelTester(self				)
							A__						=	ConfigTester(self					,					config_class=lowercase					,					has_text_modality=lowercase					,					hidden_size=37				)


			def    UpperCamelCase						(			self				)     ->  Any:
							'''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]:
							'''simple docstring'''






							return


			@unittest.skip(reason="ConvNext does not use inputs_embeds"				)
			def    UpperCamelCase						(			self				)     ->  str:
							'''simple docstring'''






							pass


			@unittest.skip(reason="ConvNext does not support input and output embeddings"				)
			def    UpperCamelCase						(			self				)     ->  List[str]:
							'''simple docstring'''






							pass


			@unittest.skip(reason="ConvNext does not use feedforward chunking"				)
			def    UpperCamelCase						(			self				)     ->  str:
							'''simple docstring'''






							pass


			def    UpperCamelCase						(			self				)     ->  Optional[Any]:
							'''simple docstring'''






							A__			, A__						=	self.model_tester.prepare_config_and_inputs_for_common()

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

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


			def    UpperCamelCase						(			self				)     ->  Union[str, Any]:
							'''simple docstring'''






							A__						=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowercase				)


			def    UpperCamelCase						(			self				)     ->  Tuple:
							'''simple docstring'''






							A__						=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_backbone(*lowercase				)


			def    UpperCamelCase						(			self				)     ->  List[str]:
							'''simple docstring'''






							def check_hidden_states_output(lowercase					,					lowercase					,					lowercase				):
											A__						=	model_class(lowercase				)
											model.to(lowercase				)
											model.eval()

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

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

											A__						=	self.model_tester.num_stages
											self.assertEqual(len(lowercase				)					,					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]					,					)

							A__			, A__						=	self.model_tester.prepare_config_and_inputs_for_common()

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

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

											check_hidden_states_output(lowercase					,					lowercase					,					lowercase				)


			def    UpperCamelCase						(			self				)     ->  int:
							'''simple docstring'''






							A__						=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowercase				)


			@slow
			def    UpperCamelCase						(			self				)     ->  Tuple:
							'''simple docstring'''






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



def     lowerCAmelCase__							(		)	->					Union[str, Any]:




				'''simple docstring'''





				A__						=	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				)     ->  Optional[Any]:
							'''simple docstring'''






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


			@slow
			def    UpperCamelCase						(			self				)     ->  Tuple:
							'''simple docstring'''






							A__						=	ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"				).to(lowercase				)

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

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

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

							A__						=	torch.tensor([-0.0260, -0.4739, 0.1911]				).to(lowercase				)

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

@require_torch
class     a__  (    unittest.TestCase							,		snake_case	):
			"""simple docstring"""







			__lowerCamelCase       				=				(ConvNextBackbone,) if is_torch_available() else ()
			__lowerCamelCase       				=				ConvNextConfig

			__lowerCamelCase       				=				False


			def    UpperCamelCase						(			self				)     ->  List[Any]:
							'''simple docstring'''






							A__						=	ConvNextModelTester(self				)







"""simple docstring"""




import json
import os
import shutil
import tempfile
import unittest

import numpy as np

from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer
from transformers.testing_utils import require_tokenizers, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
					from PIL import Image

					from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor






@require_tokenizers
@require_vision
class     __magic_name__							(       unittest.TestCase				):






				'''simple docstring'''





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					tempfile.mkdtemp()

							# fmt: off
							lowerCamelCase			      =					["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest"""]
							# fmt: on
							lowerCamelCase			      =					os.path.join(self.tmpdirname		, VOCAB_FILES_NAMES["""vocab_file"""] )
							with open(self.vocab_file		, """w"""		, encoding="""utf-8""" ) as vocab_writer:
										vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) )

							lowerCamelCase			      =					{
							    """do_resize""": True,
							    """size""": {"""height""": 18, """width""": 18},
							    """do_normalize""": True,
							    """image_mean""": [0.5, 0.5, 0.5],
							    """image_std""": [0.5, 0.5, 0.5],
							}
							lowerCamelCase			      =					os.path.join(self.tmpdirname		, _a )
							with open(self.image_processor_file		, """w"""		, encoding="""utf-8""" ) as fp:
										json.dump(_a		, _a )





				def    _lowerCAmelCase				(       self		, **_a ):





							"""simple docstring"""
							return BertTokenizer.from_pretrained(self.tmpdirname		, **_a )





				def    _lowerCAmelCase				(       self		, **_a ):





							"""simple docstring"""
							return ViTImageProcessor.from_pretrained(self.tmpdirname		, **_a )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							shutil.rmtree(self.tmpdirname )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					[np.random.randint(255		, size=(3, 30, 400)		, dtype=np.uinta )]

							lowerCamelCase			      =					[Image.fromarray(np.moveaxis(_a		, 0		, -1 ) ) for x in image_inputs]

							return image_inputs





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					self.get_tokenizer()
							lowerCamelCase			      =					self.get_image_processor()

							lowerCamelCase			      =					VisionTextDualEncoderProcessor(tokenizer=_a		, image_processor=_a )

							processor.save_pretrained(self.tmpdirname )
							lowerCamelCase			      =					VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname )

							self.assertEqual(processor.tokenizer.get_vocab()		, tokenizer.get_vocab() )
							self.assertIsInstance(processor.tokenizer		, (BertTokenizer, BertTokenizerFast) )

							self.assertEqual(processor.image_processor.to_json_string()		, image_processor.to_json_string() )
							self.assertIsInstance(processor.image_processor		, _a )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					VisionTextDualEncoderProcessor(
							    tokenizer=self.get_tokenizer()		, image_processor=self.get_image_processor() )
							processor.save_pretrained(self.tmpdirname )

							lowerCamelCase			      =					self.get_tokenizer(bos_token="""(BOS)"""		, eos_token="""(EOS)""" )
							lowerCamelCase			      =					self.get_image_processor(do_normalize=_a		, padding_value=1.0 )

							lowerCamelCase			      =					VisionTextDualEncoderProcessor.from_pretrained(
							    self.tmpdirname		, bos_token="""(BOS)"""		, eos_token="""(EOS)"""		, do_normalize=_a		, padding_value=1.0 )

							self.assertEqual(processor.tokenizer.get_vocab()		, tokenizer_add_kwargs.get_vocab() )
							self.assertIsInstance(processor.tokenizer		, (BertTokenizer, BertTokenizerFast) )

							self.assertEqual(processor.image_processor.to_json_string()		, image_processor_add_kwargs.to_json_string() )
							self.assertIsInstance(processor.image_processor		, _a )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					self.get_image_processor()
							lowerCamelCase			      =					self.get_tokenizer()

							lowerCamelCase			      =					VisionTextDualEncoderProcessor(tokenizer=_a		, image_processor=_a )

							lowerCamelCase			      =					self.prepare_image_inputs()

							lowerCamelCase			      =					image_processor(_a		, return_tensors="""np""" )
							lowerCamelCase			      =					processor(images=_a		, return_tensors="""np""" )

							for key in input_feat_extract.keys():
										self.assertAlmostEqual(input_feat_extract[key].sum()		, input_processor[key].sum()		, delta=1e-2 )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					self.get_image_processor()
							lowerCamelCase			      =					self.get_tokenizer()

							lowerCamelCase			      =					VisionTextDualEncoderProcessor(tokenizer=_a		, image_processor=_a )

							lowerCamelCase			      =					"""lower newer"""

							lowerCamelCase			      =					processor(text=_a )

							lowerCamelCase			      =					tokenizer(_a )

							for key in encoded_tok.keys():
										self.assertListEqual(encoded_tok[key]		, encoded_processor[key] )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					self.get_image_processor()
							lowerCamelCase			      =					self.get_tokenizer()

							lowerCamelCase			      =					VisionTextDualEncoderProcessor(tokenizer=_a		, image_processor=_a )

							lowerCamelCase			      =					"""lower newer"""
							lowerCamelCase			      =					self.prepare_image_inputs()

							lowerCamelCase			      =					processor(text=_a		, images=_a )

							self.assertListEqual(list(inputs.keys() )		, ["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""] )

							# test if it raises when no input is passed
							with self.assertRaises(_a ):
										processor()





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					self.get_image_processor()
							lowerCamelCase			      =					self.get_tokenizer()

							lowerCamelCase			      =					VisionTextDualEncoderProcessor(tokenizer=_a		, image_processor=_a )

							lowerCamelCase			      =					[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

							lowerCamelCase			      =					processor.batch_decode(_a )
							lowerCamelCase			      =					tokenizer.batch_decode(_a )

							self.assertListEqual(_a		, _a )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					self.get_image_processor()
							lowerCamelCase			      =					self.get_tokenizer()

							lowerCamelCase			      =					VisionTextDualEncoderProcessor(tokenizer=_a		, image_processor=_a )

							lowerCamelCase			      =					"""lower newer"""
							lowerCamelCase			      =					self.prepare_image_inputs()

							lowerCamelCase			      =					processor(text=_a		, images=_a )

							self.assertListEqual(list(inputs.keys() )		, processor.model_input_names )



