




"""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       UpperCAmelCase_    :




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




     '''simple docstring'''

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




    def 				__magic_name__				(       self		:			Optional[Any] ) ->				str:




     '''simple docstring'''

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

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

     A__			=							self.get_config()

     return config, pixel_values, labels




    def 				__magic_name__				(       self		:			Dict ) ->				Dict:




     '''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=snake_case_      ,					initializer_range=self.initializer_range      ,					)




    def 				__magic_name__				(       self		:			Optional[Any]      ,					snake_case_		:			Optional[int]      ,					snake_case_		:			Optional[int]      ,					snake_case_		:			Union[str, Any] ) ->				str:




     '''simple docstring'''

     A__			=							TFConvNextModel(config=snake_case_ )
     A__			=							model(snake_case_      ,					training=snake_case_ )
     # 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 				__magic_name__				(       self		:			Dict      ,					snake_case_		:			int      ,					snake_case_		:			Tuple      ,					snake_case_		:			List[str] ) ->				List[str]:




     '''simple docstring'''

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




    def 				__magic_name__				(       self		:			str ) ->				Dict:




     '''simple docstring'''

     A__			=							self.prepare_config_and_inputs()
     A__, A__, A__			=							config_and_inputs
     A__			=							{"pixel_values": pixel_values}
     return config, inputs_dict






@require_tf
class       UpperCAmelCase_    (		A_,  A_,  unittest.TestCase				):
    lowercase__		   = (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
    lowercase__		   = (
        {'''feature-extraction''': TFConvNextModel, '''image-classification''': TFConvNextForImageClassification}
        if is_tf_available()
        else {}
    )

    lowercase__		   = False
    lowercase__		   = False
    lowercase__		   = False
    lowercase__		   = False
    lowercase__		   = False




    def 				__magic_name__				(       self		:			Dict ) ->				str:




     '''simple docstring'''

     A__			=							TFConvNextModelTester(self )
     A__			=							ConfigTester(
         self      ,					config_class=snake_case_      ,					has_text_modality=snake_case_      ,					hidden_size=37      ,					)




    @unittest.skip(reason="ConvNext does not use inputs_embeds" )
    def 				__magic_name__				(       self		:			List[str] ) ->				Tuple:




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




     '''simple docstring'''

     super().test_keras_fit()




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




     '''simple docstring'''

     pass




    def 				__magic_name__				(       self		:			Tuple ) ->				List[str]:




     '''simple docstring'''

     A__, A__			=							self.model_tester.prepare_config_and_inputs_for_common()

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

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




    def 				__magic_name__				(       self		:			List[Any] ) ->				Optional[Any]:




     '''simple docstring'''

     A__			=							self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*snake_case_ )




    @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 				__magic_name__				(       self		:			Tuple ) ->				Optional[Any]:




     '''simple docstring'''

     super().test_dataset_conversion()




    def 				__magic_name__				(       self		:			Optional[int] ) ->				Dict:




     '''simple docstring'''

     def check_hidden_states_output(snake_case_		:			Dict      ,					snake_case_		:			int      ,					snake_case_		:			List[str] ):
      A__			=							model_class(snake_case_ )

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

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

     A__, A__			=							self.model_tester.prepare_config_and_inputs_for_common()

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

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

      check_hidden_states_output(snake_case_      ,					snake_case_      ,					snake_case_ )




    def 				__magic_name__				(       self		:			Tuple ) ->				List[str]:




     '''simple docstring'''

     A__, A__			=							self.model_tester.prepare_config_and_inputs_for_common()

     def check_equivalence(snake_case_		:			List[str]      ,					snake_case_		:			List[str]      ,					snake_case_		:			Optional[Any]      ,					snake_case_		:			List[Any]={} ):
      A__			=							model(snake_case_      ,					return_dict=snake_case_      ,					**snake_case_ )
      A__			=							model(snake_case_      ,					return_dict=snake_case_      ,					**snake_case_ ).to_tuple()

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

       recursive_check(snake_case_      ,					snake_case_ )

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

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

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

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

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




    def 				__magic_name__				(       self		:			Dict ) ->				int:




     '''simple docstring'''

     A__			=							self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*snake_case_ )




    @slow
    def 				__magic_name__				(       self		:			Dict ) ->				Union[str, Any]:




     '''simple docstring'''

     A__			=							TFConvNextModel.from_pretrained("facebook/convnext-tiny-224" )
     self.assertIsNotNone(snake_case_ )







def     _SCREAMING_SNAKE_CASE  (				)		->						Tuple:
 A__			=							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
 return image






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




    @cached_property
    def 				__magic_name__				(       self		:			Any ) ->				Optional[Any]:




     '''simple docstring'''

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




    @slow
    def 				__magic_name__				(       self		:			Union[str, Any] ) ->				Union[str, Any]:




     '''simple docstring'''

     A__			=							TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224" )

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

     # forward pass
     A__			=							model(**snake_case_ )

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

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

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











"""simple docstring"""



import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
      import torch

if is_vision_available():
      from PIL import Image

      from transformers import ViTImageProcessor




class       UpperCAmelCase_    (		unittest.TestCase				):




    def __init__(       self		:			Union[str, Any]      ,					snake_case_		:			Tuple      ,					snake_case_		:			Dict=7      ,					snake_case_		:			List[Any]=3      ,					snake_case_		:			Optional[int]=18      ,					snake_case_		:			Tuple=30      ,					snake_case_		:			Dict=400      ,					snake_case_		:			List[str]=True      ,					snake_case_		:			Optional[int]=None      ,					snake_case_		:			List[str]=True      ,					snake_case_		:			Optional[Any]=[0.5, 0.5, 0.5]      ,					snake_case_		:			Optional[int]=[0.5, 0.5, 0.5]      ,					) ->				List[Any]:




     '''simple docstring'''

     A__			=							size if size is not None else {"height": 18, "width": 18}
     A__			=							parent
     A__			=							batch_size
     A__			=							num_channels
     A__			=							image_size
     A__			=							min_resolution
     A__			=							max_resolution
     A__			=							do_resize
     A__			=							size
     A__			=							do_normalize
     A__			=							image_mean
     A__			=							image_std




    def 				__magic_name__				(       self		:			Union[str, Any] ) ->				Dict:




     '''simple docstring'''

     return {
         "image_mean": self.image_mean,
         "image_std": self.image_std,
         "do_normalize": self.do_normalize,
         "do_resize": self.do_resize,
         "size": self.size,
     }






@require_torch
@require_vision
class       UpperCAmelCase_    (		A_,  unittest.TestCase				):
    lowercase__		   = ViTImageProcessor if is_vision_available() else None




    def 				__magic_name__				(       self		:			int ) ->				Any:




     '''simple docstring'''

     A__			=							ViTImageProcessingTester(self )




    @property
    def 				__magic_name__				(       self		:			Optional[Any] ) ->				str:




     '''simple docstring'''

     return self.image_processor_tester.prepare_image_processor_dict()




    def 				__magic_name__				(       self		:			Tuple ) ->				str:




     '''simple docstring'''

     A__			=							self.image_processing_class(**self.image_processor_dict )
     self.assertTrue(hasattr(snake_case_      ,					"image_mean" ) )
     self.assertTrue(hasattr(snake_case_      ,					"image_std" ) )
     self.assertTrue(hasattr(snake_case_      ,					"do_normalize" ) )
     self.assertTrue(hasattr(snake_case_      ,					"do_resize" ) )
     self.assertTrue(hasattr(snake_case_      ,					"size" ) )




    def 				__magic_name__				(       self		:			Union[str, Any] ) ->				List[str]:




     '''simple docstring'''

     A__			=							self.image_processing_class.from_dict(self.image_processor_dict )
     self.assertEqual(image_processor.size      ,					{"height": 18, "width": 18} )

     A__			=							self.image_processing_class.from_dict(self.image_processor_dict      ,					size=42 )
     self.assertEqual(image_processor.size      ,					{"height": 42, "width": 42} )




    def 				__magic_name__				(       self		:			Any ) ->				Optional[Any]:




     '''simple docstring'''

     pass




    def 				__magic_name__				(       self		:			Optional[int] ) ->				Any:




     '''simple docstring'''

     A__			=							self.image_processing_class(**self.image_processor_dict )
     # create random PIL images
     A__			=							prepare_image_inputs(self.image_processor_tester      ,					equal_resolution=snake_case_ )
     for image in image_inputs:
      self.assertIsInstance(snake_case_      ,					Image.Image )

     # Test not batched input
     A__			=							image_processing(image_inputs[0]      ,					return_tensors="pt" ).pixel_values
     self.assertEqual(
         encoded_images.shape      ,					(
             1,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.size["height"],
             self.image_processor_tester.size["width"],
         )      ,					)

     # Test batched
     A__			=							image_processing(snake_case_      ,					return_tensors="pt" ).pixel_values
     self.assertEqual(
         encoded_images.shape      ,					(
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.size["height"],
             self.image_processor_tester.size["width"],
         )      ,					)




    def 				__magic_name__				(       self		:			str ) ->				Optional[Any]:




     '''simple docstring'''

     A__			=							self.image_processing_class(**self.image_processor_dict )
     # create random numpy tensors
     A__			=							prepare_image_inputs(self.image_processor_tester      ,					equal_resolution=snake_case_      ,					numpify=snake_case_ )
     for image in image_inputs:
      self.assertIsInstance(snake_case_      ,					np.ndarray )

     # Test not batched input
     A__			=							image_processing(image_inputs[0]      ,					return_tensors="pt" ).pixel_values
     self.assertEqual(
         encoded_images.shape      ,					(
             1,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.size["height"],
             self.image_processor_tester.size["width"],
         )      ,					)

     # Test batched
     A__			=							image_processing(snake_case_      ,					return_tensors="pt" ).pixel_values
     self.assertEqual(
         encoded_images.shape      ,					(
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.size["height"],
             self.image_processor_tester.size["width"],
         )      ,					)




    def 				__magic_name__				(       self		:			Dict ) ->				Union[str, Any]:




     '''simple docstring'''

     A__			=							self.image_processing_class(**self.image_processor_dict )
     # create random PyTorch tensors
     A__			=							prepare_image_inputs(self.image_processor_tester      ,					equal_resolution=snake_case_      ,					torchify=snake_case_ )
     for image in image_inputs:
      self.assertIsInstance(snake_case_      ,					torch.Tensor )

     # Test not batched input
     A__			=							image_processing(image_inputs[0]      ,					return_tensors="pt" ).pixel_values
     self.assertEqual(
         encoded_images.shape      ,					(
             1,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.size["height"],
             self.image_processor_tester.size["width"],
         )      ,					)

     # Test batched
     A__			=							image_processing(snake_case_      ,					return_tensors="pt" ).pixel_values
     self.assertEqual(
         encoded_images.shape      ,					(
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.size["height"],
             self.image_processor_tester.size["width"],
         )      ,					)





