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 :  Any      ,   lowercase__ :  Optional[int]      ,   lowercase__ :  int=13      ,   lowercase__ :  Optional[Any]=32      ,   lowercase__ :  Any=3      ,   lowercase__ :  Union[str, Any]=4      ,   lowercase__ :  str=[10, 20, 30, 40]      ,   lowercase__ :  Any=[2, 2, 3, 2]      ,   lowercase__ :  Optional[Any]=True      ,   lowercase__ :  Any=True      ,   lowercase__ :  Tuple=37      ,   lowercase__ :  List[str]="gelu"      ,   lowercase__ :  Any=10      ,   lowercase__ :  Dict=0.02      ,   lowercase__ :  Optional[Any]=["stage2", "stage3", "stage4"]      ,   lowercase__ :  List[Any]=[2, 3, 4]      ,   lowercase__ :  Union[str, Any]=None      ,   ):







        '''simple docstring'''



        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 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



        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 		__snake_case						(      self :  Optional[int]):







        '''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 		__snake_case						(      self :  Optional[int]      ,   lowercase__ :  Tuple      ,   lowercase__ :  List[str]      ,   lowercase__ :  Dict):







        '''simple docstring'''



        lowerCAmelCase__					     = ConvNextModel(config=lowercase__)
        model.to(lowercase__)
        model.eval()
        lowerCAmelCase__					     = 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 		__snake_case						(      self :  Optional[int]      ,   lowercase__ :  Tuple      ,   lowercase__ :  str      ,   lowercase__ :  Optional[int]):







        '''simple docstring'''



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




 def 		__snake_case						(      self :  Optional[Any]      ,   lowercase__ :  int      ,   lowercase__ :  Tuple      ,   lowercase__ :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = ConvNextBackbone(config=lowercase__)
        model.to(lowercase__)
        model.eval()
        lowerCAmelCase__					     = 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
        lowerCAmelCase__					     = None
        lowerCAmelCase__					     = ConvNextBackbone(config=lowercase__)
        model.to(lowercase__)
        model.eval()
        lowerCAmelCase__					     = 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 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



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






@require_torch
class     a_			(						SCREAMING_SNAKE_CASE	,					SCREAMING_SNAKE_CASE	,					unittest.TestCase						):






 '''simple docstring'''






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

 UpperCAmelCase_     			= True
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False




 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



        lowerCAmelCase__					     = ConvNextModelTester(self)
        lowerCAmelCase__					     = ConfigTester(self      ,   config_class=lowercase__      ,   has_text_modality=lowercase__      ,   hidden_size=37)




 def 		__snake_case						(      self :  Dict):







        '''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 		__snake_case						(      self :  str):







        '''simple docstring'''



        return




 @unittest.skip(reason='ConvNext does not use inputs_embeds')
 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        pass




 @unittest.skip(reason='ConvNext does not support input and output embeddings')
 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        pass




 @unittest.skip(reason='ConvNext does not use feedforward chunking')
 def 		__snake_case						(      self :  Tuple):







        '''simple docstring'''



        pass




 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()

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




 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase__)




 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_backbone(*lowercase__)




 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



        def check_hidden_states_output(lowercase__ :  Tuple      ,   lowercase__ :  List[str]      ,   lowercase__ :  List[str]):
               lowerCAmelCase__					     = model_class(lowercase__)
               model.to(lowercase__)
               model.eval()

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

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

               lowerCAmelCase__					     = 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]      ,   )

        lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
               lowerCAmelCase__					     = True
               check_hidden_states_output(lowercase__      ,   lowercase__      ,   lowercase__)

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

               check_hidden_states_output(lowercase__      ,   lowercase__      ,   lowercase__)




 def 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowercase__)




 @slow
 def 		__snake_case						(      self :  Any):







        '''simple docstring'''



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






def 				__lowerCamelCase		(						):
       lowerCAmelCase__					     = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
       return image
@require_torch
@require_vision
class     a_			(						unittest.TestCase						):






 '''simple docstring'''






 @cached_property
 def 		__snake_case						(      self :  str):







        '''simple docstring'''



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




 @slow
 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        lowerCAmelCase__					     = ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224').to(lowercase__)

        lowerCAmelCase__					     = self.default_image_processor
        lowerCAmelCase__					     = prepare_img()
        lowerCAmelCase__					     = image_processor(images=lowercase__      ,   return_tensors='pt').to(lowercase__)

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

        # verify the logits
        lowerCAmelCase__					     = torch.Size((1, 1_000))
        self.assertEqual(outputs.logits.shape      ,   lowercase__)

        lowerCAmelCase__					     = torch.tensor([-0.0_260, -0.4_739, 0.1_911]).to(lowercase__)

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






