




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:





     """simple docstring"""



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






         """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 				__SCREAMING_SNAKE_CASE		(      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 				__SCREAMING_SNAKE_CASE		(      self :       Dict    )			->			Any:






         """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=A						,				initializer_range=self.initializer_range						,				)

     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[int]						,				A :       Any						,				A :       Dict						,				A :       Optional[int]    )			->			List[Any]:






         """simple docstring"""
         a__      =       TFConvNextModel(config=A    )
         a__      =       model(A						,				training=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 				__SCREAMING_SNAKE_CASE		(      self :       List[Any]						,				A :       Dict						,				A :       List[Any]						,				A :       Optional[int]    )			->			int:






         """simple docstring"""
         a__      =       self.type_sequence_label_size
         a__      =       TFConvNextForImageClassification(A    )
         a__      =       model(A						,				labels=A						,				training=A    )
         self.parent.assertEqual(result.logits.shape						,				(self.batch_size, self.type_sequence_label_size)    )






     def 				__SCREAMING_SNAKE_CASE		(      self :       Tuple    )			->			Any:






         """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(		lowercase__       ,	lowercase__       ,	unittest.TestCase ):





     """simple docstring"""



     __UpperCAmelCase	: str						=    (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
     __UpperCAmelCase	: int						=    (
         {"""feature-extraction""": TFConvNextModel, """image-classification""": TFConvNextForImageClassification}
         if is_tf_available()
         else {}
     )

     __UpperCAmelCase	: Any						=    False
     __UpperCAmelCase	: Union[str, Any]						=    False
     __UpperCAmelCase	: Optional[Any]						=    False
     __UpperCAmelCase	: List[Any]						=    False
     __UpperCAmelCase	: List[Any]						=    False

     def 				__SCREAMING_SNAKE_CASE		(      self :       List[str]    )			->			List[str]:






         """simple docstring"""
         a__      =       TFConvNextModelTester(self    )
         a__      =       ConfigTester(
             self						,				config_class=A						,				has_text_modality=A						,				hidden_size=37						,				)

     @unittest.skip(reason="""ConvNext does not use inputs_embeds"""    )
     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]    )			->			str:






         """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 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]    )			->			str:






         """simple docstring"""
         super().test_keras_fit()

     @unittest.skip(reason="""ConvNext does not support input and output embeddings"""    )
     def 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]    )			->			Tuple:






         """simple docstring"""
         pass

     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict    )			->			int:






         """simple docstring"""
         a__ ,		a__      =       self.model_tester.prepare_config_and_inputs_for_common()

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

     def 				__SCREAMING_SNAKE_CASE		(      self :       List[Any]    )			->			int:






         """simple docstring"""
         a__      =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*A    )

     @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 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]    )			->			Optional[Any]:






         """simple docstring"""
         super().test_dataset_conversion()

     def 				__SCREAMING_SNAKE_CASE		(      self :       int    )			->			Dict:






         """simple docstring"""
         def check_hidden_states_output(A :       str						,				A :       List[str]						,				A :       List[str]    ):
             a__      =       model_class(A    )

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

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

         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(A						,				A						,				A    )

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

             check_hidden_states_output(A						,				A						,				A    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       int    )			->			Optional[int]:






         """simple docstring"""
         a__ ,		a__      =       self.model_tester.prepare_config_and_inputs_for_common()

         def check_equivalence(A :       Optional[Any]						,				A :       Tuple						,				A :       Optional[Any]						,				A :       Optional[Any]={}    ):
             a__      =       model(A						,				return_dict=A						,				**A    )
             a__      =       model(A						,				return_dict=A						,				**A    ).to_tuple()

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

                 recursive_check(A						,				A    )

         for model_class in self.all_model_classes:
             a__      =       model_class(A    )

             a__      =       self._prepare_for_class(A						,				A    )
             a__      =       self._prepare_for_class(A						,				A    )
             check_equivalence(A						,				A						,				A    )

             a__      =       self._prepare_for_class(A						,				A						,				return_labels=A    )
             a__      =       self._prepare_for_class(A						,				A						,				return_labels=A    )
             check_equivalence(A						,				A						,				A    )

             a__      =       self._prepare_for_class(A						,				A    )
             a__      =       self._prepare_for_class(A						,				A    )
             check_equivalence(A						,				A						,				A						,				{"""output_hidden_states""": True}    )

             a__      =       self._prepare_for_class(A						,				A						,				return_labels=A    )
             a__      =       self._prepare_for_class(A						,				A						,				return_labels=A    )
             check_equivalence(A						,				A						,				A						,				{"""output_hidden_states""": True}    )

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






         """simple docstring"""
         a__      =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*A    )






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






         """simple docstring"""
         a__      =       TFConvNextModel.from_pretrained("""facebook/convnext-tiny-224"""    )
         self.assertIsNotNone(A    )






def        __lowerCAmelCase ():
    a__      =       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
    return image







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





     """simple docstring"""



     @cached_property
     def 				__SCREAMING_SNAKE_CASE		(      self :       str    )			->			Any:






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






     @slow
     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[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=A						,				return_tensors="""tf"""    )

         # forward pass
         a__      =       model(**A    )

         # verify the logits
         a__      =       tf.TensorShape((1, 10_00)    )
         self.assertEqual(outputs.logits.shape						,				A    )

         a__      =       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]						,				A						,				atol=1E-4    )












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


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import SwinaSRImageProcessor
 from transformers.image_transforms import get_image_size







