

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							,  lowerCamelCase							,  lowerCamelCase=13							,  lowerCamelCase=32							,  lowerCamelCase=3							,  lowerCamelCase=4							,  lowerCamelCase=[10, 20, 30, 40]							,  lowerCamelCase=[2, 2, 3, 2]							,  lowerCamelCase=True							,  lowerCamelCase=True							,  lowerCamelCase=37							,  lowerCamelCase="gelu"							,  lowerCamelCase=10							,  lowerCamelCase=0.02							,  lowerCamelCase=3							,  lowerCamelCase=None							,  )						->       List[Any]:
        snake_case_       						=      parent
        snake_case_       						=      batch_size
        snake_case_       						=      image_size
        snake_case_       						=      num_channels
        snake_case_       						=      num_stages
        snake_case_       						=      hidden_sizes
        snake_case_       						=      depths
        snake_case_       						=      is_training
        snake_case_       						=      use_labels
        snake_case_       						=      intermediate_size
        snake_case_       						=      hidden_act
        snake_case_       						=      type_sequence_label_size
        snake_case_       						=      initializer_range
        snake_case_       						=      scope







      def 	lowerCAmelCase_    (     self   )						->       Any:
        snake_case_       						=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

        snake_case_       						=      self.get_config()

        return config, pixel_values, labels







      def 	lowerCAmelCase_    (     self   )						->       Optional[int]:
        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=lowerCamelCase							,  initializer_range=self.initializer_range							,  )







      def 	lowerCAmelCase_    (     self							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )						->       str:
        snake_case_       						=      TFConvNextModel(config=lowerCamelCase   )
        snake_case_       						=      model(lowerCamelCase							,  training=lowerCamelCase   )
        # 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 	lowerCAmelCase_    (     self							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )						->       str:
        snake_case_       						=      self.type_sequence_label_size
        snake_case_       						=      TFConvNextForImageClassification(lowerCamelCase   )
        snake_case_       						=      model(lowerCamelCase							,  labels=lowerCamelCase							,  training=lowerCamelCase   )
        self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.type_sequence_label_size)   )







      def 	lowerCAmelCase_    (     self   )						->       List[str]:
        snake_case_       						=      self.prepare_config_and_inputs()
        snake_case_						,				snake_case_						,				snake_case_       						=      config_and_inputs
        snake_case_       						=      {"""pixel_values""": pixel_values}
        return config, inputs_dict







@require_tf
class  __lowerCamelCase				(	__snake_case  ,							__snake_case  ,							unittest.TestCase	):
      lowerCamelCase_	:      Union[str, Any]          =					(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
      lowerCamelCase_	:      Any          =					(
          {'feature-extraction': TFConvNextModel, 'image-classification': TFConvNextForImageClassification}
          if is_tf_available()
          else {}
      )

      lowerCamelCase_	:      Any          =					False
      lowerCamelCase_	:      List[str]          =					False
      lowerCamelCase_	:      Any          =					False
      lowerCamelCase_	:      Dict          =					False
      lowerCamelCase_	:      Optional[Any]          =					False







      def 	lowerCAmelCase_    (     self   )						->       str:
        snake_case_       						=      TFConvNextModelTester(self   )
        snake_case_       						=      ConfigTester(
            self							,  config_class=lowerCamelCase							,  has_text_modality=lowerCamelCase							,  hidden_size=37							,  )







      @unittest.skip(reason="""ConvNext does not use inputs_embeds"""   )
      def 	lowerCAmelCase_    (     self   )						->       Any:
        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 	lowerCAmelCase_    (     self   )						->       Tuple:
        super().test_keras_fit()







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







      def 	lowerCAmelCase_    (     self   )						->       List[str]:
        snake_case_						,				snake_case_       						=      self.model_tester.prepare_config_and_inputs_for_common()

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

          snake_case_       						=      ["""pixel_values"""]
          self.assertListEqual(arg_names[:1]							,  lowerCamelCase   )







      def 	lowerCAmelCase_    (     self   )						->       List[Any]:
        snake_case_       						=      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCamelCase   )







      @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 	lowerCAmelCase_    (     self   )						->       Optional[int]:
        super().test_dataset_conversion()







      def 	lowerCAmelCase_    (     self   )						->       str:
        def check_hidden_states_output(lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   ):
          snake_case_       						=      model_class(lowerCamelCase   )

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

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

        snake_case_						,				snake_case_       						=      self.model_tester.prepare_config_and_inputs_for_common()

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

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

          check_hidden_states_output(lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )







      def 	lowerCAmelCase_    (     self   )						->       Union[str, Any]:
        snake_case_						,				snake_case_       						=      self.model_tester.prepare_config_and_inputs_for_common()

        def check_equivalence(lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase={}   ):
          snake_case_       						=      model(lowerCamelCase							,  return_dict=lowerCamelCase							,  **lowerCamelCase   )
          snake_case_       						=      model(lowerCamelCase							,  return_dict=lowerCamelCase							,  **lowerCamelCase   ).to_tuple()

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

            recursive_check(lowerCamelCase							,  lowerCamelCase   )

        for model_class in self.all_model_classes:
          snake_case_       						=      model_class(lowerCamelCase   )

          snake_case_       						=      self._prepare_for_class(lowerCamelCase							,  lowerCamelCase   )
          snake_case_       						=      self._prepare_for_class(lowerCamelCase							,  lowerCamelCase   )
          check_equivalence(lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )

          snake_case_       						=      self._prepare_for_class(lowerCamelCase							,  lowerCamelCase							,  return_labels=lowerCamelCase   )
          snake_case_       						=      self._prepare_for_class(lowerCamelCase							,  lowerCamelCase							,  return_labels=lowerCamelCase   )
          check_equivalence(lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )

          snake_case_       						=      self._prepare_for_class(lowerCamelCase							,  lowerCamelCase   )
          snake_case_       						=      self._prepare_for_class(lowerCamelCase							,  lowerCamelCase   )
          check_equivalence(lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  {"""output_hidden_states""": True}   )

          snake_case_       						=      self._prepare_for_class(lowerCamelCase							,  lowerCamelCase							,  return_labels=lowerCamelCase   )
          snake_case_       						=      self._prepare_for_class(lowerCamelCase							,  lowerCamelCase							,  return_labels=lowerCamelCase   )
          check_equivalence(lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  {"""output_hidden_states""": True}   )







      def 	lowerCAmelCase_    (     self   )						->       List[Any]:
        snake_case_       						=      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCamelCase   )







      @slow
      def 	lowerCAmelCase_    (     self   )						->       Tuple:
        snake_case_       						=      TFConvNextModel.from_pretrained("""facebook/convnext-tiny-224"""   )
        self.assertIsNotNone(lowerCamelCase   )



