






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 		_snake_case	:






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






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Dict:
						SCREAMING_SNAKE_CASE							=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

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






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							str:
						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=a		,       initializer_range=self.initializer_range		,       out_features=self.out_features		,       out_indices=self.out_indices		,       num_labels=self.num_labels		,       )






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a		,       a)   ->							int:
						SCREAMING_SNAKE_CASE							=			ConvNextModel(config=a)
						model.to(a)
						model.eval()
						SCREAMING_SNAKE_CASE							=			model(a)
						# 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  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a		,       a)   ->							Any:
						SCREAMING_SNAKE_CASE							=			ConvNextForImageClassification(a)
						model.to(a)
						model.eval()
						SCREAMING_SNAKE_CASE							=			model(a		,       labels=a)
						self.parent.assertEqual(result.logits.shape		,       (self.batch_size, self.num_labels))






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a		,       a)   ->							Dict:
						SCREAMING_SNAKE_CASE							=			ConvNextBackbone(config=a)
						model.to(a)
						model.eval()
						SCREAMING_SNAKE_CASE							=			model(a)

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

						# 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  SCREAMING_SNAKE_CASE__     (							self)   ->							List[Any]:
						SCREAMING_SNAKE_CASE							=			self.prepare_config_and_inputs()
						SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE							=			config_and_inputs
						SCREAMING_SNAKE_CASE							=			{'pixel_values': pixel_values}
						return config, inputs_dict



