

'''simple docstring'''

from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
       import tensorflow as tf

       from transformers import TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
       from PIL import Image

       from transformers import ConvNextImageProcessor


class   lowerCAmelCase     :







       def __init__(							self			: List[str]						,      __lowercase			: List[str]						,      __lowercase			: List[str]=13						,      __lowercase			: Dict=32						,      __lowercase			: List[str]=3						,      __lowercase			: int=4						,      __lowercase			: Dict=[10, 20, 30, 40]						,      __lowercase			: Union[str, Any]=[2, 2, 3, 2]						,      __lowercase			: Optional[int]=True						,      __lowercase			: Dict=True						,      __lowercase			: List[Any]=37						,      __lowercase			: Optional[Any]="gelu"						,      __lowercase			: Optional[Any]=10						,      __lowercase			: Union[str, Any]=0.0_2						,      __lowercase			: Tuple=3						,      __lowercase			: Tuple=None						,      ):







            """simple docstring"""







            __lowercase					=parent
            __lowercase					=batch_size
            __lowercase					=image_size
            __lowercase					=num_channels
            __lowercase					=num_stages
            __lowercase					=hidden_sizes
            __lowercase					=depths
            __lowercase					=is_training
            __lowercase					=use_labels
            __lowercase					=intermediate_size
            __lowercase					=hidden_act
            __lowercase					=type_sequence_label_size
            __lowercase					=initializer_range
            __lowercase					=scope







       def 			snake_case   (							self			: Dict      ):







            """simple docstring"""







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

            __lowercase					=None
            if self.use_labels:
                 __lowercase					=ids_tensor([self.batch_size]						,      self.type_sequence_label_size      )

            __lowercase					=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						,      )







       def 			snake_case   (							self			: int						,      __lowercase			: Dict						,      __lowercase			: Tuple						,      __lowercase			: Any      ):







            """simple docstring"""







            __lowercase					=TFConvNextModel(config=__lowercase      )
            __lowercase					=model(__lowercase						,      training=__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			: Dict						,      __lowercase			: str						,      __lowercase			: str      ):







            """simple docstring"""







            __lowercase					=self.type_sequence_label_size
            __lowercase					=TFConvNextForImageClassification(__lowercase      )
            __lowercase					=model(__lowercase						,      labels=__lowercase						,      training=__lowercase      )
            self.parent.assertEqual(result.logits.shape						,      (self.batch_size, self.type_sequence_label_size)      )







       def 			snake_case   (							self			: int      ):







            """simple docstring"""







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