def    UpperCamelCase(					)	->				Tuple:





  '''simple docstring'''





  snake_case_       						=      Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
  return image







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







      @cached_property
      def 	lowerCAmelCase_    (     self   )						->       Union[str, Any]:
        return ConvNextImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""   ) if is_vision_available() else None







      @slow
      def 	lowerCAmelCase_    (     self   )						->       Dict:
        snake_case_       						=      TFConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""   )

        snake_case_       						=      self.default_image_processor
        snake_case_       						=      prepare_img()
        snake_case_       						=      image_processor(images=lowerCamelCase							,  return_tensors="""tf"""   )

        # forward pass
        snake_case_       						=      model(**lowerCamelCase   )

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

        snake_case_       						=      tf.constant([-0.0260, -0.4739, 0.1911]   )

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







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


lowerCamelCase_						     =  logging.get_logger(__name__)




class 							a_ (						a_		):


							'''simple docstring'''






							__a:	Optional[Any]     =    ['''pixel_values''']

							def __init__(		self			,			lowercase_ = True			,			lowercase_ = None			,			lowercase_ = True			,			lowercase_ = None			,			lowercase_ = PILImageResampling.BICUBIC			,			lowercase_ = True			,			lowercase_ = 1 / 2_5_5			,			lowercase_ = True			,			lowercase_ = None			,			lowercase_ = None			,			**lowercase_			,			)					->					None:
														'''simple docstring'''

														super().__init__(**lowercase_   )
														lowerCAmelCase_										=     crop_size if crop_size is not None else {'height': 2_5_6, 'width': 2_5_6}
														lowerCAmelCase_										=     get_size_dict(lowercase_			,			param_name='crop_size'   )
														lowerCAmelCase_										=     size if size is not None else {'height': 2_2_4, 'width': 2_2_4}
														lowerCAmelCase_										=     get_size_dict(lowercase_   )

														lowerCAmelCase_										=     do_center_crop
														lowerCAmelCase_										=     crop_size
														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 IMAGENET_DEFAULT_MEAN
														lowerCAmelCase_										=     image_std if image_std is not None else IMAGENET_DEFAULT_STD

							def      _lowercase       (		self			,			lowercase_			,			lowercase_			,			lowercase_ = None			,			lowercase_ = None			,			**lowercase_			,			)					->					np.ndarray:
														'''simple docstring'''

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

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

							def      _lowercase       (		self			,			lowercase_			,			lowercase_			,			lowercase_ = PIL.Image.BICUBIC			,			lowercase_ = None			,			**lowercase_			,			)					->					np.ndarray:
														'''simple docstring'''

														lowerCAmelCase_										=     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      _lowercase       (		self			,			lowercase_			,			lowercase_			,			lowercase_ = None			,			**lowercase_			,			)					->					Any:
														'''simple docstring'''

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

							def      _lowercase       (		self			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_ = None			,			**lowercase_			,			)					->					np.ndarray:
														'''simple docstring'''

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






							def      _lowercase       (		self			,			lowercase_			,			lowercase_ = None			,			lowercase_ = None			,			lowercase_ = None			,			lowercase_ = None			,			lowercase_ = None			,			lowercase_ = None			,			lowercase_ = None			,			lowercase_ = None			,			lowercase_ = None			,			lowercase_ = None			,			lowercase_ = None			,			lowercase_ = ChannelDimension.FIRST			,			**lowercase_			,			)					->					PIL.Image.Image:
														'''simple docstring'''

														lowerCAmelCase_										=     do_center_crop if do_center_crop is not None else self.do_center_crop
														lowerCAmelCase_										=     crop_size if crop_size is not None else self.crop_size
														lowerCAmelCase_										=     get_size_dict(lowercase_			,			param_name='crop_size'   )
														lowerCAmelCase_										=     do_resize if do_resize is not None else self.do_resize
														lowerCAmelCase_										=     size if size is not None else self.size
														lowerCAmelCase_										=     get_size_dict(lowercase_   )
														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_										=     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.
														lowerCAmelCase_										=     [to_numpy_array(lowercase_   ) for image in images]

														if do_center_crop:
																					lowerCAmelCase_										=     [self.center_crop(lowercase_			,			lowercase_			,			size=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_										=     {'pixel_values': images}
														return BatchFeature(data=lowercase_			,			tensor_type=lowercase_   )