class 		__UpperCAmelCase(		unittest.TestCase ):





     """simple docstring"""



     def __init__(      self :       Optional[int]						,				A :       Dict						,				A :       Union[str, Any]=7						,				A :       List[str]=3						,				A :       Optional[int]=18						,				A :       Optional[int]=30						,				A :       Optional[Any]=4_00						,				A :       Optional[Any]=True						,				A :       Tuple=1 / 2_55						,				A :       Tuple=True						,				A :       Optional[int]=8						,				)			->			Any:






         """simple docstring"""
         a__      =       parent
         a__      =       batch_size
         a__      =       num_channels
         a__      =       image_size
         a__      =       min_resolution
         a__      =       max_resolution
         a__      =       do_rescale
         a__      =       rescale_factor
         a__      =       do_pad
         a__      =       pad_size

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






         """simple docstring"""
         return {
             "do_rescale": self.do_rescale,
             "rescale_factor": self.rescale_factor,
             "do_pad": self.do_pad,
             "pad_size": self.pad_size,
         }






     def 				__SCREAMING_SNAKE_CASE		(      self :       int						,				A :       int=False						,				A :       Any=False						,				A :       List[Any]=False    )			->			Optional[Any]:






         """simple docstring"""
         assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

         if equal_resolution:
             a__      =       []
             for i in range(self.batch_size    ):
                 image_inputs.append(
                     np.random.randint(
                         2_55						,				size=(self.num_channels, self.max_resolution, self.max_resolution)						,				dtype=np.uinta    )    )
         else:
             a__      =       []
             for i in range(self.batch_size    ):
                 a__ ,		a__      =       np.random.choice(np.arange(self.min_resolution						,				self.max_resolution    )						,				2    )
                 image_inputs.append(np.random.randint(2_55						,				size=(self.num_channels, width, height)						,				dtype=np.uinta    )    )

         if not numpify and not torchify:
             # PIL expects the channel dimension as last dimension
             a__      =       [Image.fromarray(np.moveaxis(A						,				0						,				-1    )    ) for x in image_inputs]

         if torchify:
             a__      =       [torch.from_numpy(A    ) for x in image_inputs]

         return image_inputs







@require_torch
@require_vision
class 		__UpperCAmelCase(		lowercase__       ,	unittest.TestCase ):





     """simple docstring"""



     __UpperCAmelCase	: Dict						=    SwinaSRImageProcessor if is_vision_available() else None

     def 				__SCREAMING_SNAKE_CASE		(      self :       int    )			->			Dict:






         """simple docstring"""
         a__      =       SwinaSRImageProcessingTester(self    )

     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       List[Any]    )			->			List[Any]:






         """simple docstring"""
         return self.image_processor_tester.prepare_image_processor_dict()

     def 				__SCREAMING_SNAKE_CASE		(      self :       Tuple    )			->			int:






         """simple docstring"""
         a__      =       self.image_processing_class(**self.image_processor_dict    )
         self.assertTrue(hasattr(A						,				"""do_rescale"""    )    )
         self.assertTrue(hasattr(A						,				"""rescale_factor"""    )    )
         self.assertTrue(hasattr(A						,				"""do_pad"""    )    )
         self.assertTrue(hasattr(A						,				"""pad_size"""    )    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict    )			->			List[Any]:






         """simple docstring"""
         pass

     def 				__SCREAMING_SNAKE_CASE		(      self :       int						,				A :       Optional[Any]    )			->			List[str]:






         """simple docstring"""
         a__ ,		a__      =       get_image_size(A    )
         a__      =       self.image_processor_tester.pad_size

         a__      =       (old_height // size + 1) * size - old_height
         a__      =       (old_width // size + 1) * size - old_width
         return old_height + pad_height, old_width + pad_width

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






         """simple docstring"""
         # Initialize image_processor
         a__      =       self.image_processing_class(**self.image_processor_dict    )
         # create random PIL images
         a__      =       self.image_processor_tester.prepare_inputs(equal_resolution=A    )
         for image in image_inputs:
             self.assertIsInstance(A						,				Image.Image    )

         # Test not batched input
         a__      =       image_processor(image_inputs[0]						,				return_tensors="""pt"""    ).pixel_values
         a__ ,		a__      =       self.calculate_expected_size(np.array(image_inputs[0]    )    )
         self.assertEqual(
             encoded_images.shape						,				(
                 1,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )						,				)

     def 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]    )			->			Optional[Any]:






         """simple docstring"""
         # Initialize image_processor
         a__      =       self.image_processing_class(**self.image_processor_dict    )
         # create random numpy tensors
         a__      =       self.image_processor_tester.prepare_inputs(equal_resolution=A						,				numpify=A    )
         for image in image_inputs:
             self.assertIsInstance(A						,				np.ndarray    )

         # Test not batched input
         a__      =       image_processor(image_inputs[0]						,				return_tensors="""pt"""    ).pixel_values
         a__ ,		a__      =       self.calculate_expected_size(image_inputs[0]    )
         self.assertEqual(
             encoded_images.shape						,				(
                 1,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )						,				)






     def 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]    )			->			Tuple:






         """simple docstring"""
         # Initialize image_processor
         a__      =       self.image_processing_class(**self.image_processor_dict    )
         # create random PyTorch tensors
         a__      =       self.image_processor_tester.prepare_inputs(equal_resolution=A						,				torchify=A    )
         for image in image_inputs:
             self.assertIsInstance(A						,				torch.Tensor    )

         # Test not batched input
         a__      =       image_processor(image_inputs[0]						,				return_tensors="""pt"""    ).pixel_values
         a__ ,		a__      =       self.calculate_expected_size(image_inputs[0]    )
         self.assertEqual(
             encoded_images.shape						,				(
                 1,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )						,				)






