
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					:





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





			def        _snake_case    (self				):
						lowerCamelCase__ :      Any								=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

						lowerCamelCase__ :      List[Any]								=		None
						if self.use_labels:
									lowerCamelCase__ :      int								=		ids_tensor([self.batch_size]							,    self.num_labels				)

						lowerCamelCase__ :      List[str]								=		self.get_config()
						return config, pixel_values, labels





			def        _snake_case    (self				):
						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        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__				):
						lowerCamelCase__ :      int								=		ConvNextModel(config=a_				)
						model.to(a_				)
						model.eval()
						lowerCamelCase__ :      Optional[Any]								=		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        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__				):
						lowerCamelCase__ :      List[str]								=		ConvNextForImageClassification(a_				)
						model.to(a_				)
						model.eval()
						lowerCamelCase__ :      List[Any]								=		model(a_							,    labels=a_				)
						self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.num_labels)				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__				):
						lowerCamelCase__ :      Optional[int]								=		ConvNextBackbone(config=a_				)
						model.to(a_				)
						model.eval()
						lowerCamelCase__ :      Optional[Any]								=		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
						lowerCamelCase__ :      Tuple								=		None
						lowerCamelCase__ :      List[Any]								=		ConvNextBackbone(config=a_				)
						model.to(a_				)
						model.eval()
						lowerCamelCase__ :      Optional[int]								=		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        _snake_case    (self				):
						lowerCamelCase__ :      Any								=		self.prepare_config_and_inputs()
						lowerCamelCase__ :      Union[str, Any]								=		config_and_inputs
						lowerCamelCase__ :      Union[str, Any]								=		{"pixel_values": pixel_values}
						return config, inputs_dict







@require_torch
class 				__A					( __lowerCamelCase					, __lowerCamelCase					, unittest.TestCase      ):
			UpperCamelCase					:List[str]     =			(
			    (
			        ConvNextModel,
			        ConvNextForImageClassification,
			        ConvNextBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			UpperCamelCase					:Union[str, Any]     =			(
			    {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
			    if is_torch_available()
			    else {}
			)

			UpperCamelCase					:int     =			True
			UpperCamelCase					:List[str]     =			False
			UpperCamelCase					:Optional[int]     =			False
			UpperCamelCase					:Tuple     =			False
			UpperCamelCase					:Optional[Any]     =			False





			def        _snake_case    (self				):
						lowerCamelCase__ :      Optional[int]								=		ConvNextModelTester(self				)
						lowerCamelCase__ :      int								=		ConfigTester(self							,    config_class=a_							,    has_text_modality=a_							,    hidden_size=37				)





			def        _snake_case    (self				):
						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				):
						return





			@unittest.skip(reason="""ConvNext does not use inputs_embeds"""				)
			def        _snake_case    (self				):
						pass





			@unittest.skip(reason="""ConvNext does not support input and output embeddings"""				)
			def        _snake_case    (self				):
						pass





			@unittest.skip(reason="""ConvNext does not use feedforward chunking"""				)
			def        _snake_case    (self				):
						pass





			def        _snake_case    (self				):
						lowerCamelCase__ :      Any								=		self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									lowerCamelCase__ :      Union[str, Any]								=		model_class(a_				)
									lowerCamelCase__ :      Optional[int]								=		inspect.signature(model.forward				)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									lowerCamelCase__ :      Union[str, Any]								=		[*signature.parameters.keys()]

									lowerCamelCase__ :      Any								=		["pixel_values"]
									self.assertListEqual(arg_names[:1]							,    a_				)





			def        _snake_case    (self				):
						lowerCamelCase__ :      str								=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*a_				)





			def        _snake_case    (self				):
						lowerCamelCase__ :      List[str]								=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_backbone(*a_				)





			def        _snake_case    (self				):
						def check_hidden_states_output(__magic_name__							,    __magic_name__							,    __magic_name__				):
									lowerCamelCase__ :      Optional[Any]								=		model_class(a_				)
									model.to(a_				)
									model.eval()

									with torch.no_grad():
												lowerCamelCase__ :      Tuple								=		model(**self._prepare_for_class(a_							,    a_				)				)

									lowerCamelCase__ :      List[Any]								=		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

						lowerCamelCase__ :      Any								=		self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									lowerCamelCase__ :      List[str]								=		True
									check_hidden_states_output(a_							,    a_							,    a_				)

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									lowerCamelCase__ :      Dict								=		True

									check_hidden_states_output(a_							,    a_							,    a_				)





			def        _snake_case    (self				):
						lowerCamelCase__ :      Union[str, Any]								=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*a_				)





			@slow
			def        _snake_case    (self				):
						for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowerCamelCase__ :      Any								=		ConvNextModel.from_pretrained(a_				)
									self.assertIsNotNone(a_				)