@require_tf
class   lowerCAmelCase     (      A   ,			A   ,			unittest.TestCase   ):
       lowerCAmelCase_		= (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
       lowerCAmelCase_		= (
           {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
           if is_tf_available()
           else {}
       )

       lowerCAmelCase_		= False
       lowerCAmelCase_		= False
       lowerCAmelCase_		= False
       lowerCAmelCase_		= False
       lowerCAmelCase_		= False







       def 			snake_case   (							self			: List[str]      ):







            """simple docstring"""







            __lowercase					=TFConvNextModelTester(self      )
            __lowercase					=ConfigTester(
                self						,      config_class=__lowercase						,      has_text_modality=__lowercase						,      hidden_size=37						,      )







       @unittest.skip(reason='ConvNext does not use inputs_embeds'      )
       def 			snake_case   (							self			: List[Any]      ):







            """simple docstring"""







            pass







       @unittest.skipIf(
           not is_tf_available() or len(tf.config.list_physical_devices('GPU'      )      ) == 0						,      reason='TF does not support backprop for grouped convolutions on CPU.'						,      )
       @slow
       def 			snake_case   (							self			: Union[str, Any]      ):







            """simple docstring"""







            super().test_keras_fit()







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







            """simple docstring"""







            pass







       def 			snake_case   (							self			: Dict      ):







            """simple docstring"""







            __lowercase		,     __lowercase					=self.model_tester.prepare_config_and_inputs_for_common()

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

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







       def 			snake_case   (							self			: Any      ):







            """simple docstring"""







            __lowercase					=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__lowercase      )







       @unittest.skipIf(
           not is_tf_available() or len(tf.config.list_physical_devices('GPU'      )      ) == 0						,      reason='TF does not support backprop for grouped convolutions on CPU.'						,      )
       def 			snake_case   (							self			: List[Any]      ):







            """simple docstring"""







            super().test_dataset_conversion()







       def 			snake_case   (							self			: Optional[int]      ):







            """simple docstring"""







            def check_hidden_states_output(__lowercase			: Optional[int]						,      __lowercase			: str						,      __lowercase			: Dict      ):
                 __lowercase					=model_class(__lowercase      )

                 __lowercase					=model(**self._prepare_for_class(__lowercase						,      __lowercase      )      )
                 __lowercase					=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

            __lowercase		,     __lowercase					=self.model_tester.prepare_config_and_inputs_for_common()

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

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

                 check_hidden_states_output(__lowercase						,      __lowercase						,      __lowercase      )







       def 			snake_case   (							self			: List[str]      ):







            """simple docstring"""







            __lowercase		,     __lowercase					=self.model_tester.prepare_config_and_inputs_for_common()

            def check_equivalence(__lowercase			: Tuple						,      __lowercase			: int						,      __lowercase			: Union[str, Any]						,      __lowercase			: Optional[int]={}      ):
                 __lowercase					=model(__lowercase						,      return_dict=__lowercase						,      **__lowercase      )
                 __lowercase					=model(__lowercase						,      return_dict=__lowercase						,      **__lowercase      ).to_tuple()

                 def recursive_check(__lowercase			: List[str]						,      __lowercase			: Union[str, Any]      ):
                      if isinstance(__lowercase						,      (List, Tuple)      ):
                           for tuple_iterable_value, dict_iterable_value in zip(__lowercase						,      __lowercase      ):
                                recursive_check(__lowercase						,      __lowercase      )
                      elif tuple_object is None:
                           return
                      else:
                           self.assertTrue(
                               all(tf.equal(__lowercase						,      __lowercase      )      )						,      msg=(
                                   'Tuple and dict output are not equal. Difference:'
                                   f''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object      )      )}'''
                               )						,      )

                      recursive_check(__lowercase						,      __lowercase      )

            for model_class in self.all_model_classes:
                 __lowercase					=model_class(__lowercase      )

                 __lowercase					=self._prepare_for_class(__lowercase						,      __lowercase      )
                 __lowercase					=self._prepare_for_class(__lowercase						,      __lowercase      )
                 check_equivalence(__lowercase						,      __lowercase						,      __lowercase      )

                 __lowercase					=self._prepare_for_class(__lowercase						,      __lowercase						,      return_labels=__lowercase      )
                 __lowercase					=self._prepare_for_class(__lowercase						,      __lowercase						,      return_labels=__lowercase      )
                 check_equivalence(__lowercase						,      __lowercase						,      __lowercase      )

                 __lowercase					=self._prepare_for_class(__lowercase						,      __lowercase      )
                 __lowercase					=self._prepare_for_class(__lowercase						,      __lowercase      )
                 check_equivalence(__lowercase						,      __lowercase						,      __lowercase						,      {'output_hidden_states': True}      )

                 __lowercase					=self._prepare_for_class(__lowercase						,      __lowercase						,      return_labels=__lowercase      )
                 __lowercase					=self._prepare_for_class(__lowercase						,      __lowercase						,      return_labels=__lowercase      )
                 check_equivalence(__lowercase						,      __lowercase						,      __lowercase						,      {'output_hidden_states': True}      )







       def 			snake_case   (							self			: Optional[int]      ):







            """simple docstring"""







            __lowercase					=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*__lowercase      )







       @slow
       def 			snake_case   (							self			: Dict      ):







            """simple docstring"""







            __lowercase					=TFConvNextModel.from_pretrained('facebook/convnext-tiny-224'      )
            self.assertIsNotNone(__lowercase      )






def 				__UpperCamelCase							(	):






     '''simple docstring'''





     __lowercase					=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
     return image







@require_tf
@require_vision
class   lowerCAmelCase     (      unittest.TestCase   ):







       @cached_property
       def 			snake_case   (							self			: Dict      ):







            """simple docstring"""







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







       @slow
       def 			snake_case   (							self			: Any      ):







            """simple docstring"""







            __lowercase					=TFConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'      )

            __lowercase					=self.default_image_processor
            __lowercase					=prepare_img()
            __lowercase					=image_processor(images=__lowercase						,      return_tensors='tf'      )

            # forward pass
            __lowercase					=model(**__lowercase      )

            # verify the logits
            __lowercase					=tf.TensorShape((1, 1000)      )
            self.assertEqual(outputs.logits.shape						,      __lowercase      )

            __lowercase					=tf.constant([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]      )

            tf.debugging.assert_near(outputs.logits[0, :3]						,      __lowercase						,      atol=1E-4      )





'''simple docstring'''

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_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
       import PIL


UpperCAmelCase				   =  logging.get_logger(__name__)


class   lowerCAmelCase     (      A   ):
       lowerCAmelCase_		= ["pixel_values"]







       def __init__(							self			: Dict						,      __lowercase			: bool = True						,      __lowercase			: Dict[str, int] = None						,      __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			: Any						,      ):







            """simple docstring"""







            super().__init__(**__lowercase      )
            __lowercase					=crop_size if crop_size is not None else {'height': 256, 'width': 256}
            __lowercase					=get_size_dict(__lowercase						,      param_name='crop_size'      )
            __lowercase					=size if size is not None else {'height': 224, 'width': 224}
            __lowercase					=get_size_dict(__lowercase      )

            __lowercase					=do_center_crop
            __lowercase					=crop_size
            __lowercase					=do_resize
            __lowercase					=size
            __lowercase					=resample
            __lowercase					=do_rescale
            __lowercase					=rescale_factor
            __lowercase					=do_normalize
            __lowercase					=image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
            __lowercase					=image_std if image_std is not None else IMAGENET_DEFAULT_STD







       def 			snake_case   (							self			: int						,      __lowercase			: np.ndarray						,      __lowercase			: Dict[str, int]						,      __lowercase			: Optional[int] = None						,      __lowercase			: Optional[Union[str, ChannelDimension]] = None						,      **__lowercase			: Optional[Any]						,      ):







            """simple docstring"""







            __lowercase					=self.size if size is None else size
            __lowercase					=get_size_dict(__lowercase      )
            __lowercase					=get_size_dict(__lowercase						,      param_name='crop_size'      )

            __lowercase		,     __lowercase					=get_image_size(__lowercase      )
            __lowercase					=min(__lowercase						,      __lowercase      )
            __lowercase					=(size['height'] / crop_size['height']) * min_dim
            __lowercase					=(size['width'] / crop_size['width']) * min_dim
            return center_crop(__lowercase						,      size=(cropped_height, cropped_width)						,      data_format=__lowercase						,      **__lowercase      )







       def 			snake_case   (							self			: str						,      __lowercase			: np.ndarray						,      __lowercase			: Dict[str, int]						,      __lowercase			: PILImageResampling = PIL.Image.BICUBIC						,      __lowercase			: Optional[Union[str, ChannelDimension]] = None						,      **__lowercase			: Optional[int]						,      ):







            """simple docstring"""







            __lowercase					=get_size_dict(__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()}'''      )
            return resize(
                __lowercase						,      size=(size['height'], size['width'])						,      resample=__lowercase						,      data_format=__lowercase						,      **__lowercase      )







       def 			snake_case   (							self			: Dict						,      __lowercase			: np.ndarray						,      __lowercase			: Union[int, float]						,      __lowercase			: Optional[Union[str, ChannelDimension]] = None						,      **__lowercase			: Dict						,      ):







            """simple docstring"""







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







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







            """simple docstring"""







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







       def 			snake_case   (							self			: Dict						,      __lowercase			: ImageInput						,      __lowercase			: Optional[bool] = None						,      __lowercase			: Optional[Dict[str, int]] = None						,      __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			: ChannelDimension = ChannelDimension.FIRST						,      **__lowercase			: Optional[int]						,      ):







            """simple docstring"""







            __lowercase					=do_center_crop if do_center_crop is not None else self.do_center_crop
            __lowercase					=crop_size if crop_size is not None else self.crop_size
            __lowercase					=get_size_dict(__lowercase						,      param_name='crop_size'      )
            __lowercase					=do_resize if do_resize is not None else self.do_resize
            __lowercase					=size if size is not None else self.size
            __lowercase					=get_size_dict(__lowercase      )
            __lowercase					=resample if resample is not None else self.resample
            __lowercase					=do_rescale if do_rescale is not None else self.do_rescale
            __lowercase					=rescale_factor if rescale_factor is not None else self.rescale_factor
            __lowercase					=do_normalize if do_normalize is not None else self.do_normalize
            __lowercase					=image_mean if image_mean is not None else self.image_mean
            __lowercase					=image_std if image_std is not None else self.image_std

            __lowercase					=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_center_crop and crop_size is None:
                 raise ValueError('If `do_center_crop` is set to `True`, `crop_size` must be provided.'      )

            if do_resize and size is None:
                 raise ValueError('Size 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 image standard deviation must be specified if do_normalize is True.'      )

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

            if do_center_crop:
                 __lowercase					=[self.center_crop(__lowercase						,      __lowercase						,      size=__lowercase      ) for image in images]

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

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

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

            __lowercase					=[to_channel_dimension_format(__lowercase						,      __lowercase      ) for image in images]

            __lowercase					={'pixel_values': images}
            return BatchFeature(data=__lowercase						,      tensor_type=__lowercase      )