@require_torch
class 		_snake_case	(	A__ ,     A__ ,     unittest.TestCase       ):
			_lowercase		:     List[str]        =				(
			    (
			        ConvNextModel,
			        ConvNextForImageClassification,
			        ConvNextBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			_lowercase		:     Optional[Any]        =				(
			    {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
			    if is_torch_available()
			    else {}
			)

			_lowercase		:     str        =				True
			_lowercase		:     List[Any]        =				False
			_lowercase		:     Dict        =				False
			_lowercase		:     Optional[Any]        =				False
			_lowercase		:     int        =				False






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Dict:
						SCREAMING_SNAKE_CASE							=			ConvNextModelTester(self)
						SCREAMING_SNAKE_CASE							=			ConfigTester(self		,       config_class=a		,       has_text_modality=a		,       hidden_size=37)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Union[str, Any]:
						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  SCREAMING_SNAKE_CASE__     (							self)   ->							Union[str, Any]:
						return






			@unittest.skip(reason='ConvNext does not use inputs_embeds')
			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Dict:
						pass






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






			@unittest.skip(reason='ConvNext does not use feedforward chunking')
			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Any:
						pass






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							List[Any]:
						SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE							=			self.model_tester.prepare_config_and_inputs_for_common()

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

									SCREAMING_SNAKE_CASE							=			['pixel_values']
									self.assertListEqual(arg_names[:1]		,       a)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Union[str, Any]:
						SCREAMING_SNAKE_CASE							=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*a)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Tuple:
						SCREAMING_SNAKE_CASE							=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_backbone(*a)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Dict:
						def check_hidden_states_output(a		,       a		,       a):
									SCREAMING_SNAKE_CASE							=			model_class(a)
									model.to(a)
									model.eval()

									with torch.no_grad():
												SCREAMING_SNAKE_CASE							=			model(**self._prepare_for_class(a		,       a))

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

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

						SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE							=			self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE							=			True
									check_hidden_states_output(a		,       a		,       a)

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

									check_hidden_states_output(a		,       a		,       a)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							List[str]:
						SCREAMING_SNAKE_CASE							=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*a)







			@slow
			def  SCREAMING_SNAKE_CASE__     (							self)   ->							List[Any]:
						for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									SCREAMING_SNAKE_CASE							=			ConvNextModel.from_pretrained(a)
									self.assertIsNotNone(a)






def 					lowerCamelCase__					():
			SCREAMING_SNAKE_CASE							=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
			return image

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






			@cached_property
			def  SCREAMING_SNAKE_CASE__     (							self)   ->							List[Any]:
						return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224') if is_vision_available() else None







			@slow
			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Tuple:
						SCREAMING_SNAKE_CASE							=			ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224').to(a)

						SCREAMING_SNAKE_CASE							=			self.default_image_processor
						SCREAMING_SNAKE_CASE							=			prepare_img()
						SCREAMING_SNAKE_CASE							=			image_processor(images=a		,       return_tensors='pt').to(a)

						# forward pass
						with torch.no_grad():
									SCREAMING_SNAKE_CASE							=			model(**a)

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

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

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



@require_torch
class 		_snake_case	(	unittest.TestCase ,     A__       ):
			_lowercase		:     Tuple        =				(ConvNextBackbone,) if is_torch_available() else ()
			_lowercase		:     Tuple        =				ConvNextConfig

			_lowercase		:     int        =				False






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							int:
						SCREAMING_SNAKE_CASE							=			ConvNextModelTester(self)









import unittest

from transformers import is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
   from PIL import Image
else:


   class 	lowerCamelCase__	:



    """simple docstring"""

    @staticmethod
    def     snake_case_      (    *__lowerCAmelCase					:					Optional[Any]			,						**__lowerCAmelCase					:					Any      )   ->	Any:
       pass


@is_pipeline_test
@require_vision
class 	lowerCamelCase__	(       unittest.TestCase):



 """simple docstring"""

 @require_torch
 def     snake_case_      (    self					:					Tuple      )   ->	Tuple:
    _A      =       pipeline(
        model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification'''			,						)
    _A      =       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
    _A      =       image_classifier(__lowerCAmelCase			,						candidate_labels=['''a''', '''b''', '''c''']      )

    # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
    # python and torch versions.
    self.assertIn(
        nested_simplify(__lowerCAmelCase      )			,						[
            [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}],
            [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''c'''}, {'''score''': 0.333, '''label''': '''b'''}],
        ]			,						)

    _A      =       image_classifier([image] * 5			,						candidate_labels=['''A''', '''B''', '''C''']			,						batch_size=2      )
    self.assertEqual(
        nested_simplify(__lowerCAmelCase      )			,						[
            [
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
            ],
            [
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
            ],
            [
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
            ],
            [
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
            ],
            [
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
            ],
        ]			,						)

 @require_tf
 def     snake_case_      (    self					:					int      )   ->	Optional[int]:
    _A      =       pipeline(
        model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification'''			,						framework='''tf'''      )
    _A      =       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
    _A      =       image_classifier(__lowerCAmelCase			,						candidate_labels=['''a''', '''b''', '''c''']      )

    self.assertEqual(
        nested_simplify(__lowerCAmelCase      )			,						[{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}]			,						)

    _A      =       image_classifier([image] * 5			,						candidate_labels=['''A''', '''B''', '''C''']			,						batch_size=2      )
    self.assertEqual(
        nested_simplify(__lowerCAmelCase      )			,						[
            [
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
            ],
            [
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
            ],
            [
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
            ],
            [
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
            ],
            [
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
                {'''score''': 0.333, '''label''': ANY(__lowerCAmelCase      )},
            ],
        ]			,						)

 @slow
 @require_torch
 def     snake_case_      (    self					:					Optional[int]      )   ->	int:
    _A      =       pipeline(
        task='''zero-shot-image-classification'''			,						model='''openai/clip-vit-base-patch32'''			,						)
    # This is an image of 2 cats with remotes and no planes
    _A      =       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
    _A      =       image_classifier(__lowerCAmelCase			,						candidate_labels=['''cat''', '''plane''', '''remote''']      )

    self.assertEqual(
        nested_simplify(__lowerCAmelCase      )			,						[
            {'''score''': 0.511, '''label''': '''remote'''},
            {'''score''': 0.485, '''label''': '''cat'''},
            {'''score''': 0.004, '''label''': '''plane'''},
        ]			,						)

    _A      =       image_classifier([image] * 5			,						candidate_labels=['''cat''', '''plane''', '''remote''']			,						batch_size=2      )
    self.assertEqual(
        nested_simplify(__lowerCAmelCase      )			,						[
            [
                {'''score''': 0.511, '''label''': '''remote'''},
                {'''score''': 0.485, '''label''': '''cat'''},
                {'''score''': 0.004, '''label''': '''plane'''},
            ],
        ]
        * 5			,						)

 @slow
 @require_tf
 def     snake_case_      (    self					:					Optional[int]      )   ->	Dict:
    _A      =       pipeline(
        task='''zero-shot-image-classification'''			,						model='''openai/clip-vit-base-patch32'''			,						framework='''tf'''      )
    # This is an image of 2 cats with remotes and no planes
    _A      =       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
    _A      =       image_classifier(__lowerCAmelCase			,						candidate_labels=['''cat''', '''plane''', '''remote''']      )
    self.assertEqual(
        nested_simplify(__lowerCAmelCase      )			,						[
            {'''score''': 0.511, '''label''': '''remote'''},
            {'''score''': 0.485, '''label''': '''cat'''},
            {'''score''': 0.004, '''label''': '''plane'''},
        ]			,						)

    _A      =       image_classifier([image] * 5			,						candidate_labels=['''cat''', '''plane''', '''remote''']			,						batch_size=2      )
    self.assertEqual(
        nested_simplify(__lowerCAmelCase      )			,						[
            [
                {'''score''': 0.511, '''label''': '''remote'''},
                {'''score''': 0.485, '''label''': '''cat'''},
                {'''score''': 0.004, '''label''': '''plane'''},
            ],
        ]
        * 5			,						)