def      _A				()  ->List[Any]:



			'''simple docstring'''







			lowerCamelCase__ :      Union[str, Any]								=		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
			return image
@require_torch
@require_vision
class 				__A					( unittest.TestCase      ):





			@cached_property
			def        _snake_case    (self				):
						return AutoImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""				) if is_vision_available() else None





			@slow
			def        _snake_case    (self				):
						lowerCamelCase__ :      Optional[int]								=		ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""				).to(a_				)

						lowerCamelCase__ :      Optional[int]								=		self.default_image_processor
						lowerCamelCase__ :      Tuple								=		prepare_img()
						lowerCamelCase__ :      List[str]								=		image_processor(images=a_							,    return_tensors="""pt"""				).to(a_				)

						# forward pass
						with torch.no_grad():
									lowerCamelCase__ :      str								=		model(**a_				)

						# verify the logits
						lowerCamelCase__ :      Tuple								=		torch.Size((1, 1000)				)
						self.assertEqual(outputs.logits.shape							,    a_				)

						lowerCamelCase__ :      List[str]								=		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 				__A					( unittest.TestCase					, __lowerCamelCase      ):
			UpperCamelCase					:Optional[Any]     =			(ConvNextBackbone,) if is_torch_available() else ()
			UpperCamelCase					:Dict     =			ConvNextConfig

			UpperCamelCase					:List[Any]     =			False





			def        _snake_case    (self				):
						lowerCamelCase__ :      Any								=		ConvNextModelTester(self				)








from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
				import PIL