@require_torch
class     a_			(						unittest.TestCase	,					SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






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

 UpperCAmelCase_     			= False




 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        lowerCAmelCase__					     = 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 convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_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


lowerCAmelCase__     						=			logging.get_logger(__name__)
class     a_			(						SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






 UpperCAmelCase_     			= ['pixel_values']




 def __init__(      self :  Tuple      ,   lowercase__ :  bool = True      ,   lowercase__ :  Dict[str, int] = None      ,   lowercase__ :  PILImageResampling = PILImageResampling.BICUBIC      ,   lowercase__ :  bool = True      ,   lowercase__ :  Union[int, float] = 1 / 255      ,   lowercase__ :  bool = True      ,   lowercase__ :  Optional[Union[float, List[float]]] = None      ,   lowercase__ :  Optional[Union[float, List[float]]] = None      ,   lowercase__ :  bool = True      ,   **lowercase__ :  List[Any]      ,   ):







        '''simple docstring'''



        super().__init__(**lowercase__)
        lowerCAmelCase__					     = size if size is not None else {'height': 384, 'width': 384}
        lowerCAmelCase__					     = get_size_dict(lowercase__      ,   default_to_square=lowercase__)

        lowerCAmelCase__					     = do_resize
        lowerCAmelCase__					     = size
        lowerCAmelCase__					     = resample
        lowerCAmelCase__					     = do_rescale
        lowerCAmelCase__					     = rescale_factor
        lowerCAmelCase__					     = do_normalize
        lowerCAmelCase__					     = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
        lowerCAmelCase__					     = image_std if image_std is not None else OPENAI_CLIP_STD
        lowerCAmelCase__					     = do_convert_rgb




 def 		__snake_case						(      self :  List[str]      ,   lowercase__ :  np.ndarray      ,   lowercase__ :  Dict[str, int]      ,   lowercase__ :  PILImageResampling = PILImageResampling.BICUBIC      ,   lowercase__ :  Optional[Union[str, ChannelDimension]] = None      ,   **lowercase__ :  Dict      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = get_size_dict(lowercase__      ,   default_to_square=lowercase__)
        if "height" not in size or "width" not in size:
               raise ValueError(F"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""")
        lowerCAmelCase__					     = (size['height'], size['width'])
        return resize(lowercase__      ,   size=lowercase__      ,   resample=lowercase__      ,   data_format=lowercase__      ,   **lowercase__)




 def 		__snake_case						(      self :  List[str]      ,   lowercase__ :  np.ndarray      ,   lowercase__ :  Union[int, float]      ,   lowercase__ :  Optional[Union[str, ChannelDimension]] = None      ,   **lowercase__ :  Union[str, Any]      ,   ):







        '''simple docstring'''



        return rescale(lowercase__      ,   scale=lowercase__      ,   data_format=lowercase__      ,   **lowercase__)




 def 		__snake_case						(      self :  Optional[Any]      ,   lowercase__ :  np.ndarray      ,   lowercase__ :  Union[float, List[float]]      ,   lowercase__ :  Union[float, List[float]]      ,   lowercase__ :  Optional[Union[str, ChannelDimension]] = None      ,   **lowercase__ :  Any      ,   ):







        '''simple docstring'''



        return normalize(lowercase__      ,   mean=lowercase__      ,   std=lowercase__      ,   data_format=lowercase__      ,   **lowercase__)




 def 		__snake_case						(      self :  Any      ,   lowercase__ :  ImageInput      ,   lowercase__ :  Optional[bool] = None      ,   lowercase__ :  Optional[Dict[str, int]] = None      ,   lowercase__ :  PILImageResampling = None      ,   lowercase__ :  Optional[bool] = None      ,   lowercase__ :  Optional[float] = None      ,   lowercase__ :  Optional[bool] = None      ,   lowercase__ :  Optional[Union[float, List[float]]] = None      ,   lowercase__ :  Optional[Union[float, List[float]]] = None      ,   lowercase__ :  Optional[Union[str, TensorType]] = None      ,   lowercase__ :  bool = None      ,   lowercase__ :  ChannelDimension = ChannelDimension.FIRST      ,   **lowercase__ :  Dict      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = do_resize if do_resize is not None else self.do_resize
        lowerCAmelCase__					     = resample if resample is not None else self.resample
        lowerCAmelCase__					     = do_rescale if do_rescale is not None else self.do_rescale
        lowerCAmelCase__					     = rescale_factor if rescale_factor is not None else self.rescale_factor
        lowerCAmelCase__					     = do_normalize if do_normalize is not None else self.do_normalize
        lowerCAmelCase__					     = image_mean if image_mean is not None else self.image_mean
        lowerCAmelCase__					     = image_std if image_std is not None else self.image_std
        lowerCAmelCase__					     = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

        lowerCAmelCase__					     = size if size is not None else self.size
        lowerCAmelCase__					     = get_size_dict(lowercase__      ,   default_to_square=lowercase__)

        lowerCAmelCase__					     = make_list_of_images(lowercase__)

        if not valid_images(lowercase__):
               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_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.')

        # PIL RGBA images are converted to RGB
        if do_convert_rgb:
               lowerCAmelCase__					     = [convert_to_rgb(lowercase__) for image in images]

        # All transformations expect numpy arrays.
        lowerCAmelCase__					     = [to_numpy_array(lowercase__) for image in images]

        if do_resize:
               lowerCAmelCase__					     = [self.resize(image=lowercase__      ,   size=lowercase__      ,   resample=lowercase__) for image in images]

        if do_rescale:
               lowerCAmelCase__					     = [self.rescale(image=lowercase__      ,   scale=lowercase__) for image in images]

        if do_normalize:
               lowerCAmelCase__					     = [self.normalize(image=lowercase__      ,   mean=lowercase__      ,   std=lowercase__) for image in images]

        lowerCAmelCase__					     = [to_channel_dimension_format(lowercase__      ,   lowercase__) for image in images]

        lowerCAmelCase__					     = BatchFeature(data={'pixel_values': images}      ,   tensor_type=lowercase__)

        return encoded_outputs