_lowercase     							=						logging.get_logger(__name__)
class 				__A					( A_      ):
			UpperCamelCase					:Union[str, Any]     =			['''pixel_values''']





			def __init__(self							,    __magic_name__ = True							,    __magic_name__ = None							,    __magic_name__ = PIL.Image.BICUBIC							,    __magic_name__ = True							,    __magic_name__ = None							,    __magic_name__ = 1 / 255							,    __magic_name__ = True							,    __magic_name__ = True							,    __magic_name__ = None							,    __magic_name__ = None							,    **__magic_name__							,    ):
						super().__init__(**__magic_name__				)
						lowerCamelCase__ :      str								=		size if size is not None else {"""height""": 256, """width""": 256}
						lowerCamelCase__ :      Optional[int]								=		get_size_dict(__magic_name__				)
						lowerCamelCase__ :      Any								=		crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
						lowerCamelCase__ :      Optional[int]								=		get_size_dict(__magic_name__							,    param_name="""crop_size"""				)

						lowerCamelCase__ :      str								=		do_resize
						lowerCamelCase__ :      Any								=		size
						lowerCamelCase__ :      Tuple								=		resample
						lowerCamelCase__ :      Union[str, Any]								=		do_center_crop
						lowerCamelCase__ :      List[str]								=		crop_size
						lowerCamelCase__ :      int								=		do_rescale
						lowerCamelCase__ :      Any								=		rescale_factor
						lowerCamelCase__ :      Dict								=		do_normalize
						lowerCamelCase__ :      Dict								=		image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
						lowerCamelCase__ :      int								=		image_std if image_std is not None else IMAGENET_STANDARD_STD





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__ = PIL.Image.BICUBIC							,    __magic_name__ = None							,    **__magic_name__							,    ):
						lowerCamelCase__ :      Optional[int]								=		get_size_dict(__magic_name__				)
						if "height" not in size or "width" not in size:
									raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}"				)
						return resize(
						    __magic_name__							,    size=(size["""height"""], size["""width"""])							,    resample=__magic_name__							,    data_format=__magic_name__							,    **__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__ = None							,    **__magic_name__							,    ):
						lowerCamelCase__ :      Tuple								=		get_size_dict(__magic_name__				)
						if "height" not in size or "width" not in size:
									raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}"				)
						return center_crop(__magic_name__							,    size=(size["""height"""], size["""width"""])							,    data_format=__magic_name__							,    **__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__ = None							,    **__magic_name__							,    ):
						return rescale(__magic_name__							,    scale=__magic_name__							,    data_format=__magic_name__							,    **__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__ = None							,    **__magic_name__							,    ):
						return normalize(__magic_name__							,    mean=__magic_name__							,    std=__magic_name__							,    data_format=__magic_name__							,    **__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__=None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = ChannelDimension.FIRST							,    **__magic_name__							,    ):
						lowerCamelCase__ :      Tuple								=		do_resize if do_resize is not None else self.do_resize
						lowerCamelCase__ :      str								=		resample if resample is not None else self.resample
						lowerCamelCase__ :      str								=		do_center_crop if do_center_crop is not None else self.do_center_crop
						lowerCamelCase__ :      Optional[int]								=		do_rescale if do_rescale is not None else self.do_rescale
						lowerCamelCase__ :      str								=		rescale_factor if rescale_factor is not None else self.rescale_factor
						lowerCamelCase__ :      Union[str, Any]								=		do_normalize if do_normalize is not None else self.do_normalize
						lowerCamelCase__ :      Tuple								=		image_mean if image_mean is not None else self.image_mean
						lowerCamelCase__ :      List[Any]								=		image_std if image_std is not None else self.image_std

						lowerCamelCase__ :      str								=		size if size is not None else self.size
						lowerCamelCase__ :      List[str]								=		get_size_dict(__magic_name__				)
						lowerCamelCase__ :      Tuple								=		crop_size if crop_size is not None else self.crop_size
						lowerCamelCase__ :      Optional[Any]								=		get_size_dict(__magic_name__							,    param_name="""crop_size"""				)

						lowerCamelCase__ :      Optional[int]								=		make_list_of_images(__magic_name__				)

						if not valid_images(__magic_name__				):
									raise ValueError(
									    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
									    """torch.Tensor, tf.Tensor or jax.ndarray."""				)

						if do_resize and size is None or resample is None:
									raise ValueError("""Size and resample must be specified if do_resize is True."""				)

						if do_center_crop and crop_size is None:
									raise ValueError("""Crop size must be specified if do_center_crop is True."""				)

						if do_rescale and rescale_factor is None:
									raise ValueError("""Rescale factor must be specified if do_rescale is True."""				)

						if do_normalize and (image_mean is None or image_std is None):
									raise ValueError("""Image mean and std must be specified if do_normalize is True."""				)

						# All transformations expect numpy arrays.
						lowerCamelCase__ :      Optional[int]								=		[to_numpy_array(__magic_name__				) for image in images]

						if do_resize:
									lowerCamelCase__ :      int								=		[self.resize(image=__magic_name__							,    size=__magic_name__							,    resample=__magic_name__				) for image in images]

						if do_center_crop:
									lowerCamelCase__ :      List[Any]								=		[self.center_crop(image=__magic_name__							,    size=__magic_name__				) for image in images]

						if do_rescale:
									lowerCamelCase__ :      Dict								=		[self.rescale(image=__magic_name__							,    scale=__magic_name__				) for image in images]

						if do_normalize:
									lowerCamelCase__ :      Optional[Any]								=		[self.normalize(image=__magic_name__							,    mean=__magic_name__							,    std=__magic_name__				) for image in images]

						lowerCamelCase__ :      List[str]								=		[to_channel_dimension_format(__magic_name__							,    __magic_name__				) for image in images]

						lowerCamelCase__ :      Dict								=		{"""pixel_values""": images}
						return BatchFeature(data=__magic_name__							,    tensor_type=__magic_name__				)



